yamlscript
yamlscript copied to clipboard
Custom DSL support with instaparse
How cool it would be to able to parse any string to yaml using ebnf in yamlscript ... or script your own scripting language with yamlscript?
Adding support for instaparse would do it. The parsetree from the instaparser could be easily transformed to YAML for further processing in yamlscript.
Here's a simple example:
(ns noob.instayaml
(:require [instaparse.core :as insta]
[clj-yaml.core :as yaml]
[clojure.walk :as walk]
[clojure.java.io :as io]))
(defn vector-to-map [data]
(walk/postwalk
(fn [x]
(if (and (vector? x) (keyword? (first x)))
{(first x) (if (= 2 (count x)) (second x) (vec (rest x)))}
x))
data))
(defn vector-to-yaml-string [parsed-result]
(yaml/generate-string (vector-to-map parsed-result) :dumper-options {:flow-style :block}))
(defn instayaml [expr input]
(let [parsed ((insta/parser expr) input)]
(vector-to-yaml-string parsed)))
(defn instayaml-to-file [expr input filename]
(with-open [writer (io/writer filename)]
(.write writer (instayaml expr input))))
(print (instayaml
"Lambda = Params <'=>'> Expression
Params = <'('> VarList <')'>
<VarList> = Var (<','> Var)*
Expression = Term (Op Term)*
Term = Var | Number | '(' Expression ')'
Op = '*' | '/' | '+' | '-' | '>' | '<' | '==' | '&&' | '||'
<Var> = #'[a-zA-Z_][a-zA-Z0-9_]*'
Number = #'[0-9]+'"
"(foo,bar,zyx)=>foo+bar>zyx"))
(instayaml-to-file "S = VAL | EXPR | PAR
PAR = <'('> S <')'>
<EXPR> = S OP S
<VAL> = #'[0-9]+'
OP = '+' | '-' | '*' | '/'"
"1+(5/3)*2"
"output.yaml")
This prints "(foo,bar,zyx)=>foo+bar>zyx" as:
Lambda:
- Params:
- foo
- bar
- zyx
- Expression:
- Term: foo
- Op: +
- Term: bar
- Op: '>'
- Term: zyx
And second example turns "1+(5/3)*2" to output.yaml file:
S:
- S:
- S: '1'
- OP: +
- S:
PAR:
S:
- S: '5'
- OP: /
- S: '3'
- OP: '*'
- S: '2'