pragmas.nim 51 KB

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