Скачать презентацию
Идет загрузка презентации. Пожалуйста, подождите
Презентация была опубликована 11 лет назад пользователемwww.itlab.unn.ru
1 Нина Гонова ННГУ ВМК МЛиВА
2 Zonnon Немного истории: почему еще один язык?
3 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 over- specifying it in order to apply highly complicated verification techniques
4 C# is a Good Language, but... What can be improved? – Concurrency – Composability – Extensibility – Syntax
5 Обзор семейства языков Pascal 5 Algorithms Data Structures Modules OOP Agents ??? Algol Pascal Modula-2 Oberon Active Oberon Zonnon Programming in-the-Large Programming in-the-Small
6 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
7 Особенности Zonnon: что интересного? Zonnon
8 Zonnon concepts: Inclusion of both modular and OO programming model Compositional OO model (in opposite to single inheritance class tree) Advanced abstract data types including mathematical structure types Matlab-like notation in combination with efficiency of compiled code Clean integration of concurrency and OOP in the form of active objects Uniform and generalized communication model based on dialogs (subsuming both synchronous and asynchronous method calls)
9 Zonnon concepts: Compositional OO programming model Modular programming model Concurrency Communication model based on dialogs Math extensions Interoperability
10 Zonnon concepts: Compositional OO programming model Modular programming model Concurrency Communication model based on dialogs Math extensions Interoperability
11 No inheritance Inheritance = Subtyping + Code Reuse – Subtyping implemented with interfaces – Code reuse available through aggregation Inheritance is of no use
12 Building Blocks & Relations C# Status Quo – Interfaces – Classes Zonnon – Definitions – Implementations – Object Types – Modules extends implements inherits implements aggregates refines :n :1 :n run compile imports :n
13 Compositional Model Client Servant Object as Composition of Facets via Aggregation Definition Default Implementation Custom Implementation Facet
14 Composition Example definition Vehicle; var speed: real; end Vehicle; definition Container; var capacity: real; load: real; end Container; type Truck = object implements Vehicle, Container
15 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
16 Composition Example definition Store; procedure Clear; procedure Add (s: Song); end Store. implementation Store; var rep: Lib.Song; procedure Clear; begin loop := nil end Clear; procedure Add (s: Song); begins.next := rep; rep := s end Add; begin Clear end Store. definition Player; var cur: Song; procedure Play (s: Song); procedure Stop; end Player. object JukeBox implements Player, Store; import Store; (* aggregate *) procedure Play (s: Song); implements Player.Play; procedure Stop; implements Player.Stop; end JukeBox.
17 Zonnon concepts: Compositional OO programming model Modular programming model Concurrency Communication model based on dialogs Math extensions Interoperability
18 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
19 Zonnon concepts: Compositional OO programming model Modular programming model Concurrency Communication model based on dialogs Math extensions Interoperability
20 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. Methods Behavior Initializer Active Object Mutual exclusion by Reader - Writer Lock Separate Thread Precondition of Continuation
21 Hierarchic Activities activity Sort (L, R: integer); var i, j, t, x: integer; begin { barrier } i := L; j := R; x := a[(L + R) div 2]; repeat while a[i] < x do i := i + 1 end; while x < a[j] do j := j - 1 end; if i j; if L < j then new Sort(L, j) end; if i < R then new Sort(i, R) end end Sort; … new Sort (1, N) acts as a barrier a[i] = 10, 3, 2, 5, 4, 7, 8, 1, 11, 6, 9, 12 i = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 Sort( 0, 11 ) 10,3, 2,5, 4, 7, 8, 1,11, 6, 9,12 Sort( 0, 5 ) 10, 3, 2, 5, 4, 7 Sort( 6, 11 ) 8, 1, 11, 6, 9,12 Sort( 0, 1 ) 10, 3 Sort( 2, 5 ) 2, 5, 4, 7 Sort( 2, 3 ) 2, 5 Sort( 4, 5 ) 4, 7 Sort( 6, 8 ) 8, 1, 11 Sort( 9, 11 ) 6, 9,12 Sort( 10, 11 ) 9,12 Sort( 6, 7 ) 8, 1
22 Zonnon concepts: Compositional OO programming model Modular programming model Concurrency Communication model based on dialogs Math extensions Interoperability
23 Protocols Communication Controlled by Syntax P Another Communication Controlled by Syntax P Protocol Type P Protocol Type Q Communication controlled by syntax Q Activity
24 Dialogues & Protocols Communication protocol defined as formal language in EBNF Routine dialog Activity Loader object Road object COMING READY_TO ACCEPT T: Truck Truck is at the end of the road When loading of the previous truck is finished send ready If the truck is still there send it protocol InP = ( COMING, READY_TO_ACCEPT, TOO_LATE, OK, dialog = { COMING ? READY_TO_ACCEPT ( Truck | TOO_LATE ) } );
25 Example: Electronic Ticketing TicketingService = CheckPrice Destination [ TicketType ] Price | BuyTicket Destination [ TicketType ] AccountID TicketID. Destination = CharString. TicketType = (full | reduced) [twoway]. Price = Number. AccountID = CharString : CharString. CharString. TicketID = CharString. CharString.
26 View on Application in Zonnon Activity Active link Module structure the application and introduce clear borders
27 Client-server metaphor Arbitrary topology (network) of objects activities which interact according to formalised dialogs Dynamically scheduled by the system based on validity of await preconditions send, receive and accept, return dialog elements Dialog Active object Activity
28 Zonnon concepts: Compositional OO programming model Modular programming model Concurrency Communication model based on dialogs Math extensions Interoperability
29 Математические расширения Цель – совместить – удобство программирования с использованием MATLAB – концепции объектно-ориентированного программирования – быстроту компилятора
30 Математические расширения Операции и функции над многомерными матрицами Многомерные матрицы: специально введенный тип математических массивов array {math} *,* of real Интервальная и векторная индексация Источники вдохновения: – MATLAB – R – Fortran
31 Zonnon concepts: Compositional OO programming model Modular programming model Concurrency Communication model based on dialogs Math extensions Interoperability
32 Language Interoperability Example on using.NET FCL from Zonnon for output to a file: module WriteTextFile; import System, System.IO; type SW = System.IO.StreamWriter; var sw : SW; fn : System.String; begin fn := "myfile.txt"; sw := new System.IO.StreamWriter( fn, false ); sw.Write( "Text to be written to file ); sw.Close( ); end WriteTextFile. CLS C# Visual Basic Zonnon CLR
33 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
34 Компилятор Zonnon: что внутри? Zonnon
35 Компиляторы для.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).
36 Модель компиляции Zonnon Zonnon-часть: Cпецифична для языка IR (AST) Source Scanner & Parser Visitors CCI-часть: Общая для всех языков Imported Assemblies MSIL+MD Output Assembly IL/MD Reader IL/MD Writer
37 IR (AST) Zonnon AST CCIs AST Scanner & Parser Visitors Реализуется семантическая специфика Zonnon Проекции (mappings): отображение специфических свойств Zonnon на семантически эквивалентные структуры.NET Модель компиляции Zonnon Проекции
38 definition D; type e = (a, b); var x: T; procedure f (t:T); procedure g ():T; end D; public interface D { T x { get; set; } void f(T t); T g (); }; C# implementation D; var y: T; procedure f (t: T); begin x := t; y := t end f; end D; public sealed class D_i: D_d { T y; void f(T t) { x_d = t; y = t; } }; public sealed class D_d { private T x_d; public enum e = (a, b); public T x { get { return x_d }; }; Проекции Zonnon->.NET: Definitions & Implementations Zonnon
39 Инфраструктура компилятора Компилятор Zonnon для платформы.NET реализован с использованием библиотеки Common Compiler Infrastructure (CCI). Эта библиотека, концептуально, обеспечивает поддержку для разработки компиляторов для.NET на трех уровнях: – Инфраструктура высокого уровня (в частности структуры для построения деревьев программ и методы для осуществления семантической проверки деревьев) – Поддержка низкого уровня (генерация IL кода и метаданных) – Сервис интеграции с Microsoft Visual Studio
40 Общие принципы использования CCI Все сервисы CCI представлены в виде классов. Чтобы воспользоваться этими сервисами, необходимо определить собственные классы, производные от классов CCI. В производных классах необходимо обеспечить реализацию некоторых абстрактных методов классов- прототипов (они образуют «унифицированный интерфейс» с окружением). Производные классы содержат функциональность, реализующую собственную семантику компилятора.
41 Architecture of CCI Compiler 41 Lexical analysis Syntax & semantic analysis Code generation Visual Studio Document Source code Source context Token Attributes Token context Program tree Object code (Assembly) Editor Debugger Project manager Intellisense
42 Компилятор Zonnon В целом компилятор организован довольно традиционно: сканер трансформирует исходный текст в последовательность лексем, которые принимаются синтаксическим анализатором. Далее строится Zonnon-ориентированное программное дерево, которое затем трансформируется в дерево с узлами, представляющими собой сущность класса промежуточного представления CCI. Конечным результатом трансформаций является сборка.NET. Отображение математических расширений в.NET происходит во время конвертации дерева Zonnon в дерево CCI. Исходный код Zonnon front-end Zonnon back-end Дерево Zonnon Дерево CCI MSIL + MD
43 Отображение в.NET Для реализации операции из математических расширений компилятор, используя структуры CCI, формирует соответствующую функцию, выполняющую эту операцию, и вставляет ее вызов в нужное место в дереве программы. a := b[m, n1..n2 by step] * k; MULT INDEXERINSTANCE MethodCall a = ElementWiseSRArrayScalarMult2d (b, k, m, n1, n2, step);
44 Демонстрация: на чем еще можно писать приложения в Visual Studio Zonnon
45 Tools for Zonnon ETH Zonnon, – Zonnon Command Line Compiler – Zonnon for MSVisual Studio 2008 – Zonnon plugin for Eclipse – Zonnon builder 2 Zonnon based educational courses Examples online – Zonnon webpage (>100 examples, 2 demo projects), – (>250 math. examples)
46 Демонстрация
47 Спасибо за внимание! Вопросы?
Еще похожие презентации в нашем архиве:
© 2024 MyShared Inc.
All rights reserved.