A Gentle Introduction to Reflection.key

1 downloads 0 Views 8MB Size Report
“This discussion isn't really going anywhere.” • His books “Gödel, Escher, Bach” and “Metamagical Themas” are a must-read (for any self-reflecting computer ...
Lecture 01 :
 A Gentle Introduction to Reflection Disclaimer: any pictures used in this presentation remain with the copyright of their original owner and were included here for didactical purposes only. In case of any suspected violation of copyright please contact me so that I can remove or replace those pictures.

LSINF 2335 Programming Paradigms Prof. Kim Mens UCL / EPL / INGI

Motivation

LSINF 2335 Prof. Kim Mens

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Programming Paradigms: Theory, Practice and Applications ■

Safir-Whorf Hypothesis (linguistics) – A particular language's nature influences the habitual thought of its speakers: different language patterns yield different patterns of thought.



Consequence: – language influences the thoughts of people who use it – language determines how we see and think about the world – the limits of one's language become the limits of one's world

3

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Programming Paradigms: Theory, Practice and Applications ■

Safir-Whorf Hypothesis applied to programming – The programming language used determines how we see and think about the solution.



Is a good programmer as efficient regardless of the language used? – Probably not; neither is the program...



A programming language is a problem-solving tool – Choose right programming language to solve your problem – A good language still doesn’t make a good programmer... • ... but it can make a bad programmer perform well • And make a good programmer perform better 4

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Programming Paradigms: Theory, Practice and Applications “When you only have a hammer, everything looks like a nail”



Do you only know 1 or 2 languages / paradigms? – Is that really the situation you want to be in when developing ? – Aren’t we supposed to be the computer science experts?



This course focusses on advanced programming languages, paradigms and techniques – Selected theme: reflection, metaprogramming
 and a bit of context-oriented programming. 5

Reflection

LSINF 2335 Prof. Kim Mens

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Reflection (language) ■

Meaning – one of the meanings of reflection (in English) is “introspection” : contemplation of one-self – in other words, reflection is the ability of a thing to talk about itself



Reflection in natural language – “This sentence contains 37 characters.” – “This sentence contains 27 letters.”



Reflection can easily introduce paradoxes – “This sentence is false.” • Suppose true. Then claim is correct. So false. Contradiction. • Suppose false. Then claim is wrong. So true. Contradiction. 7

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Reflection (art)

8

9

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Reflection (computing) ■



In computer science, (computational) reflection is the ability of a program to examine and control its own implementation Reflective programming – is the programming paradigm driven by reflection – is a special case of metaprogramming*



Computational reflection is good for (a.o.) – extending a language / language design – building programming environments – advanced software development tools – building knowledge and learning systems – self-modifying / self-optimising applications

* see later 10

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Reflection (computing) ■

Reflection is a pretty advanced feature – requires strong grasp of the fundamentals of the language – allows to solve problems elegantly, that were • previously handled on an ad-hoc basis • or hard / impossible to achieve



Be careful not to introduce paradoxes – It is possible to write programs that modify themselves while being executed – If you’re not careful this can lead to weird situations – Here’s an example you all know: • Modifying a data-structure while iterating over it. • And that’s not even reflection... 11

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Reflective languages ■

Many programmers (and some programming languages) do not fully recognise the importance of reflection – for example, debugging a program by manually adding debugging statements all over



Some languages provide some types of reflection – for debugging or error handling only – or only introspection but no real modification of existing programs



Aspect-oriented languages take it a step further – but still limited by the set of constructs they offer

12

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Reflective languages ■

Fully reflective languages offer the full power of reflection – allow to reason about and modify nearly any aspect of a running program



Today, many programming languages offer interesting reflective capabilities – common in high-level virtual machine programming languages like Smalltalk • note: Java is not fully reflective (mainly introspection)

– less common in lower-level programming languages like C

13

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Reflective languages ■

Have you ever thought of... – writing a program to generate a visitor class, given a class hierarchy ? – adding methods on a class while your code is running ? – finding out all the instances of a particular class at runtime, or – all messages understood by an object ? – adding new keywords to your language ?





