Initial commit

This commit is contained in:
drmortalwombat 2021-09-06 18:34:52 +02:00
commit 7af458832b
65 changed files with 22968 additions and 0 deletions

2
.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto

337
.gitignore vendored Normal file
View File

@ -0,0 +1,337 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
*.asm
*.map
*.prg

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

2
README.md Normal file
View File

@ -0,0 +1,2 @@
# oscar64
Optimizing small space C Compiler Assembler and Runtime for C64

23
autotest/arraytest.c Normal file
View File

@ -0,0 +1,23 @@
#include <assert.h>
#include <stdio.h>
int sum(int * a, int s)
{
int sum = 0;
for(int i=0; i<s; i++)
{
sum += a[i];
}
return sum;
}
int main(void)
{
int a[100];
for(int i=0; i<100; i++)
{
a[i] = i % 10;
}
assert(sum(a, 100) == 450);
return 0;
}

23
autotest/arraytestfloat.c Normal file
View File

@ -0,0 +1,23 @@
#include <assert.h>
#include <stdio.h>
float sum(float * a, int s)
{
float sum = 0;
for(int i=0; i<s; i++)
{
sum += a[i];
}
return sum;
}
int main(void)
{
float a[100];
for(int i=0; i<100; i++)
{
a[i] = i % 10;
}
assert(sum(a, 100) == 450);
return 0;
}

33
autotest/autotest.bat Normal file
View File

@ -0,0 +1,33 @@
@echo off
..\release\oscar64 -i=../include -rt=../include/crt.c -e stdlibtest.c
if %errorlevel% neq 0 goto :error
..\release\oscar64 -i=../include -rt=../include/crt.c -e testint16.c
if %errorlevel% neq 0 goto :error
..\release\oscar64 -i=../include -rt=../include/crt.c -e recursiontest.c
if %errorlevel% neq 0 goto :error
..\release\oscar64 -i=../include -rt=../include/crt.c -e strcmptest.c
if %errorlevel% neq 0 goto :error
..\release\oscar64 -i=../include -rt=../include/crt.c -e arraytest.c
if %errorlevel% neq 0 goto :error
..\release\oscar64 -i=../include -rt=../include/crt.c -e arraytestfloat.c
if %errorlevel% neq 0 goto :error
..\release\oscar64 -i=../include -rt=../include/crt.c -e optiontest.c
if %errorlevel% neq 0 goto :error
..\release\oscar64 -i=../include -rt=../include/crt.c -e floatcmptest.c
if %errorlevel% neq 0 goto :error
..\release\oscar64 -i=../include -rt=../include/crt.c -e floatmultest.c
if %errorlevel% neq 0 goto :error
exit /b 0
:error
echo Failed with error #%errorlevel%.
exit /b %errorlevel%

65
autotest/floatcmptest.c Normal file
View File

@ -0,0 +1,65 @@
#include <stdio.h>
#include <assert.h>
bool feq(float a, float b)
{
return a == b;
}
bool flt(float a, float b)
{
return a < b;
}
bool fgt(float a, float b)
{
return a > b;
}
void cmpflt(float a, float b, bool eq, bool lt, bool gt)
{
assert(feq(a, b) == eq);
assert(flt(a, b) == lt);
assert(fgt(a, b) == gt);
}
int main(void)
{
cmpflt( 0.0, 1.0, false, true, false);
cmpflt( 0.0, -1.0, false, false, true);
cmpflt( 1.0, 0.0, false, false, true);
cmpflt(-1.0, 0.0, false, true, false);
cmpflt( 1.0, 1.0, true, false, false);
cmpflt( 1.0, 2.0, false, true, false);
cmpflt( 2.0, 1.0, false, false, true);
cmpflt(-1.0, -1.0, true, false, false);
cmpflt(-1.0, -2.0, false, false, true);
cmpflt(-2.0, -1.0, false, true, false);
cmpflt( 1.0, -1.0, false, false, true);
cmpflt( 1.0, -2.0, false, false, true);
cmpflt( 2.0, -1.0, false, false, true);
cmpflt(-1.0, 1.0, false, true, false);
cmpflt(-1.0, 2.0, false, true, false);
cmpflt(-2.0, 1.0, false, true, false);
cmpflt( 0.0, 0.0, true, false, false);
cmpflt(-0.0, 0.0, true, false, false);
cmpflt( 0.0, -0.0, true, false, false);
cmpflt(-0.0, -0.0, true, false, false);
cmpflt( 1.0, 1.000001, false, true, false);
cmpflt( 1.000001, 1.0, false, false, true);
cmpflt( 1.000001, 1.000001, true, false, false);
cmpflt( -1.0, -1.000001, false, false, true);
cmpflt( -1.000001, -1.0, false, true, false);
cmpflt( -1.000001, -1.000001, true, false, false);
return 0;
}

30
autotest/floatmultest.c Normal file
View File

@ -0,0 +1,30 @@
#include <assert.h>
#include <stdio.h>
#include <math.h>
float c = 1.25;
float d = 1.0001;
int main(void)
{
int i;
float a = 0.0;
for(i=0; i<50; i++)
{
// printf("%d %f %f %f\n", i, i * c, a, i * c - a);
assert(i * c == a);
a += c;
}
a = d;
for(i=1; i<50; i++)
{
// printf("%d %f %f %f\n", i, i * d, a, fabs(i * d - a) / i);
assert(fabs(i * d - a) < i * 1.0e-6);
a += d;
}
return 0;
}

15
autotest/optiontest.c Normal file
View File

@ -0,0 +1,15 @@
#include <stdio.h>
#include <assert.h>
int option(bool a, int b, int c)
{
return a ? b : c;
}
int main(void)
{
assert(option(true, 1, 2) == 1);
assert(option(false, 1, 2) == 2);
return 0;
}

89
autotest/recursiontest.c Normal file
View File

@ -0,0 +1,89 @@
#include <assert.h>
#include <stdlib.h>
#include <string.h>
int fib(int a)
{
if (a < 2)
return a;
else
return fib(a - 1) + fib(a - 2);
}
struct Node
{
char value;
Node * left, * right;
};
typedef Node * NodePtr;
NodePtr newnode(void)
{
return (NodePtr)malloc(sizeof(Node));
}
Node * insert(Node * tree, char v)
{
if (tree)
{
if (v < tree->value)
{
tree->left = insert(tree->left, v);
}
else
{
tree->right = insert(tree->right, v);
}
}
else
{
tree = newnode();
tree->value = v;
tree->left = nullptr;
tree->right = nullptr;
}
return tree;
}
char * collect(Node * tree, char * p)
{
if (tree)
{
p = collect(tree->left, p);
*p++= tree->value;
p = collect(tree->right, p);
}
return p;
}
void btest(void)
{
const char * str = "HELLO WORLD";
char buff[20];
int i = 0;
Node * tree = nullptr;
while (str[i])
{
tree = insert(tree, str[i]);
i++;
}
collect(tree, buff)[0] = 0;
assert(strcmp(buff, " DEHLLLOORW") == 0);
}
int main(void)
{
assert(fib(23) == 28657);
btest();
return 0;
}

73
autotest/stdlibtest.c Normal file
View File

@ -0,0 +1,73 @@
// stdlibtest
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <limits.h>
void numcheck(int n)
{
char buffer[10];
itoa(n, buffer, 10);
int m = atoi(buffer);
printf("%d : %s -> %d\n", n, buffer, m);
if (m != n)
exit(-1);
}
void numchecks(void)
{
numcheck(0);
numcheck(-1);
numcheck(1);
numcheck(12345);
numcheck(-12345);
numcheck(INT_MIN);
numcheck(INT_MAX);
}
void heapcheck(void)
{
void * memp[100];
int mems[100];
int n, k, s, i;
for(n=0; n<100; n++)
{
s = rand() % 100 + 3;
mems[n] = s;
memp[n] = malloc(s);
memset(memp[n], n, s);
}
for(k=0; k<1000; k++)
{
n = rand() % 100;
int s = mems[n];
char * p = memp[n];
for(i=0; i<s; i++)
{
if (p[i] != n)
{
printf("MemError %d at %d:%d != %d\n", k, i, n, p[i]);
exit(-2);
}
}
free(memp[n]);
s = rand() % 100 + 3;
mems[n] = s;
memp[n] = malloc(s);
memset(memp[n], n, s);
}
}
int main(void)
{
numchecks();
heapcheck();
return 0;
}

11
autotest/strcmptest.c Normal file
View File

@ -0,0 +1,11 @@
#include <string.h>
#include <assert.h>
int main(void)
{
assert(strcmp("ABCD", "ABCD") == 0);
assert(strcmp("ABCE", "ABCD") == 1);
assert(strcmp("ABCD", "ABCE") == -1);
return 0;
}

121
autotest/testint16.c Normal file
View File

@ -0,0 +1,121 @@
#include <assert.h>
void testmuli(int a, int b, int ab)
{
assert (a * b == ab);
}
void testdivi(int a, int b, int ab)
{
assert (a / b == ab);
}
void shltesti(int a, int b, int ab)
{
assert (a << b == ab);
}
void shrtesti(int a, int b, int ab)
{
assert (a >> b == ab);
}
int sieve(int size)
{
bool sieve[1000];
for(int i=0; i<size; i+=2)
{
sieve[i] = false;
sieve[i+1] = true;
}
sieve[2] = true;
for (int i = 3; i * i < size;)
{
int j = i * i;
while (j < size)
{
sieve[j] = false;
j += 2 * i;
}
do {i++;} while (i < size && !sieve[i]);
}
int num = 0;
for(int i=0; i<size; i++)
{
if (sieve[i])
num++;
}
return num;
}
int main(void)
{
testmuli(0, 0, 0);
testmuli(1, 0, 0);
testmuli(0, 1, 0);
testmuli( 1, 1, 1);
testmuli(-1, 1, -1);
testmuli(-1, -1, 1);
testmuli( 1, -1, -1);
testmuli(5, 5, 25);
testmuli( 127, 255, 32385);
testmuli(-127, 255, -32385);
testmuli( 127, -255, -32385);
testmuli(-127, -255, 32385);
testdivi( 1, 1, 1);
testdivi(-1, 1, -1);
testdivi( 1, -1, -1);
testdivi(-1, -1, 1);
testdivi( 11, 4, 2);
testdivi(-11, 4, -2);
testdivi( 11, -4, -2);
testdivi(-11, -4, 2);
shltesti( 17, 1, 34);
shltesti(-17, 1, -34);
shltesti( 1700, 1, 3400);
shltesti(-1700, 1, -3400);
shrtesti( 34, 1, 17);
shrtesti(-34, 1, -17);
shrtesti( 3400, 1, 1700);
shrtesti(-3400, 1, -1700);
shrtesti( -1, 15, -1);
shrtesti(32767, 15, 0);
shrtesti( -1, 14, -1);
shrtesti(32767, 14, 1);
shltesti( -1, 14, -16384);
shltesti( 1, 14, 16384);
assert(sieve(200) == 47);
assert(sieve(1000) == 169);
int a = 0, b = 0;
for(int i=0; i<1000; i++)
{
assert( 17 * i == a);
assert(-17 * i == b);
a += 17;
b -= 17;
}
int c = 0, d = 0;
for(int i=0; i<17; i++)
{
assert( 1000 * i == c);
assert(-1000 * i == d);
c += 1000;
d -= 1000;
}
return 0;
}

8
include/assert.c Normal file
View File

@ -0,0 +1,8 @@
#include "assert.h"
#include <stdlib.h>
void assert(bool b)
{
if (!b)
exit(-1);
}

8
include/assert.h Normal file
View File

@ -0,0 +1,8 @@
#ifndef ASSERT_H
#define ASSERT_H
void assert(bool b);
#pragma compile("assert.c")
#endif

2486
include/crt.c Normal file

File diff suppressed because it is too large Load Diff

153
include/crt.h Normal file
View File

@ -0,0 +1,153 @@
#ifndef CRT_H
#define CRT_H
#define tmpy 0x02
#define tmp 0x03
#define ip 0x19
#define accu 0x1b
#define addr 0x1f
#define sp 0x23
#define fp 0x25
#define sregs 0x43
#define regs 0x53
enum ByteCode
{
BC_NOP,
BC_EXIT,
BC_CONST_P8,
BC_CONST_N8,
BC_CONST_16,
BC_CONST_32,
BC_LOAD_REG_16,
BC_STORE_REG_16,
BC_ADDR_REG,
BC_LOAD_REG_32,
BC_STORE_REG_32,
BC_LOAD_ABS_U8,
BC_LOAD_ABS_I8,
BC_LOAD_ABS_16,
BC_LOAD_ABS_32,
BC_STORE_ABS_8,
BC_STORE_ABS_16,
BC_STORE_ABS_32,
BC_LEA_ABS,
BC_LOAD_LOCAL_U8,
BC_LOAD_LOCAL_I8,
BC_LOAD_LOCAL_16,
BC_LOAD_LOCAL_32,
BC_STORE_LOCAL_8,
BC_STORE_LOCAL_16,
BC_STORE_LOCAL_32,
BC_LEA_LOCAL,
BC_STORE_FRAME_8,
BC_STORE_FRAME_16,
BC_STORE_FRAME_32,
BC_LOAD_ADDR_U8,
BC_LOAD_ADDR_I8,
BC_LOAD_ADDR_16,
BC_LOAD_ADDR_32,
BC_STORE_ADDR_8,
BC_STORE_ADDR_16,
BC_STORE_ADDR_32,
BC_BINOP_ADDR_16,
BC_BINOP_SUBR_16,
BC_BINOP_ANDR_16,
BC_BINOP_ORR_16,
BC_BINOP_XORR_16,
BC_BINOP_MULR_16,
BC_BINOP_DIVR_U16,
BC_BINOP_MODR_U16,
BC_BINOP_DIVR_I16,
BC_BINOP_MODR_I16,
BC_BINOP_SHLR_16,
BC_BINOP_SHRR_U16,
BC_BINOP_SHRR_I16,
BC_BINOP_ADDI_16,
BC_BINOP_SUBI_16,
BC_BINOP_ANDI_16,
BC_BINOP_ORI_16,
BC_BINOP_MULI8_16,
BC_BINOP_SHLI_16,
BC_BINOP_SHRI_U16,
BC_BINOP_SHRI_I16,
BC_BINOP_CMPUR_16,
BC_BINOP_CMPSR_16,
BC_BINOP_CMPUI_16,
BC_BINOP_CMPSI_16,
BC_OP_NEGATE_16,
BC_OP_INVERT_16,
BC_BINOP_ADD_F32,
BC_BINOP_SUB_F32,
BC_BINOP_MUL_F32,
BC_BINOP_DIV_F32,
BC_BINOP_CMP_F32,
BC_OP_NEGATE_F32,
BC_OP_ABS_F32,
BC_OP_FLOOR_F32,
BC_OP_CEIL_F32,
BC_CONV_U16_F32,
BC_CONV_I16_F32,
BC_CONV_F32_U16,
BC_CONV_F32_I16,
BC_JUMPS,
BC_BRANCHS_EQ,
BC_BRANCHS_NE,
BC_BRANCHS_GT,
BC_BRANCHS_GE,
BC_BRANCHS_LT,
BC_BRANCHS_LE,
BC_JUMPF,
BC_BRANCHF_EQ,
BC_BRANCHF_NE,
BC_BRANCHF_GT,
BC_BRANCHF_GE,
BC_BRANCHF_LT,
BC_BRANCHF_LE,
BC_SET_EQ,
BC_SET_NE,
BC_SET_GT,
BC_SET_GE,
BC_SET_LT,
BC_SET_LE,
BC_ENTER,
BC_RETURN,
BC_CALL,
BC_PUSH_FRAME,
BC_POP_FRAME,
BC_JSR,
BC_COPY,
BC_COPY_LONG
};
#pragma compile("crt.c")
#endif

18
include/limits.h Normal file
View File

@ -0,0 +1,18 @@
#ifndef LIMITS_H
#define LIMITS_H
#define CHAR_BIT 8
#define SCHAR_MIN -128
#define SCHAR_MAX 127
#define UCHAR_MAX 255
#define CHAR_MIN SCHAR_MIN
#define CHAR_MAX SCHAR_MAX
#define INT_MIN -32767
#define INT_MAX 32767
#define UINT_MAX 65535
#endif

201
include/math.c Normal file
View File

@ -0,0 +1,201 @@
#include "math.h"
#include "stdio.h"
float cos(float f)
{
return sin(f + 0.5 * PI);
}
#define F_SIN_1 6.283168
#define F_SIN_2 0.053878661
#define F_SIN_3 -42.5385038
#define F_SIN_4 9.23583223
#define F_SIN_5 55.7310503
float sin(float f)
{
float g = fabs(f);
float m = f < 0.0 ? -1.0 : 1.0;
g *= 0.5 / PI;
g -= floor(g);
if (g >= 0.5)
{
m = -m;
g -= 0.5;
}
if (g >= 0.25)
g = 0.5 - g;
float s = F_SIN_5;
s *= g; s += F_SIN_4;
s *= g; s += F_SIN_3;
s *= g; s += F_SIN_2;
s *= g; s += F_SIN_1;
s *= g;
return s * m;
}
float tan(float f)
{
return sin(f) / cos(f);
}
float acos(float f)
{
return atan2(sqrt(1.0 - f * f), f);
}
float asin(float f)
{
return atan2(f, sqrt(1.0 - f * f));
}
float atan(float f)
{
return atan2(f, 1.0);
}
#define F_ATAN_0 -6.435678E-5
#define F_ATAN_1 0.999648382
#define F_ATAN_2 0.018278903
#define F_ATAN_3 -0.444599298
#define F_ATAN_4 0.263177486
#define F_ATAN_5 -0.051078392
float atan2(float p, float q)
{
int quad = 0;
if (p < 0)
{
quad |= 4;
p = -p;
}
if (q < 0)
{
quad |= 2;
q = -q;
}
float g;
if (p > q)
{
g = q / p;
quad |= 1;
}
else
{
g = p / q;
}
float s = F_ATAN_5;
s *= g; s += F_ATAN_4;
s *= g; s += F_ATAN_3;
s *= g; s += F_ATAN_2;
s *= g; s += F_ATAN_1;
s *= g; s += F_ATAN_0
if (quad & 1)
s = 0.5 * PI - s;
if (quad & 2)
s = PI - s;
if (quad & 4)
s = -s;
return s;
}
#define F_EXP_0 1.0000003
#define F_EXP_1 0.693147059
#define F_EXP_2 0.240173099
#define F_EXP_3 0.055816392
#define F_EXP_4 0.008965036
#define F_EXP_5 0.001898429
float exp(float f)
{
f *= 1.442695041;
float ff = floor(f), g = f - ff;
int fi = (int)ff;
float fx = 0;
((int*)&fx)[1] = (fi + 0x7f) << 7;
float s = F_EXP_5;
s *= g; s += F_EXP_4;
s *= g; s += F_EXP_3;
s *= g; s += F_EXP_2;
s *= g; s += F_EXP_1;
s *= g; s += F_EXP_0
return s * fx;
}
#define F_LOG_0 -2.79423993
#define F_LOG_1 5.05984692
#define F_LOG_2 -3.49247429
#define F_LOG_3 1.58181193
#define F_LOG_4 -0.396821126
#define F_LOG_5 0.041845518
float log(float f)
{
if (f == 0.0)
return 1.0;
float fx = f;
int ei = ((int*)&fx)[1];
int ex = (ei >> 7) - 0x7f;
((int*)&fx)[1] = (ei & 0x007f) | 0x3f80;
float g = fx;
float fex = ex;
float s = F_LOG_5;
s *= g; s += F_LOG_4;
s *= g; s += F_LOG_3;
s *= g; s += F_LOG_2;
s *= g; s += F_LOG_1;
s *= g; s += F_LOG_0
return (fex + s) * 0.6931471806;
}
float log10(float f)
{
return log(f) * 0.4342944819;
}
float pow(float p, float q)
{
return exp(p * log(q));
}
float sqrt(float f)
{
if (f >= 0)
{
float fx = f;
int ex = (((int*)&fx)[1] >> 7) - 0x7f;
ex /= 2;
((int*)&fx)[1] = (ex + 0x7f) << 7;
float fq = fx;
fq = 0.5 * (fq + f / fq);
fq = 0.5 * (fq + f / fq);
fq = 0.5 * (fq + f / fq);
fq = 0.5 * (fq + f / fq);
return fq;
}
else
return 0.0;
}

34
include/math.h Normal file
View File

@ -0,0 +1,34 @@
#ifndef MATH_H
#define MATH_H
#define PI 3.141592653
float fabs(float f);
float floor(float f);
float ceil(float f);
float cos(float f);
float sin(float f);
float tan(float f);
float acos(float f);
float asin(float f);
float atan(float f);
float atan2(float p, float q);
float exp(float f);
float log(float f);
float log10(float f);
float pow(float p, float q);
float sqrt(float f);
#pragma intrinsic(fabs)
#pragma intrinsic(floor)
#pragma intrinsic(ceil)
#pragma compile("math.c")
#endif

165
include/stdio.c Normal file
View File

@ -0,0 +1,165 @@
#include "stdio.h"
#include <stdlib.h>
void putchar(char c)
{
__asm {
ldy #2
lda (fp), y
jsr 0xffd2
}
}
char getchar(void)
{
__asm {
jsr 0xffcf
sta 0x1b
lda #0
sta 0x1c
}
}
void puts(const char * str)
{
__asm {
ldy #2
lda (fp), y
sta 0x02
iny
lda (fp), y
sta 0x03
ldy #0
lda (0x02), y
beq done
loop:
jsr 0xffd2
inc 0x02
bne next
inc 0x03
next:
ldy #0
lda (0x02), y
bne loop
done:
}
}
char * gets(char * str)
{
__asm {
ldy #2
lda (fp), y
sta 0x02
iny
lda (fp), y
sta 0x03
loop:
jsr 0xffcf
ldy #0
cmp #13
beq done
sta (0x02), y
inc 0x02
bne loop
inc 0x03
bne loop
done:
lda #0
sta (0x02), y
}
return str;
}
void printf(const char * fmt, ...)
{
const char * p = fmt;
char c, buff[14];
int * fps = (int *)&fmt + 1;
while (c = *p++)
{
if (c == '%')
{
c = *p++;
if (c == 'd')
{
itoa(*fps++, buff, 10);
puts(buff);
}
else if (c == 'x')
{
utoa(*fps++, buff, 16);
puts(buff);
}
else if (c == 'f')
{
ftoa(*(float *)fps, buff);
puts(buff);
fps ++;
fps ++;
}
else if (c == 's')
{
puts((char *)*fps++);
}
else if (c)
{
putchar(c);
}
}
else
putchar(c);
}
}
int sprintf(char * str, const char * fmt, ...)
{
const char * p = fmt, * d = str;
char c;
int * fps = (int *)&fmt + 1;
while (c = *p++)
{
if (c == '%')
{
c = *p++;
if (c == 'd')
{
itoa(*fps++, d, 10);
while (*d)
d++;
}
else if (c == 'x')
{
utoa(*fps++, d, 16);
while (*d)
d++;
}
else if (c == 'f')
{
ftoa(*(float *)fps, d);
fps += 2;
while (*d)
d++;
}
else if (c == 's')
{
char * s = (char *)*fps++;
while (c = *s++)
*d++ = c;
}
else if (c)
{
*d++ = c;
}
}
else
*d++ = c;
}
*d = 0;
return d - str;
}

21
include/stdio.h Normal file
View File

@ -0,0 +1,21 @@
#ifndef STDIO_H
#define STDIO_H
#include <stdlib.h>
void putchar(char c);
char getchar(void);
void puts(const char * str);
char * gets(char * str);
void printf(const char * fmt, ...);
int sprintf(char * str, const char * fmt, ...);
#pragma compile("stdio.c")
#endif

307
include/stdlib.c Normal file
View File

@ -0,0 +1,307 @@
#include "stdlib.h"
#include "string.h"
#include "stdio.h"
void itoa(int n, char * s, int radix)
{
bool neg = n < 0;
if (neg)
{
n = - n;
}
int i = 0;
do {
int d = n % radix;
if (d < 10)
d += '0';
else
d += 'A' - 10;
s[i++] = d;
} while ((n /= radix) > 0);
if (neg)
{
s[i++] = '-';
}
s[i] = 0;
int j = 0;
while (j + 1 < i)
{
char c = s[j];
s[j++] = s[--i];
s[i] = c;
}
}
void utoa(unsigned int n, char * s, unsigned int radix)
{
int i = 0;
do {
unsigned int d = n % radix;
if (d < 10)
d += '0';
else
d += 'A' - 10;
s[i++] = d;
} while ((n /= radix) > 0);
s[i] = 0;
int j = 0;
while (j + 1 < i)
{
char c = s[j];
s[j++] = s[--i];
s[i] = c;
}
}
void ftoa(float f, char * s)
{
if (f < 0.0)
{
f = -f;
*s++ = '-';
}
int digits = 0;
while (f >= 1000.0)
{
f /= 1000;
digits += 3;
}
if (f != 0.0)
{
while (f < 1.0)
{
f *= 1000;
digits -= 3;
}
while (f >= 10.0)
{
f /= 10;
digits ++;
}
f += 0.0000005;
if (f >= 10.0)
{
f /= 10.0;
digits ++;
}
}
int exp = 0;
if (digits < 0)
{
exp = digits;
digits = 0;
}
else if (digits > 6)
{
exp = digits;
digits = 0;
}
for(int i=0; i<7; i++)
{
int c = (int)f;
f -= (float)c;
f *= 10.0;
*s++ = c + '0';
if (i == digits)
*s++ = '.';
}
if (exp)
{
*s++ = 'E';
if (exp < 0)
{
*s++ = '-';
exp = -exp;
}
else
*s++ = '+';
if (exp >= 10)
{
*s++ = exp / 10 + '0';
exp %= 10;
}
*s++ = exp + '0';
}
*s++= 0;
}
int atoi(const char * s)
{
char c;
while ((c = *s++) <= ' ')
if (!c) return 0;
bool neg = false;
if (c == '-')
{
neg = true;
c = *s++;
}
else if (c == '+')
c = *s++;
int v = 0;
while (c >= '0' && c <= '9')
{
v = v * 10 + (c - '0');
c = *s++;
}
if (neg)
v = -v;
return v;
}
void exit(int status)
{
__asm {
ldy #status
lda (fp), y
sta accu + 0
iny
lda (fp), y
sta accu + 1
pla
pla
}
}
struct Heap {
unsigned int size;
Heap * next;
} * freeHeap;
bool freeHeapInit = false;
void * malloc(unsigned int size)
{
size = (size + 7) & ~3;
if (!freeHeapInit)
{
freeHeap = (Heap *)*(int *)0x2d;
freeHeap->next = nullptr;
freeHeap->size = 0xa000 - 4096 - (int)freeHeap;
freeHeapInit = true;
}
Heap * pheap = nullptr, * heap = freeHeap;
while (heap)
{
if (size <= heap->size)
{
if (size == heap->size)
{
if (pheap)
pheap->next = heap->next;
else
freeHeap = heap->next;
}
else
{
Heap * nheap = (Heap *)((int)heap + size);
nheap->size = heap->size - size;
nheap->next = heap->next;
if (pheap)
pheap->next = nheap;
else
freeHeap = nheap;
heap->size = size;
}
return (void *)((int)heap + 2);
}
pheap = heap;
heap = heap->next;
}
return nullptr;
}
void free(void * ptr)
{
if (!ptr)
return;
Heap * fheap = (Heap *)((int)ptr - 2);
Heap * eheap = (Heap *)((int)ptr - 2 + fheap->size);
if (freeHeap)
{
if (eheap == freeHeap)
{
fheap->size += freeHeap->size;
fheap->next = freeHeap->next;
freeHeap = fheap;
}
else if (eheap < freeHeap)
{
fheap->next = freeHeap;
freeHeap = fheap;
}
else
{
Heap * pheap = freeHeap;
while (pheap->next && pheap->next < fheap)
pheap = pheap->next;
Heap * nheap = (Heap *)((int)pheap + pheap->size);
if (nheap == fheap)
{
pheap->size += fheap->size;
if (pheap->next == eheap)
{
pheap->size += pheap->next->size;
pheap->next = pheap->next->next;
}
}
else if (pheap->next == eheap)
{
fheap->next = pheap->next->next;
fheap->size += pheap->next->size;
pheap->next = fheap;
}
else
{
fheap->next = pheap->next;
pheap->next = fheap;
}
}
}
else
{
freeHeap = fheap;
freeHeap->next = nullptr;
}
}
void * calloc(int num, int size)
{
size *= num;
void * p = malloc(size);
if (p)
memclr(p, size);
return p;
}
unsigned seed = 31232;
unsigned int rand(void)
{
seed ^= seed << 7;
seed ^= seed >> 9;
seed ^= seed << 8;
return seed;
}

24
include/stdlib.h Normal file
View File

@ -0,0 +1,24 @@
#ifndef STDLIB_H
#define STDLIB_H
void itoa(int n, char * s, int radix);
void utoa(unsigned int n, char * s, unsigned int radix);
void ftoa(float f, char * s);
int atoi(const char * s);
void exit(int status);
void * malloc(unsigned int size);
void free(void * ptr);
void * calloc(int num, int size);
unsigned int rand(void);
#pragma compile("stdlib.c")
#endif

148
include/string.c Normal file
View File

@ -0,0 +1,148 @@
#include "string.h"
char * strcpy(char * dst, const char * src)
{
char * d = dst;
const char * s = src;
do {} while (*d++ = *s++);
return dst;
}
int strcmp(const char * ptr1, const char * ptr2)
{
const char * p = ptr1, * q = ptr2;
char c, d;
while ((c = *p++) == (d = *q++))
{
if (!c)
return 0;
}
if (c < d)
return -1;
else
return 1;
}
int strlen(const char * str)
{
const char * s = str;
int i = 0;
while (s[i])
i++;
return i;
}
char * strcat(char * dst, const char * src)
{
char * d = dst;
const char * s = src;
while (*d)
d++;
do {} while (*d++ = *s++);
return dst;
}
void * memset(void * dst, int value, int size)
{
__asm
{
ldy #dst
lda (fp), y
sta $1f
iny
lda (fp), y
sta $20
ldy #size
lda (fp), y
sta $1b
iny
lda (fp), y
sta $1c
ldy #value
lda (fp), y
ldx $1c
beq _w1
ldy #0
_loop1:
sta ($1f), y
iny
bne _loop1
inc $20
dex
bne _loop1
_w1:
ldy $1b
beq _w2
_loop2:
dey
sta ($1f), y
bne _loop2
_w2:
}
return dst;
}
void * memclr(void * dst, int size)
{
char * d = dst;
while (size--)
*d++ = 0;
return dst;
}
void * memcpy(void * dst, const void * src, int size)
{
char * d = dst, * s = src;
while (size--)
*d++ = *s++;
return dst;
}
void * memmove(void * dst, const void * src, int size)
{
char * d = dst, * s = src;
if (d < s)
{
while (size--)
*d++ = *s++;
}
else if (d > s)
{
d += size;
s += size;
while (size--)
*--d = *--s;
}
return dst;
}
int memcmp(const void * ptr1, const void * ptr2, int size)
{
char * p = ptr1, * q = ptr2;
char c, d;
while (size--)
{
c = *p++;
d = *q++;
if (c < d)
return -1;
else if (c > d)
return 1;
}
return 0;
}

25
include/string.h Normal file
View File

@ -0,0 +1,25 @@
#ifndef STRING_H
#define STRING_H
char * strcpy(char * dst, const char * src);
int strcmp(const char * ptr1, const char * ptr2);
int strlen(const char * str);
char * strcat(char * dst, const char * src);
void * memclr(void * dst, int size);
void * memset(void * dst, int value, int size);
void * memcpy(void * dst, const void * src, int size);
int memcmp(const void * ptr1, const void * ptr2, int size);
void * memmove(void * dst, const void * src, int size);
#pragma compile("string.c")
#endif

31
oscar64.sln Normal file
View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31624.102
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "oscar64", "oscar64\oscar64.vcxproj", "{1DBC623E-6109-41FE-B1BB-9B43FC984F7D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1DBC623E-6109-41FE-B1BB-9B43FC984F7D}.Debug|x64.ActiveCfg = Debug|x64
{1DBC623E-6109-41FE-B1BB-9B43FC984F7D}.Debug|x64.Build.0 = Debug|x64
{1DBC623E-6109-41FE-B1BB-9B43FC984F7D}.Debug|x86.ActiveCfg = Debug|Win32
{1DBC623E-6109-41FE-B1BB-9B43FC984F7D}.Debug|x86.Build.0 = Debug|Win32
{1DBC623E-6109-41FE-B1BB-9B43FC984F7D}.Release|x64.ActiveCfg = Release|x64
{1DBC623E-6109-41FE-B1BB-9B43FC984F7D}.Release|x64.Build.0 = Release|x64
{1DBC623E-6109-41FE-B1BB-9B43FC984F7D}.Release|x86.ActiveCfg = Release|Win32
{1DBC623E-6109-41FE-B1BB-9B43FC984F7D}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C5E1AB04-FB65-4F70-B2F1-3787E7F84A41}
EndGlobalSection
EndGlobal

250
oscar64/Array.h Normal file
View File

@ -0,0 +1,250 @@
#pragma once
#include <assert.h>
template <class T>
class DynamicArray
{
protected:
int size, range;
T* array;
void Grow(int by)
{
T* a2;
int i;
if (size + by > range)
{
range = (size + by) * 2;
a2 = new T[range];
for (i = 0; i < size; i++) a2[i] = array[i];
delete[] array;
array = a2;
}
size += by;
}
public:
DynamicArray(void)
{
size = 0;
range = 4;
array = new T[range];
}
~DynamicArray(void)
{
delete[] array;
}
T* GetAndReleaseArray(void)
{
T* a2 = array;
size = 0;
range = 4;
array = new T[range];
return a2;
}
int Size(void) { return size; }
bool Insert(T t)
{
Grow(1);
array[size - 1] = t;
return true;
}
bool Insert(int n, T t)
{
int m;
if (n >= 0 && n <= size)
{
Grow(1);
m = size - 1;
while (m > n)
{
array[m] = array[m - 1];
m--;
}
array[n] = t;
}
return true;
}
bool Lookup(int n, T& t)
{
if (n >= 0 && n < size)
{
t = array[n];
return true;
}
else
return false;
}
bool Replace(int n, T t, T& old)
{
if (n >= 0 && n < size)
{
old = array[n];
array[n] = t;
return true;
}
else
return false;
}
bool Swap(int n, int m)
{
T t;
if (n >= 0 && n < size && m >= 0 && m < size)
{
t = array[n]; array[n] = array[m]; array[m] = t;
return true;
}
else
return false;
}
bool Remove(int n)
{
if (n >= 0 && n < size)
{
while (n < size - 1)
{
array[n] = array[n + 1];
n++;
}
size--;
return true;
}
else
return false;
}
int Find(T t)
{
int n;
n = size - 1;
while (n >= 0 && t != array[n])
n--;
return n;
}
};
template <class T>
class GrowingArray
{
protected:
int size, range;
T* array;
T empty;
void Grow(int to, bool clear)
{
T* a2;
int i;
if (clear) size = 0;
if (to > range)
{
if (to > range * 2)
range = to;
else
range = range * 2;
a2 = new T[range];
for (i = 0; i < size; i++) a2[i] = array[i];
delete[] array;
array = a2;
}
for (i = size; i < to; i++) array[i] = empty;
size = to;
}
public:
GrowingArray(T empty_)
: empty(empty_)
{
size = 0;
range = 4;
array = new T[range];
}
GrowingArray(const GrowingArray& a)
: empty(a.empty)
{
int i;
size = a.size;
range = a.range;
array = new T[range];
for (i = 0; i < size; i++) array[i] = a.array[i];
}
~GrowingArray(void)
{
delete[] array;
}
__forceinline T& operator[](int n)
{
assert(n >= 0);
if (n >= size) Grow(n + 1, false);
return array[n];
}
__forceinline T operator[](int n) const
{
assert(n >= 0);
if (n >= size) return empty;
else return array[n];
}
__forceinline void Push(T t)
{
(*this)[size] = t;
}
__forceinline T Pop(void)
{
assert(size > 0);
return array[--size];
}
__forceinline T Top(void) const
{
return array[size - 1];
}
__forceinline bool IsEmpty(void) const { return size == 0; }
__forceinline int Size(void) const { return size; }
__forceinline void SetSize(int size, bool clear = false)
{
Grow(size, clear);
}
__forceinline void Clear(void)
{
Grow(size, true);
}
};

370
oscar64/Assembler.cpp Normal file
View File

