PARROT - PROGRAMMING EXAMPLES

Similar documents
Parrot is a virtual machine designed to efficiently compile and execute bytecode for interpreted languages.

Parrot VM. Allison Randal Parrot Foundation & O'Reilly Media, Inc.

printf( Please enter another number: ); scanf( %d, &num2);

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

C# MOCK TEST C# MOCK TEST II

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

4. Structure of a C++ program

Name :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

Introduction. C provides two styles of flow control:

Assembly Language Manual for the STACK Computer

Motivation was to facilitate development of systems software, especially OS development.

What Is a Function? Illustration of Program Flow

More Complicated Recursion CMPSC 122

1/29/2018. Starting a Program Executes its main Function. ECE 220: Computer Systems & Programming. The Function main Divides into Two Parts

C# MOCK TEST C# MOCK TEST I

Where We Are. Lexical Analysis. Syntax Analysis. IR Generation. IR Optimization. Code Generation. Machine Code. Optimization.

Playing with bird guts. Jonathan Worthington YAPC::EU::2007

Special Section: Building Your Own Compiler

CS1 Recitation. Week 2

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

The role of semantic analysis in a compiler

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

CIS 194: Homework 3. Due Wednesday, February 11, Interpreters. Meet SImPL

Understanding main() function Input/Output Streams

In this chapter you ll learn:

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Fundamentals of Programming Session 13

COMPUTER PROGRAMMING LOOPS

COMPILER DESIGN - RUN-TIME ENVIRONMENT

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Implementing Perl 6 Jonathan Worthington Dutch Perl Workshop 2008

Intermediate Representations

COP4020 Programming Assignment 1 - Spring 2011

CSc Introduction to Computing

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Recursion. Comp Sci 1575 Data Structures. Introduction. Simple examples. The call stack. Types of recursion. Recursive programming

Loops / Repetition Statements

We will study the MIPS assembly language as an exemplar of the concept.

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

Programming Languages Fall 2013

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

Memory Usage in Programs

CS 231 Data Structures and Algorithms, Fall 2016

Data Types The ML Type System

Software Development. Integrated Software Environment

The Compilation Process

Iterative Languages. Scoping

CS 6353 Compiler Construction Project Assignments

Advanced Computer Programming

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Methods and Functions

CMPT 379 Compilers. Anoop Sarkar.

Language Proposal: tail

Java+- Language Reference Manual

Parrot Compiler Tools. Allison Randal The Perl Foundation & O'Reilly Media, Inc.

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

PERL MOCK TEST PERL MOCK TEST II

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

Programming in C. What is C?... What is C?

SOURCE LANGUAGE DESCRIPTION

Preview from Notesale.co.uk Page 3 of 79

Standard Version of Starting Out with C++, 4th Edition. Chapter 19 Recursion. Copyright 2003 Scott/Jones Publishing

Motivation was to facilitate development of systems software, especially OS development.

CS205: Scalable Software Systems

Organization of Programming Languages CS3200/5200N. Lecture 11

Welcome to Python 3. Some history

Variables. Data Types.

19 Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd

Writing Functions. Reading: Dawson, Chapter 6. What is a function? Function declaration and parameter passing Return values Objects as parameters

Subject: Fundamental of Computer Programming 2068

CSE 230 Intermediate Programming in C and C++ Functions

Computing Science 114 Solutions to Midterm Examination Tuesday October 19, In Questions 1 20, Circle EXACTLY ONE choice as the best answer

Recursion. COMS W1007 Introduction to Computer Science. Christopher Conway 26 June 2003

CS251 Programming Languages Handout # 29 Prof. Lyn Turbak March 7, 2007 Wellesley College

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Informatica 3 Syntax and Semantics

Values, types and variables

CSC231 C Tutorial Fall 2018 Introduction to C

Programmiersprachen (Programming Languages)

CS 6353 Compiler Construction Project Assignments

A Tour of Language Implementation

SWIFT - FUNCTIONS. Function Declaration: It tells the compiler about a function's name, return type, and parameters.

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Lecture 04 FUNCTIONS AND ARRAYS

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

Chapter 5 C Functions

Outline. Programming Languages 1/16/18 PROGRAMMING LANGUAGE FOUNDATIONS AND HISTORY. Current

Building Java Programs

Briefly describe the purpose of the lexical and syntax analysis phases in a compiler.

Procedures, Parameters, Values and Variables. Steven R. Bagley

CSCI 4152/6509 Natural Language Processing. Perl Tutorial CSCI 4152/6509. CSCI 4152/6509, Perl Tutorial 1

Variable A variable is a value that can change during the execution of a program.

Computer Science Department Carlos III University of Madrid Leganés (Spain) David Griol Barres

Transcription:

PARROT - PROGRAMMING EXAMPLES http://www.tutorialspoint.com/parrot/parrot_examples.htm Copyright tutorialspoint.com Parrot programing is similar to assembly language programing and you get a chance to work at lower level. Here is the list of programming examples to make you aware of the various aspects of Parrot Programming. Classic Hello world! Using registers Summing squares Fibonacci Numbers Computing factorial Compiling to PBC PIR vs. PASM Classic Hello world! Create a file called hello.pir that contains the following code: print "Hello world!\n" Then run it by typing: parrot hello.pir As expected, this will display the text 'Hello world!' on the console, followed by a new line duetothe\n. In this above example, '' states that the instructions that follow make up a subroutine named '_main', until a '' is encountered. The second line contains the print instruction. In this case, we are calling the variant of the instruction that accepts a constant string. The assembler takes care of deciding which variant of the instruction to use for us. The third line contains the '' instruction, which causes the interpreter to terminate. Using Registers We can modify hello.pir to first store the string Hello world!\n in a register and then use that register with the print instruction. set S1, "Hello world!\n" print S1 Here we have stated exactly which register to use. However, by replacing S1 with $S1 we can delegate the choice of which register to use to Parrot. It is also possible to use an = notation instead of writing the set instruction. $S0 = "Hello world!\n" print $S0

To make PIR even more readable, named registers can be used. These are later mapped to real numbered registers..local string hello hello = "Hello world!\n" print hello The '.local' directive indicates that the named register is only needed inside the current compilation unit thatis, between. suband.. Following '.local' is a type. This can be int foriregisters, float fornregisters, string forsregisters, pmc forpregisters or the name of a PMC type. Summing squares This example introduces some more instructions and PIR syntax. Lines starting with a # are comments. # State the number of squares to sum..local int maxnum maxnum = 10 # Some named registers we'll use. # Note how we can declare many # registers of the same type on one line..local int i, total, temp total = 0 # Loop to do the sum. i = 1 loop: temp = i * i total += temp inc i if i <= maxnum goto loop # Output result. print "The sum of the first " print maxnum print " squares is " print total print ".\n" PIR provides a bit of syntactic sugar that makes it look more high level than assembly. For example: temp = i * i Is just another way of writing the more assembly-ish: mul temp, i, i And: if i <= maxnum goto loop Is the same as: le i, maxnum, loop

And: total += temp Is the same as: add total, temp As a rule, whenever a Parrot instruction modifies the contents of a register, that will be the first register when writing the instruction in assembly form. As is usual in assembly languages, loops and selections are implemented in terms of conditional branch statements and labels, as shown above. Assembly programming is one place where using goto is not a bad form! Fibonacci Numbers The Fibonacci series is defined like this: take two numbers, 1 and 1. Then repeatedly add together the last two numbers in the series to make the next one: 1, 1, 2, 3, 5, 8, 13, and so on. The Fibonacci number fibn is the n'th number in the series. Here's a simple Parrot assembler program that finds the first 20 Fibonacci numbers: # Some simple code to print some Fibonacci numbers print "The first 20 fibonacci numbers are:\n" set I1, 0 set I2, 20 set I3, 1 set I4, 1 REDO: eq I1, I2, DONE, NEXT NEXT: set I5, I4 add I4, I3, I4 set I3, I5 print I3 print "\n" inc I1 branch REDO DONE: This is the equivalent code in Perl: print "The first 20 fibonacci numbers are:\n"; my $i = 0; my $target = 20; my $a = 1; my $b = 1; until ($i == $target) { my $num = $b; $b += $a; $a = $num; print $a,"\n"; $i++; } NOTE: As a fine point of interest, one of the shortest and certainly the most beautiful ways of printing out a Fibonacci series in Perl is perl -le 'b = 1; printa+=bwhileprintb+=$a'. Recursively computing factorial In this example we define a factorial function and recursively call it to compute factorial.

.sub _fact # Get input parameter..param int n # return (n > 1? n * _fact(n - 1) : 1).local int result if n > 1 goto recurse result = 1 goto return recurse: $I0 = n - 1 result = _fact($i0) result *= n return:.return (result) :main.local int f, i # We'll do factorial 0 to 10. i = 0 loop: f = _fact(i) print "Factorial of " print i print " is " print f print ".\n" inc i if i <= 10 goto loop # That's it. Let's look at the _fact sub first. A point that was glossed over earlier is why the names of subroutines, all start with an underscore! This is done simply as a way of showing that the label is global rather than scoped to a particular subroutine. This is significant as the label is then visible to other subroutines. The first line,.param int n, specifies that this subroutine takes one integer parameter and that we'd like to refer to the register it was passed in by the name n for the rest of the sub. Much of what follows has been seen in previous examples, apart from the line reading: result = _fact($i0) This single line of PIR actually represents quite a few lines of PASM. First, the value in register $I0 is moved into the appropriate register for it to be received as an integer parameter by the _fact function. Other calling related registers are then set up, followed by _fact being invoked. Then, once _fact returns, the value returned by _fact is placed into the register given the name result. Right before the of the _fact sub, a.return directive is used to ensure the value held in the register; named result is placed into the correct register for it to be seen as a return value by the code calling the sub. The call to _fact in main works in just the same way as the recursive call to _fact within the sub _fact itself. The only remaining bit of new syntax is the :main, written after. By default, PIR assumes that execution begins with the first sub in the file. This behavior can be changed by

marking the sub to start in with :main. Compiling to PBC To compile PIR to bytecode, use the -o flag and specify an output file with the extension.pbc. parrot -o factorial.pbc factorial.pir PIR vs. PASM PIR can be turned into PASM by running: parrot -o hello.pasm hello.pir The PASM for the final example looks like this: _main: set S30, "Hello world!\n" print S30 PASM does not handle register allocation or provide support for named registers. It also does not have the.sub and directives, instead replacing them with a label at the start of the instructions. Loading [MathJax]/jax/output/HTML-CSS/jax.js