• Stars
    star
    155
  • Rank 240,864 (Top 5 %)
  • Language
    Clojure
  • License
    Eclipse Public Li...
  • Created about 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Configurable EDN/Clojure parser with location metadata

Edamame

Configurable EDN/Clojure parser with location metadata.

CircleCI Clojars Project

Reasons to use edamame

  • You want to include locations in feedback about Clojure and EDN files
  • You want to parse Clojure-like expressions without any evaluation
  • Anonymous functions are read deterministically
  • Highly configurable
  • Auto-resolve aliased keywords based on the ns form

This library works with:

  • Clojure on the JVM
  • GraalVM compiled binaries
  • ClojureScript (including self-hosted and advanced compiled)

Installation

Use as a dependency:

Clojars Project

Projects

Project using edamame:

API

See API.

Usage

(require '[edamame.core :as e :refer [parse-string]])

Location metadata

Locations are attached as metadata:

(def s "
[{:a 1}
 {:b 2}]")
(map meta (parse-string s))
;;=>
({:row 2, :col 2, :end-row 2, :end-col 8}
 {:row 3, :col 2, :end-row 3, :end-col 8})

(->> "{:a {:b {:c [a b c]}}}"
     parse-string
     (tree-seq coll? #(if (map? %) (vals %) %))
     (map meta))
;;=>
({:row 1, :col 1, :end-row 1, :end-col 23}
 {:row 1, :col 5, :end-row 1, :end-col 22}
 {:row 1, :col 9, :end-row 1, :end-col 21}
 {:row 1, :col 13, :end-row 1, :end-col 20}
 {:row 1, :col 14, :end-row 1, :end-col 15}
 {:row 1, :col 16, :end-row 1, :end-col 17}
 {:row 1, :col 18, :end-row 1, :end-col 19})

You can control on which elements locations get added using the :location? option.

Parser options

Edamame's API consists of two functions: parse-string which parses a the first form from a string and parse-string-all which parses all forms from a string. Both functions take the same options. See the docstring of parse-string for all the options.

Examples:

(parse-string "@foo" {:deref true})
;;=> (deref foo)

(parse-string "'bar" {:quote true})
;;=> (quote bar)

(parse-string "#(* % %1 %2)" {:fn true})
;;=> (fn [%1 %2] (* %1 %1 %2))

(parse-string "#=(+ 1 2 3)" {:read-eval true})
;;=> (read-eval (+ 1 2 3))

(parse-string "#\"foo\"" {:regex true})
;;=> #"foo"

(parse-string "#'foo" {:var true})
;;=> (var foo)

(parse-string "#(alter-var-root #'foo %)" {:all true})
;;=> (fn [%1] (alter-var-root (var foo) %1))

Note that standard behavior is overridable with functions:

(parse-string "#\"foo\"" {:regex #(list 're-pattern %)})
(re-pattern "foo")

Clojure defaults

The closest defaults to how Clojure reads code:

{:all true
 :row-key :line
 :col-key :column
 :end-location false
 :location? seq?}

Reader conditionals

Process reader conditionals:

(parse-string "[1 2 #?@(:cljs [3 4])]" {:features #{:cljs} :read-cond :allow})
;;=> [1 2 3 4]

(parse-string "[1 2 #?@(:cljs [3 4])]" {:features #{:cljs} :read-cond :preserve})
;;=> [1 2 #?@(:cljs [3 4])]

(let [res (parse-string "#?@(:bb 1 :clj 2)" {:read-cond identity})]
  (prn res) (prn (meta res)))
;;=> (:bb 1 :clj 2)
;;=> {:row 1, :col 1, :end-row 1, :end-col 18, :edamame/read-cond-splicing true}

Auto-resolve

Auto-resolve keywords:

(parse-string "[::foo ::str/foo]" {:auto-resolve '{:current user str clojure.string}})
;;=> [:user/foo :clojure.string/foo]

If you don't care much about the exact value of the keyword, but just want to parse something:

(parse-string "[::foo ::str/foo]" {:auto-resolve name})
;;=> [:current/foo :str/foo]

To create options from a namespace in the process where edamame is called from:

(defn auto-resolves [ns]
  (as-> (ns-aliases ns) $
    (assoc $ :current (ns-name *ns*))
    (zipmap (keys $)
            (map ns-name (vals $)))))

(require '[clojure.string :as str]) ;; create example alias

(auto-resolves *ns*) ;;=> {str clojure.string, :current user}

(parse-string "[::foo ::str/foo]" {:auto-resolve (auto-resolves *ns*)})
;;=> [:user/foo :clojure.string/foo]

To auto-resolve keywords from the running Clojure environment:

(require '[clojure.test :as t])
(e/parse-string "::t/foo" {:auto-resolve (fn [x] (if (= :current x) *ns* (get (ns-aliases *ns*) x)))})
:clojure.test/foo

:auto-resolve-ns

To auto-magically resolve keywords based on the ns form, use :auto-resolve-ns true:

(= '[(ns foo (:require [clojure.set :as set])) :clojure.set/foo]
    (parse-string-all "(ns foo (:require [clojure.set :as set])) ::set/foo"
                      {:auto-resolve-ns true}))

(def rdr (p/reader "(ns foo (:require [clojure.set :as set])) ::set/foo"))
(def opts (p/normalize-opts {:auto-resolve-ns true}))
(= (ns foo (:require [clojure.set :as set])) (p/parse-next rdr opts))
(= :clojure.set/foo (p/parse-next rdr opts))

Syntax-quote

Syntax quoting can be enabled using the :syntax-quote option. Symbols are resolved to fully qualified symbols using :resolve-symbol which is set to identity by default:

(parse-string "`(+ 1 2 3 ~x ~@y)" {:syntax-quote true})
;;=> (clojure.core/sequence (clojure.core/seq (clojure.core/concat (clojure.core/list (quote +)) (clojure.core/list 1) (clojure.core/list 2) (clojure.core/list 3) (clojure.core/list x) y)))

(parse-string "`(+ 1 2 3 ~x ~@y)" {:syntax-quote {:resolve-symbol #(symbol "user" (name %))}})
;;=> (clojure.core/sequence (clojure.core/seq (clojure.core/concat (clojure.core/list (quote user/+)) (clojure.core/list 1) (clojure.core/list 2) (clojure.core/list 3) (clojure.core/list x) y)))

To resolve symbols in syntax quote from the running Clojure environment:

(require '[clojure.tools.reader :refer [resolve-symbol]])

(require '[clojure.test :as t])
(e/parse-string "`t/run-tests" {:syntax-quote {:resolve-symbol resolve-symbol}})
;;=> (quote clojure.test/run-tests)

Data readers

Passing data readers:

(parse-string "#js [1 2 3]" {:readers {'js (fn [v] (list 'js v))}})
(js [1 2 3])

Postprocess

Postprocess read values:

(defrecord Wrapper [obj loc])

(defn iobj? [x]
  #?(:clj (instance? clojure.lang.IObj x)
     :cljs (satisfies? IWithMeta x)))

(parse-string "[1]" {:postprocess
                       (fn [{:keys [:obj :loc]}]
                         (if (iobj? obj)
                           (vary-meta obj merge loc)
                           (->Wrapper obj loc)))})

[#user.Wrapper{:obj 1, :loc {:row 1, :col 2, :end-row 1, :end-col 3}}]

This allows you to preserve metadata for objects that do not support carrying metadata. When you use a :postprocess function, it is your responsibility to attach location metadata.

Fix incomplete expressions

Edamame exposes information via ex-data in an exception in case of unmatched delimiters. This can be used to fix incomplete expressions:

(def incomplete "{:a (let [x 5")

(defn fix-expression [expr]
  (try (when (parse-string expr)
         expr)
       (catch clojure.lang.ExceptionInfo e
         (if-let [expected-delimiter (:edamame/expected-delimiter (ex-data e))]
           (fix-expression (str expr expected-delimiter))
           (throw e)))))

(fix-expression incomplete) ;; => "{:a (let [x 5])}"

Test

For the node tests, ensure clojure is installed as a command line tool as shown here. For the JVM tests you will require leiningen to be installed. Then run the following:

script/test/jvm
script/test/node
script/test/all

Credits

The code is largely inspired by rewrite-clj and derived projects.

License

Copyright ยฉ 2019-2022 Michiel Borkent

Distributed under the Eclipse Public License 1.0. This project contains code from Clojure and ClojureScript which are also licensed under the EPL 1.0. See LICENSE.

More Repositories

1

jet

CLI to transform between JSON, EDN, YAML and Transit using Clojure
Clojure
584
star
2

carve

Remove unused Clojure vars
Clojure
275
star
3

grasp

Grep Clojure code using clojure.spec regexes
Clojure
233
star
4

deps.clj

A faithful port of the clojure CLI bash script to Clojure
Clojure
225
star
5

speculative

Unofficial community-driven specs for clojure.core
Clojure
187
star
6

clojure-rust-graalvm

An example of Clojure program calling a Rust library, all combined into one executable using GraalVM.
Rust
120
star
7

re-find

Find functions by matching specs
Clojure
118
star
8

quickblog

Light-weight static blog engine for Clojure and babashka
Clojure
117
star
9

quickdoc

Quick and minimal API doc generation for Clojure
Clojure
116
star
10

bebo

Run Clojure scripts on deno
Clojure
98
star
11

flycheck-clj-kondo

Emacs integration for clj-kondo via flycheck
Emacs Lisp
84
star
12

rewrite-edn

Utility lib on top of rewrite-clj with common operations to update EDN while preserving whitespace and comments.
Clojure
76
star
13

clj2el

Transpile Clojure to Emacs Lisp!
Clojure
63
star
14

glam

A cross-platform package manager.
Clojure
62
star
15

api-diff

Print API diffs between library versions
Clojure
59
star
16

deflet

Make let-expressions REPL-friendly!
Clojure
57
star
17

cljtree-graalvm

Tree version in Clojure built with GraalVM
Clojure
53
star
18

respeced

Testing library for clojure.spec fdefs
Clojure
52
star
19

dynaload

The dynaload logic from clojure.spec.alpha as a library
Clojure
52
star
20

jayfu

Jayfu is a tutorial on how to create a Clojure CLI with GraalVM native-image and SCI.
Clojure
52
star
21

lein2deps

Lein project.clj to deps.edn converter
Clojure
50
star
22

blog

HTML
49
star
23

plsci

PostgreSQL procedural language handler for Clojure via SCI
Rust
48
star
24

advent-of-cljc

Cross platform Clojure Advent of Code solutions
Clojure
44
star
25

boot-bundle

boot-bundle: managed dependencies for boot, the clojure build tool
Clojure
43
star
26

deps-infer

Infer mvn deps from sources
Clojure
39
star
27

puget-cli

A CLI version of puget
Shell
37
star
28

specter-cli

A native Specter CLI, compiled with GraalVM native-image and executed by SCI.
Clojure
33
star
29

draggable-button-in-reagent

Very simple example of a draggable button in Reagent
Clojure
31
star
30

spartan.spec

A spartan version of clojure.spec compatible with babashka
Clojure
30
star
31

lein-new-liberagent

leiningen template for apps that use reagent and liberator
Clojure
29
star
32

re-find.web

Web version of re-find
Clojure
25
star
33

nbb-action-example

An example of writing a Github action with nbb
Clojure
24
star
34

lein2boot

The goal of this exercise is to convert a leiningen project to boot and have exactly the same workflow.
Clojure
24
star
35

gh-release-artifact

Upload artifacts to Github releases idempotently
Clojure
24
star
36

balcony

Should I water my balcony?
Clojure
23
star
37

generate-podcast

A babashka script to create a podcast from a local directory with mp3 files
Clojure
22
star
38

tools

Tools
Clojure
19
star
39

fly_io_clojure

A fly.io example for Clojure
Clojure
17
star
40

refl

Clean up generated reflection configs for GraalVM native-image compiled Clojure programs
Clojure
17
star
41

analyze-reify

Analyze occurrences of reify in Clojure code. Implemented using tree-sitter-clojure and Rust.
Rust
17
star
42

advent-of-babashka

Advent of Code using babashka and nbb
Clojure
16
star
43

aoc2017

Advent of Code 2017
Clojure
15
star
44

lein-new-wrom

Webjars + Ring + Om leiningen template
Clojure
15
star
45

clj-reflector-graal-java11-fix

A fix for an issue with clojure.lang.Reflector in GraalVM native-image JDK11.
Clojure
15
star
46

cljs-showcase

Clojure
13
star
47

clj.el

Clojure-like macros and functions in elisp
Emacs Lisp
13
star
48

balcony-hs

Should I water my balcony?
Haskell
13
star
49

babashka-docker-action-example

Dockerfile
12
star
50

who-follows-me

Check who follows you, but you're not following back and vice versa. https://twitter.michielborkent.nl
Clojure
12
star
51

trickle-playground

A Truffle Clojure Interpreter (playground)
Java
12
star
52

finitize

Limit and realize possibly infinite seqs
Clojure
12
star
53

nrepl-server

Proof of concept nREPL server
Clojure
10
star
54

full-stack-clojure-han-okt-2015

Talk about developing full stack Clojure applications at HAN University of Applied Sciences
Clojure
10
star
55

clojurecursus

Introductiecursus Functioneel Programmeren met Clojure
CSS
10
star
56

missing.test.assertions

A library that detects missing test assertions in clojure.test tests
Clojure
9
star
57

deps.add-lib

Clojure 1.12's add-lib feature for leiningen and/or other environments without a specific version of the clojure CLI
Clojure
8
star
58

figwheel-keep-om-turning

Code for blog post at http://blog.michielborkent.nl/2014/09/25/figwheel-keep-Om-turning/
Clojure
8
star
59

cljtree-planck

A ClojureScript version of `tree` in Planck
Shell
6
star
60

bun-squint-loader

JavaScript
6
star
61

simple-cljs-examples

Curated list of ClojureScript sample applications suited for those starting with ClojureScript
6
star
62

graal.locking

A workaround for CLJ-1472 as a library
Clojure
6
star
63

tictactoe

tictactoe (clojure)
Clojure
5
star
64

bb-cherry-example

A web app showing real time JS compilation with babashka and cherry
Clojure
5
star
65

immutable-webapp

Immutable Webapp!
HTML
5
star
66

spartan.test

A spartan test framework compatible with babashka.
Clojure
5
star
67

speculative-kaocha-plugin

speculative kaocha plugin
Clojure
5
star
68

aoc2015_day7

Solution of Advent of Code Day 7 using clojure.spec
Clojure
4
star
69

oredev2014

Slides and code for ร˜redev 2014
Clojure
4
star
70

tictactoe-cljs

Tictactoe in Clojurescript and Om
Clojure
4
star
71

cherry-action-example

Github action implemented with cherry
Clojure
4
star
72

homebrew-brew

Homebrew formulas
Shell
4
star
73

datalevin-native

Clojure
4
star
74

sci-wallpaper-downloader

A port of @yogthos's wallpaper downloader to the Small Clojure Interpreter on NodeJS
Clojure
4
star
75

domcode-cljs-react

Slides and code for presentation at the DomCode meetup
Clojure
4
star
76

clj-jdbc

A hypothetical Clojure command tool focusing around SQL interaction via JDBC
Clojure
4
star
77

sci-birch

tree CLI using sci, ported from lambdaisland's birch
Clojure
3
star
78

clj-native-sound-demo

A demo of using the Java sound API with GraalVM native-image
Clojure
3
star
79

bb-php-guestbook

A guestbook using babashka and PHP
Clojure
2
star
80

michielborkent.nl

Home page sources
Clojure
2
star
81

clj-kondo-configurator

CLI tool to merge clj-kondo configurations.
Clojure
2
star
82

boot.bundle.edn

My boot.bundle.edn file
Clojure
2
star
83

my-aob

Clojure
2
star
84

FP-AMS-ClojureScript-talk

Slides and code for talk at FP AMS about Clojurescript
Clojure
2
star
85

react-amsterdam

Talk for React-Amsterdam, February 12th 2015
Clojure
2
star
86

pprint

Clojure
2
star
87

sytac-core-async

Slides and code for presentation at Sytac Devjam
Clojure
2
star
88

SnakeYAML

Temporary fork of SnakeYAML
Java
1
star
89

leiningen.org

Leiningen's web site
Clojure
1
star
90

try_git

1
star
91

clj-1472-repro

A repro of CLJ-1472
Clojure
1
star
92

cljs-macro

Example of usage of a macro in ClojureScript.
Clojure
1
star
93

itunes2dropbox

Share the current playing song or selected songs from iTunes to your Dropbox public folder.
AppleScript
1
star
94

squint-bun-cloudflare

JavaScript
1
star
95

aoc2016

Advent of Clojure 2016
Clojure
1
star
96

fp-hu-may-2016

Talk about Functional Programming at Hogeschool Utrecht, May 2016
Clojure
1
star
97

Clojure-FinalAssignment

Quiz
Clojure
1
star
98

ns-parser

Helper library for parsing ns forms in combination with edamame and rewrite-clj
Clojure
1
star
99

clj-kondo.web

playground for clj-kondo
Clojure
1
star
100

test-repo

Repo to test Github features
Clojure
1
star