pragmas.nim 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325
  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. if not fileExists(src):
  466. localError(c.config, n.info, "cannot find: " & src.string)
  467. else:
  468. extccomp.addExternalFileToCompile(c.config, cf)
  469. recordPragma(c, it, "compile", src.string, dest.string, customArgs)
  470. proc getStrLit(c: PContext, n: PNode; i: int): string =
  471. n[i] = c.semConstExpr(c, n[i])
  472. case n[i].kind
  473. of nkStrLit, nkRStrLit, nkTripleStrLit:
  474. when defined(gcArc) or defined(gcOrc):
  475. result = n[i].strVal
  476. else:
  477. shallowCopy(result, n[i].strVal)
  478. else:
  479. localError(c.config, n.info, errStringLiteralExpected)
  480. result = ""
  481. let it = if n.kind in nkPragmaCallKinds and n.len == 2: n[1] else: n
  482. if it.kind in {nkPar, nkTupleConstr} and it.len == 2:
  483. let s = getStrLit(c, it, 0)
  484. let dest = getStrLit(c, it, 1)
  485. var found = parentDir(toFullPath(c.config, n.info)) / s
  486. for f in os.walkFiles(found):
  487. let obj = completeCfilePath(c.config, AbsoluteFile(dest % extractFilename(f)))
  488. docompile(c, it, AbsoluteFile f, obj, "")
  489. else:
  490. var s = ""
  491. var customArgs = ""
  492. if n.kind in nkCallKinds:
  493. s = getStrLit(c, n, 1)
  494. if n.len <= 3:
  495. customArgs = getStrLit(c, n, 2)
  496. else:
  497. localError(c.config, n.info, "'.compile' pragma takes up 2 arguments")
  498. else:
  499. s = expectStrLit(c, n)
  500. var found = AbsoluteFile(parentDir(toFullPath(c.config, n.info)) / s)
  501. if not fileExists(found):
  502. if isAbsolute(s): found = AbsoluteFile s
  503. else:
  504. found = findFile(c.config, s)
  505. if found.isEmpty: found = AbsoluteFile s
  506. let obj = toObjFile(c.config, completeCfilePath(c.config, found, false))
  507. docompile(c, it, found, obj, customArgs)
  508. proc processLink(c: PContext, n: PNode) =
  509. let found = relativeFile(c, n, CC[c.config.cCompiler].objExt)
  510. extccomp.addExternalFileToLink(c.config, found)
  511. recordPragma(c, n, "link", found.string)
  512. proc semAsmOrEmit*(con: PContext, n: PNode, marker: char): PNode =
  513. case n[1].kind
  514. of nkStrLit, nkRStrLit, nkTripleStrLit:
  515. result = newNodeI(if n.kind == nkAsmStmt: nkAsmStmt else: nkArgList, n.info)
  516. var str = n[1].strVal
  517. if str == "":
  518. localError(con.config, n.info, "empty 'asm' statement")
  519. return
  520. # now parse the string literal and substitute symbols:
  521. var a = 0
  522. while true:
  523. var b = strutils.find(str, marker, a)
  524. var sub = if b < 0: substr(str, a) else: substr(str, a, b - 1)
  525. if sub != "": result.add newStrNode(nkStrLit, sub)
  526. if b < 0: break
  527. var c = strutils.find(str, marker, b + 1)
  528. if c < 0: sub = substr(str, b + 1)
  529. else: sub = substr(str, b + 1, c - 1)
  530. if sub != "":
  531. var amb = false
  532. var e = searchInScopes(con, getIdent(con.cache, sub), amb)
  533. # XXX what to do here if 'amb' is true?
  534. if e != nil:
  535. incl(e.flags, sfUsed)
  536. result.add newSymNode(e)
  537. else:
  538. result.add newStrNode(nkStrLit, sub)
  539. else:
  540. # an empty '``' produces a single '`'
  541. result.add newStrNode(nkStrLit, $marker)
  542. if c < 0: break
  543. a = c + 1
  544. else:
  545. illFormedAstLocal(n, con.config)
  546. result = newNodeI(nkAsmStmt, n.info)
  547. proc pragmaEmit(c: PContext, n: PNode) =
  548. if n.kind notin nkPragmaCallKinds or n.len != 2:
  549. localError(c.config, n.info, errStringLiteralExpected)
  550. else:
  551. let n1 = n[1]
  552. if n1.kind == nkBracket:
  553. var b = newNodeI(nkBracket, n1.info, n1.len)
  554. for i in 0..<n1.len:
  555. b[i] = c.semExpr(c, n1[i])
  556. n[1] = b
  557. else:
  558. n[1] = c.semConstExpr(c, n1)
  559. case n[1].kind
  560. of nkStrLit, nkRStrLit, nkTripleStrLit:
  561. n[1] = semAsmOrEmit(c, n, '`')
  562. else:
  563. localError(c.config, n.info, errStringLiteralExpected)
  564. proc noVal(c: PContext; n: PNode) =
  565. if n.kind in nkPragmaCallKinds and n.len > 1: invalidPragma(c, n)
  566. proc pragmaUnroll(c: PContext, n: PNode) =
  567. if c.p.nestedLoopCounter <= 0:
  568. invalidPragma(c, n)
  569. elif n.kind in nkPragmaCallKinds and n.len == 2:
  570. var unrollFactor = expectIntLit(c, n)
  571. if unrollFactor <% 32:
  572. n[1] = newIntNode(nkIntLit, unrollFactor)
  573. else:
  574. invalidPragma(c, n)
  575. proc pragmaLine(c: PContext, n: PNode) =
  576. if n.kind in nkPragmaCallKinds and n.len == 2:
  577. n[1] = c.semConstExpr(c, n[1])
  578. let a = n[1]
  579. if a.kind in {nkPar, nkTupleConstr}:
  580. # unpack the tuple
  581. var x = a[0]
  582. var y = a[1]
  583. if x.kind == nkExprColonExpr: x = x[1]
  584. if y.kind == nkExprColonExpr: y = y[1]
  585. if x.kind != nkStrLit:
  586. localError(c.config, n.info, errStringLiteralExpected)
  587. elif y.kind != nkIntLit:
  588. localError(c.config, n.info, errIntLiteralExpected)
  589. else:
  590. n.info.fileIndex = fileInfoIdx(c.config, AbsoluteFile(x.strVal))
  591. n.info.line = uint16(y.intVal)
  592. else:
  593. localError(c.config, n.info, "tuple expected")
  594. else:
  595. # sensible default:
  596. n.info = getInfoContext(c.config, -1)
  597. proc processPragma(c: PContext, n: PNode, i: int) =
  598. ## Create and add a new custom pragma `{.pragma: name.}` node to the module's context.
  599. let it = n[i]
  600. if it.kind notin nkPragmaCallKinds and it.safeLen == 2: invalidPragma(c, n)
  601. elif it.safeLen != 2 or it[0].kind != nkIdent or it[1].kind != nkIdent:
  602. invalidPragma(c, n)
  603. var userPragma = newSym(skTemplate, it[1].ident, nextSymId(c.idgen), c.module, it.info, c.config.options)
  604. userPragma.ast = newTreeI(nkPragma, n.info, n.sons[i+1..^1])
  605. strTableAdd(c.userPragmas, userPragma)
  606. proc pragmaRaisesOrTags(c: PContext, n: PNode) =
  607. proc processExc(c: PContext, x: PNode) =
  608. if c.hasUnresolvedArgs(c, x):
  609. x.typ = makeTypeFromExpr(c, x)
  610. else:
  611. var t = skipTypes(c.semTypeNode(c, x, nil), skipPtrs)
  612. if t.kind notin {tyObject, tyOr}:
  613. localError(c.config, x.info, errGenerated, "invalid type for raises/tags list")
  614. x.typ = t
  615. if n.kind in nkPragmaCallKinds and n.len == 2:
  616. let it = n[1]
  617. if it.kind notin {nkCurly, nkBracket}:
  618. processExc(c, it)
  619. else:
  620. for e in items(it): processExc(c, e)
  621. else:
  622. invalidPragma(c, n)
  623. proc pragmaLockStmt(c: PContext; it: PNode) =
  624. if it.kind notin nkPragmaCallKinds or it.len != 2:
  625. invalidPragma(c, it)
  626. else:
  627. let n = it[1]
  628. if n.kind != nkBracket:
  629. localError(c.config, n.info, errGenerated, "locks pragma takes a list of expressions")
  630. else:
  631. for i in 0..<n.len:
  632. n[i] = c.semExpr(c, n[i])
  633. proc typeBorrow(c: PContext; sym: PSym, n: PNode) =
  634. if n.kind in nkPragmaCallKinds and n.len == 2:
  635. let it = n[1]
  636. if it.kind != nkAccQuoted:
  637. localError(c.config, n.info, "a type can only borrow `.` for now")
  638. incl(sym.typ.flags, tfBorrowDot)
  639. proc markCompilerProc(c: PContext; s: PSym) =
  640. # minor hack ahead: FlowVar is the only generic .compilerproc type which
  641. # should not have an external name set:
  642. if s.kind != skType or s.name.s != "FlowVar":
  643. makeExternExport(c, s, "$1", s.info)
  644. incl(s.flags, sfCompilerProc)
  645. incl(s.flags, sfUsed)
  646. registerCompilerProc(c.graph, s)
  647. if c.config.symbolFiles != disabledSf:
  648. addCompilerProc(c.encoder, c.packedRepr, s)
  649. proc deprecatedStmt(c: PContext; outerPragma: PNode) =
  650. let pragma = outerPragma[1]
  651. if pragma.kind in {nkStrLit..nkTripleStrLit}:
  652. incl(c.module.flags, sfDeprecated)
  653. c.module.constraint = getStrLitNode(c, outerPragma)
  654. return
  655. if pragma.kind != nkBracket:
  656. localError(c.config, pragma.info, "list of key:value pairs expected"); return
  657. for n in pragma:
  658. if n.kind in nkPragmaCallKinds and n.len == 2:
  659. let dest = qualifiedLookUp(c, n[1], {checkUndeclared})
  660. if dest == nil or dest.kind in routineKinds:
  661. localError(c.config, n.info, warnUser, "the .deprecated pragma is unreliable for routines")
  662. let src = considerQuotedIdent(c, n[0])
  663. let alias = newSym(skAlias, src, nextSymId(c.idgen), dest, n[0].info, c.config.options)
  664. incl(alias.flags, sfExported)
  665. if sfCompilerProc in dest.flags: markCompilerProc(c, alias)
  666. addInterfaceDecl(c, alias)
  667. n[1] = newSymNode(dest)
  668. else:
  669. localError(c.config, n.info, "key:value pair expected")
  670. proc pragmaGuard(c: PContext; it: PNode; kind: TSymKind): PSym =
  671. if it.kind notin nkPragmaCallKinds or it.len != 2:
  672. invalidPragma(c, it); return
  673. let n = it[1]
  674. if n.kind == nkSym:
  675. result = n.sym
  676. elif kind == skField:
  677. # First check if the guard is a global variable:
  678. result = qualifiedLookUp(c, n, {})
  679. if result.isNil or result.kind notin {skLet, skVar} or
  680. sfGlobal notin result.flags:
  681. # We return a dummy symbol; later passes over the type will repair it.
  682. # Generic instantiation needs to know about this too. But we're lazy
  683. # and perform the lookup on demand instead.
  684. result = newSym(skUnknown, considerQuotedIdent(c, n), nextSymId(c.idgen), nil, n.info,
  685. c.config.options)
  686. else:
  687. result = qualifiedLookUp(c, n, {checkUndeclared})
  688. proc semCustomPragma(c: PContext, n: PNode): PNode =
  689. var callNode: PNode
  690. if n.kind in {nkIdent, nkSym}:
  691. # pragma -> pragma()
  692. callNode = newTree(nkCall, n)
  693. elif n.kind == nkExprColonExpr:
  694. # pragma: arg -> pragma(arg)
  695. callNode = newTree(nkCall, n[0], n[1])
  696. elif n.kind in nkPragmaCallKinds:
  697. callNode = n
  698. else:
  699. invalidPragma(c, n)
  700. return n
  701. let r = c.semOverloadedCall(c, callNode, n, {skTemplate}, {efNoUndeclared})
  702. if r.isNil or sfCustomPragma notin r[0].sym.flags:
  703. invalidPragma(c, n)
  704. return n
  705. result = r
  706. # Transform the nkCall node back to its original form if possible
  707. if n.kind == nkIdent and r.len == 1:
  708. # pragma() -> pragma
  709. result = result[0]
  710. elif n.kind == nkExprColonExpr and r.len == 2:
  711. # pragma(arg) -> pragma: arg
  712. result.transitionSonsKind(n.kind)
  713. proc processEffectsOf(c: PContext, n: PNode; owner: PSym) =
  714. proc processParam(c: PContext; n: PNode) =
  715. let r = c.semExpr(c, n)
  716. if r.kind == nkSym and r.sym.kind == skParam:
  717. if r.sym.owner == owner:
  718. incl r.sym.flags, sfEffectsDelayed
  719. else:
  720. localError(c.config, n.info, errGenerated, "parameter cannot be declared as .effectsOf")
  721. else:
  722. localError(c.config, n.info, errGenerated, "parameter name expected")
  723. if n.kind notin nkPragmaCallKinds or n.len != 2:
  724. localError(c.config, n.info, errGenerated, "parameter name expected")
  725. else:
  726. let it = n[1]
  727. if it.kind in {nkCurly, nkBracket}:
  728. for x in items(it): processParam(c, x)
  729. else:
  730. processParam(c, it)
  731. proc singlePragma(c: PContext, sym: PSym, n: PNode, i: var int,
  732. validPragmas: TSpecialWords,
  733. comesFromPush, isStatement: bool): bool =
  734. var it = n[i]
  735. var key = if it.kind in nkPragmaCallKinds and it.len > 1: it[0] else: it
  736. if key.kind == nkBracketExpr:
  737. processNote(c, it)
  738. return
  739. elif key.kind == nkCast:
  740. if comesFromPush:
  741. localError(c.config, n.info, "a 'cast' pragma cannot be pushed")
  742. elif not isStatement:
  743. localError(c.config, n.info, "'cast' pragma only allowed in a statement context")
  744. case whichPragma(key[1])
  745. of wRaises, wTags, wForbids: pragmaRaisesOrTags(c, key[1])
  746. else: discard
  747. return
  748. elif key.kind notin nkIdentKinds:
  749. n[i] = semCustomPragma(c, it)
  750. return
  751. let ident = considerQuotedIdent(c, key)
  752. var userPragma = strTableGet(c.userPragmas, ident)
  753. if userPragma != nil:
  754. styleCheckUse(c, key.info, userPragma)
  755. # number of pragmas increase/decrease with user pragma expansion
  756. inc c.instCounter
  757. if c.instCounter > 100:
  758. globalError(c.config, it.info, "recursive dependency: " & userPragma.name.s)
  759. pragma(c, sym, userPragma.ast, validPragmas, isStatement)
  760. n.sons[i..i] = userPragma.ast.sons # expand user pragma with its content
  761. i.inc(userPragma.ast.len - 1) # inc by -1 is ok, user pragmas was empty
  762. dec c.instCounter
  763. else:
  764. let k = whichKeyword(ident)
  765. if k in validPragmas:
  766. checkPragmaUse(c.config, key.info, k, ident.s)
  767. case k
  768. of wExportc, wExportCpp:
  769. makeExternExport(c, sym, getOptionalStr(c, it, "$1"), it.info)
  770. if k == wExportCpp:
  771. if c.config.backend != backendCpp:
  772. localError(c.config, it.info, "exportcpp requires `cpp` backend, got: " & $c.config.backend)
  773. else:
  774. incl(sym.flags, sfMangleCpp)
  775. incl(sym.flags, sfUsed) # avoid wrong hints
  776. of wImportc:
  777. let name = getOptionalStr(c, it, "$1")
  778. cppDefine(c.config, name)
  779. recordPragma(c, it, "cppdefine", name)
  780. makeExternImport(c, sym, name, it.info)
  781. of wImportCompilerProc:
  782. let name = getOptionalStr(c, it, "$1")
  783. cppDefine(c.config, name)
  784. recordPragma(c, it, "cppdefine", name)
  785. processImportCompilerProc(c, sym, name, it.info)
  786. of wExtern: setExternName(c, sym, expectStrLit(c, it), it.info)
  787. of wDirty:
  788. if sym.kind == skTemplate: incl(sym.flags, sfDirty)
  789. else: invalidPragma(c, it)
  790. of wRedefine:
  791. if sym.kind == skTemplate: incl(sym.flags, sfTemplateRedefinition)
  792. else: invalidPragma(c, it)
  793. of wCallsite:
  794. if sym.kind == skTemplate: incl(sym.flags, sfCallsite)
  795. else: invalidPragma(c, it)
  796. of wImportCpp:
  797. processImportCpp(c, sym, getOptionalStr(c, it, "$1"), it.info)
  798. of wCppNonPod:
  799. incl(sym.flags, sfCppNonPod)
  800. of wImportJs:
  801. if c.config.backend != backendJs:
  802. localError(c.config, it.info, "`importjs` pragma requires the JavaScript target")
  803. let name = getOptionalStr(c, it, "$1")
  804. incl(sym.flags, sfImportc)
  805. incl(sym.flags, sfInfixCall)
  806. if sym.kind in skProcKinds and {'(', '#', '@'} notin name:
  807. localError(c.config, n.info, "`importjs` for routines requires a pattern")
  808. setExternName(c, sym, name, it.info)
  809. of wImportObjC:
  810. processImportObjC(c, sym, getOptionalStr(c, it, "$1"), it.info)
  811. of wSize:
  812. if sym.typ == nil: invalidPragma(c, it)
  813. var size = expectIntLit(c, it)
  814. case size
  815. of 1, 2, 4:
  816. sym.typ.size = size
  817. sym.typ.align = int16 size
  818. of 8:
  819. sym.typ.size = 8
  820. sym.typ.align = floatInt64Align(c.config)
  821. else:
  822. localError(c.config, it.info, "size may only be 1, 2, 4 or 8")
  823. of wAlign:
  824. let alignment = expectIntLit(c, it)
  825. if isPowerOfTwo(alignment) and alignment > 0:
  826. sym.alignment = max(sym.alignment, alignment)
  827. else:
  828. localError(c.config, it.info, "power of two expected")
  829. of wNodecl:
  830. noVal(c, it)
  831. incl(sym.loc.flags, lfNoDecl)
  832. of wPure, wAsmNoStackFrame:
  833. noVal(c, it)
  834. if sym != nil:
  835. if k == wPure and sym.kind in routineKinds: invalidPragma(c, it)
  836. else: incl(sym.flags, sfPure)
  837. of wVolatile:
  838. noVal(c, it)
  839. incl(sym.flags, sfVolatile)
  840. of wCursor:
  841. noVal(c, it)
  842. incl(sym.flags, sfCursor)
  843. of wRegister:
  844. noVal(c, it)
  845. incl(sym.flags, sfRegister)
  846. of wNoalias:
  847. noVal(c, it)
  848. incl(sym.flags, sfNoalias)
  849. of wEffectsOf:
  850. processEffectsOf(c, it, sym)
  851. of wThreadVar:
  852. noVal(c, it)
  853. incl(sym.flags, {sfThread, sfGlobal})
  854. of wDeadCodeElimUnused: discard # deprecated, dead code elim always on
  855. of wNoForward: pragmaNoForward(c, it)
  856. of wReorder: pragmaNoForward(c, it, flag = sfReorder)
  857. of wMagic: processMagic(c, it, sym)
  858. of wCompileTime:
  859. noVal(c, it)
  860. if comesFromPush:
  861. if sym.kind in {skProc, skFunc}:
  862. incl(sym.flags, sfCompileTime)
  863. else:
  864. incl(sym.flags, sfCompileTime)
  865. #incl(sym.loc.flags, lfNoDecl)
  866. of wGlobal:
  867. noVal(c, it)
  868. incl(sym.flags, sfGlobal)
  869. incl(sym.flags, sfPure)
  870. of wMerge:
  871. # only supported for backwards compat, doesn't do anything anymore
  872. noVal(c, it)
  873. of wConstructor:
  874. noVal(c, it)
  875. incl(sym.flags, sfConstructor)
  876. of wHeader:
  877. var lib = getLib(c, libHeader, getStrLitNode(c, it))
  878. addToLib(lib, sym)
  879. incl(sym.flags, sfImportc)
  880. incl(sym.loc.flags, lfHeader)
  881. incl(sym.loc.flags, lfNoDecl)
  882. # implies nodecl, because otherwise header would not make sense
  883. if sym.loc.r == "": sym.loc.r = rope(sym.name.s)
  884. of wNoSideEffect:
  885. noVal(c, it)
  886. if sym != nil:
  887. incl(sym.flags, sfNoSideEffect)
  888. if sym.typ != nil: incl(sym.typ.flags, tfNoSideEffect)
  889. of wSideEffect:
  890. noVal(c, it)
  891. incl(sym.flags, sfSideEffect)
  892. of wNoreturn:
  893. noVal(c, it)
  894. # Disable the 'noreturn' annotation when in the "Quirky Exceptions" mode!
  895. if c.config.exc != excQuirky:
  896. incl(sym.flags, sfNoReturn)
  897. if sym.typ[0] != nil:
  898. localError(c.config, sym.ast[paramsPos][0].info,
  899. ".noreturn with return type not allowed")
  900. of wNoDestroy:
  901. noVal(c, it)
  902. incl(sym.flags, sfGeneratedOp)
  903. of wNosinks:
  904. noVal(c, it)
  905. incl(sym.flags, sfWasForwarded)
  906. of wDynlib:
  907. processDynLib(c, it, sym)
  908. of wCompilerProc, wCore:
  909. noVal(c, it) # compilerproc may not get a string!
  910. cppDefine(c.graph.config, sym.name.s)
  911. recordPragma(c, it, "cppdefine", sym.name.s)
  912. if sfFromGeneric notin sym.flags: markCompilerProc(c, sym)
  913. of wNonReloadable:
  914. sym.flags.incl sfNonReloadable
  915. of wProcVar:
  916. # old procvar annotation, no longer needed
  917. noVal(c, it)
  918. of wExplain:
  919. sym.flags.incl sfExplain
  920. of wDeprecated:
  921. if sym != nil and sym.kind in routineKinds + {skType, skVar, skLet, skConst}:
  922. if it.kind in nkPragmaCallKinds: discard getStrLitNode(c, it)
  923. incl(sym.flags, sfDeprecated)
  924. elif sym != nil and sym.kind != skModule:
  925. # We don't support the extra annotation field
  926. if it.kind in nkPragmaCallKinds:
  927. localError(c.config, it.info, "annotation to deprecated not supported here")
  928. incl(sym.flags, sfDeprecated)
  929. # At this point we're quite sure this is a statement and applies to the
  930. # whole module
  931. elif it.kind in nkPragmaCallKinds: deprecatedStmt(c, it)
  932. else: incl(c.module.flags, sfDeprecated)
  933. of wVarargs:
  934. noVal(c, it)
  935. if sym.typ == nil: invalidPragma(c, it)
  936. else: incl(sym.typ.flags, tfVarargs)
  937. of wBorrow:
  938. if sym.kind == skType:
  939. typeBorrow(c, sym, it)
  940. else:
  941. noVal(c, it)
  942. incl(sym.flags, sfBorrow)
  943. of wFinal:
  944. noVal(c, it)
  945. if sym.typ == nil: invalidPragma(c, it)
  946. else: incl(sym.typ.flags, tfFinal)
  947. of wInheritable:
  948. noVal(c, it)
  949. if sym.typ == nil or tfFinal in sym.typ.flags: invalidPragma(c, it)
  950. else: incl(sym.typ.flags, tfInheritable)
  951. of wPackage:
  952. noVal(c, it)
  953. if sym.typ == nil: invalidPragma(c, it)
  954. else: incl(sym.flags, sfForward)
  955. of wAcyclic:
  956. noVal(c, it)
  957. if sym.typ == nil: invalidPragma(c, it)
  958. else: incl(sym.typ.flags, tfAcyclic)
  959. of wShallow:
  960. noVal(c, it)
  961. if sym.typ == nil: invalidPragma(c, it)
  962. else: incl(sym.typ.flags, tfShallow)
  963. of wThread:
  964. noVal(c, it)
  965. incl(sym.flags, sfThread)
  966. if sym.typ != nil:
  967. incl(sym.typ.flags, tfThread)
  968. if sym.typ.callConv == ccClosure: sym.typ.callConv = ccNimCall
  969. of wGcSafe:
  970. noVal(c, it)
  971. if sym != nil:
  972. if sym.kind != skType: incl(sym.flags, sfThread)
  973. if sym.typ != nil: incl(sym.typ.flags, tfGcSafe)
  974. else: invalidPragma(c, it)
  975. else:
  976. discard "no checking if used as a code block"
  977. of wPacked:
  978. noVal(c, it)
  979. if sym.typ == nil: invalidPragma(c, it)
  980. else: incl(sym.typ.flags, tfPacked)
  981. of wHint:
  982. let s = expectStrLit(c, it)
  983. recordPragma(c, it, "hint", s)
  984. message(c.config, it.info, hintUser, s)
  985. of wWarning:
  986. let s = expectStrLit(c, it)
  987. recordPragma(c, it, "warning", s)
  988. message(c.config, it.info, warnUser, s)
  989. of wError:
  990. if sym != nil and (sym.isRoutine or sym.kind == skType) and not isStatement:
  991. # This is subtle but correct: the error *statement* is only
  992. # allowed when 'wUsed' is not in validPragmas. Here this is the easiest way to
  993. # distinguish properly between
  994. # ``proc p() {.error}`` and ``proc p() = {.error: "msg".}``
  995. if it.kind in nkPragmaCallKinds: discard getStrLitNode(c, it)
  996. incl(sym.flags, sfError)
  997. excl(sym.flags, sfForward)
  998. else:
  999. let s = expectStrLit(c, it)
  1000. recordPragma(c, it, "error", s)
  1001. localError(c.config, it.info, errUser, s)
  1002. of wFatal: fatal(c.config, it.info, expectStrLit(c, it))
  1003. of wDefine: processDefine(c, it, sym)
  1004. of wUndef: processUndef(c, it)
  1005. of wCompile: processCompile(c, it)
  1006. of wLink: processLink(c, it)
  1007. of wPassl:
  1008. let s = expectStrLit(c, it)
  1009. extccomp.addLinkOption(c.config, s)
  1010. recordPragma(c, it, "passl", s)
  1011. of wPassc:
  1012. let s = expectStrLit(c, it)
  1013. extccomp.addCompileOption(c.config, s)
  1014. recordPragma(c, it, "passc", s)
  1015. of wLocalPassc:
  1016. assert sym != nil and sym.kind == skModule
  1017. let s = expectStrLit(c, it)
  1018. extccomp.addLocalCompileOption(c.config, s, toFullPathConsiderDirty(c.config, sym.info.fileIndex))
  1019. recordPragma(c, it, "localpassl", s)
  1020. of wPush:
  1021. processPush(c, n, i + 1)
  1022. result = true
  1023. of wPop:
  1024. processPop(c, it)
  1025. result = true
  1026. of wPragma:
  1027. if not sym.isNil and sym.kind == skTemplate:
  1028. sym.flags.incl sfCustomPragma
  1029. else:
  1030. processPragma(c, n, i)
  1031. result = true
  1032. of wDiscardable:
  1033. noVal(c, it)
  1034. if sym != nil: incl(sym.flags, sfDiscardable)
  1035. of wNoInit:
  1036. noVal(c, it)
  1037. if sym != nil: incl(sym.flags, sfNoInit)
  1038. of wCodegenDecl: processCodegenDecl(c, it, sym)
  1039. of wChecks, wObjChecks, wFieldChecks, wRangeChecks, wBoundChecks,
  1040. wOverflowChecks, wNilChecks, wAssertions, wWarnings, wHints,
  1041. wLineDir, wOptimization, wStaticBoundchecks, wStyleChecks,
  1042. wCallconv, wDebugger, wProfiler,
  1043. wFloatChecks, wNanChecks, wInfChecks, wPatterns, wTrMacros:
  1044. processOption(c, it, c.config.options)
  1045. of wStackTrace, wLineTrace:
  1046. if sym.kind in {skProc, skMethod, skConverter}:
  1047. processOption(c, it, sym.options)
  1048. else:
  1049. processOption(c, it, c.config.options)
  1050. of FirstCallConv..LastCallConv:
  1051. assert(sym != nil)
  1052. if sym.typ == nil: invalidPragma(c, it)
  1053. else:
  1054. sym.typ.callConv = wordToCallConv(k)
  1055. sym.typ.flags.incl tfExplicitCallConv
  1056. of wEmit: pragmaEmit(c, it)
  1057. of wUnroll: pragmaUnroll(c, it)
  1058. of wLinearScanEnd, wComputedGoto: noVal(c, it)
  1059. of wEffects:
  1060. # is later processed in effect analysis:
  1061. noVal(c, it)
  1062. of wIncompleteStruct:
  1063. noVal(c, it)
  1064. if sym.typ == nil: invalidPragma(c, it)
  1065. else: incl(sym.typ.flags, tfIncompleteStruct)
  1066. of wCompleteStruct:
  1067. noVal(c, it)
  1068. if sym.typ == nil: invalidPragma(c, it)
  1069. else: incl(sym.typ.flags, tfCompleteStruct)
  1070. of wUnchecked:
  1071. noVal(c, it)
  1072. if sym.typ == nil or sym.typ.kind notin {tyArray, tyUncheckedArray}:
  1073. invalidPragma(c, it)
  1074. else:
  1075. sym.typ.kind = tyUncheckedArray
  1076. of wUnion:
  1077. if c.config.backend == backendJs:
  1078. localError(c.config, it.info, "`{.union.}` is not implemented for js backend.")
  1079. else:
  1080. noVal(c, it)
  1081. if sym.typ == nil: invalidPragma(c, it)
  1082. else: incl(sym.typ.flags, tfUnion)
  1083. of wRequiresInit:
  1084. noVal(c, it)
  1085. if sym.kind == skField:
  1086. sym.flags.incl sfRequiresInit
  1087. elif sym.typ != nil:
  1088. incl(sym.typ.flags, tfNeedsFullInit)
  1089. else:
  1090. invalidPragma(c, it)
  1091. of wByRef:
  1092. noVal(c, it)
  1093. if sym == nil or sym.typ == nil:
  1094. processOption(c, it, c.config.options)
  1095. else:
  1096. incl(sym.typ.flags, tfByRef)
  1097. of wByCopy:
  1098. noVal(c, it)
  1099. if sym.kind != skType or sym.typ == nil: invalidPragma(c, it)
  1100. else: incl(sym.typ.flags, tfByCopy)
  1101. of wPartial:
  1102. noVal(c, it)
  1103. if sym.kind != skType or sym.typ == nil: invalidPragma(c, it)
  1104. else:
  1105. incl(sym.typ.flags, tfPartial)
  1106. of wInject, wGensym:
  1107. # We check for errors, but do nothing with these pragmas otherwise
  1108. # as they are handled directly in 'evalTemplate'.
  1109. noVal(c, it)
  1110. if sym == nil: invalidPragma(c, it)
  1111. of wLine: pragmaLine(c, it)
  1112. of wRaises, wTags, wForbids: pragmaRaisesOrTags(c, it)
  1113. of wLocks:
  1114. if sym == nil: pragmaLockStmt(c, it)
  1115. elif sym.typ == nil: invalidPragma(c, it)
  1116. else: warningDeprecated(c.config, n.info, "'Lock levels' are deprecated, now a noop")
  1117. of wBitsize:
  1118. if sym == nil or sym.kind != skField:
  1119. invalidPragma(c, it)
  1120. else:
  1121. sym.bitsize = expectIntLit(c, it)
  1122. if sym.bitsize <= 0:
  1123. localError(c.config, it.info, "bitsize needs to be positive")
  1124. of wGuard:
  1125. if sym == nil or sym.kind notin {skVar, skLet, skField}:
  1126. invalidPragma(c, it)
  1127. else:
  1128. sym.guard = pragmaGuard(c, it, sym.kind)
  1129. of wGoto:
  1130. if sym == nil or sym.kind notin {skVar, skLet}:
  1131. invalidPragma(c, it)
  1132. else:
  1133. sym.flags.incl sfGoto
  1134. of wExportNims:
  1135. if sym == nil: invalidPragma(c, it)
  1136. else: magicsys.registerNimScriptSymbol(c.graph, sym)
  1137. of wExperimental:
  1138. if not isTopLevel(c):
  1139. localError(c.config, n.info, "'experimental' pragma only valid as toplevel statement or in a 'push' environment")
  1140. processExperimental(c, it)
  1141. of wDoctype:
  1142. if not isTopLevel(c):
  1143. localError(c.config, n.info, "\"doctype\" pragma only valid as top-level statement")
  1144. of wNoRewrite:
  1145. noVal(c, it)
  1146. of wBase:
  1147. noVal(c, it)
  1148. sym.flags.incl sfBase
  1149. of wIntDefine:
  1150. processDefineConst(c, n, sym, mIntDefine)
  1151. of wStrDefine:
  1152. processDefineConst(c, n, sym, mStrDefine)
  1153. of wBoolDefine:
  1154. processDefineConst(c, n, sym, mBoolDefine)
  1155. of wUsed:
  1156. noVal(c, it)
  1157. if sym == nil: invalidPragma(c, it)
  1158. else: sym.flags.incl sfUsed
  1159. of wLiftLocals: discard
  1160. of wRequires, wInvariant, wAssume, wAssert:
  1161. pragmaProposition(c, it)
  1162. of wEnsures:
  1163. pragmaEnsures(c, it)
  1164. of wEnforceNoRaises:
  1165. sym.flags.incl sfNeverRaises
  1166. of wSystemRaisesDefect:
  1167. sym.flags.incl sfSystemRaisesDefect
  1168. else: invalidPragma(c, it)
  1169. elif comesFromPush and whichKeyword(ident) != wInvalid:
  1170. discard "ignore the .push pragma; it doesn't apply"
  1171. else:
  1172. if sym == nil or (sym.kind in {skVar, skLet, skConst, skParam, skIterator,
  1173. skField, skProc, skFunc, skConverter, skMethod, skType}):
  1174. n[i] = semCustomPragma(c, it)
  1175. elif sym != nil:
  1176. illegalCustomPragma(c, it, sym)
  1177. else:
  1178. invalidPragma(c, it)
  1179. proc overwriteLineInfo(n: PNode; info: TLineInfo) =
  1180. n.info = info
  1181. for i in 0..<n.safeLen:
  1182. overwriteLineInfo(n[i], info)
  1183. proc mergePragmas(n, pragmas: PNode) =
  1184. var pragmas = copyTree(pragmas)
  1185. overwriteLineInfo pragmas, n.info
  1186. if n[pragmasPos].kind == nkEmpty:
  1187. n[pragmasPos] = pragmas
  1188. else:
  1189. for p in pragmas: n[pragmasPos].add p
  1190. proc implicitPragmas*(c: PContext, sym: PSym, info: TLineInfo,
  1191. validPragmas: TSpecialWords) =
  1192. if sym != nil and sym.kind != skModule:
  1193. for it in c.optionStack:
  1194. let o = it.otherPragmas
  1195. if not o.isNil and sfFromGeneric notin sym.flags: # see issue #12985
  1196. pushInfoContext(c.config, info)
  1197. var i = 0
  1198. while i < o.len:
  1199. if singlePragma(c, sym, o, i, validPragmas, true, false):
  1200. internalError(c.config, info, "implicitPragmas")
  1201. inc i
  1202. popInfoContext(c.config)
  1203. if sym.kind in routineKinds and sym.ast != nil: mergePragmas(sym.ast, o)
  1204. if lfExportLib in sym.loc.flags and sfExportc notin sym.flags:
  1205. localError(c.config, info, ".dynlib requires .exportc")
  1206. var lib = c.optionStack[^1].dynlib
  1207. if {lfDynamicLib, lfHeader} * sym.loc.flags == {} and
  1208. sfImportc in sym.flags and lib != nil:
  1209. incl(sym.loc.flags, lfDynamicLib)
  1210. addToLib(lib, sym)
  1211. if sym.loc.r == "": sym.loc.r = rope(sym.name.s)
  1212. proc hasPragma*(n: PNode, pragma: TSpecialWord): bool =
  1213. if n == nil: return false
  1214. for p in n:
  1215. var key = if p.kind in nkPragmaCallKinds and p.len > 1: p[0] else: p
  1216. if key.kind == nkIdent and whichKeyword(key.ident) == pragma:
  1217. return true
  1218. return false
  1219. proc pragmaRec(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords;
  1220. isStatement: bool) =
  1221. if n == nil: return
  1222. var i = 0
  1223. while i < n.len:
  1224. if singlePragma(c, sym, n, i, validPragmas, false, isStatement): break
  1225. inc i
  1226. proc pragma(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords;
  1227. isStatement: bool) =
  1228. if n == nil: return
  1229. pragmaRec(c, sym, n, validPragmas, isStatement)
  1230. # XXX: in the case of a callable def, this should use its info
  1231. implicitPragmas(c, sym, n.info, validPragmas)
  1232. proc pragmaCallable*(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords,
  1233. isStatement: bool = false) =
  1234. if n == nil: return
  1235. if n[pragmasPos].kind != nkEmpty:
  1236. pragmaRec(c, sym, n[pragmasPos], validPragmas, isStatement)