parampatterns.nim 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements the pattern matching features for term rewriting
  10. ## macro support.
  11. import strutils, ast, types, msgs, idents, renderer, wordrecg, trees,
  12. options
  13. # we precompile the pattern here for efficiency into some internal
  14. # stack based VM :-) Why? Because it's fun; I did no benchmarks to see if that
  15. # actually improves performance.
  16. type
  17. TAliasRequest* = enum # first byte of the bytecode determines alias checking
  18. aqNone = 1, # no alias analysis requested
  19. aqShouldAlias, # with some other param
  20. aqNoAlias # request noalias
  21. TOpcode = enum
  22. ppEof = 1, # end of compiled pattern
  23. ppOr, # we could short-cut the evaluation for 'and' and 'or',
  24. ppAnd, # but currently we don't
  25. ppNot,
  26. ppSym,
  27. ppAtom,
  28. ppLit,
  29. ppIdent,
  30. ppCall,
  31. ppSymKind,
  32. ppNodeKind,
  33. ppLValue,
  34. ppLocal,
  35. ppSideEffect,
  36. ppNoSideEffect
  37. TPatternCode = string
  38. const
  39. MaxStackSize* = 64 ## max required stack size by the VM
  40. proc patternError(n: PNode; conf: ConfigRef) =
  41. localError(conf, n.info, "illformed AST: " & renderTree(n, {renderNoComments}))
  42. proc add(code: var TPatternCode, op: TOpcode) {.inline.} =
  43. code.add chr(ord(op))
  44. proc whichAlias*(p: PSym): TAliasRequest =
  45. if p.constraint != nil:
  46. result = TAliasRequest(p.constraint.strVal[0].ord)
  47. else:
  48. result = aqNone
  49. proc compileConstraints(p: PNode, result: var TPatternCode; conf: ConfigRef) =
  50. case p.kind
  51. of nkCallKinds:
  52. if p[0].kind != nkIdent:
  53. patternError(p[0], conf)
  54. return
  55. let op = p[0].ident
  56. if p.len == 3:
  57. if op.s == "|" or op.id == ord(wOr):
  58. compileConstraints(p[1], result, conf)
  59. compileConstraints(p[2], result, conf)
  60. result.add(ppOr)
  61. elif op.s == "&" or op.id == ord(wAnd):
  62. compileConstraints(p[1], result, conf)
  63. compileConstraints(p[2], result, conf)
  64. result.add(ppAnd)
  65. else:
  66. patternError(p, conf)
  67. elif p.len == 2 and (op.s == "~" or op.id == ord(wNot)):
  68. compileConstraints(p[1], result, conf)
  69. result.add(ppNot)
  70. else:
  71. patternError(p, conf)
  72. of nkAccQuoted, nkPar:
  73. if p.len == 1:
  74. compileConstraints(p[0], result, conf)
  75. else:
  76. patternError(p, conf)
  77. of nkIdent:
  78. let spec = p.ident.s.normalize
  79. case spec
  80. of "atom": result.add(ppAtom)
  81. of "lit": result.add(ppLit)
  82. of "sym": result.add(ppSym)
  83. of "ident": result.add(ppIdent)
  84. of "call": result.add(ppCall)
  85. of "alias": result[0] = chr(aqShouldAlias.ord)
  86. of "noalias": result[0] = chr(aqNoAlias.ord)
  87. of "lvalue": result.add(ppLValue)
  88. of "local": result.add(ppLocal)
  89. of "sideeffect": result.add(ppSideEffect)
  90. of "nosideeffect": result.add(ppNoSideEffect)
  91. else:
  92. # check all symkinds:
  93. internalAssert conf, int(high(TSymKind)) < 255
  94. for i in TSymKind:
  95. if cmpIgnoreStyle(i.toHumanStr, spec) == 0:
  96. result.add(ppSymKind)
  97. result.add(chr(i.ord))
  98. return
  99. # check all nodekinds:
  100. internalAssert conf, int(high(TNodeKind)) < 255
  101. for i in TNodeKind:
  102. if cmpIgnoreStyle($i, spec) == 0:
  103. result.add(ppNodeKind)
  104. result.add(chr(i.ord))
  105. return
  106. patternError(p, conf)
  107. else:
  108. patternError(p, conf)
  109. proc semNodeKindConstraints*(n: PNode; conf: ConfigRef; start: Natural): PNode =
  110. ## does semantic checking for a node kind pattern and compiles it into an
  111. ## efficient internal format.
  112. result = newNodeI(nkStrLit, n.info)
  113. result.strVal = newStringOfCap(10)
  114. result.strVal.add(chr(aqNone.ord))
  115. if n.len >= 2:
  116. for i in start..<n.len:
  117. compileConstraints(n[i], result.strVal, conf)
  118. if result.strVal.len > MaxStackSize-1:
  119. internalError(conf, n.info, "parameter pattern too complex")
  120. else:
  121. patternError(n, conf)
  122. result.strVal.add(ppEof)
  123. type
  124. TSideEffectAnalysis* = enum
  125. seUnknown, seSideEffect, seNoSideEffect
  126. proc checkForSideEffects*(n: PNode): TSideEffectAnalysis =
  127. case n.kind
  128. of nkCallKinds:
  129. # only calls can produce side effects:
  130. let op = n[0]
  131. if op.kind == nkSym and isRoutine(op.sym):
  132. let s = op.sym
  133. if sfSideEffect in s.flags:
  134. return seSideEffect
  135. elif tfNoSideEffect in op.typ.flags:
  136. result = seNoSideEffect
  137. else:
  138. # assume side effect:
  139. result = seSideEffect
  140. elif tfNoSideEffect in op.typ.flags:
  141. # indirect call without side effects:
  142. result = seNoSideEffect
  143. else:
  144. # indirect call: assume side effect:
  145. return seSideEffect
  146. # we need to check n[0] too: (FwithSideEffectButReturnsProcWithout)(args)
  147. for i in 0..<n.len:
  148. let ret = checkForSideEffects(n[i])
  149. if ret == seSideEffect: return ret
  150. elif ret == seUnknown and result == seNoSideEffect:
  151. result = seUnknown
  152. of nkNone..nkNilLit:
  153. # an atom cannot produce a side effect:
  154. result = seNoSideEffect
  155. else:
  156. # assume no side effect:
  157. result = seNoSideEffect
  158. for i in 0..<n.len:
  159. let ret = checkForSideEffects(n[i])
  160. if ret == seSideEffect: return ret
  161. elif ret == seUnknown and result == seNoSideEffect:
  162. result = seUnknown
  163. type
  164. TAssignableResult* = enum
  165. arNone, # no l-value and no discriminant
  166. arLValue, # is an l-value
  167. arLocalLValue, # is an l-value, but local var; must not escape
  168. # its stack frame!
  169. arDiscriminant, # is a discriminant
  170. arAddressableConst, # an addressable const
  171. arLentValue, # lent value
  172. arStrange # it is a strange beast like 'typedesc[var T]'
  173. proc exprRoot*(n: PNode; allowCalls = true): PSym =
  174. result = nil
  175. var it = n
  176. while true:
  177. case it.kind
  178. of nkSym: return it.sym
  179. of nkHiddenDeref, nkDerefExpr:
  180. if it[0].typ.skipTypes(abstractInst).kind in {tyPtr, tyRef}:
  181. # 'ptr' is unsafe anyway and 'ref' is always on the heap,
  182. # so allow these derefs:
  183. break
  184. else:
  185. it = it[0]
  186. of nkDotExpr, nkBracketExpr, nkHiddenAddr,
  187. nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr:
  188. it = it[0]
  189. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  190. it = it[1]
  191. of nkStmtList, nkStmtListExpr:
  192. if it.len > 0 and it.typ != nil: it = it.lastSon
  193. else: break
  194. of nkCallKinds:
  195. if allowCalls and it.typ != nil and it.typ.kind in {tyVar, tyLent} and it.len > 1:
  196. # See RFC #7373, calls returning 'var T' are assumed to
  197. # return a view into the first argument (if there is one):
  198. it = it[1]
  199. else:
  200. break
  201. else:
  202. break
  203. proc isAssignable*(owner: PSym, n: PNode): TAssignableResult =
  204. ## 'owner' can be nil!
  205. result = arNone
  206. case n.kind
  207. of nkEmpty:
  208. if n.typ != nil and n.typ.kind in {tyVar}:
  209. result = arLValue
  210. of nkSym:
  211. const kinds = {skVar, skResult, skTemp, skParam, skLet, skForVar}
  212. if n.sym.kind == skParam:
  213. result = if n.sym.typ.kind in {tyVar, tySink}: arLValue else: arAddressableConst
  214. elif n.sym.kind == skConst and dontInlineConstant(n, n.sym.astdef):
  215. result = arAddressableConst
  216. elif n.sym.kind in kinds:
  217. if n.sym.kind in {skParam, skLet, skForVar}:
  218. result = arAddressableConst
  219. else:
  220. if owner != nil and owner == n.sym.owner and
  221. sfGlobal notin n.sym.flags:
  222. result = arLocalLValue
  223. else:
  224. result = arLValue
  225. elif n.sym.kind == skType:
  226. let t = n.sym.typ.skipTypes({tyTypeDesc})
  227. if t.kind in {tyVar}: result = arStrange
  228. of nkDotExpr:
  229. let t = skipTypes(n[0].typ, abstractInst-{tyTypeDesc})
  230. if t.kind in {tyVar, tySink, tyPtr, tyRef}:
  231. result = arLValue
  232. elif t.kind == tyLent:
  233. result = arAddressableConst
  234. else:
  235. result = isAssignable(owner, n[0])
  236. if result != arNone and n[1].kind == nkSym and
  237. sfDiscriminant in n[1].sym.flags:
  238. result = arDiscriminant
  239. of nkBracketExpr:
  240. let t = skipTypes(n[0].typ, abstractInst-{tyTypeDesc})
  241. if t.kind in {tyVar, tySink, tyPtr, tyRef}:
  242. result = arLValue
  243. elif t.kind == tyLent:
  244. result = arAddressableConst
  245. else:
  246. result = isAssignable(owner, n[0])
  247. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  248. # Object and tuple conversions are still addressable, so we skip them
  249. # XXX why is 'tyOpenArray' allowed here?
  250. if skipTypes(n.typ, abstractPtrs-{tyTypeDesc}).kind in
  251. {tyOpenArray, tyTuple, tyObject}:
  252. result = isAssignable(owner, n[1])
  253. elif compareTypes(n.typ, n[1].typ, dcEqIgnoreDistinct):
  254. # types that are equal modulo distinction preserve l-value:
  255. result = isAssignable(owner, n[1])
  256. of nkHiddenDeref:
  257. let n0 = n[0]
  258. if n0.typ.kind == tyLent:
  259. if n0.kind == nkSym and n0.sym.kind == skResult:
  260. result = arLValue
  261. else:
  262. result = arLentValue
  263. else:
  264. result = arLValue
  265. of nkDerefExpr, nkHiddenAddr:
  266. result = arLValue
  267. of nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr:
  268. result = isAssignable(owner, n[0])
  269. of nkCallKinds:
  270. # builtin slice keeps lvalue-ness:
  271. if getMagic(n) in {mArrGet, mSlice}:
  272. result = isAssignable(owner, n[1])
  273. elif n.typ != nil:
  274. case n.typ.kind
  275. of tyVar: result = arLValue
  276. of tyLent: result = arLentValue
  277. else: discard
  278. of nkStmtList, nkStmtListExpr:
  279. if n.typ != nil:
  280. result = isAssignable(owner, n.lastSon)
  281. of nkVarTy:
  282. # XXX: The fact that this is here is a bit of a hack.
  283. # The goal is to allow the use of checks such as "foo(var T)"
  284. # within concepts. Semantically, it's not correct to say that
  285. # nkVarTy denotes an lvalue, but the example above is the only
  286. # possible code which will get us here
  287. result = arLValue
  288. else:
  289. discard
  290. proc isLValue*(n: PNode): bool =
  291. isAssignable(nil, n) in {arLValue, arLocalLValue, arStrange}
  292. proc matchNodeKinds*(p, n: PNode): bool =
  293. # matches the parameter constraint 'p' against the concrete AST 'n'.
  294. # Efficiency matters here.
  295. var stack {.noinit.}: array[0..MaxStackSize, bool]
  296. # empty patterns are true:
  297. stack[0] = true
  298. var sp = 1
  299. template push(x: bool) =
  300. stack[sp] = x
  301. inc sp
  302. let code = p.strVal
  303. var pc = 1
  304. while true:
  305. case TOpcode(code[pc])
  306. of ppEof: break
  307. of ppOr:
  308. stack[sp-2] = stack[sp-1] or stack[sp-2]
  309. dec sp
  310. of ppAnd:
  311. stack[sp-2] = stack[sp-1] and stack[sp-2]
  312. dec sp
  313. of ppNot: stack[sp-1] = not stack[sp-1]
  314. of ppSym: push n.kind == nkSym
  315. of ppAtom: push isAtom(n)
  316. of ppLit: push n.kind in {nkCharLit..nkNilLit}
  317. of ppIdent: push n.kind == nkIdent
  318. of ppCall: push n.kind in nkCallKinds
  319. of ppSymKind:
  320. let kind = TSymKind(code[pc+1])
  321. push n.kind == nkSym and n.sym.kind == kind
  322. inc pc
  323. of ppNodeKind:
  324. let kind = TNodeKind(code[pc+1])
  325. push n.kind == kind
  326. inc pc
  327. of ppLValue: push isAssignable(nil, n) in {arLValue, arLocalLValue}
  328. of ppLocal: push isAssignable(nil, n) == arLocalLValue
  329. of ppSideEffect: push checkForSideEffects(n) == seSideEffect
  330. of ppNoSideEffect: push checkForSideEffects(n) != seSideEffect
  331. inc pc
  332. result = stack[sp-1]