In a fully reflective language like Smalltalk you can do all that... ... and more. 14

Metaprogramming

LSINF 2335 Prof. Kim Mens

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Reflection (computing) ■



In computer science, (computational) reflection is the ability of a program to examine and control its own implementation Reflective programming – is the programming paradigm driven by reflection – is a special case of metaprogramming



Computational reflection is good for (a.o.) – extending a language / language design – building programming environments – advanced software development tools – building knowledge and learning systems – self-modifying / self-optimising applications 16

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Meta (language) ■

In Greek – The preposition µετά means "after", "beside" or "with"



In English – the prefix meta- means “about” (its own category) – for example, metadata are data about data • (who has produced it, when, what format are the data in, ...)

– Douglas Hofstadter popularised the meaning of the term • For example, “going meta” – rethorical trick to take a debate or analysis to a higher abstraction level – “This discussion isn’t really going anywhere.” • His books “Gödel, Escher, Bach” and “Metamagical Themas” are a must-read (for any self-reflecting computer scientist)

17

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Meta (computing) ■

In computer science – metaprogramming is the writing of computer programs that write or manipulate other programs as their data – reflective programming is a case of metaprogramming • where a program is its own metaprogram • i.e., when a program manipulates itself



Well-known examples of metaprogramming – a compiler – an interpreter – a code analysis tool – a code generator – ...

18

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Quine (the philosopher) ■ ■



Willard Van Orman Quine (1908–2000) Philosopher who made an extensive study of indirect self-reference Quine’s paradox –

‘Yields falsehood when preceded by its quotation’



Can you see the paradox?

19

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Quine (the philosopher) ■ ■



Willard Van Orman Quine (1908–2000) Philosopher who made an extensive study of indirect self-reference Quine’s paradox –

‘Yields falsehood when preceded by its quotation’

– “ ‘Yields falsehood when preceded by its quotation’ yields falsehood when preceded by its quotation ” • Suppose true. Then sentence states falsehood. Contradiction. • Suppose false. Then sentence is wrong. So it does yield falsehood. Therefore sentence must be true. Contradiction.

20

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Quine (programs) ■



In computing a quine is a program that produces its complete source code as its only output A quine is a metaprogram – can be a reflective program



Some restrictions – program cannot take input – empty programs are not allowed • The empty quine once won the “worst abuse of the rules” price in the Obfuscated C contest



The Quine page – http://www.nyx.net/~gthompso/quine.htm – http://en.wikipedia.org/wiki/Quine_(computing) 21

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Quine (Javascript) ■

Here’s a quine in Javascript function a() { document.write (a + "\na();"); } a();



almost trivial because Javascript gives you access to a function’s source code

22

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Bootstrapping ■

An allusion to lift yourself up by your own bootstraps



Bootstrapping means using a special process to perform a task that one would be unable to do in general – for example, writing a compiler in terms of itself – start with a simple compiler, compile a more complex version in that one



When write a Quine –

The program has a code part and a data part



The data part represents the entire code



But the code contains the data part



Seems like a paradox: how can the data part contain itself?



Bootstrapping needed: • put special character in data part • replace that character by the data part itself 23

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Quine (C)

1/6

/* A simple quine (self-printing program), in standard C. */ /* Note: in designing this quine, we have tried to make the code clear * and readable, not concise and obscure as many quines are, so that * the general principle can be made clear at the expense of length. * In a nutshell: use the same data structure (called "progdata" * below) to output the program code (which it represents) and its own * textual representation. */

#include

void quote(const char *s) /* This function takes a character string s and prints the * textual representation of s as it might appear formatted * in C code. */ { int i;

printf("

\"");

... 24

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Quine (C)

2/6

for (i=0; s[i]; ++i) { /* Certain characters are quoted. */ if (s[i] == '\\') printf("\\\\"); else if (s[i] == '"') printf("\\\""); else if (s[i] == '\n') printf("\\n"); /* Others are just printed as such. */ else printf("%c", s[i]); /* Also insert occasional line breaks. */ if (i % 48 == 47) printf("\"\n

\"");

} printf("\""); }

