SlideShare uma empresa Scribd logo
1 de 30
Baixar para ler offline
Exploring DLR
     江嘉诚
    2011.8.28
关于我
•   江嘉诚 (无厚之刃)
•   华南理工大学
•   微博:@以无厚入有间 ( 典故参见《庄子》)
•   博客:http://sharp-blade.tuita.com/
DLR是
•   Dynamic Language Runtime
•   由 IronPython 发起人Jim Hugunin开发
•   一个构建在CLR之上的运行时
•   在.Net上构建动态语言的标准体系

The DLR's mission is to enable an ecosystem of
dynamic languages on .NET.
动态语言需要什么
• Lexer & Parser

•   交互式脚本引擎(REPL)
•   动态加载代码的能力
•   动态类型
•   元编程(自省/魔术方法/动态修改类型)

• 其它:Stackless/Actor/Continuation
DLR提供了什么
•   脚本语言引擎
•   可以在运行时编译的表达式树
•   延迟绑定
•   动态语言的互操作性
ExpressionTree
ExpressionTree : Hello World

Console.WriteLine(“Hello World”);

using System.Linq.Expressions;

MethodInfo method = typeof (Console)
       .GetMethod( "WriteLine", new Type[] { typeof(string) } );

Expression call = Expression.Call(null, method,
         Expression.Constant("Hello World")) ;

Action callDelegate = Expression.Lambda<Action>(call).Compile();
callDelegate();
ExpressionTree : Binary Expression

3+5

BinaryExpression add = Expression.Add(Expression.Constant(3),
                    Expression.Constant(5));

Func<int> addDelegate = Expression.Lambda<Func<int>>(add).Compile();

Console.WriteLine("{0}", addDelegate());
ExpressionTree : Index Expression
int[] list = { 1, 2, 3 };
list [1] = 4;
int[] list = { 1, 2, 3 };
IndexExpression index = Expression.ArrayAccess(
  Expression.Constant(list),
  Expression.Constant(1));

Expression indexAccess = Expression.Assign(index,
         Expression.Constant(4));

Action indexAccessDelegate =
         Expression.Lambda<Action>(indexAccess).Compile();
indexAccessDelegate();
ExpressionTree : IfThenElse Expression
if (true) Console.WriteLine("true");
else Console.WriteLine("false");
Expression ifExpression = Expression.IfThenElse(
   Expression.Constant(true),
   Expression.Call(null,
     typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }),
     Expression.Constant("true")),
   Expression.Call(null,
     typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }),
     Expression.Constant("false"))
);

Action ifDelegate = Expression.Lambda<Action>(ifExpression).Compile();
ifDelegate();
ExpressionTree : LambdaExpression
Func<int, int, int> add = (x, y) => { return x + y; };
int result = add(3, 5);
Console.WriteLine("result is {0}", result);

ParameterExpression x = Expression.Parameter(typeof(int), "x");
ParameterExpression y = Expression.Parameter(typeof(int), "y");

Expression<Func<int, int, int>> add = Expression
  .Lambda<Func<int, int, int>>(Expression.Add(x, y), x, y);

int result = add.Compile()(3, 5);
Console.WriteLine("result is {0}", result);
代码即数据

数据即代码
Dynamic & Late Binding
Foo foo = new Foo();
foo.act();
dynamic foo = …… // new Foo()
foo.act();
Dynamic语法的绑定过程
dynamic num = 5;
int result = num + 2;
CallSite<Func<CallSite, object, int>> Site1;
CallSite<Func<CallSite, object, int, object>> Site2;
object num = 5;
if (Site1 == null)
{
   Site1 = CallSite<Func<CallSite, object, int>>
      .Create(
         Binder.Convert(
           CSharpBinderFlags.None,
           typeof(int),
           typeof(Program)));
}
Dynamic & Late Binding
Func<CallSite, object, int> convert = Site1.Target;
CallSite add = Site1;

