+;;; Return the code to initialize BINDING, and push it extending the
+;;; current lexical environment if the variable is special.
+(defun let*-initialize-value (binding)
+ (let ((var (first binding))
+ (value (second binding)))
+ (if (special-variable-p var)
+ (concat (ls-compile `(setq ,var ,value)) ";" *newline*)
+ (let ((v (gvarname var)))
+ (let ((b (make-binding var 'variable v)))
+ (prog1 (concat "var " v " = " (ls-compile value) ";" *newline*)
+ (push-to-lexenv b *environment* 'variable)))))))
+
+;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
+;;; DOES NOT generate code to initialize the value of the symbols,
+;;; unlike let-binding-wrapper.
+(defun let*-binding-wrapper (symbols body)
+ (when (null symbols)
+ (return-from let*-binding-wrapper body))
+ (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
+ (remove-if-not #'special-variable-p symbols))))
+ (concat
+ "try {" *newline*
+ (indent
+ (mapconcat (lambda (b)
+ (let ((s (ls-compile `(quote ,(car b)))))
+ (concat "var " (cdr b) " = " s ".value;" *newline*)))
+ store)
+ body)
+ "}" *newline*
+ "finally {" *newline*
+ (indent
+ (mapconcat (lambda (b)
+ (let ((s (ls-compile `(quote ,(car b)))))
+ (concat s ".value" " = " (cdr b) ";" *newline*)))
+ store))
+ "}" *newline*)))
+
+
+(define-compilation let* (bindings &rest body)
+ (let ((bindings (mapcar #'ensure-list bindings))
+ (*environment* (copy-lexenv *environment*)))
+ (js!selfcall
+ (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
+ (body (concat (mapconcat #'let*-initialize-value bindings)
+ (ls-compile-block body t))))
+ (let*-binding-wrapper specials body)))))
+
+