big ideas for cs 251 theory of programming languages...

30
Big Ideas for CS 251 Theory of Programming Languages Principles of Programming Languages CS251 Programming Languages Fall 2016, Lyn Turbak Department of Computer Science Wellesley College

Upload: others

Post on 17-Oct-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

Big Ideas for CS 251Theory of Programming Languages

Principles of Programming Languages

CS251ProgrammingLanguagesFall2016,LynTurbakDepartmentofComputerScienceWellesleyCollege

Page 2: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

Discussion: Programming Languages

•  What PLs have you used? •  Which PLs/PL features do you like/dislike. Why?

Your experience:

•  What is a PL? •  Why are new PLs created?

–  What are they used for? –  Why are there so many?

•  Why are certain PLs popular? •  What goes into the design of a PL?

More generally:

1-2

Page 3: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

PLismypassion!•  First PL project in 1982 as intern

at Xerox PARC

•  Created visual PL for 1986 MIT masters thesis

•  1994 MIT PhD on PL feature (synchronized lazy aggregates)

•  1996 – 2006: worked on types as member of Church project

•  1988 – 2008: Design Concepts in Programming Languages

•  2011 – current: lead TinkerBlocks research team at Wellesley

•  2012 – current: member of App Inventor development team

1-3

Page 4: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

GeneralPurposePLs

Python Fortran

C/C++

Java

RacketML

Haskell

CommonLisp

Perl

Ruby

1-4

JavaScript

Page 5: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

DomainSpecificPLs

IDL

CSS

PostScript�

HTML

OpenGL

LaTeX

Excel

Matlab R

Swift 1-5

Page 6: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

ProgrammingLanguages:MechanicalView

Acomputerisamachine.OuraimistomakethemachineperformsomespecifiedacEons.WithsomemachineswemightexpressourintenEonsbydepressingkeys,pushingbuIons,rotaEngknobs,etc.Foracomputer,weconstructasequenceofinstrucEons(thisisa``program'')andpresentthissequencetothemachine.–LaurenceAtkinson,PascalProgramming 1-6

Page 7: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

ProgrammingLanguages:LinguisEcView

Acomputerlanguage…isanovelformalmediumforexpressingideasaboutmethodology,notjustawaytogetacomputertoperformoperaEons.ProgramsarewriIenforpeopletoread,andonlyincidentallyformachinestoexecute.–HaroldAbelsonandGeraldJ.Sussman

1-7

Page 8: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

“Religious”ViewsTheuseofCOBOLcripplesthemind;itsteachingshould,therefore,beregardedasacriminaloffense.–EdsgerDijkstra

ItispracEcallyimpossibletoteachgoodprogrammingtostudentsthathavehadapriorexposuretoBASIC:aspotenEalprogrammerstheyarementallymuElatedbeyondhopeofregeneraEon.–EdsgerDijstra

You'reintroducingyourstudentstoprogramminginC?Youmightaswellgivethemafrontallobotomy!–Acolleagueofmine

ALISPprogrammerknowsthevalueofeverything,butthecostofnothing.-AlanPerlis

Ihavenevermetastudentwhocuttheirteethinanyoftheselanguagesanddidnotcomeawayprofoundlydamagedandunabletocope.ImeanthisreadstomeverysimilarlytoteachingsomeonetobeacarpenterbystarEngthemoffwithplasEctoytoolsandtellingthemtogosculptsandonthebeach.-AlfredThompson,onblockslanguages

Alanguagethatdoesn'taffectthewayyouthinkaboutprogramming,isnotworthknowing.-AlanPerlis 1-8

Page 9: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

ProgrammingLanguageEssenEals

PrimiEves

MeansofCombinaEon

MeansofAbstracEon

1-9

Thinkofthelanguagesyouknow.WhatmeansofabstracEondotheyhave?

Page 10: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

PL Parts Syntax: form of a PL

•  What a P in a given L look like as symbols? •  Concrete syntax vs abstract syntax trees (ASTs)

Semantics: meaning of a PL •  Static Semantics: What can we tell about P before running it?

–  Scope rules: to which declaration does a variable reference refer?

–  Type rules: which programs are well-typed (and therefore legal)?

•  Dynamic Semantics: What is the behavior of P? What actions does it perform? What values does it produce? –  Evaluation rules: what is the result or effect of evaluating each language

fragment and how are these composed?

Pragmatics: implementation of a PL (and PL environment)

1-10

•  How can we evaluate programs in the language on a computer? •  How can we optimize the performance of program execution?

Page 11: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

Syntax (Form) vs. Semantics (Meaning)in Natural Language

Furiously sleep ideas green colorless.

Colorless green ideas sleep furiously.

Little white rabbits sleep soundly.

1-11

Page 12: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

ConcreteSyntax:AbsoluteValueFuncEonLogo: to abs :n ifelse :n < 0 [output (0 - :n)] [output :n] end

Javascript: function abs (n) {if (n < 0) return -n; else return n;}

