36
SELF O poder da simplicidade Fabio Brzostek Muller Daniel Jorge Renjiffo 1

SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

SELF O poder da simplicidade

Fabio Brzostek MullerDaniel Jorge Renjiffo

1

Page 2: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Agenda

● Motivação● História● Linguagem● Semântica● Demonstração

2

Page 3: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Motivação

Linguagem orientada a objetos ?

3

Page 4: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

MotivaçãoPeter Wegner

● Classes

● Objetos

● Herança

4

Page 5: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

HistóriaEm 1986, Randall Smith fez o Alternate Reality Kit● Simulações gráficas para crianças aprenderem física● Não havia cores nem 3D nos computadores● Vários conceitos que depois apareceram em Self

● Uniformidade● Estado e comportamento unificados● Protótipos● Reflexão● Experiência consistente

5

Page 6: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

História

6

Page 7: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

História

● Criado por David Ungar e Randall Smith na Xerox PARC em 1986

● Randall foi para Londres, Ungar continuou o projeto em Stanford a partir de 1987

● Randall voltou, ambos trabalharam com o projeto na Sun de 1991 até 1995

● Versões mais recentes foram criadas e mantidas principalmente por Russell Allen

7

Page 8: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

História● Segundo Ungar, “Sun não entendeu o que tinha em

mãos”● Dois dos principais desenvolvedores da VM criaram

startup, portaram código para Java● Alguns anos depois, Sun comprou a tecnologia dessa

VM de volta por dezenas de milhões de dólares● Tornou-se a base da VM Hotspot de Java

8

Page 9: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

História

9

Page 10: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

História

O legado e a influência de Self incluem● NewtonScript, linguagem para o Apple Newton (1993);

adaptação de Self mais rápida, leve e textual● JavaScript, assim como Self, é baseada em protótipos,

não em classes● Lua não tem classes, POO usa protótipos; novos

objetos são clonados ou feitos com método Fábrica● GUI Morphic de Self foi portada para Smalltalk

(Squeak), JavaScript, Python, entre outras10

Page 11: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

História

11

Page 12: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Linguagem

Conceitos gerais● Tipagem dinâmica (distinção interna entre tipos

abstratos e concretos)● Não há classes nem variáveis; metáfora de protótipos● Acesso ao estado é unificado com envio de

mensagens; para acessar, se usa mensagens● Grande uniformidade que leva a maior expressividade

12

Page 13: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Linguagem

Conceitos● Mensagens no fundo: envio de mensagens é a

operação fundamental● Economia conceitual/minimalismo: tudo é objeto, pode

fazer papel de instância ou de repositório para compartilhar informação

● Concretude: tentar representar as coisas da forma mais concreta possível

13

Page 14: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Linguagem

Experiência● Programadores vivem no mundo real, respondem a

sentidos, não só pensamentos racionais● Humanos interagem com objetos físicos; para ter

uniformidade, Self é composta apenas por objetos● Protótipos permitem manipulação direta dos objetos● Implementação, linguagem e interface trabalham juntas

para criar uma experiência unificada

14

Page 15: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Linguagem

Protótipos● Objetos em Self têm slots que guardam estado e

comportamento● Slots com objetos pais permitem herança (compartilhar

comportamento)● Objeto tem características próprias, pai tem as

compartilhadas

15

Page 16: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Linguagem

16

Page 17: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Linguagem

Vantagens dos protótipos● Relações mais simples: “é um” e “é tipo de” X “herda

de”● Criação pela cópia: basta copiar para criar, sem ter que

interpretar informações de formato● Exemplos: protótipos são exemplos típicos de objetos;

mais fáceis de entender, encorajam reutilização● Sem meta-regresso: objetos em Self são auto-

suficientes, não dependem de nada17

Page 18: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Linguagem

18

Page 19: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Linguagem

Classe carro: Atributos: Comportamento: motor frente ano ré modelo abrirPorta portas fecharPorta

19

Page 20: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Linguagem

Ressalvas sobre protótipos● Com protótipos e herança, próximo passo seria guardar

comportamento no protótipo; mudar tudo facilmente● Mas protótipos perderiam o que têm de especial;

solução: objetos de traits, pais até do protótipo● Mudança no protótipo só afeta ele mesmo

20

Page 21: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Linguagem

Misturando estado e comportamento● Acesso de dados em slots é por envio de mensagem● Acessar estado por mensagens deixa herança mais

flexível● Compartilhamento de estado fica mais fácil● Distinção entre acesso e comportamento diminuiria o

poder das mensagens● Objetos primitivos mirrors permitem que métodos sejam

mencionados sem serem executados21

Page 22: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Linguagem

22

Page 23: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Linguagem

Interface de usuário● GUI Morphic, criada por Randall Smith e John Maloney● Assim como na linguagem, os elementos gráficos são

todos objetos diretamente manipuláveis● Objetivo é fazer a experiência ficar o mais simples

possível● Dois conceitos principais: reificação estrutural e edição

instantânea

23

Page 24: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Linguagem

Interface de usuário: Reificação estrutural● Estrutura fundamental são os morphs (grego:

coisa/forma)● Hierarquia de morphs: no topo, o protótipo; todos são

visíveis ● Todo morph pode ter submorphs; composição se dá

“colando” um no outro● Layout determinado por objetos de layout, também

