Skip to content

Commit 3cc4a3d

Browse files
Copilotjackfirth
andcommitted
Add flatten-apply-append-syntax-template refactoring rule
Co-authored-by: jackfirth <[email protected]>
1 parent 5709ca0 commit 3cc4a3d

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

default-recommendations/syntax-shortcuts-test.rkt

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,18 @@ test: "making a symbol with format from a keyword can be simplified to format-sy
5353
test: "making a symbol with format from a keyword syntax object can be simplified to format-symbol"
5454
- (string->symbol (format "make-~a" (keyword->string (syntax-e #'#:foo))))
5555
- (format-symbol "make-~a" #'#:foo)
56+
57+
58+
test: "flattening nested syntax templates with apply append can be simplified"
59+
--------------------
60+
(require racket/syntax)
61+
(define (f stx)
62+
(with-syntax ([((a ...) ...) stx])
63+
(apply append
64+
(map syntax->list (syntax->list #'((a ...) ...))))))
65+
====================
66+
(require racket/syntax)
67+
(define (f stx)
68+
(with-syntax ([((a ...) ...) stx])
69+
(syntax->list (syntax (a ... ...)))))
70+
--------------------

default-recommendations/syntax-shortcuts.rkt

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
(require racket/string
1313
racket/syntax
14+
racket/list
1415
rebellion/private/static-name
1516
resyntax/base
1617
syntax/parse)
@@ -103,6 +104,25 @@
103104
(format-symbol template (~replacement arg.simplified #:original arg) ...))
104105

105106

107+
(define-refactoring-rule flatten-apply-append-syntax-template
108+
#:description
109+
"Flattening nested syntax templates with `apply append` and `map syntax->list` can be simplified\
110+
by using a single `syntax->list` call on a flattened template."
111+
#:literals (apply append map syntax->list syntax ...)
112+
113+
(apply append (map syntax->list (syntax->list (syntax ((inner ...) ...)))))
114+
115+
#:with flattened-template
116+
(let* ([inner-attrs (attribute inner)]
117+
; Wrap in list if it's not already a list
118+
[inner-list (if (list? inner-attrs) inner-attrs (list inner-attrs))]
119+
[ellipsis-sym (datum->syntax #'here '...)])
120+
(datum->syntax #'here (append inner-list (list ellipsis-sym ellipsis-sym))))
121+
122+
(syntax->list #'flattened-template))
123+
124+
106125
(define-refactoring-suite syntax-shortcuts
107-
#:rules (format-string-to-format-symbol
126+
#:rules (flatten-apply-append-syntax-template
127+
format-string-to-format-symbol
108128
syntax-e-in-format-id-unnecessary))

0 commit comments

Comments
 (0)