Skip to content

Instantly share code, notes, and snippets.

@dogenpunk
Forked from kachayev/css-parser.md
Last active August 29, 2015 14:08
Show Gist options
  • Select an option

  • Save dogenpunk/6da9f9e7a5b621039f15 to your computer and use it in GitHub Desktop.

Select an option

Save dogenpunk/6da9f9e7a5b621039f15 to your computer and use it in GitHub Desktop.

What we have?

.container h1 {
  color: rgba(255, 0, 0, 0.9);
  font-size: 24px;
  font-family: Monaco;
}

What we want to get?

{:selector ".container h1",
 :rules
 ({:key "color", :value "rgba(255, 0, 0, 0.9)"}
  {:key "font-size", :value "24px"}
  {:key "font-family", :value "Monaco"})}

Let's do this with Monadic parsing approach. Step-by-step explanation of how it works one can find in Monadic Parsing in Python.

What about Clojure?

1. Parser abstraction

From theory:

type Parser a = String -> [(a, String)]

So, we're going to represent parser as simple function that takes input and return seq of possible results. Simplest parser:

;; takes any input and "consume" first char from it
(defn any [input]
  (if (empty? input) '()
      (list [(first input)
             (apply str (rest input))])))

(any "clojure-1.7") ;; => ([c lojure-1.7])

Will use few helpers:

(defn parse [parser input]
  (parser input))

(defn parse-all [parser input]
  (ffirst (filter #(= "" (second %)) (parse parser input))))

2. Monads

3. Basic parsers

4. Combinators

5. CSS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment