From af7c92c0038763db2ba7d7049d7d18363b15089e Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 3 Sep 2012 00:55:44 +0200 Subject: term rewriting macros fully implemented; still buggy --- compiler/ast.nim | 23 +++-- compiler/ccgexprs.nim | 4 +- compiler/evaltempl.nim | 62 +++++++++++--- compiler/msgs.nim | 9 +- compiler/parampatterns.nim | 205 +++++++++++++++++++++++++++++++++++++++++++++ compiler/patterns.nim | 200 +++++++++++++++++++++++++++++++++---------- compiler/renderer.nim | 17 ++-- compiler/rodread.nim | 3 + compiler/rodwrite.nim | 3 + compiler/sem.nim | 50 +++++++++-- compiler/semexprs.nim | 29 ++++--- compiler/semfold.nim | 12 ++- compiler/semstmts.nim | 2 + compiler/semtempl.nim | 122 ++++++++++++++++++++++----- compiler/semtypes.nim | 11 ++- compiler/trees.nim | 16 ++++ compiler/types.nim | 8 +- 17 files changed, 658 insertions(+), 118 deletions(-) create mode 100644 compiler/parampatterns.nim (limited to 'compiler') diff --git a/compiler/ast.nim b/compiler/ast.nim index 52502c5de..2b0fe6470 100755 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -176,7 +176,6 @@ type nkFromStmt, # a from * import statement nkIncludeStmt, # an include statement nkBindStmt, # a bind statement - nkPattern, # a pattern statement ('as' statement) nkCommentStmt, # a comment statement nkStmtListExpr, # a statement list followed by an expr; this is used # to allow powerful multi-line templates @@ -201,6 +200,8 @@ type nkProcTy, # proc type nkEnumTy, # enum body nkEnumFieldDef, # `ident = expr` in an enumeration + nkArgList, # argument list + nkPattern, # a special pattern; used for matching nkReturnToken, # token used for interpretation nkClosure, # (prc, env)-pair (internally used for code gen) nkGotoState, # used for the state machine (for iterators) @@ -584,7 +585,7 @@ type # for a conditional: # 1 iff the symbol is defined, else 0 # (or not in symbol table) - # for modules, a unique index correspinding + # for modules, a unique index corresponding # to the order of compilation offset*: int # offset of record field loc*: TLoc @@ -616,6 +617,7 @@ type align*: int # the type's alignment requirements containerID*: int # used for type checking of generics loc*: TLoc + constraint*: PNode # additional constraints like 'lit|result' TPair*{.final.} = object key*, val*: PObject @@ -865,13 +867,22 @@ proc newSymNode*(sym: PSym, info: TLineInfo): PNode = result.typ = sym.typ result.info = info -proc newNodeI(kind: TNodeKind, info: TLineInfo): PNode = - result = newNode(kind) +proc newNodeI(kind: TNodeKind, info: TLineInfo): PNode = + new(result) + result.kind = kind + result.info = info + +proc newNodeI*(kind: TNodeKind, info: TLineInfo, children: int): PNode = + new(result) + result.kind = kind result.info = info + if children > 0: + newSeq(result.sons, children) proc newNode*(kind: TNodeKind, info: TLineInfo, sons: TNodeSeq = @[], typ: PType = nil): PNode = - result = newNode(kind) + new(result) + result.kind = kind result.info = info result.typ = typ # XXX use shallowCopy here for ownership transfer: @@ -1184,3 +1195,5 @@ proc hasPattern*(s: PSym): bool {.inline.} = iterator items*(n: PNode): PNode = for i in 0.. = nkNone and n.kind <= nkNilLit diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index ba4111e9e..d10b37432 100755 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -1246,10 +1246,10 @@ proc genSetOp(p: BProc, e: PNode, d: var TLoc, op: TMagic) = of mIncl: var ts = "NI" & $(size * 8) binaryStmtInExcl(p, e, d, - "$1 |=(1<<((" & ts & ")($2)%(sizeof(" & ts & ")*8)));$n") + "$1 |=((" & ts & ")(1)<<(($2)%(sizeof(" & ts & ")*8)));$n") of mExcl: var ts = "NI" & $(size * 8) - binaryStmtInExcl(p, e, d, "$1 &= ~(1 << ((" & ts & ")($2) % (sizeof(" & + binaryStmtInExcl(p, e, d, "$1 &= ~((" & ts & ")(1) << (($2) % (sizeof(" & ts & ")*8)));$n") of mCard: if size <= 4: unaryExprChar(p, e, d, "#countBits32($1)") diff --git a/compiler/evaltempl.nim b/compiler/evaltempl.nim index d7006d34d..265fe3fe1 100644 --- a/compiler/evaltempl.nim +++ b/compiler/evaltempl.nim @@ -19,14 +19,17 @@ type mapping: TIdTable # every gensym'ed symbol needs to be mapped to some # new symbol -proc evalTemplateAux(templ, actual: PNode, c: var TemplCtx): PNode = - #inc genSymBaseId +proc evalTemplateAux(templ, actual: PNode, c: var TemplCtx, result: PNode) = case templ.kind of nkSym: var s = templ.sym if s.owner.id == c.owner.id: if s.kind == skParam: - result = copyTree(actual.sons[s.position]) + let x = actual.sons[s.position] + if x.kind == nkArgList: + for y in items(x): result.add(y) + else: + result.add copyTree(x) else: InternalAssert sfGenSym in s.flags var x = PSym(IdTableGet(c.mapping, s)) @@ -34,16 +37,42 @@ proc evalTemplateAux(templ, actual: PNode, c: var TemplCtx): PNode = x = copySym(s, false) x.owner = c.genSymOwner IdTablePut(c.mapping, s, x) - result = newSymNode(x, templ.info) + result.add newSymNode(x, templ.info) else: - result = copyNode(templ) + result.add copyNode(templ) of nkNone..nkIdent, nkType..nkNilLit: # atom - result = copyNode(templ) + result.add copyNode(templ) else: - result = copyNode(templ) - newSons(result, sonsLen(templ)) + var res = copyNode(templ) for i in countup(0, sonsLen(templ) - 1): - result.sons[i] = evalTemplateAux(templ.sons[i], actual, c) + evalTemplateAux(templ.sons[i], actual, c, res) + result.add res + +when false: + proc evalTemplateAux(templ, actual: PNode, c: var TemplCtx): PNode = + case templ.kind + of nkSym: + var s = templ.sym + if s.owner.id == c.owner.id: + if s.kind == skParam: + result = copyTree(actual.sons[s.position]) + else: + InternalAssert sfGenSym in s.flags + var x = PSym(IdTableGet(c.mapping, s)) + if x == nil: + x = copySym(s, false) + x.owner = c.genSymOwner + IdTablePut(c.mapping, s, x) + result = newSymNode(x, templ.info) + else: + result = copyNode(templ) + of nkNone..nkIdent, nkType..nkNilLit: # atom + result = copyNode(templ) + else: + result = copyNode(templ) + newSons(result, sonsLen(templ)) + for i in countup(0, sonsLen(templ) - 1): + result.sons[i] = evalTemplateAux(templ.sons[i], actual, c) proc evalTemplateArgs(n: PNode, s: PSym): PNode = # if the template has zero arguments, it can be called without ``()`` @@ -78,6 +107,19 @@ proc evalTemplate*(n: PNode, tmpl, genSymOwner: PSym): PNode = ctx.owner = tmpl ctx.genSymOwner = genSymOwner initIdTable(ctx.mapping) - result = evalTemplateAux(tmpl.getBody, args, ctx) + + let body = tmpl.getBody + if isAtom(body): + result = newNodeI(nkPar, body.info) + evalTemplateAux(body, args, ctx, result) + if result.len == 1: result = result.sons[0] + else: + GlobalError(result.info, errIllFormedAstX, + renderTree(result, {renderNoComments})) + else: + result = copyNode(body) + #evalTemplateAux(body, args, ctx, result) + for i in countup(0, safeLen(body) - 1): + evalTemplateAux(body.sons[i], args, ctx, result) dec(evalTemplateCounter) diff --git a/compiler/msgs.nim b/compiler/msgs.nim index f61e03e79..d0ddf7721 100755 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -109,7 +109,7 @@ type hintLineTooLong, hintXDeclaredButNotUsed, hintConvToBaseNotNeeded, hintConvFromXtoItselfNotNeeded, hintExprAlwaysX, hintQuitCalled, hintProcessing, hintCodeBegin, hintCodeEnd, hintConf, hintPath, - hintConditionAlwaysTrue, + hintConditionAlwaysTrue, hintPattern, hintUser const @@ -152,7 +152,7 @@ const errExceptionAlreadyHandled: "exception already handled", errYieldNotAllowedHere: "'yield' only allowed in an iterator", errYieldNotAllowedInTryStmt: "'yield' cannot be used within 'try' in a non-inlined iterator", - errInvalidNumberOfYieldExpr: "invalid number of \'yield\' expresions", + errInvalidNumberOfYieldExpr: "invalid number of \'yield\' expressions", errCannotReturnExpr: "current routine cannot return an expression", errAttemptToRedefine: "redefinition of \'$1\'", errStmtInvalidAfterReturn: "statement not allowed after \'return\', \'break\' or \'raise\'", @@ -366,6 +366,7 @@ const hintConf: "used config file \'$1\' [Conf]", hintPath: "added path: '$1' [Path]", hintConditionAlwaysTrue: "condition is always true: '$1' [CondTrue]", + hintPattern: "$1 [Pattern]", hintUser: "$1 [User]"] const @@ -378,10 +379,10 @@ const "AnalysisLoophole", "DifferentHeaps", "WriteToForeignHeap", "ImplicitClosure", "EachIdentIsTuple", "User"] - HintsToStr*: array[0..14, string] = ["Success", "SuccessX", "LineTooLong", + HintsToStr*: array[0..15, string] = ["Success", "SuccessX", "LineTooLong", "XDeclaredButNotUsed", "ConvToBaseNotNeeded", "ConvFromXtoItselfNotNeeded", "ExprAlwaysX", "QuitCalled", "Processing", "CodeBegin", "CodeEnd", "Conf", - "Path", "CondTrue", + "Path", "CondTrue", "Pattern", "User"] const diff --git a/compiler/parampatterns.nim b/compiler/parampatterns.nim new file mode 100644 index 000000000..83585dbd4 --- /dev/null +++ b/compiler/parampatterns.nim @@ -0,0 +1,205 @@ +# +# +# The Nimrod Compiler +# (c) Copyright 2012 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## This module implements the pattern matching features for term rewriting +## macro support. + +import strutils, ast, astalgo, types, msgs, idents, renderer, wordrecg + +# we precompile the pattern here for efficiency into some internal +# stack based VM :-) Why? Because it's fun; I did no benchmarks to see if that +# actually improves performance. +type + TAliasRequest* = enum # first byte of the bytecode determines alias checking + aqNone = 1, # no alias analysis requested + aqShouldAlias, # with what? + aqNoAlias # request noalias + TOpcode = enum + ppEof = 1, # end of compiled pattern + ppOr, # we could short-cut the evaluation for 'and' and 'or', + ppAnd, # but currently we don't + ppNot, + ppSym, + ppAtom, + ppLit, + ppIdent, + ppCall, + ppSymKind, + ppNodeKind, + ppSideEffect, + ppNoSideEffect + TPatternCode = string + +const + MaxStackSize* = 64 ## max required stack size by the VM + +proc patternError(n: PNode) = + LocalError(n.info, errIllFormedAstX, renderTree(n, {renderNoComments})) + +proc add(code: var TPatternCode, op: TOpcode) {.inline.} = + add(code, chr(ord(op))) + +proc whichAlias*(p: PSym): TAliasRequest = + if p.typ.constraint != nil: + result = TAliasRequest(p.typ.constraint.strVal[0].ord) + +proc compileConstraints(p: PNode, result: var TPatternCode) = + case p.kind + of nkCallKinds: + if p.sons[0].kind != nkIdent: + patternError(p.sons[0]) + return + let op = p.sons[0].ident + if p.len == 3: + if op.s == "|" or op.id == ord(wOr): + compileConstraints(p.sons[1], result) + compileConstraints(p.sons[2], result) + result.add(ppOr) + elif op.s == "&" or op.id == ord(wAnd): + compileConstraints(p.sons[1], result) + compileConstraints(p.sons[2], result) + result.add(ppAnd) + else: + patternError(p) + elif p.len == 2 and (op.s == "~" or op.id == ord(wNot)): + compileConstraints(p.sons[1], result) + result.add(ppNot) + else: + patternError(p) + of nkAccQuoted, nkPar: + if p.len == 1: + compileConstraints(p.sons[0], result) + else: + patternError(p) + of nkIdent: + let spec = p.ident.s.normalize + case spec + of "atom": result.add(ppAtom) + of "lit": result.add(ppLit) + of "sym": result.add(ppSym) + of "ident": result.add(ppIdent) + of "call": result.add(ppCall) + of "alias": result[0] = chr(aqShouldAlias.ord) + of "noalias": result[0] = chr(aqNoAlias.ord) + of "sideeffect": result.add(ppSideEffect) + of "nosideeffect": result.add(ppNoSideEffect) + else: + # check all symkinds: + InternalAssert int(high(TSymKind)) < 255 + for i in low(TSymKind)..high(TSymKind): + if cmpIgnoreStyle(($i).substr(2), spec) == 0: + result.add(ppSymKind) + result.add(chr(i.ord)) + return + # check all nodekinds: + InternalAssert int(high(TNodeKind)) < 255 + for i in low(TNodeKind)..high(TNodeKind): + if cmpIgnoreStyle($i, spec) == 0: + result.add(ppSymKind) + result.add(chr(i.ord)) + return + patternError(p) + else: + patternError(p) + +proc semNodeKindConstraints*(p: PNode): PNode = + ## does semantic checking for a node kind pattern and compiles it into an + ## efficient internal format. + assert p.kind == nkCurlyExpr + result = newNodeI(nkStrLit, p.info) + result.strVal = newStringOfCap(10) + result.strVal.add(chr(aqNone.ord)) + if p.len >= 2: + for i in 1.. maxStackSize-1: + InternalError(p.info, "parameter pattern too complex") + else: + patternError(p) + result.strVal.add(ppEof) + +type + TSideEffectAnalysis = enum + seUnknown, seSideEffect, seNoSideEffect + +proc checkForSideEffects(n: PNode): TSideEffectAnalysis = + # XXX is 'raise' a side effect? + case n.kind + of nkCallKinds: + # only calls can produce side effects: + let op = n.sons[0] + if op.kind == nkSym and isRoutine(op.sym): + let s = n.sym + if sfSideEffect in s.flags: + return seSideEffect + # assume no side effect: + result = seNoSideEffect + elif tfNoSideEffect in op.typ.flags: + # indirect call without side effects: + result = seNoSideEffect + else: + # indirect call: we don't know + result = seUnknown + # we need to check n[0] too: (FwithSideEffectButReturnsProcWithout)(args) + for i in 0 ..