if (Site2 == null)
{
   Site2 = CallSite<Func<CallSite, object, int, object>>
      .Create(
      Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(
        CSharpBinderFlags.None,
        ExpressionType.Add,
        typeof(Program), ...));
}
int result = convert(add, Site2.Target(Site2, num, 2));
Dynamic语法的绑定过程
dynamic num = 5;
int result = num + 2;
CallSite<Func<CallSite, object, int>> Site1;
CallSite<Func<CallSite, object, int, object>> Site2;
object num = 5;
if (Site1 == null) {
   Site1 = CallSite<Func<CallSite, object, int>>
      .Create(
         Binder.Convert(
           CSharpBinderFlags.None,
           typeof(int),
           typeof(Program)));
}
Dynamic & Late Binding
Func<CallSite, object, int> convert = Site1.Target;

if (Site2 == null)
{
   Site2 = CallSite<Func<CallSite, object, int, object>>
      .Create(
         Binder.BinaryOperation(
         CSharpBinderFlags.None,
         ExpressionType.Add,
         typeof(Program), ...));
}

int result = convert(Site1, Site2.Target(Site2, num, 2));
绑定中发生了什么?
• 绑定主要由Binder完成
• 绑定在不同语言中是不同的,这里C#编译器使用了自己的
  Binder
• 绑定是昂贵的,结果会被缓存起来
• Target(L0) => CallSite(L1) =>Binder (L2)

• 动态类型的对象可以实现自己的绑定行为
• 这种动态行为通过实现IDynamicMetaObjectProvider来
  告诉编译器
• 通常可以使用DynamicObject和ExpandoObject
ExpandoObject
dynamic any = new ExpandoObject();

any.prop = 100;
any.prop = "hello";

any.action = new Func<int>(() => { return 99 + 1; });
Console.WriteLine(any.action());

foreach (var member in (IDictionary<String, Object>)any)
{
  Console.WriteLine(member.Key + ": " + member.Value);
}
ExpandoObject
((INotifyPropertyChanged) any).PropertyChanged +=
    delegate(object sender, PropertyChangedEventArgs e)
       {
          Console.WriteLine("属性{0} 已更改", .PropertyName);
       };

any.name = "某";
any.age = 30;
any.email = "xxx@gmail.com";
Method Missing
users.getByMail(“john@gmail.com”)
自动从用户表中找到Mail为john@gmail.com的用户
在C#中通过继承DynamicObject,并override其方法来实现具
体行为。
•   TryGetMember         •   TryUnaryOperation
•   TrySetMember         •   TryGetIndex
•   TryDeleteMember      •   TrySetIndex
•   TryInvokeMember      •   TryDeleteIndex
•   TryConvert
•   TryCreateInstance    • GetDynamicMemberNames
•   TryInvoke
•   TryBinaryOperation
Method Missing
 public class AnyDynamicObject : DynamicObject
{
     public override bool TryGetMember(GetMemberBinder binder, out object
result)
     {
        Console.WriteLine("Shit happens,{0}属性被调用了", binder.Name);
        result = "no value";
        return true;
     }

      public override bool TrySetMember(SetMemberBinder binder, object value)
      {
        Console.WriteLine("Shit happens,{0}属性被赋值了", binder.Name);
        return true;
      }
  }
Method Missing

dynamic any = new AnyDynamicObject();
Console.WriteLine(any.name);
any.age = 100;




        Shit happens,name属性被调用了
        no value
        Shit happens,age属性被赋值了
调用Python引擎
example.py :
                                     引用:
def addPrice(x, y):                     IronPython.dll
       return x + y                     IronPython.Modules.dll
                                        Microsoft.Dynamic.dll
class User(object):
                                        Microsoft.Scripting.dll
  def __init__(self, name, email):
    self.Name = name
    self.AEmail = email

 def say(self):
        print "hello"

bob = User("bob", "x@gmail.com")
调用Python引擎
 ScriptEngine pyEngine =
        IronPython.Hosting.Python.CreateEngine();
ScriptScope scope = pyEngine.ExecuteFile("example.py");

Func<dynamic, dynamic, int> add = scope.GetVariable("add");
Console.WriteLine(add(2,5));

dynamic bob = scope.GetVariable("bob");
Console.WriteLine(bob.Name);
bob.say();

