;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: language/algorithms/parsing-search.lisp

;;;; Parsing as Search (Section 23.3): Bottom-Up Parsing with A* and Beam Search

;;; A state is (remaining-words . symbols): the words not yet given a
;;; category, and the list of the categories of the words before them,
;;; partly reduced by the rules of the grammar.  A step gives the next word
;;; one of its categories or, when every word has one, replaces a span of
;;; symbols that matches the right-hand side of a rule by its left-hand
;;; side.  The goal is to reduce the sentence to the start symbol.  The
;;; grammars are those of the chart parser without augmentations, e.g. *E0*.

(defstructure (parsing-problem (:include problem))
  "The problem of parsing a list of words, bottom-up."
  (grammar *grammar*))

(defun make-parsing-search-problem (words grammar)
  (make-parsing-problem :initial-state (cons words nil) :grammar grammar))

(defun parsing-successors (state grammar)
  "The states reachable in one step from STATE."
  (destructuring-bind (remaining . symbols) state
    (if remaining
        (mapcar #'(lambda (category)
                    (cons (rest remaining) (append symbols (list category))))
                (categories-for (first remaining) grammar))
      (loop for rule in (grammar-rules grammar)
            nconc (let* ((rhs (rule-rhs rule))
                         (size (length rhs)))
                    (loop for start from 0 to (- (length symbols) size)
                          when (equal rhs (subseq symbols start (+ start size)))
                            collect (cons nil
                                          (append (subseq symbols 0 start)
                                                  (list (rule-lhs rule))
                                                  (nthcdr (+ start size) symbols)))))))))

(defmethod successors ((problem parsing-problem) state)
  (mapcar #'(lambda (next) (cons 'parse next))
          (parsing-successors state (parsing-problem-grammar problem))))

(defun parsing-goal? (state grammar)
  (and (null (car state))
       (equal (cdr state) (list (grammar-start-symbol grammar)))))

(defmethod goal-test ((problem parsing-problem) state)
  (parsing-goal? state (parsing-problem-grammar problem)))

(defmethod h-cost ((problem parsing-problem) state)
  "The number of words and symbols left to reduce."
  (+ (length (car state)) (length (cdr state)) -1))

(defun astar-search-parsing (words grammar)
  "Is WORDS a sentence of GRAMMAR?  Search bottom-up with A*; return the
  list of the states from the words to the start symbol, or NIL."
  (let ((node (A*-search (make-parsing-search-problem words grammar))))
    (and node (mapcar #'node-state (solution-nodes node)))))

(defun beam-search-parsing (words grammar &optional (beam-width 3))
  "Is WORDS a sentence of GRAMMAR?  Search bottom-up keeping only the
  BEAM-WIDTH states with the fewest words and symbols at each step; return
  the list of the states from the words to the start symbol, or NIL (beam
  search is incomplete: it can miss a parse)."
  (let ((frontier (list (list (cons words nil)))))   ; paths, latest state first
    (loop while frontier
          do (let ((goal (find-if #'(lambda (path) (parsing-goal? (first path) grammar))
                                  frontier)))
               (when goal (return (reverse goal)))
               (let ((children nil))
                 (dolist (path frontier)
                   (dolist (next (parsing-successors (first path) grammar))
                     (unless (find next children :key #'first :test #'equal)
                       (push (cons next path) children))))
                 (setf frontier
                       (let ((sorted (stable-sort (nreverse children) #'<
                                                  :key #'(lambda (path)
                                                           (+ (length (car (first path)))
                                                              (length (cdr (first path))))))))
                         (subseq sorted 0 (min beam-width (length sorted))))))))))