visíveis, mostrando seu funcionamento diretamente24

Page 25: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Linguagem

Interface de usuário: Edição instantânea● A qualquer momento, objetos podem ser diretamente

modificados e mostram mudanças instantaneamente● Meta-menus permitem manipulações gráficas● Menu outliner mostra informações sobre o morph no

nível da linguagem (slots, edição)● Slots podem ser editados mesmo com objeto na tela● Reforça sensação de trabalho direto com objetos

concretos25

Page 26: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Sintaxe/Semântica

Literais● Inteiros. Ex.: 17, 2r10000, 16rFF● Floats. Ex.: 3.14159, -3e6, 5.0● Strings. Ex.: 'Hello world!', 'Quebra\n linha'● Comentários ficam dentro de aspas duplas● Palavras reservadas são self e resend● Identificadores podem ter letras, números e underline e

têm que começar com letra minúscula

26

Page 27: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Sintaxe/Semântica

Mensagens● Unárias. Ex.: 3.14 sin, atom mass● Binárias. Ex.: 3 + 4, 23 @ 47, 'bla ' , 'bla'● Com palavras-chave. Ex.: vec at: 2 Put: 50,

x > y ifTrue: 1 False: 0

● Precedência: unárias -> binárias -> palavras-chave● Mensagens binárias têm precedência sempre igual● Associatividade unária e binária da esquerda pra

direita, com palavras-chave ao contrário27

Page 28: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Sintaxe/Semântica

Objetos● Objetos planos: lista de slots. Ex.: (| x. y. z |) é

um objeto com 3 slots (getters/setters automáticos)● Slot constante tem que ser inicializado com = e um

valor. Ex.: (| x = 3. y = 4 |)● Slot variável é inicializado com <- e um valor (ou sem

nada). Ex.: (| x <- 5. y <- 6 |)● Slots de pais têm asterisco após nome.

Ex.: (| parent* = foo |)28

Page 29: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Sintaxe/Semântica

Métodos● São objetos, podem ter código além de slots● Slots de métodos servem como variáveis locais● Retornam resultado da última expressão de código (ou

retorno explícito com ^)● Argumentos podem ficar na lista de slots. Ex.:

+ y = (x + y) é igual a + = (|:y| x + y),num: n Den: d = ((x * n) / d) é igual anum:Den: = (|:n. :d| (x * n) / d) 29

Page 30: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Sintaxe/Semântica

Blocos● Parecem métodos, mas ficam entre [] e seu código só

é executado quando recebem mensagem value● Similares a funções anônimas/lambdas● Podem ter argumentos (value:, value:With:,

value:With:With:)● Permitem criação de estruturas de controle● Ex.: x != 0 ifTrue: [1/x] False: [0]

[i < j] whileTrue: [i: i * 2]30

Page 31: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Sintaxe/Semântica

Resends● Equivalente ao super de outras linguagens● Método de pai ou escolher entre pais diferentes● Ex.: (|pai* = (|foo = (x + y)|). x <- 8.

y <- 9. foo = (resend.foo - 1)|)

(| pai1* = (|f = 3|). pai2* = (|f = 4|).

f = (pai1.f + pai2.f) |)31

Page 32: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Sintaxe/Semântica

Operadores e objetos especiais● Operadores aritméticos: +, -, *, /, /+, /-, %,

square, squareRoot, sin, cos, tan, negate● Operadores lógicos: =, ==, &&, ||, not● true, false e nil são Singletons● Ao serem "copiados", na verdade retornam self● Slots que não recebem nem um valor inicial nem um

método são inicializados com nil

32

Page 33: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Sintaxe/Semântica

Coleções● Vetores (tamanho fixo, ordenados, começam em zero);

métodos at:Put:, first, last etc.● Strings são vetores, podem ser mutáveis ou não;

imutáveis usam padrão Flyweight● Conjuntos e dicionários são desordenados, elementos

comparáveis e retornam inteiro como valor hash; métodos add:, remove:, remove:IfAbsent:

● Listas podem crescer, modificação só nas pontas33

Page 34: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Sintaxe/Semântica

Coleções● do: recebe bloco e o aplica a cada elemento (e chave,

se houver) da coleção● mapBy:, filterBy: e outros mapeiam e filtram os

elementos da coleção● asDictionary, asVector, asList convertem● Listas de coletores formadas pelo método & podem ser

convertidas para coleções.Ex.: (1 & false & nil & 'foo') asVector

34

Page 35: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Demonstração

35

Page 36: SELF - USP · Referências UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991

Referências● UNGAR, David e SMITH, Randall B. - Self: The Power of Simplicity, Lisp

and Symbolic Computation 4(3), Kluwer Academic Publishers, June, 1991. Disponível em: http://bibliography.selflanguage.org/_static/self-power.pdf

● UNGAR, David e SMITH, Randall B. - Programming as an Experience: The Inspiration for Self, ECOOP ‘95 Conference Proceedings, Aarhus, Denmark, August, 1995. Disponível em: http://bibliography.selflanguage.org/_static/programming-as-experience.pdf

● http://www.selflanguage.org (em especial os dois vídeos)● http://handbook.selflanguage.org/4.5/● http://www.self-support.com● https://github.com/russellallen/self/tree/master/docs/tutorial

36