7
bob
hello
为什么Dynamic不能拯救世界
谁真正需要Dynamic/DLR
•   轻量级ORM
•   MSBuild
•   模板引擎
•   解释器/表达式引擎
•   编译正则表达式
•   调用COM
•   替代Reflection.Emit的其它场合
•   构建DSL (Antlr + DLR)
Reference
IronPython & IronRuby:
https://github.com/IronLanguages

利用DLR + Antlr快速构建DSL:
DLR - Build Your Own Language (without tears)

利用IronRuby开发WPF应用:
http://www.infoq.com/cn/articles/ironruby-wpf

Iron语言相关书籍:
IronPython in Action
IronRuby Unleashed

Graph#演示工具:
http://graphsharp.codeplex.com/
Reference
IronJS:
https://github.com/fholm/IronJS

DLR应用案例:
https://github.com/IronLanguages/main/wiki/IronLanguage-
usages

浏览器中体验IronPython编程:
http://www.trypython.org/

浏览器中使用Python代替Javascript:
http://visitmix.com/labs/gestalt/
Dlr

Mais conteúdo relacionado

Mais procurados

React Native One Day
React Native One DayReact Native One Day
React Native One DayTroy Miles
 
Testing Backbone applications with Jasmine
Testing Backbone applications with JasmineTesting Backbone applications with Jasmine
Testing Backbone applications with JasmineLeon van der Grient
 
Codegeneration With Xtend
Codegeneration With XtendCodegeneration With Xtend
Codegeneration With XtendSven Efftinge
 
descriptive programming
descriptive programmingdescriptive programming
descriptive programmingAnand Dhana
 
React Native Evening
React Native EveningReact Native Evening
React Native EveningTroy Miles
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptStoyan Stefanov
 
GR8Conf 2011: GPars
GR8Conf 2011: GParsGR8Conf 2011: GPars
GR8Conf 2011: GParsGR8Conf
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Dhaval Dalal
 
Letswift19-clean-architecture
Letswift19-clean-architectureLetswift19-clean-architecture
Letswift19-clean-architectureJung Kim
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingCodemotion
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기Arawn Park
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptDonald Sipe
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?intelliyole
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016Codemotion
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinKai Koenig
 
Say Hello To Ecmascript 5
Say Hello To Ecmascript 5Say Hello To Ecmascript 5
Say Hello To Ecmascript 5Juriy Zaytsev
 

Mais procurados (20)

React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
Testing Backbone applications with Jasmine
Testing Backbone applications with JasmineTesting Backbone applications with Jasmine
Testing Backbone applications with Jasmine
 
Codegeneration With Xtend
Codegeneration With XtendCodegeneration With Xtend
Codegeneration With Xtend
 
descriptive programming
descriptive programmingdescriptive programming
descriptive programming
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 
GR8Conf 2011: GPars
GR8Conf 2011: GParsGR8Conf 2011: GPars
GR8Conf 2011: GPars
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
 
Letswift19-clean-architecture
Letswift19-clean-architectureLetswift19-clean-architecture
Letswift19-clean-architecture
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with Kotlin
 
Say Hello To Ecmascript 5
Say Hello To Ecmascript 5Say Hello To Ecmascript 5
Say Hello To Ecmascript 5
 
Bottom Up
Bottom UpBottom Up
Bottom Up
 

Destaque

Trabalho de ciencias da thayna
Trabalho de ciencias da thaynaTrabalho de ciencias da thayna
Trabalho de ciencias da thaynapptmeirelles
 
Projecte audiovisaul Illa TV: formem bons comunicadors
Projecte audiovisaul Illa TV: formem bons comunicadorsProjecte audiovisaul Illa TV: formem bons comunicadors
Projecte audiovisaul Illa TV: formem bons comunicadorsvipremitic
 
Communique yopps lentreprisealereconnectee
Communique yopps lentreprisealereconnecteeCommunique yopps lentreprisealereconnectee
Communique yopps lentreprisealereconnecteeYael Rozencwajg
 
管好你的知识
管好你的知识管好你的知识
管好你的知识Tae Han
 
Market Awareness Overview Presentation
Market Awareness Overview PresentationMarket Awareness Overview Presentation
Market Awareness Overview Presentationmarketawareness6
 
Sensibilización+mediación+09+1º+eso+
Sensibilización+mediación+09+1º+eso+Sensibilización+mediación+09+1º+eso+
Sensibilización+mediación+09+1º+eso+Monica Lopez
 
Wolfs Projectpresentatie
Wolfs ProjectpresentatieWolfs Projectpresentatie
Wolfs Projectpresentatiemarinuswolfs
 
Wolfs linkedin projectpresentatie
Wolfs linkedin projectpresentatieWolfs linkedin projectpresentatie
Wolfs linkedin projectpresentatiemarinuswolfs
 
Progression from east norfolk magazine
Progression from east norfolk magazineProgression from east norfolk magazine
Progression from east norfolk magazinemammal90
 
Recerca acadèmica en temps d'internet
Recerca acadèmica en temps d'internetRecerca acadèmica en temps d'internet
Recerca acadèmica en temps d'internetMargalida Castells
 
Presentación (como vamos)diciembre
Presentación (como vamos)diciembrePresentación (como vamos)diciembre
Presentación (como vamos)diciembreeutanacido
 
1er Semestre 2012
1er Semestre 20121er Semestre 2012
1er Semestre 2012TOURE.BIZ
 
Foursquare for Business & Retail
Foursquare for Business & RetailFoursquare for Business & Retail
Foursquare for Business & RetailBWEST Interactive
 
Leverage Social Media to Build Blog Community - Wordcamp Victoria
Leverage Social Media to Build Blog Community - Wordcamp Victoria Leverage Social Media to Build Blog Community - Wordcamp Victoria
Leverage Social Media to Build Blog Community - Wordcamp Victoria BWEST Interactive
 
Nadya ip 9ci
Nadya ip 9ciNadya ip 9ci
Nadya ip 9cinadyaipi
 
Q U E B E C Magnifique.Jpg
Q U E B E C  Magnifique.JpgQ U E B E C  Magnifique.Jpg
Q U E B E C Magnifique.JpgVeronikStan
 
El treball col·laboratiu en xarxa. Eines 2.0 per a projectes culturals
El treball col·laboratiu en xarxa. Eines 2.0 per a projectes culturalsEl treball col·laboratiu en xarxa. Eines 2.0 per a projectes culturals
El treball col·laboratiu en xarxa. Eines 2.0 per a projectes culturalsMargalida Castells
 

Destaque (20)

Trabalho de ciencias da thayna
Trabalho de ciencias da thaynaTrabalho de ciencias da thayna
Trabalho de ciencias da thayna
 
Projecte audiovisaul Illa TV: formem bons comunicadors
Projecte audiovisaul Illa TV: formem bons comunicadorsProjecte audiovisaul Illa TV: formem bons comunicadors
Projecte audiovisaul Illa TV: formem bons comunicadors
 
Communique yopps lentreprisealereconnectee
Communique yopps lentreprisealereconnecteeCommunique yopps lentreprisealereconnectee
Communique yopps lentreprisealereconnectee
 
管好你的知识
管好你的知识管好你的知识
管好你的知识
 
Market Awareness Overview Presentation
Market Awareness Overview PresentationMarket Awareness Overview Presentation
Market Awareness Overview Presentation
 
Sensibilización+mediación+09+1º+eso+
Sensibilización+mediación+09+1º+eso+Sensibilización+mediación+09+1º+eso+
Sensibilización+mediación+09+1º+eso+
 
Wolfs Projectpresentatie
Wolfs ProjectpresentatieWolfs Projectpresentatie
Wolfs Projectpresentatie
 
Wolfs linkedin projectpresentatie
Wolfs linkedin projectpresentatieWolfs linkedin projectpresentatie
Wolfs linkedin projectpresentatie
 
Progression from east norfolk magazine
Progression from east norfolk magazineProgression from east norfolk magazine
Progression from east norfolk magazine
 
Recerca acadèmica en temps d'internet
Recerca acadèmica en temps d'internetRecerca acadèmica en temps d'internet
Recerca acadèmica en temps d'internet
 
