1 # Copyright (C) 2001-2007, Parrot Foundation.
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
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.
30 =head2 How do I generate a sub call in PIR?
32 This looks like a function call in many HLLs:
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.
46 somefunctionlabel( $P1, $P2, $P3 )
50 You can also get return value(s):
54 ($P1,$P2) = $P0( $P1, $P2, $P3 )
58 If the function name might collide with a Parrot opcode, quote it:
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.
78 .local pmc ret_val, some_obj, arg
79 ret_val = some_obj.'some_meth'(arg)
83 The method name may also be a string variable representing a method name:
94 =head2 How do I locate or create a subroutine object?
96 There are several ways to achieve this, depending on the location of
99 If the sub is in the same file use a Sub constant:
103 .const 'Sub' foo = 'foo'
109 A more dynamic way is:
114 foo = find_name 'foo'
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:
129 foo = get_root_global ['Foo'], 'foo'
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.
145 coro = find_name 'my_coro'
146 coro = newclosure coro
150 Any subroutine that contains a C<.yield> directive is automatically
151 created as a Coroutine PMC:
155 .sub my_coro # automagically a Coroutine PMC
164 =head2 How do I generate a tail call in PIR?
170 .tailcall bar(42) # tail call sub bar
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
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.
193 ar = new 'ResizablePMCArray'
202 =head2 How to I retrieve the contents of a variable-length parameter
203 list being passed to me?
210 .param pmc argv :slurpy
218 If you have a few fixed parameters too, you can use a slurpy array
219 to get the rest of the arguments
226 .param pmc varargs :slurpy
227 .local int num_varargs
228 num_varargs = varargs
234 =head2 How do I pass optional arguments?
236 Use the C<:optional> and C<:opt_flag> pragmas:
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
252 =head2 How do I create nested subroutines?
255 L<docs/pdds/pdd20_lexical_vars.pod/Nested Subroutines Have Outies; the ":outer" attribute>
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:
266 get_hll_global $P0, ['name'; 'space'], 'name_of_the_global'
267 get_hll_global $P1, 'name_of_the_global'
271 =head2 How can I delete a global?
273 You can retrieve the namespace hash and use the C<delete> opcode.
280 set_hll_global 'foo', $P0
281 set_hll_global ['Bar'], 'baz', $P0
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
291 $P0 = get_hll_global ['Bar'], 'baz'
293 if null $P0 goto is_null
303 =head2 How do I use lexical pads to have both a function scope and a
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?
321 find_name $P0, 'foo' # same thing
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?
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:
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
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:
373 newclass $P0, 'Animal'
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:
384 addattribute $P0, 'legs'
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:
395 .namespace [ 'Animal' ]
398 print "slow and steady\n"
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.
410 .namespace [ 'NearlyPi' ]
412 .sub get_string :vtable
413 .return ('three and a half')
418 Now, given an instance of NearlyPi in $P0
423 say $S0 # prints 'three and a half'
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:
451 get_class $P0, 'Animal'
455 Then you can use the C<subclass> op to create a new class that is a
456 subclass of this class:
460 subclass $P1, $P0, 'Dog'
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
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:
481 subclass $P2, $P1, 'SmallDog'
483 addparent $P2, $P3 # make "SmallDog" also a "Pet"
487 =head2 How can I specify the constructor of a class?
489 Just override the init vtable for that class.
494 newclass $P0, 'Dog' # create a class named Dog
505 Or you can specify the constructor method by setting the BUILD
506 property of the class PMC:
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
517 =head2 How do I instantiate a class?
519 You can do so either with the class name:
527 or with the class object:
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"
536 new $P0, $P1 # creates a Dog object and stores it in register $P0
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
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
563 =head2 How do I add module/class methods?
567 =head2 How do I access module/class variables?
573 =head2 How do I throw an exception in PIR?
575 The easiest way is the perl-like
583 You can also explicitly create an exception object and throw it:
587 $P0 = new 'Exception'
588 $P0 = 'something happened'
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
602 die 'whoops' # or any other code that might throw an exception...
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:
615 print 'Exception caught:'
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>.
627 .include 'except_severity.pasm'
631 $I0 = $P0['severity']
632 if $I0 == .EXCEPT_EXIT goto handle_exit
633 say 'Exception caught!'
637 rethrow $P0 # let the next handler deal with it.
646 $P0 = new 'Exception'
647 $P0 = 'something happened'
654 .local string message
655 .get_results (exception)
657 message = exception['message']
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 See L<src/dynpmc/Makefile> for an example of how to build your dynamic
675 =head2 How do I add another op to Parrot?
677 Parrot supports dynamic op libraries. These allow for ops specific to one
678 language to be used without having to place them into the Parrot core itself.
679 For examples of dynamic op libraries, see L<src/dynoplibs>.
681 =head2 How do I use the Native Calling Interface (NCI)?
683 Using the NCI you can invoke functions written in C from a Parrot script.
684 To every NCI invocation, there are two parts: the native function to be invoked,
685 and the PIR code to do the invocation.
687 First the native function, to be written in C. On Windows, it is necessary
688 to do a DLL export specification of the NCI function:
692 /* specify the function prototype */
694 __declspec(dllexport) void foo(void);
700 printf("Hello Parrot!\n");
703 Then, after having compiled the file as a shared library, the PIR code looks
711 # load the shared library
712 lib = loadlib "hello" # no extension, .so or .dll is assumed
714 # get a reference to the function from the library just
715 # loaded, called "foo", and signature "void" (and no arguments)
716 func = dlfunc lib, "foo", "v"
725 If you embedded a Parrot in your C file and you want to invoke another function
726 in that same C file, you should pass a null string to loadlib. Do that as follows:
731 .local string libname
734 lib = loadlib libname
738 Under Linux, the .c file must then be linked with the -export-dynamic option.
742 =head2 How can I access a program's environment?
744 Create a new C<Env> PMC and access it like a hash.
754 =head2 How can I access Parrot's configuration?
758 .include 'iglobals.pasm'
759 .local pmc interp, cfg
761 cfg = interp[.IGLOBALS_CONFIG_HASH]
762 $S0 = cfg['VERSION'] # "0.3.0"
766 See F<config_lib.pasm> for all the keys in the config hash - or iterate over