How do I use Smalltalk's built in Parser or Compiler to parse my own messages with optional parameters?

Viewed 78

I'm trying to create a live-coding environment in Smalltalk. The objects I'm using have long complex methods with many parameters for creating new instances. I want to be able to write a very short "command" that just specifies the parameters I'm interested in and provides default values for all the other parameters.

For instance instead of writing something like:

Polyhedron shape: #cube size: 1 rotationSpeed: 5 rotationDirection: 0.707 color: red texture: false

In my live coding environment I want to write:

poly shape: #cube

Some of the arguments could be complex and contain their own messages like:

poly shape: #cube rotationSpeed: ((pot1 max: 0) min: speedLimit)

So rather than just trying to parse the live coding string myself I thought it would be easier if I could use Smalltalk's built in parser or compiler to decode the string and call Polyhedron with the full creation message including default values.

How would I do that?

I've got as far as getting an array of tokens out of the parser but that doesn't identify message parameters and arguments. Before I tried to implement argument parsing myself I figured there's likely to be something in Smalltalk that could give me a list of message parameters and arguments?

1 Answers

It doesn't look like you have to tweak the compiler. To provide default values simply have your objects be born with them. How? In the initialize method:

Polyhedron >> initialize
   super initialize.
   shape := #triangle.
   size := 1.
   rotationSpeed := 5.
   rotationDirection := 0.707.
   color: Color red texture: false

The #initialize message is sent when you send Polyhedron new. Thus, if you want to change the shape, you only need to send

Polyhedron new shape: #cube

Note by the way that it is usually a good idea to send super initialize so to give superclasses a chance to perform their initialization routines.

Note also that Polyhedra is the plural of Polyhedron, and class names are usually in singular.


Addendum


In case you cannot edit the class Polyhedron, you can still reference it and therefore send messages to it. In particular, you can create new instance creation methods, shorter than the ones you already have. Here is how to do this:

   Polyedron compile: 'shape: aSymbol
   ^self
     shape: aSymbol
     size: 1
     rotationSpeed: 5
     rotationDirection: 0.707
     color: Color rd texture: false'

Note that the argument of #compile: is the source code of the method you want to add. By using this new method you will be able to just say

Polyedron shape: #cube

to get what you wanted.

Related