summary refs log tree commit diff stats
path: root/compiler/extccomp.nim
blob: 6f8b0b197e41c6341d9dd2cad556d5710c7acef7 (plain) (blame)
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
#
#  $Id: sdl_ttf.pas,v 1.18 2007/06/01 11:16:33 savage Exp $
#
#
#******************************************************************************
#                                                                              
#          JEDI-SDL : Pascal units for SDL - Simple DirectMedia Layer          
#       Conversion of the Simple DirectMedia Layer Headers                     
#                                                                              
# Portions created by Sam Lantinga <slouken@devolution.com> are                
# Copyright (C) 1997, 1998, 1999, 2000, 2001  Sam Lantinga                     
# 5635-34 Springhouse Dr.                                                      
# Pleasanton, CA 94588 (USA)                                                   
#                                                                              
# All Rights Reserved.                                                         
#                                                                              
# The original files are : SDL_ttf.h                                           
#                                                                              
# The initial developer of this Pascal code was :                              
# Dominqiue Louis <Dominique@SavageSoftware.com.au>                            
#                                                                              
# Portions created by Dominqiue Louis are                                      
# Copyright (C) 2000 - 2001 Dominqiue Louis.                                   
#                                                                              
#                                                                              
# Contributor(s)                                                               
# --------------                                                               
# Tom Jones <tigertomjones@gmx.de>  His Project inspired this conversion       
#                                                                              
# Obtained through:                                                            
# Joint Endeavour of Delphi Innovators ( Project JEDI )                        
#                                                                              
# You may retrieve the latest version of this file at the Project              
# JEDI home page, located at http://delphi-jedi.org                            
#                                                                              
# The contents of this file are used with permission, subject to               
# the Mozilla Public License Version 1.1 (the "License"); you may              
# not use this file except in compliance with the License. You may             
# obtain a copy of the License at                                              
# http://www.mozilla.org/MPL/MPL-1.1.html                                      
#                                                                              
# Software distributed under the License is distributed on an                  
# "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or               
# implied. See the License for the specific language governing                 
# rights and limitations under the License.                                    
#                                                                              
# Description                                                                  
# -----------                                                                  
#                                                                              
#                                                                              
#                                                                              
#                                                                              
#                                                                              
#                                                                              
#                                                                              
# Requires                                                                     
# --------                                                                     
#   The SDL Runtime libraris on Win32  : SDL.dll on Linux : libSDL.so          
#   They are available from...                                                 
#   http://www.libsdl.org .                                                    
#                                                                              
# Programming Notes                                                            
# -----------------                                                            
#                                                                              
#                                                                              
#                                                                              
#                                                                              
# Revision History                                                             
# ----------------                                                             
#   December 08 2002 - DL : Fixed definition of TTF_RenderUnicode_Solid        
#                                                                              
#   April   03 2003 - DL : Added jedi-sdl.inc include file to support more     
#                          Pascal compilers. Initial support is now included   
#                          for GnuPascal, VirtualPascal, TMT and obviously     
#                          continue support for Delphi Kylix and FreePascal.   
#                                                                              
#   April   24 2003 - DL : under instruction from Alexey Barkovoy, I have added
#                          better TMT Pascal support and under instruction     
#                          from Prof. Abimbola Olowofoyeku (The African Chief),
#                          I have added better Gnu Pascal support              
#                                                                              
#   April   30 2003 - DL : under instruction from David Mears AKA              
#                          Jason Siletto, I have added FPC Linux support.      
#                          This was compiled with fpc 1.1, so remember to set  
#                          include file path. ie. -Fi/usr/share/fpcsrc/rtl/*   
#                                                                              
#
#  $Log: sdl_ttf.pas,v $
#  Revision 1.18  2007/06/01 11:16:33  savage
#  Added IFDEF UNIX for Workaround.
#
#  Revision 1.17  2007/06/01 08:38:21  savage
#  Added TTF_RenderText_Solid workaround as suggested by Michalis Kamburelis
#
#  Revision 1.16  2007/05/29 21:32:14  savage
#  Changes as suggested by Almindor for 64bit compatibility.
#
# 
#
#
#           The Nim Compiler
#        (c) Copyright 2013 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

# Module providing functions for calling the different external C compilers
# Uses some hard-wired facts about each C/C++ compiler, plus options read
# from a configuration file, to provide generalized procedures to compile
# nim files.

