pragmas.nim 47 KB

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