<commit_before>=pod

Z<CHP-4>

=head1 Subroutines

Z<CHP-4>

X<PIR (Parrot intermediate representation);subroutines>
X<subroutines;in PIR>
Code reuse has become a cornerstone of modern software engineering.
Common tasks are routinely packaged as libraries for later reuse
by other developers. The most basic building block of code reuse is
the "function" or "subroutine". A calculation like "the factorial of
a number", for example, may be used several times in a large program.
Subroutines allow this kind of functionality to be abstracted into a
single stand-alone unit for reuse. PIR is a subroutine-based language
in that all code in PIR must exist in a subroutine. Execution starts,
as we have seen, in the C<:main> subroutine, and others can be called
to perform the tasks of a program. From subroutines we can construct
more elaborate chunks of code reusability methods and objects. In
this chapter we will talk about how subroutines work in PIR, and how
they can be used by developers to create programs for Parrot.

Parrot supports multiple high-level languages, and each language uses
a different syntax for defining and calling subroutines. The goal of
PIR is not to be a high-level language in itself, but to provide the
basic tools that other languages can use to implement them. PIR's
syntax for subroutines may seem very primitive for this reason.

=head2 Parrot Calling Conventions

Z<CHP-4-SECT-1>

X<PIR (Parrot intermediate representation);subroutines;Parrot calling conventions>
X<subroutines;Parrot calling conventions;in PIR>
The way that Parrot calls a subroutine--by passing arguments, altering
control flow, and returning results--is called the "Parrot Calling
Conventions", or PCC. The details of PCC are generally hidden from the
programmer, being partially implemented in C and being partially
implemented in PASM. PIR has several constructs to gloss over these
details, and the average programmer will not need to worry about them.
PCC uses the Continuation Passing Style X<Continuation Passing Style
(CPS)>X<CPS (Continuation Passing Style)> (CPS) to pass control to
subroutines and back again. Again, the details of this can be largely
ignored for developers who don't need it, but the power of this approach
can be harnessed by those who do. We'll talk more about PCC and CPS in
this and in later chapters as well.

=head3 Subroutine Calls

X<PIR (Parrot intermediate representation);subroutine calls>
PIR's simplest subroutine call syntax looks much like a subroutine
call from a high-level language. This example calls the subroutine
C<fact> with two arguments and assigns the result to C<$I0>:

     ($I0, $I1) = 'fact'(count, product)

