jackfirth / resyntax

A Racket refactoring engine
Apache License 2.0
51 stars 10 forks source link

impossible wish: unravel complex or-and expressions #228

Open sorawee opened 8 months ago

sorawee commented 8 months ago
     (or (and b (weak-box-value b))
         (let ([e (make-cached-element style content key)])
           (hash-set! element-cache key (make-weak-box e))
           e))

could be much better communicated with:

     (cond
       [b (weak-box-value b)]
       [else
        (let ([e (make-cached-element style content key)])
          (hash-set! element-cache key (make-weak-box e))
          e)])

which then opens an opportunity for let-in-cond simplification rule to kick in.

It's an impossible wish because the two code are not quite semantically equivalent generally. They are equivalent here though, because (weak-box-value b) is guaranteed to be non #f.

jackfirth commented 7 months ago

It's not that impossible. I made a known-not-false syntax class for this purpose. We could just add (weak-box-value _) to the list of recognized patterns. Then I think the rule would be:

(or (and cond-expr true-expr:known-not-false)
    false-expr)

=>

(cond [cond-expr true-expr] [else false-expr])
jackfirth commented 4 days ago

Actually, looking at this more, I think your original code can be simplified further down to this:

(weak-box-value
 (hash-ref! element-cache
            key
            (lambda ()
              (make-weak-box (make-cached-element style content key)))))

An existing rule recommends using hash-ref!, but it's defeated in this case by the boxing and unboxing you've added. If you were using weak hashes directly, the rule might catch this case.