@ -0,0 +1,370 @@
#pragma once
#include "Assembler.h"
#include <assert.h>
AsmInsData DecInsData[256] = {
{ASMIT_BRK, ASMIM_IMPLIED},
{ASMIT_ORA, ASMIM_INDIRECT_X},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_ORA, ASMIM_ZERO_PAGE},
{ASMIT_ASL, ASMIM_ZERO_PAGE},
{ASMIT_INV},
{ASMIT_PHP, ASMIM_IMPLIED},
{ASMIT_ORA, ASMIM_IMMEDIATE},
{ASMIT_ASL, ASMIM_IMPLIED},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_ORA, ASMIM_ABSOLUTE},
{ASMIT_ASL, ASMIM_ABSOLUTE},
{ASMIT_INV},
{ASMIT_BPL, ASMIM_RELATIVE },
{ASMIT_ORA, ASMIM_INDIRECT_Y},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_ORA, ASMIM_ZERO_PAGE_X},
{ASMIT_ASL, ASMIM_ZERO_PAGE_X},
{ASMIT_INV},
{ASMIT_CLC, ASMIM_IMPLIED},
{ASMIT_ORA, ASMIM_ABSOLUTE_Y},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_ORA, ASMIM_ABSOLUTE_X},
{ASMIT_ASL, ASMIM_ABSOLUTE_X},
{ASMIT_INV},
{ASMIT_JSR, ASMIM_ABSOLUTE},
{ASMIT_AND, ASMIM_INDIRECT_X},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_BIT, ASMIM_ZERO_PAGE},
{ASMIT_AND, ASMIM_ZERO_PAGE},
{ASMIT_ROL, ASMIM_ZERO_PAGE},
{ASMIT_INV},
{ASMIT_PLP, ASMIM_IMPLIED},
{ASMIT_AND, ASMIM_IMMEDIATE},
{ASMIT_ROL, ASMIM_IMPLIED},
{ASMIT_INV},
{ASMIT_BIT, ASMIM_ABSOLUTE},
{ASMIT_AND, ASMIM_ABSOLUTE},
{ASMIT_ROL, ASMIM_ABSOLUTE},
{ASMIT_INV},
{ASMIT_BMI, ASMIM_RELATIVE },
{ASMIT_AND, ASMIM_INDIRECT_Y},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_AND, ASMIM_ZERO_PAGE_X},
{ASMIT_ROL, ASMIM_ZERO_PAGE_X},
{ASMIT_INV},
{ASMIT_SEC, ASMIM_IMPLIED},
{ASMIT_AND, ASMIM_ABSOLUTE_Y},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_AND, ASMIM_ABSOLUTE_X},
{ASMIT_ROL, ASMIM_ABSOLUTE_X},
{ASMIT_INV},
{ASMIT_RTI, ASMIM_IMPLIED},
{ASMIT_EOR, ASMIM_INDIRECT_X},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_EOR, ASMIM_ZERO_PAGE},
{ASMIT_LSR, ASMIM_ZERO_PAGE},
{ASMIT_INV},
{ASMIT_PHA, ASMIM_IMPLIED},
{ASMIT_EOR, ASMIM_IMMEDIATE},
{ASMIT_LSR, ASMIM_IMPLIED},
{ASMIT_INV},
{ASMIT_JMP, ASMIM_ABSOLUTE},
{ASMIT_EOR, ASMIM_ABSOLUTE},
{ASMIT_LSR, ASMIM_ABSOLUTE},
{ASMIT_INV},
{ASMIT_BVC, ASMIM_RELATIVE },
{ASMIT_EOR, ASMIM_INDIRECT_Y},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_EOR, ASMIM_ZERO_PAGE_X},
{ASMIT_LSR, ASMIM_ZERO_PAGE_X},
{ASMIT_INV},
{ASMIT_CLI, ASMIM_IMPLIED},
{ASMIT_EOR, ASMIM_ABSOLUTE_Y},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_INV},
{ASMIT_EOR, ASMIM_ABSOLUTE_X},
{ASMIT_LSR, ASMIM_ABSOLUTE_X},
{ASMIT_INV},
{ ASMIT_RTS, ASMIM_IMPLIED },
{ ASMIT_ADC, ASMIM_INDIRECT_X },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_ADC, ASMIM_ZERO_PAGE },
{ ASMIT_ROR, ASMIM_ZERO_PAGE },
{ ASMIT_INV },
{ ASMIT_PLA, ASMIM_IMPLIED },
{ ASMIT_ADC, ASMIM_IMMEDIATE },
{ ASMIT_ROR, ASMIM_IMPLIED },
{ ASMIT_INV },
{ ASMIT_JMP, ASMIM_INDIRECT },
{ ASMIT_ADC, ASMIM_ABSOLUTE },
{ ASMIT_ROR, ASMIM_ABSOLUTE },
{ ASMIT_INV },
{ ASMIT_BVS, ASMIM_RELATIVE },
{ ASMIT_ADC, ASMIM_INDIRECT_Y },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_ADC, ASMIM_ZERO_PAGE_X },
{ ASMIT_ROR, ASMIM_ZERO_PAGE_X },
{ ASMIT_INV },
{ ASMIT_SEI, ASMIM_IMPLIED },
{ ASMIT_ADC, ASMIM_ABSOLUTE_Y },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_ADC, ASMIM_ABSOLUTE_X },
{ ASMIT_ROR, ASMIM_ABSOLUTE_X },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_STA, ASMIM_INDIRECT_X },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_STY, ASMIM_ZERO_PAGE },
{ ASMIT_STA, ASMIM_ZERO_PAGE },
{ ASMIT_STX, ASMIM_ZERO_PAGE },
{ ASMIT_INV },
{ ASMIT_DEY, ASMIM_IMPLIED },
{ ASMIT_INV },
{ ASMIT_TXA, ASMIM_IMPLIED },
{ ASMIT_INV },
{ ASMIT_STY, ASMIM_ABSOLUTE },
{ ASMIT_STA, ASMIM_ABSOLUTE },
{ ASMIT_STX, ASMIM_ABSOLUTE },
{ ASMIT_INV },
{ ASMIT_BCC, ASMIM_RELATIVE },
{ ASMIT_STA, ASMIM_INDIRECT_Y },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_STY, ASMIM_ZERO_PAGE_X },
{ ASMIT_STA, ASMIM_ZERO_PAGE_X },
{ ASMIT_STX, ASMIM_ZERO_PAGE_Y },
{ ASMIT_INV },
{ ASMIT_TYA, ASMIM_IMPLIED },
{ ASMIT_STA, ASMIM_ABSOLUTE_Y },
{ ASMIT_TXS },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_STA, ASMIM_ABSOLUTE_X },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_LDY, ASMIM_IMMEDIATE },
{ ASMIT_LDA, ASMIM_INDIRECT_X },
{ ASMIT_LDX, ASMIM_IMMEDIATE },
{ ASMIT_INV },
{ ASMIT_LDY, ASMIM_ZERO_PAGE },
{ ASMIT_LDA, ASMIM_ZERO_PAGE },
{ ASMIT_LDX, ASMIM_ZERO_PAGE },
{ ASMIT_INV },
{ ASMIT_TAY, ASMIM_IMPLIED },
{ ASMIT_LDA, ASMIM_IMMEDIATE },
{ ASMIT_TAX, ASMIM_IMPLIED },
{ ASMIT_INV },
{ ASMIT_LDY, ASMIM_ABSOLUTE },
{ ASMIT_LDA, ASMIM_ABSOLUTE },
{ ASMIT_LDX, ASMIM_ABSOLUTE },
{ ASMIT_INV },
{ ASMIT_BCS, ASMIM_RELATIVE },
{ ASMIT_LDA, ASMIM_INDIRECT_Y },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_LDY, ASMIM_ZERO_PAGE_X },
{ ASMIT_LDA, ASMIM_ZERO_PAGE_X },
{ ASMIT_LDX, ASMIM_ZERO_PAGE_Y },
{ ASMIT_INV },
{ ASMIT_CLV, ASMIM_IMPLIED },
{ ASMIT_LDA, ASMIM_ABSOLUTE_Y },
{ ASMIT_TSX, ASMIM_IMPLIED },
{ ASMIT_INV },
{ ASMIT_LDY, ASMIM_ABSOLUTE_X },
{ ASMIT_LDA, ASMIM_ABSOLUTE_X },
{ ASMIT_LDX, ASMIM_ABSOLUTE_Y },
{ ASMIT_INV },
{ ASMIT_CPY, ASMIM_IMMEDIATE },
{ ASMIT_CMP, ASMIM_INDIRECT_X },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_CPY, ASMIM_ZERO_PAGE },
{ ASMIT_CMP, ASMIM_ZERO_PAGE },
{ ASMIT_DEC, ASMIM_ZERO_PAGE },
{ ASMIT_INV },
{ ASMIT_INY, ASMIM_IMPLIED },
{ ASMIT_CMP, ASMIM_IMMEDIATE },
{ ASMIT_DEX, ASMIM_IMPLIED },
{ ASMIT_INV },
{ ASMIT_CPY, ASMIM_ABSOLUTE },
{ ASMIT_CMP, ASMIM_ABSOLUTE },
{ ASMIT_DEC, ASMIM_ABSOLUTE },
{ ASMIT_INV },
{ ASMIT_BNE, ASMIM_RELATIVE },
{ ASMIT_CMP, ASMIM_INDIRECT_Y },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_CMP, ASMIM_ZERO_PAGE_X },
{ ASMIT_DEC, ASMIM_ZERO_PAGE_X },
{ ASMIT_INV },
{ ASMIT_CLD, ASMIM_IMPLIED },
{ ASMIT_CMP, ASMIM_ABSOLUTE_Y },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_CMP, ASMIM_ABSOLUTE_X },
{ ASMIT_DEC, ASMIM_ABSOLUTE_X },
{ ASMIT_INV },
{ ASMIT_CPX, ASMIM_IMMEDIATE },
{ ASMIT_SBC, ASMIM_INDIRECT_X },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_CPX, ASMIM_ZERO_PAGE },
{ ASMIT_SBC, ASMIM_ZERO_PAGE },
{ ASMIT_INC, ASMIM_ZERO_PAGE },
{ ASMIT_INV },
{ ASMIT_INX, ASMIM_IMPLIED },
{ ASMIT_SBC, ASMIM_IMMEDIATE },
{ ASMIT_NOP, ASMIM_IMPLIED },
{ ASMIT_INV },
{ ASMIT_CPX, ASMIM_ABSOLUTE },
{ ASMIT_SBC, ASMIM_ABSOLUTE },
{ ASMIT_INC, ASMIM_ABSOLUTE },
{ ASMIT_INV },
{ ASMIT_BEQ, ASMIM_RELATIVE },
{ ASMIT_SBC, ASMIM_INDIRECT_Y },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_SBC, ASMIM_ZERO_PAGE_X },
{ ASMIT_INC, ASMIM_ZERO_PAGE_X },
{ ASMIT_INV },
{ ASMIT_SED, ASMIM_IMPLIED },
{ ASMIT_SBC, ASMIM_ABSOLUTE_Y },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_INV },
{ ASMIT_SBC, ASMIM_ABSOLUTE_X },
{ ASMIT_INC, ASMIM_ABSOLUTE_X },
{ ASMIT_INV },
};
short AsmInsOpcodes[NUM_ASM_INS_TYPES][NUM_ASM_INS_MODES];
const char* AsmInstructionNames[NUM_ASM_INS_TYPES] = {
"ADC", "AND", "ASL", "BCC", "BCS", "BEQ", "BIT", "BMI", "BNE", "BPL", "BRK", "BVC", "BVS", "CLC",
"CLD", "CLI", "CLV", "CMP", "CPX", "CPY", "DEC", "DEX", "DEY", "EOR", "INC", "INX", "INY", "JMP",
"JSR", "LDA", "LDX", "LDY", "LSR", "NOP", "ORA", "PHA", "PHP", "PLA", "PLP", "ROL", "ROR", "RTI",
"RTS", "SBC", "SEC", "SED", "SEI", "STA", "STX", "STY", "TAX", "TAY", "TSX", "TXA", "TXS", "TYA",
"INV", "BYT"
};
int AsmInsModeSize[NUM_ASM_INS_MODES] = {
1,
2,
2,
2,
2,
3,
3,
3,
3,
2,
2,
2,
};
void InitAssembler(void)
{
for (int i = 0; i < NUM_ASM_INS_TYPES; i++)
{
for (int j = 0; j < NUM_ASM_INS_MODES; j++)
{
AsmInsOpcodes[i][j] = -1;
}
}
for (int i = 0; i < 256; i++)
{
const AsmInsData& di(DecInsData[i]);
if (di.mType != ASMIT_INV)
{
assert(AsmInsOpcodes[di.mType][di.mMode] == -1);
AsmInsOpcodes[di.mType][di.mMode] = i;
}
}
AsmInsOpcodes[ASMIT_BYTE][ASMIM_ZERO_PAGE] = 0;
}
int AsmInsSize(AsmInsType type, AsmInsMode mode)
{
if (type < ASMIT_INV)
return AsmInsModeSize[mode];
else
return 1;
}
static inline char toupper(char ch)
{
if (ch >= 'a' && ch <= 'z')
return ch - 'a' + 'A';
else
return ch;
}
AsmInsType FindAsmInstruction(const char* ins)
{
if (!ins[3])
{
for (int i = 0; i < NUM_ASM_INS_TYPES; i++)
{
if (AsmInstructionNames[i][0] == toupper(ins[0]) &&
AsmInstructionNames[i][1] == toupper(ins[1]) &&
AsmInstructionNames[i][2] == toupper(ins[2]))
return AsmInsType(i);
}
}
return ASMIT_INV;
}
bool HasAsmInstructionMode(AsmInsType type, AsmInsMode mode)
{
return AsmInsOpcodes[type][mode] != -1;
}

54
oscar64/Assembler.h Normal file
View File

@ -0,0 +1,54 @@
#pragma once
#include "Ident.h"
enum AsmInsType
{
ASMIT_ADC, ASMIT_AND, ASMIT_ASL, ASMIT_BCC, ASMIT_BCS, ASMIT_BEQ, ASMIT_BIT, ASMIT_BMI, ASMIT_BNE, ASMIT_BPL, ASMIT_BRK, ASMIT_BVC, ASMIT_BVS, ASMIT_CLC,
ASMIT_CLD, ASMIT_CLI, ASMIT_CLV, ASMIT_CMP, ASMIT_CPX, ASMIT_CPY, ASMIT_DEC, ASMIT_DEX, ASMIT_DEY, ASMIT_EOR, ASMIT_INC, ASMIT_INX, ASMIT_INY, ASMIT_JMP,
ASMIT_JSR, ASMIT_LDA, ASMIT_LDX, ASMIT_LDY, ASMIT_LSR, ASMIT_NOP, ASMIT_ORA, ASMIT_PHA, ASMIT_PHP, ASMIT_PLA, ASMIT_PLP, ASMIT_ROL, ASMIT_ROR, ASMIT_RTI,
ASMIT_RTS, ASMIT_SBC, ASMIT_SEC, ASMIT_SED, ASMIT_SEI, ASMIT_STA, ASMIT_STX, ASMIT_STY, ASMIT_TAX, ASMIT_TAY, ASMIT_TSX, ASMIT_TXA, ASMIT_TXS, ASMIT_TYA,
ASMIT_INV, ASMIT_BYTE,
NUM_ASM_INS_TYPES
};
enum AsmInsMode
{
ASMIM_IMPLIED,
ASMIM_IMMEDIATE,
ASMIM_ZERO_PAGE,
ASMIM_ZERO_PAGE_X,
ASMIM_ZERO_PAGE_Y,
ASMIM_ABSOLUTE,
ASMIM_ABSOLUTE_X,
ASMIM_ABSOLUTE_Y,
ASMIM_INDIRECT,
ASMIM_INDIRECT_X,
ASMIM_INDIRECT_Y,
ASMIM_RELATIVE,
NUM_ASM_INS_MODES
};
struct AsmInsData
{
AsmInsType mType;
AsmInsMode mMode;
};
extern AsmInsData DecInsData[256];
extern short AsmInsOpcodes[NUM_ASM_INS_TYPES][NUM_ASM_INS_MODES];
extern const char* AsmInstructionNames[NUM_ASM_INS_TYPES];
AsmInsType FindAsmInstruction(const char * ins);
bool HasAsmInstructionMode(AsmInsType type, AsmInsMode mode);
int AsmInsSize(AsmInsType type, AsmInsMode mode);
void InitAssembler(void);

334
oscar64/BitVector.h Normal file
View File

@ -0,0 +1,334 @@
#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
class BitVector
{
protected:
unsigned* bits;
unsigned mask;
int size, dwsize;
public:
BitVector(void);
BitVector(const BitVector& v);
BitVector(int size, bool set = false);
BitVector(int size, unsigned char * data);
BitVector& operator=(const BitVector& v);
~BitVector(void);
BitVector operator+(const BitVector v) const;
BitVector operator*(const int n) const;
BitVector operator|(const BitVector v) const;
BitVector operator&(const BitVector v) const;
BitVector operator~(void) const;
void Set(int n, bool b);
bool Get(int n) const;
int Size(void) const;
int DWSize(void) const;
void Copy(unsigned* bits) const;
};
inline BitVector::BitVector(void)
{
size = 0;
dwsize = 0;
bits = nullptr;
mask = 0;
}
inline BitVector::BitVector(const BitVector& v)
{
int i;
size = v.size;
dwsize = v.dwsize;
mask = v.mask;
if (dwsize)
bits = new unsigned[dwsize];
else
bits = nullptr;
for (i = 0; i < dwsize; i++) bits[i] = v.bits[i];
}
inline BitVector::BitVector(int size, unsigned char * data)
{
this->size = size;
dwsize = ((size + 31) >> 5);
if ((size & 31) == 0)
mask = 0xffffffff;
else
mask = (1 << (size & 31)) - 1;
if (dwsize)
bits = new unsigned[dwsize];
else
bits = nullptr;
if (size)
{
memcpy(bits, data, (size + 7) / 8);
}
}
inline BitVector::BitVector(int size, bool set)
{
int i;
this->size = size;
dwsize = ((size + 31) >> 5);
if ((size & 31) == 0)
mask = 0xffffffff;
else
mask = (1 << (size & 31)) - 1;
if (dwsize)
bits = new unsigned[dwsize];
else
bits = NULL;
if (size)
{
if (set)
{
for (i = 0; i < dwsize - 1; i++) bits[i] = ~0;
bits[dwsize - 1] = mask;
}
else
for (i = 0; i < dwsize; i++) bits[i] = 0;
}
}
inline BitVector& BitVector::operator=(const BitVector& v)
{
int i;
delete[] bits;
size = v.size;
dwsize = v.dwsize;
mask = v.mask;
if (dwsize)
bits = new unsigned[dwsize];
else
bits = NULL;
for (i = 0; i < dwsize; i++) bits[i] = v.bits[i];
return *this;
}
inline BitVector::~BitVector(void)
{
delete[] bits;
}
inline BitVector BitVector::operator+(const BitVector v) const
{
int i;
int s;
unsigned merge;
BitVector vv(size + v.size);
if (dwsize == 0)
{
for (i = 0; i < v.dwsize; i++)
vv.bits[i] = v.bits[i];
}
else if (v.dwsize == 0)
{
for (i = 0; i < dwsize; i++)
vv.bits[i] = bits[i];
}
else
{
s = size & 31;
if (s == 0)
{
for (i = 0; i < dwsize; i++)
vv.bits[i] = bits[i];
for (i = 0; i < v.dwsize; i++)
vv.bits[i + dwsize] = v.bits[i];
}
else
{
for (i = 0; i < dwsize - 1; i++)
vv.bits[i] = bits[i];
merge = bits[dwsize - 1] & mask;
for (i = 0; i < v.dwsize; i++)
{
vv.bits[i + dwsize - 1] = merge | (v.bits[i] << s);
merge = v.bits[i] >> (32 - s);
}
if (dwsize - 1 + v.dwsize < vv.dwsize)
vv.bits[dwsize - 1 + v.dwsize] = merge;
}
}
return vv;
}
inline BitVector BitVector::operator*(const int n) const
{
int i, j;
int s, dw;
unsigned merge;
BitVector vv(size * n);
if (n > 0)
{
dw = 0;
for (i = 0; i < dwsize - 1; i++)
vv.bits[dw++] = bits[i];
merge = bits[dwsize - 1] & mask;
for (j = 1; j < n; j++)
{
s = (size * j) & 31;
if (s == 0)
{
vv.bits[dw++] = merge;
for (i = 0; i < dwsize - 1; i++)
vv.bits[dw++] = bits[i];
merge = bits[dwsize - 1] & mask;
}
else
{
for (i = 0; i < dwsize - 1; i++)
{
vv.bits[dw++] = merge | (bits[i] << s);
merge = bits[i] >> (32 - s);
}
if (mask >> (32 - s))
{
vv.bits[dw++] = merge | (bits[i] << s);
merge = (bits[i] & mask) >> (32 - s);
}
else
{
merge |= (bits[i] & mask) << s;
}
}
}
if (dw < vv.dwsize)
vv.bits[dw++] = merge;
if (dw > vv.dwsize)
__asm int 3
}
return vv;
}
inline BitVector BitVector::operator|(const BitVector v) const
{
int i;
if (dwsize < v.dwsize)
{
BitVector vv(v.size);
for (i = 0; i < dwsize; i++) vv.bits[i] = bits[i] | v.bits[i];
for (i = dwsize; i < v.dwsize; i++) vv.bits[i] = v.bits[i];
return vv;
}
else
{
BitVector vv(size);
for (i = 0; i < v.dwsize; i++) vv.bits[i] = bits[i] | v.bits[i];
for (i = v.dwsize; i < dwsize; i++) vv.bits[i] = bits[i];
return vv;
}
}
inline BitVector BitVector::operator&(const BitVector v) const
{
int i;
if (dwsize < v.dwsize)
{
BitVector vv(v.size);
for (i = 0; i < dwsize; i++) vv.bits[i] = bits[i] & v.bits[i];
return vv;
}
else
{
BitVector vv(size);
for (i = 0; i < v.dwsize; i++) vv.bits[i] = bits[i] & v.bits[i];
return vv;
}
}
inline BitVector BitVector::operator~(void) const
{
int i;
BitVector vv(size);
for (i = 0; i < dwsize - 1; i++) vv.bits[i] = ~bits[i];
vv.bits[dwsize - 1] = ~bits[dwsize - 1] & mask;
return vv;
}
inline void BitVector::Set(int n, bool b)
{
if (b)
bits[n >> 5] |= (1 << (n & 31));
else
bits[n >> 5] &= ~(1 << (n & 31));
}
inline bool BitVector::Get(int n) const
{
return (bits[n >> 5] & (1 << (n & 31))) != 0;
}
inline int BitVector::Size(void) const
{
return size;
}
inline int BitVector::DWSize(void) const
{
return dwsize;
}
inline void BitVector::Copy(unsigned* bits) const
{
int i;
if (dwsize > 0 && (size & 31))
this->bits[dwsize - 1] &= (1 << (size & 31)) - 1;
for (i = 0; i < dwsize; i++)
{
bits[i] = this->bits[i];
}
}

File diff suppressed because it is too large Load Diff

285
oscar64/ByteCodeGenerator.h Normal file
View File

