Quick viewing(Text Mode)

The Zonnon Project: a Language and Compiler Experiment

The Zonnon Project: a Language and Compiler Experiment

The Project: A Language and Experiment

Евгений Зуев, ETH Zürich

Нижегородский гоcударственный университет 27 сентября 2005 План История проекта, предшественники Язык Zonnon Компилятор Zonnon CCI & Модель компиляции Zonnon Интеграция в Visual Studio Zonnon Builder Инфо, Выводы, Участники 2 История проекта 1999, Oberon.NET Projects 7 & 7+, инициированные Research 2001, Active Oberon ETH Zürich; понятие active object 2004, Active C# ETH Zürich; механизм взаимодействия процессов, основанный на понятии синтаксически-ориентированных протоколов 3 Особенности языка Zonnon Младший член семейства Pascal,-2, Oberon: компактный, легкий для изучения и использования Поддерживает модульность (импорт прогр. единиц и экспорт членов прогр.единиц) Поддерживает ООП на основе концепции интерфейс/реализация и механизма уточнения (refinement) интерфейсов Поддерживает параллельность на основе понятия активных объектов и синтакси- ческих протоколов 4 Архитектура Zonnon-программ 1

Module Definition System managed object: - encapsulates resources Unified unit of abstraction: - implements definitions - represents abstract interface - aggregates implementations - refines another definition

Object Implementation

Program managed actor/resource: - def.implementation of a definition - implements definitions - standalone aggregation unit - aggregates implementations - specifies concurrent behaviour 5 Архитектура Zonnon-программ 2

Definition D1 Definition D2 Definition D3

Definition D11 (refines D1) Implementation D3 (default for Def D3) Implementation D11 (default for Def D11)

Object B (implements D2, reuses default implem for D3, and aggregates I) Object A (implements D1 & D11 without reusing def implem) Implementation I (standalone resource) 6 Definitions (* Common interface for all kind of vehicles *) definition Vehicle; var { get } Speed : integer; (* read-only *) procedure SpeedUp ( d:integer ); procedure SlowDown ( d:integer ); end Vehicle.

definition Truck refines Vehicle; (* Inherits interface from Vehicle *) const SpeedLimit = 90; end Truck.

7 Definition & Implementation (* Common interface for random numbers generators *) definition Random; var { get } Next : integer; (* read-only *) procedure Flush; (* reset *) end Random. (* A default implementation of the generator *) implementation Random; var { private } z : real; procedure { public, get } Next : integer; const a = 16807; m = 2147483647; q = m div a; r = m mod a; var g : integer; begin g := a*(z mod q) – r*(z div q); if g>0 then z := g else z := g+m end; return z*(1.0/m) end Next; procedure Flush; begin z := 3.1459 end Flush; begin Flush end Random. 8 Definitions & Objects (* Common interface for the random numbers generator *) definition Random; var { get } Next : integer; (* read-only *) procedure Flush; (* reset *) end Random. (* A custom implementation of the generator *) object myRandom implements Random; (* Procedure Next is reused from default implementation *) (* Procedure Flush is customized *) procedure Flush implements Random.Flush; begin z := 2.7189 end Flush; begin Flush end myRandom.

9 Modules & Objects

module Test; import Random, (* both definition and implem are imported *) myRandom; var x : object { Random }; (* x’s actual type is either Random or any type implementing Random *) object R2 implements Random; (* Another implementation of Random definition *) . . . end R2; begin x := new Random; . . . x := new myRandom; . . . x := new R2; end Test. 10 Ta ken from o a talk f JG, BK Пример активности: , and DL A Pipeline with Active Objects 1

Stage Stage AWAIT Buffer Activity

Get Put Put Get

AWAIT

Active Object Active Object

System-wide activity is scheduled by evaluating the set of all AWAIT preconditions 11 Ta ken from o a talk f JG, BK Activity Example: , and DL A Pipeline with Active Objects 2

object Stage (next: Stage); var { private } n, in, out: integer; buf: array N of object; (*used as a circular buffer*) procedure { private } Get (var x: object); Wait whilst begin { locked } (*mutual exclusion*) the buffer await (n # 0); (* precondition to continue*) is empty dec(n); x := buf[out]; out := (out+1) mod N end Get; procedure { public } Put (x: object); begin { locked } await (n # N); (*mutual exclusion*) inc(n); buf[in] := x; in := (in+1) mod N end Put; Wait whilst the buffer activity Processing; var x: OBJECT; is full begin loop Get(x); (*process x;*) next.Put(x) end end Processing;

begin (*initialise this new object instance*) each activity n := 0; in := 0; out := 0; new Processing; has a separate end Stage; thread 12 Activities & Protocols definition D; protocol P = (a, b, c); (* declaration of a protocol *) end D. object O; import D; activity A implements D.P; (* declaration of an activity *) begin ... return u, v, w; (* activity returns tokens *) … x, y := await; (* activity receives tokens *) end A; var p: P; (* declaration of an activity variable *) begin p := new A; (* create an activity *) (* Continued dialog between caller and callee *) p(x, y); (* caller sendstokensx, y to activityp*) u, v, w := await p; (* caller receives tokens from p *) if u = P.a then ... end; (* using the token received from p *) r := p(s, t); (* same as a(s, t); r := await p *) await p; (* wait for activity to terminate *) end O. 13 Синтаксические протоколы

definition Fighter; (* See full example in the Zonnon Language Report *) (* The protocol is used to create Fighter.Karate activities *) protocol (* syntax of the dialog*) { fight = { attack ( { defense attack } | RUNAWAY [ ?CHASE] | KO | fight ) }. attack = ATTACK strike. defense = DEFENSE strike. strike = bodypart [ strength ]. bodypart = LEG | NECK | HEAD. strength = integer. } (*enumeration of the dialog elements to be exchanged*) Karate = ( RUNAWAY, CHASE, KO, ATTACK, DEFENSE, LEG, NECK, HEAD ); end Fighter. 14 Outline История проекта Язык Zonnon Zonnon-компилятор CCI & Модель компиляции Zonnon Интеграция в Visual Studio Zonnon Builder Инфо, Выводы, Участники 15 Zonnon-компилятор Front-end реализован на C# с использо- ванием традиционных методов (recursive descent parser с полным семантическим контролем) Генерация кода и интеграция: на основе CCI framework Реализованы три варианта компилятора (все используют одно и то же ядро): - компилятор командной строки - компилятор,интегрир. в Visual Studio - компилятор,интегрир в Zonnon Builder 16 Zonnon-компилятор в Visual Studio

Демонстрация: Двоичный поиск

17 План История проекта Язык Zonnon Zonnon-компилятор CCI & Модель компиляции Zonnon Интеграция в Visual Studio Zonnon Builder Инфо, Выводы, Участники 18 Common Compiler Infrastructure Универсальный framework разработки компиляторов для .NET и их интеграции в Visual Studio Реализует CLR-ориентиров. сем.анализ, построение дерева программы и его преобразования, разрешение имен, обработку ошибок и генерацию IL+MD; не поддерживает лексич.& синт.анализ Также может использоватиься как более эффективная альтернатива System.Reflection Не требуется COM-программирование: только C# Реализован в Microsoft; используется в компиля- торах Cω & Spec# (а также в нескольких других внутренних проектах Microsoft) 19 Архитектура CCI

Compiler Front End Compiler Back End

Семантическое Сервис для представле-- генерации ние сборок Сервис для интеграции

Visual Studio .NET.NET

20 Основные компоненты CCI Intermediate Representation (IR) – A rich hierarchy of C# classes representing most common and typical notions of modern programming languages. System.Compiler.dll Transformers (“Visitors”) – A set of classes performing consecutive transformations IR Ÿ MSIL System.Compiler.Framework.dll Integration Service – Variety of classes and methods providing integration to Visual Studio environment (additional functionality required for editing, debugging, background compilation, project management etc.) 21 Использование CCI: Общие принципы

All CCI services are represented as classes. In order to make use of them the compiler writer should define classes derived from CCI ones. (The same approach is taken for Scanner, Parser, IR, Transformers, and for Integration Service) Derived classes should implement some abstract or virtual methods declared in the base classes (they compose a “unified interface” with the environment) Derived classes may (and typically do) implement some language-specific functionality. 22 Использование CCI: Синтаксический анализатор using System.Compiler; Prototype parser: abstract class from CCI namespace ZLanguageCompiler { public sealed class ZParser : System.Compiler.Parser { public override ... ParseCompilationUnit(...) {

l l . . . a } C private ... ParseZModule(...) { . . . } Parser’s “unified interface”: } implementation of the } interface between Z parser’s own logic Z compiler and environment 23 Модель компиляции CCI 1

IL/MD Writer

OutputOutput Source MSIL+MD Source IR AssemblyAssembly (AST)

IL/MD Scanner Visitors & Reader Parser ImportedImported AssembliesAssemblies Source Language Part: CCI Part: Language specific Common to all languages 24 Модель компиляции CCI 2

CCI IR Hierarchy CCI Base Transformers Visitor 1 Visitor 2 MSIL+MD … Visitor N

X Language IR Hierarchy X Language Transformers

Visitor 1

Visitor 2 MSIL+MD Visitor 3+ … Visitor M 25 Модель компиляции CCI: пример Extending the IR Hierarchy Ada exit statement: exit when ;

1 Extend existing Exit node public class If : Statement public class AdaExit : Exit { { Expression condition; Expression condition; } Block falseBlockfalseBlock;; Block trueBlocktrueBlock;; 2 Add new statement to the hierarchy } public class AdaExit : Statement { Expression condition; }

3 Use semantic equivalent from the existing hierarchy Represent Exit as an instance of class If with condition == , falseBlock == null, and trueBlock == Block with one element of type Exit. 26 Модель компиляции CCI: пример

Extending a Visitor Prototype visitor: using System.Compiler; base CCI class namespace AdaLanguageCompiler { public sealed class Looker : System.Compiler.Looker { public override Node Visit ( Node node ) { switch ( node.NodeType ) { “Dispatcher” method case NodeType.AdaExit: return thisthis.VisitAdaExit(node); defaultdefault: return basebase.Visit(node); Call to prototype visitor } } private If VisitAdaExit ( AdaExit node ) { /* Transform AdaExit node to If node */ } } } Additional semantic functionality 27 Модель компиляции Zonnon 1 Zonnon (A Subset of) IR Hierarchy CCI IR Hierarchy

Zonnon Transformers

(A Subset of) CCI Base Transformers

Visitor K … MSIL+MD Visitor N 28 Модель компиляции Zonnon 2 Example: Zonnon Tree & Transformers

public sealed class DEFINITION_DECL : UNIT_DECL { // Constructor public DEFINITION_DECL ( Identifier name ) : basebase(name) { } // Structure public DECLARATION_LIST locals; // members, procedure headings public UNIT_DECL base_definition; public UNIT_DECL default_implementation;

// Fills the structure after parsing the source public static DEFINITION_DECL create ( IDENT_LIST name, MODIFIERS modifiers ) { } // Resolves forward declarations public override NODE resolve ( ) { ... } Zonnon // Checks semantic correctness Transformers public override bool validate ( ) { ... } // Generates CCI node(s) convert transformer public override Node convert ( ) { ... } encapsulates mappings } Zonnon->CLR 29 Модель компиляции Zonnon 3

SourceSource MSIL+MD Zonnon CCI Tree Tree

Почему два дерева: • Они отражают концептуальный разрыв между Zonnon и CLR • Семантическое представление Zonnon не зависит от CCI и целевой платформы • Преобразование Zonnnon tree -> CCI tree явно реализует и капсулирует проекции (mappings) языковой модели Zonnon на языковую модель CLR 30 Модель компиляции Zonnon 4 Отображения (mappings) Zonnon->CLR

definition D; interface D { var x : T; T x { get; set; } const k = 10; // Nothing type e = (a,b,c); // Nothing procedure p ( y : T ); void p ( T y ); end d. } public class D_implem : D { implementation d; enum e { a, b, c }; var x, y : T; T x, y; // x hides d’s x procedure p ( y : T ) implements d.p; void p ( T y ) begin { ...x...... x... // “native” x ...k...... k... // d_default.k ...e...... e... // d_default.e end p; } end d. } 31 Модель компиляции Zonnon 4 Отображения (mappings) Zonnon->CLR object O implements d; procedure p ( y : T ) implements d.p; begin ...x... end p; end O. public sealed class O : D, D_implem // Option 1 { public override void p ( T y ) { // hides D_implem’s p() ...x... } } public sealed class O : D { // Option 2 private D_implem mixed; public override void p ( T y ) { ...mixed.x... } } 32 План История проекта Язык Zonnon Zonnon-компилятор CCI & Модель компиляции Zonnon Интеграция в Visual Studio Zonnon Builder Инфо, Выводы, Участники 33 Интеграция компилятора: Традиционный подход Source File Name Compilation Params

Compiler Start Up Environment Compiler

Syntax & Code Source Lexical Sequence Program Genera- Object Code Analysis of Tokens Semantic Tree Code Analysis tion

Compiler End Up

Компилятор как File with Object Code «черный ящик» Diagnostic Messages 34 Интеграция: что имеется в виду? (1)

Компоненты Visual Studio Свойства, которые должны поддерживаться компилятором • Language sources identification • Syntax Highlighting Project Manager • Automatic text formatting • Smart text browsing {  } Text Editor • Error checking while typing • Tooltip-like diagnostics & info Semantic Support • Outlining (collapsing parts (“Intellisense”) of the source); • Type member lists for classes Debugger and variables of class types • Lists of overloaded methods • Lists of method parameters • Expression evaluation • Conditional breakpoints 35 Интеграция: что имеется в виду? (2)

Пример свойства “Intellisense”

36 Интеграция компилятора: подход CCI

Token Document TokenToken Program Tree Object Code (Assembly) Source Code Token Attrs Source Context Token Context

Code Lexical Syntax & Компилятор Genera- Analysis Semantic Среда Analysis tion

Компилятор как коллекция ресурсов 37 Интеграция компилятора: подход CCI Token Document TokenToken Program Tree Source Code Token Attributes Object Code (Assembly) Source Context Token Context

Syntax & Code Lexical Genera- Analysis Semantic Компилятор Analysis tion как множество объектов Среда

Source Text Project “Intellisense” Debugger Editor Manager etc 38 План История проекта Язык Zonnon Zonnon-компилятор CCI & Модель компиляции Zonnon Интеграция в Visual Studio Zonnon Builder Инфо, Выводы, Участники 39 Zonnon Builder Независимая и легкая в использовании среда программирования: понятна и удобна для начинающих и в то же время выглядит знакомой для программистов на Паскале Более простая и легкая в использовании альтер- натива Visual Studio Поддерживает типичный цикл разработки: редак- тирование, компиляция, выполнение, тестиро- вание, отладку, управление проектами, ведение версий Поддерживает упрощенный цикл разработки: создается, компилируется и выполняется про- грамма, состоящая из единственного файла 40 Zonnon Builder

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

41 Web-страница Zonnon

www.zonnon.ethz.ch

Примеры Zonnon-программ (в ), т.ч. Тестовый наборисходники Zonnon (1000+ ), Zonnon Language Report,Chess Notebookтестов Zonnon User’s Guide (очень -), Статьи и слайды презентаций скоро, Дистрибутив Zonnon (регулярно ) 42 обновляется Выводы Zonnon – новый ЯП, сочетающий традиционную нота- цию и классическую модель модульности с мощ- ными современными парадигмами – объектной ориентацией и параллельностью на уровне языка Zonnon может использоваться совместно с другими языками .NET в одной среде программирования (Visual Studio) По нашим сведениям, Zonnon-компилятор – первый (и пока един- ственный) компилятор, созданный вне Microsoft и полностью инте- грированнный в Visual Studio

Zonnon используется как языковая основа в начальном курсе программирования (в качестве первого языка) в Нижегородском государственном университете 43 Участники J.Gutknecht, ETH Zürich Основной автор языка B.Kirk, Robinson Associates D.Lightfoot, Oxford Brookes University Zonnon Language Report H.Venter, Microsoft Common Compiler Infrastructure Е.Зуев, ETH Zürich Zonnon-компилятор, интеграция в VS В.Романов, МГУ, Россия Тестовый набор, Zonnon Builder, Chess NB A.Freed, NASA Первый «реальный» пользователь Zonnon В.Гергель, Д.Лабутин, Р.Митин, ННГУ, Россия Вводный курс по программированию на базе Zonnon; примеры программ на Zonnon 44 Вопросы? Предложения? Критика?

45