pragmas.nim 48 KB

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