Rake, a popular Ruby DSL
Rake, like make or ant, is a DSL for defining tasks.
Tasks definitions above are written using Rake DSL. In particular, they define two dependent tasks. They state that the :world task is dependent from the :hello task. In other words, when the :world task is executed, the :hello task will be executed first. This will result in the string "Hello World!" printed on the console. The neat fact about the code above is that it is perfectly legal ruby code. In particular,
- task is a ruby method that accepts an hash argument
- :hello and :world are ruby symbols
- :hello => :world is a ruby hash
- the do ... end part is a ruby block
Makengo: an internal DSL in Go
When I approached to Go the first time I was intrigued by what is stated in its homepage:
"It feels like a dynamic language but has the speed and safety of a static language. It's a joy to use."
Belonging from years of experience with dynamic languages such as ruby and enjoying its capability to build DSL, I was curious to see how much the compiled and strongly typed nature of Go can be bended in this sense. So, I started writing a small experimental project named makengo.
Using makengo DSL, the previous tasks definitions become:
How does it look compared to the ruby version? First of all, the Go version takes 117 chars against the 75 chars of the Ruby version. So, it's ~56% more verbose. In particular
- There are too many parentheses
- String names are longer than symbol names (:hello vs "hello", :world vs "world")
- The block syntax is burdened by the func keyword
- In order to express the dependency we need the long named DependsOn function rather than the concise key => value hash syntax
Go DSL capabilities
The retrospection on Makengo raises the main question of this post: is Go suitable for building internal DSLs? Let's try answering, exploring Go's DSL capability in more detail.
Closures
Go has many features that help building DSL. The first thing that comes to mind are anonymous functions that act as closures. In makengo, I use anonymous an function to define what a task does.
Also, anonymous functions can take arguments in order to push values in the block. For example:
Compared with C, this a great step towards expressivity. However, compared with Ruby, Go's anonymous functions syntax appears to be a lot more verbose. This is due to the necessity of a func keyword and to the use of many parentheses. Also, considering that since Go is a strongly typed language, anonymous function arguments need their own type declaration.
Method chaining
In Go, types can receive methods. In Makengo, this fact is exploited to express dependencies among tasks. Actually, the Task function returns a task object and task object can receive the DependsOn method allowing for method chaining:
Dynamic reception and metaprogramming
Go lacks of a ruby-like method_missing method. In ruby, when an unknown method is sent to an object the object responds executing method_missing. This language feature is known as Dynamic Reception. Dynamic Reception, combined with the metaprogramming magic of ruby, allows for very readable DSL (taken from Machinist):
Regarding metaprogramming, Go has an interesting reflect package that allows the manipulation of objects with arbitrary types. This comes in handy, for example, in variadic functions (see below).
Literal maps
In Ruby, a literal map could be passed as argument to a function allowing for more expressive function calls inside the DSL:
Moreover, Ruby allows you omit the delimiters for a literal map. So you can shorten it to:
In Go, a literal map looks like this:
but there is no way to shorten it.
Literal lists and varargs
Like maps, literal lists in Go have not optional delimiters so it's not convenient to use them as function arguments inside DSL. BTW, Go has good support for varargs that combined with types reflection, types assertion and interfaces, are good substitutes for literal lists. For example, in Makengo I can define tasks that depend on more than a single task passing multiple arguments to DependsOn:
A comparison table
Let's try summarize in a table what we discussed until this point.
DSL-related features | Go | Ruby |
---|---|---|
Method chaining | Yes | Yes |
Optional delimiters in maps | No | Yes |
Optional delimiters in lists | No but you can use varargs | Yes |
Metaprogramming | Limited | Yes |
Dynamic reception | No | Yes |
Short signature for blocks | No | Yes |
The answer
So what about the answer to the original question? Is Go suitable for building internal DSL? The answer of course is ... it depends!
As a compiled language, Go can't compete with dynamic languages in building complex and general purpose DSL. However, it's enough flexible to build simple DSL. Moreover, as said at the beginning of this post, the mean of expressivity is relative to the problem domain. Go can be very expressive when dealing with problems that involve network and concurrency issues.
Another road to explore is the implementation of a light VM in Go exploiting some of its advantages against C: built-in concurrency and GC. On top of this VM could live a set of dynamic languages more suited to implement external DSLs. It seems that Eleanor McHugh is on the right track with her GoLightly VM.
Go DSL capability need more investigation, of course. But a fact is clear to me: I should not think at Go as a Panacea trying to force its nature: Go it's not a scripting language. I should rather taking advantage of its peculiarities in order to fully exploit all of its expressivity.
| | map[string]string { "world":"hello" }
ReplyDelete|
| but there is no way to shorten it.
package main
import "fmt"
type dp map[string]string
func main() {
fmt.Print( dp{ "hello":"world" } )
}
You'll have to gofmt it as apparently the blogspot comment system is adverse to code.
Thank you Michael. Actually I was wrong, you found a shorter way :) BTW, dp type name doesn't seem so much explicative. I'd rather prefer something like
ReplyDeletedeps{ "hello":"world" }
or
dependson{ "hello":"world" }
But now the problem is: how to build a full task definition using the map type?
What about this approach (look at main):
ReplyDeletehttp://pastie.org/pastes/867451
Really, Go has pretty decent literal syntax for most things, so just using them w/ some helper functions is the right way for pretty much everything, in my experience.
Very nice piece of code @Anonymous, thank you! You proposed another interesting DSL pattern: a sort of type aliasing supported by helper functions. Very instructive. I'd like to update my post adding your example and giving you credits. If it's possible and if you like, get out from anonymity :)
ReplyDeleteAnonymity is preferred, thanks. :)
ReplyDeleteHello! I could have sworn I’ve visited your blog before but after looking at a few of the articles I realized it’s new to me. Nonetheless, I’m definitely happy I stumbled upon it and I’ll be bookmarking KBC Lottery Winner Game 2020 and checking back regularly!
ReplyDeleteI'am very much delighted to say that this blog has helped me a lot in gain some extra knowledge.
ReplyDeleteSelenium Training in chennai | Selenium Training in anna nagar | Selenium Training in omr | Selenium Training in porur | Selenium Training in tambaram | Selenium Training in velachery
Excellent post...! It is very helpful for developing my knowledge and Keep it up...oracle training in chennai
ReplyDeleteI am happy for sharing on this blog its awesome blog I really impressed. thanks for sharing. Youtube Mp3 Converter
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteReach to the best
ReplyDeleteData Science Training institute in Chennai for skyrocketing your career, Infycle Technologies. It is the best Software Training & Placement institutes in and around Chennai. that also gives the best placement training for personality tests, interview preparation, and mock interviews for leveling up the candidate's grades to a professional level.
coin haber - koin haber - kripto para haberleri - coin haber - instagram video indir - instagram takipçi satın al - instagram takipçi satın al - tiktok takipçi satın al - instagram takipçi satın al - instagram takipçi satın al - instagram takipçi satın al - instagram takipçi satın al - instagram takipçi satın al - binance güvenilir mi - binance güvenilir mi - binance güvenilir mi - binance güvenilir mi - instagram beğeni satın al - instagram beğeni satın al - google haritalara yer ekleme - btcturk güvenilir mi - binance hesap açma - kuşadası kiralık villa - tiktok izlenme satın al - instagram takipçi satın al - sms onay - paribu sahibi - binance sahibi - btcturk sahibi - paribu ne zaman kuruldu - binance ne zaman kuruldu - btcturk ne zaman kuruldu - youtube izlenme satın al - torrent oyun - google haritalara yer ekleme - altyapısız internet - bedava internet - no deposit bonus forex - erkek spor ayakkabı - tiktok jeton hilesi - tiktok beğeni satın al - microsoft word indir - misli indir - instagram takipçi satın al
ReplyDeleteThis is a subject which is important to me... Good health! Where are your contact subtleties however? best interiors
ReplyDeleteI think you can make a video for youtube about it and buy many likes for this video from here https://soclikes.com
ReplyDeletemmorpg
ReplyDeleteİnstagram takipci satın al
tiktok jeton hilesi
tiktok jeton hilesi
antalya saç ekimi
İnstagram Takipci Satın Al
instagram takipçi satın al
metin2 pvp serverlar
instagram takipçi satın al
Perde Modelleri
ReplyDeletesms onay
MOBİL ÖDEME BOZDURMA
nft nasıl alınır
ankara evden eve nakliyat
trafik sigortası
dedektör
web sitesi kurma
aşk kitapları
Fantastic blog I have never ever read this type of amazing information. My Chemical Romance Jetstar Jacket
ReplyDeleteIt s a very useful page. Thank you. 800f0ebc1a7f3065946d0c06a0402f9e
ReplyDeletesemdinli
agli
kula
cardak
alacakaya
usak
defne
darende
saruhanli
It s a very useful page. Thank you. aa1eca48ef941a281893ed05ad4459cc
ReplyDeletetaskent
digor
finike
sirnak
karahalli
silivri
muratli
kocaeli
buldan
Congratulations on your article, it was very helpful and successful. 10ea49fbedb33ade53a97e2d86a811dd
ReplyDeletenumara onay
website kurma
sms onay
Thank you for your explanation, very good content. 08fe0889fa2c5228ee886b4501eee63f
ReplyDeletealtın dedektörü
Good content. You write beautiful things.
ReplyDeletevbet
mrbahis
hacklink
sportsbet
taksi
sportsbet
korsan taksi
hacklink
mrbahis
Good text Write good content success. Thank you
ReplyDeleteslot siteleri
tipobet
kibris bahis siteleri
poker siteleri
mobil ödeme bahis
bonus veren siteler
betpark
kralbet
This post is on your page i will follow your new content.
ReplyDeletemrbahis
sportsbetgiris.net
casino siteleri
mrbahis giriş
casino siteleri
betgaranti.online
mrbahis.co
sportsbet
sportsbet giriş
elf bar
ReplyDeletebinance hesap açma
sms onay
DFC
slot siteleri
ReplyDeletekralbet
betpark
tipobet
mobil ödeme bahis
betmatik
kibris bahis siteleri
poker siteleri
bonus veren siteler
Z41UZ
betmatik
ReplyDeletekralbet
betpark
tipobet
slot siteleri
kibris bahis siteleri
poker siteleri
bonus veren siteler
mobil ödeme bahis
F0MMND
This comment has been removed by the author.
ReplyDeletekırşehir
ReplyDeletekarabük
adıyaman
niğde
ordu
S02W
kıbrıs
ReplyDeletetrabzon
zonguldak
mersin
diyarbakır
4UB
salt likit
ReplyDeletesalt likit
O1A0
burdur
ReplyDeletebursa
çanakkale
çankırı
çorum
denizli
diyarbakır
QNJ2RC
web postegro
ReplyDeletetakipcimx 1000
techy hit tools
TFFJDS
شركة تسليك مجاري بجازان cW1WOozrvL
ReplyDeleteشركه مكافحه النمل الابيض بالقصيم j5CsZsEcLc
ReplyDelete