pragmas.nim 51 KB

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