This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Eliminate opASSIGN macro usage from core
[perl5.git] / pod / perlinterp.pod
CommitLineData
04c692a8
DR
1=encoding utf8
2
3=for comment
4Consistent formatting of this file is achieved with:
5 perl ./Porting/podtidy pod/perlinterp.pod
6
7=head1 NAME
8
9perlinterp - An overview of the Perl interpreter
10
11=head1 DESCRIPTION
12
13This document provides an overview of how the Perl interpreter works at
14the level of C code, along with pointers to the relevant C source code
15files.
16
17=head1 ELEMENTS OF THE INTERPRETER
18
19The work of the interpreter has two main stages: compiling the code
20into the internal representation, or bytecode, and then executing it.
21L<perlguts/Compiled code> explains exactly how the compilation stage
22happens.
23
24Here is a short breakdown of perl's operation:
25
26=head2 Startup
27
28The action begins in F<perlmain.c>. (or F<miniperlmain.c> for miniperl)
29This is very high-level code, enough to fit on a single screen, and it
30resembles the code found in L<perlembed>; most of the real action takes
31place in F<perl.c>
32
33F<perlmain.c> is generated by C<ExtUtils::Miniperl> from
34F<miniperlmain.c> at make time, so you should make perl to follow this
35along.
36
37First, F<perlmain.c> allocates some memory and constructs a Perl
38interpreter, along these lines:
39
40 1 PERL_SYS_INIT3(&argc,&argv,&env);
41 2
42 3 if (!PL_do_undump) {
43 4 my_perl = perl_alloc();
44 5 if (!my_perl)
45 6 exit(1);
46 7 perl_construct(my_perl);
47 8 PL_perl_destruct_level = 0;
48 9 }
49
50Line 1 is a macro, and its definition is dependent on your operating
51system. Line 3 references C<PL_do_undump>, a global variable - all
52global variables in Perl start with C<PL_>. This tells you whether the
53current running program was created with the C<-u> flag to perl and
54then F<undump>, which means it's going to be false in any sane context.
55
56Line 4 calls a function in F<perl.c> to allocate memory for a Perl
57interpreter. It's quite a simple function, and the guts of it looks
58like this:
59
60 my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
61
62Here you see an example of Perl's system abstraction, which we'll see
63later: C<PerlMem_malloc> is either your system's C<malloc>, or Perl's
64own C<malloc> as defined in F<malloc.c> if you selected that option at
65configure time.
66
67Next, in line 7, we construct the interpreter using perl_construct,
68also in F<perl.c>; this sets up all the special variables that Perl
69needs, the stacks, and so on.
70
71Now we pass Perl the command line options, and tell it to go:
72
fe2024f9 73 if (!perl_parse(my_perl, xs_init, argc, argv, (char **)NULL))
04c692a8
DR
74 perl_run(my_perl);
75
76 exitstatus = perl_destruct(my_perl);
77
78 perl_free(my_perl);
79
80C<perl_parse> is actually a wrapper around C<S_parse_body>, as defined
81in F<perl.c>, which processes the command line options, sets up any
82statically linked XS modules, opens the program and calls C<yyparse> to
83parse it.
84
85=head2 Parsing
86
87The aim of this stage is to take the Perl source, and turn it into an
88op tree. We'll see what one of those looks like later. Strictly
89speaking, there's three things going on here.
90
91C<yyparse>, the parser, lives in F<perly.c>, although you're better off
92reading the original YACC input in F<perly.y>. (Yes, Virginia, there
93B<is> a YACC grammar for Perl!) The job of the parser is to take your
94code and "understand" it, splitting it into sentences, deciding which
95operands go with which operators and so on.
96
97The parser is nobly assisted by the lexer, which chunks up your input
98into tokens, and decides what type of thing each token is: a variable
99name, an operator, a bareword, a subroutine, a core function, and so
100on. The main point of entry to the lexer is C<yylex>, and that and its
101associated routines can be found in F<toke.c>. Perl isn't much like
102other computer languages; it's highly context sensitive at times, it
103can be tricky to work out what sort of token something is, or where a
104token ends. As such, there's a lot of interplay between the tokeniser
105and the parser, which can get pretty frightening if you're not used to
106it.
107
108As the parser understands a Perl program, it builds up a tree of
109operations for the interpreter to perform during execution. The
110routines which construct and link together the various operations are
111to be found in F<op.c>, and will be examined later.
112
113=head2 Optimization
114
115Now the parsing stage is complete, and the finished tree represents the
116operations that the Perl interpreter needs to perform to execute our
117program. Next, Perl does a dry run over the tree looking for
118optimisations: constant expressions such as C<3 + 4> will be computed
119now, and the optimizer will also see if any multiple operations can be
120replaced with a single one. For instance, to fetch the variable
121C<$foo>, instead of grabbing the glob C<*foo> and looking at the scalar
122component, the optimizer fiddles the op tree to use a function which
123directly looks up the scalar in question. The main optimizer is C<peep>
124in F<op.c>, and many ops have their own optimizing functions.
125
126=head2 Running
127
128Now we're finally ready to go: we have compiled Perl byte code, and all
129that's left to do is run it. The actual execution is done by the
130C<runops_standard> function in F<run.c>; more specifically, it's done
131by these three innocent looking lines:
132
133 while ((PL_op = PL_op->op_ppaddr(aTHX))) {
134 PERL_ASYNC_CHECK();
135 }
136
137You may be more comfortable with the Perl version of that:
138
139 PERL_ASYNC_CHECK() while $Perl::op = &{$Perl::op->{function}};
140
141Well, maybe not. Anyway, each op contains a function pointer, which
142stipulates the function which will actually carry out the operation.
143This function will return the next op in the sequence - this allows for
144things like C<if> which choose the next op dynamically at run time. The
145C<PERL_ASYNC_CHECK> makes sure that things like signals interrupt
146execution if required.
147
148The actual functions called are known as PP code, and they're spread
149between four files: F<pp_hot.c> contains the "hot" code, which is most
150often used and highly optimized, F<pp_sys.c> contains all the
151system-specific functions, F<pp_ctl.c> contains the functions which
152implement control structures (C<if>, C<while> and the like) and F<pp.c>
153contains everything else. These are, if you like, the C code for Perl's
154built-in functions and operators.
155
156Note that each C<pp_> function is expected to return a pointer to the
157next op. Calls to perl subs (and eval blocks) are handled within the
158same runops loop, and do not consume extra space on the C stack. For
159example, C<pp_entersub> and C<pp_entertry> just push a C<CxSUB> or
160C<CxEVAL> block struct onto the context stack which contain the address
161of the op following the sub call or eval. They then return the first op
162of that sub or eval block, and so execution continues of that sub or
163block. Later, a C<pp_leavesub> or C<pp_leavetry> op pops the C<CxSUB>
164or C<CxEVAL>, retrieves the return op from it, and returns it.
165
166=head2 Exception handing
167
168Perl's exception handing (i.e. C<die> etc.) is built on top of the
169low-level C<setjmp()>/C<longjmp()> C-library functions. These basically
170provide a way to capture the current PC and SP registers and later
171restore them; i.e. a C<longjmp()> continues at the point in code where
172a previous C<setjmp()> was done, with anything further up on the C
173stack being lost. This is why code should always save values using
174C<SAVE_FOO> rather than in auto variables.
175
176The perl core wraps C<setjmp()> etc in the macros C<JMPENV_PUSH> and
177C<JMPENV_JUMP>. The basic rule of perl exceptions is that C<exit>, and
178C<die> (in the absence of C<eval>) perform a C<JMPENV_JUMP(2)>, while
179C<die> within C<eval> does a C<JMPENV_JUMP(3)>.
180
181At entry points to perl, such as C<perl_parse()>, C<perl_run()> and
182C<call_sv(cv, G_EVAL)> each does a C<JMPENV_PUSH>, then enter a runops
183loop or whatever, and handle possible exception returns. For a 2
184return, final cleanup is performed, such as popping stacks and calling
185C<CHECK> or C<END> blocks. Amongst other things, this is how scope
186cleanup still occurs during an C<exit>.
187
188If a C<die> can find a C<CxEVAL> block on the context stack, then the
189stack is popped to that level and the return op in that block is
190assigned to C<PL_restartop>; then a C<JMPENV_JUMP(3)> is performed.
191This normally passes control back to the guard. In the case of
192C<perl_run> and C<call_sv>, a non-null C<PL_restartop> triggers
193re-entry to the runops loop. The is the normal way that C<die> or
194C<croak> is handled within an C<eval>.
195
196Sometimes ops are executed within an inner runops loop, such as tie,
197sort or overload code. In this case, something like
198
199 sub FETCH { eval { die } }
200
201would cause a longjmp right back to the guard in C<perl_run>, popping
202both runops loops, which is clearly incorrect. One way to avoid this is
203for the tie code to do a C<JMPENV_PUSH> before executing C<FETCH> in
204the inner runops loop, but for efficiency reasons, perl in fact just
205sets a flag, using C<CATCH_SET(TRUE)>. The C<pp_require>,
206C<pp_entereval> and C<pp_entertry> ops check this flag, and if true,
207they call C<docatch>, which does a C<JMPENV_PUSH> and starts a new
208runops level to execute the code, rather than doing it on the current
209loop.
210
211As a further optimisation, on exit from the eval block in the C<FETCH>,
212execution of the code following the block is still carried on in the
213inner loop. When an exception is raised, C<docatch> compares the
214C<JMPENV> level of the C<CxEVAL> with C<PL_top_env> and if they differ,
215just re-throws the exception. In this way any inner loops get popped.
216
217Here's an example.
218
219 1: eval { tie @a, 'A' };
220 2: sub A::TIEARRAY {
221 3: eval { die };
222 4: die;
223 5: }
224
225To run this code, C<perl_run> is called, which does a C<JMPENV_PUSH>
226then enters a runops loop. This loop executes the eval and tie ops on
227line 1, with the eval pushing a C<CxEVAL> onto the context stack.
228
229The C<pp_tie> does a C<CATCH_SET(TRUE)>, then starts a second runops
230loop to execute the body of C<TIEARRAY>. When it executes the entertry
231op on line 3, C<CATCH_GET> is true, so C<pp_entertry> calls C<docatch>
232which does a C<JMPENV_PUSH> and starts a third runops loop, which then
233executes the die op. At this point the C call stack looks like this:
234
235 Perl_pp_die
236 Perl_runops # third loop
237 S_docatch_body
238 S_docatch
239 Perl_pp_entertry
240 Perl_runops # second loop
241 S_call_body
242 Perl_call_sv
243 Perl_pp_tie
244 Perl_runops # first loop
245 S_run_body
246 perl_run
247 main
248
249and the context and data stacks, as shown by C<-Dstv>, look like:
250
251 STACK 0: MAIN
252 CX 0: BLOCK =>
253 CX 1: EVAL => AV() PV("A"\0)
254 retop=leave
255 STACK 1: MAGIC
256 CX 0: SUB =>
257 retop=(null)
258 CX 1: EVAL => *
259 retop=nextstate
260
261The die pops the first C<CxEVAL> off the context stack, sets
262C<PL_restartop> from it, does a C<JMPENV_JUMP(3)>, and control returns
263to the top C<docatch>. This then starts another third-level runops
264level, which executes the nextstate, pushmark and die ops on line 4. At
265the point that the second C<pp_die> is called, the C call stack looks
266exactly like that above, even though we are no longer within an inner
267eval; this is because of the optimization mentioned earlier. However,
268the context stack now looks like this, ie with the top CxEVAL popped:
269
270 STACK 0: MAIN
271 CX 0: BLOCK =>
272 CX 1: EVAL => AV() PV("A"\0)
273 retop=leave
274 STACK 1: MAGIC
275 CX 0: SUB =>
276 retop=(null)
277
278The die on line 4 pops the context stack back down to the CxEVAL,
279leaving it as:
280
281 STACK 0: MAIN
282 CX 0: BLOCK =>
283
284As usual, C<PL_restartop> is extracted from the C<CxEVAL>, and a
285C<JMPENV_JUMP(3)> done, which pops the C stack back to the docatch:
286
287 S_docatch
288 Perl_pp_entertry
289 Perl_runops # second loop
290 S_call_body
291 Perl_call_sv
292 Perl_pp_tie
293 Perl_runops # first loop
294 S_run_body
295 perl_run
296 main
297
298In this case, because the C<JMPENV> level recorded in the C<CxEVAL>
299differs from the current one, C<docatch> just does a C<JMPENV_JUMP(3)>
300and the C stack unwinds to:
301
302 perl_run
303 main
304
305Because C<PL_restartop> is non-null, C<run_body> starts a new runops
306loop and execution continues.
307
308=head2 INTERNAL VARIABLE TYPES
309
310You should by now have had a look at L<perlguts>, which tells you about
311Perl's internal variable types: SVs, HVs, AVs and the rest. If not, do
312that now.
313
314These variables are used not only to represent Perl-space variables,
315but also any constants in the code, as well as some structures
316completely internal to Perl. The symbol table, for instance, is an
317ordinary Perl hash. Your code is represented by an SV as it's read into
318the parser; any program files you call are opened via ordinary Perl
319filehandles, and so on.
320
321The core L<Devel::Peek|Devel::Peek> module lets us examine SVs from a
322Perl program. Let's see, for instance, how Perl treats the constant
323C<"hello">.
324
325 % perl -MDevel::Peek -e 'Dump("hello")'
326 1 SV = PV(0xa041450) at 0xa04ecbc
327 2 REFCNT = 1
328 3 FLAGS = (POK,READONLY,pPOK)
329 4 PV = 0xa0484e0 "hello"\0
330 5 CUR = 5
331 6 LEN = 6
332
333Reading C<Devel::Peek> output takes a bit of practise, so let's go
334through it line by line.
335
336Line 1 tells us we're looking at an SV which lives at C<0xa04ecbc> in
337memory. SVs themselves are very simple structures, but they contain a
338pointer to a more complex structure. In this case, it's a PV, a
339structure which holds a string value, at location C<0xa041450>. Line 2
340is the reference count; there are no other references to this data, so
341it's 1.
342
343Line 3 are the flags for this SV - it's OK to use it as a PV, it's a
344read-only SV (because it's a constant) and the data is a PV internally.
345Next we've got the contents of the string, starting at location
346C<0xa0484e0>.
347
348Line 5 gives us the current length of the string - note that this does
349B<not> include the null terminator. Line 6 is not the length of the
350string, but the length of the currently allocated buffer; as the string
351grows, Perl automatically extends the available storage via a routine
352called C<SvGROW>.
353
354You can get at any of these quantities from C very easily; just add
355C<Sv> to the name of the field shown in the snippet, and you've got a
356macro which will return the value: C<SvCUR(sv)> returns the current
357length of the string, C<SvREFCOUNT(sv)> returns the reference count,
358C<SvPV(sv, len)> returns the string itself with its length, and so on.
359More macros to manipulate these properties can be found in L<perlguts>.
360
361Let's take an example of manipulating a PV, from C<sv_catpvn>, in
362F<sv.c>
363
364 1 void
5aaab254 365 2 Perl_sv_catpvn(pTHX_ SV *sv, const char *ptr, STRLEN len)
04c692a8
DR
366 3 {
367 4 STRLEN tlen;
368 5 char *junk;
369
370 6 junk = SvPV_force(sv, tlen);
371 7 SvGROW(sv, tlen + len + 1);
372 8 if (ptr == junk)
373 9 ptr = SvPVX(sv);
374 10 Move(ptr,SvPVX(sv)+tlen,len,char);
375 11 SvCUR(sv) += len;
376 12 *SvEND(sv) = '\0';
377 13 (void)SvPOK_only_UTF8(sv); /* validate pointer */
378 14 SvTAINT(sv);
379 15 }
380
381This is a function which adds a string, C<ptr>, of length C<len> onto
382the end of the PV stored in C<sv>. The first thing we do in line 6 is
383make sure that the SV B<has> a valid PV, by calling the C<SvPV_force>
384macro to force a PV. As a side effect, C<tlen> gets set to the current
385value of the PV, and the PV itself is returned to C<junk>.
386
387In line 7, we make sure that the SV will have enough room to
388accommodate the old string, the new string and the null terminator. If
389C<LEN> isn't big enough, C<SvGROW> will reallocate space for us.
390
391Now, if C<junk> is the same as the string we're trying to add, we can
392grab the string directly from the SV; C<SvPVX> is the address of the PV
393in the SV.
394
395Line 10 does the actual catenation: the C<Move> macro moves a chunk of
396memory around: we move the string C<ptr> to the end of the PV - that's
397the start of the PV plus its current length. We're moving C<len> bytes
398of type C<char>. After doing so, we need to tell Perl we've extended
399the string, by altering C<CUR> to reflect the new length. C<SvEND> is a
400macro which gives us the end of the string, so that needs to be a
401C<"\0">.
402
403Line 13 manipulates the flags; since we've changed the PV, any IV or NV
404values will no longer be valid: if we have C<$a=10; $a.="6";> we don't
405want to use the old IV of 10. C<SvPOK_only_utf8> is a special
406UTF-8-aware version of C<SvPOK_only>, a macro which turns off the IOK
407and NOK flags and turns on POK. The final C<SvTAINT> is a macro which
408launders tainted data if taint mode is turned on.
409
410AVs and HVs are more complicated, but SVs are by far the most common
411variable type being thrown around. Having seen something of how we
412manipulate these, let's go on and look at how the op tree is
413constructed.
414
415=head1 OP TREES
416
417First, what is the op tree, anyway? The op tree is the parsed
418representation of your program, as we saw in our section on parsing,
419and it's the sequence of operations that Perl goes through to execute
420your program, as we saw in L</Running>.
421
422An op is a fundamental operation that Perl can perform: all the
423built-in functions and operators are ops, and there are a series of ops
424which deal with concepts the interpreter needs internally - entering
425and leaving a block, ending a statement, fetching a variable, and so
426on.
427
428The op tree is connected in two ways: you can imagine that there are
429two "routes" through it, two orders in which you can traverse the tree.
430First, parse order reflects how the parser understood the code, and
431secondly, execution order tells perl what order to perform the
432operations in.
433
434The easiest way to examine the op tree is to stop Perl after it has
435finished parsing, and get it to dump out the tree. This is exactly what
436the compiler backends L<B::Terse|B::Terse>, L<B::Concise|B::Concise>
903b1101 437and CPAN module <B::Debug do.
04c692a8
DR
438
439Let's have a look at how Perl sees C<$a = $b + $c>:
440
441 % perl -MO=Terse -e '$a=$b+$c'
442 1 LISTOP (0x8179888) leave
443 2 OP (0x81798b0) enter
444 3 COP (0x8179850) nextstate
445 4 BINOP (0x8179828) sassign
446 5 BINOP (0x8179800) add [1]
447 6 UNOP (0x81796e0) null [15]
448 7 SVOP (0x80fafe0) gvsv GV (0x80fa4cc) *b
449 8 UNOP (0x81797e0) null [15]
450 9 SVOP (0x8179700) gvsv GV (0x80efeb0) *c
451 10 UNOP (0x816b4f0) null [15]
452 11 SVOP (0x816dcf0) gvsv GV (0x80fa460) *a
453
454Let's start in the middle, at line 4. This is a BINOP, a binary
455operator, which is at location C<0x8179828>. The specific operator in
456question is C<sassign> - scalar assignment - and you can find the code
457which implements it in the function C<pp_sassign> in F<pp_hot.c>. As a
458binary operator, it has two children: the add operator, providing the
459result of C<$b+$c>, is uppermost on line 5, and the left hand side is
460on line 10.
461
462Line 10 is the null op: this does exactly nothing. What is that doing
463there? If you see the null op, it's a sign that something has been
464optimized away after parsing. As we mentioned in L</Optimization>, the
465optimization stage sometimes converts two operations into one, for
466example when fetching a scalar variable. When this happens, instead of
467rewriting the op tree and cleaning up the dangling pointers, it's
468easier just to replace the redundant operation with the null op.
469Originally, the tree would have looked like this:
470
471 10 SVOP (0x816b4f0) rv2sv [15]
472 11 SVOP (0x816dcf0) gv GV (0x80fa460) *a
473
474That is, fetch the C<a> entry from the main symbol table, and then look
f672247c 475at the scalar component of it: C<gvsv> (C<pp_gvsv> in F<pp_hot.c>)
04c692a8
DR
476happens to do both these things.
477
478The right hand side, starting at line 5 is similar to what we've just
f672247c 479seen: we have the C<add> op (C<pp_add>, also in F<pp_hot.c>) add
04c692a8
DR
480together two C<gvsv>s.
481
482Now, what's this about?
483
484 1 LISTOP (0x8179888) leave
485 2 OP (0x81798b0) enter
486 3 COP (0x8179850) nextstate
487
488C<enter> and C<leave> are scoping ops, and their job is to perform any
489housekeeping every time you enter and leave a block: lexical variables
490are tidied up, unreferenced variables are destroyed, and so on. Every
491program will have those first three lines: C<leave> is a list, and its
492children are all the statements in the block. Statements are delimited
493by C<nextstate>, so a block is a collection of C<nextstate> ops, with
494the ops to be performed for each statement being the children of
495C<nextstate>. C<enter> is a single op which functions as a marker.
496
497That's how Perl parsed the program, from top to bottom:
498
499 Program
500 |
501 Statement
502 |
503 =
504 / \
505 / \
506 $a +
507 / \
508 $b $c
509
510However, it's impossible to B<perform> the operations in this order:
511you have to find the values of C<$b> and C<$c> before you add them
512together, for instance. So, the other thread that runs through the op
513tree is the execution order: each op has a field C<op_next> which
514points to the next op to be run, so following these pointers tells us
515how perl executes the code. We can traverse the tree in this order
516using the C<exec> option to C<B::Terse>:
517
518 % perl -MO=Terse,exec -e '$a=$b+$c'
519 1 OP (0x8179928) enter
520 2 COP (0x81798c8) nextstate
521 3 SVOP (0x81796c8) gvsv GV (0x80fa4d4) *b
522 4 SVOP (0x8179798) gvsv GV (0x80efeb0) *c
523 5 BINOP (0x8179878) add [1]
524 6 SVOP (0x816dd38) gvsv GV (0x80fa468) *a
525 7 BINOP (0x81798a0) sassign
526 8 LISTOP (0x8179900) leave
527
528This probably makes more sense for a human: enter a block, start a
529statement. Get the values of C<$b> and C<$c>, and add them together.
530Find C<$a>, and assign one to the other. Then leave.
531
532The way Perl builds up these op trees in the parsing process can be
65169990
FC
533unravelled by examining F<toke.c>, the lexer, and F<perly.y>, the YACC
534grammar. Let's look at the code that constructs the tree for C<$a = $b +
535$c>.
536
537First, we'll look at the C<Perl_yylex> function in the lexer. We want to
538look for C<case 'x'>, where x is the first character of the operator.
539(Incidentally, when looking for the code that handles a keyword, you'll
540want to search for C<KEY_foo> where "foo" is the keyword.) Here is the code
541that handles assignment (there are quite a few operators beginning with
542C<=>, so most of it is omitted for brevity):
543
544 1 case '=':
545 2 s++;
546 ... code that handles == => etc. and pod ...
547 3 pl_yylval.ival = 0;
548 4 OPERATOR(ASSIGNOP);
549
550We can see on line 4 that our token type is C<ASSIGNOP> (C<OPERATOR> is a
551macro, defined in F<toke.c>, that returns the token type, among other
552things). And C<+>:
553
554 1 case '+':
555 2 {
556 3 const char tmp = *s++;
557 ... code for ++ ...
558 4 if (PL_expect == XOPERATOR) {
559 ...
560 5 Aop(OP_ADD);
561 6 }
562 ...
563 7 }
564
565Line 4 checks what type of token we are expecting. C<Aop> returns a token.
566If you search for C<Aop> elsewhere in F<toke.c>, you will see that it
567returns an C<ADDOP> token.
568
569Now that we know the two token types we want to look for in the parser,
570let's take the piece of F<perly.y> we need to construct the tree for
571C<$a = $b + $c>
04c692a8
DR
572
573 1 term : term ASSIGNOP term
574 2 { $$ = newASSIGNOP(OPf_STACKED, $1, $2, $3); }
575 3 | term ADDOP term
576 4 { $$ = newBINOP($2, 0, scalar($1), scalar($3)); }
577
578If you're not used to reading BNF grammars, this is how it works:
579You're fed certain things by the tokeniser, which generally end up in
65169990
FC
580upper case. C<ADDOP> and C<ASSIGNOP> are examples of "terminal symbols",
581because you can't get any simpler than
04c692a8
DR
582them.
583
584The grammar, lines one and three of the snippet above, tells you how to
585build up more complex forms. These complex forms, "non-terminal
586symbols" are generally placed in lower case. C<term> here is a
587non-terminal symbol, representing a single expression.
588
589The grammar gives you the following rule: you can make the thing on the
590left of the colon if you see all the things on the right in sequence.
591This is called a "reduction", and the aim of parsing is to completely
592reduce the input. There are several different ways you can perform a
593reduction, separated by vertical bars: so, C<term> followed by C<=>
594followed by C<term> makes a C<term>, and C<term> followed by C<+>
595followed by C<term> can also make a C<term>.
596
597So, if you see two terms with an C<=> or C<+>, between them, you can
598turn them into a single expression. When you do this, you execute the
599code in the block on the next line: if you see C<=>, you'll do the code
600in line 2. If you see C<+>, you'll do the code in line 4. It's this
601code which contributes to the op tree.
602
603 | term ADDOP term
604 { $$ = newBINOP($2, 0, scalar($1), scalar($3)); }
605
606What this does is creates a new binary op, and feeds it a number of
607variables. The variables refer to the tokens: C<$1> is the first token
608in the input, C<$2> the second, and so on - think regular expression
609backreferences. C<$$> is the op returned from this reduction. So, we
610call C<newBINOP> to create a new binary operator. The first parameter
611to C<newBINOP>, a function in F<op.c>, is the op type. It's an addition
612operator, so we want the type to be C<ADDOP>. We could specify this
613directly, but it's right there as the second token in the input, so we
614use C<$2>. The second parameter is the op's flags: 0 means "nothing
615special". Then the things to add: the left and right hand side of our
616expression, in scalar context.
617
65169990
FC
618The functions that create ops, which have names like C<newUNOP> and
619C<newBINOP>, call a "check" function associated with each op type, before
620returning the op. The check functions can mangle the op as they see fit,
621and even replace it with an entirely new one. These functions are defined
622in F<op.c>, and have a C<Perl_ck_> prefix. You can find out which
623check function is used for a particular op type by looking in
624F<regen/opcodes>. Take C<OP_ADD>, for example. (C<OP_ADD> is the token
625value from the C<Aop(OP_ADD)> in F<toke.c> which the parser passes to
626C<newBINOP> as its first argument.) Here is the relevant line:
627
628 add addition (+) ck_null IfsT2 S S
629
630The check function in this case is C<Perl_ck_null>, which does nothing.
631Let's look at a more interesting case:
632
633 readline <HANDLE> ck_readline t% F?
634
635And here is the function from F<op.c>:
636
637 1 OP *
638 2 Perl_ck_readline(pTHX_ OP *o)
639 3 {
640 4 PERL_ARGS_ASSERT_CK_READLINE;
641 5
642 6 if (o->op_flags & OPf_KIDS) {
643 7 OP *kid = cLISTOPo->op_first;
644 8 if (kid->op_type == OP_RV2GV)
645 9 kid->op_private |= OPpALLOW_FAKE;
646 10 }
647 11 else {
648 12 OP * const newop
649 13 = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0,
650 14 PL_argvgv));
651 15 op_free(o);
652 16 return newop;
653 17 }
654 18 return o;
655 19 }
656
a1ac675e 657One particularly interesting aspect is that if the op has no kids (i.e.,
65169990
FC
658C<readline()> or C<< <> >>) the op is freed and replaced with an entirely
659new one that references C<*ARGV> (lines 12-16).
660
04c692a8
DR
661=head1 STACKS
662
663When perl executes something like C<addop>, how does it pass on its
664results to the next op? The answer is, through the use of stacks. Perl
665has a number of stacks to store things it's currently working on, and
666we'll look at the three most important ones here.
667
668=head2 Argument stack
669
670Arguments are passed to PP code and returned from PP code using the
671argument stack, C<ST>. The typical way to handle arguments is to pop
672them off the stack, deal with them how you wish, and then push the
673result back onto the stack. This is how, for instance, the cosine
674operator works:
675
676 NV value;
677 value = POPn;
678 value = Perl_cos(value);
679 XPUSHn(value);
680
681We'll see a more tricky example of this when we consider Perl's macros
682below. C<POPn> gives you the NV (floating point value) of the top SV on
683the stack: the C<$x> in C<cos($x)>. Then we compute the cosine, and
684push the result back as an NV. The C<X> in C<XPUSHn> means that the
685stack should be extended if necessary - it can't be necessary here,
686because we know there's room for one more item on the stack, since
687we've just removed one! The C<XPUSH*> macros at least guarantee safety.
688
689Alternatively, you can fiddle with the stack directly: C<SP> gives you
690the first element in your portion of the stack, and C<TOP*> gives you
691the top SV/IV/NV/etc. on the stack. So, for instance, to do unary
692negation of an integer:
693
694 SETi(-TOPi);
695
696Just set the integer value of the top stack entry to its negation.
697
698Argument stack manipulation in the core is exactly the same as it is in
699XSUBs - see L<perlxstut>, L<perlxs> and L<perlguts> for a longer
700description of the macros used in stack manipulation.
701
702=head2 Mark stack
703
704I say "your portion of the stack" above because PP code doesn't
705necessarily get the whole stack to itself: if your function calls
706another function, you'll only want to expose the arguments aimed for
707the called function, and not (necessarily) let it get at your own data.
708The way we do this is to have a "virtual" bottom-of-stack, exposed to
709each function. The mark stack keeps bookmarks to locations in the
710argument stack usable by each function. For instance, when dealing with
711a tied variable, (internally, something with "P" magic) Perl has to
712call methods for accesses to the tied variables. However, we need to
713separate the arguments exposed to the method to the argument exposed to
714the original function - the store or fetch or whatever it may be.
715Here's roughly how the tied C<push> is implemented; see C<av_push> in
716F<av.c>:
717
718 1 PUSHMARK(SP);
719 2 EXTEND(SP,2);
720 3 PUSHs(SvTIED_obj((SV*)av, mg));
721 4 PUSHs(val);
722 5 PUTBACK;
723 6 ENTER;
724 7 call_method("PUSH", G_SCALAR|G_DISCARD);
725 8 LEAVE;
726
727Let's examine the whole implementation, for practice:
728
729 1 PUSHMARK(SP);
730
731Push the current state of the stack pointer onto the mark stack. This
732is so that when we've finished adding items to the argument stack, Perl
733knows how many things we've added recently.
734
735 2 EXTEND(SP,2);
736 3 PUSHs(SvTIED_obj((SV*)av, mg));
737 4 PUSHs(val);
738
739We're going to add two more items onto the argument stack: when you
740have a tied array, the C<PUSH> subroutine receives the object and the
741value to be pushed, and that's exactly what we have here - the tied
742object, retrieved with C<SvTIED_obj>, and the value, the SV C<val>.
743
744 5 PUTBACK;
745
746Next we tell Perl to update the global stack pointer from our internal
747variable: C<dSP> only gave us a local copy, not a reference to the
748global.
749
750 6 ENTER;
751 7 call_method("PUSH", G_SCALAR|G_DISCARD);
752 8 LEAVE;
753
754C<ENTER> and C<LEAVE> localise a block of code - they make sure that
755all variables are tidied up, everything that has been localised gets
756its previous value returned, and so on. Think of them as the C<{> and
757C<}> of a Perl block.
758
759To actually do the magic method call, we have to call a subroutine in
760Perl space: C<call_method> takes care of that, and it's described in
761L<perlcall>. We call the C<PUSH> method in scalar context, and we're
762going to discard its return value. The call_method() function removes
763the top element of the mark stack, so there is nothing for the caller
764to clean up.
765
766=head2 Save stack
767
768C doesn't have a concept of local scope, so perl provides one. We've
769seen that C<ENTER> and C<LEAVE> are used as scoping braces; the save
770stack implements the C equivalent of, for example:
771
772 {
773 local $foo = 42;
774 ...
775 }
776
548d0ee5 777See L<perlguts/"Localizing changes"> for how to use the save stack.
04c692a8
DR
778
779=head1 MILLIONS OF MACROS
780
781One thing you'll notice about the Perl source is that it's full of
782macros. Some have called the pervasive use of macros the hardest thing
783to understand, others find it adds to clarity. Let's take an example,
72876cce 784a stripped-down version the code which implements the addition operator:
04c692a8
DR
785
786 1 PP(pp_add)
787 2 {
72876cce
DM
788 3 dSP; dATARGET;
789 4 tryAMAGICbin_MG(add_amg, AMGf_assign|AMGf_numeric);
790 5 {
791 6 dPOPTOPnnrl_ul;
792 7 SETn( left + right );
793 8 RETURN;
794 9 }
795 10 }
04c692a8
DR
796
797Every line here (apart from the braces, of course) contains a macro.
798The first line sets up the function declaration as Perl expects for PP
799code; line 3 sets up variable declarations for the argument stack and
72876cce 800the target, the return value of the operation. Line 4 tries to see
04c692a8
DR
801if the addition operation is overloaded; if so, the appropriate
802subroutine is called.
803
72876cce 804Line 6 is another variable declaration - all variable declarations
04c692a8
DR
805start with C<d> - which pops from the top of the argument stack two NVs
806(hence C<nn>) and puts them into the variables C<right> and C<left>,
807hence the C<rl>. These are the two operands to the addition operator.
808Next, we call C<SETn> to set the NV of the return value to the result
809of adding the two values. This done, we return - the C<RETURN> macro
810makes sure that our return value is properly handled, and we pass the
811next operator to run back to the main run loop.
812
813Most of these macros are explained in L<perlapi>, and some of the more
814important ones are explained in L<perlxs> as well. Pay special
815attention to L<perlguts/Background and PERL_IMPLICIT_CONTEXT> for
816information on the C<[pad]THX_?> macros.
817
818=head1 FURTHER READING
819
820For more information on the Perl internals, please see the documents
821listed at L<perl/Internals and C Language Interface>.