pragmas.nim 50 KB

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