From e2af486434c7ff401c412d890b490b4ac11ab321 Mon Sep 17 00:00:00 2001 From: BigEpsilon Date: Sat, 28 Oct 2017 11:33:35 +0200 Subject: [PATCH] Add sections (type, var, let, const, using) support for reorder pragma (#6326) --- compiler/depends.nim | 2 +- compiler/docgen.nim | 4 +- compiler/importer.nim | 74 +------ compiler/modulepaths.nim | 78 +++++++ compiler/passes.nim | 3 +- compiler/reorder.nim | 426 +++++++++++++++++++++++++++++++++---- compiler/rodwrite.nim | 4 +- compiler/sem.nim | 2 +- tests/modules/treorder.nim | 12 +- tests/pragmas/treorder.nim | 75 +++++++ 10 files changed, 551 insertions(+), 129 deletions(-) create mode 100644 compiler/modulepaths.nim create mode 100644 tests/pragmas/treorder.nim diff --git a/compiler/depends.nim b/compiler/depends.nim index e8c295a349..2b600c1dab 100644 --- a/compiler/depends.nim +++ b/compiler/depends.nim @@ -10,7 +10,7 @@ # This module implements a dependency file generator. import - os, options, ast, astalgo, msgs, ropes, idents, passes, importer + os, options, ast, astalgo, msgs, ropes, idents, passes, modulepaths from modulegraphs import ModuleGraph diff --git a/compiler/docgen.nim b/compiler/docgen.nim index 8c50a4f1d4..7d32755b30 100644 --- a/compiler/docgen.nim +++ b/compiler/docgen.nim @@ -15,8 +15,8 @@ import ast, strutils, strtabs, options, msgs, os, ropes, idents, wordrecg, syntaxes, renderer, lexer, packages/docutils/rstast, packages/docutils/rst, packages/docutils/rstgen, times, - packages/docutils/highlite, importer, sempass2, json, xmltree, cgi, - typesrenderer, astalgo + packages/docutils/highlite, sempass2, json, xmltree, cgi, + typesrenderer, astalgo, modulepaths type TSections = array[TSymKind, Rope] diff --git a/compiler/importer.nim b/compiler/importer.nim index 07f42a1472..89ee00b9d4 100644 --- a/compiler/importer.nim +++ b/compiler/importer.nim @@ -11,83 +11,11 @@ import intsets, strutils, os, ast, astalgo, msgs, options, idents, rodread, lookups, - semdata, passes, renderer, gorgeimpl + semdata, passes, renderer, modulepaths proc evalImport*(c: PContext, n: PNode): PNode proc evalFrom*(c: PContext, n: PNode): PNode -proc lookupPackage(pkg, subdir: PNode): string = - let sub = if subdir != nil: renderTree(subdir, {renderNoComments}).replace(" ") else: "" - case pkg.kind - of nkStrLit, nkRStrLit, nkTripleStrLit: - result = scriptableImport(pkg.strVal, sub, pkg.info) - of nkIdent: - result = scriptableImport(pkg.ident.s, sub, pkg.info) - else: - localError(pkg.info, "package name must be an identifier or string literal") - result = "" - -proc getModuleName*(n: PNode): string = - # This returns a short relative module name without the nim extension - # e.g. like "system", "importer" or "somepath/module" - # The proc won't perform any checks that the path is actually valid - case n.kind - of nkStrLit, nkRStrLit, nkTripleStrLit: - try: - result = pathSubs(n.strVal, n.info.toFullPath().splitFile().dir) - except ValueError: - localError(n.info, "invalid path: " & n.strVal) - result = n.strVal - of nkIdent: - result = n.ident.s - of nkSym: - result = n.sym.name.s - of nkInfix: - let n0 = n[0] - let n1 = n[1] - if n0.kind == nkIdent and n0.ident.id == getIdent("as").id: - # XXX hack ahead: - n.kind = nkImportAs - n.sons[0] = n.sons[1] - n.sons[1] = n.sons[2] - n.sons.setLen(2) - return getModuleName(n.sons[0]) - if n1.kind == nkPrefix and n1[0].kind == nkIdent and n1[0].ident.s == "$": - if n0.kind == nkIdent and n0.ident.s == "/": - result = lookupPackage(n1[1], n[2]) - else: - localError(n.info, "only '/' supported with $package notation") - result = "" - else: - # hacky way to implement 'x / y /../ z': - result = getModuleName(n1) - result.add renderTree(n0, {renderNoComments}) - result.add getModuleName(n[2]) - of nkPrefix: - if n.sons[0].kind == nkIdent and n.sons[0].ident.s == "$": - result = lookupPackage(n[1], nil) - else: - # hacky way to implement 'x / y /../ z': - result = renderTree(n, {renderNoComments}).replace(" ") - of nkDotExpr: - result = renderTree(n, {renderNoComments}).replace(".", "/") - of nkImportAs: - result = getModuleName(n.sons[0]) - else: - localError(n.info, errGenerated, "invalid module name: '$1'" % n.renderTree) - result = "" - -proc checkModuleName*(n: PNode; doLocalError=true): int32 = - # This returns the full canonical path for a given module import - let modulename = n.getModuleName - let fullPath = findModule(modulename, n.info.toFullPath) - if fullPath.len == 0: - if doLocalError: - localError(n.info, errCannotOpenFile, modulename) - result = InvalidFileIDX - else: - result = fullPath.fileInfoIdx - proc importPureEnumField*(c: PContext; s: PSym) = var check = strTableGet(c.importTable.symbols, s.name) if check == nil: diff --git a/compiler/modulepaths.nim b/compiler/modulepaths.nim new file mode 100644 index 0000000000..6b9865677e --- /dev/null +++ b/compiler/modulepaths.nim @@ -0,0 +1,78 @@ +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +import ast, renderer, gorgeimpl, strutils, msgs, options, idents, ospaths + +proc lookupPackage(pkg, subdir: PNode): string = + let sub = if subdir != nil: renderTree(subdir, {renderNoComments}).replace(" ") else: "" + case pkg.kind + of nkStrLit, nkRStrLit, nkTripleStrLit: + result = scriptableImport(pkg.strVal, sub, pkg.info) + of nkIdent: + result = scriptableImport(pkg.ident.s, sub, pkg.info) + else: + localError(pkg.info, "package name must be an identifier or string literal") + result = "" + +proc getModuleName*(n: PNode): string = + # This returns a short relative module name without the nim extension + # e.g. like "system", "importer" or "somepath/module" + # The proc won't perform any checks that the path is actually valid + case n.kind + of nkStrLit, nkRStrLit, nkTripleStrLit: + try: + result = pathSubs(n.strVal, n.info.toFullPath().splitFile().dir) + except ValueError: + localError(n.info, "invalid path: " & n.strVal) + result = n.strVal + of nkIdent: + result = n.ident.s + of nkSym: + result = n.sym.name.s + of nkInfix: + let n0 = n[0] + let n1 = n[1] + if n0.kind == nkIdent and n0.ident.id == getIdent("as").id: + # XXX hack ahead: + n.kind = nkImportAs + n.sons[0] = n.sons[1] + n.sons[1] = n.sons[2] + n.sons.setLen(2) + return getModuleName(n.sons[0]) + if n1.kind == nkPrefix and n1[0].kind == nkIdent and n1[0].ident.s == "$": + if n0.kind == nkIdent and n0.ident.s == "/": + result = lookupPackage(n1[1], n[2]) + else: + localError(n.info, "only '/' supported with $package notation") + result = "" + else: + # hacky way to implement 'x / y /../ z': + result = getModuleName(n1) + result.add renderTree(n0, {renderNoComments}) + result.add getModuleName(n[2]) + of nkPrefix: + if n.sons[0].kind == nkIdent and n.sons[0].ident.s == "$": + result = lookupPackage(n[1], nil) + else: + # hacky way to implement 'x / y /../ z': + result = renderTree(n, {renderNoComments}).replace(" ") + of nkDotExpr: + result = renderTree(n, {renderNoComments}).replace(".", "/") + of nkImportAs: + result = getModuleName(n.sons[0]) + else: + localError(n.info, errGenerated, "invalid module name: '$1'" % n.renderTree) + result = "" + +proc checkModuleName*(n: PNode; doLocalError=true): int32 = + # This returns the full canonical path for a given module import + let modulename = n.getModuleName + let fullPath = findModule(modulename, n.info.toFullPath) + if fullPath.len == 0: + if doLocalError: + localError(n.info, errCannotOpenFile, modulename) + result = InvalidFileIDX + else: + result = fullPath.fileInfoIdx \ No newline at end of file diff --git a/compiler/passes.nim b/compiler/passes.nim index 6efd50385c..b84fe2f4d7 100644 --- a/compiler/passes.nim +++ b/compiler/passes.nim @@ -15,6 +15,7 @@ import condsyms, idents, renderer, types, extccomp, math, magicsys, nversion, nimsets, syntaxes, times, rodread, idgen, modulegraphs, reorder + type TPassContext* = object of RootObj # the pass's context fromCache*: bool # true if created by "openCached" @@ -211,7 +212,7 @@ proc processModule*(graph: ModuleGraph; module: PSym, stream: PLLStream, if n.kind == nkEmpty: break sl.add n if sfReorder in module.flags: - sl = reorder sl + sl = reorder(graph, sl, module, cache) discard processTopLevelStmt(sl, a) break elif not processTopLevelStmt(n, a): break diff --git a/compiler/reorder.nim b/compiler/reorder.nim index a9ad1fd97d..1cf5a02177 100644 --- a/compiler/reorder.nim +++ b/compiler/reorder.nim @@ -1,9 +1,36 @@ -import intsets, tables, ast, idents, renderer +import + intsets, ast, idents, algorithm, renderer, parser, ospaths, strutils, + sequtils, msgs, modulegraphs, syntaxes, options, modulepaths, tables -const - nfTempMark = nfTransf - nfPermMark = nfNoRewrite +type + DepN = ref object + pnode: PNode + id, idx, lowLink: int + onStack: bool + kids: seq[DepN] + hAQ, hIS, hB, hCmd: int + when not defined(release): + expls: seq[string] + DepG = seq[DepN] + +when not defined(release): + var idNames = newTable[int, string]() + +proc newDepN(id: int, pnode: PNode): DepN = + new(result) + result.id = id + result.pnode = pnode + result.idx = -1 + result.lowLink = -1 + result.onStack = false + result.kids = @[] + result.hAQ = -1 + result.hIS = -1 + result.hB = -1 + result.hCmd = -1 + when not defined(release): + result.expls = @[] proc accQuoted(n: PNode): PIdent = var id = "" @@ -21,10 +48,19 @@ proc addDecl(n: PNode; declares: var IntSet) = of nkPragmaExpr: addDecl(n[0], declares) of nkIdent: declares.incl n.ident.id + when not defined(release): + idNames[n.ident.id] = n.ident.s of nkSym: declares.incl n.sym.name.id + when not defined(release): + idNames[n.sym.name.id] = n.sym.name.s of nkAccQuoted: - declares.incl accQuoted(n).id + let a = accQuoted(n) + declares.incl a.id + when not defined(release): + idNames[a.id] = a.s + of nkEnumFieldDef: + addDecl(n[0], declares) else: discard proc computeDeps(n: PNode, declares, uses: var IntSet; topLevel: bool) = @@ -32,7 +68,7 @@ proc computeDeps(n: PNode, declares, uses: var IntSet; topLevel: bool) = template decl(n) = if topLevel: addDecl(n, declares) case n.kind - of procDefs: + of procDefs, nkMacroDef, nkTemplateDef: decl(n[0]) for i in 1..bodyPos: deps(n[i]) of nkLetSection, nkVarSection, nkUsingStmt: @@ -44,43 +80,358 @@ proc computeDeps(n: PNode, declares, uses: var IntSet; topLevel: bool) = for a in n: if a.len >= 3: decl(a[0]) - for i in 1.. 0 + if nb == 1: + return parts[0] + result = parts[0] / parts[1] + for i in 2.. 1: + for b in a: + var s = newNode(a.kind) + s.info = b.info + s.add b + result.add s + else: + result.add a + +proc haveSameKind(dns: seq[DepN]): bool = + # Check if all the nodes in a strongly connected + # component have the same kind + result = true + let kind = dns[0].pnode.kind + for dn in dns: + if dn.pnode.kind != kind: + return false + +proc mergeSections(comps: seq[seq[DepN]], res: PNode) = + # Merges typeSections and ConstSections when they form + # a strong component (ex: circular type definition) + for c in comps: + assert c.len > 0 + if c.len == 1: + res.add c[0].pnode + else: + let fstn = c[0].pnode + let kind = fstn.kind + # always return to the original order when we got circular dependencies + let cs = c.sortedByIt(it.id) + if kind in {nkTypeSection, nkConstSection} and haveSameKind(cs): + # Circular dependency between type or const sections, we just + # need to merge them + var sn = newNode(kind) + for dn in cs: + sn.add dn.pnode.sons[0] + res.add sn + else: + # Problematic circular dependency, we arrange the nodes into + # their original relative order and make sure to re-merge + # consecutive type and const sections + var wmsg = "Circular dependency detected. reorder pragma may not be able to" & + " reorder some nodes properely" + when not defined(release): + wmsg &= ":\n" + for i in 0..