├── README.md
├── LICENSE
└── foco65
/README.md:
--------------------------------------------------------------------------------
1 | foco65
2 | ======
3 |
4 | Forth cross-compiler targeting 6502 processors. Outputs [xasm](https://github.com/pfusik/xasm)
5 | compatible assembly source code containing Forth runtime and compiled user
6 | program.
7 |
8 | Runtime
9 | -------
10 |
11 | Generated Forth runtime is 16-bit indirect-threaded.
12 |
13 | Parameter stack is full-descending and addressed by `X` register. Address and
14 | size of the parameter stack are by default $600 and 256 respectively and are
15 | user-configurable.
16 |
17 | Hardware stack is used as return stack.
18 |
19 | The runtime uses 12 bytes on zero page: 2-byte instruction pointer `ip` and
20 | 5 2-byte work registers: `w`, `z`, `cntr`, `tmp`, `tmp2` which may be used
21 | in user-defined words (note than on every word entry these registers' contents
22 | are undefined).
23 |
24 | On entry runtime initializes instruction pointer and enters user-defined word
25 | `main` which is supposed to never exit (i.e. contain an infinite loop).
26 |
27 | Generated Source Code
28 | ---------------------
29 |
30 | Generated assembly source code for words/data/code blocks is logically grouped
31 | into _sections_. Default order of sections is: `init`, `boot`, `data`, `text`.
32 |
33 | Sections:
34 | * `init` - top of the output, typically contains user-provided assembly code
35 | block with `org` directive
36 | * `boot` - forth runtime
37 | * `data` - user data
38 | * `text` - core words and user program
39 |
40 | User-defined data is output into the most recently declared data section (with
41 | `[data-section]` word), everything else is output into the most recently
42 | declared text section (with `[text-section]` word).
43 |
44 | Syntax
45 | ------
46 |
47 | ### Identifiers
48 |
49 | Identifiers are case sensitive.
50 |
51 | Constant and data identifiers consist of alphanumeric characters, '\_'s, '-'s
52 | and '?'s and must start with a letter, '\_', '-' or '?'. In generated assembly
53 | labels every '-' is replaced by '\_' and every '?' is replaced by '\_is\_'.
54 |
55 | Word identifiers consist of printable ASCII characters. Word identifiers
56 | consisting only of alphanumeric characters, '\_'s, '-'s, '?'s and starting with
57 | a letter, '\_', '-' or a '?' are translated automatically to valid assembly
58 | labels. Other word identifiers require user-defined label specification (see
59 | below).
60 |
61 | Section identifiers consist of printable ASCII characters.
62 |
63 | ### Comments
64 |
65 | Syntax:
66 |
67 | \ this is a one-line comment
68 | ( this is a multi-line
69 | comment)
70 |
71 |
72 | ### Numbers
73 |
74 | Syntax:
75 |
76 | 123 \ decimal number
77 | $BA98 \ hexadecimal number
78 |
79 |
80 | ### Word definitions
81 |
82 | Syntax:
83 |
84 | `:` _name_ *[* `[label]` _asm-label_ *]* _words_ `;`
85 |
86 | or:
87 |
88 | `:` _name_
89 | *[* `[label]` _asm-label_ *]*
90 | `[code]`
91 |
92 | ; inline-assembly
93 |
94 | `[end-code]` `;`
95 |
96 | Examples:
97 |
98 | : foo begin end-flag until ;
99 |
100 |
101 | : bar
102 | [code]
103 | lda #1
104 | sta $D5E8
105 | jmp next
106 | [end-code] ;
107 |
108 |
109 | : +7 ( n1 -- n2 )
110 | [label] plus_7
111 | 7 + ;
112 |
113 |
114 | ### Data declarations
115 |
116 | One-cell variable:
117 |
118 | `variable` _name_
119 |
120 | Two-cell variable:
121 |
122 | `2variable` _name_
123 |
124 | Assembly label at current program counter:
125 |
126 | `create` _name_
127 |
128 | Compile a one-cell value:
129 |
130 | _value_ `,`
131 |
132 | Compile a one-byte value:
133 |
134 | _value_ `c,`
135 |
136 | Allocate a byte-array:
137 |
138 | _length_ `allot`
139 |
140 | Allocate Atari XL/XE Antic counted string:
141 |
142 | `,'` _text_`'`
143 |
144 | Allocate ASCII counted string:
145 |
146 | `,"` _text_`"`
147 |
148 | Allocate Atari XL/XE Antic string:
149 |
150 | `'` _text_`'`
151 |
152 | Allocate ASCII string:
153 |
154 | `"` _text_`"`
155 |
156 | ### Constants
157 |
158 | Syntax:
159 |
160 | _value_ `constant` _name_
161 |
162 | Example:
163 |
164 | $230 constant dladr
165 |
166 |
167 | ### Inline assembly blocks
168 |
169 | Syntax:
170 |
171 | `[code]`
172 |
173 | _; assembly code_
174 |
175 | `[end-code]`
176 |
177 | ### Compiler directives
178 |
179 | Syntax:
180 |
181 | `[text-section]` _name_
182 |
183 | or:
184 |
185 | `[data-section]` _name_
186 |
187 | Words
188 | -----
189 |
190 | `!` `"` `'` `[']` `(` `*` `+` `,"` `,'` `,` `-` `/` `:` `<=` `<` `<>` `<` `=`
191 | `>=` `>` `@` `[` `\` `]` `0=` `1+` `1-` `2!` `2*` `2/` `2@` `2drop` `2dup`
192 | `2over` `2swap` `2variable` `allot` `and` `c!` `c,` `c@` `cell` `cells` `cmove`
193 | `[code]` `constant` `count` `create` `d+` `d-` `d=` `[data-section]` `do`
194 | `drop` `dup` `[end-code]` `execute` `fill` `i` `j` `[label]` `lit` `+loop`
195 | `loop` `lshift` `m*` `nip` `not` `or` `over` `>r` `r>` `recursive` `rot` `-rot`
196 | `rshift` `rsp` `sp` `swap` `[text-section]` `u<` `u>` `unloop` `variable`
197 | `while`
198 |
199 | Usage
200 | -----
201 |
202 | ```sh
203 | foco65 [OPTIONS] INPUT-FILE
204 | ```
205 |
206 | OPTIONS:
207 |
208 | -h display help
209 | -p ADDR,--pstack-bottom=ADDR parameter stack bottom address
210 | -s SECTS,--sections=SECTS specify comma separated list of sections
211 | default: init,boot,data,text
212 | -S INT,--pstack-SIZE=INT parameter stack size
213 |
214 | Example:
215 |
216 | ```sh
217 | $ foco65 foo.forth > foo.asx
218 | ```
219 |
220 | Examples
221 | --------
222 |
223 | Typical Atari XL/XE executable program structure.
224 |
225 |
226 | [text-section] init
227 |
228 | [code]
229 | org $2000
230 | [end-code]
231 |
232 | \ constant definitions
233 | \ data declarations
234 | \ word definitions
235 |
236 | [text-section] text
237 |
238 | : main
239 | \ user program initialization
240 | begin
241 | \ user program main loop
242 | again ;
243 |
244 | [code]
245 | run boot
246 | [end-code]
247 |
248 |
249 | Atari XL/XE example: display character table.
250 |
251 |
252 | [text-section] init
253 |
254 | [code]
255 | org $3000
256 | [end-code]
257 |
258 | [text-section] text
259 |
260 | $230 constant dladr
261 |
262 | variable screen
263 | variable cursor
264 | variable line
265 |
266 | : cursor-next ( -- u )
267 | cursor @ dup 1+ cursor ! ;
268 |
269 | : put-char ( c -- )
270 | cursor-next c! ;
271 |
272 | : set-cursor ( u -- )
273 | screen @ + cursor ! ;
274 |
275 | : main
276 | dladr @ 4 + @ screen !
277 |
278 | 0 line !
279 | 16 0 do
280 | line @ set-cursor
281 | line @ 40 + line !
282 | 16 0 do
283 | i j 4 lshift or put-char
284 | loop
285 | loop
286 |
287 | begin again ;
288 |
289 | [code]
290 | run boot
291 | [end-code]
292 |
293 |
294 | Atari XL/XE example of defining word in assembly:
295 | wait for keypress and push the pressed key's code
296 | on the parameter stack.
297 |
298 |
299 | : get-char ( -- c )
300 | [code]
301 | lda #0
302 | dex
303 | sta pstack,x
304 | stx w
305 | jsr do_gc
306 | ldx w
307 | dex
308 | sta pstack,x
309 | jmp next
310 |
311 | do_gc
312 | lda $E425
313 | pha
314 | lda $E424
315 | pha
316 | rts
317 | [end-code] ;
318 |
319 |
320 | Increase cell at the given address. Shows defining words not
321 | being a valid assembler label.
322 |
323 |
324 | create array 16 cells allot
325 |
326 | \ increase cell at given address
327 | : ++ ( addr -- )
328 | [label] plus_plus
329 | dup @ 1+ swap ! ;
330 |
331 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/foco65:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | # foco65
4 | # Copyright (C) 2014,2018,2025 Piotr Wiszowaty
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see {http://www.gnu.org/licenses/}.
18 |
19 | import argparse
20 | import re
21 | import sys
22 |
23 | #####
24 |
25 | class StackUnderflow(Exception):
26 | def __init__(self, text, filename, line, column):
27 | self.filename = filename
28 | self.text = text
29 | self.line = line
30 | self.column = column
31 |
32 | def __str__(self):
33 | return "stack underflow (%s,%d,%d): %s" % (self.filename, self.line, self.column, self.text)
34 |
35 |
36 | class StackNotEmpty(Exception):
37 | def __init__(self, filename, line, column):
38 | self.filename = filename
39 | self.line = line
40 | self.column = column
41 |
42 | def __str__(self):
43 | return "stack not empty (%s,%d,%d)" % (self.filename, self.line, self.column)
44 |
45 |
46 | class ParseError(Exception):
47 | def __init__(self, message, filename, line, column):
48 | self.message = message
49 | self.line = line
50 | self.column = column
51 | self.filename = filename
52 |
53 | def __str__(self):
54 | return "%s at line %d column %d in file %s" % (self.message, self.line, self.column, self.filename)
55 |
56 |
57 | class UnknownWord(ParseError):
58 | def __init__(self, filename, token):
59 | ParseError.__init__(self, "unknown word '%s'" % token.text, filename, token.line, token.column)
60 |
61 |
62 | class UnexpectedEndOfStream(ParseError):
63 | def __init__(self, filename, line, column):
64 | ParseError.__init__(self, "unexpected end of input", filename, line, column)
65 |
66 | class NoSuchFile(ParseError):
67 | def __init__(self, filename, token):
68 | ParseError.__init__(self, "No such include file '%s'" % token.text, filename, token.line, token.column)
69 |
70 | #####
71 |
72 | class Token:
73 | def __init__(self, text, line, column):
74 | self.text = text
75 | self.line = line
76 | self.column = column
77 |
78 | def __eq__(self, other):
79 | return self.text == other
80 |
81 | def __str__(self):
82 | return "'%s' %d,%d" % (self.text, self.line, self.column)
83 |
84 | def endswith(self, s):
85 | return self.text.endswith(s)
86 |
87 | def replace(self, s_from, s_to):
88 | return self.text.replace(s_from, s_to)
89 |
90 | def canon(self):
91 | return self.text.replace("-", "_").replace("?", "_is_")
92 |
93 | #####
94 |
95 | class Input:
96 | WHITESPACE = " \t\n"
97 | EOL = "\n"
98 |
99 | def __init__(self, text):
100 | self.text = text
101 | self.offset = 0
102 | self.line = 1
103 | self.column = 1
104 |
105 | def __iter__(self):
106 | return self
107 |
108 | def mark_start(self):
109 | self._mark_start = self.offset
110 |
111 | def mark_end(self):
112 | self._mark_end = self.offset
113 |
114 | def marked(self):
115 | return self.text[self._mark_start:self._mark_end]
116 |
117 | def end(self):
118 | return self.offset >= len(self.text)
119 |
120 | def current_char(self):
121 | if self.end(): return None
122 | return self.text[self.offset]
123 |
124 | def next_char(self):
125 | if self.end():
126 | raise UnexpectedEndOfStream(self.current_file_name, self.line, self.column)
127 | c = self.text[self.offset]
128 | self.offset += 1
129 | if c in self.EOL:
130 | self.line += 1
131 | self.column = 1
132 | else:
133 | self.column += 1
134 | return c
135 |
136 | def skip_to_eol(self):
137 | while self.current_char() != "\n":
138 | self.next_char()
139 |
140 | def next(self):
141 | while self.current_char() in self.WHITESPACE:
142 | self.next_char()
143 | if self.end(): return None
144 | if self.end(): raise StopIteration
145 | line, column, start = self.line, self.column, self.offset
146 | while self.current_char() not in self.WHITESPACE:
147 | self.next_char()
148 | return Token(self.text[start:self.offset], line, column)
149 |
150 | #####
151 |
152 | class Code:
153 | def __init__(self, code, section):
154 | self.code = code
155 | self.section = section
156 |
157 | def output(self, section):
158 | if section == self.section:
159 | return self.code[1:] + "\n"
160 | else:
161 | return ""
162 |
163 | #####
164 |
165 | class Word:
166 | def __init__(self, name, section, code="", label=None):
167 | self.name = name
168 | self.section = section
169 | self.thread = ["enter"]
170 | self.names = []
171 | self.code = code
172 | if label:
173 | self.label = label
174 | else:
175 | self.label = name
176 | self.recursive = False
177 | self.used = False
178 |
179 | def output(self, section):
180 | if self.used and self.section == section:
181 | if self.code:
182 | cout = self.code.output(section)
183 | return "%s\n dta a(*+2)\n%s\n" % (self.label, cout)
184 | else:
185 | s = "\n".join(map(lambda l: " dta a(%s)" % l, self.thread))
186 | return "%s\n%s\n\n" % (self.label, s)
187 | else:
188 | return ""
189 |
190 | def __iter__(self):
191 | return iter(self.names)
192 |
193 | def add(self, label, name=None):
194 | self.thread.append(label)
195 | if name is not None:
196 | self.names.append(name)
197 |
198 | def ip(self):
199 | return len(self.thread)
200 |
201 | #####
202 |
203 | class RefBase:
204 | def __init__(self, name, label, value, text_section, data_section):
205 | self.name = name
206 | self.value = value
207 | self.text_section = text_section
208 | self.data_section = data_section
209 | self.used = False
210 |
211 | def output(self, section):
212 | if self.used:
213 | if section == self.text_section:
214 | return self.text_output
215 | elif section == self.data_section:
216 | return self.data_output
217 | else:
218 | return ""
219 | else:
220 | return ""
221 |
222 | def __iter__(self):
223 | return iter([])
224 |
225 |
226 | class Constant(RefBase):
227 | def __init__(self, name, label, value, text_section, data_section):
228 | RefBase.__init__(self, name, label, value, text_section, data_section)
229 | self.label = "const_" + label
230 | self.text_output = "%s\n dta a(const),a(%s)\n" % (self.label, label)
231 | self.data_output = "%s equ %s\n" % (label, self.value)
232 |
233 |
234 | class Variable(RefBase):
235 | def __init__(self, name, label, size, text_section, data_section):
236 | RefBase.__init__(self, name, label, None, text_section, data_section)
237 | self.label = "var_" + label
238 | self.text_output = "%s\n dta a(const),a(%s)\n" % (self.label, label)
239 | if size:
240 | self.data_output = "%s equ *\n org *+%d\n" % (label, 2*size)
241 | else:
242 | self.data_output = "%s equ *\n" % label
243 |
244 | #####
245 |
246 | class BranchTarget:
247 | def __init__(self, ip):
248 | self.ip = ip
249 | self.label = None
250 |
251 | def update(self, ip):
252 | if ip > self.ip:
253 | self.label = "*+%d" % (2 * (ip - self.ip))
254 | elif ip < self.ip:
255 | self.label = "*-%d" % (2 * (self.ip - ip))
256 |
257 | def __str__(self):
258 | return self.label
259 |
260 | #####
261 |
262 | class Words:
263 | def __init__(self):
264 | self.lst = []
265 | self.aliases = {"cells": "2*", "cell": "2*", "not": "0="}
266 |
267 | def __iter__(self):
268 | return iter(self.lst)
269 |
270 | def find(self, name):
271 | if name in self.aliases:
272 | name = self.aliases[name]
273 | for word in self.lst:
274 | if word.name == name:
275 | return word
276 | return None
277 |
278 | def add(self, word):
279 | self.lst.insert(0, word)
280 |
281 | #####
282 |
283 | class Forth:
284 | def __init__(self, sections):
285 | self.words = Words()
286 | self.items = []
287 | self.sections = sections
288 | self.text_section = "text"
289 | self.data_section = "data"
290 | self.stack = []
291 | self.do_loop_stack = []
292 | self.int_prog = re.compile("-?[0-9]+")
293 | self.hex_prog = re.compile(r"\$[0-9A-Fa-f]+")
294 | self.state = None
295 | self.inputs = []
296 |
297 | def push(self, item):
298 | self.stack.append(item)
299 |
300 | def pop(self, token):
301 | if not self.stack:
302 | raise StackUnderflow(token.text, self.current_file_name, token.line, token.column)
303 | else:
304 | return self.stack.pop()
305 |
306 | def push_do_loop(self):
307 | self.do_loop_stack.append([])
308 |
309 | def push_do_loop_leave(self, branch_target):
310 | self.do_loop_stack[-1].append(branch_target)
311 |
312 | def pop_do_loop(self, token):
313 | if not self.do_loop_stack:
314 | raise StackUnderflow(token.text, self.current_file_name, token.line, token.column)
315 | else:
316 | return self.do_loop_stack.pop()
317 |
318 | def add_word(self, word):
319 | self.words.add(word)
320 | self.items.append(word)
321 |
322 | def isnumber(self, token):
323 | return token is not None and \
324 | (self.int_prog.match(token.text) or \
325 | self.hex_prog.match(token.text))
326 |
327 | def tonumber(self, x):
328 | if type(x) == int:
329 | return x
330 | elif self.hex_prog.match(x):
331 | return int(x[1:], 16)
332 | else:
333 | return int(x)
334 |
335 | def next(self):
336 | token = self.input.next()
337 | if token == "\\":
338 | self.input.skip_to_eol()
339 | return self.next()
340 | elif token == "(":
341 | while not token.endswith(")"):
342 | token = self.input.next()
343 | return self.next()
344 | else:
345 | return token
346 |
347 | def set_state(self, state):
348 | self.state = state
349 |
350 | def parse_input(self, input, current_file_name):
351 | self.input = input
352 | self.current_file_name = current_file_name
353 | self.set_state("interpret")
354 | while not self.input.end():
355 | if self.state == "interpret":
356 | self.interpret()
357 | elif self.state == "compile":
358 | self.compile(self.word)
359 |
360 | def interpret(self):
361 | token = self.next()
362 | if token == ":":
363 | token = self.next()
364 | self.word = Word(token.text, self.text_section, label=token.canon())
365 | self.set_state("compile")
366 | elif token == "[include]":
367 | token = self.next();
368 | include_file_name = token.text.replace('"', '')
369 | try:
370 | self.inputs.append((self.input, self.current_file_name))
371 | with open(include_file_name, "rt") as f:
372 | self.parse_input(Input(f.read()), include_file_name)
373 | self.input, self.current_file_name = self.inputs.pop()
374 | except IOError:
375 | raise NoSuchFile(self.current_file_name, token)
376 |
377 | elif token == "[code]":
378 | self.items.append(self.parse_code())
379 | elif token == "[text-section]":
380 | self.text_section = self.parse_section()
381 | elif token == "[data-section]":
382 | self.data_section = self.parse_section()
383 | elif token == "variable":
384 | self.parse_variable(1)
385 | elif token == "2variable":
386 | self.parse_variable(2)
387 | elif token == "constant":
388 | self.parse_constant(token)
389 | elif token == "create":
390 | self.parse_create()
391 | elif token == ",":
392 | self.parse_comma(token)
393 | elif token == "c,":
394 | self.parse_c_comma(token)
395 | elif token == ',"':
396 | self.parse_comma_doublequote(True)
397 | elif token == '"':
398 | self.parse_comma_doublequote(False)
399 | elif token == ",'":
400 | self.parse_comma_quote(True)
401 | elif token == "'":
402 | self.parse_comma_quote(False)
403 | elif token == "allot":
404 | self.parse_allot(token)
405 | elif token == "+":
406 | x2 = self.pop(token)
407 | x1 = self.pop(token)
408 | self.push(x1 + x2)
409 | elif token == "-":
410 | x2 = self.pop(token)
411 | x1 = self.pop(token)
412 | self.push(x1 - x2)
413 | elif token == "*":
414 | x2 = self.pop(token)
415 | x1 = self.pop(token)
416 | self.push(x1 * x2)
417 | elif token == "cells":
418 | x = self.pop(token)
419 | self.push(2 * x)
420 | elif token == "/":
421 | x2 = self.pop(token)
422 | x1 = self.pop(token)
423 | self.push(x1 / x2)
424 | elif token == "]":
425 | self.set_state("compile")
426 | elif self.isnumber(token):
427 | self.push(self.tonumber(token.text))
428 | elif token is not None:
429 | word = self.words.find(token.text)
430 | if word is not None:
431 | word.used = True
432 | if isinstance(word, Constant):
433 | self.push(self.tonumber(word.value))
434 | else:
435 | self.push(word.name)
436 | else:
437 | raise UnknownWord(self.current_file_name, token)
438 |
439 | def compile(self, word):
440 | if self.input.end():
441 | raise UnexpectedEndOfStream(self.current_file_name, self.input.line, self.input.column)
442 | token = self.next()
443 | if token == ";":
444 | word.add("exit")
445 | self.add_word(word)
446 | self.set_state("interpret")
447 | elif token == "recursive":
448 | word.recursive = True
449 | elif token == "[label]":
450 | token = self.next()
451 | word.label = token.text
452 | elif token == "[code]":
453 | word.code = self.parse_code()
454 | elif token == "begin":
455 | self.push(word.ip())
456 | elif token == "again":
457 | word.add("branch")
458 | begin_ip = self.pop(token)
459 | target = BranchTarget(word.ip())
460 | target.update(begin_ip)
461 | word.add(target)
462 | elif token == "until":
463 | word.add("until")
464 | begin_ip = self.pop(token)
465 | target = BranchTarget(word.ip())
466 | target.update(begin_ip)
467 | word.add(target)
468 | elif token == "if":
469 | word.add("_if")
470 | target = BranchTarget(word.ip())
471 | word.add(target)
472 | self.push(target)
473 | elif token == "else":
474 | word.add("branch")
475 | target1 = BranchTarget(word.ip())
476 | word.add(target1)
477 | target0 = self.pop(token)
478 | target0.update(word.ip())
479 | self.push(target1)
480 | elif token == "then":
481 | target = self.pop(token)
482 | target.update(word.ip())
483 | elif token == "while":
484 | word.add("while", "while")
485 | target = BranchTarget(word.ip())
486 | word.add(target)
487 | self.push(target)
488 | elif token == "repeat":
489 | word.add("branch")
490 | target1 = self.pop(token)
491 | begin_ip = self.pop(token)
492 | target0 = BranchTarget(word.ip())
493 | target0.update(begin_ip)
494 | word.add(target0)
495 | target1.update(word.ip())
496 | elif token == "[":
497 | self.set_state("interpret")
498 | elif token == "literal":
499 | self.word.add("lit")
500 | tos = self.pop(token)
501 | if isinstance(tos, int):
502 | txt = str(tos)
503 | elif isinstance(tos, str):
504 | txt = tos
505 | else:
506 | txt = tos.output(self.text_section)
507 | self.word.add(txt)
508 | elif token == "do":
509 | word.add("do", "do")
510 | self.push(word.ip())
511 | self.push_do_loop()
512 | elif token == "loop" or token == "+loop":
513 | word.add(token.text.replace("+", "plus_"), token.text)
514 | do_ip = self.pop(token)
515 | target = BranchTarget(word.ip())
516 | target.update(do_ip)
517 | word.add(target)
518 | for leave in self.pop_do_loop(token):
519 | leave.update(word.ip())
520 | elif token == "leave":
521 | word.add("unloop", "unloop")
522 | word.add("branch")
523 | target = BranchTarget(word.ip())
524 | word.add(target)
525 | self.push_do_loop_leave(target)
526 | elif token == "lit":
527 | word.add("lit")
528 | token = self.next()
529 | word.add(token.text, token.text)
530 | elif token == "[']":
531 | word.add("lit")
532 | token = self.next()
533 | subword = self.words.find(token.text)
534 | if subword is not None:
535 | word.add(subword.label, token.text)
536 | else:
537 | raise UnknownWord(self.current_file_name, token)
538 | else:
539 | if word.recursive and token == word.name:
540 | subword = word
541 | else:
542 | subword = self.words.find(token.text)
543 | if subword is not None:
544 | word.add(subword.label, subword.name)
545 | else:
546 | if self.isnumber(token):
547 | word.add("lit")
548 | word.add(token.text)
549 | else:
550 | raise UnknownWord(self.current_file_name, token)
551 |
552 | def parse_code(self):
553 | self.input.mark_start()
554 | while True:
555 | self.input.mark_end()
556 | token = self.next()
557 | if token == "[end-code]":
558 | return Code(self.input.marked(), self.text_section)
559 |
560 | def parse_section(self):
561 | token = self.next()
562 | return token.text
563 |
564 | def parse_variable(self, size):
565 | token = self.next()
566 | name = token.text
567 | label = token.canon()
568 | word = Variable(name, label, size, self.text_section, self.data_section)
569 | self.add_word(word)
570 |
571 | def parse_constant(self, token):
572 | token = self.next()
573 | num = self.pop(token)
574 | word = Constant(token.text, token.canon(), num, self.text_section, self.data_section)
575 | self.add_word(word)
576 |
577 | def parse_create(self):
578 | token = self.next()
579 | name = token.text
580 | label = token.canon()
581 | word = Variable(name, label, 0, self.text_section, self.data_section)
582 | self.add_word(word)
583 |
584 | def parse_allot(self, token):
585 | count = self.pop(token)
586 | self.items.append(Code("\n org *+%d" % count, self.data_section))
587 |
588 | def parse_comma(self, token):
589 | item = Code("\n dta a(%s)" % self.pop(token), self.data_section)
590 | self.items.append(item)
591 |
592 | def parse_c_comma(self, token):
593 | item = Code("\n dta %d" % self.pop(token), self.data_section)
594 | self.items.append(item)
595 |
596 | def parse_comma_doublequote(self, counted):
597 | # allocate ASCII string
598 | self.input.mark_start()
599 | while True:
600 | token = self.next()
601 | if token.endswith('"'):
602 | self.input.mark_end()
603 | text = self.input.marked()[1:-1]
604 | if counted:
605 | count = "%d," % len(text)
606 | else:
607 | count = ""
608 | item = Code("\n dta %sc'%s'" % (count, text), self.data_section)
609 | self.items.append(item)
610 | break
611 |
612 | def parse_comma_quote(self, counted):
613 | # allocate ANTIC string
614 | self.input.mark_start()
615 | while True:
616 | token = self.next()
617 | if token.endswith("'") or token.endswith("'*"):
618 | self.input.mark_end()
619 | if token.endswith("*"):
620 | text = self.input.marked()[1:-2]
621 | inverse = "*"
622 | else:
623 | text = self.input.marked()[1:-1]
624 | inverse = ""
625 | if counted:
626 | count = "%d," % len(text)
627 | else:
628 | count = ""
629 | item = Code("\n dta %sd'%s'%s" % (count, text, inverse), self.data_section)
630 | self.items.append(item)
631 | break
632 |
633 | def filter_used_words(self, name):
634 | word = self.words.find(name)
635 | if word is not None:
636 | if not word.used:
637 | word.used = True
638 | for name in word:
639 | self.filter_used_words(name)
640 |
641 | def generate_output(self):
642 | self.filter_used_words("main")
643 | if self.stack:
644 | raise StackNotEmpty(self.current_file_name, self.input.line, self.input.column)
645 | section_outputs = []
646 | for section in self.sections:
647 | section_outputs.append("; section %s\n" % section)
648 | item_outputs = map(lambda i: i.output(section), self.items)
649 | section_outputs.append("".join(item_outputs))
650 | return "\n".join(section_outputs)
651 |
652 | #####
653 |
654 | boot_text = """
655 | [text-section] boot
656 |
657 | [code]
658 | ip equ $18
659 | w equ $1A
660 | z equ $1C
661 | cntr equ $1E
662 | tmp equ $15
663 | tmp2 equ $3D
664 | pstack equ %(pstack_bottom)s
665 |
666 | boot
667 | ldx #%(pstack_size)d
668 | lda #<[main+2]
669 | sta ip
670 | lda #>[main+2]
671 | sta ip+1
672 | jmp next
673 |
674 | ; push ip
675 | ; ip := w+2
676 | ; jmp next
677 | enter
678 | lda ip
679 | pha
680 | lda ip+1
681 | pha
682 | lda #2
683 | clc
684 | adc w
685 | sta ip
686 | lda #0
687 | adc w+1
688 | sta ip+1
689 | jmp next
690 |
691 | ; pop ip
692 | ; jmp next
693 | exit
694 | dta a(*+2)
695 | pla
696 | sta ip+1
697 | pla
698 | sta ip
699 | ;jmp next
700 |
701 | ; w := (ip)
702 | ; ip := ip+2
703 | ; z := (w)
704 | ; jmp (z)
705 | next
706 | ldy #0
707 | lda (ip),y
708 | sta w
709 | iny
710 | lda (ip),y
711 | sta w+1
712 | lda #2
713 | clc
714 | adc ip
715 | sta ip
716 | lda #0
717 | adc ip+1
718 | sta ip+1
719 | ldy #0
720 | lda (w),y
721 | sta z
722 | iny
723 | lda (w),y
724 | sta z+1
725 | jmp (z)
726 |
727 | ; push (ip)
728 | ; ip := ip+2
729 | lit
730 | dta a(*+2)
731 | ldy #1
732 | lda (ip),y
733 | dey
734 | dex
735 | sta pstack,x
736 | lda (ip),y
737 | dex
738 | sta pstack,x
739 | lda #2
740 | clc
741 | adc ip
742 | sta ip
743 | lda #0
744 | adc ip+1
745 | sta ip+1
746 | jmp next
747 |
748 | const
749 | ldy #3
750 | lda (w),y
751 | dey
752 | dex
753 | sta pstack,x
754 | lda (w),y
755 | dex
756 | sta pstack,x
757 | jmp next
758 |
759 | _if
760 | dta a(*+2)
761 | lda pstack,x
762 | inx
763 | ora pstack,x
764 | bne _if_t
765 | _if_f
766 | ldy #0
767 | lda (ip),y
768 | sta w
769 | iny
770 | lda (ip),y
771 | sta ip+1
772 | lda w
773 | sta ip
774 | inx
775 | jmp next
776 | _if_t
777 | lda #2
778 | clc
779 | adc ip
780 | sta ip
781 | lda #0
782 | adc ip+1
783 | sta ip+1
784 | inx
785 | jmp next
786 |
787 | branch
788 | dta a(*+2)
789 | ldy #0
790 | lda (ip),y
791 | sta w
792 | iny
793 | lda (ip),y
794 | sta ip+1
795 | lda w
796 | sta ip
797 | jmp next
798 |
799 | until
800 | dta a(*+2)
801 | lda pstack,x
802 | inx
803 | ora pstack,x
804 | bne until_end
805 | until_repeat
806 | inx
807 | ; ip := (ip)
808 | ldy #0
809 | lda (ip),y
810 | iny
811 | sta w
812 | lda (ip),y
813 | sta ip+1
814 | lda w
815 | sta ip
816 | jmp next
817 | until_end
818 | inx
819 | ; ip := ip+2
820 | clc
821 | lda #2
822 | adc ip
823 | sta ip
824 | lda #0
825 | adc ip+1
826 | sta ip+1
827 | jmp next
828 |
829 | [end-code]
830 | """
831 |
832 | basewords_text = r"""
833 | [text-section] text
834 |
835 | : drop
836 | [code]
837 | inx
838 | inx
839 | jmp next
840 | [end-code] ;
841 |
842 | : nip
843 | [code]
844 | lda pstack,x
845 | sta pstack+2,x
846 | inx
847 | lda pstack,x
848 | sta pstack+2,x
849 | inx
850 | jmp next
851 | [end-code] ;
852 |
853 | : while
854 | [code]
855 | lda pstack,x
856 | inx
857 | ora pstack,x
858 | beq while_end
859 | inx
860 | lda #2
861 | clc
862 | adc ip
863 | sta ip
864 | lda #0
865 | adc ip+1
866 | sta ip+1
867 | jmp next
868 | while_end
869 | inx
870 | ldy #0
871 | lda (ip),y
872 | iny
873 | sta w
874 | lda (ip),y
875 | sta ip+1
876 | lda w
877 | sta ip
878 | jmp next
879 | [end-code] ;
880 |
881 | : @
882 | [label] fetch
883 | [code]
884 | lda pstack,x
885 | inx
886 | sta w
887 | lda pstack,x
888 | sta w+1
889 | ldy #1
890 | lda (w),y
891 | sta pstack,x
892 | dey
893 | lda (w),y
894 | dex
895 | sta pstack,x
896 | jmp next
897 | [end-code] ;
898 |
899 | : c@
900 | [label] c_fetch
901 | [code]
902 | lda pstack,x
903 | inx
904 | sta w
905 | lda pstack,x
906 | sta w+1
907 | lda #0
908 | sta pstack,x
909 | ldy #0
910 | lda (w),y
911 | dex
912 | sta pstack,x
913 | jmp next
914 | [end-code] ;
915 |
916 | : ! ( x addr -- )
917 | [label] store
918 | [code]
919 | lda pstack,x
920 | inx
921 | sta w
922 | lda pstack,x
923 | inx
924 | sta w+1
925 | lda pstack,x
926 | inx
927 | ldy #0
928 | sta (w),y
929 | iny
930 | lda pstack,x
931 | inx
932 | sta (w),y
933 | jmp next
934 | [end-code] ;
935 |
936 | : c!
937 | [label] c_store
938 | [code]
939 | lda pstack,x
940 | inx
941 | sta w
942 | lda pstack,x
943 | inx
944 | sta w+1
945 | lda pstack,x
946 | inx
947 | inx
948 | ldy #0
949 | sta (w),y
950 | jmp next
951 | [end-code] ;
952 |
953 | : + ( n1|u1 n2|u2 -- n3|u3 )
954 | [label] plus
955 | [code]
956 | lda pstack,x
957 | inx
958 | ldy pstack,x
959 | inx
960 | clc
961 | adc pstack,x
962 | sta pstack,x
963 | tya
964 | adc pstack+1,x
965 | sta pstack+1,x
966 | jmp next
967 | [end-code] ;
968 |
969 | \ n1|u1 - n2|u2
970 |
971 | : - ( n1|u1 n2|u2 -- n3|u3 )
972 | [label] minus
973 | [code]
974 | sec
975 | lda pstack+2,x
976 | sbc pstack+0,x
977 | sta pstack+2,x
978 | inx
979 | lda pstack+2,x
980 | sbc pstack+0,x
981 | sta pstack+2,x
982 | inx
983 | jmp next
984 | [end-code] ;
985 |
986 | : 1+
987 | [label] one_plus
988 | [code]
989 | clc
990 | lda #1
991 | adc pstack,x
992 | sta pstack,x
993 | lda #0
994 | adc pstack+1,x
995 | sta pstack+1,x
996 | jmp next
997 | [end-code] ;
998 |
999 | : 1-
1000 | [label] one_minus
1001 | [code]
1002 | sec
1003 | lda pstack,x
1004 | sbc #1
1005 | sta pstack,x
1006 | lda pstack+1,x
1007 | sbc #0
1008 | sta pstack+1,x
1009 | jmp next
1010 | [end-code] ;
1011 |
1012 | : count ( addr1 -- addr2 u )
1013 | [code]
1014 | lda pstack,x
1015 | sta w
1016 | clc
1017 | adc #1
1018 | sta pstack,x
1019 | lda pstack+1,x
1020 | sta w+1
1021 | adc #0
1022 | sta pstack+1,x
1023 | lda #0
1024 | dex
1025 | sta pstack,x
1026 | ldy #0
1027 | lda (w),y
1028 | dex
1029 | sta pstack,x
1030 | jmp next
1031 | [end-code] ;
1032 |
1033 | : cmove ( c-addr1 c-addr2 u -- )
1034 | [code]
1035 | lda pstack,x
1036 | inx
1037 | sta cntr
1038 | lda pstack,x
1039 | inx
1040 | sta cntr+1
1041 | lda pstack,x
1042 | inx
1043 | sta w
1044 | lda pstack,x
1045 | inx
1046 | sta w+1
1047 | lda pstack,x
1048 | inx
1049 | sta z
1050 | lda pstack,x
1051 | inx
1052 | sta z+1
1053 | ldy #0
1054 | lda cntr+1
1055 | beq cmove_tail
1056 | cmove_loop_1
1057 | lda (z),y
1058 | sta (w),y
1059 | iny
1060 | bne cmove_loop_1
1061 | inc z+1
1062 | inc w+1
1063 | dec cntr+1
1064 | bne cmove_loop_1
1065 | cmove_tail
1066 | lda cntr
1067 | beq cmove_done
1068 | cmove_loop_2
1069 | lda (z),y
1070 | sta (w),y
1071 | iny
1072 | cpy cntr
1073 | bne cmove_loop_2
1074 | cmove_done
1075 | jmp next
1076 | [end-code] ;
1077 |
1078 | : fill ( c-addr u c -- )
1079 | [code]
1080 | lda pstack,x
1081 | inx
1082 | sta w
1083 | inx
1084 | lda pstack,x
1085 | inx
1086 | sta cntr
1087 | lda pstack,x
1088 | inx
1089 | sta cntr+1
1090 | lda pstack,x
1091 | inx
1092 | sta z
1093 | lda pstack,x
1094 | inx
1095 | sta z+1
1096 | ldy #0
1097 | lda cntr+1
1098 | beq fill_tail
1099 | lda w
1100 | fill_loop_1
1101 | sta (z),y
1102 | iny
1103 | bne fill_loop_1
1104 | inc z+1
1105 | dec cntr+1
1106 | bne fill_loop_1
1107 | fill_tail
1108 | lda cntr
1109 | beq fill_done
1110 | lda w
1111 | fill_loop_2
1112 | sta (z),y
1113 | iny
1114 | dec cntr
1115 | bne fill_loop_2
1116 | fill_done
1117 | jmp next
1118 | [end-code] ;
1119 |
1120 | : erase ( c-addr u -- )
1121 | [code]
1122 | lda pstack,x
1123 | inx
1124 | sta cntr
1125 | lda pstack,x
1126 | inx
1127 | sta cntr+1
1128 | lda pstack,x
1129 | inx
1130 | sta z
1131 | lda pstack,x
1132 | inx
1133 | sta z+1
1134 | ldy #0
1135 | lda cntr+1
1136 | beq erase_tail
1137 | lda #0
1138 | erase_loop_1
1139 | sta (z),y
1140 | iny
1141 | bne erase_loop_1
1142 | inc z+1
1143 | dec cntr+1
1144 | bne erase_loop_1
1145 | erase_tail
1146 | lda cntr
1147 | beq erase_done
1148 | lda #0
1149 | erase_loop_2
1150 | sta (z),y
1151 | iny
1152 | dec cntr
1153 | bne erase_loop_2
1154 | erase_done
1155 | jmp next
1156 | [end-code] ;
1157 |
1158 | : dup ( x -- x x )
1159 | [code]
1160 | ldy pstack,x
1161 | lda pstack+1,x
1162 | dex
1163 | sta pstack,x
1164 | tya
1165 | dex
1166 | sta pstack,x
1167 | jmp next
1168 | [end-code] ;
1169 |
1170 | : swap
1171 | [code]
1172 | ldy pstack,x
1173 | lda pstack+2,x
1174 | sta pstack,x
1175 | tya
1176 | sta pstack+2,x
1177 | ldy pstack+1,x
1178 | lda pstack+3,x
1179 | sta pstack+1,x
1180 | tya
1181 | sta pstack+3,x
1182 | jmp next
1183 | [end-code] ;
1184 |
1185 | : over ( x1 x2 -- x1 x2 x1 )
1186 | [code]
1187 | lda pstack+3,x
1188 | dex
1189 | sta pstack,x
1190 | lda pstack+3,x
1191 | dex
1192 | sta pstack,x
1193 | jmp next
1194 | [end-code] ;
1195 |
1196 | : and ( x1 x2 -- x3 )
1197 | [code]
1198 | lda pstack,x
1199 | inx
1200 | ldy pstack,x
1201 | inx
1202 | and pstack,x
1203 | sta pstack,x
1204 | tya
1205 | and pstack+1,x
1206 | sta pstack+1,x
1207 | jmp next
1208 | [end-code] ;
1209 |
1210 | : or ( x1 x2 -- x3 )
1211 | [code]
1212 | lda pstack,x
1213 | inx
1214 | ldy pstack,x
1215 | inx
1216 | ora pstack,x
1217 | sta pstack,x
1218 | tya
1219 | ora pstack+1,x
1220 | sta pstack+1,x
1221 | jmp next
1222 | [end-code] ;
1223 |
1224 | : rshift ( x1 u -- x2 )
1225 | [code]
1226 | ldy pstack,x
1227 | inx
1228 | inx
1229 | lda pstack,x
1230 | rshift_loop
1231 | cpy #0
1232 | beq rshift_end
1233 | dey
1234 | lsr pstack+1,x
1235 | ror @
1236 | jmp rshift_loop
1237 | rshift_end
1238 | sta pstack,x
1239 | jmp next
1240 | [end-code] ;
1241 |
1242 | : lshift ( x1 u -- x2 )
1243 | [code]
1244 | ldy pstack,x
1245 | inx
1246 | inx
1247 | lda pstack,x
1248 | lshift_loop
1249 | cpy #0
1250 | beq lshift_end
1251 | dey
1252 | asl @
1253 | rol pstack+1,x
1254 | jmp lshift_loop
1255 | lshift_end
1256 | sta pstack,x
1257 | jmp next
1258 | [end-code] ;
1259 |
1260 | \ n2-n1 : n2 N eor V = 1
1261 | \ n2>=n1 => N eor V = 0
1262 |
1263 | : > ( n1 n2 -- flag )
1264 | [label] greater_than
1265 | [code]
1266 | sec
1267 | lda pstack,x
1268 | inx
1269 | sbc pstack+1,x
1270 | lda pstack,x
1271 | inx
1272 | sbc pstack+1,x
1273 | bvc gt_v
1274 | eor #$80
1275 | gt_v
1276 | bpl gt_f
1277 | gt_t
1278 | lda #$FF
1279 | sta pstack,x
1280 | sta pstack+1,x
1281 | jmp next
1282 | gt_f
1283 | lda #$00
1284 | sta pstack,x
1285 | sta pstack+1,x
1286 | jmp next
1287 | [end-code] ;
1288 |
1289 | \ n2-n1 : n2 N eor V = 1
1290 | \ n2>=n1 => N eor V = 0
1291 |
1292 | : <= ( n1 n2 -- flag )
1293 | [label] less_than_or_equal
1294 | [code]
1295 | sec
1296 | lda pstack,x
1297 | inx
1298 | sbc pstack+1,x
1299 | lda pstack,x
1300 | inx
1301 | sbc pstack+1,x
1302 | bvc lteq_v
1303 | eor #$80
1304 | lteq_v
1305 | bmi lteq_f
1306 | lteq_t
1307 | lda #$FF
1308 | sta pstack,x
1309 | sta pstack+1,x
1310 | jmp next
1311 | lteq_f
1312 | lda #$00
1313 | sta pstack,x
1314 | sta pstack+1,x
1315 | jmp next
1316 | [end-code] ;
1317 |
1318 | \ n1-n2 : n1 N eor V = 1
1319 | \ n1>=n2 => N eor V = 0
1320 |
1321 | : < ( n1 n2 -- flag )
1322 | [label] less_than
1323 | [code]
1324 | sec
1325 | lda pstack+2,x
1326 | sbc pstack+0,x
1327 | lda pstack+3,x
1328 | sbc pstack+1,x
1329 | bvc lt_v
1330 | eor #$80
1331 | lt_v
1332 | bpl lt_f
1333 | lt_t
1334 | lda #$FF
1335 | lt_set
1336 | inx
1337 | inx
1338 | sta pstack,x
1339 | sta pstack+1,x
1340 | jmp next
1341 | lt_f
1342 | lda #$00
1343 | beq lt_set
1344 | [end-code] ;
1345 |
1346 | \ n1-n2 : n1 N eor V = 1
1347 | \ n1>=n2 => N eor V = 0
1348 |
1349 | : >= ( n1 n2 -- flag )
1350 | [label] greater_than_or_equal
1351 | [code]
1352 | sec
1353 | lda pstack+2,x
1354 | sbc pstack+0,x
1355 | lda pstack+3,x
1356 | sbc pstack+1,x
1357 | bvc gteq_v
1358 | eor #$80
1359 | gteq_v
1360 | bmi gteq_f
1361 | gteq_t
1362 | lda #$FF
1363 | gteq_set
1364 | inx
1365 | inx
1366 | sta pstack,x
1367 | sta pstack+1,x
1368 | jmp next
1369 | gteq_f
1370 | lda #$00
1371 | beq gteq_set
1372 | [end-code] ;
1373 |
1374 | \ u2-u1 : u2 C = 0
1375 | \ u2>=u1 => C = 1
1376 |
1377 | : u> ( u1 u2 -- flag )
1378 | [label] unsigned_greater_than
1379 | [code]
1380 | sec
1381 | lda pstack+0,x
1382 | sbc pstack+2,x
1383 | inx
1384 | lda pstack+0,x
1385 | sbc pstack+2,x
1386 | inx
1387 | bcc ugt_t
1388 | lda #$00
1389 | ugt_set
1390 | sta pstack+0,x
1391 | sta pstack+1,x
1392 | jmp next
1393 | ugt_t
1394 | lda #$FF
1395 | bne ugt_set
1396 | [end-code] ;
1397 |
1398 | \ u1-u2 : u1 C = 0
1399 | \ u1>=u2 => C = 1
1400 |
1401 | : u< ( u1 u2 -- flag )
1402 | [label] unsigned_less_than
1403 | [code]
1404 | sec
1405 | lda pstack+2,x
1406 | sbc pstack+0,x
1407 | inx
1408 | lda pstack+2,x
1409 | sbc pstack+0,x
1410 | inx
1411 | bcc ult_t
1412 | lda #$00
1413 | ult_set
1414 | sta pstack+0,x
1415 | sta pstack+1,x
1416 | jmp next
1417 | ult_t
1418 | lda #$FF
1419 | bne ult_set
1420 | [end-code] ;
1421 |
1422 | : = ( x1 x2 -- flag )
1423 | [label] equals
1424 | [code]
1425 | lda pstack,x
1426 | cmp pstack+2,x
1427 | bne eq_f
1428 | lda pstack+1,x
1429 | cmp pstack+3,x
1430 | bne eq_f
1431 | eq_t
1432 | lda #$FF
1433 | bne eq_end
1434 | eq_f
1435 | lda #0
1436 | eq_end
1437 | inx
1438 | inx
1439 | sta pstack,x
1440 | sta pstack+1,x
1441 | jmp next
1442 | [end-code] ;
1443 |
1444 | : <> ( x1 x2 -- flag )
1445 | [label] not_equals
1446 | [code]
1447 | lda pstack,x
1448 | cmp pstack+2,x
1449 | bne neq_t
1450 | lda pstack+1,x
1451 | cmp pstack+3,x
1452 | bne neq_t
1453 | neq_f
1454 | lda #$00
1455 | beq neq_end
1456 | neq_t
1457 | lda #$FF
1458 | neq_end
1459 | inx
1460 | inx
1461 | sta pstack,x
1462 | sta pstack+1,x
1463 | jmp next
1464 | [end-code] ;
1465 |
1466 | : 2! ( x1 x2 addr -- )
1467 | [label] two_store
1468 | [code]
1469 | lda pstack,x
1470 | inx
1471 | sta w
1472 | lda pstack,x
1473 | inx
1474 | sta w+1
1475 | ldy #0
1476 | lda pstack,x
1477 | inx
1478 | sta (w),y
1479 | iny
1480 | lda pstack,x
1481 | inx
1482 | sta (w),y
1483 | iny
1484 | lda pstack,x
1485 | inx
1486 | sta (w),y
1487 | iny
1488 | lda pstack,x
1489 | inx
1490 | sta (w),y
1491 | jmp next
1492 | [end-code] ;
1493 |
1494 | : 2@ ( addr -- x1 x2 )
1495 | [label] two_fetch
1496 | [code]
1497 | lda pstack,x
1498 | inx
1499 | sta w
1500 | lda pstack,x
1501 | sta w+1
1502 | ldy #3
1503 | lda (w),y
1504 | dey
1505 | sta pstack,x
1506 | lda (w),y
1507 | dey
1508 | dex
1509 | sta pstack,x
1510 | lda (w),y
1511 | dey
1512 | dex
1513 | sta pstack,x
1514 | lda (w),y
1515 | dex
1516 | sta pstack,x
1517 | jmp next
1518 | [end-code] ;
1519 |
1520 | : d= ( d1 d2 -- flag )
1521 | [label] d_equ
1522 | [code]
1523 | lda pstack+0,x
1524 | cmp pstack+4,x
1525 | bne d_equ_f
1526 | lda pstack+1,x
1527 | cmp pstack+5,x
1528 | bne d_equ_f
1529 | lda pstack+2,x
1530 | cmp pstack+6,x
1531 | bne d_equ_f
1532 | lda pstack+3,x
1533 | cmp pstack+7,x
1534 | bne d_equ_f
1535 | lda #$FF
1536 | d_equ_end
1537 | inx
1538 | inx
1539 | inx
1540 | inx
1541 | inx
1542 | inx
1543 | sta pstack+0,x
1544 | sta pstack+1,x
1545 | jmp next
1546 | d_equ_f
1547 | lda #$00
1548 | jmp d_equ_end
1549 | [end-code] ;
1550 |
1551 | : d+ ( d1 d2 -- d3 )
1552 | [label] d_plus
1553 | [code]
1554 | clc
1555 | lda pstack+2,x
1556 | adc pstack+6,x
1557 | sta pstack+6,x
1558 | lda pstack+3,x
1559 | adc pstack+7,x
1560 | sta pstack+7,x
1561 | lda pstack+0,x
1562 | adc pstack+4,x
1563 | sta pstack+4,x
1564 | lda pstack+1,x
1565 | adc pstack+5,x
1566 | sta pstack+5,x
1567 | inx
1568 | inx
1569 | inx
1570 | inx
1571 | jmp next
1572 | [end-code] ;
1573 |
1574 | : d- ( d1 d2 -- d3 )
1575 | [label] d_minus
1576 | [code]
1577 | sec
1578 | lda pstack+6,x
1579 | sbc pstack+2,x
1580 | sta pstack+6,x
1581 | lda pstack+7,x
1582 | sbc pstack+3,x
1583 | sta pstack+7,x
1584 | lda pstack+4,x
1585 | sbc pstack+0,x
1586 | sta pstack+4,x
1587 | lda pstack+5,x
1588 | sbc pstack+1,x
1589 | sta pstack+5,x
1590 | inx
1591 | inx
1592 | inx
1593 | inx
1594 | jmp next
1595 | [end-code] ;
1596 |
1597 | : 2drop
1598 | [label] two_drop
1599 | [code]
1600 | inx
1601 | inx
1602 | inx
1603 | inx
1604 | jmp next
1605 | [end-code] ;
1606 |
1607 | : 2dup
1608 | [label] two_dup
1609 | [code]
1610 | lda pstack+3,x
1611 | dex
1612 | sta pstack,x
1613 | lda pstack+3,x
1614 | dex
1615 | sta pstack,x
1616 | lda pstack+3,x
1617 | dex
1618 | sta pstack,x
1619 | lda pstack+3,x
1620 | dex
1621 | sta pstack,x
1622 | jmp next
1623 | [end-code] ;
1624 |
1625 | : 2over ( x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2 )
1626 | [label] two_over
1627 | [code]
1628 | lda pstack+7,x
1629 | dex
1630 | sta pstack,x
1631 | lda pstack+7,x
1632 | dex
1633 | sta pstack,x
1634 | lda pstack+7,x
1635 | dex
1636 | sta pstack,x
1637 | lda pstack+7,x
1638 | dex
1639 | sta pstack,x
1640 | jmp next
1641 | [end-code] ;
1642 |
1643 | : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
1644 | [label] two_stap
1645 | [code]
1646 | ldy pstack+0,x
1647 | lda pstack+4,x
1648 | sta pstack+0,x
1649 | tya
1650 | sta pstack+4,x
1651 | ldy pstack+1,x
1652 | lda pstack+5,x
1653 | sta pstack+1,x
1654 | tya
1655 | sta pstack+5,x
1656 | ldy pstack+2,x
1657 | lda pstack+6,x
1658 | sta pstack+2,x
1659 | tya
1660 | sta pstack+6,x
1661 | ldy pstack+3,x
1662 | lda pstack+7,x
1663 | sta pstack+3,x
1664 | tya
1665 | sta pstack+7,x
1666 | jmp next
1667 | [end-code] ;
1668 |
1669 | : sp
1670 | [code]
1671 | txa
1672 | clc
1673 | adc #pstack
1677 | dex
1678 | sta pstack,x
1679 | lda w
1680 | dex
1681 | sta pstack,x
1682 | jmp next
1683 | [end-code] ;
1684 |
1685 | : rsp
1686 | [code]
1687 | txa
1688 | tay
1689 | lda #0
1690 | dey
1691 | sta pstack,y
1692 | tsx
1693 | txa
1694 | dey
1695 | sta pstack,y
1696 | tya
1697 | tax
1698 | jmp next
1699 | [end-code] ;
1700 |
1701 | : 0=
1702 | [label] zero_eq
1703 | [code]
1704 | lda pstack,x
1705 | ora pstack+1,x
1706 | beq zero_eq_t
1707 | zero_eq_f
1708 | lda #$00
1709 | zero_eq_set
1710 | sta pstack+1,x
1711 | sta pstack,x
1712 | jmp next
1713 | zero_eq_t
1714 | lda #$FF
1715 | bne zero_eq_set
1716 | [end-code] ;
1717 |
1718 | : do
1719 | [code]
1720 | lda pstack,x ; index:lo
1721 | inx
1722 | pha
1723 | lda pstack,x ; index:hi
1724 | inx
1725 | pha
1726 | lda pstack,x ; limit:lo
1727 | inx
1728 | pha
1729 | lda pstack,x ; limit:hi
1730 | inx
1731 | pha
1732 | jmp next
1733 | [end-code] ;
1734 |
1735 | : loop
1736 | [code]
1737 | pla
1738 | sta z+1 ; limit:hi
1739 | pla
1740 | sta z ; limit:lo
1741 | pla
1742 | sta w+1 ; index:hi
1743 | pla
1744 | sta w ; index:lo
1745 | ; index := index+1
1746 | clc
1747 | lda #1
1748 | adc w
1749 | sta w
1750 | lda #0
1751 | adc w+1
1752 | sta w+1
1753 | ; limit=index?
1754 | lda w
1755 | cmp z
1756 | bne loop_again
1757 | lda w+1
1758 | cmp z+1
1759 | beq loop_end
1760 | loop_again
1761 | lda w ; index:lo
1762 | pha
1763 | lda w+1 ; index:hi
1764 | pha
1765 | lda z ; limit:lo
1766 | pha
1767 | lda z+1 ; limit:hi
1768 | pha
1769 | ; ip := (ip)
1770 | ldy #0
1771 | lda (ip),y
1772 | sta w
1773 | iny
1774 | lda (ip),y
1775 | sta ip+1
1776 | lda w
1777 | sta ip
1778 | jmp next
1779 | loop_end
1780 | ; ip := ip+2
1781 | clc
1782 | lda #2
1783 | adc ip
1784 | sta ip
1785 | lda #0
1786 | adc ip+1
1787 | sta ip+1
1788 | jmp next
1789 | [end-code] ;
1790 |
1791 | : +loop
1792 | [label] plus_loop
1793 | [code]
1794 | pla
1795 | sta z+1 ; limit:hi
1796 | pla
1797 | sta z ; limit:lo
1798 | pla
1799 | sta w+1 ; index:hi
1800 | pla
1801 | sta w ; index:lo
1802 | ; tmp := index - limit
1803 | sec
1804 | sbc z
1805 | sta tmp
1806 | lda w+1
1807 | sbc z+1
1808 | sta tmp+1
1809 | ; tmp2 := index - limit + n
1810 | clc
1811 | lda tmp
1812 | adc pstack,x
1813 | sta tmp2
1814 | lda tmp+1
1815 | adc pstack+1,x
1816 | sta tmp2+1
1817 | ; index := index+n
1818 | clc
1819 | lda pstack,x
1820 | inx
1821 | adc w
1822 | sta w
1823 | lda pstack,x
1824 | inx
1825 | adc w+1
1826 | sta w+1
1827 | ; sgn(index-limit) <> sgn(index-limit+n) ?
1828 | lda tmp+1
1829 | eor tmp2+1
1830 | bmi plus_loop_end
1831 | plus_loop_again
1832 | lda w ; index:lo
1833 | pha
1834 | lda w+1 ; index:hi
1835 | pha
1836 | lda z ; limit:lo
1837 | pha
1838 | lda z+1 ; limit:hi
1839 | pha
1840 | ; ip := (ip)
1841 | ldy #0
1842 | lda (ip),y
1843 | sta w
1844 | iny
1845 | lda (ip),y
1846 | sta ip+1
1847 | lda w
1848 | sta ip
1849 | jmp next
1850 | plus_loop_end
1851 | ; ip := ip+2
1852 | clc
1853 | lda #2
1854 | adc ip
1855 | sta ip
1856 | lda #0
1857 | adc ip+1
1858 | sta ip+1
1859 | jmp next
1860 | [end-code] ;
1861 |
1862 | : i
1863 | [code]
1864 | txa
1865 | tay
1866 | tsx
1867 | inx
1868 | inx
1869 | inx
1870 | lda $100,x ; index:hi
1871 | dey
1872 | sta pstack,y
1873 | inx
1874 | lda $100,x ; index:lo
1875 | dey
1876 | sta pstack,y
1877 | tya
1878 | tax
1879 | jmp next
1880 | [end-code] ;
1881 |
1882 | : j
1883 | [code]
1884 | txa
1885 | tay
1886 | tsx
1887 | inx
1888 | inx
1889 | inx
1890 | inx
1891 | inx
1892 | inx
1893 | inx
1894 | lda $100,x ; index:hi
1895 | dey
1896 | sta pstack,y
1897 | inx
1898 | lda $100,x ; index:lo
1899 | dey
1900 | sta pstack,y
1901 | tya
1902 | tax
1903 | jmp next
1904 | [end-code] ;
1905 |
1906 | : unloop
1907 | [code]
1908 | pla
1909 | pla
1910 | pla
1911 | pla
1912 | jmp next
1913 | [end-code] ;
1914 |
1915 | : 2*
1916 | [label] two_star
1917 | [code]
1918 | asl pstack,x
1919 | rol pstack+1,x
1920 | jmp next
1921 | [end-code] ;
1922 |
1923 | : 2/
1924 | [label] two_slash
1925 | [code]
1926 | lda pstack+1,x
1927 | cmp #$80
1928 | ror pstack+1,x
1929 | ror pstack,x
1930 | jmp next
1931 | [end-code] ;
1932 |
1933 | : m* ( n1 n2 -- d-prod )
1934 | [label] m_star
1935 | [code]
1936 | ; z := n2
1937 | lda pstack,x
1938 | sta z
1939 | lda pstack+1,x
1940 | sta z+1
1941 | ; w := n1
1942 | lda pstack+2,x
1943 | sta w
1944 | lda pstack+3,x
1945 | sta w+1
1946 | ; save sign
1947 | eor z+1
1948 | sta cntr+1
1949 | ; abs(n1)
1950 | lda w+1
1951 | bpl m_star_n1_plus
1952 | lda w
1953 | eor #$FF
1954 | clc
1955 | adc #1
1956 | sta w
1957 | lda w+1
1958 | eor #$FF
1959 | adc #0
1960 | sta w+1
1961 | m_star_n1_plus
1962 | ; abs(n2)
1963 | lda z+1
1964 | bpl m_star_n2_plus
1965 | lda z
1966 | eor #$FF
1967 | clc
1968 | adc #1
1969 | sta z
1970 | lda z+1
1971 | eor #$FF
1972 | adc #0
1973 | sta z+1
1974 | m_star_n2_plus
1975 | ; clear result
1976 | lda #0
1977 | sta tmp+0
1978 | sta tmp+1
1979 | sta tmp2+0
1980 | sta tmp2+1
1981 | ; tmp := w * z
1982 | ldy #16
1983 | m_star_loop
1984 | lsr w+1
1985 | ror w
1986 | bcc m_star_next
1987 | lda z
1988 | clc
1989 | adc tmp2+0
1990 | sta tmp2+0
1991 | lda z+1
1992 | adc tmp2+1
1993 | sta tmp2+1
1994 | m_star_next
1995 | clc
1996 | ror tmp2+1
1997 | ror tmp2+0
1998 | ror tmp+1
1999 | ror tmp+0
2000 | dey
2001 | bne m_star_loop
2002 | ; apply sign
2003 | lda cntr+1
2004 | bpl m_star_done
2005 | lda tmp+0
2006 | eor #$FF
2007 | clc
2008 | adc #1
2009 | sta tmp+0
2010 | lda tmp+1
2011 | eor #$FF
2012 | adc #0
2013 | sta tmp+1
2014 | lda tmp2+0
2015 | eor #$FF
2016 | adc #0
2017 | sta tmp2+0
2018 | lda tmp2+1
2019 | eor #$FF
2020 | adc #0
2021 | sta tmp2+1
2022 | m_star_done
2023 | ; push result on the stack
2024 | lda tmp+0
2025 | sta pstack+2,x
2026 | lda tmp+1
2027 | sta pstack+3,x
2028 | lda tmp2+0
2029 | sta pstack+0,x
2030 | lda tmp2+1
2031 | sta pstack+1,x
2032 | jmp next
2033 | [end-code] ;
2034 |
2035 | : >r ( x -- ) ( R: -- x )
2036 | [label] to_r
2037 | [code]
2038 | lda pstack+1,x
2039 | pha
2040 | lda pstack+0,x
2041 | pha
2042 | inx
2043 | inx
2044 | jmp next
2045 | [end-code] ;
2046 |
2047 | : r> ( -- x ) ( R: x -- )
2048 | [label] r_from
2049 | [code]
2050 | pla
2051 | tay
2052 | pla
2053 | dex
2054 | sta pstack,x
2055 | dex
2056 | tya
2057 | sta pstack,x
2058 | jmp next
2059 | [end-code] ;
2060 |
2061 | : execute ( x -- )
2062 | [label] execute
2063 | [code]
2064 | lda pstack,x
2065 | inx
2066 | sta w
2067 | lda pstack,x
2068 | inx
2069 | sta w+1
2070 | ldy #0
2071 | lda (w),y
2072 | sta z
2073 | iny
2074 | lda (w),y
2075 | sta z+1
2076 | jmp (z)
2077 | [end-code] ;
2078 |
2079 | \ w = n3
2080 | \ z = n2
2081 | \ tmp = n1
2082 | : rot ( n1 n2 n3 -- n2 n3 n1 )
2083 | [label] rot
2084 | [code]
2085 | lda pstack,x
2086 | inx
2087 | sta w
2088 | lda pstack,x
2089 | inx
2090 | sta w+1
2091 | lda pstack,x
2092 | inx
2093 | sta z
2094 | lda pstack,x
2095 | inx
2096 | sta z+1
2097 | lda pstack,x
2098 | inx
2099 | sta tmp
2100 | lda pstack,x
2101 | inx
2102 | sta tmp+1
2103 | lda z+1
2104 | dex
2105 | sta pstack,x
2106 | lda z
2107 | dex
2108 | sta pstack,x
2109 | lda w+1
2110 | dex
2111 | sta pstack,x
2112 | lda w
2113 | dex
2114 | sta pstack,x
2115 | lda tmp+1
2116 | dex
2117 | sta pstack,x
2118 | lda tmp
2119 | dex
2120 | sta pstack,x
2121 | jmp next
2122 | [end-code] ;
2123 |
2124 | \ w = n3
2125 | \ z = n2
2126 | \ tmp = n1
2127 | : -rot ( n1 n2 n3 -- n3 n1 n2 )
2128 | [label] minus_rot
2129 | [code]
2130 | lda pstack,x
2131 | inx
2132 | sta w
2133 | lda pstack,x
2134 | inx
2135 | sta w+1
2136 | lda pstack,x
2137 | inx
2138 | sta z
2139 | lda pstack,x
2140 | inx
2141 | sta z+1
2142 | lda pstack,x
2143 | inx
2144 | sta tmp
2145 | lda pstack,x
2146 | inx
2147 | sta tmp+1
2148 | lda w+1
2149 | dex
2150 | sta pstack,x
2151 | lda w
2152 | dex
2153 | sta pstack,x
2154 | lda tmp+1
2155 | dex
2156 | sta pstack,x
2157 | lda tmp
2158 | dex
2159 | sta pstack,x
2160 | lda z+1
2161 | dex
2162 | sta pstack,x
2163 | lda z
2164 | dex
2165 | sta pstack,x
2166 | jmp next
2167 | [end-code] ;
2168 | """
2169 |
2170 | parser = argparse.ArgumentParser()
2171 | parser.add_argument("--sections", "-s", metavar="STR", default="init,boot,data,text")
2172 | parser.add_argument("--pstack-bottom", "-p", metavar="ADDR", default="$600")
2173 | parser.add_argument("--pstack-size", "-S", metavar="NUM", default=256, type=int)
2174 | parser.add_argument("file", metavar="FILE")
2175 | args = parser.parse_args()
2176 |
2177 | boot_params = {"pstack_bottom": args.pstack_bottom,
2178 | "pstack_size": args.pstack_size & 0xff}
2179 |
2180 | with open(args.file, "rt") as f:
2181 | text = f.read()
2182 |
2183 | f = Forth(args.sections.split(","))
2184 |
2185 | try:
2186 | f.parse_input(Input(boot_text % boot_params), "foco65(boot_text)")
2187 | f.parse_input(Input(basewords_text), "foco65(basewords_text)")
2188 | f.parse_input(Input(text), args.file)
2189 | print(f.generate_output())
2190 | except (ParseError, StackUnderflow, StackNotEmpty) as e:
2191 | sys.stderr.write("error: %s\n" % str(e))
2192 | sys.exit(1)
2193 |
--------------------------------------------------------------------------------