pragmas.nim 52 KB

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