P-code Machine - Example Machine

Example Machine

Niklaus Wirth specified a simple p-code machine in the 1976 book Algorithms + Data Structures = Programs. The machine had 3 registers - a program counter p, a base register b, and a top-of-stack register t. There were 8 instructions, with one (opr) having multiple forms.

This is the code for the machine, written in Pascal:

const levmax=3; amax=2047; type fct=(lit,opr,lod,sto,cal,int,jmp,jpc); instruction=packed record f:fct; l:0..levmax; a:0..amax; end; procedure interpret; const stacksize = 500; var p, b, t: integer; {program-, base-, topstack-registers} i: instruction; {instruction register} s: array of integer; {datastore} function base(l: integer): integer; var b1: integer; begin b1 := b; {find base l levels down} while l > 0 do begin b1 := s; l := l - 1 end; base := b1 end {base}; begin writeln(' start pl/0'); t := 0; b := 1; p := 0; s := 0; s := 0; s := 0; repeat i := code; p := p + 1; with i do case f of lit: begin t := t + 1; s := a end; opr: case a of {operator} 0: begin {return} t := b - 1; p := s; b := s; end; 1: s := -s; 2: begin t := t - 1; s := s + s end; 3: begin t := t - 1; s := s - s end; 4: begin t := t - 1; s := s * s end; 5: begin t := t - 1; s := s div s end; 6: s := ord(odd(s)); 8: begin t := t - 1; s := ord(s = s) end; 9: begin t := t - 1; s := ord(s <> s) end; 10: begin t := t - 1; s := ord(s < s) end; 11: begin t := t - 1; s := ord(s >= s) end; 12: begin t := t - 1; s := ord(s > s) end; 13: begin t := t - 1; s := ord(s <= s) end; end; lod: begin t := t + 1; s := s end; sto: begin s := s; writeln(s); t := t - 1 end; cal: begin {generate new block mark} s := base(l); s := b; s := p; b := t + 1; p := a end; int: t := t + a; jmp: p := a; jpc: begin if s = 0 then p := a; t := t - 1 end end {with, case} until p = 0; writeln(' end pl/0'); end {interpret};

This machine was used to run Wirth's PL/0, which was a Pascal subset compiler used to teach compiler development.

Read more about this topic:  P-code Machine

Famous quotes containing the word machine:

    One machine can do the work of fifty ordinary men. No machine can do the work of one extraordinary man.
    Elbert Hubbard (1856–1915)

    The chrysanthemums’ astringent fragrance comes
    Each year to disguise the clanking mechanism
    Of machine within machine within machine.
    Wallace Stevens (1879–1955)