7267
|
1 Inspired by a September 14, 2006 Salon article "Why Johnny Can't Code" by
|
|
2 David Brin (http://www.salon.com/tech/feature/2006/09/14/basic/index.html),
|
|
3 I thought that a fully working BASIC interpreter might be an interesting,
|
|
4 if not questionable, PLY example. Uh, okay, so maybe it's just a bad idea,
|
|
5 but in any case, here it is.
|
|
6
|
|
7 In this example, you'll find a rough implementation of 1964 Dartmouth BASIC
|
|
8 as described in the manual at:
|
|
9
|
|
10 http://www.bitsavers.org/pdf/dartmouth/BASIC_Oct64.pdf
|
|
11
|
|
12 See also:
|
|
13
|
|
14 http://en.wikipedia.org/wiki/Dartmouth_BASIC
|
|
15
|
|
16 This dialect is downright primitive---there are no string variables
|
|
17 and no facilities for interactive input. Moreover, subroutines and functions
|
|
18 are brain-dead even more than they usually are for BASIC. Of course,
|
|
19 the GOTO statement is provided.
|
|
20
|
|
21 Nevertheless, there are a few interesting aspects of this example:
|
|
22
|
|
23 - It illustrates a fully working interpreter including lexing, parsing,
|
|
24 and interpretation of instructions.
|
|
25
|
|
26 - The parser shows how to catch and report various kinds of parsing
|
|
27 errors in a more graceful way.
|
|
28
|
|
29 - The example both parses files (supplied on command line) and
|
|
30 interactive input entered line by line.
|
|
31
|
|
32 - It shows how you might represent parsed information. In this case,
|
|
33 each BASIC statement is encoded into a Python tuple containing the
|
|
34 statement type and parameters. These tuples are then stored in
|
|
35 a dictionary indexed by program line numbers.
|
|
36
|
|
37 - Even though it's just BASIC, the parser contains more than 80
|
|
38 rules and 150 parsing states. Thus, it's a little more meaty than
|
|
39 the calculator example.
|
|
40
|
|
41 To use the example, run it as follows:
|
|
42
|
|
43 % python basic.py hello.bas
|
|
44 HELLO WORLD
|
|
45 %
|
|
46
|
|
47 or use it interactively:
|
|
48
|
|
49 % python basic.py
|
|
50 [BASIC] 10 PRINT "HELLO WORLD"
|
|
51 [BASIC] 20 END
|
|
52 [BASIC] RUN
|
|
53 HELLO WORLD
|
|
54 [BASIC]
|
|
55
|
|
56 The following files are defined:
|
|
57
|
|
58 basic.py - High level script that controls everything
|
|
59 basiclex.py - BASIC tokenizer
|
|
60 basparse.py - BASIC parser
|
|
61 basinterp.py - BASIC interpreter that runs parsed programs.
|
|
62
|
|
63 In addition, a number of sample BASIC programs (.bas suffix) are
|
|
64 provided. These were taken out of the Dartmouth manual.
|
|
65
|
|
66 Disclaimer: I haven't spent a ton of time testing this and it's likely that
|
|
67 I've skimped here and there on a few finer details (e.g., strictly enforcing
|
|
68 variable naming rules). However, the interpreter seems to be able to run
|
|
69 the examples in the BASIC manual.
|
|
70
|
|
71 Have fun!
|
|
72
|
|
73 -Dave
|
|
74
|
|
75
|
|
76
|
|
77
|
|
78
|
|
79
|