pragmas.nim 51 KB

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