repo
string
commit
string
message
string
diff
string
astashov/solutions_grid
cdccc39efa68b15fdad5712df68662776d9b4b55
Removed border HTML attribute from table, added class to header tr
diff --git a/lib/solutions_grid/helpers/grid_helper.rb b/lib/solutions_grid/helpers/grid_helper.rb index 3335206..ff7820e 100644 --- a/lib/solutions_grid/helpers/grid_helper.rb +++ b/lib/solutions_grid/helpers/grid_helper.rb @@ -1,127 +1,127 @@ module SolutionsGrid module GridHelper def show_grid(grid) prefix = set_name_prefix(grid) session[:grid] ||= {} name = grid.options[:name].to_sym session[:grid][name] ||= {} session[:grid][name][:controller] = params[:controller] session[:grid][name][:action] = params[:action] output = "<div id='#{prefix}spinner'>&nbsp;</div>\n" output += "<div id='#{prefix}grid'>\n" output += show_table(grid) output += "</div>\n" end def show_table(grid) output = "" - output += "<table class='grid' border=\"1\">\n" + output += "<table class='grid'>\n" output += show_headers(grid) output += show_values(grid) output += "</table>\n" output += show_paginate(grid) if grid.options[:paginate][:enabled] output end def show_filter(grid, show_date = false) prefix = set_name_prefix(grid) output = "" url = filter_url(:grid_name => grid.options[:name]) output += "<form action=\"#{url}\" method=\"get\" id=\"#{prefix}filter\">" output += "<input type=\"hidden\" name=\"grid_name\" class=\"grid_name\" value=\"#{grid.options[:name]}\" />" output += add_select_tags(grid) if show_date output += "<label for=\"#{prefix}string_filter\">Filter:</label> " output += text_field_tag("#{prefix}string_filter", grid.options[:filtered] ? grid.options[:filtered][:by_string] : '', :size => 20, :maxlength => 200) + " " output += submit_tag('Filter', :class => "filter_button") + " " output += submit_tag('Clear') output += "</form>" output += "<div id=\"#{prefix}filter_indicator\">" + (grid.options[:filtered] ? 'Filtered' : '') + '</div>' output end private def show_headers(grid) - output = "<tr>\n" + output = "<tr class=\"header_row\">\n" output += show_headers_of_values(grid) output += show_headers_of_actions(grid) output += "\n</tr>\n" end def show_headers_of_values(grid) output = "" # Showing headers of table, attributes is being taken from # /helpers/attributes/'something'.rb too or just humanized. grid.columns[:show].each do |column| show_value = column.show_header(grid.records.first) show_value = if grid.columns[:sort].include?(column) link_to(h(show_value), sort_url(:column => column, :grid_name => grid.options[:name]), :class => "sorted") else h(show_value) end if grid.options[:sorted] && grid.options[:sorted][:by_column] == column.name show_value += grid.options[:sorted][:order] == 'asc' ? " &#8595;" : " &#8593;" end output += "<th>#{show_value}</th>" end output end def show_headers_of_actions(grid) grid.options[:actions].inject("") { |output, action| output + "<th>#{send("action_" + action, nil)[:key]}</th>" } end def show_values(grid) output = "" # Show contents of table, attributes is being taken from # /helpers/attributes/'something'.rb too or just escaped. grid.records.each do |record| output += "<tr>\n" grid.columns[:show].each do |column| show_value = column.show_value(record) output += "<td>#{show_value}</td>" end # Adding headers for actions grid.options[:actions].each { |action| output += "<td>#{send("action_" + action, record)[:value]}</td>" } output += "\n</tr>\n" end output end def show_paginate(grid) additional_params = {:class => "grid_pagination", :id => "#{grid.options[:name]}_grid_pagination"} additional_params[:param_name] = "#{grid.options[:name]}_page" will_paginate(grid.records, additional_params) || "" end def add_select_tags(grid) prefix = set_name_prefix(grid) type = grid.options[:type_of_date_filtering] klass = (type == :datetime) ? DateTime : type.to_s.camelize.constantize output = "<label for=\"date_filter\">#{klass.to_s} Filter:</label><br />" now = klass.today rescue klass.now from_date = grid.convert_to_date(grid.options[:filtered][:from_date], type) rescue now to_date = grid.convert_to_date(grid.options[:filtered][:to_date], type) rescue now helper_name = "select_#{type}".to_sym output += send(helper_name, from_date, :prefix => "#{prefix}from_date") + "<br />" output += send(helper_name, to_date, :prefix => "#{prefix}to_date") + "<br />" output end def set_name_prefix(grid) grid.options[:name] + "_" end end end
astashov/solutions_grid
15894bc4d776810d7639786dfa86cb1ab83e0c2c
Now, it will not raise an error if there are no records in table and one of table columns not included to column_names of Model, but Model has instance method with name = name of table column.
diff --git a/lib/solutions_grid/column/active_record_column.rb b/lib/solutions_grid/column/active_record_column.rb index 8a0f616..ce441cb 100644 --- a/lib/solutions_grid/column/active_record_column.rb +++ b/lib/solutions_grid/column/active_record_column.rb @@ -1,19 +1,19 @@ require "solutions_grid/column/column" class SolutionsGrid::ActiveRecordColumn < SolutionsGrid::Column def get_type_of_column @options[:model].columns_hash[@name].type end def get_value_of_record(record, name = @name) record.send(name) end def does_column_exist? - condition = respond_to?(@methodname) || @model.column_names.include?(self.name) + condition = respond_to?(@methodname) || @model.column_names.include?(self.name) || @model.instance_methods.include?(self.name) condition ||= @example_of_record.respond_to?(self.name) if @example_of_record return condition end -end \ No newline at end of file +end
richardhaeser/Test-project
c491f63a434b8a45197daff68dc628ee1be4f494
Weer een test
diff --git a/richard.txt b/richard.txt index 6eca0c8..efab555 100644 --- a/richard.txt +++ b/richard.txt @@ -1 +1,3 @@ -dit is een test van richard \ No newline at end of file +dit is een test van richard + +Wat wil je nou? \ No newline at end of file
richardhaeser/Test-project
2ea6a7b378baee737589db7062f949fa8a29b496
Nieuw bestand er bij
diff --git a/richard.txt b/richard.txt new file mode 100644 index 0000000..6eca0c8 --- /dev/null +++ b/richard.txt @@ -0,0 +1 @@ +dit is een test van richard \ No newline at end of file
richardhaeser/Test-project
51ec484d792a2903428a0364876a09462ccddea0
Richard zijn aanpassing
diff --git a/test.txt b/test.txt index e0493f7..10ffd3f 100644 --- a/test.txt +++ b/test.txt @@ -1,6 +1,10 @@ richard wil ik wel testen Dit is een nieuw bestand Met een derde regel 123123213123 +Dit is vanaf windows pc + + +richard op 15/10/2010 9:01 \ No newline at end of file
richardhaeser/Test-project
1a44349d4c1032220948b0aef1bc7a15724dfa48
richard again
diff --git a/test.txt b/test.txt index 61fbec8..e0493f7 100644 --- a/test.txt +++ b/test.txt @@ -1,5 +1,6 @@ +richard wil ik wel testen Dit is een nieuw bestand Met een derde regel 123123213123
richardhaeser/Test-project
a61a5d87f0540ba128f50a1cbbe4df0d4c8c57ef
Weer een wijziging vanuit Windows PC
diff --git a/README b/README index 4fc445d..c5d92b1 100644 --- a/README +++ b/README @@ -1,2 +1,3 @@ +Regel er boven Dit is regel 1 Dit is van Richard
richardhaeser/Test-project
a34cdae280f63c7ae251dc1480ad34d0606d9ae3
Nieuw bestand
diff --git a/test.txt b/test.txt new file mode 100644 index 0000000..f580f45 --- /dev/null +++ b/test.txt @@ -0,0 +1 @@ +Dit is een nieuw bestand
richardhaeser/Test-project
8a4b1c845114a8aadda73fec54d2e933a650fd60
Changed the content
diff --git a/README b/README index e69de29..df42446 100644 --- a/README +++ b/README @@ -0,0 +1 @@ +Dit is van Richard
philikon/Vanadium
90716e32c70b43b75cab76aeae36d27a550fc7e9
Improve handling of about: urls (e.g. about:blank)
diff --git a/chrome/content/overlay.js b/chrome/content/overlay.js index 16758e8..1f94fcc 100644 --- a/chrome/content/overlay.js +++ b/chrome/content/overlay.js @@ -1,160 +1,164 @@ var Vanadium = { plugins: {}, init: function() { window.removeEventListener("DOMContentLoaded", this, false); this.tabbrowser = document.getElementById('content'); this.tabbrowser.addEventListener('TabSelect', this, false); this.tabbrowser.addEventListener('TabOpen', this, false); this.toolbar = document.getElementById('vanadium-toolbar'); this.toolbar.setAttribute("collapsed", "true"); }, /* Plugin "API" */ register: function(factory, host) { this.plugins[host] = factory; }, getPlugin: function() { var factory = this.plugins[this.tabbrowser.currentURI.host]; if (factory !== undefined) { factory = new factory(this.tabbrowser.contentDocument); } /* This might return undefined, and we're perfectly fine with that. */ return factory; }, havePlugin: function() { - return (this.tabbrowser.currentURI.host in this.plugins); + var uri = this.tabbrowser.currentURI; + if (uri.scheme == "about") { + return false; + } + return (uri.host in this.plugins); }, /* Event handlers */ handleEvent: function(event) { switch (event.type) { case 'DOMContentLoaded': this.init(); return; case 'TabSelect': this.onTabSelect(event); return; case 'TabOpen': this.onTabOpen(event); return; } }, onTabSelect: function(event) { this.showVanadium(this.havePlugin()); }, onTabOpen: function(event) { //TODO we should really see what's being loaded and then decide this.showVanadium(false); }, showVanadium: function(show) { var navbar = document.getElementById('nav-bar'); navbar.setAttribute("collapsed", show); this.toolbar.setAttribute("collapsed", !show); //XXX what does this do and is it really necessary? document.persist(this.toolbar.id, 'collapsed'); document.persist(navbar.id, 'collapsed'); }, onSearch: function(query) { var plugin = this.getPlugin(); if (plugin === undefined) { return; } plugin.search.value = query; this.pressEnter(plugin.search); }, onButton: function(buttontype) { var plugin = this.getPlugin(); if (plugin === undefined) { return; } var toclick = plugin[buttontype]; if (toclick === undefined) { return; } this.clickOn(toclick); }, /* Simulate a simple click on an element */ clickOn: function(element) { var event = element.ownerDocument.createEvent('MouseEvent'); event.initMouseEvent( 'click', true, // canBubble true, // cancelable element.ownerDocument.defaultView, // view (e.g. window) 1, // click count 0, 0, 0, 0, // coordinates false, false, false, false, // key modifiers 0, // button null); // target element.dispatchEvent(event); }, /* Simulate pressing the return key on an element */ pressEnter: function(element) { var event = element.ownerDocument.createEvent('KeyboardEvent'); event.initKeyEvent( 'keypress', true, // canBubble true, // cancelable element.ownerDocument.defaultView, // view (e.g. window) false, false, false, false, // key modifiers KeyEvent.DOM_VK_RETURN, // keycode 0); // charCode element.dispatchEvent(event); } }; window.addEventListener("DOMContentLoaded", Vanadium, false); function GMailPlugin(document) { var iframe = document.getElementById('canvas_frame'); if (iframe === undefined) { return; } document = jQuery(iframe.contentDocument); this.home = document.find('a[title~=Inbox]')[0]; /* It's id=":r3" for pre-Buzz GMail (e.g. Google Apps) */ this.compose = document.find('#\\:r2')[0]; /* There might be many "Reply" links in a conversation, let's just take the last one. */ this.reply = document.find('.hE:last')[0]; /* It's id="rd" for pre-Buzz GMail (e.g. Google Apps) */ this.search = document.find('#\\:rc')[0]; } Vanadium.register(GMailPlugin, "mail.google.com"); function TwitterPlugin(document) { document = jQuery(document); this.home = document.find('#home_tab > a')[0]; this.compose = document.find('#direct_messages_tab > a')[0]; this.search = document.find('#sidebar_search_q')[0]; } Vanadium.register(TwitterPlugin, "twitter.com"); function FacebookPlugin(document) { document = jQuery(document); this.home = document.find('#pageLogo > a')[0]; this.compose = document.find('#navigation_item_messages > a')[0]; //XXX doesn't work yet this.search = document.find('#q')[0]; } Vanadium.register(FacebookPlugin, "www.facebook.com"); diff --git a/chrome/skin/overlay.css b/chrome/skin/overlay.css index 9fdec78..d753776 100644 --- a/chrome/skin/overlay.css +++ b/chrome/skin/overlay.css @@ -1,25 +1,29 @@ /* "Stolen" from pinstrime theme */ #vanadium-button-home { list-style-image: url("chrome://browser/skin/Toolbar.png"); -moz-image-region: rect(0px, 180px, 23px, 144px); } #vanadium-button-home:hover:active { -moz-image-region: rect(46px, 180px, 69px, 144px); } /* "Stolen" from Thunderbird */ #vanadium-button-reply { list-style-image: url("chrome://vanadium/skin/mail-toolbar.png"); -moz-image-region: rect(0px 128px 32px 96px); } #vanadium-button-reply:hover:active { -moz-image-region: rect(32px 128px 64px 96px); } #vanadium-button-compose { list-style-image: url("chrome://vanadium/skin/mail-toolbar.png"); -moz-image-region: rect(0px 64px 32px 32px); } #vanadium-button-compose:hover:active { -moz-image-region: rect(32px 64px 64px 32px); } + +#vanadium-searchbar { + height: 28px !important; /* XXX doesn't seem to be respected */ +}
philikon/Vanadium
09c49c608f816008dda7ac3065b028d1e0dbd9c3
Minor stylistic changes
diff --git a/chrome/content/ff-overlay.xul b/chrome/content/ff-overlay.xul index b202bc1..73b2624 100644 --- a/chrome/content/ff-overlay.xul +++ b/chrome/content/ff-overlay.xul @@ -1,49 +1,51 @@ <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="chrome://vanadium/skin/overlay.css" type="text/css"?> <!DOCTYPE overlay SYSTEM "chrome://vanadium/locale/overlay.dtd"> <overlay id="vanadium-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script src="jquery.js" type="application/javascript" /> <script src="overlay.js" type="application/javascript" /> <stringbundleset id="stringbundleset"> <stringbundle id="vanadium-strings" src="chrome://vanadium/locale/overlay.properties"/> </stringbundleset> <toolbox id="navigator-toolbox"> <!-- Trick: empty toolbarname means it's not listed in 'View' menu --> <toolbar id="vanadium-toolbar" class="toolbar-primary chromeclass-toolbar" - toolbarname="" - mode="icons" - customizable="true"> + toolbarname=""> <toolbarbutton id="vanadium-button-home" label="&vanadium.button.home.label;" tooltiptext="&vanadium.button.home.tooltip;" oncommand="Vanadium.onButton('home')"/> <toolbarbutton id="vanadium-button-compose" label="&vanadium.button.compose.label;" tooltiptext="&vanadium.button.compose.tooltip;" oncommand="Vanadium.onButton('compose')"/> <toolbarbutton id="vanadium-button-reply" label="&vanadium.button.reply.label;" tooltiptext="&vanadium.button.reply.tooltip;" oncommand="Vanadium.onButton('reply')"/> <toolbaritem id="vanadium-searchbar-container" title="&vanadium.searchbar.label;" - persist="width"> + flex="1"> + <!-- XXX Do we want searchbutton="true" here? It makes the + (x) in the corner go away. --> <textbox id="vanadium-searchbar" - searchbutton="true" + type="search" + class="compact" + flex="1" onchange="Vanadium.onSearch(this.value)" /> </toolbaritem> </toolbar> </toolbox> </overlay>
philikon/Vanadium
12bbfda96794b4f5b059321866de5752932ada03
Style the toolbar a bit with buttons. Due to the lack of time, imagination and motivation on my part, I'm just stealing Thunderbird icons for now :)
diff --git a/chrome/content/ff-overlay.xul b/chrome/content/ff-overlay.xul index e16c5f2..b202bc1 100644 --- a/chrome/content/ff-overlay.xul +++ b/chrome/content/ff-overlay.xul @@ -1,48 +1,49 @@ <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="chrome://vanadium/skin/overlay.css" type="text/css"?> <!DOCTYPE overlay SYSTEM "chrome://vanadium/locale/overlay.dtd"> <overlay id="vanadium-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script src="jquery.js" type="application/javascript" /> <script src="overlay.js" type="application/javascript" /> <stringbundleset id="stringbundleset"> <stringbundle id="vanadium-strings" src="chrome://vanadium/locale/overlay.properties"/> </stringbundleset> <toolbox id="navigator-toolbox"> <!-- Trick: empty toolbarname means it's not listed in 'View' menu --> - <toolbar class="chromeclass-toolbar" + <toolbar id="vanadium-toolbar" + class="toolbar-primary chromeclass-toolbar" toolbarname="" - customizable="true" - id="vanadium-toolbar"> + mode="icons" + customizable="true"> <toolbarbutton id="vanadium-button-home" label="&vanadium.button.home.label;" tooltiptext="&vanadium.button.home.tooltip;" oncommand="Vanadium.onButton('home')"/> <toolbarbutton id="vanadium-button-compose" label="&vanadium.button.compose.label;" tooltiptext="&vanadium.button.compose.tooltip;" oncommand="Vanadium.onButton('compose')"/> <toolbarbutton id="vanadium-button-reply" label="&vanadium.button.reply.label;" tooltiptext="&vanadium.button.reply.tooltip;" oncommand="Vanadium.onButton('reply')"/> <toolbaritem id="vanadium-searchbar-container" title="&vanadium.searchbar.label;" persist="width"> <textbox id="vanadium-searchbar" searchbutton="true" onchange="Vanadium.onSearch(this.value)" /> </toolbaritem> </toolbar> </toolbox> </overlay> diff --git a/chrome/skin/mail-toolbar.png b/chrome/skin/mail-toolbar.png new file mode 100644 index 0000000..7af5f57 Binary files /dev/null and b/chrome/skin/mail-toolbar.png differ diff --git a/chrome/skin/overlay.css b/chrome/skin/overlay.css index 2342511..9fdec78 100644 --- a/chrome/skin/overlay.css +++ b/chrome/skin/overlay.css @@ -1,22 +1,25 @@ -/* This is just an example. You shouldn't do this. */ -#vanadium-hello -{ - color: red ! important; +/* "Stolen" from pinstrime theme */ +#vanadium-button-home { + list-style-image: url("chrome://browser/skin/Toolbar.png"); + -moz-image-region: rect(0px, 180px, 23px, 144px); } -#vanadium-toolbar-button -{ - list-style-image: url("chrome://vanadium/skin/toolbar-button.png"); - -moz-image-region: rect(0px 24px 24px 0px); +#vanadium-button-home:hover:active { + -moz-image-region: rect(46px, 180px, 69px, 144px); } -#vanadium-toolbar-button:hover -{ - -moz-image-region: rect(24px 24px 48px 0px); + +/* "Stolen" from Thunderbird */ +#vanadium-button-reply { + list-style-image: url("chrome://vanadium/skin/mail-toolbar.png"); + -moz-image-region: rect(0px 128px 32px 96px); } -[iconsize="small"] #vanadium-toolbar-button -{ - -moz-image-region: rect( 0px 40px 16px 24px); +#vanadium-button-reply:hover:active { + -moz-image-region: rect(32px 128px 64px 96px); } -[iconsize="small"] #vanadium-toolbar-button:hover -{ - -moz-image-region: rect(24px 40px 40px 24px); + +#vanadium-button-compose { + list-style-image: url("chrome://vanadium/skin/mail-toolbar.png"); + -moz-image-region: rect(0px 64px 32px 32px); +} +#vanadium-button-compose:hover:active { + -moz-image-region: rect(32px 64px 64px 32px); } diff --git a/chrome/skin/toolbar-button.png b/chrome/skin/toolbar-button.png deleted file mode 100644 index 45d6044..0000000 Binary files a/chrome/skin/toolbar-button.png and /dev/null differ
philikon/Vanadium
9cfd20864e07000626bd55a408ae5575be1b44bd
Facebook plugin. Search doesn't work yet :/
diff --git a/chrome/content/overlay.js b/chrome/content/overlay.js index 638a2ea..16758e8 100644 --- a/chrome/content/overlay.js +++ b/chrome/content/overlay.js @@ -1,150 +1,160 @@ var Vanadium = { plugins: {}, init: function() { window.removeEventListener("DOMContentLoaded", this, false); this.tabbrowser = document.getElementById('content'); this.tabbrowser.addEventListener('TabSelect', this, false); this.tabbrowser.addEventListener('TabOpen', this, false); this.toolbar = document.getElementById('vanadium-toolbar'); this.toolbar.setAttribute("collapsed", "true"); }, /* Plugin "API" */ register: function(factory, host) { this.plugins[host] = factory; }, getPlugin: function() { var factory = this.plugins[this.tabbrowser.currentURI.host]; if (factory !== undefined) { factory = new factory(this.tabbrowser.contentDocument); } /* This might return undefined, and we're perfectly fine with that. */ return factory; }, havePlugin: function() { return (this.tabbrowser.currentURI.host in this.plugins); }, /* Event handlers */ handleEvent: function(event) { switch (event.type) { case 'DOMContentLoaded': this.init(); return; case 'TabSelect': this.onTabSelect(event); return; case 'TabOpen': this.onTabOpen(event); return; } }, onTabSelect: function(event) { this.showVanadium(this.havePlugin()); }, onTabOpen: function(event) { //TODO we should really see what's being loaded and then decide this.showVanadium(false); }, showVanadium: function(show) { var navbar = document.getElementById('nav-bar'); navbar.setAttribute("collapsed", show); this.toolbar.setAttribute("collapsed", !show); //XXX what does this do and is it really necessary? document.persist(this.toolbar.id, 'collapsed'); document.persist(navbar.id, 'collapsed'); }, onSearch: function(query) { var plugin = this.getPlugin(); if (plugin === undefined) { return; } plugin.search.value = query; this.pressEnter(plugin.search); }, onButton: function(buttontype) { var plugin = this.getPlugin(); if (plugin === undefined) { return; } var toclick = plugin[buttontype]; if (toclick === undefined) { return; } this.clickOn(toclick); }, /* Simulate a simple click on an element */ clickOn: function(element) { var event = element.ownerDocument.createEvent('MouseEvent'); event.initMouseEvent( 'click', true, // canBubble true, // cancelable element.ownerDocument.defaultView, // view (e.g. window) 1, // click count 0, 0, 0, 0, // coordinates false, false, false, false, // key modifiers 0, // button null); // target element.dispatchEvent(event); }, /* Simulate pressing the return key on an element */ pressEnter: function(element) { var event = element.ownerDocument.createEvent('KeyboardEvent'); event.initKeyEvent( 'keypress', true, // canBubble true, // cancelable element.ownerDocument.defaultView, // view (e.g. window) false, false, false, false, // key modifiers KeyEvent.DOM_VK_RETURN, // keycode 0); // charCode element.dispatchEvent(event); } }; window.addEventListener("DOMContentLoaded", Vanadium, false); function GMailPlugin(document) { var iframe = document.getElementById('canvas_frame'); if (iframe === undefined) { return; } document = jQuery(iframe.contentDocument); this.home = document.find('a[title~=Inbox]')[0]; /* It's id=":r3" for pre-Buzz GMail (e.g. Google Apps) */ this.compose = document.find('#\\:r2')[0]; /* There might be many "Reply" links in a conversation, let's just take the last one. */ this.reply = document.find('.hE:last')[0]; /* It's id="rd" for pre-Buzz GMail (e.g. Google Apps) */ this.search = document.find('#\\:rc')[0]; } Vanadium.register(GMailPlugin, "mail.google.com"); function TwitterPlugin(document) { document = jQuery(document); this.home = document.find('#home_tab > a')[0]; - this.compose = document.find('#direct_messages_tab a')[0]; + this.compose = document.find('#direct_messages_tab > a')[0]; this.search = document.find('#sidebar_search_q')[0]; } Vanadium.register(TwitterPlugin, "twitter.com"); + + +function FacebookPlugin(document) { + document = jQuery(document); + this.home = document.find('#pageLogo > a')[0]; + this.compose = document.find('#navigation_item_messages > a')[0]; + //XXX doesn't work yet + this.search = document.find('#q')[0]; +} +Vanadium.register(FacebookPlugin, "www.facebook.com");
philikon/Vanadium
2636994ec850f708a31bbb40734522a9149b4add
Improve language
diff --git a/README.txt b/README.txt index 9aead3e..244a41c 100644 --- a/README.txt +++ b/README.txt @@ -1,12 +1,12 @@ Vanadium, n: metallic element used to strengthen steel alloys ============================================================= -Like a wrench from your toolbox, a browser UI basically is made from -two parts: the web page they're displaying (the steel) and the UI -around that (the chrome coating) to make it look shiny. Thing is, -good tools are made not from steel alone but from a stronger alloy of -steel and vanadium. +Like a wrench from your toolbox, a conventional browser's UI is +basically made from two parts: the web page they're displaying (the +steel) and the UI around that (the chrome coating) to make it look +shiny. Thing is, good tools are made not from steel alone but from a +stronger alloy, created by adding vanadium to the steel. This extension improves the Firefox UI in a similar way by blending some of the web app's UI into the Firefox UI, thereby adding an extra element to the steel and chrome mix.
philikon/Vanadium
7e9b9cca1e7ed046c0e8032ff08f593e2d47ebae
Rewrite the GMail plugin in terms of jQuery and add a Twitter plugin
diff --git a/chrome/content/overlay.js b/chrome/content/overlay.js index c16f84b..638a2ea 100644 --- a/chrome/content/overlay.js +++ b/chrome/content/overlay.js @@ -1,136 +1,150 @@ var Vanadium = { plugins: {}, init: function() { window.removeEventListener("DOMContentLoaded", this, false); this.tabbrowser = document.getElementById('content'); this.tabbrowser.addEventListener('TabSelect', this, false); this.tabbrowser.addEventListener('TabOpen', this, false); this.toolbar = document.getElementById('vanadium-toolbar'); this.toolbar.setAttribute("collapsed", "true"); }, /* Plugin "API" */ register: function(factory, host) { this.plugins[host] = factory; }, getPlugin: function() { var factory = this.plugins[this.tabbrowser.currentURI.host]; if (factory !== undefined) { factory = new factory(this.tabbrowser.contentDocument); } /* This might return undefined, and we're perfectly fine with that. */ return factory; }, havePlugin: function() { return (this.tabbrowser.currentURI.host in this.plugins); }, /* Event handlers */ handleEvent: function(event) { switch (event.type) { case 'DOMContentLoaded': this.init(); return; case 'TabSelect': this.onTabSelect(event); return; case 'TabOpen': this.onTabOpen(event); return; } }, onTabSelect: function(event) { this.showVanadium(this.havePlugin()); }, onTabOpen: function(event) { //TODO we should really see what's being loaded and then decide this.showVanadium(false); }, showVanadium: function(show) { var navbar = document.getElementById('nav-bar'); navbar.setAttribute("collapsed", show); this.toolbar.setAttribute("collapsed", !show); //XXX what does this do and is it really necessary? document.persist(this.toolbar.id, 'collapsed'); document.persist(navbar.id, 'collapsed'); }, onSearch: function(query) { var plugin = this.getPlugin(); if (plugin === undefined) { return; } plugin.search.value = query; this.pressEnter(plugin.search); }, onButton: function(buttontype) { var plugin = this.getPlugin(); if (plugin === undefined) { return; } var toclick = plugin[buttontype]; if (toclick === undefined) { return; } this.clickOn(toclick); }, /* Simulate a simple click on an element */ clickOn: function(element) { var event = element.ownerDocument.createEvent('MouseEvent'); event.initMouseEvent( 'click', true, // canBubble true, // cancelable element.ownerDocument.defaultView, // view (e.g. window) 1, // click count 0, 0, 0, 0, // coordinates false, false, false, false, // key modifiers 0, // button null); // target element.dispatchEvent(event); }, /* Simulate pressing the return key on an element */ pressEnter: function(element) { var event = element.ownerDocument.createEvent('KeyboardEvent'); event.initKeyEvent( 'keypress', true, // canBubble true, // cancelable element.ownerDocument.defaultView, // view (e.g. window) false, false, false, false, // key modifiers KeyEvent.DOM_VK_RETURN, // keycode 0); // charCode element.dispatchEvent(event); } }; window.addEventListener("DOMContentLoaded", Vanadium, false); function GMailPlugin(document) { var iframe = document.getElementById('canvas_frame'); + if (iframe === undefined) { + return; + } - /* First link of that class should be 'Inbox' */ - this.home = iframe.contentDocument.getElementsByClassName('n0')[0]; + document = jQuery(iframe.contentDocument); + this.home = document.find('a[title~=Inbox]')[0]; /* It's id=":r3" for pre-Buzz GMail (e.g. Google Apps) */ - this.compose = iframe.contentDocument.getElementById(':r2'); - this.reply = iframe.contentDocument.getElementsByClassName('hE')[0]; + this.compose = document.find('#\\:r2')[0]; + /* There might be many "Reply" links in a conversation, let's just + take the last one. */ + this.reply = document.find('.hE:last')[0]; /* It's id="rd" for pre-Buzz GMail (e.g. Google Apps) */ - this.search = iframe.contentDocument.getElementById(':rc'); + this.search = document.find('#\\:rc')[0]; } Vanadium.register(GMailPlugin, "mail.google.com"); + + +function TwitterPlugin(document) { + document = jQuery(document); + this.home = document.find('#home_tab > a')[0]; + this.compose = document.find('#direct_messages_tab a')[0]; + this.search = document.find('#sidebar_search_q')[0]; +} +Vanadium.register(TwitterPlugin, "twitter.com");
philikon/Vanadium
7cc9694fc93e0e70ceb9b605e5477b21e7576742
Vendor import of jQuery, to make writing plugins easier and less error prone.
diff --git a/chrome/content/ff-overlay.xul b/chrome/content/ff-overlay.xul index fb153d0..e16c5f2 100644 --- a/chrome/content/ff-overlay.xul +++ b/chrome/content/ff-overlay.xul @@ -1,47 +1,48 @@ <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="chrome://vanadium/skin/overlay.css" type="text/css"?> <!DOCTYPE overlay SYSTEM "chrome://vanadium/locale/overlay.dtd"> <overlay id="vanadium-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script src="jquery.js" type="application/javascript" /> <script src="overlay.js" type="application/javascript" /> <stringbundleset id="stringbundleset"> <stringbundle id="vanadium-strings" src="chrome://vanadium/locale/overlay.properties"/> </stringbundleset> <toolbox id="navigator-toolbox"> <!-- Trick: empty toolbarname means it's not listed in 'View' menu --> <toolbar class="chromeclass-toolbar" toolbarname="" customizable="true" id="vanadium-toolbar"> <toolbarbutton id="vanadium-button-home" label="&vanadium.button.home.label;" tooltiptext="&vanadium.button.home.tooltip;" oncommand="Vanadium.onButton('home')"/> <toolbarbutton id="vanadium-button-compose" label="&vanadium.button.compose.label;" tooltiptext="&vanadium.button.compose.tooltip;" oncommand="Vanadium.onButton('compose')"/> <toolbarbutton id="vanadium-button-reply" label="&vanadium.button.reply.label;" tooltiptext="&vanadium.button.reply.tooltip;" oncommand="Vanadium.onButton('reply')"/> <toolbaritem id="vanadium-searchbar-container" title="&vanadium.searchbar.label;" persist="width"> <textbox id="vanadium-searchbar" searchbutton="true" onchange="Vanadium.onSearch(this.value)" /> </toolbaritem> </toolbar> </toolbox> </overlay> diff --git a/chrome/content/jquery.js b/chrome/content/jquery.js new file mode 100644 index 0000000..1097010 --- /dev/null +++ b/chrome/content/jquery.js @@ -0,0 +1,6078 @@ +/*! + * jQuery JavaScript Library v1.4.1 + * http://jquery.com/ + * + * Copyright 2010, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * Copyright 2010, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * + * Date: Mon Jan 25 19:43:33 2010 -0500 + */ +(function( window, undefined ) { + +// Define a local copy of jQuery +var jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context ); + }, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // Use the correct document accordingly with window argument (sandbox) + document = window.document, + + // A central reference to the root jQuery(document) + rootjQuery, + + // A simple way to check for HTML strings or ID strings + // (both of which we optimize for) + quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/, + + // Is it a simple selector + isSimple = /^.[^:#\[\.,]*$/, + + // Check if a string has a non-whitespace character in it + rnotwhite = /\S/, + + // Used for trimming whitespace + rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, + + // Keep a UserAgent string for use with jQuery.browser + userAgent = navigator.userAgent, + + // For matching the engine and version of the browser + browserMatch, + + // Has the ready events already been bound? + readyBound = false, + + // The functions to execute on DOM ready + readyList = [], + + // The ready event handler + DOMContentLoaded, + + // Save a reference to some core methods + toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + push = Array.prototype.push, + slice = Array.prototype.slice, + indexOf = Array.prototype.indexOf; + +jQuery.fn = jQuery.prototype = { + init: function( selector, context ) { + var match, elem, ret, doc; + + // Handle $(""), $(null), or $(undefined) + if ( !selector ) { + return this; + } + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + // Are we dealing with HTML string or an ID? + match = quickExpr.exec( selector ); + + // Verify a match, and that no context was specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + doc = (context ? context.ownerDocument || context : document); + + // If a single string is passed in and it's a single tag + // just do a createElement and skip the rest + ret = rsingleTag.exec( selector ); + + if ( ret ) { + if ( jQuery.isPlainObject( context ) ) { + selector = [ document.createElement( ret[1] ) ]; + jQuery.fn.attr.call( selector, context, true ); + + } else { + selector = [ doc.createElement( ret[1] ) ]; + } + + } else { + ret = buildFragment( [ match[1] ], [ doc ] ); + selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes; + } + + // HANDLE: $("#id") + } else { + elem = document.getElementById( match[2] ); + + if ( elem ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $("TAG") + } else if ( !context && /^\w+$/.test( selector ) ) { + this.selector = selector; + this.context = document; + selector = document.getElementsByTagName( selector ); + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return (context || rootjQuery).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return jQuery( context ).find( selector ); + } + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if (selector.selector !== undefined) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.isArray( selector ) ? + this.setArray( selector ) : + jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.4.1", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return slice.call( this, 0 ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + // Build a new jQuery matched element set + var ret = jQuery( elems || null ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) { + ret.selector = this.selector + (this.selector ? " " : "") + selector; + } else if ( name ) { + ret.selector = this.selector + "." + name + "(" + selector + ")"; + } + + // Return the newly-formed element set + return ret; + }, + + // Force the current matched set of elements to become + // the specified array of elements (destroying the stack in the process) + // You should use pushStack() in order to do this, but maintain the stack + setArray: function( elems ) { + // Resetting the length to 0, then using the native Array push + // is a super-fast way to populate an object with array-like properties + this.length = 0; + push.apply( this, elems ); + + return this; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Attach the listeners + jQuery.bindReady(); + + // If the DOM is already ready + if ( jQuery.isReady ) { + // Execute the function immediately + fn.call( document, jQuery ); + + // Otherwise, remember the function for later + } else if ( readyList ) { + // Add the function to the wait list + readyList.push( fn ); + } + + return this; + }, + + eq: function( i ) { + return i === -1 ? + this.slice( i ) : + this.slice( i, +i + 1 ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ), + "slice", slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || jQuery(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + // copy reference to target object + var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging object literal values or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) { + var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src + : jQuery.isArray(copy) ? [] : {}; + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + noConflict: function( deep ) { + window.$ = _$; + + if ( deep ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // Handle when the DOM is ready + ready: function() { + // Make sure that the DOM is not already loaded + if ( !jQuery.isReady ) { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready, 13 ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If there are functions bound, to execute + if ( readyList ) { + // Execute all of them + var fn, i = 0; + while ( (fn = readyList[ i++ ]) ) { + fn.call( document, jQuery ); + } + + // Reset the list of functions + readyList = null; + } + + // Trigger any bound ready events + if ( jQuery.fn.triggerHandler ) { + jQuery( document ).triggerHandler( "ready" ); + } + } + }, + + bindReady: function() { + if ( readyBound ) { + return; + } + + readyBound = true; + + // Catch cases where $(document).ready() is called after the + // browser event has already occurred. + if ( document.readyState === "complete" ) { + return jQuery.ready(); + } + + // Mozilla, Opera and webkit nightlies currently support this event + if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); + + // If IE event model is used + } else if ( document.attachEvent ) { + // ensure firing before onload, + // maybe late but safe also for iframes + document.attachEvent("onreadystatechange", DOMContentLoaded); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); + + // If IE and not a frame + // continually check to see if the document is ready + var toplevel = false; + + try { + toplevel = window.frameElement == null; + } catch(e) {} + + if ( document.documentElement.doScroll && toplevel ) { + doScrollCheck(); + } + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return toString.call(obj) === "[object Function]"; + }, + + isArray: function( obj ) { + return toString.call(obj) === "[object Array]"; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) { + return false; + } + + // Not own constructor property must be Object + if ( obj.constructor + && !hasOwnProperty.call(obj, "constructor") + && !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || hasOwnProperty.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + for ( var name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw msg; + }, + + parseJSON: function( data ) { + if ( typeof data !== "string" || !data ) { + return null; + } + + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@") + .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]") + .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) { + + // Try to use the native JSON parser first + return window.JSON && window.JSON.parse ? + window.JSON.parse( data ) : + (new Function("return " + data))(); + + } else { + jQuery.error( "Invalid JSON: " + data ); + } + }, + + noop: function() {}, + + // Evalulates a script in a global context + globalEval: function( data ) { + if ( data && rnotwhite.test(data) ) { + // Inspired by code by Andrea Giammarchi + // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html + var head = document.getElementsByTagName("head")[0] || document.documentElement, + script = document.createElement("script"); + + script.type = "text/javascript"; + + if ( jQuery.support.scriptEval ) { + script.appendChild( document.createTextNode( data ) ); + } else { + script.text = data; + } + + // Use insertBefore instead of appendChild to circumvent an IE6 bug. + // This arises when a base node is used (#2709). + head.insertBefore( script, head.firstChild ); + head.removeChild( script ); + } + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); + }, + + // args is for internal usage only + each: function( object, callback, args ) { + var name, i = 0, + length = object.length, + isObj = length === undefined || jQuery.isFunction(object); + + if ( args ) { + if ( isObj ) { + for ( name in object ) { + if ( callback.apply( object[ name ], args ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.apply( object[ i++ ], args ) === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isObj ) { + for ( name in object ) { + if ( callback.call( object[ name ], name, object[ name ] ) === false ) { + break; + } + } + } else { + for ( var value = object[0]; + i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} + } + } + + return object; + }, + + trim: function( text ) { + return (text || "").replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( array, results ) { + var ret = results || []; + + if ( array != null ) { + // The window, strings (and functions) also have 'length' + // The extra typeof function check is to prevent crashes + // in Safari 2 (See: #3039) + if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) { + push.call( ret, array ); + } else { + jQuery.merge( ret, array ); + } + } + + return ret; + }, + + inArray: function( elem, array ) { + if ( array.indexOf ) { + return array.indexOf( elem ); + } + + for ( var i = 0, length = array.length; i < length; i++ ) { + if ( array[ i ] === elem ) { + return i; + } + } + + return -1; + }, + + merge: function( first, second ) { + var i = first.length, j = 0; + + if ( typeof second.length === "number" ) { + for ( var l = second.length; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var ret = []; + + // Go through the array, only saving the items + // that pass the validator function + for ( var i = 0, length = elems.length; i < length; i++ ) { + if ( !inv !== !callback( elems[ i ], i ) ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var ret = [], value; + + // Go through the array, translating each of the items to their + // new value (or values). + for ( var i = 0, length = elems.length; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + return ret.concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + proxy: function( fn, proxy, thisObject ) { + if ( arguments.length === 2 ) { + if ( typeof proxy === "string" ) { + thisObject = fn; + fn = thisObject[ proxy ]; + proxy = undefined; + + } else if ( proxy && !jQuery.isFunction( proxy ) ) { + thisObject = proxy; + proxy = undefined; + } + } + + if ( !proxy && fn ) { + proxy = function() { + return fn.apply( thisObject || this, arguments ); + }; + } + + // Set the guid of unique handler to the same of original handler, so it can be removed + if ( fn ) { + proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; + } + + // So proxy can be declared as an argument + return proxy; + }, + + // Use of jQuery.browser is frowned upon. + // More details: http://docs.jquery.com/Utilities/jQuery.browser + uaMatch: function( ua ) { + ua = ua.toLowerCase(); + + var match = /(webkit)[ \/]([\w.]+)/.exec( ua ) || + /(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) || + /(msie) ([\w.]+)/.exec( ua ) || + !/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) || + []; + + return { browser: match[1] || "", version: match[2] || "0" }; + }, + + browser: {} +}); + +browserMatch = jQuery.uaMatch( userAgent ); +if ( browserMatch.browser ) { + jQuery.browser[ browserMatch.browser ] = true; + jQuery.browser.version = browserMatch.version; +} + +// Deprecated, use jQuery.browser.webkit instead +if ( jQuery.browser.webkit ) { + jQuery.browser.safari = true; +} + +if ( indexOf ) { + jQuery.inArray = function( elem, array ) { + return indexOf.call( array, elem ); + }; +} + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); + +// Cleanup functions for the document ready method +if ( document.addEventListener ) { + DOMContentLoaded = function() { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + }; + +} else if ( document.attachEvent ) { + DOMContentLoaded = function() { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( document.readyState === "complete" ) { + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }; +} + +// The DOM ready check for Internet Explorer +function doScrollCheck() { + if ( jQuery.isReady ) { + return; + } + + try { + // If IE is used, use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + document.documentElement.doScroll("left"); + } catch( error ) { + setTimeout( doScrollCheck, 1 ); + return; + } + + // and execute any waiting functions + jQuery.ready(); +} + +function evalScript( i, elem ) { + if ( elem.src ) { + jQuery.ajax({ + url: elem.src, + async: false, + dataType: "script" + }); + } else { + jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); + } + + if ( elem.parentNode ) { + elem.parentNode.removeChild( elem ); + } +} + +// Mutifunctional method to get and set values to a collection +// The value/s can be optionally by executed if its a function +function access( elems, key, value, exec, fn, pass ) { + var length = elems.length; + + // Setting many attributes + if ( typeof key === "object" ) { + for ( var k in key ) { + access( elems, k, key[k], exec, fn, value ); + } + return elems; + } + + // Setting one attribute + if ( value !== undefined ) { + // Optionally, function values get executed if exec is true + exec = !pass && exec && jQuery.isFunction(value); + + for ( var i = 0; i < length; i++ ) { + fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + } + + return elems; + } + + // Getting an attribute + return length ? fn( elems[0], key ) : null; +} + +function now() { + return (new Date).getTime(); +} +(function() { + + jQuery.support = {}; + + var root = document.documentElement, + script = document.createElement("script"), + div = document.createElement("div"), + id = "script" + now(); + + div.style.display = "none"; + div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; + + var all = div.getElementsByTagName("*"), + a = div.getElementsByTagName("a")[0]; + + // Can't get basic test support + if ( !all || !all.length || !a ) { + return; + } + + jQuery.support = { + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: div.firstChild.nodeType === 3, + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName("tbody").length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName("link").length, + + // Get the style information from getAttribute + // (IE uses .cssText insted) + style: /red/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: a.getAttribute("href") === "/a", + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.55$/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Make sure that if no value is specified for a checkbox + // that it defaults to "on". + // (WebKit defaults to "" instead) + checkOn: div.getElementsByTagName("input")[0].value === "on", + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: document.createElement("select").appendChild( document.createElement("option") ).selected, + + // Will be defined later + checkClone: false, + scriptEval: false, + noCloneEvent: true, + boxModel: null + }; + + script.type = "text/javascript"; + try { + script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); + } catch(e) {} + + root.insertBefore( script, root.firstChild ); + + // Make sure that the execution of code works by injecting a script + // tag with appendChild/createTextNode + // (IE doesn't support this, fails, and uses .text instead) + if ( window[ id ] ) { + jQuery.support.scriptEval = true; + delete window[ id ]; + } + + root.removeChild( script ); + + if ( div.attachEvent && div.fireEvent ) { + div.attachEvent("onclick", function click() { + // Cloning a node shouldn't copy over any + // bound event handlers (IE does this) + jQuery.support.noCloneEvent = false; + div.detachEvent("onclick", click); + }); + div.cloneNode(true).fireEvent("onclick"); + } + + div = document.createElement("div"); + div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>"; + + var fragment = document.createDocumentFragment(); + fragment.appendChild( div.firstChild ); + + // WebKit doesn't clone checked state correctly in fragments + jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; + + // Figure out if the W3C box model works as expected + // document.body must exist before we can do this + jQuery(function() { + var div = document.createElement("div"); + div.style.width = div.style.paddingLeft = "1px"; + + document.body.appendChild( div ); + jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; + document.body.removeChild( div ).style.display = 'none'; + div = null; + }); + + // Technique from Juriy Zaytsev + // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ + var eventSupported = function( eventName ) { + var el = document.createElement("div"); + eventName = "on" + eventName; + + var isSupported = (eventName in el); + if ( !isSupported ) { + el.setAttribute(eventName, "return;"); + isSupported = typeof el[eventName] === "function"; + } + el = null; + + return isSupported; + }; + + jQuery.support.submitBubbles = eventSupported("submit"); + jQuery.support.changeBubbles = eventSupported("change"); + + // release memory in IE + root = script = div = all = a = null; +})(); + +jQuery.props = { + "for": "htmlFor", + "class": "className", + readonly: "readOnly", + maxlength: "maxLength", + cellspacing: "cellSpacing", + rowspan: "rowSpan", + colspan: "colSpan", + tabindex: "tabIndex", + usemap: "useMap", + frameborder: "frameBorder" +}; +var expando = "jQuery" + now(), uuid = 0, windowData = {}; +var emptyObject = {}; + +jQuery.extend({ + cache: {}, + + expando:expando, + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + "object": true, + "applet": true + }, + + data: function( elem, name, data ) { + if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { + return; + } + + elem = elem == window ? + windowData : + elem; + + var id = elem[ expando ], cache = jQuery.cache, thisCache; + + // Handle the case where there's no name immediately + if ( !name && !id ) { + return null; + } + + // Compute a unique ID for the element + if ( !id ) { + id = ++uuid; + } + + // Avoid generating a new cache unless none exists and we + // want to manipulate it. + if ( typeof name === "object" ) { + elem[ expando ] = id; + thisCache = cache[ id ] = jQuery.extend(true, {}, name); + } else if ( cache[ id ] ) { + thisCache = cache[ id ]; + } else if ( typeof data === "undefined" ) { + thisCache = emptyObject; + } else { + thisCache = cache[ id ] = {}; + } + + // Prevent overriding the named cache with undefined values + if ( data !== undefined ) { + elem[ expando ] = id; + thisCache[ name ] = data; + } + + return typeof name === "string" ? thisCache[ name ] : thisCache; + }, + + removeData: function( elem, name ) { + if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { + return; + } + + elem = elem == window ? + windowData : + elem; + + var id = elem[ expando ], cache = jQuery.cache, thisCache = cache[ id ]; + + // If we want to remove a specific section of the element's data + if ( name ) { + if ( thisCache ) { + // Remove the section of cache data + delete thisCache[ name ]; + + // If we've removed all the data, remove the element's cache + if ( jQuery.isEmptyObject(thisCache) ) { + jQuery.removeData( elem ); + } + } + + // Otherwise, we want to remove all of the element's data + } else { + // Clean up the element expando + try { + delete elem[ expando ]; + } catch( e ) { + // IE has trouble directly removing the expando + // but it's ok with using removeAttribute + if ( elem.removeAttribute ) { + elem.removeAttribute( expando ); + } + } + + // Completely remove the data cache + delete cache[ id ]; + } + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + if ( typeof key === "undefined" && this.length ) { + return jQuery.data( this[0] ); + + } else if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + var parts = key.split("."); + parts[1] = parts[1] ? "." + parts[1] : ""; + + if ( value === undefined ) { + var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); + + if ( data === undefined && this.length ) { + data = jQuery.data( this[0], key ); + } + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + } else { + return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function() { + jQuery.data( this, key, value ); + }); + } + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); +jQuery.extend({ + queue: function( elem, type, data ) { + if ( !elem ) { + return; + } + + type = (type || "fx") + "queue"; + var q = jQuery.data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( !data ) { + return q || []; + } + + if ( !q || jQuery.isArray(data) ) { + q = jQuery.data( elem, type, jQuery.makeArray(data) ); + + } else { + q.push( data ); + } + + return q; + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), fn = queue.shift(); + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + } + + if ( fn ) { + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift("inprogress"); + } + + fn.call(elem, function() { + jQuery.dequeue(elem, type); + }); + } + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + } + + if ( data === undefined ) { + return jQuery.queue( this[0], type ); + } + return this.each(function( i, elem ) { + var queue = jQuery.queue( this, type, data ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; + type = type || "fx"; + + return this.queue( type, function() { + var elem = this; + setTimeout(function() { + jQuery.dequeue( elem, type ); + }, time ); + }); + }, + + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + } +}); +var rclass = /[\n\t]/g, + rspace = /\s+/, + rreturn = /\r/g, + rspecialurl = /href|src|style/, + rtype = /(button|input)/i, + rfocusable = /(button|input|object|select|textarea)/i, + rclickable = /^(a|area)$/i, + rradiocheck = /radio|checkbox/; + +jQuery.fn.extend({ + attr: function( name, value ) { + return access( this, name, value, true, jQuery.attr ); + }, + + removeAttr: function( name, fn ) { + return this.each(function(){ + jQuery.attr( this, name, "" ); + if ( this.nodeType === 1 ) { + this.removeAttribute( name ); + } + }); + }, + + addClass: function( value ) { + if ( jQuery.isFunction(value) ) { + return this.each(function(i) { + var self = jQuery(this); + self.addClass( value.call(this, i, self.attr("class")) ); + }); + } + + if ( value && typeof value === "string" ) { + var classNames = (value || "").split( rspace ); + + for ( var i = 0, l = this.length; i < l; i++ ) { + var elem = this[i]; + + if ( elem.nodeType === 1 ) { + if ( !elem.className ) { + elem.className = value; + + } else { + var className = " " + elem.className + " "; + for ( var c = 0, cl = classNames.length; c < cl; c++ ) { + if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { + elem.className += " " + classNames[c]; + } + } + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + if ( jQuery.isFunction(value) ) { + return this.each(function(i) { + var self = jQuery(this); + self.removeClass( value.call(this, i, self.attr("class")) ); + }); + } + + if ( (value && typeof value === "string") || value === undefined ) { + var classNames = (value || "").split(rspace); + + for ( var i = 0, l = this.length; i < l; i++ ) { + var elem = this[i]; + + if ( elem.nodeType === 1 && elem.className ) { + if ( value ) { + var className = (" " + elem.className + " ").replace(rclass, " "); + for ( var c = 0, cl = classNames.length; c < cl; c++ ) { + className = className.replace(" " + classNames[c] + " ", " "); + } + elem.className = className.substring(1, className.length - 1); + + } else { + elem.className = ""; + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each(function(i) { + var self = jQuery(this); + self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, i = 0, self = jQuery(this), + state = stateVal, + classNames = value.split( rspace ); + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space seperated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery.data( this, "__className__", this.className ); + } + + // toggle whole className + this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " "; + for ( var i = 0, l = this.length; i < l; i++ ) { + if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + if ( value === undefined ) { + var elem = this[0]; + + if ( elem ) { + if ( jQuery.nodeName( elem, "option" ) ) { + return (elem.attributes.value || {}).specified ? elem.value : elem.text; + } + + // We need to handle select boxes special + if ( jQuery.nodeName( elem, "select" ) ) { + var index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type === "select-one"; + + // Nothing was selected + if ( index < 0 ) { + return null; + } + + // Loop through all the selected options + for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { + var option = options[ i ]; + + if ( option.selected ) { + // Get the specifc value for the option + value = jQuery(option).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + } + + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { + return elem.getAttribute("value") === null ? "on" : elem.value; + } + + + // Everything else, we just grab the value + return (elem.value || "").replace(rreturn, ""); + + } + + return undefined; + } + + var isFunction = jQuery.isFunction(value); + + return this.each(function(i) { + var self = jQuery(this), val = value; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call(this, i, self.val()); + } + + // Typecast each time if the value is a Function and the appended + // value is therefore different each time. + if ( typeof val === "number" ) { + val += ""; + } + + if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { + this.checked = jQuery.inArray( self.val(), val ) >= 0; + + } else if ( jQuery.nodeName( this, "select" ) ) { + var values = jQuery.makeArray(val); + + jQuery( "option", this ).each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + this.selectedIndex = -1; + } + + } else { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + attrFn: { + val: true, + css: true, + html: true, + text: true, + data: true, + width: true, + height: true, + offset: true + }, + + attr: function( elem, name, value, pass ) { + // don't set attributes on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { + return undefined; + } + + if ( pass && name in jQuery.attrFn ) { + return jQuery(elem)[name](value); + } + + var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), + // Whether we are setting (or getting) + set = value !== undefined; + + // Try to normalize/fix the name + name = notxml && jQuery.props[ name ] || name; + + // Only do all the following if this is a node (faster for style) + if ( elem.nodeType === 1 ) { + // These attributes require special treatment + var special = rspecialurl.test( name ); + + // Safari mis-reports the default selected property of an option + // Accessing the parent's selectedIndex property fixes it + if ( name === "selected" && !jQuery.support.optSelected ) { + var parent = elem.parentNode; + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + } + + // If applicable, access the attribute via the DOM 0 way + if ( name in elem && notxml && !special ) { + if ( set ) { + // We can't allow the type property to be changed (since it causes problems in IE) + if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { + jQuery.error( "type property can't be changed" ); + } + + elem[ name ] = value; + } + + // browsers index elements by id/name on forms, give priority to attributes. + if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { + return elem.getAttributeNode( name ).nodeValue; + } + + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + if ( name === "tabIndex" ) { + var attributeNode = elem.getAttributeNode( "tabIndex" ); + + return attributeNode && attributeNode.specified ? + attributeNode.value : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + + return elem[ name ]; + } + + if ( !jQuery.support.style && notxml && name === "style" ) { + if ( set ) { + elem.style.cssText = "" + value; + } + + return elem.style.cssText; + } + + if ( set ) { + // convert the value to a string (all browsers do this but IE) see #1070 + elem.setAttribute( name, "" + value ); + } + + var attr = !jQuery.support.hrefNormalized && notxml && special ? + // Some attributes require a special call on IE + elem.getAttribute( name, 2 ) : + elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return attr === null ? undefined : attr; + } + + // elem is actually elem.style ... set the style + // Using attr for specific style information is now deprecated. Use style insead. + return jQuery.style( elem, name, value ); + } +}); +var fcleanup = function( nm ) { + return nm.replace(/[^\w\s\.\|`]/g, function( ch ) { + return "\\" + ch; + }); +}; + +/* + * A number of helper functions used for managing events. + * Many of the ideas behind this code originated from + * Dean Edwards' addEvent library. + */ +jQuery.event = { + + // Bind an event to an element + // Original by Dean Edwards + add: function( elem, types, handler, data ) { + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // For whatever reason, IE has trouble passing the window object + // around, causing it to be cloned in the process + if ( elem.setInterval && ( elem !== window && !elem.frameElement ) ) { + elem = window; + } + + // Make sure that the function being executed has a unique ID + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // if data is passed, bind to handler + if ( data !== undefined ) { + // Create temporary function pointer to original handler + var fn = handler; + + // Create unique handler function, wrapped around original handler + handler = jQuery.proxy( fn ); + + // Store data in unique handler + handler.data = data; + } + + // Init the element's event structure + var events = jQuery.data( elem, "events" ) || jQuery.data( elem, "events", {} ), + handle = jQuery.data( elem, "handle" ), eventHandle; + + if ( !handle ) { + eventHandle = function() { + // Handle the second event of a trigger and when + // an event is called after a page has unloaded + return typeof jQuery !== "undefined" && !jQuery.event.triggered ? + jQuery.event.handle.apply( eventHandle.elem, arguments ) : + undefined; + }; + + handle = jQuery.data( elem, "handle", eventHandle ); + } + + // If no handle is found then we must be trying to bind to one of the + // banned noData elements + if ( !handle ) { + return; + } + + // Add elem as a property of the handle function + // This is to prevent a memory leak with non-native + // event in IE. + handle.elem = elem; + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = types.split( /\s+/ ); + + var type, i = 0; + + while ( (type = types[ i++ ]) ) { + // Namespaced event handlers + var namespaces = type.split("."); + type = namespaces.shift(); + + if ( i > 1 ) { + handler = jQuery.proxy( handler ); + + if ( data !== undefined ) { + handler.data = data; + } + } + + handler.type = namespaces.slice(0).sort().join("."); + + // Get the current list of functions bound to this event + var handlers = events[ type ], + special = this.special[ type ] || {}; + + // Init the event handler queue + if ( !handlers ) { + handlers = events[ type ] = {}; + + // Check for a special event handler + // Only use addEventListener/attachEvent if the special + // events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, handler) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, handle, false ); + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, handle ); + } + } + } + + if ( special.add ) { + var modifiedHandler = special.add.call( elem, handler, data, namespaces, handlers ); + if ( modifiedHandler && jQuery.isFunction( modifiedHandler ) ) { + modifiedHandler.guid = modifiedHandler.guid || handler.guid; + modifiedHandler.data = modifiedHandler.data || handler.data; + modifiedHandler.type = modifiedHandler.type || handler.type; + handler = modifiedHandler; + } + } + + // Add the function to the element's handler list + handlers[ handler.guid ] = handler; + + // Keep track of which events have been used, for global triggering + this.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + global: {}, + + // Detach an event or set of events from an element + remove: function( elem, types, handler ) { + // don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + var events = jQuery.data( elem, "events" ), ret, type, fn; + + if ( events ) { + // Unbind all events for the element + if ( types === undefined || (typeof types === "string" && types.charAt(0) === ".") ) { + for ( type in events ) { + this.remove( elem, type + (types || "") ); + } + } else { + // types is actually an event object here + if ( types.type ) { + handler = types.handler; + types = types.type; + } + + // Handle multiple events separated by a space + // jQuery(...).unbind("mouseover mouseout", fn); + types = types.split(/\s+/); + var i = 0; + while ( (type = types[ i++ ]) ) { + // Namespaced event handlers + var namespaces = type.split("."); + type = namespaces.shift(); + var all = !namespaces.length, + cleaned = jQuery.map( namespaces.slice(0).sort(), fcleanup ), + namespace = new RegExp("(^|\\.)" + cleaned.join("\\.(?:.*\\.)?") + "(\\.|$)"), + special = this.special[ type ] || {}; + + if ( events[ type ] ) { + // remove the given handler for the given type + if ( handler ) { + fn = events[ type ][ handler.guid ]; + delete events[ type ][ handler.guid ]; + + // remove all handlers for the given type + } else { + for ( var handle in events[ type ] ) { + // Handle the removal of namespaced events + if ( all || namespace.test( events[ type ][ handle ].type ) ) { + delete events[ type ][ handle ]; + } + } + } + + if ( special.remove ) { + special.remove.call( elem, namespaces, fn); + } + + // remove generic event handler if no more handlers exist + for ( ret in events[ type ] ) { + break; + } + if ( !ret ) { + if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, jQuery.data( elem, "handle" ), false ); + } else if ( elem.detachEvent ) { + elem.detachEvent( "on" + type, jQuery.data( elem, "handle" ) ); + } + } + ret = null; + delete events[ type ]; + } + } + } + } + + // Remove the expando if it's no longer used + for ( ret in events ) { + break; + } + if ( !ret ) { + var handle = jQuery.data( elem, "handle" ); + if ( handle ) { + handle.elem = null; + } + jQuery.removeData( elem, "events" ); + jQuery.removeData( elem, "handle" ); + } + } + }, + + // bubbling is internal + trigger: function( event, data, elem /*, bubbling */ ) { + // Event object or event type + var type = event.type || event, + bubbling = arguments[3]; + + if ( !bubbling ) { + event = typeof event === "object" ? + // jQuery.Event object + event[expando] ? event : + // Object literal + jQuery.extend( jQuery.Event(type), event ) : + // Just the event type (string) + jQuery.Event(type); + + if ( type.indexOf("!") >= 0 ) { + event.type = type = type.slice(0, -1); + event.exclusive = true; + } + + // Handle a global trigger + if ( !elem ) { + // Don't bubble custom events when global (to avoid too much overhead) + event.stopPropagation(); + + // Only trigger if we've ever bound an event for it + if ( this.global[ type ] ) { + jQuery.each( jQuery.cache, function() { + if ( this.events && this.events[type] ) { + jQuery.event.trigger( event, data, this.handle.elem ); + } + }); + } + } + + // Handle triggering a single element + + // don't do events on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { + return undefined; + } + + // Clean up in case it is reused + event.result = undefined; + event.target = elem; + + // Clone the incoming data, if any + data = jQuery.makeArray( data ); + data.unshift( event ); + } + + event.currentTarget = elem; + + // Trigger the event, it is assumed that "handle" is a function + var handle = jQuery.data( elem, "handle" ); + if ( handle ) { + handle.apply( elem, data ); + } + + var parent = elem.parentNode || elem.ownerDocument; + + // Trigger an inline bound script + try { + if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { + if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { + event.result = false; + } + } + + // prevent IE from throwing an error for some elements with some event types, see #3533 + } catch (e) {} + + if ( !event.isPropagationStopped() && parent ) { + jQuery.event.trigger( event, data, parent, true ); + + } else if ( !event.isDefaultPrevented() ) { + var target = event.target, old, + isClick = jQuery.nodeName(target, "a") && type === "click"; + + if ( !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { + try { + if ( target[ type ] ) { + // Make sure that we don't accidentally re-trigger the onFOO events + old = target[ "on" + type ]; + + if ( old ) { + target[ "on" + type ] = null; + } + + this.triggered = true; + target[ type ](); + } + + // prevent IE from throwing an error for some elements with some event types, see #3533 + } catch (e) {} + + if ( old ) { + target[ "on" + type ] = old; + } + + this.triggered = false; + } + } + }, + + handle: function( event ) { + // returned undefined or false + var all, handlers; + + event = arguments[0] = jQuery.event.fix( event || window.event ); + event.currentTarget = this; + + // Namespaced event handlers + var namespaces = event.type.split("."); + event.type = namespaces.shift(); + + // Cache this now, all = true means, any handler + all = !namespaces.length && !event.exclusive; + + var namespace = new RegExp("(^|\\.)" + namespaces.slice(0).sort().join("\\.(?:.*\\.)?") + "(\\.|$)"); + + handlers = ( jQuery.data(this, "events") || {} )[ event.type ]; + + for ( var j in handlers ) { + var handler = handlers[ j ]; + + // Filter the functions by class + if ( all || namespace.test(handler.type) ) { + // Pass in a reference to the handler function itself + // So that we can later remove it + event.handler = handler; + event.data = handler.data; + + var ret = handler.apply( this, arguments ); + + if ( ret !== undefined ) { + event.result = ret; + if ( ret === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + + if ( event.isImmediatePropagationStopped() ) { + break; + } + + } + } + + return event.result; + }, + + props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), + + fix: function( event ) { + if ( event[ expando ] ) { + return event; + } + + // store a copy of the original event object + // and "clone" to set read-only properties + var originalEvent = event; + event = jQuery.Event( originalEvent ); + + for ( var i = this.props.length, prop; i; ) { + prop = this.props[ --i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Fix target property, if necessary + if ( !event.target ) { + event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either + } + + // check if target is a textnode (safari) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && event.fromElement ) { + event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; + } + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && event.clientX != null ) { + var doc = document.documentElement, body = document.body; + event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); + event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); + } + + // Add which for key events + if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) { + event.which = event.charCode || event.keyCode; + } + + // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) + if ( !event.metaKey && event.ctrlKey ) { + event.metaKey = event.ctrlKey; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && event.button !== undefined ) { + event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); + } + + return event; + }, + + // Deprecated, use jQuery.guid instead + guid: 1E8, + + // Deprecated, use jQuery.proxy instead + proxy: jQuery.proxy, + + special: { + ready: { + // Make sure the ready event is setup + setup: jQuery.bindReady, + teardown: jQuery.noop + }, + + live: { + add: function( proxy, data, namespaces, live ) { + jQuery.extend( proxy, data || {} ); + + proxy.guid += data.selector + data.live; + data.liveProxy = proxy; + + jQuery.event.add( this, data.live, liveHandler, data ); + + }, + + remove: function( namespaces ) { + if ( namespaces.length ) { + var remove = 0, name = new RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)"); + + jQuery.each( (jQuery.data(this, "events").live || {}), function() { + if ( name.test(this.type) ) { + remove++; + } + }); + + if ( remove < 1 ) { + jQuery.event.remove( this, namespaces[0], liveHandler ); + } + } + }, + special: {} + }, + beforeunload: { + setup: function( data, namespaces, fn ) { + // We only want to do this special case on windows + if ( this.setInterval ) { + this.onbeforeunload = fn; + } + + return false; + }, + teardown: function( namespaces, fn ) { + if ( this.onbeforeunload === fn ) { + this.onbeforeunload = null; + } + } + } + } +}; + +jQuery.Event = function( src ) { + // Allow instantiation without the 'new' keyword + if ( !this.preventDefault ) { + return new jQuery.Event( src ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + // Event type + } else { + this.type = src; + } + + // timeStamp is buggy for some events on Firefox(#3843) + // So we won't rely on the native value + this.timeStamp = now(); + + // Mark it as fixed + this[ expando ] = true; +}; + +function returnFalse() { + return false; +} +function returnTrue() { + return true; +} + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + preventDefault: function() { + this.isDefaultPrevented = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + + // if preventDefault exists run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + } + // otherwise set the returnValue property of the original event to false (IE) + e.returnValue = false; + }, + stopPropagation: function() { + this.isPropagationStopped = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + // if stopPropagation exists run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + // otherwise set the cancelBubble property of the original event to true (IE) + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + }, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse +}; + +// Checks if an event happened on an element within another element +// Used in jQuery.event.special.mouseenter and mouseleave handlers +var withinElement = function( event ) { + // Check if mouse(over|out) are still within the same parent element + var parent = event.relatedTarget; + + // Traverse up the tree + while ( parent && parent !== this ) { + // Firefox sometimes assigns relatedTarget a XUL element + // which we cannot access the parentNode property of + try { + parent = parent.parentNode; + + // assuming we've left the element since we most likely mousedover a xul element + } catch(e) { + break; + } + } + + if ( parent !== this ) { + // set the correct event type + event.type = event.data; + + // handle event if we actually just moused on to a non sub-element + jQuery.event.handle.apply( this, arguments ); + } + +}, + +// In case of event delegation, we only need to rename the event.type, +// liveHandler will take care of the rest. +delegate = function( event ) { + event.type = event.data; + jQuery.event.handle.apply( this, arguments ); +}; + +// Create mouseenter and mouseleave events +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + setup: function( data ) { + jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); + }, + teardown: function( data ) { + jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); + } + }; +}); + +// submit delegation +if ( !jQuery.support.submitBubbles ) { + +jQuery.event.special.submit = { + setup: function( data, namespaces, fn ) { + if ( this.nodeName.toLowerCase() !== "form" ) { + jQuery.event.add(this, "click.specialSubmit." + fn.guid, function( e ) { + var elem = e.target, type = elem.type; + + if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { + return trigger( "submit", this, arguments ); + } + }); + + jQuery.event.add(this, "keypress.specialSubmit." + fn.guid, function( e ) { + var elem = e.target, type = elem.type; + + if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { + return trigger( "submit", this, arguments ); + } + }); + + } else { + return false; + } + }, + + remove: function( namespaces, fn ) { + jQuery.event.remove( this, "click.specialSubmit" + (fn ? "."+fn.guid : "") ); + jQuery.event.remove( this, "keypress.specialSubmit" + (fn ? "."+fn.guid : "") ); + } +}; + +} + +// change delegation, happens here so we have bind. +if ( !jQuery.support.changeBubbles ) { + +var formElems = /textarea|input|select/i; + +function getVal( elem ) { + var type = elem.type, val = elem.value; + + if ( type === "radio" || type === "checkbox" ) { + val = elem.checked; + + } else if ( type === "select-multiple" ) { + val = elem.selectedIndex > -1 ? + jQuery.map( elem.options, function( elem ) { + return elem.selected; + }).join("-") : + ""; + + } else if ( elem.nodeName.toLowerCase() === "select" ) { + val = elem.selectedIndex; + } + + return val; +} + +function testChange( e ) { + var elem = e.target, data, val; + + if ( !formElems.test( elem.nodeName ) || elem.readOnly ) { + return; + } + + data = jQuery.data( elem, "_change_data" ); + val = getVal(elem); + + // the current data will be also retrieved by beforeactivate + if ( e.type !== "focusout" || elem.type !== "radio" ) { + jQuery.data( elem, "_change_data", val ); + } + + if ( data === undefined || val === data ) { + return; + } + + if ( data != null || val ) { + e.type = "change"; + return jQuery.event.trigger( e, arguments[1], elem ); + } +} + +jQuery.event.special.change = { + filters: { + focusout: testChange, + + click: function( e ) { + var elem = e.target, type = elem.type; + + if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { + return testChange.call( this, e ); + } + }, + + // Change has to be called before submit + // Keydown will be called before keypress, which is used in submit-event delegation + keydown: function( e ) { + var elem = e.target, type = elem.type; + + if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || + (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || + type === "select-multiple" ) { + return testChange.call( this, e ); + } + }, + + // Beforeactivate happens also before the previous element is blurred + // with this event you can't trigger a change event, but you can store + // information/focus[in] is not needed anymore + beforeactivate: function( e ) { + var elem = e.target; + + if ( elem.nodeName.toLowerCase() === "input" && elem.type === "radio" ) { + jQuery.data( elem, "_change_data", getVal(elem) ); + } + } + }, + setup: function( data, namespaces, fn ) { + for ( var type in changeFilters ) { + jQuery.event.add( this, type + ".specialChange." + fn.guid, changeFilters[type] ); + } + + return formElems.test( this.nodeName ); + }, + remove: function( namespaces, fn ) { + for ( var type in changeFilters ) { + jQuery.event.remove( this, type + ".specialChange" + (fn ? "."+fn.guid : ""), changeFilters[type] ); + } + + return formElems.test( this.nodeName ); + } +}; + +var changeFilters = jQuery.event.special.change.filters; + +} + +function trigger( type, elem, args ) { + args[0].type = type; + return jQuery.event.handle.apply( elem, args ); +} + +// Create "bubbling" focus and blur events +if ( document.addEventListener ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + jQuery.event.special[ fix ] = { + setup: function() { + this.addEventListener( orig, handler, true ); + }, + teardown: function() { + this.removeEventListener( orig, handler, true ); + } + }; + + function handler( e ) { + e = jQuery.event.fix( e ); + e.type = fix; + return jQuery.event.handle.call( this, e ); + } + }); +} + +jQuery.each(["bind", "one"], function( i, name ) { + jQuery.fn[ name ] = function( type, data, fn ) { + // Handle object literals + if ( typeof type === "object" ) { + for ( var key in type ) { + this[ name ](key, data, type[key], fn); + } + return this; + } + + if ( jQuery.isFunction( data ) ) { + fn = data; + data = undefined; + } + + var handler = name === "one" ? jQuery.proxy( fn, function( event ) { + jQuery( this ).unbind( event, handler ); + return fn.apply( this, arguments ); + }) : fn; + + return type === "unload" && name !== "one" ? + this.one( type, data, fn ) : + this.each(function() { + jQuery.event.add( this, type, handler, data ); + }); + }; +}); + +jQuery.fn.extend({ + unbind: function( type, fn ) { + // Handle object literals + if ( typeof type === "object" && !type.preventDefault ) { + for ( var key in type ) { + this.unbind(key, type[key]); + } + return this; + } + + return this.each(function() { + jQuery.event.remove( this, type, fn ); + }); + }, + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + + triggerHandler: function( type, data ) { + if ( this[0] ) { + var event = jQuery.Event( type ); + event.preventDefault(); + event.stopPropagation(); + jQuery.event.trigger( event, data, this[0] ); + return event.result; + } + }, + + toggle: function( fn ) { + // Save reference to arguments for access in closure + var args = arguments, i = 1; + + // link all the functions, so any of them can unbind this click handler + while ( i < args.length ) { + jQuery.proxy( fn, args[ i++ ] ); + } + + return this.click( jQuery.proxy( fn, function( event ) { + // Figure out which function to execute + var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; + jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); + + // Make sure that clicks stop + event.preventDefault(); + + // and execute the function + return args[ lastToggle ].apply( this, arguments ) || false; + })); + }, + + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +}); + +jQuery.each(["live", "die"], function( i, name ) { + jQuery.fn[ name ] = function( types, data, fn ) { + var type, i = 0; + + if ( jQuery.isFunction( data ) ) { + fn = data; + data = undefined; + } + + types = (types || "").split( /\s+/ ); + + while ( (type = types[ i++ ]) != null ) { + type = type === "focus" ? "focusin" : // focus --> focusin + type === "blur" ? "focusout" : // blur --> focusout + type === "hover" ? types.push("mouseleave") && "mouseenter" : // hover support + type; + + if ( name === "live" ) { + // bind live handler + jQuery( this.context ).bind( liveConvert( type, this.selector ), { + data: data, selector: this.selector, live: type + }, fn ); + + } else { + // unbind live handler + jQuery( this.context ).unbind( liveConvert( type, this.selector ), fn ? { guid: fn.guid + this.selector + type } : null ); + } + } + + return this; + } +}); + +function liveHandler( event ) { + var stop, elems = [], selectors = [], args = arguments, + related, match, fn, elem, j, i, l, data, + live = jQuery.extend({}, jQuery.data( this, "events" ).live); + + // Make sure we avoid non-left-click bubbling in Firefox (#3861) + if ( event.button && event.type === "click" ) { + return; + } + + for ( j in live ) { + fn = live[j]; + if ( fn.live === event.type || + fn.altLive && jQuery.inArray(event.type, fn.altLive) > -1 ) { + + data = fn.data; + if ( !(data.beforeFilter && data.beforeFilter[event.type] && + !data.beforeFilter[event.type](event)) ) { + selectors.push( fn.selector ); + } + } else { + delete live[j]; + } + } + + match = jQuery( event.target ).closest( selectors, event.currentTarget ); + + for ( i = 0, l = match.length; i < l; i++ ) { + for ( j in live ) { + fn = live[j]; + elem = match[i].elem; + related = null; + + if ( match[i].selector === fn.selector ) { + // Those two events require additional checking + if ( fn.live === "mouseenter" || fn.live === "mouseleave" ) { + related = jQuery( event.relatedTarget ).closest( fn.selector )[0]; + } + + if ( !related || related !== elem ) { + elems.push({ elem: elem, fn: fn }); + } + } + } + } + + for ( i = 0, l = elems.length; i < l; i++ ) { + match = elems[i]; + event.currentTarget = match.elem; + event.data = match.fn.data; + if ( match.fn.apply( match.elem, args ) === false ) { + stop = false; + break; + } + } + + return stop; +} + +function liveConvert( type, selector ) { + return "live." + (type ? type + "." : "") + selector.replace(/\./g, "`").replace(/ /g, "&"); +} + +jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup error").split(" "), function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( fn ) { + return fn ? this.bind( name, fn ) : this.trigger( name ); + }; + + if ( jQuery.attrFn ) { + jQuery.attrFn[ name ] = true; + } +}); + +// Prevent memory leaks in IE +// Window isn't included so as not to unbind existing unload events +// More info: +// - http://isaacschlueter.com/2006/10/msie-memory-leaks/ +if ( window.attachEvent && !window.addEventListener ) { + window.attachEvent("onunload", function() { + for ( var id in jQuery.cache ) { + if ( jQuery.cache[ id ].handle ) { + // Try/Catch is to handle iframes being unloaded, see #4280 + try { + jQuery.event.remove( jQuery.cache[ id ].handle.elem ); + } catch(e) {} + } + } + }); +} +/*! + * Sizzle CSS Selector Engine - v1.0 + * Copyright 2009, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){ + +var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + done = 0, + toString = Object.prototype.toString, + hasDuplicate = false, + baseHasDuplicate = true; + +// Here we check if the JavaScript engine is using some sort of +// optimization where it does not always call our comparision +// function. If that is the case, discard the hasDuplicate value. +// Thus far that includes Google Chrome. +[0, 0].sort(function(){ + baseHasDuplicate = false; + return 0; +}); + +var Sizzle = function(selector, context, results, seed) { + results = results || []; + var origContext = context = context || document; + + if ( context.nodeType !== 1 && context.nodeType !== 9 ) { + return []; + } + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + var parts = [], m, set, checkSet, extra, prune = true, contextXML = isXML(context), + soFar = selector; + + // Reset the position of the chunker regexp (start from head) + while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) { + soFar = m[3]; + + parts.push( m[1] ); + + if ( m[2] ) { + extra = m[3]; + break; + } + } + + if ( parts.length > 1 && origPOS.exec( selector ) ) { + if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { + set = posProcess( parts[0] + parts[1], context ); + } else { + set = Expr.relative[ parts[0] ] ? + [ context ] : + Sizzle( parts.shift(), context ); + + while ( parts.length ) { + selector = parts.shift(); + + if ( Expr.relative[ selector ] ) { + selector += parts.shift(); + } + + set = posProcess( selector, set ); + } + } + } else { + // Take a shortcut and set the context if the root selector is an ID + // (but not if it'll be faster if the inner selector is an ID) + if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && + Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { + var ret = Sizzle.find( parts.shift(), context, contextXML ); + context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; + } + + if ( context ) { + var ret = seed ? + { expr: parts.pop(), set: makeArray(seed) } : + Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); + set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; + + if ( parts.length > 0 ) { + checkSet = makeArray(set); + } else { + prune = false; + } + + while ( parts.length ) { + var cur = parts.pop(), pop = cur; + + if ( !Expr.relative[ cur ] ) { + cur = ""; + } else { + pop = parts.pop(); + } + + if ( pop == null ) { + pop = context; + } + + Expr.relative[ cur ]( checkSet, pop, contextXML ); + } + } else { + checkSet = parts = []; + } + } + + if ( !checkSet ) { + checkSet = set; + } + + if ( !checkSet ) { + Sizzle.error( cur || selector ); + } + + if ( toString.call(checkSet) === "[object Array]" ) { + if ( !prune ) { + results.push.apply( results, checkSet ); + } else if ( context && context.nodeType === 1 ) { + for ( var i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) { + results.push( set[i] ); + } + } + } else { + for ( var i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && checkSet[i].nodeType === 1 ) { + results.push( set[i] ); + } + } + } + } else { + makeArray( checkSet, results ); + } + + if ( extra ) { + Sizzle( extra, origContext, results, seed ); + Sizzle.uniqueSort( results ); + } + + return results; +}; + +Sizzle.uniqueSort = function(results){ + if ( sortOrder ) { + hasDuplicate = baseHasDuplicate; + results.sort(sortOrder); + + if ( hasDuplicate ) { + for ( var i = 1; i < results.length; i++ ) { + if ( results[i] === results[i-1] ) { + results.splice(i--, 1); + } + } + } + } + + return results; +}; + +Sizzle.matches = function(expr, set){ + return Sizzle(expr, null, null, set); +}; + +Sizzle.find = function(expr, context, isXML){ + var set, match; + + if ( !expr ) { + return []; + } + + for ( var i = 0, l = Expr.order.length; i < l; i++ ) { + var type = Expr.order[i], match; + + if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { + var left = match[1]; + match.splice(1,1); + + if ( left.substr( left.length - 1 ) !== "\\" ) { + match[1] = (match[1] || "").replace(/\\/g, ""); + set = Expr.find[ type ]( match, context, isXML ); + if ( set != null ) { + expr = expr.replace( Expr.match[ type ], "" ); + break; + } + } + } + } + + if ( !set ) { + set = context.getElementsByTagName("*"); + } + + return {set: set, expr: expr}; +}; + +Sizzle.filter = function(expr, set, inplace, not){ + var old = expr, result = [], curLoop = set, match, anyFound, + isXMLFilter = set && set[0] && isXML(set[0]); + + while ( expr && set.length ) { + for ( var type in Expr.filter ) { + if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { + var filter = Expr.filter[ type ], found, item, left = match[1]; + anyFound = false; + + match.splice(1,1); + + if ( left.substr( left.length - 1 ) === "\\" ) { + continue; + } + + if ( curLoop === result ) { + result = []; + } + + if ( Expr.preFilter[ type ] ) { + match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); + + if ( !match ) { + anyFound = found = true; + } else if ( match === true ) { + continue; + } + } + + if ( match ) { + for ( var i = 0; (item = curLoop[i]) != null; i++ ) { + if ( item ) { + found = filter( item, match, i, curLoop ); + var pass = not ^ !!found; + + if ( inplace && found != null ) { + if ( pass ) { + anyFound = true; + } else { + curLoop[i] = false; + } + } else if ( pass ) { + result.push( item ); + anyFound = true; + } + } + } + } + + if ( found !== undefined ) { + if ( !inplace ) { + curLoop = result; + } + + expr = expr.replace( Expr.match[ type ], "" ); + + if ( !anyFound ) { + return []; + } + + break; + } + } + } + + // Improper expression + if ( expr === old ) { + if ( anyFound == null ) { + Sizzle.error( expr ); + } else { + break; + } + } + + old = expr; + } + + return curLoop; +}; + +Sizzle.error = function( msg ) { + throw "Syntax error, unrecognized expression: " + msg; +}; + +var Expr = Sizzle.selectors = { + order: [ "ID", "NAME", "TAG" ], + match: { + ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, + CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/, + NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/, + ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, + TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/, + CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, + POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, + PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ + }, + leftMatch: {}, + attrMap: { + "class": "className", + "for": "htmlFor" + }, + attrHandle: { + href: function(elem){ + return elem.getAttribute("href"); + } + }, + relative: { + "+": function(checkSet, part){ + var isPartStr = typeof part === "string", + isTag = isPartStr && !/\W/.test(part), + isPartStrNotTag = isPartStr && !isTag; + + if ( isTag ) { + part = part.toLowerCase(); + } + + for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { + if ( (elem = checkSet[i]) ) { + while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} + + checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? + elem || false : + elem === part; + } + } + + if ( isPartStrNotTag ) { + Sizzle.filter( part, checkSet, true ); + } + }, + ">": function(checkSet, part){ + var isPartStr = typeof part === "string"; + + if ( isPartStr && !/\W/.test(part) ) { + part = part.toLowerCase(); + + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + if ( elem ) { + var parent = elem.parentNode; + checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; + } + } + } else { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + if ( elem ) { + checkSet[i] = isPartStr ? + elem.parentNode : + elem.parentNode === part; + } + } + + if ( isPartStr ) { + Sizzle.filter( part, checkSet, true ); + } + } + }, + "": function(checkSet, part, isXML){ + var doneName = done++, checkFn = dirCheck; + + if ( typeof part === "string" && !/\W/.test(part) ) { + var nodeCheck = part = part.toLowerCase(); + checkFn = dirNodeCheck; + } + + checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); + }, + "~": function(checkSet, part, isXML){ + var doneName = done++, checkFn = dirCheck; + + if ( typeof part === "string" && !/\W/.test(part) ) { + var nodeCheck = part = part.toLowerCase(); + checkFn = dirNodeCheck; + } + + checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); + } + }, + find: { + ID: function(match, context, isXML){ + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + return m ? [m] : []; + } + }, + NAME: function(match, context){ + if ( typeof context.getElementsByName !== "undefined" ) { + var ret = [], results = context.getElementsByName(match[1]); + + for ( var i = 0, l = results.length; i < l; i++ ) { + if ( results[i].getAttribute("name") === match[1] ) { + ret.push( results[i] ); + } + } + + return ret.length === 0 ? null : ret; + } + }, + TAG: function(match, context){ + return context.getElementsByTagName(match[1]); + } + }, + preFilter: { + CLASS: function(match, curLoop, inplace, result, not, isXML){ + match = " " + match[1].replace(/\\/g, "") + " "; + + if ( isXML ) { + return match; + } + + for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { + if ( elem ) { + if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) { + if ( !inplace ) { + result.push( elem ); + } + } else if ( inplace ) { + curLoop[i] = false; + } + } + } + + return false; + }, + ID: function(match){ + return match[1].replace(/\\/g, ""); + }, + TAG: function(match, curLoop){ + return match[1].toLowerCase(); + }, + CHILD: function(match){ + if ( match[1] === "nth" ) { + // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' + var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( + match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || + !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); + + // calculate the numbers (first)n+(last) including if they are negative + match[2] = (test[1] + (test[2] || 1)) - 0; + match[3] = test[3] - 0; + } + + // TODO: Move to normal caching system + match[0] = done++; + + return match; + }, + ATTR: function(match, curLoop, inplace, result, not, isXML){ + var name = match[1].replace(/\\/g, ""); + + if ( !isXML && Expr.attrMap[name] ) { + match[1] = Expr.attrMap[name]; + } + + if ( match[2] === "~=" ) { + match[4] = " " + match[4] + " "; + } + + return match; + }, + PSEUDO: function(match, curLoop, inplace, result, not){ + if ( match[1] === "not" ) { + // If we're dealing with a complex expression, or a simple one + if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { + match[3] = Sizzle(match[3], null, null, curLoop); + } else { + var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); + if ( !inplace ) { + result.push.apply( result, ret ); + } + return false; + } + } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { + return true; + } + + return match; + }, + POS: function(match){ + match.unshift( true ); + return match; + } + }, + filters: { + enabled: function(elem){ + return elem.disabled === false && elem.type !== "hidden"; + }, + disabled: function(elem){ + return elem.disabled === true; + }, + checked: function(elem){ + return elem.checked === true; + }, + selected: function(elem){ + // Accessing this property makes selected-by-default + // options in Safari work properly + elem.parentNode.selectedIndex; + return elem.selected === true; + }, + parent: function(elem){ + return !!elem.firstChild; + }, + empty: function(elem){ + return !elem.firstChild; + }, + has: function(elem, i, match){ + return !!Sizzle( match[3], elem ).length; + }, + header: function(elem){ + return /h\d/i.test( elem.nodeName ); + }, + text: function(elem){ + return "text" === elem.type; + }, + radio: function(elem){ + return "radio" === elem.type; + }, + checkbox: function(elem){ + return "checkbox" === elem.type; + }, + file: function(elem){ + return "file" === elem.type; + }, + password: function(elem){ + return "password" === elem.type; + }, + submit: function(elem){ + return "submit" === elem.type; + }, + image: function(elem){ + return "image" === elem.type; + }, + reset: function(elem){ + return "reset" === elem.type; + }, + button: function(elem){ + return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; + }, + input: function(elem){ + return /input|select|textarea|button/i.test(elem.nodeName); + } + }, + setFilters: { + first: function(elem, i){ + return i === 0; + }, + last: function(elem, i, match, array){ + return i === array.length - 1; + }, + even: function(elem, i){ + return i % 2 === 0; + }, + odd: function(elem, i){ + return i % 2 === 1; + }, + lt: function(elem, i, match){ + return i < match[3] - 0; + }, + gt: function(elem, i, match){ + return i > match[3] - 0; + }, + nth: function(elem, i, match){ + return match[3] - 0 === i; + }, + eq: function(elem, i, match){ + return match[3] - 0 === i; + } + }, + filter: { + PSEUDO: function(elem, match, i, array){ + var name = match[1], filter = Expr.filters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } else if ( name === "contains" ) { + return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; + } else if ( name === "not" ) { + var not = match[3]; + + for ( var i = 0, l = not.length; i < l; i++ ) { + if ( not[i] === elem ) { + return false; + } + } + + return true; + } else { + Sizzle.error( "Syntax error, unrecognized expression: " + name ); + } + }, + CHILD: function(elem, match){ + var type = match[1], node = elem; + switch (type) { + case 'only': + case 'first': + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + if ( type === "first" ) { + return true; + } + node = elem; + case 'last': + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + return true; + case 'nth': + var first = match[2], last = match[3]; + + if ( first === 1 && last === 0 ) { + return true; + } + + var doneName = match[0], + parent = elem.parentNode; + + if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { + var count = 0; + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + node.nodeIndex = ++count; + } + } + parent.sizcache = doneName; + } + + var diff = elem.nodeIndex - last; + if ( first === 0 ) { + return diff === 0; + } else { + return ( diff % first === 0 && diff / first >= 0 ); + } + } + }, + ID: function(elem, match){ + return elem.nodeType === 1 && elem.getAttribute("id") === match; + }, + TAG: function(elem, match){ + return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; + }, + CLASS: function(elem, match){ + return (" " + (elem.className || elem.getAttribute("class")) + " ") + .indexOf( match ) > -1; + }, + ATTR: function(elem, match){ + var name = match[1], + result = Expr.attrHandle[ name ] ? + Expr.attrHandle[ name ]( elem ) : + elem[ name ] != null ? + elem[ name ] : + elem.getAttribute( name ), + value = result + "", + type = match[2], + check = match[4]; + + return result == null ? + type === "!=" : + type === "=" ? + value === check : + type === "*=" ? + value.indexOf(check) >= 0 : + type === "~=" ? + (" " + value + " ").indexOf(check) >= 0 : + !check ? + value && result !== false : + type === "!=" ? + value !== check : + type === "^=" ? + value.indexOf(check) === 0 : + type === "$=" ? + value.substr(value.length - check.length) === check : + type === "|=" ? + value === check || value.substr(0, check.length + 1) === check + "-" : + false; + }, + POS: function(elem, match, i, array){ + var name = match[2], filter = Expr.setFilters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } + } + } +}; + +var origPOS = Expr.match.POS; + +for ( var type in Expr.match ) { + Expr.match[ type ] = new RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source ); + Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, function(all, num){ + return "\\" + (num - 0 + 1); + })); +} + +var makeArray = function(array, results) { + array = Array.prototype.slice.call( array, 0 ); + + if ( results ) { + results.push.apply( results, array ); + return results; + } + + return array; +}; + +// Perform a simple check to determine if the browser is capable of +// converting a NodeList to an array using builtin methods. +try { + Array.prototype.slice.call( document.documentElement.childNodes, 0 ); + +// Provide a fallback method if it does not work +} catch(e){ + makeArray = function(array, results) { + var ret = results || []; + + if ( toString.call(array) === "[object Array]" ) { + Array.prototype.push.apply( ret, array ); + } else { + if ( typeof array.length === "number" ) { + for ( var i = 0, l = array.length; i < l; i++ ) { + ret.push( array[i] ); + } + } else { + for ( var i = 0; array[i]; i++ ) { + ret.push( array[i] ); + } + } + } + + return ret; + }; +} + +var sortOrder; + +if ( document.documentElement.compareDocumentPosition ) { + sortOrder = function( a, b ) { + if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { + if ( a == b ) { + hasDuplicate = true; + } + return a.compareDocumentPosition ? -1 : 1; + } + + var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; + if ( ret === 0 ) { + hasDuplicate = true; + } + return ret; + }; +} else if ( "sourceIndex" in document.documentElement ) { + sortOrder = function( a, b ) { + if ( !a.sourceIndex || !b.sourceIndex ) { + if ( a == b ) { + hasDuplicate = true; + } + return a.sourceIndex ? -1 : 1; + } + + var ret = a.sourceIndex - b.sourceIndex; + if ( ret === 0 ) { + hasDuplicate = true; + } + return ret; + }; +} else if ( document.createRange ) { + sortOrder = function( a, b ) { + if ( !a.ownerDocument || !b.ownerDocument ) { + if ( a == b ) { + hasDuplicate = true; + } + return a.ownerDocument ? -1 : 1; + } + + var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); + aRange.setStart(a, 0); + aRange.setEnd(a, 0); + bRange.setStart(b, 0); + bRange.setEnd(b, 0); + var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); + if ( ret === 0 ) { + hasDuplicate = true; + } + return ret; + }; +} + +// Utility function for retreiving the text value of an array of DOM nodes +function getText( elems ) { + var ret = "", elem; + + for ( var i = 0; elems[i]; i++ ) { + elem = elems[i]; + + // Get the text from text nodes and CDATA nodes + if ( elem.nodeType === 3 || elem.nodeType === 4 ) { + ret += elem.nodeValue; + + // Traverse everything else, except comment nodes + } else if ( elem.nodeType !== 8 ) { + ret += getText( elem.childNodes ); + } + } + + return ret; +} + +// Check to see if the browser returns elements by name when +// querying by getElementById (and provide a workaround) +(function(){ + // We're going to inject a fake input element with a specified name + var form = document.createElement("div"), + id = "script" + (new Date).getTime(); + form.innerHTML = "<a name='" + id + "'/>"; + + // Inject it into the root element, check its status, and remove it quickly + var root = document.documentElement; + root.insertBefore( form, root.firstChild ); + + // The workaround has to do additional checks after a getElementById + // Which slows things down for other browsers (hence the branching) + if ( document.getElementById( id ) ) { + Expr.find.ID = function(match, context, isXML){ + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; + } + }; + + Expr.filter.ID = function(elem, match){ + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + return elem.nodeType === 1 && node && node.nodeValue === match; + }; + } + + root.removeChild( form ); + root = form = null; // release memory in IE +})(); + +(function(){ + // Check to see if the browser returns only elements + // when doing getElementsByTagName("*") + + // Create a fake element + var div = document.createElement("div"); + div.appendChild( document.createComment("") ); + + // Make sure no comments are found + if ( div.getElementsByTagName("*").length > 0 ) { + Expr.find.TAG = function(match, context){ + var results = context.getElementsByTagName(match[1]); + + // Filter out possible comments + if ( match[1] === "*" ) { + var tmp = []; + + for ( var i = 0; results[i]; i++ ) { + if ( results[i].nodeType === 1 ) { + tmp.push( results[i] ); + } + } + + results = tmp; + } + + return results; + }; + } + + // Check to see if an attribute returns normalized href attributes + div.innerHTML = "<a href='#'></a>"; + if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && + div.firstChild.getAttribute("href") !== "#" ) { + Expr.attrHandle.href = function(elem){ + return elem.getAttribute("href", 2); + }; + } + + div = null; // release memory in IE +})(); + +if ( document.querySelectorAll ) { + (function(){ + var oldSizzle = Sizzle, div = document.createElement("div"); + div.innerHTML = "<p class='TEST'></p>"; + + // Safari can't handle uppercase or unicode characters when + // in quirks mode. + if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { + return; + } + + Sizzle = function(query, context, extra, seed){ + context = context || document; + + // Only use querySelectorAll on non-XML documents + // (ID selectors don't work in non-HTML documents) + if ( !seed && context.nodeType === 9 && !isXML(context) ) { + try { + return makeArray( context.querySelectorAll(query), extra ); + } catch(e){} + } + + return oldSizzle(query, context, extra, seed); + }; + + for ( var prop in oldSizzle ) { + Sizzle[ prop ] = oldSizzle[ prop ]; + } + + div = null; // release memory in IE + })(); +} + +(function(){ + var div = document.createElement("div"); + + div.innerHTML = "<div class='test e'></div><div class='test'></div>"; + + // Opera can't find a second classname (in 9.6) + // Also, make sure that getElementsByClassName actually exists + if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { + return; + } + + // Safari caches class attributes, doesn't catch changes (in 3.2) + div.lastChild.className = "e"; + + if ( div.getElementsByClassName("e").length === 1 ) { + return; + } + + Expr.order.splice(1, 0, "CLASS"); + Expr.find.CLASS = function(match, context, isXML) { + if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { + return context.getElementsByClassName(match[1]); + } + }; + + div = null; // release memory in IE +})(); + +function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + if ( elem ) { + elem = elem[dir]; + var match = false; + + while ( elem ) { + if ( elem.sizcache === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 && !isXML ){ + elem.sizcache = doneName; + elem.sizset = i; + } + + if ( elem.nodeName.toLowerCase() === cur ) { + match = elem; + break; + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + if ( elem ) { + elem = elem[dir]; + var match = false; + + while ( elem ) { + if ( elem.sizcache === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 ) { + if ( !isXML ) { + elem.sizcache = doneName; + elem.sizset = i; + } + if ( typeof cur !== "string" ) { + if ( elem === cur ) { + match = true; + break; + } + + } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { + match = elem; + break; + } + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +var contains = document.compareDocumentPosition ? function(a, b){ + return a.compareDocumentPosition(b) & 16; +} : function(a, b){ + return a !== b && (a.contains ? a.contains(b) : true); +}; + +var isXML = function(elem){ + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +var posProcess = function(selector, context){ + var tmpSet = [], later = "", match, + root = context.nodeType ? [context] : context; + + // Position selectors must be done after the filter + // And so must :not(positional) so we move all PSEUDOs to the end + while ( (match = Expr.match.PSEUDO.exec( selector )) ) { + later += match[0]; + selector = selector.replace( Expr.match.PSEUDO, "" ); + } + + selector = Expr.relative[selector] ? selector + "*" : selector; + + for ( var i = 0, l = root.length; i < l; i++ ) { + Sizzle( selector, root[i], tmpSet ); + } + + return Sizzle.filter( later, tmpSet ); +}; + +// EXPOSE +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.filters; +jQuery.unique = Sizzle.uniqueSort; +jQuery.getText = getText; +jQuery.isXMLDoc = isXML; +jQuery.contains = contains; + +return; + +window.Sizzle = Sizzle; + +})(); +var runtil = /Until$/, + rparentsprev = /^(?:parents|prevUntil|prevAll)/, + // Note: This RegExp should be improved, or likely pulled from Sizzle + rmultiselector = /,/, + slice = Array.prototype.slice; + +// Implement the identical functionality for filter and not +var winnow = function( elements, qualifier, keep ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + return !!qualifier.call( elem, i, elem ) === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem, i ) { + return (elem === qualifier) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem, i ) { + return (jQuery.inArray( elem, qualifier ) >= 0) === keep; + }); +}; + +jQuery.fn.extend({ + find: function( selector ) { + var ret = this.pushStack( "", "find", selector ), length = 0; + + for ( var i = 0, l = this.length; i < l; i++ ) { + length = ret.length; + jQuery.find( selector, this[i], ret ); + + if ( i > 0 ) { + // Make sure that the results are unique + for ( var n = length; n < ret.length; n++ ) { + for ( var r = 0; r < length; r++ ) { + if ( ret[r] === ret[n] ) { + ret.splice(n--, 1); + break; + } + } + } + } + } + + return ret; + }, + + has: function( target ) { + var targets = jQuery( target ); + return this.filter(function() { + for ( var i = 0, l = targets.length; i < l; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false), "not", selector); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true), "filter", selector ); + }, + + is: function( selector ) { + return !!selector && jQuery.filter( selector, this ).length > 0; + }, + + closest: function( selectors, context ) { + if ( jQuery.isArray( selectors ) ) { + var ret = [], cur = this[0], match, matches = {}, selector; + + if ( cur && selectors.length ) { + for ( var i = 0, l = selectors.length; i < l; i++ ) { + selector = selectors[i]; + + if ( !matches[selector] ) { + matches[selector] = jQuery.expr.match.POS.test( selector ) ? + jQuery( selector, context || this.context ) : + selector; + } + } + + while ( cur && cur.ownerDocument && cur !== context ) { + for ( selector in matches ) { + match = matches[selector]; + + if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) { + ret.push({ selector: selector, elem: cur }); + delete matches[selector]; + } + } + cur = cur.parentNode; + } + } + + return ret; + } + + var pos = jQuery.expr.match.POS.test( selectors ) ? + jQuery( selectors, context || this.context ) : null; + + return this.map(function( i, cur ) { + while ( cur && cur.ownerDocument && cur !== context ) { + if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selectors) ) { + return cur; + } + cur = cur.parentNode; + } + return null; + }); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + if ( !elem || typeof elem === "string" ) { + return jQuery.inArray( this[0], + // If it receives a string, the selector is used + // If it receives nothing, the siblings are used + elem ? jQuery( elem ) : this.parent().children() ); + } + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context || this.context ) : + jQuery.makeArray( selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? + all : + jQuery.unique( all ) ); + }, + + andSelf: function() { + return this.add( this.prevObject ); + } +}); + +// A painfully simple check to see if an element is disconnected +// from a document (should be improved, where feasible). +function isDisconnected( node ) { + return !node || !node.parentNode || node.parentNode.nodeType === 11; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return jQuery.nth( elem, 2, "nextSibling" ); + }, + prev: function( elem ) { + return jQuery.nth( elem, 2, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( elem.parentNode.firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.makeArray( elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 ? jQuery.unique( ret ) : ret; + + if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret, name, slice.call(arguments).join(",") ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], cur = elem[dir]; + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + nth: function( cur, result, dir, elem ) { + result = result || 1; + var num = 0; + + for ( ; cur; cur = cur[dir] ) { + if ( cur.nodeType === 1 && ++num === result ) { + break; + } + } + + return cur; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); +var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, + rleadingWhitespace = /^\s+/, + rxhtmlTag = /(<([\w:]+)[^>]*?)\/>/g, + rselfClosing = /^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i, + rtagName = /<([\w:]+)/, + rtbody = /<tbody/i, + rhtml = /<|&\w+;/, + rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, // checked="checked" or checked (html5) + fcloseTag = function( all, front, tag ) { + return rselfClosing.test( tag ) ? + all : + front + "></" + tag + ">"; + }, + wrapMap = { + option: [ 1, "<select multiple='multiple'>", "</select>" ], + legend: [ 1, "<fieldset>", "</fieldset>" ], + thead: [ 1, "<table>", "</table>" ], + tr: [ 2, "<table><tbody>", "</tbody></table>" ], + td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], + col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], + area: [ 1, "<map>", "</map>" ], + _default: [ 0, "", "" ] + }; + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// IE can't serialize <link> and <script> tags normally +if ( !jQuery.support.htmlSerialize ) { + wrapMap._default = [ 1, "div<div>", "</div>" ]; +} + +jQuery.fn.extend({ + text: function( text ) { + if ( jQuery.isFunction(text) ) { + return this.each(function(i) { + var self = jQuery(this); + self.text( text.call(this, i, self.text()) ); + }); + } + + if ( typeof text !== "object" && text !== undefined ) { + return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); + } + + return jQuery.getText( this ); + }, + + wrapAll: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapAll( html.call(this, i) ); + }); + } + + if ( this[0] ) { + // The elements to wrap the target around + var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); + + if ( this[0].parentNode ) { + wrap.insertBefore( this[0] ); + } + + wrap.map(function() { + var elem = this; + + while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { + elem = elem.firstChild; + } + + return elem; + }).append(this); + } + + return this; + }, + + wrapInner: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapInner( html.call(this, i) ); + }); + } + + return this.each(function() { + var self = jQuery( this ), contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + }); + }, + + wrap: function( html ) { + return this.each(function() { + jQuery( this ).wrapAll( html ); + }); + }, + + unwrap: function() { + return this.parent().each(function() { + if ( !jQuery.nodeName( this, "body" ) ) { + jQuery( this ).replaceWith( this.childNodes ); + } + }).end(); + }, + + append: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 ) { + this.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 ) { + this.insertBefore( elem, this.firstChild ); + } + }); + }, + + before: function() { + if ( this[0] && this[0].parentNode ) { + return this.domManip(arguments, false, function( elem ) { + this.parentNode.insertBefore( elem, this ); + }); + } else if ( arguments.length ) { + var set = jQuery(arguments[0]); + set.push.apply( set, this.toArray() ); + return this.pushStack( set, "before", arguments ); + } + }, + + after: function() { + if ( this[0] && this[0].parentNode ) { + return this.domManip(arguments, false, function( elem ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + }); + } else if ( arguments.length ) { + var set = this.pushStack( this, "after", arguments ); + set.push.apply( set, jQuery(arguments[0]).toArray() ); + return set; + } + }, + + clone: function( events ) { + // Do the clone + var ret = this.map(function() { + if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) { + // IE copies events bound via attachEvent when + // using cloneNode. Calling detachEvent on the + // clone will also remove the events from the orignal + // In order to get around this, we use innerHTML. + // Unfortunately, this means some modifications to + // attributes in IE that are actually only stored + // as properties will not be copied (such as the + // the name attribute on an input). + var html = this.outerHTML, ownerDocument = this.ownerDocument; + if ( !html ) { + var div = ownerDocument.createElement("div"); + div.appendChild( this.cloneNode(true) ); + html = div.innerHTML; + } + + return jQuery.clean([html.replace(rinlinejQuery, "") + .replace(rleadingWhitespace, "")], ownerDocument)[0]; + } else { + return this.cloneNode(true); + } + }); + + // Copy the events from the original to the clone + if ( events === true ) { + cloneCopyEvent( this, ret ); + cloneCopyEvent( this.find("*"), ret.find("*") ); + } + + // Return the cloned set + return ret; + }, + + html: function( value ) { + if ( value === undefined ) { + return this[0] && this[0].nodeType === 1 ? + this[0].innerHTML.replace(rinlinejQuery, "") : + null; + + // See if we can take a shortcut and just use innerHTML + } else if ( typeof value === "string" && !/<script/i.test( value ) && + (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && + !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { + + value = value.replace(rxhtmlTag, fcloseTag); + + try { + for ( var i = 0, l = this.length; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + if ( this[i].nodeType === 1 ) { + jQuery.cleanData( this[i].getElementsByTagName("*") ); + this[i].innerHTML = value; + } + } + + // If using innerHTML throws an exception, use the fallback method + } catch(e) { + this.empty().append( value ); + } + + } else if ( jQuery.isFunction( value ) ) { + this.each(function(i){ + var self = jQuery(this), old = self.html(); + self.empty().append(function(){ + return value.call( this, i, old ); + }); + }); + + } else { + this.empty().append( value ); + } + + return this; + }, + + replaceWith: function( value ) { + if ( this[0] && this[0].parentNode ) { + // Make sure that the elements are removed from the DOM before they are inserted + // this can help fix replacing a parent with child elements + if ( !jQuery.isFunction( value ) ) { + value = jQuery( value ).detach(); + + } else { + return this.each(function(i) { + var self = jQuery(this), old = self.html(); + self.replaceWith( value.call( this, i, old ) ); + }); + } + + return this.each(function() { + var next = this.nextSibling, parent = this.parentNode; + + jQuery(this).remove(); + + if ( next ) { + jQuery(next).before( value ); + } else { + jQuery(parent).append( value ); + } + }); + } else { + return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ); + } + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, table, callback ) { + var results, first, value = args[0], scripts = []; + + // We can't cloneNode fragments that contain checked, in WebKit + if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { + return this.each(function() { + jQuery(this).domManip( args, table, callback, true ); + }); + } + + if ( jQuery.isFunction(value) ) { + return this.each(function(i) { + var self = jQuery(this); + args[0] = value.call(this, i, table ? self.html() : undefined); + self.domManip( args, table, callback ); + }); + } + + if ( this[0] ) { + // If we're in a fragment, just use that instead of building a new one + if ( args[0] && args[0].parentNode && args[0].parentNode.nodeType === 11 ) { + results = { fragment: args[0].parentNode }; + } else { + results = buildFragment( args, this, scripts ); + } + + first = results.fragment.firstChild; + + if ( first ) { + table = table && jQuery.nodeName( first, "tr" ); + + for ( var i = 0, l = this.length; i < l; i++ ) { + callback.call( + table ? + root(this[i], first) : + this[i], + results.cacheable || this.length > 1 || i > 0 ? + results.fragment.cloneNode(true) : + results.fragment + ); + } + } + + if ( scripts ) { + jQuery.each( scripts, evalScript ); + } + } + + return this; + + function root( elem, cur ) { + return jQuery.nodeName(elem, "table") ? + (elem.getElementsByTagName("tbody")[0] || + elem.appendChild(elem.ownerDocument.createElement("tbody"))) : + elem; + } + } +}); + +function cloneCopyEvent(orig, ret) { + var i = 0; + + ret.each(function() { + if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) { + return; + } + + var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events; + + if ( events ) { + delete curData.handle; + curData.events = {}; + + for ( var type in events ) { + for ( var handler in events[ type ] ) { + jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data ); + } + } + } + }); +} + +function buildFragment( args, nodes, scripts ) { + var fragment, cacheable, cacheresults, doc; + + // webkit does not clone 'checked' attribute of radio inputs on cloneNode, so don't cache if string has a checked + if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && args[0].indexOf("<option") < 0 && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { + cacheable = true; + cacheresults = jQuery.fragments[ args[0] ]; + if ( cacheresults ) { + if ( cacheresults !== 1 ) { + fragment = cacheresults; + } + } + } + + if ( !fragment ) { + doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); + fragment = doc.createDocumentFragment(); + jQuery.clean( args, doc, fragment, scripts ); + } + + if ( cacheable ) { + jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; + } + + return { fragment: fragment, cacheable: cacheable }; +} + +jQuery.fragments = {}; + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var ret = [], insert = jQuery( selector ); + + for ( var i = 0, l = insert.length; i < l; i++ ) { + var elems = (i > 0 ? this.clone(true) : this).get(); + jQuery.fn[ original ].apply( jQuery(insert[i]), elems ); + ret = ret.concat( elems ); + } + return this.pushStack( ret, name, insert.selector ); + }; +}); + +jQuery.each({ + // keepData is for internal use only--do not document + remove: function( selector, keepData ) { + if ( !selector || jQuery.filter( selector, [ this ] ).length ) { + if ( !keepData && this.nodeType === 1 ) { + jQuery.cleanData( this.getElementsByTagName("*") ); + jQuery.cleanData( [ this ] ); + } + + if ( this.parentNode ) { + this.parentNode.removeChild( this ); + } + } + }, + + empty: function() { + // Remove element nodes and prevent memory leaks + if ( this.nodeType === 1 ) { + jQuery.cleanData( this.getElementsByTagName("*") ); + } + + // Remove any remaining nodes + while ( this.firstChild ) { + this.removeChild( this.firstChild ); + } + } +}, function( name, fn ) { + jQuery.fn[ name ] = function() { + return this.each( fn, arguments ); + }; +}); + +jQuery.extend({ + clean: function( elems, context, fragment, scripts ) { + context = context || document; + + // !context.createElement fails in IE with an error but returns typeof 'object' + if ( typeof context.createElement === "undefined" ) { + context = context.ownerDocument || context[0] && context[0].ownerDocument || document; + } + + var ret = []; + + jQuery.each(elems, function( i, elem ) { + if ( typeof elem === "number" ) { + elem += ""; + } + + if ( !elem ) { + return; + } + + // Convert html string into DOM nodes + if ( typeof elem === "string" && !rhtml.test( elem ) ) { + elem = context.createTextNode( elem ); + + } else if ( typeof elem === "string" ) { + // Fix "XHTML"-style tags in all browsers + elem = elem.replace(rxhtmlTag, fcloseTag); + + // Trim whitespace, otherwise indexOf won't work as expected + var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), + wrap = wrapMap[ tag ] || wrapMap._default, + depth = wrap[0], + div = context.createElement("div"); + + // Go to html and back, then peel off extra wrappers + div.innerHTML = wrap[1] + elem + wrap[2]; + + // Move to the right depth + while ( depth-- ) { + div = div.lastChild; + } + + // Remove IE's autoinserted <tbody> from table fragments + if ( !jQuery.support.tbody ) { + + // String was a <table>, *may* have spurious <tbody> + var hasBody = rtbody.test(elem), + tbody = tag === "table" && !hasBody ? + div.firstChild && div.firstChild.childNodes : + + // String was a bare <thead> or <tfoot> + wrap[1] === "<table>" && !hasBody ? + div.childNodes : + []; + + for ( var j = tbody.length - 1; j >= 0 ; --j ) { + if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { + tbody[ j ].parentNode.removeChild( tbody[ j ] ); + } + } + + } + + // IE completely kills leading whitespace when innerHTML is used + if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); + } + + elem = jQuery.makeArray( div.childNodes ); + } + + if ( elem.nodeType ) { + ret.push( elem ); + } else { + ret = jQuery.merge( ret, elem ); + } + + }); + + if ( fragment ) { + for ( var i = 0; ret[i]; i++ ) { + if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { + scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); + } else { + if ( ret[i].nodeType === 1 ) { + ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) ); + } + fragment.appendChild( ret[i] ); + } + } + } + + return ret; + }, + + cleanData: function( elems ) { + for ( var i = 0, elem, id; (elem = elems[i]) != null; i++ ) { + jQuery.event.remove( elem ); + jQuery.removeData( elem ); + } + } +}); +// exclude the following css properties to add px +var rexclude = /z-?index|font-?weight|opacity|zoom|line-?height/i, + ralpha = /alpha\([^)]*\)/, + ropacity = /opacity=([^)]*)/, + rfloat = /float/i, + rdashAlpha = /-([a-z])/ig, + rupper = /([A-Z])/g, + rnumpx = /^-?\d+(?:px)?$/i, + rnum = /^-?\d/, + + cssShow = { position: "absolute", visibility: "hidden", display:"block" }, + cssWidth = [ "Left", "Right" ], + cssHeight = [ "Top", "Bottom" ], + + // cache check for defaultView.getComputedStyle + getComputedStyle = document.defaultView && document.defaultView.getComputedStyle, + // normalize float css property + styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat", + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; + +jQuery.fn.css = function( name, value ) { + return access( this, name, value, true, function( elem, name, value ) { + if ( value === undefined ) { + return jQuery.curCSS( elem, name ); + } + + if ( typeof value === "number" && !rexclude.test(name) ) { + value += "px"; + } + + jQuery.style( elem, name, value ); + }); +}; + +jQuery.extend({ + style: function( elem, name, value ) { + // don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { + return undefined; + } + + // ignore negative width and height values #1599 + if ( (name === "width" || name === "height") && parseFloat(value) < 0 ) { + value = undefined; + } + + var style = elem.style || elem, set = value !== undefined; + + // IE uses filters for opacity + if ( !jQuery.support.opacity && name === "opacity" ) { + if ( set ) { + // IE has trouble with opacity if it does not have layout + // Force it by setting the zoom level + style.zoom = 1; + + // Set the alpha filter to set the opacity + var opacity = parseInt( value, 10 ) + "" === "NaN" ? "" : "alpha(opacity=" + value * 100 + ")"; + var filter = style.filter || jQuery.curCSS( elem, "filter" ) || ""; + style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : opacity; + } + + return style.filter && style.filter.indexOf("opacity=") >= 0 ? + (parseFloat( ropacity.exec(style.filter)[1] ) / 100) + "": + ""; + } + + // Make sure we're using the right name for getting the float value + if ( rfloat.test( name ) ) { + name = styleFloat; + } + + name = name.replace(rdashAlpha, fcamelCase); + + if ( set ) { + style[ name ] = value; + } + + return style[ name ]; + }, + + css: function( elem, name, force, extra ) { + if ( name === "width" || name === "height" ) { + var val, props = cssShow, which = name === "width" ? cssWidth : cssHeight; + + function getWH() { + val = name === "width" ? elem.offsetWidth : elem.offsetHeight; + + if ( extra === "border" ) { + return; + } + + jQuery.each( which, function() { + if ( !extra ) { + val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0; + } + + if ( extra === "margin" ) { + val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0; + } else { + val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0; + } + }); + } + + if ( elem.offsetWidth !== 0 ) { + getWH(); + } else { + jQuery.swap( elem, props, getWH ); + } + + return Math.max(0, Math.round(val)); + } + + return jQuery.curCSS( elem, name, force ); + }, + + curCSS: function( elem, name, force ) { + var ret, style = elem.style, filter; + + // IE uses filters for opacity + if ( !jQuery.support.opacity && name === "opacity" && elem.currentStyle ) { + ret = ropacity.test(elem.currentStyle.filter || "") ? + (parseFloat(RegExp.$1) / 100) + "" : + ""; + + return ret === "" ? + "1" : + ret; + } + + // Make sure we're using the right name for getting the float value + if ( rfloat.test( name ) ) { + name = styleFloat; + } + + if ( !force && style && style[ name ] ) { + ret = style[ name ]; + + } else if ( getComputedStyle ) { + + // Only "float" is needed here + if ( rfloat.test( name ) ) { + name = "float"; + } + + name = name.replace( rupper, "-$1" ).toLowerCase(); + + var defaultView = elem.ownerDocument.defaultView; + + if ( !defaultView ) { + return null; + } + + var computedStyle = defaultView.getComputedStyle( elem, null ); + + if ( computedStyle ) { + ret = computedStyle.getPropertyValue( name ); + } + + // We should always get a number back from opacity + if ( name === "opacity" && ret === "" ) { + ret = "1"; + } + + } else if ( elem.currentStyle ) { + var camelCase = name.replace(rdashAlpha, fcamelCase); + + ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ]; + + // From the awesome hack by Dean Edwards + // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + + // If we're not dealing with a regular pixel number + // but a number that has a weird ending, we need to convert it to pixels + if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { + // Remember the original values + var left = style.left, rsLeft = elem.runtimeStyle.left; + + // Put in the new values to get a computed value out + elem.runtimeStyle.left = elem.currentStyle.left; + style.left = camelCase === "fontSize" ? "1em" : (ret || 0); + ret = style.pixelLeft + "px"; + + // Revert the changed values + style.left = left; + elem.runtimeStyle.left = rsLeft; + } + } + + return ret; + }, + + // A method for quickly swapping in/out CSS properties to get correct calculations + swap: function( elem, options, callback ) { + var old = {}; + + // Remember the old values, and insert the new ones + for ( var name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + callback.call( elem ); + + // Revert the old values + for ( var name in options ) { + elem.style[ name ] = old[ name ]; + } + } +}); + +if ( jQuery.expr && jQuery.expr.filters ) { + jQuery.expr.filters.hidden = function( elem ) { + var width = elem.offsetWidth, height = elem.offsetHeight, + skip = elem.nodeName.toLowerCase() === "tr"; + + return width === 0 && height === 0 && !skip ? + true : + width > 0 && height > 0 && !skip ? + false : + jQuery.curCSS(elem, "display") === "none"; + }; + + jQuery.expr.filters.visible = function( elem ) { + return !jQuery.expr.filters.hidden( elem ); + }; +} +var jsc = now(), + rscript = /<script(.|\s)*?\/script>/gi, + rselectTextarea = /select|textarea/i, + rinput = /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i, + jsre = /=\?(&|$)/, + rquery = /\?/, + rts = /(\?|&)_=.*?(&|$)/, + rurl = /^(\w+:)?\/\/([^\/?#]+)/, + r20 = /%20/g; + +jQuery.fn.extend({ + // Keep a copy of the old load + _load: jQuery.fn.load, + + load: function( url, params, callback ) { + if ( typeof url !== "string" ) { + return this._load( url ); + + // Don't do a request if no elements are being requested + } else if ( !this.length ) { + return this; + } + + var off = url.indexOf(" "); + if ( off >= 0 ) { + var selector = url.slice(off, url.length); + url = url.slice(0, off); + } + + // Default to a GET request + var type = "GET"; + + // If the second parameter was provided + if ( params ) { + // If it's a function + if ( jQuery.isFunction( params ) ) { + // We assume that it's the callback + callback = params; + params = null; + + // Otherwise, build a param string + } else if ( typeof params === "object" ) { + params = jQuery.param( params, jQuery.ajaxSettings.traditional ); + type = "POST"; + } + } + + var self = this; + + // Request the remote document + jQuery.ajax({ + url: url, + type: type, + dataType: "html", + data: params, + complete: function( res, status ) { + // If successful, inject the HTML into all the matched elements + if ( status === "success" || status === "notmodified" ) { + // See if a selector was specified + self.html( selector ? + // Create a dummy div to hold the results + jQuery("<div />") + // inject the contents of the document in, removing the scripts + // to avoid any 'Permission Denied' errors in IE + .append(res.responseText.replace(rscript, "")) + + // Locate the specified elements + .find(selector) : + + // If not, just inject the full result + res.responseText ); + } + + if ( callback ) { + self.each( callback, [res.responseText, status, res] ); + } + } + }); + + return this; + }, + + serialize: function() { + return jQuery.param(this.serializeArray()); + }, + serializeArray: function() { + return this.map(function() { + return this.elements ? jQuery.makeArray(this.elements) : this; + }) + .filter(function() { + return this.name && !this.disabled && + (this.checked || rselectTextarea.test(this.nodeName) || + rinput.test(this.type)); + }) + .map(function( i, elem ) { + var val = jQuery(this).val(); + + return val == null ? + null : + jQuery.isArray(val) ? + jQuery.map( val, function( val, i ) { + return { name: elem.name, value: val }; + }) : + { name: elem.name, value: val }; + }).get(); + } +}); + +// Attach a bunch of functions for handling common AJAX events +jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) { + jQuery.fn[o] = function( f ) { + return this.bind(o, f); + }; +}); + +jQuery.extend({ + + get: function( url, data, callback, type ) { + // shift arguments if data argument was omited + if ( jQuery.isFunction( data ) ) { + type = type || callback; + callback = data; + data = null; + } + + return jQuery.ajax({ + type: "GET", + url: url, + data: data, + success: callback, + dataType: type + }); + }, + + getScript: function( url, callback ) { + return jQuery.get(url, null, callback, "script"); + }, + + getJSON: function( url, data, callback ) { + return jQuery.get(url, data, callback, "json"); + }, + + post: function( url, data, callback, type ) { + // shift arguments if data argument was omited + if ( jQuery.isFunction( data ) ) { + type = type || callback; + callback = data; + data = {}; + } + + return jQuery.ajax({ + type: "POST", + url: url, + data: data, + success: callback, + dataType: type + }); + }, + + ajaxSetup: function( settings ) { + jQuery.extend( jQuery.ajaxSettings, settings ); + }, + + ajaxSettings: { + url: location.href, + global: true, + type: "GET", + contentType: "application/x-www-form-urlencoded", + processData: true, + async: true, + /* + timeout: 0, + data: null, + username: null, + password: null, + traditional: false, + */ + // Create the request object; Microsoft failed to properly + // implement the XMLHttpRequest in IE7 (can't request local files), + // so we use the ActiveXObject when it is available + // This function can be overriden by calling jQuery.ajaxSetup + xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ? + function() { + return new window.XMLHttpRequest(); + } : + function() { + try { + return new window.ActiveXObject("Microsoft.XMLHTTP"); + } catch(e) {} + }, + accepts: { + xml: "application/xml, text/xml", + html: "text/html", + script: "text/javascript, application/javascript", + json: "application/json, text/javascript", + text: "text/plain", + _default: "*/*" + } + }, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {}, + + ajax: function( origSettings ) { + var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings); + + var jsonp, status, data, + callbackContext = origSettings && origSettings.context || s, + type = s.type.toUpperCase(); + + // convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Handle JSONP Parameter Callbacks + if ( s.dataType === "jsonp" ) { + if ( type === "GET" ) { + if ( !jsre.test( s.url ) ) { + s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?"; + } + } else if ( !s.data || !jsre.test(s.data) ) { + s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?"; + } + s.dataType = "json"; + } + + // Build temporary JSONP function + if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) { + jsonp = s.jsonpCallback || ("jsonp" + jsc++); + + // Replace the =? sequence both in the query string and the data + if ( s.data ) { + s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1"); + } + + s.url = s.url.replace(jsre, "=" + jsonp + "$1"); + + // We need to make sure + // that a JSONP style response is executed properly + s.dataType = "script"; + + // Handle JSONP-style loading + window[ jsonp ] = window[ jsonp ] || function( tmp ) { + data = tmp; + success(); + complete(); + // Garbage collect + window[ jsonp ] = undefined; + + try { + delete window[ jsonp ]; + } catch(e) {} + + if ( head ) { + head.removeChild( script ); + } + }; + } + + if ( s.dataType === "script" && s.cache === null ) { + s.cache = false; + } + + if ( s.cache === false && type === "GET" ) { + var ts = now(); + + // try replacing _= if it is there + var ret = s.url.replace(rts, "$1_=" + ts + "$2"); + + // if nothing was replaced, add timestamp to the end + s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : ""); + } + + // If data is available, append data to url for get requests + if ( s.data && type === "GET" ) { + s.url += (rquery.test(s.url) ? "&" : "?") + s.data; + } + + // Watch for a new set of requests + if ( s.global && ! jQuery.active++ ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // Matches an absolute URL, and saves the domain + var parts = rurl.exec( s.url ), + remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host); + + // If we're requesting a remote document + // and trying to load JSON or Script with a GET + if ( s.dataType === "script" && type === "GET" && remote ) { + var head = document.getElementsByTagName("head")[0] || document.documentElement; + var script = document.createElement("script"); + script.src = s.url; + if ( s.scriptCharset ) { + script.charset = s.scriptCharset; + } + + // Handle Script loading + if ( !jsonp ) { + var done = false; + + // Attach handlers for all browsers + script.onload = script.onreadystatechange = function() { + if ( !done && (!this.readyState || + this.readyState === "loaded" || this.readyState === "complete") ) { + done = true; + success(); + complete(); + + // Handle memory leak in IE + script.onload = script.onreadystatechange = null; + if ( head && script.parentNode ) { + head.removeChild( script ); + } + } + }; + } + + // Use insertBefore instead of appendChild to circumvent an IE6 bug. + // This arises when a base node is used (#2709 and #4378). + head.insertBefore( script, head.firstChild ); + + // We handle everything using the script element injection + return undefined; + } + + var requestDone = false; + + // Create the request object + var xhr = s.xhr(); + + if ( !xhr ) { + return; + } + + // Open the socket + // Passing null username, generates a login popup on Opera (#2865) + if ( s.username ) { + xhr.open(type, s.url, s.async, s.username, s.password); + } else { + xhr.open(type, s.url, s.async); + } + + // Need an extra try/catch for cross domain requests in Firefox 3 + try { + // Set the correct header, if data is being sent + if ( s.data || origSettings && origSettings.contentType ) { + xhr.setRequestHeader("Content-Type", s.contentType); + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + if ( jQuery.lastModified[s.url] ) { + xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]); + } + + if ( jQuery.etag[s.url] ) { + xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]); + } + } + + // Set header so the called script knows that it's an XMLHttpRequest + // Only send the header if it's not a remote XHR + if ( !remote ) { + xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); + } + + // Set the Accepts header for the server, depending on the dataType + xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ? + s.accepts[ s.dataType ] + ", */*" : + s.accepts._default ); + } catch(e) {} + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && s.beforeSend.call(callbackContext, xhr, s) === false ) { + // Handle the global AJAX counter + if ( s.global && ! --jQuery.active ) { + jQuery.event.trigger( "ajaxStop" ); + } + + // close opended socket + xhr.abort(); + return false; + } + + if ( s.global ) { + trigger("ajaxSend", [xhr, s]); + } + + // Wait for a response to come back + var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) { + // The request was aborted + if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) { + // Opera doesn't call onreadystatechange before this point + // so we simulate the call + if ( !requestDone ) { + complete(); + } + + requestDone = true; + if ( xhr ) { + xhr.onreadystatechange = jQuery.noop; + } + + // The transfer is complete and the data is available, or the request timed out + } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) { + requestDone = true; + xhr.onreadystatechange = jQuery.noop; + + status = isTimeout === "timeout" ? + "timeout" : + !jQuery.httpSuccess( xhr ) ? + "error" : + s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? + "notmodified" : + "success"; + + var errMsg; + + if ( status === "success" ) { + // Watch for, and catch, XML document parse errors + try { + // process the data (runs the xml through httpData regardless of callback) + data = jQuery.httpData( xhr, s.dataType, s ); + } catch(err) { + status = "parsererror"; + errMsg = err; + } + } + + // Make sure that the request was successful or notmodified + if ( status === "success" || status === "notmodified" ) { + // JSONP handles its own success callback + if ( !jsonp ) { + success(); + } + } else { + jQuery.handleError(s, xhr, status, errMsg); + } + + // Fire the complete handlers + complete(); + + if ( isTimeout === "timeout" ) { + xhr.abort(); + } + + // Stop memory leaks + if ( s.async ) { + xhr = null; + } + } + }; + + // Override the abort handler, if we can (IE doesn't allow it, but that's OK) + // Opera doesn't fire onreadystatechange at all on abort + try { + var oldAbort = xhr.abort; + xhr.abort = function() { + if ( xhr ) { + oldAbort.call( xhr ); + } + + onreadystatechange( "abort" ); + }; + } catch(e) { } + + // Timeout checker + if ( s.async && s.timeout > 0 ) { + setTimeout(function() { + // Check to see if the request is still happening + if ( xhr && !requestDone ) { + onreadystatechange( "timeout" ); + } + }, s.timeout); + } + + // Send the data + try { + xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null ); + } catch(e) { + jQuery.handleError(s, xhr, null, e); + // Fire the complete handlers + complete(); + } + + // firefox 1.5 doesn't fire statechange for sync requests + if ( !s.async ) { + onreadystatechange(); + } + + function success() { + // If a local callback was specified, fire it and pass it the data + if ( s.success ) { + s.success.call( callbackContext, data, status, xhr ); + } + + // Fire the global callback + if ( s.global ) { + trigger( "ajaxSuccess", [xhr, s] ); + } + } + + function complete() { + // Process result + if ( s.complete ) { + s.complete.call( callbackContext, xhr, status); + } + + // The request was completed + if ( s.global ) { + trigger( "ajaxComplete", [xhr, s] ); + } + + // Handle the global AJAX counter + if ( s.global && ! --jQuery.active ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + + function trigger(type, args) { + (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args); + } + + // return XMLHttpRequest to allow aborting the request etc. + return xhr; + }, + + handleError: function( s, xhr, status, e ) { + // If a local callback was specified, fire it + if ( s.error ) { + s.error.call( s.context || s, xhr, status, e ); + } + + // Fire the global callback + if ( s.global ) { + (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] ); + } + }, + + // Counter for holding the number of active queries + active: 0, + + // Determines if an XMLHttpRequest was successful or not + httpSuccess: function( xhr ) { + try { + // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450 + return !xhr.status && location.protocol === "file:" || + // Opera returns 0 when status is 304 + ( xhr.status >= 200 && xhr.status < 300 ) || + xhr.status === 304 || xhr.status === 1223 || xhr.status === 0; + } catch(e) {} + + return false; + }, + + // Determines if an XMLHttpRequest returns NotModified + httpNotModified: function( xhr, url ) { + var lastModified = xhr.getResponseHeader("Last-Modified"), + etag = xhr.getResponseHeader("Etag"); + + if ( lastModified ) { + jQuery.lastModified[url] = lastModified; + } + + if ( etag ) { + jQuery.etag[url] = etag; + } + + // Opera returns 0 when status is 304 + return xhr.status === 304 || xhr.status === 0; + }, + + httpData: function( xhr, type, s ) { + var ct = xhr.getResponseHeader("content-type") || "", + xml = type === "xml" || !type && ct.indexOf("xml") >= 0, + data = xml ? xhr.responseXML : xhr.responseText; + + if ( xml && data.documentElement.nodeName === "parsererror" ) { + jQuery.error( "parsererror" ); + } + + // Allow a pre-filtering function to sanitize the response + // s is checked to keep backwards compatibility + if ( s && s.dataFilter ) { + data = s.dataFilter( data, type ); + } + + // The filter can actually parse the response + if ( typeof data === "string" ) { + // Get the JavaScript object, if JSON is used. + if ( type === "json" || !type && ct.indexOf("json") >= 0 ) { + data = jQuery.parseJSON( data ); + + // If the type is "script", eval it in global context + } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) { + jQuery.globalEval( data ); + } + } + + return data; + }, + + // Serialize an array of form elements or a set of + // key/values into a query string + param: function( a, traditional ) { + var s = []; + + // Set traditional to true for jQuery <= 1.3.2 behavior. + if ( traditional === undefined ) { + traditional = jQuery.ajaxSettings.traditional; + } + + // If an array was passed in, assume that it is an array of form elements. + if ( jQuery.isArray(a) || a.jquery ) { + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + }); + + } else { + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( var prefix in a ) { + buildParams( prefix, a[prefix] ); + } + } + + // Return the resulting serialization + return s.join("&").replace(r20, "+"); + + function buildParams( prefix, obj ) { + if ( jQuery.isArray(obj) ) { + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional ) { + // Treat each array item as a scalar. + add( prefix, v ); + } else { + // If array item is non-scalar (array or object), encode its + // numeric index to resolve deserialization ambiguity issues. + // Note that rack (as of 1.0.0) can't currently deserialize + // nested arrays properly, and attempting to do so may cause + // a server error. Possible fixes are to modify rack's + // deserialization algorithm or to provide an option or flag + // to force array serialization to be shallow. + buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v ); + } + }); + + } else if ( !traditional && obj != null && typeof obj === "object" ) { + // Serialize object item. + jQuery.each( obj, function( k, v ) { + buildParams( prefix + "[" + k + "]", v ); + }); + + } else { + // Serialize scalar item. + add( prefix, obj ); + } + } + + function add( key, value ) { + // If value is a function, invoke it and return its value + value = jQuery.isFunction(value) ? value() : value; + s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value); + } + } +}); +var elemdisplay = {}, + rfxtypes = /toggle|show|hide/, + rfxnum = /^([+-]=)?([\d+-.]+)(.*)$/, + timerId, + fxAttrs = [ + // height animations + [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], + // width animations + [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], + // opacity animations + [ "opacity" ] + ]; + +jQuery.fn.extend({ + show: function( speed, callback ) { + if ( speed || speed === 0) { + return this.animate( genFx("show", 3), speed, callback); + + } else { + for ( var i = 0, l = this.length; i < l; i++ ) { + var old = jQuery.data(this[i], "olddisplay"); + + this[i].style.display = old || ""; + + if ( jQuery.css(this[i], "display") === "none" ) { + var nodeName = this[i].nodeName, display; + + if ( elemdisplay[ nodeName ] ) { + display = elemdisplay[ nodeName ]; + + } else { + var elem = jQuery("<" + nodeName + " />").appendTo("body"); + + display = elem.css("display"); + + if ( display === "none" ) { + display = "block"; + } + + elem.remove(); + + elemdisplay[ nodeName ] = display; + } + + jQuery.data(this[i], "olddisplay", display); + } + } + + // Set the display of the elements in a second loop + // to avoid the constant reflow + for ( var j = 0, k = this.length; j < k; j++ ) { + this[j].style.display = jQuery.data(this[j], "olddisplay") || ""; + } + + return this; + } + }, + + hide: function( speed, callback ) { + if ( speed || speed === 0 ) { + return this.animate( genFx("hide", 3), speed, callback); + + } else { + for ( var i = 0, l = this.length; i < l; i++ ) { + var old = jQuery.data(this[i], "olddisplay"); + if ( !old && old !== "none" ) { + jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display")); + } + } + + // Set the display of the elements in a second loop + // to avoid the constant reflow + for ( var j = 0, k = this.length; j < k; j++ ) { + this[j].style.display = "none"; + } + + return this; + } + }, + + // Save the old toggle function + _toggle: jQuery.fn.toggle, + + toggle: function( fn, fn2 ) { + var bool = typeof fn === "boolean"; + + if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { + this._toggle.apply( this, arguments ); + + } else if ( fn == null || bool ) { + this.each(function() { + var state = bool ? fn : jQuery(this).is(":hidden"); + jQuery(this)[ state ? "show" : "hide" ](); + }); + + } else { + this.animate(genFx("toggle", 3), fn, fn2); + } + + return this; + }, + + fadeTo: function( speed, to, callback ) { + return this.filter(":hidden").css("opacity", 0).show().end() + .animate({opacity: to}, speed, callback); + }, + + animate: function( prop, speed, easing, callback ) { + var optall = jQuery.speed(speed, easing, callback); + + if ( jQuery.isEmptyObject( prop ) ) { + return this.each( optall.complete ); + } + + return this[ optall.queue === false ? "each" : "queue" ](function() { + var opt = jQuery.extend({}, optall), p, + hidden = this.nodeType === 1 && jQuery(this).is(":hidden"), + self = this; + + for ( p in prop ) { + var name = p.replace(rdashAlpha, fcamelCase); + + if ( p !== name ) { + prop[ name ] = prop[ p ]; + delete prop[ p ]; + p = name; + } + + if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) { + return opt.complete.call(this); + } + + if ( ( p === "height" || p === "width" ) && this.style ) { + // Store display property + opt.display = jQuery.css(this, "display"); + + // Make sure that nothing sneaks out + opt.overflow = this.style.overflow; + } + + if ( jQuery.isArray( prop[p] ) ) { + // Create (if needed) and add to specialEasing + (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1]; + prop[p] = prop[p][0]; + } + } + + if ( opt.overflow != null ) { + this.style.overflow = "hidden"; + } + + opt.curAnim = jQuery.extend({}, prop); + + jQuery.each( prop, function( name, val ) { + var e = new jQuery.fx( self, opt, name ); + + if ( rfxtypes.test(val) ) { + e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop ); + + } else { + var parts = rfxnum.exec(val), + start = e.cur(true) || 0; + + if ( parts ) { + var end = parseFloat( parts[2] ), + unit = parts[3] || "px"; + + // We need to compute starting value + if ( unit !== "px" ) { + self.style[ name ] = (end || 1) + unit; + start = ((end || 1) / e.cur(true)) * start; + self.style[ name ] = start + unit; + } + + // If a +=/-= token was provided, we're doing a relative animation + if ( parts[1] ) { + end = ((parts[1] === "-=" ? -1 : 1) * end) + start; + } + + e.custom( start, end, unit ); + + } else { + e.custom( start, val, "" ); + } + } + }); + + // For JS strict compliance + return true; + }); + }, + + stop: function( clearQueue, gotoEnd ) { + var timers = jQuery.timers; + + if ( clearQueue ) { + this.queue([]); + } + + this.each(function() { + // go in reverse order so anything added to the queue during the loop is ignored + for ( var i = timers.length - 1; i >= 0; i-- ) { + if ( timers[i].elem === this ) { + if (gotoEnd) { + // force the next step to be the last + timers[i](true); + } + + timers.splice(i, 1); + } + } + }); + + // start the next in the queue if the last step wasn't forced + if ( !gotoEnd ) { + this.dequeue(); + } + + return this; + } + +}); + +// Generate shortcuts for custom animations +jQuery.each({ + slideDown: genFx("show", 1), + slideUp: genFx("hide", 1), + slideToggle: genFx("toggle", 1), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, callback ) { + return this.animate( props, speed, callback ); + }; +}); + +jQuery.extend({ + speed: function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? speed : { + complete: fn || !fn && easing || + jQuery.isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !jQuery.isFunction(easing) && easing + }; + + opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : + jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default; + + // Queueing + opt.old = opt.complete; + opt.complete = function() { + if ( opt.queue !== false ) { + jQuery(this).dequeue(); + } + if ( jQuery.isFunction( opt.old ) ) { + opt.old.call( this ); + } + }; + + return opt; + }, + + easing: { + linear: function( p, n, firstNum, diff ) { + return firstNum + diff * p; + }, + swing: function( p, n, firstNum, diff ) { + return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; + } + }, + + timers: [], + + fx: function( elem, options, prop ) { + this.options = options; + this.elem = elem; + this.prop = prop; + + if ( !options.orig ) { + options.orig = {}; + } + } + +}); + +jQuery.fx.prototype = { + // Simple function for setting a style value + update: function() { + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); + + // Set display property to block for height/width animations + if ( ( this.prop === "height" || this.prop === "width" ) && this.elem.style ) { + this.elem.style.display = "block"; + } + }, + + // Get the current size + cur: function( force ) { + if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { + return this.elem[ this.prop ]; + } + + var r = parseFloat(jQuery.css(this.elem, this.prop, force)); + return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0; + }, + + // Start an animation from one number to another + custom: function( from, to, unit ) { + this.startTime = now(); + this.start = from; + this.end = to; + this.unit = unit || this.unit || "px"; + this.now = this.start; + this.pos = this.state = 0; + + var self = this; + function t( gotoEnd ) { + return self.step(gotoEnd); + } + + t.elem = this.elem; + + if ( t() && jQuery.timers.push(t) && !timerId ) { + timerId = setInterval(jQuery.fx.tick, 13); + } + }, + + // Simple 'show' function + show: function() { + // Remember where we started, so that we can go back to it later + this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); + this.options.show = true; + + // Begin the animation + // Make sure that we start at a small width/height to avoid any + // flash of content + this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); + + // Start by showing the element + jQuery( this.elem ).show(); + }, + + // Simple 'hide' function + hide: function() { + // Remember where we started, so that we can go back to it later + this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); + this.options.hide = true; + + // Begin the animation + this.custom(this.cur(), 0); + }, + + // Each step of an animation + step: function( gotoEnd ) { + var t = now(), done = true; + + if ( gotoEnd || t >= this.options.duration + this.startTime ) { + this.now = this.end; + this.pos = this.state = 1; + this.update(); + + this.options.curAnim[ this.prop ] = true; + + for ( var i in this.options.curAnim ) { + if ( this.options.curAnim[i] !== true ) { + done = false; + } + } + + if ( done ) { + if ( this.options.display != null ) { + // Reset the overflow + this.elem.style.overflow = this.options.overflow; + + // Reset the display + var old = jQuery.data(this.elem, "olddisplay"); + this.elem.style.display = old ? old : this.options.display; + + if ( jQuery.css(this.elem, "display") === "none" ) { + this.elem.style.display = "block"; + } + } + + // Hide the element if the "hide" operation was done + if ( this.options.hide ) { + jQuery(this.elem).hide(); + } + + // Reset the properties, if the item has been hidden or shown + if ( this.options.hide || this.options.show ) { + for ( var p in this.options.curAnim ) { + jQuery.style(this.elem, p, this.options.orig[p]); + } + } + + // Execute the complete function + this.options.complete.call( this.elem ); + } + + return false; + + } else { + var n = t - this.startTime; + this.state = n / this.options.duration; + + // Perform the easing function, defaults to swing + var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop]; + var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear"); + this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration); + this.now = this.start + ((this.end - this.start) * this.pos); + + // Perform the next step of the animation + this.update(); + } + + return true; + } +}; + +jQuery.extend( jQuery.fx, { + tick: function() { + var timers = jQuery.timers; + + for ( var i = 0; i < timers.length; i++ ) { + if ( !timers[i]() ) { + timers.splice(i--, 1); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + }, + + stop: function() { + clearInterval( timerId ); + timerId = null; + }, + + speeds: { + slow: 600, + fast: 200, + // Default speed + _default: 400 + }, + + step: { + opacity: function( fx ) { + jQuery.style(fx.elem, "opacity", fx.now); + }, + + _default: function( fx ) { + if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { + fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; + } else { + fx.elem[ fx.prop ] = fx.now; + } + } + } +}); + +if ( jQuery.expr && jQuery.expr.filters ) { + jQuery.expr.filters.animated = function( elem ) { + return jQuery.grep(jQuery.timers, function( fn ) { + return elem === fn.elem; + }).length; + }; +} + +function genFx( type, num ) { + var obj = {}; + + jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { + obj[ this ] = type; + }); + + return obj; +} +if ( "getBoundingClientRect" in document.documentElement ) { + jQuery.fn.offset = function( options ) { + var elem = this[0]; + + if ( options ) { + return this.each(function( i ) { + jQuery.offset.setOffset( this, options, i ); + }); + } + + if ( !elem || !elem.ownerDocument ) { + return null; + } + + if ( elem === elem.ownerDocument.body ) { + return jQuery.offset.bodyOffset( elem ); + } + + var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement, + clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, + top = box.top + (self.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop, + left = box.left + (self.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft; + + return { top: top, left: left }; + }; + +} else { + jQuery.fn.offset = function( options ) { + var elem = this[0]; + + if ( options ) { + return this.each(function( i ) { + jQuery.offset.setOffset( this, options, i ); + }); + } + + if ( !elem || !elem.ownerDocument ) { + return null; + } + + if ( elem === elem.ownerDocument.body ) { + return jQuery.offset.bodyOffset( elem ); + } + + jQuery.offset.initialize(); + + var offsetParent = elem.offsetParent, prevOffsetParent = elem, + doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement, + body = doc.body, defaultView = doc.defaultView, + prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, + top = elem.offsetTop, left = elem.offsetLeft; + + while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { + if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { + break; + } + + computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; + top -= elem.scrollTop; + left -= elem.scrollLeft; + + if ( elem === offsetParent ) { + top += elem.offsetTop; + left += elem.offsetLeft; + + if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.nodeName)) ) { + top += parseFloat( computedStyle.borderTopWidth ) || 0; + left += parseFloat( computedStyle.borderLeftWidth ) || 0; + } + + prevOffsetParent = offsetParent, offsetParent = elem.offsetParent; + } + + if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { + top += parseFloat( computedStyle.borderTopWidth ) || 0; + left += parseFloat( computedStyle.borderLeftWidth ) || 0; + } + + prevComputedStyle = computedStyle; + } + + if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { + top += body.offsetTop; + left += body.offsetLeft; + } + + if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { + top += Math.max( docElem.scrollTop, body.scrollTop ); + left += Math.max( docElem.scrollLeft, body.scrollLeft ); + } + + return { top: top, left: left }; + }; +} + +jQuery.offset = { + initialize: function() { + var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.curCSS(body, "marginTop", true) ) || 0, + html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; + + jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); + + container.innerHTML = html; + body.insertBefore( container, body.firstChild ); + innerDiv = container.firstChild; + checkDiv = innerDiv.firstChild; + td = innerDiv.nextSibling.firstChild.firstChild; + + this.doesNotAddBorder = (checkDiv.offsetTop !== 5); + this.doesAddBorderForTableAndCells = (td.offsetTop === 5); + + checkDiv.style.position = "fixed", checkDiv.style.top = "20px"; + // safari subtracts parent border width here which is 5px + this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); + checkDiv.style.position = checkDiv.style.top = ""; + + innerDiv.style.overflow = "hidden", innerDiv.style.position = "relative"; + this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); + + this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); + + body.removeChild( container ); + body = container = innerDiv = checkDiv = table = td = null; + jQuery.offset.initialize = jQuery.noop; + }, + + bodyOffset: function( body ) { + var top = body.offsetTop, left = body.offsetLeft; + + jQuery.offset.initialize(); + + if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) { + top += parseFloat( jQuery.curCSS(body, "marginTop", true) ) || 0; + left += parseFloat( jQuery.curCSS(body, "marginLeft", true) ) || 0; + } + + return { top: top, left: left }; + }, + + setOffset: function( elem, options, i ) { + // set position first, in-case top/left are set even on static elem + if ( /static/.test( jQuery.curCSS( elem, "position" ) ) ) { + elem.style.position = "relative"; + } + var curElem = jQuery( elem ), + curOffset = curElem.offset(), + curTop = parseInt( jQuery.curCSS( elem, "top", true ), 10 ) || 0, + curLeft = parseInt( jQuery.curCSS( elem, "left", true ), 10 ) || 0; + + if ( jQuery.isFunction( options ) ) { + options = options.call( elem, i, curOffset ); + } + + var props = { + top: (options.top - curOffset.top) + curTop, + left: (options.left - curOffset.left) + curLeft + }; + + if ( "using" in options ) { + options.using.call( elem, props ); + } else { + curElem.css( props ); + } + } +}; + + +jQuery.fn.extend({ + position: function() { + if ( !this[0] ) { + return null; + } + + var elem = this[0], + + // Get *real* offsetParent + offsetParent = this.offsetParent(), + + // Get correct offsets + offset = this.offset(), + parentOffset = /^body|html$/i.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); + + // Subtract element margins + // note: when an element has margin: auto the offsetLeft and marginLeft + // are the same in Safari causing offset.left to incorrectly be 0 + offset.top -= parseFloat( jQuery.curCSS(elem, "marginTop", true) ) || 0; + offset.left -= parseFloat( jQuery.curCSS(elem, "marginLeft", true) ) || 0; + + // Add offsetParent borders + parentOffset.top += parseFloat( jQuery.curCSS(offsetParent[0], "borderTopWidth", true) ) || 0; + parentOffset.left += parseFloat( jQuery.curCSS(offsetParent[0], "borderLeftWidth", true) ) || 0; + + // Subtract the two offsets + return { + top: offset.top - parentOffset.top, + left: offset.left - parentOffset.left + }; + }, + + offsetParent: function() { + return this.map(function() { + var offsetParent = this.offsetParent || document.body; + while ( offsetParent && (!/^body|html$/i.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { + offsetParent = offsetParent.offsetParent; + } + return offsetParent; + }); + } +}); + + +// Create scrollLeft and scrollTop methods +jQuery.each( ["Left", "Top"], function( i, name ) { + var method = "scroll" + name; + + jQuery.fn[ method ] = function(val) { + var elem = this[0], win; + + if ( !elem ) { + return null; + } + + if ( val !== undefined ) { + // Set the scroll offset + return this.each(function() { + win = getWindow( this ); + + if ( win ) { + win.scrollTo( + !i ? val : jQuery(win).scrollLeft(), + i ? val : jQuery(win).scrollTop() + ); + + } else { + this[ method ] = val; + } + }); + } else { + win = getWindow( elem ); + + // Return the scroll offset + return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : + jQuery.support.boxModel && win.document.documentElement[ method ] || + win.document.body[ method ] : + elem[ method ]; + } + }; +}); + +function getWindow( elem ) { + return ("scrollTo" in elem && elem.document) ? + elem : + elem.nodeType === 9 ? + elem.defaultView || elem.parentWindow : + false; +} +// Create innerHeight, innerWidth, outerHeight and outerWidth methods +jQuery.each([ "Height", "Width" ], function( i, name ) { + + var type = name.toLowerCase(); + + // innerHeight and innerWidth + jQuery.fn["inner" + name] = function() { + return this[0] ? + jQuery.css( this[0], type, false, "padding" ) : + null; + }; + + // outerHeight and outerWidth + jQuery.fn["outer" + name] = function( margin ) { + return this[0] ? + jQuery.css( this[0], type, false, margin ? "margin" : "border" ) : + null; + }; + + jQuery.fn[ type ] = function( size ) { + // Get window width or height + var elem = this[0]; + if ( !elem ) { + return size == null ? null : this; + } + + if ( jQuery.isFunction( size ) ) { + return this.each(function( i ) { + var self = jQuery( this ); + self[ type ]( size.call( this, i, self[ type ]() ) ); + }); + } + + return ("scrollTo" in elem && elem.document) ? // does it walk and quack like a window? + // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode + elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] || + elem.document.body[ "client" + name ] : + + // Get document width or height + (elem.nodeType === 9) ? // is it a document + // Either scroll[Width/Height] or offset[Width/Height], whichever is greater + Math.max( + elem.documentElement["client" + name], + elem.body["scroll" + name], elem.documentElement["scroll" + name], + elem.body["offset" + name], elem.documentElement["offset" + name] + ) : + + // Get or set width or height on the element + size === undefined ? + // Get width or height on the element + jQuery.css( elem, type ) : + + // Set the width or height on the element (default to pixels if value is unitless) + this.css( type, typeof size === "string" ? size : size + "px" ); + }; + +}); +// Expose jQuery to the global object +window.jQuery = window.$ = jQuery; + +})(window);
philikon/Vanadium
1510046d12ae306080e504789d80ab23c5952159
We need to reinstantiate the plugin every time because the page might have changed and we don't want to hold on to expired DOM objects.
diff --git a/chrome/content/overlay.js b/chrome/content/overlay.js index 425a9ef..c16f84b 100644 --- a/chrome/content/overlay.js +++ b/chrome/content/overlay.js @@ -1,137 +1,136 @@ var Vanadium = { plugins: {}, - activePlugin: null, init: function() { window.removeEventListener("DOMContentLoaded", this, false); this.tabbrowser = document.getElementById('content'); this.tabbrowser.addEventListener('TabSelect', this, false); this.tabbrowser.addEventListener('TabOpen', this, false); this.toolbar = document.getElementById('vanadium-toolbar'); this.toolbar.setAttribute("collapsed", "true"); }, /* Plugin "API" */ register: function(factory, host) { this.plugins[host] = factory; }, - findPlugin: function(uri) { + getPlugin: function() { + var factory = this.plugins[this.tabbrowser.currentURI.host]; + if (factory !== undefined) { + factory = new factory(this.tabbrowser.contentDocument); + } /* This might return undefined, and we're perfectly fine with that. */ - return this.plugins[uri.host]; + return factory; + }, + + havePlugin: function() { + return (this.tabbrowser.currentURI.host in this.plugins); }, /* Event handlers */ handleEvent: function(event) { switch (event.type) { case 'DOMContentLoaded': this.init(); return; case 'TabSelect': this.onTabSelect(event); return; case 'TabOpen': this.onTabOpen(event); return; } }, onTabSelect: function(event) { - var factory = this.findPlugin(this.tabbrowser.currentURI); - if (factory == undefined) { - this.showVanadium(false); - this.activePlugin = null; - return; - } - - this.activePlugin = new factory(this.tabbrowser.contentDocument); - this.showVanadium(true); + this.showVanadium(this.havePlugin()); }, onTabOpen: function(event) { //TODO we should really see what's being loaded and then decide this.showVanadium(false); }, showVanadium: function(show) { var navbar = document.getElementById('nav-bar'); navbar.setAttribute("collapsed", show); this.toolbar.setAttribute("collapsed", !show); //XXX what does this do and is it really necessary? document.persist(this.toolbar.id, 'collapsed'); document.persist(navbar.id, 'collapsed'); }, onSearch: function(query) { - if (!this.activePlugin) { + var plugin = this.getPlugin(); + if (plugin === undefined) { return; } - this.activePlugin.search.value = query; - this.pressEnter(this.activePlugin.search); + plugin.search.value = query; + this.pressEnter(plugin.search); }, onButton: function(buttontype) { - if (!this.activePlugin) { + var plugin = this.getPlugin(); + if (plugin === undefined) { return; } - var toclick = this.activePlugin[buttontype]; + var toclick = plugin[buttontype]; if (toclick === undefined) { return; } this.clickOn(toclick); }, /* Simulate a simple click on an element */ clickOn: function(element) { var event = element.ownerDocument.createEvent('MouseEvent'); event.initMouseEvent( 'click', true, // canBubble true, // cancelable element.ownerDocument.defaultView, // view (e.g. window) 1, // click count 0, 0, 0, 0, // coordinates false, false, false, false, // key modifiers 0, // button null); // target element.dispatchEvent(event); }, /* Simulate pressing the return key on an element */ pressEnter: function(element) { var event = element.ownerDocument.createEvent('KeyboardEvent'); event.initKeyEvent( 'keypress', true, // canBubble true, // cancelable element.ownerDocument.defaultView, // view (e.g. window) false, false, false, false, // key modifiers KeyEvent.DOM_VK_RETURN, // keycode 0); // charCode element.dispatchEvent(event); } }; window.addEventListener("DOMContentLoaded", Vanadium, false); function GMailPlugin(document) { var iframe = document.getElementById('canvas_frame'); /* First link of that class should be 'Inbox' */ this.home = iframe.contentDocument.getElementsByClassName('n0')[0]; /* It's id=":r3" for pre-Buzz GMail (e.g. Google Apps) */ this.compose = iframe.contentDocument.getElementById(':r2'); this.reply = iframe.contentDocument.getElementsByClassName('hE')[0]; /* It's id="rd" for pre-Buzz GMail (e.g. Google Apps) */ this.search = iframe.contentDocument.getElementById(':rc'); - - Components.utils.reportError(this.reply); } Vanadium.register(GMailPlugin, "mail.google.com");
philikon/Vanadium
7ca5f2453b60fb0fd54bcc83b9848242479b3f31
Actually make this pluggable
diff --git a/chrome/content/overlay.js b/chrome/content/overlay.js index 1786811..425a9ef 100644 --- a/chrome/content/overlay.js +++ b/chrome/content/overlay.js @@ -1,123 +1,137 @@ var Vanadium = { + plugins: {}, + activePlugin: null, + init: function() { window.removeEventListener("DOMContentLoaded", this, false); this.tabbrowser = document.getElementById('content'); this.tabbrowser.addEventListener('TabSelect', this, false); this.tabbrowser.addEventListener('TabOpen', this, false); this.toolbar = document.getElementById('vanadium-toolbar'); this.toolbar.setAttribute("collapsed", "true"); }, + /* Plugin "API" */ + + register: function(factory, host) { + this.plugins[host] = factory; + }, + + findPlugin: function(uri) { + /* This might return undefined, and we're perfectly fine with that. */ + return this.plugins[uri.host]; + }, + + /* Event handlers */ + handleEvent: function(event) { switch (event.type) { case 'DOMContentLoaded': this.init(); return; case 'TabSelect': this.onTabSelect(event); return; case 'TabOpen': this.onTabOpen(event); return; } }, - - isAppTab: function(uri) { - return (uri.host == "mail.google.com"); //XXX - }, - + onTabSelect: function(event) { - var uri = event.originalTarget.linkedBrowser.currentURI; - //TODO: only need to do this if we're switching from non-app to app tab - if (this.isAppTab(uri)) { - this.showVanadium(true); - } else { + var factory = this.findPlugin(this.tabbrowser.currentURI); + if (factory == undefined) { this.showVanadium(false); + this.activePlugin = null; + return; } + + this.activePlugin = new factory(this.tabbrowser.contentDocument); + this.showVanadium(true); }, onTabOpen: function(event) { + //TODO we should really see what's being loaded and then decide this.showVanadium(false); }, showVanadium: function(show) { var navbar = document.getElementById('nav-bar'); navbar.setAttribute("collapsed", show); this.toolbar.setAttribute("collapsed", !show); //XXX what does this do and is it really necessary? document.persist(this.toolbar.id, 'collapsed'); document.persist(navbar.id, 'collapsed'); }, onSearch: function(query) { - if (!this.isAppTab(this.tabbrowser.currentURI)) { + if (!this.activePlugin) { return; } - - var plugin = new GMailPlugin(this.tabbrowser.contentDocument); - plugin.search.value = query; - this.pressEnter(plugin.search); + this.activePlugin.search.value = query; + this.pressEnter(this.activePlugin.search); }, onButton: function(buttontype) { - if (!this.isAppTab(this.tabbrowser.currentURI)) { + if (!this.activePlugin) { return; } - - var plugin = new GMailPlugin(this.tabbrowser.contentDocument); - var toclick = plugin[buttontype]; + var toclick = this.activePlugin[buttontype]; if (toclick === undefined) { return; } this.clickOn(toclick); }, /* Simulate a simple click on an element */ clickOn: function(element) { var event = element.ownerDocument.createEvent('MouseEvent'); event.initMouseEvent( 'click', true, // canBubble true, // cancelable element.ownerDocument.defaultView, // view (e.g. window) 1, // click count 0, 0, 0, 0, // coordinates false, false, false, false, // key modifiers 0, // button null); // target element.dispatchEvent(event); }, /* Simulate pressing the return key on an element */ pressEnter: function(element) { var event = element.ownerDocument.createEvent('KeyboardEvent'); event.initKeyEvent( 'keypress', true, // canBubble true, // cancelable element.ownerDocument.defaultView, // view (e.g. window) false, false, false, false, // key modifiers KeyEvent.DOM_VK_RETURN, // keycode 0); // charCode element.dispatchEvent(event); } }; +window.addEventListener("DOMContentLoaded", Vanadium, false); + function GMailPlugin(document) { var iframe = document.getElementById('canvas_frame'); /* First link of that class should be 'Inbox' */ this.home = iframe.contentDocument.getElementsByClassName('n0')[0]; /* It's id=":r3" for pre-Buzz GMail (e.g. Google Apps) */ this.compose = iframe.contentDocument.getElementById(':r2'); this.reply = iframe.contentDocument.getElementsByClassName('hE')[0]; /* It's id="rd" for pre-Buzz GMail (e.g. Google Apps) */ this.search = iframe.contentDocument.getElementById(':rc'); -} -window.addEventListener("DOMContentLoaded", Vanadium, false); + Components.utils.reportError(this.reply); +} +Vanadium.register(GMailPlugin, "mail.google.com");
philikon/Vanadium
6ad2920f98b88e2ac26b8abd021bd0835b42da02
Factor GMail stuff out into "plugin" object
diff --git a/chrome/content/overlay.js b/chrome/content/overlay.js index 4d2843f..1786811 100644 --- a/chrome/content/overlay.js +++ b/chrome/content/overlay.js @@ -1,127 +1,123 @@ var Vanadium = { init: function() { window.removeEventListener("DOMContentLoaded", this, false); this.tabbrowser = document.getElementById('content'); this.tabbrowser.addEventListener('TabSelect', this, false); this.tabbrowser.addEventListener('TabOpen', this, false); this.toolbar = document.getElementById('vanadium-toolbar'); this.toolbar.setAttribute("collapsed", "true"); }, handleEvent: function(event) { switch (event.type) { case 'DOMContentLoaded': this.init(); return; case 'TabSelect': this.onTabSelect(event); return; case 'TabOpen': this.onTabOpen(event); return; } }, isAppTab: function(uri) { return (uri.host == "mail.google.com"); //XXX }, onTabSelect: function(event) { var uri = event.originalTarget.linkedBrowser.currentURI; //TODO: only need to do this if we're switching from non-app to app tab if (this.isAppTab(uri)) { this.showVanadium(true); } else { this.showVanadium(false); } }, onTabOpen: function(event) { this.showVanadium(false); }, showVanadium: function(show) { var navbar = document.getElementById('nav-bar'); navbar.setAttribute("collapsed", show); this.toolbar.setAttribute("collapsed", !show); //XXX what does this do and is it really necessary? document.persist(this.toolbar.id, 'collapsed'); document.persist(navbar.id, 'collapsed'); }, onSearch: function(query) { if (!this.isAppTab(this.tabbrowser.currentURI)) { return; } - var iframe = this.tabbrowser.contentDocument.getElementById('canvas_frame'); - var input = iframe.contentDocument.getElementById(':rd'); - input.value = query; - this.pressEnter(input); + var plugin = new GMailPlugin(this.tabbrowser.contentDocument); + plugin.search.value = query; + this.pressEnter(plugin.search); }, onButton: function(buttontype) { if (!this.isAppTab(this.tabbrowser.currentURI)) { return; } - var iframe = this.tabbrowser.contentDocument.getElementById('canvas_frame'); - var toclick; - switch (buttontype) { - case "home": - /* First link of that class should be 'Inbox' */ - toclick = iframe.contentDocument.getElementsByClassName('n0'); - toclick = toclick[0]; - break; - case "compose": - toclick = iframe.contentDocument.getElementById(':r3'); - break; - case "reply": - toclick = iframe.contentDocument.getElementsByClassName('hE'); - toclick = toclick[0]; - } - + var plugin = new GMailPlugin(this.tabbrowser.contentDocument); + var toclick = plugin[buttontype]; if (toclick === undefined) { return; } - this.clickOn(toclick); }, /* Simulate a simple click on an element */ clickOn: function(element) { var event = element.ownerDocument.createEvent('MouseEvent'); event.initMouseEvent( 'click', true, // canBubble true, // cancelable element.ownerDocument.defaultView, // view (e.g. window) 1, // click count 0, 0, 0, 0, // coordinates false, false, false, false, // key modifiers 0, // button null); // target element.dispatchEvent(event); }, /* Simulate pressing the return key on an element */ pressEnter: function(element) { var event = element.ownerDocument.createEvent('KeyboardEvent'); event.initKeyEvent( 'keypress', true, // canBubble true, // cancelable element.ownerDocument.defaultView, // view (e.g. window) false, false, false, false, // key modifiers KeyEvent.DOM_VK_RETURN, // keycode 0); // charCode element.dispatchEvent(event); } }; +function GMailPlugin(document) { + var iframe = document.getElementById('canvas_frame'); + + /* First link of that class should be 'Inbox' */ + this.home = iframe.contentDocument.getElementsByClassName('n0')[0]; + /* It's id=":r3" for pre-Buzz GMail (e.g. Google Apps) */ + this.compose = iframe.contentDocument.getElementById(':r2'); + this.reply = iframe.contentDocument.getElementsByClassName('hE')[0]; + /* It's id="rd" for pre-Buzz GMail (e.g. Google Apps) */ + this.search = iframe.contentDocument.getElementById(':rc'); +} + window.addEventListener("DOMContentLoaded", Vanadium, false);
philikon/Vanadium
b3b366cb56dd6674b447c374e2d138d3f2d3c1a6
Clean up, refactor, and make sure the vanadium isn't shown when you open a new tab (of course there's a flaw in this if you open an app tab in a new tab...)
diff --git a/chrome/content/overlay.js b/chrome/content/overlay.js index 222e420..4d2843f 100644 --- a/chrome/content/overlay.js +++ b/chrome/content/overlay.js @@ -1,117 +1,127 @@ var Vanadium = { init: function() { window.removeEventListener("DOMContentLoaded", this, false); this.tabbrowser = document.getElementById('content'); this.tabbrowser.addEventListener('TabSelect', this, false); + this.tabbrowser.addEventListener('TabOpen', this, false); this.toolbar = document.getElementById('vanadium-toolbar'); this.toolbar.setAttribute("collapsed", "true"); }, handleEvent: function(event) { switch (event.type) { case 'DOMContentLoaded': this.init(); return; case 'TabSelect': this.onTabSelect(event); return; + case 'TabOpen': + this.onTabOpen(event); + return; } }, isAppTab: function(uri) { return (uri.host == "mail.google.com"); //XXX }, onTabSelect: function(event) { var uri = event.originalTarget.linkedBrowser.currentURI; - var navbar = document.getElementById('nav-bar'); + //TODO: only need to do this if we're switching from non-app to app tab if (this.isAppTab(uri)) { - //TODO: only need to do this if we're switching from non-app to app tab - navbar.setAttribute("collapsed", "true"); - this.toolbar.setAttribute("collapsed", "false"); + this.showVanadium(true); } else { - navbar.setAttribute("collapsed", "false"); - this.toolbar.setAttribute("collapsed", "true"); + this.showVanadium(false); } + }, + + onTabOpen: function(event) { + this.showVanadium(false); + }, + + showVanadium: function(show) { + var navbar = document.getElementById('nav-bar'); + navbar.setAttribute("collapsed", show); + this.toolbar.setAttribute("collapsed", !show); + //XXX what does this do and is it really necessary? document.persist(this.toolbar.id, 'collapsed'); document.persist(navbar.id, 'collapsed'); }, onSearch: function(query) { if (!this.isAppTab(this.tabbrowser.currentURI)) { return; } - Components.utils.reportError(query); var iframe = this.tabbrowser.contentDocument.getElementById('canvas_frame'); var input = iframe.contentDocument.getElementById(':rd'); - Components.utils.reportError(input); input.value = query; this.pressEnter(input); }, onButton: function(buttontype) { if (!this.isAppTab(this.tabbrowser.currentURI)) { return; } var iframe = this.tabbrowser.contentDocument.getElementById('canvas_frame'); var toclick; switch (buttontype) { case "home": /* First link of that class should be 'Inbox' */ toclick = iframe.contentDocument.getElementsByClassName('n0'); toclick = toclick[0]; break; case "compose": toclick = iframe.contentDocument.getElementById(':r3'); break; case "reply": toclick = iframe.contentDocument.getElementsByClassName('hE'); toclick = toclick[0]; } if (toclick === undefined) { return; } this.clickOn(toclick); }, /* Simulate a simple click on an element */ clickOn: function(element) { var event = element.ownerDocument.createEvent('MouseEvent'); event.initMouseEvent( 'click', true, // canBubble true, // cancelable element.ownerDocument.defaultView, // view (e.g. window) 1, // click count 0, 0, 0, 0, // coordinates false, false, false, false, // key modifiers 0, // button null); // target element.dispatchEvent(event); }, /* Simulate pressing the return key on an element */ pressEnter: function(element) { var event = element.ownerDocument.createEvent('KeyboardEvent'); event.initKeyEvent( 'keypress', true, // canBubble true, // cancelable element.ownerDocument.defaultView, // view (e.g. window) false, false, false, false, // key modifiers KeyEvent.DOM_VK_RETURN, // keycode 0); // charCode element.dispatchEvent(event); } }; window.addEventListener("DOMContentLoaded", Vanadium, false);
philikon/Vanadium
da95b06757a3a92f523c9b8a025324182899c878
Be good and remove ourselves as event listener
diff --git a/chrome/content/overlay.js b/chrome/content/overlay.js index 812dcff..222e420 100644 --- a/chrome/content/overlay.js +++ b/chrome/content/overlay.js @@ -1,115 +1,117 @@ var Vanadium = { init: function() { + window.removeEventListener("DOMContentLoaded", this, false); + this.tabbrowser = document.getElementById('content'); this.tabbrowser.addEventListener('TabSelect', this, false); this.toolbar = document.getElementById('vanadium-toolbar'); this.toolbar.setAttribute("collapsed", "true"); }, handleEvent: function(event) { switch (event.type) { case 'DOMContentLoaded': this.init(); return; case 'TabSelect': this.onTabSelect(event); return; } }, isAppTab: function(uri) { return (uri.host == "mail.google.com"); //XXX }, onTabSelect: function(event) { var uri = event.originalTarget.linkedBrowser.currentURI; var navbar = document.getElementById('nav-bar'); if (this.isAppTab(uri)) { //TODO: only need to do this if we're switching from non-app to app tab navbar.setAttribute("collapsed", "true"); this.toolbar.setAttribute("collapsed", "false"); } else { navbar.setAttribute("collapsed", "false"); this.toolbar.setAttribute("collapsed", "true"); } //XXX what does this do and is it really necessary? document.persist(this.toolbar.id, 'collapsed'); document.persist(navbar.id, 'collapsed'); }, onSearch: function(query) { if (!this.isAppTab(this.tabbrowser.currentURI)) { return; } Components.utils.reportError(query); var iframe = this.tabbrowser.contentDocument.getElementById('canvas_frame'); var input = iframe.contentDocument.getElementById(':rd'); Components.utils.reportError(input); input.value = query; this.pressEnter(input); }, onButton: function(buttontype) { if (!this.isAppTab(this.tabbrowser.currentURI)) { return; } var iframe = this.tabbrowser.contentDocument.getElementById('canvas_frame'); var toclick; switch (buttontype) { case "home": /* First link of that class should be 'Inbox' */ toclick = iframe.contentDocument.getElementsByClassName('n0'); toclick = toclick[0]; break; case "compose": toclick = iframe.contentDocument.getElementById(':r3'); break; case "reply": toclick = iframe.contentDocument.getElementsByClassName('hE'); toclick = toclick[0]; } if (toclick === undefined) { return; } this.clickOn(toclick); }, /* Simulate a simple click on an element */ clickOn: function(element) { var event = element.ownerDocument.createEvent('MouseEvent'); event.initMouseEvent( 'click', true, // canBubble true, // cancelable element.ownerDocument.defaultView, // view (e.g. window) 1, // click count 0, 0, 0, 0, // coordinates false, false, false, false, // key modifiers 0, // button null); // target element.dispatchEvent(event); }, /* Simulate pressing the return key on an element */ pressEnter: function(element) { var event = element.ownerDocument.createEvent('KeyboardEvent'); event.initKeyEvent( 'keypress', true, // canBubble true, // cancelable element.ownerDocument.defaultView, // view (e.g. window) false, false, false, false, // key modifiers KeyEvent.DOM_VK_RETURN, // keycode 0); // charCode element.dispatchEvent(event); } }; window.addEventListener("DOMContentLoaded", Vanadium, false);
philikon/Vanadium
64e2db2437fcbd96703f4c36130c5587d787542e
Searching support
diff --git a/chrome/content/ff-overlay.xul b/chrome/content/ff-overlay.xul index a8acc74..fb153d0 100644 --- a/chrome/content/ff-overlay.xul +++ b/chrome/content/ff-overlay.xul @@ -1,45 +1,47 @@ <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="chrome://vanadium/skin/overlay.css" type="text/css"?> <!DOCTYPE overlay SYSTEM "chrome://vanadium/locale/overlay.dtd"> <overlay id="vanadium-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script src="overlay.js" type="application/javascript" /> <stringbundleset id="stringbundleset"> <stringbundle id="vanadium-strings" src="chrome://vanadium/locale/overlay.properties"/> </stringbundleset> <toolbox id="navigator-toolbox"> <!-- Trick: empty toolbarname means it's not listed in 'View' menu --> <toolbar class="chromeclass-toolbar" toolbarname="" customizable="true" id="vanadium-toolbar"> <toolbarbutton id="vanadium-button-home" label="&vanadium.button.home.label;" tooltiptext="&vanadium.button.home.tooltip;" oncommand="Vanadium.onButton('home')"/> <toolbarbutton id="vanadium-button-compose" label="&vanadium.button.compose.label;" tooltiptext="&vanadium.button.compose.tooltip;" oncommand="Vanadium.onButton('compose')"/> <toolbarbutton id="vanadium-button-reply" label="&vanadium.button.reply.label;" tooltiptext="&vanadium.button.reply.tooltip;" oncommand="Vanadium.onButton('reply')"/> <toolbaritem id="vanadium-searchbar-container" title="&vanadium.searchbar.label;" persist="width"> - <textbox id="vanadium-searchbar" /> + <textbox id="vanadium-searchbar" + searchbutton="true" + onchange="Vanadium.onSearch(this.value)" /> </toolbaritem> </toolbar> </toolbox> </overlay> diff --git a/chrome/content/overlay.js b/chrome/content/overlay.js index fa910c1..812dcff 100644 --- a/chrome/content/overlay.js +++ b/chrome/content/overlay.js @@ -1,83 +1,115 @@ var Vanadium = { init: function() { this.tabbrowser = document.getElementById('content'); this.tabbrowser.addEventListener('TabSelect', this, false); this.toolbar = document.getElementById('vanadium-toolbar'); this.toolbar.setAttribute("collapsed", "true"); }, handleEvent: function(event) { switch (event.type) { case 'DOMContentLoaded': this.init(); return; case 'TabSelect': this.onTabSelect(event); return; } }, isAppTab: function(uri) { return (uri.host == "mail.google.com"); //XXX }, onTabSelect: function(event) { var uri = event.originalTarget.linkedBrowser.currentURI; var navbar = document.getElementById('nav-bar'); if (this.isAppTab(uri)) { //TODO: only need to do this if we're switching from non-app to app tab navbar.setAttribute("collapsed", "true"); this.toolbar.setAttribute("collapsed", "false"); } else { navbar.setAttribute("collapsed", "false"); this.toolbar.setAttribute("collapsed", "true"); } //XXX what does this do and is it really necessary? document.persist(this.toolbar.id, 'collapsed'); document.persist(navbar.id, 'collapsed'); }, + onSearch: function(query) { + if (!this.isAppTab(this.tabbrowser.currentURI)) { + return; + } + Components.utils.reportError(query); + + var iframe = this.tabbrowser.contentDocument.getElementById('canvas_frame'); + var input = iframe.contentDocument.getElementById(':rd'); + Components.utils.reportError(input); + input.value = query; + this.pressEnter(input); + }, + onButton: function(buttontype) { if (!this.isAppTab(this.tabbrowser.currentURI)) { return; } var iframe = this.tabbrowser.contentDocument.getElementById('canvas_frame'); var toclick; switch (buttontype) { case "home": /* First link of that class should be 'Inbox' */ toclick = iframe.contentDocument.getElementsByClassName('n0'); toclick = toclick[0]; break; case "compose": toclick = iframe.contentDocument.getElementById(':r3'); break; case "reply": toclick = iframe.contentDocument.getElementsByClassName('hE'); toclick = toclick[0]; } if (toclick === undefined) { return; } - var event = iframe.contentDocument.createEvent('MouseEvents'); + this.clickOn(toclick); + }, + + /* Simulate a simple click on an element */ + clickOn: function(element) { + var event = element.ownerDocument.createEvent('MouseEvent'); event.initMouseEvent( 'click', true, // canBubble true, // cancelable - iframe.contentDocument.defaultView, // view (e.g. window) + element.ownerDocument.defaultView, // view (e.g. window) 1, // click count 0, 0, 0, 0, // coordinates false, false, false, false, // key modifiers 0, // button null); // target - toclick.dispatchEvent(event); + element.dispatchEvent(event); }, + /* Simulate pressing the return key on an element */ + pressEnter: function(element) { + var event = element.ownerDocument.createEvent('KeyboardEvent'); + event.initKeyEvent( + 'keypress', + true, // canBubble + true, // cancelable + element.ownerDocument.defaultView, // view (e.g. window) + false, false, false, false, // key modifiers + KeyEvent.DOM_VK_RETURN, // keycode + 0); // charCode + element.dispatchEvent(event); + } + }; window.addEventListener("DOMContentLoaded", Vanadium, false);
philikon/Vanadium
0707b4c974d43a66c026fb8075e1b14a3e776eec
Home button
diff --git a/chrome/content/ff-overlay.xul b/chrome/content/ff-overlay.xul index 53fbe01..a8acc74 100644 --- a/chrome/content/ff-overlay.xul +++ b/chrome/content/ff-overlay.xul @@ -1,40 +1,45 @@ <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="chrome://vanadium/skin/overlay.css" type="text/css"?> <!DOCTYPE overlay SYSTEM "chrome://vanadium/locale/overlay.dtd"> <overlay id="vanadium-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script src="overlay.js" type="application/javascript" /> <stringbundleset id="stringbundleset"> <stringbundle id="vanadium-strings" src="chrome://vanadium/locale/overlay.properties"/> </stringbundleset> <toolbox id="navigator-toolbox"> <!-- Trick: empty toolbarname means it's not listed in 'View' menu --> <toolbar class="chromeclass-toolbar" toolbarname="" customizable="true" id="vanadium-toolbar"> + <toolbarbutton id="vanadium-button-home" + label="&vanadium.button.home.label;" + tooltiptext="&vanadium.button.home.tooltip;" + oncommand="Vanadium.onButton('home')"/> + <toolbarbutton id="vanadium-button-compose" label="&vanadium.button.compose.label;" tooltiptext="&vanadium.button.compose.tooltip;" oncommand="Vanadium.onButton('compose')"/> <toolbarbutton id="vanadium-button-reply" label="&vanadium.button.reply.label;" tooltiptext="&vanadium.button.reply.tooltip;" oncommand="Vanadium.onButton('reply')"/> <toolbaritem id="vanadium-searchbar-container" title="&vanadium.searchbar.label;" persist="width"> <textbox id="vanadium-searchbar" /> </toolbaritem> </toolbar> </toolbox> </overlay> diff --git a/chrome/content/overlay.js b/chrome/content/overlay.js index fc9f591..fa910c1 100644 --- a/chrome/content/overlay.js +++ b/chrome/content/overlay.js @@ -1,74 +1,83 @@ var Vanadium = { init: function() { this.tabbrowser = document.getElementById('content'); this.tabbrowser.addEventListener('TabSelect', this, false); this.toolbar = document.getElementById('vanadium-toolbar'); this.toolbar.setAttribute("collapsed", "true"); }, handleEvent: function(event) { switch (event.type) { case 'DOMContentLoaded': this.init(); return; case 'TabSelect': this.onTabSelect(event); return; } }, isAppTab: function(uri) { return (uri.host == "mail.google.com"); //XXX }, onTabSelect: function(event) { var uri = event.originalTarget.linkedBrowser.currentURI; var navbar = document.getElementById('nav-bar'); if (this.isAppTab(uri)) { //TODO: only need to do this if we're switching from non-app to app tab navbar.setAttribute("collapsed", "true"); this.toolbar.setAttribute("collapsed", "false"); } else { navbar.setAttribute("collapsed", "false"); this.toolbar.setAttribute("collapsed", "true"); } //XXX what does this do and is it really necessary? document.persist(this.toolbar.id, 'collapsed'); document.persist(navbar.id, 'collapsed'); }, onButton: function(buttontype) { if (!this.isAppTab(this.tabbrowser.currentURI)) { return; } var iframe = this.tabbrowser.contentDocument.getElementById('canvas_frame'); var toclick; switch (buttontype) { + case "home": + /* First link of that class should be 'Inbox' */ + toclick = iframe.contentDocument.getElementsByClassName('n0'); + toclick = toclick[0]; + break; case "compose": toclick = iframe.contentDocument.getElementById(':r3'); break; case "reply": toclick = iframe.contentDocument.getElementsByClassName('hE'); toclick = toclick[0]; } + if (toclick === undefined) { + return; + } + var event = iframe.contentDocument.createEvent('MouseEvents'); event.initMouseEvent( 'click', true, // canBubble true, // cancelable iframe.contentDocument.defaultView, // view (e.g. window) 1, // click count 0, 0, 0, 0, // coordinates false, false, false, false, // key modifiers 0, // button null); // target toclick.dispatchEvent(event); }, }; window.addEventListener("DOMContentLoaded", Vanadium, false); diff --git a/chrome/locale/en-US/overlay.dtd b/chrome/locale/en-US/overlay.dtd index 0dcdeab..e57e218 100644 --- a/chrome/locale/en-US/overlay.dtd +++ b/chrome/locale/en-US/overlay.dtd @@ -1,5 +1,7 @@ +<!ENTITY vanadium.button.home.label "Home"> +<!ENTITY vanadium.button.home.tooltip "Go to the main view"> <!ENTITY vanadium.button.compose.label "Compose"> <!ENTITY vanadium.button.compose.tooltip "Compose new message"> <!ENTITY vanadium.button.reply.label "Reply"> <!ENTITY vanadium.button.reply.tooltip "Reply to this message"> <!ENTITY vanadium.searchbar.label "Search">
philikon/Vanadium
3fe481042d4adbfd7be2fd457bea046893e4092d
Mission statement, disguised as README
diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..9aead3e --- /dev/null +++ b/README.txt @@ -0,0 +1,12 @@ +Vanadium, n: metallic element used to strengthen steel alloys +============================================================= + +Like a wrench from your toolbox, a browser UI basically is made from +two parts: the web page they're displaying (the steel) and the UI +around that (the chrome coating) to make it look shiny. Thing is, +good tools are made not from steel alone but from a stronger alloy of +steel and vanadium. + +This extension improves the Firefox UI in a similar way by blending +some of the web app's UI into the Firefox UI, thereby adding an extra +element to the steel and chrome mix.
philikon/Vanadium
eda9e0c6546cf32da19c2b7230055d85929f06cf
Compose and reply buttons for GMail
diff --git a/chrome/content/ff-overlay.xul b/chrome/content/ff-overlay.xul index 8250f2a..53fbe01 100644 --- a/chrome/content/ff-overlay.xul +++ b/chrome/content/ff-overlay.xul @@ -1,29 +1,40 @@ <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="chrome://vanadium/skin/overlay.css" type="text/css"?> <!DOCTYPE overlay SYSTEM "chrome://vanadium/locale/overlay.dtd"> <overlay id="vanadium-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script src="overlay.js" type="application/javascript" /> <stringbundleset id="stringbundleset"> <stringbundle id="vanadium-strings" src="chrome://vanadium/locale/overlay.properties"/> </stringbundleset> <toolbox id="navigator-toolbox"> + <!-- Trick: empty toolbarname means it's not listed in 'View' menu --> <toolbar class="chromeclass-toolbar" - toolbarname="&vanadiumToolbar.name;" + toolbarname="" customizable="true" id="vanadium-toolbar"> - <label value="&vanadiumToolbar.label;"/> - <toolbarbutton id="vanadium-toolbar-button" - class="toolbarbutton-1 chromeclass-toolbar-additional" - label="&vanadiumToolbarButton.label;" - tooltiptext="&vanadiumToolbarButton.tooltip;" - oncommand="vanadium.onToolbarButtonCommand()"/> + <toolbarbutton id="vanadium-button-compose" + label="&vanadium.button.compose.label;" + tooltiptext="&vanadium.button.compose.tooltip;" + oncommand="Vanadium.onButton('compose')"/> + + <toolbarbutton id="vanadium-button-reply" + label="&vanadium.button.reply.label;" + tooltiptext="&vanadium.button.reply.tooltip;" + oncommand="Vanadium.onButton('reply')"/> + + <toolbaritem id="vanadium-searchbar-container" + title="&vanadium.searchbar.label;" + persist="width"> + <textbox id="vanadium-searchbar" /> + </toolbaritem> + </toolbar> </toolbox> </overlay> diff --git a/chrome/content/overlay.js b/chrome/content/overlay.js index fe50634..fc9f591 100644 --- a/chrome/content/overlay.js +++ b/chrome/content/overlay.js @@ -1,37 +1,74 @@ var Vanadium = { init: function() { - var tabbrowser = document.getElementById('content'); - tabbrowser.addEventListener('TabSelect', this, false); + this.tabbrowser = document.getElementById('content'); + this.tabbrowser.addEventListener('TabSelect', this, false); this.toolbar = document.getElementById('vanadium-toolbar'); this.toolbar.setAttribute("collapsed", "true"); }, handleEvent: function(event) { switch (event.type) { case 'DOMContentLoaded': this.init(); return; case 'TabSelect': - Components.utils.reportError("tab select!"); this.onTabSelect(event); return; } }, + isAppTab: function(uri) { + return (uri.host == "mail.google.com"); //XXX + }, + onTabSelect: function(event) { var uri = event.originalTarget.linkedBrowser.currentURI; var navbar = document.getElementById('nav-bar'); - var vanadiumbar = document.getElementById('vanadium-toolbar'); - if (uri.host == "mail.google.com") { + if (this.isAppTab(uri)) { + //TODO: only need to do this if we're switching from non-app to app tab navbar.setAttribute("collapsed", "true"); this.toolbar.setAttribute("collapsed", "false"); } else { navbar.setAttribute("collapsed", "false"); this.toolbar.setAttribute("collapsed", "true"); } + //XXX what does this do and is it really necessary? + document.persist(this.toolbar.id, 'collapsed'); + document.persist(navbar.id, 'collapsed'); + }, + + onButton: function(buttontype) { + if (!this.isAppTab(this.tabbrowser.currentURI)) { + return; + } + + var iframe = this.tabbrowser.contentDocument.getElementById('canvas_frame'); + var toclick; + switch (buttontype) { + case "compose": + toclick = iframe.contentDocument.getElementById(':r3'); + break; + case "reply": + toclick = iframe.contentDocument.getElementsByClassName('hE'); + toclick = toclick[0]; + } + + var event = iframe.contentDocument.createEvent('MouseEvents'); + event.initMouseEvent( + 'click', + true, // canBubble + true, // cancelable + iframe.contentDocument.defaultView, // view (e.g. window) + 1, // click count + 0, 0, 0, 0, // coordinates + false, false, false, false, // key modifiers + 0, // button + null); // target + toclick.dispatchEvent(event); }, + }; window.addEventListener("DOMContentLoaded", Vanadium, false); diff --git a/chrome/locale/en-US/overlay.dtd b/chrome/locale/en-US/overlay.dtd index 3bc5c91..0dcdeab 100644 --- a/chrome/locale/en-US/overlay.dtd +++ b/chrome/locale/en-US/overlay.dtd @@ -1,8 +1,5 @@ -<!ENTITY vanadium.label "Your localized menuitem"> -<!ENTITY vanadiumContext.label "Your Menuitem"> -<!ENTITY vanadiumContext.accesskey "Y"> -<!ENTITY vanadiumToolbarButton.label "Your Toolbar Button"> -<!ENTITY vanadiumToolbarButton.tooltip "This is your toolbar button!"> -<!ENTITY vanadiumSidebar.label "Your Sidebar"> -<!ENTITY vanadiumToolbar.name "example"> -<!ENTITY vanadiumToolbar.label "This is an example toolbar. You can hide it under View &gt; toolbars &gt; &vanadiumToolbar.name;"> +<!ENTITY vanadium.button.compose.label "Compose"> +<!ENTITY vanadium.button.compose.tooltip "Compose new message"> +<!ENTITY vanadium.button.reply.label "Reply"> +<!ENTITY vanadium.button.reply.tooltip "Reply to this message"> +<!ENTITY vanadium.searchbar.label "Search">
philikon/Vanadium
e98d4583c2a3dbb110a0b65dcf4dbdac85e775be
Cute icon :)
diff --git a/icon.png b/icon.png new file mode 100644 index 0000000..c9f0db8 Binary files /dev/null and b/icon.png differ
philikon/Vanadium
56fbe14ed59ec1dcbec9507cb62b4bff6867efda
Going to an "app tab" (gmail for now) toggles between navbar and vanadium toolbar
diff --git a/chrome/content/ff-overlay.js b/chrome/content/ff-overlay.js deleted file mode 100644 index 6da48f9..0000000 --- a/chrome/content/ff-overlay.js +++ /dev/null @@ -1,11 +0,0 @@ -vanadium.onFirefoxLoad = function(event) { - document.getElementById("contentAreaContextMenu") - .addEventListener("popupshowing", function (e){ vanadium.showFirefoxContextMenu(e); }, false); -}; - -vanadium.showFirefoxContextMenu = function(event) { - // show or hide the menuitem based on what the context menu is on - document.getElementById("context-vanadium").hidden = gContextMenu.onImage; -}; - -window.addEventListener("load", vanadium.onFirefoxLoad, false); diff --git a/chrome/content/ff-overlay.xul b/chrome/content/ff-overlay.xul index b6cfdee..8250f2a 100644 --- a/chrome/content/ff-overlay.xul +++ b/chrome/content/ff-overlay.xul @@ -1,25 +1,29 @@ <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="chrome://vanadium/skin/overlay.css" type="text/css"?> <!DOCTYPE overlay SYSTEM "chrome://vanadium/locale/overlay.dtd"> -<overlay id="vanadium-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> - <script src="overlay.js"/> - <script src="ff-overlay.js"/> +<overlay id="vanadium-overlay" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + + <script src="overlay.js" type="application/javascript" /> <stringbundleset id="stringbundleset"> - <stringbundle id="vanadium-strings" src="chrome://vanadium/locale/overlay.properties"/> + <stringbundle id="vanadium-strings" + src="chrome://vanadium/locale/overlay.properties"/> </stringbundleset> - <toolbarpalette id="BrowserToolbarPalette"> - <toolbarbutton id="vanadium-toolbar-button" class="toolbarbutton-1 chromeclass-toolbar-additional" - label="&vanadiumToolbarButton.label;" tooltiptext="&vanadiumToolbarButton.tooltip;" - oncommand="vanadium.onToolbarButtonCommand()"/> - </toolbarpalette> - <toolbox id="navigator-toolbox"> - <toolbar class="chromeclass-toolbar" toolbarname="&vanadiumToolbar.name;" customizable="true" id="vanadium-toolbar"> + <toolbar class="chromeclass-toolbar" + toolbarname="&vanadiumToolbar.name;" + customizable="true" + id="vanadium-toolbar"> <label value="&vanadiumToolbar.label;"/> + + <toolbarbutton id="vanadium-toolbar-button" + class="toolbarbutton-1 chromeclass-toolbar-additional" + label="&vanadiumToolbarButton.label;" + tooltiptext="&vanadiumToolbarButton.tooltip;" + oncommand="vanadium.onToolbarButtonCommand()"/> </toolbar> </toolbox> - </overlay> diff --git a/chrome/content/overlay.js b/chrome/content/overlay.js index 0477c36..fe50634 100644 --- a/chrome/content/overlay.js +++ b/chrome/content/overlay.js @@ -1,21 +1,37 @@ -var vanadium = { - onLoad: function() { - // initialization code - this.initialized = true; - this.strings = document.getElementById("vanadium-strings"); - }, +var Vanadium = { - onMenuItemCommand: function(e) { - var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] - .getService(Components.interfaces.nsIPromptService); - promptService.alert(window, this.strings.getString("helloMessageTitle"), - this.strings.getString("helloMessage")); - }, + init: function() { + var tabbrowser = document.getElementById('content'); + tabbrowser.addEventListener('TabSelect', this, false); - onToolbarButtonCommand: function(e) { - // just reuse the function above. you can change this, obviously! - vanadium.onMenuItemCommand(e); - } + this.toolbar = document.getElementById('vanadium-toolbar'); + this.toolbar.setAttribute("collapsed", "true"); + }, + + handleEvent: function(event) { + switch (event.type) { + case 'DOMContentLoaded': + this.init(); + return; + case 'TabSelect': + Components.utils.reportError("tab select!"); + this.onTabSelect(event); + return; + } + }, + + onTabSelect: function(event) { + var uri = event.originalTarget.linkedBrowser.currentURI; + var navbar = document.getElementById('nav-bar'); + var vanadiumbar = document.getElementById('vanadium-toolbar'); + if (uri.host == "mail.google.com") { + navbar.setAttribute("collapsed", "true"); + this.toolbar.setAttribute("collapsed", "false"); + } else { + navbar.setAttribute("collapsed", "false"); + this.toolbar.setAttribute("collapsed", "true"); + } + }, }; -window.addEventListener("load", vanadium.onLoad, false); +window.addEventListener("DOMContentLoaded", Vanadium, false);
philikon/Vanadium
861093e78b3d8058f2a5040ed116a80261f8dad1
What the add-on builder spat out
diff --git a/chrome.manifest b/chrome.manifest new file mode 100644 index 0000000..6eab0ee --- /dev/null +++ b/chrome.manifest @@ -0,0 +1,7 @@ +content vanadium chrome/content/ +skin vanadium classic/1.0 chrome/skin/ +locale vanadium en-US chrome/locale/en-US/ + + +overlay chrome://browser/content/browser.xul chrome://vanadium/content/ff-overlay.xul +style chrome://global/content/customizeToolbar.xul chrome://vanadium/skin/overlay.css diff --git a/chrome/content/ff-overlay.js b/chrome/content/ff-overlay.js new file mode 100644 index 0000000..6da48f9 --- /dev/null +++ b/chrome/content/ff-overlay.js @@ -0,0 +1,11 @@ +vanadium.onFirefoxLoad = function(event) { + document.getElementById("contentAreaContextMenu") + .addEventListener("popupshowing", function (e){ vanadium.showFirefoxContextMenu(e); }, false); +}; + +vanadium.showFirefoxContextMenu = function(event) { + // show or hide the menuitem based on what the context menu is on + document.getElementById("context-vanadium").hidden = gContextMenu.onImage; +}; + +window.addEventListener("load", vanadium.onFirefoxLoad, false); diff --git a/chrome/content/ff-overlay.xul b/chrome/content/ff-overlay.xul new file mode 100644 index 0000000..b6cfdee --- /dev/null +++ b/chrome/content/ff-overlay.xul @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<?xml-stylesheet href="chrome://vanadium/skin/overlay.css" type="text/css"?> +<!DOCTYPE overlay SYSTEM "chrome://vanadium/locale/overlay.dtd"> +<overlay id="vanadium-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script src="overlay.js"/> + <script src="ff-overlay.js"/> + + <stringbundleset id="stringbundleset"> + <stringbundle id="vanadium-strings" src="chrome://vanadium/locale/overlay.properties"/> + </stringbundleset> + + <toolbarpalette id="BrowserToolbarPalette"> + <toolbarbutton id="vanadium-toolbar-button" class="toolbarbutton-1 chromeclass-toolbar-additional" + label="&vanadiumToolbarButton.label;" tooltiptext="&vanadiumToolbarButton.tooltip;" + oncommand="vanadium.onToolbarButtonCommand()"/> + </toolbarpalette> + + <toolbox id="navigator-toolbox"> + <toolbar class="chromeclass-toolbar" toolbarname="&vanadiumToolbar.name;" customizable="true" id="vanadium-toolbar"> + <label value="&vanadiumToolbar.label;"/> + </toolbar> + </toolbox> + + +</overlay> diff --git a/chrome/content/options.xul b/chrome/content/options.xul new file mode 100644 index 0000000..66552de --- /dev/null +++ b/chrome/content/options.xul @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<?xml-stylesheet href="chrome://global/skin/" type="text/css"?> +<!DOCTYPE prefwindow SYSTEM "chrome://vanadium/locale/options.dtd"> +<prefwindow id="vanadium-preferences" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" title="&prefwindow.title;"> + <prefpane id="pane1" label="&pane1.title;"> + <preferences> + <preference id="boolpref1" name="extensions.vanadium.boolpref" type="bool"/> + <preference id="intpref1" name="extensions.vanadium.intpref" type="int"/> + <preference id="stringpref1" name="extensions.vanadium.stringpref" type="string"/> <!-- note that this is only an ASCII string - use unichar for unicode strings --> + </preferences> + <checkbox id="checkboolpref" preference="boolpref1" label="&checkboolpref.label;" accesskey="&checkboolpref.accesskey;"/> + <label accesskey="&intpref.accesskey;" control="textintpref">&intpref.label;</label><textbox id="textintpref" preference="intpref1"/> + <label accesskey="&stringpref.accesskey;" control="textstringpref">&stringpref.label;</label><textbox id="textstringpref" preference="stringpref1"/> + </prefpane> +</prefwindow> diff --git a/chrome/content/overlay.js b/chrome/content/overlay.js new file mode 100644 index 0000000..0477c36 --- /dev/null +++ b/chrome/content/overlay.js @@ -0,0 +1,21 @@ +var vanadium = { + onLoad: function() { + // initialization code + this.initialized = true; + this.strings = document.getElementById("vanadium-strings"); + }, + + onMenuItemCommand: function(e) { + var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] + .getService(Components.interfaces.nsIPromptService); + promptService.alert(window, this.strings.getString("helloMessageTitle"), + this.strings.getString("helloMessage")); + }, + + onToolbarButtonCommand: function(e) { + // just reuse the function above. you can change this, obviously! + vanadium.onMenuItemCommand(e); + } +}; + +window.addEventListener("load", vanadium.onLoad, false); diff --git a/chrome/locale/en-US/options.dtd b/chrome/locale/en-US/options.dtd new file mode 100644 index 0000000..052def2 --- /dev/null +++ b/chrome/locale/en-US/options.dtd @@ -0,0 +1,8 @@ +<!ENTITY prefwindow.title "Vanadium preferences"> +<!ENTITY pane1.title "Vanadium preferences"> +<!ENTITY checkboolpref.label "A Boolean Preference"> +<!ENTITY checkboolpref.accesskey "B"> +<!ENTITY intpref.label "An Integer Preference"> +<!ENTITY intpref.accesskey "I"> +<!ENTITY stringpref.label "A String Preference"> +<!ENTITY stringpref.accesskey "S"> diff --git a/chrome/locale/en-US/overlay.dtd b/chrome/locale/en-US/overlay.dtd new file mode 100644 index 0000000..3bc5c91 --- /dev/null +++ b/chrome/locale/en-US/overlay.dtd @@ -0,0 +1,8 @@ +<!ENTITY vanadium.label "Your localized menuitem"> +<!ENTITY vanadiumContext.label "Your Menuitem"> +<!ENTITY vanadiumContext.accesskey "Y"> +<!ENTITY vanadiumToolbarButton.label "Your Toolbar Button"> +<!ENTITY vanadiumToolbarButton.tooltip "This is your toolbar button!"> +<!ENTITY vanadiumSidebar.label "Your Sidebar"> +<!ENTITY vanadiumToolbar.name "example"> +<!ENTITY vanadiumToolbar.label "This is an example toolbar. You can hide it under View &gt; toolbars &gt; &vanadiumToolbar.name;"> diff --git a/chrome/locale/en-US/overlay.properties b/chrome/locale/en-US/overlay.properties new file mode 100644 index 0000000..f1ff377 --- /dev/null +++ b/chrome/locale/en-US/overlay.properties @@ -0,0 +1,4 @@ +helloMessage=Hello World! +helloMessageTitle=Hello +prefMessage=Int Pref Value: %d [email protected]=description diff --git a/chrome/skin/overlay.css b/chrome/skin/overlay.css new file mode 100644 index 0000000..2342511 --- /dev/null +++ b/chrome/skin/overlay.css @@ -0,0 +1,22 @@ +/* This is just an example. You shouldn't do this. */ +#vanadium-hello +{ + color: red ! important; +} +#vanadium-toolbar-button +{ + list-style-image: url("chrome://vanadium/skin/toolbar-button.png"); + -moz-image-region: rect(0px 24px 24px 0px); +} +#vanadium-toolbar-button:hover +{ + -moz-image-region: rect(24px 24px 48px 0px); +} +[iconsize="small"] #vanadium-toolbar-button +{ + -moz-image-region: rect( 0px 40px 16px 24px); +} +[iconsize="small"] #vanadium-toolbar-button:hover +{ + -moz-image-region: rect(24px 40px 40px 24px); +} diff --git a/chrome/skin/toolbar-button.png b/chrome/skin/toolbar-button.png new file mode 100644 index 0000000..45d6044 Binary files /dev/null and b/chrome/skin/toolbar-button.png differ diff --git a/defaults/preferences/prefs.js b/defaults/preferences/prefs.js new file mode 100644 index 0000000..4ba5f3b --- /dev/null +++ b/defaults/preferences/prefs.js @@ -0,0 +1,6 @@ +pref("extensions.vanadium.boolpref", false); +pref("extensions.vanadium.intpref", 0); +pref("extensions.vanadium.stringpref", "A string"); + +// https://developer.mozilla.org/en/Localizing_extension_descriptions +pref("[email protected]", "chrome://vanadium/locale/overlay.properties"); diff --git a/install.rdf b/install.rdf new file mode 100644 index 0000000..bec3046 --- /dev/null +++ b/install.rdf @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> + <Description about="urn:mozilla:install-manifest"> + <em:id>[email protected]</em:id> + <em:type>2</em:type> + <em:name>Vanadium</em:name> + <em:version>1.0</em:version> + <em:creator>Philipp von Weitershausen</em:creator> + <em:contributor></em:contributor> + <em:optionsURL>chrome://vanadium/content/options.xul</em:optionsURL> + <em:targetApplication> + <Description> + <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <!-- Firefox --> + <em:minVersion>3.6</em:minVersion> + <em:maxVersion>3.6.*</em:maxVersion> + </Description> + </em:targetApplication> + </Description> +</RDF>
Agriculture/LogicInterpreter
d1f5578542a5d72186f794e2a2d9365870330aaf
cut out the transformation into binary -> now fast enough to solve wumpus
diff --git a/src/MyInterpreter.java b/src/MyInterpreter.java index 0208bed..ac152bc 100644 --- a/src/MyInterpreter.java +++ b/src/MyInterpreter.java @@ -1,770 +1,770 @@ import logicinterpreter.base.*; import logicinterpreter.cnf.*; import logicinterpreter.expressions.*; import java.util.*; public class MyInterpreter implements IInterpreter { private Expression expression; //Bereitstellen der sowieso nötigen Umwandlung in konjunktive //Normalform public CnfExpression toCnf(Expression expression) { //Expression ist die Basisklasse für viele mögliche Ausdrücke: Konstanten, Symbole, Und-verknüpfte Ausdrücke, ... //welche davon gemeint ist, erfährt man über getTyp() //Die Expression kann man dann in die entsprechende Klasse casten, um ihre Details auszulesen //und sie in KNF umwandeln zu können: //if(expression.getTyp()==Expression.Typ.CONSTANT) //{ // ConstExpression ce=(ConstExpression) expression; // boolean val=ce.getValue(); // return makeKNFFromConst(val); //} //Die konjunktive Normalform ist wie folgt repräsentiert: //->Auf oberster Ebene gibt es die CnfExpression // ->diese beinhaltet eine Liste von Clause-Objekten (d.h. konjunktiv verknüpfte Klauseln) // ->jede Klausel beinhaltet eine List von Term-Objekten (d.h. disjunktiv verknüpfte Terme) // -> ein Term ist eine boolsche Variable, die negiert sein kann, also bspw. "A" oder "~B" //Zusammengesetzt wird das folgendermassen: //Term a=new Term("A",false); //nicht negiert //Term nicht_b=new Term("B",true); //negiert //ArrayList<Term> terme=new ArrayList<Term>(); //terme.add(a); //terme.add(nicht_b); //Clause clause=new Clause(terme); //A,~B. //ArrayList<Clause> clauses=new ArrayList<Clause>(): //clauses.add(clause); //return new CnfExpression(clauses); //KNF hat nur eine Klausel: A,~B. //**************************************** //Student begin this.expression = expression; System.out.println("start\n"+this.expression); eliminateImpEquXor(); System.out.println("eliminate implications equivalence xor \n"+this.expression); deMorganNot(); System.out.println("deMorgan and Not: \n"+this.expression); - onlyBinaryFunctions(); - System.out.println("only binary:\n"+this.expression); +// onlyBinaryFunctions(); +// System.out.println("only binary:\n"+this.expression); surround(); System.out.println("surround:\n"+this.expression); transform(); System.out.println("toCNF:\n"+this.expression); ArrayList<Clause> cnf = makeResult(); System.out.println("result:\n"+cnf); return new CnfExpression(cnf); // return new CnfExpression(new ArrayList<Clause>()); //Student end //**************************************** } //Lösbarkeit des logischen Ausdrucks prüfen, falls nicht lösbar //null zurückgeben, sonst Symbolbelegung, die den Ausdruck gültig macht public HashMap<String,Boolean> getSolution(CnfExpression exprCnf) { // Es gibt 3 Möglichkeiten für diese Expression: // a) Tautologie, d.h. jede Variablenbelegung macht sie gültig // -> return new HashMap<String,Boolean>(); // b) nicht erfüllbar: // -> return null; // c) eine bestimmte Variablenbelegung macht die Aussage wahr: // -> bei der Symbolbelegung ist der Key der Name der zu belegenden Variable // und der Wert die Belegung // D.h. bei der CnfExpression "A,~B." würde die Belegung von A mit true // den Ausdruck wahr machen. Eine Lösung wäre also bspw.: // HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); // belegung.put("A",true); // return belegung; //**************************************** //Student begin List<String> symbols = collectVariables(exprCnf); HashMap<String, Boolean> result = DPLL(exprCnf, symbols, new HashMap<String, Boolean>()); return result; //Student end //**************************************** } private HashMap<String, Boolean> DPLL(CnfExpression cnf, List<String> symbols, HashMap<String, Boolean> hashMap) { if(cnf.getClauses().isEmpty()){ // empty Conjunction // so every mapping make it true return new HashMap<String, Boolean>(); } for(Clause clause : cnf.getClauses()){ if(clause.getTerms().isEmpty()){ // an empty clause // no way there is a mapping to make it true return null; } } Boolean allLiteralsMapped = true; for(Clause clause : cnf.getClauses()){ Boolean satisfyClause = null; for(Term literal : clause.getTerms()){ Boolean map = hashMap.get(literal.getName()); if(map != null){ if(!literal.isNegated() == map){ satisfyClause = true; } else { satisfyClause = false; } } if(map == null){ allLiteralsMapped = false; } } if(satisfyClause != null && satisfyClause == false){ // the mapping cant satisfy the cnf return null; } } if(allLiteralsMapped){ // everything mapped and no clause is false return hashMap; } Term term = findPureLiteral(symbols, cnf, hashMap); if(term != null){ List<String> symbols2 = new LinkedList<String>(symbols); symbols2.remove(term.getName()); HashMap<String, Boolean> hashMap2 = new HashMap<String, Boolean>(hashMap); hashMap2.put(term.getName(), !term.isNegated()); return DPLL(cnf, symbols2, hashMap2); } term = unitClause(cnf, hashMap); if(term != null){ List<String> symbols2 = new LinkedList<String>(symbols); symbols2.remove(term.getName()); HashMap<String, Boolean> hashMap2 = new HashMap<String, Boolean>(hashMap); hashMap2.put(term.getName(), !term.isNegated()); return DPLL(cnf, symbols2, hashMap2); } // nothing found -> branch String symbol = findUnused(symbols, hashMap); List<String> symbols2 = new LinkedList<String>(symbols); symbols2.remove(symbol); HashMap<String, Boolean> hashMap2 = new HashMap<String, Boolean>(hashMap); hashMap2.put(symbol, true); HashMap<String, Boolean> result = DPLL(cnf, symbols2, hashMap2); if(result != null){ return result; } else { HashMap<String, Boolean> hashMap3 = new HashMap<String, Boolean>(hashMap); hashMap3.put(symbol, false); return DPLL(cnf, symbols2, hashMap3); } } //Falls bereits getSolution aufgerufen wurde, weitere Lösungen suchen, //falls keine mehr gefunden wird, null zurückgeben //falls bereits in einem Schritt keine Lösung gefunden wurde, eine //Exception werfen public HashMap<String,Boolean> getNextSolution() throws Exception { //oftmals gibt es mehrere Lösungen. //Man kann den Löser dazu bringen, weitere Lösungen zu finden, indem man die //letzte Lösung negiert hinzufügt, d.h. das ist nun keine Lösung mehr. //Im obigen Bsp. war der urspüngliche KNF-Ausdruck "A,~B." //gefunden wurde die Lösung "A=true" //um weitere Lösungen zu finden fügt man "~A" zum Ausdruck hinzu und sucht erneut: //"A,~B. // ~A." //diesmal wäre eine Lösung "A=false, B=false" //d.h. //HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); //belegung.put("A",false); //belegung.put("B",false); //return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } List<Expression> traverse(Expression exp){ List<Expression> result = new LinkedList<Expression>(); switch(exp.getTyp()){ case CONSTANT: break; //do nothing case SYMBOL: break; //do nothing case NOT: result.add(((NotExpression) exp).getInnerExpression()); break; case EQUIVALENCE: result.add(((EquivalenceExpression) exp).getExpression1()); result.add(((EquivalenceExpression) exp).getExpression2()); break; case IMPLICATION: result.add(((ImplicationExpression) exp).getPremise()); result.add(((ImplicationExpression) exp).getConclusion()); break; case AND: for(Expression child : ((AndExpression) exp).getExpressions()){ result.add(child); } break; case OR: for(Expression child : ((OrExpression) exp).getExpressions()){ result.add(child); } break; case XOR: result.add(((XorExpression) exp).getExpression1()); result.add(((XorExpression) exp).getExpression2()); break; } return result; } private List<String> collectVariables(CnfExpression cnf) { List<String> collect = new LinkedList<String>(); for(Clause clause : cnf.getClauses()){ for(Term literal : clause.getTerms()){ String var = literal.getName(); if(!collect.contains(var)){ collect.add(var); } } } return collect; } private Term findPureLiteral(List<String> symbols, CnfExpression cnf, HashMap<String, Boolean> hashMap) { for(String symbol : symbols){ Boolean mapping = null; Boolean result = false; for(Clause clause : cnf.getClauses()){ for(Term literal : clause.getTerms()){ if(literal.getName().equals(symbol)){ if(mapping == null){ mapping = literal.isNegated(); result = true; } else { if(mapping != literal.isNegated()){ result = false; break; } } } } } if(result == true){ return new Term(symbol, mapping); } } return null; } private String findUnused(List<String> symbols, HashMap<String, Boolean> hashMap) { for(String symbol : symbols){ if(hashMap.containsKey(symbol)){ return symbol; } } return null; } private CnfExpression reduceCNF(CnfExpression cnf, Term kill) { ArrayList<Clause> clauses = new ArrayList<Clause>(); for(Clause c : cnf.getClauses()){ ArrayList<Term> terms = new ArrayList<Term>(); for(Term t : c.getTerms()){ if(!c.equals(kill)){ terms.add(t); } } clauses.add(new Clause(terms)); } return new CnfExpression(clauses); } private void surround() { ArrayList<Expression> trans = new ArrayList<Expression>(); trans.add(expression); expression = new OrExpression(trans); // System.out.println("or \n"+this.expression); trans = new ArrayList<Expression>(); trans.add(expression); expression = new AndExpression(trans); // System.out.println("and \n"+this.expression); // <[ formula ]> } private void transform() { Boolean flag = true; while(flag){ flag = false; AndExpression big = (AndExpression) expression; // System.out.println("big \n"+big); for(Expression clause : big.getExpressions()){ // System.out.println("little \n"+clause); OrExpression little = (OrExpression) clause; for(Expression exp : little.getExpressions()){ if(!isLiteral(exp)){ flag = true; if(exp.getTyp().equals(Expression.Typ.OR)){ // from <[ (a | b), d], C> // to <[ a, b, d], C> Iterator<Expression> iter = ((OrExpression) exp).getExpressions().iterator(); - Expression a = iter.next(); - Expression b = iter.next(); + List<Expression> ab = new ArrayList<Expression>(); + while(iter.hasNext()){ + ab.add(iter.next()); + } ArrayList<Expression> C = new ArrayList<Expression>(); for(Expression e : big.getExpressions()){ if(!e.equals(clause)) C.add(e); } ArrayList<Expression> d = new ArrayList<Expression>(); for(Expression f : little.getExpressions()){ if(!f.equals(exp)) d.add(f); } - d.add(a); - d.add(b); + d.addAll(ab); C.add(new OrExpression(d)); expression = new AndExpression(C); } else { // <[(a & b), d], C]> // <[a, d], [b, d], C]> Iterator<Expression> iter = ((AndExpression) exp).getExpressions().iterator(); - Expression a = iter.next(); - Expression b = iter.next(); + List<Expression> ab = new ArrayList<Expression>(); + while(iter.hasNext()){ + ab.add(iter.next()); + } ArrayList<Expression> d = new ArrayList<Expression>(); ArrayList<Expression> C = new ArrayList<Expression>(); for(Expression e : big.getExpressions()){ if(!e.equals(clause)) C.add(e); } for(Expression f : little.getExpressions()){ if(!f.equals(exp)) d.add(f); } - ArrayList<Expression> l = new ArrayList<Expression>(d); - l.add(a); - ArrayList<Expression> m = new ArrayList<Expression>(d); - m.add(b); + for(Expression a : ab){ + ArrayList<Expression> l = new ArrayList<Expression>(d); + l.add(a); + C.add(new OrExpression(l)); + } - C.add(new OrExpression(l)); - C.add(new OrExpression(m)); expression = new AndExpression(C); } } } } - - } } private boolean isLiteral(Expression exp) { if(exp.getTyp().equals(Expression.Typ.CONSTANT)) return true; if(exp.getTyp().equals(Expression.Typ.SYMBOL)) return true; if(exp.getTyp().equals(Expression.Typ.NOT)){ Expression inner = ((NotExpression) exp).getInnerExpression(); if(inner.getTyp().equals(Expression.Typ.CONSTANT)) return true; if(inner.getTyp().equals(Expression.Typ.SYMBOL)) return true; } return false; } private ArrayList<Clause> makeResult() { ArrayList<Clause> result = new ArrayList<Clause>(); List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); if(exp.getTyp().equals(Expression.Typ.AND)){ queue.addAll(traverse(exp)); } else if(exp.getTyp().equals(Expression.Typ.OR)){ ArrayList<Expression> children = new ArrayList<Expression>(); List<Expression> childQueue = new LinkedList<Expression>(); childQueue.add(exp); while(!childQueue.isEmpty()){ Expression child = childQueue.remove(0); if(child.getTyp().equals(Expression.Typ.OR)){ childQueue.addAll(traverse(child)); } else { children.add(child); } } // collected all children ArrayList<Term> collect = new ArrayList<Term>(); Boolean deleteClause = false; Boolean emptyClause = false; for(Expression child : children){ if(child.getTyp().equals(Expression.Typ.CONSTANT)){ // true -> clause is true (can be deleted) // false -> clause is false (must be empty) if(((ConstExpression) child).getValue()){ deleteClause = true; break; } else { emptyClause = true; break; } } else { Boolean negated = false; SymbolExpression var; if(child.getTyp().equals(Expression.Typ.NOT)){ negated = true; var = (SymbolExpression) ((NotExpression) child).getInnerExpression(); } else { var = (SymbolExpression) child; } Term term = new Term(var.getName(), negated); // check of already in there if(!collect.contains(term)){ // if the negated version is in there -> tautology -> delete the clause if(collect.contains(new Term(term.getName(), !term.isNegated()))){ deleteClause = true; break; } else { collect.add(term); } } } } if(!deleteClause){ if(emptyClause){ result.add(new Clause(new ArrayList<Term>())); } else { result.add(new Clause(collect)); } } } else { // no and and no or -> const or symbol if(exp.getTyp().equals(Expression.Typ.CONSTANT)){ // true -> fill in an empty clause // false -> return an empty cnf if(((ConstExpression) exp).getValue()){ result.add(new Clause(new ArrayList<Term>())); } else { return new ArrayList<Clause>(); } } else { // Symbol or ¬Symbol Boolean negated = false; SymbolExpression var; if(exp.getTyp().equals(Expression.Typ.NOT)){ negated = true; var = (SymbolExpression) ((NotExpression) exp).getInnerExpression(); } else { var = (SymbolExpression) exp; } Term term = new Term(var.getName(), negated); ArrayList<Term> collect = new ArrayList<Term>(); collect.add(term); result.add(new Clause(collect)); } } } return result; } private void deMorganNot() { Boolean flag = true; List<Expression> queue = new LinkedList<Expression>(); while(flag){ flag = false; queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(queue.size() - 1); if(exp.getTyp().equals(Expression.Typ.NOT)){ Expression child = ((NotExpression) exp).getInnerExpression(); if(child.getTyp().equals(Expression.Typ.NOT)){ // from ¬¬a // to a NotExpression var = (NotExpression) child; Expression newChild = var.getInnerExpression(); replace(exp, newChild); exp = newChild; flag = true; queue.clear();break; } else if(child.getTyp().equals(Expression.Typ.CONSTANT)){ // from ¬const // to !const ConstExpression var = (ConstExpression) child; Expression newChild = new ConstExpression(!var.getValue()); replace(exp, newChild); exp = newChild; flag = true; queue.clear();break; } else if(child.getTyp().equals(Expression.Typ.AND)){ // from ¬(a & b) // to (¬a | ¬b) AndExpression var =(AndExpression) child; ArrayList<Expression> grandChildren = new ArrayList<Expression>(); for(Expression e : var.getExpressions()){ grandChildren.add(new NotExpression(e)); } Expression newChild = new OrExpression(grandChildren); replace(exp, newChild); exp = newChild; flag = true; queue.clear();break; } else if(child.getTyp().equals(Expression.Typ.OR)){ // from ¬(a | b) // to (¬a & ¬b) OrExpression var =(OrExpression) child; ArrayList<Expression> grandChildren = new ArrayList<Expression>(); for(Expression e : var.getExpressions()){ grandChildren.add(new NotExpression(e)); } Expression newChild = new AndExpression(grandChildren); replace(exp, newChild); exp = newChild; flag = true; queue.clear();break; } } if(flag == false){ queue.addAll(traverse(exp)); } } } } private void eliminateImpEquXor() { List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); // here is the work if(exp.getTyp().equals(Expression.Typ.IMPLICATION)){ ImplicationExpression var = (ImplicationExpression) exp; // from a -> b // to b v ¬a Expression newChild = new OrExpression(var.getConclusion(), new NotExpression(var.getPremise())); replace(exp, newChild); //return; exp = newChild; // System.out.println("new Expression:\n"+expression); } if(exp.getTyp().equals(Expression.Typ.EQUIVALENCE)){ EquivalenceExpression var = (EquivalenceExpression) exp; // from a <==> b // to (a & b) | (¬a & ¬b) Expression newChild = new OrExpression( new AndExpression(var.getExpression1(), var.getExpression2()), new AndExpression(new NotExpression(var.getExpression1()), new NotExpression(var.getExpression2()))); replace(exp, newChild); exp = newChild; } if(exp.getTyp().equals(Expression.Typ.XOR)){ XorExpression var = (XorExpression) exp; // from a ^ b // to (a & ¬b) | (¬a & b) Expression newChild = new OrExpression( new AndExpression(var.getExpression1(), new NotExpression(var.getExpression2())), new AndExpression(new NotExpression(var.getExpression1()), var.getExpression2())); replace(exp, newChild); exp = newChild; } queue.addAll(traverse(exp)); } } private Expression findParent(Expression child){ List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression parent = queue.remove(0); List<Expression> children = traverse(parent); for(Expression possibleChild : children){ if(child.equals(possibleChild)){ // found parent return parent; } } queue.addAll(children); } return null; } /** * from a & b & c & d * to a & (b & (c & d)) * */ private void onlyBinaryFunctions() { List<Expression> queue = new LinkedList<Expression>(); Boolean flag = true; while(flag){ flag = false; queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); if(exp.getTyp().equals(Expression.Typ.AND)){ List<Expression> children = traverse(exp); if(children.size() > 2){ flag = true; while(children.size() > 2){ Expression a = children.remove(children.size() - 1); Expression b = children.remove(children.size() - 1); children.add(new AndExpression(a, b)); } replace(exp, new AndExpression(children.get(0), children.get(1))); } } else if(exp.getTyp().equals(Expression.Typ.OR)){ List<Expression> children = traverse(exp); if(children.size() > 2){ flag = true; while(children.size() > 2){ Expression a = children.remove(children.size() - 1); Expression b = children.remove(children.size() - 1); children.add(new AndExpression(a, b)); } replace(exp, new AndExpression(children.get(0), children.get(1))); } } if(flag == false){ queue.addAll(traverse(exp)); } else { queue.clear(); } } } } private void replace(Expression exp, Expression newChild) { // System.out.println("replace\n"+exp+"\nwith\n"+newChild); Expression parent = findParent(exp); // System.out.println("parent\n"+parent); if(parent == null){ expression = newChild; } else { Expression child; ArrayList<Expression> children; switch(parent.getTyp()){ case NOT: child = new NotExpression(newChild); replace(parent, child); break; case IMPLICATION: if(((ImplicationExpression) parent).getPremise().equals(exp)){ child = new ImplicationExpression(newChild, ((ImplicationExpression) parent).getConclusion()); } else { child = new ImplicationExpression(((ImplicationExpression) parent).getPremise(), newChild); } replace(parent, child); break; case EQUIVALENCE: if(((EquivalenceExpression) parent).getExpression1().equals(exp)){ child = new EquivalenceExpression(newChild, ((EquivalenceExpression) parent).getExpression2()); } else { child = new EquivalenceExpression(((EquivalenceExpression) parent).getExpression1(), newChild); } replace(parent, child); break; case XOR: if(((XorExpression) parent).getExpression1().equals(exp)){ child = new XorExpression(newChild, ((XorExpression) parent).getExpression2()); } else { child = new XorExpression(((XorExpression) parent).getExpression1(), newChild); } replace(parent, child); break; case AND: children = new ArrayList<Expression>(); for(Expression possibleChild : ((AndExpression) parent).getExpressions()){ if(!possibleChild.equals(exp)){ children.add(possibleChild); } else { children.add(newChild); } } child = new AndExpression(children); replace(parent, child); break; case OR: children = new ArrayList<Expression>(); for(Expression possibleChild : ((OrExpression) parent).getExpressions()){ if(!possibleChild.equals(exp)){ children.add(possibleChild); } else { children.add(newChild); } } child = new OrExpression(children); replace(parent, child); break; } } } private Term unitClause(CnfExpression cnf, HashMap<String, Boolean> hashMap) { for(Clause clause : cnf.getClauses()){ int counter = 0; Term term = null; for(Term literal : clause.getTerms()){ Boolean map = hashMap.get(literal.getName()); if(map == null){ counter++; term = new Term(literal.getName(), !literal.isNegated()); } } if(counter == 1){ return term; } } return null; } } \ No newline at end of file
Agriculture/LogicInterpreter
b5561c800c3140e33b0c9a02b2822bb0b767b7dd
first version of DPLL + bugfixing -> i bet i find more bugs later
diff --git a/src/MyInterpreter.java b/src/MyInterpreter.java index bda0af2..0208bed 100644 --- a/src/MyInterpreter.java +++ b/src/MyInterpreter.java @@ -1,561 +1,770 @@ import logicinterpreter.base.*; import logicinterpreter.cnf.*; import logicinterpreter.expressions.*; import java.util.*; public class MyInterpreter implements IInterpreter { private Expression expression; //Bereitstellen der sowieso nötigen Umwandlung in konjunktive //Normalform public CnfExpression toCnf(Expression expression) { //Expression ist die Basisklasse für viele mögliche Ausdrücke: Konstanten, Symbole, Und-verknüpfte Ausdrücke, ... //welche davon gemeint ist, erfährt man über getTyp() //Die Expression kann man dann in die entsprechende Klasse casten, um ihre Details auszulesen //und sie in KNF umwandeln zu können: //if(expression.getTyp()==Expression.Typ.CONSTANT) //{ // ConstExpression ce=(ConstExpression) expression; // boolean val=ce.getValue(); // return makeKNFFromConst(val); //} //Die konjunktive Normalform ist wie folgt repräsentiert: //->Auf oberster Ebene gibt es die CnfExpression // ->diese beinhaltet eine Liste von Clause-Objekten (d.h. konjunktiv verknüpfte Klauseln) // ->jede Klausel beinhaltet eine List von Term-Objekten (d.h. disjunktiv verknüpfte Terme) // -> ein Term ist eine boolsche Variable, die negiert sein kann, also bspw. "A" oder "~B" //Zusammengesetzt wird das folgendermassen: //Term a=new Term("A",false); //nicht negiert //Term nicht_b=new Term("B",true); //negiert //ArrayList<Term> terme=new ArrayList<Term>(); //terme.add(a); //terme.add(nicht_b); //Clause clause=new Clause(terme); //A,~B. //ArrayList<Clause> clauses=new ArrayList<Clause>(): //clauses.add(clause); //return new CnfExpression(clauses); //KNF hat nur eine Klausel: A,~B. //**************************************** //Student begin this.expression = expression; System.out.println("start\n"+this.expression); eliminateImpEquXor(); System.out.println("eliminate implications equivalence xor \n"+this.expression); deMorganNot(); System.out.println("deMorgan and Not: \n"+this.expression); onlyBinaryFunctions(); System.out.println("only binary:\n"+this.expression); + surround(); + System.out.println("surround:\n"+this.expression); + transform(); - System.out.println("toCNF:"+this.expression); + System.out.println("toCNF:\n"+this.expression); + + ArrayList<Clause> cnf = makeResult(); + System.out.println("result:\n"+cnf); - ArrayList<Clause> result = makeResult(); - System.out.println("result:\n"+result); - return new CnfExpression(result); + return new CnfExpression(cnf); // return new CnfExpression(new ArrayList<Clause>()); //Student end //**************************************** } //Lösbarkeit des logischen Ausdrucks prüfen, falls nicht lösbar //null zurückgeben, sonst Symbolbelegung, die den Ausdruck gültig macht public HashMap<String,Boolean> getSolution(CnfExpression exprCnf) { // Es gibt 3 Möglichkeiten für diese Expression: // a) Tautologie, d.h. jede Variablenbelegung macht sie gültig // -> return new HashMap<String,Boolean>(); // b) nicht erfüllbar: // -> return null; // c) eine bestimmte Variablenbelegung macht die Aussage wahr: // -> bei der Symbolbelegung ist der Key der Name der zu belegenden Variable // und der Wert die Belegung // D.h. bei der CnfExpression "A,~B." würde die Belegung von A mit true // den Ausdruck wahr machen. Eine Lösung wäre also bspw.: // HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); // belegung.put("A",true); // return belegung; //**************************************** //Student begin + List<String> symbols = collectVariables(exprCnf); - return null; + HashMap<String, Boolean> result = DPLL(exprCnf, symbols, new HashMap<String, Boolean>()); + + + + return result; //Student end //**************************************** } + private HashMap<String, Boolean> DPLL(CnfExpression cnf, List<String> symbols, HashMap<String, Boolean> hashMap) { + if(cnf.getClauses().isEmpty()){ + // empty Conjunction + // so every mapping make it true + return new HashMap<String, Boolean>(); + } + + for(Clause clause : cnf.getClauses()){ + if(clause.getTerms().isEmpty()){ + // an empty clause + // no way there is a mapping to make it true + return null; + } + } + + + Boolean allLiteralsMapped = true; + + for(Clause clause : cnf.getClauses()){ + Boolean satisfyClause = null; + for(Term literal : clause.getTerms()){ + + Boolean map = hashMap.get(literal.getName()); + if(map != null){ + if(!literal.isNegated() == map){ + satisfyClause = true; + } else { + satisfyClause = false; + } + } + + if(map == null){ + allLiteralsMapped = false; + } + } + + if(satisfyClause != null && satisfyClause == false){ + // the mapping cant satisfy the cnf + return null; + } + } + + if(allLiteralsMapped){ + // everything mapped and no clause is false + return hashMap; + } + + Term term = findPureLiteral(symbols, cnf, hashMap); + + if(term != null){ + List<String> symbols2 = new LinkedList<String>(symbols); + symbols2.remove(term.getName()); + + HashMap<String, Boolean> hashMap2 = new HashMap<String, Boolean>(hashMap); + hashMap2.put(term.getName(), !term.isNegated()); + + return DPLL(cnf, symbols2, hashMap2); + } + + term = unitClause(cnf, hashMap); + + if(term != null){ + List<String> symbols2 = new LinkedList<String>(symbols); + symbols2.remove(term.getName()); + + HashMap<String, Boolean> hashMap2 = new HashMap<String, Boolean>(hashMap); + hashMap2.put(term.getName(), !term.isNegated()); + + return DPLL(cnf, symbols2, hashMap2); + } + + // nothing found -> branch + String symbol = findUnused(symbols, hashMap); + + List<String> symbols2 = new LinkedList<String>(symbols); + symbols2.remove(symbol); + + HashMap<String, Boolean> hashMap2 = new HashMap<String, Boolean>(hashMap); + hashMap2.put(symbol, true); + + HashMap<String, Boolean> result = DPLL(cnf, symbols2, hashMap2); + + if(result != null){ + return result; + } else { + HashMap<String, Boolean> hashMap3 = new HashMap<String, Boolean>(hashMap); + hashMap3.put(symbol, false); + + return DPLL(cnf, symbols2, hashMap3); + } + + } + //Falls bereits getSolution aufgerufen wurde, weitere Lösungen suchen, //falls keine mehr gefunden wird, null zurückgeben //falls bereits in einem Schritt keine Lösung gefunden wurde, eine //Exception werfen public HashMap<String,Boolean> getNextSolution() throws Exception { //oftmals gibt es mehrere Lösungen. //Man kann den Löser dazu bringen, weitere Lösungen zu finden, indem man die //letzte Lösung negiert hinzufügt, d.h. das ist nun keine Lösung mehr. //Im obigen Bsp. war der urspüngliche KNF-Ausdruck "A,~B." //gefunden wurde die Lösung "A=true" //um weitere Lösungen zu finden fügt man "~A" zum Ausdruck hinzu und sucht erneut: //"A,~B. // ~A." //diesmal wäre eine Lösung "A=false, B=false" //d.h. //HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); //belegung.put("A",false); //belegung.put("B",false); //return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } - List<Expression> traverse(Expression exp){ + + List<Expression> traverse(Expression exp){ List<Expression> result = new LinkedList<Expression>(); switch(exp.getTyp()){ case CONSTANT: break; //do nothing case SYMBOL: break; //do nothing case NOT: result.add(((NotExpression) exp).getInnerExpression()); break; case EQUIVALENCE: result.add(((EquivalenceExpression) exp).getExpression1()); result.add(((EquivalenceExpression) exp).getExpression2()); break; case IMPLICATION: result.add(((ImplicationExpression) exp).getPremise()); result.add(((ImplicationExpression) exp).getConclusion()); break; case AND: for(Expression child : ((AndExpression) exp).getExpressions()){ result.add(child); } break; case OR: for(Expression child : ((OrExpression) exp).getExpressions()){ result.add(child); } break; case XOR: result.add(((XorExpression) exp).getExpression1()); result.add(((XorExpression) exp).getExpression2()); break; } return result; } - private void transform() { + private List<String> collectVariables(CnfExpression cnf) { + List<String> collect = new LinkedList<String>(); + for(Clause clause : cnf.getClauses()){ + for(Term literal : clause.getTerms()){ + String var = literal.getName(); + if(!collect.contains(var)){ + collect.add(var); + } + } + } + + return collect; + } + + private Term findPureLiteral(List<String> symbols, CnfExpression cnf, HashMap<String, Boolean> hashMap) { + for(String symbol : symbols){ + Boolean mapping = null; + Boolean result = false; + for(Clause clause : cnf.getClauses()){ + for(Term literal : clause.getTerms()){ + if(literal.getName().equals(symbol)){ + if(mapping == null){ + mapping = literal.isNegated(); + result = true; + } else { + if(mapping != literal.isNegated()){ + result = false; + break; + } + } + } + } + } + if(result == true){ + return new Term(symbol, mapping); + } + } + return null; + } + + private String findUnused(List<String> symbols, HashMap<String, Boolean> hashMap) { + for(String symbol : symbols){ + if(hashMap.containsKey(symbol)){ + return symbol; + } + } + return null; + } + + private CnfExpression reduceCNF(CnfExpression cnf, Term kill) { + ArrayList<Clause> clauses = new ArrayList<Clause>(); + + for(Clause c : cnf.getClauses()){ + ArrayList<Term> terms = new ArrayList<Term>(); + for(Term t : c.getTerms()){ + if(!c.equals(kill)){ + terms.add(t); + } + } + clauses.add(new Clause(terms)); + } + + + return new CnfExpression(clauses); + } + + private void surround() { ArrayList<Expression> trans = new ArrayList<Expression>(); trans.add(expression); expression = new OrExpression(trans); // System.out.println("or \n"+this.expression); trans = new ArrayList<Expression>(); trans.add(expression); expression = new AndExpression(trans); // System.out.println("and \n"+this.expression); // <[ formula ]> + } + + private void transform() { + Boolean flag = true; while(flag){ flag = false; AndExpression big = (AndExpression) expression; // System.out.println("big \n"+big); for(Expression clause : big.getExpressions()){ // System.out.println("little \n"+clause); OrExpression little = (OrExpression) clause; for(Expression exp : little.getExpressions()){ if(!isLiteral(exp)){ flag = true; if(exp.getTyp().equals(Expression.Typ.OR)){ - ArrayList<Expression> c = new ArrayList<Expression>(); + // from <[ (a | b), d], C> + // to <[ a, b, d], C> + Iterator<Expression> iter = ((OrExpression) exp).getExpressions().iterator(); + Expression a = iter.next(); + Expression b = iter.next(); + + ArrayList<Expression> C = new ArrayList<Expression>(); for(Expression e : big.getExpressions()){ if(!e.equals(clause)) - c.add(e); + C.add(e); + } + ArrayList<Expression> d = new ArrayList<Expression>(); + for(Expression f : little.getExpressions()){ + if(!f.equals(exp)) + d.add(f); } - c.add(exp); - expression = new AndExpression(c); + d.add(a); + d.add(b); + + C.add(new OrExpression(d)); + + expression = new AndExpression(C); } else { // <[(a & b), d], C]> // <[a, d], [b, d], C]> Iterator<Expression> iter = ((AndExpression) exp).getExpressions().iterator(); Expression a = iter.next(); Expression b = iter.next(); ArrayList<Expression> d = new ArrayList<Expression>(); ArrayList<Expression> C = new ArrayList<Expression>(); for(Expression e : big.getExpressions()){ if(!e.equals(clause)) C.add(e); } for(Expression f : little.getExpressions()){ if(!f.equals(exp)) d.add(f); } ArrayList<Expression> l = new ArrayList<Expression>(d); l.add(a); ArrayList<Expression> m = new ArrayList<Expression>(d); m.add(b); C.add(new OrExpression(l)); C.add(new OrExpression(m)); expression = new AndExpression(C); } } } } } } private boolean isLiteral(Expression exp) { if(exp.getTyp().equals(Expression.Typ.CONSTANT)) return true; if(exp.getTyp().equals(Expression.Typ.SYMBOL)) return true; if(exp.getTyp().equals(Expression.Typ.NOT)){ Expression inner = ((NotExpression) exp).getInnerExpression(); if(inner.getTyp().equals(Expression.Typ.CONSTANT)) return true; if(inner.getTyp().equals(Expression.Typ.SYMBOL)) return true; } return false; } private ArrayList<Clause> makeResult() { ArrayList<Clause> result = new ArrayList<Clause>(); List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); if(exp.getTyp().equals(Expression.Typ.AND)){ queue.addAll(traverse(exp)); } else if(exp.getTyp().equals(Expression.Typ.OR)){ ArrayList<Expression> children = new ArrayList<Expression>(); List<Expression> childQueue = new LinkedList<Expression>(); childQueue.add(exp); while(!childQueue.isEmpty()){ Expression child = childQueue.remove(0); if(child.getTyp().equals(Expression.Typ.OR)){ childQueue.addAll(traverse(child)); } else { children.add(child); } } // collected all children ArrayList<Term> collect = new ArrayList<Term>(); Boolean deleteClause = false; Boolean emptyClause = false; for(Expression child : children){ if(child.getTyp().equals(Expression.Typ.CONSTANT)){ // true -> clause is true (can be deleted) // false -> clause is false (must be empty) if(((ConstExpression) child).getValue()){ deleteClause = true; break; } else { emptyClause = true; break; } } else { Boolean negated = false; SymbolExpression var; if(child.getTyp().equals(Expression.Typ.NOT)){ negated = true; var = (SymbolExpression) ((NotExpression) child).getInnerExpression(); } else { var = (SymbolExpression) child; } Term term = new Term(var.getName(), negated); // check of already in there if(!collect.contains(term)){ // if the negated version is in there -> tautology -> delete the clause if(collect.contains(new Term(term.getName(), !term.isNegated()))){ deleteClause = true; break; } else { collect.add(term); } } } } if(!deleteClause){ if(emptyClause){ result.add(new Clause(new ArrayList<Term>())); } else { result.add(new Clause(collect)); } } } else { // no and and no or -> const or symbol if(exp.getTyp().equals(Expression.Typ.CONSTANT)){ // true -> fill in an empty clause // false -> return an empty cnf if(((ConstExpression) exp).getValue()){ result.add(new Clause(new ArrayList<Term>())); } else { return new ArrayList<Clause>(); } } else { // Symbol or ¬Symbol Boolean negated = false; SymbolExpression var; if(exp.getTyp().equals(Expression.Typ.NOT)){ negated = true; var = (SymbolExpression) ((NotExpression) exp).getInnerExpression(); } else { var = (SymbolExpression) exp; } Term term = new Term(var.getName(), negated); ArrayList<Term> collect = new ArrayList<Term>(); collect.add(term); result.add(new Clause(collect)); } } } return result; } private void deMorganNot() { Boolean flag = true; List<Expression> queue = new LinkedList<Expression>(); while(flag){ flag = false; queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(queue.size() - 1); if(exp.getTyp().equals(Expression.Typ.NOT)){ Expression child = ((NotExpression) exp).getInnerExpression(); if(child.getTyp().equals(Expression.Typ.NOT)){ // from ¬¬a // to a NotExpression var = (NotExpression) child; Expression newChild = var.getInnerExpression(); replace(exp, newChild); exp = newChild; flag = true; queue.clear();break; } else if(child.getTyp().equals(Expression.Typ.CONSTANT)){ // from ¬const // to !const ConstExpression var = (ConstExpression) child; Expression newChild = new ConstExpression(!var.getValue()); replace(exp, newChild); exp = newChild; flag = true; queue.clear();break; } else if(child.getTyp().equals(Expression.Typ.AND)){ // from ¬(a & b) // to (¬a | ¬b) AndExpression var =(AndExpression) child; ArrayList<Expression> grandChildren = new ArrayList<Expression>(); for(Expression e : var.getExpressions()){ grandChildren.add(new NotExpression(e)); } Expression newChild = new OrExpression(grandChildren); replace(exp, newChild); exp = newChild; flag = true; queue.clear();break; } else if(child.getTyp().equals(Expression.Typ.OR)){ // from ¬(a | b) // to (¬a & ¬b) OrExpression var =(OrExpression) child; ArrayList<Expression> grandChildren = new ArrayList<Expression>(); for(Expression e : var.getExpressions()){ grandChildren.add(new NotExpression(e)); } Expression newChild = new AndExpression(grandChildren); replace(exp, newChild); exp = newChild; flag = true; queue.clear();break; } } if(flag == false){ queue.addAll(traverse(exp)); } } } } private void eliminateImpEquXor() { List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); // here is the work if(exp.getTyp().equals(Expression.Typ.IMPLICATION)){ ImplicationExpression var = (ImplicationExpression) exp; // from a -> b // to b v ¬a Expression newChild = new OrExpression(var.getConclusion(), new NotExpression(var.getPremise())); replace(exp, newChild); //return; exp = newChild; // System.out.println("new Expression:\n"+expression); } if(exp.getTyp().equals(Expression.Typ.EQUIVALENCE)){ EquivalenceExpression var = (EquivalenceExpression) exp; // from a <==> b // to (a & b) | (¬a & ¬b) Expression newChild = new OrExpression( new AndExpression(var.getExpression1(), var.getExpression2()), new AndExpression(new NotExpression(var.getExpression1()), new NotExpression(var.getExpression2()))); replace(exp, newChild); exp = newChild; } if(exp.getTyp().equals(Expression.Typ.XOR)){ XorExpression var = (XorExpression) exp; // from a ^ b // to (a & ¬b) | (¬a & b) Expression newChild = new OrExpression( new AndExpression(var.getExpression1(), new NotExpression(var.getExpression2())), new AndExpression(new NotExpression(var.getExpression1()), var.getExpression2())); replace(exp, newChild); exp = newChild; } queue.addAll(traverse(exp)); } } private Expression findParent(Expression child){ List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression parent = queue.remove(0); List<Expression> children = traverse(parent); for(Expression possibleChild : children){ if(child.equals(possibleChild)){ // found parent return parent; } } queue.addAll(children); } return null; } /** * from a & b & c & d * to a & (b & (c & d)) * */ private void onlyBinaryFunctions() { List<Expression> queue = new LinkedList<Expression>(); Boolean flag = true; while(flag){ flag = false; queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); if(exp.getTyp().equals(Expression.Typ.AND)){ List<Expression> children = traverse(exp); if(children.size() > 2){ flag = true; while(children.size() > 2){ Expression a = children.remove(children.size() - 1); Expression b = children.remove(children.size() - 1); children.add(new AndExpression(a, b)); } replace(exp, new AndExpression(children.get(0), children.get(1))); } } else if(exp.getTyp().equals(Expression.Typ.OR)){ List<Expression> children = traverse(exp); if(children.size() > 2){ flag = true; while(children.size() > 2){ Expression a = children.remove(children.size() - 1); Expression b = children.remove(children.size() - 1); children.add(new AndExpression(a, b)); } replace(exp, new AndExpression(children.get(0), children.get(1))); } } if(flag == false){ queue.addAll(traverse(exp)); } else { queue.clear(); } } } } private void replace(Expression exp, Expression newChild) { // System.out.println("replace\n"+exp+"\nwith\n"+newChild); Expression parent = findParent(exp); // System.out.println("parent\n"+parent); if(parent == null){ expression = newChild; } else { Expression child; ArrayList<Expression> children; switch(parent.getTyp()){ case NOT: child = new NotExpression(newChild); replace(parent, child); break; case IMPLICATION: if(((ImplicationExpression) parent).getPremise().equals(exp)){ child = new ImplicationExpression(newChild, ((ImplicationExpression) parent).getConclusion()); } else { child = new ImplicationExpression(((ImplicationExpression) parent).getPremise(), newChild); } replace(parent, child); break; case EQUIVALENCE: if(((EquivalenceExpression) parent).getExpression1().equals(exp)){ child = new EquivalenceExpression(newChild, ((EquivalenceExpression) parent).getExpression2()); } else { child = new EquivalenceExpression(((EquivalenceExpression) parent).getExpression1(), newChild); } replace(parent, child); break; case XOR: if(((XorExpression) parent).getExpression1().equals(exp)){ child = new XorExpression(newChild, ((XorExpression) parent).getExpression2()); } else { child = new XorExpression(((XorExpression) parent).getExpression1(), newChild); } replace(parent, child); break; case AND: children = new ArrayList<Expression>(); for(Expression possibleChild : ((AndExpression) parent).getExpressions()){ if(!possibleChild.equals(exp)){ children.add(possibleChild); } else { children.add(newChild); } } child = new AndExpression(children); replace(parent, child); break; case OR: children = new ArrayList<Expression>(); for(Expression possibleChild : ((OrExpression) parent).getExpressions()){ if(!possibleChild.equals(exp)){ children.add(possibleChild); } else { children.add(newChild); } } child = new OrExpression(children); replace(parent, child); break; } } } + private Term unitClause(CnfExpression cnf, HashMap<String, Boolean> hashMap) { + for(Clause clause : cnf.getClauses()){ + int counter = 0; + Term term = null; + for(Term literal : clause.getTerms()){ + Boolean map = hashMap.get(literal.getName()); + if(map == null){ + counter++; + term = new Term(literal.getName(), !literal.isNegated()); + } + } + if(counter == 1){ + return term; + } + } + + + + return null; + } + } \ No newline at end of file
Agriculture/LogicInterpreter
5435b291903518271615dec9fc56f5b3f9c269d1
redo of toCnf(), and i hope this time it works
diff --git a/src/MyInterpreter.java b/src/MyInterpreter.java index 30889f9..bda0af2 100644 --- a/src/MyInterpreter.java +++ b/src/MyInterpreter.java @@ -1,536 +1,561 @@ import logicinterpreter.base.*; import logicinterpreter.cnf.*; import logicinterpreter.expressions.*; import java.util.*; public class MyInterpreter implements IInterpreter { private Expression expression; //Bereitstellen der sowieso nötigen Umwandlung in konjunktive //Normalform public CnfExpression toCnf(Expression expression) { //Expression ist die Basisklasse für viele mögliche Ausdrücke: Konstanten, Symbole, Und-verknüpfte Ausdrücke, ... //welche davon gemeint ist, erfährt man über getTyp() //Die Expression kann man dann in die entsprechende Klasse casten, um ihre Details auszulesen //und sie in KNF umwandeln zu können: //if(expression.getTyp()==Expression.Typ.CONSTANT) //{ // ConstExpression ce=(ConstExpression) expression; // boolean val=ce.getValue(); // return makeKNFFromConst(val); //} //Die konjunktive Normalform ist wie folgt repräsentiert: //->Auf oberster Ebene gibt es die CnfExpression // ->diese beinhaltet eine Liste von Clause-Objekten (d.h. konjunktiv verknüpfte Klauseln) // ->jede Klausel beinhaltet eine List von Term-Objekten (d.h. disjunktiv verknüpfte Terme) // -> ein Term ist eine boolsche Variable, die negiert sein kann, also bspw. "A" oder "~B" //Zusammengesetzt wird das folgendermassen: //Term a=new Term("A",false); //nicht negiert //Term nicht_b=new Term("B",true); //negiert //ArrayList<Term> terme=new ArrayList<Term>(); //terme.add(a); //terme.add(nicht_b); //Clause clause=new Clause(terme); //A,~B. //ArrayList<Clause> clauses=new ArrayList<Clause>(): //clauses.add(clause); //return new CnfExpression(clauses); //KNF hat nur eine Klausel: A,~B. //**************************************** //Student begin this.expression = expression; System.out.println("start\n"+this.expression); eliminateImpEquXor(); System.out.println("eliminate implications equivalence xor \n"+this.expression); deMorganNot(); System.out.println("deMorgan and Not: \n"+this.expression); - pack(); - System.out.println("pack:\n"+this.expression); + onlyBinaryFunctions(); + System.out.println("only binary:\n"+this.expression); + transform(); + System.out.println("toCNF:"+this.expression); - pullOutAnd(); - System.out.println("pull out and:\n"+this.expression); ArrayList<Clause> result = makeResult(); System.out.println("result:\n"+result); return new CnfExpression(result); // return new CnfExpression(new ArrayList<Clause>()); //Student end //**************************************** } //Lösbarkeit des logischen Ausdrucks prüfen, falls nicht lösbar //null zurückgeben, sonst Symbolbelegung, die den Ausdruck gültig macht public HashMap<String,Boolean> getSolution(CnfExpression exprCnf) { // Es gibt 3 Möglichkeiten für diese Expression: // a) Tautologie, d.h. jede Variablenbelegung macht sie gültig // -> return new HashMap<String,Boolean>(); // b) nicht erfüllbar: // -> return null; // c) eine bestimmte Variablenbelegung macht die Aussage wahr: // -> bei der Symbolbelegung ist der Key der Name der zu belegenden Variable // und der Wert die Belegung // D.h. bei der CnfExpression "A,~B." würde die Belegung von A mit true // den Ausdruck wahr machen. Eine Lösung wäre also bspw.: // HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); // belegung.put("A",true); // return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } //Falls bereits getSolution aufgerufen wurde, weitere Lösungen suchen, //falls keine mehr gefunden wird, null zurückgeben //falls bereits in einem Schritt keine Lösung gefunden wurde, eine //Exception werfen public HashMap<String,Boolean> getNextSolution() throws Exception { //oftmals gibt es mehrere Lösungen. //Man kann den Löser dazu bringen, weitere Lösungen zu finden, indem man die //letzte Lösung negiert hinzufügt, d.h. das ist nun keine Lösung mehr. //Im obigen Bsp. war der urspüngliche KNF-Ausdruck "A,~B." //gefunden wurde die Lösung "A=true" //um weitere Lösungen zu finden fügt man "~A" zum Ausdruck hinzu und sucht erneut: //"A,~B. // ~A." //diesmal wäre eine Lösung "A=false, B=false" //d.h. //HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); //belegung.put("A",false); //belegung.put("B",false); //return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } List<Expression> traverse(Expression exp){ List<Expression> result = new LinkedList<Expression>(); switch(exp.getTyp()){ case CONSTANT: break; //do nothing case SYMBOL: break; //do nothing case NOT: result.add(((NotExpression) exp).getInnerExpression()); break; case EQUIVALENCE: result.add(((EquivalenceExpression) exp).getExpression1()); result.add(((EquivalenceExpression) exp).getExpression2()); break; case IMPLICATION: result.add(((ImplicationExpression) exp).getPremise()); result.add(((ImplicationExpression) exp).getConclusion()); break; case AND: for(Expression child : ((AndExpression) exp).getExpressions()){ result.add(child); } break; case OR: for(Expression child : ((OrExpression) exp).getExpressions()){ result.add(child); } break; case XOR: result.add(((XorExpression) exp).getExpression1()); result.add(((XorExpression) exp).getExpression2()); break; } return result; } + private void transform() { + ArrayList<Expression> trans = new ArrayList<Expression>(); + trans.add(expression); + expression = new OrExpression(trans); +// System.out.println("or \n"+this.expression); + trans = new ArrayList<Expression>(); + trans.add(expression); + expression = new AndExpression(trans); +// System.out.println("and \n"+this.expression); + // <[ formula ]> + + Boolean flag = true; + while(flag){ + flag = false; + + AndExpression big = (AndExpression) expression; +// System.out.println("big \n"+big); + for(Expression clause : big.getExpressions()){ +// System.out.println("little \n"+clause); + OrExpression little = (OrExpression) clause; + for(Expression exp : little.getExpressions()){ + + if(!isLiteral(exp)){ + flag = true; + if(exp.getTyp().equals(Expression.Typ.OR)){ + + ArrayList<Expression> c = new ArrayList<Expression>(); + for(Expression e : big.getExpressions()){ + if(!e.equals(clause)) + c.add(e); + } + c.add(exp); + + expression = new AndExpression(c); + } else { + // <[(a & b), d], C]> + // <[a, d], [b, d], C]> + Iterator<Expression> iter = ((AndExpression) exp).getExpressions().iterator(); + Expression a = iter.next(); + Expression b = iter.next(); + + ArrayList<Expression> d = new ArrayList<Expression>(); + ArrayList<Expression> C = new ArrayList<Expression>(); + for(Expression e : big.getExpressions()){ + if(!e.equals(clause)) + C.add(e); + } + for(Expression f : little.getExpressions()){ + if(!f.equals(exp)) + d.add(f); + } + ArrayList<Expression> l = new ArrayList<Expression>(d); + l.add(a); + ArrayList<Expression> m = new ArrayList<Expression>(d); + m.add(b); + + C.add(new OrExpression(l)); + C.add(new OrExpression(m)); + expression = new AndExpression(C); + } + } + } + } + + + } + } + + private boolean isLiteral(Expression exp) { + if(exp.getTyp().equals(Expression.Typ.CONSTANT)) + return true; + if(exp.getTyp().equals(Expression.Typ.SYMBOL)) + return true; + if(exp.getTyp().equals(Expression.Typ.NOT)){ + Expression inner = ((NotExpression) exp).getInnerExpression(); + if(inner.getTyp().equals(Expression.Typ.CONSTANT)) + return true; + if(inner.getTyp().equals(Expression.Typ.SYMBOL)) + return true; + } + return false; + } + private ArrayList<Clause> makeResult() { ArrayList<Clause> result = new ArrayList<Clause>(); List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); if(exp.getTyp().equals(Expression.Typ.AND)){ queue.addAll(traverse(exp)); } else if(exp.getTyp().equals(Expression.Typ.OR)){ ArrayList<Expression> children = new ArrayList<Expression>(); List<Expression> childQueue = new LinkedList<Expression>(); childQueue.add(exp); while(!childQueue.isEmpty()){ Expression child = childQueue.remove(0); if(child.getTyp().equals(Expression.Typ.OR)){ childQueue.addAll(traverse(child)); } else { children.add(child); } } // collected all children ArrayList<Term> collect = new ArrayList<Term>(); Boolean deleteClause = false; Boolean emptyClause = false; for(Expression child : children){ if(child.getTyp().equals(Expression.Typ.CONSTANT)){ // true -> clause is true (can be deleted) // false -> clause is false (must be empty) if(((ConstExpression) child).getValue()){ deleteClause = true; break; } else { emptyClause = true; break; } } else { Boolean negated = false; SymbolExpression var; if(child.getTyp().equals(Expression.Typ.NOT)){ negated = true; var = (SymbolExpression) ((NotExpression) child).getInnerExpression(); } else { var = (SymbolExpression) child; } Term term = new Term(var.getName(), negated); // check of already in there if(!collect.contains(term)){ // if the negated version is in there -> tautology -> delete the clause if(collect.contains(new Term(term.getName(), !term.isNegated()))){ deleteClause = true; break; } else { collect.add(term); } } } } if(!deleteClause){ if(emptyClause){ result.add(new Clause(new ArrayList<Term>())); } else { result.add(new Clause(collect)); } } } else { // no and and no or -> const or symbol if(exp.getTyp().equals(Expression.Typ.CONSTANT)){ // true -> fill in an empty clause // false -> return an empty cnf if(((ConstExpression) exp).getValue()){ result.add(new Clause(new ArrayList<Term>())); } else { return new ArrayList<Clause>(); } } else { // Symbol or ¬Symbol Boolean negated = false; SymbolExpression var; if(exp.getTyp().equals(Expression.Typ.NOT)){ negated = true; var = (SymbolExpression) ((NotExpression) exp).getInnerExpression(); } else { var = (SymbolExpression) exp; } Term term = new Term(var.getName(), negated); ArrayList<Term> collect = new ArrayList<Term>(); collect.add(term); result.add(new Clause(collect)); } } } return result; } - private void pullOutAnd() { - Boolean flag = true; - List<Expression> queue = new LinkedList<Expression>(); - while(flag){ - pack(); - flag = false; - queue.add(expression); - while(!queue.isEmpty()){ - Expression exp = queue.remove(0); - // from (a & b) | c - // to (a | c) & (b | c) - /** - * V = (v1 | ... | vn) - * vi = (w1 & ... & wk) - * => V = W1 & ... Wk) - * Wj = (wj | vt) for all t € {1 ... n}\{i}, j € {1 ... k} - */ - if(exp.getTyp().equals(Expression.Typ.OR)){ - ArrayList<Expression> V = new ArrayList<Expression>(); - for(Expression e : ((OrExpression) exp).getExpressions()){ - V.add(e); - } - for(Expression v : V){ - if(v.getTyp().equals(Expression.Typ.AND)){ - ArrayList<Expression> newV = new ArrayList<Expression>(); - AndExpression vi = (AndExpression) v; - ArrayList<Expression> vt = new ArrayList<Expression>(V); - vt.remove(v); - for(Expression wj : vi.getExpressions()){ - ArrayList<Expression> Wj = new ArrayList<Expression>(); - Wj.add(wj); - Wj.addAll(vt); - - newV.add(new OrExpression(Wj)); - } - Expression newChild = new AndExpression(newV); - replace(exp, newChild); - exp = newChild; - flag = true; - queue.clear(); - break; - } - } - } - if(flag == false){ - queue.addAll(traverse(exp)); - } - } - } - - } - - private void pack(){ - Boolean flag = true; - List<Expression> queue = new LinkedList<Expression>(); - while(flag){ - flag = false; - queue.add(expression); - while(!queue.isEmpty()){ - Expression exp = queue.remove(0); - switch(exp.getTyp()){ - case AND: - ArrayList<Expression> V = new ArrayList<Expression>(); - for(Expression child : ((AndExpression) exp).getExpressions()){ - V.add(child); - } - for(Expression child : ((AndExpression) exp).getExpressions()){ - if(child.getTyp().equals(Expression.Typ.AND)){ - V.remove(child); - for(Expression c : ((AndExpression) child).getExpressions()){ - V.add(c); - } - Expression newChild = new AndExpression(V); - replace(exp, newChild); - flag = true; - } - } - break; - case OR: - ArrayList<Expression> W = new ArrayList<Expression>(); - for(Expression child : ((OrExpression) exp).getExpressions()){ - W.add(child); - } - for(Expression child : ((OrExpression) exp).getExpressions()){ - if(child.getTyp().equals(Expression.Typ.OR)){ - W.remove(child); - for(Expression c : ((OrExpression) child).getExpressions()){ - W.add(c); - } - Expression newChild = new OrExpression(W); - replace(exp, newChild); - flag = true; - } - } - break; - } - if(flag == false){ - queue.addAll(traverse(exp)); - } else { - queue.clear(); - } - } - } - - } - private void deMorganNot() { Boolean flag = true; List<Expression> queue = new LinkedList<Expression>(); while(flag){ flag = false; queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(queue.size() - 1); if(exp.getTyp().equals(Expression.Typ.NOT)){ Expression child = ((NotExpression) exp).getInnerExpression(); if(child.getTyp().equals(Expression.Typ.NOT)){ // from ¬¬a // to a NotExpression var = (NotExpression) child; Expression newChild = var.getInnerExpression(); replace(exp, newChild); exp = newChild; flag = true; queue.clear();break; } else if(child.getTyp().equals(Expression.Typ.CONSTANT)){ // from ¬const // to !const ConstExpression var = (ConstExpression) child; Expression newChild = new ConstExpression(!var.getValue()); replace(exp, newChild); exp = newChild; flag = true; queue.clear();break; } else if(child.getTyp().equals(Expression.Typ.AND)){ // from ¬(a & b) // to (¬a | ¬b) AndExpression var =(AndExpression) child; ArrayList<Expression> grandChildren = new ArrayList<Expression>(); for(Expression e : var.getExpressions()){ grandChildren.add(new NotExpression(e)); } Expression newChild = new OrExpression(grandChildren); replace(exp, newChild); exp = newChild; flag = true; queue.clear();break; } else if(child.getTyp().equals(Expression.Typ.OR)){ // from ¬(a | b) // to (¬a & ¬b) OrExpression var =(OrExpression) child; ArrayList<Expression> grandChildren = new ArrayList<Expression>(); for(Expression e : var.getExpressions()){ grandChildren.add(new NotExpression(e)); } Expression newChild = new AndExpression(grandChildren); replace(exp, newChild); exp = newChild; flag = true; queue.clear();break; } } if(flag == false){ queue.addAll(traverse(exp)); } } } } private void eliminateImpEquXor() { List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); // here is the work if(exp.getTyp().equals(Expression.Typ.IMPLICATION)){ ImplicationExpression var = (ImplicationExpression) exp; // from a -> b // to b v ¬a Expression newChild = new OrExpression(var.getConclusion(), new NotExpression(var.getPremise())); replace(exp, newChild); //return; exp = newChild; // System.out.println("new Expression:\n"+expression); } if(exp.getTyp().equals(Expression.Typ.EQUIVALENCE)){ EquivalenceExpression var = (EquivalenceExpression) exp; // from a <==> b // to (a & b) | (¬a & ¬b) Expression newChild = new OrExpression( new AndExpression(var.getExpression1(), var.getExpression2()), new AndExpression(new NotExpression(var.getExpression1()), new NotExpression(var.getExpression2()))); replace(exp, newChild); exp = newChild; } if(exp.getTyp().equals(Expression.Typ.XOR)){ XorExpression var = (XorExpression) exp; // from a ^ b // to (a & ¬b) | (¬a & b) Expression newChild = new OrExpression( new AndExpression(var.getExpression1(), new NotExpression(var.getExpression2())), new AndExpression(new NotExpression(var.getExpression1()), var.getExpression2())); replace(exp, newChild); exp = newChild; } queue.addAll(traverse(exp)); } } private Expression findParent(Expression child){ List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression parent = queue.remove(0); List<Expression> children = traverse(parent); for(Expression possibleChild : children){ if(child.equals(possibleChild)){ // found parent return parent; } } queue.addAll(children); } return null; } + /** + * from a & b & c & d + * to a & (b & (c & d)) + * + */ + private void onlyBinaryFunctions() { + List<Expression> queue = new LinkedList<Expression>(); + Boolean flag = true; + while(flag){ + flag = false; + queue.add(expression); + while(!queue.isEmpty()){ + Expression exp = queue.remove(0); + if(exp.getTyp().equals(Expression.Typ.AND)){ + List<Expression> children = traverse(exp); + if(children.size() > 2){ + flag = true; + while(children.size() > 2){ + Expression a = children.remove(children.size() - 1); + Expression b = children.remove(children.size() - 1); + children.add(new AndExpression(a, b)); + } + replace(exp, new AndExpression(children.get(0), children.get(1))); + } + } else if(exp.getTyp().equals(Expression.Typ.OR)){ + List<Expression> children = traverse(exp); + if(children.size() > 2){ + flag = true; + while(children.size() > 2){ + Expression a = children.remove(children.size() - 1); + Expression b = children.remove(children.size() - 1); + children.add(new AndExpression(a, b)); + } + replace(exp, new AndExpression(children.get(0), children.get(1))); + } + } + if(flag == false){ + queue.addAll(traverse(exp)); + } else { + queue.clear(); + } + } + } + + + + } + private void replace(Expression exp, Expression newChild) { // System.out.println("replace\n"+exp+"\nwith\n"+newChild); Expression parent = findParent(exp); // System.out.println("parent\n"+parent); if(parent == null){ expression = newChild; } else { Expression child; ArrayList<Expression> children; switch(parent.getTyp()){ case NOT: child = new NotExpression(newChild); replace(parent, child); break; case IMPLICATION: if(((ImplicationExpression) parent).getPremise().equals(exp)){ child = new ImplicationExpression(newChild, ((ImplicationExpression) parent).getConclusion()); } else { child = new ImplicationExpression(((ImplicationExpression) parent).getPremise(), newChild); } replace(parent, child); break; case EQUIVALENCE: if(((EquivalenceExpression) parent).getExpression1().equals(exp)){ child = new EquivalenceExpression(newChild, ((EquivalenceExpression) parent).getExpression2()); } else { child = new EquivalenceExpression(((EquivalenceExpression) parent).getExpression1(), newChild); } replace(parent, child); break; case XOR: if(((XorExpression) parent).getExpression1().equals(exp)){ child = new XorExpression(newChild, ((XorExpression) parent).getExpression2()); } else { child = new XorExpression(((XorExpression) parent).getExpression1(), newChild); } replace(parent, child); break; case AND: children = new ArrayList<Expression>(); for(Expression possibleChild : ((AndExpression) parent).getExpressions()){ if(!possibleChild.equals(exp)){ children.add(possibleChild); } else { children.add(newChild); } } child = new AndExpression(children); replace(parent, child); break; case OR: children = new ArrayList<Expression>(); for(Expression possibleChild : ((OrExpression) parent).getExpressions()){ if(!possibleChild.equals(exp)){ children.add(possibleChild); } else { children.add(newChild); } } child = new OrExpression(children); replace(parent, child); break; } } } } \ No newline at end of file
Agriculture/LogicInterpreter
880f16baf0ecd8639f838481af5c97c9c0afd9aa
bugfixing -> still not working in every case
diff --git a/src/MyInterpreter.java b/src/MyInterpreter.java index b777381..30889f9 100644 --- a/src/MyInterpreter.java +++ b/src/MyInterpreter.java @@ -1,472 +1,536 @@ import logicinterpreter.base.*; import logicinterpreter.cnf.*; import logicinterpreter.expressions.*; import java.util.*; public class MyInterpreter implements IInterpreter { private Expression expression; //Bereitstellen der sowieso nötigen Umwandlung in konjunktive //Normalform public CnfExpression toCnf(Expression expression) { //Expression ist die Basisklasse für viele mögliche Ausdrücke: Konstanten, Symbole, Und-verknüpfte Ausdrücke, ... //welche davon gemeint ist, erfährt man über getTyp() //Die Expression kann man dann in die entsprechende Klasse casten, um ihre Details auszulesen //und sie in KNF umwandeln zu können: //if(expression.getTyp()==Expression.Typ.CONSTANT) //{ // ConstExpression ce=(ConstExpression) expression; // boolean val=ce.getValue(); // return makeKNFFromConst(val); //} //Die konjunktive Normalform ist wie folgt repräsentiert: //->Auf oberster Ebene gibt es die CnfExpression // ->diese beinhaltet eine Liste von Clause-Objekten (d.h. konjunktiv verknüpfte Klauseln) // ->jede Klausel beinhaltet eine List von Term-Objekten (d.h. disjunktiv verknüpfte Terme) // -> ein Term ist eine boolsche Variable, die negiert sein kann, also bspw. "A" oder "~B" //Zusammengesetzt wird das folgendermassen: //Term a=new Term("A",false); //nicht negiert //Term nicht_b=new Term("B",true); //negiert //ArrayList<Term> terme=new ArrayList<Term>(); //terme.add(a); //terme.add(nicht_b); //Clause clause=new Clause(terme); //A,~B. //ArrayList<Clause> clauses=new ArrayList<Clause>(): //clauses.add(clause); //return new CnfExpression(clauses); //KNF hat nur eine Klausel: A,~B. //**************************************** //Student begin this.expression = expression; System.out.println("start\n"+this.expression); eliminateImpEquXor(); System.out.println("eliminate implications equivalence xor \n"+this.expression); deMorganNot(); System.out.println("deMorgan and Not: \n"+this.expression); + pack(); + System.out.println("pack:\n"+this.expression); + pullOutAnd(); System.out.println("pull out and:\n"+this.expression); ArrayList<Clause> result = makeResult(); System.out.println("result:\n"+result); return new CnfExpression(result); +// return new CnfExpression(new ArrayList<Clause>()); //Student end //**************************************** } //Lösbarkeit des logischen Ausdrucks prüfen, falls nicht lösbar //null zurückgeben, sonst Symbolbelegung, die den Ausdruck gültig macht public HashMap<String,Boolean> getSolution(CnfExpression exprCnf) { // Es gibt 3 Möglichkeiten für diese Expression: // a) Tautologie, d.h. jede Variablenbelegung macht sie gültig // -> return new HashMap<String,Boolean>(); // b) nicht erfüllbar: // -> return null; // c) eine bestimmte Variablenbelegung macht die Aussage wahr: // -> bei der Symbolbelegung ist der Key der Name der zu belegenden Variable // und der Wert die Belegung // D.h. bei der CnfExpression "A,~B." würde die Belegung von A mit true // den Ausdruck wahr machen. Eine Lösung wäre also bspw.: // HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); // belegung.put("A",true); // return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } //Falls bereits getSolution aufgerufen wurde, weitere Lösungen suchen, //falls keine mehr gefunden wird, null zurückgeben //falls bereits in einem Schritt keine Lösung gefunden wurde, eine //Exception werfen public HashMap<String,Boolean> getNextSolution() throws Exception { //oftmals gibt es mehrere Lösungen. //Man kann den Löser dazu bringen, weitere Lösungen zu finden, indem man die //letzte Lösung negiert hinzufügt, d.h. das ist nun keine Lösung mehr. //Im obigen Bsp. war der urspüngliche KNF-Ausdruck "A,~B." //gefunden wurde die Lösung "A=true" //um weitere Lösungen zu finden fügt man "~A" zum Ausdruck hinzu und sucht erneut: //"A,~B. // ~A." //diesmal wäre eine Lösung "A=false, B=false" //d.h. //HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); //belegung.put("A",false); //belegung.put("B",false); //return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } List<Expression> traverse(Expression exp){ List<Expression> result = new LinkedList<Expression>(); switch(exp.getTyp()){ case CONSTANT: break; //do nothing case SYMBOL: break; //do nothing case NOT: result.add(((NotExpression) exp).getInnerExpression()); break; case EQUIVALENCE: result.add(((EquivalenceExpression) exp).getExpression1()); result.add(((EquivalenceExpression) exp).getExpression2()); break; case IMPLICATION: result.add(((ImplicationExpression) exp).getPremise()); result.add(((ImplicationExpression) exp).getConclusion()); break; case AND: for(Expression child : ((AndExpression) exp).getExpressions()){ result.add(child); } break; case OR: for(Expression child : ((OrExpression) exp).getExpressions()){ result.add(child); } break; case XOR: result.add(((XorExpression) exp).getExpression1()); result.add(((XorExpression) exp).getExpression2()); break; } return result; } private ArrayList<Clause> makeResult() { ArrayList<Clause> result = new ArrayList<Clause>(); List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); if(exp.getTyp().equals(Expression.Typ.AND)){ queue.addAll(traverse(exp)); } else if(exp.getTyp().equals(Expression.Typ.OR)){ ArrayList<Expression> children = new ArrayList<Expression>(); List<Expression> childQueue = new LinkedList<Expression>(); childQueue.add(exp); while(!childQueue.isEmpty()){ Expression child = childQueue.remove(0); if(child.getTyp().equals(Expression.Typ.OR)){ childQueue.addAll(traverse(child)); } else { children.add(child); } } // collected all children ArrayList<Term> collect = new ArrayList<Term>(); Boolean deleteClause = false; Boolean emptyClause = false; for(Expression child : children){ if(child.getTyp().equals(Expression.Typ.CONSTANT)){ // true -> clause is true (can be deleted) // false -> clause is false (must be empty) if(((ConstExpression) child).getValue()){ deleteClause = true; break; } else { emptyClause = true; break; } } else { Boolean negated = false; SymbolExpression var; if(child.getTyp().equals(Expression.Typ.NOT)){ negated = true; var = (SymbolExpression) ((NotExpression) child).getInnerExpression(); } else { var = (SymbolExpression) child; } Term term = new Term(var.getName(), negated); // check of already in there if(!collect.contains(term)){ // if the negated version is in there -> tautology -> delete the clause if(collect.contains(new Term(term.getName(), !term.isNegated()))){ deleteClause = true; break; } else { collect.add(term); } } } } if(!deleteClause){ if(emptyClause){ result.add(new Clause(new ArrayList<Term>())); } else { result.add(new Clause(collect)); } } } else { // no and and no or -> const or symbol if(exp.getTyp().equals(Expression.Typ.CONSTANT)){ // true -> fill in an empty clause // false -> return an empty cnf if(((ConstExpression) exp).getValue()){ result.add(new Clause(new ArrayList<Term>())); } else { return new ArrayList<Clause>(); } } else { // Symbol or ¬Symbol Boolean negated = false; SymbolExpression var; if(exp.getTyp().equals(Expression.Typ.NOT)){ negated = true; var = (SymbolExpression) ((NotExpression) exp).getInnerExpression(); } else { var = (SymbolExpression) exp; } Term term = new Term(var.getName(), negated); ArrayList<Term> collect = new ArrayList<Term>(); collect.add(term); result.add(new Clause(collect)); } } } return result; } private void pullOutAnd() { Boolean flag = true; List<Expression> queue = new LinkedList<Expression>(); while(flag){ + pack(); flag = false; queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); // from (a & b) | c // to (a | c) & (b | c) /** * V = (v1 | ... | vn) * vi = (w1 & ... & wk) * => V = W1 & ... Wk) - * Wj = (wj & vt) for all t € {1 ... n}\{i} + * Wj = (wj | vt) for all t € {1 ... n}\{i}, j € {1 ... k} */ if(exp.getTyp().equals(Expression.Typ.OR)){ ArrayList<Expression> V = new ArrayList<Expression>(); for(Expression e : ((OrExpression) exp).getExpressions()){ V.add(e); } - for(int i=0; i<V.size(); i++){ - if(V.get(i).getTyp().equals(Expression.Typ.AND)){ + for(Expression v : V){ + if(v.getTyp().equals(Expression.Typ.AND)){ ArrayList<Expression> newV = new ArrayList<Expression>(); - AndExpression vi = (AndExpression) V.get(i); + AndExpression vi = (AndExpression) v; ArrayList<Expression> vt = new ArrayList<Expression>(V); - vt.remove(i); + vt.remove(v); for(Expression wj : vi.getExpressions()){ ArrayList<Expression> Wj = new ArrayList<Expression>(); Wj.add(wj); Wj.addAll(vt); newV.add(new OrExpression(Wj)); } Expression newChild = new AndExpression(newV); replace(exp, newChild); exp = newChild; flag = true; - i = V.size(); queue.clear(); + break; } } } if(flag == false){ queue.addAll(traverse(exp)); } } } } - private void deMorganNot() { + private void pack(){ Boolean flag = true; List<Expression> queue = new LinkedList<Expression>(); while(flag){ flag = false; queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); + switch(exp.getTyp()){ + case AND: + ArrayList<Expression> V = new ArrayList<Expression>(); + for(Expression child : ((AndExpression) exp).getExpressions()){ + V.add(child); + } + for(Expression child : ((AndExpression) exp).getExpressions()){ + if(child.getTyp().equals(Expression.Typ.AND)){ + V.remove(child); + for(Expression c : ((AndExpression) child).getExpressions()){ + V.add(c); + } + Expression newChild = new AndExpression(V); + replace(exp, newChild); + flag = true; + } + } + break; + case OR: + ArrayList<Expression> W = new ArrayList<Expression>(); + for(Expression child : ((OrExpression) exp).getExpressions()){ + W.add(child); + } + for(Expression child : ((OrExpression) exp).getExpressions()){ + if(child.getTyp().equals(Expression.Typ.OR)){ + W.remove(child); + for(Expression c : ((OrExpression) child).getExpressions()){ + W.add(c); + } + Expression newChild = new OrExpression(W); + replace(exp, newChild); + flag = true; + } + } + break; + } + if(flag == false){ + queue.addAll(traverse(exp)); + } else { + queue.clear(); + } + } + } + + } + + private void deMorganNot() { + Boolean flag = true; + List<Expression> queue = new LinkedList<Expression>(); + while(flag){ + flag = false; + queue.add(expression); + while(!queue.isEmpty()){ + Expression exp = queue.remove(queue.size() - 1); if(exp.getTyp().equals(Expression.Typ.NOT)){ - NotExpression var = (NotExpression) exp; - Expression child = var.getInnerExpression(); + Expression child = ((NotExpression) exp).getInnerExpression(); if(child.getTyp().equals(Expression.Typ.NOT)){ // from ¬¬a // to a - NotExpression var2 = (NotExpression) child; - Expression newChild = var2.getInnerExpression(); + NotExpression var = (NotExpression) child; + Expression newChild = var.getInnerExpression(); replace(exp, newChild); exp = newChild; flag = true; - } - if(child.getTyp().equals(Expression.Typ.CONSTANT)){ + queue.clear();break; + } else + if(child.getTyp().equals(Expression.Typ.CONSTANT)){ // from ¬const - // to const - ConstExpression var2 = (ConstExpression) child; - Expression newChild = new ConstExpression(!var2.getValue()); + // to !const + ConstExpression var = (ConstExpression) child; + Expression newChild = new ConstExpression(!var.getValue()); replace(exp, newChild); + exp = newChild; flag = true; - } - if(child.getTyp().equals(Expression.Typ.AND)){ + queue.clear();break; + } else + if(child.getTyp().equals(Expression.Typ.AND)){ // from ¬(a & b) // to (¬a | ¬b) - AndExpression var2 =(AndExpression) child; + AndExpression var =(AndExpression) child; ArrayList<Expression> grandChildren = new ArrayList<Expression>(); - for(Expression e : var2.getExpressions()){ + for(Expression e : var.getExpressions()){ grandChildren.add(new NotExpression(e)); } Expression newChild = new OrExpression(grandChildren); replace(exp, newChild); exp = newChild; flag = true; - } - if(child.getTyp().equals(Expression.Typ.OR)){ + queue.clear();break; + } else if(child.getTyp().equals(Expression.Typ.OR)){ // from ¬(a | b) // to (¬a & ¬b) - OrExpression var2 =(OrExpression) child; + OrExpression var =(OrExpression) child; ArrayList<Expression> grandChildren = new ArrayList<Expression>(); - for(Expression e : var2.getExpressions()){ + for(Expression e : var.getExpressions()){ grandChildren.add(new NotExpression(e)); } Expression newChild = new AndExpression(grandChildren); replace(exp, newChild); exp = newChild; flag = true; + queue.clear();break; } } - queue.addAll(traverse(exp)); + if(flag == false){ + queue.addAll(traverse(exp)); + } } } } private void eliminateImpEquXor() { List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); // here is the work if(exp.getTyp().equals(Expression.Typ.IMPLICATION)){ ImplicationExpression var = (ImplicationExpression) exp; // from a -> b // to b v ¬a Expression newChild = new OrExpression(var.getConclusion(), new NotExpression(var.getPremise())); replace(exp, newChild); //return; exp = newChild; // System.out.println("new Expression:\n"+expression); } if(exp.getTyp().equals(Expression.Typ.EQUIVALENCE)){ EquivalenceExpression var = (EquivalenceExpression) exp; // from a <==> b // to (a & b) | (¬a & ¬b) Expression newChild = new OrExpression( new AndExpression(var.getExpression1(), var.getExpression2()), new AndExpression(new NotExpression(var.getExpression1()), new NotExpression(var.getExpression2()))); replace(exp, newChild); exp = newChild; } if(exp.getTyp().equals(Expression.Typ.XOR)){ XorExpression var = (XorExpression) exp; // from a ^ b // to (a & ¬b) | (¬a & b) Expression newChild = new OrExpression( new AndExpression(var.getExpression1(), new NotExpression(var.getExpression2())), new AndExpression(new NotExpression(var.getExpression1()), var.getExpression2())); replace(exp, newChild); exp = newChild; } queue.addAll(traverse(exp)); } } private Expression findParent(Expression child){ List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression parent = queue.remove(0); List<Expression> children = traverse(parent); for(Expression possibleChild : children){ if(child.equals(possibleChild)){ // found parent return parent; } } queue.addAll(children); } return null; } private void replace(Expression exp, Expression newChild) { // System.out.println("replace\n"+exp+"\nwith\n"+newChild); Expression parent = findParent(exp); // System.out.println("parent\n"+parent); if(parent == null){ expression = newChild; } else { Expression child; ArrayList<Expression> children; switch(parent.getTyp()){ case NOT: child = new NotExpression(newChild); replace(parent, child); break; case IMPLICATION: if(((ImplicationExpression) parent).getPremise().equals(exp)){ child = new ImplicationExpression(newChild, ((ImplicationExpression) parent).getConclusion()); } else { child = new ImplicationExpression(((ImplicationExpression) parent).getPremise(), newChild); } replace(parent, child); break; case EQUIVALENCE: if(((EquivalenceExpression) parent).getExpression1().equals(exp)){ child = new EquivalenceExpression(newChild, ((EquivalenceExpression) parent).getExpression2()); } else { child = new EquivalenceExpression(((EquivalenceExpression) parent).getExpression1(), newChild); } replace(parent, child); break; case XOR: if(((XorExpression) parent).getExpression1().equals(exp)){ child = new XorExpression(newChild, ((XorExpression) parent).getExpression2()); } else { child = new XorExpression(((XorExpression) parent).getExpression1(), newChild); } replace(parent, child); break; case AND: children = new ArrayList<Expression>(); for(Expression possibleChild : ((AndExpression) parent).getExpressions()){ if(!possibleChild.equals(exp)){ children.add(possibleChild); } else { children.add(newChild); } } child = new AndExpression(children); replace(parent, child); break; case OR: children = new ArrayList<Expression>(); for(Expression possibleChild : ((OrExpression) parent).getExpressions()){ if(!possibleChild.equals(exp)){ children.add(possibleChild); } else { children.add(newChild); } } child = new OrExpression(children); replace(parent, child); break; } } } } \ No newline at end of file
Agriculture/LogicInterpreter
c08a89dab555d21af2b863b8eeb7080380dac719
transform into cnf seems to be working
diff --git a/src/MyInterpreter.java b/src/MyInterpreter.java index 5aa031a..b777381 100644 --- a/src/MyInterpreter.java +++ b/src/MyInterpreter.java @@ -1,373 +1,472 @@ import logicinterpreter.base.*; import logicinterpreter.cnf.*; import logicinterpreter.expressions.*; import java.util.*; public class MyInterpreter implements IInterpreter { private Expression expression; //Bereitstellen der sowieso nötigen Umwandlung in konjunktive //Normalform public CnfExpression toCnf(Expression expression) { //Expression ist die Basisklasse für viele mögliche Ausdrücke: Konstanten, Symbole, Und-verknüpfte Ausdrücke, ... //welche davon gemeint ist, erfährt man über getTyp() //Die Expression kann man dann in die entsprechende Klasse casten, um ihre Details auszulesen //und sie in KNF umwandeln zu können: //if(expression.getTyp()==Expression.Typ.CONSTANT) //{ // ConstExpression ce=(ConstExpression) expression; // boolean val=ce.getValue(); // return makeKNFFromConst(val); //} //Die konjunktive Normalform ist wie folgt repräsentiert: //->Auf oberster Ebene gibt es die CnfExpression // ->diese beinhaltet eine Liste von Clause-Objekten (d.h. konjunktiv verknüpfte Klauseln) // ->jede Klausel beinhaltet eine List von Term-Objekten (d.h. disjunktiv verknüpfte Terme) // -> ein Term ist eine boolsche Variable, die negiert sein kann, also bspw. "A" oder "~B" //Zusammengesetzt wird das folgendermassen: //Term a=new Term("A",false); //nicht negiert //Term nicht_b=new Term("B",true); //negiert //ArrayList<Term> terme=new ArrayList<Term>(); //terme.add(a); //terme.add(nicht_b); //Clause clause=new Clause(terme); //A,~B. //ArrayList<Clause> clauses=new ArrayList<Clause>(): //clauses.add(clause); //return new CnfExpression(clauses); //KNF hat nur eine Klausel: A,~B. //**************************************** //Student begin this.expression = expression; System.out.println("start\n"+this.expression); eliminateImpEquXor(); System.out.println("eliminate implications equivalence xor \n"+this.expression); deMorganNot(); System.out.println("deMorgan and Not: \n"+this.expression); pullOutAnd(); System.out.println("pull out and:\n"+this.expression); - return new CnfExpression(new ArrayList<Clause>()); + ArrayList<Clause> result = makeResult(); + System.out.println("result:\n"+result); + + return new CnfExpression(result); //Student end //**************************************** } //Lösbarkeit des logischen Ausdrucks prüfen, falls nicht lösbar //null zurückgeben, sonst Symbolbelegung, die den Ausdruck gültig macht public HashMap<String,Boolean> getSolution(CnfExpression exprCnf) { // Es gibt 3 Möglichkeiten für diese Expression: // a) Tautologie, d.h. jede Variablenbelegung macht sie gültig // -> return new HashMap<String,Boolean>(); // b) nicht erfüllbar: // -> return null; // c) eine bestimmte Variablenbelegung macht die Aussage wahr: // -> bei der Symbolbelegung ist der Key der Name der zu belegenden Variable // und der Wert die Belegung // D.h. bei der CnfExpression "A,~B." würde die Belegung von A mit true // den Ausdruck wahr machen. Eine Lösung wäre also bspw.: // HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); // belegung.put("A",true); // return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } //Falls bereits getSolution aufgerufen wurde, weitere Lösungen suchen, //falls keine mehr gefunden wird, null zurückgeben //falls bereits in einem Schritt keine Lösung gefunden wurde, eine //Exception werfen public HashMap<String,Boolean> getNextSolution() throws Exception { //oftmals gibt es mehrere Lösungen. //Man kann den Löser dazu bringen, weitere Lösungen zu finden, indem man die //letzte Lösung negiert hinzufügt, d.h. das ist nun keine Lösung mehr. //Im obigen Bsp. war der urspüngliche KNF-Ausdruck "A,~B." //gefunden wurde die Lösung "A=true" //um weitere Lösungen zu finden fügt man "~A" zum Ausdruck hinzu und sucht erneut: //"A,~B. // ~A." //diesmal wäre eine Lösung "A=false, B=false" //d.h. //HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); //belegung.put("A",false); //belegung.put("B",false); //return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } List<Expression> traverse(Expression exp){ List<Expression> result = new LinkedList<Expression>(); switch(exp.getTyp()){ case CONSTANT: break; //do nothing case SYMBOL: break; //do nothing case NOT: result.add(((NotExpression) exp).getInnerExpression()); break; case EQUIVALENCE: result.add(((EquivalenceExpression) exp).getExpression1()); result.add(((EquivalenceExpression) exp).getExpression2()); break; case IMPLICATION: result.add(((ImplicationExpression) exp).getPremise()); result.add(((ImplicationExpression) exp).getConclusion()); break; case AND: for(Expression child : ((AndExpression) exp).getExpressions()){ result.add(child); } break; case OR: for(Expression child : ((OrExpression) exp).getExpressions()){ result.add(child); } break; case XOR: result.add(((XorExpression) exp).getExpression1()); result.add(((XorExpression) exp).getExpression2()); break; } return result; } + private ArrayList<Clause> makeResult() { + ArrayList<Clause> result = new ArrayList<Clause>(); + List<Expression> queue = new LinkedList<Expression>(); + queue.add(expression); + while(!queue.isEmpty()){ + Expression exp = queue.remove(0); + if(exp.getTyp().equals(Expression.Typ.AND)){ + queue.addAll(traverse(exp)); + } else if(exp.getTyp().equals(Expression.Typ.OR)){ + ArrayList<Expression> children = new ArrayList<Expression>(); + List<Expression> childQueue = new LinkedList<Expression>(); + childQueue.add(exp); + while(!childQueue.isEmpty()){ + Expression child = childQueue.remove(0); + if(child.getTyp().equals(Expression.Typ.OR)){ + childQueue.addAll(traverse(child)); + } else { + children.add(child); + } + } + // collected all children + ArrayList<Term> collect = new ArrayList<Term>(); + Boolean deleteClause = false; + Boolean emptyClause = false; + for(Expression child : children){ + if(child.getTyp().equals(Expression.Typ.CONSTANT)){ + // true -> clause is true (can be deleted) + // false -> clause is false (must be empty) + if(((ConstExpression) child).getValue()){ + deleteClause = true; + break; + } else { + emptyClause = true; + break; + } + } else { + Boolean negated = false; + SymbolExpression var; + if(child.getTyp().equals(Expression.Typ.NOT)){ + negated = true; + var = (SymbolExpression) ((NotExpression) child).getInnerExpression(); + } else { + var = (SymbolExpression) child; + } + Term term = new Term(var.getName(), negated); + // check of already in there + if(!collect.contains(term)){ + // if the negated version is in there -> tautology -> delete the clause + if(collect.contains(new Term(term.getName(), !term.isNegated()))){ + deleteClause = true; + break; + } else { + collect.add(term); + } + } + } + } + if(!deleteClause){ + if(emptyClause){ + result.add(new Clause(new ArrayList<Term>())); + } else { + result.add(new Clause(collect)); + } + } + + + } else { + // no and and no or -> const or symbol + if(exp.getTyp().equals(Expression.Typ.CONSTANT)){ + // true -> fill in an empty clause + // false -> return an empty cnf + if(((ConstExpression) exp).getValue()){ + result.add(new Clause(new ArrayList<Term>())); + } else { + return new ArrayList<Clause>(); + } + } else { + // Symbol or ¬Symbol + Boolean negated = false; + SymbolExpression var; + if(exp.getTyp().equals(Expression.Typ.NOT)){ + negated = true; + var = (SymbolExpression) ((NotExpression) exp).getInnerExpression(); + } else { + var = (SymbolExpression) exp; + } + Term term = new Term(var.getName(), negated); + ArrayList<Term> collect = new ArrayList<Term>(); + collect.add(term); + result.add(new Clause(collect)); + } + } + } + return result; + } + private void pullOutAnd() { Boolean flag = true; List<Expression> queue = new LinkedList<Expression>(); while(flag){ flag = false; queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); // from (a & b) | c // to (a | c) & (b | c) /** * V = (v1 | ... | vn) * vi = (w1 & ... & wk) * => V = W1 & ... Wk) * Wj = (wj & vt) for all t € {1 ... n}\{i} */ if(exp.getTyp().equals(Expression.Typ.OR)){ ArrayList<Expression> V = new ArrayList<Expression>(); for(Expression e : ((OrExpression) exp).getExpressions()){ V.add(e); } for(int i=0; i<V.size(); i++){ if(V.get(i).getTyp().equals(Expression.Typ.AND)){ ArrayList<Expression> newV = new ArrayList<Expression>(); AndExpression vi = (AndExpression) V.get(i); ArrayList<Expression> vt = new ArrayList<Expression>(V); vt.remove(i); for(Expression wj : vi.getExpressions()){ ArrayList<Expression> Wj = new ArrayList<Expression>(); Wj.add(wj); Wj.addAll(vt); newV.add(new OrExpression(Wj)); } Expression newChild = new AndExpression(newV); replace(exp, newChild); exp = newChild; flag = true; i = V.size(); queue.clear(); } } } if(flag == false){ queue.addAll(traverse(exp)); } } } } private void deMorganNot() { Boolean flag = true; List<Expression> queue = new LinkedList<Expression>(); while(flag){ flag = false; queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); if(exp.getTyp().equals(Expression.Typ.NOT)){ NotExpression var = (NotExpression) exp; Expression child = var.getInnerExpression(); if(child.getTyp().equals(Expression.Typ.NOT)){ // from ¬¬a // to a NotExpression var2 = (NotExpression) child; Expression newChild = var2.getInnerExpression(); replace(exp, newChild); exp = newChild; flag = true; } if(child.getTyp().equals(Expression.Typ.CONSTANT)){ // from ¬const // to const ConstExpression var2 = (ConstExpression) child; Expression newChild = new ConstExpression(!var2.getValue()); replace(exp, newChild); flag = true; } if(child.getTyp().equals(Expression.Typ.AND)){ // from ¬(a & b) // to (¬a | ¬b) AndExpression var2 =(AndExpression) child; ArrayList<Expression> grandChildren = new ArrayList<Expression>(); for(Expression e : var2.getExpressions()){ grandChildren.add(new NotExpression(e)); } Expression newChild = new OrExpression(grandChildren); replace(exp, newChild); exp = newChild; flag = true; } if(child.getTyp().equals(Expression.Typ.OR)){ // from ¬(a | b) // to (¬a & ¬b) OrExpression var2 =(OrExpression) child; ArrayList<Expression> grandChildren = new ArrayList<Expression>(); for(Expression e : var2.getExpressions()){ grandChildren.add(new NotExpression(e)); } Expression newChild = new AndExpression(grandChildren); replace(exp, newChild); exp = newChild; flag = true; } } queue.addAll(traverse(exp)); } } } private void eliminateImpEquXor() { List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); // here is the work if(exp.getTyp().equals(Expression.Typ.IMPLICATION)){ ImplicationExpression var = (ImplicationExpression) exp; // from a -> b // to b v ¬a Expression newChild = new OrExpression(var.getConclusion(), new NotExpression(var.getPremise())); replace(exp, newChild); //return; exp = newChild; // System.out.println("new Expression:\n"+expression); } if(exp.getTyp().equals(Expression.Typ.EQUIVALENCE)){ EquivalenceExpression var = (EquivalenceExpression) exp; // from a <==> b // to (a & b) | (¬a & ¬b) Expression newChild = new OrExpression( new AndExpression(var.getExpression1(), var.getExpression2()), new AndExpression(new NotExpression(var.getExpression1()), new NotExpression(var.getExpression2()))); replace(exp, newChild); exp = newChild; } if(exp.getTyp().equals(Expression.Typ.XOR)){ XorExpression var = (XorExpression) exp; // from a ^ b // to (a & ¬b) | (¬a & b) Expression newChild = new OrExpression( new AndExpression(var.getExpression1(), new NotExpression(var.getExpression2())), new AndExpression(new NotExpression(var.getExpression1()), var.getExpression2())); replace(exp, newChild); exp = newChild; } queue.addAll(traverse(exp)); } } private Expression findParent(Expression child){ List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression parent = queue.remove(0); List<Expression> children = traverse(parent); for(Expression possibleChild : children){ if(child.equals(possibleChild)){ // found parent return parent; } } queue.addAll(children); } return null; } private void replace(Expression exp, Expression newChild) { // System.out.println("replace\n"+exp+"\nwith\n"+newChild); Expression parent = findParent(exp); // System.out.println("parent\n"+parent); if(parent == null){ expression = newChild; } else { Expression child; ArrayList<Expression> children; switch(parent.getTyp()){ case NOT: child = new NotExpression(newChild); replace(parent, child); break; case IMPLICATION: if(((ImplicationExpression) parent).getPremise().equals(exp)){ child = new ImplicationExpression(newChild, ((ImplicationExpression) parent).getConclusion()); } else { child = new ImplicationExpression(((ImplicationExpression) parent).getPremise(), newChild); } replace(parent, child); break; case EQUIVALENCE: if(((EquivalenceExpression) parent).getExpression1().equals(exp)){ child = new EquivalenceExpression(newChild, ((EquivalenceExpression) parent).getExpression2()); } else { child = new EquivalenceExpression(((EquivalenceExpression) parent).getExpression1(), newChild); } replace(parent, child); break; case XOR: if(((XorExpression) parent).getExpression1().equals(exp)){ child = new XorExpression(newChild, ((XorExpression) parent).getExpression2()); } else { child = new XorExpression(((XorExpression) parent).getExpression1(), newChild); } replace(parent, child); break; case AND: children = new ArrayList<Expression>(); for(Expression possibleChild : ((AndExpression) parent).getExpressions()){ if(!possibleChild.equals(exp)){ children.add(possibleChild); } else { children.add(newChild); } } child = new AndExpression(children); replace(parent, child); break; case OR: children = new ArrayList<Expression>(); for(Expression possibleChild : ((OrExpression) parent).getExpressions()){ if(!possibleChild.equals(exp)){ children.add(possibleChild); } else { children.add(newChild); } } child = new OrExpression(children); replace(parent, child); break; } } } } \ No newline at end of file
Agriculture/LogicInterpreter
5d8d828137e7ae6225126af477fff7a929377edb
deMorgan and pull out &
diff --git a/src/MyInterpreter.java b/src/MyInterpreter.java index 4c03f7c..5aa031a 100644 --- a/src/MyInterpreter.java +++ b/src/MyInterpreter.java @@ -1,258 +1,373 @@ import logicinterpreter.base.*; import logicinterpreter.cnf.*; import logicinterpreter.expressions.*; import java.util.*; public class MyInterpreter implements IInterpreter { private Expression expression; //Bereitstellen der sowieso nötigen Umwandlung in konjunktive //Normalform public CnfExpression toCnf(Expression expression) { //Expression ist die Basisklasse für viele mögliche Ausdrücke: Konstanten, Symbole, Und-verknüpfte Ausdrücke, ... //welche davon gemeint ist, erfährt man über getTyp() //Die Expression kann man dann in die entsprechende Klasse casten, um ihre Details auszulesen //und sie in KNF umwandeln zu können: //if(expression.getTyp()==Expression.Typ.CONSTANT) //{ // ConstExpression ce=(ConstExpression) expression; // boolean val=ce.getValue(); // return makeKNFFromConst(val); //} //Die konjunktive Normalform ist wie folgt repräsentiert: //->Auf oberster Ebene gibt es die CnfExpression // ->diese beinhaltet eine Liste von Clause-Objekten (d.h. konjunktiv verknüpfte Klauseln) // ->jede Klausel beinhaltet eine List von Term-Objekten (d.h. disjunktiv verknüpfte Terme) // -> ein Term ist eine boolsche Variable, die negiert sein kann, also bspw. "A" oder "~B" //Zusammengesetzt wird das folgendermassen: //Term a=new Term("A",false); //nicht negiert //Term nicht_b=new Term("B",true); //negiert //ArrayList<Term> terme=new ArrayList<Term>(); //terme.add(a); //terme.add(nicht_b); //Clause clause=new Clause(terme); //A,~B. //ArrayList<Clause> clauses=new ArrayList<Clause>(): //clauses.add(clause); //return new CnfExpression(clauses); //KNF hat nur eine Klausel: A,~B. //**************************************** //Student begin this.expression = expression; System.out.println("start\n"+this.expression); eliminateImpEquXor(); - System.out.println("eliminate implications\n"+this.expression); + System.out.println("eliminate implications equivalence xor \n"+this.expression); + deMorganNot(); + System.out.println("deMorgan and Not: \n"+this.expression); + pullOutAnd(); + System.out.println("pull out and:\n"+this.expression); return new CnfExpression(new ArrayList<Clause>()); //Student end //**************************************** } //Lösbarkeit des logischen Ausdrucks prüfen, falls nicht lösbar //null zurückgeben, sonst Symbolbelegung, die den Ausdruck gültig macht public HashMap<String,Boolean> getSolution(CnfExpression exprCnf) { // Es gibt 3 Möglichkeiten für diese Expression: // a) Tautologie, d.h. jede Variablenbelegung macht sie gültig // -> return new HashMap<String,Boolean>(); // b) nicht erfüllbar: // -> return null; // c) eine bestimmte Variablenbelegung macht die Aussage wahr: // -> bei der Symbolbelegung ist der Key der Name der zu belegenden Variable // und der Wert die Belegung // D.h. bei der CnfExpression "A,~B." würde die Belegung von A mit true // den Ausdruck wahr machen. Eine Lösung wäre also bspw.: // HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); // belegung.put("A",true); // return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } //Falls bereits getSolution aufgerufen wurde, weitere Lösungen suchen, //falls keine mehr gefunden wird, null zurückgeben //falls bereits in einem Schritt keine Lösung gefunden wurde, eine //Exception werfen public HashMap<String,Boolean> getNextSolution() throws Exception { //oftmals gibt es mehrere Lösungen. //Man kann den Löser dazu bringen, weitere Lösungen zu finden, indem man die //letzte Lösung negiert hinzufügt, d.h. das ist nun keine Lösung mehr. //Im obigen Bsp. war der urspüngliche KNF-Ausdruck "A,~B." //gefunden wurde die Lösung "A=true" //um weitere Lösungen zu finden fügt man "~A" zum Ausdruck hinzu und sucht erneut: //"A,~B. // ~A." //diesmal wäre eine Lösung "A=false, B=false" //d.h. //HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); //belegung.put("A",false); //belegung.put("B",false); //return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } List<Expression> traverse(Expression exp){ List<Expression> result = new LinkedList<Expression>(); switch(exp.getTyp()){ case CONSTANT: break; //do nothing case SYMBOL: break; //do nothing case NOT: result.add(((NotExpression) exp).getInnerExpression()); break; case EQUIVALENCE: result.add(((EquivalenceExpression) exp).getExpression1()); result.add(((EquivalenceExpression) exp).getExpression2()); break; case IMPLICATION: result.add(((ImplicationExpression) exp).getPremise()); result.add(((ImplicationExpression) exp).getConclusion()); break; case AND: for(Expression child : ((AndExpression) exp).getExpressions()){ result.add(child); } break; case OR: for(Expression child : ((OrExpression) exp).getExpressions()){ result.add(child); } break; case XOR: result.add(((XorExpression) exp).getExpression1()); result.add(((XorExpression) exp).getExpression2()); break; } return result; } + private void pullOutAnd() { + Boolean flag = true; + List<Expression> queue = new LinkedList<Expression>(); + while(flag){ + flag = false; + queue.add(expression); + while(!queue.isEmpty()){ + Expression exp = queue.remove(0); + // from (a & b) | c + // to (a | c) & (b | c) + /** + * V = (v1 | ... | vn) + * vi = (w1 & ... & wk) + * => V = W1 & ... Wk) + * Wj = (wj & vt) for all t € {1 ... n}\{i} + */ + if(exp.getTyp().equals(Expression.Typ.OR)){ + ArrayList<Expression> V = new ArrayList<Expression>(); + for(Expression e : ((OrExpression) exp).getExpressions()){ + V.add(e); + } + for(int i=0; i<V.size(); i++){ + if(V.get(i).getTyp().equals(Expression.Typ.AND)){ + ArrayList<Expression> newV = new ArrayList<Expression>(); + AndExpression vi = (AndExpression) V.get(i); + ArrayList<Expression> vt = new ArrayList<Expression>(V); + vt.remove(i); + for(Expression wj : vi.getExpressions()){ + ArrayList<Expression> Wj = new ArrayList<Expression>(); + Wj.add(wj); + Wj.addAll(vt); + + newV.add(new OrExpression(Wj)); + } + Expression newChild = new AndExpression(newV); + replace(exp, newChild); + exp = newChild; + flag = true; + i = V.size(); + queue.clear(); + } + } + } + if(flag == false){ + queue.addAll(traverse(exp)); + } + } + } + + } + + private void deMorganNot() { + Boolean flag = true; + List<Expression> queue = new LinkedList<Expression>(); + while(flag){ + flag = false; + queue.add(expression); + while(!queue.isEmpty()){ + Expression exp = queue.remove(0); + if(exp.getTyp().equals(Expression.Typ.NOT)){ + NotExpression var = (NotExpression) exp; + Expression child = var.getInnerExpression(); + if(child.getTyp().equals(Expression.Typ.NOT)){ + // from ¬¬a + // to a + NotExpression var2 = (NotExpression) child; + Expression newChild = var2.getInnerExpression(); + replace(exp, newChild); + exp = newChild; + flag = true; + } + if(child.getTyp().equals(Expression.Typ.CONSTANT)){ + // from ¬const + // to const + ConstExpression var2 = (ConstExpression) child; + Expression newChild = new ConstExpression(!var2.getValue()); + replace(exp, newChild); + flag = true; + } + if(child.getTyp().equals(Expression.Typ.AND)){ + // from ¬(a & b) + // to (¬a | ¬b) + AndExpression var2 =(AndExpression) child; + ArrayList<Expression> grandChildren = new ArrayList<Expression>(); + for(Expression e : var2.getExpressions()){ + grandChildren.add(new NotExpression(e)); + } + Expression newChild = new OrExpression(grandChildren); + replace(exp, newChild); + exp = newChild; + flag = true; + } + if(child.getTyp().equals(Expression.Typ.OR)){ + // from ¬(a | b) + // to (¬a & ¬b) + OrExpression var2 =(OrExpression) child; + ArrayList<Expression> grandChildren = new ArrayList<Expression>(); + for(Expression e : var2.getExpressions()){ + grandChildren.add(new NotExpression(e)); + } + Expression newChild = new AndExpression(grandChildren); + replace(exp, newChild); + exp = newChild; + flag = true; + } + } + queue.addAll(traverse(exp)); + } + } + } + private void eliminateImpEquXor() { List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); // here is the work if(exp.getTyp().equals(Expression.Typ.IMPLICATION)){ ImplicationExpression var = (ImplicationExpression) exp; // from a -> b // to b v ¬a Expression newChild = new OrExpression(var.getConclusion(), new NotExpression(var.getPremise())); replace(exp, newChild); //return; exp = newChild; // System.out.println("new Expression:\n"+expression); } if(exp.getTyp().equals(Expression.Typ.EQUIVALENCE)){ EquivalenceExpression var = (EquivalenceExpression) exp; // from a <==> b // to (a & b) | (¬a & ¬b) Expression newChild = new OrExpression( new AndExpression(var.getExpression1(), var.getExpression2()), new AndExpression(new NotExpression(var.getExpression1()), new NotExpression(var.getExpression2()))); replace(exp, newChild); exp = newChild; } if(exp.getTyp().equals(Expression.Typ.XOR)){ XorExpression var = (XorExpression) exp; // from a ^ b // to (a & ¬b) | (¬a & b) Expression newChild = new OrExpression( new AndExpression(var.getExpression1(), new NotExpression(var.getExpression2())), new AndExpression(new NotExpression(var.getExpression1()), var.getExpression2())); replace(exp, newChild); exp = newChild; } queue.addAll(traverse(exp)); } } private Expression findParent(Expression child){ List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression parent = queue.remove(0); List<Expression> children = traverse(parent); for(Expression possibleChild : children){ if(child.equals(possibleChild)){ // found parent return parent; } } queue.addAll(children); } return null; } private void replace(Expression exp, Expression newChild) { // System.out.println("replace\n"+exp+"\nwith\n"+newChild); Expression parent = findParent(exp); - System.out.println("parent\n"+parent); +// System.out.println("parent\n"+parent); if(parent == null){ expression = newChild; } else { Expression child; ArrayList<Expression> children; switch(parent.getTyp()){ case NOT: child = new NotExpression(newChild); replace(parent, child); break; case IMPLICATION: if(((ImplicationExpression) parent).getPremise().equals(exp)){ child = new ImplicationExpression(newChild, ((ImplicationExpression) parent).getConclusion()); } else { child = new ImplicationExpression(((ImplicationExpression) parent).getPremise(), newChild); } replace(parent, child); break; case EQUIVALENCE: if(((EquivalenceExpression) parent).getExpression1().equals(exp)){ child = new EquivalenceExpression(newChild, ((EquivalenceExpression) parent).getExpression2()); } else { child = new EquivalenceExpression(((EquivalenceExpression) parent).getExpression1(), newChild); } replace(parent, child); break; case XOR: if(((XorExpression) parent).getExpression1().equals(exp)){ child = new XorExpression(newChild, ((XorExpression) parent).getExpression2()); } else { child = new XorExpression(((XorExpression) parent).getExpression1(), newChild); } replace(parent, child); break; case AND: children = new ArrayList<Expression>(); for(Expression possibleChild : ((AndExpression) parent).getExpressions()){ if(!possibleChild.equals(exp)){ children.add(possibleChild); } else { children.add(newChild); } } child = new AndExpression(children); replace(parent, child); break; case OR: children = new ArrayList<Expression>(); for(Expression possibleChild : ((OrExpression) parent).getExpressions()){ if(!possibleChild.equals(exp)){ children.add(possibleChild); } else { children.add(newChild); } } child = new OrExpression(children); replace(parent, child); break; } } } } \ No newline at end of file
Agriculture/LogicInterpreter
e960decee438052dcc5cb7250f5754448f63835a
eliminate equivalence, xor
diff --git a/src/MyInterpreter.java b/src/MyInterpreter.java index dbd3aff..4c03f7c 100644 --- a/src/MyInterpreter.java +++ b/src/MyInterpreter.java @@ -1,242 +1,258 @@ import logicinterpreter.base.*; import logicinterpreter.cnf.*; import logicinterpreter.expressions.*; import java.util.*; public class MyInterpreter implements IInterpreter { private Expression expression; //Bereitstellen der sowieso nötigen Umwandlung in konjunktive //Normalform public CnfExpression toCnf(Expression expression) { //Expression ist die Basisklasse für viele mögliche Ausdrücke: Konstanten, Symbole, Und-verknüpfte Ausdrücke, ... //welche davon gemeint ist, erfährt man über getTyp() //Die Expression kann man dann in die entsprechende Klasse casten, um ihre Details auszulesen //und sie in KNF umwandeln zu können: //if(expression.getTyp()==Expression.Typ.CONSTANT) //{ // ConstExpression ce=(ConstExpression) expression; // boolean val=ce.getValue(); // return makeKNFFromConst(val); //} //Die konjunktive Normalform ist wie folgt repräsentiert: //->Auf oberster Ebene gibt es die CnfExpression // ->diese beinhaltet eine Liste von Clause-Objekten (d.h. konjunktiv verknüpfte Klauseln) // ->jede Klausel beinhaltet eine List von Term-Objekten (d.h. disjunktiv verknüpfte Terme) // -> ein Term ist eine boolsche Variable, die negiert sein kann, also bspw. "A" oder "~B" //Zusammengesetzt wird das folgendermassen: //Term a=new Term("A",false); //nicht negiert //Term nicht_b=new Term("B",true); //negiert //ArrayList<Term> terme=new ArrayList<Term>(); //terme.add(a); //terme.add(nicht_b); //Clause clause=new Clause(terme); //A,~B. //ArrayList<Clause> clauses=new ArrayList<Clause>(): //clauses.add(clause); //return new CnfExpression(clauses); //KNF hat nur eine Klausel: A,~B. //**************************************** //Student begin this.expression = expression; System.out.println("start\n"+this.expression); - eliminateImplications(); + eliminateImpEquXor(); System.out.println("eliminate implications\n"+this.expression); return new CnfExpression(new ArrayList<Clause>()); //Student end //**************************************** } //Lösbarkeit des logischen Ausdrucks prüfen, falls nicht lösbar //null zurückgeben, sonst Symbolbelegung, die den Ausdruck gültig macht public HashMap<String,Boolean> getSolution(CnfExpression exprCnf) { // Es gibt 3 Möglichkeiten für diese Expression: // a) Tautologie, d.h. jede Variablenbelegung macht sie gültig // -> return new HashMap<String,Boolean>(); // b) nicht erfüllbar: // -> return null; // c) eine bestimmte Variablenbelegung macht die Aussage wahr: // -> bei der Symbolbelegung ist der Key der Name der zu belegenden Variable // und der Wert die Belegung // D.h. bei der CnfExpression "A,~B." würde die Belegung von A mit true // den Ausdruck wahr machen. Eine Lösung wäre also bspw.: // HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); // belegung.put("A",true); // return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } //Falls bereits getSolution aufgerufen wurde, weitere Lösungen suchen, //falls keine mehr gefunden wird, null zurückgeben //falls bereits in einem Schritt keine Lösung gefunden wurde, eine //Exception werfen public HashMap<String,Boolean> getNextSolution() throws Exception { //oftmals gibt es mehrere Lösungen. //Man kann den Löser dazu bringen, weitere Lösungen zu finden, indem man die //letzte Lösung negiert hinzufügt, d.h. das ist nun keine Lösung mehr. //Im obigen Bsp. war der urspüngliche KNF-Ausdruck "A,~B." //gefunden wurde die Lösung "A=true" //um weitere Lösungen zu finden fügt man "~A" zum Ausdruck hinzu und sucht erneut: //"A,~B. // ~A." //diesmal wäre eine Lösung "A=false, B=false" //d.h. //HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); //belegung.put("A",false); //belegung.put("B",false); //return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } List<Expression> traverse(Expression exp){ List<Expression> result = new LinkedList<Expression>(); switch(exp.getTyp()){ case CONSTANT: break; //do nothing case SYMBOL: break; //do nothing case NOT: result.add(((NotExpression) exp).getInnerExpression()); break; case EQUIVALENCE: result.add(((EquivalenceExpression) exp).getExpression1()); result.add(((EquivalenceExpression) exp).getExpression2()); break; case IMPLICATION: result.add(((ImplicationExpression) exp).getPremise()); result.add(((ImplicationExpression) exp).getConclusion()); break; case AND: for(Expression child : ((AndExpression) exp).getExpressions()){ result.add(child); } break; case OR: for(Expression child : ((OrExpression) exp).getExpressions()){ result.add(child); } break; case XOR: result.add(((XorExpression) exp).getExpression1()); result.add(((XorExpression) exp).getExpression2()); break; } return result; } - private void eliminateImplications() { + private void eliminateImpEquXor() { List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); // here is the work if(exp.getTyp().equals(Expression.Typ.IMPLICATION)){ ImplicationExpression var = (ImplicationExpression) exp; - // a -> b <==> b v ¬a + // from a -> b + // to b v ¬a Expression newChild = new OrExpression(var.getConclusion(), new NotExpression(var.getPremise())); replace(exp, newChild); //return; exp = newChild; // System.out.println("new Expression:\n"+expression); } - if(exp.getTyp().equals(equals(Expression.Typ.EQUIVALENCE))){ - + if(exp.getTyp().equals(Expression.Typ.EQUIVALENCE)){ + EquivalenceExpression var = (EquivalenceExpression) exp; + // from a <==> b + // to (a & b) | (¬a & ¬b) + Expression newChild = new OrExpression( new AndExpression(var.getExpression1(), var.getExpression2()), + new AndExpression(new NotExpression(var.getExpression1()), new NotExpression(var.getExpression2()))); + replace(exp, newChild); + exp = newChild; + } + if(exp.getTyp().equals(Expression.Typ.XOR)){ + XorExpression var = (XorExpression) exp; + // from a ^ b + // to (a & ¬b) | (¬a & b) + Expression newChild = new OrExpression( new AndExpression(var.getExpression1(), new NotExpression(var.getExpression2())), + new AndExpression(new NotExpression(var.getExpression1()), var.getExpression2())); + replace(exp, newChild); + exp = newChild; } queue.addAll(traverse(exp)); } } private Expression findParent(Expression child){ List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression parent = queue.remove(0); List<Expression> children = traverse(parent); for(Expression possibleChild : children){ if(child.equals(possibleChild)){ // found parent return parent; } } queue.addAll(children); } return null; } private void replace(Expression exp, Expression newChild) { // System.out.println("replace\n"+exp+"\nwith\n"+newChild); Expression parent = findParent(exp); System.out.println("parent\n"+parent); if(parent == null){ expression = newChild; } else { Expression child; ArrayList<Expression> children; switch(parent.getTyp()){ case NOT: child = new NotExpression(newChild); replace(parent, child); break; case IMPLICATION: if(((ImplicationExpression) parent).getPremise().equals(exp)){ child = new ImplicationExpression(newChild, ((ImplicationExpression) parent).getConclusion()); } else { child = new ImplicationExpression(((ImplicationExpression) parent).getPremise(), newChild); } replace(parent, child); break; case EQUIVALENCE: if(((EquivalenceExpression) parent).getExpression1().equals(exp)){ child = new EquivalenceExpression(newChild, ((EquivalenceExpression) parent).getExpression2()); } else { child = new EquivalenceExpression(((EquivalenceExpression) parent).getExpression1(), newChild); } replace(parent, child); break; case XOR: if(((XorExpression) parent).getExpression1().equals(exp)){ child = new XorExpression(newChild, ((XorExpression) parent).getExpression2()); } else { child = new XorExpression(((XorExpression) parent).getExpression1(), newChild); } replace(parent, child); break; case AND: children = new ArrayList<Expression>(); for(Expression possibleChild : ((AndExpression) parent).getExpressions()){ if(!possibleChild.equals(exp)){ children.add(possibleChild); } else { children.add(newChild); } } child = new AndExpression(children); replace(parent, child); break; case OR: children = new ArrayList<Expression>(); for(Expression possibleChild : ((OrExpression) parent).getExpressions()){ if(!possibleChild.equals(exp)){ children.add(possibleChild); } else { children.add(newChild); } } child = new OrExpression(children); replace(parent, child); break; } } } } \ No newline at end of file
Agriculture/LogicInterpreter
8b7db88a395c14e5723b472ff395a26b04b3146a
eliminate implications
diff --git a/src/MyInterpreter.java b/src/MyInterpreter.java index 499e78d..dbd3aff 100644 --- a/src/MyInterpreter.java +++ b/src/MyInterpreter.java @@ -1,172 +1,242 @@ import logicinterpreter.base.*; import logicinterpreter.cnf.*; import logicinterpreter.expressions.*; import java.util.*; public class MyInterpreter implements IInterpreter { private Expression expression; //Bereitstellen der sowieso nötigen Umwandlung in konjunktive //Normalform public CnfExpression toCnf(Expression expression) { //Expression ist die Basisklasse für viele mögliche Ausdrücke: Konstanten, Symbole, Und-verknüpfte Ausdrücke, ... //welche davon gemeint ist, erfährt man über getTyp() //Die Expression kann man dann in die entsprechende Klasse casten, um ihre Details auszulesen //und sie in KNF umwandeln zu können: //if(expression.getTyp()==Expression.Typ.CONSTANT) //{ // ConstExpression ce=(ConstExpression) expression; // boolean val=ce.getValue(); // return makeKNFFromConst(val); //} //Die konjunktive Normalform ist wie folgt repräsentiert: //->Auf oberster Ebene gibt es die CnfExpression // ->diese beinhaltet eine Liste von Clause-Objekten (d.h. konjunktiv verknüpfte Klauseln) // ->jede Klausel beinhaltet eine List von Term-Objekten (d.h. disjunktiv verknüpfte Terme) // -> ein Term ist eine boolsche Variable, die negiert sein kann, also bspw. "A" oder "~B" //Zusammengesetzt wird das folgendermassen: //Term a=new Term("A",false); //nicht negiert //Term nicht_b=new Term("B",true); //negiert //ArrayList<Term> terme=new ArrayList<Term>(); //terme.add(a); //terme.add(nicht_b); //Clause clause=new Clause(terme); //A,~B. //ArrayList<Clause> clauses=new ArrayList<Clause>(): //clauses.add(clause); //return new CnfExpression(clauses); //KNF hat nur eine Klausel: A,~B. //**************************************** //Student begin this.expression = expression; + System.out.println("start\n"+this.expression); eliminateImplications(); + System.out.println("eliminate implications\n"+this.expression); return new CnfExpression(new ArrayList<Clause>()); //Student end //**************************************** } //Lösbarkeit des logischen Ausdrucks prüfen, falls nicht lösbar //null zurückgeben, sonst Symbolbelegung, die den Ausdruck gültig macht public HashMap<String,Boolean> getSolution(CnfExpression exprCnf) { // Es gibt 3 Möglichkeiten für diese Expression: // a) Tautologie, d.h. jede Variablenbelegung macht sie gültig // -> return new HashMap<String,Boolean>(); // b) nicht erfüllbar: // -> return null; // c) eine bestimmte Variablenbelegung macht die Aussage wahr: // -> bei der Symbolbelegung ist der Key der Name der zu belegenden Variable // und der Wert die Belegung // D.h. bei der CnfExpression "A,~B." würde die Belegung von A mit true // den Ausdruck wahr machen. Eine Lösung wäre also bspw.: // HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); // belegung.put("A",true); // return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } //Falls bereits getSolution aufgerufen wurde, weitere Lösungen suchen, //falls keine mehr gefunden wird, null zurückgeben //falls bereits in einem Schritt keine Lösung gefunden wurde, eine //Exception werfen public HashMap<String,Boolean> getNextSolution() throws Exception { //oftmals gibt es mehrere Lösungen. //Man kann den Löser dazu bringen, weitere Lösungen zu finden, indem man die //letzte Lösung negiert hinzufügt, d.h. das ist nun keine Lösung mehr. //Im obigen Bsp. war der urspüngliche KNF-Ausdruck "A,~B." //gefunden wurde die Lösung "A=true" //um weitere Lösungen zu finden fügt man "~A" zum Ausdruck hinzu und sucht erneut: //"A,~B. // ~A." //diesmal wäre eine Lösung "A=false, B=false" //d.h. //HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); //belegung.put("A",false); //belegung.put("B",false); //return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } List<Expression> traverse(Expression exp){ List<Expression> result = new LinkedList<Expression>(); switch(exp.getTyp()){ case CONSTANT: break; //do nothing case SYMBOL: break; //do nothing case NOT: result.add(((NotExpression) exp).getInnerExpression()); break; case EQUIVALENCE: result.add(((EquivalenceExpression) exp).getExpression1()); result.add(((EquivalenceExpression) exp).getExpression2()); break; case IMPLICATION: result.add(((ImplicationExpression) exp).getPremise()); result.add(((ImplicationExpression) exp).getConclusion()); break; case AND: for(Expression child : ((AndExpression) exp).getExpressions()){ result.add(child); } break; case OR: for(Expression child : ((OrExpression) exp).getExpressions()){ result.add(child); } break; case XOR: result.add(((XorExpression) exp).getExpression1()); result.add(((XorExpression) exp).getExpression2()); break; } return result; } private void eliminateImplications() { List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); // here is the work if(exp.getTyp().equals(Expression.Typ.IMPLICATION)){ - System.out.println("implication found "+exp); - System.out.println("parent is "+findParent(exp)); + ImplicationExpression var = (ImplicationExpression) exp; + // a -> b <==> b v ¬a + Expression newChild = new OrExpression(var.getConclusion(), new NotExpression(var.getPremise())); + replace(exp, newChild); + //return; + exp = newChild; +// System.out.println("new Expression:\n"+expression); } + if(exp.getTyp().equals(equals(Expression.Typ.EQUIVALENCE))){ + + } queue.addAll(traverse(exp)); } } private Expression findParent(Expression child){ List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression parent = queue.remove(0); List<Expression> children = traverse(parent); for(Expression possibleChild : children){ if(child.equals(possibleChild)){ // found parent return parent; } } queue.addAll(children); } return null; } + private void replace(Expression exp, Expression newChild) { +// System.out.println("replace\n"+exp+"\nwith\n"+newChild); + Expression parent = findParent(exp); + System.out.println("parent\n"+parent); + if(parent == null){ + expression = newChild; + } else { + Expression child; + ArrayList<Expression> children; + switch(parent.getTyp()){ + case NOT: child = new NotExpression(newChild); + replace(parent, child); + break; + case IMPLICATION: if(((ImplicationExpression) parent).getPremise().equals(exp)){ + child = new ImplicationExpression(newChild, ((ImplicationExpression) parent).getConclusion()); + } else { + child = new ImplicationExpression(((ImplicationExpression) parent).getPremise(), newChild); + } + replace(parent, child); + break; + case EQUIVALENCE: if(((EquivalenceExpression) parent).getExpression1().equals(exp)){ + child = new EquivalenceExpression(newChild, ((EquivalenceExpression) parent).getExpression2()); + } else { + child = new EquivalenceExpression(((EquivalenceExpression) parent).getExpression1(), newChild); + } + replace(parent, child); + break; + case XOR: if(((XorExpression) parent).getExpression1().equals(exp)){ + child = new XorExpression(newChild, ((XorExpression) parent).getExpression2()); + } else { + child = new XorExpression(((XorExpression) parent).getExpression1(), newChild); + } + replace(parent, child); + break; + case AND: children = new ArrayList<Expression>(); + for(Expression possibleChild : ((AndExpression) parent).getExpressions()){ + if(!possibleChild.equals(exp)){ + children.add(possibleChild); + } else { + children.add(newChild); + } + } + child = new AndExpression(children); + replace(parent, child); + break; + case OR: children = new ArrayList<Expression>(); + for(Expression possibleChild : ((OrExpression) parent).getExpressions()){ + if(!possibleChild.equals(exp)){ + children.add(possibleChild); + } else { + children.add(newChild); + } + } + child = new OrExpression(children); + replace(parent, child); + break; + } + } + } + } \ No newline at end of file
Agriculture/LogicInterpreter
e1ac6aee6e6b5ee95fa9feea43d6c2f99fc18c21
findParent
diff --git a/src/MyInterpreter.java b/src/MyInterpreter.java index e45ab56..499e78d 100644 --- a/src/MyInterpreter.java +++ b/src/MyInterpreter.java @@ -1,153 +1,172 @@ import logicinterpreter.base.*; import logicinterpreter.cnf.*; import logicinterpreter.expressions.*; import java.util.*; public class MyInterpreter implements IInterpreter { private Expression expression; //Bereitstellen der sowieso nötigen Umwandlung in konjunktive //Normalform public CnfExpression toCnf(Expression expression) { //Expression ist die Basisklasse für viele mögliche Ausdrücke: Konstanten, Symbole, Und-verknüpfte Ausdrücke, ... //welche davon gemeint ist, erfährt man über getTyp() //Die Expression kann man dann in die entsprechende Klasse casten, um ihre Details auszulesen //und sie in KNF umwandeln zu können: //if(expression.getTyp()==Expression.Typ.CONSTANT) //{ // ConstExpression ce=(ConstExpression) expression; // boolean val=ce.getValue(); // return makeKNFFromConst(val); //} //Die konjunktive Normalform ist wie folgt repräsentiert: //->Auf oberster Ebene gibt es die CnfExpression // ->diese beinhaltet eine Liste von Clause-Objekten (d.h. konjunktiv verknüpfte Klauseln) // ->jede Klausel beinhaltet eine List von Term-Objekten (d.h. disjunktiv verknüpfte Terme) // -> ein Term ist eine boolsche Variable, die negiert sein kann, also bspw. "A" oder "~B" //Zusammengesetzt wird das folgendermassen: //Term a=new Term("A",false); //nicht negiert //Term nicht_b=new Term("B",true); //negiert //ArrayList<Term> terme=new ArrayList<Term>(); //terme.add(a); //terme.add(nicht_b); //Clause clause=new Clause(terme); //A,~B. //ArrayList<Clause> clauses=new ArrayList<Clause>(): //clauses.add(clause); //return new CnfExpression(clauses); //KNF hat nur eine Klausel: A,~B. //**************************************** //Student begin this.expression = expression; - System.out.println(expression); - eliminateImplications() - switch(expression.getTyp()){ - case CONSTANT: - ConstExpression val=(ConstExpression) expression; - break; - } + eliminateImplications(); return new CnfExpression(new ArrayList<Clause>()); //Student end //**************************************** } //Lösbarkeit des logischen Ausdrucks prüfen, falls nicht lösbar //null zurückgeben, sonst Symbolbelegung, die den Ausdruck gültig macht public HashMap<String,Boolean> getSolution(CnfExpression exprCnf) { // Es gibt 3 Möglichkeiten für diese Expression: // a) Tautologie, d.h. jede Variablenbelegung macht sie gültig // -> return new HashMap<String,Boolean>(); // b) nicht erfüllbar: // -> return null; // c) eine bestimmte Variablenbelegung macht die Aussage wahr: // -> bei der Symbolbelegung ist der Key der Name der zu belegenden Variable // und der Wert die Belegung // D.h. bei der CnfExpression "A,~B." würde die Belegung von A mit true // den Ausdruck wahr machen. Eine Lösung wäre also bspw.: // HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); // belegung.put("A",true); // return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } //Falls bereits getSolution aufgerufen wurde, weitere Lösungen suchen, //falls keine mehr gefunden wird, null zurückgeben //falls bereits in einem Schritt keine Lösung gefunden wurde, eine //Exception werfen public HashMap<String,Boolean> getNextSolution() throws Exception { //oftmals gibt es mehrere Lösungen. //Man kann den Löser dazu bringen, weitere Lösungen zu finden, indem man die //letzte Lösung negiert hinzufügt, d.h. das ist nun keine Lösung mehr. //Im obigen Bsp. war der urspüngliche KNF-Ausdruck "A,~B." //gefunden wurde die Lösung "A=true" //um weitere Lösungen zu finden fügt man "~A" zum Ausdruck hinzu und sucht erneut: //"A,~B. // ~A." //diesmal wäre eine Lösung "A=false, B=false" //d.h. //HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); //belegung.put("A",false); //belegung.put("B",false); //return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } List<Expression> traverse(Expression exp){ List<Expression> result = new LinkedList<Expression>(); switch(exp.getTyp()){ case CONSTANT: break; //do nothing case SYMBOL: break; //do nothing case NOT: result.add(((NotExpression) exp).getInnerExpression()); break; case EQUIVALENCE: result.add(((EquivalenceExpression) exp).getExpression1()); result.add(((EquivalenceExpression) exp).getExpression2()); break; case IMPLICATION: result.add(((ImplicationExpression) exp).getPremise()); result.add(((ImplicationExpression) exp).getConclusion()); break; case AND: for(Expression child : ((AndExpression) exp).getExpressions()){ result.add(child); } break; case OR: for(Expression child : ((OrExpression) exp).getExpressions()){ result.add(child); } break; case XOR: result.add(((XorExpression) exp).getExpression1()); result.add(((XorExpression) exp).getExpression2()); break; } - return result; } private void eliminateImplications() { List<Expression> queue = new LinkedList<Expression>(); queue.add(expression); while(!queue.isEmpty()){ Expression exp = queue.remove(0); + + // here is the work + if(exp.getTyp().equals(Expression.Typ.IMPLICATION)){ + System.out.println("implication found "+exp); + System.out.println("parent is "+findParent(exp)); + } + queue.addAll(traverse(exp)); } } + private Expression findParent(Expression child){ + List<Expression> queue = new LinkedList<Expression>(); + queue.add(expression); + while(!queue.isEmpty()){ + Expression parent = queue.remove(0); + List<Expression> children = traverse(parent); + for(Expression possibleChild : children){ + if(child.equals(possibleChild)){ + // found parent + return parent; + } + } + queue.addAll(children); + } + + + return null; + } + } \ No newline at end of file
Agriculture/LogicInterpreter
181a4c3b5a3b454dbb57b85ed5e130b20875c839
traverse
diff --git a/src/MyInterpreter.java b/src/MyInterpreter.java index f54d5ec..e45ab56 100644 --- a/src/MyInterpreter.java +++ b/src/MyInterpreter.java @@ -1,104 +1,153 @@ import logicinterpreter.base.*; import logicinterpreter.cnf.*; import logicinterpreter.expressions.*; import java.util.*; public class MyInterpreter implements IInterpreter { + private Expression expression; //Bereitstellen der sowieso nötigen Umwandlung in konjunktive //Normalform public CnfExpression toCnf(Expression expression) { //Expression ist die Basisklasse für viele mögliche Ausdrücke: Konstanten, Symbole, Und-verknüpfte Ausdrücke, ... //welche davon gemeint ist, erfährt man über getTyp() //Die Expression kann man dann in die entsprechende Klasse casten, um ihre Details auszulesen //und sie in KNF umwandeln zu können: //if(expression.getTyp()==Expression.Typ.CONSTANT) //{ // ConstExpression ce=(ConstExpression) expression; // boolean val=ce.getValue(); // return makeKNFFromConst(val); //} //Die konjunktive Normalform ist wie folgt repräsentiert: //->Auf oberster Ebene gibt es die CnfExpression // ->diese beinhaltet eine Liste von Clause-Objekten (d.h. konjunktiv verknüpfte Klauseln) // ->jede Klausel beinhaltet eine List von Term-Objekten (d.h. disjunktiv verknüpfte Terme) // -> ein Term ist eine boolsche Variable, die negiert sein kann, also bspw. "A" oder "~B" //Zusammengesetzt wird das folgendermassen: //Term a=new Term("A",false); //nicht negiert //Term nicht_b=new Term("B",true); //negiert //ArrayList<Term> terme=new ArrayList<Term>(); //terme.add(a); //terme.add(nicht_b); //Clause clause=new Clause(terme); //A,~B. //ArrayList<Clause> clauses=new ArrayList<Clause>(): //clauses.add(clause); //return new CnfExpression(clauses); //KNF hat nur eine Klausel: A,~B. //**************************************** //Student begin + this.expression = expression; + System.out.println(expression); + eliminateImplications() + switch(expression.getTyp()){ + case CONSTANT: + ConstExpression val=(ConstExpression) expression; + break; + } return new CnfExpression(new ArrayList<Clause>()); //Student end //**************************************** } //Lösbarkeit des logischen Ausdrucks prüfen, falls nicht lösbar //null zurückgeben, sonst Symbolbelegung, die den Ausdruck gültig macht public HashMap<String,Boolean> getSolution(CnfExpression exprCnf) { // Es gibt 3 Möglichkeiten für diese Expression: // a) Tautologie, d.h. jede Variablenbelegung macht sie gültig // -> return new HashMap<String,Boolean>(); // b) nicht erfüllbar: // -> return null; // c) eine bestimmte Variablenbelegung macht die Aussage wahr: // -> bei der Symbolbelegung ist der Key der Name der zu belegenden Variable // und der Wert die Belegung // D.h. bei der CnfExpression "A,~B." würde die Belegung von A mit true // den Ausdruck wahr machen. Eine Lösung wäre also bspw.: // HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); // belegung.put("A",true); // return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } //Falls bereits getSolution aufgerufen wurde, weitere Lösungen suchen, //falls keine mehr gefunden wird, null zurückgeben //falls bereits in einem Schritt keine Lösung gefunden wurde, eine //Exception werfen public HashMap<String,Boolean> getNextSolution() throws Exception { //oftmals gibt es mehrere Lösungen. //Man kann den Löser dazu bringen, weitere Lösungen zu finden, indem man die //letzte Lösung negiert hinzufügt, d.h. das ist nun keine Lösung mehr. //Im obigen Bsp. war der urspüngliche KNF-Ausdruck "A,~B." //gefunden wurde die Lösung "A=true" //um weitere Lösungen zu finden fügt man "~A" zum Ausdruck hinzu und sucht erneut: //"A,~B. // ~A." //diesmal wäre eine Lösung "A=false, B=false" //d.h. //HashMap<String,Boolean> belegung=new HashMap<String,Boolean>(); //belegung.put("A",false); //belegung.put("B",false); //return belegung; //**************************************** //Student begin return null; //Student end //**************************************** } + + List<Expression> traverse(Expression exp){ + List<Expression> result = new LinkedList<Expression>(); + switch(exp.getTyp()){ + case CONSTANT: break; //do nothing + case SYMBOL: break; //do nothing + case NOT: result.add(((NotExpression) exp).getInnerExpression()); + break; + case EQUIVALENCE: result.add(((EquivalenceExpression) exp).getExpression1()); + result.add(((EquivalenceExpression) exp).getExpression2()); + break; + case IMPLICATION: result.add(((ImplicationExpression) exp).getPremise()); + result.add(((ImplicationExpression) exp).getConclusion()); + break; + case AND: for(Expression child : ((AndExpression) exp).getExpressions()){ + result.add(child); + } + break; + case OR: for(Expression child : ((OrExpression) exp).getExpressions()){ + result.add(child); + } + break; + case XOR: result.add(((XorExpression) exp).getExpression1()); + result.add(((XorExpression) exp).getExpression2()); + break; + } + + return result; + } + + private void eliminateImplications() { + List<Expression> queue = new LinkedList<Expression>(); + queue.add(expression); + while(!queue.isEmpty()){ + Expression exp = queue.remove(0); + queue.addAll(traverse(exp)); + } + + } + } \ No newline at end of file
mushon/dontFriendMe
96cc9c7e668bdc20f20942df73f6d568fe683413
adding titlecase
diff --git a/dontFriendMe.user.js b/dontFriendMe.user.js index 23ff461..567653c 100644 --- a/dontFriendMe.user.js +++ b/dontFriendMe.user.js @@ -1,54 +1,57 @@ // ==UserScript== // @name Don't "Friend" me! // @namespace http://mushon.com/ // @description Fixes Facebook's social terminology - Replaces the words "friend" & "ignore" with the words "contact" & "skip" // @include http://www.facebook.com/* // @include http://facebook.com/* // @copyright Modified by Mushon Zer-Aviv [http://bit.ly/friending-me] based on JoeSimmons "Replace Text On Webpages" / http://userscripts.org/scripts/review/41369 // @version 1.0.00 -// @license http://creativecommons.org/licenses/by-nc-nd/3.0/us/ // ==/UserScript== var words = { /////////////////////////////////////////////////////// // Syntax: 'Search word' : 'Replace word', "friend" : "contact", "friends" : "contacts", "ignore" : "skip", "unfriend" : "disconnect", +"Friend" : "Contact", +"Friends" : "Contacts", +"Ignore" : "Skip", +"Unfriend" : "Disconnect", /////////////////////////////////////////////////////// "":""}; ////////////////////////////////////////////////////////////////////////////// // This is where the real code is // Don't edit below this ////////////////////////////////////////////////////////////////////////////// // prepareRegex by JoeSimmons // Used to take a string and ready it for use in new RegExp() String.prototype.prepareRegex = function() { return this.replace(/([\[\]\^\&\$\.\(\)\?\/\\\+\{\}\|])/g, "\\$1"); }; function isOkTag(tag) { return (",pre,blockquote,code,input,button,textarea".indexOf(","+tag) == -1); } var regexs=new Array(), replacements=new Array(); for(var word in words) { if(word != "") { regexs.push(new RegExp("\\b"+word.prepareRegex().replace(/\*/g,'[^ ]*')+"\\b", 'gi')); replacements.push(words[word]); } } var texts = document.evaluate(".//text()[normalize-space(.)!='']",document.body,null,6,null), text=""; for(var i=0,l=texts.snapshotLength; (this_text=texts.snapshotItem(i)); i++) { if(isOkTag(this_text.parentNode.tagName.toLowerCase()) && (text=this_text.textContent)) { for(var x=0,l=regexs.length; x<l; x++) { text = text.replace(regexs[x], replacements[x]); this_text.textContent = text; } } } \ No newline at end of file
mushon/dontFriendMe
901bdb76921c49112df4fe52c6373be33a938240
adding userscript
diff --git a/dontFriendMe.user.js b/dontFriendMe.user.js new file mode 100644 index 0000000..23ff461 --- /dev/null +++ b/dontFriendMe.user.js @@ -0,0 +1,54 @@ +// ==UserScript== +// @name Don't "Friend" me! +// @namespace http://mushon.com/ +// @description Fixes Facebook's social terminology - Replaces the words "friend" & "ignore" with the words "contact" & "skip" +// @include http://www.facebook.com/* +// @include http://facebook.com/* +// @copyright Modified by Mushon Zer-Aviv [http://bit.ly/friending-me] based on JoeSimmons "Replace Text On Webpages" / http://userscripts.org/scripts/review/41369 +// @version 1.0.00 +// @license http://creativecommons.org/licenses/by-nc-nd/3.0/us/ +// ==/UserScript== + +var words = { +/////////////////////////////////////////////////////// +// Syntax: 'Search word' : 'Replace word', +"friend" : "contact", +"friends" : "contacts", +"ignore" : "skip", +"unfriend" : "disconnect", +/////////////////////////////////////////////////////// +"":""}; + +////////////////////////////////////////////////////////////////////////////// +// This is where the real code is +// Don't edit below this +////////////////////////////////////////////////////////////////////////////// + +// prepareRegex by JoeSimmons +// Used to take a string and ready it for use in new RegExp() +String.prototype.prepareRegex = function() { +return this.replace(/([\[\]\^\&\$\.\(\)\?\/\\\+\{\}\|])/g, "\\$1"); +}; + +function isOkTag(tag) { +return (",pre,blockquote,code,input,button,textarea".indexOf(","+tag) == -1); +} + +var regexs=new Array(), + replacements=new Array(); +for(var word in words) { +if(word != "") { +regexs.push(new RegExp("\\b"+word.prepareRegex().replace(/\*/g,'[^ ]*')+"\\b", 'gi')); +replacements.push(words[word]); +} +} + +var texts = document.evaluate(".//text()[normalize-space(.)!='']",document.body,null,6,null), text=""; +for(var i=0,l=texts.snapshotLength; (this_text=texts.snapshotItem(i)); i++) { + if(isOkTag(this_text.parentNode.tagName.toLowerCase()) && (text=this_text.textContent)) { + for(var x=0,l=regexs.length; x<l; x++) { + text = text.replace(regexs[x], replacements[x]); + this_text.textContent = text; + } + } +} \ No newline at end of file
trith/trith
c8fd0e8e9ac4586ffa0a91c4844787219ae9aaf8
Added a simple Autoconf check for the Raptor library.
diff --git a/configure.ac b/configure.ac index fd2e9a2..8ab68a6 100644 --- a/configure.ac +++ b/configure.ac @@ -1,18 +1,20 @@ AC_INIT([trith], [0.0.4], [[email protected]]) AC_CONFIG_SRCDIR([src/trith.h]) AC_CONFIG_AUX_DIR([etc/aclocal]) AC_CONFIG_MACRO_DIR([etc/aclocal]) AM_INIT_AUTOMAKE([foreign -Wall -Werror dist-bzip2]) AM_SILENT_RULES([yes]) LT_INIT AC_PROG_CC AM_PATH_GLIB_2_0([2.24.0], [], [], [gthread-2.0]) AC_CHECK_HEADERS(gmp.h) AC_CHECK_LIB(gmp, __gmpz_init) AC_CHECK_HEADERS(mpfr.h) AC_CHECK_LIB(mpfr, mpfr_init) AC_CHECK_HEADERS(ffi.h) AC_CHECK_LIB(ffi, ffi_call) +AC_CHECK_HEADERS(raptor.h) +AC_CHECK_LIB(raptor, raptor_init) AC_CONFIG_HEADERS([config.h]) AC_CONFIG_FILES([Makefile src/Makefile doc/Makefile doc/man/Makefile]) AC_OUTPUT
trith/trith
29be7765bdc1fb8c7b368d403822f8c4ebfb9177
Added a simple Autoconf check for the FFI library.
diff --git a/configure.ac b/configure.ac index 2cf52e7..fd2e9a2 100644 --- a/configure.ac +++ b/configure.ac @@ -1,16 +1,18 @@ AC_INIT([trith], [0.0.4], [[email protected]]) AC_CONFIG_SRCDIR([src/trith.h]) AC_CONFIG_AUX_DIR([etc/aclocal]) AC_CONFIG_MACRO_DIR([etc/aclocal]) AM_INIT_AUTOMAKE([foreign -Wall -Werror dist-bzip2]) AM_SILENT_RULES([yes]) LT_INIT AC_PROG_CC AM_PATH_GLIB_2_0([2.24.0], [], [], [gthread-2.0]) AC_CHECK_HEADERS(gmp.h) AC_CHECK_LIB(gmp, __gmpz_init) AC_CHECK_HEADERS(mpfr.h) AC_CHECK_LIB(mpfr, mpfr_init) +AC_CHECK_HEADERS(ffi.h) +AC_CHECK_LIB(ffi, ffi_call) AC_CONFIG_HEADERS([config.h]) AC_CONFIG_FILES([Makefile src/Makefile doc/Makefile doc/man/Makefile]) AC_OUTPUT
trith/trith
584b6f11dc73baf60ef2a1fdb3f7b24a190d6c1f
Added simple Autoconf checks for the GMP and MPFR libraries.
diff --git a/configure.ac b/configure.ac index 40d2b80..2cf52e7 100644 --- a/configure.ac +++ b/configure.ac @@ -1,12 +1,16 @@ AC_INIT([trith], [0.0.4], [[email protected]]) AC_CONFIG_SRCDIR([src/trith.h]) AC_CONFIG_AUX_DIR([etc/aclocal]) AC_CONFIG_MACRO_DIR([etc/aclocal]) AM_INIT_AUTOMAKE([foreign -Wall -Werror dist-bzip2]) AM_SILENT_RULES([yes]) LT_INIT AC_PROG_CC AM_PATH_GLIB_2_0([2.24.0], [], [], [gthread-2.0]) +AC_CHECK_HEADERS(gmp.h) +AC_CHECK_LIB(gmp, __gmpz_init) +AC_CHECK_HEADERS(mpfr.h) +AC_CHECK_LIB(mpfr, mpfr_init) AC_CONFIG_HEADERS([config.h]) AC_CONFIG_FILES([Makefile src/Makefile doc/Makefile doc/man/Makefile]) AC_OUTPUT
trith/trith
e2aa05d35eb2a2ac09371f435f561938680f1f94
Implemented the basic control and stack operators in C.
diff --git a/src/trith.c b/src/trith.c index 6bee1b8..7cf5a2d 100644 --- a/src/trith.c +++ b/src/trith.c @@ -1,75 +1,265 @@ /* This is free and unencumbered software released into the public domain. */ #include <assert.h> #include <stdio.h> #include <string.h> #include <strings.h> #include <math.h> + +#define __TRITH_INIT__ #include "trith.h" #include "config.h" ////////////////////////////////////////////////////////////////////////////// // Constants const char* const trith_version_string = PACKAGE_VERSION; +trith_value trith_false = { .type = TRITH_BOOL, .value.boolean = FALSE }; +trith_value trith_true = { .type = TRITH_BOOL, .value.boolean = TRUE }; + +////////////////////////////////////////////////////////////////////////////// +// Machine internals + +static inline void +trith_stack_init(trith_stack* stack) { + assert(stack != NULL); + g_queue_init(stack); +} + +static inline void +trith_stack_clear(trith_stack* stack) { + assert(stack != NULL); + // TODO: deallocate values + g_queue_clear(stack); +} + +static inline guint +trith_stack_size(const trith_stack* stack) { + return g_queue_get_length((trith_stack*)stack); +} + +static inline bool +trith_stack_is_empty(const trith_stack* stack) { + return trith_stack_size(stack) == 0; +} + +static inline trith_value* +trith_stack_peek(const trith_stack* stack) { + assert(stack != NULL); + return g_queue_peek_head((trith_stack*)stack); +} + +static inline trith_value* +trith_stack_pop(trith_stack* stack) { + assert(stack != NULL); + return g_queue_pop_head(stack); +} + +static inline void +trith_stack_push(trith_stack* stack, trith_value* value) { + assert(stack != NULL); + g_queue_push_head(stack, value); +} + +static inline bool +trith_ensure_stack_size(trith_machine* machine, size_t size) { + if (trith_stack_size(&machine->stack) < size) { + machine->error = TRITH_ERROR_STACK_UNDERFLOW; + return FALSE; + } + return TRUE; +} + ////////////////////////////////////////////////////////////////////////////// // Machine API trith_machine* trith_machine_alloc() { return trith_slice_alloc(sizeof(trith_machine)); } trith_machine* trith_machine_new() { trith_machine* machine = trith_machine_alloc(); trith_machine_init(machine); return machine; } trith_machine* trith_machine_copy(const trith_machine* machine) { assert(machine != NULL); trith_machine* copy = trith_machine_new(); // copy the stack: for (GList* list = machine->stack.head; list != NULL; list = list->next) { g_queue_push_tail(&copy->stack, list->data); } // copy the queue: for (GList* list = machine->queue.head; list != NULL; list = list->next) { g_queue_push_tail(&copy->queue, list->data); } // copy the context: copy->context.parent = machine->context.parent; GHashTableIter iter; gpointer key, value; g_hash_table_iter_init(&iter, machine->context.locals); while (g_hash_table_iter_next(&iter, &key, &value) != FALSE) { g_hash_table_insert(copy->context.locals, &key, &value); } return copy; } void trith_machine_init(trith_machine* machine) { assert(machine != NULL); - g_queue_init(&machine->stack); - g_queue_init(&machine->queue); + machine->error = TRITH_ERROR_NONE; + trith_stack_init(&machine->stack); + trith_stack_init(&machine->queue); machine->context.parent = NULL; machine->context.locals = g_hash_table_new(NULL, NULL); } void trith_machine_free(trith_machine* machine) { assert(machine != NULL); - g_queue_clear(&machine->stack); - g_queue_clear(&machine->queue); + trith_stack_clear(&machine->stack); + trith_stack_clear(&machine->queue); if (machine->context.locals) { g_hash_table_destroy(machine->context.locals); } trith_slice_free(sizeof(trith_machine), machine); } +trith_value* +trith_machine_peek(const trith_machine* machine) { + assert(machine != NULL); + return trith_stack_peek(&machine->stack); +} + +trith_value* +trith_machine_pop(trith_machine* machine) { + assert(machine != NULL); + return trith_stack_pop(&machine->stack); +} + +void +trith_machine_push(trith_machine* machine, trith_value* value) { + assert(machine != NULL); + trith_stack_push(&machine->stack, value); +} + +////////////////////////////////////////////////////////////////////////////// +// Control operators + +void +trith_op_halt(trith_machine* machine) { + assert(machine != NULL); + trith_stack_clear(&machine->queue); +} + +void +trith_op_reset(trith_machine* machine) { + assert(machine != NULL); + machine->error = TRITH_ERROR_NONE; + trith_stack_clear(&machine->stack); + trith_stack_clear(&machine->queue); + g_hash_table_remove_all(machine->context.locals); +} + +void +trith_op_nop(trith_machine* machine) { + assert(machine != NULL); + // do nothing +} + ////////////////////////////////////////////////////////////////////////////// -// Operators +// Stack operators + +void +trith_op_clear(trith_machine* machine) { + assert(machine != NULL); + trith_stack_clear(&machine->stack); +} + +void +trith_op_depth(trith_machine* machine) { + assert(machine != NULL); + trith_value* depth = trith_malloc(sizeof(trith_value)); + depth->value.integer = trith_stack_size(&machine->stack); + trith_stack_push(&machine->stack, depth); +} + +void +trith_op_pop(trith_machine* machine) { + assert(machine != NULL); + if (trith_ensure_stack_size(machine, 1)) { + trith_stack_pop(&machine->stack); + } +} + +void +trith_op_pop2(trith_machine* machine) { + assert(machine != NULL); + if (trith_ensure_stack_size(machine, 2)) { + trith_stack_pop(&machine->stack); + trith_stack_pop(&machine->stack); + } +} + +void +trith_op_pop3(trith_machine* machine) { + assert(machine != NULL); + if (trith_ensure_stack_size(machine, 3)) { + trith_stack_pop(&machine->stack); + trith_stack_pop(&machine->stack); + trith_stack_pop(&machine->stack); + } +} + +void +trith_op_dup(trith_machine* machine) { + assert(machine != NULL); + if (trith_ensure_stack_size(machine, 1)) { + trith_stack_push(&machine->stack, trith_stack_peek(&machine->stack)); + } +} + +void +trith_op_dup2(trith_machine* machine) { + assert(machine != NULL); + if (trith_ensure_stack_size(machine, 2)) { + trith_value* a = trith_stack_pop(&machine->stack); + trith_value* b = trith_stack_pop(&machine->stack); + trith_stack_push(&machine->stack, b); + trith_stack_push(&machine->stack, a); + trith_stack_push(&machine->stack, b); + trith_stack_push(&machine->stack, a); + } +} + +void +trith_op_dup3(trith_machine* machine) { + assert(machine != NULL); + if (trith_ensure_stack_size(machine, 3)) { + trith_value* a = trith_stack_pop(&machine->stack); + trith_value* b = trith_stack_pop(&machine->stack); + trith_value* c = trith_stack_pop(&machine->stack); + trith_stack_push(&machine->stack, c); + trith_stack_push(&machine->stack, b); + trith_stack_push(&machine->stack, a); + trith_stack_push(&machine->stack, c); + trith_stack_push(&machine->stack, b); + trith_stack_push(&machine->stack, a); + } +} + +void +trith_op_swap(trith_machine* machine) { + assert(machine != NULL); + if (trith_ensure_stack_size(machine, 2)) { + trith_value* a = trith_stack_pop(&machine->stack); + trith_value* b = trith_stack_pop(&machine->stack); + trith_stack_push(&machine->stack, a); + trith_stack_push(&machine->stack, b); + } +} diff --git a/src/trith.h b/src/trith.h index d68e36a..7e1188d 100644 --- a/src/trith.h +++ b/src/trith.h @@ -1,67 +1,118 @@ /* This is free and unencumbered software released into the public domain. */ #ifndef TRITH_H #define TRITH_H #ifdef __cplusplus extern "C" { #endif #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include <glib.h> ////////////////////////////////////////////////////////////////////////////// -// Constants - -extern const char* const trith_version_string; - -////////////////////////////////////////////////////////////////////////////// -// Machine API +// Types typedef GQueue trith_stack; typedef GQueue trith_queue; typedef GHashTable trith_table; typedef struct { struct trith_context* parent; trith_table* locals; } trith_context; +typedef enum { + TRITH_ERROR_NONE = 0, + TRITH_ERROR_STACK_UNDERFLOW, +} trith_error; + typedef struct { + trith_error error; trith_stack stack; trith_queue queue; trith_context context; void* user_data; } trith_machine; +typedef enum { + TRITH_NIL = 0, + TRITH_BOOL, + TRITH_INT, + TRITH_LIST, + TRITH_OP, +} trith_type; + +typedef void (*trith_op)(trith_machine* machine); + +typedef struct { + trith_type type; + union value { + bool boolean; + gint integer; + } value; +} trith_value; + +////////////////////////////////////////////////////////////////////////////// +// Constants + +extern const char* const trith_version_string; + +#ifndef __TRITH_INIT__ +extern const trith_value trith_false; +extern const trith_value trith_true; +#endif + +////////////////////////////////////////////////////////////////////////////// +// Machine + extern trith_machine* trith_machine_alloc(); extern trith_machine* trith_machine_new(); extern trith_machine* trith_machine_copy(const trith_machine* machine); extern void trith_machine_init(trith_machine* machine); extern void trith_machine_free(trith_machine* machine); +extern trith_value* trith_machine_peek(const trith_machine* machine); +extern trith_value* trith_machine_pop(trith_machine* machine); +extern void trith_machine_push(trith_machine* machine, trith_value* value); ////////////////////////////////////////////////////////////////////////////// // Operators +// Control operators +extern void trith_op_halt(trith_machine* machine); +extern void trith_op_reset(trith_machine* machine); +extern void trith_op_nop(trith_machine* machine); + +// Stack operators +extern void trith_op_clear(trith_machine* machine); +extern void trith_op_depth(trith_machine* machine); +extern void trith_op_pop(trith_machine* machine); +extern void trith_op_pop2(trith_machine* machine); +extern void trith_op_pop3(trith_machine* machine); +extern void trith_op_dup(trith_machine* machine); +extern void trith_op_dup2(trith_machine* machine); +extern void trith_op_dup3(trith_machine* machine); +extern void trith_op_swap(trith_machine* machine); + ////////////////////////////////////////////////////////////////////////////// // Utilities #define trith_malloc g_malloc0 #define trith_calloc g_malloc0_n #define trith_realloc g_realloc #define trith_free g_free #define trith_slice_alloc g_slice_alloc0 #define trith_slice_copy g_slice_copy #define trith_slice_free g_slice_free1 #define trith_memmove g_memmove ////////////////////////////////////////////////////////////////////////////// // Miscellaneous #ifdef __cplusplus } #endif #endif // TRITH_H
trith/trith
2620b058d97a73ae9067fff2f705ab2f98d4c433
Defined the low-level trith_machine data structure.
diff --git a/src/trith.c b/src/trith.c index 53decf1..6bee1b8 100644 --- a/src/trith.c +++ b/src/trith.c @@ -1,14 +1,75 @@ /* This is free and unencumbered software released into the public domain. */ #include <assert.h> #include <stdio.h> #include <string.h> #include <strings.h> #include <math.h> #include "trith.h" #include "config.h" ////////////////////////////////////////////////////////////////////////////// // Constants const char* const trith_version_string = PACKAGE_VERSION; + +////////////////////////////////////////////////////////////////////////////// +// Machine API + +trith_machine* +trith_machine_alloc() { + return trith_slice_alloc(sizeof(trith_machine)); +} + +trith_machine* +trith_machine_new() { + trith_machine* machine = trith_machine_alloc(); + trith_machine_init(machine); + return machine; +} + +trith_machine* +trith_machine_copy(const trith_machine* machine) { + assert(machine != NULL); + trith_machine* copy = trith_machine_new(); + // copy the stack: + for (GList* list = machine->stack.head; list != NULL; list = list->next) { + g_queue_push_tail(&copy->stack, list->data); + } + // copy the queue: + for (GList* list = machine->queue.head; list != NULL; list = list->next) { + g_queue_push_tail(&copy->queue, list->data); + } + // copy the context: + copy->context.parent = machine->context.parent; + GHashTableIter iter; + gpointer key, value; + g_hash_table_iter_init(&iter, machine->context.locals); + while (g_hash_table_iter_next(&iter, &key, &value) != FALSE) { + g_hash_table_insert(copy->context.locals, &key, &value); + } + return copy; +} + +void +trith_machine_init(trith_machine* machine) { + assert(machine != NULL); + g_queue_init(&machine->stack); + g_queue_init(&machine->queue); + machine->context.parent = NULL; + machine->context.locals = g_hash_table_new(NULL, NULL); +} + +void +trith_machine_free(trith_machine* machine) { + assert(machine != NULL); + g_queue_clear(&machine->stack); + g_queue_clear(&machine->queue); + if (machine->context.locals) { + g_hash_table_destroy(machine->context.locals); + } + trith_slice_free(sizeof(trith_machine), machine); +} + +////////////////////////////////////////////////////////////////////////////// +// Operators diff --git a/src/trith.h b/src/trith.h index 9ae670e..d68e36a 100644 --- a/src/trith.h +++ b/src/trith.h @@ -1,39 +1,67 @@ /* This is free and unencumbered software released into the public domain. */ #ifndef TRITH_H #define TRITH_H #ifdef __cplusplus extern "C" { #endif #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include <glib.h> ////////////////////////////////////////////////////////////////////////////// // Constants extern const char* const trith_version_string; +////////////////////////////////////////////////////////////////////////////// +// Machine API + +typedef GQueue trith_stack; +typedef GQueue trith_queue; +typedef GHashTable trith_table; + +typedef struct { + struct trith_context* parent; + trith_table* locals; +} trith_context; + +typedef struct { + trith_stack stack; + trith_queue queue; + trith_context context; + void* user_data; +} trith_machine; + +extern trith_machine* trith_machine_alloc(); +extern trith_machine* trith_machine_new(); +extern trith_machine* trith_machine_copy(const trith_machine* machine); +extern void trith_machine_init(trith_machine* machine); +extern void trith_machine_free(trith_machine* machine); + +////////////////////////////////////////////////////////////////////////////// +// Operators + ////////////////////////////////////////////////////////////////////////////// // Utilities -#define trith_malloc g_malloc0 -#define trith_calloc g_malloc0_n -#define trith_realloc g_realloc -#define trith_free g_free -#define trith_slice_alloc g_slice_alloc0 -#define trith_slice_copy g_slice_copy -#define trith_slice_free1 g_slice_free1 -#define trith_memmove g_memmove +#define trith_malloc g_malloc0 +#define trith_calloc g_malloc0_n +#define trith_realloc g_realloc +#define trith_free g_free +#define trith_slice_alloc g_slice_alloc0 +#define trith_slice_copy g_slice_copy +#define trith_slice_free g_slice_free1 +#define trith_memmove g_memmove ////////////////////////////////////////////////////////////////////////////// // Miscellaneous #ifdef __cplusplus } #endif #endif // TRITH_H
trith/trith
087681c29260641cb8c407c76db0de62f634c6bd
Implemented the GNU Autotools build system for compiling and packaging `libtrith`.
diff --git a/.gitignore b/.gitignore index 5cee983..6230afe 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,14 @@ .DS_Store .tmp .yardoc pkg tmp + +# GNU Autotools +etc/aclocal/ +Makefile.in +aclocal.m4 +autom4te.cache/ +config.h.in +config.h.in~ +configure diff --git a/Makefile.am b/Makefile.am new file mode 100644 index 0000000..2bdbeda --- /dev/null +++ b/Makefile.am @@ -0,0 +1,3 @@ +SUBDIRS = src doc +EXTRA_DIST = AUTHORS CREDITS README UNLICENSE VERSION +ACLOCAL_AMFLAGS = -I etc/aclocal diff --git a/configure.ac b/configure.ac new file mode 100644 index 0000000..40d2b80 --- /dev/null +++ b/configure.ac @@ -0,0 +1,12 @@ +AC_INIT([trith], [0.0.4], [[email protected]]) +AC_CONFIG_SRCDIR([src/trith.h]) +AC_CONFIG_AUX_DIR([etc/aclocal]) +AC_CONFIG_MACRO_DIR([etc/aclocal]) +AM_INIT_AUTOMAKE([foreign -Wall -Werror dist-bzip2]) +AM_SILENT_RULES([yes]) +LT_INIT +AC_PROG_CC +AM_PATH_GLIB_2_0([2.24.0], [], [], [gthread-2.0]) +AC_CONFIG_HEADERS([config.h]) +AC_CONFIG_FILES([Makefile src/Makefile doc/Makefile doc/man/Makefile]) +AC_OUTPUT diff --git a/doc/Makefile.am b/doc/Makefile.am new file mode 100644 index 0000000..ad800b6 --- /dev/null +++ b/doc/Makefile.am @@ -0,0 +1 @@ +SUBDIRS = man diff --git a/doc/man/Makefile.am b/doc/man/Makefile.am new file mode 100644 index 0000000..b39ad81 --- /dev/null +++ b/doc/man/Makefile.am @@ -0,0 +1,2 @@ +man_MANS = man1/3th.1 man1/3sh.1 man1/3vm.1 man1/3cc.1 man3/libtrith.3 man7/trith.7 +EXTRA_DIST = $(man_MANS) diff --git a/src/Makefile.am b/src/Makefile.am new file mode 100644 index 0000000..64a59f2 --- /dev/null +++ b/src/Makefile.am @@ -0,0 +1,12 @@ +AM_CFLAGS = -std=c99 -pedantic +AM_CPPFLAGS = $(GLIB_CFLAGS) -DG_DISABLE_DEPRECATED=1 +LDADD = libtrith.la +lib_LTLIBRARIES = libtrith.la +libtrith_la_SOURCES = trith.h trith.c +libtrith_la_LIBADD = $(GLIB_LIBS) +include_HEADERS = trith.h +#bin_PROGRAMS = 3th 3sh 3vm 3cc +#3th_SOURCES = trith.h 3th.c +#3sh_SOURCES = trith.h 3sh.c +#3vm_SOURCES = trith.h 3vm.c +#3cc_SOURCES = trith.h 3cc.c diff --git a/src/trith.c b/src/trith.c index 60aa50b..53decf1 100644 --- a/src/trith.c +++ b/src/trith.c @@ -1,14 +1,14 @@ /* This is free and unencumbered software released into the public domain. */ #include <assert.h> #include <stdio.h> #include <string.h> #include <strings.h> #include <math.h> #include "trith.h" #include "config.h" ////////////////////////////////////////////////////////////////////////////// // Constants -const char* const trith_version_string = "x.y.z"; // PACKAGE_VERSION; +const char* const trith_version_string = PACKAGE_VERSION;
trith/trith
df216a41667cc26d40e63335c6fae7ceaf3959ca
Fixed a minor inconsistency in the man page headers.
diff --git a/doc/man/man3/libtrith.3 b/doc/man/man3/libtrith.3 index 15caa82..679c99d 100644 --- a/doc/man/man3/libtrith.3 +++ b/doc/man/man3/libtrith.3 @@ -1,19 +1,19 @@ -.TH LIBTRITH 3 "December 2010" "Trith.org" "Trith Manual" +.TH LIBTRITH 3 "December 2010" "Trith" "Trith Manual" .SH NAME \fBlibtrith\fP \-\- the Trith embeddable runtime library .SH LIBRARY Trith (libtrith, \-ltrith) .SH SYNOPSIS .B #include <trith.h> .SH DESCRIPTION TODO .SH ERRORS TODO .SH NOTES TODO .SH BUGS TODO .SH EXAMPLES TODO .SH SEE ALSO .BR trith (7) diff --git a/doc/man/man7/trith.7 b/doc/man/man7/trith.7 index 9f365c8..e3eb470 100644 --- a/doc/man/man7/trith.7 +++ b/doc/man/man7/trith.7 @@ -1,37 +1,37 @@ -.TH TRITH 7 "December 2010" "Trith.org" "Trith Manual" +.TH TRITH 7 "December 2010" "Trith" "Trith Manual" .SH NAME \fBtrith\fP \-\- an experimental concatenative programming language .SH SYNOPSIS \fB3th\fP [\fB\-\-version\fR] [\fB\-\-help\fR] \fIcommand\fR [\fIargs\fR...] .br \fB3cc\fP [options] [\fIfile\fR...] .br \fB3sh\fP [options] [\fIfile\fR...] .br \fB3vm\fP [options] [\fIfile\fR...] .SH DESCRIPTION TODO .SH OPERATORS TODO .SS Core Operators TODO .SS Sequence Operators TODO .SS Math Operators TODO .SH ENVIRONMENT TODO .SH FILES TODO .SH NOTES TODO .SH BUGS Please report bugs to the mailing list at \fB<[email protected]>\fP .SH AUTHOR Arto Bendiken <[email protected]> .SH SEE ALSO .BR 3th (1), .BR 3sh (1), .BR 3vm (1), .BR 3cc (1), .BR libtrith (3)
trith/trith
37458e43abe0ce83e50ee3da2c1a9f9dd5449df1
Imported some placeholder source files for `libtrith`.
diff --git a/src/trith.c b/src/trith.c new file mode 100644 index 0000000..60aa50b --- /dev/null +++ b/src/trith.c @@ -0,0 +1,14 @@ +/* This is free and unencumbered software released into the public domain. */ + +#include <assert.h> +#include <stdio.h> +#include <string.h> +#include <strings.h> +#include <math.h> +#include "trith.h" +#include "config.h" + +////////////////////////////////////////////////////////////////////////////// +// Constants + +const char* const trith_version_string = "x.y.z"; // PACKAGE_VERSION; diff --git a/src/trith.h b/src/trith.h new file mode 100644 index 0000000..9ae670e --- /dev/null +++ b/src/trith.h @@ -0,0 +1,39 @@ +/* This is free and unencumbered software released into the public domain. */ + +#ifndef TRITH_H +#define TRITH_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include <stdbool.h> +#include <stdint.h> +#include <stdlib.h> +#include <glib.h> + +////////////////////////////////////////////////////////////////////////////// +// Constants + +extern const char* const trith_version_string; + +////////////////////////////////////////////////////////////////////////////// +// Utilities + +#define trith_malloc g_malloc0 +#define trith_calloc g_malloc0_n +#define trith_realloc g_realloc +#define trith_free g_free +#define trith_slice_alloc g_slice_alloc0 +#define trith_slice_copy g_slice_copy +#define trith_slice_free1 g_slice_free1 +#define trith_memmove g_memmove + +////////////////////////////////////////////////////////////////////////////// +// Miscellaneous + +#ifdef __cplusplus +} +#endif + +#endif // TRITH_H
trith/trith
266fd41bc2fe79a25c7153ba4ce2b6888076b8f8
Imported some initial man page stubs.
diff --git a/doc/man/man1/3cc.1 b/doc/man/man1/3cc.1 new file mode 100644 index 0000000..e7dd230 --- /dev/null +++ b/doc/man/man1/3cc.1 @@ -0,0 +1,27 @@ +.TH 3CC 1 "December 2010" "Trith" "Trith Manual" +.SH NAME +\fB3cc\fP \-\- the Trith compiler +.SH SYNOPSIS +\fB3cc\fP [options] [\fIfile\fR...] +.SH DESCRIPTION +TODO +.SH OPTIONS +TODO +.SH EXIT STATUS +The \fB3cc\fP program exits with 0 on success, and with >0 if an error +occurs. +.SH ENVIRONMENT +TODO +.SH FILES +TODO +.SH NOTES +TODO +.SH BUGS +TODO +.SH EXAMPLES +TODO +.SH SEE ALSO +.BR 3th (1), +.BR 3sh (1), +.BR 3vm (1), +.BR trith (7) diff --git a/doc/man/man1/3sh.1 b/doc/man/man1/3sh.1 new file mode 100644 index 0000000..eeb9150 --- /dev/null +++ b/doc/man/man1/3sh.1 @@ -0,0 +1,27 @@ +.TH 3SH 1 "December 2010" "Trith" "Trith Manual" +.SH NAME +\fB3sh\fP \-\- the Trith interactive shell and interpreter +.SH SYNOPSIS +\fB3sh\fP [options] [\fIfile\fR...] +.SH DESCRIPTION +TODO +.SH OPTIONS +TODO +.SH EXIT STATUS +The \fB3sh\fP program exits with 0 on success, and with >0 if an error +occurs. +.SH ENVIRONMENT +TODO +.SH FILES +TODO +.SH NOTES +TODO +.SH BUGS +TODO +.SH EXAMPLES +TODO +.SH SEE ALSO +.BR 3th (1), +.BR 3vm (1), +.BR 3cc (1), +.BR trith (7) diff --git a/doc/man/man1/3th.1 b/doc/man/man1/3th.1 new file mode 100644 index 0000000..d59b499 --- /dev/null +++ b/doc/man/man1/3th.1 @@ -0,0 +1,27 @@ +.TH 3TH 1 "December 2010" "Trith" "Trith Manual" +.SH NAME +\fB3th\fP \-\- the Trith package manager +.SH SYNOPSIS +\fB3th\fP [\fB\-\-version\fR] [\fB\-\-help\fR] \fIcommand\fR [\fIargs\fR...] +.SH DESCRIPTION +TODO +.SH OPTIONS +TODO +.SH EXIT STATUS +The \fB3th\fP program exits with 0 on success, and with >0 if an error +occurs. +.SH ENVIRONMENT +TODO +.SH FILES +TODO +.SH NOTES +TODO +.SH BUGS +TODO +.SH EXAMPLES +TODO +.SH SEE ALSO +.BR 3sh (1), +.BR 3vm (1), +.BR 3cc (1), +.BR trith (7) diff --git a/doc/man/man1/3vm.1 b/doc/man/man1/3vm.1 new file mode 100644 index 0000000..92e10d1 --- /dev/null +++ b/doc/man/man1/3vm.1 @@ -0,0 +1,27 @@ +.TH 3VM 1 "December 2010" "Trith" "Trith Manual" +.SH NAME +\fB3vm\fP \-\- the Trith virtual machine runtime +.SH SYNOPSIS +\fB3vm\fP [options] [\fIfile\fR...] +.SH DESCRIPTION +TODO +.SH OPTIONS +TODO +.SH EXIT STATUS +The \fB3vm\fP program exits with 0 on success, and with >0 if an error +occurs. +.SH ENVIRONMENT +TODO +.SH FILES +TODO +.SH NOTES +TODO +.SH BUGS +TODO +.SH EXAMPLES +TODO +.SH SEE ALSO +.BR 3th (1), +.BR 3sh (1), +.BR 3cc (1), +.BR trith (7) diff --git a/doc/man/man3/libtrith.3 b/doc/man/man3/libtrith.3 new file mode 100644 index 0000000..15caa82 --- /dev/null +++ b/doc/man/man3/libtrith.3 @@ -0,0 +1,19 @@ +.TH LIBTRITH 3 "December 2010" "Trith.org" "Trith Manual" +.SH NAME +\fBlibtrith\fP \-\- the Trith embeddable runtime library +.SH LIBRARY +Trith (libtrith, \-ltrith) +.SH SYNOPSIS +.B #include <trith.h> +.SH DESCRIPTION +TODO +.SH ERRORS +TODO +.SH NOTES +TODO +.SH BUGS +TODO +.SH EXAMPLES +TODO +.SH SEE ALSO +.BR trith (7) diff --git a/doc/man/man7/trith.7 b/doc/man/man7/trith.7 new file mode 100644 index 0000000..9f365c8 --- /dev/null +++ b/doc/man/man7/trith.7 @@ -0,0 +1,37 @@ +.TH TRITH 7 "December 2010" "Trith.org" "Trith Manual" +.SH NAME +\fBtrith\fP \-\- an experimental concatenative programming language +.SH SYNOPSIS +\fB3th\fP [\fB\-\-version\fR] [\fB\-\-help\fR] \fIcommand\fR [\fIargs\fR...] +.br +\fB3cc\fP [options] [\fIfile\fR...] +.br +\fB3sh\fP [options] [\fIfile\fR...] +.br +\fB3vm\fP [options] [\fIfile\fR...] +.SH DESCRIPTION +TODO +.SH OPERATORS +TODO +.SS Core Operators +TODO +.SS Sequence Operators +TODO +.SS Math Operators +TODO +.SH ENVIRONMENT +TODO +.SH FILES +TODO +.SH NOTES +TODO +.SH BUGS +Please report bugs to the mailing list at \fB<[email protected]>\fP +.SH AUTHOR +Arto Bendiken <[email protected]> +.SH SEE ALSO +.BR 3th (1), +.BR 3sh (1), +.BR 3vm (1), +.BR 3cc (1), +.BR libtrith (3)
trith/trith
d1d92768115b1c4ce4b375e7967d62265e24457f
Bumped the FFI dependency to 1.0+.
diff --git a/.gemspec b/.gemspec index 956e890..71a6f1f 100644 --- a/.gemspec +++ b/.gemspec @@ -1,39 +1,39 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.author = 'Arto Bendiken' gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS CREDITS README UNLICENSE VERSION) + Dir.glob('etc/*.{ttl,nt}') + Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.1' gem.requirements = [] - gem.add_runtime_dependency 'ffi', '>= 0.6' + gem.add_runtime_dependency 'ffi', '>= 1.0' gem.add_runtime_dependency 'backports', '>= 1.18' gem.add_runtime_dependency 'promise', '>= 0.3' gem.add_runtime_dependency 'sxp', '>= 0.0.12' gem.add_runtime_dependency 'rdf', '>= 0.3' gem.add_development_dependency 'yard' , '>= 0.6.0' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'buildr' , '>= 1.4.0' gem.post_install_message = nil end diff --git a/README.md b/README.md index 2e58b96..ea76ede 100644 --- a/README.md +++ b/README.md @@ -1,339 +1,339 @@ Trith: Recombinant Programming ============================== Trith is an experimental [concatenative][concat.org] programming language founded on the [unholy][lispers.org] trinity of [Forth][], [Lisp][] and [RDF][] triples. * <http://trith.org/> * <http://github.com/trith/trith> Description ----------- Trith is a stack-based, concatenative, dynamically-typed functional programming language with a homoiconic program representation. * [Stack-based][stack-oriented] means that instead of having named parameters, Trith functions operate on an implicit data structure called the _operand stack_. Trith functions can be thought of in terms of popping and pushing operands from/onto this stack, or equivalently in purely functional terms as unary functions that map from one stack to another. * [Concatenative][concatenative] means that the concatenation of any two Trith functions also denotes the [composition][] of those functions. * [Dynamically typed][type system] means that operands to Trith functions are type-checked dynamically at runtime. * [Homoiconic][homoiconic] means that in Trith there is no difference between code and data. You can manipulate and construct code at runtime as easily as you would manipulate any other data structure, enabling powerful metaprogramming facilities. Trith programs are simply nested lists of operators and operands, and can be represented externally either as [S-expressions][S-expression] or as [RDF][] triples. Trith is inspired and influenced by experience with [Forth][], [Lisp][] and [Scheme][] in general, and the concatenative languages [Joy][], [XY][], [Factor][] and [Cat][] in particular. Introduction ------------ The Trith implementation currently consists of a virtual machine, interpreter, and compiler toolchain written in Ruby and an in-the-works runtime targeting the [JVM][]. You can use the Trith shell `3sh` to explore Trith interactively: $ 3sh >> "Hello, world!" print Hello, world! For example, here's how you would start with two prime numbers and end up with the correct answer to the ultimate question of life, the universe, and everything: $ 3sh >> 3 7 swap dup + * => [42] : [] In the above `3sh` examples, `>>` indicates lines that you type, and `=>` indicates the result from the shell. After each input line is evaluated, the shell will show you the current state of the Trith virtual machine's data stack and code queue. Thus in our previous example, the `[42]` on the left-hand side shows that the machine's stack contains a single operand, the number 42. The `[]` on the right-hand side shows that the machine's code queue is empty, which is generally the case after all input has been successfully evaluated. Let's run through the above example one more time using the `--debug` option to `3sh`, which enables the tracing of each queue reduction step in the virtual machine: $ 3sh --debug >> 3 7 swap dup + * .. [] : [3 7 swap dup + *] .. [3] : [7 swap dup + *] .. [3 7] : [swap dup + *] .. [7 3] : [dup + *] .. [7 3 3] : [+ *] .. [7 6] : [*] => [42] : [] As you can see, the virtual machine starts execution with an empty operand stack on the left-hand side and with all input placed onto the operator queue on the right-hand side. When input operands such as numbers are encountered on the queue, they are simply pushed onto the stack, which grows from left to right. When an operator such as the multiplication operator `*` is encountered on the queue, it is executed. Operators pop operands from the stack and then push their result(s) back onto the stack. When fooling around in the Trith shell, two useful operators to know are `clear`, which clears the stack, and `halt`, which clears the queue (thus halting execution). You can also use `reset` which does both in one step, returning you to a guaranteed clean slate. To get a listing of all operators supported in the current release, enter the `?` metacommand in the Trith shell. Linked Code ----------- All Trith operators are identified by URIs, meaning that Trith code can be straightforwardly represented as [Linked Data][]. Here's an example of the `abs` operator defined metacircularly using the Turtle serialization format for RDF data: @base <http://trith.org/core/> . @prefix trith: <http://trith.org/lang/> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . <abs> a trith:Function ; rdfs:label "abs" ; rdfs:comment "Returns the absolute value of a number."@en ; trith:arity 1 ; trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . This function description comprises a total of 21 triples. The entire Trith core library currently weighs in at about a kilotriple (1,000 triples), with all but a handful of primitive (irreducible) operators having a metacircular definition. See `etc/trith-core.ttl` for the RDF definitions of Trith core operators. Reference --------- ### Sequences Trith has a rich set of sequence operators that will be instantly familiar to programmers coming from functional programming languages such as Scheme, Clojure or Haskell: >> 10 iota => [[0 1 2 3 4 5 6 7 8 9]] : [] >> dup seq? . true >> dup empty? . false >> dup length . 10 >> [dup mul] map => [[0 1 4 9 16 25 36 49 64 81]] : [] >> dup first . 0 >> dup fifth . 16 >> dup 7 nth . 49 >> dup last . 81 >> dup 0 [+] foldl . 285 >> rest => [[1 4 9 16 25 36 49 64 81]] : [] >> dup 1 [*] foldl . 131681894400 >> reverse => [[81 64 49 36 25 16 9 4 1]] : [] ### Strings Strings are simply sequences of characters (Unicode code points), meaning that you can make use of any of the normal sequence operators on strings as well: >> : hello "Hello," " world!" concat ; >> hello seq? . true >> hello text? . true >> hello empty? . false >> hello length . 13 >> hello first . H >> hello rest . ello, world! >> hello reverse . !dlrow ,olleH Scripting --------- The canonical "Hello, world!" script is found in `doc/examples/hello.3th`: #!/usr/bin/env 3vm "Hello, world!" print Any command-line arguments passed to 3VM scripts form the initial stack of the virtual machine. The arguments are placed on the stack in their original unparsed string form. You can print out the contents of the initial stack like so: #!/usr/bin/env 3vm stack print Here's an example of how you would interpret all given command-line arguments as numbers and then sum them up and print out the result: #!/usr/bin/env 3vm stack [num] map 0 [+] foldl print Embedding --------- ### Embedding Trith in Ruby require 'trith' # Let's start with the obligatory "Hello, world!" example: Trith::Machine.run do push "Hello, world!" print end # There are several equivalent ways to execute Trith code: Trith::Machine.run { push(6, 7).mul } #=> 42 Trith::Machine.run [6, 7] { mul } #=> 42 Trith::Machine.run [6, 7, :mul] #=> 42 # Operators in Ruby blocks can be chained together: Trith::Machine.run { push(2).dup.dup.mul.pow } #=> 16 # If you require more control, instantiate a machine manually: vm = Trith::Machine.new vm.define!(:square) { dup.mul } vm.push(10).square.peek #=> 100 # You can also define operators when constructing a machine: vm = Trith::Machine.new(data = [], code = [], { :hello => proc { push("Hello, world!").print }, }) # Should you want to use any Trith functions from Ruby, it's easy enough # to encapsulate a virtual machine inside a Ruby method: def square(n) Trith::Machine.run [n] { dup.mul } end square(10) #=> 100 ### Embedding Trith in JVM-based languages The [JVM][] runtime for Trith is a work in progress. See `src/java` for the runtime's source code and current status. Dependencies ------------ * [Ruby](http://ruby-lang.org/) (>= 1.9.1) or (>= 1.8.1 with [Backports](http://rubygems.org/gems/backports)) * [RDF.rb](http://rubygems.org/gems/rdf) (>= 0.3.0) * [SXP](http://rubygems.org/gems/sxp) (>= 0.0.12) * [Promise](http://rubygems.org/gems/promise) (>= 0.3.0) -* [FFI](http://rubygems.org/gems/ffi) (>= 0.6.3) +* [FFI](http://rubygems.org/gems/ffi) (>= 1.0.0) Installation ------------ The recommended installation method is via [RubyGems](http://rubygems.org/). To install the latest official release of the `trith` gem, do one of the following: $ [sudo] gem install trith # Ruby 1.8.x/1.9.x $ [sudo] gem1.9 install trith # Ruby 1.9 with MacPorts $ [sudo] jruby --1.9 -S gem install trith # JRuby 1.5+ Once Trith is installed, you will have four new programs available: * `3sh`, aka "trish", is the Trith interactive shell and interpreter. * `3vm`, aka "trivium", is the Trith virtual machine runtime. * `3cc`, aka "tricksy", is the Trith compiler. * `3th`, aka "trith", is the Trith package manager. Note that as of the current release, only the first two do anything much as yet. Environment ----------- The following are the default settings for environment variables that let you customize how Trith works: $ export TRITH_HOME=~/.trith $ export TRITH_CACHE=$TRITH_HOME/cache $ export TRITH_TERM=$TERM Download -------- To get a local working copy of the development repository, do: $ git clone git://github.com/trith/trith.git Alternatively, you can download the latest development version as a tarball as follows: $ wget http://github.com/trith/trith/tarball/master Mailing List ------------ * <http://groups.google.com/group/trith> Authors ------- * [Arto Bendiken](mailto:[email protected]) - <http://ar.to/> License ------- Trith is free and unencumbered public domain software. For more information, see <http://unlicense.org/> or the accompanying UNLICENSE file. [stack-oriented]: http://en.wikipedia.org/wiki/Stack-oriented_programming_language [concatenative]: http://en.wikipedia.org/wiki/Concatenative_programming_language [composition]: http://en.wikipedia.org/wiki/Function_composition [type system]: http://en.wikipedia.org/wiki/Type_system#Dynamic_typing [homoiconic]: http://en.wikipedia.org/wiki/Homoiconicity [S-expression]: http://en.wikipedia.org/wiki/S-expression [RDF]: http://en.wikipedia.org/wiki/Resource_Description_Framework [JVM]: http://en.wikipedia.org/wiki/Java_Virtual_Machine [Lisp]: http://en.wikipedia.org/wiki/Lisp_(programming_language) [Scheme]: http://en.wikipedia.org/wiki/Scheme_(programming_language) [Forth]: http://en.wikipedia.org/wiki/Forth_(programming_language) [Factor]: http://en.wikipedia.org/wiki/Factor_(programming_language) [Joy]: http://en.wikipedia.org/wiki/Joy_(programming_language) [Cat]: http://en.wikipedia.org/wiki/Cat_(programming_language) [XY]: http://www.nsl.com/k/xy/xy.htm [Linked Data]: http://linkeddata.org/ [lispers.org]: http://lispers.org/ [concat.org]: http://concatenative.org/wiki/view/Concatenative%20language diff --git a/lib/trith.rb b/lib/trith.rb index 3087b8d..94949bd 100644 --- a/lib/trith.rb +++ b/lib/trith.rb @@ -1,35 +1,39 @@ require 'bigdecimal' require 'rational' require 'digest/sha1' # @see http://rubygems.org/gems/backports require 'backports/1.9.1' if RUBY_VERSION < '1.9.1' require 'backports/basic_object' if RUBY_VERSION < '1.9.1' # @see http://rubygems.org/gems/promise require 'future' # @see http://rubygems.org/gems/sxp require 'sxp' # @see http://rubygems.org/gems/rdf require 'rdf' require 'rdf/ntriples' require 'rdf/nquads' +# @see http://rubygems.org/gems/ffi +require 'ffi' + module Trith include RDF + autoload :VERSION, 'trith/version' # Runtime autoload :Cache, 'trith/cache' autoload :Compiler, 'trith/compiler' autoload :Function, 'trith/function' autoload :Machine, 'trith/machine' autoload :Reader, 'trith/reader' autoload :Shell, 'trith/shell' # Vocabularies autoload :Core, 'trith/vocab/core' autoload :Math, 'trith/vocab/math' end
trith/trith
0ab894dd8511564f82ae3008cc2b4a9ccc3faf0b
Added a CREDITS file.
diff --git a/.gemspec b/.gemspec index 8d72d31..956e890 100644 --- a/.gemspec +++ b/.gemspec @@ -1,41 +1,39 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.author = 'Arto Bendiken' gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY - gem.files = %w(AUTHORS README UNLICENSE VERSION) - gem.files += Dir.glob('etc/*.{ttl,nt}') - gem.files += Dir.glob('lib/**/*.rb') + gem.files = %w(AUTHORS CREDITS README UNLICENSE VERSION) + Dir.glob('etc/*.{ttl,nt}') + Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.1' gem.requirements = [] gem.add_runtime_dependency 'ffi', '>= 0.6' gem.add_runtime_dependency 'backports', '>= 1.18' gem.add_runtime_dependency 'promise', '>= 0.3' gem.add_runtime_dependency 'sxp', '>= 0.0.12' gem.add_runtime_dependency 'rdf', '>= 0.3' gem.add_development_dependency 'yard' , '>= 0.6.0' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'buildr' , '>= 1.4.0' gem.post_install_message = nil end diff --git a/.yardopts b/.yardopts index 7ab539c..c06c39a 100644 --- a/.yardopts +++ b/.yardopts @@ -1,12 +1,13 @@ --title "Trith: Recombinant Programming" --output-dir doc/yard --protected --no-private --hide-void-return --markup markdown --readme README.md - AUTHORS +CREDITS UNLICENSE VERSION doc/READING.md diff --git a/CREDITS b/CREDITS new file mode 100644 index 0000000..e69de29
trith/trith
219d181ee21a6c09b2bc700539d7fc0f52c97e0b
Bumped the dependencies, and added a dependency on FFI.
diff --git a/.gemspec b/.gemspec index 04854f2..8d72d31 100644 --- a/.gemspec +++ b/.gemspec @@ -1,40 +1,41 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.author = 'Arto Bendiken' gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.1' gem.requirements = [] - gem.add_runtime_dependency 'sxp', '~> 0.0.5' - gem.add_runtime_dependency 'rdf', '~> 0.2.0' - gem.add_runtime_dependency 'promise', '>= 0.3.0' - gem.add_runtime_dependency 'backports', '>= 1.18.1' - gem.add_development_dependency 'yard' , '>= 0.5.8' + gem.add_runtime_dependency 'ffi', '>= 0.6' + gem.add_runtime_dependency 'backports', '>= 1.18' + gem.add_runtime_dependency 'promise', '>= 0.3' + gem.add_runtime_dependency 'sxp', '>= 0.0.12' + gem.add_runtime_dependency 'rdf', '>= 0.3' + gem.add_development_dependency 'yard' , '>= 0.6.0' gem.add_development_dependency 'rspec', '>= 1.3.0' - gem.add_development_dependency 'buildr' , '>= 1.3.5' + gem.add_development_dependency 'buildr' , '>= 1.4.0' gem.post_install_message = nil end diff --git a/README.md b/README.md index e1f73ef..2e58b96 100644 --- a/README.md +++ b/README.md @@ -1,338 +1,339 @@ Trith: Recombinant Programming ============================== Trith is an experimental [concatenative][concat.org] programming language founded on the [unholy][lispers.org] trinity of [Forth][], [Lisp][] and [RDF][] triples. * <http://trith.org/> * <http://github.com/trith/trith> Description ----------- Trith is a stack-based, concatenative, dynamically-typed functional programming language with a homoiconic program representation. * [Stack-based][stack-oriented] means that instead of having named parameters, Trith functions operate on an implicit data structure called the _operand stack_. Trith functions can be thought of in terms of popping and pushing operands from/onto this stack, or equivalently in purely functional terms as unary functions that map from one stack to another. * [Concatenative][concatenative] means that the concatenation of any two Trith functions also denotes the [composition][] of those functions. * [Dynamically typed][type system] means that operands to Trith functions are type-checked dynamically at runtime. * [Homoiconic][homoiconic] means that in Trith there is no difference between code and data. You can manipulate and construct code at runtime as easily as you would manipulate any other data structure, enabling powerful metaprogramming facilities. Trith programs are simply nested lists of operators and operands, and can be represented externally either as [S-expressions][S-expression] or as [RDF][] triples. Trith is inspired and influenced by experience with [Forth][], [Lisp][] and [Scheme][] in general, and the concatenative languages [Joy][], [XY][], [Factor][] and [Cat][] in particular. Introduction ------------ The Trith implementation currently consists of a virtual machine, interpreter, and compiler toolchain written in Ruby and an in-the-works runtime targeting the [JVM][]. You can use the Trith shell `3sh` to explore Trith interactively: $ 3sh >> "Hello, world!" print Hello, world! For example, here's how you would start with two prime numbers and end up with the correct answer to the ultimate question of life, the universe, and everything: $ 3sh >> 3 7 swap dup + * => [42] : [] In the above `3sh` examples, `>>` indicates lines that you type, and `=>` indicates the result from the shell. After each input line is evaluated, the shell will show you the current state of the Trith virtual machine's data stack and code queue. Thus in our previous example, the `[42]` on the left-hand side shows that the machine's stack contains a single operand, the number 42. The `[]` on the right-hand side shows that the machine's code queue is empty, which is generally the case after all input has been successfully evaluated. Let's run through the above example one more time using the `--debug` option to `3sh`, which enables the tracing of each queue reduction step in the virtual machine: $ 3sh --debug >> 3 7 swap dup + * .. [] : [3 7 swap dup + *] .. [3] : [7 swap dup + *] .. [3 7] : [swap dup + *] .. [7 3] : [dup + *] .. [7 3 3] : [+ *] .. [7 6] : [*] => [42] : [] As you can see, the virtual machine starts execution with an empty operand stack on the left-hand side and with all input placed onto the operator queue on the right-hand side. When input operands such as numbers are encountered on the queue, they are simply pushed onto the stack, which grows from left to right. When an operator such as the multiplication operator `*` is encountered on the queue, it is executed. Operators pop operands from the stack and then push their result(s) back onto the stack. When fooling around in the Trith shell, two useful operators to know are `clear`, which clears the stack, and `halt`, which clears the queue (thus halting execution). You can also use `reset` which does both in one step, returning you to a guaranteed clean slate. To get a listing of all operators supported in the current release, enter the `?` metacommand in the Trith shell. Linked Code ----------- All Trith operators are identified by URIs, meaning that Trith code can be straightforwardly represented as [Linked Data][]. Here's an example of the `abs` operator defined metacircularly using the Turtle serialization format for RDF data: @base <http://trith.org/core/> . @prefix trith: <http://trith.org/lang/> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . <abs> a trith:Function ; rdfs:label "abs" ; rdfs:comment "Returns the absolute value of a number."@en ; trith:arity 1 ; trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . This function description comprises a total of 21 triples. The entire Trith core library currently weighs in at about a kilotriple (1,000 triples), with all but a handful of primitive (irreducible) operators having a metacircular definition. See `etc/trith-core.ttl` for the RDF definitions of Trith core operators. Reference --------- ### Sequences Trith has a rich set of sequence operators that will be instantly familiar to programmers coming from functional programming languages such as Scheme, Clojure or Haskell: >> 10 iota => [[0 1 2 3 4 5 6 7 8 9]] : [] >> dup seq? . true >> dup empty? . false >> dup length . 10 >> [dup mul] map => [[0 1 4 9 16 25 36 49 64 81]] : [] >> dup first . 0 >> dup fifth . 16 >> dup 7 nth . 49 >> dup last . 81 >> dup 0 [+] foldl . 285 >> rest => [[1 4 9 16 25 36 49 64 81]] : [] >> dup 1 [*] foldl . 131681894400 >> reverse => [[81 64 49 36 25 16 9 4 1]] : [] ### Strings Strings are simply sequences of characters (Unicode code points), meaning that you can make use of any of the normal sequence operators on strings as well: >> : hello "Hello," " world!" concat ; >> hello seq? . true >> hello text? . true >> hello empty? . false >> hello length . 13 >> hello first . H >> hello rest . ello, world! >> hello reverse . !dlrow ,olleH Scripting --------- The canonical "Hello, world!" script is found in `doc/examples/hello.3th`: #!/usr/bin/env 3vm "Hello, world!" print Any command-line arguments passed to 3VM scripts form the initial stack of the virtual machine. The arguments are placed on the stack in their original unparsed string form. You can print out the contents of the initial stack like so: #!/usr/bin/env 3vm stack print Here's an example of how you would interpret all given command-line arguments as numbers and then sum them up and print out the result: #!/usr/bin/env 3vm stack [num] map 0 [+] foldl print Embedding --------- ### Embedding Trith in Ruby require 'trith' # Let's start with the obligatory "Hello, world!" example: Trith::Machine.run do push "Hello, world!" print end # There are several equivalent ways to execute Trith code: Trith::Machine.run { push(6, 7).mul } #=> 42 Trith::Machine.run [6, 7] { mul } #=> 42 Trith::Machine.run [6, 7, :mul] #=> 42 # Operators in Ruby blocks can be chained together: Trith::Machine.run { push(2).dup.dup.mul.pow } #=> 16 # If you require more control, instantiate a machine manually: vm = Trith::Machine.new vm.define!(:square) { dup.mul } vm.push(10).square.peek #=> 100 # You can also define operators when constructing a machine: vm = Trith::Machine.new(data = [], code = [], { :hello => proc { push("Hello, world!").print }, }) # Should you want to use any Trith functions from Ruby, it's easy enough # to encapsulate a virtual machine inside a Ruby method: def square(n) Trith::Machine.run [n] { dup.mul } end square(10) #=> 100 ### Embedding Trith in JVM-based languages The [JVM][] runtime for Trith is a work in progress. See `src/java` for the runtime's source code and current status. Dependencies ------------ * [Ruby](http://ruby-lang.org/) (>= 1.9.1) or (>= 1.8.1 with [Backports](http://rubygems.org/gems/backports)) -* [RDF.rb](http://rubygems.org/gems/rdf) (>= 0.2.0) -* [SXP](http://rubygems.org/gems/sxp) (>= 0.0.5) +* [RDF.rb](http://rubygems.org/gems/rdf) (>= 0.3.0) +* [SXP](http://rubygems.org/gems/sxp) (>= 0.0.12) * [Promise](http://rubygems.org/gems/promise) (>= 0.3.0) +* [FFI](http://rubygems.org/gems/ffi) (>= 0.6.3) Installation ------------ The recommended installation method is via [RubyGems](http://rubygems.org/). To install the latest official release of the `trith` gem, do one of the following: $ [sudo] gem install trith # Ruby 1.8.x/1.9.x $ [sudo] gem1.9 install trith # Ruby 1.9 with MacPorts $ [sudo] jruby --1.9 -S gem install trith # JRuby 1.5+ Once Trith is installed, you will have four new programs available: * `3sh`, aka "trish", is the Trith interactive shell and interpreter. * `3vm`, aka "trivium", is the Trith virtual machine runtime. * `3cc`, aka "tricksy", is the Trith compiler. * `3th`, aka "trith", is the Trith package manager. Note that as of the current release, only the first two do anything much as yet. Environment ----------- The following are the default settings for environment variables that let you customize how Trith works: $ export TRITH_HOME=~/.trith $ export TRITH_CACHE=$TRITH_HOME/cache $ export TRITH_TERM=$TERM Download -------- To get a local working copy of the development repository, do: $ git clone git://github.com/trith/trith.git Alternatively, you can download the latest development version as a tarball as follows: $ wget http://github.com/trith/trith/tarball/master Mailing List ------------ * <http://groups.google.com/group/trith> Authors ------- * [Arto Bendiken](mailto:[email protected]) - <http://ar.to/> License ------- Trith is free and unencumbered public domain software. For more information, see <http://unlicense.org/> or the accompanying UNLICENSE file. [stack-oriented]: http://en.wikipedia.org/wiki/Stack-oriented_programming_language [concatenative]: http://en.wikipedia.org/wiki/Concatenative_programming_language [composition]: http://en.wikipedia.org/wiki/Function_composition [type system]: http://en.wikipedia.org/wiki/Type_system#Dynamic_typing [homoiconic]: http://en.wikipedia.org/wiki/Homoiconicity [S-expression]: http://en.wikipedia.org/wiki/S-expression [RDF]: http://en.wikipedia.org/wiki/Resource_Description_Framework [JVM]: http://en.wikipedia.org/wiki/Java_Virtual_Machine [Lisp]: http://en.wikipedia.org/wiki/Lisp_(programming_language) [Scheme]: http://en.wikipedia.org/wiki/Scheme_(programming_language) [Forth]: http://en.wikipedia.org/wiki/Forth_(programming_language) [Factor]: http://en.wikipedia.org/wiki/Factor_(programming_language) [Joy]: http://en.wikipedia.org/wiki/Joy_(programming_language) [Cat]: http://en.wikipedia.org/wiki/Cat_(programming_language) [XY]: http://www.nsl.com/k/xy/xy.htm [Linked Data]: http://linkeddata.org/ [lispers.org]: http://lispers.org/ [concat.org]: http://concatenative.org/wiki/view/Concatenative%20language
trith/trith
6b2cd002dc7d475df3aca4eb1db7f83aeed2cffa
Added a gemspec symlink for Bundler compatibility.
diff --git a/.gemspec b/.gemspec index c16e7ed..04854f2 100644 --- a/.gemspec +++ b/.gemspec @@ -1,40 +1,40 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- -GEMSPEC = Gem::Specification.new do |gem| +Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.author = 'Arto Bendiken' gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.1' gem.requirements = [] gem.add_runtime_dependency 'sxp', '~> 0.0.5' gem.add_runtime_dependency 'rdf', '~> 0.2.0' gem.add_runtime_dependency 'promise', '>= 0.3.0' gem.add_runtime_dependency 'backports', '>= 1.18.1' gem.add_development_dependency 'yard' , '>= 0.5.8' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'buildr' , '>= 1.3.5' gem.post_install_message = nil end diff --git a/trith.gemspec b/trith.gemspec new file mode 120000 index 0000000..f4a047d --- /dev/null +++ b/trith.gemspec @@ -0,0 +1 @@ +.gemspec \ No newline at end of file
trith/trith
35ce287721b8d3e1911649369794aa9ced850814
Bumped the Promise dependency to 0.3.0+.
diff --git a/.gemspec b/.gemspec index 43695a0..c16e7ed 100644 --- a/.gemspec +++ b/.gemspec @@ -1,40 +1,40 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.author = 'Arto Bendiken' gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.1' gem.requirements = [] gem.add_runtime_dependency 'sxp', '~> 0.0.5' gem.add_runtime_dependency 'rdf', '~> 0.2.0' - gem.add_runtime_dependency 'promise', '>= 0.2.1' + gem.add_runtime_dependency 'promise', '>= 0.3.0' gem.add_runtime_dependency 'backports', '>= 1.18.1' gem.add_development_dependency 'yard' , '>= 0.5.8' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'buildr' , '>= 1.3.5' gem.post_install_message = nil end diff --git a/README.md b/README.md index d568a0d..e1f73ef 100644 --- a/README.md +++ b/README.md @@ -1,338 +1,338 @@ Trith: Recombinant Programming ============================== Trith is an experimental [concatenative][concat.org] programming language founded on the [unholy][lispers.org] trinity of [Forth][], [Lisp][] and [RDF][] triples. * <http://trith.org/> * <http://github.com/trith/trith> Description ----------- Trith is a stack-based, concatenative, dynamically-typed functional programming language with a homoiconic program representation. * [Stack-based][stack-oriented] means that instead of having named parameters, Trith functions operate on an implicit data structure called the _operand stack_. Trith functions can be thought of in terms of popping and pushing operands from/onto this stack, or equivalently in purely functional terms as unary functions that map from one stack to another. * [Concatenative][concatenative] means that the concatenation of any two Trith functions also denotes the [composition][] of those functions. * [Dynamically typed][type system] means that operands to Trith functions are type-checked dynamically at runtime. * [Homoiconic][homoiconic] means that in Trith there is no difference between code and data. You can manipulate and construct code at runtime as easily as you would manipulate any other data structure, enabling powerful metaprogramming facilities. Trith programs are simply nested lists of operators and operands, and can be represented externally either as [S-expressions][S-expression] or as [RDF][] triples. Trith is inspired and influenced by experience with [Forth][], [Lisp][] and [Scheme][] in general, and the concatenative languages [Joy][], [XY][], [Factor][] and [Cat][] in particular. Introduction ------------ The Trith implementation currently consists of a virtual machine, interpreter, and compiler toolchain written in Ruby and an in-the-works runtime targeting the [JVM][]. You can use the Trith shell `3sh` to explore Trith interactively: $ 3sh >> "Hello, world!" print Hello, world! For example, here's how you would start with two prime numbers and end up with the correct answer to the ultimate question of life, the universe, and everything: $ 3sh >> 3 7 swap dup + * => [42] : [] In the above `3sh` examples, `>>` indicates lines that you type, and `=>` indicates the result from the shell. After each input line is evaluated, the shell will show you the current state of the Trith virtual machine's data stack and code queue. Thus in our previous example, the `[42]` on the left-hand side shows that the machine's stack contains a single operand, the number 42. The `[]` on the right-hand side shows that the machine's code queue is empty, which is generally the case after all input has been successfully evaluated. Let's run through the above example one more time using the `--debug` option to `3sh`, which enables the tracing of each queue reduction step in the virtual machine: $ 3sh --debug >> 3 7 swap dup + * .. [] : [3 7 swap dup + *] .. [3] : [7 swap dup + *] .. [3 7] : [swap dup + *] .. [7 3] : [dup + *] .. [7 3 3] : [+ *] .. [7 6] : [*] => [42] : [] As you can see, the virtual machine starts execution with an empty operand stack on the left-hand side and with all input placed onto the operator queue on the right-hand side. When input operands such as numbers are encountered on the queue, they are simply pushed onto the stack, which grows from left to right. When an operator such as the multiplication operator `*` is encountered on the queue, it is executed. Operators pop operands from the stack and then push their result(s) back onto the stack. When fooling around in the Trith shell, two useful operators to know are `clear`, which clears the stack, and `halt`, which clears the queue (thus halting execution). You can also use `reset` which does both in one step, returning you to a guaranteed clean slate. To get a listing of all operators supported in the current release, enter the `?` metacommand in the Trith shell. Linked Code ----------- All Trith operators are identified by URIs, meaning that Trith code can be straightforwardly represented as [Linked Data][]. Here's an example of the `abs` operator defined metacircularly using the Turtle serialization format for RDF data: @base <http://trith.org/core/> . @prefix trith: <http://trith.org/lang/> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . <abs> a trith:Function ; rdfs:label "abs" ; rdfs:comment "Returns the absolute value of a number."@en ; trith:arity 1 ; trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . This function description comprises a total of 21 triples. The entire Trith core library currently weighs in at about a kilotriple (1,000 triples), with all but a handful of primitive (irreducible) operators having a metacircular definition. See `etc/trith-core.ttl` for the RDF definitions of Trith core operators. Reference --------- ### Sequences Trith has a rich set of sequence operators that will be instantly familiar to programmers coming from functional programming languages such as Scheme, Clojure or Haskell: >> 10 iota => [[0 1 2 3 4 5 6 7 8 9]] : [] >> dup seq? . true >> dup empty? . false >> dup length . 10 >> [dup mul] map => [[0 1 4 9 16 25 36 49 64 81]] : [] >> dup first . 0 >> dup fifth . 16 >> dup 7 nth . 49 >> dup last . 81 >> dup 0 [+] foldl . 285 >> rest => [[1 4 9 16 25 36 49 64 81]] : [] >> dup 1 [*] foldl . 131681894400 >> reverse => [[81 64 49 36 25 16 9 4 1]] : [] ### Strings Strings are simply sequences of characters (Unicode code points), meaning that you can make use of any of the normal sequence operators on strings as well: >> : hello "Hello," " world!" concat ; >> hello seq? . true >> hello text? . true >> hello empty? . false >> hello length . 13 >> hello first . H >> hello rest . ello, world! >> hello reverse . !dlrow ,olleH Scripting --------- The canonical "Hello, world!" script is found in `doc/examples/hello.3th`: #!/usr/bin/env 3vm "Hello, world!" print Any command-line arguments passed to 3VM scripts form the initial stack of the virtual machine. The arguments are placed on the stack in their original unparsed string form. You can print out the contents of the initial stack like so: #!/usr/bin/env 3vm stack print Here's an example of how you would interpret all given command-line arguments as numbers and then sum them up and print out the result: #!/usr/bin/env 3vm stack [num] map 0 [+] foldl print Embedding --------- ### Embedding Trith in Ruby require 'trith' # Let's start with the obligatory "Hello, world!" example: Trith::Machine.run do push "Hello, world!" print end # There are several equivalent ways to execute Trith code: Trith::Machine.run { push(6, 7).mul } #=> 42 Trith::Machine.run [6, 7] { mul } #=> 42 Trith::Machine.run [6, 7, :mul] #=> 42 # Operators in Ruby blocks can be chained together: Trith::Machine.run { push(2).dup.dup.mul.pow } #=> 16 # If you require more control, instantiate a machine manually: vm = Trith::Machine.new vm.define!(:square) { dup.mul } vm.push(10).square.peek #=> 100 # You can also define operators when constructing a machine: vm = Trith::Machine.new(data = [], code = [], { :hello => proc { push("Hello, world!").print }, }) # Should you want to use any Trith functions from Ruby, it's easy enough # to encapsulate a virtual machine inside a Ruby method: def square(n) Trith::Machine.run [n] { dup.mul } end square(10) #=> 100 ### Embedding Trith in JVM-based languages The [JVM][] runtime for Trith is a work in progress. See `src/java` for the runtime's source code and current status. Dependencies ------------ * [Ruby](http://ruby-lang.org/) (>= 1.9.1) or (>= 1.8.1 with [Backports](http://rubygems.org/gems/backports)) * [RDF.rb](http://rubygems.org/gems/rdf) (>= 0.2.0) * [SXP](http://rubygems.org/gems/sxp) (>= 0.0.5) -* [Promise](http://rubygems.org/gems/promise) (>= 0.2.1) +* [Promise](http://rubygems.org/gems/promise) (>= 0.3.0) Installation ------------ The recommended installation method is via [RubyGems](http://rubygems.org/). To install the latest official release of the `trith` gem, do one of the following: $ [sudo] gem install trith # Ruby 1.8.x/1.9.x $ [sudo] gem1.9 install trith # Ruby 1.9 with MacPorts $ [sudo] jruby --1.9 -S gem install trith # JRuby 1.5+ Once Trith is installed, you will have four new programs available: * `3sh`, aka "trish", is the Trith interactive shell and interpreter. * `3vm`, aka "trivium", is the Trith virtual machine runtime. * `3cc`, aka "tricksy", is the Trith compiler. * `3th`, aka "trith", is the Trith package manager. Note that as of the current release, only the first two do anything much as yet. Environment ----------- The following are the default settings for environment variables that let you customize how Trith works: $ export TRITH_HOME=~/.trith $ export TRITH_CACHE=$TRITH_HOME/cache $ export TRITH_TERM=$TERM Download -------- To get a local working copy of the development repository, do: $ git clone git://github.com/trith/trith.git Alternatively, you can download the latest development version as a tarball as follows: $ wget http://github.com/trith/trith/tarball/master Mailing List ------------ * <http://groups.google.com/group/trith> Authors ------- * [Arto Bendiken](mailto:[email protected]) - <http://ar.to/> License ------- Trith is free and unencumbered public domain software. For more information, see <http://unlicense.org/> or the accompanying UNLICENSE file. [stack-oriented]: http://en.wikipedia.org/wiki/Stack-oriented_programming_language [concatenative]: http://en.wikipedia.org/wiki/Concatenative_programming_language [composition]: http://en.wikipedia.org/wiki/Function_composition [type system]: http://en.wikipedia.org/wiki/Type_system#Dynamic_typing [homoiconic]: http://en.wikipedia.org/wiki/Homoiconicity [S-expression]: http://en.wikipedia.org/wiki/S-expression [RDF]: http://en.wikipedia.org/wiki/Resource_Description_Framework [JVM]: http://en.wikipedia.org/wiki/Java_Virtual_Machine [Lisp]: http://en.wikipedia.org/wiki/Lisp_(programming_language) [Scheme]: http://en.wikipedia.org/wiki/Scheme_(programming_language) [Forth]: http://en.wikipedia.org/wiki/Forth_(programming_language) [Factor]: http://en.wikipedia.org/wiki/Factor_(programming_language) [Joy]: http://en.wikipedia.org/wiki/Joy_(programming_language) [Cat]: http://en.wikipedia.org/wiki/Cat_(programming_language) [XY]: http://www.nsl.com/k/xy/xy.htm [Linked Data]: http://linkeddata.org/ [lispers.org]: http://lispers.org/ [concat.org]: http://concatenative.org/wiki/view/Concatenative%20language
trith/trith
1cf3221cf2b01f7179f3e4a44da32de83af3018a
Bumped the Promise dependency.
diff --git a/.gemspec b/.gemspec index 70b5386..43695a0 100644 --- a/.gemspec +++ b/.gemspec @@ -1,40 +1,40 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.author = 'Arto Bendiken' gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.1' gem.requirements = [] gem.add_runtime_dependency 'sxp', '~> 0.0.5' gem.add_runtime_dependency 'rdf', '~> 0.2.0' - gem.add_runtime_dependency 'promise', '>= 0.2.0' + gem.add_runtime_dependency 'promise', '>= 0.2.1' gem.add_runtime_dependency 'backports', '>= 1.18.1' gem.add_development_dependency 'yard' , '>= 0.5.8' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'buildr' , '>= 1.3.5' gem.post_install_message = nil end diff --git a/README.md b/README.md index 283c258..d568a0d 100644 --- a/README.md +++ b/README.md @@ -1,338 +1,338 @@ Trith: Recombinant Programming ============================== Trith is an experimental [concatenative][concat.org] programming language founded on the [unholy][lispers.org] trinity of [Forth][], [Lisp][] and [RDF][] triples. * <http://trith.org/> * <http://github.com/trith/trith> Description ----------- Trith is a stack-based, concatenative, dynamically-typed functional programming language with a homoiconic program representation. * [Stack-based][stack-oriented] means that instead of having named parameters, Trith functions operate on an implicit data structure called the _operand stack_. Trith functions can be thought of in terms of popping and pushing operands from/onto this stack, or equivalently in purely functional terms as unary functions that map from one stack to another. * [Concatenative][concatenative] means that the concatenation of any two Trith functions also denotes the [composition][] of those functions. * [Dynamically typed][type system] means that operands to Trith functions are type-checked dynamically at runtime. * [Homoiconic][homoiconic] means that in Trith there is no difference between code and data. You can manipulate and construct code at runtime as easily as you would manipulate any other data structure, enabling powerful metaprogramming facilities. Trith programs are simply nested lists of operators and operands, and can be represented externally either as [S-expressions][S-expression] or as [RDF][] triples. Trith is inspired and influenced by experience with [Forth][], [Lisp][] and [Scheme][] in general, and the concatenative languages [Joy][], [XY][], [Factor][] and [Cat][] in particular. Introduction ------------ The Trith implementation currently consists of a virtual machine, interpreter, and compiler toolchain written in Ruby and an in-the-works runtime targeting the [JVM][]. You can use the Trith shell `3sh` to explore Trith interactively: $ 3sh >> "Hello, world!" print Hello, world! For example, here's how you would start with two prime numbers and end up with the correct answer to the ultimate question of life, the universe, and everything: $ 3sh >> 3 7 swap dup + * => [42] : [] In the above `3sh` examples, `>>` indicates lines that you type, and `=>` indicates the result from the shell. After each input line is evaluated, the shell will show you the current state of the Trith virtual machine's data stack and code queue. Thus in our previous example, the `[42]` on the left-hand side shows that the machine's stack contains a single operand, the number 42. The `[]` on the right-hand side shows that the machine's code queue is empty, which is generally the case after all input has been successfully evaluated. Let's run through the above example one more time using the `--debug` option to `3sh`, which enables the tracing of each queue reduction step in the virtual machine: $ 3sh --debug >> 3 7 swap dup + * .. [] : [3 7 swap dup + *] .. [3] : [7 swap dup + *] .. [3 7] : [swap dup + *] .. [7 3] : [dup + *] .. [7 3 3] : [+ *] .. [7 6] : [*] => [42] : [] As you can see, the virtual machine starts execution with an empty operand stack on the left-hand side and with all input placed onto the operator queue on the right-hand side. When input operands such as numbers are encountered on the queue, they are simply pushed onto the stack, which grows from left to right. When an operator such as the multiplication operator `*` is encountered on the queue, it is executed. Operators pop operands from the stack and then push their result(s) back onto the stack. When fooling around in the Trith shell, two useful operators to know are `clear`, which clears the stack, and `halt`, which clears the queue (thus halting execution). You can also use `reset` which does both in one step, returning you to a guaranteed clean slate. To get a listing of all operators supported in the current release, enter the `?` metacommand in the Trith shell. Linked Code ----------- All Trith operators are identified by URIs, meaning that Trith code can be straightforwardly represented as [Linked Data][]. Here's an example of the `abs` operator defined metacircularly using the Turtle serialization format for RDF data: @base <http://trith.org/core/> . @prefix trith: <http://trith.org/lang/> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . <abs> a trith:Function ; rdfs:label "abs" ; rdfs:comment "Returns the absolute value of a number."@en ; trith:arity 1 ; trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . This function description comprises a total of 21 triples. The entire Trith core library currently weighs in at about a kilotriple (1,000 triples), with all but a handful of primitive (irreducible) operators having a metacircular definition. See `etc/trith-core.ttl` for the RDF definitions of Trith core operators. Reference --------- ### Sequences Trith has a rich set of sequence operators that will be instantly familiar to programmers coming from functional programming languages such as Scheme, Clojure or Haskell: >> 10 iota => [[0 1 2 3 4 5 6 7 8 9]] : [] >> dup seq? . true >> dup empty? . false >> dup length . 10 >> [dup mul] map => [[0 1 4 9 16 25 36 49 64 81]] : [] >> dup first . 0 >> dup fifth . 16 >> dup 7 nth . 49 >> dup last . 81 >> dup 0 [+] foldl . 285 >> rest => [[1 4 9 16 25 36 49 64 81]] : [] >> dup 1 [*] foldl . 131681894400 >> reverse => [[81 64 49 36 25 16 9 4 1]] : [] ### Strings Strings are simply sequences of characters (Unicode code points), meaning that you can make use of any of the normal sequence operators on strings as well: >> : hello "Hello," " world!" concat ; >> hello seq? . true >> hello text? . true >> hello empty? . false >> hello length . 13 >> hello first . H >> hello rest . ello, world! >> hello reverse . !dlrow ,olleH Scripting --------- The canonical "Hello, world!" script is found in `doc/examples/hello.3th`: #!/usr/bin/env 3vm "Hello, world!" print Any command-line arguments passed to 3VM scripts form the initial stack of the virtual machine. The arguments are placed on the stack in their original unparsed string form. You can print out the contents of the initial stack like so: #!/usr/bin/env 3vm stack print Here's an example of how you would interpret all given command-line arguments as numbers and then sum them up and print out the result: #!/usr/bin/env 3vm stack [num] map 0 [+] foldl print Embedding --------- ### Embedding Trith in Ruby require 'trith' # Let's start with the obligatory "Hello, world!" example: Trith::Machine.run do push "Hello, world!" print end # There are several equivalent ways to execute Trith code: Trith::Machine.run { push(6, 7).mul } #=> 42 Trith::Machine.run [6, 7] { mul } #=> 42 Trith::Machine.run [6, 7, :mul] #=> 42 # Operators in Ruby blocks can be chained together: Trith::Machine.run { push(2).dup.dup.mul.pow } #=> 16 # If you require more control, instantiate a machine manually: vm = Trith::Machine.new vm.define!(:square) { dup.mul } vm.push(10).square.peek #=> 100 # You can also define operators when constructing a machine: vm = Trith::Machine.new(data = [], code = [], { :hello => proc { push("Hello, world!").print }, }) # Should you want to use any Trith functions from Ruby, it's easy enough # to encapsulate a virtual machine inside a Ruby method: def square(n) Trith::Machine.run [n] { dup.mul } end square(10) #=> 100 ### Embedding Trith in JVM-based languages The [JVM][] runtime for Trith is a work in progress. See `src/java` for the runtime's source code and current status. Dependencies ------------ * [Ruby](http://ruby-lang.org/) (>= 1.9.1) or (>= 1.8.1 with [Backports](http://rubygems.org/gems/backports)) * [RDF.rb](http://rubygems.org/gems/rdf) (>= 0.2.0) * [SXP](http://rubygems.org/gems/sxp) (>= 0.0.5) -* [Promise](http://rubygems.org/gems/promise) (>= 0.2.0) +* [Promise](http://rubygems.org/gems/promise) (>= 0.2.1) Installation ------------ The recommended installation method is via [RubyGems](http://rubygems.org/). To install the latest official release of the `trith` gem, do one of the following: $ [sudo] gem install trith # Ruby 1.8.x/1.9.x $ [sudo] gem1.9 install trith # Ruby 1.9 with MacPorts $ [sudo] jruby --1.9 -S gem install trith # JRuby 1.5+ Once Trith is installed, you will have four new programs available: * `3sh`, aka "trish", is the Trith interactive shell and interpreter. * `3vm`, aka "trivium", is the Trith virtual machine runtime. * `3cc`, aka "tricksy", is the Trith compiler. * `3th`, aka "trith", is the Trith package manager. Note that as of the current release, only the first two do anything much as yet. Environment ----------- The following are the default settings for environment variables that let you customize how Trith works: $ export TRITH_HOME=~/.trith $ export TRITH_CACHE=$TRITH_HOME/cache $ export TRITH_TERM=$TERM Download -------- To get a local working copy of the development repository, do: $ git clone git://github.com/trith/trith.git Alternatively, you can download the latest development version as a tarball as follows: $ wget http://github.com/trith/trith/tarball/master Mailing List ------------ * <http://groups.google.com/group/trith> Authors ------- * [Arto Bendiken](mailto:[email protected]) - <http://ar.to/> License ------- Trith is free and unencumbered public domain software. For more information, see <http://unlicense.org/> or the accompanying UNLICENSE file. [stack-oriented]: http://en.wikipedia.org/wiki/Stack-oriented_programming_language [concatenative]: http://en.wikipedia.org/wiki/Concatenative_programming_language [composition]: http://en.wikipedia.org/wiki/Function_composition [type system]: http://en.wikipedia.org/wiki/Type_system#Dynamic_typing [homoiconic]: http://en.wikipedia.org/wiki/Homoiconicity [S-expression]: http://en.wikipedia.org/wiki/S-expression [RDF]: http://en.wikipedia.org/wiki/Resource_Description_Framework [JVM]: http://en.wikipedia.org/wiki/Java_Virtual_Machine [Lisp]: http://en.wikipedia.org/wiki/Lisp_(programming_language) [Scheme]: http://en.wikipedia.org/wiki/Scheme_(programming_language) [Forth]: http://en.wikipedia.org/wiki/Forth_(programming_language) [Factor]: http://en.wikipedia.org/wiki/Factor_(programming_language) [Joy]: http://en.wikipedia.org/wiki/Joy_(programming_language) [Cat]: http://en.wikipedia.org/wiki/Cat_(programming_language) [XY]: http://www.nsl.com/k/xy/xy.htm [Linked Data]: http://linkeddata.org/ [lispers.org]: http://lispers.org/ [concat.org]: http://concatenative.org/wiki/view/Concatenative%20language
trith/trith
820aea7bd962cf99dda77dd9589be72cc48f7ea3
Factored out the math operators into a Trith::Math module; restructured vocabulary implementation files.
diff --git a/lib/trith.rb b/lib/trith.rb index 8298414..3087b8d 100644 --- a/lib/trith.rb +++ b/lib/trith.rb @@ -1,31 +1,35 @@ require 'bigdecimal' require 'rational' require 'digest/sha1' # @see http://rubygems.org/gems/backports require 'backports/1.9.1' if RUBY_VERSION < '1.9.1' require 'backports/basic_object' if RUBY_VERSION < '1.9.1' # @see http://rubygems.org/gems/promise require 'future' # @see http://rubygems.org/gems/sxp require 'sxp' # @see http://rubygems.org/gems/rdf require 'rdf' require 'rdf/ntriples' require 'rdf/nquads' module Trith include RDF + autoload :VERSION, 'trith/version' + # Runtime autoload :Cache, 'trith/cache' autoload :Compiler, 'trith/compiler' - autoload :Core, 'trith/core' autoload :Function, 'trith/function' autoload :Machine, 'trith/machine' autoload :Reader, 'trith/reader' autoload :Shell, 'trith/shell' - autoload :VERSION, 'trith/version' + + # Vocabularies + autoload :Core, 'trith/vocab/core' + autoload :Math, 'trith/vocab/math' end diff --git a/lib/trith/core.rb b/lib/trith/core.rb deleted file mode 100644 index 57b085f..0000000 --- a/lib/trith/core.rb +++ /dev/null @@ -1,20 +0,0 @@ -module Trith - ## - # The Trith core operators. - module Core - require 'trith/core/execution' - require 'trith/core/stack' - require 'trith/core/arithmetic' - require 'trith/core/bitwise' - require 'trith/core/boolean' - require 'trith/core/comparison' - require 'trith/core/numeric' - require 'trith/core/math' - require 'trith/core/sequence' - require 'trith/core/textual' - require 'trith/core/output' - - # Include all submodule methods directly into Trith::Core: - constants.each { |mod| include(const_get(mod)) } - end # module Core -end # module Trith diff --git a/lib/trith/core/math.rb b/lib/trith/core/math.rb deleted file mode 100644 index 96abf95..0000000 --- a/lib/trith/core/math.rb +++ /dev/null @@ -1,34 +0,0 @@ -module Trith; module Core - ## - # Math operators. - # - # @see http://ruby-doc.org/core/classes/Math.html - module Math - ## - # Math constants. - module Constants - # TODO - end # module Constants - - ## - # Math operators. - module Operators - ## - # @param [Numeric, #ceil] n - # @return [Integer] - def ceil(n) - n.ceil - end - - ## - # @param [Numeric, #floor] n - # @return [Integer] - def floor(n) - n.floor - end - end # module Operators - - # Include all submodule methods directly into Trith::Core::Math: - constants.each { |mod| include(const_get(mod)) } - end # module Math -end; end # module Trith::Core diff --git a/lib/trith/machine.rb b/lib/trith/machine.rb index 4f5d6f6..13d4e9d 100644 --- a/lib/trith/machine.rb +++ b/lib/trith/machine.rb @@ -1,377 +1,378 @@ module Trith ## # The Trith virtual machine. class Machine # @return [Array] attr_reader :stack # @return [Array] attr_reader :queue # @return [Proc] attr_accessor :execute_hook ## # Executes `code` in a new virtual machine instance. # # The machine will halt when the queue is exhausted, when encountering # a `halt` operator, or when encountering an error condition. # # @overload self.run(code) # @param [Array] code # @return [Object] # # @overload self.run(code) # @param [Array] code # @yield [machine] # @yieldparam [Machine] machine # @return [Object] # # @return [Object] def self.run(code = [], &block) self.new([], code).execute(&block).peek end ## # Initializes a new virtual machine with the given initial `stack`, # `queue` and environment. # # @param [Array] stack # @param [Array] queue # @param [Hash] env # @yield [machine] # @yieldparam [Machine] machine def initialize(stack = [], queue = [], env = {}, &block) @stack, @queue, @env = stack, queue, {} import!(Trith::Core) + import!(Trith::Math) env.each do |name, operator| if operator.is_a?(Proc) define!(name, &operator) else define!(name, operator) end end execute(&block) if block_given? end ## # Returns a developer-friendly representation of this machine. # # @return [String] def inspect sprintf("#<%s:%#0x(%s : %s)>", self.class.name, __id__, @stack.inspect, @queue.inspect) end ## # Imports operators from the given `module` into the virtual machine's # current environment. # # @param [Module] module # @return [Machine] def import!(mod) case mod when Module then import_module!(mod) when Function then # TODO else # TODO: error end self end ## # Defines a new operator `name` that will execute the given `code`. # # @param [Symbol, #to_sym] name # @param [Array] code # @param [Hash{Symbol => Object}] options # @return [Machine] def define!(name, code = [], options = {}, &block) @env[name = name.to_sym] = lambda { execute(code, &block) } define_singleton_method(name, &@env[name]) unless options[:method] == false self end ## # Returns the concatenation of the stack and queue. # # @return [Array] def to_a (@stack + @queue).to_a end ## # Returns the operand at the top of the stack. # # If the stack is empty, returns `nil`. # # @return [Object] def peek @stack.last end ## # Pops and returns one or more operands off the top of the stack. # # If the stack doesn't have sufficient operands, raises a stack # underflow error. # # @overload pop # @return [Object] # # @overload pop(n) # @param [Integer] n # @return [Array] # # @return [Object] # @raise [StackUnderflowError] def pop(n = nil) if @stack.size < (n || 1) raise StackUnderflowError.new else n ? @stack.pop(n) : @stack.pop end end ## # Pushes the given operands onto the top of the stack. # # If no operands were given, shifts an operand off the front of the # queue. # # @overload push # @return [Machine] # # @overload push(*ops) # @param [Array] ops # @return [Machine] # # @return [Machine] def push(*ops) @stack.push(*(ops.empty? ? [shift] : ops)) self end ## # Shifts and returns one or more operands off the front of the queue. # # If the queue doesn't have sufficient operands, throws a `:halt` # symbol. # # @overload shift # @return [Object] # # @overload shift(n) # @param [Integer] n # @return [Array] # # @return [Object] def shift(n = nil) if @queue.size < (n || 1) throw(:halt) # caught in `#execute` else n ? @queue.shift(n) : @queue.shift end end ## # Prepends the given operands onto the front of the queue. # # If no operands were given, pops an operand off the top of the stack. # # @overload unshift # @return [Machine] # # @overload unshift(*ops) # @param [Array] ops # @return [Machine] # # @return [Machine] def unshift(*ops) @queue.unshift(*(ops.empty? ? [pop] : ops)) self end ## # Executes the virtual machine until it halts. # # The machine will halt when the queue is exhausted, when encountering # a `halt` operator, or when encountering an error condition. # # @overload execute(code) # @param [Array] code # @return [Machine] # # @overload execute(code) # @param [Array] code # @yield [machine] # @yieldparam [Machine] machine # @return [Machine] # # @return [Machine] def execute(code = [], &block) @queue.unshift(*code) unless code.empty? catch(:halt) do # thrown in `#shift` Kernel.loop do execute_hook.call if execute_hook && [email protected]? op = shift case when operator?(op) if fn = @env[op] fn.call else unshift(op) raise InvalidOperatorError.new(op) end when operand?(op) push(op) else raise InvalidOperandError.new(op) end end end if block_given? case block.arity when 1 then block.call(self) else instance_eval(&block) end end return self end protected ## # Returns `true` if `op` is an operator. # # @param [Object] op # @return [Boolean] def operator?(op) op.is_a?(Symbol) end ## # Returns `true` if `op` is an operand. # # @param [Object] op # @return [Boolean] def operand?(op) !operator?(op) end ## # Returns `true` if `op` is a quotation. # # @param [Object] op # @return [Boolean] def quotation?(op) op.is_a?(Array) end ## # @private def method_missing(operator, *operands, &block) begin super rescue NoMethodError => e raise InvalidOperatorError.new(operator) end end ## # Imports operators from the given `module` into the virtual machine's # current environment. # # @param [Module] module # @return [void] def import_module!(mod) # Include all instance methods from the module into `self`: this = class << self; self; end this.send(:include, mod) # Create wrapper methods to support operators that need their # arguments and result marshalled from/to the virtual machine stack: mod.public_instance_methods(true).map(&:to_sym).each do |method| op = mod.instance_method(method).bind(self) case method when :stack_ # FIXME @env[:stack] = op else @env[method] = this.send(:define_method, method) do |*args| result = op.call(*(!args.empty? ? args : (op.arity > 0 ? pop(op.arity) : []))) push(result) unless result.equal?(self) return self end end end end ## # Invokes the given block with an empty code queue, restoring the # queue contents after the block returns. # # @yield # @param [Symbol] name # @return [void] def with_saved_continuation(name = nil, &block) cc = capture_continuation case block.arity when 1 then block.call(cc) else block.call end @queue.push(*cc) unless cc.empty? self end ## # Invokes the given block with an empty code queue, passing the previous # queue contents as an argument. # # @yield # @return [void] def with_current_continuation(&block) block.call(capture_continuation) self end ## # Captures the current contents of the code queue, returning them to the # caller after first clearing the queue. # # @return [Array] def capture_continuation(full = false) continuation = @queue.dup @queue.clear continuation end ### # Invalid operator class InvalidOperatorError < NoMethodError attr_reader :operator def initialize(operator) @operator = operator super("invalid operator: #{operator}") end end ### # Invalid operand class InvalidOperandError < ArgumentError attr_reader :operand attr_reader :operator def initialize(operand, operator = nil) @operand, @operator = operand, operator super("invalid operand: #{operand.inspect}") end end ### # Stack underflow class StackUnderflowError < RuntimeError; end end # class Machine end # module Trith diff --git a/lib/trith/vocab/core.rb b/lib/trith/vocab/core.rb new file mode 100644 index 0000000..9e570cd --- /dev/null +++ b/lib/trith/vocab/core.rb @@ -0,0 +1,18 @@ +module Trith + ## + # The Trith core operators. + module Core + require 'trith/vocab/core/execution' + require 'trith/vocab/core/stack' + require 'trith/vocab/core/bitwise' + require 'trith/vocab/core/boolean' + require 'trith/vocab/core/comparison' + require 'trith/vocab/core/numeric' + require 'trith/vocab/core/sequence' + require 'trith/vocab/core/textual' + require 'trith/vocab/core/output' + + # Include all submodule methods directly into Trith::Core: + constants.each { |mod| include(const_get(mod)) } + end # module Core +end # module Trith diff --git a/lib/trith/core/bitwise.rb b/lib/trith/vocab/core/bitwise.rb similarity index 100% rename from lib/trith/core/bitwise.rb rename to lib/trith/vocab/core/bitwise.rb diff --git a/lib/trith/core/boolean.rb b/lib/trith/vocab/core/boolean.rb similarity index 100% rename from lib/trith/core/boolean.rb rename to lib/trith/vocab/core/boolean.rb diff --git a/lib/trith/core/comparison.rb b/lib/trith/vocab/core/comparison.rb similarity index 100% rename from lib/trith/core/comparison.rb rename to lib/trith/vocab/core/comparison.rb diff --git a/lib/trith/core/execution.rb b/lib/trith/vocab/core/execution.rb similarity index 100% rename from lib/trith/core/execution.rb rename to lib/trith/vocab/core/execution.rb diff --git a/lib/trith/core/numeric.rb b/lib/trith/vocab/core/numeric.rb similarity index 100% rename from lib/trith/core/numeric.rb rename to lib/trith/vocab/core/numeric.rb diff --git a/lib/trith/core/output.rb b/lib/trith/vocab/core/output.rb similarity index 100% rename from lib/trith/core/output.rb rename to lib/trith/vocab/core/output.rb diff --git a/lib/trith/core/sequence.rb b/lib/trith/vocab/core/sequence.rb similarity index 100% rename from lib/trith/core/sequence.rb rename to lib/trith/vocab/core/sequence.rb diff --git a/lib/trith/core/stack.rb b/lib/trith/vocab/core/stack.rb similarity index 100% rename from lib/trith/core/stack.rb rename to lib/trith/vocab/core/stack.rb diff --git a/lib/trith/core/textual.rb b/lib/trith/vocab/core/textual.rb similarity index 100% rename from lib/trith/core/textual.rb rename to lib/trith/vocab/core/textual.rb diff --git a/lib/trith/vocab/math.rb b/lib/trith/vocab/math.rb new file mode 100644 index 0000000..dea4efe --- /dev/null +++ b/lib/trith/vocab/math.rb @@ -0,0 +1,15 @@ +module Trith + ## + # The Trith math operators. + # + # @see http://ruby-doc.org/core/classes/Math.html + module Math + require 'trith/vocab/math/arithmetic' + require 'trith/vocab/math/constants' + require 'trith/vocab/math/operators' + require 'trith/vocab/math/trigonometry' + + # Include all submodule methods directly into Trith::Math: + constants.each { |mod| include(const_get(mod)) } + end # module Math +end # module Trith diff --git a/lib/trith/core/arithmetic.rb b/lib/trith/vocab/math/arithmetic.rb similarity index 96% rename from lib/trith/core/arithmetic.rb rename to lib/trith/vocab/math/arithmetic.rb index f31fdf2..7dfbf3c 100644 --- a/lib/trith/core/arithmetic.rb +++ b/lib/trith/vocab/math/arithmetic.rb @@ -1,97 +1,97 @@ -module Trith; module Core +module Trith; module Math ## # Arithmetic operators. # # @see http://www.math.bas.bg/bantchev/articles/divmod.pdf module Arithmetic ## # @param [Numeric] n # @return [Numeric] def abs(n) n.abs end ## # @param [Numeric] n # @return [Numeric] def neg(n) -n end ## # @param [Numeric] n # @return [Numeric] def inc(n) n + 1 end ## # @param [Numeric] n # @return [Numeric] def dec(n) n - 1 end ## # @param [Numeric] a # @param [Numeric] b # @return [Numeric] def add(a, b) a + b end alias_method :+, :add ## # @param [Numeric] a # @param [Numeric] b # @return [Numeric] def sub(a, b) a - b end alias_method :-, :sub ## # @param [Numeric] a # @param [Numeric] b # @return [Numeric] def mul(a, b) a * b end alias_method :*, :mul ## # @param [Numeric] a # @param [Numeric] b # @return [Numeric] def div(a, b) a / b end alias_method :'/', :div ## # @param [Numeric] a # @param [Numeric] b # @return [Numeric] def rem(a, b) a.remainder(b) end ## # @param [Numeric] a # @param [Numeric] b # @return [Numeric] def mod(a, b) a.modulo(b) end #alias_method :'%', :mod ## # @param [Numeric] a # @param [Numeric] b # @return [Numeric] def pow(a, b) a ** b end #alias_method :'^', :pow end # module Arithmetic -end; end # module Trith::Core +end; end # module Trith::Math diff --git a/lib/trith/vocab/math/constants.rb b/lib/trith/vocab/math/constants.rb new file mode 100644 index 0000000..04a904e --- /dev/null +++ b/lib/trith/vocab/math/constants.rb @@ -0,0 +1,9 @@ +module Trith; module Math + ## + # Math constants. + # + # @see http://ruby-doc.org/core/classes/Math.html + module Constants + # TODO + end # module Constants +end; end # module Trith::Math diff --git a/lib/trith/vocab/math/operators.rb b/lib/trith/vocab/math/operators.rb new file mode 100644 index 0000000..8c6c2e6 --- /dev/null +++ b/lib/trith/vocab/math/operators.rb @@ -0,0 +1,21 @@ +module Trith; module Math + ## + # Math operators. + # + # @see http://ruby-doc.org/core/classes/Math.html + module Operators + ## + # @param [Numeric, #ceil] n + # @return [Integer] + def ceil(n) + n.ceil + end + + ## + # @param [Numeric, #floor] n + # @return [Integer] + def floor(n) + n.floor + end + end # module Operators +end; end # module Trith::Math diff --git a/lib/trith/vocab/math/trigonometry.rb b/lib/trith/vocab/math/trigonometry.rb new file mode 100644 index 0000000..69b9bc6 --- /dev/null +++ b/lib/trith/vocab/math/trigonometry.rb @@ -0,0 +1,10 @@ +module Trith; module Math + ## + # Trigonometric operators. + # + # @see http://en.wikipedia.org/wiki/Trigonometric_functions + # @see http://en.wikipedia.org/wiki/Inverse_trigonometric_functions + module Trigonometry + # TODO + end # module Trigonometry +end; end # module Trith::Math
trith/trith
1951e48aa8d2b2a7385d14928eefd67c78e90de8
Bumped the Backports dependency.
diff --git a/.gemspec b/.gemspec index e460ce6..70b5386 100644 --- a/.gemspec +++ b/.gemspec @@ -1,40 +1,40 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.author = 'Arto Bendiken' gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.1' gem.requirements = [] gem.add_runtime_dependency 'sxp', '~> 0.0.5' gem.add_runtime_dependency 'rdf', '~> 0.2.0' gem.add_runtime_dependency 'promise', '>= 0.2.0' - gem.add_runtime_dependency 'backports', '>= 1.18.0' + gem.add_runtime_dependency 'backports', '>= 1.18.1' gem.add_development_dependency 'yard' , '>= 0.5.8' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'buildr' , '>= 1.3.5' gem.post_install_message = nil end diff --git a/README.md b/README.md index f1cd11e..283c258 100644 --- a/README.md +++ b/README.md @@ -1,338 +1,338 @@ Trith: Recombinant Programming ============================== Trith is an experimental [concatenative][concat.org] programming language founded on the [unholy][lispers.org] trinity of [Forth][], [Lisp][] and [RDF][] triples. * <http://trith.org/> * <http://github.com/trith/trith> Description ----------- Trith is a stack-based, concatenative, dynamically-typed functional programming language with a homoiconic program representation. * [Stack-based][stack-oriented] means that instead of having named parameters, Trith functions operate on an implicit data structure called the _operand stack_. Trith functions can be thought of in terms of popping and pushing operands from/onto this stack, or equivalently in purely functional terms as unary functions that map from one stack to another. * [Concatenative][concatenative] means that the concatenation of any two Trith functions also denotes the [composition][] of those functions. * [Dynamically typed][type system] means that operands to Trith functions are type-checked dynamically at runtime. * [Homoiconic][homoiconic] means that in Trith there is no difference between code and data. You can manipulate and construct code at runtime as easily as you would manipulate any other data structure, enabling powerful metaprogramming facilities. Trith programs are simply nested lists of operators and operands, and can be represented externally either as [S-expressions][S-expression] or as [RDF][] triples. Trith is inspired and influenced by experience with [Forth][], [Lisp][] and [Scheme][] in general, and the concatenative languages [Joy][], [XY][], [Factor][] and [Cat][] in particular. Introduction ------------ The Trith implementation currently consists of a virtual machine, interpreter, and compiler toolchain written in Ruby and an in-the-works runtime targeting the [JVM][]. You can use the Trith shell `3sh` to explore Trith interactively: $ 3sh >> "Hello, world!" print Hello, world! For example, here's how you would start with two prime numbers and end up with the correct answer to the ultimate question of life, the universe, and everything: $ 3sh >> 3 7 swap dup + * => [42] : [] In the above `3sh` examples, `>>` indicates lines that you type, and `=>` indicates the result from the shell. After each input line is evaluated, the shell will show you the current state of the Trith virtual machine's data stack and code queue. Thus in our previous example, the `[42]` on the left-hand side shows that the machine's stack contains a single operand, the number 42. The `[]` on the right-hand side shows that the machine's code queue is empty, which is generally the case after all input has been successfully evaluated. Let's run through the above example one more time using the `--debug` option to `3sh`, which enables the tracing of each queue reduction step in the virtual machine: $ 3sh --debug >> 3 7 swap dup + * .. [] : [3 7 swap dup + *] .. [3] : [7 swap dup + *] .. [3 7] : [swap dup + *] .. [7 3] : [dup + *] .. [7 3 3] : [+ *] .. [7 6] : [*] => [42] : [] As you can see, the virtual machine starts execution with an empty operand stack on the left-hand side and with all input placed onto the operator queue on the right-hand side. When input operands such as numbers are encountered on the queue, they are simply pushed onto the stack, which grows from left to right. When an operator such as the multiplication operator `*` is encountered on the queue, it is executed. Operators pop operands from the stack and then push their result(s) back onto the stack. When fooling around in the Trith shell, two useful operators to know are `clear`, which clears the stack, and `halt`, which clears the queue (thus halting execution). You can also use `reset` which does both in one step, returning you to a guaranteed clean slate. To get a listing of all operators supported in the current release, enter the `?` metacommand in the Trith shell. Linked Code ----------- All Trith operators are identified by URIs, meaning that Trith code can be straightforwardly represented as [Linked Data][]. Here's an example of the `abs` operator defined metacircularly using the Turtle serialization format for RDF data: @base <http://trith.org/core/> . @prefix trith: <http://trith.org/lang/> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . <abs> a trith:Function ; rdfs:label "abs" ; rdfs:comment "Returns the absolute value of a number."@en ; trith:arity 1 ; trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . This function description comprises a total of 21 triples. The entire Trith core library currently weighs in at about a kilotriple (1,000 triples), with all but a handful of primitive (irreducible) operators having a metacircular definition. See `etc/trith-core.ttl` for the RDF definitions of Trith core operators. Reference --------- ### Sequences Trith has a rich set of sequence operators that will be instantly familiar to programmers coming from functional programming languages such as Scheme, Clojure or Haskell: >> 10 iota => [[0 1 2 3 4 5 6 7 8 9]] : [] >> dup seq? . true >> dup empty? . false >> dup length . 10 >> [dup mul] map => [[0 1 4 9 16 25 36 49 64 81]] : [] >> dup first . 0 >> dup fifth . 16 >> dup 7 nth . 49 >> dup last . 81 >> dup 0 [+] foldl . 285 >> rest => [[1 4 9 16 25 36 49 64 81]] : [] >> dup 1 [*] foldl . 131681894400 >> reverse => [[81 64 49 36 25 16 9 4 1]] : [] ### Strings Strings are simply sequences of characters (Unicode code points), meaning that you can make use of any of the normal sequence operators on strings as well: >> : hello "Hello," " world!" concat ; >> hello seq? . true >> hello text? . true >> hello empty? . false >> hello length . 13 >> hello first . H >> hello rest . ello, world! >> hello reverse . !dlrow ,olleH Scripting --------- The canonical "Hello, world!" script is found in `doc/examples/hello.3th`: #!/usr/bin/env 3vm "Hello, world!" print Any command-line arguments passed to 3VM scripts form the initial stack of the virtual machine. The arguments are placed on the stack in their original unparsed string form. You can print out the contents of the initial stack like so: #!/usr/bin/env 3vm stack print Here's an example of how you would interpret all given command-line arguments as numbers and then sum them up and print out the result: #!/usr/bin/env 3vm stack [num] map 0 [+] foldl print Embedding --------- ### Embedding Trith in Ruby require 'trith' # Let's start with the obligatory "Hello, world!" example: Trith::Machine.run do push "Hello, world!" print end # There are several equivalent ways to execute Trith code: Trith::Machine.run { push(6, 7).mul } #=> 42 Trith::Machine.run [6, 7] { mul } #=> 42 Trith::Machine.run [6, 7, :mul] #=> 42 # Operators in Ruby blocks can be chained together: Trith::Machine.run { push(2).dup.dup.mul.pow } #=> 16 # If you require more control, instantiate a machine manually: vm = Trith::Machine.new vm.define!(:square) { dup.mul } vm.push(10).square.peek #=> 100 # You can also define operators when constructing a machine: vm = Trith::Machine.new(data = [], code = [], { :hello => proc { push("Hello, world!").print }, }) # Should you want to use any Trith functions from Ruby, it's easy enough # to encapsulate a virtual machine inside a Ruby method: def square(n) Trith::Machine.run [n] { dup.mul } end square(10) #=> 100 ### Embedding Trith in JVM-based languages The [JVM][] runtime for Trith is a work in progress. See `src/java` for the runtime's source code and current status. Dependencies ------------ * [Ruby](http://ruby-lang.org/) (>= 1.9.1) or - (>= 1.8.2 with [Backports](http://rubygems.org/gems/backports)) + (>= 1.8.1 with [Backports](http://rubygems.org/gems/backports)) * [RDF.rb](http://rubygems.org/gems/rdf) (>= 0.2.0) * [SXP](http://rubygems.org/gems/sxp) (>= 0.0.5) * [Promise](http://rubygems.org/gems/promise) (>= 0.2.0) Installation ------------ The recommended installation method is via [RubyGems](http://rubygems.org/). To install the latest official release of the `trith` gem, do one of the following: $ [sudo] gem install trith # Ruby 1.8.x/1.9.x $ [sudo] gem1.9 install trith # Ruby 1.9 with MacPorts $ [sudo] jruby --1.9 -S gem install trith # JRuby 1.5+ Once Trith is installed, you will have four new programs available: * `3sh`, aka "trish", is the Trith interactive shell and interpreter. * `3vm`, aka "trivium", is the Trith virtual machine runtime. * `3cc`, aka "tricksy", is the Trith compiler. * `3th`, aka "trith", is the Trith package manager. Note that as of the current release, only the first two do anything much as yet. Environment ----------- The following are the default settings for environment variables that let you customize how Trith works: $ export TRITH_HOME=~/.trith $ export TRITH_CACHE=$TRITH_HOME/cache $ export TRITH_TERM=$TERM Download -------- To get a local working copy of the development repository, do: $ git clone git://github.com/trith/trith.git Alternatively, you can download the latest development version as a tarball as follows: $ wget http://github.com/trith/trith/tarball/master Mailing List ------------ * <http://groups.google.com/group/trith> Authors ------- * [Arto Bendiken](mailto:[email protected]) - <http://ar.to/> License ------- Trith is free and unencumbered public domain software. For more information, see <http://unlicense.org/> or the accompanying UNLICENSE file. [stack-oriented]: http://en.wikipedia.org/wiki/Stack-oriented_programming_language [concatenative]: http://en.wikipedia.org/wiki/Concatenative_programming_language [composition]: http://en.wikipedia.org/wiki/Function_composition [type system]: http://en.wikipedia.org/wiki/Type_system#Dynamic_typing [homoiconic]: http://en.wikipedia.org/wiki/Homoiconicity [S-expression]: http://en.wikipedia.org/wiki/S-expression [RDF]: http://en.wikipedia.org/wiki/Resource_Description_Framework [JVM]: http://en.wikipedia.org/wiki/Java_Virtual_Machine [Lisp]: http://en.wikipedia.org/wiki/Lisp_(programming_language) [Scheme]: http://en.wikipedia.org/wiki/Scheme_(programming_language) [Forth]: http://en.wikipedia.org/wiki/Forth_(programming_language) [Factor]: http://en.wikipedia.org/wiki/Factor_(programming_language) [Joy]: http://en.wikipedia.org/wiki/Joy_(programming_language) [Cat]: http://en.wikipedia.org/wiki/Cat_(programming_language) [XY]: http://www.nsl.com/k/xy/xy.htm [Linked Data]: http://linkeddata.org/ [lispers.org]: http://lispers.org/ [concat.org]: http://concatenative.org/wiki/view/Concatenative%20language
trith/trith
255c396c7fcd2181285ac396fd50e60c4b9be21f
Upgraded Trith::Machine#define! to take advantage of Ruby 1.9 features.
diff --git a/lib/trith/machine.rb b/lib/trith/machine.rb index 95ea804..4f5d6f6 100644 --- a/lib/trith/machine.rb +++ b/lib/trith/machine.rb @@ -1,380 +1,377 @@ module Trith ## # The Trith virtual machine. class Machine # @return [Array] attr_reader :stack # @return [Array] attr_reader :queue # @return [Proc] attr_accessor :execute_hook ## # Executes `code` in a new virtual machine instance. # # The machine will halt when the queue is exhausted, when encountering # a `halt` operator, or when encountering an error condition. # # @overload self.run(code) # @param [Array] code # @return [Object] # # @overload self.run(code) # @param [Array] code # @yield [machine] # @yieldparam [Machine] machine # @return [Object] # # @return [Object] def self.run(code = [], &block) self.new([], code).execute(&block).peek end ## # Initializes a new virtual machine with the given initial `stack`, # `queue` and environment. # # @param [Array] stack # @param [Array] queue # @param [Hash] env # @yield [machine] # @yieldparam [Machine] machine def initialize(stack = [], queue = [], env = {}, &block) @stack, @queue, @env = stack, queue, {} import!(Trith::Core) env.each do |name, operator| if operator.is_a?(Proc) define!(name, &operator) else define!(name, operator) end end execute(&block) if block_given? end ## # Returns a developer-friendly representation of this machine. # # @return [String] def inspect sprintf("#<%s:%#0x(%s : %s)>", self.class.name, __id__, @stack.inspect, @queue.inspect) end ## # Imports operators from the given `module` into the virtual machine's # current environment. # # @param [Module] module # @return [Machine] def import!(mod) case mod when Module then import_module!(mod) when Function then # TODO else # TODO: error end self end ## # Defines a new operator `name` that will execute the given `code`. # # @param [Symbol, #to_sym] name # @param [Array] code # @param [Hash{Symbol => Object}] options # @return [Machine] def define!(name, code = [], options = {}, &block) @env[name = name.to_sym] = lambda { execute(code, &block) } - unless options[:method] == false - this = class << self; self; end - this.send(:define_method, name, &@env[name]) - end + define_singleton_method(name, &@env[name]) unless options[:method] == false self end ## # Returns the concatenation of the stack and queue. # # @return [Array] def to_a (@stack + @queue).to_a end ## # Returns the operand at the top of the stack. # # If the stack is empty, returns `nil`. # # @return [Object] def peek @stack.last end ## # Pops and returns one or more operands off the top of the stack. # # If the stack doesn't have sufficient operands, raises a stack # underflow error. # # @overload pop # @return [Object] # # @overload pop(n) # @param [Integer] n # @return [Array] # # @return [Object] # @raise [StackUnderflowError] def pop(n = nil) if @stack.size < (n || 1) raise StackUnderflowError.new else n ? @stack.pop(n) : @stack.pop end end ## # Pushes the given operands onto the top of the stack. # # If no operands were given, shifts an operand off the front of the # queue. # # @overload push # @return [Machine] # # @overload push(*ops) # @param [Array] ops # @return [Machine] # # @return [Machine] def push(*ops) @stack.push(*(ops.empty? ? [shift] : ops)) self end ## # Shifts and returns one or more operands off the front of the queue. # # If the queue doesn't have sufficient operands, throws a `:halt` # symbol. # # @overload shift # @return [Object] # # @overload shift(n) # @param [Integer] n # @return [Array] # # @return [Object] def shift(n = nil) if @queue.size < (n || 1) throw(:halt) # caught in `#execute` else n ? @queue.shift(n) : @queue.shift end end ## # Prepends the given operands onto the front of the queue. # # If no operands were given, pops an operand off the top of the stack. # # @overload unshift # @return [Machine] # # @overload unshift(*ops) # @param [Array] ops # @return [Machine] # # @return [Machine] def unshift(*ops) @queue.unshift(*(ops.empty? ? [pop] : ops)) self end ## # Executes the virtual machine until it halts. # # The machine will halt when the queue is exhausted, when encountering # a `halt` operator, or when encountering an error condition. # # @overload execute(code) # @param [Array] code # @return [Machine] # # @overload execute(code) # @param [Array] code # @yield [machine] # @yieldparam [Machine] machine # @return [Machine] # # @return [Machine] def execute(code = [], &block) @queue.unshift(*code) unless code.empty? catch(:halt) do # thrown in `#shift` Kernel.loop do execute_hook.call if execute_hook && [email protected]? op = shift case when operator?(op) if fn = @env[op] fn.call else unshift(op) raise InvalidOperatorError.new(op) end when operand?(op) push(op) else raise InvalidOperandError.new(op) end end end if block_given? case block.arity when 1 then block.call(self) else instance_eval(&block) end end return self end protected ## # Returns `true` if `op` is an operator. # # @param [Object] op # @return [Boolean] def operator?(op) op.is_a?(Symbol) end ## # Returns `true` if `op` is an operand. # # @param [Object] op # @return [Boolean] def operand?(op) !operator?(op) end ## # Returns `true` if `op` is a quotation. # # @param [Object] op # @return [Boolean] def quotation?(op) op.is_a?(Array) end ## # @private def method_missing(operator, *operands, &block) begin super rescue NoMethodError => e raise InvalidOperatorError.new(operator) end end ## # Imports operators from the given `module` into the virtual machine's # current environment. # # @param [Module] module # @return [void] def import_module!(mod) # Include all instance methods from the module into `self`: this = class << self; self; end this.send(:include, mod) # Create wrapper methods to support operators that need their # arguments and result marshalled from/to the virtual machine stack: mod.public_instance_methods(true).map(&:to_sym).each do |method| op = mod.instance_method(method).bind(self) case method when :stack_ # FIXME @env[:stack] = op else @env[method] = this.send(:define_method, method) do |*args| result = op.call(*(!args.empty? ? args : (op.arity > 0 ? pop(op.arity) : []))) push(result) unless result.equal?(self) return self end end end end ## # Invokes the given block with an empty code queue, restoring the # queue contents after the block returns. # # @yield # @param [Symbol] name # @return [void] def with_saved_continuation(name = nil, &block) cc = capture_continuation case block.arity when 1 then block.call(cc) else block.call end @queue.push(*cc) unless cc.empty? self end ## # Invokes the given block with an empty code queue, passing the previous # queue contents as an argument. # # @yield # @return [void] def with_current_continuation(&block) block.call(capture_continuation) self end ## # Captures the current contents of the code queue, returning them to the # caller after first clearing the queue. # # @return [Array] def capture_continuation(full = false) continuation = @queue.dup @queue.clear continuation end ### # Invalid operator class InvalidOperatorError < NoMethodError attr_reader :operator def initialize(operator) @operator = operator super("invalid operator: #{operator}") end end ### # Invalid operand class InvalidOperandError < ArgumentError attr_reader :operand attr_reader :operator def initialize(operand, operator = nil) @operand, @operator = operand, operator super("invalid operand: #{operand.inspect}") end end ### # Stack underflow class StackUnderflowError < RuntimeError; end end # class Machine end # module Trith
trith/trith
6770cd65d9ce5f8987fb70d0a755757f418a06a8
Added arity specs for all math operators.
diff --git a/spec/math/abs_spec.rb b/spec/math/abs_spec.rb index ce49390..8424b92 100644 --- a/spec/math/abs_spec.rb +++ b/spec/math/abs_spec.rb @@ -1,10 +1,15 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:abs" do it "is implemented" do Machine.new.should respond_to(:abs) end + it "requires one operand" do + lambda { Machine.run([:abs]) }.should underflow_stack + lambda { Machine.run([nil, :abs]) }.should_not underflow_stack + end + it "returns a number" - it "returns the absolute magnitude of the argument" + it "returns the absolute magnitude of the operand" end diff --git a/spec/math/acos_spec.rb b/spec/math/acos_spec.rb index 732ca01..995c62e 100644 --- a/spec/math/acos_spec.rb +++ b/spec/math/acos_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:acos" do it "is implemented" do Machine.new.should respond_to(:acos) end + + it "requires one operand" do + lambda { Machine.run([:acos]) }.should underflow_stack + lambda { Machine.run([nil, :acos]) }.should_not underflow_stack + end end diff --git a/spec/math/acosh_spec.rb b/spec/math/acosh_spec.rb index 240f8e7..9be9349 100644 --- a/spec/math/acosh_spec.rb +++ b/spec/math/acosh_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:acosh" do it "is implemented" do Machine.new.should respond_to(:acosh) end + + it "requires one operand" do + lambda { Machine.run([:acosh]) }.should underflow_stack + lambda { Machine.run([nil, :acosh]) }.should_not underflow_stack + end end diff --git a/spec/math/add_spec.rb b/spec/math/add_spec.rb index ae776f7..cc6215e 100644 --- a/spec/math/add_spec.rb +++ b/spec/math/add_spec.rb @@ -1,7 +1,13 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:add" do it "is implemented" do Machine.new.should respond_to(:add, :+) end + + it "requires two operands" do + lambda { Machine.run([:add]) }.should underflow_stack + lambda { Machine.run([nil, :add]) }.should underflow_stack + lambda { Machine.run([nil, nil, :add]) }.should_not underflow_stack + end end diff --git a/spec/math/asin_spec.rb b/spec/math/asin_spec.rb index 8ea606e..4ac6e19 100644 --- a/spec/math/asin_spec.rb +++ b/spec/math/asin_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:asin" do it "is implemented" do Machine.new.should respond_to(:asin) end + + it "requires one operand" do + lambda { Machine.run([:asin]) }.should underflow_stack + lambda { Machine.run([nil, :asin]) }.should_not underflow_stack + end end diff --git a/spec/math/asinh_spec.rb b/spec/math/asinh_spec.rb index c4888ad..f0b7a65 100644 --- a/spec/math/asinh_spec.rb +++ b/spec/math/asinh_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:asinh" do it "is implemented" do Machine.new.should respond_to(:asinh) end + + it "requires one operand" do + lambda { Machine.run([:asinh]) }.should underflow_stack + lambda { Machine.run([nil, :asinh]) }.should_not underflow_stack + end end diff --git a/spec/math/atan2_spec.rb b/spec/math/atan2_spec.rb index e304f79..5420555 100644 --- a/spec/math/atan2_spec.rb +++ b/spec/math/atan2_spec.rb @@ -1,7 +1,13 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:atan2" do it "is implemented" do Machine.new.should respond_to(:atan2) end + + it "requires two operands" do + lambda { Machine.run([:atan2]) }.should underflow_stack + lambda { Machine.run([nil, :atan2]) }.should underflow_stack + lambda { Machine.run([nil, nil, :atan2]) }.should_not underflow_stack + end end diff --git a/spec/math/atan_spec.rb b/spec/math/atan_spec.rb index 15864ae..54dccd6 100644 --- a/spec/math/atan_spec.rb +++ b/spec/math/atan_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:atan" do it "is implemented" do Machine.new.should respond_to(:atan) end + + it "requires one operand" do + lambda { Machine.run([:atan]) }.should underflow_stack + lambda { Machine.run([nil, :atan]) }.should_not underflow_stack + end end diff --git a/spec/math/atanh_spec.rb b/spec/math/atanh_spec.rb index 7733adc..92926da 100644 --- a/spec/math/atanh_spec.rb +++ b/spec/math/atanh_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:atanh" do it "is implemented" do Machine.new.should respond_to(:atanh) end + + it "requires one operand" do + lambda { Machine.run([:atanh]) }.should underflow_stack + lambda { Machine.run([nil, :atanh]) }.should_not underflow_stack + end end diff --git a/spec/math/cb_spec.rb b/spec/math/cb_spec.rb index 8dd612b..4d92412 100644 --- a/spec/math/cb_spec.rb +++ b/spec/math/cb_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:cb" do it "is implemented" do Machine.new.should respond_to(:cb) end + + it "requires one operand" do + lambda { Machine.run([:cb]) }.should underflow_stack + lambda { Machine.run([nil, :cb]) }.should_not underflow_stack + end end diff --git a/spec/math/cbrt_spec.rb b/spec/math/cbrt_spec.rb index 69eaa28..790aca5 100644 --- a/spec/math/cbrt_spec.rb +++ b/spec/math/cbrt_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:cbrt" do it "is implemented" do Machine.new.should respond_to(:cbrt) end + + it "requires one operand" do + lambda { Machine.run([:cbrt]) }.should underflow_stack + lambda { Machine.run([nil, :cbrt]) }.should_not underflow_stack + end end diff --git a/spec/math/ceil_spec.rb b/spec/math/ceil_spec.rb index fa76f02..e064a66 100644 --- a/spec/math/ceil_spec.rb +++ b/spec/math/ceil_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:ceil" do it "is implemented" do Machine.new.should respond_to(:ceil) end + + it "requires one operand" do + lambda { Machine.run([:ceil]) }.should underflow_stack + lambda { Machine.run([nil, :ceil]) }.should_not underflow_stack + end end diff --git a/spec/math/cos_spec.rb b/spec/math/cos_spec.rb index 155436d..4488227 100644 --- a/spec/math/cos_spec.rb +++ b/spec/math/cos_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:cos" do it "is implemented" do Machine.new.should respond_to(:cos) end + + it "requires one operand" do + lambda { Machine.run([:cos]) }.should underflow_stack + lambda { Machine.run([nil, :cos]) }.should_not underflow_stack + end end diff --git a/spec/math/cosh_spec.rb b/spec/math/cosh_spec.rb index 2010c72..7303618 100644 --- a/spec/math/cosh_spec.rb +++ b/spec/math/cosh_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:cosh" do it "is implemented" do Machine.new.should respond_to(:cosh) end + + it "requires one operand" do + lambda { Machine.run([:cosh]) }.should underflow_stack + lambda { Machine.run([nil, :cosh]) }.should_not underflow_stack + end end diff --git a/spec/math/dec_spec.rb b/spec/math/dec_spec.rb index 3476b1d..86e9099 100644 --- a/spec/math/dec_spec.rb +++ b/spec/math/dec_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:dec" do it "is implemented" do Machine.new.should respond_to(:dec) end + + it "requires one operand" do + lambda { Machine.run([:dec]) }.should underflow_stack + lambda { Machine.run([nil, :dec]) }.should_not underflow_stack + end end diff --git a/spec/math/div_spec.rb b/spec/math/div_spec.rb index 22ff807..1b5a5ae 100644 --- a/spec/math/div_spec.rb +++ b/spec/math/div_spec.rb @@ -1,7 +1,13 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:div" do it "is implemented" do Machine.new.should respond_to(:div, :'/') end + + it "requires two operands" do + lambda { Machine.run([:div]) }.should underflow_stack + lambda { Machine.run([nil, :div]) }.should underflow_stack + lambda { Machine.run([nil, nil, :div]) }.should_not underflow_stack + end end diff --git a/spec/math/exp_spec.rb b/spec/math/exp_spec.rb index 916f324..e681a74 100644 --- a/spec/math/exp_spec.rb +++ b/spec/math/exp_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:exp" do it "is implemented" do Machine.new.should respond_to(:exp) end + + it "requires one operand" do + lambda { Machine.run([:exp]) }.should underflow_stack + lambda { Machine.run([nil, :exp]) }.should_not underflow_stack + end end diff --git a/spec/math/expm1_spec.rb b/spec/math/expm1_spec.rb index 35deeb9..5caef92 100644 --- a/spec/math/expm1_spec.rb +++ b/spec/math/expm1_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:expm1" do it "is implemented" do Machine.new.should respond_to(:expm1) end + + it "requires one operand" do + lambda { Machine.run([:expm1]) }.should underflow_stack + lambda { Machine.run([nil, :expm1]) }.should_not underflow_stack + end end diff --git a/spec/math/fact_spec.rb b/spec/math/fact_spec.rb index 4a2056a..836d1f6 100644 --- a/spec/math/fact_spec.rb +++ b/spec/math/fact_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:fact" do it "is implemented" do Machine.new.should respond_to(:fact) end + + it "requires one operand" do + lambda { Machine.run([:fact]) }.should underflow_stack + lambda { Machine.run([nil, :fact]) }.should_not underflow_stack + end end diff --git a/spec/math/fib_spec.rb b/spec/math/fib_spec.rb index ed270c2..4408dfd 100644 --- a/spec/math/fib_spec.rb +++ b/spec/math/fib_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:fib" do it "is implemented" do Machine.new.should respond_to(:fib) end + + it "requires one operand" do + lambda { Machine.run([:fib]) }.should underflow_stack + lambda { Machine.run([nil, :fib]) }.should_not underflow_stack + end end diff --git a/spec/math/floor_spec.rb b/spec/math/floor_spec.rb index 5a4f286..e13b99b 100644 --- a/spec/math/floor_spec.rb +++ b/spec/math/floor_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:floor" do it "is implemented" do Machine.new.should respond_to(:floor) end + + it "requires one operand" do + lambda { Machine.run([:floor]) }.should underflow_stack + lambda { Machine.run([nil, :floor]) }.should_not underflow_stack + end end diff --git a/spec/math/gcd_spec.rb b/spec/math/gcd_spec.rb index d10e17d..ef14e67 100644 --- a/spec/math/gcd_spec.rb +++ b/spec/math/gcd_spec.rb @@ -1,7 +1,13 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:gcd" do it "is implemented" do Machine.new.should respond_to(:gcd) end + + it "requires two operands" do + lambda { Machine.run([:gcd]) }.should underflow_stack + lambda { Machine.run([nil, :gcd]) }.should underflow_stack + lambda { Machine.run([nil, nil, :gcd]) }.should_not underflow_stack + end end diff --git a/spec/math/hypot_spec.rb b/spec/math/hypot_spec.rb index 7b60490..424ef3d 100644 --- a/spec/math/hypot_spec.rb +++ b/spec/math/hypot_spec.rb @@ -1,7 +1,13 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:hypot" do it "is implemented" do Machine.new.should respond_to(:hypot) end + + it "requires two operands" do + lambda { Machine.run([:hypot]) }.should underflow_stack + lambda { Machine.run([nil, :hypot]) }.should underflow_stack + lambda { Machine.run([nil, nil, :hypot]) }.should_not underflow_stack + end end diff --git a/spec/math/inc_spec.rb b/spec/math/inc_spec.rb index 1a2ff77..c380cc5 100644 --- a/spec/math/inc_spec.rb +++ b/spec/math/inc_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:inc" do it "is implemented" do Machine.new.should respond_to(:inc) end + + it "requires one operand" do + lambda { Machine.run([:inc]) }.should underflow_stack + lambda { Machine.run([nil, :inc]) }.should_not underflow_stack + end end diff --git a/spec/math/lcm_spec.rb b/spec/math/lcm_spec.rb index 3a3bdb3..9886f9d 100644 --- a/spec/math/lcm_spec.rb +++ b/spec/math/lcm_spec.rb @@ -1,7 +1,13 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:lcm" do it "is implemented" do Machine.new.should respond_to(:lcm) end + + it "requires two operands" do + lambda { Machine.run([:lcm]) }.should underflow_stack + lambda { Machine.run([nil, :lcm]) }.should underflow_stack + lambda { Machine.run([nil, nil, :lcm]) }.should_not underflow_stack + end end diff --git a/spec/math/log10_spec.rb b/spec/math/log10_spec.rb index 3d0a226..b36426c 100644 --- a/spec/math/log10_spec.rb +++ b/spec/math/log10_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:log10" do it "is implemented" do Machine.new.should respond_to(:log10) end + + it "requires one operand" do + lambda { Machine.run([:log10]) }.should underflow_stack + lambda { Machine.run([nil, :log10]) }.should_not underflow_stack + end end diff --git a/spec/math/log1p_spec.rb b/spec/math/log1p_spec.rb index dc48105..2fd6196 100644 --- a/spec/math/log1p_spec.rb +++ b/spec/math/log1p_spec.rb @@ -1,7 +1,13 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:log1p" do it "is implemented" do Machine.new.should respond_to(:log1p) end + + it "requires two operands" do + lambda { Machine.run([:log1p]) }.should underflow_stack + lambda { Machine.run([nil, :log1p]) }.should underflow_stack + lambda { Machine.run([nil, nil, :log1p]) }.should_not underflow_stack + end end diff --git a/spec/math/log2_spec.rb b/spec/math/log2_spec.rb index 1ba932c..dd75187 100644 --- a/spec/math/log2_spec.rb +++ b/spec/math/log2_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:log2" do it "is implemented" do Machine.new.should respond_to(:log2) end + + it "requires one operand" do + lambda { Machine.run([:log2]) }.should underflow_stack + lambda { Machine.run([nil, :log2]) }.should_not underflow_stack + end end diff --git a/spec/math/log_spec.rb b/spec/math/log_spec.rb index 505daac..18fdb61 100644 --- a/spec/math/log_spec.rb +++ b/spec/math/log_spec.rb @@ -1,7 +1,13 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:log" do it "is implemented" do Machine.new.should respond_to(:log) end + + it "requires two operands" do + lambda { Machine.run([:log]) }.should underflow_stack + lambda { Machine.run([nil, :log]) }.should underflow_stack + lambda { Machine.run([nil, nil, :log]) }.should_not underflow_stack + end end diff --git a/spec/math/mod_spec.rb b/spec/math/mod_spec.rb index 88ddbb3..7c64836 100644 --- a/spec/math/mod_spec.rb +++ b/spec/math/mod_spec.rb @@ -1,7 +1,13 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:mod" do it "is implemented" do Machine.new.should respond_to(:mod) end + + it "requires two operands" do + lambda { Machine.run([:mod]) }.should underflow_stack + lambda { Machine.run([nil, :mod]) }.should underflow_stack + lambda { Machine.run([nil, nil, :mod]) }.should_not underflow_stack + end end diff --git a/spec/math/mul_spec.rb b/spec/math/mul_spec.rb index d79742a..1adc512 100644 --- a/spec/math/mul_spec.rb +++ b/spec/math/mul_spec.rb @@ -1,7 +1,13 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:mul" do it "is implemented" do Machine.new.should respond_to(:mul, :*) end + + it "requires two operands" do + lambda { Machine.run([:mul]) }.should underflow_stack + lambda { Machine.run([nil, :mul]) }.should underflow_stack + lambda { Machine.run([nil, nil, :mul]) }.should_not underflow_stack + end end diff --git a/spec/math/neg_spec.rb b/spec/math/neg_spec.rb index 3326fc8..2862594 100644 --- a/spec/math/neg_spec.rb +++ b/spec/math/neg_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:neg" do it "is implemented" do Machine.new.should respond_to(:neg) end + + it "requires one operand" do + lambda { Machine.run([:neg]) }.should underflow_stack + lambda { Machine.run([nil, :neg]) }.should_not underflow_stack + end end diff --git a/spec/math/pi_spec.rb b/spec/math/pi_spec.rb index 122e8d3..71de59d 100644 --- a/spec/math/pi_spec.rb +++ b/spec/math/pi_spec.rb @@ -1,7 +1,11 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:pi" do it "is implemented" do Machine.new.should respond_to(:pi) end + + it "requires no operands" do + lambda { Machine.run([:pi]) }.should_not underflow_stack + end end diff --git a/spec/math/pow_spec.rb b/spec/math/pow_spec.rb index 27be987..37055c8 100644 --- a/spec/math/pow_spec.rb +++ b/spec/math/pow_spec.rb @@ -1,7 +1,13 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:pow" do it "is implemented" do Machine.new.should respond_to(:pow) end + + it "requires two operands" do + lambda { Machine.run([:pow]) }.should underflow_stack + lambda { Machine.run([nil, :pow]) }.should underflow_stack + lambda { Machine.run([nil, nil, :pow]) }.should_not underflow_stack + end end diff --git a/spec/math/rand_spec.rb b/spec/math/rand_spec.rb index 058d254..b76e4d4 100644 --- a/spec/math/rand_spec.rb +++ b/spec/math/rand_spec.rb @@ -1,7 +1,11 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:rand" do it "is implemented" do Machine.new.should respond_to(:rand) end + + it "requires no operands" do + lambda { Machine.run([:rand]) }.should_not underflow_stack + end end diff --git a/spec/math/rem_spec.rb b/spec/math/rem_spec.rb index 37663bd..5678fe4 100644 --- a/spec/math/rem_spec.rb +++ b/spec/math/rem_spec.rb @@ -1,7 +1,13 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:rem" do it "is implemented" do Machine.new.should respond_to(:rem) end + + it "requires two operands" do + lambda { Machine.run([:rem]) }.should underflow_stack + lambda { Machine.run([nil, :rem]) }.should underflow_stack + lambda { Machine.run([nil, nil, :rem]) }.should_not underflow_stack + end end diff --git a/spec/math/round_spec.rb b/spec/math/round_spec.rb index c5c232b..fc1b8bd 100644 --- a/spec/math/round_spec.rb +++ b/spec/math/round_spec.rb @@ -1,7 +1,13 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:round" do it "is implemented" do Machine.new.should respond_to(:round) end + + it "requires two operands" do + lambda { Machine.run([:round]) }.should underflow_stack + lambda { Machine.run([nil, :round]) }.should underflow_stack + lambda { Machine.run([nil, nil, :round]) }.should_not underflow_stack + end end diff --git a/spec/math/sign_spec.rb b/spec/math/sign_spec.rb index 9f96ea1..1050ace 100644 --- a/spec/math/sign_spec.rb +++ b/spec/math/sign_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:sign" do it "is implemented" do Machine.new.should respond_to(:sign) end + + it "requires one operand" do + lambda { Machine.run([:sign]) }.should underflow_stack + lambda { Machine.run([nil, :sign]) }.should_not underflow_stack + end end diff --git a/spec/math/sin_spec.rb b/spec/math/sin_spec.rb index 30557fa..4bb9eda 100644 --- a/spec/math/sin_spec.rb +++ b/spec/math/sin_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:sin" do it "is implemented" do Machine.new.should respond_to(:sin) end + + it "requires one operand" do + lambda { Machine.run([:sin]) }.should underflow_stack + lambda { Machine.run([nil, :sin]) }.should_not underflow_stack + end end diff --git a/spec/math/sinh_spec.rb b/spec/math/sinh_spec.rb index f1d45b9..b872dee 100644 --- a/spec/math/sinh_spec.rb +++ b/spec/math/sinh_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:sinh" do it "is implemented" do Machine.new.should respond_to(:sinh) end + + it "requires one operand" do + lambda { Machine.run([:sinh]) }.should underflow_stack + lambda { Machine.run([nil, :sinh]) }.should_not underflow_stack + end end diff --git a/spec/math/sq_spec.rb b/spec/math/sq_spec.rb index 60d3acd..fb5564e 100644 --- a/spec/math/sq_spec.rb +++ b/spec/math/sq_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:sq" do it "is implemented" do Machine.new.should respond_to(:sq) end + + it "requires one operand" do + lambda { Machine.run([:sq]) }.should underflow_stack + lambda { Machine.run([nil, :sq]) }.should_not underflow_stack + end end diff --git a/spec/math/sqrt_spec.rb b/spec/math/sqrt_spec.rb index fbd9347..5440227 100644 --- a/spec/math/sqrt_spec.rb +++ b/spec/math/sqrt_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:sqrt" do it "is implemented" do Machine.new.should respond_to(:sqrt) end + + it "requires one operand" do + lambda { Machine.run([:sqrt]) }.should underflow_stack + lambda { Machine.run([nil, :sqrt]) }.should_not underflow_stack + end end diff --git a/spec/math/sub_spec.rb b/spec/math/sub_spec.rb index 119e164..d5d732d 100644 --- a/spec/math/sub_spec.rb +++ b/spec/math/sub_spec.rb @@ -1,7 +1,13 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:sub" do it "is implemented" do Machine.new.should respond_to(:sub, :-) end + + it "requires two operands" do + lambda { Machine.run([:sub]) }.should underflow_stack + lambda { Machine.run([nil, :sub]) }.should underflow_stack + lambda { Machine.run([nil, nil, :sub]) }.should_not underflow_stack + end end diff --git a/spec/math/tan_spec.rb b/spec/math/tan_spec.rb index 5f6ca23..b9dbf51 100644 --- a/spec/math/tan_spec.rb +++ b/spec/math/tan_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:tan" do it "is implemented" do Machine.new.should respond_to(:tan) end + + it "requires one operand" do + lambda { Machine.run([:tan]) }.should underflow_stack + lambda { Machine.run([nil, :tan]) }.should_not underflow_stack + end end diff --git a/spec/math/tanh_spec.rb b/spec/math/tanh_spec.rb index 1513dfe..60cab25 100644 --- a/spec/math/tanh_spec.rb +++ b/spec/math/tanh_spec.rb @@ -1,7 +1,12 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe "math:tanh" do it "is implemented" do Machine.new.should respond_to(:tanh) end + + it "requires one operand" do + lambda { Machine.run([:tanh]) }.should underflow_stack + lambda { Machine.run([nil, :tanh]) }.should_not underflow_stack + end end
trith/trith
f3b75ce931ea513bf4b21a7085ea33ed9ca03d20
Added a #underflow_stack RSpec matcher.
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 1cc6060..a64b823 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,2 +1,24 @@ require 'trith' include Trith + +module Trith + module Spec + module Matchers + def self.define(name, &declarations) + define_method name do |*expected| + ::Spec::Matchers::Matcher.new(name, *expected, &declarations) + end + end + + define :underflow_stack do + match do |proc| + proc.should raise_error(Machine::StackUnderflowError) + end + end + end + end +end + +Spec::Runner.configure do |config| + config.include(Trith::Spec::Matchers) +end
trith/trith
e7b3d8d3eaab8004ff91fa0813948720df7827e3
Bumped the SXP dependency.
diff --git a/.gemspec b/.gemspec index c7ee5f2..e460ce6 100644 --- a/.gemspec +++ b/.gemspec @@ -1,40 +1,40 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.author = 'Arto Bendiken' gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.1' gem.requirements = [] - gem.add_runtime_dependency 'sxp', '~> 0.0.4' + gem.add_runtime_dependency 'sxp', '~> 0.0.5' gem.add_runtime_dependency 'rdf', '~> 0.2.0' gem.add_runtime_dependency 'promise', '>= 0.2.0' gem.add_runtime_dependency 'backports', '>= 1.18.0' gem.add_development_dependency 'yard' , '>= 0.5.8' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'buildr' , '>= 1.3.5' gem.post_install_message = nil end diff --git a/README.md b/README.md index 2f5d2ce..f1cd11e 100644 --- a/README.md +++ b/README.md @@ -1,338 +1,338 @@ Trith: Recombinant Programming ============================== Trith is an experimental [concatenative][concat.org] programming language founded on the [unholy][lispers.org] trinity of [Forth][], [Lisp][] and [RDF][] triples. * <http://trith.org/> * <http://github.com/trith/trith> Description ----------- Trith is a stack-based, concatenative, dynamically-typed functional programming language with a homoiconic program representation. * [Stack-based][stack-oriented] means that instead of having named parameters, Trith functions operate on an implicit data structure called the _operand stack_. Trith functions can be thought of in terms of popping and pushing operands from/onto this stack, or equivalently in purely functional terms as unary functions that map from one stack to another. * [Concatenative][concatenative] means that the concatenation of any two Trith functions also denotes the [composition][] of those functions. * [Dynamically typed][type system] means that operands to Trith functions are type-checked dynamically at runtime. * [Homoiconic][homoiconic] means that in Trith there is no difference between code and data. You can manipulate and construct code at runtime as easily as you would manipulate any other data structure, enabling powerful metaprogramming facilities. Trith programs are simply nested lists of operators and operands, and can be represented externally either as [S-expressions][S-expression] or as [RDF][] triples. Trith is inspired and influenced by experience with [Forth][], [Lisp][] and [Scheme][] in general, and the concatenative languages [Joy][], [XY][], [Factor][] and [Cat][] in particular. Introduction ------------ The Trith implementation currently consists of a virtual machine, interpreter, and compiler toolchain written in Ruby and an in-the-works runtime targeting the [JVM][]. You can use the Trith shell `3sh` to explore Trith interactively: $ 3sh >> "Hello, world!" print Hello, world! For example, here's how you would start with two prime numbers and end up with the correct answer to the ultimate question of life, the universe, and everything: $ 3sh >> 3 7 swap dup + * => [42] : [] In the above `3sh` examples, `>>` indicates lines that you type, and `=>` indicates the result from the shell. After each input line is evaluated, the shell will show you the current state of the Trith virtual machine's data stack and code queue. Thus in our previous example, the `[42]` on the left-hand side shows that the machine's stack contains a single operand, the number 42. The `[]` on the right-hand side shows that the machine's code queue is empty, which is generally the case after all input has been successfully evaluated. Let's run through the above example one more time using the `--debug` option to `3sh`, which enables the tracing of each queue reduction step in the virtual machine: $ 3sh --debug >> 3 7 swap dup + * .. [] : [3 7 swap dup + *] .. [3] : [7 swap dup + *] .. [3 7] : [swap dup + *] .. [7 3] : [dup + *] .. [7 3 3] : [+ *] .. [7 6] : [*] => [42] : [] As you can see, the virtual machine starts execution with an empty operand stack on the left-hand side and with all input placed onto the operator queue on the right-hand side. When input operands such as numbers are encountered on the queue, they are simply pushed onto the stack, which grows from left to right. When an operator such as the multiplication operator `*` is encountered on the queue, it is executed. Operators pop operands from the stack and then push their result(s) back onto the stack. When fooling around in the Trith shell, two useful operators to know are `clear`, which clears the stack, and `halt`, which clears the queue (thus halting execution). You can also use `reset` which does both in one step, returning you to a guaranteed clean slate. To get a listing of all operators supported in the current release, enter the `?` metacommand in the Trith shell. Linked Code ----------- All Trith operators are identified by URIs, meaning that Trith code can be straightforwardly represented as [Linked Data][]. Here's an example of the `abs` operator defined metacircularly using the Turtle serialization format for RDF data: @base <http://trith.org/core/> . @prefix trith: <http://trith.org/lang/> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . <abs> a trith:Function ; rdfs:label "abs" ; rdfs:comment "Returns the absolute value of a number."@en ; trith:arity 1 ; trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . This function description comprises a total of 21 triples. The entire Trith core library currently weighs in at about a kilotriple (1,000 triples), with all but a handful of primitive (irreducible) operators having a metacircular definition. See `etc/trith-core.ttl` for the RDF definitions of Trith core operators. Reference --------- ### Sequences Trith has a rich set of sequence operators that will be instantly familiar to programmers coming from functional programming languages such as Scheme, Clojure or Haskell: >> 10 iota => [[0 1 2 3 4 5 6 7 8 9]] : [] >> dup seq? . true >> dup empty? . false >> dup length . 10 >> [dup mul] map => [[0 1 4 9 16 25 36 49 64 81]] : [] >> dup first . 0 >> dup fifth . 16 >> dup 7 nth . 49 >> dup last . 81 >> dup 0 [+] foldl . 285 >> rest => [[1 4 9 16 25 36 49 64 81]] : [] >> dup 1 [*] foldl . 131681894400 >> reverse => [[81 64 49 36 25 16 9 4 1]] : [] ### Strings Strings are simply sequences of characters (Unicode code points), meaning that you can make use of any of the normal sequence operators on strings as well: >> : hello "Hello," " world!" concat ; >> hello seq? . true >> hello text? . true >> hello empty? . false >> hello length . 13 >> hello first . H >> hello rest . ello, world! >> hello reverse . !dlrow ,olleH Scripting --------- The canonical "Hello, world!" script is found in `doc/examples/hello.3th`: #!/usr/bin/env 3vm "Hello, world!" print Any command-line arguments passed to 3VM scripts form the initial stack of the virtual machine. The arguments are placed on the stack in their original unparsed string form. You can print out the contents of the initial stack like so: #!/usr/bin/env 3vm stack print Here's an example of how you would interpret all given command-line arguments as numbers and then sum them up and print out the result: #!/usr/bin/env 3vm stack [num] map 0 [+] foldl print Embedding --------- ### Embedding Trith in Ruby require 'trith' # Let's start with the obligatory "Hello, world!" example: Trith::Machine.run do push "Hello, world!" print end # There are several equivalent ways to execute Trith code: Trith::Machine.run { push(6, 7).mul } #=> 42 Trith::Machine.run [6, 7] { mul } #=> 42 Trith::Machine.run [6, 7, :mul] #=> 42 # Operators in Ruby blocks can be chained together: Trith::Machine.run { push(2).dup.dup.mul.pow } #=> 16 # If you require more control, instantiate a machine manually: vm = Trith::Machine.new vm.define!(:square) { dup.mul } vm.push(10).square.peek #=> 100 # You can also define operators when constructing a machine: vm = Trith::Machine.new(data = [], code = [], { :hello => proc { push("Hello, world!").print }, }) # Should you want to use any Trith functions from Ruby, it's easy enough # to encapsulate a virtual machine inside a Ruby method: def square(n) Trith::Machine.run [n] { dup.mul } end square(10) #=> 100 ### Embedding Trith in JVM-based languages The [JVM][] runtime for Trith is a work in progress. See `src/java` for the runtime's source code and current status. Dependencies ------------ * [Ruby](http://ruby-lang.org/) (>= 1.9.1) or (>= 1.8.2 with [Backports](http://rubygems.org/gems/backports)) * [RDF.rb](http://rubygems.org/gems/rdf) (>= 0.2.0) -* [SXP](http://rubygems.org/gems/sxp) (>= 0.0.4) +* [SXP](http://rubygems.org/gems/sxp) (>= 0.0.5) * [Promise](http://rubygems.org/gems/promise) (>= 0.2.0) Installation ------------ The recommended installation method is via [RubyGems](http://rubygems.org/). To install the latest official release of the `trith` gem, do one of the following: $ [sudo] gem install trith # Ruby 1.8.x/1.9.x $ [sudo] gem1.9 install trith # Ruby 1.9 with MacPorts $ [sudo] jruby --1.9 -S gem install trith # JRuby 1.5+ Once Trith is installed, you will have four new programs available: * `3sh`, aka "trish", is the Trith interactive shell and interpreter. * `3vm`, aka "trivium", is the Trith virtual machine runtime. * `3cc`, aka "tricksy", is the Trith compiler. * `3th`, aka "trith", is the Trith package manager. Note that as of the current release, only the first two do anything much as yet. Environment ----------- The following are the default settings for environment variables that let you customize how Trith works: $ export TRITH_HOME=~/.trith $ export TRITH_CACHE=$TRITH_HOME/cache $ export TRITH_TERM=$TERM Download -------- To get a local working copy of the development repository, do: $ git clone git://github.com/trith/trith.git Alternatively, you can download the latest development version as a tarball as follows: $ wget http://github.com/trith/trith/tarball/master Mailing List ------------ * <http://groups.google.com/group/trith> Authors ------- * [Arto Bendiken](mailto:[email protected]) - <http://ar.to/> License ------- Trith is free and unencumbered public domain software. For more information, see <http://unlicense.org/> or the accompanying UNLICENSE file. [stack-oriented]: http://en.wikipedia.org/wiki/Stack-oriented_programming_language [concatenative]: http://en.wikipedia.org/wiki/Concatenative_programming_language [composition]: http://en.wikipedia.org/wiki/Function_composition [type system]: http://en.wikipedia.org/wiki/Type_system#Dynamic_typing [homoiconic]: http://en.wikipedia.org/wiki/Homoiconicity [S-expression]: http://en.wikipedia.org/wiki/S-expression [RDF]: http://en.wikipedia.org/wiki/Resource_Description_Framework [JVM]: http://en.wikipedia.org/wiki/Java_Virtual_Machine [Lisp]: http://en.wikipedia.org/wiki/Lisp_(programming_language) [Scheme]: http://en.wikipedia.org/wiki/Scheme_(programming_language) [Forth]: http://en.wikipedia.org/wiki/Forth_(programming_language) [Factor]: http://en.wikipedia.org/wiki/Factor_(programming_language) [Joy]: http://en.wikipedia.org/wiki/Joy_(programming_language) [Cat]: http://en.wikipedia.org/wiki/Cat_(programming_language) [XY]: http://www.nsl.com/k/xy/xy.htm [Linked Data]: http://linkeddata.org/ [lispers.org]: http://lispers.org/ [concat.org]: http://concatenative.org/wiki/view/Concatenative%20language
trith/trith
f3fe890c387fd9bfa8143dde7087a03a519c2f36
Bumped the YARD dependency.
diff --git a/.gemspec b/.gemspec index 1703cc4..c7ee5f2 100644 --- a/.gemspec +++ b/.gemspec @@ -1,40 +1,40 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.author = 'Arto Bendiken' gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.1' gem.requirements = [] gem.add_runtime_dependency 'sxp', '~> 0.0.4' gem.add_runtime_dependency 'rdf', '~> 0.2.0' gem.add_runtime_dependency 'promise', '>= 0.2.0' gem.add_runtime_dependency 'backports', '>= 1.18.0' - gem.add_development_dependency 'yard' , '>= 0.5.6' + gem.add_development_dependency 'yard' , '>= 0.5.8' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'buildr' , '>= 1.3.5' gem.post_install_message = nil end
trith/trith
0ae256b5f721ede93a228e27b7eaba7e4a027068
Bumped the Promise dependency.
diff --git a/.gemspec b/.gemspec index 2aad6cf..1703cc4 100644 --- a/.gemspec +++ b/.gemspec @@ -1,40 +1,40 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.author = 'Arto Bendiken' gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.1' gem.requirements = [] gem.add_runtime_dependency 'sxp', '~> 0.0.4' gem.add_runtime_dependency 'rdf', '~> 0.2.0' - gem.add_runtime_dependency 'promise', '~> 0.1.1' + gem.add_runtime_dependency 'promise', '>= 0.2.0' gem.add_runtime_dependency 'backports', '>= 1.18.0' gem.add_development_dependency 'yard' , '>= 0.5.6' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'buildr' , '>= 1.3.5' gem.post_install_message = nil end diff --git a/README.md b/README.md index 9a3b905..2f5d2ce 100644 --- a/README.md +++ b/README.md @@ -1,338 +1,338 @@ Trith: Recombinant Programming ============================== Trith is an experimental [concatenative][concat.org] programming language founded on the [unholy][lispers.org] trinity of [Forth][], [Lisp][] and [RDF][] triples. * <http://trith.org/> * <http://github.com/trith/trith> Description ----------- Trith is a stack-based, concatenative, dynamically-typed functional programming language with a homoiconic program representation. * [Stack-based][stack-oriented] means that instead of having named parameters, Trith functions operate on an implicit data structure called the _operand stack_. Trith functions can be thought of in terms of popping and pushing operands from/onto this stack, or equivalently in purely functional terms as unary functions that map from one stack to another. * [Concatenative][concatenative] means that the concatenation of any two Trith functions also denotes the [composition][] of those functions. * [Dynamically typed][type system] means that operands to Trith functions are type-checked dynamically at runtime. * [Homoiconic][homoiconic] means that in Trith there is no difference between code and data. You can manipulate and construct code at runtime as easily as you would manipulate any other data structure, enabling powerful metaprogramming facilities. Trith programs are simply nested lists of operators and operands, and can be represented externally either as [S-expressions][S-expression] or as [RDF][] triples. Trith is inspired and influenced by experience with [Forth][], [Lisp][] and [Scheme][] in general, and the concatenative languages [Joy][], [XY][], [Factor][] and [Cat][] in particular. Introduction ------------ The Trith implementation currently consists of a virtual machine, interpreter, and compiler toolchain written in Ruby and an in-the-works runtime targeting the [JVM][]. You can use the Trith shell `3sh` to explore Trith interactively: $ 3sh >> "Hello, world!" print Hello, world! For example, here's how you would start with two prime numbers and end up with the correct answer to the ultimate question of life, the universe, and everything: $ 3sh >> 3 7 swap dup + * => [42] : [] In the above `3sh` examples, `>>` indicates lines that you type, and `=>` indicates the result from the shell. After each input line is evaluated, the shell will show you the current state of the Trith virtual machine's data stack and code queue. Thus in our previous example, the `[42]` on the left-hand side shows that the machine's stack contains a single operand, the number 42. The `[]` on the right-hand side shows that the machine's code queue is empty, which is generally the case after all input has been successfully evaluated. Let's run through the above example one more time using the `--debug` option to `3sh`, which enables the tracing of each queue reduction step in the virtual machine: $ 3sh --debug >> 3 7 swap dup + * .. [] : [3 7 swap dup + *] .. [3] : [7 swap dup + *] .. [3 7] : [swap dup + *] .. [7 3] : [dup + *] .. [7 3 3] : [+ *] .. [7 6] : [*] => [42] : [] As you can see, the virtual machine starts execution with an empty operand stack on the left-hand side and with all input placed onto the operator queue on the right-hand side. When input operands such as numbers are encountered on the queue, they are simply pushed onto the stack, which grows from left to right. When an operator such as the multiplication operator `*` is encountered on the queue, it is executed. Operators pop operands from the stack and then push their result(s) back onto the stack. When fooling around in the Trith shell, two useful operators to know are `clear`, which clears the stack, and `halt`, which clears the queue (thus halting execution). You can also use `reset` which does both in one step, returning you to a guaranteed clean slate. To get a listing of all operators supported in the current release, enter the `?` metacommand in the Trith shell. Linked Code ----------- All Trith operators are identified by URIs, meaning that Trith code can be straightforwardly represented as [Linked Data][]. Here's an example of the `abs` operator defined metacircularly using the Turtle serialization format for RDF data: @base <http://trith.org/core/> . @prefix trith: <http://trith.org/lang/> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . <abs> a trith:Function ; rdfs:label "abs" ; rdfs:comment "Returns the absolute value of a number."@en ; trith:arity 1 ; trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . This function description comprises a total of 21 triples. The entire Trith core library currently weighs in at about a kilotriple (1,000 triples), with all but a handful of primitive (irreducible) operators having a metacircular definition. See `etc/trith-core.ttl` for the RDF definitions of Trith core operators. Reference --------- ### Sequences Trith has a rich set of sequence operators that will be instantly familiar to programmers coming from functional programming languages such as Scheme, Clojure or Haskell: >> 10 iota => [[0 1 2 3 4 5 6 7 8 9]] : [] >> dup seq? . true >> dup empty? . false >> dup length . 10 >> [dup mul] map => [[0 1 4 9 16 25 36 49 64 81]] : [] >> dup first . 0 >> dup fifth . 16 >> dup 7 nth . 49 >> dup last . 81 >> dup 0 [+] foldl . 285 >> rest => [[1 4 9 16 25 36 49 64 81]] : [] >> dup 1 [*] foldl . 131681894400 >> reverse => [[81 64 49 36 25 16 9 4 1]] : [] ### Strings Strings are simply sequences of characters (Unicode code points), meaning that you can make use of any of the normal sequence operators on strings as well: >> : hello "Hello," " world!" concat ; >> hello seq? . true >> hello text? . true >> hello empty? . false >> hello length . 13 >> hello first . H >> hello rest . ello, world! >> hello reverse . !dlrow ,olleH Scripting --------- The canonical "Hello, world!" script is found in `doc/examples/hello.3th`: #!/usr/bin/env 3vm "Hello, world!" print Any command-line arguments passed to 3VM scripts form the initial stack of the virtual machine. The arguments are placed on the stack in their original unparsed string form. You can print out the contents of the initial stack like so: #!/usr/bin/env 3vm stack print Here's an example of how you would interpret all given command-line arguments as numbers and then sum them up and print out the result: #!/usr/bin/env 3vm stack [num] map 0 [+] foldl print Embedding --------- ### Embedding Trith in Ruby require 'trith' # Let's start with the obligatory "Hello, world!" example: Trith::Machine.run do push "Hello, world!" print end # There are several equivalent ways to execute Trith code: Trith::Machine.run { push(6, 7).mul } #=> 42 Trith::Machine.run [6, 7] { mul } #=> 42 Trith::Machine.run [6, 7, :mul] #=> 42 # Operators in Ruby blocks can be chained together: Trith::Machine.run { push(2).dup.dup.mul.pow } #=> 16 # If you require more control, instantiate a machine manually: vm = Trith::Machine.new vm.define!(:square) { dup.mul } vm.push(10).square.peek #=> 100 # You can also define operators when constructing a machine: vm = Trith::Machine.new(data = [], code = [], { :hello => proc { push("Hello, world!").print }, }) # Should you want to use any Trith functions from Ruby, it's easy enough # to encapsulate a virtual machine inside a Ruby method: def square(n) Trith::Machine.run [n] { dup.mul } end square(10) #=> 100 ### Embedding Trith in JVM-based languages The [JVM][] runtime for Trith is a work in progress. See `src/java` for the runtime's source code and current status. Dependencies ------------ * [Ruby](http://ruby-lang.org/) (>= 1.9.1) or (>= 1.8.2 with [Backports](http://rubygems.org/gems/backports)) * [RDF.rb](http://rubygems.org/gems/rdf) (>= 0.2.0) * [SXP](http://rubygems.org/gems/sxp) (>= 0.0.4) -* [Promise](http://rubygems.org/gems/promise) (>= 0.1.1) +* [Promise](http://rubygems.org/gems/promise) (>= 0.2.0) Installation ------------ The recommended installation method is via [RubyGems](http://rubygems.org/). To install the latest official release of the `trith` gem, do one of the following: $ [sudo] gem install trith # Ruby 1.8.x/1.9.x $ [sudo] gem1.9 install trith # Ruby 1.9 with MacPorts $ [sudo] jruby --1.9 -S gem install trith # JRuby 1.5+ Once Trith is installed, you will have four new programs available: * `3sh`, aka "trish", is the Trith interactive shell and interpreter. * `3vm`, aka "trivium", is the Trith virtual machine runtime. * `3cc`, aka "tricksy", is the Trith compiler. * `3th`, aka "trith", is the Trith package manager. Note that as of the current release, only the first two do anything much as yet. Environment ----------- The following are the default settings for environment variables that let you customize how Trith works: $ export TRITH_HOME=~/.trith $ export TRITH_CACHE=$TRITH_HOME/cache $ export TRITH_TERM=$TERM Download -------- To get a local working copy of the development repository, do: $ git clone git://github.com/trith/trith.git Alternatively, you can download the latest development version as a tarball as follows: $ wget http://github.com/trith/trith/tarball/master Mailing List ------------ * <http://groups.google.com/group/trith> Authors ------- * [Arto Bendiken](mailto:[email protected]) - <http://ar.to/> License ------- Trith is free and unencumbered public domain software. For more information, see <http://unlicense.org/> or the accompanying UNLICENSE file. [stack-oriented]: http://en.wikipedia.org/wiki/Stack-oriented_programming_language [concatenative]: http://en.wikipedia.org/wiki/Concatenative_programming_language [composition]: http://en.wikipedia.org/wiki/Function_composition [type system]: http://en.wikipedia.org/wiki/Type_system#Dynamic_typing [homoiconic]: http://en.wikipedia.org/wiki/Homoiconicity [S-expression]: http://en.wikipedia.org/wiki/S-expression [RDF]: http://en.wikipedia.org/wiki/Resource_Description_Framework [JVM]: http://en.wikipedia.org/wiki/Java_Virtual_Machine [Lisp]: http://en.wikipedia.org/wiki/Lisp_(programming_language) [Scheme]: http://en.wikipedia.org/wiki/Scheme_(programming_language) [Forth]: http://en.wikipedia.org/wiki/Forth_(programming_language) [Factor]: http://en.wikipedia.org/wiki/Factor_(programming_language) [Joy]: http://en.wikipedia.org/wiki/Joy_(programming_language) [Cat]: http://en.wikipedia.org/wiki/Cat_(programming_language) [XY]: http://www.nsl.com/k/xy/xy.htm [Linked Data]: http://linkeddata.org/ [lispers.org]: http://lispers.org/ [concat.org]: http://concatenative.org/wiki/view/Concatenative%20language
trith/trith
1415ac6b783b784fd4b919fe1141448877578b87
Bumped the Backports dependency.
diff --git a/.gemspec b/.gemspec index b78fc94..2aad6cf 100644 --- a/.gemspec +++ b/.gemspec @@ -1,40 +1,40 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.author = 'Arto Bendiken' gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.1' gem.requirements = [] gem.add_runtime_dependency 'sxp', '~> 0.0.4' gem.add_runtime_dependency 'rdf', '~> 0.2.0' gem.add_runtime_dependency 'promise', '~> 0.1.1' - gem.add_runtime_dependency 'backports', '>= 1.17.1' + gem.add_runtime_dependency 'backports', '>= 1.18.0' gem.add_development_dependency 'yard' , '>= 0.5.6' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'buildr' , '>= 1.3.5' gem.post_install_message = nil end
trith/trith
0de8bc8d5f6d678c7c97e3d3c5c4acf8366ca266
Imported spec stubs for all math operators.
diff --git a/spec/math/abs_spec.rb b/spec/math/abs_spec.rb new file mode 100644 index 0000000..ce49390 --- /dev/null +++ b/spec/math/abs_spec.rb @@ -0,0 +1,10 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:abs" do + it "is implemented" do + Machine.new.should respond_to(:abs) + end + + it "returns a number" + it "returns the absolute magnitude of the argument" +end diff --git a/spec/math/acos_spec.rb b/spec/math/acos_spec.rb new file mode 100644 index 0000000..732ca01 --- /dev/null +++ b/spec/math/acos_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:acos" do + it "is implemented" do + Machine.new.should respond_to(:acos) + end +end diff --git a/spec/math/acosh_spec.rb b/spec/math/acosh_spec.rb new file mode 100644 index 0000000..240f8e7 --- /dev/null +++ b/spec/math/acosh_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:acosh" do + it "is implemented" do + Machine.new.should respond_to(:acosh) + end +end diff --git a/spec/math/add_spec.rb b/spec/math/add_spec.rb new file mode 100644 index 0000000..ae776f7 --- /dev/null +++ b/spec/math/add_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:add" do + it "is implemented" do + Machine.new.should respond_to(:add, :+) + end +end diff --git a/spec/math/asin_spec.rb b/spec/math/asin_spec.rb new file mode 100644 index 0000000..8ea606e --- /dev/null +++ b/spec/math/asin_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:asin" do + it "is implemented" do + Machine.new.should respond_to(:asin) + end +end diff --git a/spec/math/asinh_spec.rb b/spec/math/asinh_spec.rb new file mode 100644 index 0000000..c4888ad --- /dev/null +++ b/spec/math/asinh_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:asinh" do + it "is implemented" do + Machine.new.should respond_to(:asinh) + end +end diff --git a/spec/math/atan2_spec.rb b/spec/math/atan2_spec.rb new file mode 100644 index 0000000..e304f79 --- /dev/null +++ b/spec/math/atan2_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:atan2" do + it "is implemented" do + Machine.new.should respond_to(:atan2) + end +end diff --git a/spec/math/atan_spec.rb b/spec/math/atan_spec.rb new file mode 100644 index 0000000..15864ae --- /dev/null +++ b/spec/math/atan_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:atan" do + it "is implemented" do + Machine.new.should respond_to(:atan) + end +end diff --git a/spec/math/atanh_spec.rb b/spec/math/atanh_spec.rb new file mode 100644 index 0000000..7733adc --- /dev/null +++ b/spec/math/atanh_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:atanh" do + it "is implemented" do + Machine.new.should respond_to(:atanh) + end +end diff --git a/spec/math/cb_spec.rb b/spec/math/cb_spec.rb new file mode 100644 index 0000000..8dd612b --- /dev/null +++ b/spec/math/cb_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:cb" do + it "is implemented" do + Machine.new.should respond_to(:cb) + end +end diff --git a/spec/math/cbrt_spec.rb b/spec/math/cbrt_spec.rb new file mode 100644 index 0000000..69eaa28 --- /dev/null +++ b/spec/math/cbrt_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:cbrt" do + it "is implemented" do + Machine.new.should respond_to(:cbrt) + end +end diff --git a/spec/math/ceil_spec.rb b/spec/math/ceil_spec.rb new file mode 100644 index 0000000..fa76f02 --- /dev/null +++ b/spec/math/ceil_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:ceil" do + it "is implemented" do + Machine.new.should respond_to(:ceil) + end +end diff --git a/spec/math/cos_spec.rb b/spec/math/cos_spec.rb new file mode 100644 index 0000000..155436d --- /dev/null +++ b/spec/math/cos_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:cos" do + it "is implemented" do + Machine.new.should respond_to(:cos) + end +end diff --git a/spec/math/cosh_spec.rb b/spec/math/cosh_spec.rb new file mode 100644 index 0000000..2010c72 --- /dev/null +++ b/spec/math/cosh_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:cosh" do + it "is implemented" do + Machine.new.should respond_to(:cosh) + end +end diff --git a/spec/math/dec_spec.rb b/spec/math/dec_spec.rb new file mode 100644 index 0000000..3476b1d --- /dev/null +++ b/spec/math/dec_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:dec" do + it "is implemented" do + Machine.new.should respond_to(:dec) + end +end diff --git a/spec/math/div_spec.rb b/spec/math/div_spec.rb new file mode 100644 index 0000000..22ff807 --- /dev/null +++ b/spec/math/div_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:div" do + it "is implemented" do + Machine.new.should respond_to(:div, :'/') + end +end diff --git a/spec/math/exp_spec.rb b/spec/math/exp_spec.rb new file mode 100644 index 0000000..916f324 --- /dev/null +++ b/spec/math/exp_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:exp" do + it "is implemented" do + Machine.new.should respond_to(:exp) + end +end diff --git a/spec/math/expm1_spec.rb b/spec/math/expm1_spec.rb new file mode 100644 index 0000000..35deeb9 --- /dev/null +++ b/spec/math/expm1_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:expm1" do + it "is implemented" do + Machine.new.should respond_to(:expm1) + end +end diff --git a/spec/math/fact_spec.rb b/spec/math/fact_spec.rb new file mode 100644 index 0000000..4a2056a --- /dev/null +++ b/spec/math/fact_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:fact" do + it "is implemented" do + Machine.new.should respond_to(:fact) + end +end diff --git a/spec/math/fib_spec.rb b/spec/math/fib_spec.rb new file mode 100644 index 0000000..ed270c2 --- /dev/null +++ b/spec/math/fib_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:fib" do + it "is implemented" do + Machine.new.should respond_to(:fib) + end +end diff --git a/spec/math/floor_spec.rb b/spec/math/floor_spec.rb new file mode 100644 index 0000000..5a4f286 --- /dev/null +++ b/spec/math/floor_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:floor" do + it "is implemented" do + Machine.new.should respond_to(:floor) + end +end diff --git a/spec/math/gcd_spec.rb b/spec/math/gcd_spec.rb new file mode 100644 index 0000000..d10e17d --- /dev/null +++ b/spec/math/gcd_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:gcd" do + it "is implemented" do + Machine.new.should respond_to(:gcd) + end +end diff --git a/spec/math/hypot_spec.rb b/spec/math/hypot_spec.rb new file mode 100644 index 0000000..7b60490 --- /dev/null +++ b/spec/math/hypot_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:hypot" do + it "is implemented" do + Machine.new.should respond_to(:hypot) + end +end diff --git a/spec/math/inc_spec.rb b/spec/math/inc_spec.rb new file mode 100644 index 0000000..1a2ff77 --- /dev/null +++ b/spec/math/inc_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:inc" do + it "is implemented" do + Machine.new.should respond_to(:inc) + end +end diff --git a/spec/math/lcm_spec.rb b/spec/math/lcm_spec.rb new file mode 100644 index 0000000..3a3bdb3 --- /dev/null +++ b/spec/math/lcm_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:lcm" do + it "is implemented" do + Machine.new.should respond_to(:lcm) + end +end diff --git a/spec/math/log10_spec.rb b/spec/math/log10_spec.rb new file mode 100644 index 0000000..3d0a226 --- /dev/null +++ b/spec/math/log10_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:log10" do + it "is implemented" do + Machine.new.should respond_to(:log10) + end +end diff --git a/spec/math/log1p_spec.rb b/spec/math/log1p_spec.rb new file mode 100644 index 0000000..dc48105 --- /dev/null +++ b/spec/math/log1p_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:log1p" do + it "is implemented" do + Machine.new.should respond_to(:log1p) + end +end diff --git a/spec/math/log2_spec.rb b/spec/math/log2_spec.rb new file mode 100644 index 0000000..1ba932c --- /dev/null +++ b/spec/math/log2_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:log2" do + it "is implemented" do + Machine.new.should respond_to(:log2) + end +end diff --git a/spec/math/log_spec.rb b/spec/math/log_spec.rb new file mode 100644 index 0000000..505daac --- /dev/null +++ b/spec/math/log_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:log" do + it "is implemented" do + Machine.new.should respond_to(:log) + end +end diff --git a/spec/math/mod_spec.rb b/spec/math/mod_spec.rb new file mode 100644 index 0000000..88ddbb3 --- /dev/null +++ b/spec/math/mod_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:mod" do + it "is implemented" do + Machine.new.should respond_to(:mod) + end +end diff --git a/spec/math/mul_spec.rb b/spec/math/mul_spec.rb new file mode 100644 index 0000000..d79742a --- /dev/null +++ b/spec/math/mul_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:mul" do + it "is implemented" do + Machine.new.should respond_to(:mul, :*) + end +end diff --git a/spec/math/neg_spec.rb b/spec/math/neg_spec.rb new file mode 100644 index 0000000..3326fc8 --- /dev/null +++ b/spec/math/neg_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:neg" do + it "is implemented" do + Machine.new.should respond_to(:neg) + end +end diff --git a/spec/math/pi_spec.rb b/spec/math/pi_spec.rb new file mode 100644 index 0000000..122e8d3 --- /dev/null +++ b/spec/math/pi_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:pi" do + it "is implemented" do + Machine.new.should respond_to(:pi) + end +end diff --git a/spec/math/pow_spec.rb b/spec/math/pow_spec.rb new file mode 100644 index 0000000..27be987 --- /dev/null +++ b/spec/math/pow_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:pow" do + it "is implemented" do + Machine.new.should respond_to(:pow) + end +end diff --git a/spec/math/rand_spec.rb b/spec/math/rand_spec.rb new file mode 100644 index 0000000..058d254 --- /dev/null +++ b/spec/math/rand_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:rand" do + it "is implemented" do + Machine.new.should respond_to(:rand) + end +end diff --git a/spec/math/rem_spec.rb b/spec/math/rem_spec.rb new file mode 100644 index 0000000..37663bd --- /dev/null +++ b/spec/math/rem_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:rem" do + it "is implemented" do + Machine.new.should respond_to(:rem) + end +end diff --git a/spec/math/round_spec.rb b/spec/math/round_spec.rb new file mode 100644 index 0000000..c5c232b --- /dev/null +++ b/spec/math/round_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:round" do + it "is implemented" do + Machine.new.should respond_to(:round) + end +end diff --git a/spec/math/sign_spec.rb b/spec/math/sign_spec.rb new file mode 100644 index 0000000..9f96ea1 --- /dev/null +++ b/spec/math/sign_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:sign" do + it "is implemented" do + Machine.new.should respond_to(:sign) + end +end diff --git a/spec/math/sin_spec.rb b/spec/math/sin_spec.rb new file mode 100644 index 0000000..30557fa --- /dev/null +++ b/spec/math/sin_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:sin" do + it "is implemented" do + Machine.new.should respond_to(:sin) + end +end diff --git a/spec/math/sinh_spec.rb b/spec/math/sinh_spec.rb new file mode 100644 index 0000000..f1d45b9 --- /dev/null +++ b/spec/math/sinh_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:sinh" do + it "is implemented" do + Machine.new.should respond_to(:sinh) + end +end diff --git a/spec/math/sq_spec.rb b/spec/math/sq_spec.rb new file mode 100644 index 0000000..60d3acd --- /dev/null +++ b/spec/math/sq_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:sq" do + it "is implemented" do + Machine.new.should respond_to(:sq) + end +end diff --git a/spec/math/sqrt_spec.rb b/spec/math/sqrt_spec.rb new file mode 100644 index 0000000..fbd9347 --- /dev/null +++ b/spec/math/sqrt_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:sqrt" do + it "is implemented" do + Machine.new.should respond_to(:sqrt) + end +end diff --git a/spec/math/sub_spec.rb b/spec/math/sub_spec.rb new file mode 100644 index 0000000..119e164 --- /dev/null +++ b/spec/math/sub_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:sub" do + it "is implemented" do + Machine.new.should respond_to(:sub, :-) + end +end diff --git a/spec/math/tan_spec.rb b/spec/math/tan_spec.rb new file mode 100644 index 0000000..5f6ca23 --- /dev/null +++ b/spec/math/tan_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:tan" do + it "is implemented" do + Machine.new.should respond_to(:tan) + end +end diff --git a/spec/math/tanh_spec.rb b/spec/math/tanh_spec.rb new file mode 100644 index 0000000..1513dfe --- /dev/null +++ b/spec/math/tanh_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe "math:tanh" do + it "is implemented" do + Machine.new.should respond_to(:tanh) + end +end
trith/trith
55b0cde10fb37962a929119c42d2e1cc158f7c84
Added @see annotations for all required gems.
diff --git a/lib/trith.rb b/lib/trith.rb index 15b9341..8298414 100644 --- a/lib/trith.rb +++ b/lib/trith.rb @@ -1,26 +1,31 @@ require 'bigdecimal' require 'rational' require 'digest/sha1' # @see http://rubygems.org/gems/backports require 'backports/1.9.1' if RUBY_VERSION < '1.9.1' require 'backports/basic_object' if RUBY_VERSION < '1.9.1' +# @see http://rubygems.org/gems/promise +require 'future' + +# @see http://rubygems.org/gems/sxp +require 'sxp' + +# @see http://rubygems.org/gems/rdf require 'rdf' require 'rdf/ntriples' require 'rdf/nquads' -require 'sxp' -require 'future' module Trith include RDF autoload :Cache, 'trith/cache' autoload :Compiler, 'trith/compiler' autoload :Core, 'trith/core' autoload :Function, 'trith/function' autoload :Machine, 'trith/machine' autoload :Reader, 'trith/reader' autoload :Shell, 'trith/shell' autoload :VERSION, 'trith/version' end
trith/trith
c692fe139458659d5f46245f0ba945f18479375e
Ensured that the BasicObject and Promise/Future classes are always available.
diff --git a/lib/trith.rb b/lib/trith.rb index bfb7c93..15b9341 100644 --- a/lib/trith.rb +++ b/lib/trith.rb @@ -1,22 +1,26 @@ require 'bigdecimal' require 'rational' require 'digest/sha1' -require 'backports/1.9.1' if RUBY_VERSION < '1.9.1' + +# @see http://rubygems.org/gems/backports +require 'backports/1.9.1' if RUBY_VERSION < '1.9.1' +require 'backports/basic_object' if RUBY_VERSION < '1.9.1' require 'rdf' require 'rdf/ntriples' require 'rdf/nquads' require 'sxp' +require 'future' module Trith include RDF autoload :Cache, 'trith/cache' autoload :Compiler, 'trith/compiler' autoload :Core, 'trith/core' autoload :Function, 'trith/function' autoload :Machine, 'trith/machine' autoload :Reader, 'trith/reader' autoload :Shell, 'trith/shell' autoload :VERSION, 'trith/version' end
trith/trith
b7876def35e1fc3d432852bf89276c9210ccf450
Reordered the gem dependencies (RubyGems.org displays them in reverse order).
diff --git a/.gemspec b/.gemspec index ee666f6..b78fc94 100644 --- a/.gemspec +++ b/.gemspec @@ -1,40 +1,40 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.author = 'Arto Bendiken' gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.1' gem.requirements = [] - gem.add_development_dependency 'buildr' , '>= 1.3.5' - gem.add_development_dependency 'rspec', '>= 1.3.0' - gem.add_development_dependency 'yard' , '>= 0.5.6' - gem.add_runtime_dependency 'backports', '>= 1.17.1' - gem.add_runtime_dependency 'promise', '~> 0.1.1' - gem.add_runtime_dependency 'rdf', '~> 0.2.0' gem.add_runtime_dependency 'sxp', '~> 0.0.4' + gem.add_runtime_dependency 'rdf', '~> 0.2.0' + gem.add_runtime_dependency 'promise', '~> 0.1.1' + gem.add_runtime_dependency 'backports', '>= 1.17.1' + gem.add_development_dependency 'yard' , '>= 0.5.6' + gem.add_development_dependency 'rspec', '>= 1.3.0' + gem.add_development_dependency 'buildr' , '>= 1.3.5' gem.post_install_message = nil end
trith/trith
35824e0d0f351248d71e044d2f6df6f39a91e06d
Bumped the version to 0.0.4.
diff --git a/VERSION b/VERSION index bcab45a..81340c7 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.0.3 +0.0.4 diff --git a/lib/trith/version.rb b/lib/trith/version.rb index dad8d78..a1ffe63 100644 --- a/lib/trith/version.rb +++ b/lib/trith/version.rb @@ -1,23 +1,22 @@ module Trith module VERSION MAJOR = 0 MINOR = 0 - TINY = 3 + TINY = 4 EXTRA = nil - STRING = [MAJOR, MINOR, TINY].join('.') - STRING << ".#{EXTRA}" if EXTRA + STRING = [MAJOR, MINOR, TINY, EXTRA].compact.join('.') ## # @return [String] def self.to_s() STRING end ## # @return [String] def self.to_str() STRING end ## # @return [Array(Integer, Integer, Integer)] def self.to_a() [MAJOR, MINOR, TINY] end end end diff --git a/spec/version_spec.rb b/spec/version_spec.rb new file mode 100644 index 0000000..5bc1bff --- /dev/null +++ b/spec/version_spec.rb @@ -0,0 +1,7 @@ +require File.join(File.dirname(__FILE__), 'spec_helper') + +describe 'Trith::VERSION' do + it "should match the VERSION file" do + Trith::VERSION.to_s.should == File.read(File.join(File.dirname(__FILE__), '..', 'VERSION')).chomp + end +end
trith/trith
961b6868b7c04392bbc13de6c90e99883b67b983
Changed the gemspec to reference the mailing list as the e-mail address.
diff --git a/.gemspec b/.gemspec index 7558779..ee666f6 100644 --- a/.gemspec +++ b/.gemspec @@ -1,40 +1,40 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' - gem.authors = ['Arto Bendiken'] - gem.email = '[email protected]' + gem.author = 'Arto Bendiken' + gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.1' gem.requirements = [] gem.add_development_dependency 'buildr' , '>= 1.3.5' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'yard' , '>= 0.5.6' gem.add_runtime_dependency 'backports', '>= 1.17.1' gem.add_runtime_dependency 'promise', '~> 0.1.1' gem.add_runtime_dependency 'rdf', '~> 0.2.0' gem.add_runtime_dependency 'sxp', '~> 0.0.4' gem.post_install_message = nil end
trith/trith
6320fb204ae25def136a2978cd1a67a0ecc1641d
Changed the absolute minimum Ruby version to 1.8.1, the first version with enumerators.
diff --git a/.gemspec b/.gemspec index f3690e5..7558779 100644 --- a/.gemspec +++ b/.gemspec @@ -1,40 +1,40 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.authors = ['Arto Bendiken'] gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false - gem.required_ruby_version = '>= 1.8.2' + gem.required_ruby_version = '>= 1.8.1' gem.requirements = [] gem.add_development_dependency 'buildr' , '>= 1.3.5' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'yard' , '>= 0.5.6' gem.add_runtime_dependency 'backports', '>= 1.17.1' gem.add_runtime_dependency 'promise', '~> 0.1.1' gem.add_runtime_dependency 'rdf', '~> 0.2.0' gem.add_runtime_dependency 'sxp', '~> 0.0.4' gem.post_install_message = nil end
trith/trith
5a9c983476cc9bbf8cc8b7d5cbb178432b3c09d1
Bumped the RDF.rb dependency.
diff --git a/.gemspec b/.gemspec index 08d4d01..f3690e5 100644 --- a/.gemspec +++ b/.gemspec @@ -1,40 +1,40 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.authors = ['Arto Bendiken'] gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.2' gem.requirements = [] gem.add_development_dependency 'buildr' , '>= 1.3.5' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'yard' , '>= 0.5.6' gem.add_runtime_dependency 'backports', '>= 1.17.1' gem.add_runtime_dependency 'promise', '~> 0.1.1' - gem.add_runtime_dependency 'rdf', '~> 0.1.10' + gem.add_runtime_dependency 'rdf', '~> 0.2.0' gem.add_runtime_dependency 'sxp', '~> 0.0.4' gem.post_install_message = nil end diff --git a/README.md b/README.md index 93888ca..9a3b905 100644 --- a/README.md +++ b/README.md @@ -1,338 +1,338 @@ Trith: Recombinant Programming ============================== Trith is an experimental [concatenative][concat.org] programming language founded on the [unholy][lispers.org] trinity of [Forth][], [Lisp][] and [RDF][] triples. * <http://trith.org/> * <http://github.com/trith/trith> Description ----------- Trith is a stack-based, concatenative, dynamically-typed functional programming language with a homoiconic program representation. * [Stack-based][stack-oriented] means that instead of having named parameters, Trith functions operate on an implicit data structure called the _operand stack_. Trith functions can be thought of in terms of popping and pushing operands from/onto this stack, or equivalently in purely functional terms as unary functions that map from one stack to another. * [Concatenative][concatenative] means that the concatenation of any two Trith functions also denotes the [composition][] of those functions. * [Dynamically typed][type system] means that operands to Trith functions are type-checked dynamically at runtime. * [Homoiconic][homoiconic] means that in Trith there is no difference between code and data. You can manipulate and construct code at runtime as easily as you would manipulate any other data structure, enabling powerful metaprogramming facilities. Trith programs are simply nested lists of operators and operands, and can be represented externally either as [S-expressions][S-expression] or as [RDF][] triples. Trith is inspired and influenced by experience with [Forth][], [Lisp][] and [Scheme][] in general, and the concatenative languages [Joy][], [XY][], [Factor][] and [Cat][] in particular. Introduction ------------ The Trith implementation currently consists of a virtual machine, interpreter, and compiler toolchain written in Ruby and an in-the-works runtime targeting the [JVM][]. You can use the Trith shell `3sh` to explore Trith interactively: $ 3sh >> "Hello, world!" print Hello, world! For example, here's how you would start with two prime numbers and end up with the correct answer to the ultimate question of life, the universe, and everything: $ 3sh >> 3 7 swap dup + * => [42] : [] In the above `3sh` examples, `>>` indicates lines that you type, and `=>` indicates the result from the shell. After each input line is evaluated, the shell will show you the current state of the Trith virtual machine's data stack and code queue. Thus in our previous example, the `[42]` on the left-hand side shows that the machine's stack contains a single operand, the number 42. The `[]` on the right-hand side shows that the machine's code queue is empty, which is generally the case after all input has been successfully evaluated. Let's run through the above example one more time using the `--debug` option to `3sh`, which enables the tracing of each queue reduction step in the virtual machine: $ 3sh --debug >> 3 7 swap dup + * .. [] : [3 7 swap dup + *] .. [3] : [7 swap dup + *] .. [3 7] : [swap dup + *] .. [7 3] : [dup + *] .. [7 3 3] : [+ *] .. [7 6] : [*] => [42] : [] As you can see, the virtual machine starts execution with an empty operand stack on the left-hand side and with all input placed onto the operator queue on the right-hand side. When input operands such as numbers are encountered on the queue, they are simply pushed onto the stack, which grows from left to right. When an operator such as the multiplication operator `*` is encountered on the queue, it is executed. Operators pop operands from the stack and then push their result(s) back onto the stack. When fooling around in the Trith shell, two useful operators to know are `clear`, which clears the stack, and `halt`, which clears the queue (thus halting execution). You can also use `reset` which does both in one step, returning you to a guaranteed clean slate. To get a listing of all operators supported in the current release, enter the `?` metacommand in the Trith shell. Linked Code ----------- All Trith operators are identified by URIs, meaning that Trith code can be straightforwardly represented as [Linked Data][]. Here's an example of the `abs` operator defined metacircularly using the Turtle serialization format for RDF data: @base <http://trith.org/core/> . @prefix trith: <http://trith.org/lang/> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . <abs> a trith:Function ; rdfs:label "abs" ; rdfs:comment "Returns the absolute value of a number."@en ; trith:arity 1 ; trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . This function description comprises a total of 21 triples. The entire Trith core library currently weighs in at about a kilotriple (1,000 triples), with all but a handful of primitive (irreducible) operators having a metacircular definition. See `etc/trith-core.ttl` for the RDF definitions of Trith core operators. Reference --------- ### Sequences Trith has a rich set of sequence operators that will be instantly familiar to programmers coming from functional programming languages such as Scheme, Clojure or Haskell: >> 10 iota => [[0 1 2 3 4 5 6 7 8 9]] : [] >> dup seq? . true >> dup empty? . false >> dup length . 10 >> [dup mul] map => [[0 1 4 9 16 25 36 49 64 81]] : [] >> dup first . 0 >> dup fifth . 16 >> dup 7 nth . 49 >> dup last . 81 >> dup 0 [+] foldl . 285 >> rest => [[1 4 9 16 25 36 49 64 81]] : [] >> dup 1 [*] foldl . 131681894400 >> reverse => [[81 64 49 36 25 16 9 4 1]] : [] ### Strings Strings are simply sequences of characters (Unicode code points), meaning that you can make use of any of the normal sequence operators on strings as well: >> : hello "Hello," " world!" concat ; >> hello seq? . true >> hello text? . true >> hello empty? . false >> hello length . 13 >> hello first . H >> hello rest . ello, world! >> hello reverse . !dlrow ,olleH Scripting --------- The canonical "Hello, world!" script is found in `doc/examples/hello.3th`: #!/usr/bin/env 3vm "Hello, world!" print Any command-line arguments passed to 3VM scripts form the initial stack of the virtual machine. The arguments are placed on the stack in their original unparsed string form. You can print out the contents of the initial stack like so: #!/usr/bin/env 3vm stack print Here's an example of how you would interpret all given command-line arguments as numbers and then sum them up and print out the result: #!/usr/bin/env 3vm stack [num] map 0 [+] foldl print Embedding --------- ### Embedding Trith in Ruby require 'trith' # Let's start with the obligatory "Hello, world!" example: Trith::Machine.run do push "Hello, world!" print end # There are several equivalent ways to execute Trith code: Trith::Machine.run { push(6, 7).mul } #=> 42 Trith::Machine.run [6, 7] { mul } #=> 42 Trith::Machine.run [6, 7, :mul] #=> 42 # Operators in Ruby blocks can be chained together: Trith::Machine.run { push(2).dup.dup.mul.pow } #=> 16 # If you require more control, instantiate a machine manually: vm = Trith::Machine.new vm.define!(:square) { dup.mul } vm.push(10).square.peek #=> 100 # You can also define operators when constructing a machine: vm = Trith::Machine.new(data = [], code = [], { :hello => proc { push("Hello, world!").print }, }) # Should you want to use any Trith functions from Ruby, it's easy enough # to encapsulate a virtual machine inside a Ruby method: def square(n) Trith::Machine.run [n] { dup.mul } end square(10) #=> 100 ### Embedding Trith in JVM-based languages The [JVM][] runtime for Trith is a work in progress. See `src/java` for the runtime's source code and current status. Dependencies ------------ * [Ruby](http://ruby-lang.org/) (>= 1.9.1) or (>= 1.8.2 with [Backports](http://rubygems.org/gems/backports)) -* [RDF.rb](http://rubygems.org/gems/rdf) (>= 0.1.10) +* [RDF.rb](http://rubygems.org/gems/rdf) (>= 0.2.0) * [SXP](http://rubygems.org/gems/sxp) (>= 0.0.4) * [Promise](http://rubygems.org/gems/promise) (>= 0.1.1) Installation ------------ The recommended installation method is via [RubyGems](http://rubygems.org/). To install the latest official release of the `trith` gem, do one of the following: $ [sudo] gem install trith # Ruby 1.8.x/1.9.x $ [sudo] gem1.9 install trith # Ruby 1.9 with MacPorts $ [sudo] jruby --1.9 -S gem install trith # JRuby 1.5+ Once Trith is installed, you will have four new programs available: * `3sh`, aka "trish", is the Trith interactive shell and interpreter. * `3vm`, aka "trivium", is the Trith virtual machine runtime. * `3cc`, aka "tricksy", is the Trith compiler. * `3th`, aka "trith", is the Trith package manager. Note that as of the current release, only the first two do anything much as yet. Environment ----------- The following are the default settings for environment variables that let you customize how Trith works: $ export TRITH_HOME=~/.trith $ export TRITH_CACHE=$TRITH_HOME/cache $ export TRITH_TERM=$TERM Download -------- To get a local working copy of the development repository, do: $ git clone git://github.com/trith/trith.git Alternatively, you can download the latest development version as a tarball as follows: $ wget http://github.com/trith/trith/tarball/master Mailing List ------------ * <http://groups.google.com/group/trith> Authors ------- * [Arto Bendiken](mailto:[email protected]) - <http://ar.to/> License ------- Trith is free and unencumbered public domain software. For more information, see <http://unlicense.org/> or the accompanying UNLICENSE file. [stack-oriented]: http://en.wikipedia.org/wiki/Stack-oriented_programming_language [concatenative]: http://en.wikipedia.org/wiki/Concatenative_programming_language [composition]: http://en.wikipedia.org/wiki/Function_composition [type system]: http://en.wikipedia.org/wiki/Type_system#Dynamic_typing [homoiconic]: http://en.wikipedia.org/wiki/Homoiconicity [S-expression]: http://en.wikipedia.org/wiki/S-expression [RDF]: http://en.wikipedia.org/wiki/Resource_Description_Framework [JVM]: http://en.wikipedia.org/wiki/Java_Virtual_Machine [Lisp]: http://en.wikipedia.org/wiki/Lisp_(programming_language) [Scheme]: http://en.wikipedia.org/wiki/Scheme_(programming_language) [Forth]: http://en.wikipedia.org/wiki/Forth_(programming_language) [Factor]: http://en.wikipedia.org/wiki/Factor_(programming_language) [Joy]: http://en.wikipedia.org/wiki/Joy_(programming_language) [Cat]: http://en.wikipedia.org/wiki/Cat_(programming_language) [XY]: http://www.nsl.com/k/xy/xy.htm [Linked Data]: http://linkeddata.org/ [lispers.org]: http://lispers.org/ [concat.org]: http://concatenative.org/wiki/view/Concatenative%20language
trith/trith
23e04fd655a5e55e624165148b3a6d39590cb8d8
Bumped the YARD development dependency.
diff --git a/.gemspec b/.gemspec index cc0075f..08d4d01 100644 --- a/.gemspec +++ b/.gemspec @@ -1,40 +1,40 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.authors = ['Arto Bendiken'] gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.2' gem.requirements = [] gem.add_development_dependency 'buildr' , '>= 1.3.5' gem.add_development_dependency 'rspec', '>= 1.3.0' - gem.add_development_dependency 'yard' , '>= 0.5.5' + gem.add_development_dependency 'yard' , '>= 0.5.6' gem.add_runtime_dependency 'backports', '>= 1.17.1' gem.add_runtime_dependency 'promise', '~> 0.1.1' gem.add_runtime_dependency 'rdf', '~> 0.1.10' gem.add_runtime_dependency 'sxp', '~> 0.0.4' gem.post_install_message = nil end
trith/trith
afffb62f9ae780190468dff94cff1aa0902362d4
Added a dependency on the Backports gem.
diff --git a/.gemspec b/.gemspec index e4c9ed7..cc0075f 100644 --- a/.gemspec +++ b/.gemspec @@ -1,39 +1,40 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.authors = ['Arto Bendiken'] gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false - gem.required_ruby_version = '>= 1.9.1' + gem.required_ruby_version = '>= 1.8.2' gem.requirements = [] gem.add_development_dependency 'buildr' , '>= 1.3.5' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'yard' , '>= 0.5.5' + gem.add_runtime_dependency 'backports', '>= 1.17.1' gem.add_runtime_dependency 'promise', '~> 0.1.1' gem.add_runtime_dependency 'rdf', '~> 0.1.10' gem.add_runtime_dependency 'sxp', '~> 0.0.4' gem.post_install_message = nil end diff --git a/README.md b/README.md index 7d0e335..93888ca 100644 --- a/README.md +++ b/README.md @@ -1,338 +1,338 @@ Trith: Recombinant Programming ============================== Trith is an experimental [concatenative][concat.org] programming language founded on the [unholy][lispers.org] trinity of [Forth][], [Lisp][] and [RDF][] triples. * <http://trith.org/> * <http://github.com/trith/trith> Description ----------- Trith is a stack-based, concatenative, dynamically-typed functional programming language with a homoiconic program representation. * [Stack-based][stack-oriented] means that instead of having named parameters, Trith functions operate on an implicit data structure called the _operand stack_. Trith functions can be thought of in terms of popping and pushing operands from/onto this stack, or equivalently in purely functional terms as unary functions that map from one stack to another. * [Concatenative][concatenative] means that the concatenation of any two Trith functions also denotes the [composition][] of those functions. * [Dynamically typed][type system] means that operands to Trith functions are type-checked dynamically at runtime. * [Homoiconic][homoiconic] means that in Trith there is no difference between code and data. You can manipulate and construct code at runtime as easily as you would manipulate any other data structure, enabling powerful metaprogramming facilities. Trith programs are simply nested lists of operators and operands, and can be represented externally either as [S-expressions][S-expression] or as [RDF][] triples. Trith is inspired and influenced by experience with [Forth][], [Lisp][] and [Scheme][] in general, and the concatenative languages [Joy][], [XY][], [Factor][] and [Cat][] in particular. Introduction ------------ The Trith implementation currently consists of a virtual machine, interpreter, and compiler toolchain written in Ruby and an in-the-works runtime targeting the [JVM][]. You can use the Trith shell `3sh` to explore Trith interactively: $ 3sh >> "Hello, world!" print Hello, world! For example, here's how you would start with two prime numbers and end up with the correct answer to the ultimate question of life, the universe, and everything: $ 3sh >> 3 7 swap dup + * => [42] : [] In the above `3sh` examples, `>>` indicates lines that you type, and `=>` indicates the result from the shell. After each input line is evaluated, the shell will show you the current state of the Trith virtual machine's data stack and code queue. Thus in our previous example, the `[42]` on the left-hand side shows that the machine's stack contains a single operand, the number 42. The `[]` on the right-hand side shows that the machine's code queue is empty, which is generally the case after all input has been successfully evaluated. Let's run through the above example one more time using the `--debug` option to `3sh`, which enables the tracing of each queue reduction step in the virtual machine: $ 3sh --debug >> 3 7 swap dup + * .. [] : [3 7 swap dup + *] .. [3] : [7 swap dup + *] .. [3 7] : [swap dup + *] .. [7 3] : [dup + *] .. [7 3 3] : [+ *] .. [7 6] : [*] => [42] : [] As you can see, the virtual machine starts execution with an empty operand stack on the left-hand side and with all input placed onto the operator queue on the right-hand side. When input operands such as numbers are encountered on the queue, they are simply pushed onto the stack, which grows from left to right. When an operator such as the multiplication operator `*` is encountered on the queue, it is executed. Operators pop operands from the stack and then push their result(s) back onto the stack. When fooling around in the Trith shell, two useful operators to know are `clear`, which clears the stack, and `halt`, which clears the queue (thus halting execution). You can also use `reset` which does both in one step, returning you to a guaranteed clean slate. To get a listing of all operators supported in the current release, enter the `?` metacommand in the Trith shell. Linked Code ----------- All Trith operators are identified by URIs, meaning that Trith code can be straightforwardly represented as [Linked Data][]. Here's an example of the `abs` operator defined metacircularly using the Turtle serialization format for RDF data: @base <http://trith.org/core/> . @prefix trith: <http://trith.org/lang/> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . <abs> a trith:Function ; rdfs:label "abs" ; rdfs:comment "Returns the absolute value of a number."@en ; trith:arity 1 ; trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . This function description comprises a total of 21 triples. The entire Trith core library currently weighs in at about a kilotriple (1,000 triples), with all but a handful of primitive (irreducible) operators having a metacircular definition. See `etc/trith-core.ttl` for the RDF definitions of Trith core operators. Reference --------- ### Sequences Trith has a rich set of sequence operators that will be instantly familiar to programmers coming from functional programming languages such as Scheme, Clojure or Haskell: >> 10 iota => [[0 1 2 3 4 5 6 7 8 9]] : [] >> dup seq? . true >> dup empty? . false >> dup length . 10 >> [dup mul] map => [[0 1 4 9 16 25 36 49 64 81]] : [] >> dup first . 0 >> dup fifth . 16 >> dup 7 nth . 49 >> dup last . 81 >> dup 0 [+] foldl . 285 >> rest => [[1 4 9 16 25 36 49 64 81]] : [] >> dup 1 [*] foldl . 131681894400 >> reverse => [[81 64 49 36 25 16 9 4 1]] : [] ### Strings Strings are simply sequences of characters (Unicode code points), meaning that you can make use of any of the normal sequence operators on strings as well: >> : hello "Hello," " world!" concat ; >> hello seq? . true >> hello text? . true >> hello empty? . false >> hello length . 13 >> hello first . H >> hello rest . ello, world! >> hello reverse . !dlrow ,olleH Scripting --------- The canonical "Hello, world!" script is found in `doc/examples/hello.3th`: #!/usr/bin/env 3vm "Hello, world!" print Any command-line arguments passed to 3VM scripts form the initial stack of the virtual machine. The arguments are placed on the stack in their original unparsed string form. You can print out the contents of the initial stack like so: #!/usr/bin/env 3vm stack print Here's an example of how you would interpret all given command-line arguments as numbers and then sum them up and print out the result: #!/usr/bin/env 3vm stack [num] map 0 [+] foldl print Embedding --------- ### Embedding Trith in Ruby require 'trith' # Let's start with the obligatory "Hello, world!" example: Trith::Machine.run do push "Hello, world!" print end # There are several equivalent ways to execute Trith code: Trith::Machine.run { push(6, 7).mul } #=> 42 Trith::Machine.run [6, 7] { mul } #=> 42 Trith::Machine.run [6, 7, :mul] #=> 42 # Operators in Ruby blocks can be chained together: Trith::Machine.run { push(2).dup.dup.mul.pow } #=> 16 # If you require more control, instantiate a machine manually: vm = Trith::Machine.new vm.define!(:square) { dup.mul } vm.push(10).square.peek #=> 100 # You can also define operators when constructing a machine: vm = Trith::Machine.new(data = [], code = [], { :hello => proc { push("Hello, world!").print }, }) # Should you want to use any Trith functions from Ruby, it's easy enough # to encapsulate a virtual machine inside a Ruby method: def square(n) Trith::Machine.run [n] { dup.mul } end square(10) #=> 100 ### Embedding Trith in JVM-based languages The [JVM][] runtime for Trith is a work in progress. See `src/java` for the runtime's source code and current status. Dependencies ------------ * [Ruby](http://ruby-lang.org/) (>= 1.9.1) or - [JRuby](http://jruby.org/) (>= 1.4.0) + (>= 1.8.2 with [Backports](http://rubygems.org/gems/backports)) * [RDF.rb](http://rubygems.org/gems/rdf) (>= 0.1.10) * [SXP](http://rubygems.org/gems/sxp) (>= 0.0.4) * [Promise](http://rubygems.org/gems/promise) (>= 0.1.1) Installation ------------ The recommended installation method is via [RubyGems](http://rubygems.org/). To install the latest official release of the `trith` gem, do one of the following: - $ [sudo] gem install trith # Ruby 1.9+ + $ [sudo] gem install trith # Ruby 1.8.x/1.9.x $ [sudo] gem1.9 install trith # Ruby 1.9 with MacPorts - $ [sudo] jruby --1.9 -S gem install trith # JRuby 1.4+ + $ [sudo] jruby --1.9 -S gem install trith # JRuby 1.5+ Once Trith is installed, you will have four new programs available: * `3sh`, aka "trish", is the Trith interactive shell and interpreter. * `3vm`, aka "trivium", is the Trith virtual machine runtime. * `3cc`, aka "tricksy", is the Trith compiler. * `3th`, aka "trith", is the Trith package manager. Note that as of the current release, only the first two do anything much as yet. Environment ----------- The following are the default settings for environment variables that let you customize how Trith works: $ export TRITH_HOME=~/.trith $ export TRITH_CACHE=$TRITH_HOME/cache $ export TRITH_TERM=$TERM Download -------- To get a local working copy of the development repository, do: $ git clone git://github.com/trith/trith.git Alternatively, you can download the latest development version as a tarball as follows: $ wget http://github.com/trith/trith/tarball/master Mailing List ------------ * <http://groups.google.com/group/trith> Authors ------- * [Arto Bendiken](mailto:[email protected]) - <http://ar.to/> License ------- Trith is free and unencumbered public domain software. For more information, see <http://unlicense.org/> or the accompanying UNLICENSE file. [stack-oriented]: http://en.wikipedia.org/wiki/Stack-oriented_programming_language [concatenative]: http://en.wikipedia.org/wiki/Concatenative_programming_language [composition]: http://en.wikipedia.org/wiki/Function_composition [type system]: http://en.wikipedia.org/wiki/Type_system#Dynamic_typing [homoiconic]: http://en.wikipedia.org/wiki/Homoiconicity [S-expression]: http://en.wikipedia.org/wiki/S-expression [RDF]: http://en.wikipedia.org/wiki/Resource_Description_Framework [JVM]: http://en.wikipedia.org/wiki/Java_Virtual_Machine [Lisp]: http://en.wikipedia.org/wiki/Lisp_(programming_language) [Scheme]: http://en.wikipedia.org/wiki/Scheme_(programming_language) [Forth]: http://en.wikipedia.org/wiki/Forth_(programming_language) [Factor]: http://en.wikipedia.org/wiki/Factor_(programming_language) [Joy]: http://en.wikipedia.org/wiki/Joy_(programming_language) [Cat]: http://en.wikipedia.org/wiki/Cat_(programming_language) [XY]: http://www.nsl.com/k/xy/xy.htm [Linked Data]: http://linkeddata.org/ [lispers.org]: http://lispers.org/ [concat.org]: http://concatenative.org/wiki/view/Concatenative%20language diff --git a/lib/trith.rb b/lib/trith.rb index 39fa387..bfb7c93 100644 --- a/lib/trith.rb +++ b/lib/trith.rb @@ -1,20 +1,22 @@ require 'bigdecimal' require 'rational' require 'digest/sha1' +require 'backports/1.9.1' if RUBY_VERSION < '1.9.1' + require 'rdf' require 'rdf/ntriples' require 'rdf/nquads' require 'sxp' module Trith include RDF autoload :Cache, 'trith/cache' autoload :Compiler, 'trith/compiler' autoload :Core, 'trith/core' autoload :Function, 'trith/function' autoload :Machine, 'trith/machine' autoload :Reader, 'trith/reader' autoload :Shell, 'trith/shell' autoload :VERSION, 'trith/version' end
trith/trith
8f6fd742eb04457ee66063e6a0d03cb17718df16
Bumped the Promise and SXP dependencies.
diff --git a/.gemspec b/.gemspec index 4fcdbed..e4c9ed7 100644 --- a/.gemspec +++ b/.gemspec @@ -1,39 +1,39 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.authors = ['Arto Bendiken'] gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.9.1' gem.requirements = [] - gem.add_development_dependency 'buildr' , '>= 1.3.5' - gem.add_development_dependency 'rspec', '>= 1.3.0' - gem.add_development_dependency 'yard' , '>= 0.5.5' - gem.add_runtime_dependency 'promise', '~> 0.1.0' - gem.add_runtime_dependency 'rdf', '~> 0.1.10' - gem.add_runtime_dependency 'sxp', '~> 0.0.3' + gem.add_development_dependency 'buildr' , '>= 1.3.5' + gem.add_development_dependency 'rspec', '>= 1.3.0' + gem.add_development_dependency 'yard' , '>= 0.5.5' + gem.add_runtime_dependency 'promise', '~> 0.1.1' + gem.add_runtime_dependency 'rdf', '~> 0.1.10' + gem.add_runtime_dependency 'sxp', '~> 0.0.4' gem.post_install_message = nil end diff --git a/README.md b/README.md index b93d47e..7d0e335 100644 --- a/README.md +++ b/README.md @@ -1,338 +1,338 @@ Trith: Recombinant Programming ============================== Trith is an experimental [concatenative][concat.org] programming language founded on the [unholy][lispers.org] trinity of [Forth][], [Lisp][] and [RDF][] triples. * <http://trith.org/> * <http://github.com/trith/trith> Description ----------- Trith is a stack-based, concatenative, dynamically-typed functional programming language with a homoiconic program representation. * [Stack-based][stack-oriented] means that instead of having named parameters, Trith functions operate on an implicit data structure called the _operand stack_. Trith functions can be thought of in terms of popping and pushing operands from/onto this stack, or equivalently in purely functional terms as unary functions that map from one stack to another. * [Concatenative][concatenative] means that the concatenation of any two Trith functions also denotes the [composition][] of those functions. * [Dynamically typed][type system] means that operands to Trith functions are type-checked dynamically at runtime. * [Homoiconic][homoiconic] means that in Trith there is no difference between code and data. You can manipulate and construct code at runtime as easily as you would manipulate any other data structure, enabling powerful metaprogramming facilities. Trith programs are simply nested lists of operators and operands, and can be represented externally either as [S-expressions][S-expression] or as [RDF][] triples. Trith is inspired and influenced by experience with [Forth][], [Lisp][] and [Scheme][] in general, and the concatenative languages [Joy][], [XY][], [Factor][] and [Cat][] in particular. Introduction ------------ The Trith implementation currently consists of a virtual machine, interpreter, and compiler toolchain written in Ruby and an in-the-works runtime targeting the [JVM][]. You can use the Trith shell `3sh` to explore Trith interactively: $ 3sh >> "Hello, world!" print Hello, world! For example, here's how you would start with two prime numbers and end up with the correct answer to the ultimate question of life, the universe, and everything: $ 3sh >> 3 7 swap dup + * => [42] : [] In the above `3sh` examples, `>>` indicates lines that you type, and `=>` indicates the result from the shell. After each input line is evaluated, the shell will show you the current state of the Trith virtual machine's data stack and code queue. Thus in our previous example, the `[42]` on the left-hand side shows that the machine's stack contains a single operand, the number 42. The `[]` on the right-hand side shows that the machine's code queue is empty, which is generally the case after all input has been successfully evaluated. Let's run through the above example one more time using the `--debug` option to `3sh`, which enables the tracing of each queue reduction step in the virtual machine: $ 3sh --debug >> 3 7 swap dup + * .. [] : [3 7 swap dup + *] .. [3] : [7 swap dup + *] .. [3 7] : [swap dup + *] .. [7 3] : [dup + *] .. [7 3 3] : [+ *] .. [7 6] : [*] => [42] : [] As you can see, the virtual machine starts execution with an empty operand stack on the left-hand side and with all input placed onto the operator queue on the right-hand side. When input operands such as numbers are encountered on the queue, they are simply pushed onto the stack, which grows from left to right. When an operator such as the multiplication operator `*` is encountered on the queue, it is executed. Operators pop operands from the stack and then push their result(s) back onto the stack. When fooling around in the Trith shell, two useful operators to know are `clear`, which clears the stack, and `halt`, which clears the queue (thus halting execution). You can also use `reset` which does both in one step, returning you to a guaranteed clean slate. To get a listing of all operators supported in the current release, enter the `?` metacommand in the Trith shell. Linked Code ----------- All Trith operators are identified by URIs, meaning that Trith code can be straightforwardly represented as [Linked Data][]. Here's an example of the `abs` operator defined metacircularly using the Turtle serialization format for RDF data: @base <http://trith.org/core/> . @prefix trith: <http://trith.org/lang/> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . <abs> a trith:Function ; rdfs:label "abs" ; rdfs:comment "Returns the absolute value of a number."@en ; trith:arity 1 ; trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . This function description comprises a total of 21 triples. The entire Trith core library currently weighs in at about a kilotriple (1,000 triples), with all but a handful of primitive (irreducible) operators having a metacircular definition. See `etc/trith-core.ttl` for the RDF definitions of Trith core operators. Reference --------- ### Sequences Trith has a rich set of sequence operators that will be instantly familiar to programmers coming from functional programming languages such as Scheme, Clojure or Haskell: >> 10 iota => [[0 1 2 3 4 5 6 7 8 9]] : [] >> dup seq? . true >> dup empty? . false >> dup length . 10 >> [dup mul] map => [[0 1 4 9 16 25 36 49 64 81]] : [] >> dup first . 0 >> dup fifth . 16 >> dup 7 nth . 49 >> dup last . 81 >> dup 0 [+] foldl . 285 >> rest => [[1 4 9 16 25 36 49 64 81]] : [] >> dup 1 [*] foldl . 131681894400 >> reverse => [[81 64 49 36 25 16 9 4 1]] : [] ### Strings Strings are simply sequences of characters (Unicode code points), meaning that you can make use of any of the normal sequence operators on strings as well: >> : hello "Hello," " world!" concat ; >> hello seq? . true >> hello text? . true >> hello empty? . false >> hello length . 13 >> hello first . H >> hello rest . ello, world! >> hello reverse . !dlrow ,olleH Scripting --------- The canonical "Hello, world!" script is found in `doc/examples/hello.3th`: #!/usr/bin/env 3vm "Hello, world!" print Any command-line arguments passed to 3VM scripts form the initial stack of the virtual machine. The arguments are placed on the stack in their original unparsed string form. You can print out the contents of the initial stack like so: #!/usr/bin/env 3vm stack print Here's an example of how you would interpret all given command-line arguments as numbers and then sum them up and print out the result: #!/usr/bin/env 3vm stack [num] map 0 [+] foldl print Embedding --------- ### Embedding Trith in Ruby require 'trith' # Let's start with the obligatory "Hello, world!" example: Trith::Machine.run do push "Hello, world!" print end # There are several equivalent ways to execute Trith code: Trith::Machine.run { push(6, 7).mul } #=> 42 Trith::Machine.run [6, 7] { mul } #=> 42 Trith::Machine.run [6, 7, :mul] #=> 42 # Operators in Ruby blocks can be chained together: Trith::Machine.run { push(2).dup.dup.mul.pow } #=> 16 # If you require more control, instantiate a machine manually: vm = Trith::Machine.new vm.define!(:square) { dup.mul } vm.push(10).square.peek #=> 100 # You can also define operators when constructing a machine: vm = Trith::Machine.new(data = [], code = [], { :hello => proc { push("Hello, world!").print }, }) # Should you want to use any Trith functions from Ruby, it's easy enough # to encapsulate a virtual machine inside a Ruby method: def square(n) Trith::Machine.run [n] { dup.mul } end square(10) #=> 100 ### Embedding Trith in JVM-based languages The [JVM][] runtime for Trith is a work in progress. See `src/java` for the runtime's source code and current status. Dependencies ------------ * [Ruby](http://ruby-lang.org/) (>= 1.9.1) or [JRuby](http://jruby.org/) (>= 1.4.0) * [RDF.rb](http://rubygems.org/gems/rdf) (>= 0.1.10) -* [SXP](http://rubygems.org/gems/sxp) (>= 0.0.3) -* [Promise](http://rubygems.org/gems/promise) (>= 0.1.0) +* [SXP](http://rubygems.org/gems/sxp) (>= 0.0.4) +* [Promise](http://rubygems.org/gems/promise) (>= 0.1.1) Installation ------------ The recommended installation method is via [RubyGems](http://rubygems.org/). To install the latest official release of the `trith` gem, do one of the following: $ [sudo] gem install trith # Ruby 1.9+ $ [sudo] gem1.9 install trith # Ruby 1.9 with MacPorts $ [sudo] jruby --1.9 -S gem install trith # JRuby 1.4+ Once Trith is installed, you will have four new programs available: * `3sh`, aka "trish", is the Trith interactive shell and interpreter. * `3vm`, aka "trivium", is the Trith virtual machine runtime. * `3cc`, aka "tricksy", is the Trith compiler. * `3th`, aka "trith", is the Trith package manager. Note that as of the current release, only the first two do anything much as yet. Environment ----------- The following are the default settings for environment variables that let you customize how Trith works: $ export TRITH_HOME=~/.trith $ export TRITH_CACHE=$TRITH_HOME/cache $ export TRITH_TERM=$TERM Download -------- To get a local working copy of the development repository, do: $ git clone git://github.com/trith/trith.git Alternatively, you can download the latest development version as a tarball as follows: $ wget http://github.com/trith/trith/tarball/master Mailing List ------------ * <http://groups.google.com/group/trith> Authors ------- * [Arto Bendiken](mailto:[email protected]) - <http://ar.to/> License ------- Trith is free and unencumbered public domain software. For more information, see <http://unlicense.org/> or the accompanying UNLICENSE file. [stack-oriented]: http://en.wikipedia.org/wiki/Stack-oriented_programming_language [concatenative]: http://en.wikipedia.org/wiki/Concatenative_programming_language [composition]: http://en.wikipedia.org/wiki/Function_composition [type system]: http://en.wikipedia.org/wiki/Type_system#Dynamic_typing [homoiconic]: http://en.wikipedia.org/wiki/Homoiconicity [S-expression]: http://en.wikipedia.org/wiki/S-expression [RDF]: http://en.wikipedia.org/wiki/Resource_Description_Framework [JVM]: http://en.wikipedia.org/wiki/Java_Virtual_Machine [Lisp]: http://en.wikipedia.org/wiki/Lisp_(programming_language) [Scheme]: http://en.wikipedia.org/wiki/Scheme_(programming_language) [Forth]: http://en.wikipedia.org/wiki/Forth_(programming_language) [Factor]: http://en.wikipedia.org/wiki/Factor_(programming_language) [Joy]: http://en.wikipedia.org/wiki/Joy_(programming_language) [Cat]: http://en.wikipedia.org/wiki/Cat_(programming_language) [XY]: http://www.nsl.com/k/xy/xy.htm [Linked Data]: http://linkeddata.org/ [lispers.org]: http://lispers.org/ [concat.org]: http://concatenative.org/wiki/view/Concatenative%20language
trith/trith
d4286d40910ef3a1d3f51ad372168a9f24384e77
Added to the reading list.
diff --git a/doc/READING.md b/doc/READING.md index d8d452b..3ac0f3c 100644 --- a/doc/READING.md +++ b/doc/READING.md @@ -1,46 +1,60 @@ Some background reading materials for understanding Trith. +General +======= + Books ----- * [Thinking Forth: A Language and Philosophy for Solving Problems][Brodie] by Leo Brodie * [Lambda-Calculus and Combinators: An Introduction][HindleySeldin] by Roger Hindley and Jonathan P. Seldin * [Purely Functional Data Structures][Okasaki] by Chris Okasaki [Brodie]: http://thinking-forth.sourceforge.net/ "Brodie, L. 'Thinking Forth: A Language and Philosophy for Solving Problems' (1984)" [HindleySeldin]: http://www.cambridge.org/catalogue/catalogue.asp?isbn=9780521898850 "Hindley, J. R., and Seldin, J. P. 'Lambda-Calculus and Combinators: An Introduction' (2008)" [Okasaki]: http://www.cs.cmu.edu/~rwh/theses/okasaki.pdf "Okasaki, C. 'Purely Functional Data Structures' (1996)" Papers ------ * [Why Functional Programming Matters][WhyFP] by John Hughes * [Mathematical Foundations of Joy][JoyMath] by Manfred von Thun * [Linear Logic and Permutation Stacks -- The Forth Shall Be First][ForthStack] by Henry Baker * [Lively Linear Lisp -- 'Look Ma, No Garbage!'][LinearLisp] by Henry Baker * ['Use-Once' Variables and Linear Objects][Use1Var] by Henry Baker [WhyFP]: http://www.cs.chalmers.se/~rjmh/Papers/whyfp.html "Hughes, J. 'Why Functional Programming Matters' (1989)" [JoyMath]: http://www.latrobe.edu.au/philosophy/phimvt/joy/j02maf.html "von Thun, M. 'Mathematical Foundations of Joy' (2002)" [Use1Var]: http://www.pipeline.com/~hbaker1/Use1Var.html "Baker, H.G. 'Use-Once Variables and Linear Objects -- Storage Management, Reflection and Multi-Threading' (Jan 1995)" [ForthStack]: http://www.pipeline.com/~hbaker1/ForthStack.html "Baker, H.G. 'Linear Logic and Permutation Stacks -- The Forth Shall Be First' (Mar 1994)" [LQsort]: http://www.pipeline.com/~hbaker1/LQsort.html "Barke, H.G. 'A Linear Logic Quicksort' (Feb 1994)" [ObjectIdentity]: http://www.pipeline.com/~hbaker1/ObjectIdentity.html "Baker, H.G. 'Equal Rights for Functional Objects or, The More Things Change, The More They Are the Same' (Oct 1993)" [LinearLisp]: http://www.pipeline.com/~hbaker1/LinearLisp.html "Baker, H.G. 'Lively Linear Lisp -- Look Ma, No Garbage!' (Aug 1992)" [LazyAlloc]: http://www.pipeline.com/~hbaker1/LazyAlloc.html "Baker, H.G. 'CONS Should not CONS its Arguments, or, a Lazy Alloc is a Smart Alloc' (Mar 1992)" Articles -------- * [A Conversation with Manfred von Thun](http://www.nsl.com/papers/interview.htm) + +JVM +=== + +LLVM +==== + +Tutorials +--------- + +* [Stacker: An Example Of Using LLVM](http://llvm.org/releases/2.3/docs/Stacker.html)
trith/trith
9dfdbe3c679ac97b13316d39eac784b11aabd95f
Bumped version to 0.0.3.
diff --git a/VERSION b/VERSION index 4e379d2..bcab45a 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.0.2 +0.0.3 diff --git a/lib/trith/version.rb b/lib/trith/version.rb index 50ca6ec..dad8d78 100644 --- a/lib/trith/version.rb +++ b/lib/trith/version.rb @@ -1,23 +1,23 @@ module Trith module VERSION MAJOR = 0 MINOR = 0 - TINY = 2 + TINY = 3 EXTRA = nil STRING = [MAJOR, MINOR, TINY].join('.') STRING << ".#{EXTRA}" if EXTRA ## # @return [String] def self.to_s() STRING end ## # @return [String] def self.to_str() STRING end ## # @return [Array(Integer, Integer, Integer)] def self.to_a() [MAJOR, MINOR, TINY] end end end
trith/trith
fbc2ea430c356244094f6c4bfd85229d8f35ed41
Generated the N-Triples versions of RDF distributables.
diff --git a/etc/trith-core.nt b/etc/trith-core.nt index 7340073..8feb89a 100644 --- a/etc/trith-core.nt +++ b/etc/trith-core.nt @@ -1,714 +1,1252 @@ <http://trith.org/core/abs> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/abs> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/abs> <http://trith.org/lang/code> _:genid8 . <http://trith.org/core/abs> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/abs> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/abs> <http://www.w3.org/2000/01/rdf-schema#label> "abs" . <http://trith.org/core/add> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/add> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/add> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/add> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/add> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/add> <http://www.w3.org/2000/01/rdf-schema#label> "+" . <http://trith.org/core/add> <http://www.w3.org/2000/01/rdf-schema#label> "add" . <http://trith.org/core/and> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/and> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/and> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . -<http://trith.org/core/and> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/and> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . +<http://trith.org/core/and> <http://www.w3.org/2000/01/rdf-schema#comment> "Bitwise AND" . <http://trith.org/core/and> <http://www.w3.org/2000/01/rdf-schema#label> "and" . +<http://trith.org/core/andp> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/andp> <http://trith.org/lang/code> _:genid24 . +<http://trith.org/core/andp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/andp> <http://www.w3.org/2000/01/rdf-schema#comment> "Logical AND" . +<http://trith.org/core/andp> <http://www.w3.org/2000/01/rdf-schema#label> "and?" . +<http://trith.org/core/andp> <http://www.w3.org/2000/01/rdf-schema#label> "andp" . +<http://trith.org/core/bool> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/bool> <http://trith.org/lang/code> _:genid29 . +<http://trith.org/core/bool> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/bool> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/bool> <http://www.w3.org/2000/01/rdf-schema#label> "bool" . <http://trith.org/core/boolp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/boolp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/boolp> <http://trith.org/lang/code> _:genid34 . <http://trith.org/core/boolp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/boolp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/boolp> <http://www.w3.org/2000/01/rdf-schema#label> "bool?" . <http://trith.org/core/boolp> <http://www.w3.org/2000/01/rdf-schema#label> "boolp" . <http://trith.org/core/branch> <http://trith.org/lang/arity> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/branch> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/branch> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/branch> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/branch> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/branch> <http://www.w3.org/2000/01/rdf-schema#label> "branch" . <http://trith.org/core/branch> <http://www.w3.org/2000/01/rdf-schema#label> "if" . <http://trith.org/core/call> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/call> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/call> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/call> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/call> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/call> <http://www.w3.org/2000/01/rdf-schema#label> "call" . -<http://trith.org/core/char> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/char> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -<http://trith.org/core/char> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . -<http://trith.org/core/char> <http://www.w3.org/2000/01/rdf-schema#comment> "" . -<http://trith.org/core/char> <http://www.w3.org/2000/01/rdf-schema#label> "char" . -<http://trith.org/core/charp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/charp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -<http://trith.org/core/charp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . -<http://trith.org/core/charp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . -<http://trith.org/core/charp> <http://www.w3.org/2000/01/rdf-schema#label> "char?" . -<http://trith.org/core/charp> <http://www.w3.org/2000/01/rdf-schema#label> "charp" . +<http://trith.org/core/ceil> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/ceil> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/ceil> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/ceil> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/ceil> <http://www.w3.org/2000/01/rdf-schema#label> "ceil" . +<http://trith.org/core/chr> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/chr> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/chr> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/chr> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . +<http://trith.org/core/chr> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/chr> <http://www.w3.org/2000/01/rdf-schema#label> "chr" . +<http://trith.org/core/chr> <http://www.w3.org/2000/01/rdf-schema#seeAlso> <http://trith.org/core/ord> . +<http://trith.org/core/chrp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/chrp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/chrp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/chrp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . +<http://trith.org/core/chrp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/chrp> <http://www.w3.org/2000/01/rdf-schema#label> "chr?" . +<http://trith.org/core/chrp> <http://www.w3.org/2000/01/rdf-schema#label> "chrp" . <http://trith.org/core/clear> <http://trith.org/lang/arity> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/clear> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/clear> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . -<http://trith.org/core/clear> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/clear> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . +<http://trith.org/core/clear> <http://www.w3.org/2000/01/rdf-schema#comment> "Clear the data stack" . <http://trith.org/core/clear> <http://www.w3.org/2000/01/rdf-schema#label> "clear" . <http://trith.org/core/cmp> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/cmp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/cmp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/cmp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/cmp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/cmp> <http://www.w3.org/2000/01/rdf-schema#label> "<=>" . <http://trith.org/core/cmp> <http://www.w3.org/2000/01/rdf-schema#label> "cmp" . +<http://trith.org/core/concat> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/concat> <http://trith.org/lang/code> _:genid52 . +<http://trith.org/core/concat> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/concat> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/concat> <http://www.w3.org/2000/01/rdf-schema#label> "concat" . <http://trith.org/core/cons> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/cons> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/cons> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/cons> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/cons> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/cons> <http://www.w3.org/2000/01/rdf-schema#label> "cons" . <http://trith.org/core/dec> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/dec> <http://trith.org/lang/code> _:genid2 . +<http://trith.org/core/dec> <http://trith.org/lang/code> _:genid61 . <http://trith.org/core/dec> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/dec> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/dec> <http://www.w3.org/2000/01/rdf-schema#label> "dec" . +<http://trith.org/core/depth> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/depth> <http://trith.org/lang/code> _:genid59 . +<http://trith.org/core/depth> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/depth> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/depth> <http://www.w3.org/2000/01/rdf-schema#label> "depth" . <http://trith.org/core/dip> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/dip> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/dip> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/dip> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/dip> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/dip> <http://www.w3.org/2000/01/rdf-schema#label> "dip" . <http://trith.org/core/div> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/div> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/div> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/div> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/div> <http://www.w3.org/2000/01/rdf-schema#label> "/" . <http://trith.org/core/div> <http://www.w3.org/2000/01/rdf-schema#label> "div" . <http://trith.org/core/drop2> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/drop2> <http://trith.org/lang/code> _:genid4 . +<http://trith.org/core/drop2> <http://trith.org/lang/code> _:genid64 . <http://trith.org/core/drop2> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/drop2> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/drop2> <http://www.w3.org/2000/01/rdf-schema#label> "2drop" . <http://trith.org/core/drop2> <http://www.w3.org/2000/01/rdf-schema#label> "drop2" . <http://trith.org/core/drop3> <http://trith.org/lang/arity> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/drop3> <http://trith.org/lang/code> _:genid7 . +<http://trith.org/core/drop3> <http://trith.org/lang/code> _:genid67 . <http://trith.org/core/drop3> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/drop3> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/drop3> <http://www.w3.org/2000/01/rdf-schema#label> "3drop" . <http://trith.org/core/drop3> <http://www.w3.org/2000/01/rdf-schema#label> "drop3" . <http://trith.org/core/drop> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/drop> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/drop> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/drop> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/drop> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/drop> <http://www.w3.org/2000/01/rdf-schema#label> "drop" . <http://trith.org/core/dup2> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/dup2> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/dup2> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/dup2> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/dup2> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/dup2> <http://www.w3.org/2000/01/rdf-schema#label> "2dup" . <http://trith.org/core/dup2> <http://www.w3.org/2000/01/rdf-schema#label> "dup2" . <http://trith.org/core/dup3> <http://trith.org/lang/arity> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/dup3> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/dup3> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/dup3> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/dup3> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/dup3> <http://www.w3.org/2000/01/rdf-schema#label> "3dup" . <http://trith.org/core/dup3> <http://www.w3.org/2000/01/rdf-schema#label> "dup3" . <http://trith.org/core/dup> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/dup> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/dup> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/dup> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/dup> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/dup> <http://www.w3.org/2000/01/rdf-schema#label> "dup" . +<http://trith.org/core/each> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/each> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/each> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/each> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/each> <http://www.w3.org/2000/01/rdf-schema#label> "each" . <http://trith.org/core/eighth> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/eighth> <http://trith.org/lang/code> _:genid9 . +<http://trith.org/core/eighth> <http://trith.org/lang/code> _:genid69 . <http://trith.org/core/eighth> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/eighth> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/eighth> <http://www.w3.org/2000/01/rdf-schema#label> "eighth" . <http://trith.org/core/emptyp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/emptyp> <http://trith.org/lang/code> _:genid11 . +<http://trith.org/core/emptyp> <http://trith.org/lang/code> _:genid71 . <http://trith.org/core/emptyp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/emptyp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/emptyp> <http://www.w3.org/2000/01/rdf-schema#label> "empty?" . <http://trith.org/core/emptyp> <http://www.w3.org/2000/01/rdf-schema#label> "emptyp" . <http://trith.org/core/eq> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/eq> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/eq> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/eq> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/eq> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/eq> <http://www.w3.org/2000/01/rdf-schema#label> "=" . <http://trith.org/core/eq> <http://www.w3.org/2000/01/rdf-schema#label> "eq" . <http://trith.org/core/evenp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/evenp> <http://trith.org/lang/code> _:genid14 . +<http://trith.org/core/evenp> <http://trith.org/lang/code> _:genid74 . <http://trith.org/core/evenp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/evenp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/evenp> <http://www.w3.org/2000/01/rdf-schema#label> "even?" . <http://trith.org/core/evenp> <http://www.w3.org/2000/01/rdf-schema#label> "evenp" . <http://trith.org/core/exactp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/exactp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/exactp> <http://trith.org/lang/code> _:genid76 . <http://trith.org/core/exactp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/exactp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/exactp> <http://www.w3.org/2000/01/rdf-schema#label> "exact?" . <http://trith.org/core/exactp> <http://www.w3.org/2000/01/rdf-schema#label> "exactp" . <http://trith.org/core/false> <http://trith.org/lang/arity> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/false> <http://trith.org/lang/code> _:genid16 . +<http://trith.org/core/false> <http://trith.org/lang/code> _:genid78 . <http://trith.org/core/false> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/false> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/false> <http://www.w3.org/2000/01/rdf-schema#label> "false" . <http://trith.org/core/falsep> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/falsep> <http://trith.org/lang/code> _:genid18 . +<http://trith.org/core/falsep> <http://trith.org/lang/code> _:genid80 . <http://trith.org/core/falsep> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/falsep> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/falsep> <http://www.w3.org/2000/01/rdf-schema#label> "false?" . <http://trith.org/core/falsep> <http://www.w3.org/2000/01/rdf-schema#label> "falsep" . <http://trith.org/core/fifth> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/fifth> <http://trith.org/lang/code> _:genid20 . +<http://trith.org/core/fifth> <http://trith.org/lang/code> _:genid82 . <http://trith.org/core/fifth> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/fifth> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/fifth> <http://www.w3.org/2000/01/rdf-schema#label> "fifth" . <http://trith.org/core/first> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/first> <http://trith.org/lang/code> _:genid22 . +<http://trith.org/core/first> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/first> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/first> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/first> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/first> <http://www.w3.org/2000/01/rdf-schema#label> "first" . +<http://trith.org/core/flatten> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/flatten> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/flatten> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/flatten> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/flatten> <http://www.w3.org/2000/01/rdf-schema#label> "flatten" . +<http://trith.org/core/floor> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/floor> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/floor> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/floor> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/floor> <http://www.w3.org/2000/01/rdf-schema#label> "floor" . +<http://trith.org/core/foldl1> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/foldl1> <http://trith.org/lang/code> _:genid212 . +<http://trith.org/core/foldl1> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/foldl1> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/foldl1> <http://www.w3.org/2000/01/rdf-schema#label> "foldl1" . +<http://trith.org/core/foldl> <http://trith.org/lang/arity> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/foldl> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/foldl> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/foldl> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/foldl> <http://www.w3.org/2000/01/rdf-schema#label> "fold" . +<http://trith.org/core/foldl> <http://www.w3.org/2000/01/rdf-schema#label> "foldl" . +<http://trith.org/core/foldl> <http://www.w3.org/2000/01/rdf-schema#label> "reduce" . <http://trith.org/core/fourth> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/fourth> <http://trith.org/lang/code> _:genid24 . +<http://trith.org/core/fourth> <http://trith.org/lang/code> _:genid84 . <http://trith.org/core/fourth> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/fourth> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/fourth> <http://www.w3.org/2000/01/rdf-schema#label> "fourth" . <http://trith.org/core/ge> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/ge> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/ge> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/ge> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/ge> <http://www.w3.org/2000/01/rdf-schema#label> ">=" . <http://trith.org/core/ge> <http://www.w3.org/2000/01/rdf-schema#label> "ge" . <http://trith.org/core/gt> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/gt> <http://trith.org/lang/code> _:genid27 . +<http://trith.org/core/gt> <http://trith.org/lang/code> _:genid86 . <http://trith.org/core/gt> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/gt> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/gt> <http://www.w3.org/2000/01/rdf-schema#label> ">" . <http://trith.org/core/gt> <http://www.w3.org/2000/01/rdf-schema#label> "gt" . <http://trith.org/core/halt> <http://trith.org/lang/arity> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/halt> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/halt> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/halt> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/halt> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/halt> <http://www.w3.org/2000/01/rdf-schema#label> "halt" . <http://trith.org/core/inc> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/inc> <http://trith.org/lang/code> _:genid29 . +<http://trith.org/core/inc> <http://trith.org/lang/code> _:genid88 . <http://trith.org/core/inc> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/inc> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/inc> <http://www.w3.org/2000/01/rdf-schema#label> "inc" . <http://trith.org/core/inexactp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/inexactp> <http://trith.org/lang/code> _:genid31 . +<http://trith.org/core/inexactp> <http://trith.org/lang/code> _:genid90 . <http://trith.org/core/inexactp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/inexactp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/inexactp> <http://www.w3.org/2000/01/rdf-schema#label> "inexact?" . <http://trith.org/core/inexactp> <http://www.w3.org/2000/01/rdf-schema#label> "inexactp" . -<http://trith.org/core/integerp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/integerp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -<http://trith.org/core/integerp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . -<http://trith.org/core/integerp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . -<http://trith.org/core/integerp> <http://www.w3.org/2000/01/rdf-schema#label> "integer?" . -<http://trith.org/core/integerp> <http://www.w3.org/2000/01/rdf-schema#label> "integerp" . +<http://trith.org/core/inf> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/inf> <http://trith.org/lang/code> _:genid93 . +<http://trith.org/core/inf> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/inf> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/inf> <http://www.w3.org/2000/01/rdf-schema#label> "inf" . +<http://trith.org/core/infp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/infp> <http://trith.org/lang/code> _:genid96 . +<http://trith.org/core/infp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/infp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/infp> <http://www.w3.org/2000/01/rdf-schema#label> "inf?" . +<http://trith.org/core/infp> <http://www.w3.org/2000/01/rdf-schema#label> "infp" . +<http://trith.org/core/intp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/intp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/intp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/intp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . +<http://trith.org/core/intp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/intp> <http://www.w3.org/2000/01/rdf-schema#label> "int?" . +<http://trith.org/core/intp> <http://www.w3.org/2000/01/rdf-schema#label> "intp" . +<http://trith.org/core/iota> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/iota> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/iota> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/iota> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/iota> <http://www.w3.org/2000/01/rdf-schema#label> "iota" . <http://trith.org/core/last> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/last> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/last> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/last> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/last> <http://www.w3.org/2000/01/rdf-schema#label> "last" . <http://trith.org/core/le> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/le> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/le> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/le> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/le> <http://www.w3.org/2000/01/rdf-schema#label> "<=" . <http://trith.org/core/le> <http://www.w3.org/2000/01/rdf-schema#label> "le" . <http://trith.org/core/length> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/length> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/length> <http://trith.org/lang/code> _:genid107 . <http://trith.org/core/length> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/length> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/length> <http://www.w3.org/2000/01/rdf-schema#label> "length" . +<http://trith.org/core/list> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/list> <http://trith.org/lang/code> _:genid114 . +<http://trith.org/core/list> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/list> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/list> <http://www.w3.org/2000/01/rdf-schema#label> "list" . <http://trith.org/core/loop> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/loop> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/loop> <http://trith.org/lang/code> _:genid119 . <http://trith.org/core/loop> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/loop> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/loop> <http://www.w3.org/2000/01/rdf-schema#label> "loop" . <http://trith.org/core/lt> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/lt> <http://trith.org/lang/code> _:genid34 . +<http://trith.org/core/lt> <http://trith.org/lang/code> _:genid122 . <http://trith.org/core/lt> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/lt> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/lt> <http://www.w3.org/2000/01/rdf-schema#label> "<" . <http://trith.org/core/lt> <http://www.w3.org/2000/01/rdf-schema#label> "lt" . +<http://trith.org/core/map> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/map> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/map> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/map> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/map> <http://www.w3.org/2000/01/rdf-schema#label> "map" . <http://trith.org/core/max> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/max> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/max> <http://trith.org/lang/code> _:genid130 . <http://trith.org/core/max> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/max> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/max> <http://www.w3.org/2000/01/rdf-schema#label> "max" . +<http://trith.org/core/memberp> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/memberp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/memberp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/memberp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/memberp> <http://www.w3.org/2000/01/rdf-schema#label> "member?" . +<http://trith.org/core/memberp> <http://www.w3.org/2000/01/rdf-schema#label> "memberp" . <http://trith.org/core/min> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/min> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/min> <http://trith.org/lang/code> _:genid138 . <http://trith.org/core/min> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/min> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/min> <http://www.w3.org/2000/01/rdf-schema#label> "min" . <http://trith.org/core/mod> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/mod> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/mod> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/mod> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/mod> <http://www.w3.org/2000/01/rdf-schema#label> "mod" . <http://trith.org/core/mul> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/mul> <http://trith.org/lang/code> _:genid43 . +<http://trith.org/core/mul> <http://trith.org/lang/code> _:genid147 . <http://trith.org/core/mul> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/mul> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/mul> <http://www.w3.org/2000/01/rdf-schema#label> "*" . <http://trith.org/core/mul> <http://www.w3.org/2000/01/rdf-schema#label> "mul" . <http://trith.org/core/ne> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/ne> <http://trith.org/lang/code> _:genid45 . +<http://trith.org/core/ne> <http://trith.org/lang/code> _:genid149 . <http://trith.org/core/ne> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/ne> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/ne> <http://www.w3.org/2000/01/rdf-schema#label> "!=" . <http://trith.org/core/ne> <http://www.w3.org/2000/01/rdf-schema#label> "ne" . <http://trith.org/core/neg> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/neg> <http://trith.org/lang/code> _:genid48 . +<http://trith.org/core/neg> <http://trith.org/lang/code> _:genid152 . <http://trith.org/core/neg> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/neg> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/neg> <http://www.w3.org/2000/01/rdf-schema#label> "neg" . +<http://trith.org/core/negp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/negp> <http://trith.org/lang/code> _:genid154 . +<http://trith.org/core/negp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/negp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/negp> <http://www.w3.org/2000/01/rdf-schema#label> "neg?" . +<http://trith.org/core/negp> <http://www.w3.org/2000/01/rdf-schema#label> "negp" . <http://trith.org/core/nil> <http://trith.org/lang/arity> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/nil> <http://trith.org/lang/code> _:genid50 . +<http://trith.org/core/nil> <http://trith.org/lang/code> _:genid156 . <http://trith.org/core/nil> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/nil> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/nil> <http://www.w3.org/2000/01/rdf-schema#label> "nil" . <http://trith.org/core/nilp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/nilp> <http://trith.org/lang/code> _:genid52 . +<http://trith.org/core/nilp> <http://trith.org/lang/code> _:genid158 . <http://trith.org/core/nilp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/nilp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/nilp> <http://www.w3.org/2000/01/rdf-schema#label> "nil?" . <http://trith.org/core/nilp> <http://www.w3.org/2000/01/rdf-schema#label> "nilp" . <http://trith.org/core/ninth> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/ninth> <http://trith.org/lang/code> _:genid54 . +<http://trith.org/core/ninth> <http://trith.org/lang/code> _:genid160 . <http://trith.org/core/ninth> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/ninth> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/ninth> <http://www.w3.org/2000/01/rdf-schema#label> "ninth" . <http://trith.org/core/nip2> <http://trith.org/lang/arity> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/nip2> <http://trith.org/lang/code> _:genid60 . +<http://trith.org/core/nip2> <http://trith.org/lang/code> _:genid166 . <http://trith.org/core/nip2> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/nip2> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/nip2> <http://www.w3.org/2000/01/rdf-schema#label> "2nip" . <http://trith.org/core/nip2> <http://www.w3.org/2000/01/rdf-schema#label> "nip2" . <http://trith.org/core/nip> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/nip> <http://trith.org/lang/code> _:genid56 . +<http://trith.org/core/nip> <http://trith.org/lang/code> _:genid162 . <http://trith.org/core/nip> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/nip> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/nip> <http://www.w3.org/2000/01/rdf-schema#label> "nip" . <http://trith.org/core/nop> <http://trith.org/lang/arity> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/nop> <http://trith.org/lang/code> _:genid62 . +<http://trith.org/core/nop> <http://trith.org/lang/code> _:genid168 . <http://trith.org/core/nop> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/nop> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/nop> <http://www.w3.org/2000/01/rdf-schema#label> "," . <http://trith.org/core/nop> <http://www.w3.org/2000/01/rdf-schema#label> ";" . <http://trith.org/core/nop> <http://www.w3.org/2000/01/rdf-schema#label> "nop" . <http://trith.org/core/not> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/not> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/not> <http://trith.org/lang/code> _:genid170 . <http://trith.org/core/not> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . -<http://trith.org/core/not> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/not> <http://www.w3.org/2000/01/rdf-schema#comment> "Bitwise NOT" . <http://trith.org/core/not> <http://www.w3.org/2000/01/rdf-schema#label> "not" . +<http://trith.org/core/notp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/notp> <http://trith.org/lang/code> _:genid175 . +<http://trith.org/core/notp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/notp> <http://www.w3.org/2000/01/rdf-schema#comment> "Logical NOT" . +<http://trith.org/core/notp> <http://www.w3.org/2000/01/rdf-schema#label> "not?" . +<http://trith.org/core/notp> <http://www.w3.org/2000/01/rdf-schema#label> "notp" . <http://trith.org/core/nth> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/nth> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/nth> <http://trith.org/lang/code> _:genid180 . <http://trith.org/core/nth> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/nth> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/nth> <http://www.w3.org/2000/01/rdf-schema#label> "nth" . -<http://trith.org/core/number> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/number> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -<http://trith.org/core/number> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . -<http://trith.org/core/number> <http://www.w3.org/2000/01/rdf-schema#comment> "" . -<http://trith.org/core/number> <http://www.w3.org/2000/01/rdf-schema#label> "number" . -<http://trith.org/core/numberp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/numberp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -<http://trith.org/core/numberp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . -<http://trith.org/core/numberp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . -<http://trith.org/core/numberp> <http://www.w3.org/2000/01/rdf-schema#label> "number?" . -<http://trith.org/core/numberp> <http://www.w3.org/2000/01/rdf-schema#label> "numberp" . +<http://trith.org/core/num> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/num> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/num> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/num> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . +<http://trith.org/core/num> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/num> <http://www.w3.org/2000/01/rdf-schema#label> "num" . +<http://trith.org/core/nump> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/nump> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/nump> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/nump> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . +<http://trith.org/core/nump> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/nump> <http://www.w3.org/2000/01/rdf-schema#label> "num?" . +<http://trith.org/core/nump> <http://www.w3.org/2000/01/rdf-schema#label> "nump" . <http://trith.org/core/oddp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/oddp> <http://trith.org/lang/code> _:genid64 . +<http://trith.org/core/oddp> <http://trith.org/lang/code> _:genid182 . <http://trith.org/core/oddp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/oddp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/oddp> <http://www.w3.org/2000/01/rdf-schema#label> "odd?" . <http://trith.org/core/oddp> <http://www.w3.org/2000/01/rdf-schema#label> "oddp" . +<http://trith.org/core/onep> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/onep> <http://trith.org/lang/code> _:genid184 . +<http://trith.org/core/onep> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/onep> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/onep> <http://www.w3.org/2000/01/rdf-schema#label> "one?" . +<http://trith.org/core/onep> <http://www.w3.org/2000/01/rdf-schema#label> "onep" . <http://trith.org/core/or> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/or> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/or> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . -<http://trith.org/core/or> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/or> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . +<http://trith.org/core/or> <http://www.w3.org/2000/01/rdf-schema#comment> "Bitwise OR" . <http://trith.org/core/or> <http://www.w3.org/2000/01/rdf-schema#label> "or" . +<http://trith.org/core/ord> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/ord> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/ord> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/ord> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . +<http://trith.org/core/ord> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/ord> <http://www.w3.org/2000/01/rdf-schema#label> "ord" . +<http://trith.org/core/ord> <http://www.w3.org/2000/01/rdf-schema#seeAlso> <http://trith.org/core/chr> . +<http://trith.org/core/orp> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/orp> <http://trith.org/lang/code> _:genid192 . +<http://trith.org/core/orp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/orp> <http://www.w3.org/2000/01/rdf-schema#comment> "Logical OR" . +<http://trith.org/core/orp> <http://www.w3.org/2000/01/rdf-schema#label> "or?" . +<http://trith.org/core/orp> <http://www.w3.org/2000/01/rdf-schema#label> "orp" . <http://trith.org/core/over> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/over> <http://trith.org/lang/code> _:genid66 . +<http://trith.org/core/over> <http://trith.org/lang/code> _:genid194 . <http://trith.org/core/over> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/over> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/over> <http://www.w3.org/2000/01/rdf-schema#label> "over" . <http://trith.org/core/pick> <http://trith.org/lang/arity> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/pick> <http://trith.org/lang/code> _:genid68 . +<http://trith.org/core/pick> <http://trith.org/lang/code> _:genid196 . <http://trith.org/core/pick> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/pick> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/pick> <http://www.w3.org/2000/01/rdf-schema#label> "pick" . +<http://trith.org/core/posp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/posp> <http://trith.org/lang/code> _:genid198 . +<http://trith.org/core/posp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/posp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/posp> <http://www.w3.org/2000/01/rdf-schema#label> "pos?" . +<http://trith.org/core/posp> <http://www.w3.org/2000/01/rdf-schema#label> "posp" . <http://trith.org/core/pow> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/pow> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/pow> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/pow> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/pow> <http://www.w3.org/2000/01/rdf-schema#label> "pow" . <http://trith.org/core/print> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/print> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/print> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/print> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/print> <http://www.w3.org/2000/01/rdf-schema#label> "." . +<http://trith.org/core/print> <http://www.w3.org/2000/01/rdf-schema#label> "print!" . <http://trith.org/core/print> <http://www.w3.org/2000/01/rdf-schema#label> "print" . <http://trith.org/core/quote> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/quote> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/quote> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/quote> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/quote> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/quote> <http://www.w3.org/2000/01/rdf-schema#label> "'" . <http://trith.org/core/quote> <http://www.w3.org/2000/01/rdf-schema#label> "\\" . <http://trith.org/core/quote> <http://www.w3.org/2000/01/rdf-schema#label> "quote" . +<http://trith.org/core/range> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/range> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/range> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/range> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/range> <http://www.w3.org/2000/01/rdf-schema#label> "range" . <http://trith.org/core/rem> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/rem> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/rem> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/rem> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/rem> <http://www.w3.org/2000/01/rdf-schema#label> "rem" . <http://trith.org/core/reset> <http://trith.org/lang/arity> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/reset> <http://trith.org/lang/code> _:genid70 . +<http://trith.org/core/reset> <http://trith.org/lang/code> _:genid214 . <http://trith.org/core/reset> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/reset> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/reset> <http://www.w3.org/2000/01/rdf-schema#label> "reset" . <http://trith.org/core/rest> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/rest> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/rest> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/rest> <http://www.w3.org/2000/01/rdf-schema#label> "rest" . <http://trith.org/core/reverse> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/reverse> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/reverse> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/reverse> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/reverse> <http://www.w3.org/2000/01/rdf-schema#label> "reverse" . +<http://trith.org/core/rot> <http://trith.org/lang/arity> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/rot> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/rot> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/rot> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . +<http://trith.org/core/rot> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/rot> <http://www.w3.org/2000/01/rdf-schema#label> "rot" . <http://trith.org/core/second> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/second> <http://trith.org/lang/code> _:genid72 . +<http://trith.org/core/second> <http://trith.org/lang/code> _:genid216 . <http://trith.org/core/second> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/second> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/second> <http://www.w3.org/2000/01/rdf-schema#label> "second" . <http://trith.org/core/seq> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/seq> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/seq> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/seq> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/seq> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/seq> <http://www.w3.org/2000/01/rdf-schema#label> "seq" . <http://trith.org/core/seqp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/seqp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/seqp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/seqp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/seqp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/seqp> <http://www.w3.org/2000/01/rdf-schema#label> "seq?" . <http://trith.org/core/seqp> <http://www.w3.org/2000/01/rdf-schema#label> "seqp" . <http://trith.org/core/seventh> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/seventh> <http://trith.org/lang/code> _:genid74 . +<http://trith.org/core/seventh> <http://trith.org/lang/code> _:genid218 . <http://trith.org/core/seventh> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/seventh> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/seventh> <http://www.w3.org/2000/01/rdf-schema#label> "seventh" . <http://trith.org/core/shl> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/shl> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/shl> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/shl> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/shl> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/shl> <http://www.w3.org/2000/01/rdf-schema#label> "shl" . <http://trith.org/core/shr> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/shr> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/shr> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/shr> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/shr> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/shr> <http://www.w3.org/2000/01/rdf-schema#label> "shr" . <http://trith.org/core/sixth> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/sixth> <http://trith.org/lang/code> _:genid76 . +<http://trith.org/core/sixth> <http://trith.org/lang/code> _:genid220 . <http://trith.org/core/sixth> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/sixth> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/sixth> <http://www.w3.org/2000/01/rdf-schema#label> "sixth" . <http://trith.org/core/size> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/size> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/size> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/size> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/size> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/size> <http://www.w3.org/2000/01/rdf-schema#label> "size" . +<http://trith.org/core/stack> <http://trith.org/lang/arity> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/stack> <http://trith.org/lang/code> _:genid222 . +<http://trith.org/core/stack> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/stack> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/stack> <http://www.w3.org/2000/01/rdf-schema#label> "stack" . <http://trith.org/core/sub> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/sub> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/sub> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/sub> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/sub> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/sub> <http://www.w3.org/2000/01/rdf-schema#label> "-" . <http://trith.org/core/sub> <http://www.w3.org/2000/01/rdf-schema#label> "sub" . <http://trith.org/core/swap> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/swap> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/swap> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/swap> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . <http://trith.org/core/swap> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/swap> <http://www.w3.org/2000/01/rdf-schema#label> "swap" . <http://trith.org/core/tenth> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/tenth> <http://trith.org/lang/code> _:genid78 . +<http://trith.org/core/tenth> <http://trith.org/lang/code> _:genid224 . <http://trith.org/core/tenth> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/tenth> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/tenth> <http://www.w3.org/2000/01/rdf-schema#label> "tenth" . <http://trith.org/core/text> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/text> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/text> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/text> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/text> <http://www.w3.org/2000/01/rdf-schema#label> "text" . <http://trith.org/core/textp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/textp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/textp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/textp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/textp> <http://www.w3.org/2000/01/rdf-schema#label> "text?" . <http://trith.org/core/textp> <http://www.w3.org/2000/01/rdf-schema#label> "textp" . <http://trith.org/core/third> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/third> <http://trith.org/lang/code> _:genid80 . +<http://trith.org/core/third> <http://trith.org/lang/code> _:genid226 . <http://trith.org/core/third> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/third> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/third> <http://www.w3.org/2000/01/rdf-schema#label> "third" . <http://trith.org/core/thrice> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/thrice> <http://trith.org/lang/code> _:genid82 . +<http://trith.org/core/thrice> <http://trith.org/lang/code> _:genid228 . <http://trith.org/core/thrice> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/thrice> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/thrice> <http://www.w3.org/2000/01/rdf-schema#label> "3x" . <http://trith.org/core/thrice> <http://www.w3.org/2000/01/rdf-schema#label> "thrice" . <http://trith.org/core/times> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/times> <http://trith.org/lang/code> _:genid91 . +<http://trith.org/core/times> <http://trith.org/lang/code> _:genid237 . <http://trith.org/core/times> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/times> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/times> <http://www.w3.org/2000/01/rdf-schema#label> "times" . <http://trith.org/core/true> <http://trith.org/lang/arity> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/true> <http://trith.org/lang/code> _:genid93 . +<http://trith.org/core/true> <http://trith.org/lang/code> _:genid239 . <http://trith.org/core/true> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/true> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/true> <http://www.w3.org/2000/01/rdf-schema#label> "true" . <http://trith.org/core/truep> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/truep> <http://trith.org/lang/code> _:genid95 . +<http://trith.org/core/truep> <http://trith.org/lang/code> _:genid241 . <http://trith.org/core/truep> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/truep> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/truep> <http://www.w3.org/2000/01/rdf-schema#label> "true?" . <http://trith.org/core/truep> <http://www.w3.org/2000/01/rdf-schema#label> "truep" . <http://trith.org/core/twice> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/twice> <http://trith.org/lang/code> _:genid97 . +<http://trith.org/core/twice> <http://trith.org/lang/code> _:genid243 . <http://trith.org/core/twice> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/twice> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/twice> <http://www.w3.org/2000/01/rdf-schema#label> "2x" . <http://trith.org/core/twice> <http://www.w3.org/2000/01/rdf-schema#label> "twice" . +<http://trith.org/core/uncons> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/uncons> <http://trith.org/lang/code> _:genid247 . +<http://trith.org/core/uncons> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Operator> . +<http://trith.org/core/uncons> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/uncons> <http://www.w3.org/2000/01/rdf-schema#label> "uncons" . <http://trith.org/core/unless> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/unless> <http://trith.org/lang/code> _:genid101 . +<http://trith.org/core/unless> <http://trith.org/lang/code> _:genid251 . <http://trith.org/core/unless> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/unless> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/unless> <http://www.w3.org/2000/01/rdf-schema#label> "unless" . +<http://trith.org/core/unstack> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/unstack> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/unstack> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/unstack> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . +<http://trith.org/core/unstack> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/unstack> <http://www.w3.org/2000/01/rdf-schema#label> "unstack" . <http://trith.org/core/until> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/until> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/until> <http://trith.org/lang/code> _:genid255 . <http://trith.org/core/until> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/until> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/until> <http://www.w3.org/2000/01/rdf-schema#label> "until" . <http://trith.org/core/when> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/when> <http://trith.org/lang/code> _:genid104 . +<http://trith.org/core/when> <http://trith.org/lang/code> _:genid258 . <http://trith.org/core/when> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/when> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/when> <http://www.w3.org/2000/01/rdf-schema#label> "when" . <http://trith.org/core/while> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/while> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/while> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/while> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/while> <http://www.w3.org/2000/01/rdf-schema#label> "while" . <http://trith.org/core/xor> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . <http://trith.org/core/xor> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . <http://trith.org/core/xor> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . -<http://trith.org/core/xor> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/xor> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Primitive> . +<http://trith.org/core/xor> <http://www.w3.org/2000/01/rdf-schema#comment> "Bitwise XOR" . <http://trith.org/core/xor> <http://www.w3.org/2000/01/rdf-schema#label> "xor" . +<http://trith.org/core/xorp> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/xorp> <http://trith.org/lang/code> _:genid278 . +<http://trith.org/core/xorp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/xorp> <http://www.w3.org/2000/01/rdf-schema#comment> "Logical XOR" . +<http://trith.org/core/xorp> <http://www.w3.org/2000/01/rdf-schema#label> "xor?" . +<http://trith.org/core/xorp> <http://www.w3.org/2000/01/rdf-schema#label> "xorp" . <http://trith.org/core/zerop> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -<http://trith.org/core/zerop> <http://trith.org/lang/code> _:genid106 . +<http://trith.org/core/zerop> <http://trith.org/lang/code> _:genid280 . <http://trith.org/core/zerop> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . <http://trith.org/core/zerop> <http://www.w3.org/2000/01/rdf-schema#comment> "" . <http://trith.org/core/zerop> <http://www.w3.org/2000/01/rdf-schema#label> "zero?" . <http://trith.org/core/zerop> <http://www.w3.org/2000/01/rdf-schema#label> "zerop" . -_:genid1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/sub> . +_:genid1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/neg> . _:genid1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid10 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/zerop> . -_:genid10 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid100 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . -_:genid100 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid99 . -_:genid101 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid98 . +_:genid10 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid10 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid9 . +_:genid100 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/emptyp> . +_:genid100 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid101 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . _:genid101 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid100 . -_:genid102 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nop> . -_:genid102 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid103 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . +_:genid102 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid102 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid101 . +_:genid103 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . _:genid103 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid104 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid102 . +_:genid104 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/until> . _:genid104 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid103 . -_:genid105 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . -_:genid105 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid106 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid105 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid102 . +_:genid105 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid104 . +_:genid106 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid99 . _:genid106 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid105 . -_:genid11 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/length> . -_:genid11 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid10 . -_:genid12 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/zerop> . -_:genid12 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid13 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/mod> . -_:genid13 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid12 . -_:genid14 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid107 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid107 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid106 . +_:genid108 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/cons> . +_:genid108 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid109 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/reverse> . +_:genid109 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid11 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/false> . +_:genid11 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid110 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/times> . +_:genid110 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid109 . +_:genid111 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid111 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid110 . +_:genid112 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid108 . +_:genid112 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid111 . +_:genid113 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid113 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid112 . +_:genid114 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid114 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid113 . +_:genid115 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/loop> . +_:genid115 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid116 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/call> . +_:genid116 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid117 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid115 . +_:genid117 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid116 . +_:genid118 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/call> . +_:genid118 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid117 . +_:genid119 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . +_:genid119 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid118 . +_:genid12 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop2> . +_:genid12 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid11 . +_:genid120 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . +_:genid120 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid121 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "-1"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid121 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid120 . +_:genid122 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/cmp> . +_:genid122 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid121 . +_:genid123 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid123 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid124 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid124 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid125 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid125 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid124 . +_:genid126 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . +_:genid126 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid127 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid125 . +_:genid127 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid126 . +_:genid128 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid123 . +_:genid128 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid127 . +_:genid129 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/gt> . +_:genid129 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid128 . +_:genid13 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . +_:genid13 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid130 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup2> . +_:genid130 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid129 . +_:genid131 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid131 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid132 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid132 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid133 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid133 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid132 . +_:genid134 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . +_:genid134 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid135 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid133 . +_:genid135 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid134 . +_:genid136 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid131 . +_:genid136 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid135 . +_:genid137 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/lt> . +_:genid137 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid136 . +_:genid138 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup2> . +_:genid138 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid137 . +_:genid139 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/add> . +_:genid139 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid14 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid12 . _:genid14 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid13 . -_:genid15 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/false> . -_:genid15 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid16 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/quote> . +_:genid140 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/over> . +_:genid140 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid139 . +_:genid141 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nip> . +_:genid141 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid142 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/times> . +_:genid142 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid141 . +_:genid143 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid143 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid142 . +_:genid144 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid140 . +_:genid144 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid143 . +_:genid145 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/abs> . +_:genid145 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid144 . +_:genid146 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid146 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid145 . +_:genid147 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid147 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid146 . +_:genid148 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/notp> . +_:genid148 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid149 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . +_:genid149 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid148 . +_:genid15 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid10 . +_:genid15 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid14 . +_:genid150 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/sub> . +_:genid150 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid151 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid151 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid150 . +_:genid152 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid152 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid151 . +_:genid153 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/lt> . +_:genid153 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid154 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid154 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid153 . +_:genid155 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nil> . +_:genid155 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid156 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/quote> . +_:genid156 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid155 . +_:genid157 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . +_:genid157 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid158 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nil> . +_:genid158 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid157 . +_:genid159 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid159 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid16 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . _:genid16 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid15 . -_:genid17 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . -_:genid17 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid160 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "8"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid160 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid159 . +_:genid161 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid161 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid162 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid162 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid161 . +_:genid163 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid163 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid164 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid164 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid163 . +_:genid165 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid165 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid164 . +_:genid166 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid166 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid165 . +_:genid167 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid167 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid168 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nil> . +_:genid168 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid167 . +_:genid169 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dec> . +_:genid169 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid17 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid17 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid16 . +_:genid170 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/neg> . +_:genid170 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid169 . +_:genid171 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/false> . +_:genid171 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid172 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/true> . +_:genid172 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid173 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . +_:genid173 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid174 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid172 . +_:genid174 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid173 . +_:genid175 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid171 . +_:genid175 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid174 . +_:genid176 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/rest> . +_:genid176 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid177 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/first> . +_:genid177 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid178 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/times> . +_:genid178 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid177 . +_:genid179 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid179 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid178 . _:genid18 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/false> . -_:genid18 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid17 . -_:genid19 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . -_:genid19 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid2 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -_:genid2 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid1 . -_:genid20 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "4"^^<http://www.w3.org/2001/XMLSchema#integer> . -_:genid20 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid19 . -_:genid21 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . -_:genid21 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid22 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid18 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid180 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid176 . +_:genid180 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid179 . +_:genid181 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/notp> . +_:genid181 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid182 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/evenp> . +_:genid182 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid181 . +_:genid183 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . +_:genid183 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid184 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid184 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid183 . +_:genid185 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid185 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid186 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid186 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid185 . +_:genid187 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid187 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid188 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . +_:genid188 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid189 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid187 . +_:genid189 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid188 . +_:genid19 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop2> . +_:genid19 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid18 . +_:genid190 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid186 . +_:genid190 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid189 . +_:genid191 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . +_:genid191 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid190 . +_:genid192 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid192 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid191 . +_:genid193 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid193 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid194 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup2> . +_:genid194 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid193 . +_:genid195 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop2> . +_:genid195 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid196 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup3> . +_:genid196 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid195 . +_:genid197 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/gt> . +_:genid197 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid198 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid198 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid197 . +_:genid199 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nil> . +_:genid199 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid2 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nop> . +_:genid2 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid20 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . +_:genid20 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid200 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop2> . +_:genid200 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid199 . +_:genid201 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/foldl> . +_:genid201 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid202 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/rot> . +_:genid202 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid201 . +_:genid203 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/first> . +_:genid203 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid202 . +_:genid204 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid204 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid203 . +_:genid205 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/rest> . +_:genid205 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid204 . +_:genid206 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . +_:genid206 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid205 . +_:genid207 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . +_:genid207 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid208 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid206 . +_:genid208 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid207 . +_:genid209 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid200 . +_:genid209 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid208 . +_:genid21 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid19 . +_:genid21 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid20 . +_:genid210 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/emptyp> . +_:genid210 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid209 . +_:genid211 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . +_:genid211 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid210 . +_:genid212 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid212 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid211 . +_:genid213 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/halt> . +_:genid213 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid214 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/clear> . +_:genid214 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid213 . +_:genid215 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid215 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid216 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid216 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid215 . +_:genid217 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid217 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid218 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "6"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid218 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid217 . +_:genid219 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid219 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid22 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid17 . _:genid22 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid21 . -_:genid23 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . -_:genid23 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid24 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid220 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "5"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid220 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid219 . +_:genid221 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/list> . +_:genid221 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid222 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/depth> . +_:genid222 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid221 . +_:genid223 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid223 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid224 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "9"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid224 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid223 . +_:genid225 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid225 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid226 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid226 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid225 . +_:genid227 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/times> . +_:genid227 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid228 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid228 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid227 . +_:genid229 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/call> . +_:genid229 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid23 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . +_:genid23 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid22 . +_:genid230 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/over> . +_:genid230 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid229 . +_:genid231 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dec> . +_:genid231 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid230 . +_:genid232 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/zerop> . +_:genid232 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid233 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . +_:genid233 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid232 . +_:genid234 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop2> . +_:genid234 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid235 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/until> . +_:genid235 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid234 . +_:genid236 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid233 . +_:genid236 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid235 . +_:genid237 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid231 . +_:genid237 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid236 . +_:genid238 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/true> . +_:genid238 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid239 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/quote> . +_:genid239 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid238 . +_:genid24 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . _:genid24 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid23 . -_:genid25 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . +_:genid240 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . +_:genid240 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid241 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/true> . +_:genid241 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid240 . +_:genid242 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/times> . +_:genid242 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid243 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid243 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid242 . +_:genid244 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/rest> . +_:genid244 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid245 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid245 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid244 . +_:genid246 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/first> . +_:genid246 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid245 . +_:genid247 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . +_:genid247 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid246 . +_:genid248 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nop> . +_:genid248 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid249 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . +_:genid249 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid25 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/true> . _:genid25 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid26 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -_:genid26 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid25 . -_:genid27 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/cmp> . -_:genid27 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid26 . -_:genid28 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/add> . -_:genid28 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid29 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid250 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid250 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid249 . +_:genid251 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid248 . +_:genid251 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid250 . +_:genid252 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/notp> . +_:genid252 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid253 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/while> . +_:genid253 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid254 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/concat> . +_:genid254 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid253 . +_:genid255 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid252 . +_:genid255 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid254 . +_:genid256 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nop> . +_:genid256 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid257 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . +_:genid257 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid258 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid256 . +_:genid258 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid257 . +_:genid259 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/false> . +_:genid259 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid26 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/false> . +_:genid26 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid260 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid260 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid259 . +_:genid261 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nop> . +_:genid261 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid262 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . +_:genid262 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid263 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid261 . +_:genid263 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid262 . +_:genid264 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid260 . +_:genid264 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid263 . +_:genid265 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid265 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid264 . +_:genid266 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nop> . +_:genid266 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid267 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/false> . +_:genid267 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid268 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid268 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid267 . +_:genid269 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . +_:genid269 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid27 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . +_:genid27 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid270 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid268 . +_:genid270 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid269 . +_:genid271 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid266 . +_:genid271 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid270 . +_:genid272 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . +_:genid272 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid271 . +_:genid273 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid273 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid272 . +_:genid274 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . +_:genid274 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid275 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid273 . +_:genid275 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid274 . +_:genid276 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid265 . +_:genid276 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid275 . +_:genid277 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . +_:genid277 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid276 . +_:genid278 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid278 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid277 . +_:genid279 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . +_:genid279 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid28 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid26 . +_:genid28 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid27 . +_:genid280 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid280 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid279 . +_:genid29 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid25 . _:genid29 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid28 . -_:genid3 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid3 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . _:genid3 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid30 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/falsep> . +_:genid30 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/orp> . _:genid30 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid31 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/exactp> . +_:genid31 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/falsep> . _:genid31 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid30 . -_:genid32 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . -_:genid32 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid33 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "-1"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid32 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid32 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid31 . +_:genid33 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/truep> . _:genid33 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid32 . -_:genid34 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/cmp> . +_:genid34 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . _:genid34 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid33 . -_:genid35 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/add> . +_:genid35 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . _:genid35 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid36 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/over> . +_:genid36 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/cons> . _:genid36 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid35 . -_:genid37 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nip> . -_:genid37 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid38 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/times> . +_:genid37 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/rot> . +_:genid37 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid36 . +_:genid38 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . _:genid38 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid37 . -_:genid39 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid39 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/rest> . _:genid39 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid38 . -_:genid4 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid4 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid2 . _:genid4 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid3 . -_:genid40 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid36 . +_:genid40 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . _:genid40 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid39 . -_:genid41 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/abs> . +_:genid41 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/first> . _:genid41 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid40 . -_:genid42 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid42 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . _:genid42 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid41 . -_:genid43 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . -_:genid43 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid42 . -_:genid44 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/falsep> . -_:genid44 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid45 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . -_:genid45 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid44 . -_:genid46 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/sub> . -_:genid46 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid47 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid43 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/emptyp> . +_:genid43 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid44 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . +_:genid44 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid43 . +_:genid45 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/reverse> . +_:genid45 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid46 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid46 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid45 . +_:genid47 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/until> . _:genid47 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid46 . -_:genid48 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid48 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid44 . _:genid48 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid47 . -_:genid49 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nil> . -_:genid49 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid5 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . -_:genid5 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid50 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/quote> . +_:genid49 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid42 . +_:genid49 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid48 . +_:genid5 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid1 . +_:genid5 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid4 . +_:genid50 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . _:genid50 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid49 . -_:genid51 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . -_:genid51 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid52 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nil> . +_:genid51 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/reverse> . +_:genid51 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid50 . +_:genid52 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . _:genid52 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid51 . -_:genid53 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid53 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/unstack> . _:genid53 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid54 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "8"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid54 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/concat> . _:genid54 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid53 . -_:genid55 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . -_:genid55 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid56 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid55 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/cons> . +_:genid55 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid54 . +_:genid56 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . _:genid56 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid55 . -_:genid57 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . -_:genid57 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid58 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid57 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/length> . +_:genid57 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid56 . +_:genid58 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . _:genid58 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid57 . -_:genid59 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid59 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/stack> . _:genid59 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid58 . -_:genid6 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid6 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/lt> . _:genid6 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid5 . -_:genid60 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . -_:genid60 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid59 . -_:genid61 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . -_:genid61 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid62 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nil> . -_:genid62 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid61 . -_:genid63 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/falsep> . +_:genid60 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/sub> . +_:genid60 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid61 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid61 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid60 . +_:genid62 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid62 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid63 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/twice> . _:genid63 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid64 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/evenp> . +_:genid64 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid62 . _:genid64 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid63 . _:genid65 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . _:genid65 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid66 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup2> . -_:genid66 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid65 . -_:genid67 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop2> . -_:genid67 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid68 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup3> . -_:genid68 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid67 . -_:genid69 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/halt> . -_:genid69 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid7 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid66 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/thrice> . +_:genid66 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid67 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid65 . +_:genid67 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid66 . +_:genid68 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid68 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid69 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "7"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid69 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid68 . +_:genid7 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . _:genid7 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid6 . -_:genid70 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/clear> . -_:genid70 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid69 . -_:genid71 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . -_:genid71 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid72 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . -_:genid72 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid71 . -_:genid73 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . -_:genid73 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid74 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "6"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid70 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/zerop> . +_:genid70 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid71 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/length> . +_:genid71 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid70 . +_:genid72 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/zerop> . +_:genid72 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid73 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/mod> . +_:genid73 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid72 . +_:genid74 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . _:genid74 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid73 . -_:genid75 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid75 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/notp> . _:genid75 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid76 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "5"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid76 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/inexactp> . _:genid76 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid75 . -_:genid77 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid77 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/false> . _:genid77 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid78 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "9"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid78 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/quote> . _:genid78 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid77 . -_:genid79 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid79 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . _:genid79 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid8 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . -_:genid8 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid80 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid8 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . +_:genid8 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid7 . +_:genid80 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/false> . _:genid80 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid79 . -_:genid81 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/times> . +_:genid81 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . _:genid81 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid82 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid82 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "4"^^<http://www.w3.org/2001/XMLSchema#integer> . _:genid82 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid81 . -_:genid83 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/call> . +_:genid83 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . _:genid83 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid84 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/over> . +_:genid84 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . _:genid84 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid83 . -_:genid85 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dec> . -_:genid85 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid84 . -_:genid86 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/zerop> . -_:genid86 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid87 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . -_:genid87 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid86 . -_:genid88 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop2> . -_:genid88 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid89 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/until> . -_:genid89 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid88 . -_:genid9 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "7"^^<http://www.w3.org/2001/XMLSchema#integer> . -_:genid9 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid8 . -_:genid90 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid87 . +_:genid85 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/onep> . +_:genid85 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid86 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/cmp> . +_:genid86 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid85 . +_:genid87 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/add> . +_:genid87 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid88 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid88 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid87 . +_:genid89 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/notp> . +_:genid89 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid9 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid9 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid90 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/exactp> . _:genid90 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid89 . -_:genid91 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid85 . -_:genid91 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid90 . -_:genid92 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/true> . -_:genid92 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid93 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/quote> . +_:genid91 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/div> . +_:genid91 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid92 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "0.0"^^<http://www.w3.org/2001/XMLSchema#decimal> . +_:genid92 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid91 . +_:genid93 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "1.0"^^<http://www.w3.org/2001/XMLSchema#decimal> . _:genid93 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid92 . _:genid94 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . _:genid94 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid95 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/true> . +_:genid95 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/inf> . _:genid95 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid94 . -_:genid96 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/times> . -_:genid96 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid97 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . -_:genid97 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid96 . -_:genid98 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nop> . -_:genid98 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . -_:genid99 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . -_:genid99 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid96 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/abs> . +_:genid96 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid95 . +_:genid97 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/inc> . +_:genid97 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid98 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid98 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid97 . +_:genid99 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/rest> . +_:genid99 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid98 . diff --git a/etc/trith-lang.nt b/etc/trith-lang.nt new file mode 100644 index 0000000..0b3c4d2 --- /dev/null +++ b/etc/trith-lang.nt @@ -0,0 +1,39 @@ +<http://trith.org/lang/> <http://purl.org/dc/terms/creator> "Arto Bendiken" . +<http://trith.org/lang/> <http://purl.org/dc/terms/modified> "2010-05-23" . +<http://trith.org/lang/> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Ontology> . +<http://trith.org/lang/> <http://www.w3.org/2000/01/rdf-schema#comment> "Trith vocabulary."@en . +<http://trith.org/lang/> <http://www.w3.org/2000/01/rdf-schema#label> "Trith" . +<http://trith.org/lang/> <http://www.w3.org/2000/01/rdf-schema#seeAlso> <http://datagraph.org/bendiken/foaf> . +<http://trith.org/lang/> <http://xmlns.com/foaf/0.1/maker> <http://ar.to/#self> . +<http://trith.org/lang/Function> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2000/01/rdf-schema#Class> . +<http://trith.org/lang/Function> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> . +<http://trith.org/lang/Function> <http://www.w3.org/2000/01/rdf-schema#comment> ""@en . +<http://trith.org/lang/Function> <http://www.w3.org/2000/01/rdf-schema#isDefinedBy> <http://trith.org/lang/> . +<http://trith.org/lang/Function> <http://www.w3.org/2000/01/rdf-schema#label> "Function" . +<http://trith.org/lang/Function> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://trith.org/lang/Operator> . +<http://trith.org/lang/Operator> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2000/01/rdf-schema#Class> . +<http://trith.org/lang/Operator> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> . +<http://trith.org/lang/Operator> <http://www.w3.org/2000/01/rdf-schema#comment> ""@en . +<http://trith.org/lang/Operator> <http://www.w3.org/2000/01/rdf-schema#isDefinedBy> <http://trith.org/lang/> . +<http://trith.org/lang/Operator> <http://www.w3.org/2000/01/rdf-schema#label> "Operator" . +<http://trith.org/lang/Operator> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://www.w3.org/2000/01/rdf-schema#Resource> . +<http://trith.org/lang/Primitive> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2000/01/rdf-schema#Class> . +<http://trith.org/lang/Primitive> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> . +<http://trith.org/lang/Primitive> <http://www.w3.org/2000/01/rdf-schema#comment> ""@en . +<http://trith.org/lang/Primitive> <http://www.w3.org/2000/01/rdf-schema#isDefinedBy> <http://trith.org/lang/> . +<http://trith.org/lang/Primitive> <http://www.w3.org/2000/01/rdf-schema#label> "Primitive" . +<http://trith.org/lang/Primitive> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://trith.org/lang/Operator> . +<http://trith.org/lang/arity> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> . +<http://trith.org/lang/arity> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#DatatypeProperty> . +<http://trith.org/lang/arity> <http://www.w3.org/2000/01/rdf-schema#comment> ""@en . +<http://trith.org/lang/arity> <http://www.w3.org/2000/01/rdf-schema#domain> <http://trith.org/lang/Operator> . +<http://trith.org/lang/arity> <http://www.w3.org/2000/01/rdf-schema#isDefinedBy> <http://trith.org/lang/> . +<http://trith.org/lang/arity> <http://www.w3.org/2000/01/rdf-schema#label> "label" . +<http://trith.org/lang/arity> <http://www.w3.org/2000/01/rdf-schema#range> <http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> . +<http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#ObjectProperty> . +<http://trith.org/lang/code> <http://www.w3.org/2000/01/rdf-schema#comment> ""@en . +<http://trith.org/lang/code> <http://www.w3.org/2000/01/rdf-schema#domain> <http://trith.org/lang/Operator> . +<http://trith.org/lang/code> <http://www.w3.org/2000/01/rdf-schema#isDefinedBy> <http://trith.org/lang/> . +<http://trith.org/lang/code> <http://www.w3.org/2000/01/rdf-schema#label> "code" . +<http://trith.org/lang/code> <http://www.w3.org/2000/01/rdf-schema#range> <http://www.w3.org/1999/02/22-rdf-syntax-ns#List> .
trith/trith
ccd2099e105f341bedd76807aab7eba601da359d
Fixed the Trith::Cache specs.
diff --git a/spec/cache_spec.rb b/spec/cache_spec.rb index cdf50d5..5e08f45 100644 --- a/spec/cache_spec.rb +++ b/spec/cache_spec.rb @@ -1,43 +1,43 @@ require File.join(File.dirname(__FILE__), 'spec_helper') describe Trith::Cache do - before :each do - @cache = Trith::Cache.load(File.join(File.dirname(__FILE__), '..', 'etc', 'cache.nt')) + before :all do + @cache = Trith::Cache.load(File.join(File.dirname(__FILE__), '..', 'etc', 'trith-core.nt')) end it "should be an RDF repository" do @cache.should be_an(RDF::Repository) end it "should know whether a given function is cached" do @cache.should respond_to(:has_function?) @cache.should have_function(Trith::Function.new("http://trith.org/core/dup")) @cache.should have_function(RDF::URI("http://trith.org/core/dup")) @cache.should_not have_function(Trith::Function.new) @cache.should_not have_function(RDF::URI("http://example.org/myfunction")) @cache.should_not have_function(RDF::Node.new) end it "should know whether a function with a given label is cached" do @cache.should respond_to(:has_label?) - @cache.should have_label(:boolean?) + @cache.should have_label(:bool?) @cache.should_not have_label(:foobar) end it "should enumerate the cached functions" do @cache.should respond_to(:each_function) @cache.each_function do |function| function.should be_a(Trith::Function) end @cache.each_function.should be_a(RDF::Enumerator) end it "should find cached functions by their labels" do @cache.should respond_to(:find_functions) @cache.find_functions do |function| function.should be_a(Trith::Function) end @cache.find_functions.should be_a(RDF::Enumerator) @cache.find_functions(:label => :dup).to_a.size.should == 1 end end
trith/trith
13ba833f44594d946129ea2e80ad40f358a84fbb
Added some 3vm scripting examples.
diff --git a/README.md b/README.md index 95c6057..107b3fa 100644 --- a/README.md +++ b/README.md @@ -1,315 +1,338 @@ Trith: Recombinant Programming ============================== Trith is an experimental [concatenative][concat.org] programming language founded on the [unholy][lispers.org] trinity of [Forth][], [Lisp][] and [RDF][] triples. * <http://trith.org/> * <http://github.com/trith/trith> Description ----------- Trith is a stack-based, concatenative, dynamically-typed functional programming language with a homoiconic program representation. * [Stack-based][stack-oriented] means that instead of having named parameters, Trith functions operate on an implicit data structure called the _operand stack_. Trith functions can be thought of in terms of popping and pushing operands from/onto this stack, or equivalently in purely functional terms as unary functions that map from one stack to another. * [Concatenative][concatenative] means that the concatenation of any two Trith functions also denotes the [composition][] of those functions. * [Dynamically typed][type system] means that operands to Trith functions are type-checked dynamically at runtime. * [Homoiconic][homoiconic] means that in Trith there is no difference between code and data. You can manipulate and construct code at runtime as easily as you would manipulate any other data structure, enabling powerful metaprogramming facilities. Trith programs are simply nested lists of operators and operands, and can be represented externally either as [S-expressions][S-expression] or as [RDF][] triples. Trith is inspired and influenced by experience with [Forth][], [Lisp][] and [Scheme][] in general, and the concatenative languages [Joy][], [XY][], [Factor][] and [Cat][] in particular. Introduction ------------ The Trith implementation currently consists of a virtual machine, interpreter, and compiler toolchain written in Ruby and an in-the-works runtime targeting the [JVM][]. You can use the Trith shell `3sh` to explore Trith interactively: $ 3sh >> "Hello, world!" print Hello, world! For example, here's how you would start with two prime numbers and end up with the correct answer to the ultimate question of life, the universe, and everything: $ 3sh >> 3 7 swap dup + * => [42] : [] In the above `3sh` examples, `>>` indicates lines that you type, and `=>` indicates the result from the shell. After each input line is evaluated, the shell will show you the current state of the Trith virtual machine's data stack and code queue. Thus in our previous example, the `[42]` on the left-hand side shows that the machine's stack contains a single operand, the number 42. The `[]` on the right-hand side shows that the machine's code queue is empty, which is generally the case after all input has been successfully evaluated. Let's run through the above example one more time using the `--debug` option to `3sh`, which enables the tracing of each queue reduction step in the virtual machine: $ 3sh --debug >> 3 7 swap dup + * .. [] : [3 7 swap dup + *] .. [3] : [7 swap dup + *] .. [3 7] : [swap dup + *] .. [7 3] : [dup + *] .. [7 3 3] : [+ *] .. [7 6] : [*] => [42] : [] As you can see, the virtual machine starts execution with an empty operand stack on the left-hand side and with all input placed onto the operator queue on the right-hand side. When input operands such as numbers are encountered on the queue, they are simply pushed onto the stack, which grows from left to right. When an operator such as the multiplication operator `*` is encountered on the queue, it is executed. Operators pop operands from the stack and then push their result(s) back onto the stack. When fooling around in the Trith shell, two useful operators to know are `clear`, which clears the stack, and `halt`, which clears the queue (thus halting execution). You can also use `reset` which does both in one step, returning you to a guaranteed clean slate. To get a listing of all operators supported in the current release, enter the `?` metacommand in the Trith shell. Linked Code ----------- All Trith operators are identified by URIs, meaning that Trith code can be straightforwardly represented as [Linked Data][]. Here's an example of the `abs` operator defined metacircularly using the Turtle serialization format for RDF data: @base <http://trith.org/core/> . @prefix trith: <http://trith.org/lang/> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . <abs> a trith:Function ; rdfs:label "abs" ; rdfs:comment "Returns the absolute value of a number."@en ; trith:arity 1 ; trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . This function description comprises a total of 21 triples. The entire Trith core library currently weighs in at about a kilotriple (1,000 triples), with all but a handful of primitive (irreducible) operators having a metacircular definition. See `etc/trith-core.ttl` for the RDF definitions of Trith core operators. Reference --------- ### Sequences Trith has a rich set of sequence operators that will be instantly familiar to programmers coming from functional programming languages such as Scheme, Clojure or Haskell: >> 10 iota => [[0 1 2 3 4 5 6 7 8 9]] : [] >> dup seq? . true >> dup empty? . false >> dup length . 10 >> [dup mul] map => [[0 1 4 9 16 25 36 49 64 81]] : [] >> dup first . 0 >> dup fifth . 16 >> dup 7 nth . 49 >> dup last . 81 >> dup 0 [+] foldl . 285 >> rest => [[1 4 9 16 25 36 49 64 81]] : [] >> dup 1 [*] foldl . 131681894400 >> reverse => [[81 64 49 36 25 16 9 4 1]] : [] ### Strings Strings are simply sequences of characters (Unicode code points), meaning that you can make use of any of the normal sequence operators on strings as well: >> : hello "Hello," " world!" concat ; >> hello seq? . true >> hello text? . true >> hello empty? . false >> hello length . 13 >> hello first . H >> hello rest . ello, world! >> hello reverse . !dlrow ,olleH +Scripting +--------- + +The canonical "Hello, world!" script is found in `doc/examples/hello.3th`: + + #!/usr/bin/env 3vm + "Hello, world!" print + +Any command-line arguments passed to 3VM scripts form the initial stack of +the virtual machine. The arguments are placed on the stack in their original +unparsed string form. + +You can print out the contents of the initial stack like so: + + #!/usr/bin/env 3vm + stack print + +Here's an example of how you would interpret all given command-line +arguments as numbers and then sum them up and print out the result: + + #!/usr/bin/env 3vm + stack [num] map 0 [+] foldl print + Embedding --------- ### Embedding Trith in Ruby require 'trith' # Let's start with the obligatory "Hello, world!" example: Trith::Machine.run do push "Hello, world!" print end # There are several equivalent ways to execute Trith code: Trith::Machine.run { push(6, 7).mul } #=> 42 Trith::Machine.run [6, 7] { mul } #=> 42 Trith::Machine.run [6, 7, :mul] #=> 42 # Operators in Ruby blocks can be chained together: Trith::Machine.run { push(2).dup.dup.mul.pow } #=> 16 # If you require more control, instantiate a machine manually: vm = Trith::Machine.new vm.define!(:square) { dup.mul } vm.push(10).square.peek #=> 100 # You can also define operators when constructing a machine: vm = Trith::Machine.new(data = [], code = [], { :hello => proc { push("Hello, world!").print }, }) # Should you want to use any Trith functions from Ruby, it's easy enough # to encapsulate a virtual machine inside a Ruby method: def square(n) Trith::Machine.run [n] { dup.mul } end square(10) #=> 100 ### Embedding Trith in JVM-based languages The [JVM][] runtime for Trith is a work in progress. See `src/java` for the runtime's source code and current status. Dependencies ------------ * [Ruby](http://ruby-lang.org/) (>= 1.9.1) or [JRuby](http://jruby.org/) (>= 1.4.0) * [RDF.rb](http://rubygems.org/gems/rdf) (>= 0.1.9) * [SXP](http://rubygems.org/gems/sxp) (>= 0.0.3) * [Promise](http://rubygems.org/gems/promise) (>= 0.1.0) Installation ------------ The recommended installation method is via [RubyGems](http://rubygems.org/). To install the latest official release of the `trith` gem, do one of the following: $ [sudo] gem install trith # Ruby 1.9+ $ [sudo] gem1.9 install trith # Ruby 1.9 with MacPorts $ [sudo] jruby --1.9 -S gem install trith # JRuby 1.4+ Once Trith is installed, you will have four new programs available: * `3sh`, aka "trish", is the Trith interactive shell and interpreter. * `3vm`, aka "trivium", is the Trith virtual machine runtime. * `3cc`, aka "tricksy", is the Trith compiler. * `3th`, aka "trith", is the Trith package manager. Note that as of the current release, only the first two do anything much as yet. Environment ----------- The following are the default settings for environment variables that let you customize how Trith works: $ export TRITH_HOME=~/.trith $ export TRITH_CACHE=$TRITH_HOME/cache $ export TRITH_TERM=$TERM Download -------- To get a local working copy of the development repository, do: $ git clone git://github.com/trith/trith.git Alternatively, you can download the latest development version as a tarball as follows: $ wget http://github.com/trith/trith/tarball/master Mailing List ------------ * <http://groups.google.com/group/trith> Authors ------- * [Arto Bendiken](mailto:[email protected]) - <http://ar.to/> License ------- Trith is free and unencumbered public domain software. For more information, see <http://unlicense.org/> or the accompanying UNLICENSE file. [stack-oriented]: http://en.wikipedia.org/wiki/Stack-oriented_programming_language [concatenative]: http://en.wikipedia.org/wiki/Concatenative_programming_language [composition]: http://en.wikipedia.org/wiki/Function_composition [type system]: http://en.wikipedia.org/wiki/Type_system#Dynamic_typing [homoiconic]: http://en.wikipedia.org/wiki/Homoiconicity [S-expression]: http://en.wikipedia.org/wiki/S-expression [RDF]: http://en.wikipedia.org/wiki/Resource_Description_Framework [JVM]: http://en.wikipedia.org/wiki/Java_Virtual_Machine [Lisp]: http://en.wikipedia.org/wiki/Lisp_(programming_language) [Scheme]: http://en.wikipedia.org/wiki/Scheme_(programming_language) [Forth]: http://en.wikipedia.org/wiki/Forth_(programming_language) [Factor]: http://en.wikipedia.org/wiki/Factor_(programming_language) [Joy]: http://en.wikipedia.org/wiki/Joy_(programming_language) [Cat]: http://en.wikipedia.org/wiki/Cat_(programming_language) [XY]: http://www.nsl.com/k/xy/xy.htm [Linked Data]: http://linkeddata.org/ [lispers.org]: http://lispers.org/ [concat.org]: http://concatenative.org/wiki/view/Concatenative%20language diff --git a/doc/examples/args.3th b/doc/examples/args.3th new file mode 100755 index 0000000..85a6b72 --- /dev/null +++ b/doc/examples/args.3th @@ -0,0 +1,2 @@ +#!/usr/bin/env 3vm +stack print diff --git a/doc/examples/hello.rb b/doc/examples/hello.rb deleted file mode 100755 index db8580a..0000000 --- a/doc/examples/hello.rb +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env ruby -rubygems -require 'trith' - -Trith::Machine.run do - push("Hello, world!") - print -end diff --git a/doc/examples/sum.3th b/doc/examples/sum.3th new file mode 100755 index 0000000..3aeccfd --- /dev/null +++ b/doc/examples/sum.3th @@ -0,0 +1,2 @@ +#!/usr/bin/env 3vm +stack [num] map 0 [+] foldl print
trith/trith
2d3093c33645a4ec0a2ea2b175938d610ed036fb
Made ARGV the initial stack for Trith scripts.
diff --git a/bin/3vm b/bin/3vm index a199f8f..ff1beb6 100755 --- a/bin/3vm +++ b/bin/3vm @@ -1,38 +1,43 @@ #!/usr/bin/env ruby1.9 -rubygems $:.unshift(File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))) require 'trith' -BANNER = "Usage: #{File.basename($0)} [options] files..." +BANNER = "Usage: #{File.basename($0)} [options] file [args...]" case when %w(-V -v --version).any? { |opt| ARGV.include?(opt) } $stdout.puts Trith::VERSION.to_s exit when %w(-? -h --help).any? { |opt| ARGV.include?(opt) } $stdout.puts BANNER exit when ARGV.empty? abort BANNER end begin $machine = Trith::Machine.new $cache = Trith::Cache.load_core $machine.import!(Trith::Core) begin - ARGV.each do |file| - $machine.execute(Trith::Reader.read_file(file)) + case + when split = ARGV.index('--') + ARGV.delete_at(split) + $machine.push(*ARGV.slice!(split, ARGV.size - split)) + when ARGV.size > 1 + $machine.push(*ARGV.slice!(1, ARGV.size - 1)) end + $machine.execute(Trith::Reader.read_files(*ARGV)) rescue Trith::Machine::InvalidOperatorError => e $stderr.puts Trith::Shell.format_error(e) rescue Trith::Machine::InvalidOperandError => e $stderr.puts Trith::Shell.format_error(e) rescue Trith::Machine::StackUnderflowError => e $stderr.puts Trith::Shell.format_error("stack underflow") end exit([255, $machine.stack.size].min) rescue Interrupt abort '' # abort due to ^C (SIGINT) end
trith/trith
ab14553b36dd20bd68d7445c436e700245eeaead
Added a trith.lang.Machine#push(Object) method for convenience.
diff --git a/src/java/trith/lang/Machine.java b/src/java/trith/lang/Machine.java index 0f4bf84..bf8e6fd 100644 --- a/src/java/trith/lang/Machine.java +++ b/src/java/trith/lang/Machine.java @@ -1,23 +1,24 @@ package trith.lang; import java.util.concurrent.Future; import java.util.concurrent.Callable; /** * @author Arto Bendiken */ public interface Machine { public void execute(); public void execute(Operator operator); public Future<?> submit(Callable<?> callable); public void halt(); public Object shift(); public void unshift(Operator op); public boolean empty(); public <T> T get(); public <T> Future<T> peek(); public <T> Future<T> pop(); public void push(Future<?> value); public void push(Callable<?> callable); + public void push(Object value); }
trith/trith
863ee34ed51d31173ff3434f472756873fef278a
Made ARGV the initial stack for compiled Trith programs.
diff --git a/lib/trith/compiler/java.rb b/lib/trith/compiler/java.rb index 5ee48b2..2fa7cf2 100644 --- a/lib/trith/compiler/java.rb +++ b/lib/trith/compiler/java.rb @@ -1,97 +1,100 @@ module Trith; class Compiler ## # A Trith-to-Java compiler. class Java < Compiler ## # @param [Hash{Symbol => Object}] options def initialize(options = {}) super(options) @options[:class] ||= 'a' @output = StringIO.new end ## # @return [String] def to_s output = StringIO.new output.puts "package #{@options[:package]};" if @options[:package] output.puts "import trith.lang.*;" output.puts "import trith.core.*;" output.puts output.puts "public class #{@options[:class]} implements Operator {" output.puts " public static void main(String[] args) {" - output.puts " Operator self = new #{@options[:class]}();" - output.puts " self.execute(new StandardMachine());" + output.puts " Machine machine = new StandardMachine();" + output.puts " for (String arg : args) {" + output.puts " machine.push(arg);" + output.puts " }" + output.puts " machine.execute(new #{@options[:class]}());" output.puts " }" output.puts output.puts " public void execute(Machine machine) {" output.write @output.string output.puts " }" output.puts "}" output.string end protected ## # @see Trith::Compiler#compile_operator # @private def compile_operator(operator) - emit("machine.#{operator}();") # FIXME + emit("machine.execute(new trith.core.#{operator}());") # FIXME end ## # @see Trith::Compiler#compile_nil # @private def compile_nil(operand = nil) emit("machine.push(null);") end ## # @see Trith::Compiler#compile_boolean # @private def compile_boolean(operand) emit("machine.push(#{operand});") end ## # @see Trith::Compiler#compile_number # @private def compile_number(operand) emit("machine.push(#{operand});") # FIXME end alias_method :compile_integer, :compile_number alias_method :compile_float, :compile_number alias_method :compile_decimal, :compile_number alias_method :compile_rational, :compile_number ## # @see Trith::Compiler#compile_string # @private def compile_string(operand) emit("machine.push(#{operand.inspect});") # FIXME end ## # @see Trith::Compiler#compile_reference # @private def compile_reference(operand) emit("machine.push(#{operand.to_s.inspect});") # FIXME end ## # @see Trith::Compiler#compile_quotation # @private def compile_quotation(operand) emit("machine.push(#{operand.inspect});") # FIXME end ## # @param [String, #to_s] line # @return [void] def emit(line) @output.puts(" " << line.to_s) end end # class Java end; end # class Trith::Compiler diff --git a/lib/trith/compiler/ruby.rb b/lib/trith/compiler/ruby.rb index 6f35608..e9eb33e 100644 --- a/lib/trith/compiler/ruby.rb +++ b/lib/trith/compiler/ruby.rb @@ -1,92 +1,92 @@ module Trith; class Compiler ## # A Trith-to-Ruby compiler. class Ruby < Compiler SHEBANG = "#!/usr/bin/env ruby -rubygems" ## # @param [Hash{Symbol => Object}] options def initialize(options = {}) super(options) @options[:shebang] ||= SHEBANG @output = StringIO.new end ## # @return [String] def to_s output = StringIO.new output.puts @options[:shebang] output.puts "require 'rubygems'" if @options[:rubygems] output.puts "require 'trith'" output.puts - output.puts "Trith::Machine.run do" + output.puts "Trith::Machine.run(ARGV) do" output.write @output.string output.puts "end" output.string end protected ## # @see Trith::Compiler#compile_operator # @private def compile_operator(operator) emit("call(:#{operator}).execute") end ## # @see Trith::Compiler#compile_nil # @private def compile_nil(operand = nil) emit("push(nil)") end ## # @see Trith::Compiler#compile_boolean # @private def compile_boolean(operand) emit("push(#{operand})") end ## # @see Trith::Compiler#compile_number # @private def compile_number(operand) emit("push(#{operand})") end alias_method :compile_integer, :compile_number alias_method :compile_float, :compile_number alias_method :compile_decimal, :compile_number alias_method :compile_rational, :compile_number ## # @see Trith::Compiler#compile_string # @private def compile_string(operand) emit("push(#{operand.inspect})") end ## # @see Trith::Compiler#compile_reference # @private def compile_reference(operand) emit("push(Trith::URI.new(#{operand.to_s.inspect}))") end ## # @see Trith::Compiler#compile_quotation # @private def compile_quotation(operand) emit("push(#{operand.inspect})") end ## # @param [String, #to_s] line # @return [void] def emit(line) @output.puts(" " << line.to_s) end end # class Ruby end; end # class Trith::Compiler
trith/trith
c79aa46efcfbc397f45066720caaf887b8fc3881
Implemented a Trith::Compiler::Java target stub.
diff --git a/lib/trith/compiler.rb b/lib/trith/compiler.rb index e987351..2e99170 100644 --- a/lib/trith/compiler.rb +++ b/lib/trith/compiler.rb @@ -1,198 +1,200 @@ module Trith ## # A base class for Trith compiler targets. # # @abstract class Compiler autoload :Ruby, 'trith/compiler/ruby' + autoload :Java, 'trith/compiler/java' # @return [Hash{Symbol => Object}] attr_reader :options ## # @param [Symbol, #to_sym] target # @return [Class] def self.for(target = nil, &block) target = block.call if block_given? case target.to_sym when :ruby then Ruby + when :java then Java else nil end end ## # @param [Array<String>] filenames # @param [Hash{Symbol => Object}] options # @return [Compiler] def self.compile_files(*filenames) options = filenames.last.is_a?(Hash) ? filenames.peek : {} self.compile(Reader.read_files(*filenames), options) end ## # @param [Enumerable] program # @param [Hash{Symbol => Object}] options # @return [Compiler] def self.compile(program, options = {}) self.new(options).compile(program, options) end ## # @param [Hash{Symbol => Object}] options def initialize(options = {}) @options = options.to_hash.dup end ## # @param [Enumerable] program # @param [Hash{Symbol => Object}] options # @return [Compiler] def compile(program, options = {}) program = program.respond_to?(:each) ? program : [program] program.each { |op| compile_operand(op) } self end protected ## # @param [Object] operand # @return [void] def compile_operand(operand) case operand when Symbol compile_operator(operand) when NilClass compile_nil(operand) when TrueClass, FalseClass compile_boolean(operand) when Numeric compile_number(operand) when String compile_string(operand) when URI compile_reference(operand) when Array, SXP::List compile_quotation(operand) when Machine, Function compile_quotation(operand.to_a) else raise NotImplementedError.new("#{self.class}#compile_operand(#{operand.inspect})") end end ## # @param [Symbol, #to_sym] operator # @return [void] # @abstract def compile_operator(operator) case operator.to_sym when :nil then compile_nil(nil) when :false then compile_boolean(false) when :true then compile_boolean(true) else raise NotImplementedError.new("#{self.class}#compile_operator(#{operator.inspect})") end end ## # @param [NilClass] operand # @return [void] # @abstract def compile_nil(operand = nil) raise NotImplementedError.new("#{self.class}#compile_nil") end ## # @param [Boolean] operand # @return [void] # @abstract def compile_boolean(operand) raise NotImplementedError.new("#{self.class}#compile_boolean(#{operand.inspect})") end ## # @param [Numeric] operand # @return [void] # @abstract def compile_number(operand) case operand when Integer compile_integer(operand) when Float compile_float(operand) when BigDecimal compile_decimal(operand) when Rational compile_rational(operand) else raise NotImplementedError.new("#{self.class}#compile_number(#{operand.inspect})") end end ## # @param [Integer] operand # @return [void] # @abstract def compile_integer(operand) raise NotImplementedError.new("#{self.class}#compile_integer(#{operand.inspect})") end ## # @param [Float] operand # @return [void] # @abstract def compile_float(operand) raise NotImplementedError.new("#{self.class}#compile_float(#{operand.inspect})") end ## # @param [BigDecimal] operand # @return [void] # @abstract def compile_decimal(operand) raise NotImplementedError.new("#{self.class}#compile_decimal(#{operand.inspect})") end ## # @param [Rational] operand # @return [void] # @abstract def compile_rational(operand) raise NotImplementedError.new("#{self.class}#compile_rational(#{operand.inspect})") end ## # @param [String] operand # @return [void] # @abstract def compile_string(operand) raise NotImplementedError.new("#{self.class}#compile_string(#{operand.inspect})") end ## # @param [URI] operand # @return [void] # @abstract def compile_reference(operand) raise NotImplementedError.new("#{self.class}#compile_reference(#{operand.inspect})") end ## # @param [Array] operand # @return [void] # @abstract def compile_quotation(operand) raise NotImplementedError.new("#{self.class}#compile_quotation(#{operand.inspect})") end ## # @private def self.inherited(subclass) subclass.send(:public_class_method, :new) super end # Prevent the instantiation of this class: private_class_method :new end # class Compiler end # module Trith diff --git a/lib/trith/compiler/java.rb b/lib/trith/compiler/java.rb new file mode 100644 index 0000000..5ee48b2 --- /dev/null +++ b/lib/trith/compiler/java.rb @@ -0,0 +1,97 @@ +module Trith; class Compiler + ## + # A Trith-to-Java compiler. + class Java < Compiler + ## + # @param [Hash{Symbol => Object}] options + def initialize(options = {}) + super(options) + @options[:class] ||= 'a' + @output = StringIO.new + end + + ## + # @return [String] + def to_s + output = StringIO.new + output.puts "package #{@options[:package]};" if @options[:package] + output.puts "import trith.lang.*;" + output.puts "import trith.core.*;" + output.puts + output.puts "public class #{@options[:class]} implements Operator {" + output.puts " public static void main(String[] args) {" + output.puts " Operator self = new #{@options[:class]}();" + output.puts " self.execute(new StandardMachine());" + output.puts " }" + output.puts + output.puts " public void execute(Machine machine) {" + output.write @output.string + output.puts " }" + output.puts "}" + output.string + end + + protected + + ## + # @see Trith::Compiler#compile_operator + # @private + def compile_operator(operator) + emit("machine.#{operator}();") # FIXME + end + + ## + # @see Trith::Compiler#compile_nil + # @private + def compile_nil(operand = nil) + emit("machine.push(null);") + end + + ## + # @see Trith::Compiler#compile_boolean + # @private + def compile_boolean(operand) + emit("machine.push(#{operand});") + end + + ## + # @see Trith::Compiler#compile_number + # @private + def compile_number(operand) + emit("machine.push(#{operand});") # FIXME + end + + alias_method :compile_integer, :compile_number + alias_method :compile_float, :compile_number + alias_method :compile_decimal, :compile_number + alias_method :compile_rational, :compile_number + + ## + # @see Trith::Compiler#compile_string + # @private + def compile_string(operand) + emit("machine.push(#{operand.inspect});") # FIXME + end + + ## + # @see Trith::Compiler#compile_reference + # @private + def compile_reference(operand) + emit("machine.push(#{operand.to_s.inspect});") # FIXME + end + + ## + # @see Trith::Compiler#compile_quotation + # @private + def compile_quotation(operand) + emit("machine.push(#{operand.inspect});") # FIXME + end + + ## + # @param [String, #to_s] line + # @return [void] + def emit(line) + @output.puts(" " << line.to_s) + end + end # class Java +end; end # class Trith::Compiler
trith/trith
47b7ff4d8f05cca8ccba959c9de1ee60f40bb34c
Implemented a Trith::Compiler::Ruby target.
diff --git a/bin/3cc b/bin/3cc index ee1edd9..33c15bc 100755 --- a/bin/3cc +++ b/bin/3cc @@ -1,40 +1,25 @@ #!/usr/bin/env ruby1.9 -rubygems $:.unshift(File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))) require 'trith' BANNER = "Usage: #{File.basename($0)} [options] files..." case when %w(-V -v --version).any? { |opt| ARGV.include?(opt) } $stdout.puts Trith::VERSION.to_s exit when %w(-? -h --help).any? { |opt| ARGV.include?(opt) } $stdout.puts BANNER exit when ARGV.empty? abort BANNER # FIXME: read from stdin end begin - $compiler = Trith::Compiler.for(:ruby).new - code = Trith::Reader.read_files(*ARGV) - File.open('a.rb', 'w+', 0755) do |output| - output.puts "#!/usr/bin/env ruby -rubygems" - output.puts "require 'trith'" - output.puts - output.puts "Trith::Machine.run do" - code.each do |op| - case op - when Symbol - output.puts " call(:#{op}).execute" - else - output.puts " push(#{op.inspect})" - end - end - output.puts "end" - end + $compiler = Trith::Compiler.for(:ruby).compile_files(*ARGV) + File.open('a.rb', 'w+', 0755) { |output| output.write($compiler.to_s) } rescue SystemCallError => e abort "#{File.basename($0)}: #{e}" # abort due to e.g. Errno::ENOENT rescue Interrupt abort '' # abort due to ^C (SIGINT) end diff --git a/lib/trith/compiler.rb b/lib/trith/compiler.rb index 5603565..e987351 100644 --- a/lib/trith/compiler.rb +++ b/lib/trith/compiler.rb @@ -1,193 +1,198 @@ module Trith ## # A base class for Trith compiler targets. # # @abstract class Compiler + autoload :Ruby, 'trith/compiler/ruby' + # @return [Hash{Symbol => Object}] attr_reader :options ## # @param [Symbol, #to_sym] target # @return [Class] def self.for(target = nil, &block) target = block.call if block_given? - self # TODO + case target.to_sym + when :ruby then Ruby + else nil + end end ## # @param [Array<String>] filenames # @param [Hash{Symbol => Object}] options # @return [Compiler] def self.compile_files(*filenames) options = filenames.last.is_a?(Hash) ? filenames.peek : {} self.compile(Reader.read_files(*filenames), options) end ## # @param [Enumerable] program # @param [Hash{Symbol => Object}] options # @return [Compiler] def self.compile(program, options = {}) self.new(options).compile(program, options) end ## # @param [Hash{Symbol => Object}] options def initialize(options = {}) - @options = options + @options = options.to_hash.dup end ## # @param [Enumerable] program # @param [Hash{Symbol => Object}] options # @return [Compiler] def compile(program, options = {}) program = program.respond_to?(:each) ? program : [program] program.each { |op| compile_operand(op) } self end protected ## # @param [Object] operand # @return [void] def compile_operand(operand) case operand when Symbol compile_operator(operand) when NilClass compile_nil(operand) when TrueClass, FalseClass compile_boolean(operand) when Numeric compile_number(operand) when String compile_string(operand) when URI compile_reference(operand) when Array, SXP::List compile_quotation(operand) when Machine, Function compile_quotation(operand.to_a) else raise NotImplementedError.new("#{self.class}#compile_operand(#{operand.inspect})") end end ## # @param [Symbol, #to_sym] operator # @return [void] # @abstract def compile_operator(operator) case operator.to_sym when :nil then compile_nil(nil) when :false then compile_boolean(false) when :true then compile_boolean(true) else raise NotImplementedError.new("#{self.class}#compile_operator(#{operator.inspect})") end end ## # @param [NilClass] operand # @return [void] # @abstract def compile_nil(operand = nil) raise NotImplementedError.new("#{self.class}#compile_nil") end ## # @param [Boolean] operand # @return [void] # @abstract def compile_boolean(operand) raise NotImplementedError.new("#{self.class}#compile_boolean(#{operand.inspect})") end ## # @param [Numeric] operand # @return [void] # @abstract def compile_number(operand) case operand when Integer compile_integer(operand) when Float compile_float(operand) when BigDecimal compile_decimal(operand) when Rational compile_rational(operand) else raise NotImplementedError.new("#{self.class}#compile_number(#{operand.inspect})") end end ## # @param [Integer] operand # @return [void] # @abstract def compile_integer(operand) raise NotImplementedError.new("#{self.class}#compile_integer(#{operand.inspect})") end ## # @param [Float] operand # @return [void] # @abstract def compile_float(operand) raise NotImplementedError.new("#{self.class}#compile_float(#{operand.inspect})") end ## # @param [BigDecimal] operand # @return [void] # @abstract def compile_decimal(operand) raise NotImplementedError.new("#{self.class}#compile_decimal(#{operand.inspect})") end ## # @param [Rational] operand # @return [void] # @abstract def compile_rational(operand) raise NotImplementedError.new("#{self.class}#compile_rational(#{operand.inspect})") end ## # @param [String] operand # @return [void] # @abstract def compile_string(operand) raise NotImplementedError.new("#{self.class}#compile_string(#{operand.inspect})") end ## # @param [URI] operand # @return [void] # @abstract def compile_reference(operand) raise NotImplementedError.new("#{self.class}#compile_reference(#{operand.inspect})") end ## # @param [Array] operand # @return [void] # @abstract def compile_quotation(operand) raise NotImplementedError.new("#{self.class}#compile_quotation(#{operand.inspect})") end ## # @private def self.inherited(subclass) subclass.send(:public_class_method, :new) super end # Prevent the instantiation of this class: - #private_class_method :new + private_class_method :new end # class Compiler end # module Trith diff --git a/lib/trith/compiler/ruby.rb b/lib/trith/compiler/ruby.rb new file mode 100644 index 0000000..6f35608 --- /dev/null +++ b/lib/trith/compiler/ruby.rb @@ -0,0 +1,92 @@ +module Trith; class Compiler + ## + # A Trith-to-Ruby compiler. + class Ruby < Compiler + SHEBANG = "#!/usr/bin/env ruby -rubygems" + + ## + # @param [Hash{Symbol => Object}] options + def initialize(options = {}) + super(options) + @options[:shebang] ||= SHEBANG + @output = StringIO.new + end + + ## + # @return [String] + def to_s + output = StringIO.new + output.puts @options[:shebang] + output.puts "require 'rubygems'" if @options[:rubygems] + output.puts "require 'trith'" + output.puts + output.puts "Trith::Machine.run do" + output.write @output.string + output.puts "end" + output.string + end + + protected + + ## + # @see Trith::Compiler#compile_operator + # @private + def compile_operator(operator) + emit("call(:#{operator}).execute") + end + + ## + # @see Trith::Compiler#compile_nil + # @private + def compile_nil(operand = nil) + emit("push(nil)") + end + + ## + # @see Trith::Compiler#compile_boolean + # @private + def compile_boolean(operand) + emit("push(#{operand})") + end + + ## + # @see Trith::Compiler#compile_number + # @private + def compile_number(operand) + emit("push(#{operand})") + end + + alias_method :compile_integer, :compile_number + alias_method :compile_float, :compile_number + alias_method :compile_decimal, :compile_number + alias_method :compile_rational, :compile_number + + ## + # @see Trith::Compiler#compile_string + # @private + def compile_string(operand) + emit("push(#{operand.inspect})") + end + + ## + # @see Trith::Compiler#compile_reference + # @private + def compile_reference(operand) + emit("push(Trith::URI.new(#{operand.to_s.inspect}))") + end + + ## + # @see Trith::Compiler#compile_quotation + # @private + def compile_quotation(operand) + emit("push(#{operand.inspect})") + end + + ## + # @param [String, #to_s] line + # @return [void] + def emit(line) + @output.puts(" " << line.to_s) + end + end # class Ruby +end; end # class Trith::Compiler
trith/trith
d4c415b9420ec8bf8159f19cbf482ffdba2aea52
Bumped the RDF.rb and YARD dependencies.
diff --git a/.gemspec b/.gemspec index 4f31cc7..4fcdbed 100644 --- a/.gemspec +++ b/.gemspec @@ -1,39 +1,39 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.authors = ['Arto Bendiken'] gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.9.1' gem.requirements = [] gem.add_development_dependency 'buildr' , '>= 1.3.5' gem.add_development_dependency 'rspec', '>= 1.3.0' - gem.add_development_dependency 'yard' , '>= 0.5.4' + gem.add_development_dependency 'yard' , '>= 0.5.5' gem.add_runtime_dependency 'promise', '~> 0.1.0' - gem.add_runtime_dependency 'rdf', '~> 0.1.9' + gem.add_runtime_dependency 'rdf', '~> 0.1.10' gem.add_runtime_dependency 'sxp', '~> 0.0.3' gem.post_install_message = nil end
trith/trith
5274fad7297639d70cdeeee5b90e3f9183ae8a29
Implemented an initial version of the 3cc script.
diff --git a/bin/3cc b/bin/3cc index 4dca423..ee1edd9 100755 --- a/bin/3cc +++ b/bin/3cc @@ -1,16 +1,40 @@ #!/usr/bin/env ruby1.9 -rubygems $:.unshift(File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))) require 'trith' BANNER = "Usage: #{File.basename($0)} [options] files..." case when %w(-V -v --version).any? { |opt| ARGV.include?(opt) } $stdout.puts Trith::VERSION.to_s exit when %w(-? -h --help).any? { |opt| ARGV.include?(opt) } $stdout.puts BANNER exit when ARGV.empty? - abort BANNER + abort BANNER # FIXME: read from stdin +end + +begin + $compiler = Trith::Compiler.for(:ruby).new + code = Trith::Reader.read_files(*ARGV) + File.open('a.rb', 'w+', 0755) do |output| + output.puts "#!/usr/bin/env ruby -rubygems" + output.puts "require 'trith'" + output.puts + output.puts "Trith::Machine.run do" + code.each do |op| + case op + when Symbol + output.puts " call(:#{op}).execute" + else + output.puts " push(#{op.inspect})" + end + end + output.puts "end" + end +rescue SystemCallError => e + abort "#{File.basename($0)}: #{e}" # abort due to e.g. Errno::ENOENT +rescue Interrupt + abort '' # abort due to ^C (SIGINT) end diff --git a/lib/trith/compiler.rb b/lib/trith/compiler.rb index 32c4e31..5603565 100644 --- a/lib/trith/compiler.rb +++ b/lib/trith/compiler.rb @@ -1,193 +1,193 @@ module Trith ## # A base class for Trith compiler targets. # # @abstract class Compiler # @return [Hash{Symbol => Object}] attr_reader :options ## # @param [Symbol, #to_sym] target # @return [Class] def self.for(target = nil, &block) target = block.call if block_given? self # TODO end ## # @param [Array<String>] filenames # @param [Hash{Symbol => Object}] options # @return [Compiler] def self.compile_files(*filenames) options = filenames.last.is_a?(Hash) ? filenames.peek : {} self.compile(Reader.read_files(*filenames), options) end ## # @param [Enumerable] program # @param [Hash{Symbol => Object}] options # @return [Compiler] def self.compile(program, options = {}) self.new(options).compile(program, options) end ## # @param [Hash{Symbol => Object}] options def initialize(options = {}) @options = options end ## # @param [Enumerable] program # @param [Hash{Symbol => Object}] options # @return [Compiler] def compile(program, options = {}) program = program.respond_to?(:each) ? program : [program] program.each { |op| compile_operand(op) } self end protected ## # @param [Object] operand # @return [void] def compile_operand(operand) case operand when Symbol compile_operator(operand) when NilClass compile_nil(operand) when TrueClass, FalseClass compile_boolean(operand) when Numeric compile_number(operand) when String compile_string(operand) when URI compile_reference(operand) when Array, SXP::List compile_quotation(operand) when Machine, Function compile_quotation(operand.to_a) else raise NotImplementedError.new("#{self.class}#compile_operand(#{operand.inspect})") end end ## # @param [Symbol, #to_sym] operator # @return [void] # @abstract def compile_operator(operator) case operator.to_sym when :nil then compile_nil(nil) when :false then compile_boolean(false) when :true then compile_boolean(true) else raise NotImplementedError.new("#{self.class}#compile_operator(#{operator.inspect})") end end ## # @param [NilClass] operand # @return [void] # @abstract def compile_nil(operand = nil) raise NotImplementedError.new("#{self.class}#compile_nil") end ## # @param [Boolean] operand # @return [void] # @abstract def compile_boolean(operand) raise NotImplementedError.new("#{self.class}#compile_boolean(#{operand.inspect})") end ## # @param [Numeric] operand # @return [void] # @abstract def compile_number(operand) case operand when Integer compile_integer(operand) when Float compile_float(operand) when BigDecimal compile_decimal(operand) when Rational compile_rational(operand) else raise NotImplementedError.new("#{self.class}#compile_number(#{operand.inspect})") end end ## # @param [Integer] operand # @return [void] # @abstract def compile_integer(operand) raise NotImplementedError.new("#{self.class}#compile_integer(#{operand.inspect})") end ## # @param [Float] operand # @return [void] # @abstract def compile_float(operand) raise NotImplementedError.new("#{self.class}#compile_float(#{operand.inspect})") end ## # @param [BigDecimal] operand # @return [void] # @abstract def compile_decimal(operand) raise NotImplementedError.new("#{self.class}#compile_decimal(#{operand.inspect})") end ## # @param [Rational] operand # @return [void] # @abstract def compile_rational(operand) raise NotImplementedError.new("#{self.class}#compile_rational(#{operand.inspect})") end ## # @param [String] operand # @return [void] # @abstract def compile_string(operand) raise NotImplementedError.new("#{self.class}#compile_string(#{operand.inspect})") end ## # @param [URI] operand # @return [void] # @abstract def compile_reference(operand) raise NotImplementedError.new("#{self.class}#compile_reference(#{operand.inspect})") end ## # @param [Array] operand # @return [void] # @abstract def compile_quotation(operand) raise NotImplementedError.new("#{self.class}#compile_quotation(#{operand.inspect})") end ## # @private def self.inherited(subclass) subclass.send(:public_class_method, :new) super end # Prevent the instantiation of this class: - private_class_method :new + #private_class_method :new end # class Compiler end # module Trith
trith/trith
538755a70e2ff5fc80dceb4bf57dc679da295a89
Imported specs for the Rosetta Code examples.
diff --git a/spec/rosettacode_spec.rb b/spec/rosettacode_spec.rb new file mode 100644 index 0000000..e537f0f --- /dev/null +++ b/spec/rosettacode_spec.rb @@ -0,0 +1,282 @@ +# -*- coding: utf-8 -*- +require File.join(File.dirname(__FILE__), 'spec_helper') + +# @see http://rosettacode.org/wiki/Category:Trith +describe "Rosetta Code examples" do + before(:each) { @stdout, $stdout = $stdout, StringIO.new } + after(:each) { $stdout = @stdout } + + # @see http://rosettacode.org/wiki/Empty_program#Trith + context "Empty program" do + it "should work" do + lambda { Machine.run(Reader.read_all("")) }.should_not raise_error + end + end + + # @see http://rosettacode.org/wiki/Hello_world/Text#Trith + context "Hello world/Text" do + it "should work using :print" do + code = Reader.read_all(<<-EOF) + "Goodbye, World!" print + EOF + Machine.run(code).should be_nil + $stdout.string.should == "Goodbye, World!\n" + end + end + + # @see http://rosettacode.org/wiki/Sum_and_product_of_an_array#Trith + context "Sum and product of an array" do + it "should work using :+ and :foldl" do + code = Reader.read_all(<<-EOF) + [1 2 3 4 5] 0 [+] foldl + EOF + Machine.run(code).should == 15 + end + + it "should work using :* and :foldl" do + code = Reader.read_all(<<-EOF) + [1 2 3 4 5] 1 [*] foldl + EOF + Machine.run(code).should == 120 + end + end + + # @see http://rosettacode.org/wiki/Singly-linked_list/Traversal#Trith + context "Singly-linked list/Traversal" do + it "should work using :each" do + code = Reader.read_all(<<-EOF) + [1 2 3 4 5] [print] each + EOF + Machine.run(code).should == nil + $stdout.string.should == "1\n2\n3\n4\n5\n" + end + end + + # @see http://rosettacode.org/wiki/Loops/Infinite#Trith + context "Loops/Infinite" do + it "should work using :loop" do + code = Reader.read_all(<<-EOF) + ["SPAM" print] loop + EOF + #Machine.run(code).should == nil # FIXME: need a timeout/step limit + end + end + + # @see http://rosettacode.org/wiki/Loops/Foreach#Trith + context "Loops/Foreach" do + it "should work using :each" do + code = Reader.read_all(<<-EOF) + [1 2 3 4 5] [print] each + EOF + Machine.run(code).should == nil + $stdout.string.should == "1\n2\n3\n4\n5\n" + end + end + + # @see http://rosettacode.org/wiki/Loops/While#Trith + context "Loops/While" do + it "should work using :/ and :floor" do + code = Reader.read_all(<<-EOF) + 1024 [dup print 2 / floor] [dup 0 >] while drop + EOF + Machine.run(code).should == nil + $stdout.string.should == "1024\n512\n256\n128\n64\n32\n16\n8\n4\n2\n1\n" + end + + it "should work using :shr" do + code = Reader.read_all(<<-EOF) + 1024 [dup print 1 shr] [dup 0 >] while drop + EOF + Machine.run(code).should == nil + $stdout.string.should == "1024\n512\n256\n128\n64\n32\n16\n8\n4\n2\n1\n" + end + end + + # @see http://rosettacode.org/wiki/Loops/Downward_for#Trith + context "Loops/Downward for" do + it "should work using :each" do + code = Reader.read_all(<<-EOF) + 10 inc iota reverse [print] each + EOF + Machine.run(code).should == nil + $stdout.string.should == "10\n9\n8\n7\n6\n5\n4\n3\n2\n1\n0\n" + end + + it "should work using :while" do + code = Reader.read_all(<<-EOF) + 10 [dup print dec] [dup 0 >=] while drop + EOF + Machine.run(code).should == nil + $stdout.string.should == "10\n9\n8\n7\n6\n5\n4\n3\n2\n1\n0\n" + end + end + + # @see http://rosettacode.org/wiki/Flatten_a_list#Trith + context "Flatten a list" do + it "should work using :flatten" do + code = Reader.read_all(<<-EOF) + [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []] flatten + EOF + Machine.run(code).should == [1, 2, 3, 4, 5, 6, 7, 8] + end + end + + # @see http://rosettacode.org/wiki/Array_concatenation#Trith + context "Array concatenation" do + it "should work using :concat" do + code = Reader.read_all(<<-EOF) + [1 2 3] [4 5 6] concat + EOF + Machine.run(code).should == [1, 2, 3, 4, 5, 6] + end + end + + # @see http://rosettacode.org/wiki/Copy_a_string#Trith + context "Copy a string" do + it "should work using :dup" do + code = Reader.read_all(<<-EOF) + "Hello" dup + EOF + Machine.run(code).should == "Hello" + end + end + + # @see http://rosettacode.org/wiki/Generic_swap#Trith + context "Generic swap" do + it "should work using :swap" do + code = Reader.read_all(<<-EOF) + swap + EOF + Machine.run([1, 2] + code).should == 1 + end + end + + # @see http://rosettacode.org/wiki/String_length#Trith + context "String length" do + it "should work using :length" do + code = Reader.read_all(<<-EOF) + "møøse" length + EOF + Machine.run(code).should == 5 + end + + it "should work using :size" do + code = Reader.read_all(<<-EOF) + "møøse" size + EOF + Machine.run(code).should == 7 + end + end + + # @see http://rosettacode.org/wiki/Higher-order_functions#Trith + context "Higher-order functions" do + it "should work using :twice" do + code = Reader.read_all(<<-EOF) + : twice 2 times ; + : hello "Hello, world!" print ; + [hello] twice + EOF + Machine.run(code).should == nil # FIXME + $stdout.string.should == "Hello, world!\nHello, world!\n" + end + end + + # @see http://rosettacode.org/wiki/Conditional_structures#Trith + context "Conditional structures" do + it "should work using :branch" do + code = Reader.read_all(<<-EOF) + true ["yes" print] ["no" print] branch + EOF + Machine.run(code).should == nil + $stdout.string.should == "yes\n" + end + + it "should work using :when" do + code = Reader.read_all(<<-EOF) + true ["yes" print] when + EOF + Machine.run(code).should == nil + $stdout.string.should == "yes\n" + end + + it "should work using :unless" do + code = Reader.read_all(<<-EOF) + false ["no" print] unless + EOF + Machine.run(code).should == nil + $stdout.string.should == "no\n" + end + end + + # @see http://rosettacode.org/wiki/Boolean_values#Trith + context "Boolean values" do + it "should work" # TODO + end + + # @see http://rosettacode.org/wiki/Infinity#Trith + context "Infinity" do + it "should work" do + code = Reader.read_all(<<-EOF) + : inf 1.0 0.0 / ; + : -inf inf neg ; + : inf? abs inf = ; + EOF + Machine.run(code).should == nil # FIXME + end + end + + # @see http://rosettacode.org/wiki/Character_codes#Trith + context "Character codes" do + it "should work with ASCII" do + code = Reader.read_all(<<-EOF) + "a" ord print + 97 chr print + EOF + Machine.run(code).should == nil + $stdout.string.should == "97\na\n" + end + + it "should work with Unicode" do + code = Reader.read_all(<<-EOF) + "π" ord print + 960 chr print + EOF + Machine.run(code).should == nil + $stdout.string.should == "960\nπ\n" + end + end + + # @see http://rosettacode.org/wiki/Greatest_element_of_a_list#Trith + context "Greatest element of a list" do + it "should work using :max and :foldl1" do + code = Reader.read_all(<<-EOF) + [1 -2 3.1415 0 42 7] [max] foldl1 + EOF + Machine.run(code).should == 42 + end + end + + # @see http://rosettacode.org/wiki/Sum_of_squares#Trith + context "Sum of squares" do + it "should work using :foldl" do + code = Reader.read_all(<<-EOF) + [3 1 4 1 5 9] 0 [dup * +] foldl + EOF + Machine.run(code).should == 133 + end + end + + # @see http://rosettacode.org/wiki/Averages/Arithmetic_mean#Trith + context "Averages/Arithmetic mean" do + it "should work using :foldl1" do + code = Reader.read_all(<<-EOF) + : mean dup empty? [drop 0] [dup [+] foldl1 swap length /] branch ; + [3 1 4 1 5 9] mean + EOF + Machine.run(code).should == 3 # FIXME + end + end + + # @see http://rosettacode.org/wiki/Category:Trith_examples_needing_attention + # @see http://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_Trith +end
trith/trith
36f3a7cc0f14f1316708ff065bad0e5bcf5a60e2
Enabled the 3sh shell to accept optional files to load on startup.
diff --git a/bin/3sh b/bin/3sh index cb25f38..792cc46 100755 --- a/bin/3sh +++ b/bin/3sh @@ -1,72 +1,76 @@ #!/usr/bin/env ruby1.9 -rubygems $:.unshift(File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))) require 'trith' BANNER = "Usage: #{File.basename($0)} [options] [files...]" case - when %w(-V -v --version).any? { |opt| ARGV.include?(opt) } + when %w(-V -v --version).any? { |opt| ARGV.delete(opt) } $stdout.puts Trith::VERSION.to_s exit - when %w(-? -h --help).any? { |opt| ARGV.include?(opt) } + when %w(-? -h --help).any? { |opt| ARGV.delete(opt) } $stdout.puts BANNER exit end begin $machine = Trith::Machine.new $cache = Trith::Cache.load_core Trith::Shell.setup!($cache) Trith::Shell::History.load! - if %w(-d --debug).any? { |opt| ARGV.include?(opt) } + if %w(-d --debug).any? { |opt| ARGV.delete(opt) } $machine.execute_hook = proc do $stdout.puts Trith::Shell.inspect($machine, :prefix => '.. ', :align => true) end end + ARGV.each do |file| + $machine.execute(Trith::Reader.read_file(file)) unless file =~ /^--/ + end + while line = Trith::Shell.readline('>> ') unless (line = line.strip).empty? case line # Operator lookup when /^\?\s*(\S*)/, 'help' filter = ($1.to_s).empty? ? nil : /#{Regexp.quote($1)}/ $cache.each_function do |function| if !filter || filter =~ function.label puts "%-24s%s" % [function.label, function.comment] end end next # skip inspecting the stack # Operator definition when /^:\s*(\S*)\s+(.*)$/ Trith::Shell::History.push(": #{$1} #{$2}") name, code = $1.to_sym, Trith::Reader.read_all($2) $machine.define!(name, code, :method => false) next # skip inspecting the stack # Code execution else Trith::Shell::History.push(line) begin $machine.execute(Trith::Reader.read_all(line)) rescue Trith::Machine::InvalidOperatorError => e $stderr.puts Trith::Shell.format_error(e) rescue Trith::Machine::InvalidOperandError => e $stderr.puts Trith::Shell.format_error(e) rescue Trith::Machine::StackUnderflowError => e $stderr.puts Trith::Shell.format_error("stack underflow") rescue => e $stderr.puts Trith::Shell.format_error(e.inspect) end end end $stdout.puts Trith::Shell.inspect($machine, :prefix => '=> ', :align => !!$machine.execute_hook) end $stdout.puts rescue Interrupt abort '' # abort due to ^C (SIGINT) ensure Trith::Shell::History.dump! end
trith/trith
34566f49b835775cf25bc4fd529a0ac12d81968d
Imported an initial reading list document.
diff --git a/.yardopts b/.yardopts index 5214830..7ab539c 100644 --- a/.yardopts +++ b/.yardopts @@ -1,11 +1,12 @@ --title "Trith: Recombinant Programming" --output-dir doc/yard --protected --no-private --hide-void-return --markup markdown --readme README.md - AUTHORS UNLICENSE VERSION +doc/READING.md diff --git a/doc/READING.md b/doc/READING.md new file mode 100644 index 0000000..d8d452b --- /dev/null +++ b/doc/READING.md @@ -0,0 +1,46 @@ +Some background reading materials for understanding Trith. + +Books +----- + +* [Thinking Forth: A Language and Philosophy for Solving Problems][Brodie] by Leo Brodie +* [Lambda-Calculus and Combinators: An Introduction][HindleySeldin] by Roger Hindley and Jonathan P. Seldin +* [Purely Functional Data Structures][Okasaki] by Chris Okasaki + +[Brodie]: http://thinking-forth.sourceforge.net/ + "Brodie, L. 'Thinking Forth: A Language and Philosophy for Solving Problems' (1984)" +[HindleySeldin]: http://www.cambridge.org/catalogue/catalogue.asp?isbn=9780521898850 + "Hindley, J. R., and Seldin, J. P. 'Lambda-Calculus and Combinators: An Introduction' (2008)" +[Okasaki]: http://www.cs.cmu.edu/~rwh/theses/okasaki.pdf + "Okasaki, C. 'Purely Functional Data Structures' (1996)" + +Papers +------ + +* [Why Functional Programming Matters][WhyFP] by John Hughes +* [Mathematical Foundations of Joy][JoyMath] by Manfred von Thun +* [Linear Logic and Permutation Stacks -- The Forth Shall Be First][ForthStack] by Henry Baker +* [Lively Linear Lisp -- 'Look Ma, No Garbage!'][LinearLisp] by Henry Baker +* ['Use-Once' Variables and Linear Objects][Use1Var] by Henry Baker + +[WhyFP]: http://www.cs.chalmers.se/~rjmh/Papers/whyfp.html + "Hughes, J. 'Why Functional Programming Matters' (1989)" +[JoyMath]: http://www.latrobe.edu.au/philosophy/phimvt/joy/j02maf.html + "von Thun, M. 'Mathematical Foundations of Joy' (2002)" +[Use1Var]: http://www.pipeline.com/~hbaker1/Use1Var.html + "Baker, H.G. 'Use-Once Variables and Linear Objects -- Storage Management, Reflection and Multi-Threading' (Jan 1995)" +[ForthStack]: http://www.pipeline.com/~hbaker1/ForthStack.html + "Baker, H.G. 'Linear Logic and Permutation Stacks -- The Forth Shall Be First' (Mar 1994)" +[LQsort]: http://www.pipeline.com/~hbaker1/LQsort.html + "Barke, H.G. 'A Linear Logic Quicksort' (Feb 1994)" +[ObjectIdentity]: http://www.pipeline.com/~hbaker1/ObjectIdentity.html + "Baker, H.G. 'Equal Rights for Functional Objects or, The More Things Change, The More They Are the Same' (Oct 1993)" +[LinearLisp]: http://www.pipeline.com/~hbaker1/LinearLisp.html + "Baker, H.G. 'Lively Linear Lisp -- Look Ma, No Garbage!' (Aug 1992)" +[LazyAlloc]: http://www.pipeline.com/~hbaker1/LazyAlloc.html + "Baker, H.G. 'CONS Should not CONS its Arguments, or, a Lazy Alloc is a Smart Alloc' (Mar 1992)" + +Articles +-------- + +* [A Conversation with Manfred von Thun](http://www.nsl.com/papers/interview.htm)
trith/trith
ce0aedadb3e1f7d50a5ac3a02e377bc972d26f61
Implemented the Trith::Core#uncons operator.
diff --git a/etc/trith-core.ttl b/etc/trith-core.ttl index d6b5870..b386997 100644 --- a/etc/trith-core.ttl +++ b/etc/trith-core.ttl @@ -173,559 +173,565 @@ <emptyp> a trith:Function ; rdfs:label "emptyp", "empty?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<length> <zerop>) . <eq> a trith:Function, trith:Primitive ; rdfs:label "eq", "=" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <evenp> a trith:Function ; rdfs:label "evenp", "even?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (2 <mod> <zerop>) . <exactp> a trith:Function ; rdfs:label "exactp", "exact?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<inexactp> <notp>) . <false> a trith:Function ; rdfs:label "false" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<quote> <false>) . <falsep> a trith:Function ; rdfs:label "falsep", "false?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<false> <eq>) . <fifth> a trith:Function ; rdfs:label "fifth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (4 <nth>) . <first> a trith:Function, trith:Primitive ; rdfs:label "first" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <flatten> a trith:Function ; rdfs:label "flatten" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <floor> a trith:Function ; rdfs:label "floor" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <fourth> a trith:Function ; rdfs:label "fourth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (3 <nth>) . <ge> a trith:Function ; rdfs:label "ge", ">=" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <gt> a trith:Function ; rdfs:label "gt", ">" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<cmp> <onep>) . <halt> a trith:Function, trith:Primitive ; rdfs:label "halt" ; rdfs:comment "" ; trith:arity 0 ; trith:code () . <inc> a trith:Function ; rdfs:label "inc" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <add>) . <inexactp> a trith:Function ; rdfs:label "inexactp", "inexact?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<exactp> <notp>) . <inf> a trith:Function ; rdfs:label "inf" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1.0 0.0 <div>) . <infp> a trith:Function ; rdfs:label "infp", "inf?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<abs> <inf> <eq>) . <intp> a trith:Function, trith:Primitive ; rdfs:label "intp", "int?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <iota> a trith:Function ; rdfs:label "iota" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <last> a trith:Function ; rdfs:label "last" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <le> a trith:Function ; rdfs:label "le", "<=" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <length> a trith:Function ; rdfs:label "length" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 (<rest> <swap> <inc>) (<swap> <dup> <emptyp>) <until> <drop>) . <list> a trith:Function ; rdfs:label "list" ; rdfs:comment "" ; trith:arity 1 ; trith:code (() <swap> (<cons>) <swap> <times> <reverse>) . <loop> a trith:Function ; rdfs:label "loop" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<dup> <call> (<loop>) <call>) . <lt> a trith:Function ; rdfs:label "lt", "<" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<cmp> -1 <eq>) . <map> a trith:Function ; rdfs:label "map" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <max> a trith:Function ; rdfs:label "max" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<dup2> <gt> (<drop>) (<swap> <drop>) <branch>) . <memberp> a trith:Function ; rdfs:label "memberp", "member?" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <min> a trith:Function ; rdfs:label "min" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<dup2> <lt> (<drop>) (<swap> <drop>) <branch>) . <mod> a trith:Function ; rdfs:label "mod" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <mul> a trith:Function ; rdfs:label "mul", "*" ; rdfs:comment "" ; trith:arity 2 ; trith:code (0 <swap> <abs> (<over> <add>) <swap> <times> <nip>) . # FIXME: negative operands <ne> a trith:Function ; rdfs:label "ne", "!=" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<eq> <notp>) . <neg> a trith:Function ; rdfs:label "neg" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <swap> <sub>) . <negp> a trith:Function ; rdfs:label "negp", "neg?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <lt>) . <nil> a trith:Function ; rdfs:label "nil" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<quote> <nil>) . <nilp> a trith:Function ; rdfs:label "nilp", "nil?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<nil> <eq>) . <ninth> a trith:Function ; rdfs:label "ninth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (8 <nth>) . <nip> a trith:Function ; rdfs:label "nip" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<swap> <drop>) . <nip2> a trith:Function ; rdfs:label "nip2", "2nip" ; rdfs:comment "" ; trith:arity 3 ; trith:code (<swap> <drop> <swap> <drop>) . <nop> a trith:Function ; rdfs:label "nop", ",", ";" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<nil> <drop>) . <not> a trith:Function ; rdfs:label "not" ; rdfs:comment "Bitwise NOT" ; trith:arity 1 ; trith:code (<neg> <dec>) . <notp> a trith:Function ; rdfs:label "notp", "not?" ; rdfs:comment "Logical NOT" ; trith:arity 1 ; trith:code ((<false>) (<true>) <branch>) . <nth> a trith:Function ; rdfs:label "nth" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<rest>) <swap> <times> <first>) . <num> a trith:Function, trith:Primitive ; rdfs:label "num" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <nump> a trith:Function, trith:Primitive ; rdfs:label "nump", "num?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <oddp> a trith:Function ; rdfs:label "oddp", "odd?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<evenp> <notp>) . <onep> a trith:Function ; rdfs:label "onep", "one?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <eq>) . <or> a trith:Function, trith:Primitive ; rdfs:label "or" ; rdfs:comment "Bitwise OR" ; trith:arity 2 ; trith:code () . <ord> a trith:Function, trith:Primitive ; rdfs:label "ord" ; rdfs:comment "" ; rdfs:seeAlso <chr> ; trith:arity 1 ; trith:code () . <orp> a trith:Function ; rdfs:label "orp", "or?" ; rdfs:comment "Logical OR" ; trith:arity 2 ; trith:code (<swap> <dup> (<swap> <drop>) (<drop>) <branch>) . <over> a trith:Function ; rdfs:label "over" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<dup2> <drop>) . <pick> a trith:Function ; rdfs:label "pick" ; rdfs:comment "" ; trith:arity 3 ; trith:code (<dup3> <drop2>) . <posp> a trith:Function ; rdfs:label "posp", "pos?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <gt>) . <pow> a trith:Function ; rdfs:label "pow" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <print> a trith:Function ; rdfs:label "print", "print!", "." ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <quote> a trith:Function, trith:Primitive ; rdfs:label "quote", "\\", "'" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <foldl> a trith:Function ; rdfs:label "foldl", "fold", "reduce" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . # TODO <foldl1> a trith:Function ; rdfs:label "foldl1" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<swap> <dup> <emptyp> (<drop2> <nil>) (<dup> <rest> <swap> <first> <rot> <foldl>) <branch>) . <range> a trith:Function ; rdfs:label "range" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <rem> a trith:Function ; rdfs:label "rem" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <reset> a trith:Function ; rdfs:label "reset" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<clear> <halt>) . <rest> a trith:Function, trith:Primitive ; rdfs:label "rest" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <reverse> a trith:Function ; rdfs:label "reverse" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <rot> a trith:Function, trith:Primitive ; rdfs:label "rot" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . <second> a trith:Function ; rdfs:label "second" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <nth>) . <seq> a trith:Function, trith:Primitive ; rdfs:label "seq" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <seqp> a trith:Function, trith:Primitive ; rdfs:label "seqp", "seq?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <seventh> a trith:Function ; rdfs:label "seventh" ; rdfs:comment "" ; trith:arity 1 ; trith:code (6 <nth>) . <shl> a trith:Function, trith:Primitive ; rdfs:label "shl" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <shr> a trith:Function, trith:Primitive ; rdfs:label "shr" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <sixth> a trith:Function ; rdfs:label "sixth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (5 <nth>) . <size> a trith:Function, trith:Primitive ; rdfs:label "size" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <stack> a trith:Function ; rdfs:label "stack" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<depth> <list>) . <sub> a trith:Function, trith:Primitive ; rdfs:label "sub", "-" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <swap> a trith:Function, trith:Primitive ; rdfs:label "swap" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <tenth> a trith:Function ; rdfs:label "tenth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (9 <nth>) . <text> a trith:Function ; rdfs:label "text" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <textp> a trith:Function ; rdfs:label "textp", "text?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <third> a trith:Function ; rdfs:label "third" ; rdfs:comment "" ; trith:arity 1 ; trith:code (2 <nth>) . <thrice> a trith:Function ; rdfs:label "thrice", "3x" ; rdfs:comment "" ; trith:arity 1 ; trith:code (3 <times>) . <times> a trith:Function ; rdfs:label "times" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<dec> <over> <call>) (<dup> <zerop>) <until> <drop2>) . <true> a trith:Function ; rdfs:label "true" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<quote> <true>) . <truep> a trith:Function ; rdfs:label "truep", "true?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<true> <eq>) . <twice> a trith:Function ; rdfs:label "twice", "2x" ; rdfs:comment "" ; trith:arity 1 ; trith:code (2 <times>) . +<uncons> a trith:Operator ; + rdfs:label "uncons" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (<dup> <first> <swap> <rest>) . + <unless> a trith:Function ; rdfs:label "unless" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<nop>) <swap> <branch>) . <unstack> a trith:Function, trith:Primitive ; rdfs:label "unstack" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <until> a trith:Function ; rdfs:label "until" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<notp>) <concat> <while>) . <when> a trith:Function ; rdfs:label "when" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<nop>) <branch>) . <while> a trith:Function ; rdfs:label "while" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <xor> a trith:Function, trith:Primitive ; rdfs:label "xor" ; rdfs:comment "Bitwise XOR" ; trith:arity 2 ; trith:code () . <xorp> a trith:Function ; rdfs:label "xorp", "xor?" ; rdfs:comment "Logical XOR" ; trith:arity 2 ; trith:code (<swap> <dup> (<swap> (<drop> <false>) (<nop>) <branch>) (<drop> <dup> (<nop>) (<drop> <false>) <branch>) <branch>) . <zerop> a trith:Function ; rdfs:label "zerop", "zero?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <eq>) . diff --git a/lib/trith/core/sequence.rb b/lib/trith/core/sequence.rb index 3203203..4db377d 100644 --- a/lib/trith/core/sequence.rb +++ b/lib/trith/core/sequence.rb @@ -1,453 +1,472 @@ module Trith; module Core ## # Sequence operators. # # @see http://ruby-doc.org/core-1.9/classes/Enumerable.html # @see http://ruby-doc.org/core-1.9/classes/Enumerator.html # @see http://en.wikipedia.org/wiki/Sequence module Sequence ## # Sequence predicates. module Predicates ## # @param [String, #each, #to_enum] obj # @return [Boolean] def seqp(obj) case obj when String then true when Array then true else case when obj.respond_to?(:each) then true when obj.respond_to?(:to_enum) then true else false end end end alias_method :seq?, :seqp ## # @param [#empty?, #size, #each] seq # @return [Boolean] def emptyp(seq) case when seq.respond_to?(:empty?) seq.empty? when seq.respond_to?(:size) seq.size.zero? when seq.respond_to?(:each) seq.each.to_a.empty? # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :emptyp) end end alias_method :empty?, :emptyp ## # @param [Object] elt # @param [#member?, #each] seq # @return [Boolean] def memberp(elt, seq) case when seq.respond_to?(:member?) seq.member?(elt) when seq.respond_to?(:each) seq.each.member?(elt) else raise Machine::InvalidOperandError.new(seq, :memberp) end end alias_method :member?, :memberp end # module Predicates ## # Sequence constructors. module Constructors ## # @param [String, #each, #to_enum] obj # @return [Enumerator] def seq(obj) case obj when String then obj.each_char when Array then obj.each else case when obj.respond_to?(:each) obj.each when obj.respond_to?(:to_enum) obj.to_enum else raise Machine::InvalidOperandError.new(obj, :seq) end end end ## # @overload cons(obj, seq) # @param [#to_s] obj # @param [String] seq # @return [String] # # @overload cons(obj, seq) # @param [Object] obj # @param [Array, #to_a] seq # @return [Array] # # @return [] def cons(obj, seq) case seq when String seq.dup.insert(0, obj.to_s.chr) when Array seq.dup.unshift(obj) else case when seq.respond_to?(:to_a) seq.to_a.unshift(obj) else # TODO: support for `#each` end end end + ## + # @param [Array, #[], #each] seq + # @return [Machine] + def uncons(seq) + case + when seq.respond_to?(:[]) + case + when seq.empty? + raise Machine::InvalidOperandError.new(seq, :uncons) + else + push(seq[0], seq[1..-1]) # FIXME + end + when seq.respond_to?(:each) + uncons(seq.each.to_a) + else + raise Machine::InvalidOperandError.new(seq, :uncons) + end + end + ## # @param [Integer, #to_i] n # @return [Enumerable] def list(n) stack.pop(n.to_i) end ## # @param [Integer, #to_i] n # @return [Enumerable] def iota(n) # TODO: should support negative ranges as well. (0...(n.to_i)).to_a # FIXME end ## # @param [Integer, #to_i] a # @param [Integer, #to_i] b # @return [Enumerable] def range(a, b) # TODO: should support negative ranges as well. ((a.to_i)..(b.to_i)).to_a # FIXME end end # module Constructors ## # Sequence accessors. module Accessors ## # @param [#length, #size, #each] seq # @return [Integer] def length(seq) case when seq.respond_to?(:length) seq.length when seq.respond_to?(:size) seq.size when seq.respond_to?(:each) seq.each.to_a.size # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :length) end end ## # @param [#rest, #[], #each] seq # @return [Enumerable] def rest(seq) # TODO: check semantics for empty sequences case when seq.respond_to?(:rest) seq.rest when seq.respond_to?(:[]) seq[1..-1] when seq.respond_to?(:each) seq.each.to_a[1..-1] # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :rest) end end ## # @param [#first, #[], #each] seq # @return [Object] def first(seq) case seq when String seq[0].chr rescue nil # Ruby 1.8 compatible else case when seq.respond_to?(:first) then seq.first else nth(seq, 0) end end end ## # @param [#second, #[], #each] seq # @return [Object] def second(seq) case when seq.respond_to?(:second) then seq.second else nth(seq, 1) end end ## # @param [#third, #[], #each] seq # @return [Object] def third(seq) case when seq.respond_to?(:third) then seq.third else nth(seq, 2) end end ## # @param [#fourth, #[], #each] seq # @return [Object] def fourth(seq) case when seq.respond_to?(:fourth) then seq.fourth else nth(seq, 3) end end ## # @param [#fifth, #[], #each] seq # @return [Object] def fifth(seq) case when seq.respond_to?(:fifth) then seq.fifth else nth(seq, 4) end end ## # @param [#sixth, #[], #each] seq # @return [Object] def sixth(seq) case when seq.respond_to?(:sixth) then seq.sixth else nth(seq, 5) end end ## # @param [#seventh, #[], #each] seq # @return [Object] def seventh(seq) case when seq.respond_to?(:seventh) then seq.seventh else nth(seq, 6) end end ## # @param [#eighth, #[], #each] seq # @return [Object] def eighth(seq) case when seq.respond_to?(:eighth) then seq.eighth else nth(seq, 7) end end ## # @param [#ninth, #[], #each] seq # @return [Object] def ninth(seq) case when seq.respond_to?(:ninth) then seq.ninth else nth(seq, 8) end end ## # @param [#tenth, #[], #each] seq # @return [Object] def tenth(seq) case when seq.respond_to?(:tenth) then seq.tenth else nth(seq, 9) end end ## # @param [#nth, #[], #each] seq # @param [Integer, #to_i] n # @return [Object] def nth(seq, n) case seq when String seq[n.to_i].chr rescue nil # Ruby 1.8 compatible else case when seq.respond_to?(:nth) seq.nth(n) when seq.respond_to?(:[]) seq[n.to_i] when seq.respond_to?(:each) seq.each.to_a[n.to_i] # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :nth) end end end ## # @param [#last, #[], #each] seq # @return [Object] def last(seq) case seq when String seq[-1].chr rescue nil # Ruby 1.8 compatible else case when seq.respond_to?(:last) seq.last when seq.respond_to?(:[]) seq[-1] when seq.respond_to?(:each) seq.each.to_a.last # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :last) end end end end # module Accessors ## # Sequence operators. module Operators ## # @param [#concat, #each] seq1 # @param [#each] seq2 # @return [Enumerable] def concat(seq1, seq2) case when seq1.respond_to?(:concat) seq1.dup.concat(seq2) when seq1.respond_to?(:each) seq1.each.to_a.concat(seq2.each.to_a) # TODO: optimize else raise Machine::InvalidOperandError.new(seq1, :concat) end end ## # @param [#reverse, #each] seq # @return [Enumerable] def reverse(seq) case seq when String then seq.reverse when Array then seq.reverse else case when seq.respond_to?(:reverse) seq.reverse when seq.respond_to?(:each) seq.each.to_a.reverse # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :reverse) end end end ## # @param [#flatten, #each] seq # @return [Enumerable] def flatten(seq) case seq when String then seq when Array then seq.flatten else case when seq.respond_to?(:flatten) seq.flatten when seq.respond_to?(:each) seq.each.to_a.flatten # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :flatten) end end end end # module Operators ## # Sequence combinators. module Combinators ## # @param [#each] seq # @param [Array] quot # @return [Machine] def each(seq, quot) seq = case seq when String then seq.each_char else case when seq.respond_to?(:each) then seq.each else raise Machine::InvalidOperandError.new(seq, :each) end end with_saved_continuation(:each) do seq.each { |elem| push(elem).execute(quot) } end end ## # @param [#map, #each] seq # @param [Array] quot # @return [Machine] def map(seq, quot) seq = case seq when String then seq.each_char else case when seq.respond_to?(:map) then seq when seq.respond_to?(:each) then seq.each else raise Machine::InvalidOperandError.new(seq, :map) end end with_saved_continuation(:map) do push(seq.map { |elem| push(elem).execute(quot).pop }) end end ## # @param [#reduce, #each] seq # @param [Object] identity # @param [Array] quot # @return [Machine] def foldl(seq, identity, quot) seq = case seq when String then seq.each_char else case when seq.respond_to?(:reduce) then seq when seq.respond_to?(:each) then seq.each else raise Machine::InvalidOperandError.new(seq, :foldl) end end with_saved_continuation(:foldl) do push(seq.reduce(identity) { |prev, elem| push(prev, elem).execute(quot).pop }) end end alias_method :fold, :foldl alias_method :reduce, :foldl ## # @param [#reduce, #each] seq # @param [Array] quot # @return [Machine] def foldl1(seq, quot) raise Machine::InvalidOperandError.new(seq, :foldl1) if seq.empty? seq = case seq when String then seq.each_char.to_a else case when seq.respond_to?(:reduce) then seq.dup when seq.respond_to?(:each) then seq.each.to_a else raise Machine::InvalidOperandError.new(seq, :foldl1) end end with_saved_continuation(:foldl1) do push(seq.reduce(seq.pop) { |prev, elem| push(prev, elem).execute(quot).pop }) end end end # module Combinators # Include all submodule methods directly into Trith::Core::Sequence: constants.each { |mod| include(const_get(mod)) } end # module Sequence end; end # module Trith::Core diff --git a/spec/machine_spec.rb b/spec/machine_spec.rb index 2d995b2..afcdb83 100644 --- a/spec/machine_spec.rb +++ b/spec/machine_spec.rb @@ -90,774 +90,779 @@ describe Trith::Machine do end it "should implement the :unstack operator" do Machine.new.should respond_to(:unstack) # TODO end it "should implement the :drop operator" do Machine.new.should respond_to(:drop) Machine.new([6, 7]).execute { drop }.stack.should == [6] end it "should implement the :drop2 operator" do Machine.new.should respond_to(:drop2, :'2drop') # TODO end it "should implement the :drop3 operator" do Machine.new.should respond_to(:drop3, :'3drop') # TODO end it "should implement the :dup operator" do Machine.new.should respond_to(:dup) Machine.new([6, 7]).execute { dup }.stack.should == [6, 7, 7] end it "should implement the :dup2 operator" do Machine.new.should respond_to(:dup2, :'2dup') # TODO end it "should implement the :dup3 operator" do Machine.new.should respond_to(:dup3, :'3dup') # TODO end it "should implement the :swap operator" do Machine.new.should respond_to(:swap) Machine.new([6, 7]).execute { swap }.stack.should == [7, 6] end it "should implement the :nip operator" do Machine.new.should respond_to(:nip) # TODO end it "should implement the :nip2 operator" do Machine.new.should respond_to(:nip2, :'2nip') # TODO end it "should implement the :over operator" do Machine.new.should respond_to(:over) # TODO end it "should implement the :pick operator" do Machine.new.should respond_to(:pick) # TODO end it "should implement the :rot operator" do Machine.new.should respond_to(:rot) # TODO end end context "Stack combinators" do it "should implement the :dip operator" do Machine.new.should respond_to(:dip) Machine.new([6, 7, 1, [:mul]]).execute { dip }.stack.should == [42, 1] end end context "Arithmetic operators" do it "should implement the :abs operator" do Machine.new.should respond_to(:abs) Machine.run { push(1).abs }.should == 1 Machine.run { push(-1).abs }.should == 1 end it "should implement the :neg operator" do Machine.new.should respond_to(:neg) Machine.run { push(6).neg }.should == -6 end it "should implement the :inc operator" do Machine.new.should respond_to(:inc) Machine.run { push(6).inc }.should == 7 end it "should implement the :dec operator" do Machine.new.should respond_to(:dec) Machine.run { push(6).dec }.should == 5 end it "should implement the :add operator" do Machine.new.should respond_to(:add, :+) Machine.run { push(6).push(7).add }.should == 13 end it "should implement the :sub operator" do Machine.new.should respond_to(:sub, :-) Machine.run { push(6).push(7).sub }.should == -1 end it "should implement the :mul operator" do Machine.new.should respond_to(:mul, :*) Machine.run { push(6).push(7).mul }.should == 42 end it "should implement the :div operator" do Machine.new.should respond_to(:div, :'/') Machine.run { push(42).push(7).div }.should == 6 end it "should implement the :rem operator" do Machine.new.should respond_to(:rem) # TODO end it "should implement the :mod operator" do Machine.new.should respond_to(:mod) # TODO end it "should implement the :pow operator" do Machine.new.should respond_to(:pow) # TODO end end context "Bitwise operators" do it "should implement the :not operator" do Machine.new.should respond_to(:not) # TODO end it "should implement the :and operator" do Machine.new.should respond_to(:and) # TODO end it "should implement the :or operator" do Machine.new.should respond_to(:or) # TODO end it "should implement the :xor operator" do Machine.new.should respond_to(:xor) # TODO end it "should implement the :shl operator" do Machine.new.should respond_to(:shl) # TODO end it "should implement the :shr operator" do Machine.new.should respond_to(:shr) # TODO end end context "Boolean predicates" do it "should implement the :nilp operator" do Machine.new.should respond_to(:nilp, :nil?) # TODO end it "should implement the :boolp operator" do Machine.new.should respond_to(:boolp, :bool?) # TODO end it "should implement the :falsep operator" do Machine.new.should respond_to(:falsep, :false?) # TODO end it "should implement the :truep operator" do Machine.new.should respond_to(:truep, :true?) # TODO end it "should implement the :notp operator" do Machine.new.should respond_to(:notp, :not?) # TODO end it "should implement the :andp operator" do Machine.new.should respond_to(:andp, :and?) # TODO end it "should implement the :orp operator" do Machine.new.should respond_to(:orp, :or?) # TODO end it "should implement the :xorp operator" do Machine.new.should respond_to(:xorp, :xor?) # TODO end end context "Boolean constructors" do it "should implement the :nil operator" do Machine.new.should respond_to(:nil) # TODO end it "should implement the :bool operator" do Machine.new.should respond_to(:bool) # TODO end it "should implement the :false operator" do Machine.new.should respond_to(:false) # TODO end it "should implement the :true operator" do Machine.new.should respond_to(:true) # TODO end end context "Comparison operators" do it "should implement the :cmp operator" do Machine.new.should respond_to(:cmp, :<=>) # TODO end it "should implement the :eq operator" do Machine.new.should respond_to(:eq, :'=') # TODO end it "should implement the :ne operator" do Machine.new.should respond_to(:ne, :'!=') # TODO end it "should implement the :lt operator" do Machine.new.should respond_to(:lt, :<) # TODO end it "should implement the :le operator" do Machine.new.should respond_to(:le, :<=) # TODO end it "should implement the :gt operator" do Machine.new.should respond_to(:gt, :>) # TODO end it "should implement the :ge operator" do Machine.new.should respond_to(:ge, :>=) # TODO end it "should implement the :min operator" do Machine.new.should respond_to(:min) # TODO end it "should implement the :max operator" do Machine.new.should respond_to(:max) # TODO end end context "Numeric predicates" do it "should implement the :nump operator" do Machine.new.should respond_to(:nump, :num?) # TODO end it "should implement the :intp operator" do Machine.new.should respond_to(:intp, :int?) # TODO end it "should implement the :infp operator" do Machine.new.should respond_to(:infp, :inf?) # TODO end it "should implement the :zerop operator" do Machine.new.should respond_to(:zerop, :zero?) # TODO end it "should implement the :onep operator" do Machine.new.should respond_to(:onep, :one?) # TODO end it "should implement the :negp operator" do Machine.new.should respond_to(:negp, :neg?) # TODO end it "should implement the :posp operator" do Machine.new.should respond_to(:posp, :pos?) # TODO end it "should implement the :oddp operator" do Machine.new.should respond_to(:oddp, :odd?) # TODO end it "should implement the :evenp operator" do Machine.new.should respond_to(:evenp, :even?) # TODO end end context "Numeric constructors" do it "should implement the :num operator" do Machine.new.should respond_to(:num) # TODO end it "should implement the :int operator" do Machine.new.should respond_to(:int) # TODO end it "should implement the :inf operator" do Machine.new.should respond_to(:inf) # TODO end end context "Math constants" do it "should implement the :pi operator" do Machine.new.should respond_to(:pi) # TODO end end context "Math operators" do it "should implement the :ceil operator" do Machine.new.should respond_to(:ceil) # TODO end it "should implement the :floor operator" do Machine.new.should respond_to(:floor) # TODO end it "should implement the :round operator" do Machine.new.should respond_to(:round) # TODO end it "should implement the :sq operator" do Machine.new.should respond_to(:sq) # TODO end it "should implement the :sqrt operator" do Machine.new.should respond_to(:sqrt) # TODO end it "should implement the :cb operator" do Machine.new.should respond_to(:cb) # TODO end it "should implement the :cbrt operator" do Machine.new.should respond_to(:cbrt) # TODO end it "should implement the :exp operator" do Machine.new.should respond_to(:exp) # TODO end it "should implement the :log operator" do Machine.new.should respond_to(:log) # TODO end it "should implement the :log2 operator" do Machine.new.should respond_to(:log2) # TODO end it "should implement the :log10 operator" do Machine.new.should respond_to(:log10) # TODO end it "should implement the :hypot operator" do Machine.new.should respond_to(:hypot) # TODO end it "should implement the :cos operator" do Machine.new.should respond_to(:cos) # TODO end it "should implement the :cosh operator" do Machine.new.should respond_to(:cosh) # TODO end it "should implement the :sin operator" do Machine.new.should respond_to(:sin) # TODO end it "should implement the :sinh operator" do Machine.new.should respond_to(:sinh) # TODO end it "should implement the :tan operator" do Machine.new.should respond_to(:tan) # TODO end it "should implement the :tanh operator" do Machine.new.should respond_to(:tanh) # TODO end it "should implement the :acos operator" do Machine.new.should respond_to(:acos) # TODO end it "should implement the :acosh operator" do Machine.new.should respond_to(:acosh) # TODO end it "should implement the :asin operator" do Machine.new.should respond_to(:asin) # TODO end it "should implement the :asinh operator" do Machine.new.should respond_to(:asinh) # TODO end it "should implement the :atan operator" do Machine.new.should respond_to(:atan) # TODO end it "should implement the :atan2 operator" do Machine.new.should respond_to(:atan2) # TODO end it "should implement the :atanh operator" do Machine.new.should respond_to(:atanh) # TODO end end context "Sequence predicates" do it "should implement the :seqp operator" do Machine.new.should respond_to(:seqp) # TODO end it "should implement the :emptyp operator" do Machine.new.should respond_to(:emptyp) # TODO end it "should implement the :memberp operator" do Machine.new.should respond_to(:memberp) # TODO end it "should implement the :anyp operator" do Machine.new.should respond_to(:anyp) # TODO end it "should implement the :allp operator" do Machine.new.should respond_to(:allp) # TODO end end context "Sequence constructors" do it "should implement the :seq operator" do Machine.new.should respond_to(:seq) # TODO end it "should implement the :cons operator" do Machine.new.should respond_to(:cons) # TODO end + it "should implement the :uncons operator" do + Machine.new.should respond_to(:uncons) + # TODO + end + it "should implement the :list operator" do Machine.new.should respond_to(:list) # TODO end it "should implement the :iota operator" do Machine.new.should respond_to(:iota) # TODO end it "should implement the :range operator" do Machine.new.should respond_to(:range) # TODO end it "should implement the :repeat operator" do Machine.new.should respond_to(:repeat) # TODO end it "should implement the :cycle operator" do Machine.new.should respond_to(:cycle) # TODO end end context "Sequence accessors" do it "should implement the :length operator" do Machine.new.should respond_to(:length) # TODO end it "should implement the :rest operator" do Machine.new.should respond_to(:rest) # TODO end it "should implement the :first operator" do Machine.new.should respond_to(:first) # TODO end it "should implement the :second operator" do Machine.new.should respond_to(:second) # TODO end it "should implement the :third operator" do Machine.new.should respond_to(:third) # TODO end it "should implement the :fourth operator" do Machine.new.should respond_to(:fourth) # TODO end it "should implement the :fifth operator" do Machine.new.should respond_to(:fifth) # TODO end it "should implement the :sixth operator" do Machine.new.should respond_to(:sixth) # TODO end it "should implement the :seventh operator" do Machine.new.should respond_to(:seventh) # TODO end it "should implement the :eighth operator" do Machine.new.should respond_to(:eighth) # TODO end it "should implement the :ninth operator" do Machine.new.should respond_to(:ninth) # TODO end it "should implement the :tenth operator" do Machine.new.should respond_to(:tenth) # TODO end it "should implement the :nth operator" do Machine.new.should respond_to(:nth) # TODO end it "should implement the :last operator" do Machine.new.should respond_to(:last) # TODO end end context "Sequence operators" do it "should implement the :subseq operator" do Machine.new.should respond_to(:subseq) # TODO end it "should implement the :concat operator" do Machine.new.should respond_to(:concat) # TODO end it "should implement the :uniq operator" do Machine.new.should respond_to(:uniq) # TODO end it "should implement the :reverse operator" do Machine.new.should respond_to(:reverse) # TODO end it "should implement the :sort operator" do Machine.new.should respond_to(:sort) # TODO end it "should implement the :sortby operator" do Machine.new.should respond_to(:sortby) # TODO end it "should implement the :flatten operator" do Machine.new.should respond_to(:flatten) # TODO end it "should implement the :zip operator" do Machine.new.should respond_to(:zip) # TODO end it "should implement the :zip1 operator" do Machine.new.should respond_to(:zip1) # TODO end it "should implement the :zip2 operator" do Machine.new.should respond_to(:zip2) # TODO end it "should implement the :zip3 operator" do Machine.new.should respond_to(:zip3) # TODO end it "should implement the :zip4 operator" do Machine.new.should respond_to(:zip4) # TODO end it "should implement the :unzip operator" do Machine.new.should respond_to(:unzip) # TODO end it "should implement the :unzip1 operator" do Machine.new.should respond_to(:unzip1) # TODO end it "should implement the :unzip2 operator" do Machine.new.should respond_to(:unzip2) # TODO end it "should implement the :unzip3 operator" do Machine.new.should respond_to(:unzip3) # TODO end it "should implement the :unzip4 operator" do Machine.new.should respond_to(:unzip4) # TODO end end context "Sequence combinators" do it "should implement the :each operator" do Machine.new.should respond_to(:each) # TODO end it "should implement the :map operator" do Machine.new.should respond_to(:map) Machine.new([[1, 2, 3, 4, 5], [:dup, :mul]]).execute { map }.stack.should == [[1, 4, 9, 16, 25]] end it "should implement the :count operator" do Machine.new.should respond_to(:count) # TODO end it "should implement the :filter operator" do Machine.new.should respond_to(:filter) Machine.new([[1, 2, 3, 4, 5], [2, :mod, 0, :eq]]).execute { filter }.stack.should == [[2, 4]] end it "should implement the :remove operator" do Machine.new.should respond_to(:remove) # TODO end it "should implement the :foldl operator" do Machine.new.should respond_to(:foldl, :fold, :reduce) Machine.new([[1, 2, 3, 4, 5], 0, [:add]]).execute { foldl }.stack.should == [15] Machine.new([[], -1, [:add]]).execute { foldl }.stack.should == [-1] Machine.new([[2, 5, 3], 0, [:add]]).execute { foldl }.stack.should == [10] Machine.new([[2, 5, 3], 0, [:dup, :mul, :add]]).execute { foldl }.stack.should == [38] end it "should implement the :foldl1 operator" do Machine.new.should respond_to(:foldl1) end it "should implement the :foldr operator" do Machine.new.should respond_to(:foldr) # TODO end end context "Textual predicates" do it "should implement the :chrp operator" do Machine.new.should respond_to(:chrp, :chr?) # TODO end # TODO end context "Textual constructors" do it "should implement the :chr operator" do Machine.new.should respond_to(:chr) Machine.run([97]) { chr }.should == "a" Machine.run([960]) { chr }.should == "\u03c0" # PI end # TODO end context "Textual operators" do it "should implement the :size operator" do Machine.new.should respond_to(:size) # TODO end end context "Output operators" do it "should implement the :print operator" do Machine.new.should respond_to(:print, :print!, :'.') # TODO end end end
trith/trith
5bb0a57c0d521443bd679eef2b3edaa08752f5fb
Imported a first draft of the Trith RDFS/OWL vocabulary.
diff --git a/etc/trith-lang.ttl b/etc/trith-lang.ttl new file mode 100644 index 0000000..879706a --- /dev/null +++ b/etc/trith-lang.ttl @@ -0,0 +1,49 @@ +@base <http://trith.org/lang/> . +@prefix trith: <http://trith.org/lang/> . +@prefix xsd: <http://www.w3.org/2001/XMLSchema#> . +@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . +@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . +@prefix owl: <http://www.w3.org/2002/07/owl#> . +@prefix dc: <http://purl.org/dc/terms/> . +@prefix foaf: <http://xmlns.com/foaf/0.1/> . +@prefix doap: <http://usefulinc.com/ns/doap#> . + +<> a owl:Ontology ; + rdfs:label "Trith" ; + rdfs:comment "Trith vocabulary."@en ; + rdfs:seeAlso <http://datagraph.org/bendiken/foaf> ; + foaf:maker <http://ar.to/#self> ; + dc:creator "Arto Bendiken" ; + dc:modified "2010-05-23" . + +trith:Operator a owl:Class, rdfs:Class ; + rdfs:isDefinedBy <> ; + rdfs:subClassOf rdfs:Resource ; + rdfs:label "Operator" ; + rdfs:comment ""@en . + +trith:Primitive a owl:Class, rdfs:Class ; + rdfs:isDefinedBy <> ; + rdfs:subClassOf trith:Operator ; + rdfs:label "Primitive" ; + rdfs:comment ""@en . + +trith:Function a owl:Class, rdfs:Class ; + rdfs:isDefinedBy <> ; + rdfs:subClassOf trith:Operator ; + rdfs:label "Function" ; + rdfs:comment ""@en . + +trith:arity a owl:DatatypeProperty, rdf:Property ; + rdfs:isDefinedBy <> ; + rdfs:domain trith:Operator ; + rdfs:range xsd:integer ; + rdfs:label "label" ; + rdfs:comment ""@en . + +trith:code a owl:ObjectProperty, rdf:Property ; + rdfs:isDefinedBy <> ; + rdfs:domain trith:Operator ; + rdfs:range rdf:List ; + rdfs:label "code" ; + rdfs:comment ""@en .
trith/trith
09f5b0b539d2ba3ccbcfaccd892ef1bb15260dea
Added the Promise gem as a dependency.
diff --git a/.gemspec b/.gemspec index 47cda0a..4f31cc7 100644 --- a/.gemspec +++ b/.gemspec @@ -1,38 +1,39 @@ #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'trith' gem.homepage = 'http://trith.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'An experimental concatenative programming language.' gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' gem.rubyforge_project = 'trith' gem.authors = ['Arto Bendiken'] gem.email = '[email protected]' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) gem.files += Dir.glob('etc/*.{ttl,nt}') gem.files += Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(3th 3sh 3vm 3cc) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.9.1' gem.requirements = [] gem.add_development_dependency 'buildr' , '>= 1.3.5' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'yard' , '>= 0.5.4' + gem.add_runtime_dependency 'promise', '~> 0.1.0' gem.add_runtime_dependency 'rdf', '~> 0.1.9' gem.add_runtime_dependency 'sxp', '~> 0.0.3' gem.post_install_message = nil end diff --git a/README.md b/README.md index a20f44c..95c6057 100644 --- a/README.md +++ b/README.md @@ -1,314 +1,315 @@ Trith: Recombinant Programming ============================== Trith is an experimental [concatenative][concat.org] programming language founded on the [unholy][lispers.org] trinity of [Forth][], [Lisp][] and [RDF][] triples. * <http://trith.org/> * <http://github.com/trith/trith> Description ----------- Trith is a stack-based, concatenative, dynamically-typed functional programming language with a homoiconic program representation. * [Stack-based][stack-oriented] means that instead of having named parameters, Trith functions operate on an implicit data structure called the _operand stack_. Trith functions can be thought of in terms of popping and pushing operands from/onto this stack, or equivalently in purely functional terms as unary functions that map from one stack to another. * [Concatenative][concatenative] means that the concatenation of any two Trith functions also denotes the [composition][] of those functions. * [Dynamically typed][type system] means that operands to Trith functions are type-checked dynamically at runtime. * [Homoiconic][homoiconic] means that in Trith there is no difference between code and data. You can manipulate and construct code at runtime as easily as you would manipulate any other data structure, enabling powerful metaprogramming facilities. Trith programs are simply nested lists of operators and operands, and can be represented externally either as [S-expressions][S-expression] or as [RDF][] triples. Trith is inspired and influenced by experience with [Forth][], [Lisp][] and [Scheme][] in general, and the concatenative languages [Joy][], [XY][], [Factor][] and [Cat][] in particular. Introduction ------------ The Trith implementation currently consists of a virtual machine, interpreter, and compiler toolchain written in Ruby and an in-the-works runtime targeting the [JVM][]. You can use the Trith shell `3sh` to explore Trith interactively: $ 3sh >> "Hello, world!" print Hello, world! For example, here's how you would start with two prime numbers and end up with the correct answer to the ultimate question of life, the universe, and everything: $ 3sh >> 3 7 swap dup + * => [42] : [] In the above `3sh` examples, `>>` indicates lines that you type, and `=>` indicates the result from the shell. After each input line is evaluated, the shell will show you the current state of the Trith virtual machine's data stack and code queue. Thus in our previous example, the `[42]` on the left-hand side shows that the machine's stack contains a single operand, the number 42. The `[]` on the right-hand side shows that the machine's code queue is empty, which is generally the case after all input has been successfully evaluated. Let's run through the above example one more time using the `--debug` option to `3sh`, which enables the tracing of each queue reduction step in the virtual machine: $ 3sh --debug >> 3 7 swap dup + * .. [] : [3 7 swap dup + *] .. [3] : [7 swap dup + *] .. [3 7] : [swap dup + *] .. [7 3] : [dup + *] .. [7 3 3] : [+ *] .. [7 6] : [*] => [42] : [] As you can see, the virtual machine starts execution with an empty operand stack on the left-hand side and with all input placed onto the operator queue on the right-hand side. When input operands such as numbers are encountered on the queue, they are simply pushed onto the stack, which grows from left to right. When an operator such as the multiplication operator `*` is encountered on the queue, it is executed. Operators pop operands from the stack and then push their result(s) back onto the stack. When fooling around in the Trith shell, two useful operators to know are `clear`, which clears the stack, and `halt`, which clears the queue (thus halting execution). You can also use `reset` which does both in one step, returning you to a guaranteed clean slate. To get a listing of all operators supported in the current release, enter the `?` metacommand in the Trith shell. Linked Code ----------- All Trith operators are identified by URIs, meaning that Trith code can be straightforwardly represented as [Linked Data][]. Here's an example of the `abs` operator defined metacircularly using the Turtle serialization format for RDF data: @base <http://trith.org/core/> . @prefix trith: <http://trith.org/lang/> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . <abs> a trith:Function ; rdfs:label "abs" ; rdfs:comment "Returns the absolute value of a number."@en ; trith:arity 1 ; trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . This function description comprises a total of 21 triples. The entire Trith core library currently weighs in at about a kilotriple (1,000 triples), with all but a handful of primitive (irreducible) operators having a metacircular definition. See `etc/trith-core.ttl` for the RDF definitions of Trith core operators. Reference --------- ### Sequences Trith has a rich set of sequence operators that will be instantly familiar to programmers coming from functional programming languages such as Scheme, Clojure or Haskell: >> 10 iota => [[0 1 2 3 4 5 6 7 8 9]] : [] >> dup seq? . true >> dup empty? . false >> dup length . 10 >> [dup mul] map => [[0 1 4 9 16 25 36 49 64 81]] : [] >> dup first . 0 >> dup fifth . 16 >> dup 7 nth . 49 >> dup last . 81 >> dup 0 [+] foldl . 285 >> rest => [[1 4 9 16 25 36 49 64 81]] : [] >> dup 1 [*] foldl . 131681894400 >> reverse => [[81 64 49 36 25 16 9 4 1]] : [] ### Strings Strings are simply sequences of characters (Unicode code points), meaning that you can make use of any of the normal sequence operators on strings as well: >> : hello "Hello," " world!" concat ; >> hello seq? . true >> hello text? . true >> hello empty? . false >> hello length . 13 >> hello first . H >> hello rest . ello, world! >> hello reverse . !dlrow ,olleH Embedding --------- ### Embedding Trith in Ruby require 'trith' # Let's start with the obligatory "Hello, world!" example: Trith::Machine.run do push "Hello, world!" print end # There are several equivalent ways to execute Trith code: Trith::Machine.run { push(6, 7).mul } #=> 42 Trith::Machine.run [6, 7] { mul } #=> 42 Trith::Machine.run [6, 7, :mul] #=> 42 # Operators in Ruby blocks can be chained together: Trith::Machine.run { push(2).dup.dup.mul.pow } #=> 16 # If you require more control, instantiate a machine manually: vm = Trith::Machine.new vm.define!(:square) { dup.mul } vm.push(10).square.peek #=> 100 # You can also define operators when constructing a machine: vm = Trith::Machine.new(data = [], code = [], { :hello => proc { push("Hello, world!").print }, }) # Should you want to use any Trith functions from Ruby, it's easy enough # to encapsulate a virtual machine inside a Ruby method: def square(n) Trith::Machine.run [n] { dup.mul } end square(10) #=> 100 ### Embedding Trith in JVM-based languages The [JVM][] runtime for Trith is a work in progress. See `src/java` for the runtime's source code and current status. Dependencies ------------ * [Ruby](http://ruby-lang.org/) (>= 1.9.1) or [JRuby](http://jruby.org/) (>= 1.4.0) * [RDF.rb](http://rubygems.org/gems/rdf) (>= 0.1.9) * [SXP](http://rubygems.org/gems/sxp) (>= 0.0.3) +* [Promise](http://rubygems.org/gems/promise) (>= 0.1.0) Installation ------------ The recommended installation method is via [RubyGems](http://rubygems.org/). To install the latest official release of the `trith` gem, do one of the following: $ [sudo] gem install trith # Ruby 1.9+ $ [sudo] gem1.9 install trith # Ruby 1.9 with MacPorts $ [sudo] jruby --1.9 -S gem install trith # JRuby 1.4+ Once Trith is installed, you will have four new programs available: * `3sh`, aka "trish", is the Trith interactive shell and interpreter. * `3vm`, aka "trivium", is the Trith virtual machine runtime. * `3cc`, aka "tricksy", is the Trith compiler. * `3th`, aka "trith", is the Trith package manager. Note that as of the current release, only the first two do anything much as yet. Environment ----------- The following are the default settings for environment variables that let you customize how Trith works: $ export TRITH_HOME=~/.trith $ export TRITH_CACHE=$TRITH_HOME/cache $ export TRITH_TERM=$TERM Download -------- To get a local working copy of the development repository, do: $ git clone git://github.com/trith/trith.git Alternatively, you can download the latest development version as a tarball as follows: $ wget http://github.com/trith/trith/tarball/master Mailing List ------------ * <http://groups.google.com/group/trith> Authors ------- * [Arto Bendiken](mailto:[email protected]) - <http://ar.to/> License ------- Trith is free and unencumbered public domain software. For more information, see <http://unlicense.org/> or the accompanying UNLICENSE file. [stack-oriented]: http://en.wikipedia.org/wiki/Stack-oriented_programming_language [concatenative]: http://en.wikipedia.org/wiki/Concatenative_programming_language [composition]: http://en.wikipedia.org/wiki/Function_composition [type system]: http://en.wikipedia.org/wiki/Type_system#Dynamic_typing [homoiconic]: http://en.wikipedia.org/wiki/Homoiconicity [S-expression]: http://en.wikipedia.org/wiki/S-expression [RDF]: http://en.wikipedia.org/wiki/Resource_Description_Framework [JVM]: http://en.wikipedia.org/wiki/Java_Virtual_Machine [Lisp]: http://en.wikipedia.org/wiki/Lisp_(programming_language) [Scheme]: http://en.wikipedia.org/wiki/Scheme_(programming_language) [Forth]: http://en.wikipedia.org/wiki/Forth_(programming_language) [Factor]: http://en.wikipedia.org/wiki/Factor_(programming_language) [Joy]: http://en.wikipedia.org/wiki/Joy_(programming_language) [Cat]: http://en.wikipedia.org/wiki/Cat_(programming_language) [XY]: http://www.nsl.com/k/xy/xy.htm [Linked Data]: http://linkeddata.org/ [lispers.org]: http://lispers.org/ [concat.org]: http://concatenative.org/wiki/view/Concatenative%20language
trith/trith
db387910a7fba345da4b548892d294f41d09ff27
Reined in Ruby stack growth in the control structure primitives.
diff --git a/lib/trith/core/execution.rb b/lib/trith/core/execution.rb index 5b603a1..eddf66c 100644 --- a/lib/trith/core/execution.rb +++ b/lib/trith/core/execution.rb @@ -1,165 +1,165 @@ module Trith; module Core ## # Execution control operators. module Execution ## # @return [Machine] def reset @stack.clear @queue.clear self end ## # @return [Machine] def halt @queue.clear self end ## # @return [Machine] def nop self # do nothing end alias_method :',', :nop alias_method :';', :nop ## # @return [Machine] def quote push([shift]) end alias_method :'\\', :quote alias_method :"'", :quote ## # @return [Machine] def call(quot) case quot when Array - execute(quot) + unshift(*quot) when Symbol - execute([quot]) # FIXME + unshift(quot) # FIXME else # TODO: error end self end ## # @return [Machine] def times(quot, count) - case quot - when Array - count.to_i.times { execute(quot) } - when Symbol - count.to_i.times { execute([quot]) } # FIXME - else # TODO: error + with_saved_continuation(:times) do + case quot + when Array + count.to_i.times { unshift(quot, :call) } + when Symbol + count.to_i.times { unshift([quot], :call) } # FIXME + else # TODO: error + end end - self end ## # @return [Machine] def twice(quot) - case quot - when Array - 2.times { execute(quot) } - when Symbol - 2.times { execute([quot]) } # FIXME - else # TODO: error + with_saved_continuation(:twice) do + case quot + when Array + 2.times { unshift(quot, :call) } + when Symbol + 2.times { unshift([quot], :call) } # FIXME + else # TODO: error + end end - self end alias_method :'2x', :twice ## # @return [Machine] def thrice(quot) - case quot - when Array - 3.times { execute(quot) } - when Symbol - 3.times { execute([quot]) } # FIXME - else # TODO: error + with_saved_continuation(:thrice) do + case quot + when Array + 3.times { unshift(quot, :call) } + when Symbol + 3.times { unshift([quot], :call) } # FIXME + else # TODO: error + end end - self end alias_method :'3x', :thrice ## # @return [Machine] def loop(quot) case quot when Array - execute([quot, :loop]) - execute(quot) + unshift(quot, :call, quot, :loop) when Symbol - execute([quot, :quote, quot, :loop]) # FIXME + unshift(quot, [quot], :loop) # FIXME else # TODO: error end self end ## # @return [Machine] def while(quot, cond) with_saved_continuation(:while) do - Kernel.loop do + Kernel.loop do # FIXME execute(cond) case pop when false, nil then break else execute(quot) end end end - self end ## # @return [Machine] def until(quot, cond) with_saved_continuation(:until) do - Kernel.loop do + Kernel.loop do # FIXME execute(cond) case pop when false, nil then execute(quot) else break end end end - self end ## # @return [Machine] def branch(cond, thenop, elseop) case cond - when false, nil then execute(elseop) - else execute(thenop) + when false, nil then unshift(elseop, :call) + else unshift(thenop, :call) end self end alias_method :if, :branch ## # @return [Machine] def when(cond, quot) case cond when false, nil then # nop - else execute(quot) + else unshift(quot, :call) end self end ## # @return [Machine] def unless(cond, quot) case cond - when false, nil then execute(quot) + when false, nil then unshift(quot, :call) else # nop end self end end # module Execution end; end # module Trith::Core diff --git a/lib/trith/machine.rb b/lib/trith/machine.rb index 23d6066..95ea804 100644 --- a/lib/trith/machine.rb +++ b/lib/trith/machine.rb @@ -1,380 +1,380 @@ module Trith ## # The Trith virtual machine. class Machine # @return [Array] attr_reader :stack # @return [Array] attr_reader :queue # @return [Proc] attr_accessor :execute_hook ## # Executes `code` in a new virtual machine instance. # # The machine will halt when the queue is exhausted, when encountering # a `halt` operator, or when encountering an error condition. # # @overload self.run(code) # @param [Array] code # @return [Object] # # @overload self.run(code) # @param [Array] code # @yield [machine] # @yieldparam [Machine] machine # @return [Object] # # @return [Object] def self.run(code = [], &block) self.new([], code).execute(&block).peek end ## # Initializes a new virtual machine with the given initial `stack`, # `queue` and environment. # # @param [Array] stack # @param [Array] queue # @param [Hash] env # @yield [machine] # @yieldparam [Machine] machine def initialize(stack = [], queue = [], env = {}, &block) @stack, @queue, @env = stack, queue, {} import!(Trith::Core) env.each do |name, operator| if operator.is_a?(Proc) define!(name, &operator) else define!(name, operator) end end execute(&block) if block_given? end ## # Returns a developer-friendly representation of this machine. # # @return [String] def inspect sprintf("#<%s:%#0x(%s : %s)>", self.class.name, __id__, @stack.inspect, @queue.inspect) end ## # Imports operators from the given `module` into the virtual machine's # current environment. # # @param [Module] module # @return [Machine] def import!(mod) case mod when Module then import_module!(mod) when Function then # TODO else # TODO: error end self end ## # Defines a new operator `name` that will execute the given `code`. # # @param [Symbol, #to_sym] name # @param [Array] code # @param [Hash{Symbol => Object}] options # @return [Machine] def define!(name, code = [], options = {}, &block) @env[name = name.to_sym] = lambda { execute(code, &block) } unless options[:method] == false this = class << self; self; end this.send(:define_method, name, &@env[name]) end self end ## # Returns the concatenation of the stack and queue. # # @return [Array] def to_a (@stack + @queue).to_a end ## # Returns the operand at the top of the stack. # # If the stack is empty, returns `nil`. # # @return [Object] def peek @stack.last end ## # Pops and returns one or more operands off the top of the stack. # # If the stack doesn't have sufficient operands, raises a stack # underflow error. # # @overload pop # @return [Object] # # @overload pop(n) # @param [Integer] n # @return [Array] # # @return [Object] # @raise [StackUnderflowError] def pop(n = nil) if @stack.size < (n || 1) raise StackUnderflowError.new else n ? @stack.pop(n) : @stack.pop end end ## # Pushes the given operands onto the top of the stack. # # If no operands were given, shifts an operand off the front of the # queue. # # @overload push # @return [Machine] # # @overload push(*ops) # @param [Array] ops # @return [Machine] # # @return [Machine] def push(*ops) @stack.push(*(ops.empty? ? [shift] : ops)) self end ## # Shifts and returns one or more operands off the front of the queue. # # If the queue doesn't have sufficient operands, throws a `:halt` # symbol. # # @overload shift # @return [Object] # # @overload shift(n) # @param [Integer] n # @return [Array] # # @return [Object] def shift(n = nil) if @queue.size < (n || 1) throw(:halt) # caught in `#execute` else n ? @queue.shift(n) : @queue.shift end end ## # Prepends the given operands onto the front of the queue. # # If no operands were given, pops an operand off the top of the stack. # # @overload unshift # @return [Machine] # # @overload unshift(*ops) # @param [Array] ops # @return [Machine] # # @return [Machine] def unshift(*ops) @queue.unshift(*(ops.empty? ? [pop] : ops)) self end ## # Executes the virtual machine until it halts. # # The machine will halt when the queue is exhausted, when encountering # a `halt` operator, or when encountering an error condition. # # @overload execute(code) # @param [Array] code # @return [Machine] # # @overload execute(code) # @param [Array] code # @yield [machine] # @yieldparam [Machine] machine # @return [Machine] # # @return [Machine] def execute(code = [], &block) @queue.unshift(*code) unless code.empty? catch(:halt) do # thrown in `#shift` Kernel.loop do execute_hook.call if execute_hook && [email protected]? op = shift case when operator?(op) if fn = @env[op] fn.call else unshift(op) raise InvalidOperatorError.new(op) end when operand?(op) push(op) else raise InvalidOperandError.new(op) end end end if block_given? case block.arity when 1 then block.call(self) else instance_eval(&block) end end return self end protected ## # Returns `true` if `op` is an operator. # # @param [Object] op # @return [Boolean] def operator?(op) op.is_a?(Symbol) end ## # Returns `true` if `op` is an operand. # # @param [Object] op # @return [Boolean] def operand?(op) !operator?(op) end ## # Returns `true` if `op` is a quotation. # # @param [Object] op # @return [Boolean] def quotation?(op) op.is_a?(Array) end ## # @private def method_missing(operator, *operands, &block) begin super rescue NoMethodError => e raise InvalidOperatorError.new(operator) end end ## # Imports operators from the given `module` into the virtual machine's # current environment. # # @param [Module] module # @return [void] def import_module!(mod) # Include all instance methods from the module into `self`: this = class << self; self; end this.send(:include, mod) # Create wrapper methods to support operators that need their # arguments and result marshalled from/to the virtual machine stack: mod.public_instance_methods(true).map(&:to_sym).each do |method| op = mod.instance_method(method).bind(self) case method when :stack_ # FIXME @env[:stack] = op else @env[method] = this.send(:define_method, method) do |*args| result = op.call(*(!args.empty? ? args : (op.arity > 0 ? pop(op.arity) : []))) push(result) unless result.equal?(self) return self end end end end ## # Invokes the given block with an empty code queue, restoring the # queue contents after the block returns. # # @yield # @param [Symbol] name # @return [void] def with_saved_continuation(name = nil, &block) cc = capture_continuation case block.arity when 1 then block.call(cc) else block.call end - @queue.unshift(*cc) + @queue.push(*cc) unless cc.empty? self end ## # Invokes the given block with an empty code queue, passing the previous # queue contents as an argument. # # @yield # @return [void] def with_current_continuation(&block) block.call(capture_continuation) self end ## # Captures the current contents of the code queue, returning them to the # caller after first clearing the queue. # # @return [Array] def capture_continuation(full = false) continuation = @queue.dup @queue.clear continuation end ### # Invalid operator class InvalidOperatorError < NoMethodError attr_reader :operator def initialize(operator) @operator = operator super("invalid operator: #{operator}") end end ### # Invalid operand class InvalidOperandError < ArgumentError attr_reader :operand attr_reader :operator def initialize(operand, operator = nil) @operand, @operator = operand, operator super("invalid operand: #{operand.inspect}") end end ### # Stack underflow class StackUnderflowError < RuntimeError; end end # class Machine end # module Trith
trith/trith
1641185e5bd1e45067150493b213797993402a3c
Implemented the Trith::Core#foldl1 operator.
diff --git a/etc/trith-core.ttl b/etc/trith-core.ttl index c8d99fb..d6b5870 100644 --- a/etc/trith-core.ttl +++ b/etc/trith-core.ttl @@ -11,715 +11,721 @@ <abs> a trith:Function ; rdfs:label "abs" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . <add> a trith:Function, trith:Primitive ; rdfs:label "add", "+" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <and> a trith:Function, trith:Primitive ; rdfs:label "and" ; rdfs:comment "Bitwise AND" ; trith:arity 2 ; trith:code () . <andp> a trith:Function ; rdfs:label "andp", "and?" ; rdfs:comment "Logical AND" ; trith:arity 2 ; trith:code (<swap> <dup> (<swap> <dup> (<swap> <drop>) (<drop2> <false>) <branch>) (<drop2> <false>) <branch>) . <bool> a trith:Function ; rdfs:label "bool" ; rdfs:comment "" ; trith:arity 1 ; trith:code ((<true>) (<false>) <branch>) . <boolp> a trith:Function ; rdfs:label "boolp", "bool?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<dup> <truep> <swap> <falsep> <orp>) . <branch> a trith:Function, trith:Primitive ; rdfs:label "branch", "if" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . <call> a trith:Function, trith:Primitive ; rdfs:label "call" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <ceil> a trith:Function ; rdfs:label "ceil" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <chr> a trith:Function, trith:Primitive ; rdfs:label "chr" ; rdfs:comment "" ; rdfs:seeAlso <ord> ; trith:arity 1 ; trith:code () . <chrp> a trith:Function, trith:Primitive ; rdfs:label "chrp", "chr?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <clear> a trith:Function, trith:Primitive ; rdfs:label "clear" ; rdfs:comment "Clear the data stack" ; trith:arity 0 ; trith:code () . <cmp> a trith:Function, trith:Primitive ; rdfs:label "cmp", "<=>" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <concat> a trith:Function ; rdfs:label "concat" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<swap> <reverse> <swap> (<dup> <first> <swap> <rest> <swap> <rot> <cons> <swap>) (<dup> <emptyp>) <until> <drop> <reverse>) . <cons> a trith:Function, trith:Primitive ; rdfs:label "cons" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <depth> a trith:Function ; rdfs:label "depth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<stack> <dup> <length> () <cons> <concat> <unstack>) . <dec> a trith:Function ; rdfs:label "dec" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <sub>) . <dip> a trith:Function, trith:Primitive ; rdfs:label "dip" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <div> a trith:Function ; rdfs:label "div", "/" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <drop> a trith:Function, trith:Primitive ; rdfs:label "drop" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <drop2> a trith:Function ; rdfs:label "drop2", "2drop" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<drop>) <twice>) . <drop3> a trith:Function ; rdfs:label "drop3", "3drop" ; rdfs:comment "" ; trith:arity 3 ; trith:code ((<drop>) <thrice>) . <dup> a trith:Function, trith:Primitive ; rdfs:label "dup" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <dup2> a trith:Function, trith:Primitive ; rdfs:label "dup2", "2dup" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <dup3> a trith:Function, trith:Primitive ; rdfs:label "dup3", "3dup" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . <each> a trith:Function ; rdfs:label "each" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <eighth> a trith:Function ; rdfs:label "eighth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (7 <nth>) . <emptyp> a trith:Function ; rdfs:label "emptyp", "empty?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<length> <zerop>) . <eq> a trith:Function, trith:Primitive ; rdfs:label "eq", "=" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <evenp> a trith:Function ; rdfs:label "evenp", "even?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (2 <mod> <zerop>) . <exactp> a trith:Function ; rdfs:label "exactp", "exact?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<inexactp> <notp>) . <false> a trith:Function ; rdfs:label "false" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<quote> <false>) . <falsep> a trith:Function ; rdfs:label "falsep", "false?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<false> <eq>) . <fifth> a trith:Function ; rdfs:label "fifth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (4 <nth>) . <first> a trith:Function, trith:Primitive ; rdfs:label "first" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <flatten> a trith:Function ; rdfs:label "flatten" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <floor> a trith:Function ; rdfs:label "floor" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <fourth> a trith:Function ; rdfs:label "fourth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (3 <nth>) . <ge> a trith:Function ; rdfs:label "ge", ">=" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <gt> a trith:Function ; rdfs:label "gt", ">" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<cmp> <onep>) . <halt> a trith:Function, trith:Primitive ; rdfs:label "halt" ; rdfs:comment "" ; trith:arity 0 ; trith:code () . <inc> a trith:Function ; rdfs:label "inc" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <add>) . <inexactp> a trith:Function ; rdfs:label "inexactp", "inexact?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<exactp> <notp>) . <inf> a trith:Function ; rdfs:label "inf" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1.0 0.0 <div>) . <infp> a trith:Function ; rdfs:label "infp", "inf?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<abs> <inf> <eq>) . <intp> a trith:Function, trith:Primitive ; rdfs:label "intp", "int?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <iota> a trith:Function ; rdfs:label "iota" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <last> a trith:Function ; rdfs:label "last" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <le> a trith:Function ; rdfs:label "le", "<=" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <length> a trith:Function ; rdfs:label "length" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 (<rest> <swap> <inc>) (<swap> <dup> <emptyp>) <until> <drop>) . <list> a trith:Function ; rdfs:label "list" ; rdfs:comment "" ; trith:arity 1 ; trith:code (() <swap> (<cons>) <swap> <times> <reverse>) . <loop> a trith:Function ; rdfs:label "loop" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<dup> <call> (<loop>) <call>) . <lt> a trith:Function ; rdfs:label "lt", "<" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<cmp> -1 <eq>) . <map> a trith:Function ; rdfs:label "map" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <max> a trith:Function ; rdfs:label "max" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<dup2> <gt> (<drop>) (<swap> <drop>) <branch>) . <memberp> a trith:Function ; rdfs:label "memberp", "member?" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <min> a trith:Function ; rdfs:label "min" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<dup2> <lt> (<drop>) (<swap> <drop>) <branch>) . <mod> a trith:Function ; rdfs:label "mod" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <mul> a trith:Function ; rdfs:label "mul", "*" ; rdfs:comment "" ; trith:arity 2 ; trith:code (0 <swap> <abs> (<over> <add>) <swap> <times> <nip>) . # FIXME: negative operands <ne> a trith:Function ; rdfs:label "ne", "!=" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<eq> <notp>) . <neg> a trith:Function ; rdfs:label "neg" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <swap> <sub>) . <negp> a trith:Function ; rdfs:label "negp", "neg?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <lt>) . <nil> a trith:Function ; rdfs:label "nil" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<quote> <nil>) . <nilp> a trith:Function ; rdfs:label "nilp", "nil?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<nil> <eq>) . <ninth> a trith:Function ; rdfs:label "ninth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (8 <nth>) . <nip> a trith:Function ; rdfs:label "nip" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<swap> <drop>) . <nip2> a trith:Function ; rdfs:label "nip2", "2nip" ; rdfs:comment "" ; trith:arity 3 ; trith:code (<swap> <drop> <swap> <drop>) . <nop> a trith:Function ; rdfs:label "nop", ",", ";" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<nil> <drop>) . <not> a trith:Function ; rdfs:label "not" ; rdfs:comment "Bitwise NOT" ; trith:arity 1 ; trith:code (<neg> <dec>) . <notp> a trith:Function ; rdfs:label "notp", "not?" ; rdfs:comment "Logical NOT" ; trith:arity 1 ; trith:code ((<false>) (<true>) <branch>) . <nth> a trith:Function ; rdfs:label "nth" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<rest>) <swap> <times> <first>) . <num> a trith:Function, trith:Primitive ; rdfs:label "num" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <nump> a trith:Function, trith:Primitive ; rdfs:label "nump", "num?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <oddp> a trith:Function ; rdfs:label "oddp", "odd?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<evenp> <notp>) . <onep> a trith:Function ; rdfs:label "onep", "one?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <eq>) . <or> a trith:Function, trith:Primitive ; rdfs:label "or" ; rdfs:comment "Bitwise OR" ; trith:arity 2 ; trith:code () . <ord> a trith:Function, trith:Primitive ; rdfs:label "ord" ; rdfs:comment "" ; rdfs:seeAlso <chr> ; trith:arity 1 ; trith:code () . <orp> a trith:Function ; rdfs:label "orp", "or?" ; rdfs:comment "Logical OR" ; trith:arity 2 ; trith:code (<swap> <dup> (<swap> <drop>) (<drop>) <branch>) . <over> a trith:Function ; rdfs:label "over" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<dup2> <drop>) . <pick> a trith:Function ; rdfs:label "pick" ; rdfs:comment "" ; trith:arity 3 ; trith:code (<dup3> <drop2>) . <posp> a trith:Function ; rdfs:label "posp", "pos?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <gt>) . <pow> a trith:Function ; rdfs:label "pow" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <print> a trith:Function ; rdfs:label "print", "print!", "." ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <quote> a trith:Function, trith:Primitive ; rdfs:label "quote", "\\", "'" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <foldl> a trith:Function ; rdfs:label "foldl", "fold", "reduce" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . # TODO +<foldl1> a trith:Function ; + rdfs:label "foldl1" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code (<swap> <dup> <emptyp> (<drop2> <nil>) (<dup> <rest> <swap> <first> <rot> <foldl>) <branch>) . + <range> a trith:Function ; rdfs:label "range" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <rem> a trith:Function ; rdfs:label "rem" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <reset> a trith:Function ; rdfs:label "reset" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<clear> <halt>) . <rest> a trith:Function, trith:Primitive ; rdfs:label "rest" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <reverse> a trith:Function ; rdfs:label "reverse" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <rot> a trith:Function, trith:Primitive ; rdfs:label "rot" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . <second> a trith:Function ; rdfs:label "second" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <nth>) . <seq> a trith:Function, trith:Primitive ; rdfs:label "seq" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <seqp> a trith:Function, trith:Primitive ; rdfs:label "seqp", "seq?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <seventh> a trith:Function ; rdfs:label "seventh" ; rdfs:comment "" ; trith:arity 1 ; trith:code (6 <nth>) . <shl> a trith:Function, trith:Primitive ; rdfs:label "shl" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <shr> a trith:Function, trith:Primitive ; rdfs:label "shr" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <sixth> a trith:Function ; rdfs:label "sixth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (5 <nth>) . <size> a trith:Function, trith:Primitive ; rdfs:label "size" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <stack> a trith:Function ; rdfs:label "stack" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<depth> <list>) . <sub> a trith:Function, trith:Primitive ; rdfs:label "sub", "-" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <swap> a trith:Function, trith:Primitive ; rdfs:label "swap" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <tenth> a trith:Function ; rdfs:label "tenth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (9 <nth>) . <text> a trith:Function ; rdfs:label "text" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <textp> a trith:Function ; rdfs:label "textp", "text?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <third> a trith:Function ; rdfs:label "third" ; rdfs:comment "" ; trith:arity 1 ; trith:code (2 <nth>) . <thrice> a trith:Function ; rdfs:label "thrice", "3x" ; rdfs:comment "" ; trith:arity 1 ; trith:code (3 <times>) . <times> a trith:Function ; rdfs:label "times" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<dec> <over> <call>) (<dup> <zerop>) <until> <drop2>) . <true> a trith:Function ; rdfs:label "true" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<quote> <true>) . <truep> a trith:Function ; rdfs:label "truep", "true?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<true> <eq>) . <twice> a trith:Function ; rdfs:label "twice", "2x" ; rdfs:comment "" ; trith:arity 1 ; trith:code (2 <times>) . <unless> a trith:Function ; rdfs:label "unless" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<nop>) <swap> <branch>) . <unstack> a trith:Function, trith:Primitive ; rdfs:label "unstack" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <until> a trith:Function ; rdfs:label "until" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<notp>) <concat> <while>) . <when> a trith:Function ; rdfs:label "when" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<nop>) <branch>) . <while> a trith:Function ; rdfs:label "while" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <xor> a trith:Function, trith:Primitive ; rdfs:label "xor" ; rdfs:comment "Bitwise XOR" ; trith:arity 2 ; trith:code () . <xorp> a trith:Function ; rdfs:label "xorp", "xor?" ; rdfs:comment "Logical XOR" ; trith:arity 2 ; trith:code (<swap> <dup> (<swap> (<drop> <false>) (<nop>) <branch>) (<drop> <dup> (<nop>) (<drop> <false>) <branch>) <branch>) . <zerop> a trith:Function ; rdfs:label "zerop", "zero?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <eq>) . diff --git a/lib/trith/core/sequence.rb b/lib/trith/core/sequence.rb index 3a16641..3203203 100644 --- a/lib/trith/core/sequence.rb +++ b/lib/trith/core/sequence.rb @@ -1,434 +1,453 @@ module Trith; module Core ## # Sequence operators. # # @see http://ruby-doc.org/core-1.9/classes/Enumerable.html # @see http://ruby-doc.org/core-1.9/classes/Enumerator.html # @see http://en.wikipedia.org/wiki/Sequence module Sequence ## # Sequence predicates. module Predicates ## # @param [String, #each, #to_enum] obj # @return [Boolean] def seqp(obj) case obj when String then true when Array then true else case when obj.respond_to?(:each) then true when obj.respond_to?(:to_enum) then true else false end end end alias_method :seq?, :seqp ## # @param [#empty?, #size, #each] seq # @return [Boolean] def emptyp(seq) case when seq.respond_to?(:empty?) seq.empty? when seq.respond_to?(:size) seq.size.zero? when seq.respond_to?(:each) seq.each.to_a.empty? # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :emptyp) end end alias_method :empty?, :emptyp ## # @param [Object] elt # @param [#member?, #each] seq # @return [Boolean] def memberp(elt, seq) case when seq.respond_to?(:member?) seq.member?(elt) when seq.respond_to?(:each) seq.each.member?(elt) else raise Machine::InvalidOperandError.new(seq, :memberp) end end alias_method :member?, :memberp end # module Predicates ## # Sequence constructors. module Constructors ## # @param [String, #each, #to_enum] obj # @return [Enumerator] def seq(obj) case obj when String then obj.each_char when Array then obj.each else case when obj.respond_to?(:each) obj.each when obj.respond_to?(:to_enum) obj.to_enum else raise Machine::InvalidOperandError.new(obj, :seq) end end end ## # @overload cons(obj, seq) # @param [#to_s] obj # @param [String] seq # @return [String] # # @overload cons(obj, seq) # @param [Object] obj # @param [Array, #to_a] seq # @return [Array] # # @return [] def cons(obj, seq) case seq when String seq.dup.insert(0, obj.to_s.chr) when Array seq.dup.unshift(obj) else case when seq.respond_to?(:to_a) seq.to_a.unshift(obj) else # TODO: support for `#each` end end end ## # @param [Integer, #to_i] n # @return [Enumerable] def list(n) stack.pop(n.to_i) end ## # @param [Integer, #to_i] n # @return [Enumerable] def iota(n) # TODO: should support negative ranges as well. (0...(n.to_i)).to_a # FIXME end ## # @param [Integer, #to_i] a # @param [Integer, #to_i] b # @return [Enumerable] def range(a, b) # TODO: should support negative ranges as well. ((a.to_i)..(b.to_i)).to_a # FIXME end end # module Constructors ## # Sequence accessors. module Accessors ## # @param [#length, #size, #each] seq # @return [Integer] def length(seq) case when seq.respond_to?(:length) seq.length when seq.respond_to?(:size) seq.size when seq.respond_to?(:each) seq.each.to_a.size # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :length) end end ## # @param [#rest, #[], #each] seq # @return [Enumerable] def rest(seq) # TODO: check semantics for empty sequences case when seq.respond_to?(:rest) seq.rest when seq.respond_to?(:[]) seq[1..-1] when seq.respond_to?(:each) seq.each.to_a[1..-1] # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :rest) end end ## # @param [#first, #[], #each] seq # @return [Object] def first(seq) case seq when String seq[0].chr rescue nil # Ruby 1.8 compatible else case when seq.respond_to?(:first) then seq.first else nth(seq, 0) end end end ## # @param [#second, #[], #each] seq # @return [Object] def second(seq) case when seq.respond_to?(:second) then seq.second else nth(seq, 1) end end ## # @param [#third, #[], #each] seq # @return [Object] def third(seq) case when seq.respond_to?(:third) then seq.third else nth(seq, 2) end end ## # @param [#fourth, #[], #each] seq # @return [Object] def fourth(seq) case when seq.respond_to?(:fourth) then seq.fourth else nth(seq, 3) end end ## # @param [#fifth, #[], #each] seq # @return [Object] def fifth(seq) case when seq.respond_to?(:fifth) then seq.fifth else nth(seq, 4) end end ## # @param [#sixth, #[], #each] seq # @return [Object] def sixth(seq) case when seq.respond_to?(:sixth) then seq.sixth else nth(seq, 5) end end ## # @param [#seventh, #[], #each] seq # @return [Object] def seventh(seq) case when seq.respond_to?(:seventh) then seq.seventh else nth(seq, 6) end end ## # @param [#eighth, #[], #each] seq # @return [Object] def eighth(seq) case when seq.respond_to?(:eighth) then seq.eighth else nth(seq, 7) end end ## # @param [#ninth, #[], #each] seq # @return [Object] def ninth(seq) case when seq.respond_to?(:ninth) then seq.ninth else nth(seq, 8) end end ## # @param [#tenth, #[], #each] seq # @return [Object] def tenth(seq) case when seq.respond_to?(:tenth) then seq.tenth else nth(seq, 9) end end ## # @param [#nth, #[], #each] seq # @param [Integer, #to_i] n # @return [Object] def nth(seq, n) case seq when String seq[n.to_i].chr rescue nil # Ruby 1.8 compatible else case when seq.respond_to?(:nth) seq.nth(n) when seq.respond_to?(:[]) seq[n.to_i] when seq.respond_to?(:each) seq.each.to_a[n.to_i] # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :nth) end end end ## # @param [#last, #[], #each] seq # @return [Object] def last(seq) case seq when String seq[-1].chr rescue nil # Ruby 1.8 compatible else case when seq.respond_to?(:last) seq.last when seq.respond_to?(:[]) seq[-1] when seq.respond_to?(:each) seq.each.to_a.last # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :last) end end end end # module Accessors ## # Sequence operators. module Operators ## # @param [#concat, #each] seq1 # @param [#each] seq2 # @return [Enumerable] def concat(seq1, seq2) case when seq1.respond_to?(:concat) seq1.dup.concat(seq2) when seq1.respond_to?(:each) seq1.each.to_a.concat(seq2.each.to_a) # TODO: optimize else raise Machine::InvalidOperandError.new(seq1, :concat) end end ## # @param [#reverse, #each] seq # @return [Enumerable] def reverse(seq) case seq when String then seq.reverse when Array then seq.reverse else case when seq.respond_to?(:reverse) seq.reverse when seq.respond_to?(:each) seq.each.to_a.reverse # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :reverse) end end end ## # @param [#flatten, #each] seq # @return [Enumerable] def flatten(seq) case seq when String then seq when Array then seq.flatten else case when seq.respond_to?(:flatten) seq.flatten when seq.respond_to?(:each) seq.each.to_a.flatten # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :flatten) end end end end # module Operators ## # Sequence combinators. module Combinators ## # @param [#each] seq # @param [Array] quot # @return [Machine] def each(seq, quot) seq = case seq when String then seq.each_char else case when seq.respond_to?(:each) then seq.each else raise Machine::InvalidOperandError.new(seq, :each) end end with_saved_continuation(:each) do seq.each { |elem| push(elem).execute(quot) } end end ## # @param [#map, #each] seq # @param [Array] quot # @return [Machine] def map(seq, quot) seq = case seq when String then seq.each_char else case when seq.respond_to?(:map) then seq when seq.respond_to?(:each) then seq.each else raise Machine::InvalidOperandError.new(seq, :map) end end with_saved_continuation(:map) do push(seq.map { |elem| push(elem).execute(quot).pop }) end end ## # @param [#reduce, #each] seq # @param [Object] identity # @param [Array] quot # @return [Machine] def foldl(seq, identity, quot) seq = case seq when String then seq.each_char else case when seq.respond_to?(:reduce) then seq when seq.respond_to?(:each) then seq.each else raise Machine::InvalidOperandError.new(seq, :foldl) end end with_saved_continuation(:foldl) do push(seq.reduce(identity) { |prev, elem| push(prev, elem).execute(quot).pop }) end end alias_method :fold, :foldl alias_method :reduce, :foldl + + ## + # @param [#reduce, #each] seq + # @param [Array] quot + # @return [Machine] + def foldl1(seq, quot) + raise Machine::InvalidOperandError.new(seq, :foldl1) if seq.empty? + seq = case seq + when String then seq.each_char.to_a + else case + when seq.respond_to?(:reduce) then seq.dup + when seq.respond_to?(:each) then seq.each.to_a + else raise Machine::InvalidOperandError.new(seq, :foldl1) + end + end + with_saved_continuation(:foldl1) do + push(seq.reduce(seq.pop) { |prev, elem| push(prev, elem).execute(quot).pop }) + end + end end # module Combinators # Include all submodule methods directly into Trith::Core::Sequence: constants.each { |mod| include(const_get(mod)) } end # module Sequence end; end # module Trith::Core diff --git a/spec/machine_spec.rb b/spec/machine_spec.rb index f5fb551..2d995b2 100644 --- a/spec/machine_spec.rb +++ b/spec/machine_spec.rb @@ -309,551 +309,555 @@ describe Trith::Machine do Machine.new.should respond_to(:false) # TODO end it "should implement the :true operator" do Machine.new.should respond_to(:true) # TODO end end context "Comparison operators" do it "should implement the :cmp operator" do Machine.new.should respond_to(:cmp, :<=>) # TODO end it "should implement the :eq operator" do Machine.new.should respond_to(:eq, :'=') # TODO end it "should implement the :ne operator" do Machine.new.should respond_to(:ne, :'!=') # TODO end it "should implement the :lt operator" do Machine.new.should respond_to(:lt, :<) # TODO end it "should implement the :le operator" do Machine.new.should respond_to(:le, :<=) # TODO end it "should implement the :gt operator" do Machine.new.should respond_to(:gt, :>) # TODO end it "should implement the :ge operator" do Machine.new.should respond_to(:ge, :>=) # TODO end it "should implement the :min operator" do Machine.new.should respond_to(:min) # TODO end it "should implement the :max operator" do Machine.new.should respond_to(:max) # TODO end end context "Numeric predicates" do it "should implement the :nump operator" do Machine.new.should respond_to(:nump, :num?) # TODO end it "should implement the :intp operator" do Machine.new.should respond_to(:intp, :int?) # TODO end it "should implement the :infp operator" do Machine.new.should respond_to(:infp, :inf?) # TODO end it "should implement the :zerop operator" do Machine.new.should respond_to(:zerop, :zero?) # TODO end it "should implement the :onep operator" do Machine.new.should respond_to(:onep, :one?) # TODO end it "should implement the :negp operator" do Machine.new.should respond_to(:negp, :neg?) # TODO end it "should implement the :posp operator" do Machine.new.should respond_to(:posp, :pos?) # TODO end it "should implement the :oddp operator" do Machine.new.should respond_to(:oddp, :odd?) # TODO end it "should implement the :evenp operator" do Machine.new.should respond_to(:evenp, :even?) # TODO end end context "Numeric constructors" do it "should implement the :num operator" do Machine.new.should respond_to(:num) # TODO end it "should implement the :int operator" do Machine.new.should respond_to(:int) # TODO end it "should implement the :inf operator" do Machine.new.should respond_to(:inf) # TODO end end context "Math constants" do it "should implement the :pi operator" do Machine.new.should respond_to(:pi) # TODO end end context "Math operators" do it "should implement the :ceil operator" do Machine.new.should respond_to(:ceil) # TODO end it "should implement the :floor operator" do Machine.new.should respond_to(:floor) # TODO end it "should implement the :round operator" do Machine.new.should respond_to(:round) # TODO end it "should implement the :sq operator" do Machine.new.should respond_to(:sq) # TODO end it "should implement the :sqrt operator" do Machine.new.should respond_to(:sqrt) # TODO end it "should implement the :cb operator" do Machine.new.should respond_to(:cb) # TODO end it "should implement the :cbrt operator" do Machine.new.should respond_to(:cbrt) # TODO end it "should implement the :exp operator" do Machine.new.should respond_to(:exp) # TODO end it "should implement the :log operator" do Machine.new.should respond_to(:log) # TODO end it "should implement the :log2 operator" do Machine.new.should respond_to(:log2) # TODO end it "should implement the :log10 operator" do Machine.new.should respond_to(:log10) # TODO end it "should implement the :hypot operator" do Machine.new.should respond_to(:hypot) # TODO end it "should implement the :cos operator" do Machine.new.should respond_to(:cos) # TODO end it "should implement the :cosh operator" do Machine.new.should respond_to(:cosh) # TODO end it "should implement the :sin operator" do Machine.new.should respond_to(:sin) # TODO end it "should implement the :sinh operator" do Machine.new.should respond_to(:sinh) # TODO end it "should implement the :tan operator" do Machine.new.should respond_to(:tan) # TODO end it "should implement the :tanh operator" do Machine.new.should respond_to(:tanh) # TODO end it "should implement the :acos operator" do Machine.new.should respond_to(:acos) # TODO end it "should implement the :acosh operator" do Machine.new.should respond_to(:acosh) # TODO end it "should implement the :asin operator" do Machine.new.should respond_to(:asin) # TODO end it "should implement the :asinh operator" do Machine.new.should respond_to(:asinh) # TODO end it "should implement the :atan operator" do Machine.new.should respond_to(:atan) # TODO end it "should implement the :atan2 operator" do Machine.new.should respond_to(:atan2) # TODO end it "should implement the :atanh operator" do Machine.new.should respond_to(:atanh) # TODO end end context "Sequence predicates" do it "should implement the :seqp operator" do Machine.new.should respond_to(:seqp) # TODO end it "should implement the :emptyp operator" do Machine.new.should respond_to(:emptyp) # TODO end it "should implement the :memberp operator" do Machine.new.should respond_to(:memberp) # TODO end it "should implement the :anyp operator" do Machine.new.should respond_to(:anyp) # TODO end it "should implement the :allp operator" do Machine.new.should respond_to(:allp) # TODO end end context "Sequence constructors" do it "should implement the :seq operator" do Machine.new.should respond_to(:seq) # TODO end it "should implement the :cons operator" do Machine.new.should respond_to(:cons) # TODO end it "should implement the :list operator" do Machine.new.should respond_to(:list) # TODO end it "should implement the :iota operator" do Machine.new.should respond_to(:iota) # TODO end it "should implement the :range operator" do Machine.new.should respond_to(:range) # TODO end it "should implement the :repeat operator" do Machine.new.should respond_to(:repeat) # TODO end it "should implement the :cycle operator" do Machine.new.should respond_to(:cycle) # TODO end end context "Sequence accessors" do it "should implement the :length operator" do Machine.new.should respond_to(:length) # TODO end it "should implement the :rest operator" do Machine.new.should respond_to(:rest) # TODO end it "should implement the :first operator" do Machine.new.should respond_to(:first) # TODO end it "should implement the :second operator" do Machine.new.should respond_to(:second) # TODO end it "should implement the :third operator" do Machine.new.should respond_to(:third) # TODO end it "should implement the :fourth operator" do Machine.new.should respond_to(:fourth) # TODO end it "should implement the :fifth operator" do Machine.new.should respond_to(:fifth) # TODO end it "should implement the :sixth operator" do Machine.new.should respond_to(:sixth) # TODO end it "should implement the :seventh operator" do Machine.new.should respond_to(:seventh) # TODO end it "should implement the :eighth operator" do Machine.new.should respond_to(:eighth) # TODO end it "should implement the :ninth operator" do Machine.new.should respond_to(:ninth) # TODO end it "should implement the :tenth operator" do Machine.new.should respond_to(:tenth) # TODO end it "should implement the :nth operator" do Machine.new.should respond_to(:nth) # TODO end it "should implement the :last operator" do Machine.new.should respond_to(:last) # TODO end end context "Sequence operators" do it "should implement the :subseq operator" do Machine.new.should respond_to(:subseq) # TODO end it "should implement the :concat operator" do Machine.new.should respond_to(:concat) # TODO end it "should implement the :uniq operator" do Machine.new.should respond_to(:uniq) # TODO end it "should implement the :reverse operator" do Machine.new.should respond_to(:reverse) # TODO end it "should implement the :sort operator" do Machine.new.should respond_to(:sort) # TODO end it "should implement the :sortby operator" do Machine.new.should respond_to(:sortby) # TODO end it "should implement the :flatten operator" do Machine.new.should respond_to(:flatten) # TODO end it "should implement the :zip operator" do Machine.new.should respond_to(:zip) # TODO end it "should implement the :zip1 operator" do Machine.new.should respond_to(:zip1) # TODO end it "should implement the :zip2 operator" do Machine.new.should respond_to(:zip2) # TODO end it "should implement the :zip3 operator" do Machine.new.should respond_to(:zip3) # TODO end it "should implement the :zip4 operator" do Machine.new.should respond_to(:zip4) # TODO end it "should implement the :unzip operator" do Machine.new.should respond_to(:unzip) # TODO end it "should implement the :unzip1 operator" do Machine.new.should respond_to(:unzip1) # TODO end it "should implement the :unzip2 operator" do Machine.new.should respond_to(:unzip2) # TODO end it "should implement the :unzip3 operator" do Machine.new.should respond_to(:unzip3) # TODO end it "should implement the :unzip4 operator" do Machine.new.should respond_to(:unzip4) # TODO end end context "Sequence combinators" do it "should implement the :each operator" do Machine.new.should respond_to(:each) # TODO end it "should implement the :map operator" do Machine.new.should respond_to(:map) Machine.new([[1, 2, 3, 4, 5], [:dup, :mul]]).execute { map }.stack.should == [[1, 4, 9, 16, 25]] end it "should implement the :count operator" do Machine.new.should respond_to(:count) # TODO end it "should implement the :filter operator" do Machine.new.should respond_to(:filter) Machine.new([[1, 2, 3, 4, 5], [2, :mod, 0, :eq]]).execute { filter }.stack.should == [[2, 4]] end it "should implement the :remove operator" do Machine.new.should respond_to(:remove) # TODO end it "should implement the :foldl operator" do Machine.new.should respond_to(:foldl, :fold, :reduce) Machine.new([[1, 2, 3, 4, 5], 0, [:add]]).execute { foldl }.stack.should == [15] Machine.new([[], -1, [:add]]).execute { foldl }.stack.should == [-1] Machine.new([[2, 5, 3], 0, [:add]]).execute { foldl }.stack.should == [10] Machine.new([[2, 5, 3], 0, [:dup, :mul, :add]]).execute { foldl }.stack.should == [38] end + it "should implement the :foldl1 operator" do + Machine.new.should respond_to(:foldl1) + end + it "should implement the :foldr operator" do Machine.new.should respond_to(:foldr) # TODO end end context "Textual predicates" do it "should implement the :chrp operator" do Machine.new.should respond_to(:chrp, :chr?) # TODO end # TODO end context "Textual constructors" do it "should implement the :chr operator" do Machine.new.should respond_to(:chr) Machine.run([97]) { chr }.should == "a" Machine.run([960]) { chr }.should == "\u03c0" # PI end # TODO end context "Textual operators" do it "should implement the :size operator" do Machine.new.should respond_to(:size) # TODO end end context "Output operators" do it "should implement the :print operator" do Machine.new.should respond_to(:print, :print!, :'.') # TODO end end end
trith/trith
e71219f60acb467551c05dc4f6fb5574ffe76748
Added aliases for the :print and :foldl operators.
diff --git a/etc/trith-core.ttl b/etc/trith-core.ttl index 1012716..c8d99fb 100644 --- a/etc/trith-core.ttl +++ b/etc/trith-core.ttl @@ -1,725 +1,725 @@ @base <http://trith.org/core/> . @prefix trith: <http://trith.org/lang/> . @prefix xsd: <http://www.w3.org/2001/XMLSchema#> . @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . @prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix dc: <http://purl.org/dc/terms/> . @prefix foaf: <http://xmlns.com/foaf/0.1/> . @prefix doap: <http://usefulinc.com/ns/doap#> . <abs> a trith:Function ; rdfs:label "abs" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . <add> a trith:Function, trith:Primitive ; rdfs:label "add", "+" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <and> a trith:Function, trith:Primitive ; rdfs:label "and" ; rdfs:comment "Bitwise AND" ; trith:arity 2 ; trith:code () . <andp> a trith:Function ; rdfs:label "andp", "and?" ; rdfs:comment "Logical AND" ; trith:arity 2 ; trith:code (<swap> <dup> (<swap> <dup> (<swap> <drop>) (<drop2> <false>) <branch>) (<drop2> <false>) <branch>) . <bool> a trith:Function ; rdfs:label "bool" ; rdfs:comment "" ; trith:arity 1 ; trith:code ((<true>) (<false>) <branch>) . <boolp> a trith:Function ; rdfs:label "boolp", "bool?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<dup> <truep> <swap> <falsep> <orp>) . <branch> a trith:Function, trith:Primitive ; rdfs:label "branch", "if" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . <call> a trith:Function, trith:Primitive ; rdfs:label "call" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <ceil> a trith:Function ; rdfs:label "ceil" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <chr> a trith:Function, trith:Primitive ; rdfs:label "chr" ; rdfs:comment "" ; rdfs:seeAlso <ord> ; trith:arity 1 ; trith:code () . <chrp> a trith:Function, trith:Primitive ; rdfs:label "chrp", "chr?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <clear> a trith:Function, trith:Primitive ; rdfs:label "clear" ; rdfs:comment "Clear the data stack" ; trith:arity 0 ; trith:code () . <cmp> a trith:Function, trith:Primitive ; rdfs:label "cmp", "<=>" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <concat> a trith:Function ; rdfs:label "concat" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<swap> <reverse> <swap> (<dup> <first> <swap> <rest> <swap> <rot> <cons> <swap>) (<dup> <emptyp>) <until> <drop> <reverse>) . <cons> a trith:Function, trith:Primitive ; rdfs:label "cons" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <depth> a trith:Function ; rdfs:label "depth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<stack> <dup> <length> () <cons> <concat> <unstack>) . <dec> a trith:Function ; rdfs:label "dec" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <sub>) . <dip> a trith:Function, trith:Primitive ; rdfs:label "dip" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <div> a trith:Function ; rdfs:label "div", "/" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <drop> a trith:Function, trith:Primitive ; rdfs:label "drop" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <drop2> a trith:Function ; rdfs:label "drop2", "2drop" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<drop>) <twice>) . <drop3> a trith:Function ; rdfs:label "drop3", "3drop" ; rdfs:comment "" ; trith:arity 3 ; trith:code ((<drop>) <thrice>) . <dup> a trith:Function, trith:Primitive ; rdfs:label "dup" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <dup2> a trith:Function, trith:Primitive ; rdfs:label "dup2", "2dup" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <dup3> a trith:Function, trith:Primitive ; rdfs:label "dup3", "3dup" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . <each> a trith:Function ; rdfs:label "each" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <eighth> a trith:Function ; rdfs:label "eighth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (7 <nth>) . <emptyp> a trith:Function ; rdfs:label "emptyp", "empty?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<length> <zerop>) . <eq> a trith:Function, trith:Primitive ; rdfs:label "eq", "=" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <evenp> a trith:Function ; rdfs:label "evenp", "even?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (2 <mod> <zerop>) . <exactp> a trith:Function ; rdfs:label "exactp", "exact?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<inexactp> <notp>) . <false> a trith:Function ; rdfs:label "false" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<quote> <false>) . <falsep> a trith:Function ; rdfs:label "falsep", "false?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<false> <eq>) . <fifth> a trith:Function ; rdfs:label "fifth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (4 <nth>) . <first> a trith:Function, trith:Primitive ; rdfs:label "first" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <flatten> a trith:Function ; rdfs:label "flatten" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <floor> a trith:Function ; rdfs:label "floor" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <fourth> a trith:Function ; rdfs:label "fourth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (3 <nth>) . <ge> a trith:Function ; rdfs:label "ge", ">=" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <gt> a trith:Function ; rdfs:label "gt", ">" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<cmp> <onep>) . <halt> a trith:Function, trith:Primitive ; rdfs:label "halt" ; rdfs:comment "" ; trith:arity 0 ; trith:code () . <inc> a trith:Function ; rdfs:label "inc" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <add>) . <inexactp> a trith:Function ; rdfs:label "inexactp", "inexact?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<exactp> <notp>) . <inf> a trith:Function ; rdfs:label "inf" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1.0 0.0 <div>) . <infp> a trith:Function ; rdfs:label "infp", "inf?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<abs> <inf> <eq>) . <intp> a trith:Function, trith:Primitive ; rdfs:label "intp", "int?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <iota> a trith:Function ; rdfs:label "iota" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <last> a trith:Function ; rdfs:label "last" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <le> a trith:Function ; rdfs:label "le", "<=" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <length> a trith:Function ; rdfs:label "length" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 (<rest> <swap> <inc>) (<swap> <dup> <emptyp>) <until> <drop>) . <list> a trith:Function ; rdfs:label "list" ; rdfs:comment "" ; trith:arity 1 ; trith:code (() <swap> (<cons>) <swap> <times> <reverse>) . <loop> a trith:Function ; rdfs:label "loop" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<dup> <call> (<loop>) <call>) . <lt> a trith:Function ; rdfs:label "lt", "<" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<cmp> -1 <eq>) . <map> a trith:Function ; rdfs:label "map" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <max> a trith:Function ; rdfs:label "max" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<dup2> <gt> (<drop>) (<swap> <drop>) <branch>) . <memberp> a trith:Function ; rdfs:label "memberp", "member?" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <min> a trith:Function ; rdfs:label "min" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<dup2> <lt> (<drop>) (<swap> <drop>) <branch>) . <mod> a trith:Function ; rdfs:label "mod" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <mul> a trith:Function ; rdfs:label "mul", "*" ; rdfs:comment "" ; trith:arity 2 ; trith:code (0 <swap> <abs> (<over> <add>) <swap> <times> <nip>) . # FIXME: negative operands <ne> a trith:Function ; rdfs:label "ne", "!=" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<eq> <notp>) . <neg> a trith:Function ; rdfs:label "neg" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <swap> <sub>) . <negp> a trith:Function ; rdfs:label "negp", "neg?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <lt>) . <nil> a trith:Function ; rdfs:label "nil" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<quote> <nil>) . <nilp> a trith:Function ; rdfs:label "nilp", "nil?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<nil> <eq>) . <ninth> a trith:Function ; rdfs:label "ninth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (8 <nth>) . <nip> a trith:Function ; rdfs:label "nip" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<swap> <drop>) . <nip2> a trith:Function ; rdfs:label "nip2", "2nip" ; rdfs:comment "" ; trith:arity 3 ; trith:code (<swap> <drop> <swap> <drop>) . <nop> a trith:Function ; rdfs:label "nop", ",", ";" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<nil> <drop>) . <not> a trith:Function ; rdfs:label "not" ; rdfs:comment "Bitwise NOT" ; trith:arity 1 ; trith:code (<neg> <dec>) . <notp> a trith:Function ; rdfs:label "notp", "not?" ; rdfs:comment "Logical NOT" ; trith:arity 1 ; trith:code ((<false>) (<true>) <branch>) . <nth> a trith:Function ; rdfs:label "nth" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<rest>) <swap> <times> <first>) . <num> a trith:Function, trith:Primitive ; rdfs:label "num" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <nump> a trith:Function, trith:Primitive ; rdfs:label "nump", "num?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <oddp> a trith:Function ; rdfs:label "oddp", "odd?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<evenp> <notp>) . <onep> a trith:Function ; rdfs:label "onep", "one?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <eq>) . <or> a trith:Function, trith:Primitive ; rdfs:label "or" ; rdfs:comment "Bitwise OR" ; trith:arity 2 ; trith:code () . <ord> a trith:Function, trith:Primitive ; rdfs:label "ord" ; rdfs:comment "" ; rdfs:seeAlso <chr> ; trith:arity 1 ; trith:code () . <orp> a trith:Function ; rdfs:label "orp", "or?" ; rdfs:comment "Logical OR" ; trith:arity 2 ; trith:code (<swap> <dup> (<swap> <drop>) (<drop>) <branch>) . <over> a trith:Function ; rdfs:label "over" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<dup2> <drop>) . <pick> a trith:Function ; rdfs:label "pick" ; rdfs:comment "" ; trith:arity 3 ; trith:code (<dup3> <drop2>) . <posp> a trith:Function ; rdfs:label "posp", "pos?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <gt>) . <pow> a trith:Function ; rdfs:label "pow" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <print> a trith:Function ; - rdfs:label "print", "." ; + rdfs:label "print", "print!", "." ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <quote> a trith:Function, trith:Primitive ; rdfs:label "quote", "\\", "'" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <foldl> a trith:Function ; - rdfs:label "foldl" ; + rdfs:label "foldl", "fold", "reduce" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . # TODO <range> a trith:Function ; rdfs:label "range" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <rem> a trith:Function ; rdfs:label "rem" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <reset> a trith:Function ; rdfs:label "reset" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<clear> <halt>) . <rest> a trith:Function, trith:Primitive ; rdfs:label "rest" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <reverse> a trith:Function ; rdfs:label "reverse" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <rot> a trith:Function, trith:Primitive ; rdfs:label "rot" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . <second> a trith:Function ; rdfs:label "second" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <nth>) . <seq> a trith:Function, trith:Primitive ; rdfs:label "seq" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <seqp> a trith:Function, trith:Primitive ; rdfs:label "seqp", "seq?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <seventh> a trith:Function ; rdfs:label "seventh" ; rdfs:comment "" ; trith:arity 1 ; trith:code (6 <nth>) . <shl> a trith:Function, trith:Primitive ; rdfs:label "shl" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <shr> a trith:Function, trith:Primitive ; rdfs:label "shr" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <sixth> a trith:Function ; rdfs:label "sixth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (5 <nth>) . <size> a trith:Function, trith:Primitive ; rdfs:label "size" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <stack> a trith:Function ; rdfs:label "stack" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<depth> <list>) . <sub> a trith:Function, trith:Primitive ; rdfs:label "sub", "-" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <swap> a trith:Function, trith:Primitive ; rdfs:label "swap" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <tenth> a trith:Function ; rdfs:label "tenth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (9 <nth>) . <text> a trith:Function ; rdfs:label "text" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <textp> a trith:Function ; rdfs:label "textp", "text?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <third> a trith:Function ; rdfs:label "third" ; rdfs:comment "" ; trith:arity 1 ; trith:code (2 <nth>) . <thrice> a trith:Function ; rdfs:label "thrice", "3x" ; rdfs:comment "" ; trith:arity 1 ; trith:code (3 <times>) . <times> a trith:Function ; rdfs:label "times" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<dec> <over> <call>) (<dup> <zerop>) <until> <drop2>) . <true> a trith:Function ; rdfs:label "true" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<quote> <true>) . <truep> a trith:Function ; rdfs:label "truep", "true?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<true> <eq>) . <twice> a trith:Function ; rdfs:label "twice", "2x" ; rdfs:comment "" ; trith:arity 1 ; trith:code (2 <times>) . <unless> a trith:Function ; rdfs:label "unless" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<nop>) <swap> <branch>) . <unstack> a trith:Function, trith:Primitive ; rdfs:label "unstack" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <until> a trith:Function ; rdfs:label "until" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<notp>) <concat> <while>) . <when> a trith:Function ; rdfs:label "when" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<nop>) <branch>) . <while> a trith:Function ; rdfs:label "while" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <xor> a trith:Function, trith:Primitive ; rdfs:label "xor" ; rdfs:comment "Bitwise XOR" ; trith:arity 2 ; trith:code () . <xorp> a trith:Function ; rdfs:label "xorp", "xor?" ; rdfs:comment "Logical XOR" ; trith:arity 2 ; trith:code (<swap> <dup> (<swap> (<drop> <false>) (<nop>) <branch>) (<drop> <dup> (<nop>) (<drop> <false>) <branch>) <branch>) . <zerop> a trith:Function ; rdfs:label "zerop", "zero?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <eq>) . diff --git a/lib/trith/core/output.rb b/lib/trith/core/output.rb index ab8f554..12611db 100644 --- a/lib/trith/core/output.rb +++ b/lib/trith/core/output.rb @@ -1,13 +1,14 @@ module Trith; module Core ## # Output operators. module Output ## # @return [Machine] def print(obj) $stdout.puts(obj) # FIXME self end - alias_method :'.', :print + alias_method :print!, :print + alias_method :'.', :print end # module Output end; end # module Trith::Core diff --git a/lib/trith/core/sequence.rb b/lib/trith/core/sequence.rb index 41b7e38..3a16641 100644 --- a/lib/trith/core/sequence.rb +++ b/lib/trith/core/sequence.rb @@ -1,432 +1,434 @@ module Trith; module Core ## # Sequence operators. # # @see http://ruby-doc.org/core-1.9/classes/Enumerable.html # @see http://ruby-doc.org/core-1.9/classes/Enumerator.html # @see http://en.wikipedia.org/wiki/Sequence module Sequence ## # Sequence predicates. module Predicates ## # @param [String, #each, #to_enum] obj # @return [Boolean] def seqp(obj) case obj when String then true when Array then true else case when obj.respond_to?(:each) then true when obj.respond_to?(:to_enum) then true else false end end end alias_method :seq?, :seqp ## # @param [#empty?, #size, #each] seq # @return [Boolean] def emptyp(seq) case when seq.respond_to?(:empty?) seq.empty? when seq.respond_to?(:size) seq.size.zero? when seq.respond_to?(:each) seq.each.to_a.empty? # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :emptyp) end end alias_method :empty?, :emptyp ## # @param [Object] elt # @param [#member?, #each] seq # @return [Boolean] def memberp(elt, seq) case when seq.respond_to?(:member?) seq.member?(elt) when seq.respond_to?(:each) seq.each.member?(elt) else raise Machine::InvalidOperandError.new(seq, :memberp) end end alias_method :member?, :memberp end # module Predicates ## # Sequence constructors. module Constructors ## # @param [String, #each, #to_enum] obj # @return [Enumerator] def seq(obj) case obj when String then obj.each_char when Array then obj.each else case when obj.respond_to?(:each) obj.each when obj.respond_to?(:to_enum) obj.to_enum else raise Machine::InvalidOperandError.new(obj, :seq) end end end ## # @overload cons(obj, seq) # @param [#to_s] obj # @param [String] seq # @return [String] # # @overload cons(obj, seq) # @param [Object] obj # @param [Array, #to_a] seq # @return [Array] # # @return [] def cons(obj, seq) case seq when String seq.dup.insert(0, obj.to_s.chr) when Array seq.dup.unshift(obj) else case when seq.respond_to?(:to_a) seq.to_a.unshift(obj) else # TODO: support for `#each` end end end ## # @param [Integer, #to_i] n # @return [Enumerable] def list(n) stack.pop(n.to_i) end ## # @param [Integer, #to_i] n # @return [Enumerable] def iota(n) # TODO: should support negative ranges as well. (0...(n.to_i)).to_a # FIXME end ## # @param [Integer, #to_i] a # @param [Integer, #to_i] b # @return [Enumerable] def range(a, b) # TODO: should support negative ranges as well. ((a.to_i)..(b.to_i)).to_a # FIXME end end # module Constructors ## # Sequence accessors. module Accessors ## # @param [#length, #size, #each] seq # @return [Integer] def length(seq) case when seq.respond_to?(:length) seq.length when seq.respond_to?(:size) seq.size when seq.respond_to?(:each) seq.each.to_a.size # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :length) end end ## # @param [#rest, #[], #each] seq # @return [Enumerable] def rest(seq) # TODO: check semantics for empty sequences case when seq.respond_to?(:rest) seq.rest when seq.respond_to?(:[]) seq[1..-1] when seq.respond_to?(:each) seq.each.to_a[1..-1] # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :rest) end end ## # @param [#first, #[], #each] seq # @return [Object] def first(seq) case seq when String seq[0].chr rescue nil # Ruby 1.8 compatible else case when seq.respond_to?(:first) then seq.first else nth(seq, 0) end end end ## # @param [#second, #[], #each] seq # @return [Object] def second(seq) case when seq.respond_to?(:second) then seq.second else nth(seq, 1) end end ## # @param [#third, #[], #each] seq # @return [Object] def third(seq) case when seq.respond_to?(:third) then seq.third else nth(seq, 2) end end ## # @param [#fourth, #[], #each] seq # @return [Object] def fourth(seq) case when seq.respond_to?(:fourth) then seq.fourth else nth(seq, 3) end end ## # @param [#fifth, #[], #each] seq # @return [Object] def fifth(seq) case when seq.respond_to?(:fifth) then seq.fifth else nth(seq, 4) end end ## # @param [#sixth, #[], #each] seq # @return [Object] def sixth(seq) case when seq.respond_to?(:sixth) then seq.sixth else nth(seq, 5) end end ## # @param [#seventh, #[], #each] seq # @return [Object] def seventh(seq) case when seq.respond_to?(:seventh) then seq.seventh else nth(seq, 6) end end ## # @param [#eighth, #[], #each] seq # @return [Object] def eighth(seq) case when seq.respond_to?(:eighth) then seq.eighth else nth(seq, 7) end end ## # @param [#ninth, #[], #each] seq # @return [Object] def ninth(seq) case when seq.respond_to?(:ninth) then seq.ninth else nth(seq, 8) end end ## # @param [#tenth, #[], #each] seq # @return [Object] def tenth(seq) case when seq.respond_to?(:tenth) then seq.tenth else nth(seq, 9) end end ## # @param [#nth, #[], #each] seq # @param [Integer, #to_i] n # @return [Object] def nth(seq, n) case seq when String seq[n.to_i].chr rescue nil # Ruby 1.8 compatible else case when seq.respond_to?(:nth) seq.nth(n) when seq.respond_to?(:[]) seq[n.to_i] when seq.respond_to?(:each) seq.each.to_a[n.to_i] # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :nth) end end end ## # @param [#last, #[], #each] seq # @return [Object] def last(seq) case seq when String seq[-1].chr rescue nil # Ruby 1.8 compatible else case when seq.respond_to?(:last) seq.last when seq.respond_to?(:[]) seq[-1] when seq.respond_to?(:each) seq.each.to_a.last # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :last) end end end end # module Accessors ## # Sequence operators. module Operators ## # @param [#concat, #each] seq1 # @param [#each] seq2 # @return [Enumerable] def concat(seq1, seq2) case when seq1.respond_to?(:concat) seq1.dup.concat(seq2) when seq1.respond_to?(:each) seq1.each.to_a.concat(seq2.each.to_a) # TODO: optimize else raise Machine::InvalidOperandError.new(seq1, :concat) end end ## # @param [#reverse, #each] seq # @return [Enumerable] def reverse(seq) case seq when String then seq.reverse when Array then seq.reverse else case when seq.respond_to?(:reverse) seq.reverse when seq.respond_to?(:each) seq.each.to_a.reverse # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :reverse) end end end ## # @param [#flatten, #each] seq # @return [Enumerable] def flatten(seq) case seq when String then seq when Array then seq.flatten else case when seq.respond_to?(:flatten) seq.flatten when seq.respond_to?(:each) seq.each.to_a.flatten # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :flatten) end end end end # module Operators ## # Sequence combinators. module Combinators ## # @param [#each] seq # @param [Array] quot # @return [Machine] def each(seq, quot) seq = case seq when String then seq.each_char else case when seq.respond_to?(:each) then seq.each else raise Machine::InvalidOperandError.new(seq, :each) end end with_saved_continuation(:each) do seq.each { |elem| push(elem).execute(quot) } end end ## # @param [#map, #each] seq # @param [Array] quot # @return [Machine] def map(seq, quot) seq = case seq when String then seq.each_char else case when seq.respond_to?(:map) then seq when seq.respond_to?(:each) then seq.each else raise Machine::InvalidOperandError.new(seq, :map) end end with_saved_continuation(:map) do push(seq.map { |elem| push(elem).execute(quot).pop }) end end ## # @param [#reduce, #each] seq # @param [Object] identity # @param [Array] quot # @return [Machine] def foldl(seq, identity, quot) seq = case seq when String then seq.each_char else case when seq.respond_to?(:reduce) then seq when seq.respond_to?(:each) then seq.each else raise Machine::InvalidOperandError.new(seq, :foldl) end end with_saved_continuation(:foldl) do push(seq.reduce(identity) { |prev, elem| push(prev, elem).execute(quot).pop }) end end + alias_method :fold, :foldl + alias_method :reduce, :foldl end # module Combinators # Include all submodule methods directly into Trith::Core::Sequence: constants.each { |mod| include(const_get(mod)) } end # module Sequence end; end # module Trith::Core diff --git a/spec/machine_spec.rb b/spec/machine_spec.rb index 78d9c70..f5fb551 100644 --- a/spec/machine_spec.rb +++ b/spec/machine_spec.rb @@ -302,558 +302,558 @@ describe Trith::Machine do it "should implement the :bool operator" do Machine.new.should respond_to(:bool) # TODO end it "should implement the :false operator" do Machine.new.should respond_to(:false) # TODO end it "should implement the :true operator" do Machine.new.should respond_to(:true) # TODO end end context "Comparison operators" do it "should implement the :cmp operator" do Machine.new.should respond_to(:cmp, :<=>) # TODO end it "should implement the :eq operator" do Machine.new.should respond_to(:eq, :'=') # TODO end it "should implement the :ne operator" do Machine.new.should respond_to(:ne, :'!=') # TODO end it "should implement the :lt operator" do Machine.new.should respond_to(:lt, :<) # TODO end it "should implement the :le operator" do Machine.new.should respond_to(:le, :<=) # TODO end it "should implement the :gt operator" do Machine.new.should respond_to(:gt, :>) # TODO end it "should implement the :ge operator" do Machine.new.should respond_to(:ge, :>=) # TODO end it "should implement the :min operator" do Machine.new.should respond_to(:min) # TODO end it "should implement the :max operator" do Machine.new.should respond_to(:max) # TODO end end context "Numeric predicates" do it "should implement the :nump operator" do Machine.new.should respond_to(:nump, :num?) # TODO end it "should implement the :intp operator" do Machine.new.should respond_to(:intp, :int?) # TODO end it "should implement the :infp operator" do Machine.new.should respond_to(:infp, :inf?) # TODO end it "should implement the :zerop operator" do Machine.new.should respond_to(:zerop, :zero?) # TODO end it "should implement the :onep operator" do Machine.new.should respond_to(:onep, :one?) # TODO end it "should implement the :negp operator" do Machine.new.should respond_to(:negp, :neg?) # TODO end it "should implement the :posp operator" do Machine.new.should respond_to(:posp, :pos?) # TODO end it "should implement the :oddp operator" do Machine.new.should respond_to(:oddp, :odd?) # TODO end it "should implement the :evenp operator" do Machine.new.should respond_to(:evenp, :even?) # TODO end end context "Numeric constructors" do it "should implement the :num operator" do Machine.new.should respond_to(:num) # TODO end it "should implement the :int operator" do Machine.new.should respond_to(:int) # TODO end it "should implement the :inf operator" do Machine.new.should respond_to(:inf) # TODO end end context "Math constants" do it "should implement the :pi operator" do Machine.new.should respond_to(:pi) # TODO end end context "Math operators" do it "should implement the :ceil operator" do Machine.new.should respond_to(:ceil) # TODO end it "should implement the :floor operator" do Machine.new.should respond_to(:floor) # TODO end it "should implement the :round operator" do Machine.new.should respond_to(:round) # TODO end it "should implement the :sq operator" do Machine.new.should respond_to(:sq) # TODO end it "should implement the :sqrt operator" do Machine.new.should respond_to(:sqrt) # TODO end it "should implement the :cb operator" do Machine.new.should respond_to(:cb) # TODO end it "should implement the :cbrt operator" do Machine.new.should respond_to(:cbrt) # TODO end it "should implement the :exp operator" do Machine.new.should respond_to(:exp) # TODO end it "should implement the :log operator" do Machine.new.should respond_to(:log) # TODO end it "should implement the :log2 operator" do Machine.new.should respond_to(:log2) # TODO end it "should implement the :log10 operator" do Machine.new.should respond_to(:log10) # TODO end it "should implement the :hypot operator" do Machine.new.should respond_to(:hypot) # TODO end it "should implement the :cos operator" do Machine.new.should respond_to(:cos) # TODO end it "should implement the :cosh operator" do Machine.new.should respond_to(:cosh) # TODO end it "should implement the :sin operator" do Machine.new.should respond_to(:sin) # TODO end it "should implement the :sinh operator" do Machine.new.should respond_to(:sinh) # TODO end it "should implement the :tan operator" do Machine.new.should respond_to(:tan) # TODO end it "should implement the :tanh operator" do Machine.new.should respond_to(:tanh) # TODO end it "should implement the :acos operator" do Machine.new.should respond_to(:acos) # TODO end it "should implement the :acosh operator" do Machine.new.should respond_to(:acosh) # TODO end it "should implement the :asin operator" do Machine.new.should respond_to(:asin) # TODO end it "should implement the :asinh operator" do Machine.new.should respond_to(:asinh) # TODO end it "should implement the :atan operator" do Machine.new.should respond_to(:atan) # TODO end it "should implement the :atan2 operator" do Machine.new.should respond_to(:atan2) # TODO end it "should implement the :atanh operator" do Machine.new.should respond_to(:atanh) # TODO end end context "Sequence predicates" do it "should implement the :seqp operator" do Machine.new.should respond_to(:seqp) # TODO end it "should implement the :emptyp operator" do Machine.new.should respond_to(:emptyp) # TODO end it "should implement the :memberp operator" do Machine.new.should respond_to(:memberp) # TODO end it "should implement the :anyp operator" do Machine.new.should respond_to(:anyp) # TODO end it "should implement the :allp operator" do Machine.new.should respond_to(:allp) # TODO end end context "Sequence constructors" do it "should implement the :seq operator" do Machine.new.should respond_to(:seq) # TODO end it "should implement the :cons operator" do Machine.new.should respond_to(:cons) # TODO end it "should implement the :list operator" do Machine.new.should respond_to(:list) # TODO end it "should implement the :iota operator" do Machine.new.should respond_to(:iota) # TODO end it "should implement the :range operator" do Machine.new.should respond_to(:range) # TODO end it "should implement the :repeat operator" do Machine.new.should respond_to(:repeat) # TODO end it "should implement the :cycle operator" do Machine.new.should respond_to(:cycle) # TODO end end context "Sequence accessors" do it "should implement the :length operator" do Machine.new.should respond_to(:length) # TODO end it "should implement the :rest operator" do Machine.new.should respond_to(:rest) # TODO end it "should implement the :first operator" do Machine.new.should respond_to(:first) # TODO end it "should implement the :second operator" do Machine.new.should respond_to(:second) # TODO end it "should implement the :third operator" do Machine.new.should respond_to(:third) # TODO end it "should implement the :fourth operator" do Machine.new.should respond_to(:fourth) # TODO end it "should implement the :fifth operator" do Machine.new.should respond_to(:fifth) # TODO end it "should implement the :sixth operator" do Machine.new.should respond_to(:sixth) # TODO end it "should implement the :seventh operator" do Machine.new.should respond_to(:seventh) # TODO end it "should implement the :eighth operator" do Machine.new.should respond_to(:eighth) # TODO end it "should implement the :ninth operator" do Machine.new.should respond_to(:ninth) # TODO end it "should implement the :tenth operator" do Machine.new.should respond_to(:tenth) # TODO end it "should implement the :nth operator" do Machine.new.should respond_to(:nth) # TODO end it "should implement the :last operator" do Machine.new.should respond_to(:last) # TODO end end context "Sequence operators" do it "should implement the :subseq operator" do Machine.new.should respond_to(:subseq) # TODO end it "should implement the :concat operator" do Machine.new.should respond_to(:concat) # TODO end it "should implement the :uniq operator" do Machine.new.should respond_to(:uniq) # TODO end it "should implement the :reverse operator" do Machine.new.should respond_to(:reverse) # TODO end it "should implement the :sort operator" do Machine.new.should respond_to(:sort) # TODO end it "should implement the :sortby operator" do Machine.new.should respond_to(:sortby) # TODO end it "should implement the :flatten operator" do Machine.new.should respond_to(:flatten) # TODO end it "should implement the :zip operator" do Machine.new.should respond_to(:zip) # TODO end it "should implement the :zip1 operator" do Machine.new.should respond_to(:zip1) # TODO end it "should implement the :zip2 operator" do Machine.new.should respond_to(:zip2) # TODO end it "should implement the :zip3 operator" do Machine.new.should respond_to(:zip3) # TODO end it "should implement the :zip4 operator" do Machine.new.should respond_to(:zip4) # TODO end it "should implement the :unzip operator" do Machine.new.should respond_to(:unzip) # TODO end it "should implement the :unzip1 operator" do Machine.new.should respond_to(:unzip1) # TODO end it "should implement the :unzip2 operator" do Machine.new.should respond_to(:unzip2) # TODO end it "should implement the :unzip3 operator" do Machine.new.should respond_to(:unzip3) # TODO end it "should implement the :unzip4 operator" do Machine.new.should respond_to(:unzip4) # TODO end end context "Sequence combinators" do it "should implement the :each operator" do Machine.new.should respond_to(:each) # TODO end it "should implement the :map operator" do Machine.new.should respond_to(:map) Machine.new([[1, 2, 3, 4, 5], [:dup, :mul]]).execute { map }.stack.should == [[1, 4, 9, 16, 25]] end it "should implement the :count operator" do Machine.new.should respond_to(:count) # TODO end it "should implement the :filter operator" do Machine.new.should respond_to(:filter) Machine.new([[1, 2, 3, 4, 5], [2, :mod, 0, :eq]]).execute { filter }.stack.should == [[2, 4]] end it "should implement the :remove operator" do Machine.new.should respond_to(:remove) # TODO end it "should implement the :foldl operator" do - Machine.new.should respond_to(:foldl) + Machine.new.should respond_to(:foldl, :fold, :reduce) Machine.new([[1, 2, 3, 4, 5], 0, [:add]]).execute { foldl }.stack.should == [15] Machine.new([[], -1, [:add]]).execute { foldl }.stack.should == [-1] Machine.new([[2, 5, 3], 0, [:add]]).execute { foldl }.stack.should == [10] Machine.new([[2, 5, 3], 0, [:dup, :mul, :add]]).execute { foldl }.stack.should == [38] end it "should implement the :foldr operator" do Machine.new.should respond_to(:foldr) # TODO end end context "Textual predicates" do it "should implement the :chrp operator" do Machine.new.should respond_to(:chrp, :chr?) # TODO end # TODO end context "Textual constructors" do it "should implement the :chr operator" do Machine.new.should respond_to(:chr) Machine.run([97]) { chr }.should == "a" Machine.run([960]) { chr }.should == "\u03c0" # PI end # TODO end context "Textual operators" do it "should implement the :size operator" do Machine.new.should respond_to(:size) # TODO end end context "Output operators" do it "should implement the :print operator" do - Machine.new.should respond_to(:print) + Machine.new.should respond_to(:print, :print!, :'.') # TODO end end end
trith/trith
6ad43587a7b48ee7bc2d0f5391edcf6ebad9ad6f
Implemented the Trith::Core#memberp operator.
diff --git a/etc/trith-core.ttl b/etc/trith-core.ttl index a6ebf9c..1012716 100644 --- a/etc/trith-core.ttl +++ b/etc/trith-core.ttl @@ -1,719 +1,725 @@ @base <http://trith.org/core/> . @prefix trith: <http://trith.org/lang/> . @prefix xsd: <http://www.w3.org/2001/XMLSchema#> . @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . @prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix dc: <http://purl.org/dc/terms/> . @prefix foaf: <http://xmlns.com/foaf/0.1/> . @prefix doap: <http://usefulinc.com/ns/doap#> . <abs> a trith:Function ; rdfs:label "abs" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . <add> a trith:Function, trith:Primitive ; rdfs:label "add", "+" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <and> a trith:Function, trith:Primitive ; rdfs:label "and" ; rdfs:comment "Bitwise AND" ; trith:arity 2 ; trith:code () . <andp> a trith:Function ; rdfs:label "andp", "and?" ; rdfs:comment "Logical AND" ; trith:arity 2 ; trith:code (<swap> <dup> (<swap> <dup> (<swap> <drop>) (<drop2> <false>) <branch>) (<drop2> <false>) <branch>) . <bool> a trith:Function ; rdfs:label "bool" ; rdfs:comment "" ; trith:arity 1 ; trith:code ((<true>) (<false>) <branch>) . <boolp> a trith:Function ; rdfs:label "boolp", "bool?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<dup> <truep> <swap> <falsep> <orp>) . <branch> a trith:Function, trith:Primitive ; rdfs:label "branch", "if" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . <call> a trith:Function, trith:Primitive ; rdfs:label "call" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <ceil> a trith:Function ; rdfs:label "ceil" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <chr> a trith:Function, trith:Primitive ; rdfs:label "chr" ; rdfs:comment "" ; rdfs:seeAlso <ord> ; trith:arity 1 ; trith:code () . <chrp> a trith:Function, trith:Primitive ; rdfs:label "chrp", "chr?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <clear> a trith:Function, trith:Primitive ; rdfs:label "clear" ; rdfs:comment "Clear the data stack" ; trith:arity 0 ; trith:code () . <cmp> a trith:Function, trith:Primitive ; rdfs:label "cmp", "<=>" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <concat> a trith:Function ; rdfs:label "concat" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<swap> <reverse> <swap> (<dup> <first> <swap> <rest> <swap> <rot> <cons> <swap>) (<dup> <emptyp>) <until> <drop> <reverse>) . <cons> a trith:Function, trith:Primitive ; rdfs:label "cons" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <depth> a trith:Function ; rdfs:label "depth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<stack> <dup> <length> () <cons> <concat> <unstack>) . <dec> a trith:Function ; rdfs:label "dec" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <sub>) . <dip> a trith:Function, trith:Primitive ; rdfs:label "dip" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <div> a trith:Function ; rdfs:label "div", "/" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <drop> a trith:Function, trith:Primitive ; rdfs:label "drop" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <drop2> a trith:Function ; rdfs:label "drop2", "2drop" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<drop>) <twice>) . <drop3> a trith:Function ; rdfs:label "drop3", "3drop" ; rdfs:comment "" ; trith:arity 3 ; trith:code ((<drop>) <thrice>) . <dup> a trith:Function, trith:Primitive ; rdfs:label "dup" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <dup2> a trith:Function, trith:Primitive ; rdfs:label "dup2", "2dup" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <dup3> a trith:Function, trith:Primitive ; rdfs:label "dup3", "3dup" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . <each> a trith:Function ; rdfs:label "each" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <eighth> a trith:Function ; rdfs:label "eighth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (7 <nth>) . <emptyp> a trith:Function ; rdfs:label "emptyp", "empty?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<length> <zerop>) . <eq> a trith:Function, trith:Primitive ; rdfs:label "eq", "=" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <evenp> a trith:Function ; rdfs:label "evenp", "even?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (2 <mod> <zerop>) . <exactp> a trith:Function ; rdfs:label "exactp", "exact?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<inexactp> <notp>) . <false> a trith:Function ; rdfs:label "false" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<quote> <false>) . <falsep> a trith:Function ; rdfs:label "falsep", "false?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<false> <eq>) . <fifth> a trith:Function ; rdfs:label "fifth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (4 <nth>) . <first> a trith:Function, trith:Primitive ; rdfs:label "first" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <flatten> a trith:Function ; rdfs:label "flatten" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <floor> a trith:Function ; rdfs:label "floor" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <fourth> a trith:Function ; rdfs:label "fourth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (3 <nth>) . <ge> a trith:Function ; rdfs:label "ge", ">=" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <gt> a trith:Function ; rdfs:label "gt", ">" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<cmp> <onep>) . <halt> a trith:Function, trith:Primitive ; rdfs:label "halt" ; rdfs:comment "" ; trith:arity 0 ; trith:code () . <inc> a trith:Function ; rdfs:label "inc" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <add>) . <inexactp> a trith:Function ; rdfs:label "inexactp", "inexact?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<exactp> <notp>) . <inf> a trith:Function ; rdfs:label "inf" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1.0 0.0 <div>) . <infp> a trith:Function ; rdfs:label "infp", "inf?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<abs> <inf> <eq>) . <intp> a trith:Function, trith:Primitive ; rdfs:label "intp", "int?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <iota> a trith:Function ; rdfs:label "iota" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <last> a trith:Function ; rdfs:label "last" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <le> a trith:Function ; rdfs:label "le", "<=" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <length> a trith:Function ; rdfs:label "length" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 (<rest> <swap> <inc>) (<swap> <dup> <emptyp>) <until> <drop>) . <list> a trith:Function ; rdfs:label "list" ; rdfs:comment "" ; trith:arity 1 ; trith:code (() <swap> (<cons>) <swap> <times> <reverse>) . <loop> a trith:Function ; rdfs:label "loop" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<dup> <call> (<loop>) <call>) . <lt> a trith:Function ; rdfs:label "lt", "<" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<cmp> -1 <eq>) . <map> a trith:Function ; rdfs:label "map" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <max> a trith:Function ; rdfs:label "max" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<dup2> <gt> (<drop>) (<swap> <drop>) <branch>) . +<memberp> a trith:Function ; + rdfs:label "memberp", "member?" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . # TODO + <min> a trith:Function ; rdfs:label "min" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<dup2> <lt> (<drop>) (<swap> <drop>) <branch>) . <mod> a trith:Function ; rdfs:label "mod" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <mul> a trith:Function ; rdfs:label "mul", "*" ; rdfs:comment "" ; trith:arity 2 ; trith:code (0 <swap> <abs> (<over> <add>) <swap> <times> <nip>) . # FIXME: negative operands <ne> a trith:Function ; rdfs:label "ne", "!=" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<eq> <notp>) . <neg> a trith:Function ; rdfs:label "neg" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <swap> <sub>) . <negp> a trith:Function ; rdfs:label "negp", "neg?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <lt>) . <nil> a trith:Function ; rdfs:label "nil" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<quote> <nil>) . <nilp> a trith:Function ; rdfs:label "nilp", "nil?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<nil> <eq>) . <ninth> a trith:Function ; rdfs:label "ninth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (8 <nth>) . <nip> a trith:Function ; rdfs:label "nip" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<swap> <drop>) . <nip2> a trith:Function ; rdfs:label "nip2", "2nip" ; rdfs:comment "" ; trith:arity 3 ; trith:code (<swap> <drop> <swap> <drop>) . <nop> a trith:Function ; rdfs:label "nop", ",", ";" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<nil> <drop>) . <not> a trith:Function ; rdfs:label "not" ; rdfs:comment "Bitwise NOT" ; trith:arity 1 ; trith:code (<neg> <dec>) . <notp> a trith:Function ; rdfs:label "notp", "not?" ; rdfs:comment "Logical NOT" ; trith:arity 1 ; trith:code ((<false>) (<true>) <branch>) . <nth> a trith:Function ; rdfs:label "nth" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<rest>) <swap> <times> <first>) . <num> a trith:Function, trith:Primitive ; rdfs:label "num" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <nump> a trith:Function, trith:Primitive ; rdfs:label "nump", "num?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <oddp> a trith:Function ; rdfs:label "oddp", "odd?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<evenp> <notp>) . <onep> a trith:Function ; rdfs:label "onep", "one?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <eq>) . <or> a trith:Function, trith:Primitive ; rdfs:label "or" ; rdfs:comment "Bitwise OR" ; trith:arity 2 ; trith:code () . <ord> a trith:Function, trith:Primitive ; rdfs:label "ord" ; rdfs:comment "" ; rdfs:seeAlso <chr> ; trith:arity 1 ; trith:code () . <orp> a trith:Function ; rdfs:label "orp", "or?" ; rdfs:comment "Logical OR" ; trith:arity 2 ; trith:code (<swap> <dup> (<swap> <drop>) (<drop>) <branch>) . <over> a trith:Function ; rdfs:label "over" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<dup2> <drop>) . <pick> a trith:Function ; rdfs:label "pick" ; rdfs:comment "" ; trith:arity 3 ; trith:code (<dup3> <drop2>) . <posp> a trith:Function ; rdfs:label "posp", "pos?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <gt>) . <pow> a trith:Function ; rdfs:label "pow" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <print> a trith:Function ; rdfs:label "print", "." ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <quote> a trith:Function, trith:Primitive ; rdfs:label "quote", "\\", "'" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <foldl> a trith:Function ; rdfs:label "foldl" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . # TODO <range> a trith:Function ; rdfs:label "range" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <rem> a trith:Function ; rdfs:label "rem" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <reset> a trith:Function ; rdfs:label "reset" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<clear> <halt>) . <rest> a trith:Function, trith:Primitive ; rdfs:label "rest" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <reverse> a trith:Function ; rdfs:label "reverse" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <rot> a trith:Function, trith:Primitive ; rdfs:label "rot" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . <second> a trith:Function ; rdfs:label "second" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <nth>) . <seq> a trith:Function, trith:Primitive ; rdfs:label "seq" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <seqp> a trith:Function, trith:Primitive ; rdfs:label "seqp", "seq?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <seventh> a trith:Function ; rdfs:label "seventh" ; rdfs:comment "" ; trith:arity 1 ; trith:code (6 <nth>) . <shl> a trith:Function, trith:Primitive ; rdfs:label "shl" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <shr> a trith:Function, trith:Primitive ; rdfs:label "shr" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <sixth> a trith:Function ; rdfs:label "sixth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (5 <nth>) . <size> a trith:Function, trith:Primitive ; rdfs:label "size" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <stack> a trith:Function ; rdfs:label "stack" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<depth> <list>) . <sub> a trith:Function, trith:Primitive ; rdfs:label "sub", "-" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <swap> a trith:Function, trith:Primitive ; rdfs:label "swap" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <tenth> a trith:Function ; rdfs:label "tenth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (9 <nth>) . <text> a trith:Function ; rdfs:label "text" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <textp> a trith:Function ; rdfs:label "textp", "text?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <third> a trith:Function ; rdfs:label "third" ; rdfs:comment "" ; trith:arity 1 ; trith:code (2 <nth>) . <thrice> a trith:Function ; rdfs:label "thrice", "3x" ; rdfs:comment "" ; trith:arity 1 ; trith:code (3 <times>) . <times> a trith:Function ; rdfs:label "times" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<dec> <over> <call>) (<dup> <zerop>) <until> <drop2>) . <true> a trith:Function ; rdfs:label "true" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<quote> <true>) . <truep> a trith:Function ; rdfs:label "truep", "true?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<true> <eq>) . <twice> a trith:Function ; rdfs:label "twice", "2x" ; rdfs:comment "" ; trith:arity 1 ; trith:code (2 <times>) . <unless> a trith:Function ; rdfs:label "unless" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<nop>) <swap> <branch>) . <unstack> a trith:Function, trith:Primitive ; rdfs:label "unstack" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <until> a trith:Function ; rdfs:label "until" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<notp>) <concat> <while>) . <when> a trith:Function ; rdfs:label "when" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<nop>) <branch>) . <while> a trith:Function ; rdfs:label "while" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <xor> a trith:Function, trith:Primitive ; rdfs:label "xor" ; rdfs:comment "Bitwise XOR" ; trith:arity 2 ; trith:code () . <xorp> a trith:Function ; rdfs:label "xorp", "xor?" ; rdfs:comment "Logical XOR" ; trith:arity 2 ; trith:code (<swap> <dup> (<swap> (<drop> <false>) (<nop>) <branch>) (<drop> <dup> (<nop>) (<drop> <false>) <branch>) <branch>) . <zerop> a trith:Function ; rdfs:label "zerop", "zero?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <eq>) . diff --git a/lib/trith/core/sequence.rb b/lib/trith/core/sequence.rb index c809ee2..41b7e38 100644 --- a/lib/trith/core/sequence.rb +++ b/lib/trith/core/sequence.rb @@ -1,416 +1,432 @@ module Trith; module Core ## # Sequence operators. # # @see http://ruby-doc.org/core-1.9/classes/Enumerable.html # @see http://ruby-doc.org/core-1.9/classes/Enumerator.html # @see http://en.wikipedia.org/wiki/Sequence module Sequence ## # Sequence predicates. module Predicates ## # @param [String, #each, #to_enum] obj # @return [Boolean] def seqp(obj) case obj when String then true when Array then true else case when obj.respond_to?(:each) then true when obj.respond_to?(:to_enum) then true else false end end end alias_method :seq?, :seqp ## # @param [#empty?, #size, #each] seq # @return [Boolean] def emptyp(seq) case when seq.respond_to?(:empty?) seq.empty? when seq.respond_to?(:size) seq.size.zero? when seq.respond_to?(:each) seq.each.to_a.empty? # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :emptyp) end end alias_method :empty?, :emptyp + + ## + # @param [Object] elt + # @param [#member?, #each] seq + # @return [Boolean] + def memberp(elt, seq) + case + when seq.respond_to?(:member?) + seq.member?(elt) + when seq.respond_to?(:each) + seq.each.member?(elt) + else + raise Machine::InvalidOperandError.new(seq, :memberp) + end + end + alias_method :member?, :memberp end # module Predicates ## # Sequence constructors. module Constructors ## # @param [String, #each, #to_enum] obj # @return [Enumerator] def seq(obj) case obj when String then obj.each_char when Array then obj.each else case when obj.respond_to?(:each) obj.each when obj.respond_to?(:to_enum) obj.to_enum else raise Machine::InvalidOperandError.new(obj, :seq) end end end ## # @overload cons(obj, seq) # @param [#to_s] obj # @param [String] seq # @return [String] # # @overload cons(obj, seq) # @param [Object] obj # @param [Array, #to_a] seq # @return [Array] # # @return [] def cons(obj, seq) case seq when String seq.dup.insert(0, obj.to_s.chr) when Array seq.dup.unshift(obj) else case when seq.respond_to?(:to_a) seq.to_a.unshift(obj) else # TODO: support for `#each` end end end ## # @param [Integer, #to_i] n # @return [Enumerable] def list(n) stack.pop(n.to_i) end ## # @param [Integer, #to_i] n # @return [Enumerable] def iota(n) # TODO: should support negative ranges as well. (0...(n.to_i)).to_a # FIXME end ## # @param [Integer, #to_i] a # @param [Integer, #to_i] b # @return [Enumerable] def range(a, b) # TODO: should support negative ranges as well. ((a.to_i)..(b.to_i)).to_a # FIXME end end # module Constructors ## # Sequence accessors. module Accessors ## # @param [#length, #size, #each] seq # @return [Integer] def length(seq) case when seq.respond_to?(:length) seq.length when seq.respond_to?(:size) seq.size when seq.respond_to?(:each) seq.each.to_a.size # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :length) end end ## # @param [#rest, #[], #each] seq # @return [Enumerable] def rest(seq) # TODO: check semantics for empty sequences case when seq.respond_to?(:rest) seq.rest when seq.respond_to?(:[]) seq[1..-1] when seq.respond_to?(:each) seq.each.to_a[1..-1] # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :rest) end end ## # @param [#first, #[], #each] seq # @return [Object] def first(seq) case seq when String seq[0].chr rescue nil # Ruby 1.8 compatible else case when seq.respond_to?(:first) then seq.first else nth(seq, 0) end end end ## # @param [#second, #[], #each] seq # @return [Object] def second(seq) case when seq.respond_to?(:second) then seq.second else nth(seq, 1) end end ## # @param [#third, #[], #each] seq # @return [Object] def third(seq) case when seq.respond_to?(:third) then seq.third else nth(seq, 2) end end ## # @param [#fourth, #[], #each] seq # @return [Object] def fourth(seq) case when seq.respond_to?(:fourth) then seq.fourth else nth(seq, 3) end end ## # @param [#fifth, #[], #each] seq # @return [Object] def fifth(seq) case when seq.respond_to?(:fifth) then seq.fifth else nth(seq, 4) end end ## # @param [#sixth, #[], #each] seq # @return [Object] def sixth(seq) case when seq.respond_to?(:sixth) then seq.sixth else nth(seq, 5) end end ## # @param [#seventh, #[], #each] seq # @return [Object] def seventh(seq) case when seq.respond_to?(:seventh) then seq.seventh else nth(seq, 6) end end ## # @param [#eighth, #[], #each] seq # @return [Object] def eighth(seq) case when seq.respond_to?(:eighth) then seq.eighth else nth(seq, 7) end end ## # @param [#ninth, #[], #each] seq # @return [Object] def ninth(seq) case when seq.respond_to?(:ninth) then seq.ninth else nth(seq, 8) end end ## # @param [#tenth, #[], #each] seq # @return [Object] def tenth(seq) case when seq.respond_to?(:tenth) then seq.tenth else nth(seq, 9) end end ## # @param [#nth, #[], #each] seq # @param [Integer, #to_i] n # @return [Object] def nth(seq, n) case seq when String seq[n.to_i].chr rescue nil # Ruby 1.8 compatible else case when seq.respond_to?(:nth) seq.nth(n) when seq.respond_to?(:[]) seq[n.to_i] when seq.respond_to?(:each) seq.each.to_a[n.to_i] # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :nth) end end end ## # @param [#last, #[], #each] seq # @return [Object] def last(seq) case seq when String seq[-1].chr rescue nil # Ruby 1.8 compatible else case when seq.respond_to?(:last) seq.last when seq.respond_to?(:[]) seq[-1] when seq.respond_to?(:each) seq.each.to_a.last # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :last) end end end end # module Accessors ## # Sequence operators. module Operators ## # @param [#concat, #each] seq1 # @param [#each] seq2 # @return [Enumerable] def concat(seq1, seq2) case when seq1.respond_to?(:concat) seq1.dup.concat(seq2) when seq1.respond_to?(:each) seq1.each.to_a.concat(seq2.each.to_a) # TODO: optimize else raise Machine::InvalidOperandError.new(seq1, :concat) end end ## # @param [#reverse, #each] seq # @return [Enumerable] def reverse(seq) case seq when String then seq.reverse when Array then seq.reverse else case when seq.respond_to?(:reverse) seq.reverse when seq.respond_to?(:each) seq.each.to_a.reverse # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :reverse) end end end ## # @param [#flatten, #each] seq # @return [Enumerable] def flatten(seq) case seq when String then seq when Array then seq.flatten else case when seq.respond_to?(:flatten) seq.flatten when seq.respond_to?(:each) seq.each.to_a.flatten # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :flatten) end end end end # module Operators ## # Sequence combinators. module Combinators ## # @param [#each] seq # @param [Array] quot # @return [Machine] def each(seq, quot) seq = case seq when String then seq.each_char else case when seq.respond_to?(:each) then seq.each else raise Machine::InvalidOperandError.new(seq, :each) end end with_saved_continuation(:each) do seq.each { |elem| push(elem).execute(quot) } end end ## # @param [#map, #each] seq # @param [Array] quot # @return [Machine] def map(seq, quot) seq = case seq when String then seq.each_char else case when seq.respond_to?(:map) then seq when seq.respond_to?(:each) then seq.each else raise Machine::InvalidOperandError.new(seq, :map) end end with_saved_continuation(:map) do push(seq.map { |elem| push(elem).execute(quot).pop }) end end ## # @param [#reduce, #each] seq # @param [Object] identity # @param [Array] quot # @return [Machine] def foldl(seq, identity, quot) seq = case seq when String then seq.each_char else case when seq.respond_to?(:reduce) then seq when seq.respond_to?(:each) then seq.each else raise Machine::InvalidOperandError.new(seq, :foldl) end end with_saved_continuation(:foldl) do push(seq.reduce(identity) { |prev, elem| push(prev, elem).execute(quot).pop }) end end end # module Combinators # Include all submodule methods directly into Trith::Core::Sequence: constants.each { |mod| include(const_get(mod)) } end # module Sequence end; end # module Trith::Core diff --git a/spec/machine_spec.rb b/spec/machine_spec.rb index 1e22aec..78d9c70 100644 --- a/spec/machine_spec.rb +++ b/spec/machine_spec.rb @@ -63,792 +63,797 @@ describe Trith::Machine do end it "should implement the :when operator" do Machine.new.should respond_to(:when) # TODO end it "should implement the :unless operator" do Machine.new.should respond_to(:unless) # TODO end end context "Stack shufflers" do it "should implement the :clear operator" do Machine.new.should respond_to(:clear) Machine.new([6, 7]).execute { clear }.stack.should == [] end it "should implement the :depth operator" do Machine.new.should respond_to(:depth) # TODO end it "should implement the :stack operator" do Machine.new.should respond_to(:stack) # TODO end it "should implement the :unstack operator" do Machine.new.should respond_to(:unstack) # TODO end it "should implement the :drop operator" do Machine.new.should respond_to(:drop) Machine.new([6, 7]).execute { drop }.stack.should == [6] end it "should implement the :drop2 operator" do Machine.new.should respond_to(:drop2, :'2drop') # TODO end it "should implement the :drop3 operator" do Machine.new.should respond_to(:drop3, :'3drop') # TODO end it "should implement the :dup operator" do Machine.new.should respond_to(:dup) Machine.new([6, 7]).execute { dup }.stack.should == [6, 7, 7] end it "should implement the :dup2 operator" do Machine.new.should respond_to(:dup2, :'2dup') # TODO end it "should implement the :dup3 operator" do Machine.new.should respond_to(:dup3, :'3dup') # TODO end it "should implement the :swap operator" do Machine.new.should respond_to(:swap) Machine.new([6, 7]).execute { swap }.stack.should == [7, 6] end it "should implement the :nip operator" do Machine.new.should respond_to(:nip) # TODO end it "should implement the :nip2 operator" do Machine.new.should respond_to(:nip2, :'2nip') # TODO end it "should implement the :over operator" do Machine.new.should respond_to(:over) # TODO end it "should implement the :pick operator" do Machine.new.should respond_to(:pick) # TODO end it "should implement the :rot operator" do Machine.new.should respond_to(:rot) # TODO end end context "Stack combinators" do it "should implement the :dip operator" do Machine.new.should respond_to(:dip) Machine.new([6, 7, 1, [:mul]]).execute { dip }.stack.should == [42, 1] end end context "Arithmetic operators" do it "should implement the :abs operator" do Machine.new.should respond_to(:abs) Machine.run { push(1).abs }.should == 1 Machine.run { push(-1).abs }.should == 1 end it "should implement the :neg operator" do Machine.new.should respond_to(:neg) Machine.run { push(6).neg }.should == -6 end it "should implement the :inc operator" do Machine.new.should respond_to(:inc) Machine.run { push(6).inc }.should == 7 end it "should implement the :dec operator" do Machine.new.should respond_to(:dec) Machine.run { push(6).dec }.should == 5 end it "should implement the :add operator" do Machine.new.should respond_to(:add, :+) Machine.run { push(6).push(7).add }.should == 13 end it "should implement the :sub operator" do Machine.new.should respond_to(:sub, :-) Machine.run { push(6).push(7).sub }.should == -1 end it "should implement the :mul operator" do Machine.new.should respond_to(:mul, :*) Machine.run { push(6).push(7).mul }.should == 42 end it "should implement the :div operator" do Machine.new.should respond_to(:div, :'/') Machine.run { push(42).push(7).div }.should == 6 end it "should implement the :rem operator" do Machine.new.should respond_to(:rem) # TODO end it "should implement the :mod operator" do Machine.new.should respond_to(:mod) # TODO end it "should implement the :pow operator" do Machine.new.should respond_to(:pow) # TODO end end context "Bitwise operators" do it "should implement the :not operator" do Machine.new.should respond_to(:not) # TODO end it "should implement the :and operator" do Machine.new.should respond_to(:and) # TODO end it "should implement the :or operator" do Machine.new.should respond_to(:or) # TODO end it "should implement the :xor operator" do Machine.new.should respond_to(:xor) # TODO end it "should implement the :shl operator" do Machine.new.should respond_to(:shl) # TODO end it "should implement the :shr operator" do Machine.new.should respond_to(:shr) # TODO end end context "Boolean predicates" do it "should implement the :nilp operator" do Machine.new.should respond_to(:nilp, :nil?) # TODO end it "should implement the :boolp operator" do Machine.new.should respond_to(:boolp, :bool?) # TODO end it "should implement the :falsep operator" do Machine.new.should respond_to(:falsep, :false?) # TODO end it "should implement the :truep operator" do Machine.new.should respond_to(:truep, :true?) # TODO end it "should implement the :notp operator" do Machine.new.should respond_to(:notp, :not?) # TODO end it "should implement the :andp operator" do Machine.new.should respond_to(:andp, :and?) # TODO end it "should implement the :orp operator" do Machine.new.should respond_to(:orp, :or?) # TODO end it "should implement the :xorp operator" do Machine.new.should respond_to(:xorp, :xor?) # TODO end end context "Boolean constructors" do it "should implement the :nil operator" do Machine.new.should respond_to(:nil) # TODO end it "should implement the :bool operator" do Machine.new.should respond_to(:bool) # TODO end it "should implement the :false operator" do Machine.new.should respond_to(:false) # TODO end it "should implement the :true operator" do Machine.new.should respond_to(:true) # TODO end end context "Comparison operators" do it "should implement the :cmp operator" do Machine.new.should respond_to(:cmp, :<=>) # TODO end it "should implement the :eq operator" do Machine.new.should respond_to(:eq, :'=') # TODO end it "should implement the :ne operator" do Machine.new.should respond_to(:ne, :'!=') # TODO end it "should implement the :lt operator" do Machine.new.should respond_to(:lt, :<) # TODO end it "should implement the :le operator" do Machine.new.should respond_to(:le, :<=) # TODO end it "should implement the :gt operator" do Machine.new.should respond_to(:gt, :>) # TODO end it "should implement the :ge operator" do Machine.new.should respond_to(:ge, :>=) # TODO end it "should implement the :min operator" do Machine.new.should respond_to(:min) # TODO end it "should implement the :max operator" do Machine.new.should respond_to(:max) # TODO end end context "Numeric predicates" do it "should implement the :nump operator" do Machine.new.should respond_to(:nump, :num?) # TODO end it "should implement the :intp operator" do Machine.new.should respond_to(:intp, :int?) # TODO end it "should implement the :infp operator" do Machine.new.should respond_to(:infp, :inf?) # TODO end it "should implement the :zerop operator" do Machine.new.should respond_to(:zerop, :zero?) # TODO end it "should implement the :onep operator" do Machine.new.should respond_to(:onep, :one?) # TODO end it "should implement the :negp operator" do Machine.new.should respond_to(:negp, :neg?) # TODO end it "should implement the :posp operator" do Machine.new.should respond_to(:posp, :pos?) # TODO end it "should implement the :oddp operator" do Machine.new.should respond_to(:oddp, :odd?) # TODO end it "should implement the :evenp operator" do Machine.new.should respond_to(:evenp, :even?) # TODO end end context "Numeric constructors" do it "should implement the :num operator" do Machine.new.should respond_to(:num) # TODO end it "should implement the :int operator" do Machine.new.should respond_to(:int) # TODO end it "should implement the :inf operator" do Machine.new.should respond_to(:inf) # TODO end end context "Math constants" do it "should implement the :pi operator" do Machine.new.should respond_to(:pi) # TODO end end context "Math operators" do it "should implement the :ceil operator" do Machine.new.should respond_to(:ceil) # TODO end it "should implement the :floor operator" do Machine.new.should respond_to(:floor) # TODO end it "should implement the :round operator" do Machine.new.should respond_to(:round) # TODO end it "should implement the :sq operator" do Machine.new.should respond_to(:sq) # TODO end it "should implement the :sqrt operator" do Machine.new.should respond_to(:sqrt) # TODO end it "should implement the :cb operator" do Machine.new.should respond_to(:cb) # TODO end it "should implement the :cbrt operator" do Machine.new.should respond_to(:cbrt) # TODO end it "should implement the :exp operator" do Machine.new.should respond_to(:exp) # TODO end it "should implement the :log operator" do Machine.new.should respond_to(:log) # TODO end it "should implement the :log2 operator" do Machine.new.should respond_to(:log2) # TODO end it "should implement the :log10 operator" do Machine.new.should respond_to(:log10) # TODO end it "should implement the :hypot operator" do Machine.new.should respond_to(:hypot) # TODO end it "should implement the :cos operator" do Machine.new.should respond_to(:cos) # TODO end it "should implement the :cosh operator" do Machine.new.should respond_to(:cosh) # TODO end it "should implement the :sin operator" do Machine.new.should respond_to(:sin) # TODO end it "should implement the :sinh operator" do Machine.new.should respond_to(:sinh) # TODO end it "should implement the :tan operator" do Machine.new.should respond_to(:tan) # TODO end it "should implement the :tanh operator" do Machine.new.should respond_to(:tanh) # TODO end it "should implement the :acos operator" do Machine.new.should respond_to(:acos) # TODO end it "should implement the :acosh operator" do Machine.new.should respond_to(:acosh) # TODO end it "should implement the :asin operator" do Machine.new.should respond_to(:asin) # TODO end it "should implement the :asinh operator" do Machine.new.should respond_to(:asinh) # TODO end it "should implement the :atan operator" do Machine.new.should respond_to(:atan) # TODO end it "should implement the :atan2 operator" do Machine.new.should respond_to(:atan2) # TODO end it "should implement the :atanh operator" do Machine.new.should respond_to(:atanh) # TODO end end context "Sequence predicates" do it "should implement the :seqp operator" do Machine.new.should respond_to(:seqp) # TODO end it "should implement the :emptyp operator" do Machine.new.should respond_to(:emptyp) # TODO end + it "should implement the :memberp operator" do + Machine.new.should respond_to(:memberp) + # TODO + end + it "should implement the :anyp operator" do Machine.new.should respond_to(:anyp) # TODO end it "should implement the :allp operator" do Machine.new.should respond_to(:allp) # TODO end end context "Sequence constructors" do it "should implement the :seq operator" do Machine.new.should respond_to(:seq) # TODO end it "should implement the :cons operator" do Machine.new.should respond_to(:cons) # TODO end it "should implement the :list operator" do Machine.new.should respond_to(:list) # TODO end it "should implement the :iota operator" do Machine.new.should respond_to(:iota) # TODO end it "should implement the :range operator" do Machine.new.should respond_to(:range) # TODO end it "should implement the :repeat operator" do Machine.new.should respond_to(:repeat) # TODO end it "should implement the :cycle operator" do Machine.new.should respond_to(:cycle) # TODO end end context "Sequence accessors" do it "should implement the :length operator" do Machine.new.should respond_to(:length) # TODO end it "should implement the :rest operator" do Machine.new.should respond_to(:rest) # TODO end it "should implement the :first operator" do Machine.new.should respond_to(:first) # TODO end it "should implement the :second operator" do Machine.new.should respond_to(:second) # TODO end it "should implement the :third operator" do Machine.new.should respond_to(:third) # TODO end it "should implement the :fourth operator" do Machine.new.should respond_to(:fourth) # TODO end it "should implement the :fifth operator" do Machine.new.should respond_to(:fifth) # TODO end it "should implement the :sixth operator" do Machine.new.should respond_to(:sixth) # TODO end it "should implement the :seventh operator" do Machine.new.should respond_to(:seventh) # TODO end it "should implement the :eighth operator" do Machine.new.should respond_to(:eighth) # TODO end it "should implement the :ninth operator" do Machine.new.should respond_to(:ninth) # TODO end it "should implement the :tenth operator" do Machine.new.should respond_to(:tenth) # TODO end it "should implement the :nth operator" do Machine.new.should respond_to(:nth) # TODO end it "should implement the :last operator" do Machine.new.should respond_to(:last) # TODO end end context "Sequence operators" do it "should implement the :subseq operator" do Machine.new.should respond_to(:subseq) # TODO end it "should implement the :concat operator" do Machine.new.should respond_to(:concat) # TODO end it "should implement the :uniq operator" do Machine.new.should respond_to(:uniq) # TODO end it "should implement the :reverse operator" do Machine.new.should respond_to(:reverse) # TODO end it "should implement the :sort operator" do Machine.new.should respond_to(:sort) # TODO end it "should implement the :sortby operator" do Machine.new.should respond_to(:sortby) # TODO end it "should implement the :flatten operator" do Machine.new.should respond_to(:flatten) # TODO end it "should implement the :zip operator" do Machine.new.should respond_to(:zip) # TODO end it "should implement the :zip1 operator" do Machine.new.should respond_to(:zip1) # TODO end it "should implement the :zip2 operator" do Machine.new.should respond_to(:zip2) # TODO end it "should implement the :zip3 operator" do Machine.new.should respond_to(:zip3) # TODO end it "should implement the :zip4 operator" do Machine.new.should respond_to(:zip4) # TODO end it "should implement the :unzip operator" do Machine.new.should respond_to(:unzip) # TODO end it "should implement the :unzip1 operator" do Machine.new.should respond_to(:unzip1) # TODO end it "should implement the :unzip2 operator" do Machine.new.should respond_to(:unzip2) # TODO end it "should implement the :unzip3 operator" do Machine.new.should respond_to(:unzip3) # TODO end it "should implement the :unzip4 operator" do Machine.new.should respond_to(:unzip4) # TODO end end context "Sequence combinators" do it "should implement the :each operator" do Machine.new.should respond_to(:each) # TODO end it "should implement the :map operator" do Machine.new.should respond_to(:map) Machine.new([[1, 2, 3, 4, 5], [:dup, :mul]]).execute { map }.stack.should == [[1, 4, 9, 16, 25]] end it "should implement the :count operator" do Machine.new.should respond_to(:count) # TODO end it "should implement the :filter operator" do Machine.new.should respond_to(:filter) Machine.new([[1, 2, 3, 4, 5], [2, :mod, 0, :eq]]).execute { filter }.stack.should == [[2, 4]] end it "should implement the :remove operator" do Machine.new.should respond_to(:remove) # TODO end it "should implement the :foldl operator" do Machine.new.should respond_to(:foldl) Machine.new([[1, 2, 3, 4, 5], 0, [:add]]).execute { foldl }.stack.should == [15] Machine.new([[], -1, [:add]]).execute { foldl }.stack.should == [-1] Machine.new([[2, 5, 3], 0, [:add]]).execute { foldl }.stack.should == [10] Machine.new([[2, 5, 3], 0, [:dup, :mul, :add]]).execute { foldl }.stack.should == [38] end it "should implement the :foldr operator" do Machine.new.should respond_to(:foldr) # TODO end end context "Textual predicates" do it "should implement the :chrp operator" do Machine.new.should respond_to(:chrp, :chr?) # TODO end # TODO end context "Textual constructors" do it "should implement the :chr operator" do Machine.new.should respond_to(:chr) Machine.run([97]) { chr }.should == "a" Machine.run([960]) { chr }.should == "\u03c0" # PI end # TODO end context "Textual operators" do it "should implement the :size operator" do Machine.new.should respond_to(:size) # TODO end end context "Output operators" do it "should implement the :print operator" do Machine.new.should respond_to(:print) # TODO end end end
trith/trith
686987d4c3a24bdd4f5add8afaf50cd9342b2daf
Implemented the Trith::Core#range operator.
diff --git a/etc/trith-core.ttl b/etc/trith-core.ttl index 84c56c9..a6ebf9c 100644 --- a/etc/trith-core.ttl +++ b/etc/trith-core.ttl @@ -5,709 +5,715 @@ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . @prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix dc: <http://purl.org/dc/terms/> . @prefix foaf: <http://xmlns.com/foaf/0.1/> . @prefix doap: <http://usefulinc.com/ns/doap#> . <abs> a trith:Function ; rdfs:label "abs" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . <add> a trith:Function, trith:Primitive ; rdfs:label "add", "+" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <and> a trith:Function, trith:Primitive ; rdfs:label "and" ; rdfs:comment "Bitwise AND" ; trith:arity 2 ; trith:code () . <andp> a trith:Function ; rdfs:label "andp", "and?" ; rdfs:comment "Logical AND" ; trith:arity 2 ; trith:code (<swap> <dup> (<swap> <dup> (<swap> <drop>) (<drop2> <false>) <branch>) (<drop2> <false>) <branch>) . <bool> a trith:Function ; rdfs:label "bool" ; rdfs:comment "" ; trith:arity 1 ; trith:code ((<true>) (<false>) <branch>) . <boolp> a trith:Function ; rdfs:label "boolp", "bool?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<dup> <truep> <swap> <falsep> <orp>) . <branch> a trith:Function, trith:Primitive ; rdfs:label "branch", "if" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . <call> a trith:Function, trith:Primitive ; rdfs:label "call" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <ceil> a trith:Function ; rdfs:label "ceil" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <chr> a trith:Function, trith:Primitive ; rdfs:label "chr" ; rdfs:comment "" ; rdfs:seeAlso <ord> ; trith:arity 1 ; trith:code () . <chrp> a trith:Function, trith:Primitive ; rdfs:label "chrp", "chr?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <clear> a trith:Function, trith:Primitive ; rdfs:label "clear" ; rdfs:comment "Clear the data stack" ; trith:arity 0 ; trith:code () . <cmp> a trith:Function, trith:Primitive ; rdfs:label "cmp", "<=>" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <concat> a trith:Function ; rdfs:label "concat" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<swap> <reverse> <swap> (<dup> <first> <swap> <rest> <swap> <rot> <cons> <swap>) (<dup> <emptyp>) <until> <drop> <reverse>) . <cons> a trith:Function, trith:Primitive ; rdfs:label "cons" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <depth> a trith:Function ; rdfs:label "depth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<stack> <dup> <length> () <cons> <concat> <unstack>) . <dec> a trith:Function ; rdfs:label "dec" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <sub>) . <dip> a trith:Function, trith:Primitive ; rdfs:label "dip" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <div> a trith:Function ; rdfs:label "div", "/" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <drop> a trith:Function, trith:Primitive ; rdfs:label "drop" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <drop2> a trith:Function ; rdfs:label "drop2", "2drop" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<drop>) <twice>) . <drop3> a trith:Function ; rdfs:label "drop3", "3drop" ; rdfs:comment "" ; trith:arity 3 ; trith:code ((<drop>) <thrice>) . <dup> a trith:Function, trith:Primitive ; rdfs:label "dup" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <dup2> a trith:Function, trith:Primitive ; rdfs:label "dup2", "2dup" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <dup3> a trith:Function, trith:Primitive ; rdfs:label "dup3", "3dup" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . <each> a trith:Function ; rdfs:label "each" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <eighth> a trith:Function ; rdfs:label "eighth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (7 <nth>) . <emptyp> a trith:Function ; rdfs:label "emptyp", "empty?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<length> <zerop>) . <eq> a trith:Function, trith:Primitive ; rdfs:label "eq", "=" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <evenp> a trith:Function ; rdfs:label "evenp", "even?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (2 <mod> <zerop>) . <exactp> a trith:Function ; rdfs:label "exactp", "exact?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<inexactp> <notp>) . <false> a trith:Function ; rdfs:label "false" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<quote> <false>) . <falsep> a trith:Function ; rdfs:label "falsep", "false?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<false> <eq>) . <fifth> a trith:Function ; rdfs:label "fifth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (4 <nth>) . <first> a trith:Function, trith:Primitive ; rdfs:label "first" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <flatten> a trith:Function ; rdfs:label "flatten" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <floor> a trith:Function ; rdfs:label "floor" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <fourth> a trith:Function ; rdfs:label "fourth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (3 <nth>) . <ge> a trith:Function ; rdfs:label "ge", ">=" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <gt> a trith:Function ; rdfs:label "gt", ">" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<cmp> <onep>) . <halt> a trith:Function, trith:Primitive ; rdfs:label "halt" ; rdfs:comment "" ; trith:arity 0 ; trith:code () . <inc> a trith:Function ; rdfs:label "inc" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <add>) . <inexactp> a trith:Function ; rdfs:label "inexactp", "inexact?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<exactp> <notp>) . <inf> a trith:Function ; rdfs:label "inf" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1.0 0.0 <div>) . <infp> a trith:Function ; rdfs:label "infp", "inf?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<abs> <inf> <eq>) . <intp> a trith:Function, trith:Primitive ; rdfs:label "intp", "int?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <iota> a trith:Function ; rdfs:label "iota" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <last> a trith:Function ; rdfs:label "last" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <le> a trith:Function ; rdfs:label "le", "<=" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <length> a trith:Function ; rdfs:label "length" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 (<rest> <swap> <inc>) (<swap> <dup> <emptyp>) <until> <drop>) . <list> a trith:Function ; rdfs:label "list" ; rdfs:comment "" ; trith:arity 1 ; trith:code (() <swap> (<cons>) <swap> <times> <reverse>) . <loop> a trith:Function ; rdfs:label "loop" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<dup> <call> (<loop>) <call>) . <lt> a trith:Function ; rdfs:label "lt", "<" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<cmp> -1 <eq>) . <map> a trith:Function ; rdfs:label "map" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <max> a trith:Function ; rdfs:label "max" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<dup2> <gt> (<drop>) (<swap> <drop>) <branch>) . <min> a trith:Function ; rdfs:label "min" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<dup2> <lt> (<drop>) (<swap> <drop>) <branch>) . <mod> a trith:Function ; rdfs:label "mod" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <mul> a trith:Function ; rdfs:label "mul", "*" ; rdfs:comment "" ; trith:arity 2 ; trith:code (0 <swap> <abs> (<over> <add>) <swap> <times> <nip>) . # FIXME: negative operands <ne> a trith:Function ; rdfs:label "ne", "!=" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<eq> <notp>) . <neg> a trith:Function ; rdfs:label "neg" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <swap> <sub>) . <negp> a trith:Function ; rdfs:label "negp", "neg?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <lt>) . <nil> a trith:Function ; rdfs:label "nil" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<quote> <nil>) . <nilp> a trith:Function ; rdfs:label "nilp", "nil?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<nil> <eq>) . <ninth> a trith:Function ; rdfs:label "ninth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (8 <nth>) . <nip> a trith:Function ; rdfs:label "nip" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<swap> <drop>) . <nip2> a trith:Function ; rdfs:label "nip2", "2nip" ; rdfs:comment "" ; trith:arity 3 ; trith:code (<swap> <drop> <swap> <drop>) . <nop> a trith:Function ; rdfs:label "nop", ",", ";" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<nil> <drop>) . <not> a trith:Function ; rdfs:label "not" ; rdfs:comment "Bitwise NOT" ; trith:arity 1 ; trith:code (<neg> <dec>) . <notp> a trith:Function ; rdfs:label "notp", "not?" ; rdfs:comment "Logical NOT" ; trith:arity 1 ; trith:code ((<false>) (<true>) <branch>) . <nth> a trith:Function ; rdfs:label "nth" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<rest>) <swap> <times> <first>) . <num> a trith:Function, trith:Primitive ; rdfs:label "num" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <nump> a trith:Function, trith:Primitive ; rdfs:label "nump", "num?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <oddp> a trith:Function ; rdfs:label "oddp", "odd?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<evenp> <notp>) . <onep> a trith:Function ; rdfs:label "onep", "one?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <eq>) . <or> a trith:Function, trith:Primitive ; rdfs:label "or" ; rdfs:comment "Bitwise OR" ; trith:arity 2 ; trith:code () . <ord> a trith:Function, trith:Primitive ; rdfs:label "ord" ; rdfs:comment "" ; rdfs:seeAlso <chr> ; trith:arity 1 ; trith:code () . <orp> a trith:Function ; rdfs:label "orp", "or?" ; rdfs:comment "Logical OR" ; trith:arity 2 ; trith:code (<swap> <dup> (<swap> <drop>) (<drop>) <branch>) . <over> a trith:Function ; rdfs:label "over" ; rdfs:comment "" ; trith:arity 2 ; trith:code (<dup2> <drop>) . <pick> a trith:Function ; rdfs:label "pick" ; rdfs:comment "" ; trith:arity 3 ; trith:code (<dup3> <drop2>) . <posp> a trith:Function ; rdfs:label "posp", "pos?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <gt>) . <pow> a trith:Function ; rdfs:label "pow" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <print> a trith:Function ; rdfs:label "print", "." ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <quote> a trith:Function, trith:Primitive ; rdfs:label "quote", "\\", "'" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <foldl> a trith:Function ; rdfs:label "foldl" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . # TODO +<range> a trith:Function ; + rdfs:label "range" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . # TODO + <rem> a trith:Function ; rdfs:label "rem" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <reset> a trith:Function ; rdfs:label "reset" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<clear> <halt>) . <rest> a trith:Function, trith:Primitive ; rdfs:label "rest" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <reverse> a trith:Function ; rdfs:label "reverse" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <rot> a trith:Function, trith:Primitive ; rdfs:label "rot" ; rdfs:comment "" ; trith:arity 3 ; trith:code () . <second> a trith:Function ; rdfs:label "second" ; rdfs:comment "" ; trith:arity 1 ; trith:code (1 <nth>) . <seq> a trith:Function, trith:Primitive ; rdfs:label "seq" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <seqp> a trith:Function, trith:Primitive ; rdfs:label "seqp", "seq?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <seventh> a trith:Function ; rdfs:label "seventh" ; rdfs:comment "" ; trith:arity 1 ; trith:code (6 <nth>) . <shl> a trith:Function, trith:Primitive ; rdfs:label "shl" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <shr> a trith:Function, trith:Primitive ; rdfs:label "shr" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <sixth> a trith:Function ; rdfs:label "sixth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (5 <nth>) . <size> a trith:Function, trith:Primitive ; rdfs:label "size" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <stack> a trith:Function ; rdfs:label "stack" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<depth> <list>) . <sub> a trith:Function, trith:Primitive ; rdfs:label "sub", "-" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <swap> a trith:Function, trith:Primitive ; rdfs:label "swap" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . <tenth> a trith:Function ; rdfs:label "tenth" ; rdfs:comment "" ; trith:arity 1 ; trith:code (9 <nth>) . <text> a trith:Function ; rdfs:label "text" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <textp> a trith:Function ; rdfs:label "textp", "text?" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . # TODO <third> a trith:Function ; rdfs:label "third" ; rdfs:comment "" ; trith:arity 1 ; trith:code (2 <nth>) . <thrice> a trith:Function ; rdfs:label "thrice", "3x" ; rdfs:comment "" ; trith:arity 1 ; trith:code (3 <times>) . <times> a trith:Function ; rdfs:label "times" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<dec> <over> <call>) (<dup> <zerop>) <until> <drop2>) . <true> a trith:Function ; rdfs:label "true" ; rdfs:comment "" ; trith:arity 0 ; trith:code (<quote> <true>) . <truep> a trith:Function ; rdfs:label "truep", "true?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (<true> <eq>) . <twice> a trith:Function ; rdfs:label "twice", "2x" ; rdfs:comment "" ; trith:arity 1 ; trith:code (2 <times>) . <unless> a trith:Function ; rdfs:label "unless" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<nop>) <swap> <branch>) . <unstack> a trith:Function, trith:Primitive ; rdfs:label "unstack" ; rdfs:comment "" ; trith:arity 1 ; trith:code () . <until> a trith:Function ; rdfs:label "until" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<notp>) <concat> <while>) . <when> a trith:Function ; rdfs:label "when" ; rdfs:comment "" ; trith:arity 2 ; trith:code ((<nop>) <branch>) . <while> a trith:Function ; rdfs:label "while" ; rdfs:comment "" ; trith:arity 2 ; trith:code () . # TODO <xor> a trith:Function, trith:Primitive ; rdfs:label "xor" ; rdfs:comment "Bitwise XOR" ; trith:arity 2 ; trith:code () . <xorp> a trith:Function ; rdfs:label "xorp", "xor?" ; rdfs:comment "Logical XOR" ; trith:arity 2 ; trith:code (<swap> <dup> (<swap> (<drop> <false>) (<nop>) <branch>) (<drop> <dup> (<nop>) (<drop> <false>) <branch>) <branch>) . <zerop> a trith:Function ; rdfs:label "zerop", "zero?" ; rdfs:comment "" ; trith:arity 1 ; trith:code (0 <eq>) . diff --git a/lib/trith/core/sequence.rb b/lib/trith/core/sequence.rb index e674569..c809ee2 100644 --- a/lib/trith/core/sequence.rb +++ b/lib/trith/core/sequence.rb @@ -1,407 +1,416 @@ module Trith; module Core ## # Sequence operators. # # @see http://ruby-doc.org/core-1.9/classes/Enumerable.html # @see http://ruby-doc.org/core-1.9/classes/Enumerator.html # @see http://en.wikipedia.org/wiki/Sequence module Sequence ## # Sequence predicates. module Predicates ## # @param [String, #each, #to_enum] obj # @return [Boolean] def seqp(obj) case obj when String then true when Array then true else case when obj.respond_to?(:each) then true when obj.respond_to?(:to_enum) then true else false end end end alias_method :seq?, :seqp ## # @param [#empty?, #size, #each] seq # @return [Boolean] def emptyp(seq) case when seq.respond_to?(:empty?) seq.empty? when seq.respond_to?(:size) seq.size.zero? when seq.respond_to?(:each) seq.each.to_a.empty? # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :emptyp) end end alias_method :empty?, :emptyp end # module Predicates ## # Sequence constructors. module Constructors ## # @param [String, #each, #to_enum] obj # @return [Enumerator] def seq(obj) case obj when String then obj.each_char when Array then obj.each else case when obj.respond_to?(:each) obj.each when obj.respond_to?(:to_enum) obj.to_enum else raise Machine::InvalidOperandError.new(obj, :seq) end end end ## # @overload cons(obj, seq) # @param [#to_s] obj # @param [String] seq # @return [String] # # @overload cons(obj, seq) # @param [Object] obj # @param [Array, #to_a] seq # @return [Array] # # @return [] def cons(obj, seq) case seq when String seq.dup.insert(0, obj.to_s.chr) when Array seq.dup.unshift(obj) else case when seq.respond_to?(:to_a) seq.to_a.unshift(obj) else # TODO: support for `#each` end end end ## # @param [Integer, #to_i] n # @return [Enumerable] def list(n) stack.pop(n.to_i) end ## # @param [Integer, #to_i] n # @return [Enumerable] def iota(n) # TODO: should support negative ranges as well. - (0...(n.to_i)).to_a + (0...(n.to_i)).to_a # FIXME + end + + ## + # @param [Integer, #to_i] a + # @param [Integer, #to_i] b + # @return [Enumerable] + def range(a, b) + # TODO: should support negative ranges as well. + ((a.to_i)..(b.to_i)).to_a # FIXME end end # module Constructors ## # Sequence accessors. module Accessors ## # @param [#length, #size, #each] seq # @return [Integer] def length(seq) case when seq.respond_to?(:length) seq.length when seq.respond_to?(:size) seq.size when seq.respond_to?(:each) seq.each.to_a.size # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :length) end end ## # @param [#rest, #[], #each] seq # @return [Enumerable] def rest(seq) # TODO: check semantics for empty sequences case when seq.respond_to?(:rest) seq.rest when seq.respond_to?(:[]) seq[1..-1] when seq.respond_to?(:each) seq.each.to_a[1..-1] # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :rest) end end ## # @param [#first, #[], #each] seq # @return [Object] def first(seq) case seq when String seq[0].chr rescue nil # Ruby 1.8 compatible else case when seq.respond_to?(:first) then seq.first else nth(seq, 0) end end end ## # @param [#second, #[], #each] seq # @return [Object] def second(seq) case when seq.respond_to?(:second) then seq.second else nth(seq, 1) end end ## # @param [#third, #[], #each] seq # @return [Object] def third(seq) case when seq.respond_to?(:third) then seq.third else nth(seq, 2) end end ## # @param [#fourth, #[], #each] seq # @return [Object] def fourth(seq) case when seq.respond_to?(:fourth) then seq.fourth else nth(seq, 3) end end ## # @param [#fifth, #[], #each] seq # @return [Object] def fifth(seq) case when seq.respond_to?(:fifth) then seq.fifth else nth(seq, 4) end end ## # @param [#sixth, #[], #each] seq # @return [Object] def sixth(seq) case when seq.respond_to?(:sixth) then seq.sixth else nth(seq, 5) end end ## # @param [#seventh, #[], #each] seq # @return [Object] def seventh(seq) case when seq.respond_to?(:seventh) then seq.seventh else nth(seq, 6) end end ## # @param [#eighth, #[], #each] seq # @return [Object] def eighth(seq) case when seq.respond_to?(:eighth) then seq.eighth else nth(seq, 7) end end ## # @param [#ninth, #[], #each] seq # @return [Object] def ninth(seq) case when seq.respond_to?(:ninth) then seq.ninth else nth(seq, 8) end end ## # @param [#tenth, #[], #each] seq # @return [Object] def tenth(seq) case when seq.respond_to?(:tenth) then seq.tenth else nth(seq, 9) end end ## # @param [#nth, #[], #each] seq # @param [Integer, #to_i] n # @return [Object] def nth(seq, n) case seq when String seq[n.to_i].chr rescue nil # Ruby 1.8 compatible else case when seq.respond_to?(:nth) seq.nth(n) when seq.respond_to?(:[]) seq[n.to_i] when seq.respond_to?(:each) seq.each.to_a[n.to_i] # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :nth) end end end ## # @param [#last, #[], #each] seq # @return [Object] def last(seq) case seq when String seq[-1].chr rescue nil # Ruby 1.8 compatible else case when seq.respond_to?(:last) seq.last when seq.respond_to?(:[]) seq[-1] when seq.respond_to?(:each) seq.each.to_a.last # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :last) end end end end # module Accessors ## # Sequence operators. module Operators ## # @param [#concat, #each] seq1 # @param [#each] seq2 # @return [Enumerable] def concat(seq1, seq2) case when seq1.respond_to?(:concat) seq1.dup.concat(seq2) when seq1.respond_to?(:each) seq1.each.to_a.concat(seq2.each.to_a) # TODO: optimize else raise Machine::InvalidOperandError.new(seq1, :concat) end end ## # @param [#reverse, #each] seq # @return [Enumerable] def reverse(seq) case seq when String then seq.reverse when Array then seq.reverse else case when seq.respond_to?(:reverse) seq.reverse when seq.respond_to?(:each) seq.each.to_a.reverse # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :reverse) end end end ## # @param [#flatten, #each] seq # @return [Enumerable] def flatten(seq) case seq when String then seq when Array then seq.flatten else case when seq.respond_to?(:flatten) seq.flatten when seq.respond_to?(:each) seq.each.to_a.flatten # TODO: optimize else raise Machine::InvalidOperandError.new(seq, :flatten) end end end end # module Operators ## # Sequence combinators. module Combinators ## # @param [#each] seq # @param [Array] quot # @return [Machine] def each(seq, quot) seq = case seq when String then seq.each_char else case when seq.respond_to?(:each) then seq.each else raise Machine::InvalidOperandError.new(seq, :each) end end with_saved_continuation(:each) do seq.each { |elem| push(elem).execute(quot) } end end ## # @param [#map, #each] seq # @param [Array] quot # @return [Machine] def map(seq, quot) seq = case seq when String then seq.each_char else case when seq.respond_to?(:map) then seq when seq.respond_to?(:each) then seq.each else raise Machine::InvalidOperandError.new(seq, :map) end end with_saved_continuation(:map) do push(seq.map { |elem| push(elem).execute(quot).pop }) end end ## # @param [#reduce, #each] seq # @param [Object] identity # @param [Array] quot # @return [Machine] def foldl(seq, identity, quot) seq = case seq when String then seq.each_char else case when seq.respond_to?(:reduce) then seq when seq.respond_to?(:each) then seq.each else raise Machine::InvalidOperandError.new(seq, :foldl) end end with_saved_continuation(:foldl) do push(seq.reduce(identity) { |prev, elem| push(prev, elem).execute(quot).pop }) end end end # module Combinators # Include all submodule methods directly into Trith::Core::Sequence: constants.each { |mod| include(const_get(mod)) } end # module Sequence end; end # module Trith::Core
trith/trith
47158d8e4f82fbcaa198e9920855fd5a5efe50d0
Implemented the Trith::Core#ord operator.
diff --git a/.gemspec b/.gemspec new file mode 100644 index 0000000..47cda0a --- /dev/null +++ b/.gemspec @@ -0,0 +1,38 @@ +#!/usr/bin/env ruby -rubygems +# -*- encoding: utf-8 -*- + +GEMSPEC = Gem::Specification.new do |gem| + gem.version = File.read('VERSION').chomp + gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') + + gem.name = 'trith' + gem.homepage = 'http://trith.org/' + gem.license = 'Public Domain' if gem.respond_to?(:license=) + gem.summary = 'An experimental concatenative programming language.' + gem.description = 'An experimental concatenative programming language founded on the unholy trinity of Forth, Lisp and RDF triples.' + gem.rubyforge_project = 'trith' + + gem.authors = ['Arto Bendiken'] + gem.email = '[email protected]' + + gem.platform = Gem::Platform::RUBY + gem.files = %w(AUTHORS README UNLICENSE VERSION) + gem.files += Dir.glob('etc/*.{ttl,nt}') + gem.files += Dir.glob('lib/**/*.rb') + gem.bindir = %q(bin) + gem.executables = %w(3th 3sh 3vm 3cc) + gem.default_executable = gem.executables.first + gem.require_paths = %w(lib) + gem.extensions = %w() + gem.test_files = %w() + gem.has_rdoc = false + + gem.required_ruby_version = '>= 1.9.1' + gem.requirements = [] + gem.add_development_dependency 'buildr' , '>= 1.3.5' + gem.add_development_dependency 'rspec', '>= 1.3.0' + gem.add_development_dependency 'yard' , '>= 0.5.4' + gem.add_runtime_dependency 'rdf', '~> 0.1.9' + gem.add_runtime_dependency 'sxp', '~> 0.0.3' + gem.post_install_message = nil +end diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5cee983 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.DS_Store +.tmp +.yardoc +pkg +tmp diff --git a/.yardopts b/.yardopts new file mode 100644 index 0000000..5214830 --- /dev/null +++ b/.yardopts @@ -0,0 +1,11 @@ +--title "Trith: Recombinant Programming" +--output-dir doc/yard +--protected +--no-private +--hide-void-return +--markup markdown +--readme README.md +- +AUTHORS +UNLICENSE +VERSION diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..0134601 --- /dev/null +++ b/AUTHORS @@ -0,0 +1 @@ +* Arto Bendiken <[email protected]> diff --git a/Buildfile b/Buildfile new file mode 100644 index 0000000..37f8d6d --- /dev/null +++ b/Buildfile @@ -0,0 +1,28 @@ +#!/usr/bin/env jruby +require 'buildr' + +# Specify Maven 2.0 remote repositories here: +repositories.remote << 'http://www.ibiblio.org/maven2/' + +# Specify the project's directory layout here: +LAYOUT = Layout.new +LAYOUT[:source, :main, :java] = 'src/java' +LAYOUT[:source, :spec, :java] = 'spec/java' +LAYOUT[:source, :spec, :resources] = 'spec/resources' +LAYOUT[:reports, :specs] = 'spec/reports' +LAYOUT[:target, :main] = 'pkg' +LAYOUT[:target] = 'pkg' + +desc "Trith" +define "trith", :layout => LAYOUT do + project.version = File.read('VERSION').chomp + project.group = 'trith' + manifest['Implementation-Vendor'] = 'Trith.org' + manifest['Implementation-Version'] = project.version + + compile.options.target = '1.5' + test.using :specs + package :jar +end + +RakeFileUtils.verbose_flag = false diff --git a/README b/README new file mode 120000 index 0000000..42061c0 --- /dev/null +++ b/README @@ -0,0 +1 @@ +README.md \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..a20f44c --- /dev/null +++ b/README.md @@ -0,0 +1,314 @@ +Trith: Recombinant Programming +============================== + +Trith is an experimental [concatenative][concat.org] programming language +founded on the [unholy][lispers.org] trinity of [Forth][], [Lisp][] and +[RDF][] triples. + +* <http://trith.org/> +* <http://github.com/trith/trith> + +Description +----------- + +Trith is a stack-based, concatenative, dynamically-typed functional +programming language with a homoiconic program representation. + +* [Stack-based][stack-oriented] means that instead of having named + parameters, Trith functions operate on an implicit data structure called + the _operand stack_. Trith functions can be thought of in terms of popping + and pushing operands from/onto this stack, or equivalently in purely + functional terms as unary functions that map from one stack to another. +* [Concatenative][concatenative] means that the concatenation of any two + Trith functions also denotes the [composition][] of those functions. +* [Dynamically typed][type system] means that operands to Trith functions + are type-checked dynamically at runtime. +* [Homoiconic][homoiconic] means that in Trith there is no difference + between code and data. You can manipulate and construct code at runtime as + easily as you would manipulate any other data structure, enabling powerful + metaprogramming facilities. Trith programs are simply nested lists + of operators and operands, and can be represented externally either as + [S-expressions][S-expression] or as [RDF][] triples. + +Trith is inspired and influenced by experience with [Forth][], [Lisp][] and +[Scheme][] in general, and the concatenative languages [Joy][], [XY][], +[Factor][] and [Cat][] in particular. + +Introduction +------------ + +The Trith implementation currently consists of a virtual machine, +interpreter, and compiler toolchain written in Ruby and an in-the-works +runtime targeting the [JVM][]. + +You can use the Trith shell `3sh` to explore Trith interactively: + + $ 3sh + >> "Hello, world!" print + Hello, world! + +For example, here's how you would start with two prime numbers and end up +with the correct answer to the ultimate question of life, the universe, and +everything: + + $ 3sh + >> 3 7 swap dup + * + => [42] : [] + +In the above `3sh` examples, `>>` indicates lines that you type, and `=>` +indicates the result from the shell. After each input line is evaluated, +the shell will show you the current state of the Trith virtual machine's +data stack and code queue. + +Thus in our previous example, the `[42]` on the left-hand side shows that +the machine's stack contains a single operand, the number 42. The `[]` on +the right-hand side shows that the machine's code queue is empty, which is +generally the case after all input has been successfully evaluated. + +Let's run through the above example one more time using the `--debug` option +to `3sh`, which enables the tracing of each queue reduction step in the +virtual machine: + + $ 3sh --debug + >> 3 7 swap dup + * + .. [] : [3 7 swap dup + *] + .. [3] : [7 swap dup + *] + .. [3 7] : [swap dup + *] + .. [7 3] : [dup + *] + .. [7 3 3] : [+ *] + .. [7 6] : [*] + => [42] : [] + +As you can see, the virtual machine starts execution with an empty operand +stack on the left-hand side and with all input placed onto the operator +queue on the right-hand side. When input operands such as numbers are +encountered on the queue, they are simply pushed onto the stack, which grows +from left to right. When an operator such as the multiplication operator +`*` is encountered on the queue, it is executed. Operators pop operands +from the stack and then push their result(s) back onto the stack. + +When fooling around in the Trith shell, two useful operators to know are +`clear`, which clears the stack, and `halt`, which clears the queue (thus +halting execution). You can also use `reset` which does both in one step, +returning you to a guaranteed clean slate. + +To get a listing of all operators supported in the current release, enter +the `?` metacommand in the Trith shell. + +Linked Code +----------- + +All Trith operators are identified by URIs, meaning that Trith code can be +straightforwardly represented as [Linked Data][]. Here's an example of the +`abs` operator defined metacircularly using the Turtle serialization format +for RDF data: + + @base <http://trith.org/core/> . + @prefix trith: <http://trith.org/lang/> . + @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . + + <abs> a trith:Function ; + rdfs:label "abs" ; + rdfs:comment "Returns the absolute value of a number."@en ; + trith:arity 1 ; + trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . + +This function description comprises a total of 21 triples. The entire Trith +core library currently weighs in at about a kilotriple (1,000 triples), with +all but a handful of primitive (irreducible) operators having a metacircular +definition. See `etc/trith-core.ttl` for the RDF definitions of Trith core +operators. + +Reference +--------- + +### Sequences + +Trith has a rich set of sequence operators that will be instantly familiar +to programmers coming from functional programming languages such as Scheme, +Clojure or Haskell: + + >> 10 iota + => [[0 1 2 3 4 5 6 7 8 9]] : [] + >> dup seq? . + true + >> dup empty? . + false + >> dup length . + 10 + >> [dup mul] map + => [[0 1 4 9 16 25 36 49 64 81]] : [] + >> dup first . + 0 + >> dup fifth . + 16 + >> dup 7 nth . + 49 + >> dup last . + 81 + >> dup 0 [+] foldl . + 285 + >> rest + => [[1 4 9 16 25 36 49 64 81]] : [] + >> dup 1 [*] foldl . + 131681894400 + >> reverse + => [[81 64 49 36 25 16 9 4 1]] : [] + +### Strings + +Strings are simply sequences of characters (Unicode code points), meaning +that you can make use of any of the normal sequence operators on strings as +well: + + >> : hello "Hello," " world!" concat ; + >> hello seq? . + true + >> hello text? . + true + >> hello empty? . + false + >> hello length . + 13 + >> hello first . + H + >> hello rest . + ello, world! + >> hello reverse . + !dlrow ,olleH + +Embedding +--------- + +### Embedding Trith in Ruby + + require 'trith' + + # Let's start with the obligatory "Hello, world!" example: + + Trith::Machine.run do + push "Hello, world!" + print + end + + # There are several equivalent ways to execute Trith code: + + Trith::Machine.run { push(6, 7).mul } #=> 42 + Trith::Machine.run [6, 7] { mul } #=> 42 + Trith::Machine.run [6, 7, :mul] #=> 42 + + # Operators in Ruby blocks can be chained together: + + Trith::Machine.run { push(2).dup.dup.mul.pow } #=> 16 + + # If you require more control, instantiate a machine manually: + + vm = Trith::Machine.new + vm.define!(:square) { dup.mul } + vm.push(10).square.peek #=> 100 + + # You can also define operators when constructing a machine: + + vm = Trith::Machine.new(data = [], code = [], { + :hello => proc { push("Hello, world!").print }, + }) + + # Should you want to use any Trith functions from Ruby, it's easy enough + # to encapsulate a virtual machine inside a Ruby method: + + def square(n) + Trith::Machine.run [n] { dup.mul } + end + + square(10) #=> 100 + +### Embedding Trith in JVM-based languages + +The [JVM][] runtime for Trith is a work in progress. See `src/java` for the +runtime's source code and current status. + +Dependencies +------------ + +* [Ruby](http://ruby-lang.org/) (>= 1.9.1) or + [JRuby](http://jruby.org/) (>= 1.4.0) +* [RDF.rb](http://rubygems.org/gems/rdf) (>= 0.1.9) +* [SXP](http://rubygems.org/gems/sxp) (>= 0.0.3) + +Installation +------------ + +The recommended installation method is via [RubyGems](http://rubygems.org/). +To install the latest official release of the `trith` gem, do one of the +following: + + $ [sudo] gem install trith # Ruby 1.9+ + $ [sudo] gem1.9 install trith # Ruby 1.9 with MacPorts + $ [sudo] jruby --1.9 -S gem install trith # JRuby 1.4+ + +Once Trith is installed, you will have four new programs available: + +* `3sh`, aka "trish", is the Trith interactive shell and interpreter. +* `3vm`, aka "trivium", is the Trith virtual machine runtime. +* `3cc`, aka "tricksy", is the Trith compiler. +* `3th`, aka "trith", is the Trith package manager. + +Note that as of the current release, only the first two do anything much as +yet. + +Environment +----------- + +The following are the default settings for environment variables that let +you customize how Trith works: + + $ export TRITH_HOME=~/.trith + $ export TRITH_CACHE=$TRITH_HOME/cache + $ export TRITH_TERM=$TERM + +Download +-------- + +To get a local working copy of the development repository, do: + + $ git clone git://github.com/trith/trith.git + +Alternatively, you can download the latest development version as a tarball +as follows: + + $ wget http://github.com/trith/trith/tarball/master + +Mailing List +------------ + +* <http://groups.google.com/group/trith> + +Authors +------- + +* [Arto Bendiken](mailto:[email protected]) - <http://ar.to/> + +License +------- + +Trith is free and unencumbered public domain software. For more +information, see <http://unlicense.org/> or the accompanying UNLICENSE file. + +[stack-oriented]: http://en.wikipedia.org/wiki/Stack-oriented_programming_language +[concatenative]: http://en.wikipedia.org/wiki/Concatenative_programming_language +[composition]: http://en.wikipedia.org/wiki/Function_composition +[type system]: http://en.wikipedia.org/wiki/Type_system#Dynamic_typing +[homoiconic]: http://en.wikipedia.org/wiki/Homoiconicity +[S-expression]: http://en.wikipedia.org/wiki/S-expression +[RDF]: http://en.wikipedia.org/wiki/Resource_Description_Framework +[JVM]: http://en.wikipedia.org/wiki/Java_Virtual_Machine +[Lisp]: http://en.wikipedia.org/wiki/Lisp_(programming_language) +[Scheme]: http://en.wikipedia.org/wiki/Scheme_(programming_language) +[Forth]: http://en.wikipedia.org/wiki/Forth_(programming_language) +[Factor]: http://en.wikipedia.org/wiki/Factor_(programming_language) +[Joy]: http://en.wikipedia.org/wiki/Joy_(programming_language) +[Cat]: http://en.wikipedia.org/wiki/Cat_(programming_language) +[XY]: http://www.nsl.com/k/xy/xy.htm +[Linked Data]: http://linkeddata.org/ +[lispers.org]: http://lispers.org/ +[concat.org]: http://concatenative.org/wiki/view/Concatenative%20language diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..143edcc --- /dev/null +++ b/Rakefile @@ -0,0 +1,29 @@ +#!/usr/bin/env jruby +$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), 'lib'))) +require 'rubygems' +require 'trith' + +begin + require 'rakefile' # http://github.com/bendiken/rakefile +rescue LoadError => e +end + +CLASSPATH = ['.', 'pkg/classes', ENV['CLASSPATH']].compact.join(':') + +desc "Delete all Java class files" +task :clean do + sh "find pkg/classes -name '*.class' | xargs rm" +end + +namespace :build do + desc "Build all N-Triples distributables" + task :rdf do + sh "rapper -i turtle -o ntriples etc/trith-core.ttl | sort > etc/trith-core.nt" + end + + desc "Compile all Java source files" + task :java do + sh "mkdir -p pkg/classes" + sh "javac -cp #{CLASSPATH} -d pkg/classes #{Dir.glob('src/java/**/*.java').join(' ')}" + end +end diff --git a/UNLICENSE b/UNLICENSE new file mode 100644 index 0000000..68a49da --- /dev/null +++ b/UNLICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to <http://unlicense.org/> diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..4e379d2 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.0.2 diff --git a/bin/3cc b/bin/3cc new file mode 100755 index 0000000..4dca423 --- /dev/null +++ b/bin/3cc @@ -0,0 +1,16 @@ +#!/usr/bin/env ruby1.9 -rubygems +$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))) +require 'trith' + +BANNER = "Usage: #{File.basename($0)} [options] files..." + +case + when %w(-V -v --version).any? { |opt| ARGV.include?(opt) } + $stdout.puts Trith::VERSION.to_s + exit + when %w(-? -h --help).any? { |opt| ARGV.include?(opt) } + $stdout.puts BANNER + exit + when ARGV.empty? + abort BANNER +end diff --git a/bin/3sh b/bin/3sh new file mode 100755 index 0000000..cb25f38 --- /dev/null +++ b/bin/3sh @@ -0,0 +1,72 @@ +#!/usr/bin/env ruby1.9 -rubygems +$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))) +require 'trith' + +BANNER = "Usage: #{File.basename($0)} [options] [files...]" + +case + when %w(-V -v --version).any? { |opt| ARGV.include?(opt) } + $stdout.puts Trith::VERSION.to_s + exit + when %w(-? -h --help).any? { |opt| ARGV.include?(opt) } + $stdout.puts BANNER + exit +end + +begin + $machine = Trith::Machine.new + $cache = Trith::Cache.load_core + Trith::Shell.setup!($cache) + Trith::Shell::History.load! + + if %w(-d --debug).any? { |opt| ARGV.include?(opt) } + $machine.execute_hook = proc do + $stdout.puts Trith::Shell.inspect($machine, :prefix => '.. ', :align => true) + end + end + + while line = Trith::Shell.readline('>> ') + unless (line = line.strip).empty? + case line + # Operator lookup + when /^\?\s*(\S*)/, 'help' + filter = ($1.to_s).empty? ? nil : /#{Regexp.quote($1)}/ + $cache.each_function do |function| + if !filter || filter =~ function.label + puts "%-24s%s" % [function.label, function.comment] + end + end + next # skip inspecting the stack + + # Operator definition + when /^:\s*(\S*)\s+(.*)$/ + Trith::Shell::History.push(": #{$1} #{$2}") + name, code = $1.to_sym, Trith::Reader.read_all($2) + $machine.define!(name, code, :method => false) + next # skip inspecting the stack + + # Code execution + else + Trith::Shell::History.push(line) + begin + $machine.execute(Trith::Reader.read_all(line)) + rescue Trith::Machine::InvalidOperatorError => e + $stderr.puts Trith::Shell.format_error(e) + rescue Trith::Machine::InvalidOperandError => e + $stderr.puts Trith::Shell.format_error(e) + rescue Trith::Machine::StackUnderflowError => e + $stderr.puts Trith::Shell.format_error("stack underflow") + rescue => e + $stderr.puts Trith::Shell.format_error(e.inspect) + end + end + end + $stdout.puts Trith::Shell.inspect($machine, :prefix => '=> ', :align => !!$machine.execute_hook) + end + + $stdout.puts +rescue Interrupt + abort '' # abort due to ^C (SIGINT) +ensure + Trith::Shell::History.dump! +end diff --git a/bin/3th b/bin/3th new file mode 100755 index 0000000..d5712ee --- /dev/null +++ b/bin/3th @@ -0,0 +1,16 @@ +#!/usr/bin/env ruby1.9 -rubygems +$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))) +require 'trith' + +BANNER = "Usage: #{File.basename($0)} [options] command [args...]" + +case + when %w(-V -v --version).any? { |opt| ARGV.include?(opt) } + $stdout.puts Trith::VERSION.to_s + exit + when %w(-? -h --help).any? { |opt| ARGV.include?(opt) } + $stdout.puts BANNER + exit + when ARGV.empty? + abort BANNER +end diff --git a/bin/3vm b/bin/3vm new file mode 100755 index 0000000..a199f8f --- /dev/null +++ b/bin/3vm @@ -0,0 +1,38 @@ +#!/usr/bin/env ruby1.9 -rubygems +$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))) +require 'trith' + +BANNER = "Usage: #{File.basename($0)} [options] files..." + +case + when %w(-V -v --version).any? { |opt| ARGV.include?(opt) } + $stdout.puts Trith::VERSION.to_s + exit + when %w(-? -h --help).any? { |opt| ARGV.include?(opt) } + $stdout.puts BANNER + exit + when ARGV.empty? + abort BANNER +end + +begin + $machine = Trith::Machine.new + $cache = Trith::Cache.load_core + $machine.import!(Trith::Core) + + begin + ARGV.each do |file| + $machine.execute(Trith::Reader.read_file(file)) + end + rescue Trith::Machine::InvalidOperatorError => e + $stderr.puts Trith::Shell.format_error(e) + rescue Trith::Machine::InvalidOperandError => e + $stderr.puts Trith::Shell.format_error(e) + rescue Trith::Machine::StackUnderflowError => e + $stderr.puts Trith::Shell.format_error("stack underflow") + end + + exit([255, $machine.stack.size].min) +rescue Interrupt + abort '' # abort due to ^C (SIGINT) +end diff --git a/doc/.gitignore b/doc/.gitignore new file mode 100644 index 0000000..62eb228 --- /dev/null +++ b/doc/.gitignore @@ -0,0 +1,2 @@ +rdoc +yard diff --git a/doc/examples/hello.3th b/doc/examples/hello.3th new file mode 100755 index 0000000..1a208fa --- /dev/null +++ b/doc/examples/hello.3th @@ -0,0 +1,2 @@ +#!/usr/bin/env 3vm +"Hello, world!" print diff --git a/doc/examples/hello.rb b/doc/examples/hello.rb new file mode 100755 index 0000000..db8580a --- /dev/null +++ b/doc/examples/hello.rb @@ -0,0 +1,7 @@ +#!/usr/bin/env ruby -rubygems +require 'trith' + +Trith::Machine.run do + push("Hello, world!") + print +end diff --git a/etc/trith-core.nt b/etc/trith-core.nt new file mode 100644 index 0000000..7340073 --- /dev/null +++ b/etc/trith-core.nt @@ -0,0 +1,714 @@ +<http://trith.org/core/abs> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/abs> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/abs> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/abs> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/abs> <http://www.w3.org/2000/01/rdf-schema#label> "abs" . +<http://trith.org/core/add> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/add> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/add> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/add> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/add> <http://www.w3.org/2000/01/rdf-schema#label> "+" . +<http://trith.org/core/add> <http://www.w3.org/2000/01/rdf-schema#label> "add" . +<http://trith.org/core/and> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/and> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/and> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/and> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/and> <http://www.w3.org/2000/01/rdf-schema#label> "and" . +<http://trith.org/core/boolp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/boolp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/boolp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/boolp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/boolp> <http://www.w3.org/2000/01/rdf-schema#label> "bool?" . +<http://trith.org/core/boolp> <http://www.w3.org/2000/01/rdf-schema#label> "boolp" . +<http://trith.org/core/branch> <http://trith.org/lang/arity> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/branch> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/branch> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/branch> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/branch> <http://www.w3.org/2000/01/rdf-schema#label> "branch" . +<http://trith.org/core/branch> <http://www.w3.org/2000/01/rdf-schema#label> "if" . +<http://trith.org/core/call> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/call> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/call> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/call> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/call> <http://www.w3.org/2000/01/rdf-schema#label> "call" . +<http://trith.org/core/char> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/char> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/char> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/char> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/char> <http://www.w3.org/2000/01/rdf-schema#label> "char" . +<http://trith.org/core/charp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/charp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/charp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/charp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/charp> <http://www.w3.org/2000/01/rdf-schema#label> "char?" . +<http://trith.org/core/charp> <http://www.w3.org/2000/01/rdf-schema#label> "charp" . +<http://trith.org/core/clear> <http://trith.org/lang/arity> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/clear> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/clear> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/clear> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/clear> <http://www.w3.org/2000/01/rdf-schema#label> "clear" . +<http://trith.org/core/cmp> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/cmp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/cmp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/cmp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/cmp> <http://www.w3.org/2000/01/rdf-schema#label> "<=>" . +<http://trith.org/core/cmp> <http://www.w3.org/2000/01/rdf-schema#label> "cmp" . +<http://trith.org/core/cons> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/cons> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/cons> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/cons> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/cons> <http://www.w3.org/2000/01/rdf-schema#label> "cons" . +<http://trith.org/core/dec> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/dec> <http://trith.org/lang/code> _:genid2 . +<http://trith.org/core/dec> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/dec> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/dec> <http://www.w3.org/2000/01/rdf-schema#label> "dec" . +<http://trith.org/core/dip> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/dip> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/dip> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/dip> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/dip> <http://www.w3.org/2000/01/rdf-schema#label> "dip" . +<http://trith.org/core/div> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/div> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/div> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/div> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/div> <http://www.w3.org/2000/01/rdf-schema#label> "/" . +<http://trith.org/core/div> <http://www.w3.org/2000/01/rdf-schema#label> "div" . +<http://trith.org/core/drop2> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/drop2> <http://trith.org/lang/code> _:genid4 . +<http://trith.org/core/drop2> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/drop2> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/drop2> <http://www.w3.org/2000/01/rdf-schema#label> "2drop" . +<http://trith.org/core/drop2> <http://www.w3.org/2000/01/rdf-schema#label> "drop2" . +<http://trith.org/core/drop3> <http://trith.org/lang/arity> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/drop3> <http://trith.org/lang/code> _:genid7 . +<http://trith.org/core/drop3> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/drop3> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/drop3> <http://www.w3.org/2000/01/rdf-schema#label> "3drop" . +<http://trith.org/core/drop3> <http://www.w3.org/2000/01/rdf-schema#label> "drop3" . +<http://trith.org/core/drop> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/drop> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/drop> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/drop> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/drop> <http://www.w3.org/2000/01/rdf-schema#label> "drop" . +<http://trith.org/core/dup2> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/dup2> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/dup2> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/dup2> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/dup2> <http://www.w3.org/2000/01/rdf-schema#label> "2dup" . +<http://trith.org/core/dup2> <http://www.w3.org/2000/01/rdf-schema#label> "dup2" . +<http://trith.org/core/dup3> <http://trith.org/lang/arity> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/dup3> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/dup3> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/dup3> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/dup3> <http://www.w3.org/2000/01/rdf-schema#label> "3dup" . +<http://trith.org/core/dup3> <http://www.w3.org/2000/01/rdf-schema#label> "dup3" . +<http://trith.org/core/dup> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/dup> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/dup> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/dup> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/dup> <http://www.w3.org/2000/01/rdf-schema#label> "dup" . +<http://trith.org/core/eighth> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/eighth> <http://trith.org/lang/code> _:genid9 . +<http://trith.org/core/eighth> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/eighth> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/eighth> <http://www.w3.org/2000/01/rdf-schema#label> "eighth" . +<http://trith.org/core/emptyp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/emptyp> <http://trith.org/lang/code> _:genid11 . +<http://trith.org/core/emptyp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/emptyp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/emptyp> <http://www.w3.org/2000/01/rdf-schema#label> "empty?" . +<http://trith.org/core/emptyp> <http://www.w3.org/2000/01/rdf-schema#label> "emptyp" . +<http://trith.org/core/eq> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/eq> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/eq> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/eq> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/eq> <http://www.w3.org/2000/01/rdf-schema#label> "=" . +<http://trith.org/core/eq> <http://www.w3.org/2000/01/rdf-schema#label> "eq" . +<http://trith.org/core/evenp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/evenp> <http://trith.org/lang/code> _:genid14 . +<http://trith.org/core/evenp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/evenp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/evenp> <http://www.w3.org/2000/01/rdf-schema#label> "even?" . +<http://trith.org/core/evenp> <http://www.w3.org/2000/01/rdf-schema#label> "evenp" . +<http://trith.org/core/exactp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/exactp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/exactp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/exactp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/exactp> <http://www.w3.org/2000/01/rdf-schema#label> "exact?" . +<http://trith.org/core/exactp> <http://www.w3.org/2000/01/rdf-schema#label> "exactp" . +<http://trith.org/core/false> <http://trith.org/lang/arity> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/false> <http://trith.org/lang/code> _:genid16 . +<http://trith.org/core/false> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/false> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/false> <http://www.w3.org/2000/01/rdf-schema#label> "false" . +<http://trith.org/core/falsep> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/falsep> <http://trith.org/lang/code> _:genid18 . +<http://trith.org/core/falsep> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/falsep> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/falsep> <http://www.w3.org/2000/01/rdf-schema#label> "false?" . +<http://trith.org/core/falsep> <http://www.w3.org/2000/01/rdf-schema#label> "falsep" . +<http://trith.org/core/fifth> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/fifth> <http://trith.org/lang/code> _:genid20 . +<http://trith.org/core/fifth> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/fifth> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/fifth> <http://www.w3.org/2000/01/rdf-schema#label> "fifth" . +<http://trith.org/core/first> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/first> <http://trith.org/lang/code> _:genid22 . +<http://trith.org/core/first> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/first> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/first> <http://www.w3.org/2000/01/rdf-schema#label> "first" . +<http://trith.org/core/fourth> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/fourth> <http://trith.org/lang/code> _:genid24 . +<http://trith.org/core/fourth> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/fourth> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/fourth> <http://www.w3.org/2000/01/rdf-schema#label> "fourth" . +<http://trith.org/core/ge> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/ge> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/ge> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/ge> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/ge> <http://www.w3.org/2000/01/rdf-schema#label> ">=" . +<http://trith.org/core/ge> <http://www.w3.org/2000/01/rdf-schema#label> "ge" . +<http://trith.org/core/gt> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/gt> <http://trith.org/lang/code> _:genid27 . +<http://trith.org/core/gt> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/gt> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/gt> <http://www.w3.org/2000/01/rdf-schema#label> ">" . +<http://trith.org/core/gt> <http://www.w3.org/2000/01/rdf-schema#label> "gt" . +<http://trith.org/core/halt> <http://trith.org/lang/arity> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/halt> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/halt> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/halt> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/halt> <http://www.w3.org/2000/01/rdf-schema#label> "halt" . +<http://trith.org/core/inc> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/inc> <http://trith.org/lang/code> _:genid29 . +<http://trith.org/core/inc> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/inc> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/inc> <http://www.w3.org/2000/01/rdf-schema#label> "inc" . +<http://trith.org/core/inexactp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/inexactp> <http://trith.org/lang/code> _:genid31 . +<http://trith.org/core/inexactp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/inexactp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/inexactp> <http://www.w3.org/2000/01/rdf-schema#label> "inexact?" . +<http://trith.org/core/inexactp> <http://www.w3.org/2000/01/rdf-schema#label> "inexactp" . +<http://trith.org/core/integerp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/integerp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/integerp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/integerp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/integerp> <http://www.w3.org/2000/01/rdf-schema#label> "integer?" . +<http://trith.org/core/integerp> <http://www.w3.org/2000/01/rdf-schema#label> "integerp" . +<http://trith.org/core/last> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/last> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/last> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/last> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/last> <http://www.w3.org/2000/01/rdf-schema#label> "last" . +<http://trith.org/core/le> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/le> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/le> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/le> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/le> <http://www.w3.org/2000/01/rdf-schema#label> "<=" . +<http://trith.org/core/le> <http://www.w3.org/2000/01/rdf-schema#label> "le" . +<http://trith.org/core/length> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/length> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/length> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/length> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/length> <http://www.w3.org/2000/01/rdf-schema#label> "length" . +<http://trith.org/core/loop> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/loop> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/loop> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/loop> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/loop> <http://www.w3.org/2000/01/rdf-schema#label> "loop" . +<http://trith.org/core/lt> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/lt> <http://trith.org/lang/code> _:genid34 . +<http://trith.org/core/lt> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/lt> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/lt> <http://www.w3.org/2000/01/rdf-schema#label> "<" . +<http://trith.org/core/lt> <http://www.w3.org/2000/01/rdf-schema#label> "lt" . +<http://trith.org/core/max> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/max> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/max> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/max> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/max> <http://www.w3.org/2000/01/rdf-schema#label> "max" . +<http://trith.org/core/min> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/min> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/min> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/min> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/min> <http://www.w3.org/2000/01/rdf-schema#label> "min" . +<http://trith.org/core/mod> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/mod> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/mod> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/mod> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/mod> <http://www.w3.org/2000/01/rdf-schema#label> "mod" . +<http://trith.org/core/mul> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/mul> <http://trith.org/lang/code> _:genid43 . +<http://trith.org/core/mul> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/mul> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/mul> <http://www.w3.org/2000/01/rdf-schema#label> "*" . +<http://trith.org/core/mul> <http://www.w3.org/2000/01/rdf-schema#label> "mul" . +<http://trith.org/core/ne> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/ne> <http://trith.org/lang/code> _:genid45 . +<http://trith.org/core/ne> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/ne> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/ne> <http://www.w3.org/2000/01/rdf-schema#label> "!=" . +<http://trith.org/core/ne> <http://www.w3.org/2000/01/rdf-schema#label> "ne" . +<http://trith.org/core/neg> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/neg> <http://trith.org/lang/code> _:genid48 . +<http://trith.org/core/neg> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/neg> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/neg> <http://www.w3.org/2000/01/rdf-schema#label> "neg" . +<http://trith.org/core/nil> <http://trith.org/lang/arity> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/nil> <http://trith.org/lang/code> _:genid50 . +<http://trith.org/core/nil> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/nil> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/nil> <http://www.w3.org/2000/01/rdf-schema#label> "nil" . +<http://trith.org/core/nilp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/nilp> <http://trith.org/lang/code> _:genid52 . +<http://trith.org/core/nilp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/nilp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/nilp> <http://www.w3.org/2000/01/rdf-schema#label> "nil?" . +<http://trith.org/core/nilp> <http://www.w3.org/2000/01/rdf-schema#label> "nilp" . +<http://trith.org/core/ninth> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/ninth> <http://trith.org/lang/code> _:genid54 . +<http://trith.org/core/ninth> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/ninth> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/ninth> <http://www.w3.org/2000/01/rdf-schema#label> "ninth" . +<http://trith.org/core/nip2> <http://trith.org/lang/arity> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/nip2> <http://trith.org/lang/code> _:genid60 . +<http://trith.org/core/nip2> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/nip2> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/nip2> <http://www.w3.org/2000/01/rdf-schema#label> "2nip" . +<http://trith.org/core/nip2> <http://www.w3.org/2000/01/rdf-schema#label> "nip2" . +<http://trith.org/core/nip> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/nip> <http://trith.org/lang/code> _:genid56 . +<http://trith.org/core/nip> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/nip> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/nip> <http://www.w3.org/2000/01/rdf-schema#label> "nip" . +<http://trith.org/core/nop> <http://trith.org/lang/arity> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/nop> <http://trith.org/lang/code> _:genid62 . +<http://trith.org/core/nop> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/nop> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/nop> <http://www.w3.org/2000/01/rdf-schema#label> "," . +<http://trith.org/core/nop> <http://www.w3.org/2000/01/rdf-schema#label> ";" . +<http://trith.org/core/nop> <http://www.w3.org/2000/01/rdf-schema#label> "nop" . +<http://trith.org/core/not> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/not> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/not> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/not> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/not> <http://www.w3.org/2000/01/rdf-schema#label> "not" . +<http://trith.org/core/nth> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/nth> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/nth> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/nth> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/nth> <http://www.w3.org/2000/01/rdf-schema#label> "nth" . +<http://trith.org/core/number> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/number> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/number> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/number> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/number> <http://www.w3.org/2000/01/rdf-schema#label> "number" . +<http://trith.org/core/numberp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/numberp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/numberp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/numberp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/numberp> <http://www.w3.org/2000/01/rdf-schema#label> "number?" . +<http://trith.org/core/numberp> <http://www.w3.org/2000/01/rdf-schema#label> "numberp" . +<http://trith.org/core/oddp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/oddp> <http://trith.org/lang/code> _:genid64 . +<http://trith.org/core/oddp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/oddp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/oddp> <http://www.w3.org/2000/01/rdf-schema#label> "odd?" . +<http://trith.org/core/oddp> <http://www.w3.org/2000/01/rdf-schema#label> "oddp" . +<http://trith.org/core/or> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/or> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/or> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/or> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/or> <http://www.w3.org/2000/01/rdf-schema#label> "or" . +<http://trith.org/core/over> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/over> <http://trith.org/lang/code> _:genid66 . +<http://trith.org/core/over> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/over> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/over> <http://www.w3.org/2000/01/rdf-schema#label> "over" . +<http://trith.org/core/pick> <http://trith.org/lang/arity> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/pick> <http://trith.org/lang/code> _:genid68 . +<http://trith.org/core/pick> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/pick> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/pick> <http://www.w3.org/2000/01/rdf-schema#label> "pick" . +<http://trith.org/core/pow> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/pow> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/pow> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/pow> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/pow> <http://www.w3.org/2000/01/rdf-schema#label> "pow" . +<http://trith.org/core/print> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/print> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/print> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/print> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/print> <http://www.w3.org/2000/01/rdf-schema#label> "." . +<http://trith.org/core/print> <http://www.w3.org/2000/01/rdf-schema#label> "print" . +<http://trith.org/core/quote> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/quote> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/quote> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/quote> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/quote> <http://www.w3.org/2000/01/rdf-schema#label> "'" . +<http://trith.org/core/quote> <http://www.w3.org/2000/01/rdf-schema#label> "\\" . +<http://trith.org/core/quote> <http://www.w3.org/2000/01/rdf-schema#label> "quote" . +<http://trith.org/core/rem> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/rem> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/rem> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/rem> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/rem> <http://www.w3.org/2000/01/rdf-schema#label> "rem" . +<http://trith.org/core/reset> <http://trith.org/lang/arity> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/reset> <http://trith.org/lang/code> _:genid70 . +<http://trith.org/core/reset> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/reset> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/reset> <http://www.w3.org/2000/01/rdf-schema#label> "reset" . +<http://trith.org/core/rest> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/rest> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/rest> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/rest> <http://www.w3.org/2000/01/rdf-schema#label> "rest" . +<http://trith.org/core/reverse> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/reverse> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/reverse> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/reverse> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/reverse> <http://www.w3.org/2000/01/rdf-schema#label> "reverse" . +<http://trith.org/core/second> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/second> <http://trith.org/lang/code> _:genid72 . +<http://trith.org/core/second> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/second> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/second> <http://www.w3.org/2000/01/rdf-schema#label> "second" . +<http://trith.org/core/seq> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/seq> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/seq> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/seq> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/seq> <http://www.w3.org/2000/01/rdf-schema#label> "seq" . +<http://trith.org/core/seqp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/seqp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/seqp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/seqp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/seqp> <http://www.w3.org/2000/01/rdf-schema#label> "seq?" . +<http://trith.org/core/seqp> <http://www.w3.org/2000/01/rdf-schema#label> "seqp" . +<http://trith.org/core/seventh> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/seventh> <http://trith.org/lang/code> _:genid74 . +<http://trith.org/core/seventh> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/seventh> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/seventh> <http://www.w3.org/2000/01/rdf-schema#label> "seventh" . +<http://trith.org/core/shl> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/shl> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/shl> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/shl> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/shl> <http://www.w3.org/2000/01/rdf-schema#label> "shl" . +<http://trith.org/core/shr> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/shr> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/shr> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/shr> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/shr> <http://www.w3.org/2000/01/rdf-schema#label> "shr" . +<http://trith.org/core/sixth> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/sixth> <http://trith.org/lang/code> _:genid76 . +<http://trith.org/core/sixth> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/sixth> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/sixth> <http://www.w3.org/2000/01/rdf-schema#label> "sixth" . +<http://trith.org/core/size> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/size> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/size> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/size> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/size> <http://www.w3.org/2000/01/rdf-schema#label> "size" . +<http://trith.org/core/sub> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/sub> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/sub> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/sub> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/sub> <http://www.w3.org/2000/01/rdf-schema#label> "-" . +<http://trith.org/core/sub> <http://www.w3.org/2000/01/rdf-schema#label> "sub" . +<http://trith.org/core/swap> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/swap> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/swap> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/swap> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/swap> <http://www.w3.org/2000/01/rdf-schema#label> "swap" . +<http://trith.org/core/tenth> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/tenth> <http://trith.org/lang/code> _:genid78 . +<http://trith.org/core/tenth> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/tenth> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/tenth> <http://www.w3.org/2000/01/rdf-schema#label> "tenth" . +<http://trith.org/core/text> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/text> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/text> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/text> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/text> <http://www.w3.org/2000/01/rdf-schema#label> "text" . +<http://trith.org/core/textp> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/textp> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/textp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/textp> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/textp> <http://www.w3.org/2000/01/rdf-schema#label> "text?" . +<http://trith.org/core/textp> <http://www.w3.org/2000/01/rdf-schema#label> "textp" . +<http://trith.org/core/third> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/third> <http://trith.org/lang/code> _:genid80 . +<http://trith.org/core/third> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/third> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/third> <http://www.w3.org/2000/01/rdf-schema#label> "third" . +<http://trith.org/core/thrice> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/thrice> <http://trith.org/lang/code> _:genid82 . +<http://trith.org/core/thrice> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/thrice> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/thrice> <http://www.w3.org/2000/01/rdf-schema#label> "thrice" . +<http://trith.org/core/times> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/times> <http://trith.org/lang/code> _:genid91 . +<http://trith.org/core/times> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/times> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/times> <http://www.w3.org/2000/01/rdf-schema#label> "times" . +<http://trith.org/core/true> <http://trith.org/lang/arity> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/true> <http://trith.org/lang/code> _:genid93 . +<http://trith.org/core/true> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/true> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/true> <http://www.w3.org/2000/01/rdf-schema#label> "true" . +<http://trith.org/core/truep> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/truep> <http://trith.org/lang/code> _:genid95 . +<http://trith.org/core/truep> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/truep> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/truep> <http://www.w3.org/2000/01/rdf-schema#label> "true?" . +<http://trith.org/core/truep> <http://www.w3.org/2000/01/rdf-schema#label> "truep" . +<http://trith.org/core/twice> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/twice> <http://trith.org/lang/code> _:genid97 . +<http://trith.org/core/twice> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/twice> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/twice> <http://www.w3.org/2000/01/rdf-schema#label> "twice" . +<http://trith.org/core/unless> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/unless> <http://trith.org/lang/code> _:genid101 . +<http://trith.org/core/unless> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/unless> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/unless> <http://www.w3.org/2000/01/rdf-schema#label> "unless" . +<http://trith.org/core/until> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/until> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/until> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/until> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/until> <http://www.w3.org/2000/01/rdf-schema#label> "until" . +<http://trith.org/core/when> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/when> <http://trith.org/lang/code> _:genid104 . +<http://trith.org/core/when> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/when> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/when> <http://www.w3.org/2000/01/rdf-schema#label> "when" . +<http://trith.org/core/while> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/while> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/while> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/while> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/while> <http://www.w3.org/2000/01/rdf-schema#label> "while" . +<http://trith.org/core/xor> <http://trith.org/lang/arity> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/xor> <http://trith.org/lang/code> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +<http://trith.org/core/xor> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/xor> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/xor> <http://www.w3.org/2000/01/rdf-schema#label> "xor" . +<http://trith.org/core/zerop> <http://trith.org/lang/arity> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +<http://trith.org/core/zerop> <http://trith.org/lang/code> _:genid106 . +<http://trith.org/core/zerop> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://trith.org/lang/Function> . +<http://trith.org/core/zerop> <http://www.w3.org/2000/01/rdf-schema#comment> "" . +<http://trith.org/core/zerop> <http://www.w3.org/2000/01/rdf-schema#label> "zero?" . +<http://trith.org/core/zerop> <http://www.w3.org/2000/01/rdf-schema#label> "zerop" . +_:genid1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/sub> . +_:genid1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid10 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/zerop> . +_:genid10 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid100 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid100 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid99 . +_:genid101 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid98 . +_:genid101 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid100 . +_:genid102 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nop> . +_:genid102 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid103 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . +_:genid103 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid104 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid102 . +_:genid104 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid103 . +_:genid105 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . +_:genid105 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid106 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid106 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid105 . +_:genid11 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/length> . +_:genid11 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid10 . +_:genid12 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/zerop> . +_:genid12 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid13 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/mod> . +_:genid13 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid12 . +_:genid14 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid14 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid13 . +_:genid15 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/false> . +_:genid15 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid16 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/quote> . +_:genid16 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid15 . +_:genid17 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . +_:genid17 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid18 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/false> . +_:genid18 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid17 . +_:genid19 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid19 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid2 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid2 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid1 . +_:genid20 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "4"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid20 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid19 . +_:genid21 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid21 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid22 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid22 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid21 . +_:genid23 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid23 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid24 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid24 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid23 . +_:genid25 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . +_:genid25 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid26 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid26 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid25 . +_:genid27 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/cmp> . +_:genid27 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid26 . +_:genid28 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/add> . +_:genid28 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid29 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid29 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid28 . +_:genid3 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid3 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid30 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/falsep> . +_:genid30 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid31 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/exactp> . +_:genid31 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid30 . +_:genid32 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . +_:genid32 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid33 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "-1"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid33 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid32 . +_:genid34 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/cmp> . +_:genid34 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid33 . +_:genid35 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/add> . +_:genid35 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid36 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/over> . +_:genid36 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid35 . +_:genid37 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nip> . +_:genid37 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid38 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/times> . +_:genid38 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid37 . +_:genid39 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid39 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid38 . +_:genid4 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid4 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid3 . +_:genid40 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid36 . +_:genid40 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid39 . +_:genid41 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/abs> . +_:genid41 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid40 . +_:genid42 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid42 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid41 . +_:genid43 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid43 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid42 . +_:genid44 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/falsep> . +_:genid44 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid45 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . +_:genid45 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid44 . +_:genid46 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/sub> . +_:genid46 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid47 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid47 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid46 . +_:genid48 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "0"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid48 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid47 . +_:genid49 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nil> . +_:genid49 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid5 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid5 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid50 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/quote> . +_:genid50 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid49 . +_:genid51 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . +_:genid51 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid52 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nil> . +_:genid52 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid51 . +_:genid53 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid53 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid54 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "8"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid54 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid53 . +_:genid55 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid55 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid56 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid56 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid55 . +_:genid57 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid57 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid58 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid58 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid57 . +_:genid59 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid59 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid58 . +_:genid6 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid6 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid5 . +_:genid60 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/swap> . +_:genid60 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid59 . +_:genid61 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid61 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid62 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nil> . +_:genid62 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid61 . +_:genid63 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/falsep> . +_:genid63 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid64 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/evenp> . +_:genid64 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid63 . +_:genid65 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid65 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid66 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup2> . +_:genid66 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid65 . +_:genid67 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop2> . +_:genid67 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid68 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup3> . +_:genid68 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid67 . +_:genid69 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/halt> . +_:genid69 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid7 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop> . +_:genid7 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid6 . +_:genid70 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/clear> . +_:genid70 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid69 . +_:genid71 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid71 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid72 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "1"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid72 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid71 . +_:genid73 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid73 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid74 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "6"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid74 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid73 . +_:genid75 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid75 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid76 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "5"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid76 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid75 . +_:genid77 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid77 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid78 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "9"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid78 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid77 . +_:genid79 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid79 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid8 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nth> . +_:genid8 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid80 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid80 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid79 . +_:genid81 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/times> . +_:genid81 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid82 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "3"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid82 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid81 . +_:genid83 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/call> . +_:genid83 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid84 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/over> . +_:genid84 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid83 . +_:genid85 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dec> . +_:genid85 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid84 . +_:genid86 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/zerop> . +_:genid86 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid87 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/dup> . +_:genid87 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid86 . +_:genid88 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/drop2> . +_:genid88 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid89 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/until> . +_:genid89 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid88 . +_:genid9 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "7"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid9 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid8 . +_:genid90 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid87 . +_:genid90 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid89 . +_:genid91 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> _:genid85 . +_:genid91 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid90 . +_:genid92 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/true> . +_:genid92 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid93 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/quote> . +_:genid93 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid92 . +_:genid94 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/eq> . +_:genid94 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid95 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/true> . +_:genid95 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid94 . +_:genid96 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/times> . +_:genid96 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid97 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "2"^^<http://www.w3.org/2001/XMLSchema#integer> . +_:genid97 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:genid96 . +_:genid98 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/nop> . +_:genid98 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . +_:genid99 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://trith.org/core/branch> . +_:genid99 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . diff --git a/etc/trith-core.ttl b/etc/trith-core.ttl new file mode 100644 index 0000000..84c56c9 --- /dev/null +++ b/etc/trith-core.ttl @@ -0,0 +1,713 @@ +@base <http://trith.org/core/> . +@prefix trith: <http://trith.org/lang/> . +@prefix xsd: <http://www.w3.org/2001/XMLSchema#> . +@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . +@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . +@prefix owl: <http://www.w3.org/2002/07/owl#> . +@prefix dc: <http://purl.org/dc/terms/> . +@prefix foaf: <http://xmlns.com/foaf/0.1/> . +@prefix doap: <http://usefulinc.com/ns/doap#> . + +<abs> a trith:Function ; + rdfs:label "abs" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (<dup> 0 <lt> (<neg>) (<nop>) <branch>) . + +<add> a trith:Function, trith:Primitive ; + rdfs:label "add", "+" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . + +<and> a trith:Function, trith:Primitive ; + rdfs:label "and" ; + rdfs:comment "Bitwise AND" ; + trith:arity 2 ; + trith:code () . + +<andp> a trith:Function ; + rdfs:label "andp", "and?" ; + rdfs:comment "Logical AND" ; + trith:arity 2 ; + trith:code (<swap> <dup> (<swap> <dup> (<swap> <drop>) (<drop2> <false>) <branch>) (<drop2> <false>) <branch>) . + +<bool> a trith:Function ; + rdfs:label "bool" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code ((<true>) (<false>) <branch>) . + +<boolp> a trith:Function ; + rdfs:label "boolp", "bool?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (<dup> <truep> <swap> <falsep> <orp>) . + +<branch> a trith:Function, trith:Primitive ; + rdfs:label "branch", "if" ; + rdfs:comment "" ; + trith:arity 3 ; + trith:code () . + +<call> a trith:Function, trith:Primitive ; + rdfs:label "call" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . + +<ceil> a trith:Function ; + rdfs:label "ceil" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . # TODO + +<chr> a trith:Function, trith:Primitive ; + rdfs:label "chr" ; + rdfs:comment "" ; + rdfs:seeAlso <ord> ; + trith:arity 1 ; + trith:code () . + +<chrp> a trith:Function, trith:Primitive ; + rdfs:label "chrp", "chr?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . + +<clear> a trith:Function, trith:Primitive ; + rdfs:label "clear" ; + rdfs:comment "Clear the data stack" ; + trith:arity 0 ; + trith:code () . + +<cmp> a trith:Function, trith:Primitive ; + rdfs:label "cmp", "<=>" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . + +<concat> a trith:Function ; + rdfs:label "concat" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code (<swap> <reverse> <swap> (<dup> <first> <swap> <rest> <swap> <rot> <cons> <swap>) (<dup> <emptyp>) <until> <drop> <reverse>) . + +<cons> a trith:Function, trith:Primitive ; + rdfs:label "cons" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . + +<depth> a trith:Function ; + rdfs:label "depth" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (<stack> <dup> <length> () <cons> <concat> <unstack>) . + +<dec> a trith:Function ; + rdfs:label "dec" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (1 <sub>) . + +<dip> a trith:Function, trith:Primitive ; + rdfs:label "dip" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . + +<div> a trith:Function ; + rdfs:label "div", "/" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . # TODO + +<drop> a trith:Function, trith:Primitive ; + rdfs:label "drop" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . + +<drop2> a trith:Function ; + rdfs:label "drop2", "2drop" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code ((<drop>) <twice>) . + +<drop3> a trith:Function ; + rdfs:label "drop3", "3drop" ; + rdfs:comment "" ; + trith:arity 3 ; + trith:code ((<drop>) <thrice>) . + +<dup> a trith:Function, trith:Primitive ; + rdfs:label "dup" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . + +<dup2> a trith:Function, trith:Primitive ; + rdfs:label "dup2", "2dup" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . + +<dup3> a trith:Function, trith:Primitive ; + rdfs:label "dup3", "3dup" ; + rdfs:comment "" ; + trith:arity 3 ; + trith:code () . + +<each> a trith:Function ; + rdfs:label "each" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . # TODO + +<eighth> a trith:Function ; + rdfs:label "eighth" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (7 <nth>) . + +<emptyp> a trith:Function ; + rdfs:label "emptyp", "empty?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (<length> <zerop>) . + +<eq> a trith:Function, trith:Primitive ; + rdfs:label "eq", "=" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . + +<evenp> a trith:Function ; + rdfs:label "evenp", "even?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (2 <mod> <zerop>) . + +<exactp> a trith:Function ; + rdfs:label "exactp", "exact?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (<inexactp> <notp>) . + +<false> a trith:Function ; + rdfs:label "false" ; + rdfs:comment "" ; + trith:arity 0 ; + trith:code (<quote> <false>) . + +<falsep> a trith:Function ; + rdfs:label "falsep", "false?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (<false> <eq>) . + +<fifth> a trith:Function ; + rdfs:label "fifth" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (4 <nth>) . + +<first> a trith:Function, trith:Primitive ; + rdfs:label "first" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . + +<flatten> a trith:Function ; + rdfs:label "flatten" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . # TODO + +<floor> a trith:Function ; + rdfs:label "floor" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . # TODO + +<fourth> a trith:Function ; + rdfs:label "fourth" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (3 <nth>) . + +<ge> a trith:Function ; + rdfs:label "ge", ">=" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . # TODO + +<gt> a trith:Function ; + rdfs:label "gt", ">" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code (<cmp> <onep>) . + +<halt> a trith:Function, trith:Primitive ; + rdfs:label "halt" ; + rdfs:comment "" ; + trith:arity 0 ; + trith:code () . + +<inc> a trith:Function ; + rdfs:label "inc" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (1 <add>) . + +<inexactp> a trith:Function ; + rdfs:label "inexactp", "inexact?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (<exactp> <notp>) . + +<inf> a trith:Function ; + rdfs:label "inf" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (1.0 0.0 <div>) . + +<infp> a trith:Function ; + rdfs:label "infp", "inf?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (<abs> <inf> <eq>) . + +<intp> a trith:Function, trith:Primitive ; + rdfs:label "intp", "int?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . + +<iota> a trith:Function ; + rdfs:label "iota" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . # TODO + +<last> a trith:Function ; + rdfs:label "last" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . # TODO + +<le> a trith:Function ; + rdfs:label "le", "<=" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . # TODO + +<length> a trith:Function ; + rdfs:label "length" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (0 (<rest> <swap> <inc>) (<swap> <dup> <emptyp>) <until> <drop>) . + +<list> a trith:Function ; + rdfs:label "list" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (() <swap> (<cons>) <swap> <times> <reverse>) . + +<loop> a trith:Function ; + rdfs:label "loop" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (<dup> <call> (<loop>) <call>) . + +<lt> a trith:Function ; + rdfs:label "lt", "<" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code (<cmp> -1 <eq>) . + +<map> a trith:Function ; + rdfs:label "map" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . # TODO + +<max> a trith:Function ; + rdfs:label "max" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code (<dup2> <gt> (<drop>) (<swap> <drop>) <branch>) . + +<min> a trith:Function ; + rdfs:label "min" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code (<dup2> <lt> (<drop>) (<swap> <drop>) <branch>) . + +<mod> a trith:Function ; + rdfs:label "mod" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . # TODO + +<mul> a trith:Function ; + rdfs:label "mul", "*" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code (0 <swap> <abs> (<over> <add>) <swap> <times> <nip>) . # FIXME: negative operands + +<ne> a trith:Function ; + rdfs:label "ne", "!=" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code (<eq> <notp>) . + +<neg> a trith:Function ; + rdfs:label "neg" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (0 <swap> <sub>) . + +<negp> a trith:Function ; + rdfs:label "negp", "neg?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (0 <lt>) . + +<nil> a trith:Function ; + rdfs:label "nil" ; + rdfs:comment "" ; + trith:arity 0 ; + trith:code (<quote> <nil>) . + +<nilp> a trith:Function ; + rdfs:label "nilp", "nil?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (<nil> <eq>) . + +<ninth> a trith:Function ; + rdfs:label "ninth" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (8 <nth>) . + +<nip> a trith:Function ; + rdfs:label "nip" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code (<swap> <drop>) . + +<nip2> a trith:Function ; + rdfs:label "nip2", "2nip" ; + rdfs:comment "" ; + trith:arity 3 ; + trith:code (<swap> <drop> <swap> <drop>) . + +<nop> a trith:Function ; + rdfs:label "nop", ",", ";" ; + rdfs:comment "" ; + trith:arity 0 ; + trith:code (<nil> <drop>) . + +<not> a trith:Function ; + rdfs:label "not" ; + rdfs:comment "Bitwise NOT" ; + trith:arity 1 ; + trith:code (<neg> <dec>) . + +<notp> a trith:Function ; + rdfs:label "notp", "not?" ; + rdfs:comment "Logical NOT" ; + trith:arity 1 ; + trith:code ((<false>) (<true>) <branch>) . + +<nth> a trith:Function ; + rdfs:label "nth" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code ((<rest>) <swap> <times> <first>) . + +<num> a trith:Function, trith:Primitive ; + rdfs:label "num" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . + +<nump> a trith:Function, trith:Primitive ; + rdfs:label "nump", "num?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . + +<oddp> a trith:Function ; + rdfs:label "oddp", "odd?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (<evenp> <notp>) . + +<onep> a trith:Function ; + rdfs:label "onep", "one?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (1 <eq>) . + +<or> a trith:Function, trith:Primitive ; + rdfs:label "or" ; + rdfs:comment "Bitwise OR" ; + trith:arity 2 ; + trith:code () . + +<ord> a trith:Function, trith:Primitive ; + rdfs:label "ord" ; + rdfs:comment "" ; + rdfs:seeAlso <chr> ; + trith:arity 1 ; + trith:code () . + +<orp> a trith:Function ; + rdfs:label "orp", "or?" ; + rdfs:comment "Logical OR" ; + trith:arity 2 ; + trith:code (<swap> <dup> (<swap> <drop>) (<drop>) <branch>) . + +<over> a trith:Function ; + rdfs:label "over" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code (<dup2> <drop>) . + +<pick> a trith:Function ; + rdfs:label "pick" ; + rdfs:comment "" ; + trith:arity 3 ; + trith:code (<dup3> <drop2>) . + +<posp> a trith:Function ; + rdfs:label "posp", "pos?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (0 <gt>) . + +<pow> a trith:Function ; + rdfs:label "pow" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . # TODO + +<print> a trith:Function ; + rdfs:label "print", "." ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . # TODO + +<quote> a trith:Function, trith:Primitive ; + rdfs:label "quote", "\\", "'" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . + +<foldl> a trith:Function ; + rdfs:label "foldl" ; + rdfs:comment "" ; + trith:arity 3 ; + trith:code () . # TODO + +<rem> a trith:Function ; + rdfs:label "rem" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . # TODO + +<reset> a trith:Function ; + rdfs:label "reset" ; + rdfs:comment "" ; + trith:arity 0 ; + trith:code (<clear> <halt>) . + +<rest> a trith:Function, trith:Primitive ; + rdfs:label "rest" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . + +<reverse> a trith:Function ; + rdfs:label "reverse" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . # TODO + +<rot> a trith:Function, trith:Primitive ; + rdfs:label "rot" ; + rdfs:comment "" ; + trith:arity 3 ; + trith:code () . + +<second> a trith:Function ; + rdfs:label "second" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (1 <nth>) . + +<seq> a trith:Function, trith:Primitive ; + rdfs:label "seq" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . + +<seqp> a trith:Function, trith:Primitive ; + rdfs:label "seqp", "seq?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . + +<seventh> a trith:Function ; + rdfs:label "seventh" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (6 <nth>) . + +<shl> a trith:Function, trith:Primitive ; + rdfs:label "shl" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . + +<shr> a trith:Function, trith:Primitive ; + rdfs:label "shr" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . + +<sixth> a trith:Function ; + rdfs:label "sixth" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (5 <nth>) . + +<size> a trith:Function, trith:Primitive ; + rdfs:label "size" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . + +<stack> a trith:Function ; + rdfs:label "stack" ; + rdfs:comment "" ; + trith:arity 0 ; + trith:code (<depth> <list>) . + +<sub> a trith:Function, trith:Primitive ; + rdfs:label "sub", "-" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . + +<swap> a trith:Function, trith:Primitive ; + rdfs:label "swap" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . + +<tenth> a trith:Function ; + rdfs:label "tenth" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (9 <nth>) . + +<text> a trith:Function ; + rdfs:label "text" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . + +<textp> a trith:Function ; + rdfs:label "textp", "text?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . # TODO + +<third> a trith:Function ; + rdfs:label "third" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (2 <nth>) . + +<thrice> a trith:Function ; + rdfs:label "thrice", "3x" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (3 <times>) . + +<times> a trith:Function ; + rdfs:label "times" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code ((<dec> <over> <call>) (<dup> <zerop>) <until> <drop2>) . + +<true> a trith:Function ; + rdfs:label "true" ; + rdfs:comment "" ; + trith:arity 0 ; + trith:code (<quote> <true>) . + +<truep> a trith:Function ; + rdfs:label "truep", "true?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (<true> <eq>) . + +<twice> a trith:Function ; + rdfs:label "twice", "2x" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (2 <times>) . + +<unless> a trith:Function ; + rdfs:label "unless" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code ((<nop>) <swap> <branch>) . + +<unstack> a trith:Function, trith:Primitive ; + rdfs:label "unstack" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code () . + +<until> a trith:Function ; + rdfs:label "until" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code ((<notp>) <concat> <while>) . + +<when> a trith:Function ; + rdfs:label "when" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code ((<nop>) <branch>) . + +<while> a trith:Function ; + rdfs:label "while" ; + rdfs:comment "" ; + trith:arity 2 ; + trith:code () . # TODO + +<xor> a trith:Function, trith:Primitive ; + rdfs:label "xor" ; + rdfs:comment "Bitwise XOR" ; + trith:arity 2 ; + trith:code () . + +<xorp> a trith:Function ; + rdfs:label "xorp", "xor?" ; + rdfs:comment "Logical XOR" ; + trith:arity 2 ; + trith:code (<swap> <dup> (<swap> (<drop> <false>) (<nop>) <branch>) (<drop> <dup> (<nop>) (<drop> <false>) <branch>) <branch>) . + +<zerop> a trith:Function ; + rdfs:label "zerop", "zero?" ; + rdfs:comment "" ; + trith:arity 1 ; + trith:code (0 <eq>) . diff --git a/lib/.gitignore b/lib/.gitignore new file mode 100644 index 0000000..4560aee --- /dev/null +++ b/lib/.gitignore @@ -0,0 +1,6 @@ +bitescript +bitescript.rb +machinery +machinery.rb +sxp +sxp.rb diff --git a/lib/trith.rb b/lib/trith.rb new file mode 100644 index 0000000..39fa387 --- /dev/null +++ b/lib/trith.rb @@ -0,0 +1,20 @@ +require 'bigdecimal' +require 'rational' +require 'digest/sha1' +require 'rdf' +require 'rdf/ntriples' +require 'rdf/nquads' +require 'sxp' + +module Trith + include RDF + + autoload :Cache, 'trith/cache' + autoload :Compiler, 'trith/compiler' + autoload :Core, 'trith/core' + autoload :Function, 'trith/function' + autoload :Machine, 'trith/machine' + autoload :Reader, 'trith/reader' + autoload :Shell, 'trith/shell' + autoload :VERSION, 'trith/version' +end diff --git a/lib/trith/cache.rb b/lib/trith/cache.rb new file mode 100644 index 0000000..bfec2a7 --- /dev/null +++ b/lib/trith/cache.rb @@ -0,0 +1,97 @@ +module Trith + ## + # The Trith code cache. + class Cache < RDF::Repository + include RDF::Repository::Implementation rescue nil + + ## + # Returns a cache containing all core functions. + # + # @return [Trith::Cache] + def self.load_core + load(*Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'etc', '*.nt')))) + end + + ## + # @param [Array<String>] filenames + # @return [Trith::Cache] + def self.load(*filenames) + self.new do |repository| + filenames.each do |filename| + repository.load(filename) + end + end + end + + ## + # @param [Hash{Symbol => Object} options + def initialize(options = {}, &block) + @data = [] + super(options, &block) + end + + ## + # Returns `true` if the given `function` is cached. + # + # @param [Trith::Function, RDF::Resource] function + # @return [Boolean] + def has_function?(function) + id = case function + when Trith::Function then function.id + else Trith::Function.new(function).id + end + !query(:subject => id, :predicate => RDF.type, :object => Trith::Function::URI).empty? + end + + ## + # Returns `true` if a function with the given `label` is cached. + # + # @param [Symbol, #to_s] label + # @param [Hash{Symbol => Object} options + # @option options [Symbol, #to_s] :language (nil) + # @return [Boolean] + def has_label?(label, options = {}) + !query(:predicate => RDF::RDFS.label, :object => RDF::Literal.new(label.to_s, options)).empty? + end + + ## + # Enumerates each function in the cache. + # + # @return [Enumerator<Trith::Function>] + def each_function(&block) + unless block_given? + Enumerator.new(self, :each_function) + else + query(:predicate => RDF.type, :object => Trith::Function::URI) do |statement| + block.call(Trith::Function.new(statement.subject, :data => self)) + end + end + end + + ## + # Finds functions fulfilling the given criteria. + # + # @param [Hash{Symbol => Object}] options + # @option options [Symbol, #to_s] :label + # @return [Enumerator<Trith::Function>] + def find_functions(options = {}, &block) + unless block_given? + Enumerator.new(self, :find_functions, options) + else + # FIXME: would really need BGP query support in RDF.rb... + each_function do |function| + if options.empty? + block.call(function) + else + pattern = case + when options[:label] + {:predicate => RDF::RDFS.label, :object => options[:label].to_s} + else {} + end + block.call(function) unless query({:subject => function.id}.merge(pattern)).empty? + end + end + end + end + end # class Cache +end # module Trith diff --git a/lib/trith/compiler.rb b/lib/trith/compiler.rb new file mode 100644 index 0000000..32c4e31 --- /dev/null +++ b/lib/trith/compiler.rb @@ -0,0 +1,193 @@ +module Trith + ## + # A base class for Trith compiler targets. + # + # @abstract + class Compiler + # @return [Hash{Symbol => Object}] + attr_reader :options + + ## + # @param [Symbol, #to_sym] target + # @return [Class] + def self.for(target = nil, &block) + target = block.call if block_given? + self # TODO + end + + ## + # @param [Array<String>] filenames + # @param [Hash{Symbol => Object}] options + # @return [Compiler] + def self.compile_files(*filenames) + options = filenames.last.is_a?(Hash) ? filenames.peek : {} + self.compile(Reader.read_files(*filenames), options) + end + + ## + # @param [Enumerable] program + # @param [Hash{Symbol => Object}] options + # @return [Compiler] + def self.compile(program, options = {}) + self.new(options).compile(program, options) + end + + ## + # @param [Hash{Symbol => Object}] options + def initialize(options = {}) + @options = options + end + + ## + # @param [Enumerable] program + # @param [Hash{Symbol => Object}] options + # @return [Compiler] + def compile(program, options = {}) + program = program.respond_to?(:each) ? program : [program] + program.each { |op| compile_operand(op) } + self + end + + protected + + ## + # @param [Object] operand + # @return [void] + def compile_operand(operand) + case operand + when Symbol + compile_operator(operand) + when NilClass + compile_nil(operand) + when TrueClass, FalseClass + compile_boolean(operand) + when Numeric + compile_number(operand) + when String + compile_string(operand) + when URI + compile_reference(operand) + when Array, SXP::List + compile_quotation(operand) + when Machine, Function + compile_quotation(operand.to_a) + else + raise NotImplementedError.new("#{self.class}#compile_operand(#{operand.inspect})") + end + end + + ## + # @param [Symbol, #to_sym] operator + # @return [void] + # @abstract + def compile_operator(operator) + case operator.to_sym + when :nil then compile_nil(nil) + when :false then compile_boolean(false) + when :true then compile_boolean(true) + else raise NotImplementedError.new("#{self.class}#compile_operator(#{operator.inspect})") + end + end + + ## + # @param [NilClass] operand + # @return [void] + # @abstract + def compile_nil(operand = nil) + raise NotImplementedError.new("#{self.class}#compile_nil") + end + + ## + # @param [Boolean] operand + # @return [void] + # @abstract + def compile_boolean(operand) + raise NotImplementedError.new("#{self.class}#compile_boolean(#{operand.inspect})") + end + + ## + # @param [Numeric] operand + # @return [void] + # @abstract + def compile_number(operand) + case operand + when Integer + compile_integer(operand) + when Float + compile_float(operand) + when BigDecimal + compile_decimal(operand) + when Rational + compile_rational(operand) + else + raise NotImplementedError.new("#{self.class}#compile_number(#{operand.inspect})") + end + end + + ## + # @param [Integer] operand + # @return [void] + # @abstract + def compile_integer(operand) + raise NotImplementedError.new("#{self.class}#compile_integer(#{operand.inspect})") + end + + ## + # @param [Float] operand + # @return [void] + # @abstract + def compile_float(operand) + raise NotImplementedError.new("#{self.class}#compile_float(#{operand.inspect})") + end + + ## + # @param [BigDecimal] operand + # @return [void] + # @abstract + def compile_decimal(operand) + raise NotImplementedError.new("#{self.class}#compile_decimal(#{operand.inspect})") + end + + ## + # @param [Rational] operand + # @return [void] + # @abstract + def compile_rational(operand) + raise NotImplementedError.new("#{self.class}#compile_rational(#{operand.inspect})") + end + + ## + # @param [String] operand + # @return [void] + # @abstract + def compile_string(operand) + raise NotImplementedError.new("#{self.class}#compile_string(#{operand.inspect})") + end + + ## + # @param [URI] operand + # @return [void] + # @abstract + def compile_reference(operand) + raise NotImplementedError.new("#{self.class}#compile_reference(#{operand.inspect})") + end + + ## + # @param [Array] operand + # @return [void] + # @abstract + def compile_quotation(operand) + raise NotImplementedError.new("#{self.class}#compile_quotation(#{operand.inspect})") + end + + ## + # @private + def self.inherited(subclass) + subclass.send(:public_class_method, :new) + super + end + + # Prevent the instantiation of this class: + private_class_method :new + end # class Compiler +end # module Trith diff --git a/lib/trith/core.rb b/lib/trith/core.rb new file mode 100644 index 0000000..57b085f --- /dev/null +++ b/lib/trith/core.rb @@ -0,0 +1,20 @@ +module Trith + ## + # The Trith core operators. + module Core + require 'trith/core/execution' + require 'trith/core/stack' + require 'trith/core/arithmetic' + require 'trith/core/bitwise' + require 'trith/core/boolean' + require 'trith/core/comparison' + require 'trith/core/numeric' + require 'trith/core/math' + require 'trith/core/sequence' + require 'trith/core/textual' + require 'trith/core/output' + + # Include all submodule methods directly into Trith::Core: + constants.each { |mod| include(const_get(mod)) } + end # module Core +end # module Trith diff --git a/lib/trith/core/arithmetic.rb b/lib/trith/core/arithmetic.rb new file mode 100644 index 0000000..f31fdf2 --- /dev/null +++ b/lib/trith/core/arithmetic.rb @@ -0,0 +1,97 @@ +module Trith; module Core + ## + # Arithmetic operators. + # + # @see http://www.math.bas.bg/bantchev/articles/divmod.pdf + module Arithmetic + ## + # @param [Numeric] n + # @return [Numeric] + def abs(n) + n.abs + end + + ## + # @param [Numeric] n + # @return [Numeric] + def neg(n) + -n + end + + ## + # @param [Numeric] n + # @return [Numeric] + def inc(n) + n + 1 + end + + ## + # @param [Numeric] n + # @return [Numeric] + def dec(n) + n - 1 + end + + ## + # @param [Numeric] a + # @param [Numeric] b + # @return [Numeric] + def add(a, b) + a + b + end + alias_method :+, :add + + ## + # @param [Numeric] a + # @param [Numeric] b + # @return [Numeric] + def sub(a, b) + a - b + end + alias_method :-, :sub + + ## + # @param [Numeric] a + # @param [Numeric] b + # @return [Numeric] + def mul(a, b) + a * b + end + alias_method :*, :mul + + ## + # @param [Numeric] a + # @param [Numeric] b + # @return [Numeric] + def div(a, b) + a / b + end + alias_method :'/', :div + + ## + # @param [Numeric] a + # @param [Numeric] b + # @return [Numeric] + def rem(a, b) + a.remainder(b) + end + + ## + # @param [Numeric] a + # @param [Numeric] b + # @return [Numeric] + def mod(a, b) + a.modulo(b) + end + #alias_method :'%', :mod + + ## + # @param [Numeric] a + # @param [Numeric] b + # @return [Numeric] + def pow(a, b) + a ** b + end + #alias_method :'^', :pow + end # module Arithmetic +end; end # module Trith::Core diff --git a/lib/trith/core/bitwise.rb b/lib/trith/core/bitwise.rb new file mode 100644 index 0000000..8adfea8 --- /dev/null +++ b/lib/trith/core/bitwise.rb @@ -0,0 +1,54 @@ +module Trith; module Core + ## + # Bitwise operators. + # + # @see http://en.wikipedia.org/wiki/Bitwise_operation + module Bitwise + ## + # @param [Integer] a + # @return [Integer] + def not(a) + ~a + end + + ## + # @param [Integer] a + # @param [Integer] b + # @return [Integer] + def and(a, b) + a & b + end + + ## + # @param [Integer] a + # @param [Integer] b + # @return [Integer] + def or(a, b) + a | b + end + + ## + # @param [Integer] a + # @param [Integer] b + # @return [Integer] + def xor(a, b) + a ^ b + end + + ## + # @param [Integer] a + # @param [Integer] b + # @return [Integer] + def shl(a, b) + a << b + end + + ## + # @param [Integer] a + # @param [Integer] b + # @return [Integer] + def shr(a, b) + a >> b + end + end # module Bitwise +end; end # module Trith::Core diff --git a/lib/trith/core/boolean.rb b/lib/trith/core/boolean.rb new file mode 100644 index 0000000..11fac56 --- /dev/null +++ b/lib/trith/core/boolean.rb @@ -0,0 +1,114 @@ +module Trith; module Core + ## + # Boolean operators. + # + # @see http://ruby-doc.org/core-1.9/classes/NilClass.html + # @see http://ruby-doc.org/core-1.9/classes/FalseClass.html + # @see http://ruby-doc.org/core-1.9/classes/TrueClass.html + # @see http://en.wikipedia.org/wiki/Nil#Computer_programming + # @see http://en.wikipedia.org/wiki/Boolean_data_type + module Boolean + ## + # Boolean predicates. + module Predicates + ## + # @param [Object, #nil?] obj + # @return [Boolean] + def nilp(obj) + obj.nil? + end + alias_method :nil?, :nilp + + ## + # @param [Object] obj + # @return [Boolean] + def boolp(obj) + obj.equal?(false) || obj.equal?(true) + end + alias_method :bool?, :boolp + + ## + # @param [Object] obj + # @return [Boolean] + def falsep(obj) + obj.equal?(false) + end + alias_method :false?, :falsep + + ## + # @param [Object] obj + # @return [Boolean] + def truep(obj) + obj.equal?(true) + end + alias_method :true?, :truep + + ## + # @param [Object] a + # @return [Object] + def notp(a) + !a + end + alias_method :not?, :notp + + ## + # @param [Object] a + # @param [Object] b + # @return [Object] + def andp(a, b) + a && b + end + alias_method :and?, :andp + + ## + # @param [Object] a + # @param [Object] b + # @return [Object] + def orp(a, b) + a || b + end + alias_method :or?, :orp + + ## + # @param [Object] a + # @param [Object] b + # @return [Object] + def xorp(a, b) + a ^ b + end + alias_method :xor?, :xorp + end # module Predicates + + ## + # Boolean constructors. + module Constructors + ## + # @return [NilClass] + def nil + nil + end + + ## + # @param [Object] obj + # @return [Boolean] + def bool(obj) + !!obj + end + + ## + # @return [FalseClass] + def false + false + end + + ## + # @return [TrueClass] + def true + true + end + end # module Constructors + + # Include all submodule methods directly into Trith::Core::Boolean: + constants.each { |mod| include(const_get(mod)) } + end # module Boolean +end; end # module Trith::Core diff --git a/lib/trith/core/comparison.rb b/lib/trith/core/comparison.rb new file mode 100644 index 0000000..7d8086a --- /dev/null +++ b/lib/trith/core/comparison.rb @@ -0,0 +1,88 @@ +module Trith; module Core + ## + # Comparison operators. + # + # @see http://ruby-doc.org/core-1.9/classes/Comparable.html + # @see http://en.wikipedia.org/wiki/Comparison_(computer_programming) + # @see http://en.wikipedia.org/wiki/Relational_operator + module Comparison + ## + # @param [Object] a + # @param [Object] b + # @return [Integer] + def cmp(a, b) + a <=> b + end + alias_method :<=>, :cmp + + ## + # @param [Object] a + # @param [Object] b + # @return [Boolean] + def eq(a, b) + a == b + end + alias_method :'=', :eq + + ## + # @param [Object] a + # @param [Object] b + # @return [Boolean] + def ne(a, b) + a != b + end + alias_method :'!=', :ne + + ## + # @param [Object] a + # @param [Object] b + # @return [Boolean] + def lt(a, b) + a < b + end + alias_method :<, :lt + + ## + # @param [Object] a + # @param [Object] b + # @return [Boolean] + def le(a, b) + a <= b + end + alias_method :<=, :le + + ## + # @param [Object] a + # @param [Object] b + # @return [Boolean] + def gt(a, b) + a > b + end + alias_method :>, :gt + + ## + # @param [Object] a + # @param [Object] b + # @return [Boolean] + def ge(a, b) + a >= b + end + alias_method :>=, :ge + + ## + # @param [Object] a + # @param [Object] b + # @return [Object] + def min(a, b) + [a, b].min + end + + ## + # @param [Object] a + # @param [Object] b + # @return [Object] + def max(a, b) + [a, b].max + end + end # module Comparison +end; end # module Trith::Core diff --git a/lib/trith/core/execution.rb b/lib/trith/core/execution.rb new file mode 100644 index 0000000..5b603a1 --- /dev/null +++ b/lib/trith/core/execution.rb @@ -0,0 +1,165 @@ +module Trith; module Core + ## + # Execution control operators. + module Execution + ## + # @return [Machine] + def reset + @stack.clear + @queue.clear + self + end + + ## + # @return [Machine] + def halt + @queue.clear + self + end + + ## + # @return [Machine] + def nop + self # do nothing + end + alias_method :',', :nop + alias_method :';', :nop + + ## + # @return [Machine] + def quote + push([shift]) + end + alias_method :'\\', :quote + alias_method :"'", :quote + + ## + # @return [Machine] + def call(quot) + case quot + when Array + execute(quot) + when Symbol + execute([quot]) # FIXME + else # TODO: error + end + self + end + + ## + # @return [Machine] + def times(quot, count) + case quot + when Array + count.to_i.times { execute(quot) } + when Symbol + count.to_i.times { execute([quot]) } # FIXME + else # TODO: error + end + self + end + + ## + # @return [Machine] + def twice(quot) + case quot + when Array + 2.times { execute(quot) } + when Symbol + 2.times { execute([quot]) } # FIXME + else # TODO: error + end + self + end + alias_method :'2x', :twice + + ## + # @return [Machine] + def thrice(quot) + case quot + when Array + 3.times { execute(quot) } + when Symbol + 3.times { execute([quot]) } # FIXME + else # TODO: error + end + self + end + alias_method :'3x', :thrice + + ## + # @return [Machine] + def loop(quot) + case quot + when Array + execute([quot, :loop]) + execute(quot) + when Symbol + execute([quot, :quote, quot, :loop]) # FIXME + else # TODO: error + end + self + end + + ## + # @return [Machine] + def while(quot, cond) + with_saved_continuation(:while) do + Kernel.loop do + execute(cond) + case pop + when false, nil then break + else execute(quot) + end + end + end + self + end + + ## + # @return [Machine] + def until(quot, cond) + with_saved_continuation(:until) do + Kernel.loop do + execute(cond) + case pop + when false, nil then execute(quot) + else break + end + end + end + self + end + + ## + # @return [Machine] + def branch(cond, thenop, elseop) + case cond + when false, nil then execute(elseop) + else execute(thenop) + end + self + end + alias_method :if, :branch + + ## + # @return [Machine] + def when(cond, quot) + case cond + when false, nil then # nop + else execute(quot) + end + self + end + + ## + # @return [Machine] + def unless(cond, quot) + case cond + when false, nil then execute(quot) + else # nop + end + self + end + end # module Execution +end; end # module Trith::Core diff --git a/lib/trith/core/math.rb b/lib/trith/core/math.rb new file mode 100644 index 0000000..96abf95 --- /dev/null +++ b/lib/trith/core/math.rb @@ -0,0 +1,34 @@ +module Trith; module Core + ## + # Math operators. + # + # @see http://ruby-doc.org/core/classes/Math.html + module Math + ## + # Math constants. + module Constants + # TODO + end # module Constants + + ## + # Math operators. + module Operators + ## + # @param [Numeric, #ceil] n + # @return [Integer] + def ceil(n) + n.ceil + end + + ## + # @param [Numeric, #floor] n + # @return [Integer] + def floor(n) + n.floor + end + end # module Operators + + # Include all submodule methods directly into Trith::Core::Math: + constants.each { |mod| include(const_get(mod)) } + end # module Math +end; end # module Trith::Core diff --git a/lib/trith/core/numeric.rb b/lib/trith/core/numeric.rb new file mode 100644 index 0000000..aee16e0 --- /dev/null +++ b/lib/trith/core/numeric.rb @@ -0,0 +1,157 @@ +module Trith; module Core + ## + # Numerical operators. + # + # @see http://ruby-doc.org/core-1.9/classes/Numeric.html + # @see http://ruby-doc.org/core-1.9/classes/Integer.html + # @see http://ruby-doc.org/core-1.9/classes/Rational.html + # @see http://ruby-doc.org/core-1.9/classes/Float.html + module Numeric + ## + # Numeric constants. + module Constants + INF = (1.0 / 0.0).freeze + end # module Constants + + ## + # Numeric predicates. + module Predicates + ## + # @param [Object] obj + # @return [Boolean] + def nump(obj) + obj.is_a?(Numeric) + end + alias_method :num?, :nump + + ## + # @param [Object, #integer?] obj + # @return [Boolean] + def intp(obj) + obj.respond_to?(:integer?) && obj.integer? + end + alias_method :int?, :intp + + ## + # @param [Numeric, #infinite?] n + # @return [Boolean] + def infp(n) + case + when n.respond_to?(:infinite?) + !!n.infinite? + else false + end + end + alias_method :inf?, :infp + + ## + # @param [Numeric, #zero?] n + # @return [Boolean] + def zerop(n) + n.zero? + end + alias_method :zero?, :zerop + + ## + # @param [Numeric, #<=>] n + # @return [Boolean] + def onep(n) + n == 1 + end + alias_method :one?, :onep + + ## + # @param [Numeric, #<=>] n + # @return [Boolean] + def negp(n) + n < 0 + end + alias_method :neg?, :negp + + ## + # @param [Numeric, #<=>] n + # @return [Boolean] + def posp(n) + n > 0 + end + alias_method :pos?, :posp + + ## + # @param [Numeric, #odd?] n + # @return [Boolean] + def oddp(n) + n.odd? + end + alias_method :odd?, :oddp + + ## + # @param [Numeric, #even?] n + # @return [Boolean] + def evenp(n) + n.even? + end + alias_method :even?, :evenp + end # module Predicates + + ## + # Numeric constructors. + module Constructors + ## + # @param [Object] obj + # @return [Numeric] + def num(obj) + case obj + when Numeric then obj + else obj.to_i # FIXME + end + end + + ## + # @return [Numeric] + def inf + Constants::INF + end + end # module Constructors + + ## + # @private + module Experimental + ## + # @param [Numeric, #exact?] n + # @return [Boolean] + def exactp(n) + case n + when Integer then true + when Rational then true + when Float then false + else case + when n.respond_to?(:exact?) + n.exact? + else nil + end + end + end + alias_method :exact?, :exactp + + ## + # @param [Numeric, #inexact?] n + # @return [Boolean] + def inexactp(n) + case n + when Integer then false + when Rational then false + when Float then true + else case + when n.respond_to?(:inexact?) + n.inexact? + else nil + end + end + end + alias_method :inexact?, :inexactp + end # module Experimental + + # Include all submodule methods directly into Trith::Core::Numeric: + constants.each { |mod| include(const_get(mod)) } + end # module Numeric +end; end # module Trith::Core diff --git a/lib/trith/core/output.rb b/lib/trith/core/output.rb new file mode 100644 index 0000000..ab8f554 --- /dev/null +++ b/lib/trith/core/output.rb @@ -0,0 +1,13 @@ +module Trith; module Core + ## + # Output operators. + module Output + ## + # @return [Machine] + def print(obj) + $stdout.puts(obj) # FIXME + self + end + alias_method :'.', :print + end # module Output +end; end # module Trith::Core diff --git a/lib/trith/core/sequence.rb b/lib/trith/core/sequence.rb new file mode 100644 index 0000000..e674569 --- /dev/null +++ b/lib/trith/core/sequence.rb @@ -0,0 +1,407 @@ +module Trith; module Core + ## + # Sequence operators. + # + # @see http://ruby-doc.org/core-1.9/classes/Enumerable.html + # @see http://ruby-doc.org/core-1.9/classes/Enumerator.html + # @see http://en.wikipedia.org/wiki/Sequence + module Sequence + ## + # Sequence predicates. + module Predicates + ## + # @param [String, #each, #to_enum] obj + # @return [Boolean] + def seqp(obj) + case obj + when String then true + when Array then true + else case + when obj.respond_to?(:each) then true + when obj.respond_to?(:to_enum) then true + else false + end + end + end + alias_method :seq?, :seqp + + ## + # @param [#empty?, #size, #each] seq + # @return [Boolean] + def emptyp(seq) + case + when seq.respond_to?(:empty?) + seq.empty? + when seq.respond_to?(:size) + seq.size.zero? + when seq.respond_to?(:each) + seq.each.to_a.empty? # TODO: optimize + else + raise Machine::InvalidOperandError.new(seq, :emptyp) + end + end + alias_method :empty?, :emptyp + end # module Predicates + + ## + # Sequence constructors. + module Constructors + ## + # @param [String, #each, #to_enum] obj + # @return [Enumerator] + def seq(obj) + case obj + when String then obj.each_char + when Array then obj.each + else case + when obj.respond_to?(:each) + obj.each + when obj.respond_to?(:to_enum) + obj.to_enum + else + raise Machine::InvalidOperandError.new(obj, :seq) + end + end + end + + ## + # @overload cons(obj, seq) + # @param [#to_s] obj + # @param [String] seq + # @return [String] + # + # @overload cons(obj, seq) + # @param [Object] obj + # @param [Array, #to_a] seq + # @return [Array] + # + # @return [] + def cons(obj, seq) + case seq + when String + seq.dup.insert(0, obj.to_s.chr) + when Array + seq.dup.unshift(obj) + else case + when seq.respond_to?(:to_a) + seq.to_a.unshift(obj) + else # TODO: support for `#each` + end + end + end + + ## + # @param [Integer, #to_i] n + # @return [Enumerable] + def list(n) + stack.pop(n.to_i) + end + + ## + # @param [Integer, #to_i] n + # @return [Enumerable] + def iota(n) + # TODO: should support negative ranges as well. + (0...(n.to_i)).to_a + end + end # module Constructors + + ## + # Sequence accessors. + module Accessors + ## + # @param [#length, #size, #each] seq + # @return [Integer] + def length(seq) + case + when seq.respond_to?(:length) + seq.length + when seq.respond_to?(:size) + seq.size + when seq.respond_to?(:each) + seq.each.to_a.size # TODO: optimize + else + raise Machine::InvalidOperandError.new(seq, :length) + end + end + + ## + # @param [#rest, #[], #each] seq + # @return [Enumerable] + def rest(seq) + # TODO: check semantics for empty sequences + case + when seq.respond_to?(:rest) + seq.rest + when seq.respond_to?(:[]) + seq[1..-1] + when seq.respond_to?(:each) + seq.each.to_a[1..-1] # TODO: optimize + else + raise Machine::InvalidOperandError.new(seq, :rest) + end + end + + ## + # @param [#first, #[], #each] seq + # @return [Object] + def first(seq) + case seq + when String + seq[0].chr rescue nil # Ruby 1.8 compatible + else case + when seq.respond_to?(:first) then seq.first + else nth(seq, 0) + end + end + end + + ## + # @param [#second, #[], #each] seq + # @return [Object] + def second(seq) + case + when seq.respond_to?(:second) then seq.second + else nth(seq, 1) + end + end + + ## + # @param [#third, #[], #each] seq + # @return [Object] + def third(seq) + case + when seq.respond_to?(:third) then seq.third + else nth(seq, 2) + end + end + + ## + # @param [#fourth, #[], #each] seq + # @return [Object] + def fourth(seq) + case + when seq.respond_to?(:fourth) then seq.fourth + else nth(seq, 3) + end + end + + ## + # @param [#fifth, #[], #each] seq + # @return [Object] + def fifth(seq) + case + when seq.respond_to?(:fifth) then seq.fifth + else nth(seq, 4) + end + end + + ## + # @param [#sixth, #[], #each] seq + # @return [Object] + def sixth(seq) + case + when seq.respond_to?(:sixth) then seq.sixth + else nth(seq, 5) + end + end + + ## + # @param [#seventh, #[], #each] seq + # @return [Object] + def seventh(seq) + case + when seq.respond_to?(:seventh) then seq.seventh + else nth(seq, 6) + end + end + + ## + # @param [#eighth, #[], #each] seq + # @return [Object] + def eighth(seq) + case + when seq.respond_to?(:eighth) then seq.eighth + else nth(seq, 7) + end + end + + ## + # @param [#ninth, #[], #each] seq + # @return [Object] + def ninth(seq) + case + when seq.respond_to?(:ninth) then seq.ninth + else nth(seq, 8) + end + end + + ## + # @param [#tenth, #[], #each] seq + # @return [Object] + def tenth(seq) + case + when seq.respond_to?(:tenth) then seq.tenth + else nth(seq, 9) + end + end + + ## + # @param [#nth, #[], #each] seq + # @param [Integer, #to_i] n + # @return [Object] + def nth(seq, n) + case seq + when String + seq[n.to_i].chr rescue nil # Ruby 1.8 compatible + else case + when seq.respond_to?(:nth) + seq.nth(n) + when seq.respond_to?(:[]) + seq[n.to_i] + when seq.respond_to?(:each) + seq.each.to_a[n.to_i] # TODO: optimize + else + raise Machine::InvalidOperandError.new(seq, :nth) + end + end + end + + ## + # @param [#last, #[], #each] seq + # @return [Object] + def last(seq) + case seq + when String + seq[-1].chr rescue nil # Ruby 1.8 compatible + else case + when seq.respond_to?(:last) + seq.last + when seq.respond_to?(:[]) + seq[-1] + when seq.respond_to?(:each) + seq.each.to_a.last # TODO: optimize + else + raise Machine::InvalidOperandError.new(seq, :last) + end + end + end + end # module Accessors + + ## + # Sequence operators. + module Operators + ## + # @param [#concat, #each] seq1 + # @param [#each] seq2 + # @return [Enumerable] + def concat(seq1, seq2) + case + when seq1.respond_to?(:concat) + seq1.dup.concat(seq2) + when seq1.respond_to?(:each) + seq1.each.to_a.concat(seq2.each.to_a) # TODO: optimize + else + raise Machine::InvalidOperandError.new(seq1, :concat) + end + end + + ## + # @param [#reverse, #each] seq + # @return [Enumerable] + def reverse(seq) + case seq + when String then seq.reverse + when Array then seq.reverse + else case + when seq.respond_to?(:reverse) + seq.reverse + when seq.respond_to?(:each) + seq.each.to_a.reverse # TODO: optimize + else + raise Machine::InvalidOperandError.new(seq, :reverse) + end + end + end + + ## + # @param [#flatten, #each] seq + # @return [Enumerable] + def flatten(seq) + case seq + when String then seq + when Array then seq.flatten + else case + when seq.respond_to?(:flatten) + seq.flatten + when seq.respond_to?(:each) + seq.each.to_a.flatten # TODO: optimize + else + raise Machine::InvalidOperandError.new(seq, :flatten) + end + end + end + end # module Operators + + ## + # Sequence combinators. + module Combinators + ## + # @param [#each] seq + # @param [Array] quot + # @return [Machine] + def each(seq, quot) + seq = case seq + when String then seq.each_char + else case + when seq.respond_to?(:each) then seq.each + else raise Machine::InvalidOperandError.new(seq, :each) + end + end + with_saved_continuation(:each) do + seq.each { |elem| push(elem).execute(quot) } + end + end + + ## + # @param [#map, #each] seq + # @param [Array] quot + # @return [Machine] + def map(seq, quot) + seq = case seq + when String then seq.each_char + else case + when seq.respond_to?(:map) then seq + when seq.respond_to?(:each) then seq.each + else raise Machine::InvalidOperandError.new(seq, :map) + end + end + with_saved_continuation(:map) do + push(seq.map { |elem| push(elem).execute(quot).pop }) + end + end + + ## + # @param [#reduce, #each] seq + # @param [Object] identity + # @param [Array] quot + # @return [Machine] + def foldl(seq, identity, quot) + seq = case seq + when String then seq.each_char + else case + when seq.respond_to?(:reduce) then seq + when seq.respond_to?(:each) then seq.each + else raise Machine::InvalidOperandError.new(seq, :foldl) + end + end + with_saved_continuation(:foldl) do + push(seq.reduce(identity) { |prev, elem| push(prev, elem).execute(quot).pop }) + end + end + end # module Combinators + + # Include all submodule methods directly into Trith::Core::Sequence: + constants.each { |mod| include(const_get(mod)) } + end # module Sequence +end; end # module Trith::Core diff --git a/lib/trith/core/stack.rb b/lib/trith/core/stack.rb new file mode 100644 index 0000000..ea6d41d --- /dev/null +++ b/lib/trith/core/stack.rb @@ -0,0 +1,138 @@ +module Trith; module Core + ## + # Stack operators. + module Stack + ## + # Stack shufflers. + module Shufflers + ## + # @return [Machine] + def clear + @stack.clear + self + end + + ## + # @return [Machine] + def depth + push(@stack.size) + end + + ## + # @return [Machine] + def stack_ + @stack = [@stack] + self + end + + ## + # @param [#to_a, #each] + # @return [Machine] + def unstack(seq) + @stack = case seq + when String then seq.each_char.to_a + when Array then seq + else case + when seq.respond_to?(:to_a) then seq.to_a + when seq.respond_to?(:each) then seq.each.to_a + else raise Machine::InvalidOperandError.new(seq, :unstack) + end + end + self + end + + ## + # @return [Machine] + def drop + pop + self + end + + ## + # @return [Machine] + def drop2 + pop(2) + self + end + alias_method :'2drop', :drop2 + + ## + # @return [Machine] + def drop3 + pop(3) + self + end + alias_method :'3drop', :drop3 + + ## + # @return [Machine] + def dup + push(*(pop(1) * 2)) + end + + ## + # @return [Machine] + def dup2 + push(*(pop(2) * 2)) + end + alias_method :'2dup', :dup2 + + ## + # @return [Machine] + def dup3 + push(*(pop(3) * 2)) + end + alias_method :'3dup', :dup3 + + ## + # @return [Machine] + def swap + push(*pop(2).reverse) + end + + ## + # @return [Machine] + def nip + push(pop(2).last) + end + + ## + # @return [Machine] + def nip2 + push(pop(3).last) + end + alias_method :'2nip', :nip2 + + ## + # @return [Machine] + def over + push(*((ops = pop(2)) + [ops.first])) + end + + ## + # @return [Machine] + def pick + push(*((ops = pop(3)) + [ops.first])) + end + + ## + # @return [Machine] + def rot(a, b, c) + push(b, c, a) + end + end # module Shufflers + + ## + # Stack combinators. + module Combinators + ## + # @return [Machine] + def dip + # TODO + end + end # module Combinators + + # Include all submodule methods directly into Trith::Core::Stack: + constants.each { |mod| include(const_get(mod)) } + end # module Stack +end; end # module Trith::Core diff --git a/lib/trith/core/textual.rb b/lib/trith/core/textual.rb new file mode 100644 index 0000000..7adb703 --- /dev/null +++ b/lib/trith/core/textual.rb @@ -0,0 +1,86 @@ +module Trith; module Core + ## + # Textual operators. + # + # @see http://ruby-doc.org/core-1.9/classes/String.html + module Textual + ## + # Textual predicates. + module Predicates + ## + # @param [Object] obj + # @return [Boolean] + def chrp(obj) + case obj + when String then obj.size == 1 + else false + end + end + alias_method :chr?, :chrp + + ## + # @param [Object] obj + # @return [Boolean] + def textp(obj) + case obj + when String then true + else false + end + end + alias_method :text?, :textp + end + + ## + # Textual constructors. + module Constructors + ## + # @param [Integer, String] obj + # @return [String] + def chr(obj) + case obj + when Integer then obj.chr(Encoding::UTF_8) + when String then obj.chr + else raise Machine::InvalidOperandError.new(obj, :chr) + end + end + + ## + # @param [Object] obj + # @return [String] + def text(obj) + case obj + when String then obj + else obj.to_s # FIXME + end + end + end # module Constructors + + ## + # Textual operators. + module Operators + ## + # @param [Integer, String] obj + # @return [Integer] + def ord(obj) + case obj + when Integer then obj + when String then obj.ord + else raise Machine::InvalidOperandError.new(obj, :ord) + end + end + + ## + # @param [String] str + # @return [Integer] + def size(str) + case str + when String then str.bytesize + else -1 # TODO: error + end + end + end # module Operators + + # Include all submodule methods directly into Trith::Core::Textual: + constants.each { |mod| include(const_get(mod)) } + end # module Textual +end; end # module Trith::Core diff --git a/lib/trith/function.rb b/lib/trith/function.rb new file mode 100644 index 0000000..9260ea5 --- /dev/null +++ b/lib/trith/function.rb @@ -0,0 +1,84 @@ +module Trith + ## + # A Trith function. + class Function + URI = RDF::URI("http://trith.org/lang/Function").freeze + + # @return [RDF::Resource] + attr_accessor :id + + # @return [Symbol] + attr_accessor :label + + # @return [String] + attr_accessor :comment + + ## + # @param [RDF::Resource] id + def initialize(id = nil, options = {}, &block) + @id = case id + when nil then RDF::Node.new + when RDF::Resource then id + else RDF::Resource.new(id) + end + + if block_given? + case block.arity + when 1 then block.call(self) + else self.instance_eval(&block) + end + end + end + + ## + # @return [Symbol] + def label + @label ||= id.to_s.sub(/^(.*)\/([^\/]+)$/, '\2').to_sym # FIXME + end + + ## + # @return [Enumerable<Symbol>] + def labels + [label] # FIXME + end + + ## + # Returns `true` if this is a primitive function. + # + # Primitive functions are implemented directly in the Trith interpreter + # or compiler using native code. + # + # @return [Boolean] + def is_primitive? + false # TODO + end + + alias_method :is_native?, :is_primitive? + + ## + # Returns a developer-friendly representation of this function. + # + # @return [String] + def inspect + sprintf("#<%s:%#0x(%s)>", self.class.name, __id__, id.to_s) + end + + ## + # Returns the RDF representation of this function. + # + # @return [RDF::Graph] + def to_rdf + RDF::Graph.new(id) do |graph| + graph << [id, RDF.type, Trith::Function::URI] + graph << [id, RDF::RDFS.label, label] if label + graph << [id, RDF::RDFS.comment, label] if comment + end + end + + ## + # @return [Enumerator] + def each_statement(&block) + to_rdf.each_statement(&block) + end + end # class Function +end # module Trith diff --git a/lib/trith/machine.rb b/lib/trith/machine.rb new file mode 100644 index 0000000..23d6066 --- /dev/null +++ b/lib/trith/machine.rb @@ -0,0 +1,380 @@ +module Trith + ## + # The Trith virtual machine. + class Machine + # @return [Array] + attr_reader :stack + + # @return [Array] + attr_reader :queue + + # @return [Proc] + attr_accessor :execute_hook + + ## + # Executes `code` in a new virtual machine instance. + # + # The machine will halt when the queue is exhausted, when encountering + # a `halt` operator, or when encountering an error condition. + # + # @overload self.run(code) + # @param [Array] code + # @return [Object] + # + # @overload self.run(code) + # @param [Array] code + # @yield [machine] + # @yieldparam [Machine] machine + # @return [Object] + # + # @return [Object] + def self.run(code = [], &block) + self.new([], code).execute(&block).peek + end + + ## + # Initializes a new virtual machine with the given initial `stack`, + # `queue` and environment. + # + # @param [Array] stack + # @param [Array] queue + # @param [Hash] env + # @yield [machine] + # @yieldparam [Machine] machine + def initialize(stack = [], queue = [], env = {}, &block) + @stack, @queue, @env = stack, queue, {} + import!(Trith::Core) + env.each do |name, operator| + if operator.is_a?(Proc) + define!(name, &operator) + else + define!(name, operator) + end + end + execute(&block) if block_given? + end + + ## + # Returns a developer-friendly representation of this machine. + # + # @return [String] + def inspect + sprintf("#<%s:%#0x(%s : %s)>", self.class.name, __id__, @stack.inspect, @queue.inspect) + end + + ## + # Imports operators from the given `module` into the virtual machine's + # current environment. + # + # @param [Module] module + # @return [Machine] + def import!(mod) + case mod + when Module then import_module!(mod) + when Function then # TODO + else # TODO: error + end + self + end + + ## + # Defines a new operator `name` that will execute the given `code`. + # + # @param [Symbol, #to_sym] name + # @param [Array] code + # @param [Hash{Symbol => Object}] options + # @return [Machine] + def define!(name, code = [], options = {}, &block) + @env[name = name.to_sym] = lambda { execute(code, &block) } + unless options[:method] == false + this = class << self; self; end + this.send(:define_method, name, &@env[name]) + end + self + end + + ## + # Returns the concatenation of the stack and queue. + # + # @return [Array] + def to_a + (@stack + @queue).to_a + end + + ## + # Returns the operand at the top of the stack. + # + # If the stack is empty, returns `nil`. + # + # @return [Object] + def peek + @stack.last + end + + ## + # Pops and returns one or more operands off the top of the stack. + # + # If the stack doesn't have sufficient operands, raises a stack + # underflow error. + # + # @overload pop + # @return [Object] + # + # @overload pop(n) + # @param [Integer] n + # @return [Array] + # + # @return [Object] + # @raise [StackUnderflowError] + def pop(n = nil) + if @stack.size < (n || 1) + raise StackUnderflowError.new + else + n ? @stack.pop(n) : @stack.pop + end + end + + ## + # Pushes the given operands onto the top of the stack. + # + # If no operands were given, shifts an operand off the front of the + # queue. + # + # @overload push + # @return [Machine] + # + # @overload push(*ops) + # @param [Array] ops + # @return [Machine] + # + # @return [Machine] + def push(*ops) + @stack.push(*(ops.empty? ? [shift] : ops)) + self + end + + ## + # Shifts and returns one or more operands off the front of the queue. + # + # If the queue doesn't have sufficient operands, throws a `:halt` + # symbol. + # + # @overload shift + # @return [Object] + # + # @overload shift(n) + # @param [Integer] n + # @return [Array] + # + # @return [Object] + def shift(n = nil) + if @queue.size < (n || 1) + throw(:halt) # caught in `#execute` + else + n ? @queue.shift(n) : @queue.shift + end + end + + ## + # Prepends the given operands onto the front of the queue. + # + # If no operands were given, pops an operand off the top of the stack. + # + # @overload unshift + # @return [Machine] + # + # @overload unshift(*ops) + # @param [Array] ops + # @return [Machine] + # + # @return [Machine] + def unshift(*ops) + @queue.unshift(*(ops.empty? ? [pop] : ops)) + self + end + + ## + # Executes the virtual machine until it halts. + # + # The machine will halt when the queue is exhausted, when encountering + # a `halt` operator, or when encountering an error condition. + # + # @overload execute(code) + # @param [Array] code + # @return [Machine] + # + # @overload execute(code) + # @param [Array] code + # @yield [machine] + # @yieldparam [Machine] machine + # @return [Machine] + # + # @return [Machine] + def execute(code = [], &block) + @queue.unshift(*code) unless code.empty? + + catch(:halt) do # thrown in `#shift` + Kernel.loop do + execute_hook.call if execute_hook && [email protected]? + + op = shift + case + when operator?(op) + if fn = @env[op] + fn.call + else + unshift(op) + raise InvalidOperatorError.new(op) + end + when operand?(op) + push(op) + else + raise InvalidOperandError.new(op) + end + end + end + + if block_given? + case block.arity + when 1 then block.call(self) + else instance_eval(&block) + end + end + + return self + end + + protected + + ## + # Returns `true` if `op` is an operator. + # + # @param [Object] op + # @return [Boolean] + def operator?(op) + op.is_a?(Symbol) + end + + ## + # Returns `true` if `op` is an operand. + # + # @param [Object] op + # @return [Boolean] + def operand?(op) + !operator?(op) + end + + ## + # Returns `true` if `op` is a quotation. + # + # @param [Object] op + # @return [Boolean] + def quotation?(op) + op.is_a?(Array) + end + + ## + # @private + def method_missing(operator, *operands, &block) + begin + super + rescue NoMethodError => e + raise InvalidOperatorError.new(operator) + end + end + + ## + # Imports operators from the given `module` into the virtual machine's + # current environment. + # + # @param [Module] module + # @return [void] + def import_module!(mod) + # Include all instance methods from the module into `self`: + this = class << self; self; end + this.send(:include, mod) + + # Create wrapper methods to support operators that need their + # arguments and result marshalled from/to the virtual machine stack: + mod.public_instance_methods(true).map(&:to_sym).each do |method| + op = mod.instance_method(method).bind(self) + case method + when :stack_ # FIXME + @env[:stack] = op + else + @env[method] = this.send(:define_method, method) do |*args| + result = op.call(*(!args.empty? ? args : (op.arity > 0 ? pop(op.arity) : []))) + push(result) unless result.equal?(self) + return self + end + end + end + end + + ## + # Invokes the given block with an empty code queue, restoring the + # queue contents after the block returns. + # + # @yield + # @param [Symbol] name + # @return [void] + def with_saved_continuation(name = nil, &block) + cc = capture_continuation + case block.arity + when 1 then block.call(cc) + else block.call + end + @queue.unshift(*cc) + self + end + + ## + # Invokes the given block with an empty code queue, passing the previous + # queue contents as an argument. + # + # @yield + # @return [void] + def with_current_continuation(&block) + block.call(capture_continuation) + self + end + + ## + # Captures the current contents of the code queue, returning them to the + # caller after first clearing the queue. + # + # @return [Array] + def capture_continuation(full = false) + continuation = @queue.dup + @queue.clear + continuation + end + + ### + # Invalid operator + class InvalidOperatorError < NoMethodError + attr_reader :operator + + def initialize(operator) + @operator = operator + super("invalid operator: #{operator}") + end + end + + ### + # Invalid operand + class InvalidOperandError < ArgumentError + attr_reader :operand + attr_reader :operator + + def initialize(operand, operator = nil) + @operand, @operator = operand, operator + super("invalid operand: #{operand.inspect}") + end + end + + ### + # Stack underflow + class StackUnderflowError < RuntimeError; end + end # class Machine +end # module Trith diff --git a/lib/trith/reader.rb b/lib/trith/reader.rb new file mode 100644 index 0000000..5845f58 --- /dev/null +++ b/lib/trith/reader.rb @@ -0,0 +1,50 @@ +module Trith + ## + # The Trith code parser. + # + # @see http://sxp.rubyforge.org/ + class Reader + ## + # @param [String, #to_s] url + # @param [Hash{Symbol => Object}] options + # @return [Enumerable<Object>] + def self.read_url(url, options = {}) + SXP.read_url(url, options) + end + + ## + # @param [Enumerable<String>] filenames + # @param [Hash{Symbol => Object}] options + # @return [Enumerable<Object>] + def self.read_files(*filenames) + SXP.read_files(*filenames) + end + + ## + # @param [String, #to_s] filename + # @param [Hash{Symbol => Object}] options + # @return [Enumerable<Object>] + def self.read_file(filename, options = {}) + SXP.read_file(filename, options) + end + + ## + # @param [IO, StringIO, String] input + # @param [Hash{Symbol => Object}] options + # @return [Enumerable<Object>] + def self.read_all(input, options = {}) + SXP.read_all(input, options) + end + + ## + # @param [IO, StringIO, String] input + # @param [Hash{Symbol => Object}] options + # @return [Object] + def self.read(input, options = {}) + SXP.read(input, options) + end + + # Prevent the instantiation of this class: + private_class_method :new + end # class Reader +end # module Trith diff --git a/lib/trith/shell.rb b/lib/trith/shell.rb new file mode 100644 index 0000000..84405f5 --- /dev/null +++ b/lib/trith/shell.rb @@ -0,0 +1,145 @@ +module Trith + ## + # Supporting code for the `3sh` shell. + module Shell + require 'readline' unless defined?(Readline) + + autoload :History, 'trith/shell/history' + autoload :Inspect, 'trith/shell/inspect' + + ## + # Initializes shell functionality and the Readline library. + # + # @param [Trith::Cache] cache + # @return [void] + def self.setup!(cache) + Readline.completion_proc = completion_proc(cache) + end + + ## + # Returns a developer-friendly representation of `value`. + # + # @param [Object] value + # @param [Hash{Symbol => Object}] options + # @return [String] + def self.inspect(value, options = {}) + Inspect.inspect(value, {:color => has_color?}.merge(options)) + end + + ## + # Returns a colorized error message string. + # + # @param [Exception] error + # @param [Hash{Symbol => Object}] options + # @return [String] + def self.format_error(error, options = {}) + Inspect.colorize(error.to_s, has_color? ? :red : nil) + end + + ## + # Reads and returns a line of input from the terminal. + # + # @param [String] prompt + # @return [String] + # @see http://bogojoker.com/readline/ + def self.readline(prompt) + Readline.readline(prompt) + end + + ## + # Returns a symbol indicating which Readline library this Ruby + # implementation uses. + # + # The possible return values are `:readline`, `:libedit` and `:jruby`. + # + # The default Ruby versions shipped with Mac OS X use `:libedit` as + # their Readline library and have buggy functionality that needs to be + # worked around. + # + # @return [Symbol] + # @see http://bogojoker.com/readline/#libedit_detection + def self.readline_library + @readline_library ||= case RUBY_PLATFORM.to_sym + when :java + RUBY_ENGINE.to_sym rescue :jruby # JRuby 1.4.x/1.5.x + else + begin # Ruby with `readline` + Readline.emacs_editing_mode + :readline + rescue NotImplementedError # Ruby with `libedit` (Mac OS X) + :libedit + rescue + :libedit # just to be on the safe side + end + end + end + + ## + # Returns an input completion proc for use with Readline. + # + # @param [Trith::Cache] cache + # @return [Proc] + # @see http://bogojoker.com/readline/ + def self.completion_proc(cache) + Readline.completion_append_character = ' ' unless broken_append_character? + proc do |prefix| + candidates = [] + # TODO: optimize this once RDF::Queryable supports #query([s, p, /o/]) + cache.each_function do |function| + function.labels.each do |label| + candidates << label.to_s if label.to_s.start_with?(prefix) + end + end + candidates.map! { |candidate| candidate << ' ' } if broken_append_character? + candidates.uniq + end + end + + ## + # Returns `true` if the shell's terminal supports ANSI color escapes. + # + # @return [Boolean] + def self.has_color? + @has_color ||= case + when !$stdout.isatty then false + when ENV['TERM'] =~ /color/ then true # e.g. "xterm-color" + else + begin + # @see http://rubygems.org/gems/ruby-terminfo + require 'terminfo' unless defined?(TermInfo) + TermInfo.default_object.tigetnum('colors').to_i > 1 + rescue + false # the only safe default + end + end + end + + protected + + ## + # Returns `true` if the first call to `Readline::HISTORY.push` is broken + # on this Ruby implementation. + # + # This is a `libedit`-related bug encountered with the default Ruby + # versions shipped with Mac OS X. + # + # @return [Boolean] + # @see http://bogojoker.com/readline/#libedit_history_issue + def self.broken_initial_history? + readline_library == :libedit + end + + ## + # Returns `true` if `Readline.completion_append_character` is broken on + # this Ruby implementation. + # + # The feature in question is currently broken on Ruby with `libedit` and + # just unimplemented on JRuby 1.4.x/1.5.x + # + # @return [Boolean] + # @see http://bogojoker.com/readline/#libedit_completion_append_character_issue + def self.broken_append_character? + [:libedit, :jruby].include?(readline_library) + end + end # module Shell +end # module Trith diff --git a/lib/trith/shell/history.rb b/lib/trith/shell/history.rb new file mode 100644 index 0000000..7b510f0 --- /dev/null +++ b/lib/trith/shell/history.rb @@ -0,0 +1,108 @@ +module Trith; module Shell + ## + # Supporting code for the `3sh` shell's input line history. + module History + require 'readline' unless defined?(Readline) + + FILE = File.join(ENV['TRITH_HOME'] || '~', '.trith', '3sh.log').freeze unless const_defined?(:FILE) + MODE = 0640 + + ## + # Loads the shell history from the `~/.trith/3sh.log` file. + # + # @return [void] + def self.load! + unless (lines = File.readlines(File.expand_path(FILE)) rescue []).empty? + Readline::HISTORY.push(*lines.map { |line| line.chomp.strip }) + @load_count = Readline::HISTORY.size + end + end + + ## + # Dumps the shell history to the `~/.trith/3sh.log` file. + # + # @return [void] + def self.dump! + begin + require 'fileutils' unless defined?(FileUtils) + FileUtils.mkdir_p(File.expand_path(File.dirname(FILE)), :mode => 0750) + File.open(File.expand_path(FILE), 'a+', MODE) do |file| + lines = Readline::HISTORY.to_a + lines.slice!(0, @load_count) if @load_count + file.puts(lines) + end + rescue Errno::ENOENT # ignore 'No such file or directory' errors + rescue Errno::EACCES # ignore 'Permission denied' errors + end + end + + ## + # Returns `true` if the shell history is empty. + # + # @return [Boolean] + def self.empty? + Readline::HISTORY.empty? + end + + ## + # Returns the number of lines in the shell history. + # + # @return [Integer] + def self.size + Readline::HISTORY.size + end + + ## + # Returns `true` if the shell history includes `line`. + # + # @param [String] line + # @return [Boolean] + def self.include?(line) + Readline::HISTORY.include?(line) + end + + ## + # Appends `line` to the shell history. + # + # Does not append empty lines or consecutive duplicates, and works + # around implementation-specific issues where needed. + # + # @param [String] line + # @return [void] + def self.push(line) + unless line =~ /^\s$/ || line == peek + Readline::HISTORY.push(line) + + # This is a workaround for a libedit-related bug encountered with + # the default Ruby versions shipped with Mac OS X. + # @see http://bogojoker.com/readline/#libedit_history_issue + unless Readline::HISTORY.include?(line) + Readline::HISTORY.push(line) + end + end + end + + ## + # Returns the most recent line from the shell history. + # + # @return [String] + def self.peek + case + when Readline::HISTORY.respond_to?(:peek) + Readline::HISTORY.peek + when Readline::HISTORY.respond_to?(:last) + Readline::HISTORY.last + else + Readline::HISTORY.to_a.last + end + end + + ## + # Returns an array representation of the shell history. + # + # @return [Array<String>] + def self.to_a + Readline::HISTORY.to_a + end + end # module History +end; end # module Trith::Shell diff --git a/lib/trith/shell/inspect.rb b/lib/trith/shell/inspect.rb new file mode 100644 index 0000000..3986b78 --- /dev/null +++ b/lib/trith/shell/inspect.rb @@ -0,0 +1,100 @@ +module Trith; module Shell + ## + module Inspect + ## + # Escape codes for colored shell output. + module Color + NOTHING = "\033[0;0m".freeze + BLACK = "\033[0;30m".freeze + RED = "\033[0;31m".freeze + GREEN = "\033[0;32m".freeze + BROWN = "\033[0;33m".freeze + BLUE = "\033[0;34m".freeze + PURPLE = "\033[0;35m".freeze + CYAN = "\033[0;36m".freeze + LIGHT_GRAY = "\033[0;37m".freeze + DARK_GRAY = "\033[1;30m".freeze + LIGHT_RED = "\033[1;31m".freeze + LIGHT_GREEN = "\033[1;32m".freeze + YELLOW = "\033[1;33m".freeze + LIGHT_BLUE = "\033[1;34m".freeze + LIGHT_PURPLE = "\033[1;35m".freeze + LIGHT_CYAN = "\033[1;36m".freeze + WHITE = "\033[1;37m".freeze + + # Freeze all color escape strings: + constants.each do |color| + color.force_encoding(Encoding::ASCII) if color.respond_to?(:force_encoding) + color.freeze + end + end + + ## + # @param [String, #to_s] text + # @param [Symbol, #to_s] color + # @return [String] + def self.colorize(text, color) + !color ? text.to_s : [(Color.const_get(color.to_s.upcase) rescue nil), text.to_s, Color::NOTHING].join('') + end + + ## + # @param [Object] value + # @param [Hash{Symbol => Object}] options + # @return [String] + def self.inspect(value, options = {}) + case value + when NilClass then colorize(:nil, options[:color] ? :green : nil) + when FalseClass then colorize(false, options[:color] ? :green : nil) + when TrueClass then colorize(true, options[:color] ? :green : nil) + when Symbol then colorize(value.to_s, options[:color] ? :yellow : nil) + when Numeric then colorize(value.inspect, options[:color] ? :cyan : nil) + when String then inspect_string(value, options) + when Array then inspect_array(value, options) + when RDF::URI then inspect_reference(value, options) + when Machine then inspect_machine(value, options) + else value.inspect + end + end + + ## + # @param [Machine] machine + # @param [Hash{Symbol => Object}] options + # @return [String] + def self.inspect_machine(machine, options = {}) + (options[:prefix].to_s || '') + + (options[:align] ? ' ' * [20 - inspect(machine.stack, :color => false).size, 0].max : '') + + inspect(machine.stack, options) + ' : ' + + inspect(machine.queue, options) + end + + ## + # @param [Array, #to_ary] array + # @param [Hash{Symbol => Object}] options + # @return [String] + def self.inspect_array(array, options = {}) + colorize('[', options[:color] ? :green : nil) << + array.to_ary.map { |element| inspect(element, options) }.join(' ') << + colorize(']', options[:color] ? :green : nil) + end + + ## + # @param [String, #to_str] string + # @param [Hash{Symbol => Object}] options + # @return [String] + def self.inspect_string(string, options = {}) + colorize('"', options[:color] ? :red : nil) << + colorize(string.to_str.inspect[1...-1], options[:color] ? :cyan : nil) << + colorize('"', options[:color] ? :red : nil) + end + + ## + # @param [RDF::URI, #to_uri] uri + # @param [Hash{Symbol => Object}] options + # @return [String] + def self.inspect_reference(uri, options = {}) + colorize('<', options[:color] ? :red : nil) << + colorize(uri.to_uri.to_s, options[:color] ? :cyan : nil) << + colorize('>', options[:color] ? :red : nil) + end + end # module Color +end; end # module Trith::Shell diff --git a/lib/trith/version.rb b/lib/trith/version.rb new file mode 100644 index 0000000..50ca6ec --- /dev/null +++ b/lib/trith/version.rb @@ -0,0 +1,23 @@ +module Trith + module VERSION + MAJOR = 0 + MINOR = 0 + TINY = 2 + EXTRA = nil + + STRING = [MAJOR, MINOR, TINY].join('.') + STRING << ".#{EXTRA}" if EXTRA + + ## + # @return [String] + def self.to_s() STRING end + + ## + # @return [String] + def self.to_str() STRING end + + ## + # @return [Array(Integer, Integer, Integer)] + def self.to_a() [MAJOR, MINOR, TINY] end + end +end diff --git a/spec/cache_spec.rb b/spec/cache_spec.rb new file mode 100644 index 0000000..cdf50d5 --- /dev/null +++ b/spec/cache_spec.rb @@ -0,0 +1,43 @@ +require File.join(File.dirname(__FILE__), 'spec_helper') + +describe Trith::Cache do + before :each do + @cache = Trith::Cache.load(File.join(File.dirname(__FILE__), '..', 'etc', 'cache.nt')) + end + + it "should be an RDF repository" do + @cache.should be_an(RDF::Repository) + end + + it "should know whether a given function is cached" do + @cache.should respond_to(:has_function?) + @cache.should have_function(Trith::Function.new("http://trith.org/core/dup")) + @cache.should have_function(RDF::URI("http://trith.org/core/dup")) + @cache.should_not have_function(Trith::Function.new) + @cache.should_not have_function(RDF::URI("http://example.org/myfunction")) + @cache.should_not have_function(RDF::Node.new) + end + + it "should know whether a function with a given label is cached" do + @cache.should respond_to(:has_label?) + @cache.should have_label(:boolean?) + @cache.should_not have_label(:foobar) + end + + it "should enumerate the cached functions" do + @cache.should respond_to(:each_function) + @cache.each_function do |function| + function.should be_a(Trith::Function) + end + @cache.each_function.should be_a(RDF::Enumerator) + end + + it "should find cached functions by their labels" do + @cache.should respond_to(:find_functions) + @cache.find_functions do |function| + function.should be_a(Trith::Function) + end + @cache.find_functions.should be_a(RDF::Enumerator) + @cache.find_functions(:label => :dup).to_a.size.should == 1 + end +end diff --git a/spec/compiler_spec.rb b/spec/compiler_spec.rb new file mode 100644 index 0000000..39f053a --- /dev/null +++ b/spec/compiler_spec.rb @@ -0,0 +1,5 @@ +require File.join(File.dirname(__FILE__), 'spec_helper') + +describe Trith::Compiler do + # TODO +end diff --git a/spec/function_spec.rb b/spec/function_spec.rb new file mode 100644 index 0000000..ef8dc9d --- /dev/null +++ b/spec/function_spec.rb @@ -0,0 +1,12 @@ +require File.join(File.dirname(__FILE__), 'spec_helper') + +describe Trith::Function do + before :each do + @fn = Trith::Function.new + end + + it "should have an RDF representation" do + @fn.should respond_to(:to_rdf) + @fn.to_rdf.should be_an(RDF::Graph) + end +end diff --git a/spec/library_spec.rb b/spec/library_spec.rb new file mode 100644 index 0000000..0d58421 --- /dev/null +++ b/spec/library_spec.rb @@ -0,0 +1,91 @@ +require 'trith' + +include Trith + +require 'trith/sys/posix' +describe System::POSIX do + before(:each) do + @machine = Machine.new { import Trith::System::POSIX } + end + + context "Time operations" do + it "should support the :time operation" do + @machine.should respond_to(:time) + @machine.execute { time }.pop.should be_a(Integer) + @machine.stack.should be_empty + end + end + + context "File operations" do + it "should support the :stdin operation" do + @machine.should respond_to(:stdin) + @machine.execute { stdin }.pop.should == $stdin + @machine.stack.should be_empty + end + + it "should support the :stdout operation" do + @machine.should respond_to(:stdout) + @machine.execute { stdout }.pop.should == $stdout + @machine.stack.should be_empty + end + + it "should support the :stderr operation" do + @machine.should respond_to(:stderr) + @machine.execute { stderr }.pop.should == $stderr + @machine.stack.should be_empty + end + + it "should support the :fileno operation" do + @machine.should respond_to(:fileno) + @machine.execute([$stderr]) { fileno }.pop.should == 2 + @machine.stack.should be_empty + end + + it "should support the :fopen operation" + it "should support the :fseek operation" + + it "should support the :fread operation" do + @machine.should respond_to(:fwrite) + @machine.execute([__FILE__, 'r']) { fopen }.peek.should be_a(IO) + @machine.execute(["require 'trith'".length]) { fread }.pop.should == "require 'trith'" + @machine.stack.should be_empty + end + + it "should support the :fwrite operation" do + buffer = StringIO.new + @machine.should respond_to(:fwrite) + @machine.execute([buffer, "Hello, world!\n"]) { fwrite }.pop.should be_an(Integer) + buffer.string.should == "Hello, world!\n" + @machine.stack.should be_empty + end + + it "should support the :feof operation" + it "should support the :fflush operation" + it "should support the :fclose operation" + it "should support the :fsync operation" + it "should support the :popen operation" + it "should support the :pclose operation" + end +end + +require 'trith/lib/openssl' +describe Library::OpenSSL do + before(:each) do + @machine = Machine.new { import Trith::Library::OpenSSL } + end + + context "Random number generator" do + it "should support the :rand_bytes operation" + end + + context "Message digest algorithms" do + it "should support the :md4 operation" + it "should support the :md5 operation" + it "should support the :ripemd160 operation" + it "should support the :sha1 operation" + it "should support the :sha224 operation" + it "should support the :sha256 operation" + it "should support the :sha384 operation" + it "should support the :sha512 operation" + end +end diff --git a/spec/machine_spec.rb b/spec/machine_spec.rb new file mode 100644 index 0000000..1e22aec --- /dev/null +++ b/spec/machine_spec.rb @@ -0,0 +1,854 @@ +require File.join(File.dirname(__FILE__), 'spec_helper') + +describe Trith::Machine do + context "Execution operators" do + it "should implement the :reset operator" do + Machine.new.should respond_to(:reset) + Machine.new([6, 7]).execute { reset }.to_a.should == [] + end + + it "should implement the :halt operator" do + Machine.new.should respond_to(:halt) + Machine.run { push(42).halt }.should == 42 + end + + it "should implement the :nop operator" do + Machine.new.should respond_to(:nop, :',', :';') + Machine.run { push(42).nop }.should == 42 + end + + it "should implement the :quote operator" do + Machine.new.should respond_to(:quote, :'\\', :"'") + # TODO + end + + it "should implement the :call operator" do + Machine.new.should respond_to(:call) + # TODO + end + + it "should implement the :times operator" do + Machine.new.should respond_to(:times) + # TODO + end + + it "should implement the :twice operator" do + Machine.new.should respond_to(:twice, :'2x') + # TODO + end + + it "should implement the :thrice operator" do + Machine.new.should respond_to(:thrice, :'3x') + # TODO + end + + it "should implement the :loop operator" do + Machine.new.should respond_to(:loop) + # TODO + end + + it "should implement the :while operator" do + Machine.new.should respond_to(:while) + # TODO + end + + it "should implement the :until operator" do + Machine.new.should respond_to(:until) + # TODO + end + + it "should implement the :branch operator" do + Machine.new.should respond_to(:branch, :if) + # TODO + end + + it "should implement the :when operator" do + Machine.new.should respond_to(:when) + # TODO + end + + it "should implement the :unless operator" do + Machine.new.should respond_to(:unless) + # TODO + end + end + + context "Stack shufflers" do + it "should implement the :clear operator" do + Machine.new.should respond_to(:clear) + Machine.new([6, 7]).execute { clear }.stack.should == [] + end + + it "should implement the :depth operator" do + Machine.new.should respond_to(:depth) + # TODO + end + + it "should implement the :stack operator" do + Machine.new.should respond_to(:stack) + # TODO + end + + it "should implement the :unstack operator" do + Machine.new.should respond_to(:unstack) + # TODO + end + + it "should implement the :drop operator" do + Machine.new.should respond_to(:drop) + Machine.new([6, 7]).execute { drop }.stack.should == [6] + end + + it "should implement the :drop2 operator" do + Machine.new.should respond_to(:drop2, :'2drop') + # TODO + end + + it "should implement the :drop3 operator" do + Machine.new.should respond_to(:drop3, :'3drop') + # TODO + end + + it "should implement the :dup operator" do + Machine.new.should respond_to(:dup) + Machine.new([6, 7]).execute { dup }.stack.should == [6, 7, 7] + end + + it "should implement the :dup2 operator" do + Machine.new.should respond_to(:dup2, :'2dup') + # TODO + end + + it "should implement the :dup3 operator" do + Machine.new.should respond_to(:dup3, :'3dup') + # TODO + end + + it "should implement the :swap operator" do + Machine.new.should respond_to(:swap) + Machine.new([6, 7]).execute { swap }.stack.should == [7, 6] + end + + it "should implement the :nip operator" do + Machine.new.should respond_to(:nip) + # TODO + end + + it "should implement the :nip2 operator" do + Machine.new.should respond_to(:nip2, :'2nip') + # TODO + end + + it "should implement the :over operator" do + Machine.new.should respond_to(:over) + # TODO + end + + it "should implement the :pick operator" do + Machine.new.should respond_to(:pick) + # TODO + end + + it "should implement the :rot operator" do + Machine.new.should respond_to(:rot) + # TODO + end + end + + context "Stack combinators" do + it "should implement the :dip operator" do + Machine.new.should respond_to(:dip) + Machine.new([6, 7, 1, [:mul]]).execute { dip }.stack.should == [42, 1] + end + end + + context "Arithmetic operators" do + it "should implement the :abs operator" do + Machine.new.should respond_to(:abs) + Machine.run { push(1).abs }.should == 1 + Machine.run { push(-1).abs }.should == 1 + end + + it "should implement the :neg operator" do + Machine.new.should respond_to(:neg) + Machine.run { push(6).neg }.should == -6 + end + + it "should implement the :inc operator" do + Machine.new.should respond_to(:inc) + Machine.run { push(6).inc }.should == 7 + end + + it "should implement the :dec operator" do + Machine.new.should respond_to(:dec) + Machine.run { push(6).dec }.should == 5 + end + + it "should implement the :add operator" do + Machine.new.should respond_to(:add, :+) + Machine.run { push(6).push(7).add }.should == 13 + end + + it "should implement the :sub operator" do + Machine.new.should respond_to(:sub, :-) + Machine.run { push(6).push(7).sub }.should == -1 + end + + it "should implement the :mul operator" do + Machine.new.should respond_to(:mul, :*) + Machine.run { push(6).push(7).mul }.should == 42 + end + + it "should implement the :div operator" do + Machine.new.should respond_to(:div, :'/') + Machine.run { push(42).push(7).div }.should == 6 + end + + it "should implement the :rem operator" do + Machine.new.should respond_to(:rem) + # TODO + end + + it "should implement the :mod operator" do + Machine.new.should respond_to(:mod) + # TODO + end + + it "should implement the :pow operator" do + Machine.new.should respond_to(:pow) + # TODO + end + end + + context "Bitwise operators" do + it "should implement the :not operator" do + Machine.new.should respond_to(:not) + # TODO + end + + it "should implement the :and operator" do + Machine.new.should respond_to(:and) + # TODO + end + + it "should implement the :or operator" do + Machine.new.should respond_to(:or) + # TODO + end + + it "should implement the :xor operator" do + Machine.new.should respond_to(:xor) + # TODO + end + + it "should implement the :shl operator" do + Machine.new.should respond_to(:shl) + # TODO + end + + it "should implement the :shr operator" do + Machine.new.should respond_to(:shr) + # TODO + end + end + + context "Boolean predicates" do + it "should implement the :nilp operator" do + Machine.new.should respond_to(:nilp, :nil?) + # TODO + end + + it "should implement the :boolp operator" do + Machine.new.should respond_to(:boolp, :bool?) + # TODO + end + + it "should implement the :falsep operator" do + Machine.new.should respond_to(:falsep, :false?) + # TODO + end + + it "should implement the :truep operator" do + Machine.new.should respond_to(:truep, :true?) + # TODO + end + + it "should implement the :notp operator" do + Machine.new.should respond_to(:notp, :not?) + # TODO + end + + it "should implement the :andp operator" do + Machine.new.should respond_to(:andp, :and?) + # TODO + end + + it "should implement the :orp operator" do + Machine.new.should respond_to(:orp, :or?) + # TODO + end + + it "should implement the :xorp operator" do + Machine.new.should respond_to(:xorp, :xor?) + # TODO + end + end + + context "Boolean constructors" do + it "should implement the :nil operator" do + Machine.new.should respond_to(:nil) + # TODO + end + + it "should implement the :bool operator" do + Machine.new.should respond_to(:bool) + # TODO + end + + it "should implement the :false operator" do + Machine.new.should respond_to(:false) + # TODO + end + + it "should implement the :true operator" do + Machine.new.should respond_to(:true) + # TODO + end + end + + context "Comparison operators" do + it "should implement the :cmp operator" do + Machine.new.should respond_to(:cmp, :<=>) + # TODO + end + + it "should implement the :eq operator" do + Machine.new.should respond_to(:eq, :'=') + # TODO + end + + it "should implement the :ne operator" do + Machine.new.should respond_to(:ne, :'!=') + # TODO + end + + it "should implement the :lt operator" do + Machine.new.should respond_to(:lt, :<) + # TODO + end + + it "should implement the :le operator" do + Machine.new.should respond_to(:le, :<=) + # TODO + end + + it "should implement the :gt operator" do + Machine.new.should respond_to(:gt, :>) + # TODO + end + + it "should implement the :ge operator" do + Machine.new.should respond_to(:ge, :>=) + # TODO + end + + it "should implement the :min operator" do + Machine.new.should respond_to(:min) + # TODO + end + + it "should implement the :max operator" do + Machine.new.should respond_to(:max) + # TODO + end + end + + context "Numeric predicates" do + it "should implement the :nump operator" do + Machine.new.should respond_to(:nump, :num?) + # TODO + end + + it "should implement the :intp operator" do + Machine.new.should respond_to(:intp, :int?) + # TODO + end + + it "should implement the :infp operator" do + Machine.new.should respond_to(:infp, :inf?) + # TODO + end + + it "should implement the :zerop operator" do + Machine.new.should respond_to(:zerop, :zero?) + # TODO + end + + it "should implement the :onep operator" do + Machine.new.should respond_to(:onep, :one?) + # TODO + end + + it "should implement the :negp operator" do + Machine.new.should respond_to(:negp, :neg?) + # TODO + end + + it "should implement the :posp operator" do + Machine.new.should respond_to(:posp, :pos?) + # TODO + end + + it "should implement the :oddp operator" do + Machine.new.should respond_to(:oddp, :odd?) + # TODO + end + + it "should implement the :evenp operator" do + Machine.new.should respond_to(:evenp, :even?) + # TODO + end + end + + context "Numeric constructors" do + it "should implement the :num operator" do + Machine.new.should respond_to(:num) + # TODO + end + + it "should implement the :int operator" do + Machine.new.should respond_to(:int) + # TODO + end + + it "should implement the :inf operator" do + Machine.new.should respond_to(:inf) + # TODO + end + end + + context "Math constants" do + it "should implement the :pi operator" do + Machine.new.should respond_to(:pi) + # TODO + end + end + + context "Math operators" do + it "should implement the :ceil operator" do + Machine.new.should respond_to(:ceil) + # TODO + end + + it "should implement the :floor operator" do + Machine.new.should respond_to(:floor) + # TODO + end + + it "should implement the :round operator" do + Machine.new.should respond_to(:round) + # TODO + end + + it "should implement the :sq operator" do + Machine.new.should respond_to(:sq) + # TODO + end + + it "should implement the :sqrt operator" do + Machine.new.should respond_to(:sqrt) + # TODO + end + + it "should implement the :cb operator" do + Machine.new.should respond_to(:cb) + # TODO + end + + it "should implement the :cbrt operator" do + Machine.new.should respond_to(:cbrt) + # TODO + end + + it "should implement the :exp operator" do + Machine.new.should respond_to(:exp) + # TODO + end + + it "should implement the :log operator" do + Machine.new.should respond_to(:log) + # TODO + end + + it "should implement the :log2 operator" do + Machine.new.should respond_to(:log2) + # TODO + end + + it "should implement the :log10 operator" do + Machine.new.should respond_to(:log10) + # TODO + end + + it "should implement the :hypot operator" do + Machine.new.should respond_to(:hypot) + # TODO + end + + it "should implement the :cos operator" do + Machine.new.should respond_to(:cos) + # TODO + end + + it "should implement the :cosh operator" do + Machine.new.should respond_to(:cosh) + # TODO + end + + it "should implement the :sin operator" do + Machine.new.should respond_to(:sin) + # TODO + end + + it "should implement the :sinh operator" do + Machine.new.should respond_to(:sinh) + # TODO + end + + it "should implement the :tan operator" do + Machine.new.should respond_to(:tan) + # TODO + end + + it "should implement the :tanh operator" do + Machine.new.should respond_to(:tanh) + # TODO + end + + it "should implement the :acos operator" do + Machine.new.should respond_to(:acos) + # TODO + end + + it "should implement the :acosh operator" do + Machine.new.should respond_to(:acosh) + # TODO + end + + it "should implement the :asin operator" do + Machine.new.should respond_to(:asin) + # TODO + end + + it "should implement the :asinh operator" do + Machine.new.should respond_to(:asinh) + # TODO + end + + it "should implement the :atan operator" do + Machine.new.should respond_to(:atan) + # TODO + end + + it "should implement the :atan2 operator" do + Machine.new.should respond_to(:atan2) + # TODO + end + + it "should implement the :atanh operator" do + Machine.new.should respond_to(:atanh) + # TODO + end + end + + context "Sequence predicates" do + it "should implement the :seqp operator" do + Machine.new.should respond_to(:seqp) + # TODO + end + + it "should implement the :emptyp operator" do + Machine.new.should respond_to(:emptyp) + # TODO + end + + it "should implement the :anyp operator" do + Machine.new.should respond_to(:anyp) + # TODO + end + + it "should implement the :allp operator" do + Machine.new.should respond_to(:allp) + # TODO + end + end + + context "Sequence constructors" do + it "should implement the :seq operator" do + Machine.new.should respond_to(:seq) + # TODO + end + + it "should implement the :cons operator" do + Machine.new.should respond_to(:cons) + # TODO + end + + it "should implement the :list operator" do + Machine.new.should respond_to(:list) + # TODO + end + + it "should implement the :iota operator" do + Machine.new.should respond_to(:iota) + # TODO + end + + it "should implement the :range operator" do + Machine.new.should respond_to(:range) + # TODO + end + + it "should implement the :repeat operator" do + Machine.new.should respond_to(:repeat) + # TODO + end + + it "should implement the :cycle operator" do + Machine.new.should respond_to(:cycle) + # TODO + end + end + + context "Sequence accessors" do + it "should implement the :length operator" do + Machine.new.should respond_to(:length) + # TODO + end + + it "should implement the :rest operator" do + Machine.new.should respond_to(:rest) + # TODO + end + + it "should implement the :first operator" do + Machine.new.should respond_to(:first) + # TODO + end + + it "should implement the :second operator" do + Machine.new.should respond_to(:second) + # TODO + end + + it "should implement the :third operator" do + Machine.new.should respond_to(:third) + # TODO + end + + it "should implement the :fourth operator" do + Machine.new.should respond_to(:fourth) + # TODO + end + + it "should implement the :fifth operator" do + Machine.new.should respond_to(:fifth) + # TODO + end + + it "should implement the :sixth operator" do + Machine.new.should respond_to(:sixth) + # TODO + end + + it "should implement the :seventh operator" do + Machine.new.should respond_to(:seventh) + # TODO + end + + it "should implement the :eighth operator" do + Machine.new.should respond_to(:eighth) + # TODO + end + + it "should implement the :ninth operator" do + Machine.new.should respond_to(:ninth) + # TODO + end + + it "should implement the :tenth operator" do + Machine.new.should respond_to(:tenth) + # TODO + end + + it "should implement the :nth operator" do + Machine.new.should respond_to(:nth) + # TODO + end + + it "should implement the :last operator" do + Machine.new.should respond_to(:last) + # TODO + end + end + + context "Sequence operators" do + it "should implement the :subseq operator" do + Machine.new.should respond_to(:subseq) + # TODO + end + + it "should implement the :concat operator" do + Machine.new.should respond_to(:concat) + # TODO + end + + it "should implement the :uniq operator" do + Machine.new.should respond_to(:uniq) + # TODO + end + + it "should implement the :reverse operator" do + Machine.new.should respond_to(:reverse) + # TODO + end + + it "should implement the :sort operator" do + Machine.new.should respond_to(:sort) + # TODO + end + + it "should implement the :sortby operator" do + Machine.new.should respond_to(:sortby) + # TODO + end + + it "should implement the :flatten operator" do + Machine.new.should respond_to(:flatten) + # TODO + end + + it "should implement the :zip operator" do + Machine.new.should respond_to(:zip) + # TODO + end + + it "should implement the :zip1 operator" do + Machine.new.should respond_to(:zip1) + # TODO + end + + it "should implement the :zip2 operator" do + Machine.new.should respond_to(:zip2) + # TODO + end + + it "should implement the :zip3 operator" do + Machine.new.should respond_to(:zip3) + # TODO + end + + it "should implement the :zip4 operator" do + Machine.new.should respond_to(:zip4) + # TODO + end + + it "should implement the :unzip operator" do + Machine.new.should respond_to(:unzip) + # TODO + end + + it "should implement the :unzip1 operator" do + Machine.new.should respond_to(:unzip1) + # TODO + end + + it "should implement the :unzip2 operator" do + Machine.new.should respond_to(:unzip2) + # TODO + end + + it "should implement the :unzip3 operator" do + Machine.new.should respond_to(:unzip3) + # TODO + end + + it "should implement the :unzip4 operator" do + Machine.new.should respond_to(:unzip4) + # TODO + end + end + + context "Sequence combinators" do + it "should implement the :each operator" do + Machine.new.should respond_to(:each) + # TODO + end + + it "should implement the :map operator" do + Machine.new.should respond_to(:map) + Machine.new([[1, 2, 3, 4, 5], [:dup, :mul]]).execute { map }.stack.should == [[1, 4, 9, 16, 25]] + end + + it "should implement the :count operator" do + Machine.new.should respond_to(:count) + # TODO + end + + it "should implement the :filter operator" do + Machine.new.should respond_to(:filter) + Machine.new([[1, 2, 3, 4, 5], [2, :mod, 0, :eq]]).execute { filter }.stack.should == [[2, 4]] + end + + it "should implement the :remove operator" do + Machine.new.should respond_to(:remove) + # TODO + end + + it "should implement the :foldl operator" do + Machine.new.should respond_to(:foldl) + Machine.new([[1, 2, 3, 4, 5], 0, [:add]]).execute { foldl }.stack.should == [15] + Machine.new([[], -1, [:add]]).execute { foldl }.stack.should == [-1] + Machine.new([[2, 5, 3], 0, [:add]]).execute { foldl }.stack.should == [10] + Machine.new([[2, 5, 3], 0, [:dup, :mul, :add]]).execute { foldl }.stack.should == [38] + end + + it "should implement the :foldr operator" do + Machine.new.should respond_to(:foldr) + # TODO + end + end + + context "Textual predicates" do + it "should implement the :chrp operator" do + Machine.new.should respond_to(:chrp, :chr?) + # TODO + end + + # TODO + end + + context "Textual constructors" do + it "should implement the :chr operator" do + Machine.new.should respond_to(:chr) + Machine.run([97]) { chr }.should == "a" + Machine.run([960]) { chr }.should == "\u03c0" # PI + end + + # TODO + end + + context "Textual operators" do + it "should implement the :size operator" do + Machine.new.should respond_to(:size) + # TODO + end + end + + context "Output operators" do + it "should implement the :print operator" do + Machine.new.should respond_to(:print) + # TODO + end + end +end diff --git a/spec/optimizer_spec.rb b/spec/optimizer_spec.rb new file mode 100644 index 0000000..40af81e --- /dev/null +++ b/spec/optimizer_spec.rb @@ -0,0 +1,227 @@ +require 'trith' + +include Trith + +describe Optimizer do + describe Reader::LiteralCanonicalization do + it "should canonicalize :nil instructions" do + optimized[:nil].should == [nil] + end + + it "should canonicalize :true and :false instructions" do + optimized[:false].should == [false] + optimized[:true].should == [true] + end + end + + describe Optimizer::EmptyQuotationElimination do + it "should replace empty quotations with the :nop instruction" do + optimized[[]].should == [:nop] + optimized[true, [], [], :branch].should == [true, :nop, :nop, :branch] + end + end + + describe Optimizer::QuotationFactoring do + it "should convert quotations into gensym definitions" do + optimized[[]].first.should be_instance_of(Symbol) + optimized[[:+], :call].first.should be_instance_of(Symbol) + end + end + + describe Optimizer::TailRecursionAnalysis do + it "should replace tail recursion with the :recur pseudo-instruction" do + optimized[1, :+, :input].should == [1, :+, :recur] + end + end + + describe Optimizer::ConstantArithmeticFolding do + it "should evaluate constant integer negation" do + optimized[-1, :neg].should == [1] + optimized[ 0, :neg].should == [0] + optimized[ 1, :neg].should == [-1] + end + + it "should evaluate constant integer increments" do + optimized[-1, :inc].should == [0] + optimized[ 0, :inc].should == [1] + optimized[ 1, :inc].should == [2] + end + + it "should evaluate constant integer decrements" do + optimized[-1, :dec].should == [-2] + optimized[ 0, :dec].should == [-1] + optimized[ 1, :dec].should == [0] + end + + it "should evaluate constant integer addition" do + optimized[1, 2, :+].should == [3] + end + + it "should evaluate constant integer subtraction" do + optimized[4, 5, :-].should == [-1] + end + + it "should evaluate constant integer multiplication" do + optimized[6, 7, :*].should == [42] + end + + it "should evaluate constant integer division when the remainder is zero" do + optimized[8, 1, :'/'].should == [8] + optimized[8, 4, :'/'].should == [2] + end + + it "should not evaluate constant integer division when the remainder is not zero" do + optimized[8, 3, :'/'].should == [8, 3, :'/'] + end + + it "should evaluate constant integer modulo and remainder operations" do + optimized[ 13, 4, :mod].should == [1] + optimized[ 13, 4, :rem].should == [1] + optimized[ 13, -4, :mod].should == [-3] + optimized[ 13, -4, :rem].should == [1] + optimized[-13, 4, :mod].should == [3] + optimized[-13, 4, :rem].should == [-1] + optimized[-13, -4, :mod].should == [-1] + optimized[-13, -4, :rem].should == [-1] + end + + it "should evaluate constant integer exponentiation" do + optimized[2, 0, :pow].should == [1] + optimized[2, 1, :pow].should == [2] + optimized[2, 4, :pow].should == [16] + end + + it "should evaluate constant integer absolute values" do + optimized[ 0, :abs].should == [0] + optimized[ 1, :abs].should == [1] + optimized[-1, :abs].should == [1] + end + + it "should evaluate constant integer maxima and minima" do + optimized[ 0, 1, :max].should == [1] + optimized[ 1, 1, :max].should == [1] + optimized[-1, 1, :max].should == [1] + + optimized[ 0, 1, :min].should == [0] + optimized[ 1, 1, :min].should == [1] + optimized[-1, 1, :min].should == [-1] + end + end + + describe Optimizer::ConstantBitwiseFolding do + it "should evaluate constant bitwise operations" + end + + describe Optimizer::ConstantComparisonFolding do + it "should evaluate constant comparison operations" do + optimized[-1, 0, :cmp].should == [-1] + optimized[ 0, 0, :cmp].should == [0] + optimized[ 1, 0, :cmp].should == [1] + + optimized[-1, 0, :eq].should == [false] + optimized[ 0, 0, :eq].should == [true] + optimized[ 1, 0, :eq].should == [false] + + optimized[-1, 0, :ne].should == [true] + optimized[ 0, 0, :ne].should == [false] + optimized[ 1, 0, :ne].should == [true] + + %w(== < <= > >=).map(&:to_sym).each do |op| # FIXME + optimized[-1, 0, op].should == [-1.send(op, 0)] + optimized[ 0, 0, op].should == [ 0.send(op, 0)] + optimized[ 1, 0, op].should == [ 1.send(op, 0)] + end + end + end + + describe Optimizer::ConstantBranchFolding do + it "should evaluate constant branch operations" do + optimized[true, :a, :b, :branch].should == [:a] + optimized[:true, :a, :b, :branch].should == [:a] + optimized[false, :a, :b, :branch].should == [:b] + optimized[:false, :a, :b, :branch].should == [:b] + + optimized[:a, :b, :c, :branch].should == [:a, :b, :c, :branch] + end + end + + describe Optimizer::AlgebraicSimplification do + it "should simplify constant integer addition" do + optimized[:x, 0, :+].should == [:x] + optimized[0, :x, :+].should == [:x] + end + + it "should simplify constant integer subtraction" do + optimized[:x, 0, :-].should == [:x] + optimized[:x, :x, :-].should == [0] + end + + it "should simplify constant integer multiplication" do + optimized[:x, 0, :*].should == [0] + optimized[0, :x, :*].should == [0] + optimized[:x, 1, :*].should == [:x] + optimized[1, :x, :*].should == [:x] + end + + it "should simplify constant integer division" do + optimized[:x, 1, :'/'].should == [:x] + optimized[:x, :x, :'/'].should == [1] + end + + it "should simplify constant integer exponentiation" do + optimized[:x, 0, :pow].should == [1] + optimized[:x, 1, :pow].should == [:x] + end + end + + describe Optimizer::StrengthReduction do + it "should reduce constant integer addition" do + optimized[:x, 1, :+].should == [:x, :inc] + optimized[1, :x, :+].should == [:x, :inc] + end + + it "should reduce constant integer subtraction" do + optimized[:x, 1, :-].should == [:x, :dec] + optimized[:x, :x, :-].should == [:x, :drop, 0] + optimized[0, :x, :-].should == [:x, :neg] + optimized[1, :x, :-].should == [:x, :neg, :inc] + end + + it "should reduce constant integer multiplication" do + optimized[:x, 2, :*].should == [:x, :dup, :+] + end + + it "should reduce constant integer division" do + optimized[:x, :x, :'/'].should == [:x, :drop, 1] + end + + it "should reduce constant integer exponentiation" do + optimized[:x, 2, :pow].should == [:x, :dup, :*] + optimized[:x, 3, :pow].should == [:x, :dup, :dup, :*, :*] + end + end + + describe Optimizer::RedundantCodeElimination do + it "should eliminate redundant :dup/:drop instruction sequences" do + optimized[:dup3, :drop3].should == [] + optimized[:dup2, :drop2].should == [] + optimized[:dup2, :drop, :drop].should == [] + optimized[:dup, :drop].should == [] + optimized[1, :dup, 2, :swap, :drop].should == [1, 2] + end + end + + def optimized + proxy = OpenStruct.new(:example => self) + class << proxy + def [](*instructions) + example.optimize(*instructions) + end + end + proxy + end + + def optimize(*input) + described_class.transform(Program.new(:input => input)).definitions[:input] + end +end diff --git a/spec/program_spec.rb b/spec/program_spec.rb new file mode 100644 index 0000000..fa87127 --- /dev/null +++ b/spec/program_spec.rb @@ -0,0 +1,7 @@ +require 'trith' + +include Trith + +describe Program do + # TODO +end diff --git a/spec/reader_spec.rb b/spec/reader_spec.rb new file mode 100644 index 0000000..97420a6 --- /dev/null +++ b/spec/reader_spec.rb @@ -0,0 +1,35 @@ +require File.join(File.dirname(__FILE__), 'spec_helper') + +describe Trith::Reader do + it "should not be instantiable" do + lambda { Trith::Reader.new }.should raise_error(NoMethodError) + end + + it "should support reading URLs" do + Trith::Reader.should respond_to(:read_url) + # TODO + end + + it "should support reading files" do + Trith::Reader.should respond_to(:read_files) + Trith::Reader.should respond_to(:read_file) + # TODO + end + + it "should support reading IO objects" do + Trith::Reader.should respond_to(:read) + # TODO + end + + it "should support reading StringIO objects" do + Trith::Reader.should respond_to(:read) + lambda { Trith::Reader.read(StringIO.new('123')) }.should_not raise_error + # TODO + end + + it "should support reading strings" do + Trith::Reader.should respond_to(:read) + lambda { Trith::Reader.read('123') }.should_not raise_error + # TODO + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..1cc6060 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,2 @@ +require 'trith' +include Trith diff --git a/src/java/trith/.gitignore b/src/java/trith/.gitignore new file mode 100644 index 0000000..6b468b6 --- /dev/null +++ b/src/java/trith/.gitignore @@ -0,0 +1 @@ +*.class diff --git a/src/java/trith/core/booleanp.java b/src/java/trith/core/booleanp.java new file mode 100644 index 0000000..a544ee2 --- /dev/null +++ b/src/java/trith/core/booleanp.java @@ -0,0 +1,14 @@ +package trith.core; +import trith.lang.*; + +/** + * @author Arto Bendiken + * @see http://trith.org/core/booleanp + */ +public class booleanp extends UnaryOperator<Boolean, Object> { + public static final String URL = "http://trith.org/core/booleanp"; + + public Boolean execute(Object x) { + return Boolean.valueOf(x instanceof Boolean); + } +} diff --git a/src/java/trith/core/dup.java b/src/java/trith/core/dup.java new file mode 100644 index 0000000..7a1a48f --- /dev/null +++ b/src/java/trith/core/dup.java @@ -0,0 +1,14 @@ +package trith.core; +import trith.lang.*; + +/** + * @author Arto Bendiken + * @see http://trith.org/core/dup + */ +public class dup implements Operator { + public static final String URL = "http://trith.org/core/dup"; + + public void execute(Machine machine) { + machine.push(machine.peek()); + } +} diff --git a/src/java/trith/core/falsep.java b/src/java/trith/core/falsep.java new file mode 100644 index 0000000..4a93352 --- /dev/null +++ b/src/java/trith/core/falsep.java @@ -0,0 +1,14 @@ +package trith.core; +import trith.lang.*; + +/** + * @author Arto Bendiken + * @see http://trith.org/core/falsep + */ +public class falsep extends UnaryOperator<Boolean, Object> { + public static final String URL = "http://trith.org/core/falsep"; + + public Boolean execute(Object x) { + return Boolean.valueOf((x instanceof Boolean) && !((Boolean)x).booleanValue()); + } +} diff --git a/src/java/trith/core/nil.java b/src/java/trith/core/nil.java new file mode 100644 index 0000000..95a9de8 --- /dev/null +++ b/src/java/trith/core/nil.java @@ -0,0 +1,14 @@ +package trith.core; +import trith.lang.*; + +/** + * @author Arto Bendiken + * @see http://trith.org/core/nil + */ +public class nil extends NullaryOperator<Object> { + public static final String URL = "http://trith.org/core/nil"; + + public Object execute() { + return null; + } +} diff --git a/src/java/trith/core/nilp.java b/src/java/trith/core/nilp.java new file mode 100644 index 0000000..5c89929 --- /dev/null +++ b/src/java/trith/core/nilp.java @@ -0,0 +1,14 @@ +package trith.core; +import trith.lang.*; + +/** + * @author Arto Bendiken + * @see http://trith.org/core/nilp + */ +public class nilp extends UnaryOperator<Boolean, Object> { + public static final String URL = "http://trith.org/core/nilp"; + + public Boolean execute(Object x) { + return Boolean.valueOf(x == null); + } +} diff --git a/src/java/trith/core/nump.java b/src/java/trith/core/nump.java new file mode 100644 index 0000000..f7e747b --- /dev/null +++ b/src/java/trith/core/nump.java @@ -0,0 +1,14 @@ +package trith.core; +import trith.lang.*; + +/** + * @author Arto Bendiken + * @see http://trith.org/core/nump + */ +public class nump extends UnaryOperator<Boolean, Object> { + public static final String URL = "http://trith.org/core/nump"; + + public Boolean execute(Object n) { + return Boolean.valueOf(n instanceof java.lang.Number); + } +} diff --git a/src/java/trith/core/stringp.java b/src/java/trith/core/stringp.java new file mode 100644 index 0000000..966c2a6 --- /dev/null +++ b/src/java/trith/core/stringp.java @@ -0,0 +1,14 @@ +package trith.core; +import trith.lang.*; + +/** + * @author Arto Bendiken + * @see http://trith.org/core/stringp + */ +public class stringp extends UnaryOperator<Boolean, Object> { + public static final String URL = "http://trith.org/core/stringp"; + + public Boolean execute(Object x) { + return Boolean.valueOf(x instanceof String); + } +} diff --git a/src/java/trith/core/truep.java b/src/java/trith/core/truep.java new file mode 100644 index 0000000..447c989 --- /dev/null +++ b/src/java/trith/core/truep.java @@ -0,0 +1,14 @@ +package trith.core; +import trith.lang.*; + +/** + * @author Arto Bendiken + * @see http://trith.org/core/truep + */ +public class truep extends UnaryOperator<Boolean, Object> { + public static final String URL = "http://trith.org/core/truep"; + + public Boolean execute(Object x) { + return Boolean.valueOf((x instanceof Boolean) && ((Boolean)x).booleanValue()); + } +} diff --git a/src/java/trith/core/zerop.java b/src/java/trith/core/zerop.java new file mode 100644 index 0000000..1bcbbf8 --- /dev/null +++ b/src/java/trith/core/zerop.java @@ -0,0 +1,15 @@ +package trith.core; +import trith.lang.*; +import java.math.BigDecimal; + +/** + * @author Arto Bendiken + * @see http://trith.org/core/zerop + */ +public class zerop extends UnaryOperator<Boolean, BigDecimal> { + public static final String URL = "http://trith.org/core/zerop"; + + public Boolean execute(BigDecimal n) { + return Boolean.valueOf(n.compareTo(BigDecimal.ZERO) == 0); + } +} diff --git a/src/java/trith/lang/AbstractMachine.java b/src/java/trith/lang/AbstractMachine.java new file mode 100644 index 0000000..2a658b6 --- /dev/null +++ b/src/java/trith/lang/AbstractMachine.java @@ -0,0 +1,155 @@ +package trith.lang; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.Stack; +import java.util.EmptyStackException; + +/** + * @author Arto Bendiken + */ +public abstract class AbstractMachine implements Machine { + public final Stack<Future> stack = new Stack<Future>(); + public final Stack<Future> queue = new Stack<Future>(); + + protected ExecutorService executor; + + protected ExecutorService getExecutor() { + return executor; + } + + protected AbstractMachine() {} + + protected AbstractMachine(ExecutorService executor) { + this.executor = executor; + } + + public void execute() { + Object op; + while ((op = shift()) != null) { + if (op instanceof Future) { + try { + op = ((Future)op).get(); + } + catch (InterruptedException e) { + e.printStackTrace(); // FIXME + } + catch (ExecutionException e) { + e.printStackTrace(); // FIXME + } + } + if (op instanceof Operator) { + ((Operator)op).execute(this); + } + else { + push(op); + } + } + } + + public void execute(Operator operator) { + unshift(operator); + execute(); + } + + public Future<?> submit(Callable<?> callable) { + return getExecutor().submit(callable); + } + + public void halt() { + getExecutor().shutdown(); + } + + public Object shift() { + if (!queue.empty()) { + return queue.pop(); + } + else { + return null; + } + } + + public void unshift(Operator op) { + queue.push(new Value(op)); + } + + public boolean empty() { + return stack.empty(); + } + + public <T> T get() { + try { + return this.<T>pop().get(); + } + catch (InterruptedException e) { + e.printStackTrace(); // FIXME + } + catch (ExecutionException e) { + e.printStackTrace(); // FIXME + } + return null; + } + + public <T> Future<T> peek() { + try { + return stack.peek(); + } + catch (EmptyStackException e) { + return null; + } + } + + public <T> Future<T> pop() { + try { + return stack.pop(); + } + catch (EmptyStackException e) { + throw new StackUnderflowError(); + } + } + + public void push(Future<?> value) { + stack.push(value); + } + + public void push(Callable<?> callable) { + push(submit(callable)); + } + + public void push(Object value) { + push(new Value(value)); + } + + public void push(boolean value) { + push(Boolean.valueOf(value)); + } + + public void push(char value) { + push(Character.valueOf(value)); + } + + public void push(byte value) { + push(Number.valueOf(value)); + } + + public void push(short value) { + push(Number.valueOf(value)); + } + + public void push(int value) { + push(Number.valueOf(value)); + } + + public void push(long value) { + push(Number.valueOf(value)); + } + + public void push(float value) { + push(Number.valueOf(value)); + } + + public void push(double value) { + push(Number.valueOf(value)); + } +} diff --git a/src/java/trith/lang/BinaryOperator.java b/src/java/trith/lang/BinaryOperator.java new file mode 100644 index 0000000..d8b4fba --- /dev/null +++ b/src/java/trith/lang/BinaryOperator.java @@ -0,0 +1,32 @@ +package trith.lang; +import java.util.concurrent.Future; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; + +/** + * @author Arto Bendiken + * @see http://en.wikipedia.org/wiki/Binary_operation + */ +public abstract class BinaryOperator<T, A, B> implements Operator { + public void execute(Machine machine) { + final Future<B> b = machine.pop(); + final Future<A> a = machine.pop(); + + machine.push(new Callable<T>() { + public T call() { + try { + return execute(a.get(), b.get()); + } + catch (InterruptedException e) { + e.printStackTrace(); // FIXME + } + catch (ExecutionException e) { + e.printStackTrace(); // FIXME + } + return null; + } + }); + } + + public abstract T execute(A a, B b); +} diff --git a/src/java/trith/lang/Machine.java b/src/java/trith/lang/Machine.java new file mode 100644 index 0000000..0f4bf84 --- /dev/null +++ b/src/java/trith/lang/Machine.java @@ -0,0 +1,23 @@ +package trith.lang; +import java.util.concurrent.Future; +import java.util.concurrent.Callable; + +/** + * @author Arto Bendiken + */ +public interface Machine { + public void execute(); + public void execute(Operator operator); + public Future<?> submit(Callable<?> callable); + public void halt(); + + public Object shift(); + public void unshift(Operator op); + + public boolean empty(); + public <T> T get(); + public <T> Future<T> peek(); + public <T> Future<T> pop(); + public void push(Future<?> value); + public void push(Callable<?> callable); +} diff --git a/src/java/trith/lang/NullaryOperator.java b/src/java/trith/lang/NullaryOperator.java new file mode 100644 index 0000000..f66f806 --- /dev/null +++ b/src/java/trith/lang/NullaryOperator.java @@ -0,0 +1,20 @@ +package trith.lang; +import java.util.concurrent.Future; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; + +/** + * @author Arto Bendiken + * @see http://en.wikipedia.org/wiki/Arity#Nullary + */ +public abstract class NullaryOperator<T> implements Operator { + public void execute(Machine machine) { + machine.push(new Callable<T>() { + public T call() { + return execute(); + } + }); + } + + public abstract T execute(); +} diff --git a/src/java/trith/lang/Number.java b/src/java/trith/lang/Number.java new file mode 100644 index 0000000..f68e742 --- /dev/null +++ b/src/java/trith/lang/Number.java @@ -0,0 +1,53 @@ +package trith.lang; +import java.math.BigDecimal; +import java.math.BigInteger; + +public class Number { + public static final BigDecimal ZERO = BigDecimal.ZERO; + public static final BigDecimal ONE = BigDecimal.ONE; + public static final BigDecimal TWO = BigDecimal.valueOf(2); + public static final BigDecimal THREE = BigDecimal.valueOf(3); + public static final BigDecimal FOUR = BigDecimal.valueOf(4); + public static final BigDecimal FIVE = BigDecimal.valueOf(5); + public static final BigDecimal SIX = BigDecimal.valueOf(6); + public static final BigDecimal SEVEN = BigDecimal.valueOf(7); + public static final BigDecimal EIGHT = BigDecimal.valueOf(8); + public static final BigDecimal NINE = BigDecimal.valueOf(9); + public static final BigDecimal TEN = BigDecimal.TEN; + + public static BigDecimal valueOf(BigDecimal value) { + return value; + } + + public static BigDecimal valueOf(BigInteger value) { + return new BigDecimal(value); + } + + public static BigDecimal valueOf(String value) { + return new BigDecimal(value); + } + + public static BigDecimal valueOf(byte value) { + return BigDecimal.valueOf(value); + } + + public static BigDecimal valueOf(short value) { + return BigDecimal.valueOf(value); + } + + public static BigDecimal valueOf(int value) { + return BigDecimal.valueOf(value); + } + + public static BigDecimal valueOf(long value) { + return BigDecimal.valueOf(value); + } + + public static BigDecimal valueOf(float value) { + return BigDecimal.valueOf(value); + } + + public static BigDecimal valueOf(double value) { + return BigDecimal.valueOf(value); + } +} diff --git a/src/java/trith/lang/Operator.java b/src/java/trith/lang/Operator.java new file mode 100644 index 0000000..17ba481 --- /dev/null +++ b/src/java/trith/lang/Operator.java @@ -0,0 +1,8 @@ +package trith.lang; + +/** + * @author Arto Bendiken + */ +public interface Operator { + public void execute(Machine machine); +} diff --git a/src/java/trith/lang/ParallelMachine.java b/src/java/trith/lang/ParallelMachine.java new file mode 100644 index 0000000..fbfcdbb --- /dev/null +++ b/src/java/trith/lang/ParallelMachine.java @@ -0,0 +1,15 @@ +package trith.lang; +import java.util.concurrent.Executors; + +/** + * @author Arto Bendiken + */ +public class ParallelMachine extends AbstractMachine { + public ParallelMachine() { + this(4); // TODO: figure out how many CPUs are available + } + + public ParallelMachine(int threads) { + super(Executors.newFixedThreadPool(threads)); + } +} diff --git a/src/java/trith/lang/Promise.java b/src/java/trith/lang/Promise.java new file mode 100644 index 0000000..6bec915 --- /dev/null +++ b/src/java/trith/lang/Promise.java @@ -0,0 +1,59 @@ +package trith.lang; +import java.util.concurrent.Future; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * @author Arto Bendiken + * @see http://en.wikipedia.org/wiki/Futures_and_promises + */ +public class Promise<V> implements Future { + protected boolean isForced = false; + protected V result; + protected Callable<V> callable; + + public Promise() {} + + public Promise(Callable<V> callable) { + this.callable = callable; + } + + public boolean cancel(boolean mayInterruptIfRunning) { + return false; + } + + public boolean isCancelled() { + return false; + } + + public boolean isDone() { + return true; + } + + public V get() throws InterruptedException, ExecutionException { + try { + return force(); + } + catch (Exception e) { + throw new ExecutionException(e); + } + } + + public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + return get(); // FIXME + } + + public V force() throws Exception { + if (!isForced) { // TODO: make this atomic + isForced = true; + result = call(); + } + return result; + } + + public V call() throws Exception { + return callable.call(); + } +} diff --git a/src/java/trith/lang/Reference.java b/src/java/trith/lang/Reference.java new file mode 100644 index 0000000..cb54ff9 --- /dev/null +++ b/src/java/trith/lang/Reference.java @@ -0,0 +1,3 @@ +package trith.lang; + +public class Reference {} diff --git a/src/java/trith/lang/SequentialMachine.java b/src/java/trith/lang/SequentialMachine.java new file mode 100644 index 0000000..f2abd6e --- /dev/null +++ b/src/java/trith/lang/SequentialMachine.java @@ -0,0 +1,11 @@ +package trith.lang; +import java.util.concurrent.Executors; + +/** + * @author Arto Bendiken + */ +public class SequentialMachine extends AbstractMachine { + public SequentialMachine() { + super(Executors.newSingleThreadExecutor()); + } +} diff --git a/src/java/trith/lang/StackUnderflowError.java b/src/java/trith/lang/StackUnderflowError.java new file mode 100644 index 0000000..4d0ba23 --- /dev/null +++ b/src/java/trith/lang/StackUnderflowError.java @@ -0,0 +1,4 @@ +package trith.lang; +import java.util.EmptyStackException; + +class StackUnderflowError extends EmptyStackException {} diff --git a/src/java/trith/lang/StandardMachine.java b/src/java/trith/lang/StandardMachine.java new file mode 100644 index 0000000..adfa95f --- /dev/null +++ b/src/java/trith/lang/StandardMachine.java @@ -0,0 +1,249 @@ +package trith.lang; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +/** + * @author Arto Bendiken + */ +public class StandardMachine extends AbstractMachine { + protected final AbstractMachine machine; + + protected ExecutorService getExecutor() { + return machine.getExecutor(); + } + + public StandardMachine() { + this(new SequentialMachine()); + } + + public StandardMachine(int concurrencyLevel) { + this(new ParallelMachine(concurrencyLevel)); + } + + public StandardMachine(AbstractMachine machine) { + this.machine = machine; + } + + public Object shift() { + return machine.shift(); + } + + public void unshift(Operator op) { + machine.unshift(op); + } + + public <T> Future<T> peek() { + return machine.peek(); + } + + public <T> Future<T> pop() { + return machine.pop(); + } + + public void push(Future<?> value) { + machine.push(value); + } + + /** + * @see trith.core.dup + */ + public void dup() { + execute(new trith.core.dup()); + } + + /** + * @see trith.core.nilp + */ + public void nilp() { + execute(new trith.core.nilp()); + } + + /** + * @see trith.core.nil + */ + public void nil() { + execute(new trith.core.nil()); + } + + /** + * @see trith.core.booleanp + */ + public void booleanp() { + execute(new trith.core.booleanp()); + } + + /** + * @see trith.core.falsep + */ + public void falsep() { + execute(new trith.core.falsep()); + } + + /** + * @see trith.core.truep + */ + public void truep() { + execute(new trith.core.truep()); + } + + /** + * @see trith.core.stringp + */ + public void stringp() { + execute(new trith.core.stringp()); + } + + /** + * @see trith.core.nump + */ + public void nump() { + execute(new trith.core.nump()); + } + + /** + * @see trith.core.zerop + */ + public void zerop() { + execute(new trith.core.zerop()); + } + + /* + * @see trith.math.abs + */ + public void abs() { + execute(new trith.math.abs()); + } + + /* + * @see trith.math.min + */ + public void min() { + execute(new trith.math.min()); + } + + /* + * @see trith.math.max + */ + public void max() { + execute(new trith.math.max()); + } + + /* + * @see trith.math.neg + */ + public void neg() { + execute(new trith.math.neg()); + } + + /* + * @see trith.math.inc + */ + public void inc() { + execute(new trith.math.inc()); + } + + /* + * @see trith.math.dec + */ + public void dec() { + execute(new trith.math.dec()); + } + + /* + * @see trith.math.add + */ + public void add() { + execute(new trith.math.add()); + } + + /* + * @see trith.math.sub + */ + public void sub() { + execute(new trith.math.sub()); + } + + /* + * @see trith.math.mul + */ + public void mul() { + execute(new trith.math.mul()); + } + + /* + * @see trith.math.div + */ + public void div() { + execute(new trith.math.div()); + } + + /* + * @see trith.math.rem + */ + public void rem() { + execute(new trith.math.rem()); + } + + /* + * @see trith.math.mod + */ + public void mod() { + execute(new trith.math.mod()); + } + + /* + * @see trith.math.pow + */ + public void pow() { + execute(new trith.math.pow()); + } + + /* + * @see trith.stream.emptyp + */ + public void emptyp() { + execute(new trith.stream.emptyp()); + } + + /* + * @see trith.stream.length + */ + public void length() { + execute(new trith.stream.length()); + } + + /* + * @see trith.stream.rest + */ + public void rest() { + execute(new trith.stream.rest()); + } + + /* + * @see trith.stream.first + */ + public void first() { + execute(new trith.stream.first()); + } + + /* + * @see trith.stream.nth + */ + public void nth() { + execute(new trith.stream.nth()); + } + + /* + * @see trith.stream.last + */ + public void last() { + execute(new trith.stream.last()); + } + + /* + * @see trith.stream.cons + */ + public void cons() { + execute(new trith.stream.cons()); + } +} diff --git a/src/java/trith/lang/Symbol.java b/src/java/trith/lang/Symbol.java new file mode 100644 index 0000000..0bf84c6 --- /dev/null +++ b/src/java/trith/lang/Symbol.java @@ -0,0 +1,29 @@ +package trith.lang; + +class Symbol { + public final String name; + + public static Symbol intern(String name) { + return new Symbol(name); + } + + public static Symbol valueOf(String name) { + return new Symbol(name); + } + + public static Symbol valueOf(char name) { + return new Symbol(name); + } + + public Symbol(String name) { + this.name = name.intern(); + } + + public Symbol(char name) { + this.name = String.valueOf(name).intern(); + } + + public String toString() { + return name; + } +} diff --git a/src/java/trith/lang/UnaryOperator.java b/src/java/trith/lang/UnaryOperator.java new file mode 100644 index 0000000..58c5350 --- /dev/null +++ b/src/java/trith/lang/UnaryOperator.java @@ -0,0 +1,31 @@ +package trith.lang; +import java.util.concurrent.Future; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; + +/** + * @author Arto Bendiken + * @see http://en.wikipedia.org/wiki/Unary_operation + */ +public abstract class UnaryOperator<T, A> implements Operator { + public void execute(Machine machine) { + final Future<A> a = machine.pop(); + + machine.push(new Callable<T>() { + public T call() { + try { + return execute(a.get()); + } + catch (InterruptedException e) { + e.printStackTrace(); // FIXME + } + catch (ExecutionException e) { + e.printStackTrace(); // FIXME + } + return null; + } + }); + } + + public abstract T execute(A a); +} diff --git a/src/java/trith/lang/UnaryStreamOperator.java b/src/java/trith/lang/UnaryStreamOperator.java new file mode 100644 index 0000000..2bc99b9 --- /dev/null +++ b/src/java/trith/lang/UnaryStreamOperator.java @@ -0,0 +1,43 @@ +package trith.lang; +import java.util.Iterator; +import java.util.Collection; +import java.util.List; + +/** + * @author Arto Bendiken + */ +public abstract class UnaryStreamOperator<T, A> extends UnaryOperator<T, A> { + public T execute(A a) { + if (a instanceof String) { + return execute((String)a); + } + if (a instanceof List) { + return execute((List)a); + } + if (a instanceof Collection) { + return execute((Collection)a); + } + if (a instanceof Iterator) { + return execute((Iterator)a); + } + if (a instanceof Iterable) { + return execute((Iterable)a); + } + return null; // FIXME + } + + public abstract T execute(String a); + public abstract T execute(Iterator a); + + public T execute(List a) { + return execute((Collection)a); + } + + public T execute(Collection a) { + return execute(a.iterator()); + } + + public T execute(Iterable a) { + return execute(a.iterator()); + } +} diff --git a/src/java/trith/lang/Value.java b/src/java/trith/lang/Value.java new file mode 100644 index 0000000..c24be37 --- /dev/null +++ b/src/java/trith/lang/Value.java @@ -0,0 +1,36 @@ +package trith.lang; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; + +/** + * @author Arto Bendiken + */ +public class Value implements Future<Object> { + protected Object value; + + public Value(Object value) { + this.value = value; + } + + public boolean cancel(boolean mayInterruptIfRunning) { + return false; + } + + public boolean isCancelled() { + return false; + } + + public boolean isDone() { + return true; + } + + public Object get() throws InterruptedException, ExecutionException { + return value; + } + + public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + return value; + } +} diff --git a/src/java/trith/math/abs.java b/src/java/trith/math/abs.java new file mode 100644 index 0000000..e84bf26 --- /dev/null +++ b/src/java/trith/math/abs.java @@ -0,0 +1,15 @@ +package trith.math; +import trith.lang.*; +import java.math.BigDecimal; + +/** + * @author Arto Bendiken + * @see http://trith.org/math/abs + */ +public class abs extends UnaryOperator<BigDecimal, BigDecimal> { + public static final String URL = "http://trith.org/math/abs"; + + public BigDecimal execute(BigDecimal n) { + return n.abs(); + } +} diff --git a/src/java/trith/math/add.java b/src/java/trith/math/add.java new file mode 100644 index 0000000..fc9be24 --- /dev/null +++ b/src/java/trith/math/add.java @@ -0,0 +1,15 @@ +package trith.math; +import trith.lang.*; +import java.math.BigDecimal; + +/** + * @author Arto Bendiken + * @see http://trith.org/math/add + */ +public class add extends BinaryOperator<BigDecimal, BigDecimal, BigDecimal> { + public static final String URL = "http://trith.org/math/add"; + + public BigDecimal execute(BigDecimal a, BigDecimal b) { + return a.add(b); + } +} diff --git a/src/java/trith/math/dec.java b/src/java/trith/math/dec.java new file mode 100644 index 0000000..a383925 --- /dev/null +++ b/src/java/trith/math/dec.java @@ -0,0 +1,16 @@ +package trith.math; +import trith.lang.*; +import trith.lang.Number; +import java.math.BigDecimal; + +/** + * @author Arto Bendiken + * @see http://trith.org/math/dec + */ +public class dec extends UnaryOperator<BigDecimal, BigDecimal> { + public static final String URL = "http://trith.org/math/dec"; + + public BigDecimal execute(BigDecimal n) { + return n.subtract(Number.ONE); + } +} diff --git a/src/java/trith/math/div.java b/src/java/trith/math/div.java new file mode 100644 index 0000000..a80ac8d --- /dev/null +++ b/src/java/trith/math/div.java @@ -0,0 +1,15 @@ +package trith.math; +import trith.lang.*; +import java.math.BigDecimal; + +/** + * @author Arto Bendiken + * @see http://trith.org/math/div + */ +public class div extends BinaryOperator<BigDecimal, BigDecimal, BigDecimal> { + public static final String URL = "http://trith.org/math/div"; + + public BigDecimal execute(BigDecimal a, BigDecimal b) { + return a.divide(b); + } +} diff --git a/src/java/trith/math/inc.java b/src/java/trith/math/inc.java new file mode 100644 index 0000000..91edd66 --- /dev/null +++ b/src/java/trith/math/inc.java @@ -0,0 +1,16 @@ +package trith.math; +import trith.lang.*; +import trith.lang.Number; +import java.math.BigDecimal; + +/** + * @author Arto Bendiken + * @see http://trith.org/math/inc + */ +public class inc extends UnaryOperator<BigDecimal, BigDecimal> { + public static final String URL = "http://trith.org/math/inc"; + + public BigDecimal execute(BigDecimal n) { + return n.add(Number.ONE); + } +} diff --git a/src/java/trith/math/max.java b/src/java/trith/math/max.java new file mode 100644 index 0000000..8f90db5 --- /dev/null +++ b/src/java/trith/math/max.java @@ -0,0 +1,15 @@ +package trith.math; +import trith.lang.*; +import java.math.BigDecimal; + +/** + * @author Arto Bendiken + * @see http://trith.org/math/max + */ +public class max extends BinaryOperator<BigDecimal, BigDecimal, BigDecimal> { + public static final String URL = "http://trith.org/math/max"; + + public BigDecimal execute(BigDecimal a, BigDecimal b) { + return a.max(b); + } +} diff --git a/src/java/trith/math/min.java b/src/java/trith/math/min.java new file mode 100644 index 0000000..b3f6d5d --- /dev/null +++ b/src/java/trith/math/min.java @@ -0,0 +1,15 @@ +package trith.math; +import trith.lang.*; +import java.math.BigDecimal; + +/** + * @author Arto Bendiken + * @see http://trith.org/math/min + */ +public class min extends BinaryOperator<BigDecimal, BigDecimal, BigDecimal> { + public static final String URL = "http://trith.org/math/min"; + + public BigDecimal execute(BigDecimal a, BigDecimal b) { + return a.min(b); + } +} diff --git a/src/java/trith/math/mod.java b/src/java/trith/math/mod.java new file mode 100644 index 0000000..0d174d3 --- /dev/null +++ b/src/java/trith/math/mod.java @@ -0,0 +1,16 @@ +package trith.math; +import trith.lang.*; +import java.math.BigDecimal; +import java.math.BigInteger; + +/** + * @author Arto Bendiken + * @see http://trith.org/math/mod + */ +public class mod extends BinaryOperator<BigDecimal, BigDecimal, BigDecimal> { + public static final String URL = "http://trith.org/math/mod"; + + public BigDecimal execute(BigDecimal a, BigDecimal b) { + return new BigDecimal(a.toBigIntegerExact().mod(b.toBigIntegerExact())); + } +} diff --git a/src/java/trith/math/mul.java b/src/java/trith/math/mul.java new file mode 100644 index 0000000..a708963 --- /dev/null +++ b/src/java/trith/math/mul.java @@ -0,0 +1,15 @@ +package trith.math; +import trith.lang.*; +import java.math.BigDecimal; + +/** + * @author Arto Bendiken + * @see http://trith.org/math/mul + */ +public class mul extends BinaryOperator<BigDecimal, BigDecimal, BigDecimal> { + public static final String URL = "http://trith.org/math/mul"; + + public BigDecimal execute(BigDecimal a, BigDecimal b) { + return a.multiply(b); + } +} diff --git a/src/java/trith/math/neg.java b/src/java/trith/math/neg.java new file mode 100644 index 0000000..8726f15 --- /dev/null +++ b/src/java/trith/math/neg.java @@ -0,0 +1,15 @@ +package trith.math; +import trith.lang.*; +import java.math.BigDecimal; + +/** + * @author Arto Bendiken + * @see http://trith.org/math/neg + */ +public class neg extends UnaryOperator<BigDecimal, BigDecimal> { + public static final String URL = "http://trith.org/math/neg"; + + public BigDecimal execute(BigDecimal n) { + return n.negate(); + } +} diff --git a/src/java/trith/math/pow.java b/src/java/trith/math/pow.java new file mode 100644 index 0000000..2435db1 --- /dev/null +++ b/src/java/trith/math/pow.java @@ -0,0 +1,15 @@ +package trith.math; +import trith.lang.*; +import java.math.BigDecimal; + +/** + * @author Arto Bendiken + * @see http://trith.org/math/pow + */ +public class pow extends BinaryOperator<BigDecimal, BigDecimal, BigDecimal> { + public static final String URL = "http://trith.org/math/pow"; + + public BigDecimal execute(BigDecimal a, BigDecimal b) { + return a.pow(b.intValue()); // FIXME + } +} diff --git a/src/java/trith/math/rem.java b/src/java/trith/math/rem.java new file mode 100644 index 0000000..942e7ec --- /dev/null +++ b/src/java/trith/math/rem.java @@ -0,0 +1,15 @@ +package trith.math; +import trith.lang.*; +import java.math.BigDecimal; + +/** + * @author Arto Bendiken + * @see http://trith.org/math/rem + */ +public class rem extends BinaryOperator<BigDecimal, BigDecimal, BigDecimal> { + public static final String URL = "http://trith.org/math/rem"; + + public BigDecimal execute(BigDecimal a, BigDecimal b) { + return a.remainder(b); + } +} diff --git a/src/java/trith/math/sub.java b/src/java/trith/math/sub.java new file mode 100644 index 0000000..87e616a --- /dev/null +++ b/src/java/trith/math/sub.java @@ -0,0 +1,15 @@ +package trith.math; +import trith.lang.*; +import java.math.BigDecimal; + +/** + * @author Arto Bendiken + * @see http://trith.org/math/sub + */ +public class sub extends BinaryOperator<BigDecimal, BigDecimal, BigDecimal> { + public static final String URL = "http://trith.org/math/sub"; + + public BigDecimal execute(BigDecimal a, BigDecimal b) { + return a.subtract(b); + } +} diff --git a/src/java/trith/stream/cons.java b/src/java/trith/stream/cons.java new file mode 100644 index 0000000..6eb5019 --- /dev/null +++ b/src/java/trith/stream/cons.java @@ -0,0 +1,80 @@ +package trith.stream; +import trith.lang.*; +import java.util.Iterator; +import java.util.Collection; +import java.util.List; +import java.util.LinkedList; +import java.util.ArrayList; + +/** + * @author Arto Bendiken + * @see http://trith.org/stream/cons + */ +public class cons extends BinaryOperator<Object, Object, Object> { + public static final String URL = "http://trith.org/stream/cons"; + + public Object execute(Object a, Object b) { + if (b instanceof String) { + return execute(a, (String)b); + } + if (b instanceof List) { + return execute(a, (List)b); + } + if (b instanceof Collection) { + return execute(a, (Collection)b); + } + if (b instanceof Iterator) { + return execute(a, (Iterator)b); + } + if (b instanceof Iterable) { + return execute(a, (Iterable)b); + } + return null; // FIXME + } + + public Object execute(Object first, String rest) { + if (!(first instanceof Character)) { + // TODO: should we throw an error? + } + return first.toString().concat(rest); + } + + public Object execute(Object first, List rest) { + if (rest instanceof LinkedList) { + LinkedList result = (LinkedList)((LinkedList)rest).clone(); + result.addFirst(first); + return result; + } + if (rest instanceof ArrayList) { + ArrayList result = (ArrayList)((ArrayList)rest).clone(); + result.add(0, first); + return result; + } + else { + // Object#clone is protected in classes we don't explicitly know + // about, so we'll have to fall back to the Collection interface: + return execute(first, (Collection)rest); + } + } + + public Object execute(Object first, Collection rest) { + // TODO: this should work lazily + LinkedList result = new LinkedList(rest); + result.addFirst(first); + return result; + } + + public Object execute(Object first, Iterator rest) { + // FIXME: this should work lazily + LinkedList result = new LinkedList(); + result.addFirst(first); + while (rest.hasNext()) { + result.addLast(rest.next()); + } + return result; + } + + public Object execute(Object first, Iterable rest) { + return execute(first, rest.iterator()); + } +} diff --git a/src/java/trith/stream/emptyp.java b/src/java/trith/stream/emptyp.java new file mode 100644 index 0000000..b378d98 --- /dev/null +++ b/src/java/trith/stream/emptyp.java @@ -0,0 +1,24 @@ +package trith.stream; +import trith.lang.*; +import java.util.Iterator; +import java.util.Collection; + +/** + * @author Arto Bendiken + * @see http://trith.org/stream/emptyp + */ +public class emptyp extends UnaryStreamOperator<Boolean, Object> { + public static final String URL = "http://trith.org/stream/emptyp"; + + public Boolean execute(String str) { + return Boolean.valueOf(str.isEmpty()); + } + + public Boolean execute(Collection coll) { + return Boolean.valueOf(coll.isEmpty()); + } + + public Boolean execute(Iterator iter) { + return Boolean.valueOf(!iter.hasNext()); + } +} diff --git a/src/java/trith/stream/first.java b/src/java/trith/stream/first.java new file mode 100644 index 0000000..541f2b9 --- /dev/null +++ b/src/java/trith/stream/first.java @@ -0,0 +1,39 @@ +package trith.stream; +import trith.lang.*; +import java.util.Iterator; +import java.util.List; + +/** + * @author Arto Bendiken + * @see http://trith.org/stream/first + */ +public class first extends UnaryStreamOperator<Object, Object> { + public static final String URL = "http://trith.org/stream/first"; + + public Object execute(String str) { + if (str.isEmpty()) { + return null; + } + else { + return Character.valueOf(str.charAt(0)); + } + } + + public Object execute(List list) { + if (list.isEmpty()) { + return null; + } + else { + return list.get(0); + } + } + + public Object execute(Iterator iter) { + if (!iter.hasNext()) { + return null; + } + else { + return iter.next(); + } + } +} diff --git a/src/java/trith/stream/last.java b/src/java/trith/stream/last.java new file mode 100644 index 0000000..e6e9e7b --- /dev/null +++ b/src/java/trith/stream/last.java @@ -0,0 +1,44 @@ +package trith.stream; +import trith.lang.*; +import java.util.Iterator; +import java.util.List; + +/** + * @author Arto Bendiken + * @see http://trith.org/stream/last + */ +public class last extends UnaryStreamOperator<Object, Object> { + public static final String URL = "http://trith.org/stream/last"; + + public Object execute(String str) { + if (str.isEmpty()) { + return null; + } + else { + //return Character.valueOf(str.codePointBefore(str.length())); + return Character.valueOf(str.charAt(str.length() - 1)); + } + } + + public Object execute(List list) { + if (list.isEmpty()) { + return null; + } + else { + return list.get(list.size() - 1); + } + } + + public Object execute(Iterator iter) { + if (!iter.hasNext()) { + return null; + } + else { + Object element = null; + while (iter.hasNext()) { + element = iter.next(); + } + return element; + } + } +} diff --git a/src/java/trith/stream/length.java b/src/java/trith/stream/length.java new file mode 100644 index 0000000..3068a16 --- /dev/null +++ b/src/java/trith/stream/length.java @@ -0,0 +1,35 @@ +package trith.stream; +import trith.lang.*; +import trith.lang.Number; +import java.math.BigDecimal; +import java.util.Iterator; +import java.util.Collection; + +/** + * @author Arto Bendiken + * @see http://trith.org/stream/length + */ +public class length extends UnaryStreamOperator<BigDecimal, Object> { + public static final String URL = "http://trith.org/stream/length"; + + /** + * @see http://java.sun.com/javase/6/docs/api/java/lang/Character.html#unicode + */ + public BigDecimal execute(String str) { + //return Number.valueOf(str.codePointCount(0, str.length())); // TODO + return Number.valueOf(str.length()); + } + + public BigDecimal execute(Collection coll) { + return Number.valueOf(coll.size()); + } + + public BigDecimal execute(Iterator iter) { + long length = 0; + while (iter.hasNext()) { + length++; + iter.next(); + } + return Number.valueOf(length); + } +} diff --git a/src/java/trith/stream/nth.java b/src/java/trith/stream/nth.java new file mode 100644 index 0000000..520c34d --- /dev/null +++ b/src/java/trith/stream/nth.java @@ -0,0 +1,55 @@ +package trith.stream; +import trith.lang.*; +import java.util.concurrent.Future; +import java.util.concurrent.ExecutionException; +import java.util.Iterator; +import java.util.Collection; +import java.util.List; +import java.math.BigDecimal; + +/** + * @author Arto Bendiken + * @see http://trith.org/stream/nth + */ +public class nth implements Operator { + public static final String URL = "http://trith.org/stream/nth"; + + public void execute(final Machine machine) { + final Future<BigDecimal> a = machine.pop(); + + machine.unshift(new UnaryStreamOperator<Object, Object>() { + public int getIndex() { + try { + return a.get().intValue(); + } + catch (InterruptedException e) { + e.printStackTrace(); // FIXME + } + catch (ExecutionException e) { + e.printStackTrace(); // FIXME + } + return -1; // FIXME + } + + public Object execute(String str) { + return str.charAt(getIndex()); + } + + public Object execute(List list) { + return list.get(getIndex()); + } + + public Object execute(Iterator iter) { + int index = getIndex(); + int position = 0; + while (iter.hasNext()) { + Object element = iter.next(); + if (index == position++) { + return element; + } + } + throw new ArrayIndexOutOfBoundsException(index); + } + }); + } +} diff --git a/src/java/trith/stream/rest.java b/src/java/trith/stream/rest.java new file mode 100644 index 0000000..87fa40b --- /dev/null +++ b/src/java/trith/stream/rest.java @@ -0,0 +1,42 @@ +package trith.stream; +import trith.lang.*; +import java.util.Iterator; +import java.util.List; +import java.util.Collections; + +/** + * @author Arto Bendiken + * @see http://trith.org/stream/rest + */ +public class rest extends UnaryStreamOperator<Object, Object> { + public static final String URL = "http://trith.org/stream/rest"; + + public Object execute(String str) { + if (str.isEmpty()) { + return Collections.EMPTY_LIST; + } + else { + return str.substring(1); + } + } + + public Object execute(List list) { + if (list.isEmpty()) { + return Collections.EMPTY_LIST; + } + else { + //return list.listIterator(1); + return list.subList(1, list.size()); + } + } + + public Object execute(Iterator iter) { + if (!iter.hasNext()) { + return Collections.EMPTY_LIST; + } + else { + iter.next(); + return iter; + } + } +}
zorgnax/libtap
af1fc82f565d8aa8874798ef70019872e756e326
Only conditionally include sys/types.h and sys/mman.h
diff --git a/tap.c b/tap.c index 9ea8bb1..b4de9bc 100644 --- a/tap.c +++ b/tap.c @@ -1,366 +1,365 @@ /* libtap - Write tests in C Copyright 2012 Jake Gelbman <[email protected]> This file is licensed under the LGPL */ #define _DEFAULT_SOURCE 1 #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> -#include <sys/types.h> -#include <sys/mman.h> #include "tap.h" #ifndef _WIN32 +#include <sys/types.h> #include <sys/mman.h> #include <sys/param.h> #include <regex.h> #ifndef MAP_ANONYMOUS #ifdef MAP_ANON #define MAP_ANONYMOUS MAP_ANON #else #error "System does not support mapping anonymous pages" #endif #endif #endif static int expected_tests = NO_PLAN; static int failed_tests; static int current_test; static char *todo_mesg; static char * vstrdupf (const char *fmt, va_list args) { char *str; int size; va_list args2; va_copy(args2, args); if (!fmt) fmt = ""; size = vsnprintf(NULL, 0, fmt, args2) + 2; str = malloc(size); if (!str) { perror("malloc error"); exit(1); } vsprintf(str, fmt, args); va_end(args2); return str; } void tap_plan (int tests, const char *fmt, ...) { expected_tests = tests; if (tests == SKIP_ALL) { char *why; va_list args; va_start(args, fmt); why = vstrdupf(fmt, args); va_end(args); printf("1..0 "); diag("SKIP %s\n", why); exit(0); } if (tests != NO_PLAN) { printf("1..%d\n", tests); } } int vok_at_loc (const char *file, int line, int test, const char *fmt, va_list args) { char *name = vstrdupf(fmt, args); if (!test) { printf("not "); } printf("ok %d", ++current_test); if (*name) printf(" - %s", name); if (todo_mesg) { printf(" # TODO"); if (*todo_mesg) printf(" %s", todo_mesg); } printf("\n"); if (!test) { printf("# Failed "); if (todo_mesg) printf("(TODO) "); printf("test "); if (*name) printf("'%s'\n# ", name); printf("at %s line %d.\n", file, line); if (!todo_mesg) failed_tests++; } free(name); return test; } int ok_at_loc (const char *file, int line, int test, const char *fmt, ...) { va_list args; va_start(args, fmt); vok_at_loc(file, line, test, fmt, args); va_end(args); return test; } static int mystrcmp (const char *a, const char *b) { return a == b ? 0 : !a ? -1 : !b ? 1 : strcmp(a, b); } #define eq(a, b) (!mystrcmp(a, b)) #define ne(a, b) (mystrcmp(a, b)) int is_at_loc (const char *file, int line, const char *got, const char *expected, const char *fmt, ...) { int test = eq(got, expected); va_list args; va_start(args, fmt); vok_at_loc(file, line, test, fmt, args); va_end(args); if (!test) { diag(" got: '%s'", got); diag(" expected: '%s'", expected); } return test; } int isnt_at_loc (const char *file, int line, const char *got, const char *expected, const char *fmt, ...) { int test = ne(got, expected); va_list args; va_start(args, fmt); vok_at_loc(file, line, test, fmt, args); va_end(args); if (!test) { diag(" got: '%s'", got); diag(" expected: anything else"); } return test; } int cmp_ok_at_loc (const char *file, int line, int a, const char *op, int b, const char *fmt, ...) { int test = eq(op, "||") ? a || b : eq(op, "&&") ? a && b : eq(op, "|") ? a | b : eq(op, "^") ? a ^ b : eq(op, "&") ? a & b : eq(op, "==") ? a == b : eq(op, "!=") ? a != b : eq(op, "<") ? a < b : eq(op, ">") ? a > b : eq(op, "<=") ? a <= b : eq(op, ">=") ? a >= b : eq(op, "<<") ? a << b : eq(op, ">>") ? a >> b : eq(op, "+") ? a + b : eq(op, "-") ? a - b : eq(op, "*") ? a * b : eq(op, "/") ? a / b : eq(op, "%") ? a % b : diag("unrecognized operator '%s'", op); va_list args; va_start(args, fmt); vok_at_loc(file, line, test, fmt, args); va_end(args); if (!test) { diag(" %d", a); diag(" %s", op); diag(" %d", b); } return test; } static int find_mem_diff (const char *a, const char *b, size_t n, size_t *offset) { size_t i; if (a == b) return 0; if (!a || !b) return 2; for (i = 0; i < n; i++) { if (a[i] != b[i]) { *offset = i; return 1; } } return 0; } int cmp_mem_at_loc (const char *file, int line, const void *got, const void *expected, size_t n, const char *fmt, ...) { size_t offset; int diff = find_mem_diff(got, expected, n, &offset); va_list args; va_start(args, fmt); vok_at_loc(file, line, !diff, fmt, args); va_end(args); if (diff == 1) { diag(" Difference starts at offset %d", offset); diag(" got: 0x%02x", ((const unsigned char *)got)[offset]); diag(" expected: 0x%02x", ((const unsigned char *)expected)[offset]); } else if (diff == 2) { diag(" got: %s", got ? "not NULL" : "NULL"); diag(" expected: %s", expected ? "not NULL" : "NULL"); } return !diff; } int diag (const char *fmt, ...) { va_list args; char *mesg, *line; int i; va_start(args, fmt); if (!fmt) { va_end(args); return 0; } mesg = vstrdupf(fmt, args); line = mesg; for (i = 0; *line; i++) { char c = mesg[i]; if (!c || c == '\n') { mesg[i] = '\0'; printf("# %s\n", line); if (!c) break; mesg[i] = c; line = mesg + i + 1; } } free(mesg); va_end(args); return 0; } int exit_status () { int retval = 0; if (expected_tests == NO_PLAN) { printf("1..%d\n", current_test); } else if (current_test != expected_tests) { diag("Looks like you planned %d test%s but ran %d.", expected_tests, expected_tests > 1 ? "s" : "", current_test); retval = 2; } if (failed_tests) { diag("Looks like you failed %d test%s of %d run.", failed_tests, failed_tests > 1 ? "s" : "", current_test); retval = 1; } return retval; } int bail_out (int ignore, const char *fmt, ...) { va_list args; (void) ignore; va_start(args, fmt); printf("Bail out! "); vprintf(fmt, args); printf("\n"); va_end(args); exit(255); return 0; } void tap_skip (int n, const char *fmt, ...) { char *why; va_list args; va_start(args, fmt); why = vstrdupf(fmt, args); va_end(args); while (n --> 0) { printf("ok %d ", ++current_test); diag("skip %s\n", why); } free(why); } void tap_todo (int ignore, const char *fmt, ...) { va_list args; (void) ignore; va_start(args, fmt); todo_mesg = vstrdupf(fmt, args); va_end(args); } void tap_end_todo () { free(todo_mesg); todo_mesg = NULL; } #ifndef _WIN32 /* Create a shared memory int to keep track of whether a piece of code executed dies. to be used in the dies_ok and lives_ok macros. */ int tap_test_died (int status) { static int *test_died = NULL; int prev; if (!test_died) { test_died = mmap(0, sizeof (int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); *test_died = 0; } prev = *test_died; *test_died = status; return prev; } int like_at_loc (int for_match, const char *file, int line, const char *got, const char *expected, const char *fmt, ...) { int test; regex_t re; va_list args; int err = regcomp(&re, expected, REG_EXTENDED); if (err) { char errbuf[256]; regerror(err, &re, errbuf, sizeof errbuf); fprintf(stderr, "Unable to compile regex '%s': %s at %s line %d\n", expected, errbuf, file, line); exit(255); } err = regexec(&re, got, 0, NULL, 0); regfree(&re); test = for_match ? !err : err; va_start(args, fmt); vok_at_loc(file, line, test, fmt, args); va_end(args); if (!test) { if (for_match) { diag(" '%s'", got); diag(" doesn't match: '%s'", expected); } else { diag(" '%s'", got); diag(" matches: '%s'", expected); } } return test; } #endif