How does an interpreter use a DSL? - parsing

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 compiled).
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:
All nested properties are optional
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.

Related

Create object from Map - Dart

I have a class with a large number of properties that map to some JSON data I've parsed into a Map object elsewhere. I'd like to be able to instantiate a class by passing in this map:
class Card {
String name, layout, mana_cost, cmc, type, rarity, text, flavor, artist,
number, power, toughness, loyalty, watermark, border,
timeshifted, hand, life, release_date, starter, original_text, original_type,
source, image_url, set, set_name, id;
int multiverse_id;
List<String> colors, names, supertypes, subtypes, types, printings, variations, legalities;
List<Map> foreign_names, rulings;
// This doesn't work
Card.fromMap(Map card) {
for (var key in card.keys) {
this[key] = card[key];
}
}
}
I'd prefer to not have to assign everything manually. Is there a way to do what I'm trying to do?
I don't think there is a good way to do it in the language itself.
Reflection would be one approach but it's good practice to avoid it in the browser because it can cause code bloat.
There is the reflectable package that limits the negative size impact of reflection and provides almost the same capabilities.
I'd use the code generation approach, where you use tools like build, source_gen to generate the code that assigns the values.
built_value is a package that uses that approach. This might even work directly for your use case.

Using Dart as a DSL

I am trying to use Dart to tersely define entities in an application, following the idiom of code = configuration. Since I will be defining many entities, I'd like to keep the code as trim and concise and readable as possible.
In an effort to keep boilerplate as close to 0 lines as possible, I recently wrote some code like this:
// man.dart
part of entity_component_framework;
var _man = entity('man', (entityBuilder) {
entityBuilder.add([TopHat, CrookedTeeth]);
})
// test.dart
part of entity_component_framework;
var man = EntityBuilder.entities['man']; // null, since _man wasn't ever accessed.
The entity method associates the entityBuilder passed into the function with a name ('man' in this case). var _man exists because only variable assignments can be top-level in Dart. This seems to be the most concise way possible to use Dart as a DSL.
One thing I wasn't counting on, though, is lazy initialization. If I never access _man -- and I had no intention to, since the entity function neatly stored all the relevant information I required in another data structure -- then the entity function is never run. This is a feature, not a bug.
So, what's the cleanest way of using Dart as a DSL given the lazy initialization restriction?
So, as you point out, it's a feature that Dart doesn't run any code until it's told to. So if you want something to happen, you need to do it in code that runs. Some possibilities
Put your calls to entity() inside the main() function. I assume you don't want to do that, and probably that you want people to be able to add more of these in additional files without modifying the originals.
If you're willing to incur the overhead of mirrors, which is probably not that much if they're confined to this library, use them to find all the top-level variables in that library and access them. Or define them as functions or getters. But I assume that you like the property that variables are automatically one-shot. You'd want to use a MirrorsUsed annotation.
A variation on that would be to use annotations to mark the things you want to be initialized. Though this is similar in that you'd have to iterate over the annotated things, which I think would also require mirrors.

Binding nested complex objects with KSOAP2 Android

