Skip to main content

One post tagged with "wip"

View All Tags

· 2 min read

Here's how you can use Janet's built-in Parsing Expression Grammar (PEG) module to define a grammar capable of parsing valid JSON into an Abstract Syntax Tree in only 13 lines of code (one of which is just the "define" keyword and a symbol name):

(def json-parser
~{:null (/ (<- "null") ,|[$ :null])
:bool (/ (<- (+ "true" "false")) ,|[$ :bool])
:number (/ (<- (* (? "-") :d+ (? (* "." :d+)))) ,|[$ :number])
:string (/ (* "\"" (<- (to (* (> -1 (not "\\")) "\"")))
(* (> -1 (not "\\")) "\"")) ,|[$ :string])
:array (/ (* "[" :value (any (* :s* "," :value)) "]") ,|[$& :array])
:object (/ (* "{" :s* :string :s* ":" :value
(any (* :s* "," :s* :string :s* ":" :value))
"}") ,|[(from-pairs (partition 2 $&)) :object])
:value (* :s* (+ :null :bool :number :string :array :object) :s*)
:unmatched (/ (<- (some 1)) ,|[$ :unmatched])
:main (some (+ :value "\n" :unmatched))})

[WIP]