java scriptの進化

262
JavaScriptの進化 maruyama097 丸山不二夫

Upload: maruyama097

Post on 08-May-2015

6.617 views

Category:

Documents


6 download

TRANSCRIPT

JavaScriptの進化

maruyama097 丸山不二夫

Agenda I 進化の概観

o  I-1 JavaScriptの適用範囲の拡大 n  ブラウザー・サーバー内言語としての誕生 n  jQueryの成功 -- WebのAJAX世代 n  HTML5への期待の拡大 n  Node.js -- クライアントからサーバーへ n  JavaScriptの繁栄

o  I-2 JavaScriptの言語機能の拡大 n  Intel RiverTrail – Multi-Coreへの対応 n  Google Dart – 新しいWeb言語の提案 n  Microsoft TypeScript – 新しい標準?

Agenda II 言語としての進化

o  II-1 JavaScriptの言語としての本来の特徴 n  ホスト環境内言語 n  オブジェクト指向:Prototype-Based Inheritance n  関数型言語

o  II-2 JavaScript言語の進化 n  jQuery -- 非同期・関数型の展開 n  Node.jsの飛躍 -- ホスト環境からの脱却 n  RiverTrail -- ParallelArrayパターン n  Dartの問題提起 -- JavaScriptはScaleしない n  TypeScriptの目指すもの

“Initially, however, many professional programmers denigrated the language because its target audience was web authors and other such "amateurs", among other reasons.” --- JavaScript Wikipedia

“Java is a blue collar language. It’s not PhD thesis material but a language for a job. Java feels very familiar to many different programmers because we preferred tried-and-tested things.” --- “The Feel of Java” James Gosling IEEE Computer, June 1997

“Much of the relative simplicity of Java is — like for most new languages—partly an illusion and partly a function of its incompleteness. As time passes, Java will grow significantly in size and complexity. It will double or triple in size and grow implementation-dependent extensions or libraries.” — Bjarne Stroustrup, ≤ 2/97

Part I 進化の概観

細かな技術的な議論に入る前に、大雑把に、JavaScriptの発展を、現象として概観しよう。

初に、その領域の拡大の歴史をみておこう。そして、 近、活発に行われている、言語機能の強化の動きをみることにしよう。

進化の概観 JavaScriptの適用範囲の拡大

p  ブラウザー・サーバー内言語としての誕生 p  jQueryの成功 -- WebのAJAX世代 p  HTML5への期待の拡大 p  Node.js -- クライアントからサーバーへ p  JavaScriptの繁栄

Webブラウザー・ Webサーバー内言語としての誕生

JavaScriptは、1995年、NetScapeのブラウザー内の言語として生まれた。 indeed, there are no provisions in this specification for input of external data or output of computed results. ECMA 262 3rd

JavaScriptの誕生

o  Author Brendan Eich o  1994年 Mocha, LiveScript o  1995年 12月4日 プレスリリース o  1996年 3月 Version 1.0

on NetScape 2.0 o  1996年 8月 Version 1.1

on NetScape 3.0 o  1998年 10月 1.3 ECMA-262 1st + 2nd o  2000年 11月 1.4 ECMA-262 3rd o  2010年  7月 1.8.5 ECMA-262 5th

1995年12月4日 プレス・リリース

http://web.archive.org/web/20070916144913 /http://wp.netscape.com/newsref/pr/newsrelease67.html

jQueryの成功 -- WebのAJAX世代

JavaScriptの大きな成功は、AJAXの登場によってもたらされた。それはまた、jQueryの成功と、ほぼ重なっていた。 jQuery is designed to change the way that you write JavaScript.

jQuery

o  Author John Resig now led by Dave Methvin o  2006年1月 at BarCamp NYC o  1.0 August 26, 2006

o  1.1 January 14, 2007   ... ... o  1.8.0 August 9, 2012 o  1.8.3 November 13, 2012 o  1.9.0 early 2013 o  2.0 early 2013

JavaScript Library 利用状況

o  jQuery 91% o  Modernizr 58% o  underscore.js

          33% o  backbone.js 30% o  Raphael.js 19% o  YUI 15% o  Google Closure

15% o  Zepto 13%

o  Prototype 13% o  Ext.js 11% o  MooTools 10% o  KnockoutJS 10% o  Sencha Touch

10% o  AngularJS 8% o  Ember 6% o  Dojo 6% o  Kendo UI 4%

JavaScriptへの期待は、新しいWeb標準であるHTML5への期待によって、更に、拡大してきた。JavaScriptは、Webの世界の標準言語としての地位を確立しつつある。

HTML5への期待の拡大

HTML5

o  2008 - First Public Working Draft

o  2011 - Last Call o  2012 - Working Draft o  Plan 2014

W3C HTML5 Multi Media HTML5 Forms HTML5 Parser Mouse Key ev. Offline Support XHTML WAI ARIA Semantic Element

Mozilla浅井さんの資料、”Pure Web Apps”より。 http://www.slideshare.net/dynamis

WHATWG HTML Canvas Web Messaging Web Socket Server Setn Evnt Web Storage Web Workers Micro Data

CSS3 Media Queries Layout Flex Box Transform Animation Regions

WebGL SVG SMIL GeoLocation Vibration Orientation SPDY XHR2 DNT FileAPI CSP ECMA Script Indexed DB XPath WOFF DOM4 MathML RSS OGP

Node.js   -- クライアントからサーバーへ

Node.jsは、JavaScriptの適応範囲をサーバーへと広げた。それは、JavaScriptのブラウザー内言語からの脱却を意味している。 Node's goal is to provide an easy way to build scalable network programs

Node.js

o  Author Ryan Dahl o  2009年5月 v0.0.1 o  2009年11月 JSConf EUで発表 o  2009.06.11, Version 0.0.3 (GitHub) o  2010.08.20, Version 0.2.0 o  2011.02.10, Version 0.4.0 o  2011.11.04, Version 0.6.0 o  2012.06.25, Version 0.8.0 ... ... o  2012.10.24, Version 0.9.3 (Unstable)

CommonJS o  January 2009: "ServerJS"

Kevin Dangoor o  March 2009:

CommonJS API 0.1 o  April 2009:

JSConf in Washington, DC. o  August 2009: The group name was formally

changed to “CommonJS”

JavaScriptの繁栄

JavaScriptは、現在、大きな繁栄の時期を迎えている。言語のスピードは、ネーティブに迫るほど早くなり、無数のライブラリーが生まれている。

ブラウザー内の JavaScriptの スピードアップ

http://v8-io12.appspot.com/#94

958種のライブラリー !!

List of languages that compile to JS 200種類以上

o  CoffeeScript Family (& Friends) o  JavaScript Extensions

n  Security enforcing JavaScript n  Static typing n  Synchronous to Asynchronous JavaScript

Compilers (CPS) n  JavaScript Language Extensions

o  Ruby, Python, Perl, Java/JVM, Scala, C# .NET, Lisp Schema, OCaml, Haskell, Smalltalk, C/C++. Basic, Pascal, Go

https://github.com/jashkenas/coffee-script/wiki/ List-of-languages-that-compile-to-JS

進化の概観 JavaScriptの言語機能の拡大

p  Intel RiverTrail – Multi-Coreへの対応 p  Google Dart – 新しいWeb言語の提案 p  Microsoft TypeScript – 新しい標準?

Intel RiverTrail -- Multi-Coreへの対応

RiverTrailは、デバイスのマルチコアのパワーをブラウザーで活用することを目的としたJavaScriptの拡張である。 https://github.com/rivertrail/rivertrail/wiki

RiverTrail o  Stephan Herhut

Richard L. Hudson Jaswanth Sreeram

o  2011年9月 IDF 2011で発表

Presented by Justin Rattner, in IDF 2011

Google Dart – 新しいWeb言語の提案

Dartは、Googleによる、JavaScriptに代わる新しいWeb言語の提唱である。 Dart brings structure to web app engineering with a new language, libraries, and tools. http://www.dartlang.org

Dart o  Lars Bak

Kasper Lund Seth Ladd Eli Brandt ...

o  2011年10月 GOTO Conferenceで発表

http://www.dartlang.org/slides/

Microsoft TypeScript -- 新しい標準?

TypeScriptは、新しいJavaScriptの標準であるECMA6を意識した、Microsoftによる、JavaScriptの拡張の試みである。 Starts from JavaScript, Ends with JavaScript

TypeScript o  Anders Hejlsberg

Steve Lucco Luke Hoban ...

o  2012年10月1日 発表

Part II 言語としての進化

ここでは、まず、JavaScriptが言語として、本来持っていたいくつかの特質に注目しよう。 ついで、先に概観した言語の発展の歴史の節目が、こうした特質についての言語としての進化の節目でもあることを確認する。

JavaScriptの 言語としての本来の特徴

p  ホスト環境内言語 p  オブジェクト指向:Prototype-Based

Inheritance p  関数型言語

JavaScriptの 言語としての本来の特徴

p  ホスト環境内言語 Node.jsでの見直し p  オブジェクト指向:Prototype-Based

Inheritance    TypeScriptでの発展 p  関数型言語  jQuery,Node.jsでの展開

ECMA 262 6th?

o  ECMAScript is a vibrant language and the evolution of the language is not complete. Significant technical enhancement will continue with future editions of this specification.

ホスト環境内言語

JavaScriptの 大の特徴の一つは、当初は、自立した言語としてではなく、特定のホスト環境内で働く言語として設計されたことにある。

ホスト環境内言語 ブラウザー内のWeb記述言語

o  当初は、Webブラウザーだけではなく、Webサーバーでも動くことが期待されていた。

o  実際には、Webブラウザー内で動く、Web記述言語として、いわば、ブラウザーとの共生関係の下で、ブラウザーとともに発展してきた。Webブラウザーが、JavaScriptの環境を提供している。

o  Webアプリのフレームワークが想定しているように、Webブラウザーが、アプリの唯一のユーザー・インターフェースであるならば、それは言語としては、さほど大きな制限にならない。

o  同時に、Thin Server Architectureのような、Webアプリのフレームワーク以外でも、ブラウザーは、クライアントのプレゼンテーション層の担い手として重要である。

Core JavaScript Guide October 30, 1998 Version 1.4

o  JavaScript is Netscape’s cross-platform, object-oriented scripting language.

o  JavaScript is a small, lightweight language; it is not useful as a standalone language, but is designed for easy embedding in other products and applications, such as web browsers. Inside a host environment, JavaScript can be connected to the objects of its environment to provide programmatic control over them.

ホスト環境内言語 ECMA 262 3rd

o  ECMAScript is an object-oriented programming language for performing computations and manipulating computational objects within a host environment.

o  ECMAScript as defined here is not intended to be computationally self-sufficient; indeed, there are no provisions in this specification for input of external data or output of computed results.

o  A web browser provides an ECMAScript host environment for client-side computation including, for instance, objects that represent windows, menus, pop-ups, dialog boxes, text areas, anchors, frames, history, cookies, and input/output.

Web記述言語 ECMA 262 5th

o  前ページの一項と同じ記述 o  ECMAScript was originally designed to be a

Web scripting language, providing a mechanism to enliven Web pages in browsers and to perform server computation as part of a Web-based client-server architecture.

o  前ページの二項と同じ記述 o  Further, the host environment provides a

means to attach scripting code to events such as change of focus, page and image loading, unloading, ...

ブラウザーAPIが提供する JavaScriptの実行環境

o  Document Object Model (DOM) n  ページ内のDocumentを、nodeの木構造/親子関係

で表現したもの n  nodeは、オブジェクトでpropertyを持つ

o  Browser Object Model (BOM) n  ブラウザーをコントロールするオブジェクト群 n  frame, history, location, XMLHttpRequest 等

o  JavaScript objects and functions n  JavaScriptは、DOM, BOMへのアクセスを可能にす

る言語。 n  それ自身のオブジェクト、関数を持つ

ブラウザーAPIが提供する JavaScriptの実行環境

document.body.style. backgroundColor = 'red’;

location.replace('newpage.html');

http://javascript.info/files/tutorial/browser/JSTop.png

ブラウザーのEvent Loopの利用

o  JavaScriptは、ブラウザーの一つのWindowに対応した1スレッド上で実行される。それゆえ、JavaScriptは、スレッド操作命令を持たない。

o  JavaScript上のイベントは、ブラウザーのEvent Loop / Event queueでハンドルされる。

o  基本的には、イベントのCallback関数を、ブラウザーのEvent queueに積み込んでいく。ブラウザーのEvent Loopが、定期的にEvent queueをチェックする。

o  ブラウザー内言語としての、この特別な特徴は、jQueryで全面的に利用され、ブラウザー内言語からの脱却であるnode.jsのアーキテクチャに、直接的な影響を与えた。

オブジェクト指向: Prototype-Based Inheritance

JavaScriptのオブジェクト指向の特徴である、prototypeの利用は、ごく早い時期から、NetScape Navigator 3.0上の、JavaScript 1.1から、実装されている。

http://web.archive.org/web/20020611210350/ http://wp.netscape.com/eng/mozilla/3.0/handbook/ javascript/index.html

JavaScript 1.1 HandBook

オブジェクト指向: Prototype-Based Inheritance

o  Each constructor has a Prototype property that is used to implement prototype-based inheritance and shared properties. ECMAScript 3rd

o  Each constructor is a function that has a property named ―”prototype” that is used to implement prototype-based inheritance and shared properties.

ECMAScript 5th

Prototype

o  Every object created by a constructor has an implicit reference (called the object‘s prototype) to the value of its constructor‘s ―”prototype” property.

o  Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain

Object/Prototype Relationships

Example

var today = new Date() var birthday = new Date(95,12,17) Date.prototype.description=null today.description="Oh what a beautiful mornin\'" birthday.description="The day you were born” startDate=new Date() startDate.description=“Started the daily grind”

Example 1: Add a property to a user-defined object.

function Car(make, model, year) { this.make = make this.model = model this.year = year } var myCar = new Car("Acura", "Integra", 1987) Car.prototype.wheels = 4 // no 3-wheelers please! if (myCar.wheels == 4) document.write("The car myCar has ", myCar.wheels, " wheels.”)

Example 2: Add a method to String objects.

var s1 = new String("a") var s2 = new String("b") var s3 = new String("c") // Create a repeat-string-N-times method for all String objects function str_rep(n) { var s = "", t = this.toString() while (--n >= 0) s += t return s } String.prototype.rep = str_rep // Display the results document.write("<P>s1.rep(3) is " + s1.rep(3)) // "aaa" document.write("<BR>s2.rep(5) is " + s2.rep(5)) // "bbbbb" document.write("<BR>s3.rep(2) is " + s3.rep(2)) // "cc”

Prototype.js Class.create() -- Obsolete

var Person = Class.create(); Person.prototype = { initialize: function(name) { this.name = name; }, say: function(message) { return this.name + ': ' + message; } }; var guy = new Person('Miro'); guy.say('hi'); // -> "Miro: hi”

Prototype.js Object.extend() -- Obsolete

var Pirate = Class.create(); // inherit from Person class: Pirate.prototype = Object.extend(new Person(), { // redefine the speak method say: function(message) { return this.name + ': ' + message + ', yarr!'; } }); var john = new Pirate('Long John'); john.say('ahoy matey'); // -> "Long John: ahoy matey, yarr!"

Prototype.js Class.create() – New!

// properties are directly passed to `create` method var Person = Class.create({ initialize: function(name) { this.name = name; }, say: function(message) { return this.name + ': ' + message; } }); // when subclassing, specify the class you want to inherit from var Pirate = Class.create(Person, { // redefine the speak method say: function($super, message) { return $super(message) + ', yarr!'; } });

Prototype.js Class.create() Mixin – New!

var Vulnerable = { wound: function(hp) { this.health -= hp; if (this.health < 0) this.kill(); }, kill: function() { this.dead = true; } }; // the first argument isn't a class object, so there is no inheritance ... // simply mix in all the arguments as methods: var Person = Class.create(Vulnerable, { initialize: function() { this.health = 100; this.dead = false; } });

TypeScript Class ==> JavaScript

class BankAccount { balance = 0; deposit(credit: number) { this.balance += credit; return this.balance; } }

var BankAccount = (function () { function BankAccount() { this.balance = 0; } BankAccount.prototype.deposit = function(credit) { this.balance += credit; return this.balance; }; return BankAccount; })();

Dart Class ==> JavaScript

class Point { var x, y; Point(this.x, this.y); toString() => "($x,$y)”; }

Isolate.$defineClass("Point", "Object", ["x", "y"], { toString$0: function() { return '(' + $.toString(this.x) + ',' + $.toString(this.y) + ')’; } });

Dartは、prototypeを使っていない

オブジェクト指向言語としての JavaScript o  現時点で、JavaScriptの言語としての進化の、

一つの焦点になっているのが、大規模開発を意識した、JavaScriptのオブジェクト指向言語としての機能強化である。

o  JavaScriptの発展を目指すTypeScriptも、JavaScriptの対抗言語となることも辞さないDartも、このことを強く意識している。

o  ただ、確認しておきたいことは、JavaScriptが本来持っていた、prototypeベースのオブジェクト指向が、極めて柔軟で強力なオブジェクト指向の枠組みを提供しているということである。

関数型言語としてのJavaScript

prototypeと同様に、functionは、言語のごく初期から、JavaScript 1.1から導入された。

オブジェクト指向 Class型とPrototype型

o  Class型のJavaでは、クラスは、フィールドとメソッドによって定義され、クラスのインスタンスとしてのオブジェクトは、基本的にフィールドの値で特徴付けられる。

o  Prototype型のJavaScriptのオブジェクトは、それが持つプロパティのオブジェクトによって定義される。JavaScriptでは、フィールドとメソッドの区別は、相対的なものである。

o  重要なのは、JavaScriptでは、functionもオブジェクトであり、プロパティの値になること。

http://web.archive.org/web/20020611210350/ http://wp.netscape.com/eng/mozilla/3.0/handbook/ javascript/index.html

JavaScript 1.1 HandBook

Operator, Function

o  ECMAScript also defines a set of built-in operators that may not be, strictly speaking, functions or methods.                     ECMAScript 3rd

o  a function is a callable object.

A function that is associated with an object via a property is a method.                   ECMAScript 5th

JavaScriptで、functionは、 第一級の市民

o  JavaScript 1.0では、functionは、operatorと呼ばれていたようだ。

o  JavaScriptの特徴として、functionが第一級の市民であることの認識は、当初からあったものではなく、歴史的に形成されてきたように見える。

o  おそらく、jQueryの非同期のCallbackの実装スタイルが広く知られたことが、大きな転機になったように思える。

o  もちろん、Prototype型のオブジェクト指向が、もともと、それを可能にしていたのではあるが。

// Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){

jQuery.fn[ o ] = function( f ){ return this.on( o, f ); };

}); jQuery.each( [ "get", "post" ], function( i, method ) {

jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; });

関数型言語としてのJavaScript o  jQuery, node.jsという発展を通じて、関数型言

語としてのJavaScriptの特質は、その進化を牽引してきた。今日でも、それは、JavaScriptのもっとも魅力的で強力な特徴の一つになっている。

o  オブジェクト指向言語であると同時に、関数型言語でもあるという、JavaScriptの二つの側面が、今後、どのように発展していくかは、興味深いものがある。

o  次回のセミナーでは、関数型言語としてのJavaScriptに、あらためて焦点を合わせたいと考えている。

JavaScript言語の進化

p  jQuery -- 非同期・関数型の展開 p  Node.jsの飛躍 -- ホスト環境からの脱却 p  RiverTrail -- ParallelArrayパターン p  Dartの問題提起 -- JavaScriptはScale

しない p  TypeScriptの目指すもの

jQuery -- 非同期・関数型の展開

jQueryは、Structured Web世代の AJAX(Asynchronous JavaScript + XML)技術を支える代表的なJavaScriptライブラリーである。そこではDOMは、HTTPのRequest/Responseを待たずに、非同期に書き換えられる。

jQueryとは何か?

o  jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.

o  jQuery is designed to change the way that you write JavaScript.

DOM Tree

Parent/Children

CSS Selector

AJAX用のメソッド

o  jQuery.get() n  Load data from the server using a HTTP GET request.

o  jQuery.getJSON() n  Load JSON-encoded data from the server using a GET

HTTP request. o  jQuery.getScript()

n  Load a JavaScript file from the server using a GET HTTP request, then execute it.

o  .load() n  Load data from the server and place the returned

HTML into the matched element. o  jQuery.post()

n  Load data from the server using a HTTP POST request.

AJAX Event o  ajaxStart (Global Event)

n  beforeSend (Local Event) n  ajaxSend (Global Event) n  success (Local Event) n  ajaxSuccess (Global Event) n  error (Local Event) n  ajaxError (Global Event) n  complete (Local Event) n  ajaxComplete (Global Event)

o  ajaxStop (Global Event)

jQuery.ajax( url [, settings] ) o  Ajax関連の関数の実装には、関数ajax()が使

われている。 o  この関数は、引数一つだけをとるのだが、次のよ

うに、Hashを渡すことで、多数のオプションを指定出来る。

$.ajax( { url: "script.php", type: "post", success: function(result) { alert(result); } });

ajax()のオプションの例

o  async : boolean o  cache : boolean o  complete :

function o  contentType :

string o  data : object,

string o  dataFilter :

function

o  dataType : string o  error : function o  jsonp : string o  scriptCharset :

string o  success : function o  timeout : number o  type : string o  url : string o  xhr : function

Ajaxの呼び出し例

<div id = "form"> <input type = "text" id = "name"> <input type = "text" id = "email_address"> <input type = "text" id = "number"> <input type = "submit" onclick = "$.ajax({url:'submit.php' + getform('input', '#form'), type:'post'})"> </div>

function getform(input, form) { /* Copyright Greg Sidelnikov - www.learnjquery.org - [email protected]. You can use it in your own projects, retain this line, if you wish to give me credit. */ var ret = "?"; var Length = $(element, parent).length; var idnamelist = new Array(); var idvaluelist = new Array(); for (var i = 0; i < Length; i++) { idnamelist[i] = $(element, parent)[i].id; idvaluelist[i] = $(element, parent)[i].value; ret = idnamelist[i] + '=' + idvaluelist[i]; if (i < Length - 1) ret += "&"; } }

EventHandlerのbind/unbind

p  要素に、特定のイベントのEventHandlerを設定しておくことが出来る。

p  要素上で、そのイベントが発生した特、EventHandlerが呼び出される。

var handler = function() {    alert(‘ Hello World!'); }; $(’#greet').bind('click', handler); $(’#greet').unbind('click', handler);

eventの「名前」と、同名の関数

o  次の二つは、同じ働きをする。  $(window).bind( “load”, function()      { alert('Window finished loading.'); } );  $(window).load( function()      { alert('Window finished loading.'); } );

jQueryの特徴

o  jQueryの大きな特徴は、AJAXを、イベント・ドリブンで非同期な関数呼び出しのスタイルで実装したことにある。そこでは、JavaScriptの関数型言語としての特質が、全面的に利用されている。

o  JavaScriptは、もともと、Single-Threadで走っているので、それは、Multi-threadではない、Single-Thread上の、「並列」処理という、一見奇妙な形を取る。

o  ただ、こうした、アプローチは、孤立したものではない。ErlangやScalaのAkkaも、原理的には同じアプローチだと言っていい。

jQueryの特徴

o  もともと、一つのCPUを取ってみれば、同時には一つの処理しか行えない。Multi-Process / Multi-Thredといった「並行」処理は、OSのタイム・スライスが生み出す、擬似的なものである。

o  その点は、多数のCPUが協調動作する、「分散」処理の「並列性」とは、別のものである。

o  ブラウザー内言語という性格もあって、jQueryの疑似並列性は、OSによってではなく、ホスト環境としてのブラウザーのEvent Loop / Event Queueによって担保されている。

Node.jsの飛躍 -- ホスト環境からの脱却

JavaScriptの、この間の言語としての進化で、大のものは、Node.jsの登場である。

ブラウザーというホスト環境に依存していた言語は、そこからの脱却を始める。EventLoopを自分自身で持つことによって。

クライアントからサーバーへ?

o  今回の講演の前半では、node.jsの登場を、「クライアントからサーバーへ」と、JavaScriptの適応範囲の拡大として、特徴付けた。

o  ただ、node.jsをよく見ていくと、node.jsの登場を、JavaScriptの側からだけみる、こうした見方は、いささか狭いものであることに気付く。

o  基本的には、JavaScriptの内部の問題ではなく、より一般的な、イベント・ドリブンで非同期な入出力に対する関心の高まりが背景にあることがわかる。

2009年11月 JSConf Ryan Dahlの登場

o  ここでは、node.jsの爆発的な拡大の起点となった、2009年ベルリンで行われた、JSConfでのnode.jsの創始者Ryan Dahlの講演の一部を見てみよう。

“Node.js, Evented I/O for V8 Javascript”

by Ryan Dahl n  http://jsconf.eu/2009/speaker/

speakers_selected.html#entry-3356 n  http://s3.amazonaws.com/four.livejournal/

20091117/jsconf.pdf

I/O は、違ったやり方で 行われる必要がある。

o  多くのWebアプリは、次のようなコードを使う。 var result =

db.query("select * from T"); // use result o  データベースを検索している間、ソフトウェアは何

をしているのだろう? たいていの場合、ただレスポンスを待っているだけである。

o  それに加えて、IOによる遅延は、コンピュータの能力と比較すると、次のように、巨大なものである。

http://s3.amazonaws.com/four.livejournal/20091117/jsconf.pdf

I/O による遅延

l  L1: 3 cycles l  L2: 14 cycles l  RAM: 250 cycles l  DISK: 41,000,000 cycles l  NETWORK: 240,000,000 cycles

o  別の例を挙げよう。サーバーのパフォーマンスも実装によって大きな違いが生まれている。次のズは、AppacheとNGINXを比較したものである。

Apache vs NGINX 違いはどこにあるのか?

o  Apache はコネクションあたり一つのスレッドを使っているが、NGINXは、スレッドを使っていない。それは、event loopを使っている。

o  コンテキストの切り替えは、ただで出来る訳ではないし、スレッドの実行用のスタックは、メモリーを食う。大規模な並列処理では、それぞれのコネクション毎にOSのスレッドを使うことは出来ない。グリーン・スレッドやコルーティンは、こうした状況を劇的に改善出来る。

o  しかし、I/Oの実行を維持しているという幻想を生み出す、入り組んだメカニズムが、依然として存在している。スレッドによる並列性は、漏れの多い抽象である。

o  このようなコードは、全体のプロセスをブロックするか、複数のプロセスの実行をスタックさせることになるかのいずれかである。

o  しかし、次のようなコードでは、プログラムは、すぐにevent loopに戻ることが可能である。どのようなメカニズムも必要としない。

o  これが、I/Oが行われるべき方法である。 o  では、何故、誰もがevent loopやCallbackや

Non-BlokingI/Oを使わないのだろうか?

db.query("select..", function (result) { // use result });

var result = db.query("select..");

文化的偏見

o  我々は、I/Oを次のように行うと教えられてきた 1.  puts("Enter your name: "); 2.  var name = gets(); 3.  puts("Name: " + name);

o  我々は、入力を要求されたら、それが終わるまで何もしないと教えられてきた。次のようなコードは、複雑すぎるとして、退けられてきた。 1.  puts("Enter your name: "); 2.  gets(function (name) { 3.  puts("Name: " + name); });

インフラの不在

o  それでは、何故、誰もが event loopを使わないのだろう?

o  シングル・スレッドのevent loopは、I/Oが non-blockingであることを要求するのだが、ほとんどのライブラリーはそうなっていない。 n  POSIX async file I/O は使えない. n  Man pagesは、関数がディスクにアクセスすることが

あることを触れていない。 (e.g getpwuid()) n  Cに、クロージャーや無名関数がないことが、コール

バックを難しくしている。 n  データベースのライブラリーは(e.g. libmysql)、非同

期のサポートをしていない。

JavaScript o  Javascriptは、event loopと一緒に使われるよ

うに、特別にデザインされた言語である。 n  無名関数、クロージャー n  同時には、一つだけのコールバック n  DOMのイベントコールバックを通じたI/O

o  JavaScriptのカルチャーは、既に、イベント中心のプログラミングの準備ができている。

node.js project:

高度な並列プログラムを記述する、純粋にイベント中心で、non-blockingなインフラを提供すること。

Design Goals

o  No function should direct perform I/O. n  To receive info from disk, network, or

another process there must be a callback. o  Low-level.

n  Stream everything; never force the buffering of data.

n  Do not remove functionality present at the POSIX layer. For example, support half-closed TCP connections.

n  Have built-in support for the most important protocols: TCP, DNS, HTTP

Design Goals

o  Support many HTTP features. n  Chunked requests and responses. n  Keep-alive. n  Hang requests for comet applications.

o  The API should be both familiar to client-side JS programmers and old school UNIX hackers.

o  Be platform independent.

An Introduction to libuv http://nikhilm.github.com/uvbook/An%20Introduction%20to%20libuv.pdf

http://vimeo.com/51637038

Libuv

o  libuv enforces an asynchronous, event-driven style of programming.

o  Its core job is to provide an event loop and callback based notifications of I/O and other activities.

o  libuv offers core utilities like timers, non-blocking networking support, asynchronous file system access, child processes and more.

Event loops

o  In event-driven programming, an application expresses interest in certain events and respond to them when they occur.

o  The responsibility of gathering events from the operating system or monitoring other sources of events is handled by libuv, and the user can register callbacks to be invoked when an event occurs.

o  The event-loop usually keeps running forever.

#include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <uv.h> void on_read(uv_fs_t *req); uv_fs_t open_req; uv_fs_t read_req; uv_fs_t write_req; char buffer[1024]; void on_write(uv_fs_t *req) { // callbackのsigniture uv_fs_req_cleanup(req); if (req->result < 0) { fprintf(stderr, "Write error: %s\n",         uv_strerror(uv_last_error(uv_default_loop()))); } else { uv_fs_read(uv_default_loop(), &read_req, open_req.result,       buffer, sizeof(buffer), -1, on_read); // callback } } // on_write callbackの中で、on_read callbackが呼ばれる

libuvスタイルでの catの実装

open, red, writeの libuv版は、第一引数に loopを取る。 終引数は callback

イベントの ようなもの

void on_read(uv_fs_t *req) { // callbackのsigniture uv_fs_req_cleanup(req); if (req->result < 0) { fprintf(stderr, "Read error: %s\n",        uv_strerror(uv_last_error(uv_default_loop()))); } else if (req->result == 0) { uv_fs_t close_req; // synchronous uv_fs_close(uv_default_loop(),            &close_req, open_req.result, NULL); } // callbackがNULL、同期型 else { uv_fs_write(uv_default_loop(),            &write_req, 1, buffer, req->result, -1, on_write); } // callback }  // on_read callbackの中で、on_write callbackが呼ばれる

void on_open(uv_fs_t *req) { // callbackのsigniture if (req->result != -1) { uv_fs_read(uv_default_loop(), &read_req, req->result, buffer, sizeof(buffer), -1, on_read); // callback } else { fprintf(stderr, "error opening file: %d\n", req->errorno); } uv_fs_req_cleanup(req); } // on_open callbackの中で、on_read callbackが呼ばれる int main(int argc, char **argv) { uv_fs_open(uv_default_loop(),       &open_req, argv[1], O_RDONLY, 0, on_open); // callback return 0; } // openは、on_open callbackを呼んで、すぐループに入る。

RiverTrail -- ParallelArray パターン

River Trail gently extends JavaScript with simple deterministic data-parallel constructs

RiverTailの背景

o  Intel LabのRiverTrailプロジェクトは、Webアプリにおいて、データの並列計算を可能にするものである。

o  Webブラウザーが、ユーザーのコンピューティングの窓口になっている世界では、 良のユーザー・エクスペリエンスを提供するために、ブラウザーのアプリケーションは、利用可能な全ての計算資源の力にてこ入れをしなければならない。

API デザイン 三つの柱のアプローチ

o  ParallelArray と呼ばれるデータの値を保持する型

o  mapのような、並列計算を実装した、いくつかのprototypical methodsと呼ばれる ParallelArrayのメソッド

o  典型的には、一つのデータ要素を返し、ParallelArrayのような構成物に渡されるelemental function のコンセプト

ParallelArray Constructor pa1 = new ParallelArray([ [0,1], [2,3], [4,5] ]); // <<0,1>, <2,3>, <4.5>> pa2 = new ParallelArray(pa1); new ParallelArray(<0,1>, <2,3>); // <<0,1>,<2,3>> new ParallelArray(3, function(i){return [i, i+1];}); // <<0,1><1,2><2,3>> new ParallelArray([3,2], function(iv){return iv[0]*iv[1];}); // <<0,0><0,1><0,4>> new ParallelArray(canvas);

Prototype Methods

var source = new ParallelArray([1,2,3,4,5]); var plusOne = source.map( function inc(v) { return v+1; }); // <2,3,4,5,6> var source = new ParallelArray([1,2,3,4,5]); var plusOne = source.combine( function inc(i) { return this.get(i)+1; }); // <2,3,4,5,6> var source = new ParallelArray([1,2,3,4,5]); var reverse = source.combine(function rev(i) { return this.get(this.length-i[0]-1); }); // <5,4,3,2,1>

Prototype Methods

var source = new ParallelArray([1,2,3,4,5]); var sum = source.reduce( function plus(a,b) { return a+b; }); // 15 var source = new ParallelArray([1,2,3,4,5]); var psum = source.scan( function plus(a,b) { return a+b; }); // <1, 3, 6, 10, 15>

Prototype Methods

var source = new ParallelArray([1,2,3,4,5]); var even = source.filter( function even(iv) { return (this.get(iv) % 2) == 0; }); // <2,4> pa = new ParallelArray([ [1,2], [3,4] ]) // <<1,2>,<3,4>> pa.flatten() // <1,2,3,4>

Prototype Methods

var source = new ParallelArray([1,2,3,4,5]); var indices = [0, 1, 2, 3, 4]; var identity = source.scatter(indices); // <1, 2, 3, 4, 5> var reorder = source.scatter([4,0,3,1,2]); // <2, 4, 5, 3, 1> // if there is a conflict use the max. // use 33 as a default value. var reorder = source.scatter([4,0,3,4,2], 33, function max(a, b) {return a>b?a:b; }); // <2, 33, 5, 3, 4>

プログラマは、どのように 並列アルゴリズムを記述しうるか?

o  Multi-core化の進展は、特に、身近なデバイス上でのその進展は、普通のプログラマにとっても、並列アルゴリズムの必要性を意識させるきっかけになるかもしれない。

o  ただ、並列アルゴリズムの実装は、難しい。ParallelArrayは、プログラマが、容易に並列アルゴリズムにアクセス出来るように設計された、パターンである。

o  Javaの新しいバージョンも、基本的には、同じParallelArrayのアプローチを採用している。

DartとTypeScript

これ以降の節で取り上げる、GoogleのDartとMicrosoftのTypeScriptは、いずれも、JavaScriptの開発の大規模化が抱える問題の認識から出発している。それはまた、前回のセミナーで取り上げた、Facebookも共有しているであろう問題意識である。 ただ、JavaScriptに対する両者のスタンスは、異なっている。JavaScriptの枠の中での発展を目指すTypeScriptと、JavaScriptの置き換えを目指すDartという構造になる。

Dartの問題提起 -- JavaScriptはScaleしない

Dartは、Googleの提案する、新しいWeb言語である。ブラウザーを中心として対象とする領域は、JavaScriptと重なっている。基本的には独自のVM上で動くのだが、JavaScriptに変換するコンパイラーを持ち、JavaScriptを強く意識している。 なぜ、GoogleはJavaScriptに代わるWeb言語を提案しているのだろう?

何故、Webはプログラムが難しいのか

o  大規模の、きちんと動くアプリを書くのは、大変難しい。 o  プログラムの構造を推察するのが難しい o  立ち上がりのパフォーマンスが、しばしば、非常に悪い。 o  (型がないことによる)意図を文書化することの困難 o  modules, packages, librariesがサポートされていな

い。

Dart: Modern Web Language Kasper Lund http://www.infoq.com/presentations/Dart-A-Modern-Web-Language

それでは、何故、 我々は、Dartを作ったのか?

o  我々は、Webプラットフォームを改善したい n  大規模なプログラミングの、より良いサポート n  とりわけ、モバイルでの迅速なアプリの立ち上げ n  より予測可能で、より良い実行時のパフォーマンス n  JavaScriptは強力なツールではあるが、危険なところ

も持っている o  イノベーションの勢いを維持する

n  Webは、ファンタスティクなペースで進化し続けている n  開発者のツールは、水準を上げなければならない

JavaScriptは、「驚き」に満ちている

o  沢山の沢山の、暗黙の型変換 o  間違った、あるいは、初期化しないままで値を渡

したとき、ほとんどの関数は、理解可能な仕方で失敗するのではなく、とんでもない結果を返してくる。

Keep on truckin’

Dart Technical Overview Design Goalから

o  小さなスクリプトが、明確な構造を持たないまま、大規模なWebアプリに発展することがよくあるが、こうしたアプリは、デバッグも難しいし、メンテするのも難しい。

o  それに加えて、こうしたモノリシックなアプリは、別々のチームが独立にそのアプリについて仕事をしようとしても、分割が出来ない。Webアプリが大きくなるにつれて、生産的であることは難しくなる。

o  スクリプト言語が人気があるのは、その軽量な性格がコードを早く書くことを容易にしているからである。一般的に言って、アプリのその他の部分との契約関係は、言語の構造自身というよりも、コメントによってになわれることになる。その結果、ある特定のコードの一部は、そのコードを書いた本人以外にとっては、読むこともメンテすることも難しくなる。

o  既存の言語では、開発者は、静的な言語と動的な言語の間で選択を迫られる。伝統的な静的言語では、重たい沢山のツール群と柔軟ではなく束縛し過ぎと感じられるコーディング・スタイルが要求されることになる。

o  開発者は、これまで、クライアントとサーバーの両方をまたいだ、均質なシステムを作り出すことが出来なかった。Node.jsやGoogle Web Toolkit (GWT)といった少数の例外を除いては。

o  異なる言語とフォーマットは、退屈なコンテキストの切り替えを必然的に伴い、コーディングのプロセスに複雑さを付け加えている。

Technical Overview

Key features p  Classes p  Optional types p  Libraries p  Tooling http://www.dartlang.org/docs/technical-overview/

Design goals

o  Create a structured yet flexible programming language for the web.

o  Make Dart feel familiar and natural to programmers and thus easy to learn.

o  Ensure that all Dart language constructs allow high performance and fast application startup.

o  Make Dart appropriate for the full range of devices on the web—including phones, tablets, laptops, and servers.

o  Provide tools that make Dart run fast across all major modern browsers.

interface Shape { num perimeter(); } class Rectangle implements Shape { final num height, width; Rectangle(num this.height, num this.width); // Compact constructor syntax. num perimeter() => 2*height + 2*width; // Short function syntax. } class Square extends Rectangle { Square(num size) : super(size, size); }

import 'dart:math'; class Point { var x, y; Point(this.x, this.y); scale(factor) => new Point(x*factor, y*factor); distance() => sqrt(x*x + y*y); } main() { var a = new Point(2,3).scale(10); print(a.distance()); }

import 'dart:math'; class Point { num x, y; Point(num this.x, num this.y); Point scale(num factor) => new Point(x*factor, y*factor); num distance() => sqrt(x*x + y*y); } void main() { Point a = new Point(2,3).scale(10); print(a.distance()); }

Improving the DOM

http://www.dartlang.org/articles/improving-the-dom/

Use real collections

Old

o  elem.hasAttribute('name');

o  elem.getAttribute('name')

o  elem.setAttribute('name', 'value');

o  elem.removeAttribute('name');

New

o  elem.attributes.containsKey('name');

o  elem.attributes['name'];

o  elem.attributes['name'] = 'value';

o  elem.attributes.remove('name');

Use real collections / Use Constructor Old

o  elem.hasChildNodes();

o  elem.firstChild(); o  elem.appendChild(chi

ld);

o  document.createElement('div');

New

o  elem.nodes.isEmpty();

o  elem.nodes[0]; o  elem.nodes.add(child

);

o  new DivElement();

Events

Old

o  elem.addEventListener('click',

(event) => print('click!'), false);

o  elem.removeEventListener(

'click', listener);

New

o  elem.on.click.add( (event) => print('click!'));

o  elem.on.click.remove(listener);

Events

Old

o  elem.addEventListener(

'some' + 'name', (event) => print('dynamic!'), false);

New

o  elem.on['some' + 'name'].add(

(event) => print('dynamic!'));

TypeScriptの目指すもの

p  Scalable p  Starts from JavaScript, Ends with

JavaScript p  Strong Tools for Large Applications

Scalable

o  TypeScriptは、頑健なコンポーネント作成を助ける為に、class, module, interfaceを提供する。

o  これらの特徴を、高信頼なアプリ開発において、開発時に利用出来る。ただし、それらは、シンプルなJavaScriptにコンパイルされる。

o  TypeScriptの型は、ソフトウェア・コンポーネント間のインターフェース定義を可能とし、また、既存のJavaScriptライブラリーの振る舞いの洞察も得ることが出来る。

Starts from JavaScript, Ends with JavaScript o  TypeScriptは、数百万のJavaScript開発者が今日知っ

ている、シンタックスとセマンティックスから始まる。 o  TypeScriptでは、 既存のJavaScriptコードを利用する

ことが出来るし、よく使われているJavaScriptライブラリと合体することも出来る。また、他のJavaScriptコードから呼び出されることも出来る。

o  TypeScriptは、どんなブラウザー上でも、node.jsでも、どんなES3互換の環境でも動く、クリーンでシンプルな JavaScriptコードにコンパイルされる。

Strong Tools for Large Applications

o  型は、静的チェック、シンボルベースのナビゲーション、文の補完、コードのリファクタリングといった、高い生産性を持つ開発ツールと実践を、TypeScript開発者が行うことを可能とする。

o  これらの型は、オプショナルなものである。型推論は、少数の型のアノテーションでも、コードの静的な検証に、大きな違いをもたらすことが出来る。

TypeScript Language Specification

http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf

Introduction o  TypeScript is a syntactic sugar for

JavaScript. TypeScript syntax is a superset of Ecmascript 5 (ES5) syntax. Every JavaScript program is also a TypeScript program.

o  TypeScript syntax includes several proposed features of Ecmascript 6 (ES6), including classes and modules.

o  TypeScript also provides to JavaScript programmers a system of optional type annotations. These type

Introduction

o  1.1 Ambient Declarations o  1.2 Function Types o  1.3 Object Types o  1.4 Structural Subtyping o  1.5 Contextual Typing o  1.6 Classes o  1.7 Modules .

Ambient Declarations o  An ambient declaration introduces a

variable into a TypeScript scope, but has zero impact on the emitted JavaScript program.

o  Programmers can use ambient declarations to tell the TypeScript compiler that some other component will supply a variable

declare var document; document.title = "Hello"; // Ok because document has been declared

Function Types o  TypeScript function types make it

possible for programmers to express the expected signature of a function.

function vote(candidate: string,            callback: (result: string) => any)   { // ... }

A function type literal of the form    ( ParamList ) => ReturnType is exactly equivalent to the object type literal    { ( ParamList ) : ReturnType }

Object Types o  TypeScript programmers use object

types to declare their expectations of object behavior.

o  The following code uses an object type literal to specify the return type of the ‘MakePoint’ function

var MakePoint: () => { x: number; y: number; };

Object Types : Interfaces

o  Programmers can give names to object types; we call named object types interfaces.

o  For example, in the following code, an interface declares one required field (name) and one optional field (favoriteColor).

interface Friend { name: string; favoriteColor?: string; }

interface Friend { name: string; favoriteColor?: string; } function add(friend: Friend) { var name = friend.name; } add({ name: "Fred" }); // Ok add({ favoriteColor: "blue" }); // Error, name required add({ name: "Jill", favoriteColor: "green" }); // Ok

Structural Subtyping o  Object types are compared structurally. o  A class may optionally declare that it

implements an interface, so that the compiler will check the declaration for structural compatibility.

interface Point { x: number; y: number; } function getX(p: Point) { return p.x; } class CPoint { constructor ( public x: number, public y: number) {} } getX(new CPoint(0, 0)); // Ok, fields match getX({ x: 0, y: 0, color: "red" }); // Extra fields Ok getX({ x: 0 }); // Error: supplied parameter does not match

Contextual Typing interface EventObject { x: number; y: number; } interface EventHandlers { mousedown?: (event: EventObject) => void; mouseup?: (event: EventObject) => void; mousemove?: (event: EventObject) => void; } function setEventHandlers(handlers: EventHandlers) { ... } setEventHandlers({ mousedown: e => { startTracking(e.x, e.y); }, mouseup: e => { endTracking(); } });

Classes class BankAccount { balance = 0; deposit(credit: number) { this.balance += credit; return this.balance; } }

var BankAccount = (function () { function BankAccount() { this.balance = 0; } BankAccount.prototype.deposit = function(credit) { this.balance += credit; return this.balance; }; return BankAccount; })();

Modules

module M { var s = "hello"; export function f() { return s; } } M.f(); M.s; // Error, s is not exported

TypeScript to JavaScript

interface Person { firstname: string; lastname: string; } function greeter(person : Person) { return "Hello, " + person.firstname + " " + person.lastname; } var user = {firstname: "Jane", lastname: "User"}; document.body.innerHTML = greeter(user);

function greeter(person) { return "Hello, " + person.firstname + " " + person.lastname; } var user = { firstname: "Jane", lastname: "User" }; document.body.innerHTML = greeter(user);

class Greeter { greeting: string; constructor ( message: String ) { this.greeting = message; } greet () { return “Hello, “ + this.greeting ; } } var greeter =new Greeter("world");

var Greeter=( function() { function Greeter(message){ this.greeting=message; ] Greeter.prototype.greet = function(){ return “Hello, “ + this.greeting ; }; return Greeter: }) (); var greeter = new Greeter("world");

class Student { fullname : string; constructor(public firstname, public middleinitial, public lastname) { this.fullname = firstname + " " + middleinitial + " " + lastname; } } interface Person { firstname: string; lastname: string; } function greeter(person : Person) { return "Hello, " + person.firstname + " " + person.lastname; } var user = new Student("Jane", "M.", "User"); document.body.innerHTML = greeter(user);

var Student = (function () { function Student(firstname, middleinitial, lastname) { this.firstname = firstname; this.middleinitial = middleinitial; this.lastname = lastname; this.fullname = firstname + " " + middleinitial + " " + lastname; } return Student; })(); function greeter(person) { return "Hello, " + person.firstname + " " + person.lastname; } var user = new Student("Jane", "M.", "User"); document.body.innerHTML = greeter(user);

module Sayings { export class Greeter { greeting: string; constructor (message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } } var greeter = new Sayings.Greeter("world"); var button = document.createElement('button') button.innerText = "Say Hello" button.onclick = function() {

alert(greeter.greet()) } document.body.appendChild(button)

var Sayings; (function (Sayings) { var Greeter = (function () { function Greeter(message) { this.greeting = message; } Greeter.prototype.greet = function () { return "Hello, " + this.greeting; }; return Greeter; })(); Sayings.Greeter = Greeter; })(Sayings || (Sayings = {})); var greeter = new Sayings.Greeter("world"); var button = document.createElement('button'); button.innerText = "Say Hello"; button.onclick = function () { alert(greeter.greet()); }; document.body.appendChild(button);

class Animal { constructor(public name) { } move(meters) { alert(this.name + " moved " + meters + "m."); } } class Snake extends Animal { constructor(name) { super(name); } move() { alert("Slithering..."); super.move(5); } }

var __extends = this.__extends || function (d, b) { function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var Animal = (function () { function Animal(name) { this.name = name; } Animal.prototype.move = function (meters) { alert(this.name + " moved " + meters + "m."); }; return Animal; })(); var Snake = (function (_super) { __extends(Snake, _super); function Snake(name) { _super.call(this, name); } Snake.prototype.move = function () { alert("Slithering..."); _super.prototype.move.call(this, 5); }; return Snake; })(Animal);

// Create an alternate method and assign it to only one String variable function fake_rep(n) { return "repeat " + this + n + " times." } s1.rep = fake_rep document.write("<P>s1.rep(1) is " + s1.rep(1)) // "repeat a 1 times." document.write("<BR>s2.rep(4) is " + s2.rep(4)) // "bbbb" document.write("<BR>s3.rep(6) is " + s3.rep(6)) // "cccccc”

あらためて、 JavaScriptの進化について

もちろん、DartとTypeScriptだけが、JavaScriptの進化の未来形ではないだろう。これからも、これまでのJavaScriptは、残り続けるだろうし、強力な草の根のJavaScriptコミュニティの中から、新しい進化が生まれる可能性は、きっとあると思う。 いずれにしても、プラグラム言語の進化の様々な動きの中心の一つが、JavaScriptになることは、間違いないと思う。

資料編

End of the World

資料目次

o  JavaScript n  ECMAScript Language Specification 3rd n  ECMAScript Language Specification 5th n  Javascript Territory – Jster Javascript

Catalog n  List of languages that compile to JS

o  About Node.js n  src/node.cc n  deps/uv/include/uv.h n  deps/uv/src/unix/loop.c n  What Server Side JavaScript needs

資料目次

o  Intel RiverTrail o  Dart

n  Dart: A modern web language n  Dart Frequently Asked Questions

ECMAScript Language Specification

ECMA-262 3rd Edition / December 1999 http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf

Overview

o  ECMAScript is an object-oriented programming language for performing computations and manipulating computational objects within a host environment.

o  ECMAScript as defined here is not intended to be computationally self-sufficient; indeed, there are no provisions in this specification for input of external data or output of computed results.

Web Scripting

o  A web browser provides an ECMAScript host environment for client-side computation including, for instance, objects that represent windows, menus, pop-ups, dialog boxes, text areas, anchors, frames, history, cookies, and input/output.

Server Side

o  A web server provides a different host environment for server-side computation including objects representing requests, clients, and files; and mechanisms to lock and share data. By using browser-side and server-side scripting together, it is possible to distribute computation between the client and server while providing a customised user interface for a Web-based application.

Language Overview

o  ECMAScript is object-based: basic language and host facilities are provided by objects, and an ECMAScript program is a cluster of communicating objects

o  ECMAScript also defines a set of built-in operators that may not be, strictly speaking, functions or methods.

Object o  ECMAScript does not contain proper

classes such as those in C++, Smalltalk, or Java, but rather, supports constructors which create objects by executing code that allocates storage for the objects and initialises all or part of them by assigning initial values to their properties. All constructors are objects, but not all objects are constructors.

Prototype

o  Each constructor has a Prototype property that is used to implement prototype-based inheritance and shared properties.

o  ECMAScript supports prototype-based inheritance. Every constructor has an associated prototype, and every object created by that constructor has an implicit reference to the prototype (called the object’s prototype) associated with its constructor.

ECMAScript Language Specification

ECMA-262 5.1 Edition / June 2011 http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

Overview

o  ECMAScript is an object-oriented programming language for performing computations and manipulating computational objects within a host environment.

o  ECMAScript was originally designed to be a Web scripting language, providing a mechanism to enliven Web pages in browsers and to perform server computation as part of a Web-based client-server architecture.

Web Scripting

o  A web browser provides an ECMAScript host environment for client-side computation including, for instance, objects that represent windows, menus, pop-ups, dialog boxes, text areas, anchors, frames, history, cookies, and input/output.

o  Further, the host environment provides a means to attach scripting code to events such as change of focus, page and image loading, unloading, ...

Language Overview

o  ECMAScript is object-based: basic language and host facilities are provided by objects, and an ECMAScript program is a cluster of communicating objects.

o  a function is a callable object. A function that is associated with an object via a property is a method.

Objects

o  Each constructor is a function that has a property named ―”prototype” that is used to implement prototype-based inheritance and shared properties.

o  Objects are created by using constructors in new expressions;

Prototype

o  Every object created by a constructor has an implicit reference (called the object‘s prototype) to the value of its constructor‘s ―”prototype” property.

o  Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain

Prototype

o  When a reference is made to a property in an object, that reference is to the property of that name in the first object in the prototype chain that contains a property of that name.

o  In other words, first the object mentioned directly is examined for such a property; if that object contains the named property, that is the property to which the reference refers; if that object does not contain the named property, the prototype for that object is examined next; and so on.

Object/Prototype Relationships

Class-based / Prototype-based

o  In a class-based object-oriented language, in general, state is carried by instances, methods are carried by classes, and inheritance is only of structure and behaviour.

o  In ECMAScript, the state and methods are carried by objects, and structure, behaviour, and state are all inherited.

Prototype

o  Property. Defines a property that is shared by all objects of the specified type.

o  Syntax objectType.prototype.propertyName = value

o  Parameters n  objectType is the name of a constructor or

function specifying an object type. n  propertyName is the name of the property

to be created. n  value is the property value initially assigned

for all objects of the specified objectType.

Description

o  Use the prototype property to explicitly add properties to objects created with the new operator.

o  For example, you can create Date objects by using the Date() constructor and the new operator. Date.prototype refers to the prototype object for the Date() constructor. If you set a property for the prototype, such as Date.prototype.description, then all objects created with Date() will have the description property, even if the objects already exist.

Example

var today = new Date() var birthday = new Date(95,12,17) Date.prototype.description=null today.description="Oh what a beautiful mornin\'" birthday.description="The day you were born” startDate=new Date() startDate.description=“Started the daily grind”

Example 1: Add a property to a user-defined object.

function Car(make, model, year) { this.make = make this.model = model this.year = year } var myCar = new Car("Acura", "Integra", 1987) Car.prototype.wheels = 4 // no 3-wheelers please! if (myCar.wheels == 4) document.write("The car myCar has ", myCar.wheels, " wheels.”)

Example 2: Add a method to String objects.

var s1 = new String("a") var s2 = new String("b") var s3 = new String("c") // Create a repeat-string-N-times method for all String objects function str_rep(n) { var s = "", t = this.toString() while (--n >= 0) s += t return s } String.prototype.rep = str_rep // Display the results document.write("<P>s1.rep(3) is " + s1.rep(3)) // "aaa" document.write("<BR>s2.rep(5) is " + s2.rep(5)) // "bbbbb" document.write("<BR>s3.rep(2) is " + s3.rep(2)) // "cc”

function Greeter(greeting) { this.greeting = greeting; } Greeter.prototype.greet = function () { return "Hello, " + this.greeting; }; var greeter = new Greeter("world"); var button = document.createElement('button'); button.innerText = "Say Hello"; button.onclick = function () { alert(greeter.greet()); }; document.body.appendChild(button);

Javascript Territory – Jster Javascript Catalog

http://jster.net/

958種のライブラリー !!

JavaScriptライブラリーの種類

o  Essentials o  UI o  Multimedia o  Graphics o  Data o  Development o  Utilities o  Applications

Essentials

o  Application Frameworks (37) o  Mobile Frameworks (17) o  MVC Frameworks (27) o  Realtime Frameworks (4) o  Desktop GUI (3) o  ServerSide Libraries (9) o  Testing Frameworks (55) o  Templating Engines (20) o  Loaders (32)

UI o  UI Frameworks (21) o  Windows, Modals, Popups (21) o  Keyboard Wrappers (25) o  Form Widgets (52) o  UI Components (14) o  Sliders & Galleries (38) o  Notifications (12) o  WYSIWYG Editors (30) o  Touch (51)

Multimedia

o  Game Engines (77) o  Physics Libraries (12) o  Animation Libraries (15) o  Audio Libraries (17) o  Presentation Libraries (19) o  Video Players (9)

Graphics

o  Canvas Wrappers (16) o  WebGL (13) o  Image Manipulation (12) o  Visualization Libraries (38) o  Color Libraries (9) o  Mapping Libraries (9)

Data

o  Data Structures (19) o  Date Libraries (9) o  ORM (3) o  Storage Libraries (16) o  Strings (5)

Development o  Timing (3) o  Toolkits (12) o  Code Protection (15) o  Language Compilers (16) o  Debugging Tools (7) o  Documentation Tools (12) o  Build Utilities (5)

Utilities

o  Async, Control Flow, Event (25) o  Class System (16) o  DOM (7) o  Functional Programming (17) o  Math Libraries (12) o  Routing (8) o  Selector Libraries (6)

Applications

o Html5 Applications (10) o Code Editors (23)   

List of languages that compile to JS

https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS

List of languages that compile to JS 200種類以上

o  CoffeeScript Family (& Friends) o  JavaScript Extensions

n  Security enforcing JavaScript n  Static typing n  Synchronous to Asynchronous JavaScript

Compilers (CPS) n  JavaScript Language Extensions

o  Ruby, Python, Perl, Java/JVM, Scala, C# .NET, Lisp Schema, OCaml, Haskell, Smalltalk, C/C++. Basic, Pascal, Go

https://github.com/jashkenas/coffee-script/wiki/ List-of-languages-that-compile-to-JS

o  MultiTarget o  Tierless languages (produce both client

& server) o  Visual programming tools o  Others o  Tools for Compiler Writers

n  JavaScript Parsers and Extensions n  Javascript Optimizers n  Javascript Parser Generators n  Javascript AST, Semantics

About Node.js

Node's goal is to provide an easy way to build scalable network programs http://nodejs.org/about/

o  In the "hello world" web server example below, many client connections can be handled concurrently. Node tells the operating system (through epoll, kqueue, /dev/poll, or select) that it should be notified when a new connection is made, and then it goes to sleep. If someone new connects, then it executes the callback. Each connection is only a small heap allocation.

var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, "127.0.0.1"); console.log('Server running at http://127.0.0.1:1337/');

Node is similar in design to and influenced by systems like Ruby's Event Machine or Python's Twisted. Node takes the event model a bit further—it presents the event loop as a language construct instead of as a library. In other systems there is always a blocking call to start the event-loop. Typically one defines behavior through callbacks at the beginning of a script and at the end starts a server through a blocking call like EventMachine::run(). In Node there is no such start-the-event-loop call. Node simply enters the event loop after executing the input script. Node exits the event loop when there are no more callbacks to perform. This behavior is like browser javascript—the event loop is hidden from the user.

But what about multiple-processor concurrency? Aren't threads necessary to scale programs to multi-core computers? You can start new processes via child_process.fork() these other processes will be scheduled in parallel. For load balancing incoming connections across multiple processes use the cluster module.

Class: ChildProcess

o  ChildProcess is an EventEmitter. o  Child processes always have three streams

associated with them. child.stdin, child.stdout, and child.stderr. These may be shared with the stdio streams of the parent process, or they may be separate stream objects which can be piped to and from.

o  The ChildProcess class is not intended to be used directly. Use the spawn() or fork() methods to create a Child Process instance.

child.send(message, [sendHandle])

var cp = require('child_process'); var n = cp.fork(__dirname + '/sub.js'); n.on('message', function(m) { console.log('PARENT got message:', m); }); n.send({ hello: 'world' });

process.on('message', function(m) { console.log('CHILD got message:', m); }); process.send({ foo: 'bar' });

src/node.cc

int Start(int argc, char *argv[]) { // Hack aroung with the argv pointer. Used for process.title = "blah". argv = uv_setup_args(argc, argv); // Logic to duplicate argv as Init() modifies arguments // that are passed into it. char **argv_copy = copy_argv(argc, argv); // This needs to run *before* V8::Initialize() // Use copy here as to not modify the original argv: Init(argc, argv_copy); V8::Initialize(); { Locker locker; HandleScope handle_scope; // Create the one and only Context. Persistent<Context> context = Context::New(); Context::Scope context_scope(context); process_symbol = NODE_PSYMBOL("process"); domain_symbol = NODE_PSYMBOL("domain");

// Use original argv, as we're just copying values out of it. Handle<Object> process_l = SetupProcessObject(argc, argv); v8_typed_array::AttachBindings(context->Global()); // Create all the objects, load modules, do everything. // so your next reading stop should be node::Load()! Load(process_l); // All our arguments are loaded. We've evaluated all of the scripts. We // might even have created TCP servers. // Now we enter the main eventloop. // If there are no watchers on the loop (except for the ones that were // uv_unref'd) then this function exits. As long as there are active // watchers, it blocks. uv_run(uv_default_loop()); EmitExit(process_l); RunAtExit(); #ifndef NDEBUG context.Dispose(); #endif }

#ifndef NDEBUG // Clean up. Not strictly necessary. V8::Dispose(); #endif // NDEBUG // Clean up the copy: free(argv_copy); return 0; }

deps/uv/include/uv.h

/* * This function must be called before any other functions in libuv. * * All functions besides uv_run() are non-blocking. * * All callbacks in libuv are made asynchronously. That is they are never * made by the function that takes them as a parameter. */ UV_EXTERN uv_loop_t* uv_loop_new(void); UV_EXTERN void uv_loop_delete(uv_loop_t*); /* * Returns the default loop. */ UV_EXTERN uv_loop_t* uv_default_loop(void); /* * This function starts the event loop. It blocks until the reference count * of the loop drops to zero. Always returns zero. */ UV_EXTERN int uv_run(uv_loop_t*);

deps/uv/src/unix/loop.c

int uv__loop_init(uv_loop_t* loop, int default_loop) { #if HAVE_KQUEUE int flags = EVBACKEND_KQUEUE; #else int flags = EVFLAG_AUTO; #endif memset(loop, 0, sizeof(*loop)); RB_INIT(&loop->ares_handles); RB_INIT(&loop->timer_handles); ngx_queue_init(&loop->active_reqs); ngx_queue_init(&loop->idle_handles); ngx_queue_init(&loop->async_handles); ngx_queue_init(&loop->check_handles); ngx_queue_init(&loop->prepare_handles); ngx_queue_init(&loop->handle_queue); loop->closing_handles = NULL; loop->channel = NULL; loop->time = uv_hrtime() / 1000000; loop->async_pipefd[0] = -1; loop->async_pipefd[1] = -1;

loop->ev = (default_loop ? ev_default_loop : ev_loop_new)(flags); ev_set_userdata(loop->ev, loop); eio_channel_init(&loop->uv_eio_channel, loop); #if __linux__ loop->inotify_watchers = NULL; loop->inotify_fd = -1; #endif #if HAVE_PORTS_FS loop->fs_fd = -1; #endif return 0; }

CommonJS

What Server Side JavaScript needs by Kevin Dangoor http://www.blueskyonmars.com/2009/01/29/what-server-side-javascript-needs/

What Server Side JavaScript needs by Kevin Dangoor

o  Server side JavaScript technology has been around for a long time. Netscape offered server side JavaScript in their server software back in 1996, and Helma has existed for a number of years as well. But, server side development has changed a lot over the past few years.

cross-interpreter standard library

o  For example, JavaScript needs a cross-interpreter standard library. Thankfully, some amount of standard library exists (the part inherited from the browsers). So, you get regular expressions and dates. But, what about files and directories? Why can’t the same API be made to work in Rhino, Spidermonkey, V8 and JSCore?

standard way to include other modules

o  JavaScript needs a standard way to include other modules and for those modules to live in discreet namespaces. There are easy ways to do namespaces, but there’s no standard programmatic way to load a module (once!). This is really important, because server side apps can include a lot of code and will likely mix and match parts that meet those standard interfaces.

package up code for deployment and distribution

o  There needs to be a way to package up code for deployment and distribution and further to install packages. Linux people will correctly point out that they can just type “apt get” (or yum, or whatever) and their work is done. But there are a lot of people using Macs and Windows who need a convenient way to get their development environments set up and to package up the code they write for deployment and for other people to use.

package repository

o  Part of the distribution and installation problem is a package repository. I don’t know if JSAN is the answer there, but I do know that an easy way to install a package and its dependencies makes a huge difference in how many libraries people will likely pull together in their apps.

Intel RiverTrail

https://github.com/rivertrail/rivertrail/wiki

RiverTrail o  Stephan Herhut

Richard L. Hudson Jaswanth Sreeram

o  2011年9月 IDF 2011で発表

Presented by Justin Rattner, in IDF 2011

Background

o  The goal of Intel Lab’s River Trail project is to enable data-parallelism in web applications. In a world where the web browser is the user’s window into computing, browser applications must leverage all available computing resources to provide the best possible user experience.

Background

o  Today web applications do not take full advantage of parallel client hardware due to the lack of appropriate programming models.

o  River Trail puts the parallel compute power of client’s hardware into the hands of the web developer while staying within the safe and secure boundaries of the familiar JavaScript programming paradigm.

Background

o  River Trail gently extends JavaScript with simple deterministic data-parallel constructs that are translated at runtime into a low-level hardware abstraction layer. By leveraging multiple CPU cores and vector instructions, River Trail achieves significant speedup over sequential JavaScript.

API Design Three Pillar Approach

o  a type called ParallelArray that holds data values

o  several prototypical methods of ParallelArray that implement parallel constructs like map

o  the concept of an elemental function which is passed to the constructs and typically returns a single data element.

ParallelArray Data Structure

o  We add ParallelArray, a new data type, to JavaScript. It is a read only data structure holding the actual Parallel Array data that is created by a call to a constructor or is returned from a call to one of the ParallelArray prototype methods. Input to the constructor is typically a JavaScript array, a typed array, or a function that is used to generate the ParallelArray’s values.

Prototype Methods

o  ParallelArray comes with the following 5 data parallel methods: map, combine, scan, filter, and scatter. Each of these methods when combined with kernel functions creates new freshly minted ParallelArray.

o  ParallelArray sixth core data parallel method is reduce which can return a scalar value.

Elemental Functions

o  Any JavaScript function with an appropriate signature can be used as an elemental function. It is the responsibility of the system to determine if the elemental function can be optimized to take advantage of the data parallel hardware. If optimization is not possible the function is simple executed sequentially.

Dart: A modern web language

Kasper Lund http://www.infoq.com/presentations/Dart-A-Modern-Web-Language

The rise of JavaScript

Why is the web hard to program for?

o  Writing large well-performing applications is hard

o  Hard to reason about the program structure

o  Startup performance is often really bad o  Difficult to document intent (lack of

types) o  No support for modules, packages, or

libraries

So why are we building Dart?

o  We want to improve the web platform n  Better support for programming in the large n  Faster application startup in particular on

mobile n  More predictable and better runtime

performance n  JavaScript is a powerful tool but it has sharp

edges o  Keep up the innovation momentum

n  The web is evolving at a fantastic pace! n  The developer tools have to keep up

JavaScript is full of ... surprises

o  Lots and lots of implicit type conversions o  Most operations produce weird results

when passed wrong or uninitialized values instead of failing in a recognizable way

Keep on truckin'

No argument type checking var x = 42; assert(x + null == 42); assert(x + [] == 42); assert(isNaN(x + undefined)); assert(isNaN(x - {})); No array bounds checking var array = new Array(32); ... assert(array[32] === undefined); assert(array[-1] === undefined); assert(array[.1] === undefined); assert(array[null] === undefined); assert(array[array] === undefined);

JavaScript has improved but ... o  JavaScript has fundamental issues at the

language level that impact productivity o  Performance has improved but mostly

for a pretty static subset of JavaScript o  It remains very time consuming to build

and maintain large web apps

What is Dart?

o  Unsurprising object-oriented programming language

o  Class-based single inheritance with interfaces

o  Familiar syntax with proper lexical scoping

o  Single-threaded with isolate-based concurrency

o  Optional static types

Conventional type checking

o  Tries to prove that your program obeys the type system

o  Considers it a fatal error no proof can be constructed

o  In Dart, you are innocent until proven guilty...

List<Apple> apples = tree.pickApples(); printFruits(apples); void printFruits(List<Fruit> fruits) {     for (Fruit each in fruits) print(each); }

Optional static types

o  Static types convey the intent of the programmer

o  Checkable documentation for code and interfaces

o  Avoids awkward variable naming or comment schemes

o  Type annotations have no effect on runtime semantics.

Dart virtual machine

o  Dart has been designed for performance n  Simplicity gives more performance

headroom n  Enforced structure leads to better

predictability n  Virtual machine performs better than V8 at

launch o  Works standalone or embedded in

browser n  Experimental Dart-enabled build of

Chromium n  SDK includes preliminary server-side librarie

Snapshots

o  Snapshots contain serialized program structures n  Cyclic graph of classes, interfaces, and

statics n  Can be read in without parsing source code n  improve startup performance by more than

10x o  Snapshots can be generated server-side

or client-side n  Platform independent format sent over the

wire n  Can be cached locally in browser app cache

Dart-to-JavaScript o  Compiler is implemented in Dart

n  Generates JavaScript that runs in modern browsers

n  Built for future optimizations (type inferencing, etc.)

n  Uses tree shaking to cut down on code size

Dart Frequently Asked Questions

http://www.dartlang.org/support/faq.html#why-dart

Dart Frequently Asked Questions

http://www.dartlang.org/support/faq.html#why-dart

Why Dart?

o  At Google we've written our share of web apps, and we've tried in many ways to make improvements to that development process, short of introducing a new language. Now we think it's time to take that leap. We designed Dart to be easy to write development tools for, well-suited to modern app development, and capable of high-performance implementations.

Is the language really what needs to be fixed in web development?

o  We want to fix ALL the things. There's "Dart" the language, and then there's "Dart" the overall project. The Dart project is betting that the language needs some changes, but we also want to improve the DOM and other libraries, and to improve the tools we use.

o  At the same time, Google is also placing bets that JavaScript can be evolved as needed, and contributing to that work. Google wants web development to be great, and if that happens with JavaScript, we're happy.

Is Dart going to divert community effort from JavaScript-based web development?

o  If people like Dart and use it, then to a certain extent, yes, but isn't this true of any improvement to existing web development? Nothing is zero-effort to learn or 100% back-compatible to legacy browsers, so people use both new and old. You might look at it this way: Google is putting significant effort behind both Dart and JavaScript, choosing to develop Dart while at the same time using JavaScript extensively, and working on JavaScript tools, implementation, and language spec. We're doing both because we think Dart is worth it.

o  Server-side web programming finds room for many languages: does Python divert effort from Perl, and does Java undercut C++? Again, to a certain extent, yes they do, but people generally consider that a healthy situation, better than if we all used a single programming language. Multiple languages have allowed for faster change than any single language has achieved through a standards process. Furthermore, languages coexist in different niches: does Groovy really compete directly with C++? People face different engineering tradeoffs and choose different languages to meet them. Ultimately, we think client-side developers should have this kind of flexibility.

Why didn't Google make Dart an open standard right from the start?

o  We're taking the usual route to get to an open-standard programming language: someone creates a coherent first version, people experiment with it, and we standardize later. The open standard web platform has been known to add other pieces this way, where standardization follows after a vendor experiment: canvas, for example. We understand that this route raises concerns, but we think it is sometimes useful, and in particular that it is useful for programming languages, where design by committee is risky.

o  The most recent successful language designed by an open committee was Haskell, starting in 1990. The most widely used was COBOL, followed by Ada. It's not a common way to do language design. Among dozens and dozens of major languages, six (give or take a couple of debatables) were designed this way. (And one of those six was ALGOL-68.)

Is it really a dynamic language if it doesn't have eval() or adding fields to a value at run time?

o  Dart as initially released didn't have anything like these, but future versions of Dart will look at adding dynamic features of this sort. The feature set won't match up exactly with the features in your question, but we hope to serve very much the same purposes. When we see what gets added, then everyone can decide how they classify the language.

Why do type annotations have no effect on the runtime behavior?

o  If type annotations affect the runtime, programs will change their behavior as programmers add type information, even though the logic remains unchanged. The normal mode of development is to gradually add types for documentation and validation, and if that changes what the program does, programmers have no stable foundation to work on. This is especially true given that types could be inaccurate.

o  In addition, this policy helps us and others add additional type-checking tools that implement different policies without unforeseen interactions with the runtime.