pragmas.nim 49 KB

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