1PERLINTERP(1)          Perl Programmers Reference Guide          PERLINTERP(1)
2
3
4

NAME

6       perlinterp - An overview of the Perl interpreter
7

DESCRIPTION

9       This document provides an overview of how the Perl interpreter works at
10       the level of C code, along with pointers to the relevant C source code
11       files.
12

ELEMENTS OF THE INTERPRETER

14       The work of the interpreter has two main stages: compiling the code
15       into the internal representation, or bytecode, and then executing it.
16       "Compiled code" in perlguts explains exactly how the compilation stage
17       happens.
18
19       Here is a short breakdown of perl's operation:
20
21   Startup
22       The action begins in perlmain.c. (or miniperlmain.c for miniperl) This
23       is very high-level code, enough to fit on a single screen, and it
24       resembles the code found in perlembed; most of the real action takes
25       place in perl.c
26
27       perlmain.c is generated by "ExtUtils::Miniperl" from miniperlmain.c at
28       make time, so you should make perl to follow this along.
29
30       First, perlmain.c allocates some memory and constructs a Perl
31       interpreter, along these lines:
32
33           1 PERL_SYS_INIT3(&argc,&argv,&env);
34           2
35           3 if (!PL_do_undump) {
36           4     my_perl = perl_alloc();
37           5     if (!my_perl)
38           6         exit(1);
39           7     perl_construct(my_perl);
40           8     PL_perl_destruct_level = 0;
41           9 }
42
43       Line 1 is a macro, and its definition is dependent on your operating
44       system. Line 3 references "PL_do_undump", a global variable - all
45       global variables in Perl start with "PL_". This tells you whether the
46       current running program was created with the "-u" flag to perl and then
47       undump, which means it's going to be false in any sane context.
48
49       Line 4 calls a function in perl.c to allocate memory for a Perl
50       interpreter. It's quite a simple function, and the guts of it looks
51       like this:
52
53        my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
54
55       Here you see an example of Perl's system abstraction, which we'll see
56       later: "PerlMem_malloc" is either your system's "malloc", or Perl's own
57       "malloc" as defined in malloc.c if you selected that option at
58       configure time.
59
60       Next, in line 7, we construct the interpreter using perl_construct,
61       also in perl.c; this sets up all the special variables that Perl needs,
62       the stacks, and so on.
63
64       Now we pass Perl the command line options, and tell it to go:
65
66        if (!perl_parse(my_perl, xs_init, argc, argv, (char **)NULL))
67            perl_run(my_perl);
68
69        exitstatus = perl_destruct(my_perl);
70
71        perl_free(my_perl);
72
73       "perl_parse" is actually a wrapper around "S_parse_body", as defined in
74       perl.c, which processes the command line options, sets up any
75       statically linked XS modules, opens the program and calls "yyparse" to
76       parse it.
77
78   Parsing
79       The aim of this stage is to take the Perl source, and turn it into an
80       op tree. We'll see what one of those looks like later. Strictly
81       speaking, there's three things going on here.
82
83       "yyparse", the parser, lives in perly.c, although you're better off
84       reading the original YACC input in perly.y. (Yes, Virginia, there is a
85       YACC grammar for Perl!) The job of the parser is to take your code and
86       "understand" it, splitting it into sentences, deciding which operands
87       go with which operators and so on.
88
89       The parser is nobly assisted by the lexer, which chunks up your input
90       into tokens, and decides what type of thing each token is: a variable
91       name, an operator, a bareword, a subroutine, a core function, and so
92       on. The main point of entry to the lexer is "yylex", and that and its
93       associated routines can be found in toke.c. Perl isn't much like other
94       computer languages; it's highly context sensitive at times, it can be
95       tricky to work out what sort of token something is, or where a token
96       ends. As such, there's a lot of interplay between the tokeniser and the
97       parser, which can get pretty frightening if you're not used to it.
98
99       As the parser understands a Perl program, it builds up a tree of
100       operations for the interpreter to perform during execution. The
101       routines which construct and link together the various operations are
102       to be found in op.c, and will be examined later.
103
104   Optimization
105       Now the parsing stage is complete, and the finished tree represents the
106       operations that the Perl interpreter needs to perform to execute our
107       program. Next, Perl does a dry run over the tree looking for
108       optimisations: constant expressions such as "3 + 4" will be computed
109       now, and the optimizer will also see if any multiple operations can be
110       replaced with a single one. For instance, to fetch the variable $foo,
111       instead of grabbing the glob *foo and looking at the scalar component,
112       the optimizer fiddles the op tree to use a function which directly
113       looks up the scalar in question. The main optimizer is "peep" in op.c,
114       and many ops have their own optimizing functions.
115
116   Running
117       Now we're finally ready to go: we have compiled Perl byte code, and all
118       that's left to do is run it. The actual execution is done by the
119       "runops_standard" function in run.c; more specifically, it's done by
120       these three innocent looking lines:
121
122           while ((PL_op = PL_op->op_ppaddr(aTHX))) {
123               PERL_ASYNC_CHECK();
124           }
125
126       You may be more comfortable with the Perl version of that:
127
128           PERL_ASYNC_CHECK() while $Perl::op = &{$Perl::op->{function}};
129
130       Well, maybe not. Anyway, each op contains a function pointer, which
131       stipulates the function which will actually carry out the operation.
132       This function will return the next op in the sequence - this allows for
133       things like "if" which choose the next op dynamically at run time. The
134       "PERL_ASYNC_CHECK" makes sure that things like signals interrupt
135       execution if required.
136
137       The actual functions called are known as PP code, and they're spread
138       between four files: pp_hot.c contains the "hot" code, which is most
139       often used and highly optimized, pp_sys.c contains all the system-
140       specific functions, pp_ctl.c contains the functions which implement
141       control structures ("if", "while" and the like) and pp.c contains
142       everything else. These are, if you like, the C code for Perl's built-in
143       functions and operators.
144
145       Note that each "pp_" function is expected to return a pointer to the
146       next op. Calls to perl subs (and eval blocks) are handled within the
147       same runops loop, and do not consume extra space on the C stack. For
148       example, "pp_entersub" and "pp_entertry" just push a "CXt_SUB" or
149       "CXt_EVAL" block struct onto the context stack, which contain the
150       address of the op following the sub call or eval. They then return the
151       first op of that sub or eval block, and so execution continues of that
152       sub or block. Later, a "pp_leavesub" or "pp_leavetry" op pops the
153       "CXt_SUB" or "CXt_EVAL", retrieves the return op from it, and returns
154       it.
155
156   Exception handing
157       Perl's exception handing (i.e. "die" etc.) is built on top of the low-
158       level setjmp()/longjmp() C-library functions. These basically provide a
159       way to capture the current PC and SP registers of the CPU and later
160       restore them: i.e. a longjmp() continues at the point in code where a
161       previous setjmp() was done, with anything further up on the C stack
162       being lost. (This is why code should always save values using
163       "SAVE_FOO" rather than in auto variables.)
164
165       The perl core wraps setjmp() and longjmp() in the macros "JMPENV_PUSH"
166       and "JMPENV_JUMP". The push operation, as well as setting a setjump(),
167       stores some temporary state in a struct local to the current function
168       (allocated by "dJMPENV"). In particular, it stores a pointer to the
169       previous "JMPENV" struct, and updates "PL_top_env" to point to the
170       newest one, forming a chain of "JMPENV" states. Both the push and jump
171       can output debugging information under "perl -Dl".
172
173       A basic rule of the perl internals is that all interpreter exits are
174       achieved via a JMPENV_JUMP(). In particular:
175
176       •   level 2: perl-level exit() and internals my_exit()
177
178           These unwind all stacks, then perform a JMPENV_JUMP(2).
179
180       •   level 3: perl-level die() and internals croak()
181
182           If currently within an eval, these pop the context stack back to
183           the nearest "CXt_EVAL" frame, set $@ as appropriate, set
184           "PL_restartop" to the op which follows the eval associated with
185           that frame, then perform a JMPENV_JUMP(3).
186
187           Otherwise, the error message is printed to "STDERR", then it is
188           treated as an exit: unwind all stacks and perform a JMPENV_JUMP(2).
189
190       •   level 1: unused
191
192           JMPENV_JUMP(1) is currently unused except in perl_run().
193
194       •   level 0: normal return.
195
196           The zero value is for a normal return from JMPENV_PUSH()
197
198       So the perl interpreter expects that, at all times, there is a suitable
199       "JMPENV_PUSH" set up (and at a suitable location within the CPU call
200       stack) that can catch and process a 2- or 3-valued jump; and in the
201       case of a 3, start a new runops loop to execute "PL_restartop" and all
202       remaining ops (as will be explained shortly).
203
204       The entry points to the perl interpreter all provide such a facility.
205       For example, perl_parse(),  perl_run() and  "call_sv(cv, G_EVAL)" all
206       contain something similar in outline to:
207
208           {
209               dJMPENV;
210               JMPENV_PUSH(ret);
211               switch (ret) {
212               case 0:                     /* normal return from JMPENV_PUSH() */
213                 redo_body:
214                   CALLRUNOPS(aTHX);
215                   break;
216               case 2:                     /* caught longjmp(2) - exit / die */
217                   break;
218               case 3:                     /* caught longjmp(3) - eval { die } */
219                   PL_op = PL_restartop;
220                   goto redo_body;
221               }
222
223               JMPENV_POP;
224           }
225
226       A runops loop such as Perl_runops_standard() (as set up by
227       CALLRUNOPS()) is, at its heart, just a simple:
228
229           while ((PL_op = PL_op->op_ppaddr(aTHX))) { 1; }
230
231       which calls the pp() function associated with each op, relying on that
232       to return a pointer to the next op to be executed.
233
234       As well as setting catches at the entry points to the perl interpreter,
235       you might expect perl to also do a JMPENV_PUSH() in places like
236       pp_entertry(), just before some trappable ops are executed. In fact
237       perl doesn't normally do this. The drawback with doing it is that with
238       nested or recursive code such as:
239
240           sub foo { my ($i) = @_; return if $i < 0; eval { foo(--$i) } }
241
242       Then the C stack would quickly overflow with pairs of entries like
243
244           ...
245           #N+3 Perl_runops()
246           #N+2 Perl_pp_entertry()
247           #N+1 Perl_runops()
248           #N   Perl_pp_entertry()
249           ...
250
251       Instead, perl puts its guards at the callers of runops loops. Then as
252       many nested subroutine calls and evals may be called as you like, all
253       within the one runops loop. If an exception occurs, control passes back
254       to the caller of the loop, which just immediately restarts a new loop
255       with "PL_restartop" being the next op to call.
256
257       So in normal operation where there are several nested evals, there will
258       be multiple "CXt_EVAL" context stack entries, but only a single runops
259       loop, guarded by a single "JMPENV_PUSH". Each caught eval will pop the
260       next "CXt_EVAL" off the stack, set "PL_restartop", then longjmp() back
261       to perl_run() and continue.
262
263       However, ops are sometimes executed within an inner runops loop, such
264       as in a tie, sort, or overload code. In this case, something like
265
266           sub FETCH { eval { die }; .... }
267
268       would, unless handled specially, cause a longjmp() right back to the
269       guard in perl_run(), popping both the runops loops - which is clearly
270       incorrect.  One way to avoid this is for the tie code to do a
271       "JMPENV_PUSH" before executing "FETCH" in the inner runops loop, but
272       for efficiency reasons, perl in fact just temporarily sets a flag using
273       CATCH_SET(TRUE). This flag warns any subsequent "require", "entereval"
274       or "entertry" ops that the caller is no longer promising to catch any
275       raised exceptions on their behalf.
276
277       These ops check this flag, and if true, they (via docatch()) do a
278       "JMPENV_PUSH" and start a new runops loop to execute the code, rather
279       than doing it with the current loop.
280
281       As a consequence, on exit from the eval block in the "FETCH" above,
282       execution of the code following the block is still carried on in the
283       inner loop (i.e. the one established by the pp_entertry()). To avoid
284       confusion, if a further exception is then raised, docatch() compares
285       the "JMPENV" level of the "CXt_EVAL" with "PL_top_env" and if they
286       differ, just re-throws the exception. In this way any inner loops get
287       popped, and the exception will be dealt with properly by the level
288       which is expecting it.
289
290       Here's an example.
291
292           1: eval { tie @a, 'A' };
293           2: sub A::TIEARRAY {
294           3:     eval { die };
295           4:     die;
296           5: }
297
298       To run this code, perl_run() is called, which does a JMPENV_PUSH(),
299       then enters a runops loop. This loop executes the "entereval" and "tie"
300       ops on line 1, with the "entereval" pushing a "CXt_EVAL" onto the
301       context stack.
302
303       The pp_tie() does a CATCH_SET(TRUE), then starts a second runops loop
304       to execute the body of TIEARRAY(). When the loop executes the
305       "entertry" op on line 3, CATCH_GET() is true, so pp_entertry() calls
306       docatch() which does a "JMPENV_PUSH" and starts a third runops loop,
307       which restarts the pp_entertry(), then executes the "die" op. At this
308       point the C call stack looks like this:
309
310           #10 Perl_pp_die()
311           #9  Perl_runops()      # runops loop 3
312           #8  S_docatch()        # JMPENV level 2
313           #7  Perl_pp_entertry()
314           #6  Perl_runops()      # runops loop 2
315           #5  Perl_call_sv()
316           #4  Perl_pp_tie()
317           #3  Perl_runops()      # runops loop 1
318           #2  S_run_body()
319           #1  perl_run()         # JMPENV level 1
320           #0  main()
321
322       and the context and data stacks, as shown by "perl -Dstv", look like:
323
324           STACK 0: MAIN
325             CX 0: BLOCK  =>
326             CX 1: EVAL   => AV()  PV("A"\0)
327             retop=leave
328           STACK 1: MAGIC
329             CX 0: SUB    =>
330             retop=(null)
331             CX 1: EVAL   => *
332           retop=nextstate
333
334       The die() pops the first "CXt_EVAL" off the context stack, sets
335       "PL_restartop" from it, does a JMPENV_JUMP(3), and control returns to
336       the "JMPENV" level set in docatch(). This then starts another third-
337       level runops level, which executes the "nextstate", "pushmark" and
338       "die" ops from line 4. At the point that the second pp_die() is called,
339       the C call stack looks exactly like that above, even though we are no
340       longer within an inner eval. However, the context stack now looks like
341       this, i.e. with the top CXt_EVAL popped:
342
343           STACK 0: MAIN
344             CX 0: BLOCK  =>
345             CX 1: EVAL   => AV()  PV("A"\0)
346             retop=leave
347           STACK 1: MAGIC
348             CX 0: SUB    =>
349             retop=(null)
350
351       The die() on line 4 pops the context stack back down to the "CXt_EVAL",
352       leaving it as:
353
354           STACK 0: MAIN
355             CX 0: BLOCK  =>
356
357       As usual, "PL_restartop" is extracted from the "CXt_EVAL", and a
358       JMPENV_JUMP(3) done, which pops the C stack back to the docatch():
359
360           #8  S_docatch()        # JMPENV level 2
361           #7  Perl_pp_entertry()
362           #6  Perl_runops()      # runops loop 2
363           #5  Perl_call_sv()
364           #4  Perl_pp_tie()
365           #3  Perl_runops()      # runops loop 1
366           #2  S_run_body()
367           #1  perl_run()         # JMPENV level 1
368           #0  main()
369
370       In  this case, because the "JMPENV" level recorded in the "CXt_EVAL"
371       differs from the current one, docatch() just does a JMPENV_JUMP(3) to
372       re-throw the exception, and the C stack unwinds to:
373
374           #1  perl_run()         # JMPENV level 1
375           #0  main()
376
377       Because "PL_restartop" is non-null, run_body() starts a new runops
378       loop, and execution continues.
379
380   INTERNAL VARIABLE TYPES
381       You should by now have had a look at perlguts, which tells you about
382       Perl's internal variable types: SVs, HVs, AVs and the rest. If not, do
383       that now.
384
385       These variables are used not only to represent Perl-space variables,
386       but also any constants in the code, as well as some structures
387       completely internal to Perl. The symbol table, for instance, is an
388       ordinary Perl hash. Your code is represented by an SV as it's read into
389       the parser; any program files you call are opened via ordinary Perl
390       filehandles, and so on.
391
392       The core Devel::Peek module lets us examine SVs from a Perl program.
393       Let's see, for instance, how Perl treats the constant "hello".
394
395             % perl -MDevel::Peek -e 'Dump("hello")'
396           1 SV = PV(0xa041450) at 0xa04ecbc
397           2   REFCNT = 1
398           3   FLAGS = (POK,READONLY,pPOK)
399           4   PV = 0xa0484e0 "hello"\0
400           5   CUR = 5
401           6   LEN = 6
402
403       Reading "Devel::Peek" output takes a bit of practise, so let's go
404       through it line by line.
405
406       Line 1 tells us we're looking at an SV which lives at 0xa04ecbc in
407       memory. SVs themselves are very simple structures, but they contain a
408       pointer to a more complex structure. In this case, it's a PV, a
409       structure which holds a string value, at location 0xa041450. Line 2 is
410       the reference count; there are no other references to this data, so
411       it's 1.
412
413       Line 3 are the flags for this SV - it's OK to use it as a PV, it's a
414       read-only SV (because it's a constant) and the data is a PV internally.
415       Next we've got the contents of the string, starting at location
416       0xa0484e0.
417
418       Line 5 gives us the current length of the string - note that this does
419       not include the null terminator. Line 6 is not the length of the
420       string, but the length of the currently allocated buffer; as the string
421       grows, Perl automatically extends the available storage via a routine
422       called "SvGROW".
423
424       You can get at any of these quantities from C very easily; just add
425       "Sv" to the name of the field shown in the snippet, and you've got a
426       macro which will return the value: SvCUR(sv) returns the current length
427       of the string, SvREFCOUNT(sv) returns the reference count, "SvPV(sv,
428       len)" returns the string itself with its length, and so on.  More
429       macros to manipulate these properties can be found in perlguts.
430
431       Let's take an example of manipulating a PV, from "sv_catpvn", in sv.c
432
433            1  void
434            2  Perl_sv_catpvn(pTHX_ SV *sv, const char *ptr, STRLEN len)
435            3  {
436            4      STRLEN tlen;
437            5      char *junk;
438
439            6      junk = SvPV_force(sv, tlen);
440            7      SvGROW(sv, tlen + len + 1);
441            8      if (ptr == junk)
442            9          ptr = SvPVX(sv);
443           10      Move(ptr,SvPVX(sv)+tlen,len,char);
444           11      SvCUR(sv) += len;
445           12      *SvEND(sv) = '\0';
446           13      (void)SvPOK_only_UTF8(sv);          /* validate pointer */
447           14      SvTAINT(sv);
448           15  }
449
450       This is a function which adds a string, "ptr", of length "len" onto the
451       end of the PV stored in "sv". The first thing we do in line 6 is make
452       sure that the SV has a valid PV, by calling the "SvPV_force" macro to
453       force a PV. As a side effect, "tlen" gets set to the current value of
454       the PV, and the PV itself is returned to "junk".
455
456       In line 7, we make sure that the SV will have enough room to
457       accommodate the old string, the new string and the null terminator. If
458       "LEN" isn't big enough, "SvGROW" will reallocate space for us.
459
460       Now, if "junk" is the same as the string we're trying to add, we can
461       grab the string directly from the SV; "SvPVX" is the address of the PV
462       in the SV.
463
464       Line 10 does the actual catenation: the "Move" macro moves a chunk of
465       memory around: we move the string "ptr" to the end of the PV - that's
466       the start of the PV plus its current length. We're moving "len" bytes
467       of type "char". After doing so, we need to tell Perl we've extended the
468       string, by altering "CUR" to reflect the new length. "SvEND" is a macro
469       which gives us the end of the string, so that needs to be a "\0".
470
471       Line 13 manipulates the flags; since we've changed the PV, any IV or NV
472       values will no longer be valid: if we have "$a=10; $a.="6";" we don't
473       want to use the old IV of 10. "SvPOK_only_utf8" is a special
474       UTF-8-aware version of "SvPOK_only", a macro which turns off the IOK
475       and NOK flags and turns on POK. The final "SvTAINT" is a macro which
476       launders tainted data if taint mode is turned on.
477
478       AVs and HVs are more complicated, but SVs are by far the most common
479       variable type being thrown around. Having seen something of how we
480       manipulate these, let's go on and look at how the op tree is
481       constructed.
482

