tests/harness.py
author David Anderson <dvander@alliedmods.net>
Sat Nov 17 18:41:01 2012 -0800 (2012-11-17)
changeset 195 c1ba166f3fc4
child 205 5a91709da263
permissions -rw-r--r--
Massive SemA/BC refactoring to support better type systems. Read on for more.

The previous compiler had a simple pipeline, best outlined as:
(1) Parsing and name binding -> AST
(2) Storage allocation -> AST
(3) Semantic Analysis (SemA) -> AST
(4) Bytecode Compilation (BC) -> Code

This pipeline, unfortunately, had two problems. First, name binding cannot be performed in one pass if we wish to have multi-file support in the form of modules. Name binding must be two-pass.

Second, because SemA was only capable of annotating AST nodes with a single type, most coercion work had to be duplicated in the BC phase, as coercion was not explicit in the SemA output. This made introducing new type rules extremely difficult, and all but precluded concepts like operator overloading (or overloading at all).

This patch rewrites most of Keima's backend. Of interest are the following changes:
(1) CompileContext has been refactored around future multi-file support.
(2) Parsing no longer performs any name binding.
(3) The grammar for type-and-name has been changed from:
(Label | Identifier)? Identifier
to:
Type? Identifier
where:
Type ::= OldType | NewType
OldType ::= Label
NewType ::= Identifier (. NewType)*


Although we do not implement the full production for Type yet, this
distinction is important. A type identifier is now affixed to the AST
as an Expression (right now, always a NameProxy), so it can fully
participate in name binding.

(4) Immediately after parsing, the AST goes through a NamePopulation phase.
This phase creates Scope objects for every scope which declares a name,
and if those names are declaring types or functions, a Symbol is created
and entered into the scope. Symbols entirely replace the old BoundName
classes.

(5) After NamePopulation comes NameBinding. This phase performs three steps:
(a) Links Scope objects together, to form a tree.
(b) Binds any free name to an existing name in the scope chain.
(c) Creates and registers any Symbols for names which have not yet been
added to the scope (for example, local variables).

In accordance, all "allocation" and "binding" concepts have been removed
from Scopes, which are now lightweight container classes.

(6) SemA now generates bytecode for each statement in the AST. Expression
compilation is performed via a separate mechanism called HIR (High-level
Intermediate Representation). To analyze an expression, SemA will walk
the AST, and produce a HIR object for each node. HIR is typed, and SemA
may insert coercion nodes, or even expand an AST node into multiple HIR
nodes. The result of evaluating an expression in SemA is therefore the
the root of a HIR tree, which SemA then sends to the HIRTranslator, which
performs bytecode generation.

As before, SemA still performs full semantic analysis. However, not it
also produces each function's bytecode.

This split allows us to decompose potentially complex semantics into
a more fine-grained, AST-like structure, which can have very simple
code-generation logic. For example, (1.0 + 5) might look like:

HAdd(HFloat(1.0), HConvert(HInteger(5), <Float>))

As part of this decomposition, many opcodes have been removed. Rather than
using typed jumps, we now expand jumps into longer tests. For example:
jge.f <label>
becomes:
ge.f
cvt.f2b
jt <label>

This simplifies the pipeline, and JITs should be able to melt the added
work away.

HIR is not used at a statement level, and HIR does not have any concept
of control-flow.

(7) The old BytecodeCompiler has been removed, as its work is now split
between SemA and HIRTranslator.


In addition, some minor refactorings have taken place:

(1) Opcodes.tbl no longer hardcodes numbers (aaah).
(2) Type has been split into smaller, typed structs.
(3) BytecodeEmitter no longer relies on Pools or RootScopes.
(4) SemA is now responsible for variable/storage allocation.
(5) Native table are now global, rather than per-module. As such, native
declarations now result in a Native object (which still requires a
CALLNATIVE opcode), which is an index into the global table. Natives
must be bound globally. This is in preparation for module support.
(6) Publics are no longer tracked, but rather registered via a global
callback upon module load. This callback can be set by embedders. This
is in preparation for multi-file support.
(7) The BytecodeEmitter now performs Symbol allocations itself, and it
also generates Code objects itself, which removes a good deal of
complexity.

