tccgen.nim 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. import
  10. os, strutils, options, msgs, tinyc
  11. {.compile: "../tinyc/libtcc.c".}
  12. proc tinyCErrorHandler(closure: pointer, msg: cstring) {.cdecl.} =
  13. rawMessage(errGenerated, $msg)
  14. proc initTinyCState: PccState =
  15. result = openCCState()
  16. setErrorFunc(result, nil, tinyCErrorHandler)
  17. var
  18. gTinyC = initTinyCState()
  19. libIncluded = false
  20. proc addFile(filename: string) =
  21. if addFile(gTinyC, filename) != 0'i32:
  22. rawMessage(errCannotOpenFile, filename)
  23. proc setupEnvironment =
  24. when defined(amd64):
  25. defineSymbol(gTinyC, "__x86_64__", nil)
  26. elif defined(i386):
  27. defineSymbol(gTinyC, "__i386__", nil)
  28. when defined(linux):
  29. defineSymbol(gTinyC, "__linux__", nil)
  30. defineSymbol(gTinyC, "__linux", nil)
  31. var nimDir = getPrefixDir()
  32. addIncludePath(gTinyC, libpath)
  33. when defined(windows):
  34. addSysincludePath(gTinyC, nimrodDir / "tinyc/win32/include")
  35. addSysincludePath(gTinyC, nimrodDir / "tinyc/include")
  36. when defined(windows):
  37. defineSymbol(gTinyC, "_WIN32", nil)
  38. # we need Mingw's headers too:
  39. var gccbin = getConfigVar("gcc.path") % ["nim", nimDir]
  40. addSysincludePath(gTinyC, gccbin /../ "include")
  41. #addFile(nimrodDir / r"tinyc\win32\wincrt1.o")
  42. addFile(nimrodDir / r"tinyc\win32\alloca86.o")
  43. addFile(nimrodDir / r"tinyc\win32\chkstk.o")
  44. #addFile(nimrodDir / r"tinyc\win32\crt1.o")
  45. #addFile(nimrodDir / r"tinyc\win32\dllcrt1.o")
  46. #addFile(nimrodDir / r"tinyc\win32\dllmain.o")
  47. addFile(nimrodDir / r"tinyc\win32\libtcc1.o")
  48. #addFile(nimrodDir / r"tinyc\win32\lib\crt1.c")
  49. #addFile(nimrodDir / r"tinyc\lib\libtcc1.c")
  50. else:
  51. addSysincludePath(gTinyC, "/usr/include")
  52. when defined(amd64):
  53. addSysincludePath(gTinyC, "/usr/include/x86_64-linux-gnu")
  54. proc compileCCode*(ccode: string) =
  55. if not libIncluded:
  56. libIncluded = true
  57. setupEnvironment()
  58. discard compileString(gTinyC, ccode)
  59. proc run*(args: string) =
  60. var s = @[cstring(gProjectName)] & map(split(args), proc(x: string): cstring = cstring(x))
  61. var err = tinyc.run(gTinyC, cint(len(s)), cast[cstringArray](addr(s[0]))) != 0'i32
  62. closeCCState(gTinyC)
  63. if err: rawMessage(errExecutionOfProgramFailed, "")