image thumbnail
from Growing a Compiler by Bill McKeeman
Bootstrap compilers starting from a tiny compiler-compiler.

testGem5()
% FILE:     testGem5.m 
% PURPOSE:  test gem (the grammar executing machine)
% METHOD:   hardware access
% REQUIRES: gem.m iog4.c iog4.h runX86.c nonox.c nox.c
% EXAMPLE:    
%   testGem5() % for all tests

% COPYRIGHT: 2009 W. M. McKeeman.  See license.txt.

function testGem5()  
  tests  = 0;                                     % none yet
  passed = 0;                                     % none yet
  
  G = gem5();                                     % instantiate GEM object

  positiveTest(strcmp('',     G.run('', 'g=;')));
  positiveTest(strcmp('',     G.run('abc', 'g = ''abc'' ;')));
  positiveTest(strcmp('abc',  G.run('', 'g = "abc";')));
  positiveTest(3  == G.exe(G.run('a=3;', G.calc, 'D')));
  positiveTest(9  == G.exe(G.run('a=9;', G.calc, 'D'))); 
  positiveTest( 3 == G.exe(G.run('b=3;a=0;a+=b;', G.calc, 'D'))); 
  positiveTest(-3 == G.exe(G.run('b=3;a=0;a-=b;', G.calc, 'D'))); % neg
  positiveTest(12 == G.exe(G.run('b=3;a=4;a*=b;', G.calc, 'D'))); 
  positiveTest( 7 == G.exe(G.run('b=5;a=2;a|=b;', G.calc, 'D'))); 
  make31=G.run(G.scan('b=9; a=3; c=4; a*=b; a+=c;'), G.calc, 'D');
  positiveTest(31 == G.exe(make31));
  
  
  negativeTest('',    'g=g;', '');     % left recursion
  negativeTest('',    'g=rg;r="a";');  % infinite output
  negativeTest('a',   'g=''b'';');     % bad input
    
  fprintf('gem5: passed %d tests out of %d\n', passed, tests);
  
  %return;
  
  function positiveTest(bexpr)
    tests = tests + 1;
    if bexpr; passed = passed + 1; end
    %tests, passed
  end

  function negativeTest(i, g, f)  
    try
      res = G.run(i, g, f);
      positiveTest(false);    % should not get here
    catch err
      positiveTest(true);     % should get here
      %fprintf('gem test %d, %s', tests, err.message);
    end
  end

end

Contact us