esolang
Learn · Ideas392 languages show it

Stack machines

One pile of numbers. Push on top, pop off the top. Half of all esolangs keep their memory this way.

●○○ easy · where to see it

The idea

A stack is a pile; you can only add to the top (push) and take from the top (pop). A stack machine keeps its working data on a stack, so instructions don't need operands. + doesn't say what to add; it adds the top two items.

Read the story

The idea is old and in wide use. The Burroughs B5000 (1961) was a hardware stack machine. The Java virtual machine, WebAssembly and PostScript are stack machines today. Reverse Polish notation, the order 2 3 +, comes from Jan Łukasiewicz's Polish notation turned around.

Esolang authors love stacks because they make an interpreter almost trivial, and because a program becomes a flat row of symbols with no parentheses.

How it works

Evaluate 2 3 + 4 *, that is (2 + 3) × 4.

Evaluate 2 3 + 4 *, that is (2 + 3) × 4.

token   stack after
2       [2]
3       [2, 3]
+       [5]          pop 3, pop 2, push 2 + 3
4       [5, 4]
*       [20]         pop 4, pop 5, push 5 × 4

Every instruction does the same three moves. It pops its inputs, computes, and pushes the result. So the interpreter is a loop and a table.

A few standard stack words appear everywhere under different names.

WordBefore → afterTypical spelling
dupa → a a: in Befunge, Underload and ><>
dropa →$ in Befunge
swapa b → b a\ in Befunge
overa b → a b aover in Forth

Variations

  • Two stacks. Forth keeps a separate return stack for calls; Brain-Flak gives you two data stacks and you toggle between them.
  • A stack of stacks. ><> can open a new stack on top of the old one.
  • One stack per type. Push has an integer stack, a boolean stack, a code stack and more. An instruction takes its inputs from the stacks of the right type.

What happens on an empty stack?

This is a design choice, and it matters for robustness.

  • crash (many real VMs);
  • pop a 0 (Befunge does this);
  • do nothing; Push treats an instruction without enough inputs as a no-op.

Five machines

The machines, what they remember, and where to see them
MachineMemoryControlExamples
Tapea row of cells and a pointerloops that test the current cellbrainfuck, Ook!, Boolfuck
Stackvalues piled up; only the top is easy to reachjumps, loops or quotations that runUnderload, FALSE, the kernel
Queuevalues in a line, added at the back and taken from the frontloops on the front valueSceql, Qdeql, Emmental
Rewritingnothing but the text itselfreplace a pattern until none matches///, Thue, Markov algorithms
2Dusually a stack; the program is a grida cursor that arrows and mirrors turnBefunge-93, ><>, Labyrinth

One task on four machines

Each program below reverses its input.

Each program below reverses its input.

Tape: walk right, then walk back

Each byte goes into its own cell. The pointer then walks back and prints. The tape remembers the order by position.

Expected output

desserts

Output


Stack and lists: fold

The kernel puts each element in front of an accumulator list. See map, filter and fold.

Expected output

desserts

Output


2D stack: pushing reverses by itself

Row 1 reads characters onto the stack until the end of input. A stack gives back the last thing first, so printing it all is already the reverse. $ drops the −1 that marked the end.

Expected output

desserts

Output


Rewriting: no input at all

/// cannot read input, so the text to change is in the program. The rule swaps ab to ba until none is left, which moves every b to the front.

Expected output

bbaa

Output


Why it matters

A tape makes "where" cheap and "copy" expensive (see moving and copying).

A tape makes "where" cheap and "copy" expensive (see moving and copying). A stack makes copying cheap and far-away values expensive. A queue keeps order. Rewriting has no variables at all. In 2D the shape of the text is the control flow.

The kernel was built to host all of them. It has a stack, memory with a pointer, quotations, a 2D reader and a rewrite reader. See how a language can evolve.

Try this

  1. Write (1 + 2) × (3 + 4) in stack order.
  2. Using only dup, swap, drop and *, compute x³ from [x].
  3. Hard: write a stack program that, given [a b], leaves [a b a b], using only dup, swap and over. How few words do you need?

Seen in

  • Forth and FALSE. The classic stack languages.
  • Befunge, ><> and Piet. A 2D instruction pointer driving a stack.
  • Whitespace. A stack machine with a heap, written in spaces, tabs and newlines.
  • Brain-Flak. Two stacks and brackets only.
  • GolfScript. A stack makes golfed programs short.
  • Stack Cats. Stacks where every operation can be undone.
  • Push. Typed stacks, designed for genetic programming.

Further

Where to see it

