Debian Codegraph @

upstream/mageia-cauldron/man1/perlinterp.1

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man v6.0.2 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\"
56 .\" Required to disable full justification in groff 1.23.0.
57 .if n .ds AD l
58 .\" ========================================================================
59 .\"
60 .IX Title "PERLINTERP 1"
61 .TH PERLINTERP 1 2023-12-22 "perl v5.42.0" "Perl Programmers Reference Guide"
62 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
63 .\" way too many mistakes in technical documents.
64 .if n .ad l
65 .nh
66 .SH NAME
67 perlinterp \- An overview of the Perl interpreter
68 .SH DESCRIPTION
69 .IX Header "DESCRIPTION"
70 This document provides an overview of how the Perl interpreter works at
71 the level of C code, along with pointers to the relevant C source code
72 files.
73 .SH "ELEMENTS OF THE INTERPRETER"
74 .IX Header "ELEMENTS OF THE INTERPRETER"
75 The work of the interpreter has two main stages: compiling the code
76 into the internal representation, or bytecode, and then executing it.
77 "Compiled code" in perlguts explains exactly how the compilation stage
78 happens.
79 .PP
80 Here is a short breakdown of perl\*(Aqs operation:
81 .SS Startup
82 .IX Subsection "Startup"
83 The action begins in \fIperlmain.c\fR. (or \fIminiperlmain.c\fR for miniperl)
84 This is very high\-level code, enough to fit on a single screen, and it
85 resembles the code found in perlembed; most of the real action takes
86 place in \fIperl.c\fR
87 .PP
88 \&\fIperlmain.c\fR is generated by \f(CW\*(C`ExtUtils::Miniperl\*(C'\fR from
89 \&\fIminiperlmain.c\fR at make time, so you should make perl to follow this
90 along.
91 .PP
92 First, \fIperlmain.c\fR allocates some memory and constructs a Perl
93 interpreter, along these lines:
94 .PP
95 .Vb 9
96 \& 1 PERL_SYS_INIT3(&argc,&argv,&env);
97 \& 2
98 \& 3 if (!PL_do_undump) {
99 \& 4 my_perl = perl_alloc();
100 \& 5 if (!my_perl)
101 \& 6 exit(1);
102 \& 7 perl_construct(my_perl);
103 \& 8 PL_perl_destruct_level = 0;
104 \& 9 }
105 .Ve
106 .PP
107 Line 1 is a macro, and its definition is dependent on your operating
108 system. Line 3 references \f(CW\*(C`PL_do_undump\*(C'\fR, a global variable \- all
109 global variables in Perl start with \f(CW\*(C`PL_\*(C'\fR. This tells you whether the
110 current running program was created with the \f(CW\*(C`\-u\*(C'\fR flag to perl and
111 then \fIundump\fR, which means it\*(Aqs going to be false in any sane context.
112 .PP
113 Line 4 calls a function in \fIperl.c\fR to allocate memory for a Perl
114 interpreter. It\*(Aqs quite a simple function, and the guts of it looks
115 like this:
116 .PP
117 .Vb 1
118 \& my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
119 .Ve
120 .PP
121 Here you see an example of Perl\*(Aqs system abstraction, which we\*(Aqll see
122 later: \f(CW\*(C`PerlMem_malloc\*(C'\fR is either your system\*(Aqs \f(CW\*(C`malloc\*(C'\fR, or Perl\*(Aqs
123 own \f(CW\*(C`malloc\*(C'\fR as defined in \fImalloc.c\fR if you selected that option at
124 configure time.
125 .PP
126 Next, in line 7, we construct the interpreter using perl_construct,
127 also in \fIperl.c\fR; this sets up all the special variables that Perl
128 needs, the stacks, and so on.
129 .PP
130 Now we pass Perl the command line options, and tell it to go:
131 .PP
132 .Vb 2
133 \& if (!perl_parse(my_perl, xs_init, argc, argv, (char **)NULL))
134 \& perl_run(my_perl);
135 \&
136 \& exitstatus = perl_destruct(my_perl);
137 \&
138 \& perl_free(my_perl);
139 .Ve
140 .PP
141 \&\f(CW\*(C`perl_parse\*(C'\fR is actually a wrapper around \f(CW\*(C`S_parse_body\*(C'\fR, as defined
142 in \fIperl.c\fR, which processes the command line options, sets up any
143 statically linked XS modules, opens the program and calls \f(CW\*(C`yyparse\*(C'\fR to
144 parse it.
145 .SS Parsing
146 .IX Subsection "Parsing"
147 The aim of this stage is to take the Perl source, and turn it into an
148 op tree. We\*(Aqll see what one of those looks like later. Strictly
149 speaking, there\*(Aqs three things going on here.
150 .PP
151 \&\f(CW\*(C`yyparse\*(C'\fR, the parser, lives in \fIperly.c\fR, although you\*(Aqre better off
152 reading the original YACC input in \fIperly.y\fR. (Yes, Virginia, there
153 \&\fBis\fR a YACC grammar for Perl!) The job of the parser is to take your
154 code and "understand" it, splitting it into sentences, deciding which
155 operands go with which operators and so on.
156 .PP
157 The parser is nobly assisted by the lexer, which chunks up your input
158 into tokens, and decides what type of thing each token is: a variable
159 name, an operator, a bareword, a subroutine, a core function, and so
160 on. The main point of entry to the lexer is \f(CW\*(C`yylex\*(C'\fR, and that and its
161 associated routines can be found in \fItoke.c\fR. Perl isn\*(Aqt much like
162 other computer languages; it\*(Aqs highly context sensitive at times, it
163 can be tricky to work out what sort of token something is, or where a
164 token ends. As such, there\*(Aqs a lot of interplay between the tokeniser
165 and the parser, which can get pretty frightening if you\*(Aqre not used to
166 it.
167 .PP
168 As the parser understands a Perl program, it builds up a tree of
169 operations for the interpreter to perform during execution. The
170 routines which construct and link together the various operations are
171 to be found in \fIop.c\fR, and will be examined later.
172 .SS Optimization
173 .IX Subsection "Optimization"
174 Now the parsing stage is complete, and the finished tree represents the
175 operations that the Perl interpreter needs to perform to execute our
176 program. Next, Perl does a dry run over the tree looking for
177 optimisations: constant expressions such as \f(CW\*(C`3 + 4\*(C'\fR will be computed
178 now, and the optimizer will also see if any multiple operations can be
179 replaced with a single one. For instance, to fetch the variable
180 \&\f(CW$foo\fR, instead of grabbing the glob \f(CW*foo\fR and looking at the scalar
181 component, the optimizer fiddles the op tree to use a function which
182 directly looks up the scalar in question. The main optimizer is \f(CW\*(C`peep\*(C'\fR
183 in \fIop.c\fR, and many ops have their own optimizing functions.
184 .SS Running
185 .IX Subsection "Running"
186 Now we\*(Aqre finally ready to go: we have compiled Perl byte code, and all
187 that\*(Aqs left to do is run it. The actual execution is done by the
188 \&\f(CW\*(C`runops_standard\*(C'\fR function in \fIrun.c\fR; more specifically, it\*(Aqs done
189 by these three innocent looking lines:
190 .PP
191 .Vb 3
192 \& while ((PL_op = PL_op\->op_ppaddr(aTHX))) {
193 \& PERL_ASYNC_CHECK();
194 \& }
195 .Ve
196 .PP
197 You may be more comfortable with the Perl version of that:
198 .PP
199 .Vb 1
200 \& PERL_ASYNC_CHECK() while $Perl::op = &{$Perl::op\->{function}};
201 .Ve
202 .PP
203 Well, maybe not. Anyway, each op contains a function pointer, which
204 stipulates the function which will actually carry out the operation.
205 This function will return the next op in the sequence \- this allows for
206 things like \f(CW\*(C`if\*(C'\fR which choose the next op dynamically at run time. The
207 \&\f(CW\*(C`PERL_ASYNC_CHECK\*(C'\fR makes sure that things like signals interrupt
208 execution if required.
209 .PP
210 The actual functions called are known as PP code, and they\*(Aqre spread
211 between four files: \fIpp_hot.c\fR contains the "hot" code, which is most
212 often used and highly optimized, \fIpp_sys.c\fR contains all the
213 system\-specific functions, \fIpp_ctl.c\fR contains the functions which
214 implement control structures (\f(CW\*(C`if\*(C'\fR, \f(CW\*(C`while\*(C'\fR and the like) and \fIpp.c\fR
215 contains everything else. These are, if you like, the C code for Perl\*(Aqs
216 built\-in functions and operators.
217 .PP
218 Note that each \f(CW\*(C`pp_\*(C'\fR function is expected to return a pointer to the
219 next op. Calls to perl subs (and eval blocks) are handled within the
220 same runops loop, and do not consume extra space on the C stack. For
221 example, \f(CW\*(C`pp_entersub\*(C'\fR and \f(CW\*(C`pp_entertry\*(C'\fR just push a \f(CW\*(C`CXt_SUB\*(C'\fR or
222 \&\f(CW\*(C`CXt_EVAL\*(C'\fR block struct onto the context stack, which contain the address
223 of the op following the sub call or eval. They then return the first op
224 of that sub or eval block, and so execution continues of that sub or
225 block. Later, a \f(CW\*(C`pp_leavesub\*(C'\fR or \f(CW\*(C`pp_leavetry\*(C'\fR op pops the \f(CW\*(C`CXt_SUB\*(C'\fR
226 or \f(CW\*(C`CXt_EVAL\*(C'\fR, retrieves the return op from it, and returns it.
227 .SS "Exception handing"
228 .IX Subsection "Exception handing"
229 Perl\*(Aqs exception handing (i.e. \f(CW\*(C`die\*(C'\fR etc.) is built on top of the
230 low\-level \f(CWsetjmp()\fR/\f(CWlongjmp()\fR C\-library functions. These basically
231 provide a way to capture the current PC and SP registers of the CPU and
232 later restore them: i.e. a \f(CWlongjmp()\fR continues at the point in code
233 where a previous \f(CWsetjmp()\fR was done, with anything further up on the C
234 stack being lost. (This is why code should always save values using
235 \&\f(CW\*(C`SAVE_\fR\f(CIFOO\fR\f(CW\*(C'\fR rather than in auto variables.)
236 .PP
237 The perl core wraps \f(CWsetjmp()\fR and \f(CWlongjmp()\fR in the macros
238 \&\f(CW\*(C`JMPENV_PUSH\*(C'\fR and \f(CW\*(C`JMPENV_JUMP\*(C'\fR. The push operation, as well as setting
239 a \f(CWsetjump()\fR, stores some temporary state in a struct local to the
240 current function (allocated by \f(CW\*(C`dJMPENV\*(C'\fR). In particular, it stores a
241 pointer to the previous \f(CW\*(C`JMPENV\*(C'\fR struct, and updates \f(CW\*(C`PL_top_env\*(C'\fR to
242 point to the newest one, forming a chain of \f(CW\*(C`JMPENV\*(C'\fR states. Both the
243 push and jump can output debugging information under \f(CW\*(C`perl \-Dl\*(C'\fR.
244 .PP
245 A basic rule of the perl internals is that all interpreter exits are
246 achieved via a \f(CWJMPENV_JUMP()\fR. In particular:
247 .IP \(bu 4
248 level 2: perl\-level \fBexit()\fR and internals \fBmy_exit()\fR
249 .Sp
250 These unwind all stacks, then perform a \fBJMPENV_JUMP\fR\|(2).
251 .IP \(bu 4
252 level 3: perl\-level \fBdie()\fR and internals \fBcroak()\fR
253 .Sp
254 If currently within an eval, these pop the context stack back to the
255 nearest \f(CW\*(C`CXt_EVAL\*(C'\fR frame, set \f(CW$@\fR as appropriate, set \f(CW\*(C`PL_restartop\*(C'\fR
256 to the op which follows the eval associated with that frame, then perform
257 a \fBJMPENV_JUMP\fR\|(3).
258 .Sp
259 Otherwise, the error message is printed to \f(CW\*(C`STDERR\*(C'\fR, then it is treated
260 as an exit: unwind all stacks and perform a \fBJMPENV_JUMP\fR\|(2).
261 .IP \(bu 4
262 level 1: unused
263 .Sp
264 \&\fBJMPENV_JUMP\fR\|(1) is currently unused except in \fBperl_run()\fR.
265 .IP \(bu 4
266 level 0: normal return.
267 .Sp
268 The zero value is for a normal return from \fBJMPENV_PUSH()\fR
269 .PP
270 So the perl interpreter expects that, at all times, there is a suitable
271 \&\f(CW\*(C`JMPENV_PUSH\*(C'\fR set up (and at a suitable location within the CPU call
272 stack) that can catch and process a 2\- or 3\-valued jump; and in the case
273 of a 3, start a new runops loop to execute \f(CW\*(C`PL_restartop\*(C'\fR and all
274 remaining ops (as will be explained shortly).
275 .PP
276 The entry points to the perl interpreter all provide such a facility. For
277 example, \fBperl_parse()\fR, \fBperl_run()\fR and \f(CW\*(C`call_sv(cv, G_EVAL)\*(C'\fR all contain
278 something similar in outline to:
279 .PP
280 .Vb 10
281 \& {
282 \& dJMPENV;
283 \& JMPENV_PUSH(ret);
284 \& switch (ret) {
285 \& case 0: /* normal return from JMPENV_PUSH() */
286 \& redo_body:
287 \& CALLRUNOPS(aTHX);
288 \& break;
289 \& case 2: /* caught longjmp(2) \- exit / die */
290 \& break;
291 \& case 3: /* caught longjmp(3) \- eval { die } */
292 \& PL_op = PL_restartop;
293 \& goto redo_body;
294 \& }
295 \&
296 \& JMPENV_POP;
297 \& }
298 .Ve
299 .PP
300 A runops loop such as \fBPerl_runops_standard()\fR (as set up by \fBCALLRUNOPS()\fR)
301 is, at its heart, just a simple:
302 .PP
303 .Vb 1
304 \& while ((PL_op = PL_op\->op_ppaddr(aTHX))) { 1; }
305 .Ve
306 .PP
307 which calls the \fBpp()\fR function associated with each op, relying on that to
308 return a pointer to the next op to be executed.
309 .PP
310 As well as setting catches at the entry points to the perl interpreter,
311 you might expect perl to also do a \fBJMPENV_PUSH()\fR in places like
312 \&\fBpp_entertry()\fR, just before some trappable ops are executed. In fact perl
313 doesn\*(Aqt normally do this. The drawback with doing it is that with nested
314 or recursive code such as:
315 .PP
316 .Vb 1
317 \& sub foo { my ($i) = @_; return if $i < 0; eval { foo(\-\-$i) } }
318 .Ve
319 .PP
320 Then the C stack would quickly overflow with pairs of entries like
321 .PP
322 .Vb 6
323 \& ...
324 \& #N+3 Perl_runops()
325 \& #N+2 Perl_pp_entertry()
326 \& #N+1 Perl_runops()
327 \& #N Perl_pp_entertry()
328 \& ...
329 .Ve
330 .PP
331 Instead, perl puts its guards at the \fIcallers\fR of runops loops. Then as
332 many nested subroutine calls and evals may be called as you like, all
333 within the one runops loop. If an exception occurs, control passes back to
334 the caller of the loop, which just immediately restarts a new loop with
335 \&\f(CW\*(C`PL_restartop\*(C'\fR being the next op to call.
336 .PP
337 So in normal operation where there are several nested evals, there
338 will be multiple \f(CW\*(C`CXt_EVAL\*(C'\fR context stack entries, but only a single
339 runops loop, guarded by a single \f(CW\*(C`JMPENV_PUSH\*(C'\fR. Each caught eval will pop
340 the next \f(CW\*(C`CXt_EVAL\*(C'\fR off the stack, set \f(CW\*(C`PL_restartop\*(C'\fR, then \fBlongjmp()\fR
341 back to \fBperl_run()\fR and continue.
342 .PP
343 However, ops are sometimes executed within an inner runops loop, such as
344 in a tie, sort, or overload code. In this case, something like
345 .PP
346 .Vb 1
347 \& sub FETCH { eval { die }; .... }
348 .Ve
349 .PP
350 would, unless handled specially, cause a \fBlongjmp()\fR right back to the guard
351 in \fBperl_run()\fR, popping \fIboth\fR the runops loops \- which is clearly
352 incorrect. One way to avoid this is for the tie code to do a
353 \&\f(CW\*(C`JMPENV_PUSH\*(C'\fR before executing \f(CW\*(C`FETCH\*(C'\fR in the inner runops loop, but for
354 efficiency reasons, perl in fact just temporarily sets a flag using
355 \&\f(CWCATCH_SET(TRUE)\fR. This flag warns any subsequent \f(CW\*(C`require\*(C'\fR,
356 \&\f(CW\*(C`entereval\*(C'\fR or \f(CW\*(C`entertry\*(C'\fR ops that the caller is no longer promising to
357 catch any raised exceptions on their behalf.
358 .PP
359 These ops check this flag, and if true, they (via \fBdocatch()\fR) do a
360 \&\f(CW\*(C`JMPENV_PUSH\*(C'\fR and start a new runops loop to execute the code, rather
361 than doing it with the current loop.
362 .PP
363 As a consequence, on exit from the eval block in the \f(CW\*(C`FETCH\*(C'\fR above,
364 execution of the code following the block is still carried on in the
365 inner loop (i.e. the one established by the \fBpp_entertry()\fR). To avoid
366 confusion, if a further exception is then raised, \fBdocatch()\fR compares the
367 \&\f(CW\*(C`JMPENV\*(C'\fR level of the \f(CW\*(C`CXt_EVAL\*(C'\fR with \f(CW\*(C`PL_top_env\*(C'\fR and if they differ,
368 just re\-throws the exception. In this way any inner loops get popped,
369 and the exception will be dealt with properly by the level which is
370 expecting it.
371 .PP
372 Here\*(Aqs an example.
373 .PP
374 .Vb 5
375 \& 1: eval { tie @a, \*(AqA\*(Aq };
376 \& 2: sub A::TIEARRAY {
377 \& 3: eval { die };
378 \& 4: die;
379 \& 5: }
380 .Ve
381 .PP
382 To run this code, \fBperl_run()\fR is called, which does a \fBJMPENV_PUSH()\fR,
383 then enters a runops loop. This loop executes the \f(CW\*(C`entereval\*(C'\fR and \f(CW\*(C`tie\*(C'\fR
384 ops on line 1, with the \f(CW\*(C`entereval\*(C'\fR pushing a \f(CW\*(C`CXt_EVAL\*(C'\fR onto the context
385 stack.
386 .PP
387 The \fBpp_tie()\fR does a \f(CWCATCH_SET(TRUE)\fR, then starts a second runops
388 loop to execute the body of \fBTIEARRAY()\fR. When the loop executes the
389 \&\f(CW\*(C`entertry\*(C'\fR op on line 3, \fBCATCH_GET()\fR is true, so \fBpp_entertry()\fR calls
390 \&\fBdocatch()\fR which does a \f(CW\*(C`JMPENV_PUSH\*(C'\fR and starts a third runops loop,
391 which restarts the \fBpp_entertry()\fR, then executes the \f(CW\*(C`die\*(C'\fR op. At this
392 point the C call stack looks like this:
393 .PP
394 .Vb 11
395 \& #10 Perl_pp_die()
396 \& #9 Perl_runops() # runops loop 3
397 \& #8 S_docatch() # JMPENV level 2
398 \& #7 Perl_pp_entertry()
399 \& #6 Perl_runops() # runops loop 2
400 \& #5 Perl_call_sv()
401 \& #4 Perl_pp_tie()
402 \& #3 Perl_runops() # runops loop 1
403 \& #2 S_run_body()
404 \& #1 perl_run() # JMPENV level 1
405 \& #0 main()
406 .Ve
407 .PP
408 and the context and data stacks, as shown by \f(CW\*(C`perl \-Dstv\*(C'\fR, look like:
409 .PP
410 .Vb 9
411 \& STACK 0: MAIN
412 \& CX 0: BLOCK =>
413 \& CX 1: EVAL => AV() PV("A"\e0)
414 \& retop=leave
415 \& STACK 1: MAGIC
416 \& CX 0: SUB =>
417 \& retop=(null)
418 \& CX 1: EVAL => *
419 \& retop=nextstate
420 .Ve
421 .PP
422 The \fBdie()\fR pops the first \f(CW\*(C`CXt_EVAL\*(C'\fR off the context stack, sets
423 \&\f(CW\*(C`PL_restartop\*(C'\fR from it, does a \f(CWJMPENV_JUMP(3)\fR, and control returns
424 to the \f(CW\*(C`JMPENV\*(C'\fR level set in \fBdocatch()\fR. This then starts another
425 third\-level runops level, which executes the \f(CW\*(C`nextstate\*(C'\fR, \f(CW\*(C`pushmark\*(C'\fR and
426 \&\f(CW\*(C`die\*(C'\fR ops from line 4. At the point that the second \fBpp_die()\fR is called,
427 the C call stack looks exactly like that above, even though we are no
428 longer within an inner eval. However, the context stack now looks like
429 this, i.e. with the top CXt_EVAL popped:
430 .PP
431 .Vb 7
432 \& STACK 0: MAIN
433 \& CX 0: BLOCK =>
434 \& CX 1: EVAL => AV() PV("A"\e0)
435 \& retop=leave
436 \& STACK 1: MAGIC
437 \& CX 0: SUB =>
438 \& retop=(null)
439 .Ve
440 .PP
441 The \fBdie()\fR on line 4 pops the context stack back down to the \f(CW\*(C`CXt_EVAL\*(C'\fR,
442 leaving it as:
443 .PP
444 .Vb 2
445 \& STACK 0: MAIN
446 \& CX 0: BLOCK =>
447 .Ve
448 .PP
449 As usual, \f(CW\*(C`PL_restartop\*(C'\fR is extracted from the \f(CW\*(C`CXt_EVAL\*(C'\fR, and a
450 \&\fBJMPENV_JUMP\fR\|(3) done, which pops the C stack back to the \fBdocatch()\fR:
451 .PP
452 .Vb 9
453 \& #8 S_docatch() # JMPENV level 2
454 \& #7 Perl_pp_entertry()
455 \& #6 Perl_runops() # runops loop 2
456 \& #5 Perl_call_sv()
457 \& #4 Perl_pp_tie()
458 \& #3 Perl_runops() # runops loop 1
459 \& #2 S_run_body()
460 \& #1 perl_run() # JMPENV level 1
461 \& #0 main()
462 .Ve
463 .PP
464 In this case, because the \f(CW\*(C`JMPENV\*(C'\fR level recorded in the \f(CW\*(C`CXt_EVAL\*(C'\fR
465 differs from the current one, \fBdocatch()\fR just does a \fBJMPENV_JUMP\fR\|(3)
466 to re\-throw the exception, and the C stack unwinds to:
467 .PP
468 .Vb 2
469 \& #1 perl_run() # JMPENV level 1
470 \& #0 main()
471 .Ve
472 .PP
473 Because \f(CW\*(C`PL_restartop\*(C'\fR is non\-null, \fBrun_body()\fR starts a new runops
474 loop, and execution continues.
475 .SS "INTERNAL VARIABLE TYPES"
476 .IX Subsection "INTERNAL VARIABLE TYPES"
477 You should by now have had a look at perlguts, which tells you about
478 Perl\*(Aqs internal variable types: SVs, HVs, AVs and the rest. If not, do
479 that now.
480 .PP
481 These variables are used not only to represent Perl\-space variables,
482 but also any constants in the code, as well as some structures
483 completely internal to Perl. The symbol table, for instance, is an
484 ordinary Perl hash. Your code is represented by an SV as it\*(Aqs read into
485 the parser; any program files you call are opened via ordinary Perl
486 filehandles, and so on.
487 .PP
488 The core Devel::Peek module lets us examine SVs from a
489 Perl program. Let\*(Aqs see, for instance, how Perl treats the constant
490 \&\f(CW"hello"\fR.
491 .PP
492 .Vb 7
493 \& % perl \-MDevel::Peek \-e \*(AqDump("hello")\*(Aq
494 \& 1 SV = PV(0xa041450) at 0xa04ecbc
495 \& 2 REFCNT = 1
496 \& 3 FLAGS = (POK,READONLY,pPOK)
497 \& 4 PV = 0xa0484e0 "hello"\e0
498 \& 5 CUR = 5
499 \& 6 LEN = 6
500 .Ve
501 .PP
502 Reading \f(CW\*(C`Devel::Peek\*(C'\fR output takes a bit of practise, so let\*(Aqs go
503 through it line by line.
504 .PP
505 Line 1 tells us we\*(Aqre looking at an SV which lives at \f(CW0xa04ecbc\fR in
506 memory. SVs themselves are very simple structures, but they contain a
507 pointer to a more complex structure. In this case, it\*(Aqs a PV, a
508 structure which holds a string value, at location \f(CW0xa041450\fR. Line 2
509 is the reference count; there are no other references to this data, so
510 it\*(Aqs 1.
511 .PP
512 Line 3 are the flags for this SV \- it\*(Aqs OK to use it as a PV, it\*(Aqs a
513 read\-only SV (because it\*(Aqs a constant) and the data is a PV internally.
514 Next we\*(Aqve got the contents of the string, starting at location
515 \&\f(CW0xa0484e0\fR.
516 .PP
517 Line 5 gives us the current length of the string \- note that this does
518 \&\fBnot\fR include the null terminator. Line 6 is not the length of the
519 string, but the length of the currently allocated buffer; as the string
520 grows, Perl automatically extends the available storage via a routine
521 called \f(CW\*(C`SvGROW\*(C'\fR.
522 .PP
523 You can get at any of these quantities from C very easily; just add
524 \&\f(CW\*(C`Sv\*(C'\fR to the name of the field shown in the snippet, and you\*(Aqve got a
525 macro which will return the value: \f(CWSvCUR(sv)\fR returns the current
526 length of the string, \f(CWSvREFCOUNT(sv)\fR returns the reference count,
527 \&\f(CW\*(C`SvPV(sv, len)\*(C'\fR returns the string itself with its length, and so on.
528 More macros to manipulate these properties can be found in perlguts.
529 .PP
530 Let\*(Aqs take an example of manipulating a PV, from \f(CW\*(C`sv_catpvn\*(C'\fR, in
531 \&\fIsv.c\fR
532 .PP
533 .Vb 5
534 \& 1 void
535 \& 2 Perl_sv_catpvn(pTHX_ SV *sv, const char *ptr, STRLEN len)
536 \& 3 {
537 \& 4 STRLEN tlen;
538 \& 5 char *junk;
539 \&
540 \& 6 junk = SvPV_force(sv, tlen);
541 \& 7 SvGROW(sv, tlen + len + 1);
542 \& 8 if (ptr == junk)
543 \& 9 ptr = SvPVX(sv);
544 \& 10 Move(ptr,SvPVX(sv)+tlen,len,char);
545 \& 11 SvCUR(sv) += len;
546 \& 12 *SvEND(sv) = \*(Aq\e0\*(Aq;
547 \& 13 (void)SvPOK_only_UTF8(sv); /* validate pointer */
548 \& 14 SvTAINT(sv);
549 \& 15 }
550 .Ve
551 .PP
552 This is a function which adds a string, \f(CW\*(C`ptr\*(C'\fR, of length \f(CW\*(C`len\*(C'\fR onto
553 the end of the PV stored in \f(CW\*(C`sv\*(C'\fR. The first thing we do in line 6 is
554 make sure that the SV \fBhas\fR a valid PV, by calling the \f(CW\*(C`SvPV_force\*(C'\fR
555 macro to force a PV. As a side effect, \f(CW\*(C`tlen\*(C'\fR gets set to the current
556 value of the PV, and the PV itself is returned to \f(CW\*(C`junk\*(C'\fR.
557 .PP
558 In line 7, we make sure that the SV will have enough room to
559 accommodate the old string, the new string and the null terminator. If
560 \&\f(CW\*(C`LEN\*(C'\fR isn\*(Aqt big enough, \f(CW\*(C`SvGROW\*(C'\fR will reallocate space for us.
561 .PP
562 Now, if \f(CW\*(C`junk\*(C'\fR is the same as the string we\*(Aqre trying to add, we can
563 grab the string directly from the SV; \f(CW\*(C`SvPVX\*(C'\fR is the address of the PV
564 in the SV.
565 .PP
566 Line 10 does the actual catenation: the \f(CW\*(C`Move\*(C'\fR macro moves a chunk of
567 memory around: we move the string \f(CW\*(C`ptr\*(C'\fR to the end of the PV \- that\*(Aqs
568 the start of the PV plus its current length. We\*(Aqre moving \f(CW\*(C`len\*(C'\fR bytes
569 of type \f(CW\*(C`char\*(C'\fR. After doing so, we need to tell Perl we\*(Aqve extended
570 the string, by altering \f(CW\*(C`CUR\*(C'\fR to reflect the new length. \f(CW\*(C`SvEND\*(C'\fR is a
571 macro which gives us the end of the string, so that needs to be a
572 \&\f(CW"\e0"\fR.
573 .PP
574 Line 13 manipulates the flags; since we\*(Aqve changed the PV, any IV or NV
575 values will no longer be valid: if we have \f(CW\*(C`$x=10; $x.="6";\*(C'\fR we don\*(Aqt
576 want to use the old IV of 10. \f(CW\*(C`SvPOK_only_utf8\*(C'\fR is a special
577 UTF\-8\-aware version of \f(CW\*(C`SvPOK_only\*(C'\fR, a macro which turns off the IOK
578 and NOK flags and turns on POK. The final \f(CW\*(C`SvTAINT\*(C'\fR is a macro which
579 launders tainted data if taint mode is turned on.
580 .PP
581 AVs and HVs are more complicated, but SVs are by far the most common
582 variable type being thrown around. Having seen something of how we
583 manipulate these, let\*(Aqs go on and look at how the op tree is
584 constructed.
585 .SH "OP TREES"
586 .IX Header "OP TREES"
587 First, what is the op tree, anyway? The op tree is the parsed
588 representation of your program, as we saw in our section on parsing,
589 and it\*(Aqs the sequence of operations that Perl goes through to execute
590 your program, as we saw in "Running".
591 .PP
592 An op is a fundamental operation that Perl can perform: all the
593 built\-in functions and operators are ops, and there are a series of ops
594 which deal with concepts the interpreter needs internally \- entering
595 and leaving a block, ending a statement, fetching a variable, and so
596 on.
597 .PP
598 The op tree is connected in two ways: you can imagine that there are
599 two "routes" through it, two orders in which you can traverse the tree.
600 First, parse order reflects how the parser understood the code, and
601 secondly, execution order tells perl what order to perform the
602 operations in.
603 .PP
604 The easiest way to examine the op tree is to stop Perl after it has
605 finished parsing, and get it to dump out the tree. This is exactly what
606 the compiler backends B::Terse, B::Concise
607 and CPAN module <B::Debug do.
608 .PP
609 Let\*(Aqs have a look at how Perl sees \f(CW\*(C`$x = $y + $z\*(C'\fR:
610 .PP
611 .Vb 12
612 \& % perl \-MO=Terse \-e \*(Aq$x=$y+$z\*(Aq
613 \& 1 LISTOP (0x8179888) leave
614 \& 2 OP (0x81798b0) enter
615 \& 3 COP (0x8179850) nextstate
616 \& 4 BINOP (0x8179828) sassign
617 \& 5 BINOP (0x8179800) add [1]
618 \& 6 UNOP (0x81796e0) null [15]
619 \& 7 SVOP (0x80fafe0) gvsv GV (0x80fa4cc) *y
620 \& 8 UNOP (0x81797e0) null [15]
621 \& 9 SVOP (0x8179700) gvsv GV (0x80efeb0) *z
622 \& 10 UNOP (0x816b4f0) null [15]
623 \& 11 SVOP (0x816dcf0) gvsv GV (0x80fa460) *x
624 .Ve
625 .PP
626 Let\*(Aqs start in the middle, at line 4. This is a BINOP, a binary
627 operator, which is at location \f(CW0x8179828\fR. The specific operator in
628 question is \f(CW\*(C`sassign\*(C'\fR \- scalar assignment \- and you can find the code
629 which implements it in the function \f(CW\*(C`pp_sassign\*(C'\fR in \fIpp_hot.c\fR. As a
630 binary operator, it has two children: the add operator, providing the
631 result of \f(CW\*(C`$y+$z\*(C'\fR, is uppermost on line 5, and the left hand side is
632 on line 10.
633 .PP
634 Line 10 is the null op: this does exactly nothing. What is that doing
635 there? If you see the null op, it\*(Aqs a sign that something has been
636 optimized away after parsing. As we mentioned in "Optimization", the
637 optimization stage sometimes converts two operations into one, for
638 example when fetching a scalar variable. When this happens, instead of
639 rewriting the op tree and cleaning up the dangling pointers, it\*(Aqs
640 easier just to replace the redundant operation with the null op.
641 Originally, the tree would have looked like this:
642 .PP
643 .Vb 2
644 \& 10 SVOP (0x816b4f0) rv2sv [15]
645 \& 11 SVOP (0x816dcf0) gv GV (0x80fa460) *x
646 .Ve
647 .PP
648 That is, fetch the \f(CW\*(C`a\*(C'\fR entry from the main symbol table, and then look
649 at the scalar component of it: \f(CW\*(C`gvsv\*(C'\fR (\f(CW\*(C`pp_gvsv\*(C'\fR in \fIpp_hot.c\fR)
650 happens to do both these things.
651 .PP
652 The right hand side, starting at line 5 is similar to what we\*(Aqve just
653 seen: we have the \f(CW\*(C`add\*(C'\fR op (\f(CW\*(C`pp_add\*(C'\fR, also in \fIpp_hot.c\fR) add
654 together two \f(CW\*(C`gvsv\*(C'\fRs.
655 .PP
656 Now, what\*(Aqs this about?
657 .PP
658 .Vb 3
659 \& 1 LISTOP (0x8179888) leave
660 \& 2 OP (0x81798b0) enter
661 \& 3 COP (0x8179850) nextstate
662 .Ve
663 .PP
664 \&\f(CW\*(C`enter\*(C'\fR and \f(CW\*(C`leave\*(C'\fR are scoping ops, and their job is to perform any
665 housekeeping every time you enter and leave a block: lexical variables
666 are tidied up, unreferenced variables are destroyed, and so on. Every
667 program will have those first three lines: \f(CW\*(C`leave\*(C'\fR is a list, and its
668 children are all the statements in the block. Statements are delimited
669 by \f(CW\*(C`nextstate\*(C'\fR, so a block is a collection of \f(CW\*(C`nextstate\*(C'\fR ops, with
670 the ops to be performed for each statement being the children of
671 \&\f(CW\*(C`nextstate\*(C'\fR. \f(CW\*(C`enter\*(C'\fR is a single op which functions as a marker.
672 .PP
673 That\*(Aqs how Perl parsed the program, from top to bottom:
674 .PP
675 .Vb 10
676 \& Program
677 \& |
678 \& Statement
679 \& |
680 \& =
681 \& / \e
682 \& / \e
683 \& $x +
684 \& / \e
685 \& $y $z
686 .Ve
687 .PP
688 However, it\*(Aqs impossible to \fBperform\fR the operations in this order:
689 you have to find the values of \f(CW$y\fR and \f(CW$z\fR before you add them
690 together, for instance. So, the other thread that runs through the op
691 tree is the execution order: each op has a field \f(CW\*(C`op_next\*(C'\fR which
692 points to the next op to be run, so following these pointers tells us
693 how perl executes the code. We can traverse the tree in this order
694 using the \f(CW\*(C`exec\*(C'\fR option to \f(CW\*(C`B::Terse\*(C'\fR:
695 .PP
696 .Vb 9
697 \& % perl \-MO=Terse,exec \-e \*(Aq$x=$y+$z\*(Aq
698 \& 1 OP (0x8179928) enter
699 \& 2 COP (0x81798c8) nextstate
700 \& 3 SVOP (0x81796c8) gvsv GV (0x80fa4d4) *y
701 \& 4 SVOP (0x8179798) gvsv GV (0x80efeb0) *z
702 \& 5 BINOP (0x8179878) add [1]
703 \& 6 SVOP (0x816dd38) gvsv GV (0x80fa468) *x
704 \& 7 BINOP (0x81798a0) sassign
705 \& 8 LISTOP (0x8179900) leave
706 .Ve
707 .PP
708 This probably makes more sense for a human: enter a block, start a
709 statement. Get the values of \f(CW$y\fR and \f(CW$z\fR, and add them together.
710 Find \f(CW$x\fR, and assign one to the other. Then leave.
711 .PP
712 The way Perl builds up these op trees in the parsing process can be
713 unravelled by examining \fItoke.c\fR, the lexer, and \fIperly.y\fR, the YACC
714 grammar. Let\*(Aqs look at the code that constructs the tree for \f(CW$x = $y +
715 $z\fR.
716 .PP
717 First, we\*(Aqll look at the \f(CW\*(C`Perl_yylex\*(C'\fR function in the lexer. We want to
718 look for \f(CW\*(C`case \*(Aqx\*(Aq\*(C'\fR, where x is the first character of the operator.
719 (Incidentally, when looking for the code that handles a keyword, you\*(Aqll
720 want to search for \f(CW\*(C`KEY_foo\*(C'\fR where "foo" is the keyword.) Here is the code
721 that handles assignment (there are quite a few operators beginning with
722 \&\f(CW\*(C`=\*(C'\fR, so most of it is omitted for brevity):
723 .PP
724 .Vb 5
725 \& 1 case \*(Aq=\*(Aq:
726 \& 2 s++;
727 \& ... code that handles == => etc. and pod ...
728 \& 3 pl_yylval.ival = 0;
729 \& 4 OPERATOR(ASSIGNOP);
730 .Ve
731 .PP
732 We can see on line 4 that our token type is \f(CW\*(C`ASSIGNOP\*(C'\fR (\f(CW\*(C`OPERATOR\*(C'\fR is a
733 macro, defined in \fItoke.c\fR, that returns the token type, among other
734 things). And \f(CW\*(C`+\*(C'\fR:
735 .PP
736 .Vb 10
737 \& 1 case \*(Aq+\*(Aq:
738 \& 2 {
739 \& 3 const char tmp = *s++;
740 \& ... code for ++ ...
741 \& 4 if (PL_expect == XOPERATOR) {
742 \& ...
743 \& 5 Aop(OP_ADD);
744 \& 6 }
745 \& ...
746 \& 7 }
747 .Ve
748 .PP
749 Line 4 checks what type of token we are expecting. \f(CW\*(C`Aop\*(C'\fR returns a token.
750 If you search for \f(CW\*(C`Aop\*(C'\fR elsewhere in \fItoke.c\fR, you will see that it
751 returns an \f(CW\*(C`ADDOP\*(C'\fR token.
752 .PP
753 Now that we know the two token types we want to look for in the parser,
754 let\*(Aqs take the piece of \fIperly.y\fR we need to construct the tree for
755 \&\f(CW\*(C`$x = $y + $z\*(C'\fR
756 .PP
757 .Vb 4
758 \& 1 term : term ASSIGNOP term
759 \& 2 { $$ = newASSIGNOP(OPf_STACKED, $1, $2, $3); }
760 \& 3 | term ADDOP term
761 \& 4 { $$ = newBINOP($2, 0, scalar($1), scalar($3)); }
762 .Ve
763 .PP
764 If you\*(Aqre not used to reading BNF grammars, this is how it works:
765 You\*(Aqre fed certain things by the tokeniser, which generally end up in
766 upper case. \f(CW\*(C`ADDOP\*(C'\fR and \f(CW\*(C`ASSIGNOP\*(C'\fR are examples of "terminal symbols",
767 because you can\*(Aqt get any simpler than
768 them.
769 .PP
770 The grammar, lines one and three of the snippet above, tells you how to
771 build up more complex forms. These complex forms, "non\-terminal
772 symbols" are generally placed in lower case. \f(CW\*(C`term\*(C'\fR here is a
773 non\-terminal symbol, representing a single expression.
774 .PP
775 The grammar gives you the following rule: you can make the thing on the
776 left of the colon if you see all the things on the right in sequence.
777 This is called a "reduction", and the aim of parsing is to completely
778 reduce the input. There are several different ways you can perform a
779 reduction, separated by vertical bars: so, \f(CW\*(C`term\*(C'\fR followed by \f(CW\*(C`=\*(C'\fR
780 followed by \f(CW\*(C`term\*(C'\fR makes a \f(CW\*(C`term\*(C'\fR, and \f(CW\*(C`term\*(C'\fR followed by \f(CW\*(C`+\*(C'\fR
781 followed by \f(CW\*(C`term\*(C'\fR can also make a \f(CW\*(C`term\*(C'\fR.
782 .PP
783 So, if you see two terms with an \f(CW\*(C`=\*(C'\fR or \f(CW\*(C`+\*(C'\fR, between them, you can
784 turn them into a single expression. When you do this, you execute the
785 code in the block on the next line: if you see \f(CW\*(C`=\*(C'\fR, you\*(Aqll do the code
786 in line 2. If you see \f(CW\*(C`+\*(C'\fR, you\*(Aqll do the code in line 4. It\*(Aqs this
787 code which contributes to the op tree.
788 .PP
789 .Vb 2
790 \& | term ADDOP term
791 \& { $$ = newBINOP($2, 0, scalar($1), scalar($3)); }
792 .Ve
793 .PP
794 What this does is creates a new binary op, and feeds it a number of
795 variables. The variables refer to the tokens: \f(CW$1\fR is the first token
796 in the input, \f(CW$2\fR the second, and so on \- think regular expression
797 backreferences. \f(CW$$\fR is the op returned from this reduction. So, we
798 call \f(CW\*(C`newBINOP\*(C'\fR to create a new binary operator. The first parameter
799 to \f(CW\*(C`newBINOP\*(C'\fR, a function in \fIop.c\fR, is the op type. It\*(Aqs an addition
800 operator, so we want the type to be \f(CW\*(C`ADDOP\*(C'\fR. We could specify this
801 directly, but it\*(Aqs right there as the second token in the input, so we
802 use \f(CW$2\fR. The second parameter is the op\*(Aqs flags: 0 means "nothing
803 special". Then the things to add: the left and right hand side of our
804 expression, in scalar context.
805 .PP
806 The functions that create ops, which have names like \f(CW\*(C`newUNOP\*(C'\fR and
807 \&\f(CW\*(C`newBINOP\*(C'\fR, call a "check" function associated with each op type, before
808 returning the op. The check functions can mangle the op as they see fit,
809 and even replace it with an entirely new one. These functions are defined
810 in \fIop.c\fR, and have a \f(CW\*(C`Perl_ck_\*(C'\fR prefix. You can find out which
811 check function is used for a particular op type by looking in
812 \&\fIregen/opcodes\fR. Take \f(CW\*(C`OP_ADD\*(C'\fR, for example. (\f(CW\*(C`OP_ADD\*(C'\fR is the token
813 value from the \f(CWAop(OP_ADD)\fR in \fItoke.c\fR which the parser passes to
814 \&\f(CW\*(C`newBINOP\*(C'\fR as its first argument.) Here is the relevant line:
815 .PP
816 .Vb 1
817 \& add addition (+) ck_null IfsT2 S S
818 .Ve
819 .PP
820 The check function in this case is \f(CW\*(C`Perl_ck_null\*(C'\fR, which does nothing.
821 Let\*(Aqs look at a more interesting case:
822 .PP
823 .Vb 1
824 \& readline <HANDLE> ck_readline t% F?
825 .Ve
826 .PP
827 And here is the function from \fIop.c\fR:
828 .PP
829 .Vb 10
830 \& 1 OP *
831 \& 2 Perl_ck_readline(pTHX_ OP *o)
832 \& 3 {
833 \& 4 PERL_ARGS_ASSERT_CK_READLINE;
834 \& 5
835 \& 6 if (o\->op_flags & OPf_KIDS) {
836 \& 7 OP *kid = cLISTOPo\->op_first;
837 \& 8 if (kid\->op_type == OP_RV2GV)
838 \& 9 kid\->op_private |= OPpALLOW_FAKE;
839 \& 10 }
840 \& 11 else {
841 \& 12 OP * const newop
842 \& 13 = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0,
843 \& 14 PL_argvgv));
844 \& 15 op_free(o);
845 \& 16 return newop;
846 \& 17 }
847 \& 18 return o;
848 \& 19 }
849 .Ve
850 .PP
851 One particularly interesting aspect is that if the op has no kids (i.e.,
852 \&\f(CWreadline()\fR or \f(CW\*(C`<>\*(C'\fR) the op is freed and replaced with an entirely
853 new one that references \f(CW*ARGV\fR (lines 12\-16).
854 .SH STACKS
855 .IX Header "STACKS"
856 When perl executes something like \f(CW\*(C`addop\*(C'\fR, how does it pass on its
857 results to the next op? The answer is, through the use of stacks. Perl
858 has a number of stacks to store things it\*(Aqs currently working on, and
859 we\*(Aqll look at the three most important ones here.
860 .SS "Argument stack"
861 .IX Subsection "Argument stack"
862 Arguments are passed to PP code and returned from PP code using the
863 argument stack, \f(CW\*(C`ST\*(C'\fR. The typical way to handle arguments is to pop
864 them off the stack, deal with them how you wish, and then push the
865 result back onto the stack. This is how, for instance, the cosine
866 operator works:
867 .PP
868 .Vb 4
869 \& NV value;
870 \& value = POPn;
871 \& value = Perl_cos(value);
872 \& XPUSHn(value);
873 .Ve
874 .PP
875 We\*(Aqll see a more tricky example of this when we consider Perl\*(Aqs macros
876 below. \f(CW\*(C`POPn\*(C'\fR gives you the NV (floating point value) of the top SV on
877 the stack: the \f(CW$x\fR in \f(CWcos($x)\fR. Then we compute the cosine, and
878 push the result back as an NV. The \f(CW\*(C`X\*(C'\fR in \f(CW\*(C`XPUSHn\*(C'\fR means that the
879 stack should be extended if necessary \- it can\*(Aqt be necessary here,
880 because we know there\*(Aqs room for one more item on the stack, since
881 we\*(Aqve just removed one! The \f(CW\*(C`XPUSH*\*(C'\fR macros at least guarantee safety.
882 .PP
883 Alternatively, you can fiddle with the stack directly: \f(CW\*(C`SP\*(C'\fR gives you
884 the first element in your portion of the stack, and \f(CW\*(C`TOP*\*(C'\fR gives you
885 the top SV/IV/NV/etc. on the stack. So, for instance, to do unary
886 negation of an integer:
887 .PP
888 .Vb 1
889 \& SETi(\-TOPi);
890 .Ve
891 .PP
892 Just set the integer value of the top stack entry to its negation.
893 .PP
894 Argument stack manipulation in the core is exactly the same as it is in
895 XSUBs \- see perlxstut, perlxs and perlguts for a longer
896 description of the macros used in stack manipulation.
897 .SS "Mark stack"
898 .IX Subsection "Mark stack"
899 I say "your portion of the stack" above because PP code doesn\*(Aqt
900 necessarily get the whole stack to itself: if your function calls
901 another function, you\*(Aqll only want to expose the arguments aimed for
902 the called function, and not (necessarily) let it get at your own data.
903 The way we do this is to have a "virtual" bottom\-of\-stack, exposed to
904 each function. The mark stack keeps bookmarks to locations in the
905 argument stack usable by each function. For instance, when dealing with
906 a tied variable, (internally, something with "P" magic) Perl has to
907 call methods for accesses to the tied variables. However, we need to
908 separate the arguments exposed to the method to the argument exposed to
909 the original function \- the store or fetch or whatever it may be.
910 Here\*(Aqs roughly how the tied \f(CW\*(C`push\*(C'\fR is implemented; see \f(CW\*(C`av_push\*(C'\fR in
911 \&\fIav.c\fR:
912 .PP
913 .Vb 8
914 \& 1 PUSHMARK(SP);
915 \& 2 EXTEND(SP,2);
916 \& 3 PUSHs(SvTIED_obj((SV*)av, mg));
917 \& 4 PUSHs(val);
918 \& 5 PUTBACK;
919 \& 6 ENTER;
920 \& 7 call_method("PUSH", G_SCALAR|G_DISCARD);
921 \& 8 LEAVE;
922 .Ve
923 .PP
924 Let\*(Aqs examine the whole implementation, for practice:
925 .PP
926 .Vb 1
927 \& 1 PUSHMARK(SP);
928 .Ve
929 .PP
930 Push the current state of the stack pointer onto the mark stack. This
931 is so that when we\*(Aqve finished adding items to the argument stack, Perl
932 knows how many things we\*(Aqve added recently.
933 .PP
934 .Vb 3
935 \& 2 EXTEND(SP,2);
936 \& 3 PUSHs(SvTIED_obj((SV*)av, mg));
937 \& 4 PUSHs(val);
938 .Ve
939 .PP
940 We\*(Aqre going to add two more items onto the argument stack: when you
941 have a tied array, the \f(CW\*(C`PUSH\*(C'\fR subroutine receives the object and the
942 value to be pushed, and that\*(Aqs exactly what we have here \- the tied
943 object, retrieved with \f(CW\*(C`SvTIED_obj\*(C'\fR, and the value, the SV \f(CW\*(C`val\*(C'\fR.
944 .PP
945 .Vb 1
946 \& 5 PUTBACK;
947 .Ve
948 .PP
949 Next we tell Perl to update the global stack pointer from our internal
950 variable: \f(CW\*(C`dSP\*(C'\fR only gave us a local copy, not a reference to the
951 global.
952 .PP
953 .Vb 3
954 \& 6 ENTER;
955 \& 7 call_method("PUSH", G_SCALAR|G_DISCARD);
956 \& 8 LEAVE;
957 .Ve
958 .PP
959 \&\f(CW\*(C`ENTER\*(C'\fR and \f(CW\*(C`LEAVE\*(C'\fR localise a block of code \- they make sure that
960 all variables are tidied up, everything that has been localised gets
961 its previous value returned, and so on. Think of them as the \f(CW\*(C`{\*(C'\fR and
962 \&\f(CW\*(C`}\*(C'\fR of a Perl block.
963 .PP
964 To actually do the magic method call, we have to call a subroutine in
965 Perl space: \f(CW\*(C`call_method\*(C'\fR takes care of that, and it\*(Aqs described in
966 perlcall. We call the \f(CW\*(C`PUSH\*(C'\fR method in scalar context, and we\*(Aqre
967 going to discard its return value. The \fBcall_method()\fR function removes
968 the top element of the mark stack, so there is nothing for the caller
969 to clean up.
970 .SS "Save stack"
971 .IX Subsection "Save stack"
972 C doesn\*(Aqt have a concept of local scope, so perl provides one. We\*(Aqve
973 seen that \f(CW\*(C`ENTER\*(C'\fR and \f(CW\*(C`LEAVE\*(C'\fR are used as scoping braces; the save
974 stack implements the C equivalent of, for example:
975 .PP
976 .Vb 4
977 \& {
978 \& local $foo = 42;
979 \& ...
980 \& }
981 .Ve
982 .PP
983 See "Localizing changes" in perlguts for how to use the save stack.
984 .SH "MILLIONS OF MACROS"
985 .IX Header "MILLIONS OF MACROS"
986 One thing you\*(Aqll notice about the Perl source is that it\*(Aqs full of
987 macros. Some have called the pervasive use of macros the hardest thing
988 to understand, others find it adds to clarity. Let\*(Aqs take an example,
989 a stripped\-down version the code which implements the addition operator:
990 .PP
991 .Vb 10
992 \& 1 PP(pp_add)
993 \& 2 {
994 \& 3 dSP; dATARGET;
995 \& 4 tryAMAGICbin_MG(add_amg, AMGf_assign|AMGf_numeric);
996 \& 5 {
997 \& 6 dPOPTOPnnrl_ul;
998 \& 7 SETn( left + right );
999 \& 8 RETURN;
1000 \& 9 }
1001 \& 10 }
1002 .Ve
1003 .PP
1004 Every line here (apart from the braces, of course) contains a macro.
1005 The first line sets up the function declaration as Perl expects for PP
1006 code; line 3 sets up variable declarations for the argument stack and
1007 the target, the return value of the operation. Line 4 tries to see
1008 if the addition operation is overloaded; if so, the appropriate
1009 subroutine is called.
1010 .PP
1011 Line 6 is another variable declaration \- all variable declarations
1012 start with \f(CW\*(C`d\*(C'\fR \- which pops from the top of the argument stack two NVs
1013 (hence \f(CW\*(C`nn\*(C'\fR) and puts them into the variables \f(CW\*(C`right\*(C'\fR and \f(CW\*(C`left\*(C'\fR,
1014 hence the \f(CW\*(C`rl\*(C'\fR. These are the two operands to the addition operator.
1015 Next, we call \f(CW\*(C`SETn\*(C'\fR to set the NV of the return value to the result
1016 of adding the two values. This done, we return \- the \f(CW\*(C`RETURN\*(C'\fR macro
1017 makes sure that our return value is properly handled, and we pass the
1018 next operator to run back to the main run loop.
1019 .PP
1020 Most of these macros are explained in perlapi, and some of the more
1021 important ones are explained in perlxs as well. Pay special
1022 attention to "Background and MULTIPLICITY" in perlguts for
1023 information on the \f(CW\*(C`[pad]THX_?\*(C'\fR macros.
1024 .SH "FURTHER READING"
1025 .IX Header "FURTHER READING"
1026 For more information on the Perl internals, please see the documents
1027 listed at "Internals and C Language Interface" in perl.