I'm trying to bind a XML response from a WS to a set of POJO's classes using ksoap2-android.
A lot of examples on the internet treat very simple responses like this one.
In my case however, I have a lot of custom classes and they keep a reference of each other, sometimes even inside an arraylist.
Here's what i'm trying to do, i would like to bind this kind of response :
<Car number="35">
<Engine>
[...]
</Engine>
<Passenger id="1">
[...]
</Passenger>
<Passenger id="2">
[...]
</Passenger>
</Car>
To this kind of class :
public class Car {
private int number;
private Engine engine;
private ArrayList<Passenger> passengers;
}
With, if possible, only modifying POJOs files (the Simple XML annotations system is very elegant, too bad there's no equivalent to this in ksoap).
I looked into the KVMSerializable interface, but when I try to override the getPropertyInfo() method, I have no idea of what I should return in the PropertyInfo.type and how will ksoap handle ArrayLists.
I got a huge headache right now, please help me
Please go to the below URL and read it.
http://www.c-sharpcorner.com/UploadFile/88b6e5/how-to-call-web-service-in-android-using-soap/
Thanks
Ashok Parmar
Traction Software Co.
You should read the document from ksoap 2, they have many useful examples in there.
For getting an array of complex type, you can check here
And I have used this approach to parse a complex object.
If all of them not work, you have to map field by field from soap object to your pojo.
Updated:
Thanks a lot for the 3rd link, it's very useful and I'm now able to
map custom objects. However, in the wiki page you provided, the author
is parsing an array of custom classes, wrapped in a parent element. Is
there a way to do this with inline lists like in my example ?
I have never tried it before, but I think you can combine my answer and the wiki.
First, you can try an example from wiki to implement your passengers list (extends Vector). Then you can use my approach to create a complex object with arraylist inside. The important thing is you must register your object with the response from web service. Something like this:
public class PassengerVector extends Vector<Passenger> implements KvmSerializable {
}
envelope.addMapping(NAMESPACE, "Car", Car.class);
envelope.addMapping(NAMESPACE, "Passenger", PassengerVector.class);
But I'm not sure this way can work. For a very complex object like your example, I recommend you should get data field by field by its name, as like the wiki

Dynamic method definition with GroovyDSL in IntelliJ

I was trying to define a dynamic method using the GroovyDSL scripting capabilities in IntelliJ. The starting guide "Scripting IDE for DSL awareness" gives you a good idea on how to get started with this. The dynamic method definition in my DSL is more complex than the example though and I am not quite sure how to build this. You can imagine it working like dynamic finder methods in Grails except that you can combine an arbitrary number of criteria with a boolean And keyword in any order. All keywords are not defined in the class that I am invoking the method on but could be defined in the GDSL file. The method always starts with submitTransactionWith. Here's an example:
clientDSL.submitTransactionWithCriteria1AndCriteria2AndCriteria3(arg1, arg2, arg3)
I started out with this but that only works for one criteria and doesn't take into account that you can combined multiple criteria in any order.
def ctx = context(ctype: "my.client.ClientDSL")
contributor(ctx) {
['Criteria1', 'Criteria2', 'Criteria3'].each {
method name: "submitTransactionWith${it}",
type: 'java.util.Map',
params: [args: 'java.util.Collection']
}
}
I was wondering if there's special support for that kind of dynamic method. I'd also be interested in how the DSL for Grails is modeled internally in IntelliJ.
The Grails DSL in located in ${idea.home}/plugins/GrailsGriffon/lib/standardDsls
It would probably help you for your problem. They create string arrays of all the method name combinations ahead of time, and then just iterate through them in their contributor creating a method using the arrays of strings for names.

F# mutual recursion between modules

For recursion in F#, existing documentation is clear about how to do it in the special case where it's just one function calling itself, or a group of physically adjacent functions calling each other.
But in the general case where a group of functions in different modules need to call each other, how do you do it?
I don't think there is a way to achieve this in F#. It is usually possible to structure the application in a way that doesn't require this, so perhaps if you described your scenario, you may get some useful comments.
Anyway, there are various ways to workaround the issue - you can declare a record or an interface to hold the functions that you need to export from the module. Interfaces allow you to export polymorphic functions too, so they are probably a better choice:
// Before the declaration of modules
type Module1Funcs =
abstract Foo : int -> int
type Module2Funcs =
abstract Bar : int -> int
The modules can then export a value that implements one of the interfaces and functions that require the other module can take it as an argument (or you can store it in a mutable value).
module Module1 =
// Import functions from Module2 (needs to be initialized before using!)
let mutable module2 = Unchecked.defaultof<Module2Funcs>
// Sample function that references Module2
let foo a = module2.Bar(a)
// Export functions of the module
let impl =
{ new Module1Funcs with
member x.Foo(a) = foo a }
// Somewhere in the main function
Module1.module2 <- Module2.impl
Module2.module1 <- Module1.impl
The initializationcould be also done automatically using Reflection, but that's a bit ugly, however if you really need it frequently, I could imagine developing some reusable library for this.
In many cases, this feels a bit ugly and restructuring the application to avoid recursive references is a better approach (in fact, I find recursive references between classes in object-oriented programming often quite confusing). However, if you really need something like this, then exporting functions using interfaces/records is probably the only option.
This is not supported. One evidence is that, in visual stuido, you need to order the project files correctly for F#.
It would be really rare to recursively call two functions in two different modules.
If this case does happen, you'd better factor the common part of the two functions out.
I don't think that there's any way for functions in different modules to directly refer to functions in other modules. Is there a reason that functions whose behavior is so tightly intertwined need to be in separate modules?
If you need to keep them separated, one possible workaround is to make your functions higher order so that they take a parameter representing the recursive call, so that you can manually "tie the knot" later.
If you were talking about C#, and methods in two different assemblies needed to mutually recursively call each other, I'd pull out the type signatures they both needed to know into a third, shared, assembly. I don't know however how well those concepts map to F#.
Definetely solution here would use module signatures. A signature file contains information about the public signatures of a set of F# program elements, such as types, namespaces, and modules.
For each F# code file, you can have a signature file, which is a file that has the same name as the code file but with the extension .fsi instead of .fs.

Resources