Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 6598ffc9b8
Fetching contributors…

Cannot retrieve contributors at this time

514 lines (342 sloc) 13.617 kb

NAME

Parrot Subroutines

ABSTRACT

This document describes how to define, call, and return from Parrot subroutine objects and other invokables.

DESCRIPTION

Parrot comes with different subroutine and related classes which implement CPS (Continuation Passing Style) and PCC (Parrot Calling Conventions) docs/pdds/pdd03_calling_conventions.pod.

Class Tree

These are all of the built-in classes that are directly callable, or "invokable":

  Sub
    Closure
    Coroutine
    Eval
  Continuation
    ExceptionHandler

By "invokable" we mean that they can be supplied as the first argument to the invoke, invokecc, or tailcall instructions. Generally speaking, invokable objects are divided into two subtypes: Sub and classes that are built on it create a new context when invoked, and Continuation classes return control to an existing context that was captured when the Continuation was created.

There are (of course) two classes that straddle this distinction:

  1. Invoking a Closure object creates a new context for the sub it refers to directly, but it also captures an "outer" context that provides bindings for the immediately-enclosing lexical scope (and, if that context is itself is for a Closure, the subsequent scopes working outwards).

    [add a newclosure example? -- rgr, 6-Apr-08.]

  2. A Coroutine acts like a normal sub when called initially, and can also return normally, but acts like a continuation when exited via the yield instruction and re-entered by re-invoking.

    [need a reference to a coroutine example. -- rgr, 6-Apr-08.]

SYNOPSIS

Creating subs

Subs are created by IMCC (the PIR compiler) via the .sub directive. Unless the :anon pragma is included, they are stored in the constant table associated with the bytecode and can be fetched with the get_hll_global and get_root_global opcodes. Within the PIR source, they can also be put in registers with a .const 'Sub' declaration:

This uses find_sub_not_null under the hood to look up the sub named "random_sub".

Here's an example of fetching a sub from another namespace:

Note that the_sub could be defined in a different bytecode or PIR source file from main.

Program entry point

One subroutine in the first executed source or bytecode file may be flagged as the "main" subroutine, where execution starts.

In the absence of a :main entry Parrot starts execution at the first statement. Any :main directives in a subsequent PIR or bytecode file that are loaded under program control are ignored.

Note that if the first executed source or bytecode file contains more than one sub flagged as :main, Parrot currently picks the last such sub to start execution. This is arguably a bug, so users should not depend upon it.

Load-time initialization

If a subroutine is marked as :load this subroutine is run, before the load_bytecode opcode returns.

e.g.

If a subroutine is marked as :init this subroutine is run before the :main or the first subroutine in the source file runs. Unlike :main subs, :init subs are also run when compiling from memory. :load subs are run only in any source or bytecode files loaded subsequently.

These markers are called "pragmas", and are defined fully in "pdds/pdd19_pir.pod" in docs. The following table summarizes the behavior of the five pragmas that cause Parrot to run a sub implicitly:

                ------ Executed when --------
                compiling to    -- loading --
  Sub Pragma    disk  memory    first   after
  ==========    ====  ======    =====   =====
   :immediate   yes   yes       no      no        
   :postcomp    yes   no        no      no        
   :load        no    no        no      yes       
   :init        no    yes       yes     no        
   :main        no    no        yes     no        

The same load-time behavior applies regardless of whether the loaded file is PIR source or bytecode. Note that it is possible to mark a sub with both :load and :init.

Defining subs

A sub is defined by a block of code starting with .sub and ending with .end. Parameters which the sub can be called with are defined by .param:

The set of .param instructions are converted to a single get_params instruction. The compiler will decide which registers to use.

A parameter can be declared optional with the :optional command. If an optional parameter is followed by parameter declared :opt_flag, this parameter will store an integer indicating whether the optional parameter was used.

A sub can accept an arbitrary number of parameters by declaring a :slurpy parameter. This creates a pmc containing an array of all parameters passed to the sub, these can be accessed like so:

A slurpy parameter can also be defined after a set of positional parameters, in which case it will only hold any additional parameters passed.

A parameter may also be declared :named, giving them a string which can be used when calling the sub to explicitly assign a parameter, ignoring position.

This can be combined with :optional as well as :opt_flag, so that the parameter need only be passed when necessary.

If a parameter is declared with :slurpy and :named (with no string), it creates an associative array containing all named parameters which can be accessed like so:

Calling the sub

PIR sub invocation syntax is similar to HLL syntax:

This is syntactic sugar for the following four bytecode instructions:

The sub name could be replaced with a PMC register, in which case the find_sub_not_null instruction would not be needed. If the return values from the sub were ignored (by dropping the $P0 = part), the get_results instruction would be omitted. However, set_args is emitted even in the case of a call without arguments.

The first operands to the set_args and get_results instructions are actually placeholders for an integer array that describes the register types. For example, the '(0,0)' for set_args is replaced internally with [2, 1], which means "two arguments, of type PMC and string". Note that return values get the same register type coercion as sub parameters. This is all described in much more detail in "pdds/pdd03_calling_conventions.pod" in docs.

Named parameters can be explicity called in one of two ways:

To receive multiple values, put the register names in parentheses:

To test whether a value was returned, declare it :optional, and follow it with an integer register declared :opt_val:

A :slurpy value can be declared, as in parameter declarations, to catch an arbitrary number of return values:

Note that the parameters stored in a :slurpy, or :slurpy :named array can be used as parameters for another call using the :flat declaration:

Subs may also return :named values, which can be explicitly accessed similar to parameter declarations:

All of these affect only the signature provided via get_results.

[not sure what this is for, leaving it alone for now -aninhumer]

Returning from a sub

PIR supports a convenient syntax for returning any number of values from a sub or closure:

Integer, float, and string constants are also accepted. This is translated to:

As for set_args, the '(0,0,0)' is actually a placeholder for an integer array that describes the register types; it is replaced internally with [2, 0, 1], which means "three arguments, of type PMC, integer, and string".

All of the declarations allowed for calls to a sub can also be used with return values. (:named, :flat)

Another way to return from a sub is to use tail-calling, which calls a new sub with the current continuation, so that the new sub returns directly to the caller of the old sub (i.e. without first returning to the old sub). This passes the three values to another_sub via tail-calling:

This is translated into a set_args instruction for the call, but with tailcall instead of invokecc:

As for calling, the sub name could be replaced with a PMC register, in which case the find_sub_not_null instruction would not be needed.

If needed, the current continuation can be extracted and called explicitly as follows:

To return values, use set_args as before.

All together now

The following complete example illustrates the typical call/return pattern:

Notice that we are not passing or returning values here.

[example of passing values. this could get pretty elaborate; look for other examples first. -- rgr, 6-Apr-08.]

If a short subroutine is called several times, for instance inside a loop, the creation of the return continuation can be done outside the loop:

If the sub returns values, the get_results must be after ret_label in order to receive them.

Since this is much more obscure than the PIR calling syntax, it should only be done if there is a measurable performance advantage. Even in this trivial example, calling "rsub(i)" is only about a third slower on x86.

FILES

src/pmc/sub.pmc, src/pmc/closure.pmc, src/pmc/continuation.pmc, src/pmc/coroutine.pmc, src/sub.c, t/pmc/sub.t

SEE ALSO

docs/pdds/pdd03_calling_conventions.pod docs/pdds/pdd19_pir.pod

AUTHOR

Leopold Toetsch <lt@toetsch.at>

Jump to Line
Something went wrong with that request. Please try again.