ForthFALSEBefungeFish (><>)PietWhitespaceBrain-FlakGolfScriptStack CatsPush0(nop^)0x29A'129''14'1><> (1Fish)2ds2sable3x4ME9f87m4atttaaaou;A Language Programmed While Listening to Godspeed You! Black EmperorA Slow LanguageabobaAcetoActuallyAFTLAGGAheuiAlice & BobAliceALLSCIIAlphabet StewAlphaStackAluminAmong UsAnnoyingScriptAnyfixArgh!ASCIIORbAt some landaxoBackhandBackwordsBasic StackBeatnikBedtimeBeeblesBeeswaxBefalseBefunge-96 and Funge-97 (MTFI)Befunge-98BespokeBetaloadBFIBIITIBinerdyBitBounceBolagaBoxesBrainf*ckBraingolfBurBurlesqueByTCalcutapeCalScriptCanvasCarol & DaveCarriageCerberusCeresCheckCheesecakeChefChickenChronosCipherCJamClem',,,'CommlangComplackComunConvexCOPY WITH @CoreaCOSOL26CrayonCscallsCSLCubixCyDashesdcDecimal'Del|m|t'DipdiracDirectionDirtyDJ Qarkegs - Above The SkyDODODominoScriptDotSFDStackDUPeacal'!@#$%^&*()_+'ElectraElementElogEmmentalEmojiEniuqETAEvaleWagonExcellerated Short-Term Memory LossEXDotSFExecodeFactoryFAGIFalsishFILOFilthFish CodeFissionFlurryFlux (Esolangist)FobFoldyFooForgetForkedForWhileFrackitFull StackFynylGaiaGaot++GASOILGechoGlass"Gol><>"GolfScratchGoofy Ahh EsolangGraphemeGrawlixGrocery ListGrokGS2HanabiHanoi LoveHARSHHaystackHeckHeliosHollowHexadecimal Stacking Pseudo-Assembly LanguageHZCode?index.phpInputerInternational Phonetic Esoteric LanguageInterstackJackassJollyScriptJoyKarmaKavodKegKimLKleinLabyrinthLocksmithLogStackLossiaLostLRIP<stack>LyMacmacMadbrainMaentwrogMagiStackMalfungeMascarponeMathGolfMATLMAWPMazerunnerMemory GAPMETAMicroscriptMilky WayMineFriffMini-FlakMinkolangMinreg the CatMNNBFSLMoaiscriptModulousMogusMonkyMoreThanZeroMotorwayMouseMuMutating Stack MachineNASALNeimNikudNioNixNoCommentNoErrorNoetherNondescriptNoobinaryNOPQRSTNotQuiteThereNqublNS!NTFJNULL-NONE NOTHINGNumbersNumSymOasisObCodeOhmOhm v2OISC:2bisOLNMLNOmgroflOML1+ONE WAYOpenBSD toasterOr+305AB1EOsisOuroborosPain-FlakPancake StackPDA-erPDAsephonePhDPhoneboardPhooeyPipepithPlanesPointerBPointstackPops Are OverratedPreludePurlPushDupAddSubPushyPxemPykePylonsPytqoRabbitsfootRailRainRalRASELRecallRecurRecurseReflectorefractRengReticularRevaver2piRopyRotorRozpachRProgN 2RProgNRunespellsRunic EnchantmentsS.B.M.F.BSad-Flaksbsdac2SecretarySenpaiSerenitySeriouslyShakespeareShapeScriptSharpShortOShoveSimplackSimplefungeSimpleScriptSkoundSlimSmilefuckSMITHbsmolSmurfSockZSommeStæckStack-basedStack-gptStackBitStackCellStackfuckStackintStackoweyStackPointStacks of QueuesStackStacksStaPLeStaq"*><> (Starfish)"StarrystrStrawStruffoliStupidStackLanguageSTXTRMSuper SNUSPSuper Stack!SussyLangSwapSwordfishSymsTakeoverTaxiTetrastackTextileTgthaMThe Temporary StackThis esolang is not a push-down automataTierTirTonoco(top, height)TPPLUnefunge-98 and Trefunge-98TriTriangularTriple ThreatTruTseptTuri ip ip ip=,-&~^!彳亍退!退!退!UnderloadUnleashURSLVar'aqVarsigVarStackVerboseVerticalvflVirageVitsyv^vWARPWhopperWidthWiseWiwaWumpusxEecXihcuteXRFYAASELYATDEL--yayyupZalgoZedBrainfuckOok!BoolfuckSceqlQdeql///ThueMarkov algorithm