... 25

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Quine (C)

3/6

/* What follows is a string representation of the program code, * from beginning to end (formatted as per the quote() function * above), except that the string _itself_ is coded as two * consecutive '@' characters. */ const char progdata[] = "/* A simple quine (self-printing program), in st" "andard C. */\n\n/* Note: in designing this quine, " "we have tried to make the code clear\n * and read" "able, not concise and obscure as many quines are" ", so that\n * the general principle can be made c" "lear at the expense of length.\n * In a nutshell:" " use the same data structure (called \"progdata\"\n" " * below) to output the program code (which it r" "epresents) and its own\n * textual representation" ". */\n\n#include \n\nvoid quote(const char " "*s)\n

/* This function takes a character stri"

"ng s and prints the\n

* textual representati"

"on of s as it might appear formatted\n "C code. */\n{\n ...

int i;\n\n

printf(\"

* in " \\\"\");\n 26

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Quine (C) "

4/6

for (i=0; s[i]; ++i) {\n

"racters are quoted. */\n "\n

if (s[i] == '\\\\')"

printf(\"\\\\\\\\\");\n

"i] == '\"')\n

" " " "n

else if (s["

printf(\"\\\\\\\"\");\n

"lse if (s[i] == '\\n')\n "\n

/* Certain cha"

e"

printf(\"\\\\n\");"

/* Others are just printed as such. */\n" else\n

printf(\"%c\", s[i]);\n

"

/* Also insert occasional line breaks. */\n " if (i % 48 == 47)\n \\\"\");\n

}\n

printf(\"\\\"\\" printf(\"\\\"\");\n}\n\n/* What fo"

"llows is a string representation of the program " "code,\n * from beginning to end (formatted as per" " the quote() function\n * above), except that the" " string _itself_ is coded as two\n * consecutive " "'@' characters. */\nconst char progdata[] =\n@@;\n\n" "int main(void)\n

/* The program itself... */\n"

"{\n

/* Print the program code, cha"

int i;\n\n

"racter by character. */\n "]; ++i) {\n ...

for (i=0; progdata[i"

if (progdata[i] == '@' && prog" 27

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Quine (C) "data[i+1] == '@')\n

5/6 /* We encounter tw"

"o '@' signs, so we must print the quoted\n "

"

* form of the program code. */\n

"

quote(progdata);

"

i++;

"@'. */\n

/* Quote all. */\n" /* Skip second '"

} else\n

"rogdata[i]);

{\n "

printf(\"%c\", p"

/* Print character. */\n

}\n

r"

"eturn 0;\n}\n";

int main(void) /* The program itself... */ { int i;

look for two consecutive @ characters and replace them by program string itself

/* Print the program code, character by character. */ for (i=0; progdata[i]; ++i) { if (progdata[i] == '@' && progdata[i+1] == '@') /* We encounter two '@' signs, so we must print the quoted * form of the program code. */ ...

28

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Quine (C)

6/6

{ quote(progdata);

/* Quote all. */

i++;

/* Skip second '@'. */

} else printf("%c", progdata[i]);

/* Print character. */

} return 0; }



Reflective questions (pun intended) – Is this a metaprogram? – Is it a reflective program? – Is it self-modifying?

29

Wrap up

LSINF 2335 Prof. Kim Mens

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Things to remember ■

Meta (programming)



(Computational) Reflection



Bootstrapping

31

LSINF2335: Prog. Paradigms: Theory, Pract. and Applic.

Comprehension exercises ■





Do you believe the Safir-Whorf hypothesis applies to programming ? Write a paradoxical reflective sentence and explain why it is paradoxical Is the following “definition” reflective? – recursive: adjective, see recursive



Explain reflection, metaprogramming and bootstrapping in your own words.



Explain the word “meta” without going meta.



Write a quine in a programming language of your choice.



Can you write one that makes use of reflection?





Are you programming reflectively when you use the keyword “this” in Java? Read the book : “Gödel, Escher, Bach”.

32