OP TREES

484       First, what is the op tree, anyway? The op tree is the parsed
485       representation of your program, as we saw in our section on parsing,
486       and it's the sequence of operations that Perl goes through to execute
487       your program, as we saw in "Running".
488
489       An op is a fundamental operation that Perl can perform: all the built-
490       in functions and operators are ops, and there are a series of ops which
491       deal with concepts the interpreter needs internally - entering and
492       leaving a block, ending a statement, fetching a variable, and so on.
493
494       The op tree is connected in two ways: you can imagine that there are
495       two "routes" through it, two orders in which you can traverse the tree.
496       First, parse order reflects how the parser understood the code, and
497       secondly, execution order tells perl what order to perform the
498       operations in.
499
500       The easiest way to examine the op tree is to stop Perl after it has
501       finished parsing, and get it to dump out the tree. This is exactly what
502       the compiler backends B::Terse, B::Concise and CPAN module <B::Debug
503       do.
504
505       Let's have a look at how Perl sees "$a = $b + $c":
506
507            % perl -MO=Terse -e '$a=$b+$c'
508            1  LISTOP (0x8179888) leave
509            2      OP (0x81798b0) enter
510            3      COP (0x8179850) nextstate
511            4      BINOP (0x8179828) sassign
512            5          BINOP (0x8179800) add [1]
513            6              UNOP (0x81796e0) null [15]
514            7                  SVOP (0x80fafe0) gvsv  GV (0x80fa4cc) *b
515            8              UNOP (0x81797e0) null [15]
516            9                  SVOP (0x8179700) gvsv  GV (0x80efeb0) *c
517           10          UNOP (0x816b4f0) null [15]
518           11              SVOP (0x816dcf0) gvsv  GV (0x80fa460) *a
519
520       Let's start in the middle, at line 4. This is a BINOP, a binary
521       operator, which is at location 0x8179828. The specific operator in
522       question is "sassign" - scalar assignment - and you can find the code
523       which implements it in the function "pp_sassign" in pp_hot.c. As a
524       binary operator, it has two children: the add operator, providing the
525       result of "$b+$c", is uppermost on line 5, and the left hand side is on
526       line 10.
527
528       Line 10 is the null op: this does exactly nothing. What is that doing
529       there? If you see the null op, it's a sign that something has been
530       optimized away after parsing. As we mentioned in "Optimization", the
531       optimization stage sometimes converts two operations into one, for
532       example when fetching a scalar variable. When this happens, instead of
533       rewriting the op tree and cleaning up the dangling pointers, it's
534       easier just to replace the redundant operation with the null op.
535       Originally, the tree would have looked like this:
536
537           10          SVOP (0x816b4f0) rv2sv [15]
538           11              SVOP (0x816dcf0) gv  GV (0x80fa460) *a
539
540       That is, fetch the "a" entry from the main symbol table, and then look
541       at the scalar component of it: "gvsv" ("pp_gvsv" in pp_hot.c) happens
542       to do both these things.
543
544       The right hand side, starting at line 5 is similar to what we've just
545       seen: we have the "add" op ("pp_add", also in pp_hot.c) add together
546       two "gvsv"s.
547
548       Now, what's this about?
549
550            1  LISTOP (0x8179888) leave
551            2      OP (0x81798b0) enter
552            3      COP (0x8179850) nextstate
553
554       "enter" and "leave" are scoping ops, and their job is to perform any
555       housekeeping every time you enter and leave a block: lexical variables
556       are tidied up, unreferenced variables are destroyed, and so on. Every
557       program will have those first three lines: "leave" is a list, and its
558       children are all the statements in the block. Statements are delimited
559       by "nextstate", so a block is a collection of "nextstate" ops, with the
560       ops to be performed for each statement being the children of
561       "nextstate". "enter" is a single op which functions as a marker.
562
563       That's how Perl parsed the program, from top to bottom:
564
565                               Program
566                                  |
567                              Statement
568                                  |
569                                  =
570                                 / \
571                                /   \
572                               $a   +
573                                   / \
574                                 $b   $c
575
576       However, it's impossible to perform the operations in this order: you
577       have to find the values of $b and $c before you add them together, for
578       instance. So, the other thread that runs through the op tree is the
579       execution order: each op has a field "op_next" which points to the next
580       op to be run, so following these pointers tells us how perl executes
581       the code. We can traverse the tree in this order using the "exec"
582       option to "B::Terse":
583
584            % perl -MO=Terse,exec -e '$a=$b+$c'
585            1  OP (0x8179928) enter
586            2  COP (0x81798c8) nextstate
587            3  SVOP (0x81796c8) gvsv  GV (0x80fa4d4) *b
588            4  SVOP (0x8179798) gvsv  GV (0x80efeb0) *c
589            5  BINOP (0x8179878) add [1]
590            6  SVOP (0x816dd38) gvsv  GV (0x80fa468) *a
591            7  BINOP (0x81798a0) sassign
592            8  LISTOP (0x8179900) leave
593
594       This probably makes more sense for a human: enter a block, start a
595       statement. Get the values of $b and $c, and add them together.  Find
596       $a, and assign one to the other. Then leave.
597
598       The way Perl builds up these op trees in the parsing process can be
599       unravelled by examining toke.c, the lexer, and perly.y, the YACC
600       grammar. Let's look at the code that constructs the tree for $a = $b +
601       $c.
602
603       First, we'll look at the "Perl_yylex" function in the lexer. We want to
604       look for "case 'x'", where x is the first character of the operator.
605       (Incidentally, when looking for the code that handles a keyword, you'll
606       want to search for "KEY_foo" where "foo" is the keyword.) Here is the
607       code that handles assignment (there are quite a few operators beginning
608       with "=", so most of it is omitted for brevity):
609
610            1    case '=':
611            2        s++;
612                     ... code that handles == => etc. and pod ...
613            3        pl_yylval.ival = 0;
614            4        OPERATOR(ASSIGNOP);
615
616       We can see on line 4 that our token type is "ASSIGNOP" ("OPERATOR" is a
617       macro, defined in toke.c, that returns the token type, among other
618       things). And "+":
619
620            1     case '+':
621            2         {
622            3             const char tmp = *s++;
623                          ... code for ++ ...
624            4             if (PL_expect == XOPERATOR) {
625                              ...
626            5                 Aop(OP_ADD);
627            6             }
628                          ...
629            7         }
630
631       Line 4 checks what type of token we are expecting. "Aop" returns a
632       token.  If you search for "Aop" elsewhere in toke.c, you will see that
633       it returns an "ADDOP" token.
634
635       Now that we know the two token types we want to look for in the parser,
636       let's take the piece of perly.y we need to construct the tree for "$a =
637       $b + $c"
638
639           1 term    :   term ASSIGNOP term
640           2                { $$ = newASSIGNOP(OPf_STACKED, $1, $2, $3); }
641           3         |   term ADDOP term
642           4                { $$ = newBINOP($2, 0, scalar($1), scalar($3)); }
643
644       If you're not used to reading BNF grammars, this is how it works:
645       You're fed certain things by the tokeniser, which generally end up in
646       upper case. "ADDOP" and "ASSIGNOP" are examples of "terminal symbols",
647       because you can't get any simpler than them.
648
649       The grammar, lines one and three of the snippet above, tells you how to
650       build up more complex forms. These complex forms, "non-terminal
651       symbols" are generally placed in lower case. "term" here is a non-
652       terminal symbol, representing a single expression.
653
654       The grammar gives you the following rule: you can make the thing on the
655       left of the colon if you see all the things on the right in sequence.
656       This is called a "reduction", and the aim of parsing is to completely
657       reduce the input. There are several different ways you can perform a
658       reduction, separated by vertical bars: so, "term" followed by "="
659       followed by "term" makes a "term", and "term" followed by "+" followed
660       by "term" can also make a "term".
661
662       So, if you see two terms with an "=" or "+", between them, you can turn
663       them into a single expression. When you do this, you execute the code
664       in the block on the next line: if you see "=", you'll do the code in
665       line 2. If you see "+", you'll do the code in line 4. It's this code
666       which contributes to the op tree.
667
668                   |   term ADDOP term
669                   { $$ = newBINOP($2, 0, scalar($1), scalar($3)); }
670
671       What this does is creates a new binary op, and feeds it a number of
672       variables. The variables refer to the tokens: $1 is the first token in
673       the input, $2 the second, and so on - think regular expression
674       backreferences. $$ is the op returned from this reduction. So, we call
675       "newBINOP" to create a new binary operator. The first parameter to
676       "newBINOP", a function in op.c, is the op type. It's an addition
677       operator, so we want the type to be "ADDOP". We could specify this
678       directly, but it's right there as the second token in the input, so we
679       use $2. The second parameter is the op's flags: 0 means "nothing
680       special". Then the things to add: the left and right hand side of our
681       expression, in scalar context.
682
683       The functions that create ops, which have names like "newUNOP" and
684       "newBINOP", call a "check" function associated with each op type,
685       before returning the op. The check functions can mangle the op as they
686       see fit, and even replace it with an entirely new one. These functions
687       are defined in op.c, and have a "Perl_ck_" prefix. You can find out
688       which check function is used for a particular op type by looking in
689       regen/opcodes.  Take "OP_ADD", for example. ("OP_ADD" is the token
690       value from the Aop(OP_ADD) in toke.c which the parser passes to
691       "newBINOP" as its first argument.) Here is the relevant line:
692
693           add             addition (+)            ck_null         IfsT2   S S
694
695       The check function in this case is "Perl_ck_null", which does nothing.
696       Let's look at a more interesting case:
697
698           readline        <HANDLE>                ck_readline     t%      F?
699
700       And here is the function from op.c:
701
702            1 OP *
703            2 Perl_ck_readline(pTHX_ OP *o)
704            3 {
705            4     PERL_ARGS_ASSERT_CK_READLINE;
706            5
707            6     if (o->op_flags & OPf_KIDS) {
708            7          OP *kid = cLISTOPo->op_first;
709            8          if (kid->op_type == OP_RV2GV)
710            9              kid->op_private |= OPpALLOW_FAKE;
711           10     }
712           11     else {
713           12         OP * const newop
714           13             = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0,
715           14                                               PL_argvgv));
716           15         op_free(o);
717           16         return newop;
718           17     }
719           18     return o;
720           19 }
721
722       One particularly interesting aspect is that if the op has no kids
723       (i.e., readline() or "<>") the op is freed and replaced with an
724       entirely new one that references *ARGV (lines 12-16).
725