@ -0,0 +1,285 @@
#pragma once
#include "InterCode.h"
#include "Ident.h"
enum ByteCode
{
BC_NOP,
BC_EXIT,
BC_CONST_P8,
BC_CONST_N8,
BC_CONST_16,
BC_CONST_32,
BC_LOAD_REG_16,
BC_STORE_REG_16,
BC_ADDR_REG,
BC_LOAD_REG_32,
BC_STORE_REG_32,
BC_LOAD_ABS_U8,
BC_LOAD_ABS_I8,
BC_LOAD_ABS_16,
BC_LOAD_ABS_32,
BC_STORE_ABS_8,
BC_STORE_ABS_16,
BC_STORE_ABS_32,
BC_LEA_ABS,
BC_LOAD_LOCAL_U8,
BC_LOAD_LOCAL_I8,
BC_LOAD_LOCAL_16,
BC_LOAD_LOCAL_32,
BC_STORE_LOCAL_8,
BC_STORE_LOCAL_16,
BC_STORE_LOCAL_32,
BC_LEA_LOCAL,
BC_STORE_FRAME_8,
BC_STORE_FRAME_16,
BC_STORE_FRAME_32,
BC_LOAD_ADDR_U8,
BC_LOAD_ADDR_I8,
BC_LOAD_ADDR_16,
BC_LOAD_ADDR_32,
BC_STORE_ADDR_8,
BC_STORE_ADDR_16,
BC_STORE_ADDR_32,
BC_BINOP_ADDR_16,
BC_BINOP_SUBR_16,
BC_BINOP_ANDR_16,
BC_BINOP_ORR_16,
BC_BINOP_XORR_16,
BC_BINOP_MULR_16,
BC_BINOP_DIVR_U16,
BC_BINOP_MODR_U16,
BC_BINOP_DIVR_I16,
BC_BINOP_MODR_I16,
BC_BINOP_SHLR_16,
BC_BINOP_SHRR_U16,
BC_BINOP_SHRR_I16,
BC_BINOP_ADDI_16,
BC_BINOP_SUBI_16,
BC_BINOP_ANDI_16,
BC_BINOP_ORI_16,
BC_BINOP_MULI8_16,
BC_BINOP_SHLI_16,
BC_BINOP_SHRI_U16,
BC_BINOP_SHRI_I16,
BC_BINOP_CMPUR_16,
BC_BINOP_CMPSR_16,
BC_BINOP_CMPUI_16,
BC_BINOP_CMPSI_16,
BC_OP_NEGATE_16,
BC_OP_INVERT_16,
BC_BINOP_ADD_F32,
BC_BINOP_SUB_F32,
BC_BINOP_MUL_F32,
BC_BINOP_DIV_F32,
BC_BINOP_CMP_F32,
BC_OP_NEGATE_F32,
BC_OP_ABS_F32,
BC_OP_FLOOR_F32,
BC_OP_CEIL_F32,
BC_CONV_U16_F32,
BC_CONV_I16_F32,
BC_CONV_F32_U16,
BC_CONV_F32_I16,
BC_JUMPS,
BC_BRANCHS_EQ,
BC_BRANCHS_NE,
BC_BRANCHS_GT,
BC_BRANCHS_GE,
BC_BRANCHS_LT,
BC_BRANCHS_LE,
BC_JUMPF,
BC_BRANCHF_EQ,
BC_BRANCHF_NE,
BC_BRANCHF_GT,
BC_BRANCHF_GE,
BC_BRANCHF_LT,
BC_BRANCHF_LE,
BC_SET_EQ,
BC_SET_NE,
BC_SET_GT,
BC_SET_GE,
BC_SET_LT,
BC_SET_LE,
BC_ENTER,
BC_RETURN,
BC_CALL,
BC_PUSH_FRAME,
BC_POP_FRAME,
BC_JSR,
BC_COPY,
BC_COPY_LONG
};
class ByteCodeProcedure;
class ByteCodeGenerator;
class ByteCodeRelocation
{
public:
uint16 mAddr;
bool mFunction, mLower, mUpper;
uint16 mIndex, mOffset;
};
class ByteCodeBasicBlock;
class ByteCodeInstruction
{
public:
ByteCodeInstruction(ByteCode code = BC_NOP);
void Assemble(ByteCodeGenerator* generator, ByteCodeBasicBlock* block);
ByteCode mCode;
uint32 mRegister;
int mValue, mVIndex;
bool mRelocate, mFunction, mRegisterFinal;
bool IsStore(void) const;
bool ChangesAccu(void) const;
bool ChangesAddr(void) const;
bool ChangesRegister(uint32 reg) const;
bool LoadsRegister(uint32 reg) const;
bool StoresRegister(uint32 reg) const;
bool IsCommutative(void) const;
};
class ByteCodeBasicBlock
{
public:
DynamicArray<uint8> code;
int num;
ByteCodeBasicBlock * trueJump, * falseJump;
ByteCodeBasicBlock * trueLink, * falseLink;
ByteCode branch;
GrowingArray<ByteCodeInstruction> mIns;
GrowingArray<ByteCodeRelocation> mRelocations;
int mOffset, mSize;
bool placed, copied, knownShortBranch, killed, bypassed, mAssembled;
ByteCodeBasicBlock(void);
void Assemble(ByteCodeGenerator* generator);
void Compile(InterCodeProcedure* iproc, ByteCodeProcedure * proc, InterCodeBasicBlock * block);
void Close(ByteCodeBasicBlock* trueJump, ByteCodeBasicBlock* falseJump, ByteCode branch);
void PutByte(uint8 code);
void PutWord(uint16 code);
void PutDWord(uint32 code);
void PutBytes(const uint8* code, int num);
void PutCode(ByteCodeGenerator* generator, ByteCode code);
int PutBranch(ByteCodeGenerator* generator, ByteCode code, int offset);
ByteCodeBasicBlock* BypassEmptyBlocks(void);
void CalculateOffset(int& total);
void CopyCode(ByteCodeGenerator* generator, uint8* target);
void IntConstToAccu(__int64 val);
void IntConstToAddr(__int64 val);
void FloatConstToAccu(double val);
void CopyValue(InterCodeProcedure* proc, const InterInstruction& ins);
void LoadConstant(InterCodeProcedure* proc, const InterInstruction& ins);
void StoreDirectValue(InterCodeProcedure* proc, const InterInstruction & ins);
void LoadDirectValue(InterCodeProcedure* proc, const InterInstruction& ins);
void LoadEffectiveAddress(InterCodeProcedure* proc, const InterInstruction& ins);
void CallFunction(InterCodeProcedure* proc, const InterInstruction& ins);
void CallAssembler(InterCodeProcedure* proc, const InterInstruction& ins);
void BinaryOperator(InterCodeProcedure* proc, const InterInstruction& ins);
void UnaryOperator(InterCodeProcedure* proc, const InterInstruction& ins);
void BinaryRROperator(InterCodeProcedure* proc, const InterInstruction& ins);
ByteCode RelationalOperator(InterCodeProcedure* proc, const InterInstruction& ins);
void BinaryIntOperator(InterCodeProcedure* proc, const InterInstruction& ins, ByteCode code);
void NumericConversion(InterCodeProcedure* proc, const InterInstruction& ins);
void PeepHoleOptimizer(void);
};
class ByteCodeGenerator;
class ByteCodeProcedure
{
public:
ByteCodeProcedure(void);
~ByteCodeProcedure(void);
ByteCodeBasicBlock * entryBlock, * exitBlock;
ByteCodeBasicBlock ** tblocks;
int mProgStart, mProgSize;
void Compile(ByteCodeGenerator* generator, InterCodeProcedure* proc);
ByteCodeBasicBlock * CompileBlock(InterCodeProcedure* iproc, InterCodeBasicBlock* block);
void Disassemble(FILE * file, ByteCodeGenerator* generator, InterCodeProcedure* proc);
protected:
const char* TempName(uint8 tmp, char * buffer, InterCodeProcedure* proc);
};
class ByteCodeGenerator
{
public:
ByteCodeGenerator(void);
~ByteCodeGenerator(void);
void WriteBasicHeader(void);
void WriteByteCodeHeader(void);
void SetBasicEntry(int index);
bool WritePRGFile(const char* filename);
bool WriteMapFile(const char* filename);
void WriteAsmFile(FILE * file);
void ResolveRelocations(void);
int AddGlobal(int index, const Ident* ident, int size, const uint8* data, bool assembler);
void AddAddress(int index, bool function, int address, int size, const Ident * ident, bool assembler);
struct Address
{
int mIndex, mAddress, mSize;
bool mFunction, mAssembler;
const Ident * mIdent;
};
GrowingArray<Address> mProcedureAddr, mGlobalAddr;
GrowingArray<ByteCodeRelocation> mRelocations;
bool mByteCodeUsed[128];
uint8 mMemory[0x10000];
int mProgEnd, mProgStart, mProgEntry;
};

View File

@ -0,0 +1,96 @@
#include "CompilationUnits.h"
#include <io.h>
#include <stdio.h>
#include <string.h>
CompilationUnits::CompilationUnits(Errors * errors)
: mErrors(errors)
{
mCompilationUnits = nullptr;
mPendingUnits = nullptr;
mScope = new DeclarationScope(nullptr);
mStartup = nullptr;
for (int i = 0; i < 128; i++)
mByteCodes[i] = nullptr;
}
CompilationUnits::~CompilationUnits(void)
{
}
bool CompilationUnits::AddUnit(Location& location, const char* name, const char* from)
{
char filename[200];
if (!from)
{
strcpy_s(filename, name);
}
else
{
strcpy_s(filename, from);
int i = strlen(filename);
while (i > 0 && (filename[i - 1] != '/' && filename[i - 1] != '\\'))
i--;
while (name[0] == '.' && name[1] == '.' && name[2] == '/')
{
name += 3;
while (i > 0 && (filename[i - 1] != '/' && filename[i - 1] != '\\'))
i--;
}
filename[i] = 0;
strcat_s(filename, name);
}
int i = 0;
while (filename[i])
{
if (filename[i] == '\\')
filename[i] = '/';
i++;
}
if (_access(filename, 0) != 0)
{
mErrors->Error(location, "Could not open source file.", filename);
return false;
}
CompilationUnit* cunit = mCompilationUnits, * punit = nullptr;
while (cunit && strcmp(cunit->mFileName, filename) != 0)
{
punit = cunit;
cunit = cunit->mNext;
}
if (cunit)
return true;
cunit = new CompilationUnit();
cunit->mLocation = location;
strcpy_s(cunit->mFileName, filename);
cunit->mCompiled = false;
cunit->mNext = nullptr;
if (punit)
punit->mNext = cunit;
else
mCompilationUnits = cunit;
if (!mPendingUnits)
mPendingUnits = cunit;
return true;
}
CompilationUnit* CompilationUnits::PendingUnit(void)
{
CompilationUnit* unit = mPendingUnits;
if (mPendingUnits)
mPendingUnits = mPendingUnits->mNext;
return unit;
}

View File

@ -0,0 +1,32 @@
#pragma once
#include "Declaration.h"
#include "Errors.h"
class CompilationUnit
{
public:
Location mLocation;
char mFileName[200];
CompilationUnit * mNext;
bool mCompiled;
};
class CompilationUnits
{
public:
CompilationUnits(Errors * errors);
~CompilationUnits(void);
DeclarationScope* mScope;
CompilationUnit* mCompilationUnits, * mPendingUnits;
Declaration* mStartup;
Declaration* mByteCodes[128];
bool AddUnit(Location & location, const char* name, const char * from);
CompilationUnit* PendingUnit(void);
protected:
Errors* mErrors;
};

240
oscar64/Compiler.cpp Normal file
View File

@ -0,0 +1,240 @@
#include "Compiler.h"
#include "Scanner.h"
#include "Parser.h"
#include "InterCodeGenerator.h"
#include "InterCode.h"
#include "ByteCodeGenerator.h"
#include "Emulator.h"
#include <stdio.h>
Compiler::Compiler(void)
: mByteCodeFunctions(nullptr)
{
mErrors = new Errors();
mCompilationUnits = new CompilationUnits(mErrors);
mPreprocessor = new Preprocessor(mErrors);
mByteCodeGenerator = new ByteCodeGenerator();
mInterCodeGenerator = new InterCodeGenerator(mErrors);
mInterCodeModule = new InterCodeModule();
}
Compiler::~Compiler(void)
{
}
bool Compiler::ParseSource(void)
{
CompilationUnit* cunit;
while (mErrors->mErrorCount == 0 && (cunit = mCompilationUnits->PendingUnit()))
{
if (mPreprocessor->OpenSource(cunit->mFileName, true))
{
Scanner* scanner = new Scanner(mErrors, mPreprocessor);
Parser* parser = new Parser(mErrors, scanner, mCompilationUnits);
parser->Parse();
}
else
mErrors->Error(cunit->mLocation, "Could not open source file", cunit->mFileName);
}
return mErrors->mErrorCount == 0;
}
bool Compiler::GenerateCode(void)
{
Location loc;
Declaration* dcrtstart = mCompilationUnits->mStartup;
if (!dcrtstart)
{
mErrors->Error(loc, "Runtime startup not found");
return false;
}
mInterCodeGenerator->TranslateAssembler(mInterCodeModule, dcrtstart->mValue);
if (mErrors->mErrorCount != 0)
return false;
mByteCodeGenerator->WriteBasicHeader();
mInterCodeModule->UseGlobal(dcrtstart->mVarIndex);
InterVariable& vmain(mInterCodeModule->mGlobalVars[dcrtstart->mVarIndex]);
vmain.mAddr = mByteCodeGenerator->AddGlobal(vmain.mIndex, vmain.mIdent, vmain.mSize, vmain.mData, vmain.mAssembler);
vmain.mPlaced = true;
mByteCodeGenerator->SetBasicEntry(dcrtstart->mVarIndex);
mByteCodeGenerator->mProgEnd = 0x0a00;
mByteCodeGenerator->WriteByteCodeHeader();
const Ident* imain = Ident::Unique("main");
Declaration* dmain = mCompilationUnits->mScope->Lookup(imain);
if (!dmain)
{
mErrors->Error(loc, "main function not found");
return false;
}
InterCodeProcedure* iproc = mInterCodeGenerator->TranslateProcedure(mInterCodeModule, dmain->mValue, dmain);
if (mErrors->mErrorCount != 0)
return false;
for (int i = 0; i < mInterCodeModule->mProcedures.Size(); i++)
{
ByteCodeProcedure* bgproc = new ByteCodeProcedure();
mInterCodeModule->mProcedures[i]->ReduceTemporaries();
#if _DEBUG
mInterCodeModule->mProcedures[i]->Disassemble("final");
#endif
bgproc->Compile(mByteCodeGenerator, mInterCodeModule->mProcedures[i]);
mByteCodeFunctions.Push(bgproc);
#if _DEBUG
FILE* file;
fopen_s(&file, "r:\\cldiss.txt", "a");
if (file)
{
bgproc->Disassemble(file, mByteCodeGenerator, mInterCodeModule->mProcedures[i]);
fclose(file);
}
#endif
}
for (int i = 0; i < 128; i++)
{
if (mByteCodeGenerator->mByteCodeUsed[i])
{
Declaration* bcdec = mCompilationUnits->mByteCodes[i];
if (bcdec)
{
int index = -1, offset = 0;
if (bcdec->mType == DT_CONST_ASSEMBLER)
{
if (bcdec->mVarIndex < 0)
mInterCodeGenerator->TranslateAssembler(mInterCodeModule, bcdec->mValue);
index = bcdec->mVarIndex;
}
else if (bcdec->mType == DT_LABEL)
{
if (bcdec->mBase->mVarIndex < 0)
mInterCodeGenerator->TranslateAssembler(mInterCodeModule, bcdec->mBase->mValue);
index = bcdec->mBase->mVarIndex;
offset = bcdec->mInteger;
}
assert(index > 0);
mInterCodeModule->UseGlobal(index);
ByteCodeRelocation rel;
rel.mAddr = 0x900 + 2 * i;
rel.mFunction = false;
rel.mLower = true;
rel.mUpper = true;
rel.mIndex = index;
rel.mOffset = offset;
mByteCodeGenerator->mRelocations.Push(rel);
}
}
}
for (int i = 0; i < mInterCodeModule->mGlobalVars.Size(); i++)
{
InterVariable& var(mInterCodeModule->mGlobalVars[i]);
if (var.mUsed)
{
if (!var.mPlaced)
{
var.mAddr = mByteCodeGenerator->AddGlobal(var.mIndex, var.mIdent, var.mSize, var.mData, var.mAssembler);
var.mPlaced = true;
}
for (int j = 0; j < var.mNumReferences; j++)
{
InterVariable::Reference& ref(var.mReferences[j]);
ByteCodeRelocation rel;
rel.mAddr = var.mAddr + ref.mAddr;
rel.mFunction = ref.mFunction;
rel.mLower = ref.mLower;
rel.mUpper = ref.mUpper;
rel.mIndex = ref.mIndex;
rel.mOffset = ref.mOffset;
mByteCodeGenerator->mRelocations.Push(rel);
}
}
}
mByteCodeGenerator->ResolveRelocations();
return mErrors->mErrorCount == 0;
}
bool Compiler::WriteOutputFile(const char* targetPath)
{
char prgPath[200], mapPath[200], asmPath[200];
strcpy_s(prgPath, targetPath);
int i = strlen(prgPath);
while (i > 0 && prgPath[i - 1] != '.')
i--;
prgPath[i] = 0;
strcpy_s(mapPath, prgPath);
strcpy_s(asmPath, prgPath);
strcat_s(prgPath, "prg");
strcat_s(mapPath, "map");
strcat_s(asmPath, "asm");
printf("Writing <%s>\n", prgPath);
mByteCodeGenerator->WritePRGFile(prgPath);
printf("Writing <%s>\n", mapPath);
mByteCodeGenerator->WriteMapFile(mapPath);
printf("Writing <%s>\n", asmPath);
{
FILE* file;
fopen_s(&file, asmPath, "w");
if (file)
{
for (int i = 0; i < mByteCodeFunctions.Size(); i++)
mByteCodeFunctions[i]->Disassemble(file, mByteCodeGenerator, mInterCodeModule->mProcedures[i]);
mByteCodeGenerator->WriteAsmFile(file);
fclose(file);
}
}
return true;
}
int Compiler::ExecuteCode(void)
{
Location loc;
printf("Running emulation...\n");
Emulator* emu = new Emulator();
memcpy(emu->mMemory + mByteCodeGenerator->mProgStart, mByteCodeGenerator->mMemory + mByteCodeGenerator->mProgStart, mByteCodeGenerator->mProgEnd - mByteCodeGenerator->mProgStart);
emu->mMemory[0x2d] = mByteCodeGenerator->mProgEnd & 0xff;
emu->mMemory[0x2e] = mByteCodeGenerator->mProgEnd >> 8;
int ecode = emu->Emulate(2061);
printf("Emulation result %d\n", ecode);
if (ecode != 0)
{
char sd[20];
sprintf_s(sd, "%d", ecode);
mErrors->Error(loc, "Execution failed", sd);
}
return ecode;
}

28
oscar64/Compiler.h Normal file
View File

@ -0,0 +1,28 @@
#pragma once
#include "Errors.h"
#include "CompilationUnits.h"
#include "Preprocessor.h"
#include "ByteCodeGenerator.h"
#include "InterCodeGenerator.h"
class Compiler
{
public:
Compiler(void);
~Compiler(void);
Errors* mErrors;
CompilationUnits* mCompilationUnits;
Preprocessor* mPreprocessor;
ByteCodeGenerator* mByteCodeGenerator;
InterCodeGenerator* mInterCodeGenerator;
InterCodeModule* mInterCodeModule;
GrowingArray<ByteCodeProcedure*> mByteCodeFunctions;
bool ParseSource(void);
bool GenerateCode(void);
bool WriteOutputFile(const char* targetPath);
int ExecuteCode(void);
};

513
oscar64/Declaration.cpp Normal file
View File

