From cce1b24b1cc3860ff503668761d2798b1b1d1ef0 Mon Sep 17 00:00:00 2001 From: Timothee Cour Date: Fri, 9 Apr 2021 01:00:13 -0500 Subject: [PATCH] ast: add getPIdent (#17684) * ast: add getPIdent * fixup --- compiler/ast.nim | 8 ++++++++ compiler/renderer.nim | 20 +++++++++----------- compiler/reorder.nim | 7 ++----- 3 files changed, 19 insertions(+), 16 deletions(-) diff --git a/compiler/ast.nim b/compiler/ast.nim index 7d13956e9..fffe08cb7 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -1054,6 +1054,14 @@ const defaultAlignment = -1 defaultOffset = -1 +proc getPIdent*(a: PNode): PIdent {.inline.} = + ## Returns underlying `PIdent` for `{nkSym, nkIdent}`, or `nil`. + # xxx consider whether also returning the 1st ident for {nkOpenSymChoice, nkClosedSymChoice} + # which may simplify code. + case a.kind + of nkSym: a.sym.name + of nkIdent: a.ident + else: nil proc getnimblePkg*(a: PSym): PSym = result = a diff --git a/compiler/renderer.nim b/compiler/renderer.nim index 9a867b0a1..78e2fe20e 100644 --- a/compiler/renderer.nim +++ b/compiler/renderer.nim @@ -964,14 +964,12 @@ proc skipHiddenNodes(n: PNode): PNode = else: break proc accentedName(g: var TSrcGen, n: PNode) = + # This is for cases where ident should've really been a `nkAccQuoted`, e.g. `:tmp` + # or if user writes a macro with `ident":foo"`. It's unclear whether these should be legal. const backticksNeeded = OpChars + {'[', '{', '\''} if n == nil: return - let isOperator = - if n.kind == nkIdent and n.ident.s.len > 0 and n.ident.s[0] in backticksNeeded: true - elif n.kind == nkSym and n.sym.name.s.len > 0 and n.sym.name.s[0] in backticksNeeded: true - else: false - - if isOperator: + let ident = n.getPIdent + if ident != nil and ident.s[0] in backticksNeeded: put(g, tkAccent, "`") gident(g, n) put(g, tkAccent, "`") @@ -999,9 +997,9 @@ proc infixArgument(g: var TSrcGen, n: PNode, i: int) = put(g, tkParRi, ")") proc isCustomLit(n: PNode): bool = - n.len == 2 and n[0].kind == nkRStrLit and - (n[1].kind == nkIdent and n[1].ident.s.startsWith('\'')) or - (n[1].kind == nkSym and n[1].sym.name.s.startsWith('\'')) + if n.len == 2 and n[0].kind == nkRStrLit: + let ident = n[1].getPIdent + result = ident != nil and ident.s.startsWith('\'') proc gsub(g: var TSrcGen, n: PNode, c: TContext, fromStmtList = false) = if isNil(n): return @@ -1234,8 +1232,8 @@ proc gsub(g: var TSrcGen, n: PNode, c: TContext, fromStmtList = false) = else: gsub(g, n, 0) put(g, tkDot, ".") - if n.len > 1: - accentedName(g, n[1]) + assert n.len == 2, $n.len + accentedName(g, n[1]) of nkBind: putWithSpace(g, tkBind, "bind") gsub(g, n, 0) diff --git a/compiler/reorder.nim b/compiler/reorder.nim index 4ffe4ccf8..65c1fb9ee 100644 --- a/compiler/reorder.nim +++ b/compiler/reorder.nim @@ -36,11 +36,8 @@ proc newDepN(id: int, pnode: PNode): DepN = proc accQuoted(cache: IdentCache; n: PNode): PIdent = var id = "" for i in 0..