[harness] Update smolder submission info
[parrot.git] / docs / compiler_faq.pod
bloba5773ddc0403ad3c912e8c3422cecd9cda2c3141
1 # Copyright (C) 2001-2007, Parrot Foundation.
2 # $Id$
4 =head1 NAME
6 docs/compiler_faq.pod - Parrot FAQ for compiler writers in PIR
8 =head1 General Questions
10 =head2 Which C compilers can I use with Parrot?
12 Whoa, there--you're looking at the wrong FAQ.  This document is for people
13 writing compilers that target Parrot.
15 To answer your question, though, Parrot should theoretically work with any
16 C89-compliant C compiler. See the F<README> files in the root directory for
17 more information about building Parrot.
19 =head2 How can I implement a compiler to use as a compiler object from within
20 Parrot?
22 See L<http://www.parrotblog.org/2008/03/targeting-parrot-vm.html>.
24 =head2 How do I embed source locations in my code for debugging?
26 Use C<.line 42 "file.pir"> for this.
28 =head1 Subroutines
30 =head2 How do I generate a sub call in PIR?
32 This looks like a function call in many HLLs:
34 =begin PIR_FRAGMENT
36    $P0( $P1, $P2, $P3 )
38 =end PIR_FRAGMENT
40 where $P0 is the function object, and $P1, $P2, and $P3 are its
41 parameters. You can also use a function's name in place of the
42 object, as long as it's in the same namespace.
44 =begin PIR_FRAGMENT
46    somefunctionlabel( $P1, $P2, $P3 )
48 =end PIR_FRAGMENT
50 You can also get return value(s):
52 =begin PIR_FRAGMENT
54   ($P1,$P2) = $P0( $P1, $P2, $P3 )
56 =end PIR_FRAGMENT
58 If the function name might collide with a Parrot opcode, quote it:
60 =begin PIR_FRAGMENT
62    .local int i
63    i = 'new'(42)
65 =end PIR_FRAGMENT
67 You can also use the full PCC for these calls. See
68 L<docs/pdd19_pir.pod/Parameter Passing and Getting Flags> and other
69 questions below for more information.
71 =head2 How do I generate a method call in PIR?
73 Similar to function calls, just append C<.> and the method name to the object.
74 You should quote a literal method name to avoid confusion.
76 =begin PIR_FRAGMENT
78   .local pmc ret_val, some_obj, arg
79   ret_val = some_obj.'some_meth'(arg)
81 =end PIR_FRAGMENT
83 The method name may also be a string variable representing a method name:
85 =begin PIR_FRAGMENT
87   .local string m
88   .local pmc curses_obj
89   m = 'bold'
90   curses_obj.m()
92 =end PIR_FRAGMENT
94 =head2 How do I locate or create a subroutine object?
96 There are several ways to achieve this, depending on the location of
97 the subroutine.
99 If the sub is in the same file use a Sub constant:
101 =begin PIR_FRAGMENT
103   .const 'Sub' foo = 'foo'
104   # ...
105   foo()
107 =end PIR_FRAGMENT
109 A more dynamic way is:
111 =begin PIR_FRAGMENT
113   .local pmc foo
114   foo = find_name 'foo'
116 =end PIR_FRAGMENT
118 This searches for a subroutine 'foo' in the current lexical pad, in
119 the current namespace, in the global, and in the builtin namespace in
120 that order. This opcode is generated, if I<foo()> is used, but the
121 compiler can't figure out, where the function is.
123 If the subroutine is in a different namespace, use the
124 C<get_hll_global> or C<get_root_global> opcodes:
126 =begin PIR_FRAGMENT
128   .local pmc foo
129   foo = get_root_global ['Foo'], 'foo'
131 =end PIR_FRAGMENT
133 This fetches the sub C<foo> in the C<Foo> namespace.
135 =head2 How do I create a Closure or Coroutine?
137 Closure and Coroutine carry both a dynamic state.
138 Therefore you need to perform two steps.
139 First use one of the above ways to locate the Sub object.
140 Then use the op C<newclosure> to capture the environment.
142 =begin PIR_FRAGMENT
144   .local pmc coro
145   coro = find_name 'my_coro'
146   coro = newclosure coro
148 =end PIR_FRAGMENT
150 Any subroutine that contains a C<.yield> directive is automatically
151 created as a Coroutine PMC:
153 =begin PIR
155   .sub my_coro             # automagically a Coroutine PMC
156      .param pmc result
157      #...
158      .yield (result)
159      #...
160   .end
162 =end PIR
164 =head2 How do I generate a tail call in PIR?
166 =begin PIR
168   .sub foo
169       # ...
170       .tailcall bar(42)           # tail call sub bar
171   .end
173   .sub bar
174       .param int answer
175       inc answer
176       .return(answer)
177   .end
179 =end PIR
181 The sub C<bar> will return to the caller of C<foo>. (Warning! This fails
182 in some cases. XXX Find the Trac ticket and reference it here.)
184 =head2 How do I generate a sub call with a variable-length parameter
185 list in PIR?
187 If you have a variable amounts of arguments in an array, you can
188 pass all items of that array with the C<:flat> directive.
190 =begin PIR_FRAGMENT
192   .local pmc ar, foo
193   ar = new 'ResizablePMCArray'
194   push ar, "arg 1\n"
195   push ar, "arg 2\n"
196   #...
197   foo(ar :flat)
198   #...
200 =end PIR_FRAGMENT
202 =head2 How to I retrieve the contents of a variable-length parameter
203 list being passed to me?
205 Use a slurpy array:
207 =begin PIR
209   .sub mysub
210     .param pmc argv      :slurpy
211     .local int argc
212     argc = argv
213     #...
214   .end
216 =end PIR
218 If you have a few fixed parameters too, you can use a slurpy array
219 to get the rest of the arguments
221 =begin PIR
223   .sub mysub
224     .param pmc arg0
225     .param pmc arg1
226     .param pmc varargs   :slurpy
227     .local int num_varargs
228     num_varargs = varargs
229     # ...
230   .end
232 =end PIR
234 =head2 How do I pass optional arguments?
236 Use the C<:optional> and C<:opt_flag> pragmas:
238 =begin PIR
240   .sub foo
241      .param pmc arg1       :optional
242      .param int has_arg1   :opt_flag
243      .param pmc arg2       :optional
244      .param int has_arg2   :opt_flag
246      if has_arg1 goto got_arg1
247      #...
248   .end
250 =end PIR
252 =head2 How do I create nested subroutines?
254 Please refer to
255 L<docs/pdds/pdd20_lexical_vars.pod/Nested Subroutines Have Outies; the ":outer" attribute>
256 for details.
258 =head1 Variables
260 =head2 How do I fetch a variable from the global namespace?
262 Use the C<get_root_global> or C<get_hll_global> op:
264 =begin PIR_FRAGMENT
266     get_hll_global $P0, ['name'; 'space'], 'name_of_the_global'
267     get_hll_global $P1, 'name_of_the_global'
269 =end PIR_FRAGMENT
271 =head2 How can I delete a global?
273 You can retrieve the namespace hash and use the C<delete> opcode.
275 =begin PIR
277     .sub main :main
278     $P0 = new 'Integer'
279     $P0 = 42
280     set_hll_global 'foo', $P0
281     set_hll_global ['Bar'], 'baz', $P0
282     show_baz()
283     .local pmc ns, Bar_ns
284     ns = get_hll_namespace
285     delete ns['foo']              # delete from top level
286     Bar_ns = ns['Bar']            # get Bar namespace
287     delete Bar_ns['baz']
288     show_baz()
289     .end
290     .sub show_baz
291     $P0 = get_hll_global ['Bar'], 'baz'
292     print "'baz' is "
293     if null $P0 goto is_null
294     print $P0
295     print ".\n"
296     .return ()
297     is_null:
298     print "null.\n"
299     .end
301 =end PIR
303 =head2 How do I use lexical pads to have both a function scope and a
304 global scope?
306 Please refer to L<docs/pdds/pdd20_lexical_vars.pod> for details.
308 =head2 How can I delete a lexical variable?
310 You can't.  You can store a PMCNULL as the value though, which will catch all
311 further access to that variable and throw an exception. (You can create
312 a PMCNULL with the C<null> opcode.)
314 =head2 How do I resolve a variable name?
316 Use C<find_name>:
318 =begin PIR_FRAGMENT
320     $P0 = find_name '$x'
321     find_name $P0, 'foo'    # same thing
323 =end PIR_FRAGMENT
325 This will find the name C<foo> in the lexical, global, or builtin namespace, in
326 that order, and store it in C<$P0>.
328 =head2 How do I fetch a variable from the current lexical pad?
330 =begin PIR_FRAGMENT
332     find_lex $P0, 'foo'
334 =end PIR_FRAGMENT
336 or much better, if possible just use the variable defined along with
337 the C<.lex> definition of C<foo>.
339 =head2 How do I fetch a variable from any nesting depth?
341 That is still the same:
343 =begin PIR_FRAGMENT
345     find_lex $P0, 'foo'
347 =end PIR_FRAGMENT
349 This finds a C<foo> variable at any B<outer> depth starting from the top.
351 If your language looks up variables differently, you have to walk the
352 'caller' chain. See also F<t/dynpmc/dynlexpad.t>.
354 =head2 How can I produce more efficient code for lexicals?
356 Don't emit C<store_lex> at all. Use C<find_lex> only if the compiler
357 doesn't know the variable. You can always just use the register that was
358 defined in the C<.lex> directive as an alias to that lexical, if you are in
359 the same scope.
361 =head1 Modules, Classes, and Objects
363 =head2 How do I create a module?
367 =head2 How do I create a class?
369 With the C<newclass> op:
371 =begin PIR_FRAGMENT
373     newclass $P0, 'Animal'
375 =end PIR_FRAGMENT
377 =head2 How do I add instance variables/attributes?
379 Each class knows which attributes its objects can have. You can add attributes
380 to a class (not to individual objects) like so:
382 =begin PIR_FRAGMENT
384     addattribute $P0, 'legs'
386 =end PIR_FRAGMENT
388 =head2 How do I add instance methods to a class?
390 Methods are declared as functions in the class namespace with the C<:method>
391 keyword appended to the function declaration:
393 =begin PIR
395   .namespace [ 'Animal' ]
397   .sub run :method
398      print "slow and steady\n"
399   .end
401 =end PIR
403 =head2 How do I override a vtable on a class?
405 As with methods, but note the new keyword. The vtable name specified B<must>
406 be an existing vtable slot.
408 =begin PIR
410   .namespace [ 'NearlyPi' ]
412   .sub get_string :vtable
413      .return ('three and a half')
414   .end
416 =end PIR
418 Now, given an instance of NearlyPi in $P0
420 =begin PIR_FRAGMENT
422   $S0 = $P0
423   say $S0  # prints 'three and a half'
425 =end PIR_FRAGMENT
427 =head2 How do I access attributes?
429 You can access attributes by a short name:
431 =begin PIR_FRAGMENT_INVALID
433   $P0 = getattribute self, 'legs'
434   assign $P0, 4                   # set attribute's value
436 =end PIR_FRAGMENT_INVALID
438 =head2 When should I use properties vs. attributes?
440 Properties aren't inherited. If you have some additional data that
441 don't fit into the class's hierarchy, you could use properties.
443 =head2 How do I create a class that is a subclass of another class?
445 You first have to get the class PMC of the class you want to subclass.
446 Either you use the PMC returned by the C<newclass> op if you created
447 the class, or use the C<get_class> op:
449 =begin PIR_FRAGMENT
451     get_class $P0, 'Animal'
453 =end PIR_FRAGMENT
455 Then you can use the C<subclass> op to create a new class that is a
456 subclass of this class:
458 =begin PIR_FRAGMENT
460     subclass $P1, $P0, 'Dog'
462 =end PIR_FRAGMENT
464 This stores the newly created class PMC in $P1.
466 =head2 How do I create a class that has more than one parent class?
468 First, create a class without a parent class using C<newclass> (or
469 with only one subclass, see previous question). Then add the other
470 parent classes to it.  Please refer to the next question for an
471 example.
473 =head2 How do I add another parent class to my class?
475 If you have a class PMC (created with C<newclass> or by C<subclass>),
476 you can add more parent classes to it with the C<addparent> op:
478 =begin PIR_FRAGMENT
480     get_class $P1, 'Dog'
481     subclass $P2, $P1, 'SmallDog'
482     get_class $P3, 'Pet'
483     addparent $P2, $P3  # make "SmallDog" also a "Pet"
485 =end PIR_FRAGMENT
487 =head2 How can I specify the constructor of a class?
489 Just override the init vtable for that class.
491 =begin PIR
493     .sub _ :main
494       newclass $P0, 'Dog'         # create a class named Dog
495     .end
497     .namespace ['Dog']
499     .sub init :vtable
500       # ...
501     .end
503 =end PIR
505 Or you can specify the constructor method by setting the BUILD
506 property of the class PMC:
508 =begin PIR_FRAGMENT
510     newclass $P0, 'Dog'         # create a class named Dog
511     new $P1, 'String'           # create a string
512     set $P1, 'initialise'       # set it to the name of the constructor method
513     setprop $P0, 'BUILD', $P1   # set the BUILD property
515 =end PIR_FRAGMENT
517 =head2 How do I instantiate a class?
519 You can do so either with the class name:
521 =begin PIR_FRAGMENT
523     new $P0, 'Dog'
525 =end PIR_FRAGMENT
527 or with the class object:
529 =begin PIR_FRAGMENT_INVALID
531     .loadlib 'io_ops'
533     $P1 = get_class 'Dog'   # find the 'Dog' class
534     unless null $P1 goto have_dog_class
535     printerr "Oops; can't find the 'Dog' class.\n"
536     .return ()
537   have_dog_class:
538     new $P0, $P1    # creates a Dog object and stores it in register $P0
540 =end PIR_FRAGMENT_INVALID
542 The chief difference is that using a string constant will produce the
543 specific error "Class 'Dog' not found" if that happens to be the case;
544 the other code has to check explicitly.
546 During the C<new> opcode the constructor is called.
548 =head2 How can I pass arguments to a constructor?
550 You can pass only a single argument to a constructor.  By convention,
551 a hash PMC is passed to the constructor that contains the arguments as
552 key/value pairs:
554 =begin PIR_FRAGMENT
556     new $P0, 'Hash'
557     set $P0['greeting'], 'hello'
558     set $P0['size'], 1.23
560     new $P1, 'Alien', $P0       # create an Alien object and pass
561                                 # the hash to the constructor
563 =end PIR_FRAGMENT
565 =head2 How do I add module/class methods?
569 =head2 How do I access module/class variables?
573 =head1 Exceptions
575 =head2 How do I throw an exception in PIR?
577 The easiest way is the perl-like
579 =begin PIR_FRAGMENT
581     die 'Eeeek!'
583 =end PIR_FRAGMENT
585 You can also explicitly create an exception object and throw it:
587 =begin PIR_FRAGMENT
589     $P0 = new 'Exception'
590     $P0 = 'something happened'
591     throw $P0
593 =end PIR_FRAGMENT
595 =head2 How do I catch an exception in PIR?
597 Use C<push_eh> to push an exception handler onto the stack. End the set of
598 instructions that might throw the exception you're interested in with
599 C<pop_eh>.
601 =begin PIR_FRAGMENT
603     push_eh handler
604       die 'whoops'  # or any other code that might throw an exception...
605     pop_eh
606     # ok
608 =end PIR_FRAGMENT
610 An exception handler is called with one argument, which is the exception object.
611 The message of the exception can be easily extracted, as follows:
613 =begin PIR_FRAGMENT
615   handler: # exception
616     .get_results ($P0)
617     print 'Exception caught:'
618     $S0 = $P0['message']
619     say $S0
621 =end PIR_FRAGMENT
623 =head2 How do I let exceptions from C<exit> pass through my handler?
625 Rethrow the exception if it has a severity of C<EXCEPT_EXIT>.
627 =begin PIR_FRAGMENT
629   .include 'except_severity.pasm'
630   # ...
631   handler:
632     .get_results ($P0)
633     $I0 = $P0['severity']
634     if $I0 == .EXCEPT_EXIT goto handle_exit
635     say 'Exception caught!'
636     # ...
638   handle_exit:
639     rethrow $P0 # let the next handler deal with it.
641 =end PIR_FRAGMENT
643 Exception example:
645 =begin PIR_FRAGMENT
647     push_eh handler
648     $P0 = new 'Exception'
649     $P0 = 'something happened'
650     throw $P0
651     pop_eh
652     exit 0
654   handler:
655     .local pmc exception
656     .local string message
657     .get_results (exception)
658     print 'Exception: '
659     message = exception['message']
660     print message
661     print "\n"
662     exit 1
664 =end PIR_FRAGMENT
666 =head1 C Extensions
668 =head2 How do I create PMCs for my compiler?
670 Parrot supports dynamic PMCs, loadable at runtime, to allow compiler writers
671 to extend Parrot with additional types. For more information about writing
672 PMCs, see L<tools/build/pmc2c.pl> and L<docs/pmc.pod>.
674 See L<src/dynpmc/Makefile> for an example of how to build your dynamic
675 PMCS.
677 =head2 How do I add another op to Parrot?
679 Parrot supports dynamic op libraries. These allow for ops specific to one
680 language to be used without having to place them into the Parrot core itself.
681 For examples of dynamic op libraries, see L<src/dynoplibs>.
683 =head2 How do I use the Native Calling Interface (NCI)?
685 Using the NCI you can invoke functions written in C from a Parrot script.
686 To every NCI invocation, there are two parts: the native function to be invoked,
687 and the PIR code to do the invocation.
689 First the native function, to be written in C.  On Windows, it is necessary
690 to do a DLL export specification of the NCI function:
692   /* foo.c */
694   /* specify the function prototype */
695   #ifdef __WIN32
696   __declspec(dllexport) void foo(void);
697   #else
698   void foo(void);
699   #endif
701   void foo(void) {
702     printf("Hello Parrot!\n");
703   }
705 Then, after having compiled the file as a shared library, the PIR code looks
706 like this:
708 =begin PIR
710   .sub main :main
711      .local pmc lib, func
713      # load the shared library
714      lib = loadlib "hello" # no extension, .so or .dll is assumed
716      # get a reference to the function from the library just
717      # loaded, called "foo", and signature "void" (and no arguments)
718      func = dlfunc lib, "foo", "v"
720      # invoke
721      func()
723   .end
725 =end PIR
727 If you embedded a Parrot in your C file and you want to invoke another function
728 in that same C file, you should pass a null string to loadlib. Do that as follows:
730 =begin PIR_FRAGMENT
732  .local pmc lib
733  .local string libname
734  null libname
736  lib = loadlib libname
738 =end PIR_FRAGMENT
740 Under Linux, the .c file must then be linked with the -export-dynamic option.
742 =head1 Misc
744 =head2 How can I access a program's environment?
746 Create a new C<Env> PMC and access it like a hash.
748 =begin PIR_FRAGMENT
750     .local pmc e
751     e = new 'Env'
752     $P0 = e['USER']      # lt
754 =end PIR_FRAGMENT
756 =head2 How can I access Parrot's configuration?
758 =begin PIR_FRAGMENT
760     .include 'iglobals.pasm'
761     .local pmc interp, cfg
762     interp = getinterp
763     cfg = interp[.IGLOBALS_CONFIG_HASH]
764     $S0 = cfg['VERSION']    # "0.3.0"
766 =end PIR_FRAGMENT
768 See F<config_lib.pasm> for all the keys in the config hash - or iterate over
769 the config hash.
771 =cut