@ -0,0 +1,513 @@
#include "Declaration.h"
DeclarationScope::DeclarationScope(DeclarationScope* parent)
{
mParent = parent;
mHashSize = 0;
mHashFill = 0;
mHash = nullptr;
}
DeclarationScope::~DeclarationScope(void)
{
delete[] mHash;
}
Declaration * DeclarationScope::Insert(const Ident* ident, Declaration* dec)
{
if (!mHash)
{
mHashSize = 16;
mHashFill = 0;
mHash = new Entry[mHashSize];
for (int i = 0; i < mHashSize; i++)
{
mHash[i].mDec = nullptr;
mHash[i].mIdent = nullptr;
}
}
int hm = mHashSize - 1;
int hi = ident->mHash & hm;
while (mHash[hi].mIdent)
{
if (ident == mHash[hi].mIdent)
return mHash[hi].mDec;
hi = (hi + 1) & hm;
}
mHash[hi].mIdent = ident;
mHash[hi].mDec = dec;
mHashFill++;
if (2 * mHashFill >= mHashSize)
{
int size = mHashSize;
Entry* entries = mHash;
mHashSize *= 2;
mHashFill = 0;
mHash = new Entry[mHashSize];
for (int i = 0; i < mHashSize; i++)
{
mHash[i].mDec = nullptr;
mHash[i].mIdent = nullptr;
}
for (int i = 0; i < size; i++)
{
if (entries[i].mIdent)
Insert(entries[i].mIdent, entries[i].mDec);
}
delete[] entries;
}
return nullptr;
}
Declaration* DeclarationScope::Lookup(const Ident* ident)
{
if (mHashSize > 0)
{
int hm = mHashSize - 1;
int hi = ident->mHash & hm;
while (mHash[hi].mIdent)
{
if (ident == mHash[hi].mIdent)
return mHash[hi].mDec;
hi = (hi + 1) & hm;
}
}
return mParent ? mParent->Lookup(ident) : nullptr;
}
Expression::Expression(const Location& loc, ExpressionType type)
: mLocation(loc), mType(type), mLeft(nullptr), mRight(nullptr), mConst(false)
{
}
Expression::~Expression(void)
{
}
Expression* Expression::LogicInvertExpression(void)
{
if (mType == EX_LOGICAL_NOT)
return mLeft;
else if (mType == EX_LOGICAL_AND)
{
mType = EX_LOGICAL_OR;
mLeft = mLeft->LogicInvertExpression();
mRight = mRight->LogicInvertExpression();
return this;
}
else if (mType == EX_LOGICAL_OR)
{
mType = EX_LOGICAL_OR;
mLeft = mLeft->LogicInvertExpression();
mRight = mRight->LogicInvertExpression();
return this;
}
else if (mType == EX_RELATIONAL)
{
switch (mToken)
{
case TK_EQUAL:
mToken = TK_NOT_EQUAL;
break;
case TK_NOT_EQUAL:
mToken = TK_EQUAL;
break;
case TK_GREATER_THAN:
mToken = TK_LESS_EQUAL;
break;
case TK_GREATER_EQUAL:
mToken = TK_LESS_THAN;
break;
case TK_LESS_THAN:
mToken = TK_GREATER_EQUAL;
break;
case TK_LESS_EQUAL:
mToken = TK_GREATER_THAN;
break;
}
return this;
}
else
{
Expression* ex = new Expression(mLocation, EX_LOGICAL_NOT);
ex->mLeft = this;
return ex;
}
}
Expression* Expression::ConstantFold(void)
{
if (mType == EX_PREFIX && mLeft->mType == EX_CONSTANT)
{
if (mLeft->mDecValue->mType == DT_CONST_INTEGER)
{
switch (mToken)
{
case TK_ADD:
return mLeft;
case TK_SUB:
{
Expression* ex = new Expression(mLocation, EX_CONSTANT);
Declaration * dec = new Declaration(mLocation, DT_CONST_INTEGER);
dec->mBase = TheSignedIntTypeDeclaration;
dec->mInteger = - mLeft->mDecValue->mInteger;
ex->mDecValue = dec;
ex->mDecType = TheSignedIntTypeDeclaration;
return ex;
}
case TK_BINARY_NOT:
{
Expression* ex = new Expression(mLocation, EX_CONSTANT);
Declaration* dec = new Declaration(mLocation, DT_CONST_INTEGER);
dec->mBase = mLeft->mDecValue->mBase;
dec->mInteger = ~mLeft->mDecValue->mInteger;
ex->mDecValue = dec;
ex->mDecType = dec->mBase;
return ex;
}
}
}
else if (mLeft->mDecValue->mType == DT_CONST_FLOAT)
{
switch (mToken)
{
case TK_ADD:
return mLeft;
case TK_SUB:
{
Expression* ex = new Expression(mLocation, EX_CONSTANT);
Declaration* dec = new Declaration(mLocation, DT_CONST_FLOAT);
dec->mBase = TheFloatTypeDeclaration;
dec->mNumber = -mLeft->mDecValue->mNumber;
ex->mDecValue = dec;
ex->mDecType = TheFloatTypeDeclaration;
return ex;
}
}
}
}
else if (mType == EX_TYPECAST && mRight->mType == EX_CONSTANT)
{
if (mLeft->mDecType->mType == DT_TYPE_POINTER)
{
if (mRight->mDecValue->mType == DT_CONST_ADDRESS || mRight->mDecValue->mType == DT_CONST_INTEGER)
{
Expression* ex = new Expression(mLocation, EX_CONSTANT);
Declaration* dec = new Declaration(mLocation, DT_CONST_ADDRESS);
dec->mBase = mLeft->mDecType;
dec->mInteger = mRight->mDecValue->mInteger;
ex->mDecValue = dec;
ex->mDecType = mLeft->mDecType;
return ex;
}
}
else if (mLeft->mDecType->mType == DT_CONST_INTEGER)
{
if (mRight->mDecValue->mType == DT_CONST_FLOAT)
{
Expression* ex = new Expression(mLocation, EX_CONSTANT);
Declaration* dec = new Declaration(mLocation, DT_CONST_INTEGER);
dec->mBase = mLeft->mDecType;
dec->mInteger = mRight->mDecValue->mNumber;
ex->mDecValue = dec;
ex->mDecType = mLeft->mDecType;
return ex;
}
}
else if (mLeft->mDecType->mType == DT_CONST_FLOAT)
{
if (mRight->mDecValue->mType == DT_CONST_INTEGER)
{
Expression* ex = new Expression(mLocation, EX_CONSTANT);
Declaration* dec = new Declaration(mLocation, DT_CONST_FLOAT);
dec->mBase = mLeft->mDecType;
dec->mNumber = mRight->mDecValue->mInteger;
ex->mDecValue = dec;
ex->mDecType = mLeft->mDecType;
return ex;
}
}
}
else if (mType == EX_BINARY && mLeft->mType == EX_CONSTANT && mRight->mType == EX_CONSTANT)
{
if (mLeft->mDecValue->mType == DT_CONST_INTEGER && mRight->mDecValue->mType == DT_CONST_INTEGER)
{
__int64 ival, ileft = mLeft->mDecValue->mInteger, iright = mRight->mDecValue->mInteger;
switch (mToken)
{
case TK_ADD:
ival = ileft + iright;
break;
case TK_SUB:
ival = ileft - iright;
break;
case TK_MUL:
ival = ileft * iright;
break;
case TK_DIV:
ival = ileft / iright;
break;
case TK_MOD:
ival = ileft % iright;
break;
case TK_LEFT_SHIFT:
ival = ileft << iright;
break;
case TK_RIGHT_SHIFT:
ival = ileft >> iright;
break;
case TK_BINARY_AND:
ival = ileft & iright;
break;
case TK_BINARY_OR:
ival = ileft | iright;
break;
case TK_BINARY_XOR:
ival = ileft ^ iright;
break;
default:
ival = 0;
}
Expression* ex = new Expression(mLocation, EX_CONSTANT);
Declaration* dec = new Declaration(mLocation, DT_CONST_INTEGER);
dec->mBase = ival < 32768 ? TheSignedIntTypeDeclaration : TheUnsignedIntTypeDeclaration;
dec->mInteger = ival;
ex->mDecValue = dec;
ex->mDecType = dec->mBase;
return ex;
}
else if ((mLeft->mDecValue->mType == DT_CONST_INTEGER || mLeft->mDecValue->mType == DT_CONST_FLOAT) && (mRight->mDecValue->mType == DT_CONST_INTEGER || mRight->mDecValue->mType == DT_CONST_FLOAT))
{
double dval;
double dleft = mLeft->mDecValue->mType == DT_CONST_INTEGER ? mLeft->mDecValue->mInteger : mLeft->mDecValue->mNumber;
double dright = mRight->mDecValue->mType == DT_CONST_INTEGER ? mRight->mDecValue->mInteger : mRight->mDecValue->mNumber;
switch (mToken)
{
case TK_ADD:
dval = dleft + dright;
break;
case TK_SUB:
dval = dleft - dright;
break;
case TK_MUL:
dval = dleft * dright;
break;
case TK_DIV:
dval = dleft / dright;
break;
default:
dval = 0;
}
Expression* ex = new Expression(mLocation, EX_CONSTANT);
Declaration* dec = new Declaration(mLocation, DT_CONST_FLOAT);
dec->mBase = TheFloatTypeDeclaration;
dec->mNumber = dval;
ex->mDecValue = dec;
ex->mDecType = dec->mBase;
return ex;
}
}
return this;
}
Declaration::Declaration(const Location& loc, DecType type)
: mLocation(loc), mType(type), mScope(nullptr), mData(nullptr), mIdent(nullptr), mSize(0), mOffset(0), mFlags(0), mBase(nullptr), mParams(nullptr), mValue(nullptr), mNext(nullptr)
{}
Declaration::~Declaration(void)
{
delete mScope;
delete[] mData;
}
bool Declaration::IsSubType(const Declaration* dec) const
{
if (this == dec)
return true;
if (mType != dec->mType)
return false;
if (mSize != dec->mSize)
return false;
if ((mFlags & DTF_SIGNED) != (dec->mFlags & DTF_SIGNED))
return false;
if ((dec->mFlags & ~mFlags) & (DTF_CONST | DTF_VOLATILE))
return false;
if (mType == DT_TYPE_INTEGER)
return true;
else if (mType == DT_TYPE_BOOL || mType == DT_TYPE_FLOAT || mType == DT_TYPE_VOID)
return true;
else if (mType == DT_TYPE_STRUCT || mType == DT_TYPE_ENUM)
return false;
else if (mType == DT_TYPE_POINTER || mType == DT_TYPE_ARRAY)
return mBase->IsSubType(dec->mBase);
else if (mType == DT_TYPE_FUNCTION)
{
if (!dec->mBase->IsSubType(mBase))
return false;
Declaration* dl = mParams, * dr = dec->mParams;
while (dl && dr)
{
if (!dl->mBase->IsSubType(dr->mBase))
return false;
dl = dl->mNext;
dr = dr->mNext;
}
if (dl || dr)
return false;
if ((mFlags & DTF_VARIADIC) != (dec->mFlags & DTF_VARIADIC))
return false;
return true;
}
return false;
}
bool Declaration::IsSame(const Declaration* dec) const
{
if (this == dec)
return true;
if (mType != dec->mType)
return false;
if (mSize != dec->mSize)
return false;
if ((mFlags & (DTF_SIGNED | DTF_CONST | DTF_VOLATILE)) != (dec->mFlags & (DTF_SIGNED | DTF_CONST | DTF_VOLATILE)))
return false;
if (mType == DT_TYPE_INTEGER)
return true;
else if (mType == DT_TYPE_BOOL || mType == DT_TYPE_FLOAT || mType == DT_TYPE_VOID)
return true;
else if (mType == DT_TYPE_STRUCT || mType == DT_TYPE_ENUM)
return false;
else if (mType == DT_TYPE_POINTER || mType == DT_TYPE_ARRAY)
return mBase->IsSame(dec->mBase);
else if (mType == DT_TYPE_FUNCTION)
{
if (!mBase->IsSame(dec->mBase))
return false;
Declaration* dl = mParams, * dr = dec->mParams;
while (dl && dr)
{
if (!dl->mBase->IsSame(dr->mBase))
return false;
dl = dl->mNext;
dr = dr->mNext;
}
if (dl || dr)
return false;
if ((mFlags & DTF_VARIADIC) != (dec->mFlags & DTF_VARIADIC))
return false;
return true;
}
return false;
}
bool Declaration::CanAssign(const Declaration* fromType) const
{
if (this->IsSame(fromType))
return true;
else if (IsNumericType())
{
if (fromType->IsNumericType())
return true;
}
else if (mType == DT_TYPE_POINTER)
{
if (fromType->mType == DT_TYPE_POINTER || fromType->mType == DT_TYPE_ARRAY)
{
if (mBase->mType == DT_TYPE_VOID || fromType->mBase->mType == DT_TYPE_VOID)
return true;
else if (mBase->IsSubType(fromType->mBase))
return true;
}
else if (mBase->mType == DT_TYPE_FUNCTION && fromType->mType == DT_TYPE_FUNCTION)
{
return mBase->IsSame(fromType);
}
}
return false;
}
bool Declaration::IsIntegerType(void) const
{
return mType == DT_TYPE_INTEGER || mType == DT_TYPE_BOOL || mType == DT_TYPE_ENUM;
}
bool Declaration::IsNumericType(void) const
{
return mType == DT_TYPE_INTEGER || mType == DT_TYPE_BOOL || mType == DT_TYPE_FLOAT || mType == DT_TYPE_ENUM;
}
Declaration* TheVoidTypeDeclaration, * TheSignedIntTypeDeclaration, * TheUnsignedIntTypeDeclaration, * TheConstSignedCharTypeDeclaration, * TheSignedCharTypeDeclaration, * TheUnsignedCharTypeDeclaration, * TheBoolTypeDeclaration, * TheFloatTypeDeclaration, * TheVoidPointerTypeDeclaration;
void InitDeclarations(void)
{
static Location noloc;
TheVoidTypeDeclaration = new Declaration(noloc, DT_TYPE_VOID);
TheVoidTypeDeclaration->mFlags = DTF_DEFINED;
TheVoidPointerTypeDeclaration = new Declaration(noloc, DT_TYPE_POINTER);
TheVoidPointerTypeDeclaration->mBase = TheVoidTypeDeclaration;
TheVoidPointerTypeDeclaration->mSize = 2;
TheVoidPointerTypeDeclaration->mFlags = DTF_DEFINED;
TheSignedIntTypeDeclaration = new Declaration(noloc, DT_TYPE_INTEGER);
TheSignedIntTypeDeclaration->mSize = 2;
TheSignedIntTypeDeclaration->mFlags = DTF_DEFINED | DTF_SIGNED;
TheUnsignedIntTypeDeclaration = new Declaration(noloc, DT_TYPE_INTEGER);
TheUnsignedIntTypeDeclaration->mSize = 2;
TheUnsignedIntTypeDeclaration->mFlags = DTF_DEFINED;
TheSignedCharTypeDeclaration = new Declaration(noloc, DT_TYPE_INTEGER);
TheSignedCharTypeDeclaration->mSize = 1;
TheSignedCharTypeDeclaration->mFlags = DTF_DEFINED | DTF_SIGNED;
TheConstSignedCharTypeDeclaration = new Declaration(noloc, DT_TYPE_INTEGER);
TheConstSignedCharTypeDeclaration->mSize = 1;
TheConstSignedCharTypeDeclaration->mFlags = DTF_DEFINED | DTF_SIGNED | DTF_CONST;
TheUnsignedCharTypeDeclaration = new Declaration(noloc, DT_TYPE_INTEGER);
TheUnsignedCharTypeDeclaration->mSize = 1;
TheUnsignedCharTypeDeclaration->mFlags = DTF_DEFINED;
TheBoolTypeDeclaration = new Declaration(noloc, DT_TYPE_BOOL);
TheBoolTypeDeclaration->mSize = 1;
TheBoolTypeDeclaration->mFlags = DTF_DEFINED;
TheFloatTypeDeclaration = new Declaration(noloc, DT_TYPE_FLOAT);
TheFloatTypeDeclaration->mSize = 4;
TheFloatTypeDeclaration->mFlags = DTF_DEFINED | DTF_SIGNED;
}

165
oscar64/Declaration.h Normal file
View File

@ -0,0 +1,165 @@
#pragma once
#include "Ident.h"
#include "Scanner.h"
#include "MachineTypes.h"
#include "Assembler.h"
enum DecType
{
DT_TYPE_VOID,
DT_TYPE_NULL,
DT_TYPE_BOOL,
DT_TYPE_INTEGER,
DT_TYPE_FLOAT,
DT_TYPE_ENUM,
DT_TYPE_POINTER,
DT_TYPE_ARRAY,
DT_TYPE_STRUCT,
DT_TYPE_UNION,
DT_TYPE_FUNCTION,
DT_TYPE_ASSEMBLER,
DT_TYPE_CONST,
DT_TYPE_VOLATILE,
DT_CONST_INTEGER,
DT_CONST_FLOAT,
DT_CONST_FUNCTION,
DT_CONST_ADDRESS,
DT_CONST_DATA,
DT_CONST_STRUCT,
DT_CONST_POINTER,
DT_CONST_ASSEMBLER,
DT_VARIABLE,
DT_ARGUMENT,
DT_ELEMENT,
DT_ANON,
DT_LABEL,
DT_VARIABLE_REF,
DT_LABEL_REF
};
// TypeFlags
static const uint32 DTF_SIGNED = 0x00000001;
static const uint32 DTF_DEFINED = 0x00000002;
static const uint32 DTF_GLOBAL = 0x00000004;
static const uint32 DTF_VARIADIC = 0x00000008;
static const uint32 DTF_INTRINSIC = 0x00000010;
static const uint32 DTF_STATIC = 0x00000020;
static const uint32 DTF_CONST = 0x00000040;
static const uint32 DTF_VOLATILE = 0x00000080;
static const uint32 DTF_EXTERN = 0x00000100;
class Declaration;
class DeclarationScope
{
public:
DeclarationScope(DeclarationScope * parent);
~DeclarationScope(void);
Declaration* Insert(const Ident* ident, Declaration* dec);
Declaration* Lookup(const Ident* ident);
DeclarationScope* mParent;
protected:
struct Entry
{
const Ident* mIdent;
Declaration* mDec;
};
Entry * mHash;
int mHashSize, mHashFill;
};
enum ExpressionType
{
EX_ERROR,
EX_VOID,
EX_CONSTANT,
EX_VARIABLE,
EX_ASSIGNMENT,
EX_BINARY,
EX_RELATIONAL,
EX_PREINCDEC,
EX_PREFIX,
EX_POSTFIX,
EX_POSTINCDEC,
EX_INDEX,
EX_QUALIFY,
EX_CALL,
EX_LIST,
EX_RETURN,
EX_SEQUENCE,
EX_WHILE,
EX_IF,
EX_ELSE,
EX_FOR,
EX_DO,
EX_BREAK,
EX_CONTINUE,
EX_TYPE,
EX_TYPECAST,
EX_LOGICAL_AND,
EX_LOGICAL_OR,
EX_LOGICAL_NOT,
EX_ASSEMBLER,
EX_UNDEFINED,
EX_SWITCH,
EX_CASE,
EX_DEFAULT,
EX_CONDITIONAL
};
class Expression
{
public:
Expression(const Location& loc, ExpressionType type);
~Expression(void);
Location mLocation;
ExpressionType mType;
Expression * mLeft, * mRight;
Token mToken;
Declaration * mDecValue, * mDecType;
AsmInsType mAsmInsType;
AsmInsMode mAsmInsMode;
bool mConst;
Expression* LogicInvertExpression(void);
Expression* ConstantFold(void);
};
class Declaration
{
public:
Declaration(const Location & loc, DecType type);
~Declaration(void);
Location mLocation;
DecType mType;
Token mToken;
Declaration* mBase, *mParams, * mNext;
Expression* mValue;
DeclarationScope* mScope;
int mOffset, mSize, mVarIndex;
__int64 mInteger;
double mNumber;
uint32 mFlags;
const Ident * mIdent;
const uint8* mData;
bool CanAssign(const Declaration* fromType) const;
bool IsSame(const Declaration* dec) const;
bool IsSubType(const Declaration* dec) const;
bool IsIntegerType(void) const;
bool IsNumericType(void) const;
};
void InitDeclarations(void);
extern Declaration* TheVoidTypeDeclaration, * TheSignedIntTypeDeclaration, * TheUnsignedIntTypeDeclaration, * TheConstSignedCharTypeDeclaration, * TheSignedCharTypeDeclaration, * TheUnsignedCharTypeDeclaration, * TheBoolTypeDeclaration, * TheFloatTypeDeclaration, * TheVoidPointerTypeDeclaration;

608
oscar64/Emulator.cpp Normal file
View File

