`_
diff --git a/gpl.html b/gpl.html
new file mode 100644
index 0000000000..0aec9fff0d
--- /dev/null
+++ b/gpl.html
@@ -0,0 +1,493 @@
+
+
+
+GNU General Public License - GNU Project - Free Software Foundation (FSF)
+
+
+GNU General Public License
+
+Table of Contents
+
+
+
+
+
+
+
+
+
+
+
+
+Version 2, June 1991
+
+
+
+
+Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
+
+Everyone is permitted to copy and distribute verbatim copies
+of this license document, but changing it is not allowed.
+
+
+
+
+
+
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) 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
+this service 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 make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. 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.
+
+
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+
+
+
+
+
+
+
+
+0.
+ This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+
+
+1.
+ You may copy and distribute 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 and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+
+2.
+ You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+
+
+
+- a)
+ You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+
+
- b)
+ You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+
+
- c)
+ If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+
+
+3.
+ You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+
+
+
+
+
+- a)
+ Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+
+
- b)
+ Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+
+
- c)
+ Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+
+4.
+ You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+
+
+5.
+ You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+
+
+6.
+ Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+
+
+7.
+ If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+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
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+
+
+8.
+ If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+
+
+9.
+ The Free Software Foundation may publish revised and/or new versions
+of the 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 a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+
+
+
+10.
+ If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+
+
+
NO WARRANTY
+
+
+
+11.
+ BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
+
+
+
+12.
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE 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.
+
+
+
+
+
END OF TERMS AND CONDITIONS
+
+
+
+
+
+
+ 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
+convey 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 an idea of what it does.
+Copyright (C) yyyy 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 2
+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, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+
+
+
+Gnomovision version 69, Copyright (C) year name of author
+Gnomovision 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, the
+commands you use may be called something other than `show w' and
+`show c'; they could even be mouse-clicks or menu items--whatever
+suits your program.
+
+
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+
+
+
+Yoyodyne, Inc., hereby disclaims all copyright
+interest in the program `Gnomovision'
+(which makes passes at compilers) written
+by James Hacker.
+
+signature of Ty Coon, 1 April 1989
+Ty Coon, President of Vice
+
+
+
+This 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 Library General
+Public License instead of this License.
+
diff --git a/ide/config.nim b/ide/config.nim
new file mode 100644
index 0000000000..448a67bda2
--- /dev/null
+++ b/ide/config.nim
@@ -0,0 +1,93 @@
+# Does the config parsing for us
+
+import
+ parsecfg, strtabs, strutils
+
+type
+ TTokenClass* = enum
+ gtBackground,
+ gtNone,
+ gtWhitespace,
+ gtDecNumber,
+ gtBinNumber,
+ gtHexNumber,
+ gtOctNumber,
+ gtFloatNumber,
+ gtIdentifier,
+ gtKeyword,
+ gtStringLit,
+ gtLongStringLit,
+ gtCharLit,
+ gtEscapeSequence,
+ gtOperator,
+ gtPunctation,
+ gtComment,
+ gtLongComment,
+ gtRegularExpression,
+ gtTagStart,
+ gtTagEnd,
+ gtKey,
+ gtValue,
+ gtRawData,
+ gtAssembler,
+ gtPreprocessor,
+ gtDirective,
+ gtCommand,
+ gtRule,
+ gtHyperlink,
+ gtLabel,
+ gtReference,
+ gtOther,
+ gtCursor
+
+ TColor* = colKeywords, colIdentifiers, colComments
+ TConfiguration* = object of TObject ## the configuration object
+ colors*: array [TTokenClass] of TColor ## the colors to use
+ filelist*: seq[string] ## the filelist
+
+const
+ colWhite = 0x00ffffff # rgb
+ colBlack = 0x00000000
+ colYellow =
+
+proc readConfig(filename: string): TConfiguration =
+ # fill with reasonable defaults:
+ result.filelist = []
+ result.colors[gtBackground] = colWhite
+ gtNone:
+ gtWhitespace,
+ gtDecNumber,
+ gtBinNumber,
+ gtHexNumber,
+ gtOctNumber,
+ gtFloatNumber,
+ gtIdentifier,
+ gtKeyword,
+ gtStringLit,
+ gtLongStringLit,
+ gtCharLit,
+ gtEscapeSequence,
+ gtOperator,
+ gtPunctation,
+ gtComment,
+ gtLongComment,
+ gtRegularExpression,
+ gtTagStart,
+ gtTagEnd,
+ gtKey,
+ gtValue,
+ gtRawData,
+ gtAssembler,
+ gtPreprocessor,
+ gtDirective,
+ gtCommand,
+ gtRule,
+ gtHyperlink,
+ gtLabel,
+ gtReference,
+ gtOther
+ gtCursor
+ var
+ p: TCfgParser
+ if open(p, filename):
+
diff --git a/ide/main.nim b/ide/main.nim
index 22ab88d676..a7e9bb642e 100644
--- a/ide/main.nim
+++ b/ide/main.nim
@@ -1,13 +1,13 @@
# The beginning of an IDE for Nimrod
# (c) 2008 Andreas Rumpf
-import glib2, gtk2, libglade2, dialogs, parseopt
+import os, glib2, gtk2, libglade2, dialogs, parseopt
proc on_window_destroy(obj: PGtkObject, data: pointer) {.cdecl.} =
gtk_main_quit()
const
- GuiTemplate = "/media/hda4/nimrod/ide/nimide.glade"
+ GuiTemplate = "/media/hda1/Eigenes/nimrod/ide/nimide.glade"
type
TTab = object of TObject
@@ -35,19 +35,19 @@ proc on_about_menu_item_activate(menuItem: PGtkMenuItem,
proc load_file(e: var TMyTextEditor, filename: string) =
var
- err: ptr GError
+ err: pointer
status: cstring
text: cstring
result: bool
buffer: PGtkTextBuffer
- gtk_statusbar_push(e.statusbar, e.statusbar_context_id, "Loading...")
- while gtk_events_pending(): gtk_main_iteration()
+ discard gtk_statusbar_push(e.statusbar, e.statusbar_context_id, "Loading...")
+ while gtk_events_pending() != 0: discard gtk_main_iteration()
# get the file contents
result = g_file_get_contents(filename, addr(text), nil, addr(err))
if not result:
- error_message("Cannot load file")
- g_error_free(err)
+ error(e.window, "Cannot load file")
+ #g_error_free(err)
# disable the text view while loading the buffer with the text
gtk_widget_set_sensitive(e.text_view, false)
@@ -103,7 +103,8 @@ proc check_for_save(e: var TMyTextEditor): bool =
GtkWidget *dialog;
const gchar *msg = "Do you want to save the changes you have made?";
dialog = gtk_message_dialog_new (nil,
- GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
+ GTK_DIALOG_MODAL or
+ GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_QUESTION,
GTK_BUTTONS_YES_NO,
msg);
@@ -146,15 +147,13 @@ proc main() =
var
editor: TMyTextEditor
- gtk_nimrod_init()
initApp(editor)
gtk_widget_show(editor.window)
gtk_main()
+gtk_nimrod_init()
main()
-
-
proc on_window_delete_event(widget: PGtkWidget, event: PGdkEvent,
e: TMyTextEditor): bool {.cdecl.} =
if check_for_save(editor):
diff --git a/ide/nimide.glade b/ide/nimide.glade
index 0bd5f11f1c..ce24683b2e 100644
--- a/ide/nimide.glade
+++ b/ide/nimide.glade
@@ -1,224 +1,192 @@
-
-
-
-
-
-
- GDK_EXTENSION_EVENTS_ALL
-
- GTK_WINDOW_TOPLEVEL
- GTK_WIN_POS_NONE
- False
- True
- False
- True
- False
- False
- GDK_WINDOW_TYPE_HINT_NORMAL
- GDK_GRAVITY_NORTH_WEST
- True
- False
-
-
-
-
- 600
- 400
- True
- False
- 0
-
-
-
-
- 0
- False
- True
-
-
-
-
-
- 1
- True
- True
- GTK_POLICY_AUTOMATIC
- GTK_POLICY_AUTOMATIC
- GTK_SHADOW_ETCHED_IN
- GTK_CORNER_TOP_LEFT
-
-
-
- True
- True
- True
- False
- True
- GTK_JUSTIFY_LEFT
- GTK_WRAP_NONE
- True
- 0
- 0
- 0
- 2
- 2
- 0
-
-
-
-
-
- 0
- True
- True
-
-
-
-
-
- True
- True
-
-
- 0
- False
- True
-
-
-
-
-
-
-
+
+
+
+
+
+ GDK_EXTENSION_EVENTS_ALL
+
+
+
+ 600
+ 400
+ True
+
+
+
+ False
+
+
+
+
+ True
+ True
+ 10
+ 0
+
+
+
+
+
+
+ tab
+
+
+
+
+
+
+
+
+ tab
+
+
+
+
+
+
+
+
+ tab
+
+
+
+
+ 1
+
+
+
+
+ True
+
+
+ False
+ 2
+
+
+
+
+
+
diff --git a/ide/nimide.nim b/ide/nimide.nim
new file mode 100644
index 0000000000..c5abc3bbf0
--- /dev/null
+++ b/ide/nimide.nim
@@ -0,0 +1,118 @@
+# The beginning of an IDE for Nimrod
+# (c) 2008 Andreas Rumpf
+
+import os, glib2, gdk2, gtk2, libglade2, pango, dialogs, parseopt
+
+const
+ GuiTemplate = "nimide.glade"
+ dummyConst = ""
+
+type
+ TTab {.pure, final.} = object
+ textview: PGtkTextView
+ filename: string
+ untitled: bool
+ hbox: PGtkHBox
+ e: PEditor
+ PTab = ptr TTab
+
+ TEditor = object of TObject
+ window: PGtkWindow
+ statusbar: PGtkStatusBar
+ menu: PGtkMenuBar
+ notebook: PGtkNotebook
+ tabname: int # used for generating tab names
+ PEditor = ptr TEditor
+
+proc on_window_destroy(obj: PGtkObject, event: PGdkEvent,
+ data: pointer): gboolean {.cdecl.} =
+ gtk_main_quit()
+
+proc on_about_menu_item_activate(menuItem: PGtkMenuItem, e: PEditor) {.cdecl.} =
+ gtk_show_about_dialog(e.window,
+ "comments", "A fast and leight-weight IDE for Nimrod",
+ "copyright", "Copyright \xc2\xa9 2008 Andreas Rumpf",
+ "version", "0.1",
+ "website", "http://nimrod.ethexor.com",
+ "program-name", "Nimrod IDE",
+ nil)
+
+proc getTabIndex(e: PEditor, tab: PTab): int =
+ var i = 0
+ while true:
+ var w = gtk_notebook_get_nth_page(e.notebook, i)
+ if w == nil: return -1
+ var v = gtk_notebook_get_tab_label(e.notebook, w)
+ if tab.hbox == v: return i
+ inc(i)
+
+proc OnCloseTab(button: PGtkButton, tab: PTab) {.cdecl.} =
+ var idx = getTabIndex(tab.e, tab)
+ if idx >= 0: gtk_notebook_remove_page(tab.e.notebook, idx)
+
+proc createTab(e: PEditor, filename: string, untitled: bool) =
+ var t = cast[PTab](alloc0(sizeof(TTab)))
+ t.textview = gtk_text_view_new_with_buffer(gtk_text_buffer_new(nil))
+ var font_desc = pango_font_description_from_string("monospace 10")
+ gtk_widget_modify_font(t.textview, font_desc)
+ pango_font_description_free(font_desc)
+ t.filename = filename
+ t.untitled = untitled
+ gtk_widget_show(t.textview)
+ var scroll = gtk_scrolled_window_new(nil, nil)
+ gtk_container_add(scroll, t.textview)
+ gtk_widget_show(scroll)
+
+ t.e = e
+ t.hbox = gtk_hbox_new(false, 0)
+ var image = gtk_image_new_from_stock(GTK_STOCK_CLOSE, GTK_ICON_SIZE_MENU)
+ var button = gtk_button_new()
+ var lab = gtk_label_new(filename)
+ gtk_button_set_image(button, image)
+ gtk_button_set_relief(button, GTK_RELIEF_NONE)
+ gtk_box_pack_start(t.hbox, lab, false, false, 2)
+ gtk_box_pack_end(t.hbox, button, false, false, 0)
+
+ discard g_signal_connect(button, "clicked", G_Callback(onCloseTab), t)
+ gtk_widget_show(button)
+ gtk_widget_show(lab)
+
+ var idx = gtk_notebook_append_page(e.notebook, scroll, t.hbox)
+ gtk_notebook_set_current_page(e.notebook, idx)
+
+proc on_new_menu_item_activate(menuItem: PGtkMenuItem, e: PEditor) {.cdecl.} =
+ inc(e.tabname)
+ createTab(e, "untitled-" & $e.tabname, true)
+
+proc main(e: PEditor) =
+ var builder = glade_xml_new(getApplicationDir() / GuiTemplate, nil, nil)
+ if builder == nil: quit("cannot open: " & GuiTemplate)
+ # get the components:
+ e.window = GTK_WINDOW(glade_xml_get_widget(builder, "window"))
+ e.statusbar = GTK_STATUSBAR(glade_xml_get_widget(builder, "statusbar"))
+ e.notebook = GTK_NOTEBOOK(glade_xml_get_widget(builder, "notebook"))
+ setHomogeneous(e.notebook^, 1)
+
+ # connect the signal handlers:
+ glade_xml_signal_connect(builder, "on_window_destroy",
+ GCallback(on_window_destroy))
+ var about = GTK_MENU_ITEM(glade_xml_get_widget(builder, "about_menu_item"))
+ discard g_signal_connect(about, "activate",
+ G_CALLBACK(on_about_menu_item_activate), e)
+
+ var newItem = GTK_MENU_ITEM(glade_xml_get_widget(builder, "new_menu_item"))
+ discard g_signal_connect(newItem, "activate",
+ G_CALLBACK(on_new_menu_item_activate), e)
+
+ var quitItem = GTK_MENU_ITEM(glade_xml_get_widget(builder, "quit_menu_item"))
+ discard g_signal_connect(quitItem, "activate",
+ G_CALLBACK(on_window_destroy), e)
+
+ gtk_window_set_default_icon_name(GTK_STOCK_EDIT)
+ gtk_widget_show(e.window)
+ gtk_main()
+
+
+gtk_nimrod_init()
+var e = cast[PEditor](alloc0(sizeof(TEditor)))
+main(e)
diff --git a/install.sh b/install.sh
new file mode 100644
index 0000000000..eb592da843
--- /dev/null
+++ b/install.sh
@@ -0,0 +1,126 @@
+#! /bin/sh
+#
+# Nimrod installation script
+# (c) 2008 Andreas Rumpf
+#
+
+if [ $# -eq 1 ] ; then
+
+ if test -f bin/nimrod
+ then
+ echo "Nimrod already built -- skipping this phase"
+ else
+ echo "building Nimrod..."
+ sh ./build.sh || exit 1
+ echo "...done"
+ fi
+
+ case $1 in
+ "/usr/bin")
+ configdir=/etc
+ libdir=/usr/lib/nimrod
+ mkdir -p /usr/lib/nimrod
+ mkdir -p /usr/share/nimrod/doc
+
+ cp bin/nimrod /usr/bin/nimrod
+ cp config/nimdoc.cfg /etc/nimdoc.cfg
+ cp -r -p lib /usr/lib/nimrod
+ cp -r -p doc /usr/share/nimrod/doc
+ ;;
+ "/usr/local/bin")
+ configdir=/etc
+ libdir=/usr/local/lib/nimrod
+ mkdir -p /usr/local/lib/nimrod
+ mkdir -p /usr/local/share/nimrod/doc
+
+ cp bin/nimrod /usr/local/bin/nimrod
+ cp config/nimdoc.cfg /etc/nimdoc.cfg
+ cp -r -p lib /usr/local/lib/nimrod
+ cp -r -p doc /usr/local/share/nimrod/doc
+ ;;
+ *)
+ configdir="$1/nimrod/config"
+ libdir="$1/nimrod/lib"
+ mkdir -p $1/nimrod
+ mkdir -p $1/nimrod/bin
+ mkdir -p $1/nimrod/config
+ mkdir -p $1/nimrod/lib
+ mkdir -p $1/nimrod/doc
+
+ cp bin/nimrod $1/nimrod/bin/nimrod
+ cp config/nimdoc.cfg $1/nimrod/config/nimdoc.cfg
+ cp -r -p lib $1/nimrod
+ cp -r -p doc $1/nimrod
+ ;;
+ esac
+ # write the configuration file
+ cat >$configdir/nimrod.cfg < (treated like '/opt')"
+ echo "To deinstall, use the command:"
+ echo "sh deinstall.sh DIR"
+ exit 1
+fi
diff --git a/install.txt b/install.txt
index 60d52e2285..c6059882a1 100644
--- a/install.txt
+++ b/install.txt
@@ -61,5 +61,6 @@ Currently, the following C compilers are supported under Windows:
- | Digital Mars C++
| http://www.digitalmars.com/download/freecompiler.html
-For faster compile times I recommend Digital Mars C++ -- it is easy to install
+For better compile times I recommend Digital Mars C++ -- it is easy to install
and a small package.
+
diff --git a/koch.py b/koch.py
index d8d42a02b3..1f5ae0d2ce 100644
--- a/koch.py
+++ b/koch.py
@@ -18,7 +18,7 @@ False = 0 == 1
# --------------------- constants ----------------------------------------
-NIMROD_VERSION = '0.7.0'
+NIMROD_VERSION = '0.7.2'
# This string contains Nimrod's version. It is the only place
# where the version needs to be updated. The rest is done by
# the build process automatically. It is replaced **everywhere**
@@ -405,8 +405,10 @@ Possible Commands:
clean cleans Nimrod project; removes generated files
boot [options] bootstraps with given command line options
rodsrc generates Nimrod version from Pascal version
- web generates the website (requires Cheetah)
+ web generates the website
profile profile the Nimrod compiler
+ zip build the installation ZIP package
+ inno build the Inno Setup installer
""" % (NIMROD_VERSION + ' ' * (44-len(NIMROD_VERSION)), sys.version)
def main(args):
@@ -440,8 +442,20 @@ def main(args):
elif cmd == "rodsrc": cmd_rodsrc()
elif cmd == "web": cmd_web()
elif cmd == "profile": cmd_profile()
+ elif cmd == "zip": cmd_zip()
+ elif cmd == "inno": cmd_inno()
else: Error("illegal command: " + cmd)
+def cmd_zip():
+ Exec("nimrod cc -r tools/niminst --var:version=%s csource rod/nimrod" %
+ NIMROD_VERSION)
+ Exec("nimrod cc -r tools/niminst --var:version=%s zip rod/nimrod" %
+ NIMROD_VERSION)
+
+def cmd_inno():
+ Exec("nimrod cc -r tools/niminst --var:version=%s inno rod/nimrod" %
+ NIMROD_VERSION)
+
# -------------------------- bootstrap ----------------------------------------
def readCFiles():
@@ -678,6 +692,8 @@ def getOSandProcessor():
else: processor = os.uname()[4]
if lower(processor) in ("i686", "i586", "i468", "i386"):
processor = "i386"
+ if lower(processor) in ("x86_64", "x86-64", "amd64"):
+ processor = "amd64"
if find(lower(processor), "sparc") >= 0:
processor = "sparc"
return (host, processor)
diff --git a/lib/alloc.nim b/lib/alloc.nim
new file mode 100644
index 0000000000..504453699a
--- /dev/null
+++ b/lib/alloc.nim
@@ -0,0 +1,394 @@
+#
+#
+# Nimrod's Runtime Library
+# (c) Copyright 2008 Andreas Rumpf
+#
+# See the file "copying.txt", included in this
+# distribution, for details about the copyright.
+#
+
+# Low level allocator for Nimrod.
+
+# ------------ platform specific chunk allocation code -----------------------
+
+when defined(posix):
+ const # XXX: make these variables for portability?
+ PROT_READ = 1 # page can be read
+ PROT_WRITE = 2 # page can be written
+ PROT_EXEC = 4 # page can be executed
+ PROT_NONE = 0 # page can not be accessed
+
+ MAP_SHARED = 1 # Share changes
+ MAP_PRIVATE = 2 # Changes are private
+ MAP_TYPE = 0xf # Mask for type of mapping
+ MAP_FIXED = 0x10 # Interpret addr exactly
+ MAP_ANONYMOUS = 0x20 # don't use a file
+
+ MAP_GROWSDOWN = 0x100 # stack-like segment
+ MAP_DENYWRITE = 0x800 # ETXTBSY
+ MAP_EXECUTABLE = 0x1000 # mark it as an executable
+ MAP_LOCKED = 0x2000 # pages are locked
+ MAP_NORESERVE = 0x4000 # don't check for reservations
+
+ proc mmap(adr: pointer, len: int, prot, flags, fildes: cint,
+ off: int): pointer {.header: "".}
+
+ proc munmap(adr: pointer, len: int) {.header: "".}
+
+ proc osAllocPages(size: int): pointer {.inline.} =
+ result = mmap(nil, size, PROT_READ or PROT_WRITE,
+ MAP_PRIVATE or MAP_ANONYMOUS, -1, 0)
+ if result == nil or result == cast[pointer](-1):
+ raiseOutOfMem()
+
+ proc osDeallocPages(p: pointer, size: int) {.inline} =
+ munmap(p, len)
+
+elif defined(windows):
+ const
+ MEM_RESERVE = 0x2000
+ MEM_COMMIT = 0x1000
+ MEM_TOP_DOWN = 0x100000
+ PAGE_READWRITE = 0x04
+
+ proc VirtualAlloc(lpAddress: pointer, dwSize: int, flAllocationType,
+ flProtect: int32): pointer {.
+ header: "", stdcall.}
+
+ proc osAllocPages(size: int): pointer {.inline.} =
+ result = VirtualAlloc(nil, size, MEM_RESERVE or MEM_COMMIT,
+ PAGE_READWRITE)
+ if result == nil: raiseOutOfMem()
+
+ proc osDeallocPages(p: pointer, size: int) {.inline.} =
+ nil
+
+else:
+ {.error: "Port GC to your platform".}
+
+# --------------------- end of non-portable code -----------------------------
+
+# We manage *chunks* of memory. Each chunk is a multiple of the page size.
+# The page size may or may not the operating system's page size. Each chunk
+# starts at an address that is divisible by the page size. Chunks that are
+# bigger than ``ChunkOsReturn`` are returned back to the operating system
+# immediately.
+
+
+# Guess the page size of the system; if it is the
+# wrong value, performance may be worse (this is not
+# for sure though), but GC still works; must be a power of two!
+const
+ PageShift = if sizeof(pointer) == 4: 12 else: 13
+ PageSize = 1 shl PageShift # on 32 bit systems 4096
+
+ MemAlignment = sizeof(pointer)*2 # minimal memory block that can be allocated
+ BitsPerUnit = sizeof(int)*8
+ # a "unit" is a word, i.e. 4 bytes
+ # on a 32 bit system; I do not use the term "word" because under 32-bit
+ # Windows it is sometimes only 16 bits
+
+ BitsPerPage = PageSize div MemAlignment
+ UnitsPerPage = BitsPerPage div BitsPerUnit
+ # how many units do we need to describe a page:
+ # on 32 bit systems this is only 16 (!)
+
+ smallRequest = PageSize div 4
+ ChunkOsReturn = 1024 # in pages
+ InitialMemoryRequest = ChunkOsReturn div 2 # < ChunkOsReturn!
+ debugMemMan = true # we wish to debug the memory manager...
+
+type
+ PChunkDesc = ptr TChunkDesc
+ TChunkDesc {.final, pure.} = object
+ key: TAddress # address at bit 0
+ next: PChunkDesc
+ bits: array[0..127, int] # a bit vector
+
+ PChunkDescArray = ptr array[0..1000_000, PChunkDesc]
+ TChunkSet {.final, pure.} = object
+ counter, max: int
+ head: PChunkDesc
+ data: PChunkDescArray
+
+when sizeof(int) == 4:
+ type THalfWord = int16
+else:
+ type THalfWord = int32
+
+type
+ TFreeCell {.final, pure.} = object
+ zeroField: pointer # type info nil means cell is not used
+ next: ptr TFreeCell # next free cell in chunk
+
+ PChunk = ptr TChunk
+ TChunk {.final, pure.} = object
+ size: int # lowest two bits are used for merging:
+ # bit 0: chunk to the left is accessible and free
+ # bit 1: chunk to the right is accessible and free
+ len: int # for small object allocation
+ prev, next: PChunk # chunks of the same (or bigger) size
+ #len, used: THalfWord # index of next to allocate cell
+ freeList: ptr TFreeCell
+ data: float # a float for alignment purposes
+
+proc roundup(x, v: int): int {.inline.} = return ((-x) and (v-1)) +% x
+
+assert(roundup(14, PageSize) == PageSize)
+assert(roundup(15, 8) == 16)
+
+# ------------- chunk table ---------------------------------------------------
+# We use a PtrSet of chunk starts and a table[Page, chunksize] for chunk
+# endings of big chunks. This is needed by the merging operation. The only
+# remaining operation is best-fit for big chunks. Since there is a size-limit
+# for big chunks (because greater than the limit means they are returned back
+# to the OS), a fixed size array can be used.
+
+type
+ PLLChunk = ptr TLLChunk
+ TLLChunk {.pure.} = object ## *low-level* chunk
+ size: int
+ when sizeof(int) == 4:
+ align: int
+
+ TAllocator {.final, pure.} = object
+ llmem: PLLChunk
+ UsedPagesCount, FreePagesCount, maxPagesCount: int
+ freeSmallChunks: array[0..smallRequest div MemAlign-1, PChunk]
+ freeBigChunks: array[0..ChunkOsReturn-1, PChunk]
+
+
+proc llAlloc(a: var TAllocator, size: int): pointer =
+ # *low-level* alloc for the memory managers data structures. Deallocation
+ # is never done.
+ assert(size <= PageSize-8)
+ if a.llmem.size + size > PageSize:
+ a.llmem = osGetPages(PageSize)
+ inc(a.gUsedPages)
+ a.llmem.size = 8
+ result = cast[pointer](cast[TAddress](a.llmem) + a.llmem.size)
+ inc(llmem.size, size)
+ zeroMem(result, size)
+
+
+const
+ InitChunkSetSize = 1024 # must be a power of two!
+
+proc ChunkSetInit(s: var TChunkSet) =
+ s.data = cast[PChunkDescArray](llAlloc(InitChunkSetSize * sizeof(PChunkDesc)))
+ s.max = InitChunkSetSize-1
+ s.counter = 0
+ s.head = nil
+
+proc ChunkSetGet(t: TChunkSet, key: TAddress): PChunkDesc =
+ var h = cast[int](key) and t.max
+ while t.data[h] != nil:
+ if t.data[h].key == key: return t.data[h]
+ h = nextTry(h, t.max)
+ return nil
+
+proc ChunkSetRawInsert(t: TChunkSet, data: PChunkDescArray,
+ desc: PChunkDesc) =
+ var h = cast[int](desc.key) and t.max
+ while data[h] != nil:
+ assert(data[h] != desc)
+ h = nextTry(h, t.max)
+ assert(data[h] == nil)
+ data[h] = desc
+
+proc ChunkSetEnlarge(t: var TChunkSet) =
+ var oldMax = t.max
+ t.max = ((t.max+1)*2)-1
+ var n = cast[PChunkDescArray](llAlloc((t.max + 1) * sizeof(PChunkDescArray)))
+ for i in 0 .. oldmax:
+ if t.data[i] != nil:
+ ChunkSetRawInsert(t, n, t.data[i])
+ tlsf_free(t.data)
+ t.data = n
+
+proc ChunkSetPut(t: var TChunkSet, key: TAddress): PChunkDesc =
+ var h = cast[int](key) and t.max
+ while true:
+ var x = t.data[h]
+ if x == nil: break
+ if x.key == key: return x
+ h = nextTry(h, t.max)
+
+ if ((t.max+1)*2 < t.counter*3) or ((t.max+1)-t.counter < 4):
+ ChunkSetEnlarge(t)
+ inc(t.counter)
+ h = cast[int](key) and t.max
+ while t.data[h] != nil: h = nextTry(h, t.max)
+ assert(t.data[h] == nil)
+ # the new page descriptor goes into result
+ result = cast[PChunkDesc](llAlloc(sizeof(TChunkDesc)))
+ result.next = t.head
+ result.key = key
+ t.head = result
+ t.data[h] = result
+
+# ---------- slightly higher level procs --------------------------------------
+
+proc in_Operator(s: TChunkSet, cell: PChunk): bool =
+ var u = cast[TAddress](cell)
+ var t = ChunkSetGet(s, u shr PageShift)
+ if t != nil:
+ u = (u %% PageSize) /% MemAlignment
+ result = (t.bits[u /% BitsPerUnit] and (1 shl (u %% BitsPerUnit))) != 0
+ else:
+ result = false
+
+proc incl(s: var TCellSet, cell: PCell) =
+ var u = cast[TAddress](cell)
+ var t = ChunkSetPut(s, u shr PageShift)
+ u = (u %% PageSize) /% MemAlignment
+ t.bits[u /% BitsPerUnit] = t.bits[u /% BitsPerUnit] or
+ (1 shl (u %% BitsPerUnit))
+
+proc excl(s: var TCellSet, cell: PCell) =
+ var u = cast[TAddress](cell)
+ var t = ChunkSetGet(s, u shr PageShift)
+ if t != nil:
+ u = (u %% PageSize) /% MemAlignment
+ t.bits[u /% BitsPerUnit] = (t.bits[u /% BitsPerUnit] and
+ not (1 shl (u %% BitsPerUnit)))
+
+iterator elements(t: TChunkSet): PChunk {.inline.} =
+ # while traversing it is forbidden to add pointers to the tree!
+ var r = t.head
+ while r != nil:
+ var i = 0
+ while i <= high(r.bits):
+ var w = r.bits[i] # taking a copy of r.bits[i] here is correct, because
+ # modifying operations are not allowed during traversation
+ var j = 0
+ while w != 0: # test all remaining bits for zero
+ if (w and 1) != 0: # the bit is set!
+ yield cast[PCell]((r.key shl PageShift) or # +%
+ (i*%BitsPerUnit+%j) *% MemAlignment)
+ inc(j)
+ w = w shr 1
+ inc(i)
+ r = r.next
+
+
+# ------------- chunk management ----------------------------------------------
+proc removeChunk(a: var TAllocator, c: PChunk) {.inline.} =
+ if c.prev != nil: c.prev.next = c.next
+ if c.next != nil: c.next.prev = c.prev
+ if a.freeChunks[c.size div PageSize] == c:
+ a.freeChunks[c.size div PageSize] = c.next
+
+proc addChunk(a: var TAllocator, c: PChunk) {.inline.} =
+ var s = abs(c.size) div PageSize
+ c.prev = nil
+ c.next = a.freeChunks[s]
+ a.freeChunks[s] = c
+
+proc freeChunk(a: var TAllocator, c: PChunk) =
+ assert(c.size > 0)
+ if c.size < PageSize: c.size = PageSize
+ var le = cast[PChunk](cast[TAddress](p) and not PageMask -% PageSize)
+ var ri = cast[PChunk](cast[TAddress](p) and not PageMask +%
+ c.size +% PageSize)
+ if isStartOfAChunk(ri) and ri.size < 0:
+ removeChunk(a, ri)
+ inc(c.size, -ri.size)
+ if isEndOfAChunk(le):
+ le = cast[PChunk](cast[TAddress](p) and not PageMask -%
+ le.chunkStart+PageSize)
+ if le.size < 0:
+ removeChunk(a, le)
+ inc(le.size, c.size)
+ addChunk(a, le)
+ return
+ c.size = -c.size
+ addChunk(a, c)
+
+proc splitChunk(a: var TAllocator, c: PChunk, size: int) =
+ var rest = cast[PChunk](cast[TAddress](p) + size)
+ rest.size = size - c.size # results in negative number, because rest is free
+ addChunk(a, rest)
+ # mark pages as accessible:
+ ChunkTablePut(a, rest, bitAccessible)
+ c.size = size
+
+proc getChunkOfSize(a: var TAllocator, size: int): PChunk =
+ for i in size..high(a.freeChunks):
+ result = a.freeChunks[i]
+ if result != nil:
+ if i != size: splitChunk(a, result, size)
+ else: removeChunk(a, result)
+ result.prev = nil
+ result.next = nil
+ break
+
+# -----------------------------------------------------------------------------
+
+proc getChunk(p: pointer): PChunk {.inline.} =
+ result = cast[PChunk](cast[TAddress](p) and not PageMask)
+
+proc getCellSize(p: pointer): int {.inline.} =
+ var c = getChunk(p)
+ result = abs(c.size)
+
+proc alloc(a: var TAllocator, size: int): pointer =
+ if size <= smallRequest:
+ # allocate a small block
+ var s = size div MemAlign
+ var c = a.freeSmallChunks[s]
+ if c == nil:
+ c = getChunkOfSize(0)
+ c.freeList = nil
+ c.size = size
+ a.freeSmallChunks[s] = c
+ c.len = 1
+ c.used = 1
+ c.chunkStart = 0
+ result = addr(c.data[0])
+ elif c.freeList != nil:
+ result = c.freeList
+ assert(c.freeList.zeroField == nil)
+ c.freeList = c.freeList.next
+ inc(c.used)
+ if c.freeList == nil: removeChunk(a, c)
+ else:
+ assert(c.len*size <= high(c.data))
+ result = addr(c.data[c.len*size])
+ inc(c.len)
+ inc(c.used)
+ if c.len*size > high(c.data): removeChunk(a, c)
+ else:
+ # allocate a large block
+ var c = getChunkOfSize(size shr PageShift)
+ result = addr(c.data[0])
+ c.freeList = nil
+ c.size = size
+ c.len = 0
+ c.used = 0
+ c.chunkStart = 0
+
+proc dealloc(a: var TAllocator, p: pointer) =
+ var c = getChunk(p)
+ if c.size <= smallRequest:
+ # free small block:
+ var f = cast[ptr TFreeCell](p)
+ f.zeroField = nil
+ f.next = c.freeList
+ c.freeList = p
+ dec(c.used)
+ if c.used == 0: freeChunk(c)
+ else:
+ # free big chunk
+ freeChunk(c)
+
+proc realloc(a: var TAllocator, p: pointer, size: int): pointer =
+ # could be made faster, but this is unnecessary, the GC does not use it anyway
+ result = alloc(a, size)
+ copyMem(result, p, getCellSize(p))
+ dealloc(a, p)
+
+proc isAllocatedPtr(a: TAllocator, p: pointer): bool =
+ var c = getChunk(p)
+ if c in a.accessibleChunks and c.size > 0:
+ result = cast[ptr TFreeCell](p).zeroField != nil
diff --git a/lib/arithm.nim b/lib/arithm.nim
index 91a2232c95..5c8b5726c3 100644
--- a/lib/arithm.nim
+++ b/lib/arithm.nim
@@ -14,7 +14,7 @@ proc raiseOverflow {.compilerproc, noinline.} =
# a single proc to reduce code size to a minimum
raise newException(EOverflow, "over- or underflow")
-proc raiseDivByZero {.exportc: "raiseDivByZero", noinline.} =
+proc raiseDivByZero {.compilerproc, noinline.} =
raise newException(EDivByZero, "divison by zero")
proc addInt64(a, b: int64): int64 {.compilerProc, inline.} =
diff --git a/lib/atomic.h b/lib/atomic.h
new file mode 100644
index 0000000000..afab4843f0
--- /dev/null
+++ b/lib/atomic.h
@@ -0,0 +1,2716 @@
+/* Atomic operations for Nimrod */
+
+#if defined(_MSCVER)
+__declspec(naked) int __fastcall Xadd (volatile int* pNum, int val)
+{
+ __asm
+ {
+ lock xadd dword ptr [ECX], EDX
+ mov EAX, EDX
+ ret
+ }
+}
+
+
+
+#endif
+
+
+#define ATOMIC_ASM(type,op) \
+ __asm __volatile ("lock; " op : "=m" (*(type *)p) : "ir" (v), "0" (*(type *)p))
+
+#define ATOMIC_ASM_NOLOCK(type,op) \
+ __asm __volatile (op : "=m" (*(type *)p) : "ir" (v), "0" (*(type *)p))
+
+static __inline void
+atomic_add_int(void *p, u_int v)
+{
+ ATOMIC_ASM(int, "addl %1,%0");
+}
+
+static __inline void
+atomic_add_int_nolock(void *p, u_int v)
+{
+ ATOMIC_ASM_NOLOCK(int, "addl %1,%0");
+}
+
+
+
+/*
+Atomic.h
+
+Joshua Scholar
+May 26, 2003
+
+This header contains:
+
+a multiprocessor nonblocking FIFO,
+
+a multiprocessor nonblocking LIFO
+
+multiprocessor nonblocking reference counting (including volatile pointers
+that can be safely shared between processors)
+
+nonblocking memory allocation routines
+
+template types that encapsulate variables meant to be shared between
+processors - all changes to these variables are atomic and globally visible
+
+All kinds of atomic operations that are useful in a multiprocessor context.
+
+The philosophy behind this code is that I created templates that encapsulate
+atomic access so that while the templates themselves may not be the easiest
+code to read, code that uses these templates can be simple, abstract and
+reliable.
+
+I also created regular C style functions, overloaded by type for some of
+the more basic operations. If you have regular variables or memory
+locations that you want to use in a globally visible way you have two
+choices.
+
+If the operation you want is one of the basic building blocks you can
+call one of the overloaded functions like InterlockedSetIfEqual().
+
+Otherwise it's perfectly safe to cast a pointer to your data to be a pointer
+to one of the atomic types so that you can use their methods. For instance:
+if (((AtomicInt *)foo)->CompareSomeBitsAndExchangeSomeOtherBits(exchange,
+ bitsToExchange,
+ comperand,
+ bitsToCompare))
+ ...
+or even
+
+//atomically allocate n bytes out of the pool
+ data = ((*(AtomicPtr *)curPool)+= n) - n;
+
+
+
+State of code:
+
+Unlike other libraries of similar routines that I wrote in the past, this
+has not been thoroughly tested. In fact I don't remember how much of it has
+been tested at this point.
+
+It would take an 8 way machine for me to really pound on the routines.
+
+
+
+Overview
+
+Some basic types are:
+typedef Atomic AtomicInt;
+typedef Atomic AtomicUInt;
+typedef Atomic<__int64> AtomicInt64;
+typedef Atomic AtomicUInt64;
+
+Fancier types include
+template struct AtomicPtr;
+This is a pointer that has the same semantics as the above integer types
+
+template struct AtomicPtrWithCount;
+
+AtomicPtrWithCount is a very important type. It has 32 bits of pointer
+and 32 bits of counter. There are a number of algorithms that are possible
+when a pointer and a counter can be changed atomically together including a
+lock free pushdown stack and reference counted garbage collection where
+multiple processors can share pointers as well as sharing the data that's
+pointed at.
+
+template struct AtomicPtrWithMark;
+
+This is similar to AtomicPtrWithCount but the extra 32 bits are accessed
+as individual bits instead of being accessed as a counter. It's not as
+important. I was playing with algorithms before I realized that the
+important ones I was afraid of using had been published independently of my
+former employer.
+
+
+
+The atomic number types act as integer variables, but all changes to these
+variable happen through interlocked atomic instructions.
+All changes are therefor "globally visible" in Intel's parlance.
+
+Note that incrementing (or decrementing or adding to) one of these uses
+InterlockedExchangeAdd, which for 64 bit numbers ends up relying on "lock
+CMPXCHG8B"
+
+There's an Exchange method.
+
+There are also special methods that use compare exchange in some forms that
+I've found useful:
+
+T CompareExchange(T exchange, T comperand)
+bool SetIfEqual(T exchange, T comperand)
+
+and fancier ones I found some uses for
+
+ inline bool SetIfSomeBitsAreEqual(T exchange, T comperand, T bitsToCompare)
+ inline bool SetSomeBitsIfThoseBitsAreEqual(T exchange,
+ T comperand,
+ T bitsToCompare)
+ inline bool SetSomeBitsIfSomeOtherBitsAreEqual(T exchange,
+ T bitsToExchange,
+ T comperand,
+ T bitsToCompare
+ )
+
+ inline T CompareSomeBitsAndExchange(T exchange,
+ T comperand,
+ T bitsToCompare)
+ inline T CompareSomeBitsAndExchangeThoseBits(T exchange,
+ T comperand,
+ T bitsToCompare)
+ inline T CompareSomeBitsAndExchangeSomeOtherBits(T exchange,
+ T bitsToExchange,
+ T comperand,
+ T bitsToCompare
+ )
+
+There are also atomic bit test, bit test and set etc. methods:
+
+ inline bool BTS(int bit)
+ inline bool BTC(int bit)
+ inline bool BTR(int bit)
+ inline bool BT(int bit)
+
+ALGORITHMS and their classes:
+
+The important ones are:
+
+struct Counted
+Use this as the base type for any object you want to be reference counted
+
+template class CountedPtr;
+Safely acts as pointer to a reference counted type. This pointer can not be
+shared between threads safely.
+
+template class AtomicCountedPtr;
+Like CountedPtr but this pointer CAN be shared between threads/processors
+safely.
+
+template class MPQueue;
+Multiprocessor queue. This is the nonblocking shared FIFO.
+
+Note, for the sake of convenience there is a Fifo that has the same
+semantics but can only be used single threaded:
+template class Queue ;
+
+class MPCountStack;
+This is the multiprocessor nonblocking LIFO stack. Note that what gets
+pushed on the stack are pointers to MPStackElement. Your data must be
+objects derived from MPStackElements. Note that it is not legal to push a
+NULL onto the stack - NULL is used to signal an empty stack.
+
+Note that for the sake of convienience there is, once again, a single
+threaded version of the stack:
+class SimpleStack.
+
+There are also classes for allocators that use the MPCountStack as a
+freelist.
+template
+struct MPCountFreeListAllocator;
+
+This template is recursive in the sense that each allocator gets new blocks
+from a shared allocatorn passed in the constructor (of type
+BLOCK_ALLOCATOR). You can build a tree of allocators this way. The root of
+the tree should be of type SimpleAllocator which just calls new and
+delete.
+
+Once again, for the sake of simplicity, there is a single threaded version
+of the block allocator called
+template struct SimpleBlockAllocator
+
+*/
+#ifndef ATOMIC_H
+#define ATOMIC_H
+#include
+#include
+#include
+using namespace std;
+/*
+ windows defines the following interlocked routines
+ we need to define the equivalent for volatiles (which
+ they should have been in the first place, and the following
+ types voltatile long, volatile int, volatile unsigned long,
+ volatile unsigned int, volatile T*, volatile __int64,
+ volatile unsigned __int64.
+
+ Note: I use the platform SDK which has different header files
+ for interlocked instructions than the Windows includes in Visual
+ C
+
+ If you have the platform SDK and the code doesn't compile then
+ you need to make sure that
+ "C:\Program Files\Microsoft Platform SDK\include"
+ is the first directory listed under menus "Tools" -> menu item
+ "Options" -> tab "Directories" (of course if you installed the
+ platform SDK in a different directory than
+ "C:\Program Files\Microsoft Platform SDK" then you should use
+ YOUR path.
+
+ If you don't have the plaform SDK then InterlockedCompareExchange
+ is defined for void * instead of being defined for longs... and
+ there is no InterlockedCompareExchangePointer
+
+ The whole point of Microsoft having different headers was an update
+ to support 64 bit platforms which doesn't matter here at all (some
+ of the code here relies on CMPXCHG8B swaping out both a pointer AND
+ a counter - a trick that won't work on the current 64 bit platforms).
+
+ In any case, if you don't have the platform SDK then just
+ appropriate casts to make the code compile. Keep in mind that
+ casting from 64 bit types to 32 bit types is wrong - where there's
+ a 64 bit type I meant it to call one of my assembly language
+ routines that uses CMPXCHG8B.
+
+ LONG
+ InterlockedIncrement(
+ LPLONG lpAddend
+ );
+
+ LONG
+ InterlockedDecrement(
+ LPLONG lpAddend
+ );
+
+ LONG
+ InterlockedExchange(
+ LPLONG Target,
+ LONG Value
+ );
+
+ LONG
+ InterlockedExchangeAdd(
+ LPLONG Addend,
+ LONG Value
+ );
+
+ LONG
+ InterlockedCompareExchange (
+ PLONG Destination,
+ LONG ExChange,
+ LONG Comperand
+ );
+
+ PVOID
+ InterlockedExchangePointer (
+ PVOID *Target,
+ PVOID Value
+ );
+
+ PVOID
+ InterlockedCompareExchangePointer (
+ PVOID *Destination,
+ PVOID ExChange,
+ PVOID Comperand
+ );
+*/
+
+//we'll need a special cases for volatile __int64 and
+//volatile unsigned __int64
+
+template
+inline T InterlockedIncrement(volatile T * ptr)
+{
+ return (T)InterlockedIncrement((LPLONG)ptr);
+}
+
+template
+inline T InterlockedDecrement(volatile T * ptr)
+{
+ return (T)InterlockedDecrement((LPLONG)ptr);
+}
+
+template
+inline T InterlockedExchange(volatile T * target,T value)
+{
+ return (T)InterlockedExchange((LPLONG)target,(LONG)value);
+}
+
+template
+inline T InterlockedExchangeAdd(volatile T *addend,T value)
+{
+ return (T)InterlockedExchangeAdd((LPLONG)addend,(LONG)value);
+}
+
+template
+T InterlockedCompareExchange (volatile T * dest,T exchange,T comperand)
+{
+ return (T)InterlockedCompareExchange ((LPLONG)dest,
+ (LONG)exchange,
+ (LONG)comperand);
+}
+//most common use of InterlockedCompareExchange
+template
+bool InterlockedSetIfEqual (volatile T * dest,T exchange,T comperand)
+{
+ return comperand==InterlockedCompareExchange(dest,exchange,comperand);
+}
+
+//disable the no return value warning, because the assembly language
+//routines load the appropriate registers directly
+#pragma warning(disable:4035)
+
+inline unsigned __int64
+InterlockedCompareExchange(volatile unsigned __int64 *dest
+ ,unsigned __int64 exchange
+ ,unsigned __int64 comperand)
+{
+ //value returned in eax::edx
+ __asm {
+ lea esi,comperand;
+ lea edi,exchange;
+
+ mov eax,[esi];
+ mov edx,4[esi];
+ mov ebx,[edi];
+ mov ecx,4[edi];
+ mov esi,dest;
+ //lock CMPXCHG8B [esi] is equivalent to the following except
+ //that it's atomic:
+ //ZeroFlag = (edx:eax == *esi);
+ //if (ZeroFlag) *esi = ecx:ebx;
+ //else edx:eax = *esi;
+ lock CMPXCHG8B [esi];
+ }
+}
+
+//most common use of InterlockedCompareExchange
+//It's more efficient to use the z flag than to do another compare
+inline bool
+InterlockedSetIfEqual(volatile unsigned __int64 *dest
+ ,unsigned __int64 exchange
+ ,unsigned __int64 comperand)
+{
+ //value returned in eax
+ __asm {
+ lea esi,comperand;
+ lea edi,exchange;
+
+ mov eax,[esi];
+ mov edx,4[esi];
+ mov ebx,[edi];
+ mov ecx,4[edi];
+ mov esi,dest;
+ //lock CMPXCHG8B [esi] is equivalent to the following except
+ //that it's atomic:
+ //ZeroFlag = (edx:eax == *esi);
+ //if (ZeroFlag) *esi = ecx:ebx;
+ //else edx:eax = *esi;
+ lock CMPXCHG8B [esi];
+ mov eax,0;
+ setz al;
+ }
+}
+#pragma warning(default:4035)
+
+inline unsigned __int64 InterlockedIncrement(volatile unsigned __int64 * ptr)
+{
+ unsigned __int64 comperand;
+ unsigned __int64 exchange;
+ do {
+ comperand = *ptr;
+ exchange = comperand+1;
+ }while(!InterlockedSetIfEqual(ptr,exchange,comperand));
+ return exchange;
+}
+
+inline unsigned __int64 InterlockedDecrement(volatile unsigned __int64 * ptr)
+{
+ unsigned __int64 comperand;
+ unsigned __int64 exchange;
+ do {
+ comperand = *ptr;
+ exchange = comperand-1;
+ }while(!InterlockedSetIfEqual(ptr,exchange,comperand));
+ return exchange;
+}
+
+inline unsigned __int64 InterlockedExchange(volatile unsigned __int64 * target,
+ unsigned __int64 value)
+{
+ unsigned __int64 comperand;
+ do {
+ comperand = *target;
+ }while(!InterlockedSetIfEqual(target,value,comperand));
+ return comperand;
+}
+
+inline unsigned __int64 InterlockedExchangeAdd(volatile unsigned __int64 *addend,
+ unsigned __int64 value)
+{
+ unsigned __int64 comperand;
+ do {
+ comperand = *addend;
+ }while(!InterlockedSetIfEqual(addend,comperand+value,comperand));
+ return comperand;
+}
+
+#pragma warning(disable:4035)
+inline __int64
+InterlockedCompareExchange(volatile __int64 *dest
+ ,__int64 exchange
+ ,__int64 comperand)
+{
+ //value returned in eax::edx
+ __asm {
+ lea esi,comperand;
+ lea edi,exchange;
+
+ mov eax,[esi];
+ mov edx,4[esi];
+ mov ebx,[edi];
+ mov ecx,4[edi];
+ mov esi,dest;
+ //lock CMPXCHG8B [esi] is equivalent to the following except
+ //that it's atomic:
+ //ZeroFlag = (edx:eax == *esi);
+ //if (ZeroFlag) *esi = ecx:ebx;
+ //else edx:eax = *esi;
+ lock CMPXCHG8B [esi];
+ }
+}
+
+//most common use of InterlockedCompareExchange
+//It's more efficient to use the z flag than to do another compare
+inline bool
+InterlockedSetIfEqual(volatile __int64 *dest
+ ,__int64 exchange
+ ,__int64 comperand)
+{
+ //value returned in eax
+ __asm {
+ lea esi,comperand;
+ lea edi,exchange;
+
+ mov eax,[esi];
+ mov edx,4[esi];
+ mov ebx,[edi];
+ mov ecx,4[edi];
+ mov esi,dest;
+ //lock CMPXCHG8B [esi] is equivalent to the following except
+ //that it's atomic:
+ //ZeroFlag = (edx:eax == *esi);
+ //if (ZeroFlag) *esi = ecx:ebx;
+ //else edx:eax = *esi;
+ lock CMPXCHG8B [esi];
+ mov eax,0;
+ setz al;
+ }
+}
+#pragma warning(default:4035)
+
+inline __int64 InterlockedIncrement(volatile __int64 * dest)
+{
+ __int64 comperand;
+ __int64 exchange;
+ do {
+ comperand = *dest;
+ exchange = comperand+1;
+ }while(!InterlockedSetIfEqual(dest,exchange,comperand));
+ return exchange;
+}
+
+inline __int64 InterlockedDecrement(volatile __int64 * dest)
+{
+ __int64 comperand;
+ __int64 exchange;
+ do {
+ comperand = *dest;
+ exchange = comperand-1;
+ }while(!InterlockedSetIfEqual(dest,exchange,comperand));
+ return exchange;
+}
+
+inline __int64 InterlockedExchange(volatile __int64 * target,__int64 value)
+{
+ __int64 comperand;
+ do {
+ comperand = *target;
+ }while(!InterlockedSetIfEqual(target,value,comperand));
+ return comperand;
+}
+
+inline __int64 InterlockedExchangeAdd(volatile __int64 *addend,
+ __int64 value)
+{
+ __int64 comperand;
+ do {
+ comperand = *addend;
+ }while(!InterlockedSetIfEqual(addend,comperand+value,comperand));
+ return comperand;
+}
+
+#pragma warning(disable:4035)
+//I've just thought of some algorithms that use BTS and all so I'm including them
+inline bool InterlockedBTS(volatile int *dest, int bit)
+{
+ //value returned in eax
+ __asm{
+ mov eax,bit;
+ mov ebx,dest;
+ lock bts [ebx],eax;
+ mov eax,0;
+ setc al;
+ }
+}
+inline bool InterlockedBTC(volatile int *dest, int bit)
+{
+ //value returned in eax
+ __asm{
+ mov eax,bit;
+ mov ebx,dest;
+ lock btc [ebx],eax;
+ mov eax,0;
+ setc al;
+ }
+}
+inline bool InterlockedBTR(volatile int *dest, int bit)
+{
+ //value returned in eax
+ __asm{
+ mov eax,bit;
+ mov ebx,dest;
+ lock btr [ebx],eax;
+ mov eax,0;
+ setc al;
+ }
+}
+//you can lock BT but since it doesn't change memory there isn't really any point
+inline bool BT(volatile int *dest, int bit)
+{
+ //value returned in eax
+ __asm{
+ mov eax,bit;
+ mov ebx,dest;
+ bt [ebx],eax;
+ mov eax,0;
+ setc al;
+ }
+}
+#pragma warning(default:4035)
+
+inline bool InterlockedBTS(volatile unsigned *dest, int bit)
+{
+ return InterlockedBTS((volatile int *)dest,bit);
+}
+inline bool InterlockedBTC(volatile unsigned *dest, int bit)
+{
+ return InterlockedBTC((volatile int *)dest,bit);
+}
+inline bool InterlockedBTR(volatile unsigned *dest, int bit)
+{
+ return InterlockedBTR((volatile int *)dest,bit);
+}
+inline bool BT(volatile unsigned *dest, int bit)
+{
+ return BT((volatile int *)dest,bit);
+}
+
+inline bool InterlockedBTS(volatile unsigned long *dest, int bit)
+{
+ return InterlockedBTS((volatile int *)dest,bit);
+}
+inline bool InterlockedBTC(volatile unsigned long *dest, int bit)
+{
+ return InterlockedBTC((volatile int *)dest,bit);
+}
+inline bool InterlockedBTR(volatile unsigned long *dest, int bit)
+{
+ return InterlockedBTR((volatile int *)dest,bit);
+}
+inline bool BT(volatile unsigned long *dest, int bit)
+{
+ return BT((volatile int *)dest,bit);
+}
+
+inline bool InterlockedBTS(volatile long *dest, int bit)
+{
+ return InterlockedBTS((volatile int *)dest,bit);
+}
+inline bool InterlockedBTC(volatile long *dest, int bit)
+{
+ return InterlockedBTC((volatile int *)dest,bit);
+}
+inline bool InterlockedBTR(volatile long *dest, int bit)
+{
+ return InterlockedBTR((volatile int *)dest,bit);
+}
+inline bool BT(volatile long *dest, int bit)
+{
+ return BT((volatile int *)dest,bit);
+}
+
+inline bool InterlockedBTS(volatile __int64 *dest, int bit)
+{
+ if (bit<32) return InterlockedBTS((volatile int *)&dest,bit);
+ return InterlockedBTS(1+(volatile int *)&dest,bit-32);
+}
+inline bool InterlockedBTC(volatile __int64 *dest, int bit)
+{
+ if (bit<32) return InterlockedBTC((volatile int *)&dest,bit);
+ return InterlockedBTC(1+(volatile int *)&dest,bit-32);
+}
+inline bool InterlockedBTR(volatile __int64 *dest, int bit)
+{
+ if (bit<32) return InterlockedBTR((volatile int *)&dest,bit);
+ return InterlockedBTR(1+(volatile int *)&dest,bit-32);
+}
+inline bool BT(volatile __int64 *dest, int bit)
+{
+ if (bit<32) return BT((volatile int *)&dest,bit);
+ return BT(1+(volatile int *)&dest,bit-32);
+}
+inline bool InterlockedBTS(volatile unsigned __int64 *dest, int bit)
+{
+ if (bit<32) return InterlockedBTS((volatile int *)&dest,bit);
+ return InterlockedBTS(1+(volatile int *)&dest,bit-32);
+}
+inline bool InterlockedBTC(volatile unsigned __int64 *dest, int bit)
+{
+ if (bit<32) return InterlockedBTC((volatile int *)&dest,bit);
+ return InterlockedBTC(1+(volatile int *)&dest,bit-32);
+}
+inline bool InterlockedBTR(volatile unsigned __int64 *dest, int bit)
+{
+ if (bit<32) return InterlockedBTR((volatile int *)&dest,bit);
+ return InterlockedBTR(1+(volatile int *)&dest,bit-32);
+}
+inline bool BT(volatile unsigned __int64 *dest, int bit)
+{
+ if (bit<32) return BT((volatile int *)&dest,bit);
+ return BT(1+(volatile int *)&dest,bit-32);
+}
+
+//T can be int, unsigned int, long, unsigned long
+//__int64 or unsigned __int64
+template
+struct Atomic
+{
+ volatile T value;
+
+ inline Atomic(){}
+
+ explicit inline Atomic(T n)
+ { //so that it's globally visible (to use intel's terminology)
+ InterlockedExchange(&value,n);
+ }
+
+ //if you need an atomic load then use (*this += 0)
+ //but I haven't found any algorithms that
+ //require an atomic load
+ inline operator T() const
+ {
+ return value;
+ }
+
+ inline T CompareExchange(T exchange, T comperand)
+ {
+ return InterlockedCompareExchange(&value,exchange,comperand);
+ }
+
+ //useful - simulates having a compareexchange that ignores some bits in
+ //the compare
+ inline T CompareSomeBitsAndExchange(T exchange, T comperand, T bitsToCompare)
+ {
+ T returned;
+ T bitsToIgnore = ~bitsToCompare;
+ for (;;){
+ returned = InterlockedCompareExchange(&value,exchange,comperand);
+ if (returned == comperand) return returned;
+ if (0 != ((returned ^ comperand) & bitsToCompare)) break;
+ comparand = (comparand&bitsToCompare) | (bitsToIgnore&returned);
+ }
+ return returned;
+ }
+
+ //useful - simulates having a compareexchange that ignores some bits in
+ //the compare and in the set
+ inline T CompareSomeBitsAndExchangeThoseBits(T exchange, T comperand, T bitsToCompare)
+ {
+ T returned = comperand;
+ T bitsToIgnore = ~bitsToCompare;
+ for (;;){
+ exchange = (exchange&bitsToCompare) | (bitsToIgnore&returned);
+ returned = InterlockedCompareExchange(&value,exchange,comperand);
+ if (returned == comperand) return returned;
+ if (0 != ((returned ^ comperand) & bitsToCompare)) break;
+ comparand = (comparand&bitsToCompare) | (bitsToIgnore&returned);
+ }
+ return returned;
+ }
+
+ //useful - simulates having a compareexchange that ignores some bits in
+ //the compare and others in the set
+ inline T CompareSomeBitsAndExchangeSomeOtherBits(T exchange,
+ T bitsToExchange,
+ T comperand,
+ T bitsToCompare
+ )
+ {
+ T returned = value;
+ T bitsToIgnore = ~bitsToCompare;
+ T bitsToLeave = ~bitsToExchange;
+ for (;;){
+ exchange = (exchange&bitsToExchange) | (bitsToLeave&returned);
+ returned = InterlockedCompareExchange(&value,exchange,comperand);
+ if (returned == comperand) return returned;
+ if (0 != ((returned ^ comperand) & bitsToCompare)) break;
+ comparand = (comparand&bitsToCompare) | (bitsToIgnore&returned);
+ }
+ return returned;
+ }
+
+ inline T Exchange(T exchange)
+ {
+ return InterlockedExchange(&value,exchange);
+ }
+
+ inline bool SetIfEqual(T exchange, T comperand)
+ {
+ return InterlockedSetIfEqual(&value,exchange,comperand);
+ }
+
+ //useful - simulates having a compareexchange that ignores some bits in
+ //the compare
+ inline bool SetIfSomeBitsAreEqual(T exchange, T comperand, T bitsToCompare)
+ {
+ T returned;
+ T bitsToIgnore = ~bitsToCompare;
+ for (;;){
+ returned = InterlockedCompareExchange(&value,exchange,comperand);
+ if (returned == comperand) return true;
+ if (0 != ((returned ^ comperand) & bitsToCompare)) break;
+ comparand = (comparand&bitsToCompare) | (bitsToIgnore&returned);
+ }
+ return false;
+ }
+
+ //useful - simulates having a compareexchange that ignores some bits in
+ //the compare and in the set
+ inline bool SetSomeBitsIfThoseBitsAreEqual(T exchange, T comperand, T bitsToCompare)
+ {
+ T returned = comperand;
+ T bitsToIgnore = ~bitsToCompare;
+ for (;;){
+ exchange = (exchange&bitsToCompare) | (bitsToIgnore&returned);
+ returned = InterlockedCompareExchange(&value,exchange,comperand);
+ if (returned == comperand) return true;
+ if (0 != ((returned ^ comperand) & bitsToCompare)) break;
+ comperand = (comperand&bitsToCompare) | (bitsToIgnore&returned);
+ }
+ return false;
+ }
+ //useful - simulates having a compareexchange that ignores some bits in
+ //the compare and others in the set
+ inline bool SetSomeBitsIfSomeOtherBitsAreEqual(T exchange,
+ T bitsToExchange,
+ T comperand,
+ T bitsToCompare
+ )
+ {
+ T returned = value;
+ T bitsToIgnore = ~bitsToCompare;
+ T bitsToLeave = ~bitsToExchange;
+ for (;;){
+ exchange = (exchange&bitsToExchange) | (bitsToLeave&returned);
+ returned = InterlockedCompareExchange(&value,exchange,comperand);
+ if (returned == comperand) return true;
+ if (0 != ((returned ^ comperand) & bitsToCompare)) break;
+ comperand = (comperand&bitsToCompare) | (bitsToIgnore&returned);
+ }
+ return false;
+ }
+
+ inline T operator =(T exchange)
+ {
+ Exchange(exchange);
+ return exchange;
+ }
+
+ inline T operator +=(T n)
+ {
+ return n + InterlockedExchangeAdd(&value, n);
+ }
+
+ inline T operator -=(T n)
+ {
+ return InterlockedExchangeAdd(&value, -n) - n;
+ }
+ inline T operator ++()
+ {
+ return (*this += 1);
+ }
+
+ inline T operator --()
+ {
+ return (*this -= 1);
+ }
+
+ inline T operator ++(int)
+ {
+ return InterlockedExchangeAdd(&value, (T)1);
+ }
+
+ inline T operator --(int)
+ {
+ return InterlockedExchangeAdd(&value, (T)-1);
+ }
+
+ inline T operator &=(T n)
+ {
+ T comperand;
+ T exchange;
+ do {
+ comperand = value;
+ exchange = comperand & n;
+ }while(!SetIfEqual(exchange, comperand));
+ return exchange;
+ }
+
+ inline T operator |= (T n)
+ {
+ T comperand;
+ T exchange;
+ do {
+ comperand = value;
+ exchange = comperand | n;
+ }while(!SetIfEqual(exchange, comperand));
+ return exchange;
+ }
+
+ //yes this isn't standard, but it's useful
+ inline T Mask(T bitsToKeep, T bitsToSet)
+ {
+ T comperand;
+ T exchange;
+ do {
+ comperand = value ;
+ exchange = ((comperand & bitsToKeep) | bitsToSet);
+ }while(!SetIfEqual(exchange, comperand));
+ return exchange;
+ }
+
+ inline T operator ^= (T n)
+ {
+ T comperand;
+ T exchange;
+ do {
+ comperand = value;
+ exchange = comperand ^ n;
+ }while(!SetIfEqual(exchange, comperand));
+ return exchange;
+ }
+ inline T operator *= (T n)
+ {
+ T comperand;
+ T exchange;
+ do {
+ comperand = value;
+ exchange = comperand * n;
+ }while(!SetIfEqual(exchange, comperand));
+ return exchange;
+ }
+
+ inline T operator /= (T n)
+ {
+ T comperand;
+ T exchange;
+ do {
+ comperand = value;
+ exchange = comperand / n;
+ }while(!SetIfEqual(exchange, comperand));
+ return exchange;
+ }
+
+ inline T operator >>= (unsigned n)
+ {
+ T comperand;
+ T exchange;
+ do {
+ comperand = value;
+ exchange = comperand >> n;
+ }while(!SetIfEqual(exchange, comperand));
+ return exchange;
+ }
+
+ inline T operator <<= (unsigned n)
+ {
+ T comperand;
+ T exchange;
+ do {
+ comperand = value;
+ exchange = comperand << n;
+ }while(!SetIfEqual(exchange, comperand));
+ return exchange;
+ }
+ inline bool BTS(int bit)
+ {
+ return InterlockedBTS(&value,bit);
+ }
+ inline bool BTC(int bit)
+ {
+ return InterlockedBTC(&value,bit);
+ }
+ inline bool BTR(int bit)
+ {
+ return InterlockedBTR(&value,bit);
+ }
+ inline bool BT(int bit)
+ {
+ return BT(&value,bit);
+ }
+};
+
+template
+T * InterlockedCompareExchangePointer (
+ T *volatile *dest,
+ T * exchange,
+ T * comperand
+ )
+{
+ return (T*)InterlockedCompareExchangePointer((PVOID *)dest,(PVOID)exchange,(PVOID)comperand);
+}
+
+template
+struct AtomicPtr
+{
+ T * volatile value;
+
+ inline AtomicPtr(){}
+
+ explicit inline AtomicPtr(T *n)
+ { //so that it's globally visible (to use intel's terminology)
+ InterlockedExchange(&value,n);
+ }
+ explicit inline AtomicPtr(const T *n)
+ { //so that it's globally visible (to use intel's terminology)
+ InterlockedExchange(&value,(T *)n);
+ }
+
+ inline operator T *() const
+ {
+ return value;
+ }
+
+ inline operator const T *() const
+ {
+ return value;
+ }
+
+ inline T *CompareExchange(T *exchange, T *comperand)
+ {
+ return InterlockedCompareExchangePointer(&value,exchange,comperand);
+ }
+
+ //useful - simulates having a compareexchange that ignores some bits in
+ //the compare
+ inline T * CompareSomeBitsAndExchange(T * exchange, T * comperand, int bitsToCompare)
+ {
+ T *returned;
+ int bitsToIgnore = ~bitsToCompare;
+ for (;;){
+ returned = InterlockedCompareExchangePointer(&value,exchange,comperand);
+ if (returned == comperand) return returned;
+ if (0 != ((returned ^ comperand) & bitsToCompare)) break;
+ comparand = (comparand&bitsToCompare) | (bitsToIgnore&returned);
+ }
+ return returned;
+ }
+
+ //useful - simulates having a compareexchange that ignores some bits in
+ //the compare and in the set
+ inline T * CompareSomeBitsAndExchangeThoseBits(T * exchange, T * comperand, int bitsToCompare)
+ {
+ T *returned = comperand;
+ int bitsToIgnore = ~bitsToCompare;
+ for (;;){
+ exchange = (T*)((int)exchange&bitsToCompare) | (bitsToIgnore&(int)returned);
+ returned = InterlockedCompareExchangePointer(&value,exchange,comperand);
+ if (returned == comperand) return returned;
+ if (0 != ((returned ^ comperand) & bitsToCompare)) break;
+ comparand = (T*)((int)comparand&bitsToCompare) | (bitsToIgnore&(int)returned);
+ }
+ return returned;
+ }
+ //useful - simulates having a compareexchange that ignores some bits in
+ //the compare and others in the set
+ inline T* CompareSomeBitsAndExchangeSomeOtherBits(T *exchange,
+ int bitsToExchange,
+ T * comperand,
+ int bitsToCompare
+ )
+ {
+ T * returned = value;
+ int bitsToIgnore = ~bitsToCompare;
+ int bitsToLeave = ~bitsToExchange;
+ for (;;){
+ exchange = (T*)((int)exchange&bitsToExchange) | (bitsToLeave&(int)returned);
+ returned = InterlockedCompareExchange(&value,exchange,comperand);
+ if (returned == comperand) return returned;
+ if (0 != ((returned ^ comperand) & bitsToCompare)) break;
+ comparand = (T*)((int)comparand&bitsToCompare) | (bitsToIgnore&(int)returned);
+ }
+ return returned;
+ }
+
+ inline T * operator ->() const
+ {
+ assert (value != NULL);
+ return value;
+ }
+
+ inline T *Exchange(T *exchange)
+ {
+ return InterlockedExchange(&value,exchange);
+ }
+
+ inline bool SetIfEqual(T *exchange, T *comperand)
+ {
+ return comperand==InterlockedCompareExchangePointer(&value,exchange,comperand);
+ }
+
+ //useful - simulates having a compareexchange that ignores some bits in
+ //the compare
+ inline bool SetIfSomeBitsAreEqual(T * exchange, T * comperand, int bitsToCompare)
+ {
+ T *returned;
+ int bitsToIgnore = ~bitsToCompare;
+ for (;;){
+ returned = InterlockedCompareExchangePointer(&value,exchange,comperand);
+ if (returned == comperand) return true;
+ if (0 != ((returned ^ comperand) & bitsToCompare)) break;
+ comparand = (comparand&bitsToCompare) | (bitsToIgnore&returned);
+ }
+ return false;
+ }
+
+ //useful - simulates having a compareexchange that ignores some bits in
+ //the compare and in the set
+ inline bool SetSomeBitsIfThoseBitsAreEqual(T * exchange, T * comperand, int bitsToCompare)
+ {
+ T *returned = comperand;
+ int bitsToIgnore = ~bitsToCompare;
+ for (;;){
+ exchange = (T*)((int)exchange&bitsToCompare) | (bitsToIgnore&(int)returned);
+ returned = InterlockedCompareExchangePointer(&value,exchange,comperand);
+ if (returned == comperand) return true;
+ if (0 != ((returned ^ comperand) & bitsToCompare)) break;
+ comparand = (T*)((int)comparand&bitsToCompare) | (bitsToIgnore&(int)returned);
+ }
+ return false;
+ }
+
+ //useful - simulates having a compareexchange that ignores some bits in
+ //the compare and others in the set
+ inline bool SetSomeBitsIfSomeOtherBitsAreEqual(T *exchange,
+ int bitsToExchange,
+ T * comperand,
+ int bitsToCompare
+ )
+ {
+ T * returned = value;
+ int bitsToIgnore = ~bitsToCompare;
+ int bitsToLeave = ~bitsToExchange;
+ for (;;){
+ exchange = (T*)((int)exchange&bitsToExchange) | (bitsToLeave&(int)returned);
+ returned = InterlockedCompareExchange(&value,exchange,comperand);
+ if (returned == comperand) return true;
+ if (0 != ((returned ^ comperand) & bitsToCompare)) break;
+ comparand = (T*)((int)comparand&bitsToCompare) | (bitsToIgnore&(int)returned);
+ }
+ return false;
+ }
+
+ inline T *operator =(T *exchange)
+ {
+ Exchange(exchange);
+ return exchange;
+ }
+
+ template
+ inline T *operator +=(INT_TYPE n)
+ {
+ return n + (T *)InterlockedExchangeAdd((LPLONG)&value, (LONG)(n * (LONG)sizeof(T)));
+ }
+
+ template
+ inline T *operator -=(INT_TYPE n)
+ {
+ return (T *)InterlockedExchangeAdd((LPLONG)&value, (LONG)(-n * (LONG)sizeof(T))) - n;
+ }
+ inline T *operator ++()
+ {
+ return (T *)InterlockedExchangeAdd((LPLONG)&value, (LONG)(sizeof(T))) + 1;
+ }
+
+ inline T *operator --()
+ {
+ return (T *)InterlockedExchangeAdd((LPLONG)&value, -(LONG)(sizeof(T))) - 1;
+ }
+
+ inline T *operator ++(int)
+ {
+ return (T*)InterlockedExchangeAdd((LPLONG)&value, (LONG)sizeof(T));
+ }
+
+ inline T *operator --(int)
+ {
+ return (T*)InterlockedExchangeAdd((LPLONG)&value, -(LONG)sizeof(T));
+ }
+
+ //yes this isn't standard, but it's useful
+ template
+ inline T *operator &=(INT_TYPE n)
+ {
+ T * comperand;
+ T * exchange;
+ do {
+ comperand = value;
+ exchange = (T *)((LONG)comperand & n);
+ }while(!SetIfEqual(exchange, comperand));
+ return exchange;
+ }
+
+ //yes this isn't standard, but it's useful
+ template
+ inline T *operator |= (INT_TYPE n)
+ {
+ T * comperand;
+ T * exchange;
+ do {
+ comperand = value;
+ exchange = (T *)((LONG)comperand | n);
+ }while(!SetIfEqual(exchange, comperand));
+ return exchange;
+ }
+
+ //yes this isn't standard, but it's useful
+ template
+ inline T operator ^= (INT_TYPE n)
+ {
+ T * comperand;
+ T * exchange;
+ do {
+ comperand = value;
+ exchange = (T *)((LONG)comperand ^ n);
+ }while(!SetIfEqual(exchange, comperand));
+ return exchange;
+ }
+
+ //yes this isn't standard, but it's useful
+ template
+ inline T * Mask(INT_TYPE_A bitsToKeep, INT_TYPE_B bitsToSet)
+ {
+ T * comperand;
+ T * exchange;
+ do {
+ comperand = value ;
+ exchange = (T *)(((LONG)comperand & bitsToKeep) | bitsToSet);
+ }while(!SetIfEqual(exchange, comperand));
+ return exchange;
+ }
+
+
+ inline bool BTS(int bit)
+ {
+ return InterlockedBTS((volatile int *)&value,bit);
+ }
+ inline bool BTC(int bit)
+ {
+ return InterlockedBTC((volatile int *)&value,bit);
+ }
+ inline bool BTR(int bit)
+ {
+ return InterlockedBTR((volatile int *)&value,bit);
+ }
+ inline bool BT(int bit)
+ {
+ return BT((volatile int *)&value,bit);
+ }
+};
+
+typedef Atomic AtomicInt;
+typedef Atomic AtomicUInt;
+typedef Atomic<__int64> AtomicInt64;
+typedef Atomic AtomicUInt64;
+
+template
+
+struct AtomicUnion
+{
+ A whole;
+
+ AtomicUnion()
+ {
+ assert(sizeof(T)<=sizeof(A));
+ new((void *)&whole) T();//in place new
+
+ }
+
+ ~AtomicUnion()
+ {
+ ((T *)&whole)->~T();
+ }
+
+ T &Value()
+ {
+ return *(T *)&whole;
+ }
+ const T &Value() const
+ {
+ return *(const T *)&whole;
+ }
+};
+
+
+template
+struct AtomicPtrWithCountStruct
+{
+ AtomicPtr ptr;
+ AtomicInt count;
+};
+
+
+template
+struct PtrWithCountStruct
+{
+ T* ptr;
+ int count;
+};
+
+template
+struct BitMarkedAtomicPtr : public AtomicPtr
+{
+ const int MarkMask() const
+ {
+ return (1<
+struct AtomicPtrWithCount : public AtomicUnion< AtomicPtrWithCountStruct >
+{
+ typedef AtomicUnion< PtrWithCountStruct, unsigned __int64 > SimpleUnionType;
+ AtomicPtrWithCount()
+ {
+ whole = 0;
+ }
+ AtomicPtrWithCount(unsigned __int64 o)
+ {
+ whole = o.whole;
+ }
+ AtomicPtrWithCount(T *ptr)
+ {
+ SimpleUnionType o;
+ o.Value().ptr = ptr;
+ o.Value().count = 0;
+ whole = o.whole;
+ }
+
+ operator unsigned __int64() const
+ {
+ return whole;
+ }
+ T *Ptr() const
+ {
+ return Value().ptr;
+ }
+ int Count() const
+ {
+ return Value().count;
+ }
+ unsigned __int64 Whole() const
+ {
+ return whole;
+ }
+
+ AtomicPtr & Ptr()
+ {
+ return Value().ptr;
+ }
+ AtomicInt & Count()
+ {
+ return Value().count;
+ }
+ AtomicUInt64 & Whole()
+ {
+ return whole;
+ }
+ unsigned __int64 SetPtrAndIncCount(T *ptr)
+ {
+ SimpleUnionType was;
+ SimpleUnionType to;
+ to.Value().ptr = ptr;
+ do {
+ was.whole = whole;
+ to.Value().count = was.Value().count+1;
+ }while(!whole.SetIfEqual(to.whole,was.whole));
+ return to.whole;
+ }
+ bool SetIfPtrEqualAndIncCount(T *exchange, T *comperand)
+ {
+ SimpleUnionType was;
+ SimpleUnionType to;
+ to.ptr = exchange;
+ do {
+ was.whole = whole;
+ if (was.Value().ptr != comperand) return false;
+ to.Value().count = was.Value().count+1;
+ }while(!whole.SetIfEqual(to.whole,was.whole));
+ return true;
+ }
+ unsigned __int64 ExchangeIfPtrEqualAndIncCount(T *exchange, T *comperand)
+ {
+ SimpleUnionType was;
+ SimpleUnionType to;
+ to.ptr = exchange;
+ do {
+ was.whole = whole;
+ if (was.Value().ptr != comperand) return was.whole;
+ to.Value().count = was.Value().count+1;
+ }while(!whole.SetIfEqual(to.whole,was.whole));
+ return was.whole;
+ }
+ inline T *operator =(T *exchange)
+ {
+ SetPtrAndIncCount(exchange);
+ return exchange;
+ }
+
+ template
+ inline T *operator +=(INT_TYPE n)
+ {
+ T *was;
+ T *to;
+ do {
+ was = Ptr();
+ to = was + n;
+ }while (!SetIfPtrEqualAndIncCount(to,was));
+ return to;
+ }
+
+ template
+ inline T *operator -=(INT_TYPE n)
+ {
+ T *was;
+ T *to;
+ do {
+ was = Ptr();
+ to = was - n;
+ }while (!SetIfPtrEqualAndIncCount(to,was));
+ return to;
+ }
+ inline T *operator ++()
+ {
+ return (*this += 1);
+ }
+
+ inline T *operator --()
+ {
+ return (*this -= 1);
+ }
+
+ inline T *operator ++(int)
+ {
+ return (++ *this) - 1;
+ }
+
+ inline T *operator --(int)
+ {
+ return (-- *this) + 1;
+ }
+};
+
+template
+struct AtomicPtrWithMarkStruct
+{
+ AtomicPtr ptr;
+ AtomicUInt mark;
+};
+
+
+template
+struct PtrWithMarkStruct
+{
+ T* ptr;
+ unsigned int mark;
+};
+
+template
+struct AtomicPtrWithMark : public AtomicUnion< AtomicPtrWithMarkStruct >
+{
+ typedef AtomicUnion< PtrWithMarkStruct, unsigned __int64 > SimpleUnionType;
+ AtomicPtrWithMark()
+ {
+ whole = 0;
+ }
+ AtomicPtrWithMark(unsigned __int64 o)
+ {
+ whole = o.whole;
+ }
+ AtomicPtrWithMark(T *ptr)
+ {
+ SimpleUnionType o;
+ o.Value().ptr = ptr;
+ o.Value().mark = 0;
+ whole = o.whole;
+ }
+
+ operator unsigned __int64() const
+ {
+ return whole;
+ }
+ T *Ptr() const
+ {
+ return Value().ptr;
+ }
+ int Mark() const
+ {
+ return Value().mark;
+ }
+ unsigned __int64 Whole() const
+ {
+ return whole;
+ }
+
+ AtomicPtr & Ptr()
+ {
+ return Value().ptr;
+ }
+ AtomicInt & Mark()
+ {
+ return Value().mark;
+ }
+ AtomicUInt64 & Whole()
+ {
+ return whole;
+ }
+
+ inline bool SetAndClearOtherMarksIfMarked(T *exchange, int bit)
+ {
+ assert(bit<32);
+ SimpleUnionType compareMask;
+ compareMask.Value().ptr = NULL;
+ compareMask.Value().mark = 1u< tos;
+ AtomicUInt availableThreadBits;
+ AtomicInt lastReserved;
+
+public:
+
+ MPStackElement* ExchangeStack(MPStackElement *newStack = NULL)
+ {
+ AtomicPtrWithMark::SimpleUnionType newWhole, ret;
+ newWhole.Value().mark = 0;
+ newWhole.Value().ptr = newStack;
+ ret.whole = tos.whole.Exchange(newWhole.whole);
+ return ret.Value().ptr;
+ }
+
+ MPMarkStack()
+ {
+ lastReserved = 0;
+ tos.whole = 0;
+ availableThreadBits = (unsigned)-1;
+ }
+
+ //expensive - call once per thread to reserve a bit
+ int ReserveThreadBit()
+ {
+ int offset = lastReserved;
+ //since locked operations are slow we only do
+ //bit tests on bits that look acceptable because
+ //of a nonlocked read.
+ unsigned readOnce = availableThreadBits;
+ for (int i=0; i< 32;++i){
+ const int bit = (31&(i+offset));
+ const unsigned mask = 1u<next = tos.Value().ptr;
+ }while(!tos.SetAndClearMarksIfPtrEqual(element,next));
+ }
+
+ void PushList(MPStackElement *top, MPStackElement *bottom)
+ {
+ MPStackElement * next;
+ do {
+ next = tos.Value().ptr;
+ bottom->next = tos.Value().ptr;
+ }while(!tos.SetAndClearMarksIfPtrEqual(top,next));
+ }
+
+ MPStackElement* PopElement(int i)
+ {
+ for(;;) {
+ tos.Value().mark.BTS(i-1);
+ MPStackElement * was = tos.Value().ptr;
+ if (was == NULL) return NULL;
+ if (tos.SetAndClearMarksIfMarked(was->next,i-1)) return was;
+ }
+ }
+ MPStackElement* PopElement()
+ {
+ int id = BlockingReserveThreadBit();
+ MPStackElement * ret = PopElement(id);
+ ReturnThreadBit(id);
+ return ret;
+ }
+};
+class MPCountStack
+{
+protected:
+ AtomicPtrWithCount tos;
+
+public:
+
+ MPStackElement* ExchangeStack(MPStackElement *newStack = NULL)
+ {
+ return tos.Value().ptr.Exchange(newStack);
+ }
+
+ MPCountStack()
+ {
+ tos = 0;
+ }
+
+
+ void PushElement(MPStackElement *element)
+ {
+ MPStackElement * next;
+ do {
+ next = tos.Value().ptr;
+ element->next = tos.Value().ptr;
+ }while(!tos.Value().ptr.SetIfEqual(element,next));
+ }
+
+ void PushList(MPStackElement *top, MPStackElement *bottom)
+ {
+ MPStackElement * next;
+ do {
+ next = tos.Value().ptr;
+ bottom->next = tos.Value().ptr;
+ }while(!tos.Value().ptr.SetIfEqual(top,next));
+ }
+
+ MPStackElement* PopElement()
+ {
+ AtomicPtrWithCount::SimpleUnionType was;
+ AtomicPtrWithCount::SimpleUnionType to;
+ do {
+ was.whole = tos.whole;
+ if (was.Value().ptr == NULL) return NULL;
+ to.Value().count = was.Value().count + 1;
+ to.Value().ptr = was.Value().ptr->next;
+ }while(!tos.whole.SetIfEqual(was.whole,to.whole));
+ return was.Value().ptr;
+ }
+};
+
+class SimpleStack
+{
+protected:
+ MPStackElement * tos;
+
+public:
+
+ MPStackElement* ExchangeStack(MPStackElement *newStack = NULL)
+ {
+ MPStackElement* was = tos;
+ tos = newStack;
+ return was;
+ }
+
+ SimpleStack()
+ {
+ tos = 0;
+ }
+
+
+ void PushElement(MPStackElement *element)
+ {
+ element->next = tos;
+ tos = element;
+ }
+
+ void PushList(MPStackElement *top, MPStackElement *bottom)
+ {
+ bottom->next = tos;
+ tos = top;
+ }
+
+ MPStackElement* PopElement()
+ {
+ MPStackElement* was = tos;
+ if (was) tos = was->next;
+ return was;
+ }
+};
+
+template
+struct MPMemBlock : public MPStackElement
+{
+ T data;
+ char bottomOfBlock;
+};
+
+#define OFFSET_OF_MEMBER(type,member) ((int)&(((type *)0)->member))
+
+//put one of these in each thread object
+//and you have thread local allocation
+template
+struct SimpleBlockAllocator
+{
+ SimpleStack data;
+
+ typedef SimpleBlockAllocator