Presentación (como vamos)diciembre
Presentación (como vamos)diciembrePresentación (como vamos)diciembre
Presentación (como vamos)diciembre
 
1er Semestre 2012
1er Semestre 20121er Semestre 2012
1er Semestre 2012
 
Basic mm
Basic mmBasic mm
Basic mm
 
Foursquare for Business & Retail
Foursquare for Business & RetailFoursquare for Business & Retail
Foursquare for Business & Retail
 
Leverage Social Media to Build Blog Community - Wordcamp Victoria
Leverage Social Media to Build Blog Community - Wordcamp Victoria Leverage Social Media to Build Blog Community - Wordcamp Victoria
Leverage Social Media to Build Blog Community - Wordcamp Victoria
 
Nadya ip 9ci
Nadya ip 9ciNadya ip 9ci
Nadya ip 9ci
 
Q U E B E C Magnifique.Jpg
Q U E B E C  Magnifique.JpgQ U E B E C  Magnifique.Jpg
Q U E B E C Magnifique.Jpg
 
Aula inaugural
Aula inauguralAula inaugural
Aula inaugural
 
El treball col·laboratiu en xarxa. Eines 2.0 per a projectes culturals
El treball col·laboratiu en xarxa. Eines 2.0 per a projectes culturalsEl treball col·laboratiu en xarxa. Eines 2.0 per a projectes culturals
El treball col·laboratiu en xarxa. Eines 2.0 per a projectes culturals
 
Elecciones al Consejo Escolar
Elecciones al Consejo EscolarElecciones al Consejo Escolar
Elecciones al Consejo Escolar
 

Semelhante a Dlr

Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Vagif Abilov
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
HashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureHashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureNicolas Corrarello
 
The Challenge of Bringing FEZ to PlayStation Platforms
The Challenge of Bringing FEZ to PlayStation PlatformsThe Challenge of Bringing FEZ to PlayStation Platforms
The Challenge of Bringing FEZ to PlayStation PlatformsMiguel Angel Horna
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldChristian Melchior
 
IronPython and Dynamic Languages on .NET by Mahesh Prakriya
 IronPython and Dynamic Languages on .NET by Mahesh Prakriya IronPython and Dynamic Languages on .NET by Mahesh Prakriya
IronPython and Dynamic Languages on .NET by Mahesh Prakriyacodebits
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript EverywherePascal Rettig
 
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...Stefan Marr
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
Building High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterBuilding High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterMithun T. Dhar
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationIvan Dolgushin
 
Java script Techniques Part I
Java script Techniques Part IJava script Techniques Part I
Java script Techniques Part ILuis Atencio
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)Piyush Katariya
 
Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011Jimmy Schementi
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 

Semelhante a Dlr (20)

Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
HashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureHashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin Infrastructure
 
The Challenge of Bringing FEZ to PlayStation Platforms
The Challenge of Bringing FEZ to PlayStation PlatformsThe Challenge of Bringing FEZ to PlayStation Platforms
The Challenge of Bringing FEZ to PlayStation Platforms
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
 
IronPython and Dynamic Languages on .NET by Mahesh Prakriya
 IronPython and Dynamic Languages on .NET by Mahesh Prakriya IronPython and Dynamic Languages on .NET by Mahesh Prakriya
IronPython and Dynamic Languages on .NET by Mahesh Prakriya
 
Dynamic C#
Dynamic C# Dynamic C#
Dynamic C#
 
обзор Python
обзор Pythonобзор Python
обзор Python
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
Clean code
Clean codeClean code
Clean code
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Building High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterBuilding High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 Firestarter
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code Generation
 
Java script Techniques Part I
Java script Techniques Part IJava script Techniques Part I
Java script Techniques Part I
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 

Último

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 

Último (20)

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