STACKS

727       When perl executes something like "addop", how does it pass on its
728       results to the next op? The answer is, through the use of stacks. Perl
729       has a number of stacks to store things it's currently working on, and
730       we'll look at the three most important ones here.
731
732   Argument stack
733       Arguments are passed to PP code and returned from PP code using the
734       argument stack, "ST". The typical way to handle arguments is to pop
735       them off the stack, deal with them how you wish, and then push the
736       result back onto the stack. This is how, for instance, the cosine
737       operator works:
738
739             NV value;
740             value = POPn;
741             value = Perl_cos(value);
742             XPUSHn(value);
743
744       We'll see a more tricky example of this when we consider Perl's macros
745       below. "POPn" gives you the NV (floating point value) of the top SV on
746       the stack: the $x in cos($x). Then we compute the cosine, and push the
747       result back as an NV. The "X" in "XPUSHn" means that the stack should
748       be extended if necessary - it can't be necessary here, because we know
749       there's room for one more item on the stack, since we've just removed
750       one! The "XPUSH*" macros at least guarantee safety.
751
752       Alternatively, you can fiddle with the stack directly: "SP" gives you
753       the first element in your portion of the stack, and "TOP*" gives you
754       the top SV/IV/NV/etc. on the stack. So, for instance, to do unary
755       negation of an integer:
756
757            SETi(-TOPi);
758
759       Just set the integer value of the top stack entry to its negation.
760
761       Argument stack manipulation in the core is exactly the same as it is in
762       XSUBs - see perlxstut, perlxs and perlguts for a longer description of
763       the macros used in stack manipulation.
764
765   Mark stack
766       I say "your portion of the stack" above because PP code doesn't
767       necessarily get the whole stack to itself: if your function calls
768       another function, you'll only want to expose the arguments aimed for
769       the called function, and not (necessarily) let it get at your own data.
770       The way we do this is to have a "virtual" bottom-of-stack, exposed to
771       each function. The mark stack keeps bookmarks to locations in the
772       argument stack usable by each function. For instance, when dealing with
773       a tied variable, (internally, something with "P" magic) Perl has to
774       call methods for accesses to the tied variables. However, we need to
775       separate the arguments exposed to the method to the argument exposed to
776       the original function - the store or fetch or whatever it may be.
777       Here's roughly how the tied "push" is implemented; see "av_push" in
778       av.c:
779
780            1  PUSHMARK(SP);
781            2  EXTEND(SP,2);
782            3  PUSHs(SvTIED_obj((SV*)av, mg));
783            4  PUSHs(val);
784            5  PUTBACK;
785            6  ENTER;
786            7  call_method("PUSH", G_SCALAR|G_DISCARD);
787            8  LEAVE;
788
789       Let's examine the whole implementation, for practice:
790
791            1  PUSHMARK(SP);
792
793       Push the current state of the stack pointer onto the mark stack. This
794       is so that when we've finished adding items to the argument stack, Perl
795       knows how many things we've added recently.
796
797            2  EXTEND(SP,2);
798            3  PUSHs(SvTIED_obj((SV*)av, mg));
799            4  PUSHs(val);
800
801       We're going to add two more items onto the argument stack: when you
802       have a tied array, the "PUSH" subroutine receives the object and the
803       value to be pushed, and that's exactly what we have here - the tied
804       object, retrieved with "SvTIED_obj", and the value, the SV "val".
805
806            5  PUTBACK;
807
808       Next we tell Perl to update the global stack pointer from our internal
809       variable: "dSP" only gave us a local copy, not a reference to the
810       global.
811
812            6  ENTER;
813            7  call_method("PUSH", G_SCALAR|G_DISCARD);
814            8  LEAVE;
815
816       "ENTER" and "LEAVE" localise a block of code - they make sure that all
817       variables are tidied up, everything that has been localised gets its
818       previous value returned, and so on. Think of them as the "{" and "}" of
819       a Perl block.
820
821       To actually do the magic method call, we have to call a subroutine in
822       Perl space: "call_method" takes care of that, and it's described in
823       perlcall. We call the "PUSH" method in scalar context, and we're going
824       to discard its return value. The call_method() function removes the top
825       element of the mark stack, so there is nothing for the caller to clean
826       up.
827
828   Save stack
829       C doesn't have a concept of local scope, so perl provides one. We've
830       seen that "ENTER" and "LEAVE" are used as scoping braces; the save
831       stack implements the C equivalent of, for example:
832
833           {
834               local $foo = 42;
835               ...
836           }
837
838       See "Localizing changes" in perlguts for how to use the save stack.
839

