pragmas.nim 44 KB

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