Java: public static int abs (int n) {if (n < 0) return -n; else return n;}

Python: App Inventor: def abs(n): if n < 0: return -n else: return n

Scheme: (define abs (lambda (n) (if (< n 0) (- n) n)))

PostScript: /abs {dup 0 lt {0 swap sub} if} def

1-12

Page 13: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

AbstractSyntaxTree(AST):AbsoluteValueFuncEon

varref

return

n

return

intlit

0

relaEonalOperaEon

varref

n

condiEonalStatement

funcEonDeclaraEon

absn

testthen

bodyparamsfuncDo

nName

rand1

name

name

1-13

arithmeEcOperaEon

value

subtract

varref

nname

value

intlit

0

lessThan

valuerand1

ThisASTabstractsovertheconcretesyntaxfortheLogo,JavaScript,andPythondefiniEons.TheotherdefiniEonswouldhavedifferentASTs.

Page 14: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

SemanEcsExample1

1-14

Whatisthemeaningofthefollowingexpression?

(1 + 11) * 10

Somepossibleanswers:•  120(regularintepretaEonofnumbers,operators)•  1000(binarynumbers,regularoperators)•  0(“+”means“minus”,“*”means“plus”)•  13(numberofcharactersinstring)•  5(numberofnodesinAST)•  3(numberofleavesinAST)

Page 15: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

SemanEcsExample2

1-15

Whatisprintedbythefollowingprogram?

a = 1;

b = a + 20;

print(b);

a = 300

print(b);

count = 0;

fun inc() { count = count + 1; return count; }

fun dbl(ignore, x) { return x + x; }

print(dbl(inc(), inc())

21214

21212

213203

213202

Herearesomepossibleanswers.WhatexecuEonmodelsgiverisetotheseanswers?

Page 16: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

SemanEcsExample3

1-16

Supposeaisanarray(orlist)containingthethreeintegervalues10,20,and30inthefollowinglanguages.Whatisthemeaningofthefollowingexpressions/statementsinvariouslanguages(thesyntaxmightdifferfromwhat’sshown).

a[1] a[3] a[2] = "foo" a[3] = 17

Java

C

Python

JavaScript

Pascal

AppInventor

Page 17: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

SemanEcsExample3(Answers)

1-17

Supposeaisanarray(orlist)containingthethreeintegervalues10,20,and30inthefollowinglanguages.Whatisthemeaningofthefollowingexpressions/statementsinvariouslanguages(thesyntaxmightdifferfromwhat’sshown).

a[1] a[3] a[2] = "foo" a[3] = 17

Java 20 dynamicindexoutofboundserror

staEctypeerror dynamicindexoutofboundserror

C 20 returnsvalueinmemoryslotalera[2]

staEctypeerror

Stores17inmemoryslotalera[2]

Python 20 dynamiclistindexoutofrangeerror

stores“foo”inthirdslotofa

dynamiclistindexoutofrangeerror

JavaScript 20 “undefined”value stores“foo”inthirdslotofa

Stores17ina[3]

Pascal 20 staEcindexoutofboundserror

staEctypeerror

staEcindexoutofboundserror

AppInventor 10 30 stores“foo”insecondslotofa

Stores17inthirdslotofa

Page 18: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

Pragmatics: Raffle App In App Inventor

DesignerWindow BlocksEditor

18

Toentertheraffle,textmenowwithanemptymessage:339-225-0287

hIp://ai2.appinventor.mit.edu

HowhardisthistodoinmoretradiEonaldevelopmentenvironmentsforAndroid/iOS?

Page 19: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

PL Dimensions

1-19

PLsdifferbasedondecisionslanguagedesignersmakeinmanydimensions.E.g.:

•  First-classvalues:whatvaluescanbenamed,passedasargumentstofuncEons,returnedasvaluesfromfuncEons,storedindatastructures.Whichofthesearefirst-classinyourfavoritePL:arrays,funcEons,variables?

•  Naming:Dovariables/parametersnameexpressions,thevaluesresulEngfromevaluaEngexpressions,ormutableslotsholdingthevaluesfromevaluaEngexpressions?Howarenamesdeclaredandreferenced?Whatdeterminestheirscope?

•  State:Whatismutableandimmutable;i.e.,whatenEEesinthelanguage(variables,datastructures,objects)canchangeoverEme.

•  Control:Whatconstructsarethereforcontrolflowinthelanguage,e.g.condiEonals,loops,non-localexits,excepEonhandling,conEnuaEons?

•  Data:Whatkindsofdatastructuresaresupportedinthelanguage,includingproducts(arrays,tuples,records,dicEonaries),sums(opEons,oneofs,variants),sum-of-products,andobjects.

•  Types:AreprogramsstaEcallyordynamicallytyped?Whattypesareexpressible?

Page 20: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

ProgrammingParadigms

1-20

•  Impera:ve(e.g.C,Python):ComputaEonisstep-by-stepexecuEononastatefulabstractmachineinvolvingmemoryslotsandmutabledatastructures.

•  Func:onal,func:on-oriented(e.gRacket,ML,Haskell):ComputaEonisexpressedbycomposingfuncEonsthatmanipulateimmutabledata.

•  Object-oriented(e.g.Simula,Smalltalk,Java):ComputaEonisexpressedintermsofstatefulobjectsthatcommunicatebypassingmessagestooneanother.

•  Logic-oriented(e.g.Prolog):ComputaEonisexpressedintermsofdeclaraEverelaEonships.

Note:InpracEce,mostPLsinvolvemulEpleparadigms.E.g.

•  PythonsupportsfuncEonalfeatures(map,filter,listcomprehensions)andobjects

•  RacketandMLhaveimperaEvefeatures.

Page 21: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

quicksort :: Ord a => [a] -> [a]quicksort [] = []quicksort (p:xs) =

(quicksort lesser) ++ [p] ++ (quicksort greater) where lesser = filter (< p) xs greater = filter (>= p) xs

1-21

ParadigmExample:Quicksortvoid qsort(int a[], int lo, int hi) { int h, l, p, t;

if (lo < hi) {

l = lo; h = hi; p = a[hi];

do { while ((l < h) && (a[l] <= p)) l = l+1;

while ((h > l) && (a[h] >= p)) h = h-1; if (l < h) {

t = a[l]; a[l] = a[h]; a[h] = t; }

} while (l < h);

a[hi] = a[l]; a[l] = p;

qsort( a, lo, l-1 ); qsort( a, l+1, hi );

}}

ImperaEveStyle(inC;Javawouldbesimilar)

FuncEonalStyle(inHaskell)

Page 22: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

Pragmatics: Metaprogramming

1-22

PLsareimplementedintermsofmetaprogams=programsthatmanipulateotherprograms.

Thismaysoundweird,butprogramsarejusttrees(ASTs),soametaprogramisjustaprogramthatmanipulatestrees(thinkamorecomplexversionofCS230binarytreeprograms).

ImplementaEonstrategies:•  Interpreta:on:interpretaprogramPinasourcelanguageSintermsofan

implementaEonlanguageI.

•  Transla:on(compila:on):translateaprogramPinasourcelanguageStoaprogramP’inatargetlanguageTusingatranslatorwriIeninimplementaEonlanguageI.

•  Embedding:expressprogramPinsourcelanguageSintermsofdatastructuresandfuncEonsinimplementaEonlanguageI.

Page 23: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

Metaprogramming:InterpretaEon

InterpreterforlanguageLonmachineM

MachineMPrograminlanguageL

1-23

Page 24: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

Metaprogramming:TranslaEon

InterpreterforlanguageBonmachineM

MachineM

PrograminlanguageA AtoBtranslator

PrograminlanguageB

1-24

Page 25: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

Metaprogramming:Embedding

InterpreterforlanguageBonmachineM

MachineMPrograminlanguageAembeddedinlanguageB

1-25

Page 26: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

Metaprogramming:BootstrappingPuzzles

1-26

HowcanwewriteaJava-to-x86compilerinJava?

We’lllearnhowtounderstandsuchpuzzles!

Page 27: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

Metaprogramming:ProgrammingLanguageLayers

kernel

syntacEcsugar

primiEvevalues/datatypes

systemlibraries

userlibraries

1-27

Page 28: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

Why?Who?When?Where?DesignandApplicaEon

•  Historical context •  Motivating applications

–  Lisp: symbolic computation, logic, AI, experimental programming –  ML: theorem-proving, case analysis, type system –  C: Unix operating system –  Simula: simulation of physical phenomena, operations, objects –  Smalltalk: communicating objects, user-programmer,

pervasiveness •  Design goals, implementation constraints

–  performance, productivity, reliability, modularity, abstraction, extensibility, strong guarantees, …

•  Well-suited to what sorts of problems? 1-28

Page 29: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

WhystudyPL?•  CrossroadsofCS

•  Approachproblemsasalanguagedesigner.

–  "Agoodprogramminglanguageisaconceptualuniverseforthinkingaboutprogramming"--AlanPerlis

–  Evaluate,compare,andchooselanguages

–  BecomebeIeratlearningnewlanguages

–  becomeabeIerproblem-solver

–  viewAPIdesignaslanguagedesign•  Ask:

–  WhyarePLsarethewaytheyare?

–  Howcouldthey(orcouldn'tthey)bebeIer?–  Whatisthecost-conveniencetrade-offforfeatureX?

1-29

Page 30: Big Ideas for CS 251 Theory of Programming Languages …cs251/f16/slides/intro_with_answers_1up.pdf · Pragmatics: Metaprogramming 1-22 PLs are implemented in terms of metaprogams

Administrivia

•  Schedule, psets, quizzes, lateness policy, etc.:see http://cs.wellesley.edu/~cs251/

•  PS1 is available; due next Friday •  office hours poll •  visit me in office hours next week! •  Install Dr. Racket for next time

1-30