Semana Interop: Trabalhando com IronPython e com Ironruby
-
Upload
alessandro-binhara -
Category
Technology
-
view
441 -
download
1
description
Transcript of Semana Interop: Trabalhando com IronPython e com Ironruby
Trabalhando com IronPython e com IronRuby
Palestrantes
Alessandro de Oliveira BinharaMestre em Projetos Complexos pela UTFPRDiretor de Tecnologia da Marketing Card do BrasilDesenvolvedor MonoBasic, CSDO, LifeLet´sFundador Projeto Mono Brasil
Giovanni BassiConsultor IndependenteScrumMaster CertifiedMicrosoft MVP C#
3
Compilado x Interpretado
− O C# tem tipagem forte com verificação de tipo em tempo de compilação type safety− C# o compilador lê o código , realiza a
verificação de tipos e gera o IL− O python tem tipagem fraca com tipos
e objetos dinâmicos em tempo de execução− O Python lê o fonte compila
dinâmicamente gerando o IL. O tipos podem mudar em memória durante a execução.
4
Estático x Dinâmico
DynamicLanguages
Simple and succinct
Implicitly typed
Meta-programming
No compilation
Late bound
Loosely type
Highly expressive
StaticLanguages
Robust
Performant
Intelligent tools
Better scaling
Type safetyCompile-time
checkingRunTime
Performance
5
CaracterísticasLinguagem Tipagem Compilação Objetos Tipos
C# Forte Estática Estáticos Estáticos
VB.NET Forte ou Fraca
Estática Estáticos Dinânicos
Boo Forte Dinâmica Dinâmicos Dinâmicos
Python Fraca Dinâmica Dinâmicos Dinâmicos
Ruby Fraca Dinâmica Dinâmicos Dinâmicos
6
Boo− Rodrigo Bamboo
− Desenvolvedor Python− Criador da Linguagem Boo http://boo.codehaus.org/
Um linguagem que combina características C# e PythonLinguagem Script fortemente tipada com inferência de tipos dinâmicosPossibilidade de criação de macros em tempo de compilação através de
uma pipeline de compilação plugável
− Type Inference , Builtin Literals for lists, hashes, arrays, regular expressions and timespans, Slicing
− String Interpolation, Syntactic Macros, − Generators − Generator Expressions, List Generators, [Array Generators], Generator Methods− First Class Functions − Functions As Objects− Closures, Callable Types, Duck Typing− Extensible Compilation Pipeline− Interactive Interpreter
7
Por que Python?
− Os conceitos fundamentais da linguagem são simples − A sintaxe é clara e fácil de aprender; − O código curto e legível.− Os tipos pré-definidos são poderosos, − Possui um interpretador de comandos interativo − Python é expressivo, com abstrações de alto nível.− Apresenta potencial de defeitos reduzido - menos código,
menos oportunidade para errar. − Existe suporte para uma diversidade grande de bibliotecas
externas. − É possível escrever extensões a Python em C e C++ − Python permite que o programa execute inalterado em
múltiplas plataformas; − Python é livre
8
Por que Python?
−Regra KISS, Simples, fácil de ensinar e aprender
print “Alo mundo”
9
O que é Python
− É uma linguagem interpretada. − Não há pré-declaração de variáveis, e os
tipos das variáveis são determinados dinamicamente.
− O controle de bloco é feito apenas por indentação;
− Oferece tipos de alto nível: − strings, listas, tuplas, dicionários, arquivos,
classes. − É orientada a objetos; aliás, em Python,
tudo é um objeto.
10
TimeLine
− Projeto iniciou em Dez 1989− Primeiro versão pública(USENET) - Feb
1991− Site python.org - 1996 or 1997− 2.0 disponível - 2000− Python Software Foundation - 2001− …− 2.4 disponível - 2004− 2.5 disponível - 2006
11
Boas idéias do Python
− Sem checagem de tipos no compilador
− Tipos Dinâmicos− Tudo é objeto− Tudo pode ser inspecionado− Prompt interativo
12
http://www.codeplex.com/IronPython
13
Inspiração“The speed of the current system is so low as to render the
current implementation useless for anything beyond demonstration purposes.” – ActiveState’s report on Python for .NET
“The CLI is, by design, not friendly to dynamic languages. Prototypes were built, but ran way too slowly.”
– Jon Udell, InfoWorld, Aug. 2003
− How could Microsoft have screwed up so badly that the CLR is far worse than the JVM for dynamic languages?− Jython shows that dynamic languages can run well on the
JVM
− I decided to write a short pithy paper called, “Why .NET is a terrible platform for dynamic languages” Jim Hugunin
14
Nascimento do IronPython
Criador por Jim HuguninTambém criou o Jythonhttp://blogs.msdn.com/hugunin/
Anúncio oficial http://blogs.msdn.com/hugunin/archive/2006/09/05/741605.aspx
15
O que é o IronPython ?
− IronPython é uma implementação open source do Python desenvolvida pela Microsoft que roda sobre o .NET
− Uma implementação rápida do Python para CLI− Compila o código Python para IL (CLI bytecode)− Inclui suporte a bibliotecas (com código gerenciado)− 1.8x mais rápido que o Python-2.4− Roda todos os parrotbench com a mesma velocidade do CPython
− Integra com as outras liguagens da CLI− C#, VB, J#, JScript, Cobol, Eiffel, C++, …
16
O que significa IRON ?− Implementação Verdadeira da
Linguagem− Excelente performance− Fiel a Linguagem − Fiel a comunidade− Fiel a experiência
− Grande integração ao .NET− Fácil de usar com Bibliotecas .NET − Fácil de usar com outras linguagens .NET− Fácil de usar em Hostsin .NET− Fácil de usar com ferramentas .NET
− Implementation Running On .NET
17
RoadMap
18
IronPython no Mono• 100% Compatível com Mono• Roda mais rápido no Mono que na vm Python
19
Arquitetura do IronPython
− Mesma arquitetura do CPython− scanner, parser, bytecode generator, support library
− Diferenças nos bytecode e suporte a biblioteca− Bytecode é IL para CLR – vai produzir código nativo− Biblioteca de suporte é escrita em C# e não C
− Compilação pode ser estática ou dinâmica− Produz .exe/.dll ou pode ser carregado e executado
dinâmicamente− IronPython é escrito inteiramente em C#
− Foram construídos 3 protitupo em Python inicialmente− Depois re-escrito em C#
PythonSource File
orCode
Snippet
PythonScanner Tokens
PythonParser AST
ILGenerator IL CLR
IronPython.Objects
refs
20
Compilando Fatorial para IL
def factorial(n): if n == 1: return 1 return n * factorial(n-1)
0 LOAD_FAST 0 (n) IL_0000: ldarg.0
3 LOAD_CONST 1 (1) IL_0001: ldsfld object __main__::c$0$PST04000002
6 COMPARE_OP 2 (==) IL_0006: call object IronPython…Ops::Equal(object,object)
9 JUMP_IF_FALSE 8 (to 20) IL_000b: call bool IronPython...Ops::IsTrue(object)IL_0010: brfalse IL_0020
12 POP_TOP
13 LOAD_CONST 1 (1) IL_0015: ldsfld object __main__::c$0$PST04000002
16 RETURN_VALUE IL_001a: ret
21
Compilando Fatorial para C#
def factorial(n): if n == 1: return 1 return n * factorial(n-1)
public static object factorial_f1(object n) { if (Ops.EqualIsTrue(n, 1)) return Main.c_1; return Ops.Multiply(n, Ops.Call(Main.factorial, Ops.Subtract(n, Main.c_1)));}
22
Compilando Fatorial – x86
0 LOAD_FAST 0 (n) 0000001b mov ecx,esi 0000001d mov edx,1 3 LOAD_CONST 1 (1)
6 COMPARE_OP 2 (==) 00000023 call dword ptr ds:[036E3184h]
9 JUMP_IF_FALSE 8 (to 20) 00000028 mov edi,eax 0000002a test edi,edi 0000002c je 00000038
12 POP_TOP
13 LOAD_CONST 1 (1) 00000039 mov eax,dword ptr ds:[01B054E4h]
16 RETURN_VALUE <pop 4 registers and ret>
23
Performance
7 11 16 1521
69
0
10
20
30
40
50
60
70
80
Python-2.1 Python-2.3 Python-2.4 IronPython on1.1
IronPython on2.0
IronPython on2.0 w/opt
Milh
ões d
e te
ste
s p
or
seg
un
do
def t2(): for i in L: if i == 1000000: break <snip 18 identical lines> if i == 1000000: break
Exemplos de Código
24
Exemplos
26
Exemplos
Exemplos
28
Exemplo
29
PythonBinder
RubyBinder
COMBinder
JavaScriptBinder
ObjectBinder
Adding Dynamic to .NET
Dynamic Language RuntimeExpression Trees Dynamic Dispatch Call Site Caching
IronPython IronRuby C# VB.NET Others…
30
IronPython Consumindo C#
public class Calculator { … public int Add(int x, int y) { return x + y; }}
class Calculator: … def Add(self, x, y): return x + y
calc = GetCalculator()sum = calc.Add(10, 20)
31
C# 3.0 Consumindo IronPython
Calculator calc = GetCalculator();int sum = calc.Add(10, 20);
public class Calculator { … public int Add(int x, int y) { return x + y; }}
class Calculator: … def Add(self, x, y): return x + y
PyObject calc = GetCalculator();object res = calc.Invoke("Add", 10, 20);int sum = Convert.ToInt32(res);
object calc = GetCalculator();Type calcType = calc.GetType();object res = calcType.InvokeMember("Add", BindingFlags.InvokeMethod, null, new object[] { 10, 20 });int sum = Convert.ToInt32(res);
32
IronPython Studio
33
IronPython com SilverLigth
− www.trypython.org
34
DLR Console
− http://silverlight.net/content/samples/sl2/dlrconsole/
© 2009 Microsoft Corporation. All rights reserved. Microsoft, MSDN, the MSDN logo, and [list other trademarks referenced] are trademarks of the Microsoft group of companies. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond
to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation.
MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED, OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.