开发者

How does an interpreter use a DSL?

I'm using an interpreter for my domain specific language rather than a compiler (despite the performance). I'm struggling to understand some of the concepts though:

Suppose I have a DSL (in XML style) for a game so that developers can make building objects easily:

<building>
  <name> hotel </name>
  <capacity> 10 </capacity> 
</building>

The DSL script is parsed, then what happens?

Does it execute an existing method for creating a new building? As I understand it does not simply transform the DSL into a lower level language (as this would then need to be co开发者_如何学运维mpiled).

Could someone please describe what an interpreter would do with the resulting parsed tree?

Thank you for your help.


Much depends on your specific application details. For example, are name and capacity required? I'm going to give a fairly generic answer, which might be a bit overkill.

Assumptions:

  1. All nested properties are optional
  2. There are many nested properties, possibly of varying depth

This invites 2 ideas: structuring your interpreter as a recursive descent parser and using some sort of builder for your objects. In your specific example, you'd have a BuildingBuilder that looks something like (in Java):

public class BuildingBuilder {
  public BuildingBuilder() { ... }
  public BuildingBuilder setName(String name) { ... return this; }
  public BuildingBuilder setCapacity(int capacity) { ... return this; }
  ...
  public Building build() { ... }
}

Now, when your parser encounters a building element, use the BuildingBuilder to build a building. Then add that object to whatever context the DSL applies to (city.addBuilding(building)).

Note that if the name and capacity are exhaustive and are always required, you can just create a building by passing the two parameters directly. You can also construct the building and set the properties directly as encountered instead of using the builder (the Builder Pattern is nice when you have many properties and said properties are both immutable and optional).

If this is in a non-object-oriented context, you'll end up implementing some sort of buildBuilding function that takes the current context and the inner xml of the building element. Effectively, you are building a recursive descent parser by hand with an xml library providing the actual parsing of individual elements.

However you implement it, you will probably appreciate having a direct semantic mapping between xml elements in your DSL and methods/objects in your interpreter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