view 2-Io/day3-DSL.io @ 43:d2764720ea17

Add the Day 3 'Domain Specific Language'
author IBBoard <dev@ibboard.co.uk>
date Mon, 18 Sep 2017 20:45:32 +0100
parents
children 6347bacb3be7
line wrap: on
line source

# Creating a simple "domain-specific language"
# (Except it's not really - it's just a little extension to support
# the "{ key:value[, key:value[…]] }" format of specifying dictionaries)

# Because this is a string then we can do it at any time!
OperatorTable addAssignOperator(":", "atPutThing")

# curlyBrackets is an automatically invoked function from the parser whenever
# it encounters curly brackets.
# This is hidden black magic that you need to know about to override it.
# It appears to call the method for all of the content within the brackets.
curlyBrackets := method(
    map := Map clone
    call message arguments foreach(arg,
        map doMessage(arg)
    )
    map
)

Map atPutThing := method(
    self atPut(
        call evalArgAt(0) asMutable removePrefix("\"") removeSuffix("\""),
        call evalArgAt(1)
    )
)

the_string := "{
    \"foo\": \"12345\",
    \"bar\": \"7890\"
}"

phoneNumbers := doString(the_string)
phoneNumbers keys println
phoneNumbers values println

# But presumably this will break, because there's no "atPutThing" method
a := 1
b := 5
range :=  a : b
# Yep - "Exception: Number does not respond to ':'"
# So you've got to be careful for reusable operators