Sugar

Ingvar von Schoultz ingvar-v-s at comhem.se
Wed Aug 27 12:10:15 PDT 2008


The following would let people create syntax sugar for their
favorite paradigms.

Suppose we want the word |Constructor| to become a syntax-sugar
keyword. We inform the compiler at the top of the scope:

     use sugar Constructor;

We define |Constructor| as a function:

     sugar function Constructor (...)
     {   ...
     }

Now we can use |Constructor| as a keyword:

     Constructor Example (...)
     {   ...
     }

This has become syntax sugar for creating a new function named
Example() and passing it to the above function Constructor():

     const Example = Constructor
     (   function Example (...)
         {   ...
         }
     );

Sugar keywords are also intended for expression constructs:

     use sugar func;
     ...
     x = func (...) {...}

This desugars to:

     x = func (function (...) {...})

In this case the name for the new function is optional. The sugar
function can of course do whatever it wants with the new function,
including calling it.

We can combine several sugar keywords:

     use sugar frozen, Constructor, inherits;
     ...
     frozen Constructor Child (...)
     inherits new Parent (...)
     {   ...
     }

This desugars to:

     const Child = Constructor
     (   frozen(),
         function Child (...)
         {   ...
         },
         inherits (new Parent (...))
     );

However, the desugaring shown here is inefficient, and I've chosen
it for its simplicity, a real desugaring will be different. Here,
frozen() and inherits() return objects that Constructor() recognizes
and acts on.

If the parser needs stable rules that don't depend on the meaning of
individual keywords, it can look for the first "(", "{" or ";". Then,
if the preceding identifier is a sugar keyword, an anonymous function
is created, otherwise this identifier becomes the name of the newly
created function.

The nearest sugar keyword before that first "(", "{" or ";" becomes
the main, enclosing sugar-function call.

All sugar keywords are called as functions. Anything else, like
|new  Parent (...)| above, is an expression whose value becomes
an argument to the nearest preceding sugar function.

-- 
Ingvar von Schoultz



More information about the Es-discuss mailing list