Finally, a test harness has been added. This harness is a python script which finds *.test files, recursively, in the tests folder. For each file it runs the corresponding .sp. The contents of the .test file must match stdout+stderr.
     1 # vim: set ts=2 sw=4 tw=99 ft=python et:
     2 import os
     3 import re
     4 import sys
     5 import time
     6 import os.path
     7 from test import Test
     8 from subprocess import *
     9 from threading import Thread
    10 from display import Interactive
    11 
    12 def FindTests(tests, root, folder):
    13   folders = []
    14   for name in os.listdir(os.path.join(root, folder)):
    15     path = os.path.join(root, folder, name)
    16     if os.path.isdir(path):
    17       folders.append(name)
    18       continue
    19 
    20     path = os.path.join(root, folder)
    21     out = re.match("^([^\.]+)\.out$", name)
    22     err = re.match("^([^\.]+)\.err$", name)
    23     if out:
    24         name = out.group(1)
    25         tests.append(Test(path, name, 'out'))
    26     elif err:
    27         name = err.group(1)
    28         tests.append(Test(path, name, 'err'))
    29 
    30   for name in folders:
    31     path = os.path.join(folder, name)
    32     FindTests(tests, root, path)
    33 
    34 def IsTestRoot(path, name):
    35   return os.path.isdir(path)
    36 
    37 def RunTest_(argv, options, L):
    38   if sys.platform != 'win32':
    39     options['close_fds'] = True
    40 
    41   p = Popen(argv, stdin=PIPE, stdout=PIPE, stderr=PIPE, **options)
    42 
    43   L[0] = p
    44   out, err = p.communicate()
    45   L[1] = (out, err, p.returncode)
    46 
    47 def RunTest(test, options, shell):
    48   argv = [shell, test.cmd()]
    49 
    50   L = [None, None]
    51   timeout = False
    52   th = Thread(target = RunTest_, args = (argv, options, L))
    53   th.start()
    54   th.join(60.0)
    55   while th.isAlive():
    56     if L[0] is not None:
    57       try:
    58         L[0].kill()
    59         time.sleep(.1)
    60         timeout = True
    61       except OSError:
    62         # Expecting a "No such process" error
    63         pass
    64 
    65   th.join()
    66   (out, err, code) = L[1]
    67 
    68   return test.check(out, err, code, timeout)
    69 
    70 def RunTests(display, tests, shell):
    71   display.begin(tests)
    72   ok = True
    73   try:
    74     for test in tests:
    75       options = { }
    76       result = RunTest(test, options, shell)
    77 
    78       ok = ok and result.ok
    79       
    80       display.result(test, result)
    81   except KeyboardInterrupt:
    82     display.cancel()
    83     ok = False
    84 
    85   return ok
    86 
    87   
    88 def main(argv):
    89   root = os.path.dirname(os.path.abspath(__file__))
    90 
    91   from optparse import OptionParser
    92   op = OptionParser(usage='%prog [options] <shell>')
    93   (options, args) = op.parse_args(argv)
    94 
    95   if len(args) != 1:
    96     op.error('missing <shell> argument')
    97 
    98   shell = os.path.normpath(args[0])
    99 
   100   tests = []
   101   for name in os.listdir(root):
   102     path = os.path.join(root, name)
   103     if IsTestRoot(path, name):
   104       FindTests(tests, root, name)
   105 
   106   if len(tests) == 0:
   107     op.error('no test cases found')
   108 
   109   display = Interactive()
   110   ok = RunTests(display, tests, shell)
   111   if ok:
   112     sys.exit(0)
   113   else:
   114     sys.exit(1)
   115 
   116 if __name__ == '__main__':
   117   main(sys.argv[1:])
   118