Domain Specific Languages Ralf Westphal Student Technology Conference 2005 Domain Specific Languages Ralf Westphal
Domain Specific Languages Ralf Westphal Freier Autor, Berater, Trainer, Entwickler und Associate of thinktecture Microsoft Regional Director & MVP ralfw@ralfw.de
Allgemeine Programmierung General Purpose Languages (GPL) Generic Languages C#, VB.NET, C, C++, Java, Modula-2, Ada usw. Meist imperative Programmierung „Turing Complete“ Fallunterscheidungen Schleifen/Sprünge IO Datentypen/Speicherzugriff Keiner Problemdomäne (z.B. Finanzwesen, Betriebssysteme, UI) zugeordnet Lösungen für alle möglichen Probleme lassen sich „irgendwie“ formulieren
Beispiel Suchen: GPL VB.NET Code Nutzung Suche „ab“ oder „ac“ in einem String. Private Function Match(ByVal input As String) As Boolean Dim iA As Integer = -1 Do iA = input.IndexOf("a", iA + 1) If iA < 0 Then Return False If iA < input.Length - 1 Then Dim nextChar As Char nextChar = input.Chars(iA + 1) If nextChar = "b" Or nextChar = "c" Then Return True End If Loop End Function Nutzung If Match(t) Then ...
What is a Domain? Real-Time Business Systems Systems Requirements Aircraft control systems Airline Baggage Handling Systems Insurance Management Systems Specification Implementation Deployment
What is a Language? Declarative Textual Pictorial Procedural ¶C(x) h2 ¶ 2C(x) ¶ t 2m ¶ x2 ih = – a>b && c==d jo biscuits 24 green pat cakes 32 pink <CallRecord> <caller><number>07713248</number> Employee name address promote Job description pay assign 0..* Textual Pictorial call Call Record call length base rate: £/s store class Magnox : NuclearPowerStation { public void dropRods () Procedural
Spezielle Programmierung Domain Specific Languages (DSL) Einer Problemdomäne zugeordnet Verringerung der semantischen Distanz zwischen Problem und Programm Es soll bewusst nicht alles möglich sein Oft auch: Little Languages, Mini Languages Horizontal: SQL, Reg Ex, XSLT, HTML Vertikal: EBNF, lex/yacc, Call/C, Frob, LexiFi, Postscript, Tex, VHDL Oft deklarativ Oft nicht „Turing complete“ Frob: Functional ROBotics, Sprache zur Steuerung von Robotern, http://www.cs.jhu.edu/CIRL/publications/pdf/isrr_springer.pdf Call/C: Sprache zur Entwicklung von Telephony-Anwendungen, http://www.brics.dk/~brabrand/callc.pdf LexiFi: Modellierung von Financial Products, http://www.lexifi.com/ VHDL: Beschreibung von elektronischen Schaltungen, http://www.acc-eda.com/vhdlref/index.html
Beispiel Suchen: DSL Reg Ex Code a(b|c) Nutzung If RegEx.Match(t, "a(b|c)").Success Then ...
DSLs machen Probleme „überschaubar“ Ziel von DSL ist die Artefaktgenerierung! Höhere Produktivität Weniger Zeilen Code Deklarativ statt imperativ Bessere Wartbarkeit Höhere Transparenz, bessere Lesbarkeit Modularisierung Code Reuse Höhere Sicherheit „Sandbox“ Involvierung von Domänenexperten Hohe Ausdrucksfähigkeit, Vokabular der Domäne steht zur Verfügung Leichte Erlernbarkeit
Primzahlenermittlung ist “überschaubar”… …wenn wir ein System haben, dass… multiplizieren und dividieren und Dinge wiederholt tun kann _*_ _/_ _%_ while (…) {…} Von Neumann computer with conventional CPU C, Pascal, Fortran,… language: platform:
Teilelisten ermitteln ist “überschaubar”… …wenn wir ein System haben, dass… Lange Listen speichern und schnell traviersieren kann Listen filtern und kombinieren kann JOIN … … WHERE … CREATE … SELECT … SQL platform: language: Relational Database
GUI-Entwicklung ist “überschaubar”… …wenn wir ein Systen haben, dass… Fenster und Controls anzeigen kann und Strukturen interaktiv modifizierbar macht language: platform: Visual programming languages Interactive app platform
Telefonabrechnungssysteme sind “überschaubar”… …wenn wir eine language dafür haben… …und eine runtime platform call calendar month Call Record call length base rate: £/s friend discount rate: £/s store friends calls other calls - bill billing period Telephone Billing Scheme Phone Billing Engine
Mit einer DSL arbeiten customer -facing developer customer tablet PC prospect initiated prospective sale empty overflow Sat weekly accumulator 4 £20 1 week delay £30 cancels salesperson’s account 31 monthly bank a/c pay 7 £ animator prototype for review customer tablet PC generator phone bill system customer -facing developer Here’s part of how we envisage a domain specific language being used. (This is a big topic! In fact, DSLs are just part of the Software Factory story. See the book by Jack Greenfield and Keith Short.) Firstly, DSLs enable us to develop some of our system with the customer. The DSL is based on notations they use within their branch of engineering or business. The customer-facing developer – what we might have called an analyst in the past – has the role of gathering the customers’ requirements statements, ensuring the customers understand their consequences, and making a consistent story out of them. We now provide this developer with an extra tool: one that helps express some aspects of the requirements and a high-level design. [click] One of the analyst/developer’s tools could be an animator that takes the model and runs a simulation or prototype – the best form for this would depend on the domain. This takes the development process rapidly round the requirements development loop, so that the customers gain a clear idea of what they will get, at an early stage. [click] One of the advantages of restricting our language to a particular domain is that it’s easier (than with general purpose specification languages) to generate executable code from a pure requirements statement. This is because there are well-understood implementation patterns within the domain. Consider for example SQL, a language specific to the horizontal domain of database management. Writers of SQL have to understand what the database does, but need know nothing of how the DBMS works internally. The language just expresses the semantics of a database query, but there’s no problem in executing it. [click] In general, a generator (or interpreter) is taking the DSL statement and using it to parameterise a generic implementation. So we could imagine that our phone-bill-software company develops its generator by generalizing one of its pre-existing billing systems. But one of the differences between long-established horizontal DSLs and the kind of in-house DSL that we envisage, is that the latter is unlikely ever to reach a point of being finalized: as the company’s market shifts, so must the language and its implementations. So we’re unlikely ever to produce a complete phone bill system just by pressing the button in the evening after the models have been drawn with the customer. Rather than tweak the end-result of generation, however, we should always tweak the generators themselves. That way, we avoid having to re-tweak every time the model is adjusted; and we stand some chance of generalising our tweaks to improve the generator for future uses. If you already have an existing system that is parameterised with a configuration file, then it’s not difficult to imagine a generator creating the config file from a model. tweak hack
DSL-Output list of parts business plan prototype for review animator prospect initiated prospective sale empty overflow Sat weekly accumulator 4 £20 1 week delay £30 cancels salesperson’s account 31 monthly bank a/c pay 7 £ generator list of parts generator business plan prototype for review animator generator phone bill system [click] We don’t just have to generate single files here of course. All sorts of configuration files etc can be created from the same model. And we’re not just talking about software of course: [click] Lists of hardware parts for the installation … [click] An intranet website for your customer telling their employees how they’re going to migrate to the new system … C# XML C#, Java SQL mixed code and config files
“Mind The Gap” – Von der Abstraktion zum Code Application Code Model Platform Frameworks Generated (a) Model Application Code Domain Specific Framework Platform Frameworks Generated Code Pattern Language (c) Platform Frameworks Application Code Model Generated Code (d) Model Application Code Platform Frameworks Generated Code (b) CASE b)Low-level abstractions – Together Class Diagram c)Good Framework – windows GUI C++ programming vs VisualBasic d)DSL
Microsofts DSL Tools für VS2005
DSL Definition in VS2005 Domain Model Designer Definition Abbildung einer Problemdomäne in ein Klassenmodell Verknüpfung von Konzepten über Beziehungen inkl. Nebenbedingungen Beschreibung mittels Designer Designer Definition Visualisierung des Domain Model Wie sollen Konzepte dargestellt werden? Wie sollen Beziehungen dargestellt werden? Beschreibung mittels XML Dokument Artifact Generator Template basiert Übersetzt Instanzierung des Domain Models in „Code“ Microsofts DSLs sind immer visuell!
Domain Model Designer
DSL-Programmierung
Microsoft DSLs I Application Designer
Microsoft DSLs II System Designer
Microsoft DSLs III Logical Datacenter Designer
Microsoft DSLs IV Deployment Designer
Microsoft DSLs V Class Designer
War das alles? Microsoft unterstützt textuelle DSL z.Z. nur schlecht DSL Tools fokussieren auf visuelle DSLs VSIP Babel ist umständlich zu nutzen C++ bzw. COM-basiert Schlechte Dokumentation Unterstützt nur Lex/Yacc bzw. Bison Common Compiler Infrastructure (CCI) nur für den akademischen Bereich verfügbar VS200x Add-Ins bieten einen alternativen Einstieg DSL-Code = textueller Project Item Gemischtsprachige Entwicklung möglich Add-In implementiert Übersetzer Übersetzung autom. oder durch Benutzer angestoßen Ergebnis der Übersetzung steht im Projekt sofort zur Verfügung Fehlermeldungen in Task Pane möglich Allerdings… Kein Syntax Highlighting Kein Intellisense in DSL-Code Ausnahme: XML-basierte DSL
Beispiel einer textuellen DSL Kapselung von SQL Anweisungen XML-basiert, horizontal Deklarativ Codeerzeugung mit Templates Eigene Grammatik, horizontal Codeerzeugung durch Compiler-Compiler erzeugten Übersetzer mit Zwischensprache „Pipelining“
Architektur der Beispiel-DSL CodeSmith adc.sqlobjects.compiler Xml.SqlObjects.Compiler <sqlobjects name="…"> <sqlobjects name="…"> Cocor.SqlObjects.Compiler sqlobjects … … end sqlobjects adc.sqlobjects.compiler.cocor SqlObjectsPreCompiler sqlobjects … … end sqlobjects adcSqlObjectsAddIn Connect Scanner Parser adc.compiler.shared ACompiler CompilerResult sqlobjectsgrammar.ATG Coco/R
Fazit DSLs sind nicht nur cool, sondern hilfreich Codereduktion Modularisierung Horizontal & vertikal DSLs sind nicht so schwer zu implementieren, wie allgemein angenommen DSL Tools unterstützen graphische Sprachen mit enger Integration in VS2005 XML oder Coco/R bieten Tools für die Analyse von DSL-Quelltext CodeSmith bietet Unterstützung bei der Codeerzeugung DSLs können schon heute in VS.NET integriert werden!
Questions and Answers ? ? ? ? ?
Ressourcen DSL Compilerbau/Codegenerierung VS2003 Integration Microsoft DSL Tools, http://lab.msdn.microsoft.com/teamsystem/workshop/dsltools/ Wikipedia, Domain Specific Language, http://c2.com/cgi/wiki?DomainSpecificLanguage Wikipedia, Turing Complete, http://c2.com/cgi/wiki?TuringComplete Paul Klint et al., Domain-Specific Languages: An Annotated Bibliography, http://homepages.cwi.nl/~arie/papers/dslbib/ Diomidis Spinellis, Notable Design Patterns for Domain-Specific Languages, http://www.dmst.aueb.gr/dds/pubs/jrnl/2000-JSS-DSLPatterns/html/dslpat.html Eric Steven Raymond, Designing Minilanguages in: The Art of Unix Programming, http://www.faqs.org/docs/artu/ Compilerbau/Codegenerierung Pat Terry, Comiling with C# and Java, Addison-Wesley 2005 (setzt Coco/R ein) Kathleen Dollard, Code Generation in Microsoft .NET, apress 2004 Edward G. Nigles, Build Your Own .NET Language and Compiler, apress 2004 Codesmith, http://www.codesmithtools.com/ Coco/R, http://www.ssw.uni-linz.ac.at/Research/Projects/Coco/ http://www.codegeneration.net/ VS2003 Integration Les Smith, Writing Add-ins for Visual Studio .NET, apress 2002 Quellen für Teile des Vortrags Joel Semeniuk, Visual Studio Team System – Feature Roundup, Microsoft, http://download.microsoft.com/documents/uk/partner/events/presentations/downloads/2005-03-08/business1-vsts-feature-roundup.ppt José António Silva, DSL Tools in Visual Studio, Microsoft, http://labnet.cc.isel.ipl.pt/docs/Eventos/6-04-2005/20050405%20DSL%20Tools%20VS2005%20joseas%20ISEL.ppt
Über den Referenten Ralf Westphal (www.ralfw.de) ist freier Softwaretechnologievermittler. Er arbeitet als Fachautor, Coach/Berater, Softwareentwickler und Sprecher auf Entwickler-Events im In- und Ausland wie dem Microsoft Technical Summit, Microsoft DevDays, ADC, BASTA!, COMDEX oder SD West. Der Schwerpunkt seiner Arbeit liegt bei der Vermittlung und Anwendung moderner Softwaretechnologien und -konzepte im Zusammenhang mit dem .NET Framework. Darüber hinaus ist Ralf Westphal einer der unabhängigen deutschen Microsoft Regional Directors, Produzent von .NET TV (www.dotnettv.de), Associate der ersten Stunde bei thinktecture (www.thinktecture.com) und zusammen mit Christian Weyer einer der .NET Twins (www.dotnettwins.de). Email: ralfw@ralfw.de www.thinktecture.com
Publikationen Bücher In Fachzeitschriften Video .NET kompakt, Spektrum Akademischer Verlag 2002, ISBN 3827411858 ADO.NET Datenbankprogrammierung, Addison-Wesley 2002, ISBN 3827319978 Jetzt lerne ich ADO.NET, Markt+Technik, 2003, ISBN 3827262291 (zusammen mit Christian Weyer) Video www.dotnettv.de tv.dotnetpro.de