;;; flex-compile-repl.el --- A REPL based compiler  -*- lexical-binding: t; -*-

;; Copyright (C) 2015 - 2025 Paul Landes

;; Author: Paul Landes
;; Maintainer: Paul Landes
;; Keywords: compilation integration processes
;; URL: https://github.com/plandes/flex-compile
;; Package-Requires: ((emacs "26.1"))

;; This file is not part of GNU Emacs.

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.

;;; Commentary:

;; Run, evaluate and compile functionality for a variety of different languages
;; and modes.  The specific "compilation" method is different across each
;; add-on library.  For example, for ESS and Clojure you can evaluate a
;; specific file and/or evaluate a specfic expression via a REPL.  For running
;; a script or starting a `make` an async process is started.
;;
;; For more information see https://github.com/plandes/flex-compile

;;; Code:

(require 'comint)
(require 'eieio)
(require 'flex-compile-config)

(defclass repl-flex-compiler (single-buffer-flex-compiler
			      conf-file-flex-compiler)
  ((repl-buffer-regexp :initarg :repl-buffer-regexp
		       :type string
		       :documentation "\
Regular expression to match buffers for functions like killing the session.")
   (derived-buffer-names :initarg :derived-buffer-names
			 :initform nil
			 :type list
			 :documentation "\
List of buffers for functions (like killing a buffer) when session ends.")
   (repl-buffer-start-wait :initarg :repl-buffer-start-wait
			   :initform 0.1
			   :type number
			   :documentation "\
Number of seconds (as a float) to wait before issuing any first command to the
REPL.")
   (repl-buffer-start-timeout :initarg :repl-buffer-start-timeout
			      :initform 1
			      :type integer
			      :documentation "\
Number of seconds as an integer to wait to start before giving up (and not
displaying).  If this is 0, don't wait or display the buffer when it comes
up.")
   (prompt-kill-repl-buffer :initarg :prompt-kill-repl-buffer
			    :initform t
			    :type boolean
			    :documentation "\
If non-`nil' then prompt to kill a REPL buffer on clean.")
   (repl-restart :initarg :repl-restart
		 :initform nil
		 :type boolean
		 :documentation "\
Whether to restart the REPL after each compilation invocation.")
   (output-clear :initarg :output-clear
		 :initform nil
		 :type boolean
		 :documentation "\
Whether or not to clear comint buffer after a compilation.")
   (form-history :initarg :form-history
		 :initform (gensym "config-repl-form-history")
		 :type symbol
		 :documentation "\
The history variable for the eval form history.")
   (--run-depth :initarg :run-depth
		:initform 0
		:accessor nil))
  :method-invocation-order :c3
  :documentation "Compiles by evaluating expressions in the REPL.")

(cl-defmethod initialize-instance ((this repl-flex-compiler) &optional slots)
  "Initialize instance THIS with arguments SLOTS."
  (let ((props
	 (list
	  (config-boolean-prop :object-name 'output-clear
			       :prop-entry this
			       :prompt "Clear output on compile"
			       :input-type 'toggle)
	  (config-boolean-prop :object-name 'prompt-kill-repl-buffer
			       :prop-entry this
			       :prompt "Confirm REPL buffer kills"
			       :input-type 'toggle)
	  (config-number-prop :object-name 'repl-buffer-start-timeout
			      :prop-entry this
			      :prompt "Seconds to wait for REPL to start")
	  (config-number-prop :object-name 'repl-buffer-start-wait
			      :prop-entry this
			      :number-type 'float
			      :prompt "Seconds to wait before starting the REPL")
	  (config-boolean-prop :object-name 'repl-restart
			       :prop-entry this
			       :prompt "Restart REPL after each compile"
			       :input-type 'toggle))))
    (setq slots (plist-put slots
			   :props (append (plist-get slots :props) props))))
  (cl-call-next-method this slots))

(cl-defmethod flex-compiler-repl-start ((this repl-flex-compiler))
  "Start the REPL using THIS compiler."
  (config-persistent--unimplemented this "start-repl"))

(cl-defmethod flex-compiler-repl-compile ((this repl-flex-compiler) file)
  "Invoked by `compile' type messages from THIS compiler.

FILE gets evaluated by the compiler either as a IPC communication or by direct
insertion in the REPL buffer.

This method is meant to allow for REPL compiles \(really some kind of
evaluation), while allowing base class compilation features.."
  (ignore this file)
  (config-persistent--unimplemented this "repl-compile"))

(cl-defmethod flex-compiler-wait-for-buffer ((this repl-flex-compiler))
  "Wait for the compilation to start using THIS compiler.

The caller raises and error if it doesn't start in time."
  (with-slots (repl-buffer-start-timeout) this
    (let ((count-down repl-buffer-start-timeout)
	  buf)
      (cl-block wfb
       (dotimes (i count-down)
	 (setq buf (flex-compiler-buffer this))
	 (if buf
	     (cl-return-from wfb buf)
	   (message "Waiting for buffer to start... (%d)"
		    (- count-down i))
	   (sit-for 1)))))))

(cl-defmethod flex-compiler-repl-running-p ((this repl-flex-compiler))
  "Return whether or not THIS REPL is currently running."
  (not (null (flex-compiler-buffer this))))

(cl-defmethod flex-compiler-repl-assert-running ((this repl-flex-compiler))
  "Raise an error if THIS REPL *is* running."
  (unless (flex-compiler-repl-running-p this)
    (error "The REPL for %s isn't started" (config-entry-name this))))

(cl-defmethod flex-compiler-repl-assert-not-running ((this repl-flex-compiler))
  "Raise an error if THIS REPL isn't running."
  (if (flex-compiler-repl-running-p this)
      (error "Compiler %s is already running"
	     (config-entry-name this))))

(cl-defmethod flex-compiler-repl--run-start ((this repl-flex-compiler))
  "Start THIS compiler's REPL if it isn't already."
  (with-slots (repl-buffer-start-timeout
	       repl-buffer-start-wait
	       start-directory) this
    (let ((timeout repl-buffer-start-timeout)
	  buf)
      (unless (flex-compiler-repl-running-p this)
	(config-prop-entry-set-required this)
	(let ((default-directory (or start-directory default-directory)))
	  (flex-compiler-repl-start this))
	(when (> timeout 0)
	  (setq buf (flex-compiler-wait-for-buffer this))
	  (unless buf
	    (error "Couldn't create REPL for compiler %s"
		   (config-entry-name this))))
	(when (> repl-buffer-start-wait 0)
	  (sit-for repl-buffer-start-wait))))))

(cl-defmethod flex-compiler-send-input ((this repl-flex-compiler)
					&optional command)
  "Send a COMMAND \(input) to THIS compiler's REPL."
  (ignore this)
  (goto-char (point-max))
  (insert command)
  (comint-send-input))

(cl-defmethod flex-compiler-run-command ((this repl-flex-compiler)
					 &optional command)
  "Send COMMAND to THIS compiler's REPL to evaluate or start a process."
  (flex-compiler-repl-assert-running this)
  (let ((buf (flex-compiler-buffer this)))
    (with-current-buffer buf
      (if command
	  (flex-compiler-send-input this command)))))

(cl-defmethod flex-compiler-buffer ((this repl-flex-compiler))
  "Find THIS compiler's first REPL buffer found in the buffer list."
  (with-slots (repl-buffer-regexp) this
    (cl-block found-buf
      (dolist (buf (buffer-list))
	(let ((buf-name (buffer-name buf)))
	  (when (string-match repl-buffer-regexp buf-name)
	    (cl-return-from found-buf buf)))))))

(cl-defmethod flex-compiler--kill-buffer ((this repl-flex-compiler) buffer)
  "Kill THIS compiler's BUFFER.
It kills the buffer without prompting  However, in some cases, it might raise
an erorr."
  (ignore this)
  (with-slots (prompt-kill-repl-buffer) this
    (when (buffer-live-p buffer)
      (let ((kill-buffer-query-functions
	     (if prompt-kill-repl-buffer
		 kill-buffer-query-functions
	       nil)))
	(kill-buffer buffer)))))

(cl-defmethod flex-compiler-kill-repl ((this repl-flex-compiler))
  "Kill THIS compiler's REPL."
  (with-slots (derived-buffer-names prompt-kill-repl-buffer) this
    (let ((bufs (append (mapcar 'get-buffer derived-buffer-names)
			(cons (flex-compiler-buffer this) nil)))
	  (count 0))
      (dolist (buf bufs)
	(when (and buf (buffer-live-p buf))
	  (flex-compiler--kill-buffer this buf)
	  (cl-incf count)))
      (message "%s killed %d buffer(s)"
	       (capitalize (config-entry-name this)) count))))

(cl-defmethod flex-compiler-clear-buffer ((this repl-flex-compiler))
  "Clear THIS compiler's REPL buffer."
  (with-current-buffer (flex-compiler-buffer this)
    (comint-clear-buffer)))

(cl-defmethod flex-compiler-start-buffer ((this repl-flex-compiler) start-type)
  "Return a new buffer for THIS compiler with a processing compilation.
START-TYPE is either symbols `compile', `run', `clean' depending
if invoked by `flex-compiler-compile' or `flex-compiler-run'."
  (config-prop-entry-set-required this)
  (with-slots (config-file output-clear repl-restart) this
    (setf (slot-value this '--run-depth)
	  (cond ((eq start-type 'compile) (+ (slot-value this '--run-depth) 1))
		((eq start-type 'run) 0)
		(t (slot-value this '--run-depth))))
    (let ((runningp (flex-compiler-repl-running-p this)))
      (cl-case start-type
	(compile (let ((prompt-kill 'prompt-kill-repl-buffer))
		   (unless runningp
		     (flex-compiler-run this))
		   (if (flex-compiler-repl-running-p this)
		       (progn
			 (when (and repl-restart
				    (eq start-type 'compile)
				    (> (slot-value this '--run-depth) 1))
			   (let ((prev (slot-value this prompt-kill)))
			     (unwind-protect
				 (progn
				   (setf (slot-value this prompt-kill) nil)
				   (flex-compiler-kill-repl this)
				   (flex-compiler-repl--run-start this))
			       (setf (slot-value this prompt-kill) prev))))
			 (when output-clear
			   (flex-compiler-clear-buffer this))
			 (flex-compiler-repl-compile this config-file))
		     (if runningp
			 (error "REPL hasn't started")
		       (message "REPL still starting, please wait")))
		   (flex-compiler-buffer this)))
	(run (progn
	       (flex-compiler-repl--run-start this)
	       (flex-compiler-buffer this)))
	(clean (progn
		 (flex-compiler-kill-repl this)
		 'killed-buffer))))))

(cl-defmethod flex-compiler-eval-initial-at-point ((this repl-flex-compiler))
  "Return the expression at or right before the point for THIS compiler."
  (ignore this))

(cl-defmethod flex-compiler-eval-form-impl ((this repl-flex-compiler) form)
  "Evaluate the FORM and return the response of the REPL for THIS compiler."
  (ignore this form)
  (config-persistent--unimplemented this "eval-form-impl"))

(cl-defmethod flex-compiler-query-read-form ((this repl-flex-compiler)
					     no-input-p)
  "Read a form, meaningful for THIS compiler from the user.
NO-INPUT-P, if non-nil, use the symbolic expression at the current point."
  (with-slots (form-history) this
    (let ((init (flex-compiler-eval-initial-at-point this)))
      (if no-input-p
	  init
	(read-string "Form: " init form-history)))))

(cl-defmethod flex-compiler-evaluate-form ((this repl-flex-compiler)
					   &optional form)
  "Return the evaluation of FORM for THIS compiler.
See the `:eval-form' slot."
  (let ((res (flex-compiler-eval-form-impl this form)))
    (if (stringp res)
	res
      (prin1-to-string res))))

(provide 'flex-compile-repl)

;;; flex-compile-repl.el ends here