@ -0,0 +1,608 @@
#include "Emulator.h"
#include <stdio.h>
Emulator::Emulator(void)
{
for (int i = 0; i < 0x10000; i++)
mMemory[i] = 0;
}
Emulator::~Emulator(void)
{
}
static const uint8 STATUS_SIGN = 0x80;
static const uint8 STATUS_OVERFLOW = 0x40;
static const uint8 STATUS_ZERO = 0x02;
static const uint8 STATUS_CARRY = 0x01;
void Emulator::UpdateStatus(uint8 result)
{
mRegP &= ~(STATUS_ZERO | STATUS_SIGN);
if (result == 0) mRegP |= STATUS_ZERO;
if (result & 0x80) mRegP |= STATUS_SIGN;
}
void Emulator::UpdateStatusCarry(uint8 result, bool carry)
{
mRegP &= ~(STATUS_ZERO | STATUS_SIGN | STATUS_CARRY);
if (result == 0) mRegP |= STATUS_ZERO;
if (result & 0x80) mRegP |= STATUS_SIGN;
if (carry)
mRegP |= STATUS_CARRY;
}
void Emulator::DumpCycles(void)
{
int numTops = 0;
int topIP[101], topCycles[101];
int totalCycles = 0;
for (int i = 0; i < 0x10000; i++)
{
int cycles = mCycles[i];
totalCycles += cycles;
if (cycles > 0)
{
if (numTops == 0 || cycles > topCycles[numTops])
{
if (numTops < 40)
numTops++;
int j = numTops;
while (j > 0 && topCycles[j-1] < cycles)
{
topCycles[j] = topCycles[j - 1];
topIP[j] = topIP[j - 1];
j--;
}
topCycles[j] = cycles;
topIP[j] = i;
}
}
}
printf("Total Cycles %d\n", totalCycles);
return;
for (int i = 0; i < numTops; i++)
{
printf(" %2d : %04x : %d\n", i, topIP[i], topCycles[i]);
}
}
bool Emulator::EmulateInstruction(AsmInsType type, AsmInsMode mode, int addr, int & cycles)
{
int t;
switch (type)
{
case ASMIT_ADC:
if (mode != ASMIM_IMMEDIATE)
addr = mMemory[addr];
t = mRegA + addr + (mRegP & STATUS_CARRY);
mRegP = 0;
if ((mRegA & 0x80) && (addr & 0x80) && !(t & 0x80) ||
!(mRegA & 0x80) && !(addr & 0x80) && (t & 0x80))
mRegP |= STATUS_OVERFLOW;
mRegA = (t & 255);
UpdateStatusCarry(mRegA, t >= 256);
break;
case ASMIT_AND:
if (mode != ASMIM_IMMEDIATE)
addr = mMemory[addr];
mRegA &= addr;
UpdateStatus(mRegA);
break;
case ASMIT_ASL:
if (mode == ASMIM_IMPLIED)
{
t = mRegA << 1;
mRegA = (t & 255);
UpdateStatusCarry(mRegA, t >= 256);
}
else
{
t = mMemory[addr] << 1;
mMemory[addr] = t & 255;
UpdateStatusCarry(t & 255, t >= 256);
cycles += 2;
}
break;
case ASMIT_BCC:
if (!(mRegP & STATUS_CARRY))
mIP = addr;
break;
case ASMIT_BCS:
if ((mRegP & STATUS_CARRY))
mIP = addr;
break;
case ASMIT_BEQ:
if ((mRegP & STATUS_ZERO))
mIP = addr;
break;
case ASMIT_BIT:
t = mMemory[addr];
mRegP &= ~(STATUS_ZERO | STATUS_SIGN | STATUS_OVERFLOW);
if (t & 0x80) mRegP |= STATUS_SIGN;
if (t & 0x40) mRegP |= STATUS_OVERFLOW;
if (!(t & mRegA)) mRegP |= STATUS_ZERO;
break;
case ASMIT_BMI:
if ((mRegP & STATUS_SIGN))
{
mIP = addr;
cycles++;
}
break;
case ASMIT_BNE:
if (!(mRegP & STATUS_ZERO))
{
mIP = addr;
cycles++;
}
break;
case ASMIT_BPL:
if (!(mRegP & STATUS_SIGN))
{
mIP = addr;
cycles++;
}
break;
case ASMIT_BRK:
return false;
break;
case ASMIT_BVC:
if (!(mRegP & STATUS_OVERFLOW))
{
mIP = addr;
cycles++;
}
break;
case ASMIT_BVS:
if ((mRegP & STATUS_OVERFLOW))
{
mIP = addr;
cycles++;
}
break;
case ASMIT_CLC:
mRegP &= ~STATUS_CARRY;
break;
case ASMIT_CLD:
break;
case ASMIT_CLI:
break;
case ASMIT_CLV:
mRegP &= ~STATUS_OVERFLOW;
break;
case ASMIT_CMP:
if (mode != ASMIM_IMMEDIATE)
addr = mMemory[addr];
t = mRegA + (addr ^ 0xff) + 1;
mRegP = 0;
if ((mRegA & 0x80) && !(addr & 0x80) && !(t & 0x80) ||
!(mRegA & 0x80) && (addr & 0x80) && (t & 0x80))
mRegP |= STATUS_OVERFLOW;
UpdateStatusCarry(t & 255, t >= 256);
break;
case ASMIT_CPX:
if (mode != ASMIM_IMMEDIATE)
addr = mMemory[addr];
t = mRegX + (addr ^ 0xff) + 1;
mRegP = 0;
if ((mRegX & 0x80) && !(addr & 0x80) && !(t & 0x80) ||
!(mRegX & 0x80) && (addr & 0x80) && (t & 0x80))
mRegP |= STATUS_OVERFLOW;
UpdateStatusCarry(t & 255, t >= 256);
break;
case ASMIT_CPY:
if (mode != ASMIM_IMMEDIATE)
addr = mMemory[addr];
t = mRegY + (addr ^ 0xff) + 1;
mRegP = 0;
if ((mRegY & 0x80) && !(addr & 0x80) && !(t & 0x80) ||
!(mRegY & 0x80) && (addr & 0x80) && (t & 0x80))
mRegP |= STATUS_OVERFLOW;
UpdateStatusCarry(t & 255, t >= 256);
break;
case ASMIT_DEC:
if (mode == ASMIM_IMPLIED)
{
t = mRegA - 1;
mRegA = (t & 255);
UpdateStatus(mRegA);
}
else
{
t = mMemory[addr] - 1;
mMemory[addr] = t & 255;
UpdateStatus(t & 255);
cycles += 2;
}
break;
case ASMIT_DEX:
t = mRegX - 1;
mRegX = (t & 255);
UpdateStatus(mRegX);
break;
case ASMIT_DEY:
t = mRegY - 1;
mRegY = (t & 255);
UpdateStatus(mRegY);
break;
case ASMIT_EOR:
if (mode != ASMIM_IMMEDIATE)
addr = mMemory[addr];
mRegA ^= addr;
UpdateStatus(mRegA);
break;
case ASMIT_INC:
if (mode == ASMIM_IMPLIED)
{
t = mRegA + 1;
mRegA = (t & 255);
UpdateStatus(mRegA);
}
else
{
t = mMemory[addr] + 1;
mMemory[addr] = t & 255;
UpdateStatus(t & 255);
cycles += 2;
}
break;
case ASMIT_INX:
t = mRegX + 1;
mRegX = (t & 255);
UpdateStatus(mRegX);
break;
case ASMIT_INY:
t = mRegY + 1;
mRegY = (t & 255);
UpdateStatus(mRegY);
break;
case ASMIT_JMP:
mIP = addr;
break;
case ASMIT_JSR:
mRegS--;
mMemory[0x100 + mRegS] = (mIP - 1) >> 8;
mRegS--;
mMemory[0x100 + mRegS] = (mIP - 1) & 0xff;
mIP = addr;
cycles += 2;
break;
case ASMIT_LDA:
if (mode != ASMIM_IMMEDIATE)
addr = mMemory[addr];
mRegA = addr;
UpdateStatus(mRegA);
break;
case ASMIT_LDX:
if (mode != ASMIM_IMMEDIATE)
addr = mMemory[addr];
mRegX = addr;
UpdateStatus(mRegX);
break;
case ASMIT_LDY:
if (mode != ASMIM_IMMEDIATE)
addr = mMemory[addr];
mRegY = addr;
UpdateStatus(mRegY);
break;
case ASMIT_LSR:
if (mode == ASMIM_IMPLIED)
{
int c = mRegA & 1;
t = mRegA >> 1;
mRegA = (t & 255);
UpdateStatusCarry(mRegA, c != 0);
}
else
{
int c = mMemory[addr] & 1;
t = mMemory[addr] >> 1;
mMemory[addr] = t & 255;
UpdateStatusCarry(t & 255, c != 0);
cycles += 2;
}
break;
case ASMIT_NOP:
break;
case ASMIT_ORA:
if (mode != ASMIM_IMMEDIATE)
addr = mMemory[addr];
mRegA |= addr;
UpdateStatus(mRegA);
break;
case ASMIT_PHA:
mRegS--;
mMemory[0x100 + mRegS] = mRegA;
cycles ++;
break;
case ASMIT_PHP:
mRegS--;
mMemory[0x100 + mRegS] = mRegP;
cycles++;
break;
case ASMIT_PLA:
mRegA = mMemory[0x100 + mRegS];
mRegS++;
cycles++;
break;
case ASMIT_PLP:
mRegP = mMemory[0x100 + mRegS];
mRegS++;
cycles++;
break;
case ASMIT_ROL:
if (mode == ASMIM_IMPLIED)
{
t = (mRegA << 1) | (mRegP & STATUS_CARRY);
mRegA = (t & 255);
UpdateStatusCarry(mRegA, t >= 256);
}
else
{
t = (mMemory[addr] << 1) | (mRegP & STATUS_CARRY);;
mMemory[addr] = t & 255;
UpdateStatusCarry(t & 255, t >= 256);
cycles+=2;
}
break;
case ASMIT_ROR:
if (mode == ASMIM_IMPLIED)
{
int c = mRegA & 1;
t = (mRegA >> 1) | ((mRegP & STATUS_CARRY) << 7);
mRegA = (t & 255);
UpdateStatusCarry(mRegA, c != 0);
}
else
{
int c = mMemory[addr] & 1;
t = (mMemory[addr] >> 1) | ((mRegP & STATUS_CARRY) << 7);
mMemory[addr] = t & 255;
UpdateStatusCarry(t & 255, c != 0);
cycles++;
}
break;
case ASMIT_RTI:
break;
case ASMIT_RTS:
mIP = (mMemory[0x100 + mRegS] + 256 * mMemory[0x101 + mRegS] + 1) & 0xffff;
mRegS += 2;
cycles += 4;
break;
case ASMIT_SBC:
if (mode != ASMIM_IMMEDIATE)
addr = mMemory[addr];
t = mRegA + (addr ^ 0xff) + (mRegP & STATUS_CARRY);
mRegP = 0;
if ((mRegA & 0x80) && !(addr & 0x80) && !(t & 0x80) ||
!(mRegA & 0x80) && (addr & 0x80) && (t & 0x80))
mRegP |= STATUS_OVERFLOW;
mRegA = (t & 255);
UpdateStatusCarry(t & 255, t >= 256);
break;
case ASMIT_SEC:
mRegP |= STATUS_CARRY;
break;
case ASMIT_SED:
break;
case ASMIT_SEI:
break;
case ASMIT_STA:
mMemory[addr] = mRegA;
break;
case ASMIT_STX:
mMemory[addr] = mRegX;
break;
case ASMIT_STY:
mMemory[addr] = mRegY;
break;
case ASMIT_TAX:
mRegX = mRegA;
UpdateStatus(mRegX);
break;
case ASMIT_TAY:
mRegY = mRegA;
UpdateStatus(mRegY);
break;
case ASMIT_TSX:
mRegX = mRegS;
UpdateStatus(mRegX);
break;
case ASMIT_TXA:
mRegA = mRegX;
UpdateStatus(mRegA);
break;
case ASMIT_TXS:
mRegS = mRegX;
break;
case ASMIT_TYA:
mRegA = mRegY;
UpdateStatus(mRegA);
break;
case ASMIT_INV:
return false;
break;
}
return true;
}
int Emulator::Emulate(int startIP)
{
int trace = 0;
for (int i = 0; i < 0x10000; i++)
mCycles[i] = 0;
mIP = startIP;
mRegA = 0;
mRegX = 0;
mRegY = 0;
mRegP = 0;
mRegS = 0xfe;
mMemory[0x1fe] = 0xff;
mMemory[0x1ff] = 0xff;
while (mIP != 0)
{
if (mIP == 0xffd2)
{
if (mRegA == 13)
putchar('\n');
else
putchar(mRegA);
mIP = mMemory[0x100 + mRegS] + 256 * mMemory[0x101 + mRegS] + 1;
mRegS += 2;
}
uint8 opcode = mMemory[mIP];
AsmInsData d = DecInsData[opcode];
int addr = 0, taddr;
int ip = mIP;
int iip = mMemory[BC_REG_IP] + 256 * mMemory[BC_REG_IP + 1];
mIP++;
switch (d.mMode)
{
case ASMIM_IMPLIED:
if (trace & 2)
printf("%04x : %04x %02x __ __ %s (A:%02x X:%02x Y:%02x P:%02x S:%02x)\n", iip, ip, mMemory[ip], AsmInstructionNames[d.mType], mRegA, mRegX, mRegY, mRegP, mRegS);
mCycles[ip] += 2;
break;
case ASMIM_IMMEDIATE:
addr = mMemory[mIP++];
if (trace & 2)
printf("%04x : %04x %02x %02x __ %s #$%02x (A:%02x X:%02x Y:%02x P:%02x S:%02x)\n", iip, ip, mMemory[ip], mMemory[ip+1], AsmInstructionNames[d.mType], addr, mRegA, mRegX, mRegY, mRegP, mRegS);
mCycles[ip] += 2;
break;
case ASMIM_ZERO_PAGE:
addr = mMemory[mIP++];
if (trace & 2)
printf("%04x : %04x %02x %02x __ %s $%02x (A:%02x X:%02x Y:%02x P:%02x S:%02x)\n", iip, ip, mMemory[ip], mMemory[ip + 1], AsmInstructionNames[d.mType], addr, mRegA, mRegX, mRegY, mRegP, mRegS);
mCycles[ip] += 3;
break;
case ASMIM_ZERO_PAGE_X:
taddr = mMemory[mIP++];
addr = (taddr + mRegX) & 0xff;
if (trace & 2)
printf("%04x : %04x %02x %02x __ %s $%02x,x (A:%02x X:%02x Y:%02x P:%02x S:%02x %04x)\n", iip, ip, mMemory[ip], mMemory[ip + 1], AsmInstructionNames[d.mType], taddr, mRegA, mRegX, mRegY, mRegP, mRegS, addr);
mCycles[ip] += 3;
break;
case ASMIM_ZERO_PAGE_Y:
taddr = mMemory[mIP++];
addr = (taddr + mRegY) & 0xff;
if (trace & 2)
printf("%04x : %04x %02x %02x __ %s $%02x,y (A:%02x X:%02x Y:%02x P:%02x S:%02x %04x)\n", iip, ip, mMemory[ip], mMemory[ip + 1], AsmInstructionNames[d.mType], taddr, mRegA, mRegX, mRegY, mRegP, mRegS, addr);
mCycles[ip] += 3;
break;
case ASMIM_ABSOLUTE:
addr = mMemory[mIP] + 256 * mMemory[mIP + 1];
if (trace & 2)
printf("%04x : %04x %02x %02x %02x %s $%04x (A:%02x X:%02x Y:%02x P:%02x S:%02x)\n", iip, ip, mMemory[ip], mMemory[ip + 1], mMemory[ip + 2], AsmInstructionNames[d.mType], addr, mRegA, mRegX, mRegY, mRegP, mRegS);
mIP += 2;
mCycles[ip] += 4;
break;
case ASMIM_ABSOLUTE_X:
taddr = mMemory[mIP] + 256 * mMemory[mIP + 1];
addr = (taddr + mRegX) & 0xffff;
if (trace & 2)
printf("%04x : %04x %02x %02x %02x %s $%04x,x (A:%02x X:%02x Y:%02x P:%02x S:%02x %04x)\n", iip, ip, mMemory[ip], mMemory[ip + 1], mMemory[ip + 2], AsmInstructionNames[d.mType], taddr, mRegA, mRegX, mRegY, mRegP, mRegS, addr);
mIP += 2;
mCycles[ip] += 5;
break;
case ASMIM_ABSOLUTE_Y:
taddr = mMemory[mIP] + 256 * mMemory[mIP + 1];
addr = (taddr + mRegY) & 0xffff;
if (trace & 2)
printf("%04x : %04x %02x %02x %02x %s $%04x,y (A:%02x X:%02x Y:%02x P:%02x S:%02x %04x)\n", iip, ip, mMemory[ip], mMemory[ip + 1], mMemory[ip + 2], AsmInstructionNames[d.mType], taddr, mRegA, mRegX, mRegY, mRegP, mRegS, addr);
mIP += 2;
mCycles[ip] += 5;
break;
case ASMIM_INDIRECT:
taddr = mMemory[mIP] + 256 * mMemory[mIP + 1];
mIP += 2;
addr = mMemory[taddr] + 256 * mMemory[taddr + 1];
if (trace & 2)
printf("%04x : %04x %02x %02x %02x %s ($%04x) (A:%02x X:%02x Y:%02x P:%02x S:%02x %04x)\n", iip, ip, mMemory[ip], mMemory[ip + 1], mMemory[ip + 2], AsmInstructionNames[d.mType], taddr, mRegA, mRegX, mRegY, mRegP, mRegS, addr);
mCycles[ip] += 6;
break;
case ASMIM_INDIRECT_X:
taddr = (mMemory[mIP++] + mRegX) & 0xff;
addr = mMemory[taddr] + 256 * mMemory[taddr + 1];
if (trace & 2)
printf("%04x : %04x %02x %02x __ %s ($%02x,x) (A:%02x X:%02x Y:%02x P:%02x S:%02x %02x %04x)\n", iip, ip, mMemory[ip], mMemory[ip + 1], AsmInstructionNames[d.mType], mMemory[ip + 1], mRegA, mRegX, mRegY, mRegP, mRegS, taddr, addr);
mCycles[ip] += 5;
break;
case ASMIM_INDIRECT_Y:
taddr = mMemory[mIP++];
addr = (mMemory[taddr] + 256 * mMemory[taddr + 1] + mRegY) & 0xffff;
if (trace & 2)
printf("%04x : %04x %02x %02x __ %s ($%02x),y (A:%02x X:%02x Y:%02x P:%02x S:%02x %04x)\n", iip, ip, mMemory[ip], mMemory[ip + 1], AsmInstructionNames[d.mType], taddr, mRegA, mRegX, mRegY, mRegP, mRegS, addr);
mCycles[ip] += 4;
break;
case ASMIM_RELATIVE:
taddr = mMemory[mIP++];
if (taddr & 0x80)
addr = taddr + mIP - 256;
else
addr = taddr + mIP;
if (trace & 2)
printf("%04x : %04x %02x %02x __ %s $%02x (A:%02x X:%02x Y:%02x P:%02x S:%02x %04x)\n", iip, ip, mMemory[ip], mMemory[ip + 1], AsmInstructionNames[d.mType], taddr, mRegA, mRegX, mRegY, mRegP, mRegS, addr);
mCycles[ip] += 2;
break;
}
if ((trace & 1) && ip == 0x0823)
{
int accu = mMemory[BC_REG_ACCU] + 256 * mMemory[BC_REG_ACCU + 1];
int ptr = mMemory[BC_REG_ADDR] + 256 * mMemory[BC_REG_ADDR + 1];
int sp = mMemory[BC_REG_STACK] + 256 * mMemory[BC_REG_STACK + 1];
printf("%04x (A:%04x P:%04x S:%04x) %04x %04x %04x %04x %04x %04x %04x %04x\n", addr, accu, ptr, sp,
mMemory[BC_REG_TMP + 0] + 256 * mMemory[BC_REG_TMP + 1],
mMemory[BC_REG_TMP + 2] + 256 * mMemory[BC_REG_TMP + 3],
mMemory[BC_REG_TMP + 4] + 256 * mMemory[BC_REG_TMP + 5],
mMemory[BC_REG_TMP + 6] + 256 * mMemory[BC_REG_TMP + 7],
mMemory[BC_REG_TMP + 8] + 256 * mMemory[BC_REG_TMP + 9],
mMemory[BC_REG_TMP + 10] + 256 * mMemory[BC_REG_TMP + 11],
mMemory[BC_REG_TMP + 12] + 256 * mMemory[BC_REG_TMP + 13],
mMemory[BC_REG_TMP + 14] + 256 * mMemory[BC_REG_TMP + 15]
);
}
if (!EmulateInstruction(d.mType, d.mMode, addr, mCycles[ip]))
return -1;
}
if (mRegS == 0)
{
DumpCycles();
return int16(mMemory[BC_REG_ACCU] + 256 * mMemory[BC_REG_ACCU + 1]);
}
return -1;
}

24
oscar64/Emulator.h Normal file
View File

@ -0,0 +1,24 @@
#pragma once
#include "Assembler.h"
#include "MachineTypes.h"
class Emulator
{
public:
Emulator(void);
~Emulator(void);
uint8 mMemory[0x10000];
int mCycles[0x10000];
int mIP;
uint8 mRegA, mRegX, mRegY, mRegS, mRegP;
int Emulate(int startIP);
bool EmulateInstruction(AsmInsType type, AsmInsMode mode, int addr, int & cycles);
protected:
void UpdateStatus(uint8 result);
void UpdateStatusCarry(uint8 result, bool carry);
void DumpCycles(void);
};

33
oscar64/Errors.cpp Normal file
View File

@ -0,0 +1,33 @@
#include "Errors.h"
#include <stdio.h>
#include <stdlib.h>
Errors::Errors(void)
: mErrorCount(0)
{
}
void Errors::Warning(const Location& loc, const char* error)
{
printf("Warning %s in %s: %d, %d\n", error, loc.mFileName, loc.mLine, loc.mColumn);
}
void Errors::Error(const Location& loc, const char* error)
{
printf("Error %s in %s: %d, %d\n", error, loc.mFileName, loc.mLine, loc.mColumn);
mErrorCount++;
if (mErrorCount > 10)
exit(10);
}
void Errors::Error(const Location& loc, const char* error, const char* info)
{
printf("Error %s '%s' in %s: %d, %d\n", error, info, loc.mFileName, loc.mLine, loc.mColumn);
mErrorCount++;
if (mErrorCount > 10)
exit(10);
}

23
oscar64/Errors.h Normal file
View File

@ -0,0 +1,23 @@
#pragma once
class Location
{
public:
const char* mFileName;
int mLine, mColumn;
Location() : mFileName(nullptr), mLine(0), mColumn(0) {}
};
class Errors
{
public:
Errors(void);
int mErrorCount;
void Error(const Location& loc, const char* msg);
void Error(const Location& loc, const char* msg, const char * info);
void Warning(const Location& loc, const char* msg);
};

138
oscar64/Ident.cpp Normal file
View File

@ -0,0 +1,138 @@
#include "Ident.h"
#include <string.h>
Ident::~Ident()
{
delete[] mString;
}
unsigned int IHash(const char* str)
{
unsigned int hash = 32324124;
int i = 0;
while (str[i])
{
hash = hash * 123211 + str[i];
i++;
}
return hash;
}
Ident::Ident(const char* str, unsigned int hash)
{
ptrdiff_t ssize = strlen(str);
mString = new char[ssize + 1];
strcpy_s(mString, ssize + 1, str);
mHash = hash;
}
Ident * UniqueIdents[0x10000];
const Ident* Ident::Unique(const char* str)
{
unsigned int hash = IHash(str);
int i = hash & 0xffff;
while (UniqueIdents[i])
{
if (!strcmp(UniqueIdents[i]->mString, str))
return UniqueIdents[i];
i = (i + 1) & 0xffff;
}
return UniqueIdents[i] = new Ident(str, hash);
}
IdentDict::IdentDict(void)
{
mHashSize = 0;
mHashFill = 0;
mHash = nullptr;
}
IdentDict::~IdentDict(void)
{
delete[] mHash;
}
void IdentDict::Insert(const Ident* ident, const char* str)
{
int s = strlen(str);
char* nstr = new char[s + 1];
strcpy_s(nstr, s + 1, str);
InsertCopy(ident, nstr);
}
void IdentDict::InsertCopy(const Ident* ident, char* str)
{
if (!mHash)
{
mHashSize = 16;
mHashFill = 0;
mHash = new Entry[mHashSize];
for (int i = 0; i < mHashSize; i++)
{
mHash[i].mString = nullptr;
mHash[i].mIdent = nullptr;
}
}
int hm = mHashSize - 1;
int hi = ident->mHash & hm;
while (mHash[hi].mIdent)
{
if (ident == mHash[hi].mIdent)
{
mHash[hi].mString = str;
return;
}
hi = (hi + 1) & hm;
}
mHash[hi].mIdent = ident;
mHash[hi].mString = str;
mHashFill++;
if (2 * mHashFill >= mHashSize)
{
int size = mHashSize;
Entry* entries = mHash;
mHashSize *= 2;
mHashFill = 0;
mHash = new Entry[mHashSize];
for (int i = 0; i < mHashSize; i++)
{
mHash[i].mString = nullptr;
mHash[i].mIdent = nullptr;
}
for (int i = 0; i < size; i++)
{
if (entries[i].mIdent)
InsertCopy(entries[i].mIdent, entries[i].mString);
}
delete[] entries;
}
}
const char * IdentDict::Lookup(const Ident* ident)
{
if (mHashSize > 0)
{
int hm = mHashSize - 1;
int hi = ident->mHash & hm;
while (mHash[hi].mIdent)
{
if (ident == mHash[hi].mIdent)
return mHash[hi].mString;
hi = (hi + 1) & hm;
}
}
return nullptr;
}