import
  lists, ropes, os, strutils, osproc, platform, condsyms, options, msgs,
  securehash, streams

from debuginfo import writeDebugInfo

type
  TSystemCC* = enum
    ccNone, ccGcc, ccLLVM_Gcc, ccCLang, ccLcc, ccBcc, ccDmc, ccWcc, ccVcc,
    ccTcc, ccPcc, ccUcc, ccIcl, asmFasm
  TInfoCCProp* = enum         # properties of the C compiler:
    hasSwitchRange,           # CC allows ranges in switch statements (GNU C)
    hasComputedGoto,          # CC has computed goto (GNU C extension)
    hasCpp,                   # CC is/contains a C++ compiler
    hasAssume,                # CC has __assume (Visual C extension)
    hasGcGuard,               # CC supports GC_GUARD to keep stack roots
    hasGnuAsm,                # CC's asm uses the absurd GNU assembler syntax
    hasDeclspec,              # CC has __declspec(X)
    hasAttribute,             # CC has __attribute__((X))
  TInfoCCProps* = set[TInfoCCProp]
  TInfoCC* = tuple[
    name: string,        # the short name of the compiler
    objExt: string,      # the compiler's object file extenstion
    optSpeed: string,    # the options for optimization for speed
    optSize: string,     # the options for optimization for size
    compilerExe: string, # the compiler's executable
    cppCompiler: string, # name of the C++ compiler's executable (if supported)
    compileTmpl: string, # the compile command template
    buildGui: string,    # command to build a GUI application
    buildDll: string,    # command to build a shared library
    buildLib: string,    # command to build a static library
    linkerExe: string,   # the linker's executable (if not matching compiler's)
    linkTmpl: string,    # command to link files to produce an exe
    includeCmd: string,  # command to add an include dir
    linkDirCmd: string,  # command to add a lib dir
    linkLibCmd: string,  # command to link an external library
    debug: string,       # flags for debug build
    pic: string,         # command for position independent code
                         # used on some platforms
    asmStmtFrmt: string, # format of ASM statement
    structStmtFmt: string, # Format for struct statement
    packedPragma: string,  # Attribute/pragma to make struct packed (1-byte aligned)
    props: TInfoCCProps] # properties of the C compiler


# Configuration settings for various compilers.
# When adding new compilers, the cmake sources could be a good reference:
# http://cmake.org/gitweb?p=cmake.git;a=tree;f=Modules/Platform;

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

# GNU C and C++ Compiler
compiler gcc:
  result = (
    name: "gcc",
    objExt: "o",
    optSpeed: " -O3 -ffast-math ",
    optSize: " -Os -ffast-math ",
    compilerExe: "gcc",
    cppCompiler: "g++",
    compileTmpl: "-c $options $include -o $objfile $file",
    buildGui: " -mwindows",
    buildDll: " -shared",
    buildLib: "ar rcs $libfile $objfiles",
    linkerExe: "",
    linkTmpl: "$buildgui $builddll -o $exefile $objfiles $options",
    includeCmd: " -I",
    linkDirCmd: " -L",
    linkLibCmd: " -l$1",
    debug: "",
    pic: "-fPIC",
    asmStmtFrmt: "asm($1);$n",
    structStmtFmt: "$1 $3 $2 ", # struct|union [packed] $name
    packedPragma: "__attribute__((__packed__))",
    props: {hasSwitchRange, hasComputedGoto, hasCpp, hasGcGuard, hasGnuAsm,
            hasAttribute})

# LLVM Frontend for GCC/G++
compiler llvmGcc:
  result = gcc() # Uses settings from GCC

  result.name = "llvm_gcc"
  result.compilerExe = "llvm-gcc"
  result.cppCompiler = "llvm-g++"
  result.buildLib = "llvm-ar rcs $libfile $objfiles"

# Clang (LLVM) C/C++ Compiler
compiler clang:
  result = llvmGcc() # Uses settings from llvmGcc

  result.name = "clang"
  result.compilerExe = "clang"
  result.cppCompiler = "clang++"

# Microsoft Visual C/C++ Compiler
compiler vcc:
  result = (
    name: "vcc",
    objExt: "obj",
    optSpeed: " /Ogityb2 /G7 /arch:SSE2 ",
    optSize: " /O1 /G7 ",
    compilerExe: "cl",
    cppCompiler: "cl",
    compileTmpl: "/c $options $include /Fo$objfile $file",
    buildGui: " /link /SUBSYSTEM:WINDOWS ",
    buildDll: " /LD",
    buildLib: "lib /OUT:$libfile $objfiles",
    linkerExe: "cl",
    linkTmpl: "$options $builddll /Fe$exefile $objfiles $buildgui",
    includeCmd: " /I",
    linkDirCmd: " /LIBPATH:",
    linkLibCmd: " $1.lib",
    debug: " /RTC1 /Z7 ",
    pic: "",
    asmStmtFrmt: "__asm{$n$1$n}$n",
    structStmtFmt: "$3$n$1 $2",
    packedPragma: "#pragma pack(1)",
    props: {hasCpp, hasAssume, hasDeclspec})

# Intel C/C++ Compiler
compiler icl:
  # Intel compilers try to imitate the native ones (gcc and msvc)
  when defined(windows):
    result = vcc()
  else:
    result = gcc()

  result.name = "icl"
  result.compilerExe = "icl"
  result.linkerExe = "icl"

# Local C Compiler
compiler lcc:
  result = (
    name: "lcc",
    objExt: "obj",
    optSpeed: " -O -p6 ",
    optSize: " -O -p6 ",
    compilerExe: "lcc",
    cppCompiler: "",
    compileTmpl: "$options $include -Fo$objfile $file",
    buildGui: " -subsystem windows",
    buildDll: " -dll",
    buildLib: "", # XXX: not supported yet
    linkerExe: "lcclnk",
    linkTmpl: "$options $buildgui $builddll -O $exefile $objfiles",
    includeCmd: " -I",
    linkDirCmd: "", # XXX: not supported yet
    linkLibCmd: "", # XXX: not supported yet
    debug: " -g5 ",
    pic: "",
    asmStmtFrmt: "_asm{$n$1$n}$n",
    structStmtFmt: "$1 $2",
    packedPragma: "", # XXX: not supported yet
    props: {})

# Borland C Compiler
compiler bcc:
  result = (
    name: "bcc",
    objExt: "obj",
    optSpeed: " -O2 -6 ",
    optSize: " -O1 -6 ",
    compilerExe: "bcc32",
    cppCompiler: "",
    compileTmpl: "-c $options $include -o$objfile $file",
    buildGui: " -tW",
    buildDll: " -tWD",
    buildLib: "", # XXX: not supported yet
    linkerExe: "bcc32",
    linkTmpl: "$options $buildgui $builddll -e$exefile $objfiles",
    includeCmd: " -I",
    linkDirCmd: "", # XXX: not supported yet
    linkLibCmd: "", # XXX: not supported yet
    debug: "",
    pic: "",
    asmStmtFrmt: "__asm{$n$1$n}$n",
    structStmtFmt: "$1 $2",
    packedPragma: "", # XXX: not supported yet
    props: {hasCpp})

# Digital Mars C Compiler
compiler dmc:
  result = (
    name: "dmc",
    objExt: "obj",
    optSpeed: " -ff -o -6 ",
    optSize: " -ff -o -6 ",
    compilerExe: "dmc",
    cppCompiler: "",
    compileTmpl: "-c $options $include -o$objfile $file",
    buildGui: " -L/exet:nt/su:windows",
    buildDll: " -WD",
    buildLib: "", # XXX: not supported yet
    linkerExe: "dmc",
    linkTmpl: "$options $buildgui $builddll -o$exefile $objfiles",
    includeCmd: " -I",
    linkDirCmd: "", # XXX: not supported yet
    linkLibCmd: "", # XXX: not supported yet
    debug: " -g ",
    pic: "",
    asmStmtFrmt: "__asm{$n$1$n}$n",
    structStmtFmt: "$3$n$1 $2",
    packedPragma: "#pragma pack(1)",
    props: {hasCpp})

# Watcom C Compiler
compiler wcc:
  result = (
    name: "wcc",
    objExt: "obj",
    optSpeed: " -ox -on -6 -d0 -fp6 -zW ",
    optSize: "",
    compilerExe: "wcl386",
    cppCompiler: "",
    compileTmpl: "-c $options $include -fo=$objfile $file",
    buildGui: " -bw",
    buildDll: " -bd",
    buildLib: "", # XXX: not supported yet
    linkerExe: "wcl386",
    linkTmpl: "$options $buildgui $builddll -fe=$exefile $objfiles ",
    includeCmd: " -i=",
    linkDirCmd: "", # XXX: not supported yet
    linkLibCmd: "", # XXX: not supported yet
    debug: " -d2 ",
    pic: "",
    asmStmtFrmt: "__asm{$n$1$n}$n",
    structStmtFmt: "$1 $2",
    packedPragma: "", # XXX: not supported yet
    props: {hasCpp})

# Tiny C Compiler
compiler tcc:
  result = (
    name: "tcc",
    objExt: "o",
    optSpeed: "",
    optSize: "",
    compilerExe: "tcc",
    cppCompiler: "",
    compileTmpl: "-c $options $include -o $objfile $file",
    buildGui: "UNAVAILABLE!",
    buildDll: " -shared",
    buildLib: "", # XXX: not supported yet
    linkerExe: "tcc",
    linkTmpl: "-o $exefile $options $buildgui $builddll $objfiles",
    includeCmd: " -I",
    linkDirCmd: "", # XXX: not supported yet
    linkLibCmd: "", # XXX: not supported yet
    debug: " -g ",
    pic: "",
    asmStmtFrmt: "__asm{$n$1$n}$n",
    structStmtFmt: "$1 $2",
    packedPragma: "", # XXX: not supported yet
    props: {hasSwitchRange, hasComputedGoto})

# Pelles C Compiler
compiler pcc:
  # Pelles C
  result = (
    name: "pcc",
    objExt: "obj",
    optSpeed: " -Ox ",
    optSize: " -Os ",
    compilerExe: "cc",
    cppCompiler: "",
    compileTmpl: "-c $options $include -Fo$objfile $file",
    buildGui: " -SUBSYSTEM:WINDOWS",
    buildDll: " -DLL",
    buildLib: "", # XXX: not supported yet
    linkerExe: "cc",
    linkTmpl: "$options $buildgui $builddll -OUT:$exefile $objfiles",
    includeCmd: " -I",
    linkDirCmd: "", # XXX: not supported yet
    linkLibCmd: "", # XXX: not supported yet
    debug: " -Zi ",
    pic: "",
    asmStmtFrmt: "__asm{$n$1$n}$n",
    structStmtFmt: "$1 $2",
    packedPragma: "", # XXX: not supported yet
    props: {})

# Your C Compiler
compiler ucc:
  result = (
    name: "ucc",
    objExt: "o",
    optSpeed: " -O3 ",
    optSize: " -O1 ",
    compilerExe: "cc",
    cppCompiler: "",
    compileTmpl: "-c $options $include -o $objfile $file",
    buildGui: "",
    buildDll: " -shared ",
    buildLib: "", # XXX: not supported yet
    linkerExe: "cc",
    linkTmpl: "-o $exefile $buildgui $builddll $objfiles $options",
    includeCmd: " -I",
    linkDirCmd: "", # XXX: not supported yet
    linkLibCmd: "", # XXX: not supported yet
    debug: "",
    pic: "",
    asmStmtFrmt: "__asm{$n$1$n}$n",
    structStmtFmt: "$1 $2",
    packedPragma: "", # XXX: not supported yet
    props: {})

# fasm assembler
compiler fasm:
  result = (
    name: "fasm",
    objExt: "o",
    optSpeed: "",
    optSize: "",
    compilerExe: "fasm",
    cppCompiler: "fasm",
    compileTmpl: "$file $objfile",
    buildGui: "",
    buildDll: "",
    buildLib: "",
    linkerExe: "",
    linkTmpl: "",
    includeCmd: "",
    linkDirCmd: "",
    linkLibCmd: "",
    debug: "",
    pic: "",
    asmStmtFrmt: "",
    structStmtFmt: "",
    packedPragma: "",
    props: {})

const
  CC*: array[succ(low(TSystemCC))..high(TSystemCC), TInfoCC] = [
    gcc(),
    llvmGcc(),
    clang(),
    lcc(),
    bcc(),
    dmc(),
    wcc(),
    vcc(),
    tcc(),
    pcc(),
    ucc(),
    icl(),
    fasm()]

  hExt* = ".h"

var
  cCompiler* = ccGcc # the used compiler
  cAssembler* = ccNone
  gMixedMode*: bool  # true if some module triggered C++ codegen
  cIncludes*: seq[string] = @[]   # directories to search for included files
  cLibs*: seq[string] = @[]       # directories to search for lib files
  cLinkedLibs*: seq[string] = @[] # libraries to link

const
  cValidAssemblers* = {asmFasm}

# implementation

proc libNameTmpl(): string {.inline.} =
  result = if targetOS == osWindows: "$1.lib" else: "lib$1.a"

var
  toLink, toCompile, externalToCompile: TLinkedList
  linkOptions: string = ""
  compileOptions: string = ""
  ccompilerpath: string = ""

proc nameToCC*(name: string): TSystemCC =
  ## Returns the kind of compiler referred to by `name`, or ccNone
  ## if the name doesn't refer to any known compiler.
  for i in countup(succ(ccNone), high(TSystemCC)):
    if cmpIgnoreStyle(name, CC[i].name) == 0:
      return i
  result = ccNone

proc getConfigVar(c: TSystemCC, suffix: string): string =
  # use ``cpu.os.cc`` for cross compilation, unless ``--compileOnly`` is given
  # for niminst support
  let fullSuffix =
    if gCmd == cmdCompileToCpp:
      ".cpp" & suffix
    elif gCmd == cmdCompileToOC:
      ".objc" & suffix
    elif gCmd == cmdCompileToJS:
      ".js" & suffix
    else:
      suffix

  if (platform.hostOS != targetOS or platform.hostCPU != targetCPU) and
      optCompileOnly notin gGlobalOptions:
    let fullCCname = platform.CPU[targetCPU].name & '.' &
                     platform.OS[targetOS].name & '.' &
                     CC[c].name & fullSuffix
    result = getConfigVar(fullCCname)
    if result.len == 0:
      # not overriden for this cross compilation setting?
      result = getConfigVar(CC[c].name & fullSuffix)
  else:
    result = getConfigVar(CC[c].name & fullSuffix)

proc setCC*(ccname: string) =
  cCompiler = nameToCC(ccname)
  if cCompiler == ccNone: rawMessage(errUnknownCcompiler, ccname)
  compileOptions = getConfigVar(cCompiler, ".options.always")
  linkOptions = ""
  ccompilerpath = getConfigVar(cCompiler, ".path")
  for i in countup(low(CC), high(CC)): undefSymbol(CC[i].name)
  defineSymbol(CC[cCompiler].name)

proc addOpt(dest: var string, src: string) =
  if len(dest) == 0 or dest[len(dest)-1] != ' ': add(dest, " ")
  add(dest, src)

proc addLinkOption*(option: string) =
  addOpt(linkOptions, option)

proc addCompileOption*(option: string) =
  if strutils.find(compileOptions, option, 0) < 0:
    addOpt(compileOptions, option)

proc initVars*() =
  # we need to define the symbol here, because ``CC`` may have never been set!
  for i in countup(low(CC), high(CC)): undefSymbol(CC[i].name)
  defineSymbol(CC[cCompiler].name)
  addCompileOption(getConfigVar(cCompiler, ".options.always"))
  #addLinkOption(getConfigVar(cCompiler, ".options.linker"))
  if len(ccompilerpath) == 0:
    ccompilerpath = getConfigVar(cCompiler, ".path")

proc completeCFilePath*(cfile: string, createSubDir: bool = true): string =
  result = completeGeneratedFilePath(cfile, createSubDir)

proc toObjFile*(filename: string): string =
  # Object file for compilation
  result = changeFileExt(filename, CC[cCompiler].objExt)

proc addFileToCompile*(filename: string) =
  appendStr(toCompile, filename)

proc resetCompilationLists* =
  initLinkedList(toCompile)
  ## XXX: we must associate these with their originating module
  # when the module is loaded/unloaded it adds/removes its items
  # That's because we still need to hash check the external files
  # Maybe we can do that in checkDep on the other hand?
  initLinkedList(externalToCompile)
  initLinkedList(toLink)

proc addFileToLink*(filename: string) =
  prependStr(toLink, filename)
  # BUGFIX: was ``appendStr``

proc execWithEcho(cmd: string, msg = hintExecuting): int =
  rawMessage(msg, cmd)
  result = execCmd(cmd)

proc execExternalProgram*(cmd: string, msg = hintExecuting) =
  if execWithEcho(cmd, msg) != 0:
    rawMessage(errExecutionOfProgramFailed, cmd)

proc generateScript(projectFile: string, script: Rope) =
  let (dir, name, ext) = splitFile(projectFile)
  writeRope(script, dir / addFileExt("compile_" & name,
                                     platform.OS[targetOS].scriptExt))

proc getOptSpeed(c: TSystemCC): string =
  result = getConfigVar(c, ".options.speed")
  if result == "":
    result = CC[c].optSpeed   # use default settings from this file

proc getDebug(c: TSystemCC): string =
  result = getConfigVar(c, ".options.debug")
  if result == "":
    result = CC[c].debug      # use default settings from this file

proc getOptSize(c: TSystemCC): string =
  result = getConfigVar(c, ".options.size")
  if result == "":
    result = CC[c].optSize    # use default settings from this file

proc noAbsolutePaths: bool {.inline.} =
  # We used to check current OS != specified OS, but this makes no sense
  # really: Cross compilation from Linux to Linux for example is entirely
  # reasonable.
  # `optGenMapping` is included here for niminst.
  result = gGlobalOptions * {optGenScript, optGenMapping} != {}

var fileCounter: int

proc add(s: var string, many: openArray[string]) =
  s.add many.join

proc cFileSpecificOptions(cfilename: string): string =
  result = compileOptions
  var trunk = splitFile(cfilename).name
  if optCDebug in gGlobalOptions:
    var key = trunk & ".debug"
    if existsConfigVar(key): addOpt(result, getConfigVar(key))
    else: addOpt(result, getDebug(cCompiler))
  if optOptimizeSpeed in gOptions:
    var key = trunk & ".speed"
    if existsConfigVar(key): addOpt(result, getConfigVar(key))
    else: addOpt(result, getOptSpeed(cCompiler))
  elif optOptimizeSize in gOptions:
    var key = trunk & ".size"
    if existsConfigVar(key): addOpt(result, getConfigVar(key))
    else: addOpt(result, getOptSize(cCompiler))
  var key = trunk & ".always"
  if existsConfigVar(key): addOpt(result, getConfigVar(key))

proc getCompileOptions: string =
  result = cFileSpecificOptions("__dummy__")

proc getLinkOptions: string =
  result = linkOptions
  for linkedLib in items(cLinkedLibs):
    result.add(CC[cCompiler].linkLibCmd % linkedLib.quoteShell)
  for libDir in items(cLibs):
    result.add([CC[cCompiler].linkDirCmd, libDir.quoteShell])

proc needsExeExt(): bool {.inline.} =
  result = (optGenScript in gGlobalOptions and targetOS == osWindows) or
           (platform.hostOS == osWindows)

proc getCompilerExe(compiler: TSystemCC): string =
  result = if gCmd == cmdCompileToCpp: CC[compiler].cppCompiler
           else: CC[compiler].compilerExe
  if result.len == 0:
    rawMessage(errCompilerDoesntSupportTarget, CC[compiler].name)

proc getLinkerExe(compiler: TSystemCC): string =
  result = if CC[compiler].linkerExe.len > 0: CC[compiler].linkerExe
           elif gMixedMode and gCmd != cmdCompileToCpp: CC[compiler].cppCompiler
           else: compiler.getCompilerExe

proc getCompileCFileCmd*(cfilename: string, isExternal = false): string =
  var c = cCompiler
  if cfilename.endswith(".asm"):
    var customAssembler = getConfigVar("assembler")
    if customAssembler.len > 0:
      c = nameToCC(customAssembler)
    else:
      if targetCPU == cpuI386 or targetCPU == cpuAmd64:
        c = asmFasm
      else:
        c = ccNone

    if c == ccNone:
      rawMessage(errExternalAssemblerNotFound, "")
    elif c notin cValidAssemblers:
      rawMessage(errExternalAssemblerNotValid, customAssembler)

  var options = cFileSpecificOptions(cfilename)
  var exe = getConfigVar(c, ".exe")
  if exe.len == 0: exe = c.getCompilerExe

  if needsExeExt(): exe = addFileExt(exe, "exe")
  if optGenDynLib in gGlobalOptions and
      ospNeedsPIC in platform.OS[targetOS].props:
    add(options, ' ' & CC[c].pic)

  var includeCmd, compilePattern: string
  if not noAbsolutePaths():
    # compute include paths:
    includeCmd = CC[c].includeCmd & quoteShell(libpath)

    for includeDir in items(cIncludes):
      includeCmd.add([CC[c].includeCmd, includeDir.quoteShell])

    compilePattern = joinPath(ccompilerpath, exe)
  else:
    includeCmd = ""
    compilePattern = c.getCompilerExe

  var cfile = if noAbsolutePaths(): extractFilename(cfilename)
              else: cfilename
  var objfile = if not isExternal or noAbsolutePaths():
                  toObjFile(cfile)
                else:
                  completeCFilePath(toObjFile(cfile))
  objfile = quoteShell(objfile)
  cfile = quoteShell(cfile)
  result = quoteShell(compilePattern % [
    "file", cfile, "objfile", objfile, "options", options,
    "include", includeCmd, "nim", getPrefixDir(),
    "nim", getPrefixDir(), "lib", libpath])
  add(result, ' ')
  addf(result, CC[c].compileTmpl, [
    "file", cfile, "objfile", objfile,
    "options", options, "include", includeCmd,
    "nim", quoteShell(getPrefixDir()),
    "nim", quoteShell(getPrefixDir()),
    "lib", quoteShell(libpath)])

proc footprint(filename: string): SecureHash =
  result = secureHash(
    $secureHashFile(filename) &
    platform.OS[targetOS].name &
    platform.CPU[targetCPU].name &
    extccomp.CC[extccomp.cCompiler].name &
    getCompileCFileCmd(filename, true))

proc externalFileChanged(filename: string): bool =
  if gCmd notin {cmdCompileToC, cmdCompileToCpp, cmdCompileToOC, cmdCompileToLLVM}:
    return false

  var hashFile = toGeneratedFile(filename.withPackageName, "sha1")
  var currentHash = footprint(filename)
  var f: File
  if open(f, hashFile, fmRead):
    let oldHash = parseSecureHash(f.readLine())
    close(f)
    result = oldHash != currentHash
  else:
    result = true
  if result:
    if open(f, hashFile, fmWrite):
      f.writeLine($currentHash)
      close(f)

proc addExternalFileToCompile*(filename: string) =
  if optForceFullMake in gGlobalOptions or externalFileChanged(filename):
    appendStr(externalToCompile, filename)

proc compileCFile(list: TLinkedList, script: var Rope, cmds: var TStringSeq,
                  prettyCmds: var TStringSeq, isExternal: bool) =
  var it = PStrEntry(list.head)
  while it != nil:
    inc(fileCounter)          # call the C compiler for the .c file:
    var compileCmd = getCompileCFileCmd(it.data, isExternal)
    if optCompileOnly notin gGlobalOptions:
      add(cmds, compileCmd)
      let (dir, name, ext) = splitFile(it.data)
      add(prettyCmds, "CC: " & name)
    if optGenScript in gGlobalOptions:
      add(script, compileCmd)
      add(script, tnl)
    it = PStrEntry(it.next)

proc callCCompiler*(projectfile: string) =
  var
    linkCmd, buildgui, builddll: string
  if gGlobalOptions * {optCompileOnly, optGenScript} == {optCompileOnly}:
    return # speed up that call if only compiling and no script shall be
           # generated
  fileCounter = 0
  var c = cCompiler
  var script: Rope = nil
  var cmds: TStringSeq = @[]
  var prettyCmds: TStringSeq = @[]
  let prettyCb = proc (idx: int) =
    echo prettyCmds[idx]
  let runCb = proc (idx: int, p: Process) =
    let exitCode = p.peekExitCode
    if exitCode != 0:
      rawMessage(errGenerated, "execution of an external compiler program '" &
        cmds[idx] & "' failed with exit code: " & $exitCode & "\n\n" &
        p.outputStream.readAll.strip)
  compileCFile(toCompile, script, cmds, prettyCmds, false)
  compileCFile(externalToCompile, script, cmds, prettyCmds, true)
  if optCompileOnly notin gGlobalOptions:
    if gNumberOfProcessors == 0: gNumberOfProcessors = countProcessors()
    var res = 0
    if gNumberOfProcessors <= 1:
      for i in countup(0, high(cmds)):
        res = execWithEcho(cmds[i])
        if res != 0: rawMessage(errExecutionOfProgramFailed, cmds[i])
    elif optListCmd in gGlobalOptions or gVerbosity > 1:
      res = execProcesses(cmds, {poEchoCmd, poStdErrToStdOut, poUsePath, poParentStreams},
                          gNumberOfProcessors, afterRunEvent=runCb)
    elif gVerbosity == 1:
      res = execProcesses(cmds, {poStdErrToStdOut, poUsePath, poParentStreams},
                          gNumberOfProcessors, prettyCb, afterRunEvent=runCb)
    else:
      res = execProcesses(cmds, {poStdErrToStdOut, poUsePath, poParentStreams},
                          gNumberOfProcessors, afterRunEvent=runCb)
    if res != 0:
      if gNumberOfProcessors <= 1:
        rawMessage(errExecutionOfProgramFailed, cmds.join())
  if optNoLinking notin gGlobalOptions:
    # call the linker:
    var it = PStrEntry(toLink.head)
    var objfiles = ""
    while it != nil:
      let objFile = if noAbsolutePaths(): it.data.extractFilename else: it.data
      add(objfiles, ' ')
      add(objfiles, quoteShell(
          addFileExt(objFile, CC[cCompiler].objExt)))
      it = PStrEntry(it.next)

    if optGenStaticLib in gGlobalOptions:
      let name = splitFile(gProjectName).name
      linkCmd = CC[c].buildLib % ["libfile", (libNameTmpl() % name),
                                  "objfiles", objfiles]
    else:
      var linkerExe = getConfigVar(c, ".linkerexe")
      if len(linkerExe) == 0: linkerExe = c.getLinkerExe
      if needsExeExt(): linkerExe = addFileExt(linkerExe, "exe")
      if noAbsolutePaths(): linkCmd = quoteShell(linkerExe)
      else: linkCmd = quoteShell(joinPath(ccompilerpath, linkerExe))
      if optGenGuiApp in gGlobalOptions: buildgui = CC[c].buildGui
      else: buildgui = ""
      var exefile: string
      if optGenDynLib in gGlobalOptions:
        exefile = platform.OS[targetOS].dllFrmt % splitFile(projectfile).name
        builddll = CC[c].buildDll
      else:
        exefile = splitFile(projectfile).name & platform.OS[targetOS].exeExt
        builddll = ""
      if options.outFile.len > 0:
        exefile = options.outFile.expandTilde
        if not exefile.isAbsolute():
          exefile = getCurrentDir() / exefile
      if not noAbsolutePaths():
        if not exefile.isAbsolute():
          exefile = joinPath(splitFile(projectfile).dir, exefile)
      if optCDebug in gGlobalOptions:
        writeDebugInfo(exefile.changeFileExt("ndb"))
      exefile = quoteShell(exefile)
      let linkOptions = getLinkOptions() & " " &
                        getConfigVar(cCompiler, ".options.linker")
      linkCmd = quoteShell(linkCmd % ["builddll", builddll,
          "buildgui", buildgui, "options", linkOptions, "objfiles", objfiles,
          "exefile", exefile, "nim", getPrefixDir(), "lib", libpath])
      linkCmd.add ' '
      addf(linkCmd, CC[c].linkTmpl, ["builddll", builddll,
          "buildgui", buildgui, "options", linkOptions,
          "objfiles", objfiles, "exefile", exefile,
          "nim", quoteShell(getPrefixDir()),
          "lib", quoteShell(libpath)])
    if optCompileOnly notin gGlobalOptions:
      execExternalProgram(linkCmd,
        if optListCmd in gGlobalOptions or gVerbosity > 1: hintExecuting else: hintLinking)
  else:
    linkCmd = ""
  if optGenScript in gGlobalOptions:
    add(script, linkCmd)
    add(script, tnl)
    generateScript(projectfile, script)

proc genMappingFiles(list: TLinkedList): Rope =
  var it = PStrEntry(list.head)
  while it != nil:
    addf(result, "--file:r\"$1\"$N", [rope(it.data)])
    it = PStrEntry(it.next)

proc writeMapping*(gSymbolMapping: Rope) =
  if optGenMapping notin gGlobalOptions: return
  var code = rope("[C_Files]\n")
  add(code, genMappingFiles(toCompile))
  add(code, genMappingFiles(externalToCompile))
  add(code, "\n[C_Compiler]\nFlags=")
  add(code, strutils.escape(getCompileOptions()))

  add(code, "\n[Linker]\nFlags=")
  add(code, strutils.escape(getLinkOptions() & " " &
                            getConfigVar(cCompiler, ".options.linker")))

  add(code, "\n[Environment]\nlibpath=")
  add(code, strutils.escape(libpath))

  addf(code, "\n[Symbols]$n$1", [gSymbolMapping])
  writeRope(code, joinPath(gProjectPath, "mapping.txt"))