Язык программирования Zonnon Нина Гонова ННГУ ВМК МЛиВА Zonnon Немного истории: почему еще один язык? Verification vs. Model improvements • Mistakes happen in the limits of a system • Improving the model is essential to make verification feasible • The only way to improve the programming model is by developing expressive structured languages It is an alternative way to • Writing code in a lousy model and then overspecifying it in order to apply highly complicated verification techniques C# is a Good Language, but ... • What can be improved? – Concurrency – Composability – Extensibility – Syntax Обзор семейства языков Pascal Programming in-the-Small Algorithms Data Structures Programming in-the-Large Modules OOP Agents ??? 5 Zonnon Project Purposes • Provide a Pascal Family Language for .NET – Suitable for Teaching Algorithms & Data Structures without Object Oriented Corset (+ ‘programming in the large’) • Modern object model that supports concurrency • Support multi-processor and distributed systems • Support inter-operation with other languages and their libraries Zonnon Особенности Zonnon: что интересного? Zonnon concepts: • Compositional OO programming model • Modular programming model • Concurrency • Communication model based on dialogs • Math extensions • Interoperability Zonnon concepts: • Compositional OO programming model • Modular programming model • Concurrency • Communication model based on dialogs • Math extensions • Interoperability No inheritance • Inheritance = Subtyping + Code Reuse – Subtyping implemented with interfaces – Code reuse available through aggregation • Inheritance is of no use Building Blocks & Relations • C# Status Quo – Interfaces – Classes run compile • Zonnon – Definitions – Implementations – Object Types – Modules extends :n implements :n inherits :1 refines :1 implements :1 aggregates :n imports :n Compositional Model Definition Default Implementation Custom Implementation Client ”Facet” Client Client Servant Object as Composition of Facets via Aggregation Abstractions: What is it Primarily? JukeBox: Player or Store? class JukeBox: Player, Store { ... } Truck: Container or Vehicle? class Truck: Vehicle, Container { ... } Computer: Calculator or DataBase or Browser? class Computer: Calculator, DataBase, Browser { ... } Base class Interface Composition Example definition Player; implementation Store; var cur: Song; var rep: Lib.Song; procedure Play (s: Song); procedure Clear; procedure Stop; begin loop := nil end Player. end Clear; procedure Add (s: Song); definition Store; begin s.next := rep; procedure Clear; rep := s procedure Add (s: Song); end Add; end Store. begin Clear end Store. object JukeBox implements Player, Store; import Store; (* aggregate *) procedure Play (s: Song); implements Player.Play; procedure Stop; implements Player.Stop; end JukeBox. Zonnon concepts: • Compositional OO programming model • Modular programming model • Concurrency • Communication model based on dialogs • Math extensions • Interoperability Modules as Structural Units • What is a Module? – A Container for Logically Related Object Types – A Static Object Managed by the System • Loaded on Demand by the Runtime • Why are Modules Important? – Modules Provide a Simple Tool for • Encapsulating Separate Concerns • Static Decomposition of a System – Modules Narrow Down and Make Explicit Mutual Dependences via the IMPORT Relation – Modules Uniform System and Application Levels Zonnon concepts: • Compositional OO programming model • Modular programming model • Concurrency • Communication model based on dialogs • Math extensions • Interoperability Active Object Methods Behavior Initializer Activities OBJECT {PROTECTED} X; VAR c, d: BOOLEAN; PROCEDURE p (u: U); BEGIN … END p; ACTIVITY; VAR … BEGIN … AWAIT cond; END BEGIN t := t0; c := TRUE END X. Mutual exclusion by Reader Writer Lock Separate Thread Precondition of Continuation Hierarchic Activities a[i] = 10, 3, 2 , 5 , 4 , 7 , 8 , 1 , 11 , 6 , 9 , 12 activity Sort (L, R: integer); i = 1, 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 var i, j, t, x: integer; begin { barrier } Sort( 0, 11 ) 10,3, 2 ,5, 4, 7, 8, 1,11, 6, 9,12 i := L; j := R; Sort( 0, 5 ) 10, 3, 2, 5, 4, 7 x := a[(L + R) div 2]; Sort( 0, 1 ) 10, 3 repeat Sort( 2, 5 ) 2, 5, 4, 7 while a[i] < x do i := i + 1 end; while x < a[j] do j := j - 1 end; Sort( 2, 3 ) 2, 5 if i <= j then Sort( 4, 5 ) 4, 7 t := a[i]; a[i] := a[j]; a[j] := t; Sort( 6, 11 ) 8, 1, 11, 6, 9,12 i := i + 1; j := j - 1 Sort( 6, 8 ) 8, 1, 11 end until i > j; Sort( 6, 7 ) 8, 1 if L < j then new Sort(L, j) end; Sort( 9, 11 ) 6, 9,12 if i < R then new Sort(i, R) end Sort( 10, 11 ) 9,12 end Sort; acts as … new Sort (1, N) a barrier Zonnon concepts: • Compositional OO programming model • Modular programming model • Concurrency • Communication model based on dialogs • Math extensions • Interoperability Protocols Protocol Type Q Activity Protocol Type P Dialogues & Protocols Communication protocol defined as formal language in EBNF protocol InP = ( COMING, READY_TO_ACCEPT, TOO_LATE, OK, dialog = { COMING ? READY_TO_ACCEPT ( Truck | TOO_LATE ) } ); Road object Activity Routine dialog Truck is at the end of the road COMING READY_TO ACCEPT If the truck is still there send it Loader object T: Truck When loading of the previous truck is finished send ready View on Application in Zonnon 1 2 3 4 Active link Activity 6 5 8 Module structure the application and introduce clear borders 7 Zonnon concepts: • Compositional OO programming model • Modular programming model • Concurrency • Communication model based on dialogs • Math extensions • Interoperability Математические расширения • Цель – совместить – удобство программирования с использованием MATLAB – концепции объектно-ориентированного программирования – быстроту компилятора Математические расширения • Операции и функции над многомерными матрицами • Многомерные матрицы: специально введенный тип математических массивов array {math} *,* of real • Интервальная и векторная индексация • Источники вдохновения: – MATLAB –R – Fortran Zonnon concepts: • Compositional OO programming model • Modular programming model • Concurrency • Communication model based on dialogs • Math extensions • Interoperability Language Interoperability • Example on using .NET FCL from Zonnon for output to a file: CLR module WriteTextFile; import System, System.IO; Visual type Basic C# SW = System.IO.StreamWriter; CLS var sw : SW; fn : System.String; begin Zonnon fn := "myfile.txt"; sw := new System.IO.StreamWriter( fn, false ); sw.Write( "Text to be written to file“ ); sw.Close( ); end WriteTextFile. Benefits of the approach • Compiler has knowledge about the whole application which opens new opportunities for model validation • Compiler is fully in charge of using middleware - new opportunities for optimization through moving data close to execution and compile time balancing of computation Zonnon Компилятор Zonnon: что внутри? Компиляторы для .NET: возможные подходы • • • • Непосредственная («ручная») компиляция в MSIL/Metadata (нет примеров) или в язык ассемблера MSIL («toy compilers»). Использование «родного» для .NET языка (напр. C#) в качестве промежуточного (Eiffel) Генерация MSIL-кода средствами низкого уровня из пространств имен System.Reflection и System.Reflection.Emit (Component Pascal, авт. John Gough; Oberon.NET) Высокоуровневая поддержка - CCI: построение дерева программы с (полу)автоматической генерацией IL+MD (ASML, Zonnon for .NET). Модель компиляции Zonnon IL/MD Writer Source IR (AST) Scanner & Parser Output Assembly MSIL+MD IL/MD Visitors Reader Imported Assemblies Zonnon-часть: Cпецифична для языка CCI-часть: Общая для всех языков Модель компиляции Zonnon Scanner & Parser Visitors IR (AST) Проекции Zonnon AST Реализуется семантическая специфика Zonnon CCI’s AST Проекции (mappings): отображение специфических свойств Zonnon на семантически эквивалентные структуры .NET Проекции Zonnon->.NET: Definitions & Implementations Zonnon definition D; type e = (a, b); var x: T; procedure f (t:T); procedure g ():T; end D; implementation D; var y: T; procedure f (t: T); begin x := t; y := t end f; end D; C# public interface D { T x { get; set; } void f(T t); T g (); }; public sealed class D_d { private T x_d; public enum e = (a, b); public T x { get { return x_d }; }; public sealed class D_i: D_d { T y; void f(T t) { x_d = t; y = t; } }; Инфраструктура компилятора • Компилятор Zonnon для платформы .NET реализован с использованием библиотеки Common Compiler Infrastructure (CCI). Эта библиотека, концептуально, обеспечивает поддержку для разработки компиляторов для .NET на трех уровнях: – Инфраструктура высокого уровня (в частности структуры для построения деревьев программ и методы для осуществления семантической проверки деревьев) – Поддержка низкого уровня (генерация IL кода и метаданных) – Сервис интеграции с Microsoft Visual Studio Общие принципы использования CCI • • • Все сервисы CCI представлены в виде классов. Чтобы воспользоваться этими сервисами, необходимо определить собственные классы, производные от классов CCI. В производных классах необходимо обеспечить реализацию некоторых абстрактных методов классовпрототипов (они образуют «унифицированный интерфейс» с окружением). Производные классы содержат функциональность, реализующую собственную семантику компилятора. Architecture of CCI Compiler Token Token Token Document Source code Attributes Source context Token context Lexical analysis Program tree Syntax & semantic analysis Object code (Assembly) Code generation Visual Studio Editor Project manager “Intellisense” Debugger 41 Zonnon Демонстрация: на чем еще можно писать приложения в Visual Studio Tools for Zonnon • ETH Zonnon, www.zonnon.ethz.ch – – – – Zonnon Command Line Compiler Zonnon for MSVisual Studio 2008 Zonnon plugin for Eclipse Zonnon builder • 2 Zonnon based educational courses http://www.microsoft.com/Rus/Msdnaa/Curricula/Default.mspx • Examples online – Zonnon webpage (>100 examples, 2 demo projects), – www.AlgLib.net (>250 math. examples) Демонстрация Спасибо за внимание! Вопросы?
© Copyright 2024 Paperzz