Нина Гонова ННГУ ВМК МЛиВА. Zonnon Немного истории: почему еще один язык?

Презентация:



Advertisements
Похожие презентации
© 2002 IBM Corporation Confidential | Date | Other Information, if necessary © Wind River Systems, released under EPL 1.0. All logos are TM of their respective.
Advertisements

Loader Design Options Linkage Editors Dynamic Linking Bootstrap Loaders.
1/27 Chapter 9: Template Functions And Template Classes.
The waterfall model is a popular version of the systems development life cycle model for software engineering. Often considered the classic approach to.
The waterfall model is a popular version of the systems development life cycle model for software engineering. Often considered the classic approach to.
© Luxoft Training 2013 Annotations. © Luxoft Training 2013 Java reflection / RTTI // given the name of a class, get a "Class" object that // has all info.
WEB SERVICES Mr. P. VASANTH SENA. W EB SERVICES The world before Situation Problems Solutions Motiv. for Web Services Probs. with Curr. sols. Web Services.
Java Server Pages(JSP). JavaServer Pages (JSP) позволяют вам отделить динамическую часть ваших страниц от статического HTML. Вы, как обычно, пишете обычный.
Copyright 2003 CCNA 1 Chapter 9 TCP/IP Transport and Application Layers By Your Name.
1 © Luxoft Training 2012 Inner and anonymous classes.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Optimizing BGP Scalability Implementing BGP Peer Groups.
© 2009 Avaya Inc. All rights reserved.1 Chapter Three, Voic Pro Advanced Functions Module Three – TAPI.
Lecture # Computer Architecture Computer Architecture = ISA + MO ISA stands for instruction set architecture is a logical view of computer system.
© 2005 Cisco Systems, Inc. All rights reserved.INTRO v Building a Simple Serial Network Understanding the OSI Model.
WiseImage Open Architecture. Why to open? Modern technology demands A growing amount of customers demands for custom commands The limited development.
Developing a PDMWorks Enterprise add-in in Microsoft VB.NET Jonathan Freeson Senior Consultant / Partner xLM Solutions, LLC.
SSD1: Introduction to Information Systems SSD1: Introduction to Information Systems ISS, Wuhan University.
XjCharts A C++ / Java Statecharts Tool for Developers Experimental Object Technologies
1 When And How To Make Interfaces Work For You Advanced OO Techniques Alex Herbstritt Principal Software Engineer, Progress Software Session 102.
CSTA is a kind of standard communication protocol used between PBX and computer that is famous in Europe. What is CSTA ? Control Requests Event Notifications.
Транксрипт:

Нина Гонова ННГУ ВМК МЛиВА

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 over- specifying it in order to apply highly complicated verification techniques

C# is a Good Language, but... What can be improved? – Concurrency – Composability – Extensibility – Syntax

Обзор семейства языков Pascal 5 Algorithms Data Structures Modules OOP Agents ??? Algol Pascal Modula-2 Oberon Active Oberon Zonnon Programming in-the-Large Programming in-the-Small

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: 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)

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 Zonnon – Definitions – Implementations – Object Types – Modules extends implements inherits implements aggregates refines :n :1 :n run compile imports :n

Compositional Model Client Servant Object as Composition of Facets via Aggregation Definition Default Implementation Custom Implementation Facet

Composition Example definition Vehicle; var speed: real; end Vehicle; definition Container; var capacity: real; load: real; end Container; type Truck = object implements Vehicle, Container

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 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.

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

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

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

Zonnon concepts: Compositional OO programming model Modular programming model Concurrency Communication model based on dialogs Math extensions Interoperability

Protocols Communication Controlled by Syntax P Another Communication Controlled by Syntax P Protocol Type P Protocol Type Q Communication controlled by syntax Q Activity

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 ) } );

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.

View on Application in Zonnon Activity Active link Module structure the application and introduce clear borders

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

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: 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

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 Zonnon-часть: Cпецифична для языка IR (AST) Source Scanner & Parser Visitors CCI-часть: Общая для всех языков Imported Assemblies MSIL+MD Output Assembly IL/MD Reader IL/MD Writer

IR (AST) Zonnon AST CCIs AST Scanner & Parser Visitors Реализуется семантическая специфика Zonnon Проекции (mappings): отображение специфических свойств Zonnon на семантически эквивалентные структуры.NET Модель компиляции Zonnon Проекции

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

Инфраструктура компилятора Компилятор Zonnon для платформы.NET реализован с использованием библиотеки Common Compiler Infrastructure (CCI). Эта библиотека, концептуально, обеспечивает поддержку для разработки компиляторов для.NET на трех уровнях: – Инфраструктура высокого уровня (в частности структуры для построения деревьев программ и методы для осуществления семантической проверки деревьев) – Поддержка низкого уровня (генерация IL кода и метаданных) – Сервис интеграции с Microsoft Visual Studio

Общие принципы использования CCI Все сервисы CCI представлены в виде классов. Чтобы воспользоваться этими сервисами, необходимо определить собственные классы, производные от классов CCI. В производных классах необходимо обеспечить реализацию некоторых абстрактных методов классов- прототипов (они образуют «унифицированный интерфейс» с окружением). Производные классы содержат функциональность, реализующую собственную семантику компилятора.

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

Компилятор Zonnon В целом компилятор организован довольно традиционно: сканер трансформирует исходный текст в последовательность лексем, которые принимаются синтаксическим анализатором. Далее строится Zonnon-ориентированное программное дерево, которое затем трансформируется в дерево с узлами, представляющими собой сущность класса промежуточного представления CCI. Конечным результатом трансформаций является сборка.NET. Отображение математических расширений в.NET происходит во время конвертации дерева Zonnon в дерево CCI. Исходный код Zonnon front-end Zonnon back-end Дерево Zonnon Дерево CCI MSIL + MD

Отображение в.NET Для реализации операции из математических расширений компилятор, используя структуры CCI, формирует соответствующую функцию, выполняющую эту операцию, и вставляет ее вызов в нужное место в дереве программы. a := b[m, n1..n2 by step] * k; MULT INDEXERINSTANCE MethodCall a = ElementWiseSRArrayScalarMult2d (b, k, m, n1, n2, step);

Демонстрация: на чем еще можно писать приложения в Visual Studio Zonnon

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)

Демонстрация

Спасибо за внимание! Вопросы?