[debugger] Add ability to assign to registers
[parrot.git] / docs / compiler_faq.pod
blobf7d0f207414b197998d6376c2300545c18307548
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 compilation unit 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 RT 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
531     $P1 = get_class 'Dog'   # find the 'Dog' class
532     unless null $P1 goto have_dog_class
533     printerr "Oops; can't find the 'Dog' class.\n"
534     .return ()
535   have_dog_class:
536     new $P0, $P1    # creates a Dog object and stores it in register $P0
538 =end PIR_FRAGMENT
540 The chief difference is that using a string constant will produce the
541 specific error "Class 'Dog' not found" if that happens to be the case;
542 the other code has to check explicitly.
544 During the C<new> opcode the constructor is called.
546 =head2 How can I pass arguments to a constructor?
548 You can pass only a single argument to a constructor.  By convention,
549 a hash PMC is passed to the constructor that contains the arguments as
550 key/value pairs:
552 =begin PIR_FRAGMENT
554     new $P0, 'Hash'
555     set $P0['greeting'], 'hello'
556     set $P0['size'], 1.23
558     new $P1, 'Alien', $P0       # create an Alien object and pass
559                                 # the hash to the constructor
561 =end PIR_FRAGMENT
563 =head2 How do I add module/class methods?
567 =head2 How do I access module/class variables?
571 =head1 Exceptions
573 =head2 How do I throw an exception in PIR?
575 The easiest way is the perl-like
577 =begin PIR_FRAGMENT
579     die 'Eeeek!'
581 =end PIR_FRAGMENT
583 You can also explicitly create an exception object and throw it:
585 =begin PIR_FRAGMENT
587     $P0 = new 'Exception'
588     $P0 = 'something happened'
589     throw $P0
591 =end PIR_FRAGMENT
593 =head2 How do I catch an exception in PIR?
595 Use C<push_eh> to push an exception handler onto the stack. End the set of
596 instructions that might throw the exception you're interested in with
597 C<pop_eh>.
599 =begin PIR_FRAGMENT
601     push_eh handler
602       die 'whoops'  # or any other code that might throw an exception...
603     pop_eh
604     # ok
606 =end PIR_FRAGMENT
608 An exception handler is called with one argument, which is the exception object.
609 The message of the exception can be easily extracted, as follows:
611 =begin PIR_FRAGMENT
613   handler: # exception
614     .get_results ($P0)
615     print 'Exception caught:'
616     $S0 = $P0['message']
617     say $S0
619 =end PIR_FRAGMENT
621 =head2 How do I let exceptions from C<exit> pass through my handler?
623 Rethrow the exception if it has a severity of C<EXCEPT_EXIT>.
625 =begin PIR_FRAGMENT
627   .include 'except_severity.pasm'
628   # ...
629   handler:
630     .get_results ($P0)
631     $I0 = $P0['severity']
632     if $I0 == .EXCEPT_EXIT goto handle_exit
633     say 'Exception caught!'
634     # ...
636   handle_exit:
637     rethrow $P0 # let the next handler deal with it.
639 =end PIR_FRAGMENT
641 Exception example:
643 =begin PIR_FRAGMENT
645     push_eh handler
646     $P0 = new 'Exception'
647     $P0 = 'something happened'
648     throw $P0
649     pop_eh
650     exit 0
652   handler:
653     .local pmc exception
654     .local string message
655     .get_results (exception)
656     print 'Exception: '
657     message = exception['message']
658     print message
659     print "\n"
660     exit 1
662 =end PIR_FRAGMENT
664 =head1 C Extensions
666 =head2 How do I create PMCs for my compiler?
668 Parrot supports dynamic PMCs, loadable at runtime, to allow compiler writers
669 to extend Parrot with additional types. For more information about writing
670 PMCs, see L<tools/build/pmc2c.pl> and L<docs/pmc.pod>.
672 To build dynamic PMCs, add something like the following to your Makefile:
674   PERL     = /usr/bin/perl
675   PMCBUILD = $(PERL) /path/to/parrot/tools/build/dynpmc.pl
676   DESTDIR  = /path/to/parrot/runtime/parrot/dynext
677   LOAD_EXT = .so
679   PMCDIR    = pmc
680   PMCS      = MyInteger MyFloat MyString MyObject
681   PMC_FILES = MyInteger.pmc MyFloat.pmc MyString.pmc MyObject.pmc
683   dynpmcs : $(PMC_FILES)
684       @cd $(PMCDIR) && $(PMCBUILD) generate $(PMCS)
685       @cd $(PMCDIR) && $(PMCBUILD) compile $(PMCS)
686       @cd $(PMCDIR) && $(PMCBUILD) linklibs $(PMCS)
687       @cd $(PMCDIR) && $(PMCBUILD) copy "--destination=$(DESTDIR)" $(PMCS)
689 =head2 How do I add another op to Parrot?
691 Parrot supports dynamic op libraries. These allow for ops specific to one
692 language to be used without having to place them into the Parrot core itself.
693 For examples of dynamic op libraries, see L<src/dynoplibs>.
695 =head2 How do I use the Native Calling Interface (NCI)?
697 Using the NCI you can invoke functions written in C from a Parrot script.
698 To every NCI invocation, there are two parts: the native function to be invoked,
699 and the PIR code to do the invocation.
701 First the native function, to be written in C.  On Windows, it is necessary
702 to do a DLL export specification of the NCI function:
704   /* foo.c */
706   /* specify the function prototype */
707   #ifdef __WIN32
708   __declspec(dllexport) void foo(void);
709   #else
710   void foo(void);
711   #endif
713   void foo(void) {
714     printf("Hello Parrot!\n");
715   }
717 Then, after having compiled the file as a shared library, the PIR code looks
718 like this:
720 =begin PIR
722   .sub main :main
723      .local pmc lib, func
725      # load the shared library
726      lib = loadlib "hello" # no extension, .so or .dll is assumed
728      # get a reference to the function from the library just
729      # loaded, called "foo", and signature "void" (and no arguments)
730      func = dlfunc lib, "foo", "v"
732      # invoke
733      func()
735   .end
737 =end PIR
739 If you embedded a Parrot in your C file and you want to invoke another function
740 in that same C file, you should pass a null string to loadlib. Do that as follows:
742 =begin PIR_FRAGMENT
744  .local pmc lib
745  .local string libname
746  null libname
748  lib = loadlib libname
750 =end PIR_FRAGMENT
752 Under Linux, the .c file must then be linked with the -export-dynamic option.
754 =head1 Misc
756 =head2 How can I access a program's environment?
758 Create a new C<Env> PMC and access it like a hash.
760 =begin PIR_FRAGMENT
762     .local pmc e
763     e = new 'Env'
764     $P0 = e['USER']      # lt
766 =end PIR_FRAGMENT
768 =head2 How can I access Parrot's configuration?
770 =begin PIR_FRAGMENT
772     .include 'iglobals.pasm'
773     .local pmc interp, cfg
774     interp = getinterp
775     cfg = interp[.IGLOBALS_CONFIG_HASH]
776     $S0 = cfg['VERSION']    # "0.3.0"
778 =end PIR_FRAGMENT
780 See F<config_lib.pasm> for all the keys in the config hash - or iterate over
781 the config hash.
783 =head1 Languages
785 =head2 What files do I need to modify to add my new language compiler?
787 Aside from the files in your new language directory, you must modify
789     CREDITS
790     MANIFEST
791     config/gen/languages.pm
792     config/gen/makefiles/languages.in
794 Inside your language dir, you may consider adding the following:
796     LICENSE
797     MAINTAINER
798     README
799     STATUS
801 Look to existing languages for some examples.