ccgutils.nim 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. # This module declares some helpers for the C code generator.
  10. import
  11. ast, types, msgs, wordrecg,
  12. platform, trees, options, cgendata
  13. import std/[hashes, strutils, formatfloat]
  14. when defined(nimPreviewSlimSystem):
  15. import std/assertions
  16. proc getPragmaStmt*(n: PNode, w: TSpecialWord): PNode =
  17. case n.kind
  18. of nkStmtList:
  19. result = nil
  20. for i in 0..<n.len:
  21. result = getPragmaStmt(n[i], w)
  22. if result != nil: break
  23. of nkPragma:
  24. result = nil
  25. for i in 0..<n.len:
  26. if whichPragma(n[i]) == w: return n[i]
  27. else:
  28. result = nil
  29. proc stmtsContainPragma*(n: PNode, w: TSpecialWord): bool =
  30. result = getPragmaStmt(n, w) != nil
  31. proc hashString*(conf: ConfigRef; s: string): BiggestInt =
  32. # has to be the same algorithm as strmantle.hashString!
  33. if CPU[conf.target.targetCPU].bit == 64:
  34. # we have to use the same bitwidth
  35. # as the target CPU
  36. var b = 0'u64
  37. for i in 0..<s.len:
  38. b = b + uint(s[i])
  39. b = b + (b shl 10)
  40. b = b xor (b shr 6)
  41. b = b + (b shl 3)
  42. b = b xor (b shr 11)
  43. b = b + (b shl 15)
  44. result = cast[Hash](b)
  45. else:
  46. var a = 0'u32
  47. for i in 0..<s.len:
  48. a = a + uint32(s[i])
  49. a = a + (a shl 10)
  50. a = a xor (a shr 6)
  51. a = a + (a shl 3)
  52. a = a xor (a shr 11)
  53. a = a + (a shl 15)
  54. result = cast[Hash](uint(a))
  55. template getUniqueType*(key: PType): PType = key
  56. proc makeSingleLineCString*(s: string): string =
  57. result = "\""
  58. for c in items(s):
  59. c.toCChar(result)
  60. result.add('\"')
  61. proc mangle*(name: string): string =
  62. result = newStringOfCap(name.len)
  63. var start = 0
  64. if name[0] in Digits:
  65. result.add("X" & name[0])
  66. start = 1
  67. var requiresUnderscore = false
  68. template special(x) =
  69. result.add x
  70. requiresUnderscore = true
  71. for i in start..<name.len:
  72. let c = name[i]
  73. case c
  74. of 'a'..'z', '0'..'9', 'A'..'Z':
  75. result.add(c)
  76. of '_':
  77. # we generate names like 'foo_9' for scope disambiguations and so
  78. # disallow this here:
  79. if i > 0 and i < name.len-1 and name[i+1] in Digits:
  80. discard
  81. else:
  82. result.add(c)
  83. of '$': special "dollar"
  84. of '%': special "percent"
  85. of '&': special "amp"
  86. of '^': special "roof"
  87. of '!': special "emark"
  88. of '?': special "qmark"
  89. of '*': special "star"
  90. of '+': special "plus"
  91. of '-': special "minus"
  92. of '/': special "slash"
  93. of '\\': special "backslash"
  94. of '=': special "eq"
  95. of '<': special "lt"
  96. of '>': special "gt"
  97. of '~': special "tilde"
  98. of ':': special "colon"
  99. of '.': special "dot"
  100. of '@': special "at"
  101. of '|': special "bar"
  102. else:
  103. result.add("X" & toHex(ord(c), 2))
  104. requiresUnderscore = true
  105. if requiresUnderscore:
  106. result.add "_"
  107. proc mapSetType(conf: ConfigRef; typ: PType): TCTypeKind =
  108. case int(getSize(conf, typ))
  109. of 1: result = ctInt8
  110. of 2: result = ctInt16
  111. of 4: result = ctInt32
  112. of 8: result = ctInt64
  113. else: result = ctArray
  114. proc ccgIntroducedPtr*(conf: ConfigRef; s: PSym, retType: PType): bool =
  115. var pt = skipTypes(s.typ, typedescInst)
  116. assert skResult != s.kind
  117. #note precedence: params override types
  118. if optByRef in s.options: return true
  119. elif sfByCopy in s.flags: return false
  120. elif tfByRef in pt.flags: return true
  121. elif tfByCopy in pt.flags: return false
  122. case pt.kind
  123. of tyObject:
  124. if s.typ.sym != nil and sfForward in s.typ.sym.flags:
  125. # forwarded objects are *always* passed by pointers for consistency!
  126. result = true
  127. elif (optByRef in s.options) or (getSize(conf, pt) > conf.target.floatSize * 3):
  128. result = true # requested anyway
  129. elif (tfFinal in pt.flags) and (pt[0] == nil):
  130. result = false # no need, because no subtyping possible
  131. else:
  132. result = true # ordinary objects are always passed by reference,
  133. # otherwise casting doesn't work
  134. of tyTuple:
  135. result = (getSize(conf, pt) > conf.target.floatSize*3) or (optByRef in s.options)
  136. else:
  137. result = false
  138. # first parameter and return type is 'lent T'? --> use pass by pointer
  139. if s.position == 0 and retType != nil and retType.kind == tyLent:
  140. result = not (pt.kind in {tyVar, tyArray, tyOpenArray, tyVarargs, tyRef, tyPtr, tyPointer} or
  141. pt.kind == tySet and mapSetType(conf, pt) == ctArray)
  142. proc encodeName*(name: string): string =
  143. result = mangle(name)
  144. result = $result.len & result
  145. proc makeUnique(m: BModule; s: PSym, name: string = ""): string =
  146. result = if name == "": s.name.s else: name
  147. result.add "__"
  148. result.add m.g.graph.ifaces[s.itemId.module].uniqueName
  149. result.add "_u"
  150. result.add $s.itemId.item
  151. proc encodeSym*(m: BModule; s: PSym; makeUnique: bool = false): string =
  152. #Module::Type
  153. var name = s.name.s
  154. if makeUnique:
  155. name = makeUnique(m, s, name)
  156. "N" & encodeName(s.owner.name.s) & encodeName(name) & "E"
  157. proc encodeType*(m: BModule; t: PType): string =
  158. result = ""
  159. var kindName = ($t.kind)[2..^1]
  160. kindName[0] = toLower($kindName[0])[0]
  161. case t.kind
  162. of tyObject, tyEnum, tyDistinct, tyUserTypeClass, tyGenericParam:
  163. result = encodeSym(m, t.sym)
  164. of tyGenericInst, tyUserTypeClassInst, tyGenericBody:
  165. result = encodeName(t[0].sym.name.s)
  166. result.add "I"
  167. for i in 1..<t.len - 1:
  168. result.add encodeType(m, t[i])
  169. result.add "E"
  170. of tySequence, tyOpenArray, tyArray, tyVarargs, tyTuple, tyProc, tySet, tyTypeDesc,
  171. tyPtr, tyRef, tyVar, tyLent, tySink, tyStatic, tyUncheckedArray, tyOr, tyAnd, tyBuiltInTypeClass:
  172. result =
  173. case t.kind:
  174. of tySequence: encodeName("seq")
  175. else: encodeName(kindName)
  176. result.add "I"
  177. for i in 0..<t.len:
  178. let s = t[i]
  179. if s.isNil: continue
  180. result.add encodeType(m, s)
  181. result.add "E"
  182. of tyRange:
  183. var val = "range_"
  184. if t.n[0].typ.kind in {tyFloat..tyFloat128}:
  185. val.addFloat t.n[0].floatVal
  186. val.add "_"
  187. val.addFloat t.n[1].floatVal
  188. else:
  189. val.add $t.n[0].intVal & "_" & $t.n[1].intVal
  190. result = encodeName(val)
  191. of tyString..tyUInt64, tyPointer, tyBool, tyChar, tyVoid, tyAnything, tyNil, tyEmpty:
  192. result = encodeName(kindName)
  193. of tyAlias, tyInferred, tyOwned:
  194. result = encodeType(m, t.elementType)
  195. else:
  196. assert false, "encodeType " & $t.kind