|
| 1 | +(ns socket-repl.parser |
| 2 | + (:require |
| 3 | + [clojure.string :as string] |
| 4 | + [clojure.tools.reader.reader-types :as reader-types] |
| 5 | + [clojure.tools.reader :as reader])) |
| 6 | + |
| 7 | +(defn position |
| 8 | + "Returns the zero-indexed position in a code string given line and column." |
| 9 | + [code-str row col] |
| 10 | + (->> code-str |
| 11 | + string/split-lines |
| 12 | + (take (dec row)) |
| 13 | + (string/join) |
| 14 | + count |
| 15 | + (+ col (dec row)) ;; `(dec row)` to include for newlines |
| 16 | + dec |
| 17 | + (max 0))) |
| 18 | + |
| 19 | +(defn search-start |
| 20 | + "Find the place to start reading from. Search backwards from the starting |
| 21 | + point, looking for a '[', '{', or '('. If none can be found, search from |
| 22 | + the beginning of `code-str`." |
| 23 | + [code-str start-row start-col] |
| 24 | + (let [openers #{\[ \( \{} |
| 25 | + start-position (position code-str start-row start-col)] |
| 26 | + (if (contains? openers (nth code-str start-position)) |
| 27 | + start-position |
| 28 | + (let [code-str-prefix (subs code-str 0 start-position)] |
| 29 | + (->> openers |
| 30 | + (map #(string/last-index-of code-str-prefix %)) |
| 31 | + (remove nil?) |
| 32 | + (apply max 0)))))) |
| 33 | + |
| 34 | +(defn read-next |
| 35 | + "Reads the next expression from some code. Uses an `indexing-pushback-reader` |
| 36 | + to determine how much was read, and return that substring of the original |
| 37 | + `code-str`, rather than what was actually read by the reader." |
| 38 | + [code-str start-row start-col] |
| 39 | + (let [code-str (subs code-str (search-start code-str start-row start-col)) |
| 40 | + rdr (reader-types/indexing-push-back-reader code-str)] |
| 41 | + ;; Read a form, but discard it, as we want the original string. |
| 42 | + (reader/read rdr) |
| 43 | + (subs code-str |
| 44 | + 0 |
| 45 | + ;; Even though this returns the position *after* the read, this works |
| 46 | + ;; because subs is end point exclusive. |
| 47 | + (position code-str |
| 48 | + (reader-types/get-line-number rdr) |
| 49 | + (reader-types/get-column-number rdr))))) |
0 commit comments