by k__ · 10y ago · 0 comments
I've written a number of Nim libs at this point. Rosencrantz is missing the idiomatic 'feel' of Nim -- blocks and trees. I would rather see a syntax like this:
let handler = firstOf:
get:
firstOf:
path("/api/status"):
ok(getStatus())
pathChunk("/api/message"):
accept("application/json"):
intSegment(id):
let message = getMessageById(id)
ok(message)
post:
path("/api/new-message"):
jsonBody(msg):
let
id = generateId()
saved = saveMessage(id, msg)
if saved: ok(id)
else: complete(Http500, "save failed")
I believe all of that should be possible using templates; grab the AST for the `stmt` passed to each function, then iterate over each node.Templates would allow for the syntax you present, but do not combine.
For example, the 'firstOf' template above would be responsible for scanning the AST it's given, taking each node and putting it in to a sequence. Then it instantiates a Handler with that sequence and returns it.
I agree with the other posters that the multi-line [ ] syntax is not very beautiful or Nim-idiomatic. As @Nycto suggests, nested code blocks would seem more Nim-idiomatic.
Also, I haven't seen anywhere else in Nim stdlib where multi-line [ ] expressions are used. In my mental model of Nim, [ ] is for 4 uses: 1. generics, 2. tuples/subranges, 3. array literals, and 4. array indexing. And none of these scenarios contain nested code blocks inside them.
For nesting of routes I would find nested code blocks most idiomatic. Or, if you find that nested code blocks simply do not work well, the key-value idiom of a table constructor {k:v} seems more idiomatic than [ ]: http://nim-lang.org/docs/manual.html#statements-and-expressi...
If it compiles (I admit I haven't tested it -- this is just off the top of my head), you could perhaps use a syntax something like:
get {
path("/api/status"): ok(getStatus()),
pathChunk("/api/message"): # etc.
}
Since the order of the (key,value)-pairs is preserved, this would automatically handle the ordered composition `h1 ~ h2`.The problem with the syntax you propose is that it does not compose well.
For instance, in the example you give, `path`, `get` and `ok` are all handlers, but they appear in very different roles syntax-wise. It is not clear to me how one would add one more level, say to parse handlers.
I agree that the [] syntax is not the best-looking in the world, but I need something where I can do the equivalent of `h1[h2]`, where `h1` and `h2` are both handlers.
Templates and blocks would sort of work, but not in the case where both `h1` and `h2` are, say, stored in a variable. I am all for trying to obtain a better syntax, but I would not like to lose composability for that