MILLIONS OF MACROS

841       One thing you'll notice about the Perl source is that it's full of
842       macros. Some have called the pervasive use of macros the hardest thing
843       to understand, others find it adds to clarity. Let's take an example, a
844       stripped-down version the code which implements the addition operator:
845
846          1  PP(pp_add)
847          2  {
848          3      dSP; dATARGET;
849          4      tryAMAGICbin_MG(add_amg, AMGf_assign|AMGf_numeric);
850          5      {
851          6        dPOPTOPnnrl_ul;
852          7        SETn( left + right );
853          8        RETURN;
854          9      }
855         10  }
856
857       Every line here (apart from the braces, of course) contains a macro.
858       The first line sets up the function declaration as Perl expects for PP
859       code; line 3 sets up variable declarations for the argument stack and
860       the target, the return value of the operation. Line 4 tries to see if
861       the addition operation is overloaded; if so, the appropriate subroutine
862       is called.
863
864       Line 6 is another variable declaration - all variable declarations
865       start with "d" - which pops from the top of the argument stack two NVs
866       (hence "nn") and puts them into the variables "right" and "left", hence
867       the "rl". These are the two operands to the addition operator.  Next,
868       we call "SETn" to set the NV of the return value to the result of
869       adding the two values. This done, we return - the "RETURN" macro makes
870       sure that our return value is properly handled, and we pass the next
871       operator to run back to the main run loop.
872
873       Most of these macros are explained in perlapi, and some of the more
874       important ones are explained in perlxs as well. Pay special attention
875       to "Background and MULTIPLICITY" in perlguts for information on the
876       "[pad]THX_?" macros.
877

FURTHER READING

879       For more information on the Perl internals, please see the documents
880       listed at "Internals and C Language Interface" in perl.
881
882
883
884perl v5.38.2                      2023-11-30                     PERLINTERP(1)
Impressum