pragmas.nim 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # This module implements semantic checking for pragmas
  10. import
  11. os, condsyms, ast, astalgo, idents, semdata, msgs, renderer,
  12. wordrecg, ropes, options, strutils, extccomp, math, magicsys, trees,
  13. types, lookups, lineinfos, pathutils, linter
  14. when defined(nimPreviewSlimSystem):
  15. import std/assertions
  16. from ic / ic import addCompilerProc
  17. const
  18. FirstCallConv* = wNimcall
  19. LastCallConv* = wNoconv
  20. const
  21. declPragmas = {wImportc, wImportObjC, wImportCpp, wImportJs, wExportc, wExportCpp,
  22. wExportNims, wExtern, wDeprecated, wNodecl, wError, wUsed}
  23. ## common pragmas for declarations, to a good approximation
  24. procPragmas* = declPragmas + {FirstCallConv..LastCallConv,
  25. wMagic, wNoSideEffect, wSideEffect, wNoreturn, wNosinks, wDynlib, wHeader,
  26. wCompilerProc, wNonReloadable, wCore, wProcVar, wVarargs, wCompileTime, wMerge,
  27. wBorrow, wImportCompilerProc, wThread,
  28. wAsmNoStackFrame, wDiscardable, wNoInit, wCodegenDecl,
  29. wGensym, wInject, wRaises, wEffectsOf, wTags, wForbids, wLocks, wDelegator, wGcSafe,
  30. wConstructor, wLiftLocals, wStackTrace, wLineTrace, wNoDestroy,
  31. wRequires, wEnsures, wEnforceNoRaises}
  32. converterPragmas* = procPragmas
  33. methodPragmas* = procPragmas+{wBase}-{wImportCpp}
  34. templatePragmas* = {wDeprecated, wError, wGensym, wInject, wDirty,
  35. wDelegator, wExportNims, wUsed, wPragma, wRedefine, wCallsite}
  36. macroPragmas* = declPragmas + {FirstCallConv..LastCallConv,
  37. wMagic, wNoSideEffect, wCompilerProc, wNonReloadable, wCore,
  38. wDiscardable, wGensym, wInject, wDelegator}
  39. iteratorPragmas* = declPragmas + {FirstCallConv..LastCallConv, wNoSideEffect, wSideEffect,
  40. wMagic, wBorrow,
  41. wDiscardable, wGensym, wInject, wRaises, wEffectsOf,
  42. wTags, wForbids, wLocks, wGcSafe, wRequires, wEnsures}
  43. exprPragmas* = {wLine, wLocks, wNoRewrite, wGcSafe, wNoSideEffect}
  44. stmtPragmas* = {
  45. wHint, wWarning, wError,
  46. wFatal, wDefine, wUndef, wCompile, wLink, wLinksys, wPure, wPush, wPop,
  47. wPassl, wPassc, wLocalPassc,
  48. wDeadCodeElimUnused, # deprecated, always on
  49. wDeprecated,
  50. wPragma, wEmit, wUnroll,
  51. wLinearScanEnd, wPatterns, wTrMacros, wEffects, wNoForward, wReorder, wComputedGoto,
  52. wExperimental, wDoctype, wThis, wUsed, wInvariant, wAssume, wAssert}
  53. stmtPragmasTopLevel* = {wChecks, wObjChecks, wFieldChecks, wRangeChecks,
  54. wBoundChecks, wOverflowChecks, wNilChecks, wStaticBoundchecks,
  55. wStyleChecks, wAssertions,
  56. wWarnings, wHints,
  57. wLineDir, wStackTrace, wLineTrace, wOptimization,
  58. wFloatChecks, wInfChecks, wNanChecks}
  59. lambdaPragmas* = {FirstCallConv..LastCallConv,
  60. wNoSideEffect, wSideEffect, wNoreturn, wNosinks, wDynlib, wHeader,
  61. wThread, wAsmNoStackFrame,
  62. wRaises, wLocks, wTags, wForbids, wRequires, wEnsures, wEffectsOf,
  63. wGcSafe, wCodegenDecl, wNoInit, wCompileTime}
  64. typePragmas* = declPragmas + {wMagic, wAcyclic,
  65. wPure, wHeader, wCompilerProc, wCore, wFinal, wSize, wShallow,
  66. wIncompleteStruct, wCompleteStruct, wByCopy, wByRef,
  67. wInheritable, wGensym, wInject, wRequiresInit, wUnchecked, wUnion, wPacked,
  68. wCppNonPod, wBorrow, wGcSafe, wPartial, wExplain, wPackage}
  69. fieldPragmas* = declPragmas + {wGuard, wBitsize, wCursor,
  70. wRequiresInit, wNoalias, wAlign} - {wExportNims, wNodecl} # why exclude these?
  71. varPragmas* = declPragmas + {wVolatile, wRegister, wThreadVar,
  72. wMagic, wHeader, wCompilerProc, wCore, wDynlib,
  73. wNoInit, wCompileTime, wGlobal,
  74. wGensym, wInject, wCodegenDecl,
  75. wGuard, wGoto, wCursor, wNoalias, wAlign}
  76. constPragmas* = declPragmas + {wHeader, wMagic,
  77. wGensym, wInject,
  78. wIntDefine, wStrDefine, wBoolDefine, wCompilerProc, wCore}
  79. paramPragmas* = {wNoalias, wInject, wGensym}
  80. letPragmas* = varPragmas
  81. procTypePragmas* = {FirstCallConv..LastCallConv, wVarargs, wNoSideEffect,
  82. wThread, wRaises, wEffectsOf, wLocks, wTags, wForbids, wGcSafe,
  83. wRequires, wEnsures}
  84. forVarPragmas* = {wInject, wGensym}
  85. allRoutinePragmas* = methodPragmas + iteratorPragmas + lambdaPragmas
  86. enumFieldPragmas* = {wDeprecated}
  87. proc getPragmaVal*(procAst: PNode; name: TSpecialWord): PNode =
  88. let p = procAst[pragmasPos]
  89. if p.kind == nkEmpty: return nil
  90. for it in p:
  91. if it.kind in nkPragmaCallKinds and it.len == 2 and it[0].kind == nkIdent and
  92. it[0].ident.id == ord(name):
  93. return it[1]
  94. proc pragma*(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords;
  95. isStatement: bool = false)
  96. proc recordPragma(c: PContext; n: PNode; args: varargs[string]) =
  97. var recorded = newNodeI(nkReplayAction, n.info)
  98. for i in 0..args.high:
  99. recorded.add newStrNode(args[i], n.info)
  100. addPragmaComputation(c, recorded)
  101. const
  102. errStringLiteralExpected = "string literal expected"
  103. errIntLiteralExpected = "integer literal expected"
  104. proc invalidPragma*(c: PContext; n: PNode) =
  105. localError(c.config, n.info, "invalid pragma: " & renderTree(n, {renderNoComments}))
  106. proc illegalCustomPragma*(c: PContext, n: PNode, s: PSym) =
  107. localError(c.config, n.info, "cannot attach a custom pragma to '" & s.name.s & "'")
  108. proc pragmaProposition(c: PContext, n: PNode) =
  109. if n.kind notin nkPragmaCallKinds or n.len != 2:
  110. localError(c.config, n.info, "proposition expected")
  111. else:
  112. n[1] = c.semExpr(c, n[1])
  113. proc pragmaEnsures(c: PContext, n: PNode) =
  114. if n.kind notin nkPragmaCallKinds or n.len != 2:
  115. localError(c.config, n.info, "proposition expected")
  116. else:
  117. openScope(c)
  118. let o = getCurrOwner(c)
  119. if o.kind in routineKinds and o.typ != nil and o.typ.sons[0] != nil:
  120. var s = newSym(skResult, getIdent(c.cache, "result"), nextSymId(c.idgen), o, n.info)
  121. s.typ = o.typ.sons[0]
  122. incl(s.flags, sfUsed)
  123. addDecl(c, s)
  124. n[1] = c.semExpr(c, n[1])
  125. closeScope(c)
  126. proc pragmaAsm*(c: PContext, n: PNode): char =
  127. result = '\0'
  128. if n != nil:
  129. for i in 0..<n.len:
  130. let it = n[i]
  131. if it.kind in nkPragmaCallKinds and it.len == 2 and it[0].kind == nkIdent:
  132. case whichKeyword(it[0].ident)
  133. of wSubsChar:
  134. if it[1].kind == nkCharLit: result = chr(int(it[1].intVal))
  135. else: invalidPragma(c, it)
  136. else: invalidPragma(c, it)
  137. else:
  138. invalidPragma(c, it)
  139. proc setExternName(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  140. # special cases to improve performance:
  141. if extname == "$1":
  142. s.loc.r = rope(s.name.s)
  143. elif '$' notin extname:
  144. s.loc.r = rope(extname)
  145. else:
  146. try:
  147. s.loc.r = rope(extname % s.name.s)
  148. except ValueError:
  149. localError(c.config, info, "invalid extern name: '" & extname & "'. (Forgot to escape '$'?)")
  150. when hasFFI:
  151. s.cname = $s.loc.r
  152. if c.config.cmd == cmdNimfix and '$' notin extname:
  153. # note that '{.importc.}' is transformed into '{.importc: "$1".}'
  154. s.loc.flags.incl(lfFullExternalName)
  155. proc makeExternImport(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  156. setExternName(c, s, extname, info)
  157. incl(s.flags, sfImportc)
  158. excl(s.flags, sfForward)
  159. proc makeExternExport(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  160. setExternName(c, s, extname, info)
  161. incl(s.flags, sfExportc)
  162. proc processImportCompilerProc(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  163. setExternName(c, s, extname, info)
  164. incl(s.flags, sfImportc)
  165. excl(s.flags, sfForward)
  166. incl(s.loc.flags, lfImportCompilerProc)
  167. proc processImportCpp(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  168. setExternName(c, s, extname, info)
  169. incl(s.flags, sfImportc)
  170. incl(s.flags, sfInfixCall)
  171. excl(s.flags, sfForward)
  172. if c.config.backend == backendC:
  173. let m = s.getModule()
  174. incl(m.flags, sfCompileToCpp)
  175. incl c.config.globalOptions, optMixedMode
  176. proc processImportObjC(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  177. setExternName(c, s, extname, info)
  178. incl(s.flags, sfImportc)
  179. incl(s.flags, sfNamedParamCall)
  180. excl(s.flags, sfForward)
  181. let m = s.getModule()
  182. incl(m.flags, sfCompileToObjc)
  183. proc newEmptyStrNode(c: PContext; n: PNode): PNode {.noinline.} =
  184. result = newNodeIT(nkStrLit, n.info, getSysType(c.graph, n.info, tyString))
  185. result.strVal = ""
  186. proc getStrLitNode(c: PContext, n: PNode): PNode =
  187. if n.kind notin nkPragmaCallKinds or n.len != 2:
  188. localError(c.config, n.info, errStringLiteralExpected)
  189. # error correction:
  190. result = newEmptyStrNode(c, n)
  191. else:
  192. n[1] = c.semConstExpr(c, n[1])
  193. case n[1].kind
  194. of nkStrLit, nkRStrLit, nkTripleStrLit: result = n[1]
  195. else:
  196. localError(c.config, n.info, errStringLiteralExpected)
  197. # error correction:
  198. result = newEmptyStrNode(c, n)
  199. proc expectStrLit(c: PContext, n: PNode): string =
  200. result = getStrLitNode(c, n).strVal
  201. proc expectIntLit(c: PContext, n: PNode): int =
  202. if n.kind notin nkPragmaCallKinds or n.len != 2:
  203. localError(c.config, n.info, errIntLiteralExpected)
  204. else:
  205. n[1] = c.semConstExpr(c, n[1])
  206. case n[1].kind
  207. of nkIntLit..nkInt64Lit: result = int(n[1].intVal)
  208. else: localError(c.config, n.info, errIntLiteralExpected)
  209. proc getOptionalStr(c: PContext, n: PNode, defaultStr: string): string =
  210. if n.kind in nkPragmaCallKinds: result = expectStrLit(c, n)
  211. else: result = defaultStr
  212. proc processCodegenDecl(c: PContext, n: PNode, sym: PSym) =
  213. sym.constraint = getStrLitNode(c, n)
  214. proc processMagic(c: PContext, n: PNode, s: PSym) =
  215. #if sfSystemModule notin c.module.flags:
  216. # liMessage(n.info, errMagicOnlyInSystem)
  217. if n.kind notin nkPragmaCallKinds or n.len != 2:
  218. localError(c.config, n.info, errStringLiteralExpected)
  219. return
  220. var v: string
  221. if n[1].kind == nkIdent: v = n[1].ident.s
  222. else: v = expectStrLit(c, n)
  223. for m in TMagic:
  224. if substr($m, 1) == v:
  225. s.magic = m
  226. break
  227. if s.magic == mNone: message(c.config, n.info, warnUnknownMagic, v)
  228. proc wordToCallConv(sw: TSpecialWord): TCallingConvention =
  229. # this assumes that the order of special words and calling conventions is
  230. # the same
  231. TCallingConvention(ord(ccNimCall) + ord(sw) - ord(wNimcall))
  232. proc isTurnedOn(c: PContext, n: PNode): bool =
  233. if n.kind in nkPragmaCallKinds and n.len == 2:
  234. let x = c.semConstBoolExpr(c, n[1])
  235. n[1] = x
  236. if x.kind == nkIntLit: return x.intVal != 0
  237. localError(c.config, n.info, "'on' or 'off' expected")
  238. proc onOff(c: PContext, n: PNode, op: TOptions, resOptions: var TOptions) =
  239. if isTurnedOn(c, n): resOptions.incl op
  240. else: resOptions.excl op
  241. proc pragmaNoForward(c: PContext, n: PNode; flag=sfNoForward) =
  242. if isTurnedOn(c, n):
  243. incl(c.module.flags, flag)
  244. c.features.incl codeReordering
  245. else:
  246. excl(c.module.flags, flag)
  247. # c.features.excl codeReordering
  248. # deprecated as of 0.18.1
  249. message(c.config, n.info, warnDeprecated,
  250. "use {.experimental: \"codeReordering\".} instead; " &
  251. (if flag == sfNoForward: "{.noForward.}" else: "{.reorder.}") & " is deprecated")
  252. proc processCallConv(c: PContext, n: PNode) =
  253. if n.kind in nkPragmaCallKinds and n.len == 2 and n[1].kind == nkIdent:
  254. let sw = whichKeyword(n[1].ident)
  255. case sw
  256. of FirstCallConv..LastCallConv:
  257. c.optionStack[^1].defaultCC = wordToCallConv(sw)
  258. else: localError(c.config, n.info, "calling convention expected")
  259. else:
  260. localError(c.config, n.info, "calling convention expected")
  261. proc getLib(c: PContext, kind: TLibKind, path: PNode): PLib =
  262. for it in c.libs:
  263. if it.kind == kind and trees.exprStructuralEquivalent(it.path, path):
  264. return it
  265. result = newLib(kind)
  266. result.path = path
  267. c.libs.add result
  268. if path.kind in {nkStrLit..nkTripleStrLit}:
  269. result.isOverriden = options.isDynlibOverride(c.config, path.strVal)
  270. proc expectDynlibNode(c: PContext, n: PNode): PNode =
  271. if n.kind notin nkPragmaCallKinds or n.len != 2:
  272. localError(c.config, n.info, errStringLiteralExpected)
  273. # error correction:
  274. result = newEmptyStrNode(c, n)
  275. else:
  276. # For the OpenGL wrapper we support:
  277. # {.dynlib: myGetProcAddr(...).}
  278. result = c.semExpr(c, n[1])
  279. if result.kind == nkSym and result.sym.kind == skConst:
  280. result = result.sym.astdef # look it up
  281. if result.typ == nil or result.typ.kind notin {tyPointer, tyString, tyProc}:
  282. localError(c.config, n.info, errStringLiteralExpected)
  283. result = newEmptyStrNode(c, n)
  284. proc processDynLib(c: PContext, n: PNode, sym: PSym) =
  285. if (sym == nil) or (sym.kind == skModule):
  286. let lib = getLib(c, libDynamic, expectDynlibNode(c, n))
  287. if not lib.isOverriden:
  288. c.optionStack[^1].dynlib = lib
  289. else:
  290. if n.kind in nkPragmaCallKinds:
  291. var lib = getLib(c, libDynamic, expectDynlibNode(c, n))
  292. if not lib.isOverriden:
  293. addToLib(lib, sym)
  294. incl(sym.loc.flags, lfDynamicLib)
  295. else:
  296. incl(sym.loc.flags, lfExportLib)
  297. # since we'll be loading the dynlib symbols dynamically, we must use
  298. # a calling convention that doesn't introduce custom name mangling
  299. # cdecl is the default - the user can override this explicitly
  300. if sym.kind in routineKinds and sym.typ != nil and
  301. tfExplicitCallConv notin sym.typ.flags:
  302. sym.typ.callConv = ccCDecl
  303. proc processNote(c: PContext, n: PNode) =
  304. template handleNote(enumVals, notes) =
  305. let x = findStr(enumVals.a, enumVals.b, n[0][1].ident.s, errUnknown)
  306. if x != errUnknown:
  307. nk = TNoteKind(x)
  308. let x = c.semConstBoolExpr(c, n[1])
  309. n[1] = x
  310. if x.kind == nkIntLit and x.intVal != 0: incl(notes, nk)
  311. else: excl(notes, nk)
  312. else:
  313. invalidPragma(c, n)
  314. if n.kind in nkPragmaCallKinds and n.len == 2 and
  315. n[0].kind == nkBracketExpr and
  316. n[0].len == 2 and
  317. n[0][1].kind == nkIdent and n[0][0].kind == nkIdent:
  318. var nk: TNoteKind
  319. case whichKeyword(n[0][0].ident)
  320. of wHint: handleNote(hintMin .. hintMax, c.config.notes)
  321. of wWarning: handleNote(warnMin .. warnMax, c.config.notes)
  322. of wWarningAsError: handleNote(warnMin .. warnMax, c.config.warningAsErrors)
  323. of wHintAsError: handleNote(hintMin .. hintMax, c.config.warningAsErrors)
  324. else: invalidPragma(c, n)
  325. else: invalidPragma(c, n)
  326. proc pragmaToOptions(w: TSpecialWord): TOptions {.inline.} =
  327. case w
  328. of wChecks: ChecksOptions
  329. of wObjChecks: {optObjCheck}
  330. of wFieldChecks: {optFieldCheck}
  331. of wRangeChecks: {optRangeCheck}
  332. of wBoundChecks: {optBoundsCheck}
  333. of wOverflowChecks: {optOverflowCheck}
  334. of wFloatChecks: {optNaNCheck, optInfCheck}
  335. of wNanChecks: {optNaNCheck}
  336. of wInfChecks: {optInfCheck}
  337. of wStaticBoundchecks: {optStaticBoundsCheck}
  338. of wStyleChecks: {optStyleCheck}
  339. of wAssertions: {optAssert}
  340. of wWarnings: {optWarns}
  341. of wHints: {optHints}
  342. of wLineDir: {optLineDir}
  343. of wStackTrace: {optStackTrace}
  344. of wLineTrace: {optLineTrace}
  345. of wDebugger: {optNone}
  346. of wProfiler: {optProfiler, optMemTracker}
  347. of wMemTracker: {optMemTracker}
  348. of wByRef: {optByRef}
  349. of wImplicitStatic: {optImplicitStatic}
  350. of wPatterns, wTrMacros: {optTrMacros}
  351. of wSinkInference: {optSinkInference}
  352. else: {}
  353. proc processExperimental(c: PContext; n: PNode) =
  354. if n.kind notin nkPragmaCallKinds or n.len != 2:
  355. c.features.incl oldExperimentalFeatures
  356. else:
  357. n[1] = c.semConstExpr(c, n[1])
  358. case n[1].kind
  359. of nkStrLit, nkRStrLit, nkTripleStrLit:
  360. try:
  361. let feature = parseEnum[Feature](n[1].strVal)
  362. c.features.incl feature
  363. if feature == codeReordering:
  364. if not isTopLevel(c):
  365. localError(c.config, n.info,
  366. "Code reordering experimental pragma only valid at toplevel")
  367. c.module.flags.incl sfReorder
  368. except ValueError:
  369. localError(c.config, n[1].info, "unknown experimental feature")
  370. else:
  371. localError(c.config, n.info, errStringLiteralExpected)
  372. proc tryProcessOption(c: PContext, n: PNode, resOptions: var TOptions): bool =
  373. result = true
  374. if n.kind notin nkPragmaCallKinds or n.len != 2: result = false
  375. elif n[0].kind == nkBracketExpr: processNote(c, n)
  376. elif n[0].kind != nkIdent: result = false
  377. else:
  378. let sw = whichKeyword(n[0].ident)
  379. if sw == wExperimental:
  380. processExperimental(c, n)
  381. return true
  382. let opts = pragmaToOptions(sw)
  383. if opts != {}:
  384. onOff(c, n, opts, resOptions)
  385. else:
  386. case sw
  387. of wCallconv: processCallConv(c, n)
  388. of wDynlib: processDynLib(c, n, nil)
  389. of wOptimization:
  390. if n[1].kind != nkIdent:
  391. invalidPragma(c, n)
  392. else:
  393. case n[1].ident.s.normalize
  394. of "speed":
  395. incl(resOptions, optOptimizeSpeed)
  396. excl(resOptions, optOptimizeSize)
  397. of "size":
  398. excl(resOptions, optOptimizeSpeed)
  399. incl(resOptions, optOptimizeSize)
  400. of "none":
  401. excl(resOptions, optOptimizeSpeed)
  402. excl(resOptions, optOptimizeSize)
  403. else: localError(c.config, n.info, "'none', 'speed' or 'size' expected")
  404. else: result = false
  405. proc processOption(c: PContext, n: PNode, resOptions: var TOptions) =
  406. if not tryProcessOption(c, n, resOptions):
  407. # calling conventions (boring...):
  408. localError(c.config, n.info, "option expected")
  409. proc processPush(c: PContext, n: PNode, start: int) =
  410. if n[start-1].kind in nkPragmaCallKinds:
  411. localError(c.config, n.info, "'push' cannot have arguments")
  412. var x = pushOptionEntry(c)
  413. for i in start..<n.len:
  414. if not tryProcessOption(c, n[i], c.config.options):
  415. # simply store it somewhere:
  416. if x.otherPragmas.isNil:
  417. x.otherPragmas = newNodeI(nkPragma, n.info)
  418. x.otherPragmas.add n[i]
  419. #localError(c.config, n.info, errOptionExpected)
  420. # If stacktrace is disabled globally we should not enable it
  421. if optStackTrace notin c.optionStack[0].options:
  422. c.config.options.excl(optStackTrace)
  423. when defined(debugOptions):
  424. echo c.config $ n.info, " PUSH config is now ", c.config.options
  425. proc processPop(c: PContext, n: PNode) =
  426. if c.optionStack.len <= 1:
  427. localError(c.config, n.info, "{.pop.} without a corresponding {.push.}")
  428. else:
  429. popOptionEntry(c)
  430. when defined(debugOptions):
  431. echo c.config $ n.info, " POP config is now ", c.config.options
  432. proc processDefine(c: PContext, n: PNode) =
  433. if (n.kind in nkPragmaCallKinds and n.len == 2) and (n[1].kind == nkIdent):
  434. defineSymbol(c.config.symbols, n[1].ident.s)
  435. else:
  436. invalidPragma(c, n)
  437. proc processUndef(c: PContext, n: PNode) =
  438. if (n.kind in nkPragmaCallKinds and n.len == 2) and (n[1].kind == nkIdent):
  439. undefSymbol(c.config.symbols, n[1].ident.s)
  440. else:
  441. invalidPragma(c, n)
  442. proc relativeFile(c: PContext; n: PNode; ext=""): AbsoluteFile =
  443. var s = expectStrLit(c, n)
  444. if ext.len > 0 and splitFile(s).ext == "":
  445. s = addFileExt(s, ext)
  446. result = AbsoluteFile parentDir(toFullPath(c.config, n.info)) / s
  447. if not fileExists(result):
  448. if isAbsolute(s): result = AbsoluteFile s
  449. else:
  450. result = findFile(c.config, s)
  451. if result.isEmpty: result = AbsoluteFile s
  452. proc processCompile(c: PContext, n: PNode) =
  453. proc docompile(c: PContext; it: PNode; src, dest: AbsoluteFile; customArgs: string) =
  454. var cf = Cfile(nimname: splitFile(src).name,
  455. cname: src, obj: dest, flags: {CfileFlag.External},
  456. customArgs: customArgs)
  457. extccomp.addExternalFileToCompile(c.config, cf)
  458. recordPragma(c, it, "compile", src.string, dest.string, customArgs)
  459. proc getStrLit(c: PContext, n: PNode; i: int): string =
  460. n[i] = c.semConstExpr(c, n[i])
  461. case n[i].kind
  462. of nkStrLit, nkRStrLit, nkTripleStrLit:
  463. when defined(gcArc) or defined(gcOrc):
  464. result = n[i].strVal
  465. else:
  466. shallowCopy(result, n[i].strVal)
  467. else:
  468. localError(c.config, n.info, errStringLiteralExpected)
  469. result = ""
  470. let it = if n.kind in nkPragmaCallKinds and n.len == 2: n[1] else: n
  471. if it.kind in {nkPar, nkTupleConstr} and it.len == 2:
  472. let s = getStrLit(c, it, 0)
  473. let dest = getStrLit(c, it, 1)
  474. var found = parentDir(toFullPath(c.config, n.info)) / s
  475. for f in os.walkFiles(found):
  476. let obj = completeCfilePath(c.config, AbsoluteFile(dest % extractFilename(f)))
  477. docompile(c, it, AbsoluteFile f, obj, "")
  478. else:
  479. var s = ""
  480. var customArgs = ""
  481. if n.kind in nkCallKinds:
  482. s = getStrLit(c, n, 1)
  483. if n.len <= 3:
  484. customArgs = getStrLit(c, n, 2)
  485. else:
  486. localError(c.config, n.info, "'.compile' pragma takes up 2 arguments")
  487. else:
  488. s = expectStrLit(c, n)
  489. var found = AbsoluteFile(parentDir(toFullPath(c.config, n.info)) / s)
  490. if not fileExists(found):
  491. if isAbsolute(s): found = AbsoluteFile s
  492. else:
  493. found = findFile(c.config, s)
  494. if found.isEmpty: found = AbsoluteFile s
  495. let obj = toObjFile(c.config, completeCfilePath(c.config, found, false))
  496. docompile(c, it, found, obj, customArgs)
  497. proc processLink(c: PContext, n: PNode) =
  498. let found = relativeFile(c, n, CC[c.config.cCompiler].objExt)
  499. extccomp.addExternalFileToLink(c.config, found)
  500. recordPragma(c, n, "link", found.string)
  501. proc semAsmOrEmit*(con: PContext, n: PNode, marker: char): PNode =
  502. case n[1].kind
  503. of nkStrLit, nkRStrLit, nkTripleStrLit:
  504. result = newNodeI(if n.kind == nkAsmStmt: nkAsmStmt else: nkArgList, n.info)
  505. var str = n[1].strVal
  506. if str == "":
  507. localError(con.config, n.info, "empty 'asm' statement")
  508. return
  509. # now parse the string literal and substitute symbols:
  510. var a = 0
  511. while true:
  512. var b = strutils.find(str, marker, a)
  513. var sub = if b < 0: substr(str, a) else: substr(str, a, b - 1)
  514. if sub != "": result.add newStrNode(nkStrLit, sub)
  515. if b < 0: break
  516. var c = strutils.find(str, marker, b + 1)
  517. if c < 0: sub = substr(str, b + 1)
  518. else: sub = substr(str, b + 1, c - 1)
  519. if sub != "":
  520. var amb = false
  521. var e = searchInScopes(con, getIdent(con.cache, sub), amb)
  522. # XXX what to do here if 'amb' is true?
  523. if e != nil:
  524. incl(e.flags, sfUsed)
  525. result.add newSymNode(e)
  526. else:
  527. result.add newStrNode(nkStrLit, sub)
  528. else:
  529. # an empty '``' produces a single '`'
  530. result.add newStrNode(nkStrLit, $marker)
  531. if c < 0: break
  532. a = c + 1
  533. else:
  534. illFormedAstLocal(n, con.config)
  535. result = newNodeI(nkAsmStmt, n.info)
  536. proc pragmaEmit(c: PContext, n: PNode) =
  537. if n.kind notin nkPragmaCallKinds or n.len != 2:
  538. localError(c.config, n.info, errStringLiteralExpected)
  539. else:
  540. let n1 = n[1]
  541. if n1.kind == nkBracket:
  542. var b = newNodeI(nkBracket, n1.info, n1.len)
  543. for i in 0..<n1.len:
  544. b[i] = c.semExpr(c, n1[i])
  545. n[1] = b
  546. else:
  547. n[1] = c.semConstExpr(c, n1)
  548. case n[1].kind
  549. of nkStrLit, nkRStrLit, nkTripleStrLit:
  550. n[1] = semAsmOrEmit(c, n, '`')
  551. else:
  552. localError(c.config, n.info, errStringLiteralExpected)
  553. proc noVal(c: PContext; n: PNode) =
  554. if n.kind in nkPragmaCallKinds and n.len > 1: invalidPragma(c, n)
  555. proc pragmaUnroll(c: PContext, n: PNode) =
  556. if c.p.nestedLoopCounter <= 0:
  557. invalidPragma(c, n)
  558. elif n.kind in nkPragmaCallKinds and n.len == 2:
  559. var unrollFactor = expectIntLit(c, n)
  560. if unrollFactor <% 32:
  561. n[1] = newIntNode(nkIntLit, unrollFactor)
  562. else:
  563. invalidPragma(c, n)
  564. proc pragmaLine(c: PContext, n: PNode) =
  565. if n.kind in nkPragmaCallKinds and n.len == 2:
  566. n[1] = c.semConstExpr(c, n[1])
  567. let a = n[1]
  568. if a.kind in {nkPar, nkTupleConstr}:
  569. # unpack the tuple
  570. var x = a[0]
  571. var y = a[1]
  572. if x.kind == nkExprColonExpr: x = x[1]
  573. if y.kind == nkExprColonExpr: y = y[1]
  574. if x.kind != nkStrLit:
  575. localError(c.config, n.info, errStringLiteralExpected)
  576. elif y.kind != nkIntLit:
  577. localError(c.config, n.info, errIntLiteralExpected)
  578. else:
  579. n.info.fileIndex = fileInfoIdx(c.config, AbsoluteFile(x.strVal))
  580. n.info.line = uint16(y.intVal)
  581. else:
  582. localError(c.config, n.info, "tuple expected")
  583. else:
  584. # sensible default:
  585. n.info = getInfoContext(c.config, -1)
  586. proc processPragma(c: PContext, n: PNode, i: int) =
  587. ## Create and add a new custom pragma `{.pragma: name.}` node to the module's context.
  588. let it = n[i]
  589. if it.kind notin nkPragmaCallKinds and it.safeLen == 2: invalidPragma(c, n)
  590. elif it.safeLen != 2 or it[0].kind != nkIdent or it[1].kind != nkIdent:
  591. invalidPragma(c, n)
  592. var userPragma = newSym(skTemplate, it[1].ident, nextSymId(c.idgen), c.module, it.info, c.config.options)
  593. userPragma.ast = newTreeI(nkPragma, n.info, n.sons[i+1..^1])
  594. strTableAdd(c.userPragmas, userPragma)
  595. proc pragmaRaisesOrTags(c: PContext, n: PNode) =
  596. proc processExc(c: PContext, x: PNode) =
  597. if c.hasUnresolvedArgs(c, x):
  598. x.typ = makeTypeFromExpr(c, x)
  599. else:
  600. var t = skipTypes(c.semTypeNode(c, x, nil), skipPtrs)
  601. if t.kind notin {tyObject, tyOr}:
  602. localError(c.config, x.info, errGenerated, "invalid type for raises/tags list")
  603. x.typ = t
  604. if n.kind in nkPragmaCallKinds and n.len == 2:
  605. let it = n[1]
  606. if it.kind notin {nkCurly, nkBracket}:
  607. processExc(c, it)
  608. else:
  609. for e in items(it): processExc(c, e)
  610. else:
  611. invalidPragma(c, n)
  612. proc pragmaLockStmt(c: PContext; it: PNode) =
  613. if it.kind notin nkPragmaCallKinds or it.len != 2:
  614. invalidPragma(c, it)
  615. else:
  616. let n = it[1]
  617. if n.kind != nkBracket:
  618. localError(c.config, n.info, errGenerated, "locks pragma takes a list of expressions")
  619. else:
  620. for i in 0..<n.len:
  621. n[i] = c.semExpr(c, n[i])
  622. proc pragmaLocks(c: PContext, it: PNode): TLockLevel =
  623. if it.kind notin nkPragmaCallKinds or it.len != 2:
  624. invalidPragma(c, it)
  625. else:
  626. case it[1].kind
  627. of nkStrLit, nkRStrLit, nkTripleStrLit:
  628. if it[1].strVal == "unknown":
  629. result = UnknownLockLevel
  630. else:
  631. localError(c.config, it[1].info, "invalid string literal for locks pragma (only allowed string is \"unknown\")")
  632. else:
  633. let x = expectIntLit(c, it)
  634. if x < 0 or x > MaxLockLevel:
  635. localError(c.config, it[1].info, "integer must be within 0.." & $MaxLockLevel)
  636. else:
  637. result = TLockLevel(x)
  638. proc typeBorrow(c: PContext; sym: PSym, n: PNode) =
  639. if n.kind in nkPragmaCallKinds and n.len == 2:
  640. let it = n[1]
  641. if it.kind != nkAccQuoted:
  642. localError(c.config, n.info, "a type can only borrow `.` for now")
  643. incl(sym.typ.flags, tfBorrowDot)
  644. proc markCompilerProc(c: PContext; s: PSym) =
  645. # minor hack ahead: FlowVar is the only generic .compilerproc type which
  646. # should not have an external name set:
  647. if s.kind != skType or s.name.s != "FlowVar":
  648. makeExternExport(c, s, "$1", s.info)
  649. incl(s.flags, sfCompilerProc)
  650. incl(s.flags, sfUsed)
  651. registerCompilerProc(c.graph, s)
  652. if c.config.symbolFiles != disabledSf:
  653. addCompilerProc(c.encoder, c.packedRepr, s)
  654. proc deprecatedStmt(c: PContext; outerPragma: PNode) =
  655. let pragma = outerPragma[1]
  656. if pragma.kind in {nkStrLit..nkTripleStrLit}:
  657. incl(c.module.flags, sfDeprecated)
  658. c.module.constraint = getStrLitNode(c, outerPragma)
  659. return
  660. if pragma.kind != nkBracket:
  661. localError(c.config, pragma.info, "list of key:value pairs expected"); return
  662. for n in pragma:
  663. if n.kind in nkPragmaCallKinds and n.len == 2:
  664. let dest = qualifiedLookUp(c, n[1], {checkUndeclared})
  665. if dest == nil or dest.kind in routineKinds:
  666. localError(c.config, n.info, warnUser, "the .deprecated pragma is unreliable for routines")
  667. let src = considerQuotedIdent(c, n[0])
  668. let alias = newSym(skAlias, src, nextSymId(c.idgen), dest, n[0].info, c.config.options)
  669. incl(alias.flags, sfExported)
  670. if sfCompilerProc in dest.flags: markCompilerProc(c, alias)
  671. addInterfaceDecl(c, alias)
  672. n[1] = newSymNode(dest)
  673. else:
  674. localError(c.config, n.info, "key:value pair expected")
  675. proc pragmaGuard(c: PContext; it: PNode; kind: TSymKind): PSym =
  676. if it.kind notin nkPragmaCallKinds or it.len != 2:
  677. invalidPragma(c, it); return
  678. let n = it[1]
  679. if n.kind == nkSym:
  680. result = n.sym
  681. elif kind == skField:
  682. # First check if the guard is a global variable:
  683. result = qualifiedLookUp(c, n, {})
  684. if result.isNil or result.kind notin {skLet, skVar} or
  685. sfGlobal notin result.flags:
  686. # We return a dummy symbol; later passes over the type will repair it.
  687. # Generic instantiation needs to know about this too. But we're lazy
  688. # and perform the lookup on demand instead.
  689. result = newSym(skUnknown, considerQuotedIdent(c, n), nextSymId(c.idgen), nil, n.info,
  690. c.config.options)
  691. else:
  692. result = qualifiedLookUp(c, n, {checkUndeclared})
  693. proc semCustomPragma(c: PContext, n: PNode): PNode =
  694. var callNode: PNode
  695. if n.kind in {nkIdent, nkSym}:
  696. # pragma -> pragma()
  697. callNode = newTree(nkCall, n)
  698. elif n.kind == nkExprColonExpr:
  699. # pragma: arg -> pragma(arg)
  700. callNode = newTree(nkCall, n[0], n[1])
  701. elif n.kind in nkPragmaCallKinds:
  702. callNode = n
  703. else:
  704. invalidPragma(c, n)
  705. return n
  706. let r = c.semOverloadedCall(c, callNode, n, {skTemplate}, {efNoUndeclared})
  707. if r.isNil or sfCustomPragma notin r[0].sym.flags:
  708. invalidPragma(c, n)
  709. return n
  710. result = r
  711. # Transform the nkCall node back to its original form if possible
  712. if n.kind == nkIdent and r.len == 1:
  713. # pragma() -> pragma
  714. result = result[0]
  715. elif n.kind == nkExprColonExpr and r.len == 2:
  716. # pragma(arg) -> pragma: arg
  717. result.transitionSonsKind(n.kind)
  718. proc processEffectsOf(c: PContext, n: PNode; owner: PSym) =
  719. proc processParam(c: PContext; n: PNode) =
  720. let r = c.semExpr(c, n)
  721. if r.kind == nkSym and r.sym.kind == skParam:
  722. if r.sym.owner == owner:
  723. incl r.sym.flags, sfEffectsDelayed
  724. else:
  725. localError(c.config, n.info, errGenerated, "parameter cannot be declared as .effectsOf")
  726. else:
  727. localError(c.config, n.info, errGenerated, "parameter name expected")
  728. if n.kind notin nkPragmaCallKinds or n.len != 2:
  729. localError(c.config, n.info, errGenerated, "parameter name expected")
  730. else:
  731. let it = n[1]
  732. if it.kind in {nkCurly, nkBracket}:
  733. for x in items(it): processParam(c, x)
  734. else:
  735. processParam(c, it)
  736. proc singlePragma(c: PContext, sym: PSym, n: PNode, i: var int,
  737. validPragmas: TSpecialWords,
  738. comesFromPush, isStatement: bool): bool =
  739. var it = n[i]
  740. var key = if it.kind in nkPragmaCallKinds and it.len > 1: it[0] else: it
  741. if key.kind == nkBracketExpr:
  742. processNote(c, it)
  743. return
  744. elif key.kind == nkCast:
  745. if comesFromPush:
  746. localError(c.config, n.info, "a 'cast' pragma cannot be pushed")
  747. elif not isStatement:
  748. localError(c.config, n.info, "'cast' pragma only allowed in a statement context")
  749. case whichPragma(key[1])
  750. of wRaises, wTags, wForbids: pragmaRaisesOrTags(c, key[1])
  751. else: discard
  752. return
  753. elif key.kind notin nkIdentKinds:
  754. n[i] = semCustomPragma(c, it)
  755. return
  756. let ident = considerQuotedIdent(c, key)
  757. var userPragma = strTableGet(c.userPragmas, ident)
  758. if userPragma != nil:
  759. styleCheckUse(c, key.info, userPragma)
  760. # number of pragmas increase/decrease with user pragma expansion
  761. inc c.instCounter
  762. if c.instCounter > 100:
  763. globalError(c.config, it.info, "recursive dependency: " & userPragma.name.s)
  764. pragma(c, sym, userPragma.ast, validPragmas, isStatement)
  765. n.sons[i..i] = userPragma.ast.sons # expand user pragma with its content
  766. i.inc(userPragma.ast.len - 1) # inc by -1 is ok, user pragmas was empty
  767. dec c.instCounter
  768. else:
  769. let k = whichKeyword(ident)
  770. if k in validPragmas:
  771. checkPragmaUse(c.config, key.info, k, ident.s)
  772. case k
  773. of wExportc, wExportCpp:
  774. makeExternExport(c, sym, getOptionalStr(c, it, "$1"), it.info)
  775. if k == wExportCpp:
  776. if c.config.backend != backendCpp:
  777. localError(c.config, it.info, "exportcpp requires `cpp` backend, got: " & $c.config.backend)
  778. else:
  779. incl(sym.flags, sfMangleCpp)
  780. incl(sym.flags, sfUsed) # avoid wrong hints
  781. of wImportc:
  782. let name = getOptionalStr(c, it, "$1")
  783. cppDefine(c.config, name)
  784. recordPragma(c, it, "cppdefine", name)
  785. makeExternImport(c, sym, name, it.info)
  786. of wImportCompilerProc:
  787. let name = getOptionalStr(c, it, "$1")
  788. cppDefine(c.config, name)
  789. recordPragma(c, it, "cppdefine", name)
  790. processImportCompilerProc(c, sym, name, it.info)
  791. of wExtern: setExternName(c, sym, expectStrLit(c, it), it.info)
  792. of wDirty:
  793. if sym.kind == skTemplate: incl(sym.flags, sfDirty)
  794. else: invalidPragma(c, it)
  795. of wRedefine:
  796. if sym.kind == skTemplate: incl(sym.flags, sfTemplateRedefinition)
  797. else: invalidPragma(c, it)
  798. of wCallsite:
  799. if sym.kind == skTemplate: incl(sym.flags, sfCallsite)
  800. else: invalidPragma(c, it)
  801. of wImportCpp:
  802. processImportCpp(c, sym, getOptionalStr(c, it, "$1"), it.info)
  803. of wCppNonPod:
  804. incl(sym.flags, sfCppNonPod)
  805. of wImportJs:
  806. if c.config.backend != backendJs:
  807. localError(c.config, it.info, "`importjs` pragma requires the JavaScript target")
  808. let name = getOptionalStr(c, it, "$1")
  809. incl(sym.flags, sfImportc)
  810. incl(sym.flags, sfInfixCall)
  811. if sym.kind in skProcKinds and {'(', '#', '@'} notin name:
  812. localError(c.config, n.info, "`importjs` for routines requires a pattern")
  813. setExternName(c, sym, name, it.info)
  814. of wImportObjC:
  815. processImportObjC(c, sym, getOptionalStr(c, it, "$1"), it.info)
  816. of wSize:
  817. if sym.typ == nil: invalidPragma(c, it)
  818. var size = expectIntLit(c, it)
  819. case size
  820. of 1, 2, 4:
  821. sym.typ.size = size
  822. sym.typ.align = int16 size
  823. of 8:
  824. sym.typ.size = 8
  825. sym.typ.align = floatInt64Align(c.config)
  826. else:
  827. localError(c.config, it.info, "size may only be 1, 2, 4 or 8")
  828. of wAlign:
  829. let alignment = expectIntLit(c, it)
  830. if isPowerOfTwo(alignment) and alignment > 0:
  831. sym.alignment = max(sym.alignment, alignment)
  832. else:
  833. localError(c.config, it.info, "power of two expected")
  834. of wNodecl:
  835. noVal(c, it)
  836. incl(sym.loc.flags, lfNoDecl)
  837. of wPure, wAsmNoStackFrame:
  838. noVal(c, it)
  839. if sym != nil:
  840. if k == wPure and sym.kind in routineKinds: invalidPragma(c, it)
  841. else: incl(sym.flags, sfPure)
  842. of wVolatile:
  843. noVal(c, it)
  844. incl(sym.flags, sfVolatile)
  845. of wCursor:
  846. noVal(c, it)
  847. incl(sym.flags, sfCursor)
  848. of wRegister:
  849. noVal(c, it)
  850. incl(sym.flags, sfRegister)
  851. of wNoalias:
  852. noVal(c, it)
  853. incl(sym.flags, sfNoalias)
  854. of wEffectsOf:
  855. processEffectsOf(c, it, sym)
  856. of wThreadVar:
  857. noVal(c, it)
  858. incl(sym.flags, {sfThread, sfGlobal})
  859. of wDeadCodeElimUnused: discard # deprecated, dead code elim always on
  860. of wNoForward: pragmaNoForward(c, it)
  861. of wReorder: pragmaNoForward(c, it, flag = sfReorder)
  862. of wMagic: processMagic(c, it, sym)
  863. of wCompileTime:
  864. noVal(c, it)
  865. if comesFromPush:
  866. if sym.kind in {skProc, skFunc}:
  867. incl(sym.flags, sfCompileTime)
  868. else:
  869. incl(sym.flags, sfCompileTime)
  870. #incl(sym.loc.flags, lfNoDecl)
  871. of wGlobal:
  872. noVal(c, it)
  873. incl(sym.flags, sfGlobal)
  874. incl(sym.flags, sfPure)
  875. of wMerge:
  876. # only supported for backwards compat, doesn't do anything anymore
  877. noVal(c, it)
  878. of wConstructor:
  879. noVal(c, it)
  880. incl(sym.flags, sfConstructor)
  881. of wHeader:
  882. var lib = getLib(c, libHeader, getStrLitNode(c, it))
  883. addToLib(lib, sym)
  884. incl(sym.flags, sfImportc)
  885. incl(sym.loc.flags, lfHeader)
  886. incl(sym.loc.flags, lfNoDecl)
  887. # implies nodecl, because otherwise header would not make sense
  888. if sym.loc.r == "": sym.loc.r = rope(sym.name.s)
  889. of wNoSideEffect:
  890. noVal(c, it)
  891. if sym != nil:
  892. incl(sym.flags, sfNoSideEffect)
  893. if sym.typ != nil: incl(sym.typ.flags, tfNoSideEffect)
  894. of wSideEffect:
  895. noVal(c, it)
  896. incl(sym.flags, sfSideEffect)
  897. of wNoreturn:
  898. noVal(c, it)
  899. # Disable the 'noreturn' annotation when in the "Quirky Exceptions" mode!
  900. if c.config.exc != excQuirky:
  901. incl(sym.flags, sfNoReturn)
  902. if sym.typ[0] != nil:
  903. localError(c.config, sym.ast[paramsPos][0].info,
  904. ".noreturn with return type not allowed")
  905. of wNoDestroy:
  906. noVal(c, it)
  907. incl(sym.flags, sfGeneratedOp)
  908. of wNosinks:
  909. noVal(c, it)
  910. incl(sym.flags, sfWasForwarded)
  911. of wDynlib:
  912. processDynLib(c, it, sym)
  913. of wCompilerProc, wCore:
  914. noVal(c, it) # compilerproc may not get a string!
  915. cppDefine(c.graph.config, sym.name.s)
  916. recordPragma(c, it, "cppdefine", sym.name.s)
  917. if sfFromGeneric notin sym.flags: markCompilerProc(c, sym)
  918. of wNonReloadable:
  919. sym.flags.incl sfNonReloadable
  920. of wProcVar:
  921. # old procvar annotation, no longer needed
  922. noVal(c, it)
  923. of wExplain:
  924. sym.flags.incl sfExplain
  925. of wDeprecated:
  926. if sym != nil and sym.kind in routineKinds + {skType, skVar, skLet, skConst}:
  927. if it.kind in nkPragmaCallKinds: discard getStrLitNode(c, it)
  928. incl(sym.flags, sfDeprecated)
  929. elif sym != nil and sym.kind != skModule:
  930. # We don't support the extra annotation field
  931. if it.kind in nkPragmaCallKinds:
  932. localError(c.config, it.info, "annotation to deprecated not supported here")
  933. incl(sym.flags, sfDeprecated)
  934. # At this point we're quite sure this is a statement and applies to the
  935. # whole module
  936. elif it.kind in nkPragmaCallKinds: deprecatedStmt(c, it)
  937. else: incl(c.module.flags, sfDeprecated)
  938. of wVarargs:
  939. noVal(c, it)
  940. if sym.typ == nil: invalidPragma(c, it)
  941. else: incl(sym.typ.flags, tfVarargs)
  942. of wBorrow:
  943. if sym.kind == skType:
  944. typeBorrow(c, sym, it)
  945. else:
  946. noVal(c, it)
  947. incl(sym.flags, sfBorrow)
  948. of wFinal:
  949. noVal(c, it)
  950. if sym.typ == nil: invalidPragma(c, it)
  951. else: incl(sym.typ.flags, tfFinal)
  952. of wInheritable:
  953. noVal(c, it)
  954. if sym.typ == nil or tfFinal in sym.typ.flags: invalidPragma(c, it)
  955. else: incl(sym.typ.flags, tfInheritable)
  956. of wPackage:
  957. noVal(c, it)
  958. if sym.typ == nil: invalidPragma(c, it)
  959. else: incl(sym.flags, sfForward)
  960. of wAcyclic:
  961. noVal(c, it)
  962. if sym.typ == nil: invalidPragma(c, it)
  963. else: incl(sym.typ.flags, tfAcyclic)
  964. of wShallow:
  965. noVal(c, it)
  966. if sym.typ == nil: invalidPragma(c, it)
  967. else: incl(sym.typ.flags, tfShallow)
  968. of wThread:
  969. noVal(c, it)
  970. incl(sym.flags, sfThread)
  971. if sym.typ != nil:
  972. incl(sym.typ.flags, tfThread)
  973. if sym.typ.callConv == ccClosure: sym.typ.callConv = ccNimCall
  974. of wGcSafe:
  975. noVal(c, it)
  976. if sym != nil:
  977. if sym.kind != skType: incl(sym.flags, sfThread)
  978. if sym.typ != nil: incl(sym.typ.flags, tfGcSafe)
  979. else: invalidPragma(c, it)
  980. else:
  981. discard "no checking if used as a code block"
  982. of wPacked:
  983. noVal(c, it)
  984. if sym.typ == nil: invalidPragma(c, it)
  985. else: incl(sym.typ.flags, tfPacked)
  986. of wHint:
  987. let s = expectStrLit(c, it)
  988. recordPragma(c, it, "hint", s)
  989. message(c.config, it.info, hintUser, s)
  990. of wWarning:
  991. let s = expectStrLit(c, it)
  992. recordPragma(c, it, "warning", s)
  993. message(c.config, it.info, warnUser, s)
  994. of wError:
  995. if sym != nil and (sym.isRoutine or sym.kind == skType) and not isStatement:
  996. # This is subtle but correct: the error *statement* is only
  997. # allowed when 'wUsed' is not in validPragmas. Here this is the easiest way to
  998. # distinguish properly between
  999. # ``proc p() {.error}`` and ``proc p() = {.error: "msg".}``
  1000. if it.kind in nkPragmaCallKinds: discard getStrLitNode(c, it)
  1001. incl(sym.flags, sfError)
  1002. excl(sym.flags, sfForward)
  1003. else:
  1004. let s = expectStrLit(c, it)
  1005. recordPragma(c, it, "error", s)
  1006. localError(c.config, it.info, errUser, s)
  1007. of wFatal: fatal(c.config, it.info, expectStrLit(c, it))
  1008. of wDefine: processDefine(c, it)
  1009. of wUndef: processUndef(c, it)
  1010. of wCompile: processCompile(c, it)
  1011. of wLink: processLink(c, it)
  1012. of wPassl:
  1013. let s = expectStrLit(c, it)
  1014. extccomp.addLinkOption(c.config, s)
  1015. recordPragma(c, it, "passl", s)
  1016. of wPassc:
  1017. let s = expectStrLit(c, it)
  1018. extccomp.addCompileOption(c.config, s)
  1019. recordPragma(c, it, "passc", s)
  1020. of wLocalPassc:
  1021. assert sym != nil and sym.kind == skModule
  1022. let s = expectStrLit(c, it)
  1023. extccomp.addLocalCompileOption(c.config, s, toFullPathConsiderDirty(c.config, sym.info.fileIndex))
  1024. recordPragma(c, it, "localpassl", s)
  1025. of wPush:
  1026. processPush(c, n, i + 1)
  1027. result = true
  1028. of wPop:
  1029. processPop(c, it)
  1030. result = true
  1031. of wPragma:
  1032. if not sym.isNil and sym.kind == skTemplate:
  1033. sym.flags.incl sfCustomPragma
  1034. else:
  1035. processPragma(c, n, i)
  1036. result = true
  1037. of wDiscardable:
  1038. noVal(c, it)
  1039. if sym != nil: incl(sym.flags, sfDiscardable)
  1040. of wNoInit:
  1041. noVal(c, it)
  1042. if sym != nil: incl(sym.flags, sfNoInit)
  1043. of wCodegenDecl: processCodegenDecl(c, it, sym)
  1044. of wChecks, wObjChecks, wFieldChecks, wRangeChecks, wBoundChecks,
  1045. wOverflowChecks, wNilChecks, wAssertions, wWarnings, wHints,
  1046. wLineDir, wOptimization, wStaticBoundchecks, wStyleChecks,
  1047. wCallconv, wDebugger, wProfiler,
  1048. wFloatChecks, wNanChecks, wInfChecks, wPatterns, wTrMacros:
  1049. processOption(c, it, c.config.options)
  1050. of wStackTrace, wLineTrace:
  1051. if sym.kind in {skProc, skMethod, skConverter}:
  1052. processOption(c, it, sym.options)
  1053. else:
  1054. processOption(c, it, c.config.options)
  1055. of FirstCallConv..LastCallConv:
  1056. assert(sym != nil)
  1057. if sym.typ == nil: invalidPragma(c, it)
  1058. else:
  1059. sym.typ.callConv = wordToCallConv(k)
  1060. sym.typ.flags.incl tfExplicitCallConv
  1061. of wEmit: pragmaEmit(c, it)
  1062. of wUnroll: pragmaUnroll(c, it)
  1063. of wLinearScanEnd, wComputedGoto: noVal(c, it)
  1064. of wEffects:
  1065. # is later processed in effect analysis:
  1066. noVal(c, it)
  1067. of wIncompleteStruct:
  1068. noVal(c, it)
  1069. if sym.typ == nil: invalidPragma(c, it)
  1070. else: incl(sym.typ.flags, tfIncompleteStruct)
  1071. of wCompleteStruct:
  1072. noVal(c, it)
  1073. if sym.typ == nil: invalidPragma(c, it)
  1074. else: incl(sym.typ.flags, tfCompleteStruct)
  1075. of wUnchecked:
  1076. noVal(c, it)
  1077. if sym.typ == nil or sym.typ.kind notin {tyArray, tyUncheckedArray}:
  1078. invalidPragma(c, it)
  1079. else:
  1080. sym.typ.kind = tyUncheckedArray
  1081. of wUnion:
  1082. if c.config.backend == backendJs:
  1083. localError(c.config, it.info, "`{.union.}` is not implemented for js backend.")
  1084. else:
  1085. noVal(c, it)
  1086. if sym.typ == nil: invalidPragma(c, it)
  1087. else: incl(sym.typ.flags, tfUnion)
  1088. of wRequiresInit:
  1089. noVal(c, it)
  1090. if sym.kind == skField:
  1091. sym.flags.incl sfRequiresInit
  1092. elif sym.typ != nil:
  1093. incl(sym.typ.flags, tfNeedsFullInit)
  1094. else:
  1095. invalidPragma(c, it)
  1096. of wByRef:
  1097. noVal(c, it)
  1098. if sym == nil or sym.typ == nil:
  1099. processOption(c, it, c.config.options)
  1100. else:
  1101. incl(sym.typ.flags, tfByRef)
  1102. of wByCopy:
  1103. noVal(c, it)
  1104. if sym.kind != skType or sym.typ == nil: invalidPragma(c, it)
  1105. else: incl(sym.typ.flags, tfByCopy)
  1106. of wPartial:
  1107. noVal(c, it)
  1108. if sym.kind != skType or sym.typ == nil: invalidPragma(c, it)
  1109. else:
  1110. incl(sym.typ.flags, tfPartial)
  1111. of wInject, wGensym:
  1112. # We check for errors, but do nothing with these pragmas otherwise
  1113. # as they are handled directly in 'evalTemplate'.
  1114. noVal(c, it)
  1115. if sym == nil: invalidPragma(c, it)
  1116. of wLine: pragmaLine(c, it)
  1117. of wRaises, wTags, wForbids: pragmaRaisesOrTags(c, it)
  1118. of wLocks:
  1119. if sym == nil: pragmaLockStmt(c, it)
  1120. elif sym.typ == nil: invalidPragma(c, it)
  1121. else: sym.typ.lockLevel = pragmaLocks(c, it)
  1122. of wBitsize:
  1123. if sym == nil or sym.kind != skField:
  1124. invalidPragma(c, it)
  1125. else:
  1126. sym.bitsize = expectIntLit(c, it)
  1127. if sym.bitsize <= 0:
  1128. localError(c.config, it.info, "bitsize needs to be positive")
  1129. of wGuard:
  1130. if sym == nil or sym.kind notin {skVar, skLet, skField}:
  1131. invalidPragma(c, it)
  1132. else:
  1133. sym.guard = pragmaGuard(c, it, sym.kind)
  1134. of wGoto:
  1135. if sym == nil or sym.kind notin {skVar, skLet}:
  1136. invalidPragma(c, it)
  1137. else:
  1138. sym.flags.incl sfGoto
  1139. of wExportNims:
  1140. if sym == nil: invalidPragma(c, it)
  1141. else: magicsys.registerNimScriptSymbol(c.graph, sym)
  1142. of wExperimental:
  1143. if not isTopLevel(c):
  1144. localError(c.config, n.info, "'experimental' pragma only valid as toplevel statement or in a 'push' environment")
  1145. processExperimental(c, it)
  1146. of wDoctype:
  1147. if not isTopLevel(c):
  1148. localError(c.config, n.info, "\"doctype\" pragma only valid as top-level statement")
  1149. of wNoRewrite:
  1150. noVal(c, it)
  1151. of wBase:
  1152. noVal(c, it)
  1153. sym.flags.incl sfBase
  1154. of wIntDefine:
  1155. sym.magic = mIntDefine
  1156. of wStrDefine:
  1157. sym.magic = mStrDefine
  1158. of wBoolDefine:
  1159. sym.magic = mBoolDefine
  1160. of wUsed:
  1161. noVal(c, it)
  1162. if sym == nil: invalidPragma(c, it)
  1163. else: sym.flags.incl sfUsed
  1164. of wLiftLocals: discard
  1165. of wRequires, wInvariant, wAssume, wAssert:
  1166. pragmaProposition(c, it)
  1167. of wEnsures:
  1168. pragmaEnsures(c, it)
  1169. of wEnforceNoRaises:
  1170. sym.flags.incl sfNeverRaises
  1171. else: invalidPragma(c, it)
  1172. elif comesFromPush and whichKeyword(ident) != wInvalid:
  1173. discard "ignore the .push pragma; it doesn't apply"
  1174. else:
  1175. if sym == nil or (sym.kind in {skVar, skLet, skConst, skParam, skIterator,
  1176. skField, skProc, skFunc, skConverter, skMethod, skType}):
  1177. n[i] = semCustomPragma(c, it)
  1178. elif sym != nil:
  1179. illegalCustomPragma(c, it, sym)
  1180. else:
  1181. invalidPragma(c, it)
  1182. proc overwriteLineInfo(n: PNode; info: TLineInfo) =
  1183. n.info = info
  1184. for i in 0..<n.safeLen:
  1185. overwriteLineInfo(n[i], info)
  1186. proc mergePragmas(n, pragmas: PNode) =
  1187. var pragmas = copyTree(pragmas)
  1188. overwriteLineInfo pragmas, n.info
  1189. if n[pragmasPos].kind == nkEmpty:
  1190. n[pragmasPos] = pragmas
  1191. else:
  1192. for p in pragmas: n[pragmasPos].add p
  1193. proc implicitPragmas*(c: PContext, sym: PSym, info: TLineInfo,
  1194. validPragmas: TSpecialWords) =
  1195. if sym != nil and sym.kind != skModule:
  1196. for it in c.optionStack:
  1197. let o = it.otherPragmas
  1198. if not o.isNil and sfFromGeneric notin sym.flags: # see issue #12985
  1199. pushInfoContext(c.config, info)
  1200. var i = 0
  1201. while i < o.len:
  1202. if singlePragma(c, sym, o, i, validPragmas, true, false):
  1203. internalError(c.config, info, "implicitPragmas")
  1204. inc i
  1205. popInfoContext(c.config)
  1206. if sym.kind in routineKinds and sym.ast != nil: mergePragmas(sym.ast, o)
  1207. if lfExportLib in sym.loc.flags and sfExportc notin sym.flags:
  1208. localError(c.config, info, ".dynlib requires .exportc")
  1209. var lib = c.optionStack[^1].dynlib
  1210. if {lfDynamicLib, lfHeader} * sym.loc.flags == {} and
  1211. sfImportc in sym.flags and lib != nil:
  1212. incl(sym.loc.flags, lfDynamicLib)
  1213. addToLib(lib, sym)
  1214. if sym.loc.r == "": sym.loc.r = rope(sym.name.s)
  1215. proc hasPragma*(n: PNode, pragma: TSpecialWord): bool =
  1216. if n == nil: return false
  1217. for p in n:
  1218. var key = if p.kind in nkPragmaCallKinds and p.len > 1: p[0] else: p
  1219. if key.kind == nkIdent and whichKeyword(key.ident) == pragma:
  1220. return true
  1221. return false
  1222. proc pragmaRec(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords;
  1223. isStatement: bool) =
  1224. if n == nil: return
  1225. var i = 0
  1226. while i < n.len:
  1227. if singlePragma(c, sym, n, i, validPragmas, false, isStatement): break
  1228. inc i
  1229. proc pragma(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords;
  1230. isStatement: bool) =
  1231. if n == nil: return
  1232. pragmaRec(c, sym, n, validPragmas, isStatement)
  1233. # XXX: in the case of a callable def, this should use its info
  1234. implicitPragmas(c, sym, n.info, validPragmas)
  1235. proc pragmaCallable*(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords,
  1236. isStatement: bool = false) =
  1237. if n == nil: return
  1238. if n[pragmasPos].kind != nkEmpty:
  1239. pragmaRec(c, sym, n[pragmasPos], validPragmas, isStatement)