35
oscar64/Ident.h Normal file
View File

@ -0,0 +1,35 @@
#pragma once
class Ident
{
public:
~Ident();
char * mString;
unsigned int mHash;
static const Ident* Unique(const char* str);
protected:
Ident(const char* str, unsigned int hash);
};
class IdentDict
{
public:
IdentDict(void);
~IdentDict(void);
void Insert(const Ident* ident, const char * str);
const char * Lookup(const Ident* ident);
protected:
void InsertCopy(const Ident* ident, char* str);
struct Entry
{
const Ident* mIdent;
char* mString;
};
Entry* mHash;
int mHashSize, mHashFill;
};

3355
oscar64/InterCode.cpp Normal file

File diff suppressed because it is too large Load Diff

486
oscar64/InterCode.h Normal file
View File

@ -0,0 +1,486 @@
#pragma once
#include "Array.h"
#include "NumberSet.h"
#include "Errors.h"
#include "BitVector.h"
#include <stdio.h>
#include "MachineTypes.h"
#include "Ident.h"
enum InterCode
{
IC_NONE,
IC_LOAD_TEMPORARY,
IC_STORE_TEMPORARY,
IC_BINARY_OPERATOR,
IC_UNARY_OPERATOR,
IC_RELATIONAL_OPERATOR,
IC_CONVERSION_OPERATOR,
IC_STORE,
IC_LOAD,
IC_LEA,
IC_COPY,
IC_TYPECAST,
IC_CONSTANT,
IC_BRANCH,
IC_JUMP,
IC_PUSH_FRAME,
IC_POP_FRAME,
IC_CALL,
IC_JSR,
IC_RETURN_VALUE,
IC_RETURN_STRUCT,
IC_RETURN
};
enum InterType
{
IT_NONE,
IT_UNSIGNED,
IT_SIGNED,
IT_FLOAT,
IT_POINTER,
IT_BOOL
};
enum InterMemory
{
IM_NONE,
IM_PARAM,
IM_LOCAL,
IM_GLOBAL,
IM_FRAME,
IM_PROCEDURE,
IM_INDIRECT,
IM_TEMPORARY,
IM_ABSOLUTE
};
enum InterOperator
{
IA_NONE,
IA_ADD,
IA_SUB,
IA_MUL,
IA_DIVU,
IA_DIVS,
IA_MODU,
IA_MODS,
IA_OR,
IA_AND,
IA_XOR,
IA_NEG,
IA_ABS,
IA_FLOOR,
IA_CEIL,
IA_NOT,
IA_SHL,
IA_SHR,
IA_SAR,
IA_CMPEQ,
IA_CMPNE,
IA_CMPGES,
IA_CMPLES,
IA_CMPGS,
IA_CMPLS,
IA_CMPGEU,
IA_CMPLEU,
IA_CMPGU,
IA_CMPLU,
IA_FLOAT2INT,
IA_INT2FLOAT
};
class InterInstruction;
class InterCodeBasicBlock;
class InterCodeProcedure;
class InterVariable;
typedef InterInstruction* InterInstructionPtr;
typedef InterCodeBasicBlock* InterCodeBasicBlockPtr;
typedef InterCodeProcedure* InterCodeProcedurePtr;
typedef GrowingArray<InterType> GrowingTypeArray;
typedef GrowingArray<int> GrowingIntArray;
typedef GrowingArray<InterInstructionPtr> GrowingInstructionPtrArray;
typedef GrowingArray<InterCodeBasicBlockPtr> GrowingInterCodeBasicBlockPtrArray;
typedef GrowingArray<InterInstruction> GrowingInstructionArray;
typedef GrowingArray<InterCodeProcedurePtr > GrowingInterCodeProcedurePtrArray;
typedef GrowingArray<InterVariable> GrowingVariableArray;
#define INVALID_TEMPORARY (-1)
class ValueSet
{
protected:
InterInstructionPtr * instructions;
int num, size;
public:
ValueSet(void);
ValueSet(const ValueSet& values);
~ValueSet(void);
void FlushAll(void);
void FlushCallAliases(void);
void RemoveValue(int index);
void InsertValue(InterInstruction& ins);
void UpdateValue(InterInstruction& ins, const GrowingInstructionPtrArray& tvalue, const NumberSet& aliasedLocals);
};
class TempForwardingTable
{
protected:
struct Assoc
{
int assoc, succ, pred;
Assoc(void) {}
Assoc(int assoc, int succ, int pred) { this->assoc = assoc; this->succ = succ; this->pred = pred; }
Assoc(const Assoc& assoc) { this->assoc = assoc.assoc; this->succ = assoc.succ; this->pred = assoc.pred; }
};
GrowingArray<Assoc> assoc;
public:
TempForwardingTable(void) : assoc(Assoc(-1, -1, -1))
{
}
TempForwardingTable(const TempForwardingTable & table) : assoc(Assoc(-1, -1, -1))
{
for (int i = 0; i < table.assoc.Size(); i++)
{
assoc[i].assoc = table.assoc[i].assoc;
assoc[i].succ = table.assoc[i].succ;
assoc[i].pred = table.assoc[i].pred;
}
}
void SetSize(int size)
{
int i;
assoc.SetSize(size);
for (i = 0; i < size; i++)
assoc[i] = Assoc(i, i, i);
}
void Reset(void)
{
int i;
for (i = 0; i < assoc.Size(); i++)
assoc[i] = Assoc(i, i, i);
}
int operator[](int n)
{
return assoc[n].assoc;
}
void Destroy(int n)
{
int i, j;
if (assoc[n].assoc == n)
{
i = assoc[n].succ;
while (i != n)
{
j = assoc[i].succ;
assoc[i] = Assoc(i, i, i);
i = j;
}
}
else
{
assoc[assoc[n].pred].succ = assoc[n].succ;
assoc[assoc[n].succ].pred = assoc[n].pred;
}
assoc[n] = Assoc(n, n, n);
}
void Build(int from, int to)
{
int i;
from = assoc[from].assoc;
to = assoc[to].assoc;
if (from != to)
{
i = assoc[from].succ;
while (i != from)
{
assoc[i].assoc = to;
i = assoc[i].succ;
}
assoc[from].assoc = to;
assoc[assoc[to].succ].pred = assoc[from].pred;
assoc[assoc[from].pred].succ = assoc[to].succ;
assoc[to].succ = from;
assoc[from].pred = to;
}
}
};
class InterVariable
{
public:
bool mUsed, mAliased, mPlaced, mAssembler;
int mIndex, mSize, mOffset, mAddr;
int mNumReferences;
const uint8 * mData;
const Ident * mIdent;
struct Reference
{
uint16 mAddr;
bool mFunction, mLower, mUpper;
uint16 mIndex, mOffset;
} *mReferences;
InterVariable(void)
: mUsed(false), mAliased(false), mPlaced(false), mIndex(-1), mSize(0), mOffset(0), mNumReferences(0), mData(nullptr), mIdent(nullptr), mReferences(nullptr), mAssembler(false)
{
}
};
class InterInstruction
{
public:
InterCode code;
InterType ttype, stype[3];
int ttemp, stemp[3];
bool sfinal[3];
__int64 siconst[3];
double sfconst[3];
int spconst[3];
InterMemory mem;
InterOperator oper;
int opsize;
int vindex;
__int64 ivalue;
double fvalue;
bool zeroFrame;
Location loc;
InterCodeBasicBlock * exceptionJump;
InterInstruction(void);
void SetCode(const Location & loc, InterCode code);
void CollectLocalAddressTemps(GrowingIntArray& localTable);
void MarkAliasedLocalTemps(const GrowingIntArray& localTable, NumberSet& aliasedLocals);
void FilterTempUsage(NumberSet& requiredVars, NumberSet& providedVars);
void FilterVarsUsage(const GrowingVariableArray& localVars, NumberSet& requiredTemps, NumberSet& providedTemps);
bool RemoveUnusedResultInstructions(InterInstruction* pre, NumberSet& requiredTemps, int numStaticTemps);
bool RemoveUnusedStoreInstructions(const GrowingVariableArray& localVars, InterInstruction* pre, NumberSet& requiredTemps);
void PerformValueForwarding(GrowingInstructionPtrArray& tvalue, FastNumberSet& tvalid);
void LocalRenameRegister(GrowingIntArray& renameTable, int& num, int fixed);
void GlobalRenameRegister(const GrowingIntArray& renameTable, GrowingTypeArray& temporaries);
void PerformTempForwarding(TempForwardingTable& forwardingTable);
void BuildCollisionTable(NumberSet& liveTemps, NumberSet* collisionSets);
void ReduceTemporaries(const GrowingIntArray& renameTable, GrowingTypeArray& temporaries);
void CollectActiveTemporaries(FastNumberSet& set);
void ShrinkActiveTemporaries(FastNumberSet& set, GrowingTypeArray& temporaries);
void CollectSimpleLocals(FastNumberSet& complexLocals, FastNumberSet& simpleLocals, GrowingTypeArray& localTypes);
void SimpleLocalToTemp(int vindex, int temp);
void Disassemble(FILE* file);
};
class InterCodeException
{
public:
InterCodeException()
{
}
};
class InterCodeStackException : public InterCodeException
{
public:
InterCodeStackException()
: InterCodeException()
{
}
};
class InterCodeUndefinedException : public InterCodeException
{
public:
InterCodeUndefinedException()
: InterCodeException()
{
}
};
class InterCodeTypeMismatchException : public InterCodeException
{
public:
InterCodeTypeMismatchException()
: InterCodeException()
{
}
};
class InterCodeUninitializedException : public InterCodeException
{
public:
InterCodeUninitializedException()
: InterCodeException()
{
}
};
class InterCodeBasicBlock
{
public:
int num, numEntries;
InterCodeBasicBlock* trueJump, * falseJump;
GrowingInstructionArray code;
bool visited;
int entryISP, entryPSP, entryFSP;
NumberSet localRequiredTemps, localProvidedTemps;
NumberSet entryRequiredTemps, entryProvidedTemps;
NumberSet exitRequiredTemps, exitProvidedTemps;
NumberSet mLocalRequiredVars, mLocalProvidedVars;
NumberSet mEntryRequiredVars, mEntryProvidedVars;
NumberSet mExitRequiredVars, mExitProvidedVars;
InterCodeBasicBlock(void);
~InterCodeBasicBlock(void);
void Append(InterInstruction & code);
void Close(InterCodeBasicBlock* trueJump, InterCodeBasicBlock* falseJump);
void CollectEntries(void);
void GenerateTraces(void);
void LocalToTemp(int vindex, int temp);
void CollectLocalAddressTemps(GrowingIntArray& localTable);
void MarkAliasedLocalTemps(const GrowingIntArray& localTable, NumberSet& aliasedLocals);
void BuildLocalTempSets(int num, int numFixed);
void BuildGlobalProvidedTempSet(NumberSet fromProvidedTemps);
bool BuildGlobalRequiredTempSet(NumberSet& fromRequiredTemps);
bool RemoveUnusedResultInstructions(int numStaticTemps);
void BuildLocalVariableSets(const GrowingVariableArray& localVars);
void BuildGlobalProvidedVariableSet(const GrowingVariableArray& localVars, NumberSet fromProvidedVars);
bool BuildGlobalRequiredVariableSet(const GrowingVariableArray& localVars, NumberSet& fromRequiredVars);
bool RemoveUnusedStoreInstructions(const GrowingVariableArray& localVars);
GrowingIntArray entryRenameTable;
GrowingIntArray exitRenameTable;
void LocalRenameRegister(const GrowingIntArray& renameTable, int& num, int fixed);
void BuildGlobalRenameRegisterTable(const GrowingIntArray& renameTable, GrowingIntArray& globalRenameTable);
void GlobalRenameRegister(const GrowingIntArray& renameTable, GrowingTypeArray& temporaries);
void CheckValueUsage(InterInstruction& ins, const GrowingInstructionPtrArray& tvalue);
void PerformTempForwarding(TempForwardingTable& forwardingTable);
void PerformValueForwarding(const GrowingInstructionPtrArray& tvalue, const ValueSet& values, FastNumberSet& tvalid, const NumberSet& aliasedLocals);
void PerformMachineSpecificValueUsageCheck(const GrowingInstructionPtrArray& tvalue, FastNumberSet& tvalid);
void BuildCollisionTable(NumberSet* collisionSets);
void ReduceTemporaries(const GrowingIntArray& renameTable, GrowingTypeArray& temporaries);
void CollectSimpleLocals(FastNumberSet& complexLocals, FastNumberSet& simpleLocals, GrowingTypeArray & localTypes);
void SimpleLocalToTemp(int vindex, int temp);
void CollectActiveTemporaries(FastNumberSet& set);
void ShrinkActiveTemporaries(FastNumberSet& set, GrowingTypeArray& temporaries);
void ApplyExceptionStackChanges(GrowingInterCodeBasicBlockPtrArray& exceptionStack);
void Disassemble(FILE* file, bool dumpSets);
void CollectVariables(GrowingVariableArray & globalVars, GrowingVariableArray & localVars);
void MapVariables(GrowingVariableArray& globalVars, GrowingVariableArray& localVars);
void CollectOuterFrame(int level, int& size);
bool IsLeafProcedure(void);
};
class InterCodeModule;
class InterCodeProcedure
{
protected:
GrowingIntArray renameTable, renameUnionTable, globalRenameTable;
TempForwardingTable tempForwardingTable;
GrowingInstructionPtrArray valueForwardingTable;
int numFixedTemporaries;
NumberSet localAliasedSet;
void ResetVisited(void);
public:
GrowingInterCodeBasicBlockPtrArray blocks;
GrowingTypeArray temporaries;
GrowingIntArray mTempOffset;
int mTempSize, mCommonFrameSize;
bool mLeafProcedure;
InterCodeModule * mModule;
int mID;
int mLocalSize;
GrowingVariableArray mLocalVars;
Location mLocation;
const Ident * mIdent;
InterCodeProcedure(InterCodeModule * module, const Location & location, const Ident * ident);
~InterCodeProcedure(void);
int AddTemporary(InterType type);
void Append(InterCodeBasicBlock * block);
void Close(void);
// void Set(InterCodeIDMapper* mapper, BitVector localStructure, Scanner scanner, bool debug);
void MapVariables(void);
void ReduceTemporaries(void);
void Disassemble(const char* name, bool dumpSets = false);
protected:
void BuildTraces(void);
void BuildDataFlowSets(void);
void RenameTemporaries(void);
void TempForwarding(void);
void DisassembleDebug(const char* name);
};
class InterCodeModule
{
public:
InterCodeModule(void);
~InterCodeModule(void);
GrowingInterCodeProcedurePtrArray mProcedures;
GrowingVariableArray mGlobalVars;
void UseGlobal(int index);
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,36 @@
#pragma once
#include "Parser.h"
#include "InterCode.h"
class InterCodeGenerator
{
public:
InterCodeGenerator(Errors * errors);
~InterCodeGenerator(void);
struct ExValue
{
Declaration* mType;
int mTemp, mReference;
ExValue(Declaration* type = nullptr, int temp = -1, int reference = 0)
: mType(type), mTemp(temp), mReference(reference)
{}
};
InterCodeProcedure* TranslateProcedure(InterCodeModule* mod, Expression* exp, Declaration * dec);
void TranslateAssembler(InterCodeModule* mod, Expression * exp);
protected:
Errors* mErrors;
ExValue Dereference(InterCodeProcedure* proc, InterCodeBasicBlock*& block, ExValue v, int level = 0);
ExValue CoerceType(InterCodeProcedure* proc, InterCodeBasicBlock*& block, ExValue v, Declaration * type);
ExValue TranslateExpression(Declaration * procType, InterCodeProcedure * proc, InterCodeBasicBlock*& block, Expression* exp, InterCodeBasicBlock* breakBlock, InterCodeBasicBlock* continueBlock);
void TranslateLogic(Declaration* procType, InterCodeProcedure* proc, InterCodeBasicBlock* block, InterCodeBasicBlock* tblock, InterCodeBasicBlock* fblock, Expression* exp);
void InitGlobalVariable(InterCodeModule* mod, Declaration* dec);
void BuildInitializer(InterCodeModule* mod, uint8 * dp, int offset, Declaration* data, GrowingArray<InterVariable::Reference> & references);
};

18
oscar64/MachineTypes.h Normal file
View File

@ -0,0 +1,18 @@
#pragma once
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef signed char int8;
typedef signed short int16;
typedef signed short int32;
static const uint8 BC_REG_IP = 0x19;
static const uint8 BC_REG_ACCU = 0x1b;
static const uint8 BC_REG_ADDR = 0x1f;
static const uint8 BC_REG_STACK = 0x23;
static const uint8 BC_REG_LOCALS = 0x25;
static const uint8 BC_REG_TMP = 0x43;
static const uint8 BC_REG_TMP_SAVED = 0x53;

242
oscar64/NumberSet.cpp Normal file
View File

@ -0,0 +1,242 @@
#include "NumberSet.h"
NumberSet::NumberSet(void)
{
size = 0;
dwsize = 0;
bits = 0;
}
NumberSet::NumberSet(int size, bool set)
{
int i;
this->size = size;
dwsize = (size + 31) >> 5;
bits = new uint32[dwsize];
if (set)
{
for (i = 0; i < dwsize; i++)
bits[i] = 0xffffffff;
}
else
{
for (i = 0; i < dwsize; i++)
bits[i] = 0;
}
}
NumberSet::NumberSet(const NumberSet& set)
{
int i;
this->size = set.size;
this->dwsize = set.dwsize;
this->bits = new uint32[dwsize];
for (i = 0; i < dwsize; i++)
bits[i] = set.bits[i];
}
NumberSet::~NumberSet(void)
{
delete[] bits;
}
void NumberSet::Reset(int size, bool set)
{
int i;
delete[] bits;
this->size = size;
dwsize = (size + 31) >> 5;
bits = new uint32[dwsize];
if (set)
{
for (i = 0; i < dwsize; i++)
bits[i] = 0xffffffff;
}
else
{
for (i = 0; i < dwsize; i++)
bits[i] = 0;
}
}
void NumberSet::Clear(void)
{
int i;
for (i = 0; i < dwsize; i++)
bits[i] = 0;
}
NumberSet& NumberSet::operator=(const NumberSet& set)
{
int i;
this->size = set.size;
if (dwsize != set.dwsize)
{
delete[] bits;
this->dwsize = set.dwsize;
this->bits = new uint32[dwsize];
}
for (i = 0; i < dwsize; i++)
bits[i] = set.bits[i];
return *this;
}
NumberSet& NumberSet::operator&=(const NumberSet& set)
{
int i;
for (i = 0; i < dwsize; i++)
bits[i] &= set.bits[i];
return *this;
}
NumberSet& NumberSet::operator|=(const NumberSet& set)
{
int i;
for (i = 0; i < dwsize; i++)
bits[i] |= set.bits[i];
return *this;
}
NumberSet& NumberSet::operator-=(const NumberSet& set)
{
int i;
for (i = 0; i < dwsize; i++)
bits[i] &= ~set.bits[i];
return *this;
}
bool NumberSet::operator<=(const NumberSet& set)
{
int i;
for (i = 0; i < dwsize; i++)
if (bits[i] & ~set.bits[i]) return false;
return true;
}
FastNumberSet::FastNumberSet(void)
{
num = 0;
size = 0;
asize = 0;
buffer = nullptr;
}
FastNumberSet::FastNumberSet(int size, bool set)
{
this->size = this->asize = size;
buffer = new uint32[2 * size];
if (set)
{
for (num = 0; num < size; num++)
{
buffer[num] = num;
buffer[num + size] = num;
}
}
else
num = 0;
}
FastNumberSet::FastNumberSet(const FastNumberSet& set)
{
int i;
this->size = this->asize = set.size;
this->num = set.num;
buffer = new uint32[2 * size];
for (i = 0; i < num; i++)
{
buffer[i] = set.buffer[i];
buffer[size + buffer[i]] = i;
}
}
void FastNumberSet::Reset(int size, bool set)
{
if (size > this->asize)
{
delete[] buffer;
buffer = new uint32[2 * size];
this->asize = size;
}
this->size = size;
if (set)
{
for (num = 0; num < size; num++)
{
buffer[num] = num;
buffer[num + size] = num;
}
}
else
num = 0;
}
FastNumberSet::~FastNumberSet(void)
{
delete[] buffer;
}
FastNumberSet& FastNumberSet::operator=(const FastNumberSet& set)
{
if (set.size > this->asize)
{
delete[] buffer;
buffer = new uint32[2 * set.size];
this->asize = set.size;
}
this->size = set.size;
for (num = 0; num < set.num; num++)
{
buffer[num] = set.buffer[num];
buffer[buffer[num] + size] = num;
}
return *this;
}
void FastNumberSet::Clear(void)
{
num = 0;
}
int FastNumberSet::Index(int elem)
{
uint32 dw = buffer[size + elem];
if (dw < num && buffer[dw] == elem)
return dw;
else
return -1;
}

127
oscar64/NumberSet.h Normal file
View File

@ -0,0 +1,127 @@
#pragma once
typedef unsigned __int32 uint32;
class NumberSet
{
protected:
uint32 * bits;
int size, dwsize;
public:
NumberSet(void);
NumberSet(int size, bool set = false);
NumberSet(const NumberSet& set);
~NumberSet(void);
void Reset(int size, bool set = false);
NumberSet& operator+=(int elem);
NumberSet& operator-=(int elem);
bool operator[](int elem) const;
NumberSet& operator=(const NumberSet& set);
NumberSet& operator&=(const NumberSet& set);
NumberSet& operator|=(const NumberSet& set);
NumberSet& operator-=(const NumberSet& set);
bool operator<=(const NumberSet& set);
void Clear(void);
int Size(void) { return size; }
};
__forceinline NumberSet& NumberSet::operator+=(int elem)
{
bits[elem >> 5] |= (1UL << (elem & 31));
return *this;
}
__forceinline NumberSet& NumberSet::operator-=(int elem)
{
bits[elem >> 5] &= ~(1UL << (elem & 31));
return *this;
}
__forceinline bool NumberSet::operator[](int elem) const
{
return (bits[elem >> 5] & (1UL << (elem & 31))) != 0;
}
class FastNumberSet
{
protected:
uint32 * buffer;
int size, num, asize;
public:
FastNumberSet(void);
FastNumberSet(int size, bool set = false);
FastNumberSet(const FastNumberSet& set);
~FastNumberSet(void);
void Reset(int size, bool set = false);
FastNumberSet& operator+=(int elem);
FastNumberSet& operator-=(int elem);
bool operator[](int elem);
FastNumberSet& operator=(const FastNumberSet& set);
bool Empty(void) { return !num; }
void Clear(void);
int Num(void) { return num; }
int Element(int i);
int Size(void) { return size; }
int Index(int elem);
};
__forceinline bool FastNumberSet::operator[](int elem)
{
uint32 dw = buffer[size + elem];
return (dw < num&& buffer[dw] == elem);
}
__forceinline FastNumberSet& FastNumberSet::operator+=(int elem)
{
uint32 dw = buffer[size + elem];
if (dw >= num || buffer[dw] != elem)
{
buffer[num] = elem;
buffer[size + elem] = num;
num++;
}
return *this;
}
__forceinline FastNumberSet& FastNumberSet::operator-=(int elem)
{
uint32 dw = buffer[size + elem];
if (dw < num && buffer[dw] == elem)
{
num--;
buffer[dw] = buffer[num];
buffer[size + buffer[dw]] = dw;
}
return *this;
}
__forceinline int FastNumberSet::Element(int i)
{
if (i < num)
return buffer[i];
else
return -1;
}

2209
oscar64/Parser.cpp Normal file

File diff suppressed because it is too large Load Diff

66
oscar64/Parser.h Normal file
View File

@ -0,0 +1,66 @@
#pragma once
#include "Scanner.h"
#include "Declaration.h"
#include "CompilationUnits.h"
class Parser
{
public:
Parser(Errors * errors, Scanner* scanner, CompilationUnits * compilationUnits);
~Parser(void);
DeclarationScope * mGlobals, * mScope;
int mLocalIndex;
CompilationUnits * mCompilationUnits;
void Parse(void);
protected:
bool ConsumeToken(Token token);
bool ConsumeTokenIf(Token token);
void ParsePragma(void);
Declaration* ParseBaseTypeDeclaration(uint32 flags);
Declaration* ParseDeclaration(bool variable);
Declaration* CopyConstantInitializer(int offset, Declaration* dtype, Expression* exp);
Expression* ParseInitExpression(Declaration* dtype);
Expression* ParseDeclarationExpression(void);
Declaration* ParsePostfixDeclaration(void);
Declaration* ReverseDeclaration(Declaration* odec, Declaration* bdec);
Expression* ParseFunction(Declaration* dec);
Expression* ParseAssembler(void);
Expression* ParseAssemblerBaseOperand(void);
Expression* ParseAssemblerAddOperand(void);
Expression* ParseAssemblerOperand(void);
Expression* ParseStatement(void);
Expression* ParseSwitchStatement(void);
Expression* ParseSimpleExpression(void);
Expression* ParsePrefixExpression(void);
Expression* ParsePostfixExpression(void);
Expression* ParseMulExpression(void);
Expression* ParseAddExpression(void);
Expression* ParseShiftExpression(void);
Expression* ParseRelationalExpression(void);
Expression* ParseBinaryAndExpression(void);
Expression* ParseBinaryXorExpression(void);
Expression* ParseBinaryOrExpression(void);
Expression* ParseLogicAndExpression(void);
Expression* ParseLogicOrExpression(void);
Expression* ParseConditionalExpression(void);
Expression* ParseAssignmentExpression(void);
Expression* ParseExpression(void);
Expression* ParseRExpression(void);
Expression* ParseListExpression(void);
Expression* ParseParenthesisExpression(void);
Errors* mErrors;
Scanner* mScanner;
};

170
oscar64/Preprocessor.cpp Normal file
View File

@ -0,0 +1,170 @@
#include "Preprocessor.h"
#include <string.h>
SourcePath::SourcePath(const char* path)
{
strcpy_s(mPathName, path);
}
SourcePath::~SourcePath(void)
{
}
bool SourceFile::ReadLine(char* line)
{
if (mFile)
{
if (fgets(line, 1024, mFile))
return true;
fclose(mFile);
mFile = nullptr;
}
return false;
}
SourceFile::SourceFile(void)
: mFile(nullptr), mFileName{ 0 }
{
}
SourceFile::~SourceFile(void)
{
if (mFile)
{
fclose(mFile);
mFile = nullptr;
}
}
bool SourceFile::Open(const char* name, const char* path)
{
strcpy_s(mFileName, path);
int n = strlen(mFileName);
if (n > 0 && mFileName[n - 1] != '/')
{
mFileName[n++] = '/';
mFileName[n] = 0;
}
strcat_s(mFileName + n, sizeof(mFileName) - n, name);
if (!fopen_s(&mFile, mFileName, "r"))
return true;
return false;
}
void SourceFile::Close(void)
{
if (mFile)
{
fclose(mFile);
mFile = nullptr;
}
}
bool Preprocessor::NextLine(void)
{
int s = 0;
while (mSource->ReadLine(mLine + s))
{
mLocation.mLine++;
s = strlen(mLine);
while (s > 0 && mLine[s - 1] == '\n')
s--;
if (s == 0 || mLine[s - 1] != '\\')
return true;
s--;
}
return false;
}
bool Preprocessor::OpenSource(const char* name, bool local)
{
if (mSource)
mSource->mLocation = mLocation;
SourceFile * source = new SourceFile();
bool ok = false;
if (source->Open(name, ""))
ok = true;
if (!ok && local && mSource)
{
char lpath[200];
strcpy_s(lpath, mSource->mFileName);
int i = strlen(lpath);
while (i > 0 && lpath[i - 1] != '/')
i--;
lpath[i] = 0;
if (source->Open(name, lpath))
ok = true;
}
SourcePath* p = mPaths;
while (!ok && p)
{
if (source->Open(name, p->mPathName))
ok = true;
else
p = p->mNext;
}
if (ok)
{
printf("Reading %s\n", source->mFileName);
source->mUp = mSource;
mSource = source;
mLocation.mFileName = mSource->mFileName;
mLocation.mLine = 0;
mLine[0] = 0;
return true;
}
else
return false;
}
bool Preprocessor::CloseSource(void)
{
if (mSource)
{
mSource = mSource->mUp;
if (mSource)
{
mLocation = mSource->mLocation;
mLine[0] = 0;
return true;
}
}
return false;
}
Preprocessor::Preprocessor(Errors* errors)
: mSource(nullptr), mSourceList(nullptr), mPaths(nullptr), mErrors(errors)
{
}
Preprocessor::~Preprocessor(void)
{
}
void Preprocessor::AddPath(const char* path)
{
SourcePath* sp = new SourcePath(path);
sp->mNext = mPaths;
mPaths = sp;
}

55
oscar64/Preprocessor.h Normal file
View File

@ -0,0 +1,55 @@
#pragma once
#include "Errors.h"
#include <stdio.h>
class SourceFile
{
public:
char mFileName[200];
SourceFile * mUp, * mNext;
Location mLocation;
bool ReadLine(char* line);
SourceFile(void);
~SourceFile(void);
bool Open(const char* name, const char * path);
void Close(void);
protected:
FILE* mFile;
};
class SourcePath
{
public:
char mPathName[200];
SourcePath* mNext;
SourcePath(const char* path);
~SourcePath(void);
};
class Preprocessor
{
public:
char mLine[32768];
Location mLocation;
Errors* mErrors;
SourceFile* mSource, * mSourceList;
SourcePath* mPaths;
void AddPath(const char* path);
bool NextLine(void);
bool OpenSource(const char* name, bool local);
bool CloseSource(void);
Preprocessor(Errors * errors);
~Preprocessor(void);
};

1260
oscar64/Scanner.cpp Normal file

File diff suppressed because it is too large Load Diff

211
oscar64/Scanner.h Normal file
View File

@ -0,0 +1,211 @@
#pragma once
#include "Ident.h"
#include "Errors.h"
#include "Preprocessor.h"
enum Token
{
TK_NONE,
TK_EOF,
TK_ERROR,
TK_EOL,
TK_IF,
TK_ELSE,
TK_WHILE,
TK_DO,
TK_FOR,
TK_VOID,
TK_INT,
TK_CHAR,
TK_FLOAT,
TK_UNSIGNED,
TK_SWITCH,
TK_CASE,
TK_DEFAULT,
TK_BREAK,
TK_RETURN,
TK_SHORT,
TK_LONG,
TK_CONTINUE,
TK_INTEGER,
TK_BOOL,
TK_CONST,
TK_VOLATILE,
TK_TYPEDEF,
TK_STRUCT,
TK_UNION,
TK_ENUM,
TK_SIZEOF,
TK_ASM,
TK_NUMBER,
TK_STRING,
TK_IDENT,
TK_TRUE,
TK_FALSE,
TK_NULL,
TK_ADD,
TK_SUB,
TK_MUL,
TK_DIV,
TK_MOD,
TK_LEFT_SHIFT,
TK_RIGHT_SHIFT,
TK_INC,
TK_DEC,
TK_LOGICAL_NOT,
TK_LOGICAL_AND,
TK_LOGICAL_OR,
TK_BINARY_NOT,
TK_BINARY_AND,
TK_BINARY_OR,
TK_BINARY_XOR,
TK_EQUAL,
TK_NOT_EQUAL,
TK_GREATER_THAN,
TK_GREATER_EQUAL,
TK_LESS_THAN,
TK_LESS_EQUAL,
TK_ASSIGN,
TK_ASSIGN_ADD,
TK_ASSIGN_SUB,
TK_ASSIGN_MUL,
TK_ASSIGN_DIV,
TK_ASSIGN_MOD,
TK_ASSIGN_SHL,
TK_ASSIGN_SHR,
TK_ASSIGN_AND,
TK_ASSIGN_XOR,
TK_ASSIGN_OR,
TK_ARROW,
TK_HASH,
TK_DOLLAR,
TK_OPEN_PARENTHESIS,
TK_CLOSE_PARENTHESIS,
TK_OPEN_BRACE,
TK_CLOSE_BRACE,
TK_OPEN_BRACKET,
TK_CLOSE_BRACKET,
TK_DOT,
TK_DOTDOT,
TK_ELLIPSIS,
TK_COMMA,
TK_SEMICOLON,
TK_COLON,
TK_QUESTIONMARK,
TK_PREP_DEFINE,
TK_PREP_INCLUDE,
TK_PREP_IF,
TK_PREP_ELIF,
TK_PREP_ELSE,
TK_PREP_ENDIF,
TK_PREP_IFDEF,
TK_PREP_IFNDEF,
TK_PREP_PRAGMA,
NUM_TOKENS
};
extern const char* TokenNames[];
class Macro
{
public:
Macro(const Ident* ident);
~Macro(void);
void SetString(const char* str);
void SetString(const char* str, int length);
void AddArgument(const Ident * ident);
const Ident* mIdent;
const char* mString;
int mNumArguments;
const Ident * mArguments[32];
};
typedef Macro* MacroPtr;
class MacroDict
{
public:
MacroDict(void);
~MacroDict(void);
void Insert(Macro * macro);
Macro* Lookup(const Ident* ident);
protected:
MacroPtr * mHash;
int mHashSize, mHashFill;
};
class Scanner
{
public:
Scanner(Errors * errors, Preprocessor * preprocessor);
~Scanner(void);
const char* TokenName(Token token) const;
void NextToken(void);
void Warning(const char * error);
void Error(const char * error);
Errors* mErrors;
Preprocessor * mPreprocessor;
int mPrepCondition, mPrepPending;
int mOffset;
const char * mLine;
const Ident * mTokenIdent;
char mTokenString[1024], mTokenChar;
Token mToken;
double mTokenNumber;
unsigned int mTokenInteger;
Location mLocation;
void SetAssemblerMode(bool mode);
bool mAssemblerMode;
protected:
void NextRawToken(void);
struct MacroExpansion
{
MacroExpansion * mLink;
const char * mLine;
int mOffset;
char mChar;
MacroDict* mDefinedArguments;
} * mMacroExpansion;
MacroDict* mDefines, * mDefineArguments;
void StringToken(char terminator);
void CharToken(void);
bool NextChar(void);
void ParseNumberToken(void);
};

24
oscar64/Type.h Normal file
View File

@ -0,0 +1,24 @@
#pragma once
enum TType
{
TT_VOID,
TT_NULL,
TT_BOOL,
TT_INTEGER,
TT_FLOAT,
TT_POINTER,
TT_ARRAY,
TT_STRUCT,
TT_UNION,
TT_FUNCTION
};
class Type
{
public:
TType mType;
Type* mBase;
Scope* mScope;
};

152
oscar64/oscar64.cpp Normal file
View File

@ -0,0 +1,152 @@
#include <stdio.h>
#include <windows.h>
#include "Compiler.h"
bool GetProductAndVersion(char* strProductName, char* strProductVersion)
{
// get the filename of the executable containing the version resource
TCHAR szFilename[MAX_PATH + 1] = { 0 };
if (GetModuleFileName(NULL, szFilename, MAX_PATH) == 0)
{
return false;
}
// allocate a block of memory for the version info
DWORD dummy;
DWORD dwSize = GetFileVersionInfoSize(szFilename, &dummy);
if (dwSize == 0)
{
return false;
}
BYTE* data = new BYTE[dwSize];
// load the version info
if (!GetFileVersionInfo(szFilename, NULL, dwSize, data))
{
return false;
}
// get the name and version strings
LPVOID pvProductName = NULL;
unsigned int iProductNameLen = 0;
LPVOID pvProductVersion = NULL;
unsigned int iProductVersionLen = 0;
// replace "040904e4" with the language ID of your resources
if (!VerQueryValueA(&data[0], "\\StringFileInfo\\000904b0\\ProductName", &pvProductName, &iProductNameLen) ||
!VerQueryValueA(&data[0], "\\StringFileInfo\\000904b0\\ProductVersion", &pvProductVersion, &iProductVersionLen))
{
return false;
}
strcpy_s(strProductName, 100, (LPCSTR)pvProductName);
strcpy_s(strProductVersion, 100, (LPCSTR)pvProductVersion);
return true;
}
int main(int argc, const char** argv)
{
InitDeclarations();
InitAssembler();
if (argc > 0)
{
char basePath[200], crtPath[200], includePath[200], targetPath[200];
char strProductName[100], strProductVersion[200];
if (GetProductAndVersion(strProductName, strProductVersion))
{
printf("Starting %s %s\n", strProductName, strProductVersion);
}
DWORD length = ::GetModuleFileNameA(NULL, basePath, sizeof(basePath));
while (length > 0 && basePath[length - 1] != '/' && basePath[length - 1] != '\\')
length--;
#ifdef _DEBUG
if (length > 0)
{
length--;
while (length > 0 && basePath[length - 1] != '/' && basePath[length - 1] != '\\')
length--;
}
#endif
basePath[length] = 0;
Compiler* compiler = new Compiler();
Location loc;
compiler->mPreprocessor->AddPath(basePath);
strcpy_s(includePath, basePath);
strcat_s(includePath, "include/");
compiler->mPreprocessor->AddPath(includePath);
strcpy_s(crtPath, includePath);
strcat_s(crtPath, "crt.c");
bool emulate = false;
targetPath[0] = 0;
for (int i = 1; i < argc; i++)
{
const char* arg = argv[i];
if (arg[0] == '-')
{
if (arg[1] == 'i' && arg[2] == '=')
{
compiler->mPreprocessor->AddPath(arg + 3);
}
else if (arg[1] == 'o' && arg[2] == '=')
{
strcpy_s(targetPath, arg + 3);
}
else if (arg[1] == 'r' && arg[2] == 't' && arg[3] == '=')
{
strcpy_s(crtPath, arg + 4);
}
else if (arg[1] == 'e')
{
emulate = true;
}
else
compiler->mErrors->Error(loc, "Invalid command line argument", arg);
}
else
{
if (!targetPath[0])
strcpy_s(targetPath, argv[i]);
compiler->mCompilationUnits->AddUnit(loc, argv[i], nullptr);
}
}
// Add runtime module
compiler->mCompilationUnits->AddUnit(loc, crtPath, nullptr);
if (compiler->ParseSource() && compiler->GenerateCode())
{
compiler->WriteOutputFile(targetPath);
if (emulate)
compiler->ExecuteCode();
}
if (compiler->mErrors->mErrorCount != 0)
return 20;
}
else
{
printf("oscar64 {-i=includePath} [-o=output.prg] [-cr=runtime.c] [-e] {source.c}\n");
return 0;
}
return 0;
}

110
oscar64/oscar64.rc Normal file
View File

@ -0,0 +1,110 @@
// Microsoft Visual C++ generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE LANG_ENGLISH, SUBLANG_NEUTRAL
#pragma code_page(1252)
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,0,20
PRODUCTVERSION 1,0,0,20
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x40004L
FILETYPE 0x1L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "000904b0"
BEGIN
VALUE "CompanyName", "oscar64"
VALUE "FileDescription", "oscar64 compiler"
VALUE "FileVersion", "1.0.0.20"
VALUE "InternalName", "oscar64.exe"
VALUE "LegalCopyright", "Copyright (C) 2021"
VALUE "OriginalFilename", "oscar64.exe"
VALUE "ProductName", "oscar64"
VALUE "ProductVersion", "1.0.0.20"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x9, 1200
END
END
#endif // English resources
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// German (Germany) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_DEU)
LANGUAGE LANG_GERMAN, SUBLANG_GERMAN
#pragma code_page(1252)
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""winres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
#endif // German (Germany) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED

187
oscar64/oscar64.vcxproj Normal file
View File

@ -0,0 +1,187 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{1dbc623e-6109-41fe-b1bb-9b43fc984f7d}</ProjectGuid>
<RootNamespace>oscar64</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;version.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;version.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="Assembler.cpp" />
<ClCompile Include="ByteCodeGenerator.cpp" />
<ClCompile Include="CompilationUnits.cpp" />
<ClCompile Include="Compiler.cpp" />
<ClCompile Include="Declaration.cpp" />
<ClCompile Include="Emulator.cpp" />
<ClCompile Include="Errors.cpp" />
<ClCompile Include="Ident.cpp" />
<ClCompile Include="InterCode.cpp" />
<ClCompile Include="InterCodeGenerator.cpp" />
<ClCompile Include="NumberSet.cpp" />
<ClCompile Include="oscar64.cpp" />
<ClCompile Include="Parser.cpp" />
<ClCompile Include="Preprocessor.cpp" />
<ClCompile Include="Scanner.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="Array.h" />
<ClInclude Include="Assembler.h" />
<ClInclude Include="BitVector.h" />
<ClInclude Include="ByteCodeGenerator.h" />
<ClInclude Include="CompilationUnits.h" />
<ClInclude Include="Compiler.h" />
<ClInclude Include="Declaration.h" />
<ClInclude Include="Emulator.h" />
<ClInclude Include="Errors.h" />
<ClInclude Include="Ident.h" />
<ClInclude Include="InterCode.h" />
<ClInclude Include="InterCodeGenerator.h" />
<ClInclude Include="MachineTypes.h" />
<ClInclude Include="NumberSet.h" />
<ClInclude Include="Parser.h" />
<ClInclude Include="Preprocessor.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="Scanner.h" />
<ClInclude Include="Type.h" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="oscar64.rc" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,128 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="oscar64.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Assembler.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ByteCodeGenerator.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="CompilationUnits.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Compiler.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Declaration.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Emulator.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Errors.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Ident.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="InterCode.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="InterCodeGenerator.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="NumberSet.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Parser.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Preprocessor.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Scanner.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="Array.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Assembler.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="BitVector.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ByteCodeGenerator.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="CompilationUnits.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Compiler.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Declaration.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Emulator.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Errors.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Ident.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="InterCode.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="InterCodeGenerator.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="MachineTypes.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="NumberSet.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Parser.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Preprocessor.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Scanner.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Type.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="resource.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="oscar64.rc">
<Filter>Resource Files</Filter>
</ResourceCompile>
</ItemGroup>
</Project>

14
oscar64/resource.h Normal file
View File

@ -0,0 +1,14 @@
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by oscar64.rc
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif