parampatterns.nim 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 low(TSymKind)..high(TSymKind):
  95. if cmpIgnoreStyle(($i).substr(2), 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 low(TNodeKind)..high(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. # assume no side effect:
  136. result = seNoSideEffect
  137. elif tfNoSideEffect in op.typ.flags:
  138. # indirect call without side effects:
  139. result = seNoSideEffect
  140. else:
  141. # indirect call: assume side effect:
  142. return seSideEffect
  143. # we need to check n[0] too: (FwithSideEffectButReturnsProcWithout)(args)
  144. for i in 0..<n.len:
  145. let ret = checkForSideEffects(n[i])
  146. if ret == seSideEffect: return ret
  147. elif ret == seUnknown and result == seNoSideEffect:
  148. result = seUnknown
  149. of nkNone..nkNilLit:
  150. # an atom cannot produce a side effect:
  151. result = seNoSideEffect
  152. else:
  153. # assume no side effect:
  154. result = seNoSideEffect
  155. for i in 0..<n.len:
  156. let ret = checkForSideEffects(n[i])
  157. if ret == seSideEffect: return ret
  158. elif ret == seUnknown and result == seNoSideEffect:
  159. result = seUnknown
  160. type
  161. TAssignableResult* = enum
  162. arNone, # no l-value and no discriminant
  163. arLValue, # is an l-value
  164. arLocalLValue, # is an l-value, but local var; must not escape
  165. # its stack frame!
  166. arDiscriminant, # is a discriminant
  167. arLentValue, # lent value
  168. arStrange # it is a strange beast like 'typedesc[var T]'
  169. proc exprRoot*(n: PNode): PSym =
  170. var it = n
  171. while true:
  172. case it.kind
  173. of nkSym: return it.sym
  174. of nkHiddenDeref, nkDerefExpr:
  175. if it[0].typ.skipTypes(abstractInst).kind in {tyPtr, tyRef}:
  176. # 'ptr' is unsafe anyway and 'ref' is always on the heap,
  177. # so allow these derefs:
  178. break
  179. else:
  180. it = it[0]
  181. of nkDotExpr, nkBracketExpr, nkHiddenAddr,
  182. nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr:
  183. it = it[0]
  184. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  185. it = it[1]
  186. of nkStmtList, nkStmtListExpr:
  187. if it.len > 0 and it.typ != nil: it = it.lastSon
  188. else: break
  189. of nkCallKinds:
  190. if it.typ != nil and it.typ.kind in {tyVar, tyLent} and it.len > 1:
  191. # See RFC #7373, calls returning 'var T' are assumed to
  192. # return a view into the first argument (if there is one):
  193. it = it[1]
  194. else:
  195. break
  196. else:
  197. break
  198. proc isAssignable*(owner: PSym, n: PNode; isUnsafeAddr=false): TAssignableResult =
  199. ## 'owner' can be nil!
  200. result = arNone
  201. case n.kind
  202. of nkEmpty:
  203. if n.typ != nil and n.typ.kind in {tyVar}:
  204. result = arLValue
  205. of nkSym:
  206. let kinds = if isUnsafeAddr: {skVar, skResult, skTemp, skParam, skLet, skForVar}
  207. else: {skVar, skResult, skTemp}
  208. if n.sym.kind == skParam and n.sym.typ.kind in {tyVar, tySink}:
  209. result = arLValue
  210. elif isUnsafeAddr and n.sym.kind == skParam:
  211. result = arLValue
  212. elif n.sym.kind in kinds:
  213. if owner != nil and owner == n.sym.owner and
  214. sfGlobal notin n.sym.flags:
  215. result = arLocalLValue
  216. else:
  217. result = arLValue
  218. elif n.sym.kind == skType:
  219. let t = n.sym.typ.skipTypes({tyTypeDesc})
  220. if t.kind in {tyVar}: result = arStrange
  221. of nkDotExpr:
  222. let t = skipTypes(n[0].typ, abstractInst-{tyTypeDesc})
  223. if t.kind in {tyVar, tySink, tyPtr, tyRef}:
  224. result = arLValue
  225. elif isUnsafeAddr and t.kind == tyLent:
  226. result = arLValue
  227. else:
  228. result = isAssignable(owner, n[0], isUnsafeAddr)
  229. if result != arNone and n[1].kind == nkSym and
  230. sfDiscriminant in n[1].sym.flags:
  231. result = arDiscriminant
  232. of nkBracketExpr:
  233. let t = skipTypes(n[0].typ, abstractInst-{tyTypeDesc})
  234. if t.kind in {tyVar, tySink, tyPtr, tyRef}:
  235. result = arLValue
  236. elif isUnsafeAddr and t.kind == tyLent:
  237. result = arLValue
  238. else:
  239. result = isAssignable(owner, n[0], isUnsafeAddr)
  240. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  241. # Object and tuple conversions are still addressable, so we skip them
  242. # XXX why is 'tyOpenArray' allowed here?
  243. if skipTypes(n.typ, abstractPtrs-{tyTypeDesc}).kind in
  244. {tyOpenArray, tyTuple, tyObject}:
  245. result = isAssignable(owner, n[1], isUnsafeAddr)
  246. elif compareTypes(n.typ, n[1].typ, dcEqIgnoreDistinct):
  247. # types that are equal modulo distinction preserve l-value:
  248. result = isAssignable(owner, n[1], isUnsafeAddr)
  249. of nkHiddenDeref:
  250. let n0 = n[0]
  251. if n0.typ.kind == tyLent:
  252. if isUnsafeAddr or (n0.kind == nkSym and n0.sym.kind == skResult):
  253. result = arLValue
  254. else:
  255. result = arLentValue
  256. else:
  257. result = arLValue
  258. of nkDerefExpr, nkHiddenAddr:
  259. result = arLValue
  260. of nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr:
  261. result = isAssignable(owner, n[0], isUnsafeAddr)
  262. of nkCallKinds:
  263. # builtin slice keeps lvalue-ness:
  264. if getMagic(n) in {mArrGet, mSlice}:
  265. result = isAssignable(owner, n[1], isUnsafeAddr)
  266. elif n.typ != nil and n.typ.kind in {tyVar}:
  267. result = arLValue
  268. elif isUnsafeAddr and n.typ != nil and n.typ.kind == tyLent:
  269. result = arLValue
  270. of nkStmtList, nkStmtListExpr:
  271. if n.typ != nil:
  272. result = isAssignable(owner, n.lastSon, isUnsafeAddr)
  273. of nkVarTy:
  274. # XXX: The fact that this is here is a bit of a hack.
  275. # The goal is to allow the use of checks such as "foo(var T)"
  276. # within concepts. Semantically, it's not correct to say that
  277. # nkVarTy denotes an lvalue, but the example above is the only
  278. # possible code which will get us here
  279. result = arLValue
  280. else:
  281. discard
  282. proc isLValue*(n: PNode): bool =
  283. isAssignable(nil, n) in {arLValue, arLocalLValue, arStrange}
  284. proc matchNodeKinds*(p, n: PNode): bool =
  285. # matches the parameter constraint 'p' against the concrete AST 'n'.
  286. # Efficiency matters here.
  287. var stack {.noinit.}: array[0..MaxStackSize, bool]
  288. # empty patterns are true:
  289. stack[0] = true
  290. var sp = 1
  291. template push(x: bool) =
  292. stack[sp] = x
  293. inc sp
  294. let code = p.strVal
  295. var pc = 1
  296. while true:
  297. case TOpcode(code[pc])
  298. of ppEof: break
  299. of ppOr:
  300. stack[sp-2] = stack[sp-1] or stack[sp-2]
  301. dec sp
  302. of ppAnd:
  303. stack[sp-2] = stack[sp-1] and stack[sp-2]
  304. dec sp
  305. of ppNot: stack[sp-1] = not stack[sp-1]
  306. of ppSym: push n.kind == nkSym
  307. of ppAtom: push isAtom(n)
  308. of ppLit: push n.kind in {nkCharLit..nkNilLit}
  309. of ppIdent: push n.kind == nkIdent
  310. of ppCall: push n.kind in nkCallKinds
  311. of ppSymKind:
  312. let kind = TSymKind(code[pc+1])
  313. push n.kind == nkSym and n.sym.kind == kind
  314. inc pc
  315. of ppNodeKind:
  316. let kind = TNodeKind(code[pc+1])
  317. push n.kind == kind
  318. inc pc
  319. of ppLValue: push isAssignable(nil, n) in {arLValue, arLocalLValue}
  320. of ppLocal: push isAssignable(nil, n) == arLocalLValue
  321. of ppSideEffect: push checkForSideEffects(n) == seSideEffect
  322. of ppNoSideEffect: push checkForSideEffects(n) != seSideEffect
  323. inc pc
  324. result = stack[sp-1]