{
    "content": [
        {
            "type": "text",
            "text": "# PERLINTERP (man)\n\n## NAME\n\nperlinterp - An overview of the Perl interpreter\n\n## DESCRIPTION\n\nThis document provides an overview of how the Perl interpreter works at the level of C code,\nalong with pointers to the relevant C source code files.\n\n## Sections\n\n- **NAME**\n- **DESCRIPTION**\n- **ELEMENTS OF THE INTERPRETER** (5 subsections)\n- **OP TREES**\n- **STACKS** (3 subsections)\n- **MILLIONS OF MACROS**\n- **FURTHER READING**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "PERLINTERP",
        "section": "",
        "mode": "man",
        "summary": "perlinterp - An overview of the Perl interpreter",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 3,
                "subsections": []
            },
            {
                "name": "ELEMENTS OF THE INTERPRETER",
                "lines": 6,
                "subsections": [
                    {
                        "name": "Startup",
                        "lines": 49
                    },
                    {
                        "name": "Parsing",
                        "lines": 20
                    },
                    {
                        "name": "Optimization",
                        "lines": 9
                    },
                    {
                        "name": "Running",
                        "lines": 31
                    },
                    {
                        "name": "Exception handing",
                        "lines": 216
                    }
                ]
            },
            {
                "name": "OP TREES",
                "lines": 213,
                "subsections": []
            },
            {
                "name": "STACKS",
                "lines": 4,
                "subsections": [
                    {
                        "name": "Argument stack",
                        "lines": 29
                    },
                    {
                        "name": "Mark stack",
                        "lines": 53
                    },
                    {
                        "name": "Save stack",
                        "lines": 11
                    }
                ]
            },
            {
                "name": "MILLIONS OF MACROS",
                "lines": 32,
                "subsections": []
            },
            {
                "name": "FURTHER READING",
                "lines": 6,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "perlinterp - An overview of the Perl interpreter\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "This document provides an overview of how the Perl interpreter works at the level of C code,\nalong with pointers to the relevant C source code files.\n",
                "subsections": []
            },
            "ELEMENTS OF THE INTERPRETER": {
                "content": "The work of the interpreter has two main stages: compiling the code into the internal\nrepresentation, or bytecode, and then executing it.  \"Compiled code\" in perlguts explains\nexactly how the compilation stage happens.\n\nHere is a short breakdown of perl's operation:\n",
                "subsections": [
                    {
                        "name": "Startup",
                        "content": "The action begins in perlmain.c. (or miniperlmain.c for miniperl) This is very high-level\ncode, enough to fit on a single screen, and it resembles the code found in perlembed; most of\nthe real action takes place in perl.c\n\nperlmain.c is generated by \"ExtUtils::Miniperl\" from miniperlmain.c at make time, so you\nshould make perl to follow this along.\n\nFirst, perlmain.c allocates some memory and constructs a Perl interpreter, along these lines:\n\n1 PERLSYSINIT3(&argc,&argv,&env);\n2\n3 if (!PLdoundump) {\n4     myperl = perlalloc();\n5     if (!myperl)\n6         exit(1);\n7     perlconstruct(myperl);\n8     PLperldestructlevel = 0;\n9 }\n\nLine 1 is a macro, and its definition is dependent on your operating system. Line 3\nreferences \"PLdoundump\", a global variable - all global variables in Perl start with \"PL\".\nThis tells you whether the current running program was created with the \"-u\" flag to perl and\nthen undump, which means it's going to be false in any sane context.\n\nLine 4 calls a function in perl.c to allocate memory for a Perl interpreter. It's quite a\nsimple function, and the guts of it looks like this:\n\nmyperl = (PerlInterpreter*)PerlMemmalloc(sizeof(PerlInterpreter));\n\nHere you see an example of Perl's system abstraction, which we'll see later: \"PerlMemmalloc\"\nis either your system's \"malloc\", or Perl's own \"malloc\" as defined in malloc.c if you\nselected that option at configure time.\n\nNext, in line 7, we construct the interpreter using perlconstruct, also in perl.c; this sets\nup all the special variables that Perl needs, the stacks, and so on.\n\nNow we pass Perl the command line options, and tell it to go:\n\nif (!perlparse(myperl, xsinit, argc, argv, (char )NULL))\nperlrun(myperl);\n\nexitstatus = perldestruct(myperl);\n\nperlfree(myperl);\n\n\"perlparse\" is actually a wrapper around \"Sparsebody\", as defined in perl.c, which\nprocesses the command line options, sets up any statically linked XS modules, opens the\nprogram and calls \"yyparse\" to parse it.\n"
                    },
                    {
                        "name": "Parsing",
                        "content": "The aim of this stage is to take the Perl source, and turn it into an op tree. We'll see what\none of those looks like later. Strictly speaking, there's three things going on here.\n\n\"yyparse\", the parser, lives in perly.c, although you're better off reading the original YACC\ninput in perly.y. (Yes, Virginia, there is a YACC grammar for Perl!) The job of the parser is\nto take your code and \"understand\" it, splitting it into sentences, deciding which operands\ngo with which operators and so on.\n\nThe parser is nobly assisted by the lexer, which chunks up your input into tokens, and\ndecides what type of thing each token is: a variable name, an operator, a bareword, a\nsubroutine, a core function, and so on. The main point of entry to the lexer is \"yylex\", and\nthat and its associated routines can be found in toke.c. Perl isn't much like other computer\nlanguages; it's highly context sensitive at times, it can be tricky to work out what sort of\ntoken something is, or where a token ends. As such, there's a lot of interplay between the\ntokeniser and the parser, which can get pretty frightening if you're not used to it.\n\nAs the parser understands a Perl program, it builds up a tree of operations for the\ninterpreter to perform during execution. The routines which construct and link together the\nvarious operations are to be found in op.c, and will be examined later.\n"
                    },
                    {
                        "name": "Optimization",
                        "content": "Now the parsing stage is complete, and the finished tree represents the operations that the\nPerl interpreter needs to perform to execute our program. Next, Perl does a dry run over the\ntree looking for optimisations: constant expressions such as \"3 + 4\" will be computed now,\nand the optimizer will also see if any multiple operations can be replaced with a single one.\nFor instance, to fetch the variable $foo, instead of grabbing the glob *foo and looking at\nthe scalar component, the optimizer fiddles the op tree to use a function which directly\nlooks up the scalar in question. The main optimizer is \"peep\" in op.c, and many ops have\ntheir own optimizing functions.\n"
                    },
                    {
                        "name": "Running",
                        "content": "Now we're finally ready to go: we have compiled Perl byte code, and all that's left to do is\nrun it. The actual execution is done by the \"runopsstandard\" function in run.c; more\nspecifically, it's done by these three innocent looking lines:\n\nwhile ((PLop = PLop->opppaddr(aTHX))) {\nPERLASYNCCHECK();\n}\n\nYou may be more comfortable with the Perl version of that:\n\nPERLASYNCCHECK() while $Perl::op = &{$Perl::op->{function}};\n\nWell, maybe not. Anyway, each op contains a function pointer, which stipulates the function\nwhich will actually carry out the operation.  This function will return the next op in the\nsequence - this allows for things like \"if\" which choose the next op dynamically at run time.\nThe \"PERLASYNCCHECK\" makes sure that things like signals interrupt execution if required.\n\nThe actual functions called are known as PP code, and they're spread between four files:\npphot.c contains the \"hot\" code, which is most often used and highly optimized, ppsys.c\ncontains all the system-specific functions, ppctl.c contains the functions which implement\ncontrol structures (\"if\", \"while\" and the like) and pp.c contains everything else. These are,\nif you like, the C code for Perl's built-in functions and operators.\n\nNote that each \"pp\" function is expected to return a pointer to the next op. Calls to perl\nsubs (and eval blocks) are handled within the same runops loop, and do not consume extra\nspace on the C stack. For example, \"ppentersub\" and \"ppentertry\" just push a \"CxSUB\" or\n\"CxEVAL\" block struct onto the context stack which contain the address of the op following\nthe sub call or eval. They then return the first op of that sub or eval block, and so\nexecution continues of that sub or block. Later, a \"ppleavesub\" or \"ppleavetry\" op pops the\n\"CxSUB\" or \"CxEVAL\", retrieves the return op from it, and returns it.\n"
                    },
                    {
                        "name": "Exception handing",
                        "content": "Perl's exception handing (i.e. \"die\" etc.) is built on top of the low-level\n\"setjmp()\"/\"longjmp()\" C-library functions. These basically provide a way to capture the\ncurrent PC and SP registers and later restore them; i.e. a \"longjmp()\" continues at the point\nin code where a previous \"setjmp()\" was done, with anything further up on the C stack being\nlost. This is why code should always save values using \"SAVEFOO\" rather than in auto\nvariables.\n\nThe perl core wraps \"setjmp()\" etc in the macros \"JMPENVPUSH\" and \"JMPENVJUMP\". The basic\nrule of perl exceptions is that \"exit\", and \"die\" (in the absence of \"eval\") perform a\nJMPENVJUMP(2), while \"die\" within \"eval\" does a JMPENVJUMP(3).\n\nAt entry points to perl, such as \"perlparse()\", \"perlrun()\" and \"callsv(cv, GEVAL)\" each\ndoes a \"JMPENVPUSH\", then enter a runops loop or whatever, and handle possible exception\nreturns. For a 2 return, final cleanup is performed, such as popping stacks and calling\n\"CHECK\" or \"END\" blocks. Amongst other things, this is how scope cleanup still occurs during\nan \"exit\".\n\nIf a \"die\" can find a \"CxEVAL\" block on the context stack, then the stack is popped to that\nlevel and the return op in that block is assigned to \"PLrestartop\"; then a JMPENVJUMP(3) is\nperformed.  This normally passes control back to the guard. In the case of \"perlrun\" and\n\"callsv\", a non-null \"PLrestartop\" triggers re-entry to the runops loop. The is the normal\nway that \"die\" or \"croak\" is handled within an \"eval\".\n\nSometimes ops are executed within an inner runops loop, such as tie, sort or overload code.\nIn this case, something like\n\nsub FETCH { eval { die } }\n\nwould cause a longjmp right back to the guard in \"perlrun\", popping both runops loops, which\nis clearly incorrect. One way to avoid this is for the tie code to do a \"JMPENVPUSH\" before\nexecuting \"FETCH\" in the inner runops loop, but for efficiency reasons, perl in fact just\nsets a flag, using \"CATCHSET(TRUE)\". The \"pprequire\", \"ppentereval\" and \"ppentertry\" ops\ncheck this flag, and if true, they call \"docatch\", which does a \"JMPENVPUSH\" and starts a\nnew runops level to execute the code, rather than doing it on the current loop.\n\nAs a further optimisation, on exit from the eval block in the \"FETCH\", execution of the code\nfollowing the block is still carried on in the inner loop. When an exception is raised,\n\"docatch\" compares the \"JMPENV\" level of the \"CxEVAL\" with \"PLtopenv\" and if they differ,\njust re-throws the exception. In this way any inner loops get popped.\n\nHere's an example.\n\n1: eval { tie @a, 'A' };\n2: sub A::TIEARRAY {\n3:     eval { die };\n4:     die;\n5: }\n\nTo run this code, \"perlrun\" is called, which does a \"JMPENVPUSH\" then enters a runops loop.\nThis loop executes the eval and tie ops on line 1, with the eval pushing a \"CxEVAL\" onto the\ncontext stack.\n\nThe \"pptie\" does a \"CATCHSET(TRUE)\", then starts a second runops loop to execute the body\nof \"TIEARRAY\". When it executes the entertry op on line 3, \"CATCHGET\" is true, so\n\"ppentertry\" calls \"docatch\" which does a \"JMPENVPUSH\" and starts a third runops loop,\nwhich then executes the die op. At this point the C call stack looks like this:\n\nPerlppdie\nPerlrunops      # third loop\nSdocatchbody\nSdocatch\nPerlppentertry\nPerlrunops      # second loop\nScallbody\nPerlcallsv\nPerlpptie\nPerlrunops      # first loop\nSrunbody\nperlrun\nmain\n\nand the context and data stacks, as shown by \"-Dstv\", look like:\n\nSTACK 0: MAIN\nCX 0: BLOCK  =>\nCX 1: EVAL   => AV()  PV(\"A\"\\0)\nretop=leave\nSTACK 1: MAGIC\nCX 0: SUB    =>\nretop=(null)\nCX 1: EVAL   => *\nretop=nextstate\n\nThe die pops the first \"CxEVAL\" off the context stack, sets \"PLrestartop\" from it, does a\nJMPENVJUMP(3), and control returns to the top \"docatch\". This then starts another third-\nlevel runops level, which executes the nextstate, pushmark and die ops on line 4. At the\npoint that the second \"ppdie\" is called, the C call stack looks exactly like that above,\neven though we are no longer within an inner eval; this is because of the optimization\nmentioned earlier. However, the context stack now looks like this, ie with the top CxEVAL\npopped:\n\nSTACK 0: MAIN\nCX 0: BLOCK  =>\nCX 1: EVAL   => AV()  PV(\"A\"\\0)\nretop=leave\nSTACK 1: MAGIC\nCX 0: SUB    =>\nretop=(null)\n\nThe die on line 4 pops the context stack back down to the CxEVAL, leaving it as:\n\nSTACK 0: MAIN\nCX 0: BLOCK  =>\n\nAs usual, \"PLrestartop\" is extracted from the \"CxEVAL\", and a JMPENVJUMP(3) done, which\npops the C stack back to the docatch:\n\nSdocatch\nPerlppentertry\nPerlrunops      # second loop\nScallbody\nPerlcallsv\nPerlpptie\nPerlrunops      # first loop\nSrunbody\nperlrun\nmain\n\nIn  this case, because the \"JMPENV\" level recorded in the \"CxEVAL\" differs from the current\none, \"docatch\" just does a JMPENVJUMP(3) and the C stack unwinds to:\n\nperlrun\nmain\n\nBecause \"PLrestartop\" is non-null, \"runbody\" starts a new runops loop and execution\ncontinues.\n\nINTERNAL VARIABLE TYPES\nYou should by now have had a look at perlguts, which tells you about Perl's internal variable\ntypes: SVs, HVs, AVs and the rest. If not, do that now.\n\nThese variables are used not only to represent Perl-space variables, but also any constants\nin the code, as well as some structures completely internal to Perl. The symbol table, for\ninstance, is an ordinary Perl hash. Your code is represented by an SV as it's read into the\nparser; any program files you call are opened via ordinary Perl filehandles, and so on.\n\nThe core Devel::Peek module lets us examine SVs from a Perl program. Let's see, for instance,\nhow Perl treats the constant \"hello\".\n\n% perl -MDevel::Peek -e 'Dump(\"hello\")'\n1 SV = PV(0xa041450) at 0xa04ecbc\n2   REFCNT = 1\n3   FLAGS = (POK,READONLY,pPOK)\n4   PV = 0xa0484e0 \"hello\"\\0\n5   CUR = 5\n6   LEN = 6\n\nReading \"Devel::Peek\" output takes a bit of practise, so let's go through it line by line.\n\nLine 1 tells us we're looking at an SV which lives at 0xa04ecbc in memory. SVs themselves are\nvery simple structures, but they contain a pointer to a more complex structure. In this case,\nit's a PV, a structure which holds a string value, at location 0xa041450. Line 2 is the\nreference count; there are no other references to this data, so it's 1.\n\nLine 3 are the flags for this SV - it's OK to use it as a PV, it's a read-only SV (because\nit's a constant) and the data is a PV internally.  Next we've got the contents of the string,\nstarting at location 0xa0484e0.\n\nLine 5 gives us the current length of the string - note that this does not include the null\nterminator. Line 6 is not the length of the string, but the length of the currently allocated\nbuffer; as the string grows, Perl automatically extends the available storage via a routine\ncalled \"SvGROW\".\n\nYou can get at any of these quantities from C very easily; just add \"Sv\" to the name of the\nfield shown in the snippet, and you've got a macro which will return the value: \"SvCUR(sv)\"\nreturns the current length of the string, \"SvREFCOUNT(sv)\" returns the reference count,\n\"SvPV(sv, len)\" returns the string itself with its length, and so on.  More macros to\nmanipulate these properties can be found in perlguts.\n\nLet's take an example of manipulating a PV, from \"svcatpvn\", in sv.c\n\n1  void\n2  Perlsvcatpvn(pTHX SV *sv, const char *ptr, STRLEN len)\n3  {\n4      STRLEN tlen;\n5      char *junk;\n\n6      junk = SvPVforce(sv, tlen);\n7      SvGROW(sv, tlen + len + 1);\n8      if (ptr == junk)\n9          ptr = SvPVX(sv);\n10      Move(ptr,SvPVX(sv)+tlen,len,char);\n11      SvCUR(sv) += len;\n12      *SvEND(sv) = '\\0';\n13      (void)SvPOKonlyUTF8(sv);          /* validate pointer */\n14      SvTAINT(sv);\n15  }\n\nThis is a function which adds a string, \"ptr\", of length \"len\" onto the end of the PV stored\nin \"sv\". The first thing we do in line 6 is make sure that the SV has a valid PV, by calling\nthe \"SvPVforce\" macro to force a PV. As a side effect, \"tlen\" gets set to the current value\nof the PV, and the PV itself is returned to \"junk\".\n\nIn line 7, we make sure that the SV will have enough room to accommodate the old string, the\nnew string and the null terminator. If \"LEN\" isn't big enough, \"SvGROW\" will reallocate space\nfor us.\n\nNow, if \"junk\" is the same as the string we're trying to add, we can grab the string directly\nfrom the SV; \"SvPVX\" is the address of the PV in the SV.\n\nLine 10 does the actual catenation: the \"Move\" macro moves a chunk of memory around: we move\nthe string \"ptr\" to the end of the PV - that's the start of the PV plus its current length.\nWe're moving \"len\" bytes of type \"char\". After doing so, we need to tell Perl we've extended\nthe string, by altering \"CUR\" to reflect the new length. \"SvEND\" is a macro which gives us\nthe end of the string, so that needs to be a \"\\0\".\n\nLine 13 manipulates the flags; since we've changed the PV, any IV or NV values will no longer\nbe valid: if we have \"$a=10; $a.=\"6\";\" we don't want to use the old IV of 10.\n\"SvPOKonlyutf8\" is a special UTF-8-aware version of \"SvPOKonly\", a macro which turns off\nthe IOK and NOK flags and turns on POK. The final \"SvTAINT\" is a macro which launders tainted\ndata if taint mode is turned on.\n\nAVs and HVs are more complicated, but SVs are by far the most common variable type being\nthrown around. Having seen something of how we manipulate these, let's go on and look at how\nthe op tree is constructed.\n"
                    }
                ]
            },
            "OP TREES": {
                "content": "First, what is the op tree, anyway? The op tree is the parsed representation of your program,\nas we saw in our section on parsing, and it's the sequence of operations that Perl goes\nthrough to execute your program, as we saw in \"Running\".\n\nAn op is a fundamental operation that Perl can perform: all the built-in functions and\noperators are ops, and there are a series of ops which deal with concepts the interpreter\nneeds internally - entering and leaving a block, ending a statement, fetching a variable, and\nso on.\n\nThe op tree is connected in two ways: you can imagine that there are two \"routes\" through it,\ntwo orders in which you can traverse the tree.  First, parse order reflects how the parser\nunderstood the code, and secondly, execution order tells perl what order to perform the\noperations in.\n\nThe easiest way to examine the op tree is to stop Perl after it has finished parsing, and get\nit to dump out the tree. This is exactly what the compiler backends B::Terse, B::Concise and\nCPAN module <B::Debug do.\n\nLet's have a look at how Perl sees \"$a = $b + $c\":\n\n% perl -MO=Terse -e '$a=$b+$c'\n1  LISTOP (0x8179888) leave\n2      OP (0x81798b0) enter\n3      COP (0x8179850) nextstate\n4      BINOP (0x8179828) sassign\n5          BINOP (0x8179800) add [1]\n6              UNOP (0x81796e0) null [15]\n7                  SVOP (0x80fafe0) gvsv  GV (0x80fa4cc) *b\n8              UNOP (0x81797e0) null [15]\n9                  SVOP (0x8179700) gvsv  GV (0x80efeb0) *c\n10          UNOP (0x816b4f0) null [15]\n11              SVOP (0x816dcf0) gvsv  GV (0x80fa460) *a\n\nLet's start in the middle, at line 4. This is a BINOP, a binary operator, which is at\nlocation 0x8179828. The specific operator in question is \"sassign\" - scalar assignment - and\nyou can find the code which implements it in the function \"ppsassign\" in pphot.c. As a\nbinary operator, it has two children: the add operator, providing the result of \"$b+$c\", is\nuppermost on line 5, and the left hand side is on line 10.\n\nLine 10 is the null op: this does exactly nothing. What is that doing there? If you see the\nnull op, it's a sign that something has been optimized away after parsing. As we mentioned in\n\"Optimization\", the optimization stage sometimes converts two operations into one, for\nexample when fetching a scalar variable. When this happens, instead of rewriting the op tree\nand cleaning up the dangling pointers, it's easier just to replace the redundant operation\nwith the null op.  Originally, the tree would have looked like this:\n\n10          SVOP (0x816b4f0) rv2sv [15]\n11              SVOP (0x816dcf0) gv  GV (0x80fa460) *a\n\nThat is, fetch the \"a\" entry from the main symbol table, and then look at the scalar\ncomponent of it: \"gvsv\" (\"ppgvsv\" in pphot.c) happens to do both these things.\n\nThe right hand side, starting at line 5 is similar to what we've just seen: we have the \"add\"\nop (\"ppadd\", also in pphot.c) add together two \"gvsv\"s.\n\nNow, what's this about?\n\n1  LISTOP (0x8179888) leave\n2      OP (0x81798b0) enter\n3      COP (0x8179850) nextstate\n\n\"enter\" and \"leave\" are scoping ops, and their job is to perform any housekeeping every time\nyou enter and leave a block: lexical variables are tidied up, unreferenced variables are\ndestroyed, and so on. Every program will have those first three lines: \"leave\" is a list, and\nits children are all the statements in the block. Statements are delimited by \"nextstate\", so\na block is a collection of \"nextstate\" ops, with the ops to be performed for each statement\nbeing the children of \"nextstate\". \"enter\" is a single op which functions as a marker.\n\nThat's how Perl parsed the program, from top to bottom:\n\nProgram\n|\nStatement\n|\n=\n/ \\\n/   \\\n$a   +\n/ \\\n$b   $c\n\nHowever, it's impossible to perform the operations in this order: you have to find the values\nof $b and $c before you add them together, for instance. So, the other thread that runs\nthrough the op tree is the execution order: each op has a field \"opnext\" which points to the\nnext op to be run, so following these pointers tells us how perl executes the code. We can\ntraverse the tree in this order using the \"exec\" option to \"B::Terse\":\n\n% perl -MO=Terse,exec -e '$a=$b+$c'\n1  OP (0x8179928) enter\n2  COP (0x81798c8) nextstate\n3  SVOP (0x81796c8) gvsv  GV (0x80fa4d4) *b\n4  SVOP (0x8179798) gvsv  GV (0x80efeb0) *c\n5  BINOP (0x8179878) add [1]\n6  SVOP (0x816dd38) gvsv  GV (0x80fa468) *a\n7  BINOP (0x81798a0) sassign\n8  LISTOP (0x8179900) leave\n\nThis probably makes more sense for a human: enter a block, start a statement. Get the values\nof $b and $c, and add them together.  Find $a, and assign one to the other. Then leave.\n\nThe way Perl builds up these op trees in the parsing process can be unravelled by examining\ntoke.c, the lexer, and perly.y, the YACC grammar. Let's look at the code that constructs the\ntree for \"$a = $b + $c\".\n\nFirst, we'll look at the \"Perlyylex\" function in the lexer. We want to look for \"case 'x'\",\nwhere x is the first character of the operator.  (Incidentally, when looking for the code\nthat handles a keyword, you'll want to search for \"KEYfoo\" where \"foo\" is the keyword.) Here\nis the code that handles assignment (there are quite a few operators beginning with \"=\", so\nmost of it is omitted for brevity):\n\n1    case '=':\n2        s++;\n... code that handles == => etc. and pod ...\n3        plyylval.ival = 0;\n4        OPERATOR(ASSIGNOP);\n\nWe can see on line 4 that our token type is \"ASSIGNOP\" (\"OPERATOR\" is a macro, defined in\ntoke.c, that returns the token type, among other things). And \"+\":\n\n1     case '+':\n2         {\n3             const char tmp = *s++;\n... code for ++ ...\n4             if (PLexpect == XOPERATOR) {\n...\n5                 Aop(OPADD);\n6             }\n...\n7         }\n\nLine 4 checks what type of token we are expecting. \"Aop\" returns a token.  If you search for\n\"Aop\" elsewhere in toke.c, you will see that it returns an \"ADDOP\" token.\n\nNow that we know the two token types we want to look for in the parser, let's take the piece\nof perly.y we need to construct the tree for \"$a = $b + $c\"\n\n1 term    :   term ASSIGNOP term\n2                { $$ = newASSIGNOP(OPfSTACKED, $1, $2, $3); }\n3         |   term ADDOP term\n4                { $$ = newBINOP($2, 0, scalar($1), scalar($3)); }\n\nIf you're not used to reading BNF grammars, this is how it works: You're fed certain things\nby the tokeniser, which generally end up in upper case. \"ADDOP\" and \"ASSIGNOP\" are examples\nof \"terminal symbols\", because you can't get any simpler than them.\n\nThe grammar, lines one and three of the snippet above, tells you how to build up more complex\nforms. These complex forms, \"non-terminal symbols\" are generally placed in lower case. \"term\"\nhere is a non-terminal symbol, representing a single expression.\n\nThe grammar gives you the following rule: you can make the thing on the left of the colon if\nyou see all the things on the right in sequence.  This is called a \"reduction\", and the aim\nof parsing is to completely reduce the input. There are several different ways you can\nperform a reduction, separated by vertical bars: so, \"term\" followed by \"=\" followed by\n\"term\" makes a \"term\", and \"term\" followed by \"+\" followed by \"term\" can also make a \"term\".\n\nSo, if you see two terms with an \"=\" or \"+\", between them, you can turn them into a single\nexpression. When you do this, you execute the code in the block on the next line: if you see\n\"=\", you'll do the code in line 2. If you see \"+\", you'll do the code in line 4. It's this\ncode which contributes to the op tree.\n\n|   term ADDOP term\n{ $$ = newBINOP($2, 0, scalar($1), scalar($3)); }\n\nWhat this does is creates a new binary op, and feeds it a number of variables. The variables\nrefer to the tokens: $1 is the first token in the input, $2 the second, and so on - think\nregular expression backreferences. $$ is the op returned from this reduction. So, we call\n\"newBINOP\" to create a new binary operator. The first parameter to \"newBINOP\", a function in\nop.c, is the op type. It's an addition operator, so we want the type to be \"ADDOP\". We could\nspecify this directly, but it's right there as the second token in the input, so we use $2.\nThe second parameter is the op's flags: 0 means \"nothing special\". Then the things to add:\nthe left and right hand side of our expression, in scalar context.\n\nThe functions that create ops, which have names like \"newUNOP\" and \"newBINOP\", call a \"check\"\nfunction associated with each op type, before returning the op. The check functions can\nmangle the op as they see fit, and even replace it with an entirely new one. These functions\nare defined in op.c, and have a \"Perlck\" prefix. You can find out which check function is\nused for a particular op type by looking in regen/opcodes.  Take \"OPADD\", for example.\n(\"OPADD\" is the token value from the \"Aop(OPADD)\" in toke.c which the parser passes to\n\"newBINOP\" as its first argument.) Here is the relevant line:\n\nadd             addition (+)            cknull         IfsT2   S S\n\nThe check function in this case is \"Perlcknull\", which does nothing.  Let's look at a more\ninteresting case:\n\nreadline        <HANDLE>                ckreadline     t%      F?\n\nAnd here is the function from op.c:\n\n1 OP *\n2 Perlckreadline(pTHX OP *o)\n3 {\n4     PERLARGSASSERTCKREADLINE;\n5\n6     if (o->opflags & OPfKIDS) {\n7          OP *kid = cLISTOPo->opfirst;\n8          if (kid->optype == OPRV2GV)\n9              kid->opprivate |= OPpALLOWFAKE;\n10     }\n11     else {\n12         OP * const newop\n13             = newUNOP(OPREADLINE, 0, newGVOP(OPGV, 0,\n14                                               PLargvgv));\n15         opfree(o);\n16         return newop;\n17     }\n18     return o;\n19 }\n\nOne particularly interesting aspect is that if the op has no kids (i.e., \"readline()\" or\n\"<>\") the op is freed and replaced with an entirely new one that references *ARGV (lines\n12-16).\n",
                "subsections": []
            },
            "STACKS": {
                "content": "When perl executes something like \"addop\", how does it pass on its results to the next op?\nThe answer is, through the use of stacks. Perl has a number of stacks to store things it's\ncurrently working on, and we'll look at the three most important ones here.\n",
                "subsections": [
                    {
                        "name": "Argument stack",
                        "content": "Arguments are passed to PP code and returned from PP code using the argument stack, \"ST\". The\ntypical way to handle arguments is to pop them off the stack, deal with them how you wish,\nand then push the result back onto the stack. This is how, for instance, the cosine operator\nworks:\n\nNV value;\nvalue = POPn;\nvalue = Perlcos(value);\nXPUSHn(value);\n\nWe'll see a more tricky example of this when we consider Perl's macros below. \"POPn\" gives\nyou the NV (floating point value) of the top SV on the stack: the $x in \"cos($x)\". Then we\ncompute the cosine, and push the result back as an NV. The \"X\" in \"XPUSHn\" means that the\nstack should be extended if necessary - it can't be necessary here, because we know there's\nroom for one more item on the stack, since we've just removed one! The \"XPUSH*\" macros at\nleast guarantee safety.\n\nAlternatively, you can fiddle with the stack directly: \"SP\" gives you the first element in\nyour portion of the stack, and \"TOP*\" gives you the top SV/IV/NV/etc. on the stack. So, for\ninstance, to do unary negation of an integer:\n\nSETi(-TOPi);\n\nJust set the integer value of the top stack entry to its negation.\n\nArgument stack manipulation in the core is exactly the same as it is in XSUBs - see\nperlxstut, perlxs and perlguts for a longer description of the macros used in stack\nmanipulation.\n"
                    },
                    {
                        "name": "Mark stack",
                        "content": "I say \"your portion of the stack\" above because PP code doesn't necessarily get the whole\nstack to itself: if your function calls another function, you'll only want to expose the\narguments aimed for the called function, and not (necessarily) let it get at your own data.\nThe way we do this is to have a \"virtual\" bottom-of-stack, exposed to each function. The mark\nstack keeps bookmarks to locations in the argument stack usable by each function. For\ninstance, when dealing with a tied variable, (internally, something with \"P\" magic) Perl has\nto call methods for accesses to the tied variables. However, we need to separate the\narguments exposed to the method to the argument exposed to the original function - the store\nor fetch or whatever it may be.  Here's roughly how the tied \"push\" is implemented; see\n\"avpush\" in av.c:\n\n1  PUSHMARK(SP);\n2  EXTEND(SP,2);\n3  PUSHs(SvTIEDobj((SV*)av, mg));\n4  PUSHs(val);\n5  PUTBACK;\n6  ENTER;\n7  callmethod(\"PUSH\", GSCALAR|GDISCARD);\n8  LEAVE;\n\nLet's examine the whole implementation, for practice:\n\n1  PUSHMARK(SP);\n\nPush the current state of the stack pointer onto the mark stack. This is so that when we've\nfinished adding items to the argument stack, Perl knows how many things we've added recently.\n\n2  EXTEND(SP,2);\n3  PUSHs(SvTIEDobj((SV*)av, mg));\n4  PUSHs(val);\n\nWe're going to add two more items onto the argument stack: when you have a tied array, the\n\"PUSH\" subroutine receives the object and the value to be pushed, and that's exactly what we\nhave here - the tied object, retrieved with \"SvTIEDobj\", and the value, the SV \"val\".\n\n5  PUTBACK;\n\nNext we tell Perl to update the global stack pointer from our internal variable: \"dSP\" only\ngave us a local copy, not a reference to the global.\n\n6  ENTER;\n7  callmethod(\"PUSH\", GSCALAR|GDISCARD);\n8  LEAVE;\n\n\"ENTER\" and \"LEAVE\" localise a block of code - they make sure that all variables are tidied\nup, everything that has been localised gets its previous value returned, and so on. Think of\nthem as the \"{\" and \"}\" of a Perl block.\n\nTo actually do the magic method call, we have to call a subroutine in Perl space:\n\"callmethod\" takes care of that, and it's described in perlcall. We call the \"PUSH\" method\nin scalar context, and we're going to discard its return value. The callmethod() function\nremoves the top element of the mark stack, so there is nothing for the caller to clean up.\n"
                    },
                    {
                        "name": "Save stack",
                        "content": "C doesn't have a concept of local scope, so perl provides one. We've seen that \"ENTER\" and\n\"LEAVE\" are used as scoping braces; the save stack implements the C equivalent of, for\nexample:\n\n{\nlocal $foo = 42;\n...\n}\n\nSee \"Localizing changes\" in perlguts for how to use the save stack.\n"
                    }
                ]
            },
            "MILLIONS OF MACROS": {
                "content": "One thing you'll notice about the Perl source is that it's full of macros. Some have called\nthe pervasive use of macros the hardest thing to understand, others find it adds to clarity.\nLet's take an example, a stripped-down version the code which implements the addition\noperator:\n\n1  PP(ppadd)\n2  {\n3      dSP; dATARGET;\n4      tryAMAGICbinMG(addamg, AMGfassign|AMGfnumeric);\n5      {\n6        dPOPTOPnnrlul;\n7        SETn( left + right );\n8        RETURN;\n9      }\n10  }\n\nEvery line here (apart from the braces, of course) contains a macro.  The first line sets up\nthe function declaration as Perl expects for PP code; line 3 sets up variable declarations\nfor the argument stack and the target, the return value of the operation. Line 4 tries to see\nif the addition operation is overloaded; if so, the appropriate subroutine is called.\n\nLine 6 is another variable declaration - all variable declarations start with \"d\" - which\npops from the top of the argument stack two NVs (hence \"nn\") and puts them into the variables\n\"right\" and \"left\", hence the \"rl\". These are the two operands to the addition operator.\nNext, we call \"SETn\" to set the NV of the return value to the result of adding the two\nvalues. This done, we return - the \"RETURN\" macro makes sure that our return value is\nproperly handled, and we pass the next operator to run back to the main run loop.\n\nMost of these macros are explained in perlapi, and some of the more important ones are\nexplained in perlxs as well. Pay special attention to \"Background and PERLIMPLICITCONTEXT\"\nin perlguts for information on the \"[pad]THX?\" macros.\n",
                "subsections": []
            },
            "FURTHER READING": {
                "content": "For more information on the Perl internals, please see the documents listed at \"Internals and\nC Language Interface\" in perl.\n\n\n\nperl v5.34.0                                 2026-06-23                                PERLINTERP(1)",
                "subsections": []
            }
        }
    }
}