fam 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 80a521187255f27791f45b197a66fa69160a5d37cb2d6599a59d7001fd2b86ff
4
+ data.tar.gz: 25f69d87e3148bc616964bcc15287c5b6fd6406548251a730a5b48abaddef081
5
+ SHA512:
6
+ metadata.gz: 570f5e1160997bdcd2f8e9aa15d81068cef6b5bc94ec2483715baa3d25b5af90840375d2ef546a793aad728ce8e89a93224a70fc71ebf5af657759160de5bb78
7
+ data.tar.gz: 7675fc3184c4210a21f47cc2a35991a40faccbd1bd9f1953ab2d8a8ca3da258511b305d45b73306b1c9a3a0223d5a1353439bd64a0c82d99222eff798d699e61
data/DOC.md ADDED
File without changes
data/LICENSE ADDED
@@ -0,0 +1,339 @@
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 2, June 1991
3
+
4
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6
+ Everyone is permitted to copy and distribute verbatim copies
7
+ of this license document, but changing it is not allowed.
8
+
9
+ Preamble
10
+
11
+ The licenses for most software are designed to take away your
12
+ freedom to share and change it. By contrast, the GNU General Public
13
+ License is intended to guarantee your freedom to share and change free
14
+ software--to make sure the software is free for all its users. This
15
+ General Public License applies to most of the Free Software
16
+ Foundation's software and to any other program whose authors commit to
17
+ using it. (Some other Free Software Foundation software is covered by
18
+ the GNU Lesser General Public License instead.) You can apply it to
19
+ your programs, too.
20
+
21
+ When we speak of free software, we are referring to freedom, not
22
+ price. Our General Public Licenses are designed to make sure that you
23
+ have the freedom to distribute copies of free software (and charge for
24
+ this service if you wish), that you receive source code or can get it
25
+ if you want it, that you can change the software or use pieces of it
26
+ in new free programs; and that you know you can do these things.
27
+
28
+ To protect your rights, we need to make restrictions that forbid
29
+ anyone to deny you these rights or to ask you to surrender the rights.
30
+ These restrictions translate to certain responsibilities for you if you
31
+ distribute copies of the software, or if you modify it.
32
+
33
+ For example, if you distribute copies of such a program, whether
34
+ gratis or for a fee, you must give the recipients all the rights that
35
+ you have. You must make sure that they, too, receive or can get the
36
+ source code. And you must show them these terms so they know their
37
+ rights.
38
+
39
+ We protect your rights with two steps: (1) copyright the software, and
40
+ (2) offer you this license which gives you legal permission to copy,
41
+ distribute and/or modify the software.
42
+
43
+ Also, for each author's protection and ours, we want to make certain
44
+ that everyone understands that there is no warranty for this free
45
+ software. If the software is modified by someone else and passed on, we
46
+ want its recipients to know that what they have is not the original, so
47
+ that any problems introduced by others will not reflect on the original
48
+ authors' reputations.
49
+
50
+ Finally, any free program is threatened constantly by software
51
+ patents. We wish to avoid the danger that redistributors of a free
52
+ program will individually obtain patent licenses, in effect making the
53
+ program proprietary. To prevent this, we have made it clear that any
54
+ patent must be licensed for everyone's free use or not licensed at all.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ GNU GENERAL PUBLIC LICENSE
60
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61
+
62
+ 0. This License applies to any program or other work which contains
63
+ a notice placed by the copyright holder saying it may be distributed
64
+ under the terms of this General Public License. The "Program", below,
65
+ refers to any such program or work, and a "work based on the Program"
66
+ means either the Program or any derivative work under copyright law:
67
+ that is to say, a work containing the Program or a portion of it,
68
+ either verbatim or with modifications and/or translated into another
69
+ language. (Hereinafter, translation is included without limitation in
70
+ the term "modification".) Each licensee is addressed as "you".
71
+
72
+ Activities other than copying, distribution and modification are not
73
+ covered by this License; they are outside its scope. The act of
74
+ running the Program is not restricted, and the output from the Program
75
+ is covered only if its contents constitute a work based on the
76
+ Program (independent of having been made by running the Program).
77
+ Whether that is true depends on what the Program does.
78
+
79
+ 1. You may copy and distribute verbatim copies of the Program's
80
+ source code as you receive it, in any medium, provided that you
81
+ conspicuously and appropriately publish on each copy an appropriate
82
+ copyright notice and disclaimer of warranty; keep intact all the
83
+ notices that refer to this License and to the absence of any warranty;
84
+ and give any other recipients of the Program a copy of this License
85
+ along with the Program.
86
+
87
+ You may charge a fee for the physical act of transferring a copy, and
88
+ you may at your option offer warranty protection in exchange for a fee.
89
+
90
+ 2. You may modify your copy or copies of the Program or any portion
91
+ of it, thus forming a work based on the Program, and copy and
92
+ distribute such modifications or work under the terms of Section 1
93
+ above, provided that you also meet all of these conditions:
94
+
95
+ a) You must cause the modified files to carry prominent notices
96
+ stating that you changed the files and the date of any change.
97
+
98
+ b) You must cause any work that you distribute or publish, that in
99
+ whole or in part contains or is derived from the Program or any
100
+ part thereof, to be licensed as a whole at no charge to all third
101
+ parties under the terms of this License.
102
+
103
+ c) If the modified program normally reads commands interactively
104
+ when run, you must cause it, when started running for such
105
+ interactive use in the most ordinary way, to print or display an
106
+ announcement including an appropriate copyright notice and a
107
+ notice that there is no warranty (or else, saying that you provide
108
+ a warranty) and that users may redistribute the program under
109
+ these conditions, and telling the user how to view a copy of this
110
+ License. (Exception: if the Program itself is interactive but
111
+ does not normally print such an announcement, your work based on
112
+ the Program is not required to print an announcement.)
113
+
114
+ These requirements apply to the modified work as a whole. If
115
+ identifiable sections of that work are not derived from the Program,
116
+ and can be reasonably considered independent and separate works in
117
+ themselves, then this License, and its terms, do not apply to those
118
+ sections when you distribute them as separate works. But when you
119
+ distribute the same sections as part of a whole which is a work based
120
+ on the Program, the distribution of the whole must be on the terms of
121
+ this License, whose permissions for other licensees extend to the
122
+ entire whole, and thus to each and every part regardless of who wrote it.
123
+
124
+ Thus, it is not the intent of this section to claim rights or contest
125
+ your rights to work written entirely by you; rather, the intent is to
126
+ exercise the right to control the distribution of derivative or
127
+ collective works based on the Program.
128
+
129
+ In addition, mere aggregation of another work not based on the Program
130
+ with the Program (or with a work based on the Program) on a volume of
131
+ a storage or distribution medium does not bring the other work under
132
+ the scope of this License.
133
+
134
+ 3. You may copy and distribute the Program (or a work based on it,
135
+ under Section 2) in object code or executable form under the terms of
136
+ Sections 1 and 2 above provided that you also do one of the following:
137
+
138
+ a) Accompany it with the complete corresponding machine-readable
139
+ source code, which must be distributed under the terms of Sections
140
+ 1 and 2 above on a medium customarily used for software interchange; or,
141
+
142
+ b) Accompany it with a written offer, valid for at least three
143
+ years, to give any third party, for a charge no more than your
144
+ cost of physically performing source distribution, a complete
145
+ machine-readable copy of the corresponding source code, to be
146
+ distributed under the terms of Sections 1 and 2 above on a medium
147
+ customarily used for software interchange; or,
148
+
149
+ c) Accompany it with the information you received as to the offer
150
+ to distribute corresponding source code. (This alternative is
151
+ allowed only for noncommercial distribution and only if you
152
+ received the program in object code or executable form with such
153
+ an offer, in accord with Subsection b above.)
154
+
155
+ The source code for a work means the preferred form of the work for
156
+ making modifications to it. For an executable work, complete source
157
+ code means all the source code for all modules it contains, plus any
158
+ associated interface definition files, plus the scripts used to
159
+ control compilation and installation of the executable. However, as a
160
+ special exception, the source code distributed need not include
161
+ anything that is normally distributed (in either source or binary
162
+ form) with the major components (compiler, kernel, and so on) of the
163
+ operating system on which the executable runs, unless that component
164
+ itself accompanies the executable.
165
+
166
+ If distribution of executable or object code is made by offering
167
+ access to copy from a designated place, then offering equivalent
168
+ access to copy the source code from the same place counts as
169
+ distribution of the source code, even though third parties are not
170
+ compelled to copy the source along with the object code.
171
+
172
+ 4. You may not copy, modify, sublicense, or distribute the Program
173
+ except as expressly provided under this License. Any attempt
174
+ otherwise to copy, modify, sublicense or distribute the Program is
175
+ void, and will automatically terminate your rights under this License.
176
+ However, parties who have received copies, or rights, from you under
177
+ this License will not have their licenses terminated so long as such
178
+ parties remain in full compliance.
179
+
180
+ 5. You are not required to accept this License, since you have not
181
+ signed it. However, nothing else grants you permission to modify or
182
+ distribute the Program or its derivative works. These actions are
183
+ prohibited by law if you do not accept this License. Therefore, by
184
+ modifying or distributing the Program (or any work based on the
185
+ Program), you indicate your acceptance of this License to do so, and
186
+ all its terms and conditions for copying, distributing or modifying
187
+ the Program or works based on it.
188
+
189
+ 6. Each time you redistribute the Program (or any work based on the
190
+ Program), the recipient automatically receives a license from the
191
+ original licensor to copy, distribute or modify the Program subject to
192
+ these terms and conditions. You may not impose any further
193
+ restrictions on the recipients' exercise of the rights granted herein.
194
+ You are not responsible for enforcing compliance by third parties to
195
+ this License.
196
+
197
+ 7. If, as a consequence of a court judgment or allegation of patent
198
+ infringement or for any other reason (not limited to patent issues),
199
+ conditions are imposed on you (whether by court order, agreement or
200
+ otherwise) that contradict the conditions of this License, they do not
201
+ excuse you from the conditions of this License. If you cannot
202
+ distribute so as to satisfy simultaneously your obligations under this
203
+ License and any other pertinent obligations, then as a consequence you
204
+ may not distribute the Program at all. For example, if a patent
205
+ license would not permit royalty-free redistribution of the Program by
206
+ all those who receive copies directly or indirectly through you, then
207
+ the only way you could satisfy both it and this License would be to
208
+ refrain entirely from distribution of the Program.
209
+
210
+ If any portion of this section is held invalid or unenforceable under
211
+ any particular circumstance, the balance of the section is intended to
212
+ apply and the section as a whole is intended to apply in other
213
+ circumstances.
214
+
215
+ It is not the purpose of this section to induce you to infringe any
216
+ patents or other property right claims or to contest validity of any
217
+ such claims; this section has the sole purpose of protecting the
218
+ integrity of the free software distribution system, which is
219
+ implemented by public license practices. Many people have made
220
+ generous contributions to the wide range of software distributed
221
+ through that system in reliance on consistent application of that
222
+ system; it is up to the author/donor to decide if he or she is willing
223
+ to distribute software through any other system and a licensee cannot
224
+ impose that choice.
225
+
226
+ This section is intended to make thoroughly clear what is believed to
227
+ be a consequence of the rest of this License.
228
+
229
+ 8. If the distribution and/or use of the Program is restricted in
230
+ certain countries either by patents or by copyrighted interfaces, the
231
+ original copyright holder who places the Program under this License
232
+ may add an explicit geographical distribution limitation excluding
233
+ those countries, so that distribution is permitted only in or among
234
+ countries not thus excluded. In such case, this License incorporates
235
+ the limitation as if written in the body of this License.
236
+
237
+ 9. The Free Software Foundation may publish revised and/or new versions
238
+ of the General Public License from time to time. Such new versions will
239
+ be similar in spirit to the present version, but may differ in detail to
240
+ address new problems or concerns.
241
+
242
+ Each version is given a distinguishing version number. If the Program
243
+ specifies a version number of this License which applies to it and "any
244
+ later version", you have the option of following the terms and conditions
245
+ either of that version or of any later version published by the Free
246
+ Software Foundation. If the Program does not specify a version number of
247
+ this License, you may choose any version ever published by the Free Software
248
+ Foundation.
249
+
250
+ 10. If you wish to incorporate parts of the Program into other free
251
+ programs whose distribution conditions are different, write to the author
252
+ to ask for permission. For software which is copyrighted by the Free
253
+ Software Foundation, write to the Free Software Foundation; we sometimes
254
+ make exceptions for this. Our decision will be guided by the two goals
255
+ of preserving the free status of all derivatives of our free software and
256
+ of promoting the sharing and reuse of software generally.
257
+
258
+ NO WARRANTY
259
+
260
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261
+ FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262
+ OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263
+ PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264
+ OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266
+ TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267
+ PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268
+ REPAIR OR CORRECTION.
269
+
270
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272
+ REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273
+ INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274
+ OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275
+ TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276
+ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277
+ PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278
+ POSSIBILITY OF SUCH DAMAGES.
279
+
280
+ END OF TERMS AND CONDITIONS
281
+
282
+ How to Apply These Terms to Your New Programs
283
+
284
+ If you develop a new program, and you want it to be of the greatest
285
+ possible use to the public, the best way to achieve this is to make it
286
+ free software which everyone can redistribute and change under these terms.
287
+
288
+ To do so, attach the following notices to the program. It is safest
289
+ to attach them to the start of each source file to most effectively
290
+ convey the exclusion of warranty; and each file should have at least
291
+ the "copyright" line and a pointer to where the full notice is found.
292
+
293
+ <one line to give the program's name and a brief idea of what it does.>
294
+ Copyright (C) <year> <name of author>
295
+
296
+ This program is free software; you can redistribute it and/or modify
297
+ it under the terms of the GNU General Public License as published by
298
+ the Free Software Foundation; either version 2 of the License, or
299
+ (at your option) any later version.
300
+
301
+ This program is distributed in the hope that it will be useful,
302
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
303
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304
+ GNU General Public License for more details.
305
+
306
+ You should have received a copy of the GNU General Public License along
307
+ with this program; if not, write to the Free Software Foundation, Inc.,
308
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309
+
310
+ Also add information on how to contact you by electronic and paper mail.
311
+
312
+ If the program is interactive, make it output a short notice like this
313
+ when it starts in an interactive mode:
314
+
315
+ Gnomovision version 69, Copyright (C) year name of author
316
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317
+ This is free software, and you are welcome to redistribute it
318
+ under certain conditions; type `show c' for details.
319
+
320
+ The hypothetical commands `show w' and `show c' should show the appropriate
321
+ parts of the General Public License. Of course, the commands you use may
322
+ be called something other than `show w' and `show c'; they could even be
323
+ mouse-clicks or menu items--whatever suits your program.
324
+
325
+ You should also get your employer (if you work as a programmer) or your
326
+ school, if any, to sign a "copyright disclaimer" for the program, if
327
+ necessary. Here is a sample; alter the names:
328
+
329
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
331
+
332
+ <signature of Ty Coon>, 1 April 1989
333
+ Ty Coon, President of Vice
334
+
335
+ This General Public License does not permit incorporating your program into
336
+ proprietary programs. If your program is a subroutine library, you may
337
+ consider it more useful to permit linking proprietary applications with the
338
+ library. If this is what you want to do, use the GNU Lesser General
339
+ Public License instead of this License.
@@ -0,0 +1,2 @@
1
+ # FAM
2
+ A very Fake Assembly(ish-language) Machine thingy...
data/bin/fam ADDED
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'fam'
4
+
5
+ $VERBOSE = false
6
+ $CLOCK = $VERBOSE ? 20 : Float::INFINITY
7
+
8
+ file_names = ARGV.select { |file| file.include? '.fam'}
9
+ lexed = FAM::Syntax::Lexer.lex file_names[-1]
10
+ puts lexed if $VERBOSE
11
+ puts if $VERBOSE
12
+
13
+ parsed = FAM::Syntax::Parser.parse lexed.tokens
14
+ AST = parsed.ast
15
+ pp AST if $VERBOSE
16
+
17
+ MEM = FAM::Machine::RAM.new '100B'
18
+ CPU = FAM::Machine::CPU.new MEM
19
+ puts if $VERBOSE
20
+
21
+ CPU.run AST do |pc|
22
+ puts "Program counter: #{pc}" if $VERBOSE
23
+ end
@@ -0,0 +1,16 @@
1
+ class Object
2
+ def base_name
3
+ self.class.name.split(/(\:\:)|(\.)/)[-1]
4
+ end
5
+ end
6
+
7
+ module FAM
8
+ VERSIONS = { :major => 0, :minor => 0, :tiny => 1 }
9
+
10
+ def self.version *args
11
+ VERSIONS.flatten.select.with_index { |val, i| i.odd? }.join '.'
12
+ end
13
+ end
14
+
15
+ Dir["#{File.dirname __FILE__}/fam/*.rb"].each { |f| require f }
16
+ Dir["#{File.dirname __FILE__}/fam/**/*.rb"].each { |f| require f }
@@ -0,0 +1,35 @@
1
+ class String
2
+ def black; "\e[30m#{self}\e[0m"; end
3
+ def red; "\e[31m#{self}\e[0m"; end
4
+ def green; "\e[32m#{self}\e[0m"; end
5
+ def brown; "\e[33m#{self}\e[0m"; end
6
+ def blue; "\e[34m#{self}\e[0m"; end
7
+ def magenta; "\e[35m#{self}\e[0m"; end
8
+ def cyan; "\e[36m#{self}\e[0m"; end
9
+ def gray; "\e[37m#{self}\e[0m"; end
10
+
11
+ def bg_black; "\e[40m#{self}\e[0m"; end
12
+ def bg_red; "\e[41m#{self}\e[0m"; end
13
+ def bg_green; "\e[42m#{self}\e[0m"; end
14
+ def bg_brown; "\e[43m#{self}\e[0m"; end
15
+ def bg_blue; "\e[44m#{self}\e[0m"; end
16
+ def bg_magenta; "\e[45m#{self}\e[0m"; end
17
+ def bg_cyan; "\e[46m#{self}\e[0m"; end
18
+ def bg_gray; "\e[47m#{self}\e[0m"; end
19
+
20
+ def bold; "\e[1m#{self}\e[22m"; end
21
+ def italic; "\e[3m#{self}\e[23m"; end
22
+ def underline; "\e[4m#{self}\e[24m"; end
23
+ def blink; "\e[5m#{self}\e[25m"; end
24
+ def reverse_color; "\e[7m#{self}\e[27m"; end
25
+ end
26
+
27
+ def UnexpectedToken token
28
+ puts "\nUnexpected token type: '#{token.type}', at line: #{token.line}:#{token.col}".red.bold
29
+ exit 1
30
+ end
31
+
32
+ def ExpectedToken name, token
33
+ puts "\nExpected token: '#{name}', instead got: '#{token}' at line: #{token.line}:#{token.col}".red.bold
34
+ exit 1
35
+ end
@@ -0,0 +1,174 @@
1
+ require_relative 'memory'
2
+ require_relative '../syntax/ast'
3
+
4
+ module FAM::Machine
5
+ class CPU
6
+ include FAM::Syntax
7
+ attr_reader :ram, :registers, :memory_aliases, :labels
8
+
9
+ def initialize ram
10
+ @ram = ram
11
+ @registers = {
12
+ :ACC => 0,
13
+ :DAT => 0,
14
+ :PC => 0
15
+ }
16
+ @memory_aliases = Hash.new
17
+
18
+ @labels = Hash.new
19
+ @last_jump = nil
20
+ @back_index = 0
21
+ end
22
+
23
+ def self.quick_run ram, parsed, &block
24
+ cpu = self.new ram
25
+ if block_given?
26
+ cpu.run parsed, &block
27
+ else
28
+ cpu.run parsed
29
+ end
30
+ cpu
31
+ end
32
+
33
+ def run parsed, &block
34
+ @block = block if block_given?
35
+ @parsed = parsed
36
+
37
+ @tree_index = -1
38
+ while @tree_index < parsed.tree.size
39
+ @tree_index += 1
40
+
41
+ sleep 1.0 / $CLOCK
42
+ node = parsed[@tree_index]
43
+ status = execute node
44
+ break if status == :STOP
45
+ next if status == :SKIP
46
+ puts "\n _BACK: #{parsed[@back_index].inspect}\n " if $VERBOSE
47
+ display if $VERBOSE
48
+ end
49
+ end
50
+
51
+ def execute node
52
+ @registers[:PC] = @tree_index
53
+ @block.call @registers[:PC] unless @block.nil?
54
+ case node
55
+ when AST::LabelNode
56
+ @last_jump = node.label
57
+ @labels[node.label] = @tree_index
58
+ @back_index = @tree_index
59
+ when AST::HaltNode
60
+ return :STOP
61
+ when AST::GotoNode
62
+ back = @tree_index
63
+ if @labels.include? node.ident.name
64
+ @tree_index = @labels[node.ident.name]
65
+ elsif node.ident.name == '_BACK'
66
+ @tree_index = @back_index
67
+ return :PASS
68
+ else # Search ahead
69
+ found = false
70
+ @parsed.tree.each.with_index do |top_node, i|
71
+ @tree_index = i
72
+ if top_node.base_name == 'LabelNode'
73
+ (found = true; break) if top_node.label == node.ident.name
74
+ end
75
+ end
76
+ abort "Label: `#{node.label.name}` was not found. Execution HALTED!".red.bold unless found
77
+ end
78
+ @last_jump = node.ident.name
79
+ @back_index = back
80
+ when AST::StoreNode
81
+ mem_index = case node.to
82
+ when AST::AddressNode
83
+ node.to.address
84
+ when AST::IdentNode
85
+ @memory_aliases[node.to.name]
86
+ end
87
+ @ram[mem_index] = get_value node, node.value
88
+ when AST::LoadNode
89
+ @registers[node.register.register.to_sym] = get_value node, node.value
90
+ when AST::DataNode
91
+ initial_value = get_value node, node.initial
92
+ free_index = nil
93
+ @ram.array.each.with_index { |value, i| if value == NULL then free_index = i; break; end }
94
+ abort ("No free memory, allocation of `#{node.name.name}`,\n" +
95
+ "cannot happen! Execution HALTED!").red.bold if free_index.nil?
96
+ @memory_aliases[node.name.name] = free_index
97
+ @ram[free_index] = initial_value
98
+ when AST::InNode
99
+ @registers[node.register.register.to_sym] = cpu_input
100
+ when AST::OutNode, AST::AsciiNode
101
+ value = get_value node, node.value
102
+ cpu_output value, (node.base_name == 'OutNode' ? :PLAIN : :ASCII)
103
+ when AST::SubNode, AST::AddNode, AST::MulNode, AST::DivNode, AST::ModNode
104
+ value = get_value node, node.value
105
+ ExpectedNode 'REGISTER', node.to unless node.to.base_name == 'RegisterNode'
106
+ if node.base_name[/Sub|Add/]
107
+ @registers[node.to.register.to_sym] += value * (node.base_name == 'AddNode' ? 1 : -1)
108
+ elsif node.base_name == 'Mul'
109
+ @registers[node.to.register.to_sym] *= value
110
+ elsif node.base_name == 'Div'
111
+ @registers[node.to.register.to_sym] /= value
112
+ else
113
+ @registers[node.to.register.to_sym] %= value
114
+ end
115
+ when AST::EqualNode, AST::MoreNode, AST::LessNode
116
+ left = get_value node, node.left
117
+ right = get_value node, node.right
118
+ if node.base_name == 'EqualNode' ? (left == right) : (node.base_name == 'MoreNode' ? (left > right) : (left < right))
119
+ execute node.valid
120
+ else
121
+ execute node.invalid
122
+ end
123
+ else
124
+ print "\n" * (@ram.to_s.count("\n") + 1) if $VERBOSE
125
+ abort ("Unknown Node: `#{node.base_name}`,\nparser generated an " +
126
+ "unexecutable/unknown node... Execution HALTED!").red.bold
127
+ end
128
+ return :PASS
129
+ end
130
+
131
+ def display
132
+ puts "#{@ram.to_s}"
133
+ puts
134
+ @registers.each { |key, value| print "#{key} => #{value}\n" }
135
+ puts
136
+ # print "\033[F" * (self.to_s.count("\n"))
137
+ # print "\n" * (@ram.to_s.count("\n") + 1)
138
+ end
139
+
140
+ def cpu_input # Ment to be changed
141
+ print 'INPUT: '
142
+ $stdin.gets.to_i
143
+ end
144
+
145
+ def cpu_output out, ascii=:PLAIN # Ment to be changed
146
+ puts "OUTPUT: #{ascii != :PLAIN ? out.chr : out }"
147
+ end
148
+
149
+ private def get_value super_value, value_node
150
+ case value_node
151
+ when AST::NumericNode
152
+ value_node.numeric
153
+ when AST::AddressNode
154
+ @ram[value_node.address]
155
+ when AST::RegisterNode
156
+ @registers[value_node.register.to_sym]
157
+ when AST::IdentNode
158
+ @ram[@memory_aliases[value_node.name]]
159
+ else
160
+ AST::UnexpectedNode super_value, value_node
161
+ end
162
+ end
163
+
164
+ private def UnexpectedNode node, sub_node
165
+ print "\n" * (@ram.to_s.count("\n") + 1) if $VERBOSE
166
+ abort ("Unexpected Node, you've given `#{sub_node.base_name}` AST::to Node: `#{node.base_name}`?").red.bold
167
+ end
168
+
169
+ private def ExpectedNode expect, got
170
+ print "\n" * (@ram.to_s.count("\n") + 1) if $VERBOSE
171
+ abort ("Expected: `#{expect}`, but insted got: `#{got}`").red.bold
172
+ end
173
+ end
174
+ end
@@ -0,0 +1,59 @@
1
+ SIZES = {
2
+ :B => 1e0, :kB => 1e3, :MB => 1e6,
3
+ :GB => 1e9, :TB => 1e12
4
+ }
5
+
6
+ class NULL < NilClass
7
+ def to_s *args; 'NULL'; end
8
+ end
9
+
10
+ module FAM::Machine
11
+ class RAM
12
+ attr_accessor :array
13
+
14
+ def initialize size
15
+ alloc = 0
16
+ case size
17
+ when Numeric
18
+ alloc = size
19
+ when String
20
+ suffix = size.upcase[/[A-Z]+/]
21
+ suffix = 'kB' if suffix == 'KB'
22
+ unless suffix.empty?
23
+ alloc = size[/[0-9]+/].to_i * SIZES[suffix.to_sym]
24
+ else
25
+ alloc = size.to_i
26
+ end
27
+ else
28
+ abort 'ERROR: `size` argument must be a string or numeric!'.red
29
+ end
30
+ @array = Array.new(alloc, NULL)
31
+ end
32
+
33
+ def [](i)
34
+ @array[i]
35
+ end
36
+
37
+ def []=(i, value)
38
+ abort 'ERROR: Only integers can be stored in memory!' unless i.class == Integer
39
+ @array[i] = value
40
+ end
41
+
42
+ def to_s
43
+ result = String.new
44
+ width = %x{ tput cols }.to_i
45
+ i = j = 0
46
+ loop do
47
+ break if j >= @array.size
48
+ line = String.new
49
+ i = j
50
+ while line.size < width && j <= @array.size
51
+ line << "#{@array[j].to_s.rjust 4, '0'}XXXXX" # `X` padding
52
+ j += 1
53
+ end
54
+ result << "| #{@array[i..j].map {|e| e.to_s.rjust 4, '0'}.join ' | '} |\n"
55
+ end
56
+ result
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,141 @@
1
+ module FAM::Syntax::AST
2
+ class Node
3
+ def to_s
4
+ "<#{self.class.name.split('Node')[0]} :: NODE>"
5
+ end
6
+ end
7
+
8
+ class SyntaxTree
9
+ attr_reader :tree
10
+
11
+ def initialize
12
+ @tree = []
13
+ end
14
+
15
+ def <<(node)
16
+ @tree << node
17
+ end
18
+
19
+ def [](i)
20
+ @tree[i]
21
+ end
22
+ end
23
+
24
+ class LabelNode < Node
25
+ attr_accessor :label
26
+ def initialize label
27
+ @label = label.name[0..-2]
28
+ end
29
+ end
30
+
31
+ class GotoNode < Node
32
+ attr_accessor :ident
33
+ def initialize ident
34
+ @ident = ident
35
+ end
36
+ end
37
+
38
+ class HaltNode < Node
39
+ attr_accessor :status
40
+ def initialize status
41
+ @status = status
42
+ end
43
+ end
44
+
45
+ class StoreNode < Node
46
+ attr_accessor :value, :to
47
+ def initialize value, to
48
+ @value = value
49
+ @to = to
50
+ end
51
+ end
52
+
53
+ class LoadNode < Node
54
+ attr_accessor :value, :register
55
+ def initialize value, register
56
+ @value = value
57
+ @register = register
58
+ end
59
+ end
60
+
61
+ class DataNode < Node
62
+ attr_accessor :name, :initial
63
+ def initialize name, initial
64
+ @name = name
65
+ @initial = initial
66
+ end
67
+ end
68
+
69
+ class InNode < Node
70
+ attr_accessor :register
71
+ def initialize reg
72
+ @register = reg
73
+ end
74
+ end
75
+
76
+ class OutputNode < Node
77
+ attr_accessor :value
78
+ def initialize value
79
+ @value = value
80
+ end
81
+ end
82
+
83
+ class OutNode < OutputNode; end
84
+ class AsciiNode < OutputNode; end
85
+
86
+ class ArithmeticNode < Node
87
+ attr_accessor :value, :to
88
+ def initialize value, to
89
+ @value = value
90
+ @to = to
91
+ end
92
+ end
93
+
94
+ class AddNode < ArithmeticNode; end
95
+ class SubNode < ArithmeticNode; end
96
+ class MulNode < ArithmeticNode; end
97
+ class DivNode < ArithmeticNode; end
98
+ class ModNode < ArithmeticNode; end
99
+
100
+ class ConditionNode < Node
101
+ attr_accessor :left, :right, :valid, :invalid
102
+ def initialize left, right, valid, invalid
103
+ @left = left
104
+ @right = right
105
+ @valid = valid
106
+ @invalid = invalid
107
+ end
108
+ end
109
+
110
+ class EqualNode < ConditionNode; end
111
+ class MoreNode < ConditionNode; end
112
+ class LessNode < ConditionNode; end
113
+
114
+ class IdentNode
115
+ attr_accessor :name
116
+ def initialize name
117
+ @name = name.name
118
+ end
119
+ end
120
+
121
+ class AddressNode < Node
122
+ attr_accessor :address
123
+ def initialize address
124
+ @address = address.name[1..-1].to_i
125
+ end
126
+ end
127
+
128
+ class NumericNode < Node
129
+ attr_accessor :numeric
130
+ def initialize numeric
131
+ @numeric = Integer numeric.name
132
+ end
133
+ end
134
+
135
+ class RegisterNode < Node
136
+ attr_accessor :register
137
+ def initialize register
138
+ @register = register.name[1..-1]
139
+ end
140
+ end
141
+ end
@@ -0,0 +1,123 @@
1
+ require_relative 'tokens'
2
+
3
+ module FAM::Syntax
4
+ class Lexer
5
+ attr_reader :tokens
6
+
7
+ def initialize io_file
8
+ @file_name = io_file
9
+ @tokens = TokenStream.new
10
+ end
11
+
12
+ def self.lex io_file
13
+ obj = self.new io_file
14
+ obj.lexer
15
+ obj
16
+ end
17
+
18
+ def lexer
19
+ puts "Lexing..." if $VERBOSE
20
+ @raw = File.read @file_name
21
+ @raw << EOF unless @raw[-1] == EOF
22
+
23
+ loc = {:line => 1, :col => 1}
24
+ i = 0
25
+ while i < @raw.size
26
+ unread = @raw[i..-1]
27
+
28
+ if ["\n", ";"].include? unread[0]
29
+ loc[:line] += 1
30
+ loc[:col] = 1
31
+ @tokens << tokenize(unread[0], :TERMINATOR, loc)
32
+ i += 1
33
+
34
+ elsif unread[0] == ' '
35
+ loc[:col] += 1
36
+ i += 1
37
+
38
+ elsif unread[/\A{{/, 0] || unread[/\A!/, 0]
39
+ comment = unread[/\A{{/, 0] || unread[/\A!/, 0]
40
+ comment_start = loc.clone
41
+ j = 0
42
+ if comment == '!'
43
+ until unread[j] == "\n" || unread[j] == EOF
44
+ i += 1
45
+ j += 1
46
+ end
47
+ j -= 1
48
+ else
49
+ until unread[j..j+1] == '}}' || unread[j] == EOF
50
+ i += 1
51
+ loc[:col] += 1
52
+ if unread[j] == "\n"
53
+ loc[:line] += 1
54
+ loc[:col] = 1
55
+ end
56
+ j += 1
57
+ end
58
+ j += 1
59
+ end
60
+ @tokens << tokenize(unread[0..j], :COMMENT, comment_start)
61
+
62
+ elsif label = unread[/\A[a-zA-Z_]([a-zA-Z0-9_]+)?:/, 0]
63
+ @tokens << tokenize(label, :LABEL, loc)
64
+ loc[:col] += label.size
65
+ i += label.size
66
+
67
+ elsif numeric = unread[/\A(\-|\+)??((?=0x|0b)([0-9A-Za-z]+)|([0-9]+((e(\-|\+)?[0-9]+)?)))/, 0]
68
+ @tokens << tokenize(numeric, :NUMERIC, loc)
69
+ loc[:col] += numeric.size
70
+ i += numeric.size
71
+
72
+ elsif address = unread[/\A@[0-9]+/, 0]
73
+ @tokens << tokenize(address, :ADDRESS, loc)
74
+ loc[:col] += address.size
75
+ i += address.size
76
+
77
+ elsif register = unread[/\A&[a-zA-Z0-9]+/, 0]
78
+ @tokens << tokenize(register, :REGISTER, loc)
79
+ loc[:col] += register.size
80
+ i += register.size
81
+
82
+ elsif ident = unread[/\A[A-Za-z_]([A-Za-z0-9_]+)?/, 0]
83
+ if Tokens::OPCODES.include? ident
84
+ @tokens << tokenize(ident, :OPCODE, loc)
85
+ else
86
+ @tokens << tokenize(ident, :IDENT, loc)
87
+ end
88
+
89
+ loc[:col] += ident.size
90
+ i += ident.size
91
+
92
+
93
+ elsif op = unread[/\A[(\+)(\-)(\:)(\|)]/, 0]
94
+ @tokens << tokenize(op, :OPERATOR, loc)
95
+ loc[:col] += op.size
96
+ i += op.size
97
+
98
+ else
99
+ i += 1
100
+ loc[:col] += 1
101
+ end
102
+
103
+ end
104
+
105
+ @tokens
106
+ end
107
+
108
+ private def tokenize name, type, location={:line => 'IMPLICIT TOKEN', :col => 'IMPLICIT TOKEN'}
109
+ TokenObject.new type, name, location
110
+ end
111
+
112
+ def to_s
113
+ result = "LEXED TOKENS:\n"
114
+ @tokens.tokens.each do |token|
115
+ widest = @tokens.tokens.map(&:type).max
116
+ result << " :#{token.type}#{' ' * (widest.size - token.type.size)} :: " +
117
+ "[#{token.line.to_s.rjust 3}:#{token.col.to_s.ljust 3}] " +
118
+ "{ #{token.name.inspect.size > 10 ? (token.name[0..7] + '...').inspect : token.name.inspect} }\n"
119
+ end
120
+ result
121
+ end
122
+ end
123
+ end
@@ -0,0 +1,139 @@
1
+ require_relative 'lexer'
2
+
3
+ module FAM::Syntax
4
+ class Parser < Lexer
5
+ include AST
6
+ attr_reader :ast
7
+
8
+ def initialize token_stream
9
+ @tokens = token_stream
10
+ @ast = SyntaxTree.new
11
+ end
12
+
13
+ def self.parse stream
14
+ obj = self.new stream
15
+ obj.parser
16
+ obj
17
+ end
18
+
19
+ def parser
20
+ @tokens.tokens.each do |t|
21
+ break if @tokens.current.nil?
22
+ puts "Parsing: (#{@tokens.current.to_s.brown})" if $VERBOSE
23
+ node = parse_token @tokens.current
24
+ puts "Parsed to: (#{node.nil? ? 'NOT PARSED'.red : node.to_s.gray})" if $VERBOSE
25
+ @ast << node unless node.nil?
26
+ @tokens.next
27
+ puts if $VERBOSE
28
+ end
29
+ end
30
+
31
+ def parse_token t
32
+ case t.type
33
+ when :LABEL
34
+ return LabelNode.new @tokens.current
35
+ when :OPCODE
36
+ case t.name
37
+ when 'HALT'
38
+ exit_status = NumericNode.new tokenize('0000', :NUMERIC)
39
+ exit_status = parse_token @tokens.next if @tokens.peek.type == @NUMERIC
40
+ return HaltNode.new exit_status
41
+ when 'GOTO'
42
+ label = parse_token @tokens.next
43
+ UnexpectedToken @tokens.current unless @tokens.current.type == :IDENT
44
+ return GotoNode.new label
45
+ when 'STORE'
46
+ value = parse_token @tokens.next
47
+ @tokens.next
48
+ ExpectedToken 'TOKEN<:OPERATOR>(`:`)', @tokens.current unless @tokens.current.name == ':'
49
+ to = parse_token @tokens.next
50
+ ExpectedToken 'ADDRESS or IDENT', @tokens.current unless @tokens.current.type == :ADDRESS || @tokens.current.type == :IDENT
51
+ return StoreNode.new value, to
52
+ when 'LOAD'
53
+ value = parse_token @tokens.next
54
+ @tokens.next
55
+ ExpectedToken 'TOKEN<:OPERATOR>(`:`)', @tokens.current unless @tokens.current.name == ':'
56
+ reg = parse_token @tokens.next
57
+ ExpectedToken 'REGISTER', @tokens.current unless @tokens.current.type == :REGISTER
58
+ return LoadNode.new value, reg
59
+ when 'DATA'
60
+ name = parse_token @tokens.next
61
+ UnexpectedValue name unless @tokens.current.type == :IDENT
62
+ if @tokens.peek.name == ':'
63
+ @tokens.next
64
+ value = parse_token @tokens.next
65
+ else
66
+ value = NumericNode.new tokenize('0000', :NUMERIC)
67
+ end
68
+ return DataNode.new name, value
69
+ when 'ADD', 'SUB', 'MUL', 'DIV', 'MOD'
70
+ value = parse_token @tokens.next
71
+ @tokens.next
72
+ ExpectedToken 'TOKEN<:OPERATOR>(`:`)', @tokens.current unless @tokens.current.name == ':'
73
+ to = parse_token @tokens.next
74
+
75
+ return case t.name
76
+ when 'ADD'
77
+ AddNode.new value, to
78
+ when 'SUB'
79
+ SubNode.new value, to
80
+ when 'MUL'
81
+ MulNode.new value, to
82
+ when 'DIV'
83
+ DivNode.new value, to
84
+ when 'MOD'
85
+ ModNode.new value, to
86
+ end
87
+ when 'EQUAL', 'MORE', 'LESS'
88
+ parse_condition
89
+ when 'IN'
90
+ reg = parse_token @tokens.next
91
+ ExpectedToken 'TOKEN<:REGISTER>', @tokens.current unless @tokens.current.type == :REGISTER
92
+ return InNode.new reg
93
+ when 'OUT', 'ASCII'
94
+ value = parse_token @tokens.next
95
+ if t.name == 'OUT'
96
+ return OutNode.new value
97
+ else
98
+ return AsciiNode.new value
99
+ end
100
+ else
101
+ abort "Unknown/unparsable OPCODE: `#{t.name}` at [#{t.line}:#{t.col}]!".red.bold
102
+ end
103
+ when :ADDRESS
104
+ return AddressNode.new @tokens.current
105
+ when :NUMERIC
106
+ return NumericNode.new @tokens.current
107
+ when :REGISTER
108
+ return RegisterNode.new @tokens.current
109
+ when :IDENT
110
+ return IdentNode.new @tokens.current
111
+ else
112
+ return nil
113
+ end
114
+ end
115
+
116
+ private def parse_condition
117
+ condition_type = @tokens.current.name
118
+ left = parse_token @tokens.next
119
+ @tokens.next
120
+ ExpectedToken 'TOKEN<:OPERATOR>(`:`)', @tokens.current unless @tokens.current.name == ':'
121
+ right = parse_token @tokens.next
122
+
123
+ @tokens.next until @tokens.current.name == '|'
124
+ valid = parse_token @tokens.next
125
+ @tokens.next until @tokens.current.name == '|'
126
+ invalid = parse_token @tokens.next
127
+
128
+ params = [left, right, valid, invalid]
129
+ case condition_type
130
+ when 'EQUAL'
131
+ EqualNode.new(*params)
132
+ when 'MORE'
133
+ MoreNode.new(*params)
134
+ when 'LESS'
135
+ LessNode.new(*params)
136
+ end
137
+ end
138
+ end
139
+ end
@@ -0,0 +1,106 @@
1
+ EOF = "\0"
2
+
3
+ module FAM::Syntax
4
+ class TokenStream
5
+ attr_accessor :tokens
6
+ attr_accessor :index
7
+
8
+ def initialize
9
+ @tokens = []
10
+ @index = 0
11
+ end
12
+
13
+ def <<(token)
14
+ @tokens << token
15
+ end
16
+
17
+ def [](i)
18
+ @tokens[i]
19
+ end
20
+
21
+ def current
22
+ @tokens[@index]
23
+ end
24
+
25
+ def next
26
+ @index += 1
27
+ @tokens[@index]
28
+ end
29
+
30
+ def back
31
+ @index -= 1
32
+ @tokens[@index]
33
+ end
34
+
35
+ def peek i=1
36
+ @tokens[i + @index]
37
+ end
38
+
39
+ def previous i=1
40
+ @tokens[@index - i]
41
+ end
42
+
43
+ def to_s
44
+ @tokens.to_s
45
+ end
46
+ end
47
+
48
+ class TokenObject
49
+ attr_reader :type, :name, :line, :col
50
+
51
+ def initialize type, name, location
52
+ @type = type
53
+ @name = name
54
+ @line = location[:line]
55
+ @col = location[:col]
56
+ end
57
+
58
+ def to_s
59
+ value = @name == "\n" ? '\n' : @name
60
+ "TOKEN<:#{@type}>(`#{value}`)"
61
+ end
62
+
63
+ alias :pretty_inspect :to_s
64
+ end
65
+
66
+ module Tokens
67
+ TYPES = [
68
+ :OPCODE,
69
+ :OPERAND,
70
+ :NUMERTIC,
71
+ :REGISTER,
72
+ :ADDRESS,
73
+ :LABEL,
74
+ :IDENT
75
+ ].map(&:to_s)
76
+
77
+ OPERATORS = [
78
+ :'+',
79
+ :'-',
80
+ :'|',
81
+ :':'
82
+ ].map(&:to_s)
83
+
84
+ OPCODES = [
85
+ :HALT,
86
+ :ALIAS,
87
+ :DATA,
88
+ :STORE,
89
+ :LOAD,
90
+ :GOTO,
91
+ :DATA,
92
+ :EQUAL,
93
+ :MORE,
94
+ :LESS,
95
+ :ADD,
96
+ :SUB,
97
+ :MUL,
98
+ :DIV,
99
+ :MOD,
100
+ :SLEEP,
101
+ :IN,
102
+ :OUT,
103
+ :ASCII
104
+ ].map(&:to_s)
105
+ end
106
+ end
metadata ADDED
@@ -0,0 +1,56 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: fam
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Demonstrandum
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2018-03-13 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: A very watered down language ment to look like an assembly language.
14
+ email: knutsen@jetspace.co
15
+ executables:
16
+ - fam
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - DOC.md
21
+ - LICENSE
22
+ - README.md
23
+ - bin/fam
24
+ - lib/fam.rb
25
+ - lib/fam/error.rb
26
+ - lib/fam/machine/cpu.rb
27
+ - lib/fam/machine/memory.rb
28
+ - lib/fam/syntax/ast.rb
29
+ - lib/fam/syntax/lexer.rb
30
+ - lib/fam/syntax/parser.rb
31
+ - lib/fam/syntax/tokens.rb
32
+ homepage: https://github.com/Demonstrandum/FAM
33
+ licenses:
34
+ - GPL-3.0
35
+ metadata: {}
36
+ post_install_message:
37
+ rdoc_options: []
38
+ require_paths:
39
+ - lib
40
+ required_ruby_version: !ruby/object:Gem::Requirement
41
+ requirements:
42
+ - - ">="
43
+ - !ruby/object:Gem::Version
44
+ version: 2.0.0
45
+ required_rubygems_version: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '0'
50
+ requirements: []
51
+ rubyforge_project:
52
+ rubygems_version: 2.7.4
53
+ signing_key:
54
+ specification_version: 4
55
+ summary: Fake Assembly(ish) Machine
56
+ test_files: []