Dlr

  • 1. Exploring DLR 江嘉诚 2011.8.28
  • 2. 关于我 • 江嘉诚 (无厚之刃) • 华南理工大学 • 微博:@以无厚入有间 ( 典故参见《庄子》) • 博客:http://sharp-blade.tuita.com/
  • 3. DLR是 • Dynamic Language Runtime • 由 IronPython 发起人Jim Hugunin开发 • 一个构建在CLR之上的运行时 • 在.Net上构建动态语言的标准体系 The DLR's mission is to enable an ecosystem of dynamic languages on .NET.
  • 4. 动态语言需要什么 • Lexer & Parser • 交互式脚本引擎(REPL) • 动态加载代码的能力 • 动态类型 • 元编程(自省/魔术方法/动态修改类型) • 其它:Stackless/Actor/Continuation
  • 5. DLR提供了什么 • 脚本语言引擎 • 可以在运行时编译的表达式树 • 延迟绑定 • 动态语言的互操作性
  • 7. ExpressionTree : Hello World Console.WriteLine(“Hello World”); using System.Linq.Expressions; MethodInfo method = typeof (Console) .GetMethod( "WriteLine", new Type[] { typeof(string) } ); Expression call = Expression.Call(null, method, Expression.Constant("Hello World")) ; Action callDelegate = Expression.Lambda<Action>(call).Compile(); callDelegate();
  • 8. ExpressionTree : Binary Expression 3+5 BinaryExpression add = Expression.Add(Expression.Constant(3), Expression.Constant(5)); Func<int> addDelegate = Expression.Lambda<Func<int>>(add).Compile(); Console.WriteLine("{0}", addDelegate());
  • 9. ExpressionTree : Index Expression int[] list = { 1, 2, 3 }; list [1] = 4; int[] list = { 1, 2, 3 }; IndexExpression index = Expression.ArrayAccess( Expression.Constant(list), Expression.Constant(1)); Expression indexAccess = Expression.Assign(index, Expression.Constant(4)); Action indexAccessDelegate = Expression.Lambda<Action>(indexAccess).Compile(); indexAccessDelegate();
  • 10. ExpressionTree : IfThenElse Expression if (true) Console.WriteLine("true"); else Console.WriteLine("false"); Expression ifExpression = Expression.IfThenElse( Expression.Constant(true), Expression.Call(null, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }), Expression.Constant("true")), Expression.Call(null, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }), Expression.Constant("false")) ); Action ifDelegate = Expression.Lambda<Action>(ifExpression).Compile(); ifDelegate();
  • 11. ExpressionTree : LambdaExpression Func<int, int, int> add = (x, y) => { return x + y; }; int result = add(3, 5); Console.WriteLine("result is {0}", result); ParameterExpression x = Expression.Parameter(typeof(int), "x"); ParameterExpression y = Expression.Parameter(typeof(int), "y"); Expression<Func<int, int, int>> add = Expression .Lambda<Func<int, int, int>>(Expression.Add(x, y), x, y); int result = add.Compile()(3, 5); Console.WriteLine("result is {0}", result);
  • 13. Dynamic & Late Binding Foo foo = new Foo(); foo.act(); dynamic foo = …… // new Foo() foo.act();
  • 14. Dynamic语法的绑定过程 dynamic num = 5; int result = num + 2; CallSite<Func<CallSite, object, int>> Site1; CallSite<Func<CallSite, object, int, object>> Site2; object num = 5; if (Site1 == null) { Site1 = CallSite<Func<CallSite, object, int>> .Create( Binder.Convert( CSharpBinderFlags.None, typeof(int), typeof(Program))); }
  • 15. Dynamic & Late Binding Func<CallSite, object, int> convert = Site1.Target; CallSite add = Site1; if (Site2 == null) { Site2 = CallSite<Func<CallSite, object, int, object>> .Create( Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation( CSharpBinderFlags.None, ExpressionType.Add, typeof(Program), ...)); } int result = convert(add, Site2.Target(Site2, num, 2));
  • 16. Dynamic语法的绑定过程 dynamic num = 5; int result = num + 2; CallSite<Func<CallSite, object, int>> Site1; CallSite<Func<CallSite, object, int, object>> Site2; object num = 5; if (Site1 == null) { Site1 = CallSite<Func<CallSite, object, int>> .Create( Binder.Convert( CSharpBinderFlags.None, typeof(int), typeof(Program))); }
  • 17. Dynamic & Late Binding Func<CallSite, object, int> convert = Site1.Target; if (Site2 == null) { Site2 = CallSite<Func<CallSite, object, int, object>> .Create( Binder.BinaryOperation( CSharpBinderFlags.None, ExpressionType.Add, typeof(Program), ...)); } int result = convert(Site1, Site2.Target(Site2, num, 2));
  • 18. 绑定中发生了什么? • 绑定主要由Binder完成 • 绑定在不同语言中是不同的,这里C#编译器使用了自己的 Binder • 绑定是昂贵的,结果会被缓存起来 • Target(L0) => CallSite(L1) =>Binder (L2) • 动态类型的对象可以实现自己的绑定行为 • 这种动态行为通过实现IDynamicMetaObjectProvider来 告诉编译器 • 通常可以使用DynamicObject和ExpandoObject
  • 19. ExpandoObject dynamic any = new ExpandoObject(); any.prop = 100; any.prop = "hello"; any.action = new Func<int>(() => { return 99 + 1; }); Console.WriteLine(any.action()); foreach (var member in (IDictionary<String, Object>)any) { Console.WriteLine(member.Key + ": " + member.Value); }
  • 20. ExpandoObject ((INotifyPropertyChanged) any).PropertyChanged += delegate(object sender, PropertyChangedEventArgs e) { Console.WriteLine("属性{0} 已更改", .PropertyName); }; any.name = "某"; any.age = 30; any.email = "xxx@gmail.com";
  • 21. Method Missing users.getByMail(“john@gmail.com”) 自动从用户表中找到Mail为john@gmail.com的用户 在C#中通过继承DynamicObject,并override其方法来实现具 体行为。 • TryGetMember • TryUnaryOperation • TrySetMember • TryGetIndex • TryDeleteMember • TrySetIndex • TryInvokeMember • TryDeleteIndex • TryConvert • TryCreateInstance • GetDynamicMemberNames • TryInvoke • TryBinaryOperation
  • 22. Method Missing public class AnyDynamicObject : DynamicObject { public override bool TryGetMember(GetMemberBinder binder, out object result) { Console.WriteLine("Shit happens,{0}属性被调用了", binder.Name); result = "no value"; return true; } public override bool TrySetMember(SetMemberBinder binder, object value) { Console.WriteLine("Shit happens,{0}属性被赋值了", binder.Name); return true; } }
  • 23. Method Missing dynamic any = new AnyDynamicObject(); Console.WriteLine(any.name); any.age = 100; Shit happens,name属性被调用了 no value Shit happens,age属性被赋值了
  • 24. 调用Python引擎 example.py : 引用: def addPrice(x, y): IronPython.dll return x + y IronPython.Modules.dll Microsoft.Dynamic.dll class User(object): Microsoft.Scripting.dll def __init__(self, name, email): self.Name = name self.AEmail = email def say(self): print "hello" bob = User("bob", "x@gmail.com")
  • 25. 调用Python引擎 ScriptEngine pyEngine = IronPython.Hosting.Python.CreateEngine(); ScriptScope scope = pyEngine.ExecuteFile("example.py"); Func<dynamic, dynamic, int> add = scope.GetVariable("add"); Console.WriteLine(add(2,5)); dynamic bob = scope.GetVariable("bob"); Console.WriteLine(bob.Name); bob.say(); 7 bob hello
  • 27. 谁真正需要Dynamic/DLR • 轻量级ORM • MSBuild • 模板引擎 • 解释器/表达式引擎 • 编译正则表达式 • 调用COM • 替代Reflection.Emit的其它场合 • 构建DSL (Antlr + DLR)
  • 28. Reference IronPython & IronRuby: https://github.com/IronLanguages 利用DLR + Antlr快速构建DSL: DLR - Build Your Own Language (without tears) 利用IronRuby开发WPF应用: http://www.infoq.com/cn/articles/ironruby-wpf Iron语言相关书籍: IronPython in Action IronRuby Unleashed Graph#演示工具: http://graphsharp.codeplex.com/