parampatterns.nim 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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, astalgo, 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. add(code, 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.sons[0].kind != nkIdent:
  53. patternError(p.sons[0], conf)
  54. return
  55. let op = p.sons[0].ident
  56. if p.len == 3:
  57. if op.s == "|" or op.id == ord(wOr):
  58. compileConstraints(p.sons[1], result, conf)
  59. compileConstraints(p.sons[2], result, conf)
  60. result.add(ppOr)
  61. elif op.s == "&" or op.id == ord(wAnd):
  62. compileConstraints(p.sons[1], result, conf)
  63. compileConstraints(p.sons[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.sons[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.sons[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.sons[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.sons[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.sons[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. arStrange # it is a strange beast like 'typedesc[var T]'
  168. proc exprRoot*(n: PNode): PSym =
  169. var it = n
  170. while true:
  171. case it.kind
  172. of nkSym: return it.sym
  173. of nkHiddenDeref, nkDerefExpr:
  174. if it[0].typ.skipTypes(abstractInst).kind in {tyPtr, tyRef}:
  175. # 'ptr' is unsafe anyway and 'ref' is always on the heap,
  176. # so allow these derefs:
  177. break
  178. else:
  179. it = it[0]
  180. of nkDotExpr, nkBracketExpr, nkHiddenAddr,
  181. nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr:
  182. it = it[0]
  183. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  184. it = it[1]
  185. of nkStmtList, nkStmtListExpr:
  186. if it.len > 0 and it.typ != nil: it = it.lastSon
  187. else: break
  188. of nkCallKinds:
  189. if it.typ != nil and it.typ.kind == tyVar and it.len > 1:
  190. # See RFC #7373, calls returning 'var T' are assumed to
  191. # return a view into the first argument (if there is one):
  192. it = it[1]
  193. else:
  194. break
  195. else:
  196. break
  197. proc isAssignable*(owner: PSym, n: PNode; isUnsafeAddr=false): TAssignableResult =
  198. ## 'owner' can be nil!
  199. result = arNone
  200. case n.kind
  201. of nkEmpty:
  202. if n.typ != nil and n.typ.kind == tyVar:
  203. result = arLValue
  204. of nkSym:
  205. let kinds = if isUnsafeAddr: {skVar, skResult, skTemp, skParam, skLet, skForVar}
  206. else: {skVar, skResult, skTemp}
  207. if n.sym.kind in kinds:
  208. if owner != nil and owner == n.sym.owner and
  209. sfGlobal notin n.sym.flags:
  210. result = arLocalLValue
  211. else:
  212. result = arLValue
  213. elif n.sym.kind == skParam and n.sym.typ.kind == tyVar:
  214. result = arLValue
  215. elif n.sym.kind == skType:
  216. let t = n.sym.typ.skipTypes({tyTypeDesc})
  217. if t.kind == tyVar: result = arStrange
  218. of nkDotExpr:
  219. let t = skipTypes(n.sons[0].typ, abstractInst-{tyTypeDesc})
  220. if t.kind in {tyVar, tyPtr, tyRef}:
  221. result = arLValue
  222. elif isUnsafeAddr and t.kind == tyLent:
  223. result = arLValue
  224. else:
  225. result = isAssignable(owner, n.sons[0], isUnsafeAddr)
  226. if result != arNone and n[1].kind == nkSym and
  227. sfDiscriminant in n[1].sym.flags:
  228. result = arDiscriminant
  229. of nkBracketExpr:
  230. let t = skipTypes(n.sons[0].typ, abstractInst-{tyTypeDesc})
  231. if t.kind in {tyVar, tyPtr, tyRef}:
  232. result = arLValue
  233. elif isUnsafeAddr and t.kind == tyLent:
  234. result = arLValue
  235. else:
  236. result = isAssignable(owner, n.sons[0], isUnsafeAddr)
  237. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  238. # Object and tuple conversions are still addressable, so we skip them
  239. # XXX why is 'tyOpenArray' allowed here?
  240. if skipTypes(n.typ, abstractPtrs-{tyTypeDesc}).kind in
  241. {tyOpenArray, tyTuple, tyObject}:
  242. result = isAssignable(owner, n.sons[1], isUnsafeAddr)
  243. elif compareTypes(n.typ, n.sons[1].typ, dcEqIgnoreDistinct):
  244. # types that are equal modulo distinction preserve l-value:
  245. result = isAssignable(owner, n.sons[1], isUnsafeAddr)
  246. of nkHiddenDeref:
  247. if isUnsafeAddr and n[0].typ.kind == tyLent: result = arLValue
  248. elif n[0].typ.kind == tyLent: result = arDiscriminant
  249. else: result = arLValue
  250. of nkDerefExpr, nkHiddenAddr:
  251. result = arLValue
  252. of nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr:
  253. result = isAssignable(owner, n.sons[0], isUnsafeAddr)
  254. of nkCallKinds:
  255. # builtin slice keeps lvalue-ness:
  256. if getMagic(n) in {mArrGet, mSlice}:
  257. result = isAssignable(owner, n.sons[1], isUnsafeAddr)
  258. elif n.typ != nil and n.typ.kind == tyVar:
  259. result = arLValue
  260. elif isUnsafeAddr and n.typ != nil and n.typ.kind == tyLent:
  261. result = arLValue
  262. of nkStmtList, nkStmtListExpr:
  263. if n.typ != nil:
  264. result = isAssignable(owner, n.lastSon, isUnsafeAddr)
  265. of nkVarTy:
  266. # XXX: The fact that this is here is a bit of a hack.
  267. # The goal is to allow the use of checks such as "foo(var T)"
  268. # within concepts. Semantically, it's not correct to say that
  269. # nkVarTy denotes an lvalue, but the example above is the only
  270. # possible code which will get us here
  271. result = arLValue
  272. else:
  273. discard
  274. proc isLValue*(n: PNode): bool =
  275. isAssignable(nil, n) in {arLValue, arLocalLValue, arStrange}
  276. proc matchNodeKinds*(p, n: PNode): bool =
  277. # matches the parameter constraint 'p' against the concrete AST 'n'.
  278. # Efficiency matters here.
  279. var stack {.noinit.}: array[0..MaxStackSize, bool]
  280. # empty patterns are true:
  281. stack[0] = true
  282. var sp = 1
  283. template push(x: bool) =
  284. stack[sp] = x
  285. inc sp
  286. let code = p.strVal
  287. var pc = 1
  288. while true:
  289. case TOpcode(code[pc])
  290. of ppEof: break
  291. of ppOr:
  292. stack[sp-2] = stack[sp-1] or stack[sp-2]
  293. dec sp
  294. of ppAnd:
  295. stack[sp-2] = stack[sp-1] and stack[sp-2]
  296. dec sp
  297. of ppNot: stack[sp-1] = not stack[sp-1]
  298. of ppSym: push n.kind == nkSym
  299. of ppAtom: push isAtom(n)
  300. of ppLit: push n.kind in {nkCharLit..nkNilLit}
  301. of ppIdent: push n.kind == nkIdent
  302. of ppCall: push n.kind in nkCallKinds
  303. of ppSymKind:
  304. let kind = TSymKind(code[pc+1])
  305. push n.kind == nkSym and n.sym.kind == kind
  306. inc pc
  307. of ppNodeKind:
  308. let kind = TNodeKind(code[pc+1])
  309. push n.kind == kind
  310. inc pc
  311. of ppLValue: push isAssignable(nil, n) in {arLValue, arLocalLValue}
  312. of ppLocal: push isAssignable(nil, n) == arLocalLValue
  313. of ppSideEffect: push checkForSideEffects(n) == seSideEffect
  314. of ppNoSideEffect: push checkForSideEffects(n) != seSideEffect
  315. inc pc
  316. result = stack[sp-1]