This simple statement hides a great deal of complexity. It generates a
subroutine PMC object, creates a continuation PMC object to return
control flow after the subroutine, passes the arguments, looks up the
subroutine by name (and by signature if it's been overloaded), it calls
the subroutine, and finally it assigns the results of the call to the
given register variables. This is quite a lot of work for a single
statement, and that's ignoring the computational logic that the
subroutine itself implements.

=head3 Expanded Subroutine Syntax

The single line subroutine call is incredibly convenient, but it isn't
always flexible enough. So PIR also has a more verbose call syntax
that is still more convenient than manual calls. This example pulls
the subroutine C<fact> out of the global symbol table into a PMC
register and calls it:

  find_global $P1, "fact"

  .begin_call
    .arg count
    .arg product
    .call $P1
    .result $I0
  .end_call

X<.arg directive>
X<.result directive>
The whole chunk of code from C<.begin_call> to C<.end_call> acts as a
single unit. The C<.arg> directive sets up and passes arguments to
the call. The C<.call> directive calls the subroutine, returns control
flow after the subroutine has completed. The C<.result> directive
retrieves returned values from the call.

=head3 Subroutine Declarations

X<.param directive>
In addition to syntax for subroutine calls, PIR provides syntax for
subroutine definitions. Subroutines are defined with the C<.sub>
directive, and end with the C<.end> directive. We've already seen
this syntax in our earlier examples. The C<.param> defines input
parameters and creates local named variables for them:

  .param int c

X<.return directive>
The C<.return> directive allows the subroutine to return control flow
to the calling subroutine, and optionally returns result output values.

Here's a complete code example that implements the factorial algorithm.
The subroutine C<fact> is a separate compilation unit, assembled and
processed after the C<main> function.  Parrot resolves global symbols
like the C<fact> label between different units.

  # factorial.pir
  .sub main
     .local int count
     .local int product
     count = 5
     product = 1

     $I0 = fact(count, product)

     print $I0
     print "\n"
     end
  .end

  .sub fact
     .param int c
     .param int p

  loop:
     if c <= 1 goto fin
     p = c * p
     dec c
     branch loop
  fin:
     .return p
  .end

This example defines two local named variables, C<count> and
C<product>, and assigns them the values 1 and 5. It calls the C<fact>
subroutine passing the two variables as arguments. In the call, the
two arguments are assigned to consecutive integer registers, because
they're stored in typed integer variables. The C<fact> subroutine
uses C<.param> and the C<.return> directives for retrieving parameters
and returning results. The final printed result is 120.

=head3 Named Parameters

Parameters that are passed in a strict order like we've seen above are
called '''positional arguments'''. Positional arguments are
differentiated from one another by their position in the function call.
Putting positional arguments in a different order will produce different
effects, or may cause errors. Parrot supports a second type of parameter,
a '''named parameter'''. Instead of passing parameters by their position
in the string, parameters are passed by name and can be in any order.
Here's an example:

 .sub 'MySub'
    .param int yrs :named("age")
    .param string call :named("name")
    $S0 = "Hello " . call
    $S1 = "You are " . yrs
    $S1 = $S1 . " years old
    print $S0
    print $S1
 .end

 .sub main :main
    'MySub'("age" => 42, "name" => "Bob")
 .end

In the example above, we could have easily reversed the order too:

 .sub main :main
    'MySub'("name" => "Bob", "age" => 42)    # Same!
 .end

Named arguments can be a big help because you don't have to worry about
the exact order of variables, especially as argument lists get very long.

=head3 Optional Parameters

Sometimes there are parameters to a function that don't always need to be
passed, or values for a parameter which should be given a default value
if a different value hasn't been explicitly provided. Parrot provides
a mechanism for allowing optional parameters to be specifed, so an
error won't be raised if the parameter isn't provided. Parrot also
provides a flag value that can be tested to determine if an optional
parameter has been provided or not, so a default value can be supplied.

Optional parameters are actually treated like two parameters: The value
that may or may not be passed, and the flag value to determine if it
has been or not. Here's an example declaration of an optional parameter:

  .param string name :optional
  .param int has_name :opt_flag

The C<:optional> flag specifies that the given parameter is optional and
does not necessarily need to be provided. The C<:opt_flag> specifies that
an integer parameter contains a boolean flag. This flag is true if the
value was passed, and false otherwise. This means we can use logic like
this to provide a default value:

  .param string name :optional
  .param int has_name :opt_flag
  if has_name goto we_have_a_name
    name = "Default value"
  we_have_a_name:

Optional parameters can be positional or named parameters. When using them
with positional parameters, they must appear at the end of the list of
postional parameters. Also, the C<:opt_flag> parameter must always appear
directly after the C<:optional> parameter.

  .sub 'Foo'
    .param int optvalue :optional
    .param int hasvalue :opt_flag
    .param pmc notoptional          # WRONG!
    ...

  .sub 'Bar'
     .param int hasvalue :opt_flag
     .param int optvalue :optional  # WRONG!
     ...

  .sub 'Baz'
    .param int optvalue :optional
    .param pmc notoptional
    .param int hasvalue :opt_flag   # WRONG!
    ...

Optional parameters can also be mixed with named parameters:

  .sub 'MySub'
    .param int value :named("answer") :optional
    .param int has_value :opt_flag
    ...

This could be called in two ways:

  'MySub'("answer" => 42)  # with a value
  'MySub'()                # without

=head2 Continuation Passing Style

Continuations are snapshots, a frozen image of the current execution
state of the VM. Once we have a continuation we can invoke it to
return to the point where the continuation was first created. It's
like a magical timewarp that allows the developer to arbitrarily move
control flow back to any previous point in the program N<there's actually
no magic involved, just a lot of interesting ideas and involved code>.

Continuations are not a new concept, they've been boggling the minds
of Lisp and Scheme programmers for many years. However, despite all
their power and flexibility they haven't been well-utilized in most
modern programming languages or in their underlying libraries and
virtual machines. Parrot aims to change that: In Parrot, almost every
control flow manipulation including all subroutine, method, and
coroutine calls, are performed using continuations. This mechanism
is mostly hidden from developers who build applications on top of
Parrot. The power and flexibility is available if people want to use
it, but it's hidden behind more familiar constucts if not.

Doing all sorts of flow control using continuations is called
X<Continuation Passing Style;CPS> Continuation Passing Style (CPS).
CPS allows parrot to offer all sorts of neat features, such as tail-call
optimizations and lexical subroutines.

=head3 Tailcalls

In many cases, a subroutine will set up and call another subroutine,
and then return the result of the second call directly. This is called
a X<tailcall> tailcall, and is an important opportunity for optimization.
Here's a contrived example in pseudocode:

 call add_two(5)

 subroutine add_two(value)
	 value = add_one(value)
	 return add_one(value)

In this example, the subroutine C<add_two> makes two calls to
c<add_one>. The second call to C<add_one> is used as the return
value. C<add_one> is called and its result is immediately returned
to the caller of C<add_two>, it is never stored in a local register or
variable in C<add_two>, it's immediately returned. We can
optimize this situation if we realize that the second call to
C<add_one> is returning to the same place that C<add_two> is, and therefore
can utilize the same return continuation as C<add_two> uses. The
two subroutine calls can share a return continution, instead of
having to create a new continuation for each call.

X<.tailcall directive>
In PIR code, we use the C<.tailcall> directive to make a tailcall
like this, instead of the C<.return> directive. C<.tailcall>
performs this optimization by reusing the return continution of
the parent function to make the tailcall.

=head3 Creating and Using Continuations

Most often continuations are used implicitly in the other control-flow
operations in Parrot. However, they can also be created and used explicitly
when required. Continuations are like any other PMC, and can be created
using the C<new> keyword:

  $P0 = new 'Continuation'
  
The new continuation starts off in an undefined state. Attempting to invoke
a new continuation after it's first been created will raise an exception. To
prepare the continuation for use, a destination label must be assigned to it
with the C<set_addr> opcode:

  $P0 = new 'Continuation'
  set_addr $P0, my_label
 
 my_label:
  ...

To jump to the continuation's stored label and return the context to the
state it was in when the continuation was created, use the C<invoke> opcode
or the C<()> notaton:

  invoke $P0  # Explicit using PASM-like opcodes
  $P0()       # Same, but nicer syntax

Notice that even though you can use the subroutine notation C<$P0()> to
invoke the continuation, it doesn't make any sense to try and pass arguments
to it or to try and return values from it:

  $P0 = new 'Continuation'
  set_addr $P0, my_label

  $P0(1, 2)      # WRONG!
  
  $P1 = $P0()    # WRONG!

=head2 Lexical Subroutines

X<Lexical Subroutines>
As we've mentioned above, Parrot offers support for lexical subroutines.
What this means is that we can define a subroutine by name inside a
larger subroutine, and our "inner" subroutine is only visible and callable
from the "outer" subroutine. Plus, the "inner" subroutine inherits all the
lexical variables from the outer subroutine, but is able to define its
own lexical variables that cannot be seen or modified by the outer subroutine.
This is important because PIR doesn't have anything corresponding to blocks
or nested scopes like some other languages have. Lexical subroutines play
the role of nested scopes when they are needed.

=head3 Scope and HLLs

Let us diverge for a minute and start looking forward at the idea of X<High
Level Languages;HLL> High Level Languages (HLLs) such as Perl, Python, and
Ruby. All of these languages allow nested scopes, or blocks within blocks
that can have their own lexical variables. Let's look back at the C
programming language, where this kind of construct is not uncommon:

  {
      int x = 0;
      int y = 1;
      {
          int z = 2;
          // x, y, and z are all visible here
      }
      // only x and y are visible here
  }

The code above illustrates this idea perfectly without having to get into a
detailed and convoluted example: In the inner block, we define the variable
C<z> which is only visible inside that block. The outer block has no
knowledge of C<z> at all. However, the inner block does have access to the
variables C<x> and C<y>. This is an example of nested scopes where the
visibility of different data items can change in a single subroutine. As
we've discussed above, Parrot does't have any direct analog for this
situation: If we tried to write the code above directly, we would end up
with this PIR code:

  .param int x
  .param int y
  .param int z
  x = 0
  y = 1
  z = 2
  ...

This PIR code is similar, but the handling of the variable C<z> is
different: C<z> is visible throughout the entire current subroutine, where it
is not visible throughout the entire C function. To help approximate this
effect, PIR supplies lexical subroutines to create nested lexical scopes.

=head3 PIR Scoping

In PIR, there is only one structure that supports scoping like this: the
subroutine N<and objects that inherit from subroutines, such as methods,
coroutines, and multisubs, which we will discuss later>. There are no blocks
in PIR that have their own scope, we have only subroutines. Fortunately,
we can use lexical subroutines to simulate this behavior that HLLs require:

  .sub 'MyOuter'
      .lex int x
      .lex int y
      'MyInner'()
      # only x and y are visible here
  .end

  .sub 'MyInner' :outer('MyOuter')
      .lex int z
      #x, y, and z are all visible here
  .end

=head3 Lexical Variables

As we have seen above, we can declare a new subroutine to be a nested inner
subroutine of an existing outer subroutine using the C<:outer> flag. The
outer flag is used to specify the name of the outer subroutine. Where there
may be multiple subroutines with the same name N<such is the case with
multisubs, which we will discuss soon>, we can use the C<:subid> flag on the
outer subroutine to give it a different--and unique--name that the lexical
subroutines can reference in their C<:outer> declarations. Within lexical
subroutines, the C<.lex> command defines a local variable that follows these
scoping rules.

=head3 LexPad and LexInfo PMCs

Information about lexical variables in a subroutine is stored in two different
types of PMCs: The LexPad and LexInfo PMCs. Neither of these PMC types are
really usable from PIR code, but are instead used by Parrot internally to
store information about lexical variables.

C<LexInfo> PMCs are used to store information about lexical variables at
compile time. This is read-only information that is generated during
compilation to represent what is known about lexical variables. Not all
subroutines get a LexInfo PMC by default, you need to indicate to Parrot
somehow that you require a LexInfo PMC to be created. One way to do this is
with the C<.lex> directive that we looked at above. Of course, the C<.lex>
directive only works for languages where the names of lexical variables are
all known at compile time. For languages where this information isn't known,
the subroutine can be flagged with C<:lex> instead.

C<LexPad> PMCs are used to store run-time information about lexical variables.
This includes their current values and their type information. LexPad PMCs are
created at runtime for subs that have a C<LexInfo> PMC already. These are
created each time the subroutine is invoked, which allows for recursive
subroutine calls without overwriting variable names.

There is no easy way to get a reference to the current LexPad or LexInfo PMCs
in a given subroutine, but that doesn't matter because they aren't useful by
themselves anyway. Remember that subroutines themselves can be lexical and
that therefore the lexical environment of a given variable can extend to
multiple subroutines and therefore multiple LexPads. The opcodes C<find_lex>
and C<store_lex> automatically search through nested LexPads recursively to
find the proper environment information about variables.

=head2 Compilation Units Revisited

Z<CHP-4-SECT-1.2>

The term "compilation unit" is one that's been bandied about throughout the
chapter and it's worth some amount of explanation here. A compilation unit
is a section of code that forms a single unit. In some instances the term
can be used to describe an entire file. In most other cases, it's used to
describe a single subroutine. Our earlier example which created a C<'fact'>
subroutine for calculating factorials could be considered to have used two
separate compilation units: The C<main> subroutine and the C<fact> subroutine.
Here is a way to rewrite that algorithm using only a single subroutine instead:

  .sub main
      $I1 = 5         # counter
      call fact       # same as bsr fact
      print $I0
      print "\n"
      $I1 = 6         # counter
      call fact
      print $I0
      print "\n"
      end

  fact:
      $I0 = 1           # product
  L1:
      $I0 = $I0 * $I1
      dec $I1
      if $I1 > 0 goto L1
      ret
  .end

The unit of code from the C<fact> label definition to C<ret> is a
reusable routine. There are several problems with this simple
approach. In terms of the interface, the caller has to know to pass the
argument to C<fact> in C<$I1> and to get the result from C<$I0>. This is
different from how subroutines are normally invoked in PIR.

Another disadvantage of this approach is that C<main> and C<fact>
share the same compilation unit, so they're parsed and processed as
one piece of code. They share registers, and they would also share LexInfo
and LexPad PMCs, if any were needed by C<main>. This is a problem when trying
to follow normal encapsulation guidelines.

=head3 PASM Subroutines

Z<CHP-4-SECT-1.1>

X<subroutines;PASM>
X<PASM (Parrot assembly language);subroutines>
PIR code can include pure PASM compilation units. These are wrapped in
the C<.emit> and C<.eom> directives instead of C<.sub> and C<.end>.
The C<.emit> directive doesn't take a name, it only acts as a
container for the PASM code. These primitive compilation units can be
useful for grouping PASM functions or function wrappers. Subroutine
entry labels inside C<.emit> blocks have to be global labels:

  .emit
  _substr:
      ...
      ret
  _grep:
      ...
      ret
  .eom

=head2 Namespaces, Methods, and VTABLES

Z<CHP-4-SECT-2>

X<PIR (Parrot intermediate representation);methods>
X<methods;in PIR>
X<classes;methods>
X<. (dot);. (method call);instruction (PIR)>
PIR provides syntax to simplify writing methods and method calls for
object-oriented programming. These calls follow the Parrot
calling conventions as well. First we want to discuss I<namespaces>
in Parrot.

=head3 Namespaces

Z<CHP-4-SECT-2>

X<Namespaces>
X<.namespace>
Namespaces provide a mechanism where names can be reused. This may not
sound like much, but in large complicated systems, or systems with
many included libraries, it can be very handy. Each namespace get's its
own area for function names and global variables. This way, you can have
multiple functions named C<create> or C<new> or C<convert>, for
instance, without having to use I<Multi-Method Dispatch> (MMD), which we
will describe later. Namespaces are also important for defining classes,
which we will also talk about a little later.

Namespaces are specified with the C<.namespace []> directive. The brackets
are not optional, but the keys inside them are. Here are some examples:

    .namespace [ ]               # The root namespace
    .namespace [ "Foo" ]         # The namespace "Foo"
    .namespace [ "Foo" ; "Bar" ] # Namespace Foo::Bar
    .namespace                   # WRONG! The [] are needed

Using semicolons, namespaces can be nested to any arbitrary depth.
Namespaces are special types of PMC, so we can access them and manipulate
them just like other data objects. We can get the PMC for the root
namespace using the C<get_root_namespace> opcode:

    $P0 = get_root_namespace

The current namespace, which might be different from the root namespace
can be retrieved with the C<get_namespace> opcode:

    $P0 = get_namespace             # get current namespace PMC
    $P0 = get_namespace ["Foo"]     # get PMC for namespace "Foo"

Once we have a namespace PMC we can retrieve global variables and
subroutine PMCs from it using the following functions:

    $P1 = get_global $S0            # Get global in current namespace
    $P1 = get_global ["Foo"], $S0   # Get global in namespace "Foo"
    $P1 = get_global $P0, $S0       # Get global in $P0 namespace PMC

Of course, once we have found a subroutine PMC from a namespace, we
can invoke it like a normal subroutine:

    $P1 = get_global ["Foo"], "MySubroutine"
    $P1()                           # invoke it

=head3 Calling Methods

Z<CHP-4-SECT-2>

Now that we've discussed namespaces, we can start to discuss all the
interesting things that namespaces enable, like object-oriented
programming and method calls. Methods are just like subroutines, except
they are invoked on a object PMC, and that PMC is passed as the c<self>
parameter.

The basic syntax for a method call is similar to the single line
subroutine call above. It takes a variable for the invocant PMC and a
string with the name of the method:

  object."methodname"(arguments)

Notice that the name of the method must be contained in quotes. If the
name of the method is not contained in quotes, it's treated as a named
variable that does. Here's an example:

  .local string methname = "Foo"
  object.methname()               # Same as object."Foo"()
  object."Foo"()                  # Same 

The invocant can be a variable or register, and the method name can be
a literal string, string variable, or method object PMC.

=head3 Defining Methods

Methods are defined like any other subroutine except with two major
differences: They must be inside a namespace named after the class
they are a part of, and they must use the C<:method> flag.

  .namespace [ "MyClass"]

  .sub "MyMethod" :method
    ...

Inside the method, the invocant object can be accessed using the C<self>
keyword. C<self> isn't the only name you can call this value, however.
You can also use the C<:invocant> flag to define a new name for the invocant
object:

  .sub "MyMethod" :method
    $S0 = self                    # Already defined as "self"
    say $S0
  .end
  
  .sub "MyMethod2" :method
    .param pmc item :invocant     # "self" is now called "item"
    $S0 = item
    say $S0
  .end

This example defines two methods in the C<Foo> class. It calls one
from the main body of the subroutine and the other from within the
first method:

  .sub main
    .local pmc class
    .local pmc obj
    newclass class, "Foo"       # create a new Foo class
    new obj, "Foo"              # instantiate a Foo object
    obj."meth"()                # call obj."meth" which is actually
    print "done\n"              # in the "Foo" namespace
    end
  .end

  .namespace [ "Foo" ]          # start namespace "Foo"

  .sub meth :method             # define Foo::meth global
     print "in meth\n"
     $S0 = "other_meth"         # method names can be in a register too
     self.$S0()                 # self is the invocant
  .end

  .sub other_meth :method       # define another method
     print "in other_meth\n"    # as above Parrot provides a return
  .end                          # statement

Each method call looks up the method name in the object's class namespace.
The C<.sub> directive automatically makes a symbol table entry for the
subroutine in the current namespace.

When a C<.sub> is declared as a C<:method>, it automatically creates a
local variable named C<self> and assigns it the object passed in
C<P2>. You don't need to write C<.param pmc self> to get it, it comes
free with the method.

You can pass multiple arguments to a method and retrieve multiple
return values just like a single line subroutine call:

  (res1, res2) = obj."method"(arg1, arg2)

=head3 VTABLEs

PMCs all subscribe to a common interface of functions called X<VTABLE>
VTABLEs. Every PMC implements the same set of these interfaces, which
perform very specific low-level tasks on the PMC. The term VTABLE was
originally a shortened form of the name "virtual function table",
although that name isn't used any more by the developers, or in any of
the documentation N<In fact, if you say "virtual function table" to
one of the developers, they probably won't know what you are talking
about>. The virtual functions in the VTABLE, called X<VTABLE
interfaces> VTABLE interfaces, are similar to ordinary functions and
methods in many respects. VTABLE interfaces are occasionally called
"VTABLE functions", or "VTABLE methods" or even "VTABLE entries" in
casual conversation. A quick comparison shows that VTABLE interfaces
are not really subroutines or methods in the way that those terms have
been used throughout the rest of Parrot. Like methods on an object,
VTABLE interfaces are defined for a specific class of PMC, and can be
invoked on any member of that class. Likewise, in a VTABLE interface
declaration, the C<self> keyword is used to describe the object that
it is invoked upon. That's where the similarities end, however. Unlike
ordinary subroutines or methods, VTABLE methods cannot be invoked
directly, they are also not inherited through class hierarchies like
how methods are. With all this terminology discussion out of the way,
we can start talking about what VTABLES are and how they are used in
Parrot.

VTABLE interfaces are the primary way that data in the PMC is accessed
and modified. VTABLES also provide a way to invoke the PMC if it's a
subroutine or subroutine-like PMC. VTABLE interfaces are not called
directly from PIR code, but are instead called internally by Parrot to
implement specific opcodes and behaviors. For instance, the C<invoke>
opcode calls the C<invoke> VTABLE interface of the subroutine PMC,
while the C<inc> opcode on a PMC calls the C<increment> VTABLE
interface on that PMC. What VTABLE interface overrides do, in essence,
is to allow the programmer to change the very way that Parrot accesses
PMC data in the most fundamental way, and changes the very way that the
opcodes act on that data.

PMCs, as we will look at more closely in later chapters, are typically
implemented using X<PMC Script> PMC Script, a layer of syntax and macros
over ordinary C code. A X<PMC Compiler> PMC compiler program converts the
PMC files into C code for compilation as part of the ordinary build
process. However, VTABLE interfaces can be written I<and overwritten> in
PIR using the C<:vtable> flag on a subroutine declaration. This technique
is used most commonly when subclassing an existing PMC class in PIR code
to create a new data type with custom access methods.

VTABLE interfaces are declared with the C<:vtable> flag:

  .sub 'set_integer' :vtable
      #set the integer value of the PMC here
  .end

in which case the subroutine must have the same name as the VTABLE
interface it is intended to implement. VTABLE interfaces all have very
specific names, and you can't override one with just any arbitrary name.
However, if you would like to namethe function something different but
still use it as a VTABLE interface, you could add an additional name
parameter to the flag:

  .sub 'MySetInteger' :vtable('set_integer')
      #set the integer value of the PMC here
  .end

VTABLE interfaces are often given the C<:method> flag also, so that they can
be used directly in PIR code as methods, in addition to being used by Parrot
as VTABLE interfaces. This means we can have the following:

  .namespace [ "MyClass" ]

  .sub 'ToString' :vtable('get_string') :method
      $S0 = "hello!"
      .return($S0)
  .end

  .namespace [ "OtherClass" ]

  .local pmc myclass = new "MyClass"
  say myclass                 # say converts to string internally
  $S0 = myclass               # Convert to a string, store in SS0
  $S0 = myclass.'ToString'()  # The same

Inside a VTABLE interface definition, the C<self> local variable contains
the PMC on which the VTABLE interface is invoked, just like in a method
declaration.

=head2 Coroutines

X<PIR;Coroutines>
X<Coroutines>
We've mentioned coroutines several times before, and we're finally going
to explain what they are. Coroutines are similar to subroutines except
that they have an internal notion of I<state> N<And the cool new name!>.
Coroutines, in addition to performing a normal C<.return> to return
control flow back to the caller and destroy the lexical environment of
the subroutine, may also perform a C<.yield> operation. C<.yield> returns
a value to the caller like C<.return> can, but it does not destroy the
lexical state of the coroutine. The next time the coroutine is called, it
continues execution from the point of the last C<.yield>, not at the
beginning of the coroutine.

In a Coroutine, when we continue from a C<.yield>, the entire lexical
environment is the same as it was when C<.yield> was called. This
means that the parameter values don't change, even if we call the
coroutine with different arguments later.

=head3 Defining Coroutines

Coroutines are defined like any ordinary subroutine. They do not require
any special flag or any special syntax to mark them as being a
coroutine. However, what sets them apart is the use of the C<.yield>
directive. C<.yield> plays several roles:

=over 4

=item* Identifies coroutines

When Parrot sees a yield, it knows to create a coroutine PMC object
instead of a Subroutine one.

=item* Creates a continuation

Continuations, as we have already seen, allow us to continue
execution at the point of the continuation later. It's like a snapshot of
the current execution environment. C<.yield> creates a continuation in
the coroutine and stores the continuation object in the coroutine object
or later resuming from the point of the C<.yield>.

=item* Returns a value

C<.yield> can return a value N<or many values, or no values> to the caller.
It is basically the same as a C<.return> in this regard.

=back

=head2 Multiple Dispatch

Multiple dispatch is when there are multiple subroutines in a single
namespace with the same name. These functions must differ, however, in
their parameter list, or "signature". All subs with the same name get
put into a single PMC called a MultiSub. The MultiSub is like a list
of subroutines. When the multisub is invoked, the MultiSub PMC object
searches through the list of subroutines and searches for the one with
the closest matching signature. The best match is the sub that gets
invoked.

=head3 Defining MultiSubs

MultiSubs are subroutines with the C<:multi> flag applied to them.
MultiSubs (also called "Multis") must all differ from one another in
the number and/or type of arguments passed to the function. Having
two multisubs with the same function signature could result in a
parsing error, or the later function could overwrite the former one
in the multi.

Multisubs are defined like this:

  .sub 'MyMulti' :multi
      # does whatever a MyMulti does
  .end

Multis belong to a specific namespace. Functions in different namespaces
with the same name do not conflict with each other N<this is one of the
reasons for having multisubs in the first place!>. It's only when
multiple functions in a single namespace need to have the same name that
a multi is used.

=cut

##########################################################################
#                              PSEUDOPOD LEGEND
#
#  Interior Sequences
#  ..................
#  A<>         link anchor (source)
#  B<>         bold text
#  C<>         monospace text
#  E<>         named character
#  F<>         file name
#  G<>         superscript
#  H<>         subscript
#  I<>         italicized text
#  L<>         link to other manpage (see A<>)
#  M<>         firstterm
#  N<>         footnote
#  Q<>         quoted text
#  R<>         replaceable item
#  S<>         text with non-breaking spaces
#  T<>         cited title for book, etc.
#  U<>         URL
#  X<>         a single index term of the form:
#                    primary:sortas;secondary:sortas;tertiary:sortas;;ETC
#                    where ETC is either (see term) or (see also term)
#                    only primary term is required
#  Z<>         link anchor (destination)
#
#  Heads
#  .....
#  head0                    chapter title
#  head{1-4}                section title (4 levels)
#
#  Command Paragraphs (begin/end Blocks)
#  .....................................
#  blockquote               quotation
#  comment                  ignored text
#  caution                  admonition
#  epigraph                 quotation
#  example                  container
#  figure CAPTION           figure
#  important                admonition
#  note                     admonition
#  programlisting           literal text
#  screen                   literal text
#  sidebar                  container
#  table html [CAPTION]     table rendered in HTML
#  table picture [CAPTION]  table rendered in plain text
#  tip                      admonition
#  warning                  admonition
#
#
#  Command Paragraphs (for Blocks)
#  ...............................
#  This structure will be used only for comments. For example:
#
#    =for editor
#    Check my spelling on this.
#    =end
#
#  This will be rendered as a visible comment in the final output
#  with a label at the top addressing it to "editor". The exception is
#  =for ignore which will always be ignored by the parser.
#
#  Tables
#  ......
#  A 2x2 table with top header row looks like this:
#
#  =begin table An Example Table
#  =headrow
#  =row
#  =cell Header for first column (row 1, col 1)
#  =cell Header for 2nd column (row 1, col 2)
#  =bodyrows
#  =cell Cell for row 2, col 1
#  =cell Cell for row 2, col 2
#  =end table
#
#  For more information on PSEUDOPOD, write to <EMAIL>
##########################################################################

# Local variables:
#   c-file-style: "parrot"
# End:
# vim: expandtab shiftwidth=4:
<commit_msg>[Book] Add a little footnote about .emit and .eom<commit_after>=pod

Z<CHP-4>

=head1 Subroutines

Z<CHP-4>

X<PIR (Parrot intermediate representation);subroutines>
X<subroutines;in PIR>
Code reuse has become a cornerstone of modern software engineering.
Common tasks are routinely packaged as libraries for later reuse
by other developers. The most basic building block of code reuse is
the "function" or "subroutine". A calculation like "the factorial of
a number", for example, may be used several times in a large program.
Subroutines allow this kind of functionality to be abstracted into a
single stand-alone unit for reuse. PIR is a subroutine-based language
in that all code in PIR must exist in a subroutine. Execution starts,
as we have seen, in the C<:main> subroutine, and others can be called
to perform the tasks of a program. From subroutines we can construct
more elaborate chunks of code reusability methods and objects. In
this chapter we will talk about how subroutines work in PIR, and how
they can be used by developers to create programs for Parrot.

Parrot supports multiple high-level languages, and each language uses
a different syntax for defining and calling subroutines. The goal of
PIR is not to be a high-level language in itself, but to provide the
basic tools that other languages can use to implement them. PIR's
syntax for subroutines may seem very primitive for this reason.

=head2 Parrot Calling Conventions

Z<CHP-4-SECT-1>

X<PIR (Parrot intermediate representation);subroutines;Parrot calling conventions>
X<subroutines;Parrot calling conventions;in PIR>
The way that Parrot calls a subroutine--by passing arguments, altering
control flow, and returning results--is called the "Parrot Calling
Conventions", or PCC. The details of PCC are generally hidden from the
programmer, being partially implemented in C and being partially
implemented in PASM. PIR has several constructs to gloss over these
details, and the average programmer will not need to worry about them.
PCC uses the Continuation Passing Style X<Continuation Passing Style
(CPS)>X<CPS (Continuation Passing Style)> (CPS) to pass control to
subroutines and back again. Again, the details of this can be largely
ignored for developers who don't need it, but the power of this approach
can be harnessed by those who do. We'll talk more about PCC and CPS in
this and in later chapters as well.

=head3 Subroutine Calls

X<PIR (Parrot intermediate representation);subroutine calls>
PIR's simplest subroutine call syntax looks much like a subroutine
call from a high-level language. This example calls the subroutine
C<fact> with two arguments and assigns the result to C<$I0>:

     ($I0, $I1) = 'fact'(count, product)

This simple statement hides a great deal of complexity. It generates a
subroutine PMC object, creates a continuation PMC object to return
control flow after the subroutine, passes the arguments, looks up the
subroutine by name (and by signature if it's been overloaded), it calls
the subroutine, and finally it assigns the results of the call to the
given register variables. This is quite a lot of work for a single
statement, and that's ignoring the computational logic that the
subroutine itself implements.

=head3 Expanded Subroutine Syntax

The single line subroutine call is incredibly convenient, but it isn't
always flexible enough. So PIR also has a more verbose call syntax
that is still more convenient than manual calls. This example pulls
the subroutine C<fact> out of the global symbol table into a PMC
register and calls it:

  find_global $P1, "fact"

  .begin_call
    .arg count
    .arg product
    .call $P1
    .result $I0
  .end_call

X<.arg directive>
X<.result directive>
The whole chunk of code from C<.begin_call> to C<.end_call> acts as a
single unit. The C<.arg> directive sets up and passes arguments to
the call. The C<.call> directive calls the subroutine, returns control
flow after the subroutine has completed. The C<.result> directive
retrieves returned values from the call.

=head3 Subroutine Declarations

X<.param directive>
In addition to syntax for subroutine calls, PIR provides syntax for
subroutine definitions. Subroutines are defined with the C<.sub>
directive, and end with the C<.end> directive. We've already seen
this syntax in our earlier examples. The C<.param> defines input
parameters and creates local named variables for them:

  .param int c

X<.return directive>
The C<.return> directive allows the subroutine to return control flow
to the calling subroutine, and optionally returns result output values.

Here's a complete code example that implements the factorial algorithm.
The subroutine C<fact> is a separate compilation unit, assembled and
processed after the C<main> function.  Parrot resolves global symbols
like the C<fact> label between different units.

  # factorial.pir
  .sub main
     .local int count
     .local int product
     count = 5
     product = 1

     $I0 = fact(count, product)

     print $I0
     print "\n"
     end
  .end

  .sub fact
     .param int c
     .param int p

  loop:
     if c <= 1 goto fin
     p = c * p
     dec c
     branch loop
  fin:
     .return p
  .end

This example defines two local named variables, C<count> and
C<product>, and assigns them the values 1 and 5. It calls the C<fact>
subroutine passing the two variables as arguments. In the call, the
two arguments are assigned to consecutive integer registers, because
they're stored in typed integer variables. The C<fact> subroutine
uses C<.param> and the C<.return> directives for retrieving parameters
and returning results. The final printed result is 120.

=head3 Named Parameters

Parameters that are passed in a strict order like we've seen above are
called '''positional arguments'''. Positional arguments are
differentiated from one another by their position in the function call.
Putting positional arguments in a different order will produce different
effects, or may cause errors. Parrot supports a second type of parameter,
a '''named parameter'''. Instead of passing parameters by their position
in the string, parameters are passed by name and can be in any order.
Here's an example:

 .sub 'MySub'
    .param int yrs :named("age")
    .param string call :named("name")
    $S0 = "Hello " . call
    $S1 = "You are " . yrs
    $S1 = $S1 . " years old
    print $S0
    print $S1
 .end

 .sub main :main
    'MySub'("age" => 42, "name" => "Bob")
 .end

In the example above, we could have easily reversed the order too:

 .sub main :main
    'MySub'("name" => "Bob", "age" => 42)    # Same!
 .end

Named arguments can be a big help because you don't have to worry about
the exact order of variables, especially as argument lists get very long.

=head3 Optional Parameters

Sometimes there are parameters to a function that don't always need to be
passed, or values for a parameter which should be given a default value
if a different value hasn't been explicitly provided. Parrot provides
a mechanism for allowing optional parameters to be specifed, so an
error won't be raised if the parameter isn't provided. Parrot also
provides a flag value that can be tested to determine if an optional
parameter has been provided or not, so a default value can be supplied.

Optional parameters are actually treated like two parameters: The value
that may or may not be passed, and the flag value to determine if it
has been or not. Here's an example declaration of an optional parameter:

  .param string name :optional
  .param int has_name :opt_flag

The C<:optional> flag specifies that the given parameter is optional and
does not necessarily need to be provided. The C<:opt_flag> specifies that
an integer parameter contains a boolean flag. This flag is true if the
value was passed, and false otherwise. This means we can use logic like
this to provide a default value:

  .param string name :optional
  .param int has_name :opt_flag
  if has_name goto we_have_a_name
    name = "Default value"
  we_have_a_name:

Optional parameters can be positional or named parameters. When using them
with positional parameters, they must appear at the end of the list of
postional parameters. Also, the C<:opt_flag> parameter must always appear
directly after the C<:optional> parameter.

  .sub 'Foo'
    .param int optvalue :optional
    .param int hasvalue :opt_flag
    .param pmc notoptional          # WRONG!
    ...

  .sub 'Bar'
     .param int hasvalue :opt_flag
     .param int optvalue :optional  # WRONG!
     ...

  .sub 'Baz'
    .param int optvalue :optional
    .param pmc notoptional
    .param int hasvalue :opt_flag   # WRONG!
    ...

Optional parameters can also be mixed with named parameters:

  .sub 'MySub'
    .param int value :named("answer") :optional
    .param int has_value :opt_flag
    ...

This could be called in two ways:

  'MySub'("answer" => 42)  # with a value
  'MySub'()                # without

=head2 Continuation Passing Style

Continuations are snapshots, a frozen image of the current execution
state of the VM. Once we have a continuation we can invoke it to
return to the point where the continuation was first created. It's
like a magical timewarp that allows the developer to arbitrarily move
control flow back to any previous point in the program N<there's actually
no magic involved, just a lot of interesting ideas and involved code>.

Continuations are not a new concept, they've been boggling the minds
of Lisp and Scheme programmers for many years. However, despite all
their power and flexibility they haven't been well-utilized in most
modern programming languages or in their underlying libraries and
virtual machines. Parrot aims to change that: In Parrot, almost every
control flow manipulation including all subroutine, method, and
coroutine calls, are performed using continuations. This mechanism
is mostly hidden from developers who build applications on top of
Parrot. The power and flexibility is available if people want to use
it, but it's hidden behind more familiar constucts if not.

Doing all sorts of flow control using continuations is called
X<Continuation Passing Style;CPS> Continuation Passing Style (CPS).
CPS allows parrot to offer all sorts of neat features, such as tail-call
optimizations and lexical subroutines.

=head3 Tailcalls

In many cases, a subroutine will set up and call another subroutine,
and then return the result of the second call directly. This is called
a X<tailcall> tailcall, and is an important opportunity for optimization.
Here's a contrived example in pseudocode:

 call add_two(5)

 subroutine add_two(value)
	 value = add_one(value)
	 return add_one(value)

In this example, the subroutine C<add_two> makes two calls to
c<add_one>. The second call to C<add_one> is used as the return
value. C<add_one> is called and its result is immediately returned
to the caller of C<add_two>, it is never stored in a local register or
variable in C<add_two>, it's immediately returned. We can
optimize this situation if we realize that the second call to
C<add_one> is returning to the same place that C<add_two> is, and therefore
can utilize the same return continuation as C<add_two> uses. The
two subroutine calls can share a return continution, instead of
having to create a new continuation for each call.

X<.tailcall directive>
In PIR code, we use the C<.tailcall> directive to make a tailcall
like this, instead of the C<.return> directive. C<.tailcall>
performs this optimization by reusing the return continution of
the parent function to make the tailcall.

=head3 Creating and Using Continuations

Most often continuations are used implicitly in the other control-flow
operations in Parrot. However, they can also be created and used explicitly
when required. Continuations are like any other PMC, and can be created
using the C<new> keyword:

  $P0 = new 'Continuation'
  
The new continuation starts off in an undefined state. Attempting to invoke
a new continuation after it's first been created will raise an exception. To
prepare the continuation for use, a destination label must be assigned to it
with the C<set_addr> opcode:

  $P0 = new 'Continuation'
  set_addr $P0, my_label
 
 my_label:
  ...

To jump to the continuation's stored label and return the context to the
state it was in when the continuation was created, use the C<invoke> opcode
or the C<()> notaton:

  invoke $P0  # Explicit using PASM-like opcodes
  $P0()       # Same, but nicer syntax

Notice that even though you can use the subroutine notation C<$P0()> to
invoke the continuation, it doesn't make any sense to try and pass arguments
to it or to try and return values from it:

  $P0 = new 'Continuation'
  set_addr $P0, my_label

  $P0(1, 2)      # WRONG!
  
  $P1 = $P0()    # WRONG!

=head2 Lexical Subroutines

X<Lexical Subroutines>
As we've mentioned above, Parrot offers support for lexical subroutines.
What this means is that we can define a subroutine by name inside a
larger subroutine, and our "inner" subroutine is only visible and callable
from the "outer" subroutine. Plus, the "inner" subroutine inherits all the
lexical variables from the outer subroutine, but is able to define its
own lexical variables that cannot be seen or modified by the outer subroutine.
This is important because PIR doesn't have anything corresponding to blocks
or nested scopes like some other languages have. Lexical subroutines play
the role of nested scopes when they are needed.

=head3 Scope and HLLs

Let us diverge for a minute and start looking forward at the idea of X<High
Level Languages;HLL> High Level Languages (HLLs) such as Perl, Python, and
Ruby. All of these languages allow nested scopes, or blocks within blocks
that can have their own lexical variables. Let's look back at the C
programming language, where this kind of construct is not uncommon:

  {
      int x = 0;
      int y = 1;
      {
          int z = 2;
          // x, y, and z are all visible here
      }
      // only x and y are visible here
  }

The code above illustrates this idea perfectly without having to get into a
detailed and convoluted example: In the inner block, we define the variable
C<z> which is only visible inside that block. The outer block has no
knowledge of C<z> at all. However, the inner block does have access to the
variables C<x> and C<y>. This is an example of nested scopes where the
visibility of different data items can change in a single subroutine. As
we've discussed above, Parrot does't have any direct analog for this
situation: If we tried to write the code above directly, we would end up
with this PIR code:

  .param int x
  .param int y
  .param int z
  x = 0
  y = 1
  z = 2
  ...

This PIR code is similar, but the handling of the variable C<z> is
different: C<z> is visible throughout the entire current subroutine, where it
is not visible throughout the entire C function. To help approximate this
effect, PIR supplies lexical subroutines to create nested lexical scopes.

=head3 PIR Scoping

In PIR, there is only one structure that supports scoping like this: the
subroutine N<and objects that inherit from subroutines, such as methods,
coroutines, and multisubs, which we will discuss later>. There are no blocks
in PIR that have their own scope, we have only subroutines. Fortunately,
we can use lexical subroutines to simulate this behavior that HLLs require:

  .sub 'MyOuter'
      .lex int x
      .lex int y
      'MyInner'()
      # only x and y are visible here
  .end

  .sub 'MyInner' :outer('MyOuter')
      .lex int z
      #x, y, and z are all visible here
  .end

=head3 Lexical Variables

As we have seen above, we can declare a new subroutine to be a nested inner
subroutine of an existing outer subroutine using the C<:outer> flag. The
outer flag is used to specify the name of the outer subroutine. Where there
may be multiple subroutines with the same name N<such is the case with
multisubs, which we will discuss soon>, we can use the C<:subid> flag on the
outer subroutine to give it a different--and unique--name that the lexical
subroutines can reference in their C<:outer> declarations. Within lexical
subroutines, the C<.lex> command defines a local variable that follows these
scoping rules.

=head3 LexPad and LexInfo PMCs

Information about lexical variables in a subroutine is stored in two different
types of PMCs: The LexPad and LexInfo PMCs. Neither of these PMC types are
really usable from PIR code, but are instead used by Parrot internally to
store information about lexical variables.

C<LexInfo> PMCs are used to store information about lexical variables at
compile time. This is read-only information that is generated during
compilation to represent what is known about lexical variables. Not all
subroutines get a LexInfo PMC by default, you need to indicate to Parrot
somehow that you require a LexInfo PMC to be created. One way to do this is
with the C<.lex> directive that we looked at above. Of course, the C<.lex>
directive only works for languages where the names of lexical variables are
all known at compile time. For languages where this information isn't known,
the subroutine can be flagged with C<:lex> instead.

C<LexPad> PMCs are used to store run-time information about lexical variables.
This includes their current values and their type information. LexPad PMCs are
created at runtime for subs that have a C<LexInfo> PMC already. These are
created each time the subroutine is invoked, which allows for recursive
subroutine calls without overwriting variable names.

There is no easy way to get a reference to the current LexPad or LexInfo PMCs
in a given subroutine, but that doesn't matter because they aren't useful by
themselves anyway. Remember that subroutines themselves can be lexical and
that therefore the lexical environment of a given variable can extend to
multiple subroutines and therefore multiple LexPads. The opcodes C<find_lex>
and C<store_lex> automatically search through nested LexPads recursively to
find the proper environment information about variables.

=head2 Compilation Units Revisited

Z<CHP-4-SECT-1.2>

The term "compilation unit" is one that's been bandied about throughout the
chapter and it's worth some amount of explanation here. A compilation unit
is a section of code that forms a single unit. In some instances the term
can be used to describe an entire file. In most other cases, it's used to
describe a single subroutine. Our earlier example which created a C<'fact'>
subroutine for calculating factorials could be considered to have used two
separate compilation units: The C<main> subroutine and the C<fact> subroutine.
Here is a way to rewrite that algorithm using only a single subroutine instead:

  .sub main
      $I1 = 5         # counter
      call fact       # same as bsr fact
      print $I0
      print "\n"
      $I1 = 6         # counter
      call fact
      print $I0
      print "\n"
      end

  fact:
      $I0 = 1           # product
  L1:
      $I0 = $I0 * $I1
      dec $I1
      if $I1 > 0 goto L1
      ret
  .end

The unit of code from the C<fact> label definition to C<ret> is a
reusable routine. There are several problems with this simple
approach. In terms of the interface, the caller has to know to pass the
argument to C<fact> in C<$I1> and to get the result from C<$I0>. This is
different from how subroutines are normally invoked in PIR.

Another disadvantage of this approach is that C<main> and C<fact>
share the same compilation unit, so they're parsed and processed as
one piece of code. They share registers, and they would also share LexInfo
and LexPad PMCs, if any were needed by C<main>. This is a problem when trying
to follow normal encapsulation guidelines.

=head3 PASM Subroutines

Z<CHP-4-SECT-1.1>

X<subroutines;PASM>
X<PASM (Parrot assembly language);subroutines>
PIR code can include pure PASM compilation units. These are wrapped in
the C<.emit> and C<.eom> directives instead of C<.sub> and C<.end>.
The C<.emit> directive doesn't take a name, it only acts as a
container for the PASM code N<in terms of parser terminology, the C<.emit>
directive causes the parser to transition into PASM mode. The C<.eom> directive
causes the parser to transition back into PIR mode>. These primitive
compilation units can be useful for grouping PASM functions or function
wrappers. Subroutine entry labels inside C<.emit> blocks have to be global
labels:

  .emit
  _substr:
      ...
      ret
  _grep:
      ...
      ret
  .eom

=head2 Namespaces, Methods, and VTABLES

Z<CHP-4-SECT-2>

X<PIR (Parrot intermediate representation);methods>
X<methods;in PIR>
X<classes;methods>
X<. (dot);. (method call);instruction (PIR)>
PIR provides syntax to simplify writing methods and method calls for
object-oriented programming. These calls follow the Parrot
calling conventions as well. First we want to discuss I<namespaces>
in Parrot.

=head3 Namespaces

Z<CHP-4-SECT-2>

X<Namespaces>
X<.namespace>
Namespaces provide a mechanism where names can be reused. This may not
sound like much, but in large complicated systems, or systems with
many included libraries, it can be very handy. Each namespace get's its
own area for function names and global variables. This way, you can have
multiple functions named C<create> or C<new> or C<convert>, for
instance, without having to use I<Multi-Method Dispatch> (MMD), which we
will describe later. Namespaces are also important for defining classes,
which we will also talk about a little later.

Namespaces are specified with the C<.namespace []> directive. The brackets
are not optional, but the keys inside them are. Here are some examples:

    .namespace [ ]               # The root namespace
    .namespace [ "Foo" ]         # The namespace "Foo"
    .namespace [ "Foo" ; "Bar" ] # Namespace Foo::Bar
    .namespace                   # WRONG! The [] are needed

Using semicolons, namespaces can be nested to any arbitrary depth.
Namespaces are special types of PMC, so we can access them and manipulate
them just like other data objects. We can get the PMC for the root
namespace using the C<get_root_namespace> opcode:

    $P0 = get_root_namespace

The current namespace, which might be different from the root namespace
can be retrieved with the C<get_namespace> opcode:

    $P0 = get_namespace             # get current namespace PMC
    $P0 = get_namespace ["Foo"]     # get PMC for namespace "Foo"

Once we have a namespace PMC we can retrieve global variables and
subroutine PMCs from it using the following functions:

    $P1 = get_global $S0            # Get global in current namespace
    $P1 = get_global ["Foo"], $S0   # Get global in namespace "Foo"
    $P1 = get_global $P0, $S0       # Get global in $P0 namespace PMC

Of course, once we have found a subroutine PMC from a namespace, we
can invoke it like a normal subroutine:

    $P1 = get_global ["Foo"], "MySubroutine"
    $P1()                           # invoke it

=head3 Calling Methods

Z<CHP-4-SECT-2>

Now that we've discussed namespaces, we can start to discuss all the
interesting things that namespaces enable, like object-oriented
programming and method calls. Methods are just like subroutines, except
they are invoked on a object PMC, and that PMC is passed as the c<self>
parameter.

The basic syntax for a method call is similar to the single line
subroutine call above. It takes a variable for the invocant PMC and a
string with the name of the method:

  object."methodname"(arguments)

Notice that the name of the method must be contained in quotes. If the
name of the method is not contained in quotes, it's treated as a named
variable that does. Here's an example:

  .local string methname = "Foo"
  object.methname()               # Same as object."Foo"()
  object."Foo"()                  # Same 

The invocant can be a variable or register, and the method name can be
a literal string, string variable, or method object PMC.

=head3 Defining Methods

Methods are defined like any other subroutine except with two major
differences: They must be inside a namespace named after the class
they are a part of, and they must use the C<:method> flag.

  .namespace [ "MyClass"]

  .sub "MyMethod" :method
    ...

Inside the method, the invocant object can be accessed using the C<self>
keyword. C<self> isn't the only name you can call this value, however.
You can also use the C<:invocant> flag to define a new name for the invocant
object:

  .sub "MyMethod" :method
    $S0 = self                    # Already defined as "self"
    say $S0
  .end
  
  .sub "MyMethod2" :method
    .param pmc item :invocant     # "self" is now called "item"
    $S0 = item
    say $S0
  .end

This example defines two methods in the C<Foo> class. It calls one
from the main body of the subroutine and the other from within the
first method:

  .sub main
    .local pmc class
    .local pmc obj
    newclass class, "Foo"       # create a new Foo class
    new obj, "Foo"              # instantiate a Foo object
    obj."meth"()                # call obj."meth" which is actually
    print "done\n"              # in the "Foo" namespace
    end
  .end

  .namespace [ "Foo" ]          # start namespace "Foo"

  .sub meth :method             # define Foo::meth global
     print "in meth\n"
     $S0 = "other_meth"         # method names can be in a register too
     self.$S0()                 # self is the invocant
  .end

  .sub other_meth :method       # define another method
     print "in other_meth\n"    # as above Parrot provides a return
  .end                          # statement

Each method call looks up the method name in the object's class namespace.
The C<.sub> directive automatically makes a symbol table entry for the
subroutine in the current namespace.

When a C<.sub> is declared as a C<:method>, it automatically creates a
local variable named C<self> and assigns it the object passed in
C<P2>. You don't need to write C<.param pmc self> to get it, it comes
free with the method.

You can pass multiple arguments to a method and retrieve multiple
return values just like a single line subroutine call:

  (res1, res2) = obj."method"(arg1, arg2)

=head3 VTABLEs

PMCs all subscribe to a common interface of functions called X<VTABLE>
VTABLEs. Every PMC implements the same set of these interfaces, which
perform very specific low-level tasks on the PMC. The term VTABLE was
originally a shortened form of the name "virtual function table",
although that name isn't used any more by the developers, or in any of
the documentation N<In fact, if you say "virtual function table" to
one of the developers, they probably won't know what you are talking
about>. The virtual functions in the VTABLE, called X<VTABLE
interfaces> VTABLE interfaces, are similar to ordinary functions and
methods in many respects. VTABLE interfaces are occasionally called
"VTABLE functions", or "VTABLE methods" or even "VTABLE entries" in
casual conversation. A quick comparison shows that VTABLE interfaces
are not really subroutines or methods in the way that those terms have
been used throughout the rest of Parrot. Like methods on an object,
VTABLE interfaces are defined for a specific class of PMC, and can be
invoked on any member of that class. Likewise, in a VTABLE interface
declaration, the C<self> keyword is used to describe the object that
it is invoked upon. That's where the similarities end, however. Unlike
ordinary subroutines or methods, VTABLE methods cannot be invoked
directly, they are also not inherited through class hierarchies like
how methods are. With all this terminology discussion out of the way,
we can start talking about what VTABLES are and how they are used in
Parrot.

VTABLE interfaces are the primary way that data in the PMC is accessed
and modified. VTABLES also provide a way to invoke the PMC if it's a
subroutine or subroutine-like PMC. VTABLE interfaces are not called
directly from PIR code, but are instead called internally by Parrot to
implement specific opcodes and behaviors. For instance, the C<invoke>
opcode calls the C<invoke> VTABLE interface of the subroutine PMC,
while the C<inc> opcode on a PMC calls the C<increment> VTABLE
interface on that PMC. What VTABLE interface overrides do, in essence,
is to allow the programmer to change the very way that Parrot accesses
PMC data in the most fundamental way, and changes the very way that the
opcodes act on that data.

PMCs, as we will look at more closely in later chapters, are typically
implemented using X<PMC Script> PMC Script, a layer of syntax and macros
over ordinary C code. A X<PMC Compiler> PMC compiler program converts the
PMC files into C code for compilation as part of the ordinary build
process. However, VTABLE interfaces can be written I<and overwritten> in
PIR using the C<:vtable> flag on a subroutine declaration. This technique
is used most commonly when subclassing an existing PMC class in PIR code
to create a new data type with custom access methods.

VTABLE interfaces are declared with the C<:vtable> flag:

  .sub 'set_integer' :vtable
      #set the integer value of the PMC here
  .end

in which case the subroutine must have the same name as the VTABLE
interface it is intended to implement. VTABLE interfaces all have very
specific names, and you can't override one with just any arbitrary name.
However, if you would like to namethe function something different but
still use it as a VTABLE interface, you could add an additional name
parameter to the flag:

  .sub 'MySetInteger' :vtable('set_integer')
      #set the integer value of the PMC here
  .end

VTABLE interfaces are often given the C<:method> flag also, so that they can
be used directly in PIR code as methods, in addition to being used by Parrot
as VTABLE interfaces. This means we can have the following:

  .namespace [ "MyClass" ]

  .sub 'ToString' :vtable('get_string') :method
      $S0 = "hello!"
      .return($S0)
  .end

  .namespace [ "OtherClass" ]

  .local pmc myclass = new "MyClass"
  say myclass                 # say converts to string internally
  $S0 = myclass               # Convert to a string, store in SS0
  $S0 = myclass.'ToString'()  # The same

Inside a VTABLE interface definition, the C<self> local variable contains
the PMC on which the VTABLE interface is invoked, just like in a method
declaration.

=head2 Coroutines

X<PIR;Coroutines>
X<Coroutines>
We've mentioned coroutines several times before, and we're finally going
to explain what they are. Coroutines are similar to subroutines except
that they have an internal notion of I<state> N<And the cool new name!>.
Coroutines, in addition to performing a normal C<.return> to return
control flow back to the caller and destroy the lexical environment of
the subroutine, may also perform a C<.yield> operation. C<.yield> returns
a value to the caller like C<.return> can, but it does not destroy the
lexical state of the coroutine. The next time the coroutine is called, it
continues execution from the point of the last C<.yield>, not at the
beginning of the coroutine.

In a Coroutine, when we continue from a C<.yield>, the entire lexical
environment is the same as it was when C<.yield> was called. This
means that the parameter values don't change, even if we call the
coroutine with different arguments later.

=head3 Defining Coroutines

Coroutines are defined like any ordinary subroutine. They do not require
any special flag or any special syntax to mark them as being a
coroutine. However, what sets them apart is the use of the C<.yield>
directive. C<.yield> plays several roles:

=over 4

=item* Identifies coroutines

When Parrot sees a yield, it knows to create a coroutine PMC object
instead of a Subroutine one.

=item* Creates a continuation

Continuations, as we have already seen, allow us to continue
execution at the point of the continuation later. It's like a snapshot of
the current execution environment. C<.yield> creates a continuation in
the coroutine and stores the continuation object in the coroutine object
or later resuming from the point of the C<.yield>.

=item* Returns a value

C<.yield> can return a value N<or many values, or no values> to the caller.
It is basically the same as a C<.return> in this regard.

=back

=head2 Multiple Dispatch

Multiple dispatch is when there are multiple subroutines in a single
namespace with the same name. These functions must differ, however, in
their parameter list, or "signature". All subs with the same name get
put into a single PMC called a MultiSub. The MultiSub is like a list
of subroutines. When the multisub is invoked, the MultiSub PMC object
searches through the list of subroutines and searches for the one with
the closest matching signature. The best match is the sub that gets
invoked.

=head3 Defining MultiSubs

MultiSubs are subroutines with the C<:multi> flag applied to them.
MultiSubs (also called "Multis") must all differ from one another in
the number and/or type of arguments passed to the function. Having
two multisubs with the same function signature could result in a
parsing error, or the later function could overwrite the former one
in the multi.

Multisubs are defined like this:

  .sub 'MyMulti' :multi
      # does whatever a MyMulti does
  .end

Multis belong to a specific namespace. Functions in different namespaces
with the same name do not conflict with each other N<this is one of the
reasons for having multisubs in the first place!>. It's only when
multiple functions in a single namespace need to have the same name that
a multi is used.

=cut

##########################################################################
#                              PSEUDOPOD LEGEND
#
#  Interior Sequences
#  ..................
#  A<>         link anchor (source)
#  B<>         bold text
#  C<>         monospace text
#  E<>         named character
#  F<>         file name
#  G<>         superscript
#  H<>         subscript
#  I<>         italicized text
#  L<>         link to other manpage (see A<>)
#  M<>         firstterm
#  N<>         footnote
#  Q<>         quoted text
#  R<>         replaceable item
#  S<>         text with non-breaking spaces
#  T<>         cited title for book, etc.
#  U<>         URL
#  X<>         a single index term of the form:
#                    primary:sortas;secondary:sortas;tertiary:sortas;;ETC
#                    where ETC is either (see term) or (see also term)
#                    only primary term is required
#  Z<>         link anchor (destination)
#
#  Heads
#  .....
#  head0                    chapter title
#  head{1-4}                section title (4 levels)
#
#  Command Paragraphs (begin/end Blocks)
#  .....................................
#  blockquote               quotation
#  comment                  ignored text
#  caution                  admonition
#  epigraph                 quotation
#  example                  container
#  figure CAPTION           figure
#  important                admonition
#  note                     admonition
#  programlisting           literal text
#  screen                   literal text
#  sidebar                  container
#  table html [CAPTION]     table rendered in HTML
#  table picture [CAPTION]  table rendered in plain text
#  tip                      admonition
#  warning                  admonition
#
#
#  Command Paragraphs (for Blocks)
#  ...............................
#  This structure will be used only for comments. For example:
#
#    =for editor
#    Check my spelling on this.
#    =end
#
#  This will be rendered as a visible comment in the final output
#  with a label at the top addressing it to "editor". The exception is
#  =for ignore which will always be ignored by the parser.
#
#  Tables
#  ......
#  A 2x2 table with top header row looks like this:
#
#  =begin table An Example Table
#  =headrow
#  =row
#  =cell Header for first column (row 1, col 1)
#  =cell Header for 2nd column (row 1, col 2)
#  =bodyrows
#  =cell Cell for row 2, col 1
#  =cell Cell for row 2, col 2
#  =end table
#
#  For more information on PSEUDOPOD, write to <EMAIL>
##########################################################################

# Local variables:
#   c-file-style: "parrot"
# End:
# vim: expandtab shiftwidth=4:

{'fraction_non_alphanumeric': 0.05960934147320625, 'fraction_numerical': 0.004291429599789581, 'mean_word_length': 3.538132931272773, 'pattern_counts': {'":': 0, '<': 384, '<?xml version=': 0, '>': 394, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5811838', 'n_tokens_mistral': 20332, 'n_tokens_neox': 19405, 'n_words': 10682}