txt
stringlengths
202
72.4k
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: examples/channel-clock.raku ### ---------------------------------------------------- #!perl6 use API::Discord; sub MAIN($token, $channel-id) { my $discord = API::Discord.new(:$token); $discord.connect; await $discord.ready; my $channel = $discord.get-channel($channel-id); react { whenever Supply.interval(60) { $channel.name = '🕒 ' ~ sprintf("%02d:%02d", .hour, .minute) given DateTime.now; $channel.update; CATCH {.say} } } }
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: examples/sort-of-bot.raku ### ---------------------------------------------------- #!perl6 use API::Discord; sub MAIN($token) { my $discord = API::Discord.new(:$token); await $discord.connect; react { whenever $discord.messages -> $message { if $message.addressed { my $c = $message.content; my Str $id = $discord.user.real-id; $c ~~ s/^ '<@' $id '>' \s+//; given $c { when 'pin' { await $message.pin; } } } } } }
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: examples/echo-server.raku ### ---------------------------------------------------- #!perl6 use API::Discord; sub MAIN($token) { my $discord = API::Discord.new(:$token, :script-mode); $discord.connect; await $discord.ready; react { whenever $discord.messages -> $message { $message.channel.send-message($message.content); } } }
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: examples/direct-message.raku ### ---------------------------------------------------- #!raku use API::Discord; sub MAIN($token) { my $discord = API::Discord.new(:$token); $discord.connect; await $discord.ready; react { whenever $discord.messages -> $message { my $dm = await $discord.user.create-dm($message.author); $dm.send-message($message.content); } } }
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: examples/fetching-things.raku ### ---------------------------------------------------- #!perl6 use API::Discord; sub MAIN($token) { my $discord = API::Discord.new(:$token); await $discord.connect; react { # We can't access $discord.user until we've received the READY event # When we do get that, we can ask for the list of guilds. Although we # always get a Promise, we only actualy fetch the list once. # # Some properties of objects return Promises because we have to fetch # them when requested. This will always return the same Promise, to # avoid race conditions. whenever $discord.events -> $event { if $event<t> eq 'READY' { my @guilds = (await $discord.user.guilds).map: {$_.to-json}; @guilds.say; } } } }
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Discord.rakumod ### ---------------------------------------------------- use API::Discord::Connection; use API::Discord::HTTPResource; use API::Discord::Intents; use API::Discord::Channel; use API::Discord::Guild; use API::Discord::Message; use API::Discord::User; use API::Discord::Debug <FROM-MODULE>; use Cro::WebSocket::Client; use Cro::WebSocket::Client::Connection; unit class API::Discord is export; =begin pod =head1 NAME API::Discord - Perl6 interface to L<Discord|https://discordapp.com> API =head1 DESCRIPTION This provides a lowish-level interface to the Discord API. It supplies a stream of messages and other events to which your app can listen. =head1 SYNOPSIS use API::Discord; use API::Discord::Debug; # remove to disable debug output my $d = API::Discord.new(:token(my-bot-token), :script-mode); $d.connect; await $d.ready; react { whenever $d.messages -> $m { ... } # Events not yet implemented #whenever $d.events -> $e { # ... #} } =head1 USING OBJECTS API::Discord models the various API objects in corresponding classes. These classes can either be used directly, or used via the API object. The API object has the advantage of also having connections to Discord, thus allowing you to fetch and send data without doing it manually. Most of the time, you will want to use an existing object to create and send another object. For example, Discord communicates with us which Guilds and Channels we are in, so the API constantly keeps a cache of these, since they are usually few and rarely change. Therefore, to create a Channel, you might do it via Guild, and to send a Message, you might do it via Channel. Channel and Guild are usually your entrypoints to doing things. $api.get-channel($id).send-message("Hi I'm a bot"); $api.get-guild($id).create-channel({ ... }); The other entrypoint to information are the message and event supplies. These emit complete objects, which can be used to perform further actions. For example, the Message class stores the Channel from which it came, and Channel has send-message: whenever $api.messages -> $m { $m.channel.send-message("I heard that!"); } All of these classes use the API to fetch and send if they need to. This prevents them from having to know about one another, which would result in circular dependencies. It also makes them easier to test N<If we ever did that>. Ultimately, you can always just create and send an object to Discord if you want to do it that way. my $m = API::Discord::Message.new(...); $api.send($m); This requires you to know all the parts you need for the operation to be successful, however. =head2 CRUD The core of the Discord API is simple CRUD mechanics over REST. The general idea in API::Discord is that if an object has an ID, then C<send> will update it; otherwise, it will create it and populate the ID from the response. This way, the same few methods handle most of the interaction you will have with Discord: editing a message is done by calling C<send> with a Message object that already has an ID; whereas posting a new message would simply be calling C<send> with a message with no ID, but of course a channel ID instead. API::Discord also handles deflating your objects into JSON. The structures defined by the Discord docs are supported recursively, which means if you set an object on another object, the inner object will also be deflated—into the correct JSON property—to be sent along with the outer object. However, if the Discord API doesn't support that structure in a particular situation, it just won't try to do it. For example, you can set an Embed on a Message and just send the Message, and this will serialise the Embed and send that too. my $m = API::Discord::Message.new(:channel($channel)); $m.embed(...); API::Discord.send($m); This example will serialise the Message and the Embed and send them, but will not attempt to serialise the entire Channel object into the Message object because that is not supported. Instead, it will take the channel ID from the Channel object and put that in the expected place. Naturally, one cannot delete an object with no ID, just as one cannot attempt to read an object given anything but an ID. (Searching notwithstanding.) =head1 SHARDING Discord implements sharding but you have to set it up yourself. This allows you to run multiple processes to handle data. To do so, pass a value for C<shard> and a value for C<shards-max> in each process. You have to know how many processes you are running altogether. To add a shard, it is therefore necessary to restart all of your existing shards; otherwise, it would suddenly change which process is handling data for which guild. Remember that only shard 0 will receive DMs. By default, the connection will assume you have only one shard. =head1 PROPERTIES =head2 script-mode This is a fake boolean property. If set, we handle SIGINT for you and disconnect properly. =end pod has Connection $!conn; #| The API version to use. I suppose we should try to keep this up to date. has Int $.version = 10; #| Host to which to connect. Can be overridden for testing e.g. has Str $.ws-host = 'gateway.discord.gg'; #| Host for REST requests has Str $.rest-host = 'discord.com'; #| Host for CDN URLs. This is gonna change eventually. has Str $.cdn-url = 'https://cdn.discordapp.com'; #| Bot token or whatever, used for auth. has Str $.token is required; #| Shard number for this connection has Int $.shard = 0; #| Number of shards you're running has Int $.shards-max = 1; #| Bitmask of intents has Int $.intents = ([+|] guilds, guild-messages, guild-message-reactions, message-content); # Docs say, increment number each time, per process has Int $!snowflake = 0; has Supplier $!messages = Supplier.new; has Supplier $!events = Supplier.new; #| Our user, populated on READY event has $.user is rw; #| A hash of Channel objects, keyed by the Channel ID. has %.channels; #| A hash of Guild objects that the user is a member of, keyed by the Guild ID. B<TODO> Currently this is not populated. has %.guilds; # Kept when all guild IDs we expect to receive have been received. TODO: timeout has Promise $!guilds-ready = Promise.new; method new (*%args) { my $script-mode = %args<script-mode>:delete; my $self = callwith |%args; if $script-mode { signal(SIGINT).tap: { await $self.disconnect; debug-say "Bye! 👋"; exit; } } return $self; } method !handle-message($message) { # TODO - send me an object please if $message<t> eq 'GUILD_CREATE' { for $message<d><channels><> -> $c { $c<guild_id> = $message<d><id>; my $id = $c<id>; my $chan = Channel.new( id => $id, api => self, real => Channel.reify( $c, self ) ); %.channels{$id} = $chan; } %.guilds{$message<d><id>} = self.inflate-guild($message<d>); # TODO: We might never get all of the guilds in the READY event. Set up # a timeout to keep it. if [&&] map *.defined, %.guilds.values { debug-say "All guilds ready!"; $!guilds-ready.keep unless $!guilds-ready; } } elsif $message<t> eq 'READY' { $.user = self.inflate-user(%( |$message<d><user>, id => '@me', real-id => $message<d><user><id> )); # Initialise empty objects for later. %.guilds{$_<id>} = Any for $message<d><guilds><>; } } #| Disconnects gracefully. Remember to await it! method disconnect { $!conn.close; } #| Connects to discord. Await the L</ready> Promise, then tap $.messages and $.events method connect($session-id?, $sequence?) returns Promise { $!conn = Connection.new( ws-url => "wss://{$.ws-host}/?v={$.version}&encoding=json", rest-url => "https://{$.rest-host}/api", :$.token, :$.shard, :$.shards-max, :$.intents, |(:$session-id if $session-id), |(:$sequence if $sequence), ); start react whenever $!conn.messages -> $message { self!handle-message($message); if $message<t> eq 'MESSAGE_CREATE' { my $m = self.inflate-message($message<d>); $!messages.emit($m) unless $message<d><author><id> == $.user.real-id; } else { $!events.emit($message); } } } #| Proxies the READY promise on connection. Await this before communicating with #discord. method ready returns Promise { Promise.allof($!conn.ready, $!guilds-ready); } #| Emits a Message object whenever a message is received. B<TODO> Currently this emits hashes. method messages returns Supply { $!messages.Supply; } #| A Supplier that emits things that aren't messages. B<TODO> Implement this method events returns Supply { $!events.Supply; } #| Creates an integer using the snowflake algorithm, guaranteed unique probably. method generate-snowflake { my $time = DateTime.now - DateTime.new(year => 2015); my $worker = 0; my $proc = 0; my $s = $!snowflake++; return ($time.Int +< 22) + ($worker +< 17) + ($proc +< 12) + $s; } method rest { $!conn.rest } =begin pod =head3 Factories and fetchers C<inflate-> and C<create-> methods return the object directly because they do not involve communication. All the other methods return a Promise that resolve to the documented return value. =end pod #| See also get-message(s) on the Channel class. method get-message (Any:D $channel-id, Any:D $id) returns Message { Message.new(:$channel-id, :$id, _api => self); } method get-messages (Any:D $channel-id, Any:D @message-ids) returns Array { @message-ids.map: self.get-message($channel-id, *); } method inflate-message (%json) returns Message { Message.new( api => self, id => %json<id>, channel-id => %json<channel_id>, real => Message.reify( %json ) ); } method create-message (%params) returns Message { Message.new( api => self, |%params ); } method get-channel (Any:D $id) returns Channel { %.channels{$id} //= Channel.new( id => $id, api => self ); } method get-channels (Any:D @channel-ids) returns Array { @channel-ids.map: self.get-channel(*); } method inflate-channel (%json) returns Channel { Channel.new( api => self, id => %json<id>, real => Channel.reify( %json, self ) ); } method create-channel (%params) returns Channel { Channel.new(|%params, api => self); } method get-guild (Any:D $id) returns Guild { %.guilds{$id} //= Guild.new(id => $id, _api => self) } method get-guilds (Any:D @guild-ids) returns Array { @guild-ids.map: self.get-guild(*); } method inflate-guild (%json) returns Guild { Guild.new( api => self, id => %json<id>, real => Guild.reify( %json ) ); } method create-guild (%params) returns Guild { Guild.new(|%params, api => self); } method get-user (Any:D $id) returns User { User.new(id => $id, api => self); } method get-users (Any:D @user-ids) returns Array { @user-ids.map: self.get-user(*); } method inflate-user (%json) returns User { User.new( api => self, id => %json<id>, real-id => %json<real-id>, real => User.reify( %json, self ) ); } method create-user (%params) returns User { User.new(|%params, api => self); } # TODO method inflate-member(%json) returns Guild::Member { Guild::Member.from-json(%(|%json, _api => self)); }
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Discord/User.rakumod ### ---------------------------------------------------- use Object::Delayed; use API::Discord::Object; use API::Discord::Endpoints; use Subset::Helper; unit class API::Discord::User does API::Discord::Object is export; class ButReal does API::Discord::DataObject { has $.username; has $.discriminator; has $.avatar; # The actual image has $.avatar-hash; # The URL bit for the CDN has $.is-bot; has $.is-mfa-enabled; has $.is-verified; has $.email; has $.locale; # to-json might not be necessary method to-json {} method from-json ($json) { my %constructor = $json<id username discriminator email locale real-id>:kv; %constructor<avatar-hash is-bot is-mfa-enabled is-verified> = $json<avatar bot mfa_enabled verified>; %constructor<api> = $json<_api>; return self.new(|%constructor); } } has Promise $!dms-promise; has Promise $!guilds-promise; #| Use real-id if you want to compare the user's numeric ID. This lets us put #| '@me' in id itself, for endpoints has $.real-id; has $.real handles < username discriminator avatar avatar-hash is-bot is-mfa-enabled is-verified email locale > = slack { await API::Discord::User::ButReal.read({:$!id, :$!api}, $!api.rest) }; multi method reify (::?CLASS:U: $data, $api) { ButReal.new(|%$data, :$api); } multi method reify (::?CLASS:D: $data) { my $r = ButReal.new(|%$data, api => $.api); $!real = $r; } submethod TWEAK() { $!real-id //= $!id; } my %image-formats = JPEG => '.jpeg', PNG => '.png', WebP => '.webp', GIF => '.gif'; subset ReallyInt of Numeric where subset-is { $_.Int == $_ }; subset PowerOfTwo of Int where subset-is { log($_, 2) ~~ ReallyInt }; subset ImageSize of PowerOfTwo where subset-is 16 <= * <= 4096; subset ImageFormat of Str where subset-is * ~~ %image-formats; # If I put :$format = 'PNG' it tells me PNG is a Str, not an ImageFormat method avatar-url( ImageSize :$desired-size, ImageFormat :$format ) { my $url = $.api.cdn-url ~ '/avatars/' ~ $.real-id ~ '/' ~ $.avatar-hash ~ %image-formats{$format // 'PNG'}; if $desired-size { $url ~= '?size=' ~ $desired-size } return $url; } method guilds returns Promise { if not $!guilds-promise { $!guilds-promise = start { my @guilds; my $e = endpoint-for( self, 'get-guilds' ) ; my $p = await $.api.rest.get($e); @guilds = (await $p.body).map( { $!api.inflate-guild($_) } ); @guilds; } } $!guilds-promise } method dms returns Promise { if not $!dms-promise { $!dms-promise = start { my @dms; my $e = endpoint-for( self, 'get-dms' ) ; my $p = await $.api.rest.get($e); @dms = (await $p.body).map: $!api.inflate-channel(*); @dms; } } $!dms-promise } method create-dm($user) returns Promise { start { my $body = { recipient_id => $user.id }; my $ret = await $.api.rest.post: endpoint-for(self, 'create-dm'), body => $body; my $dm = await $ret.body; $.api.inflate-channel($dm); } } =begin pod =head1 NAME API::Discord::User - Represents Discord user =head1 DESCRIPTION Represents a Discord user, usually sent to us via the websocket. See L<https://discordapp.com/developers/docs/resources/user>. Users cannot be created or deleted. See also L<API::Discord::Object>. =head1 PROMISES =head2 guilds Resolves to a list of L<API::Discord::Guild> objects =head2 dms Resolves to a list of L<API::Discord::Channel> objects (direct messages) =head1 METHODS =head2 create-dm Creates a DM with the provided C<$user>. This is an L<API::Discord::Channel> object; the method returns a Promise that resolves to this. =end pod
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Discord/Channel.rakumod ### ---------------------------------------------------- use API::Discord::Object; use API::Discord::Endpoints; use API::Discord::Types; use Object::Delayed; unit class API::Discord::Channel does API::Discord::Object is export; # The channel-but-real is the Object because it actually communicates with the # REST API to get its data. The other one is just a shiv for it. class ButReal does API::Discord::DataObject { has $.id; has $.type; has $.guild-id; has $.position; has $.name is rw; has $.topic; has $.is-nsfw; has $.last-message-id; has $.bitrate; has $.user-limit; has $.icon; has $.owner-id; has $.application-id; has $.parent-id; has $.rate-limit-per-user; has DateTime $.last-pin-timestamp; has $.parent-category; has $.owner; has @.recipients; has @.permission-overwrites; method to-json { # We're only allowed to update a subset of the fields we receive. my %self := self.Capture.hash; my %json = %self<position bitrate name topic icon>:kv; %json<nsfw rate_limit_per_user user_limit parent_id> = %self<is-nsfw rate-limit-per-user user-limit parent-id>; # TODO: permission overwrites %json = %json.grep( *.value.defined ); return %json } method from-json(::?CLASS:U: $json) { my %constructor = $json<id position bitrate name topic icon api>:kv; #%constructor<type> = ChannelType($json<type>.Int); %constructor< guild-id last-message-id rate-limit-per-user owner-id application-id parent-id is-nsfw user-limit> = $json< guild_id last_message_id rate_limit_per_user owner_id application_id parent_id nsfw user_limit>; %constructor<last-pin-timestamp> = DateTime.new($json<last_pin_timestamp>) if $json<last_pin_timestamp>; # TODO: permission overwrites return self.new(|%constructor); } } has $.real handles < type guild-id position name is rw topic is-nsfw last-message-id bitrate user-limit icon owner-id application-id parent-id rate-limit-per-user last-pin-timestamp parent-category owner recipients permission-overwrites > = slack { await API::Discord::Channel::ButReal.read({id => $!id, api => $!api}, $!api.rest) }; # Channel.new( id => $id, api => self, real => Channel.reify($hash) ); multi method reify (::?CLASS:U: $data, $api) { ButReal.from-json($data); } multi method reify (::?CLASS:D: $data) { my $r = ButReal.from-json($data); $!real = $r; } has @.messages; has Promise $!fetch-message-promise; has Promise $!fetch-pins-promise; submethod TWEAK() { # Seed the promise for fetch-messages to chain from $!fetch-message-promise = start {}; } method guild { $.api.get-guild($.guild-id); } #| Fetch N messages and returns a Promise that resolves to the complete new list #| of messages. If something is already fetching messages, your call will await #| those before making its own call on top of them. #| TODO: maybe only fetch enough extra messages after that one? method fetch-messages(Int $how-many) returns Promise { $!fetch-message-promise = $!fetch-message-promise.then: { my $get = 'get-messages'; if @.messages { $get ~= '?after=' ~ @.messages[*-1].id; } my $e = endpoint-for(self, $get); my $p = await $.api.rest.get($e); @.messages.append: (await $p.body).map: { $.api.inflate-message($_) }; @.messages; }; } #| Returns all pinned messages at once, in a Promise method pinned-messages($force?) returns Promise { if $force or not $!fetch-pins-promise { $!fetch-pins-promise = start { my @pins; my $e = endpoint-for( self, 'pinned-messages' ) ; my $p = await $.api.rest.get($e); @pins = (await $p.body).map( { $!api.inflate-message($_) } ); @pins; } } $!fetch-pins-promise; } #| Sends a message to the channel and returns the POST promise. multi method send-message($content, :$reference) returns Promise { self.send-message(:$content, :$reference) } multi method send-message(:$embed, :$content, :$reference) returns Promise { # FIXME: proper exception. And validate Message instead of doing it here. die "Provide at least one of embed or content" unless $embed or $content; $.api.create-message({ channel-id => $.id, |(:$embed if $embed), |(:$content if $content), |(:$reference if $reference), }).create; } method pin($message) returns Promise { $.api.rest.touch(endpoint-for(self, 'pinned-message', message-id => $message.id)); } method unpin($message) returns Promise { $.api.rest.remove(endpoint-for(self, 'pinned-message', message-id => $message.id)); } #| Shows the "user is typing..." message to everyone in the channel. Disappears #| after ~10 seconds or when a message is sent. method trigger-typing { # TODO: Handle error $.api.rest.post(endpoint-for(self, 'trigger-typing'), :body('')); } #| Deletes these messages. Max 100, minimum 2. If any message does not belong to #| this channel, the whole operation fails. Returns a promise that resolves to #| the new message array. method bulk-delete(@messages) { start { # TODO: I don't think we're handling a failure from this correctly await $.api.rest.post(endpoint-for(self, 'bulk-delete-messages'), body => {messages => [@messages.map: *.id]}); my %antipairs{Any} = @!messages.antipairs; my @removed-idxs = %antipairs{@messages}; my \to-remove = set(@removed-idxs); my @keep = @!messages.keys.grep(none(to-remove)); @!messages = @!messages[@keep]; } } =begin pod =head1 NAME API::Discord::Channel - Represents a channel or DM =head1 DESCRIPTION Represents a channel in a guild, or a pseudo-channel used for direct messages. See also L<API::Discord::Messages>. =head1 CONSTANTS =head2 API::Discord::Channel::ChannelType Contains values for the C<type> property guild-text dm guild-voice group-dm guild-category =head1 MESSAGES Messages are handled differently from many other things in this API because they are constantly changing. The API will update each channel with messages as they arrive. The messages are therefore stored in the C<@.messages> array, the first item of which will be the most recent message. The array may change at any time, so you should refer to it directly rather than saving a copy if you want the most recent facts. No historical messages are getch at the point of construction; the array will merely track messages as they arrive. Use L<fetch-messages> to append historical messages to the array. =end pod
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Discord/Types.rakumod ### ---------------------------------------------------- unit module API::Discord::Types; subset Snowflake is export of Str where /^ <[ 0 1 ]> ** 64 $/; enum OPCODE is export ( <dispatch heartbeat identify status-update voice-state-update voice-ping resume reconnect request-members invalid-session hello heartbeat-ack> ); enum CLOSE-EVENT is export ( 4000 => 'Unknown error', 4001 => 'Unknown opcode', 4002 => 'Decode error', 4003 => 'Not authenticated', 4004 => 'Authentication failed', 4005 => 'Already authenticated', 4007 => 'Invalid seq', 4008 => 'Rate limited', 4009 => 'Session timed out', 4010 => 'Invalid shard', 4011 => 'Sharding required', 4012 => 'Invalid API version', 4013 => 'Invalid intent(s)', 4014 => 'Disallowed intent(s)', ); package ChannelType is export { enum :: <guild-text dm guild-voice group-dm guild-category guild-news guild-store> ; }
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Discord/Guild.rakumod ### ---------------------------------------------------- use Object::Delayed; use API::Discord::Object; use API::Discord::Endpoints; use API::Discord::Permissions; use Subset::Helper; unit class API::Discord::Guild does API::Discord::Object is export; class ButReal does API::Discord::DataObject { has $.id; has $.name; has $.icon; has $.splash; has $.is-owner; has $.owner-id; has $.permissions; has $.region; has $.afk-channel-id; has $.afk-timeout; has $.verification-level; has $.default-message-notifications; has $.explicit-content-filter; has $.mfa-level; has $.application-id; has $.is-widget-enabled; has $.widget-channel-id; has $.system-channel-id; has $.system-channel-flags; has DateTime $.joined-at; has $.is-large; has $.is-unavailable; has $.member-count; method to-json { my %self = self.Capture.hash; my %json = %self<id name icon splash>:kv; %json<owner> = %self<is-owner>; return %json; } method from-json (%json) { # TODO I guess my %constructor = %json<id name icon splash pemissions region>:kv; for < owner-id afk-channel-id afk-timeout widget-channel-id verification-level default-message-notifications explicit-content-filter mfa-level application-id system-channel-id system-channel-flags member-count > { %constructor{$_} = %json{ S:g/ "-" /_/ } } %constructor<is-owner> = %json<owner>; %constructor<is-large> = %json<large>; %constructor<is-unavailable> = %json<unavailable>; %constructor<is-widget-enabled> = %json<widget-enabled>; return self.new(|%constructor); } } class Member { ... }; class Role { ... }; class Ban { ... }; enum MessageNotificationLevel ( <notification-all-messages notification-only-mentions> ); enum ContentFilterLevel ( <filter-disabled filter-members-without-roles filter-all-members> ); enum MFALevel ( <mfa-none mfa-elevated> ); enum VerificationLevel ( <verification-none verification-low verification-medium verification-high verification-very-high> ); has $.real handles < name icon splash owner-id permissions region afk-channel-id afk-channel-timeout is-embeddable embed-channel-id verification-level default-notification-level content-filter-level mfa-level-required application-id is-widget-enabled widget-channel-id system-channel-id joined-at is-large is-unavailable member-count create read update delete > = slack { await API::Discord::Guild::ButReal.read({:$!id, :$!api}, $!api.rest) }; multi method reify (::?CLASS:U: $data) { ButReal.from-json($data); } multi method reify (::?CLASS:D: $data) { my $r = ButReal.from-json($data); $!real = $r; } has %.roles; has @.emojis; has @.features; has @.voice-states; has @.members; has @.channels; has @.presences; submethod TWEAK { my $e = endpoint-for(self, 'list-roles'); my $roles = $!api.rest.get($e).result.body.result; %!roles = $roles.map: { $_<id> => Role.from-json($_) }; } method assign-role($user, *@role-ids) { start { my $member = self.get-member($user); $member<roles>.append: @role-ids; await self.update-member($user, { roles => $member<roles> }); } } method unassign-role($user, *@role-ids) { start { my $member = self.get-member($user); $member<roles> = $member<roles>.grep: @role-ids !~~ *; await self.update-member($user, { roles => $member<roles> }); } } multi method get-member(API::Discord::Object $user) returns Member { # The type constraint is to help selecting the multi candidate, not to # constrain it to User objects. samewith($user.real-id); } multi method get-member(Str() $user-id) returns Member { my $e = endpoint-for( self, 'get-member', :$user-id ); my $member = $.api.rest.get($e).result.body.result; $member<guild> = self; $.api.inflate-member($member); } multi method update-member(API::Discord::Object $user, %new-data) returns Promise { samewith($user.id, %new-data); } multi method update-member(Int $user-id, %new-data) returns Promise { my $e = endpoint-for( self, 'get-member', :$user-id ); $.api.rest.patch($e, body => %new-data) } multi method remove-member(API::Discord::Object $user) returns Promise { samewith($user.id); } multi method remove-member(Int $user-id) returns Promise { my $e = endpoint-for( self, 'remove-member', :$user-id ); return $.api.rest.delete($e); } method get-role($role-id) returns Role { return %.roles{$role-id}; } method get-bans() returns Array { my $e = endpoint-for( self, 'get-bans' ); my $bans = $.api.rest.get($e).result.body.result; return $bans.map({ $_<api> = $.api; Ban.from-json($_) }); } method get-ban(Int $user-id) returns Ban { my $e = endpoint-for( self, 'get-ban', :$user-id ); return $.api.rest.get($e); } method create-ban(Int $user-id, Str :$reason, Int :$delete-message-days) { my $e = endpoint-for( self, 'create-ban', :$user-id ); my $ban = Ban.new( :$user-id, |(:$reason if $reason), |(:$delete-message-days if $delete-message-days) ); # TODO - the HTTP communication stuff is a bit of a mess. The BodySerialiser # stuff should help, but not all "create" endpoints are post, so for now we # have to call put ourselves. $.api.rest.put($e, body => $ban.to-json); } method remove-ban(Int $user-id) { my $e = endpoint-for( self, 'remove-ban', :$user-id ); return $.api.rest.delete($e); } my %image-formats = JPEG => '.jpeg', WebP => '.webp', PNG => '.png', GIF => '.gif'; subset ReallyInt of Numeric where subset-is { $_.Int == $_ }; subset PowerOfTwo of Int where subset-is { log($_, 2) ~~ ReallyInt }; subset ImageSize of PowerOfTwo where subset-is 16 <= * <= 4096; subset ImageFormat of Str where subset-is * ~~ %image-formats; method icon-url( ImageSize :$desired-size, ImageFormat :$format ) { my $url = $.api.cdn-url ~ '/icons/' ~ $.id ~ '/' ~ $.icon ~ %image-formats{$format // 'PNG'}; if $desired-size { $url ~= '?size=' ~ $desired-size } return $url; } class Member does API::Discord::DataObject { has $.guild; has $.user; has $.nick; has Bool $.is-owner; has $.roles; has DateTime $.joined-at; has DateTime $.premium-since; has Bool $.is-deaf; has Bool $.is-mute; method user-id { return $.user.id; } method display-name { return $.nick || $.user.username; } method combined-permissions returns Int { $.roles.map(*.permissions).reduce(&[+|]); } method has-all-permissions(@permissions) returns Bool { return True if $.is-owner; API::Discord::Permissions::has-all-permissions(self.combined-permissions, @permissions); } method has-any-permission(@permissions) returns Bool { return True if $.is-owner; API::Discord::Permissions::has-any-permission(self.combined-permissions, @permissions); } method to-json() returns Hash { } method from-json(%json) { my %constructor = %json<nick guild>:kv; my $api = %constructor<api> = %json<_api>; %constructor<is-deaf is-mute> = %json<deaf mute>; # We discovered this user has no avatar hash for some reason, so just # let it get fetched. It's probably cached anyway. %constructor<user> = $api.get-user(%json<user><id>); %constructor<is-owner> = %constructor<guild>.owner-id == %constructor<user>.id; %constructor<joined-at> = DateTime.new(%json<joined_at>); %constructor<premium-since> = DateTime.new($_) with %json<premium_since>; %constructor<roles> = %json<roles>.map: { %json<guild>.get-role($_) }; return self.new(|%constructor); } } class Role does API::Discord::DataObject { has $.id; has $.guild; has $.name; has $.permissions; has $.color; has $.hoist; has $.mentionable; method to-json { my %self = self.Capture.hash; my %json = %self<name permissions color hoist mentionable>:kv; return %json; } method from-json (%json) { my %constructor = %json<name permissions color hoist mentionable>:kv; return self.new(|%constructor); } } class Ban does API::Discord::DataObject { has $.reason; has $.user-id; has $.delete-message-days; method to-json { my %json; %json<reason> = $_ with self.reason; %json<delete_message_days> = $_ with self.delete-message-days; return %json; } method from-json (%json) { my %constructor = %json<reason>:kv; %constructor<user-id> = %json<user><id>; return self.new(|%constructor); } } =begin pod =head1 NAME API::Discord::Guild - Colloquially known as a server =head1 DESCRIPTION Defines a guild, or server, slightly adapting the JSON object defined in the documentation at L<https://discordapp.com/developers/docs/resources/guild>. Guilds are usually created by the websocket layer, as a result of the bot user being added to the guild. However, the Discord documentation does allow for guilds to be fetched or created via the API in some circumstances. Knowing whether or not you can do this is up to the user; you can always try. =end pod =begin pod =head2 JSON fields See L<API::Discord::Object> for JSON fields discussion < id name icon splash is-owner owner-id permissions region afk-channel-id afk-channel-timeout is-embeddable embed-channel-id verification-level default-notification-level content-filter-level mfa-level-required application-id is-widget-enabled widget-channel-id system-channel-id joined-at is-large is-unavailable member-count > =end pod =begin pod =head2 Object properties See L<API::Discord::Object> for Object properties discussion < roles emojis features voice-states members channels presences > =end pod
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Discord/WebSocket.rakumod ### ---------------------------------------------------- use API::Discord::Exceptions; use API::Discord::Types; use API::Discord::WebSocket::Messages; use Cro::WebSocket::Client; use API::Discord::Debug <FROM-MODULE>; unit class API::Discord::WebSocket; #| The WebSocket URL to connect to. has $!ws-url is built is required; #| The access token. has $!token is built is required; #| A bitmask, all the way from the user has $!intents is built is required; #| The connection from Cro::WebSocket::Client.connect has $!conn; #| Session ID, set so long as we have a valid/active session. has Str $!session-id; #| The current sequence number, used so we can recover missed messages upon resumption of #| an existing session. has Int $!sequence; #| The number of connection attempts we have made. has Int $!attempt-no = 0; #| Establishes a new connection, resuming the session if applicable. Returns a Supply of the #| messages emitted on the connection, and is done when the connection ends for some reason #| (disconnect of some kind or heartbeat not acknowledged). method connection-messages(--> Supply) { $!attempt-no++; my $websocket = Cro::WebSocket::Client.new: :json; $!conn = await $websocket.connect($!ws-url); debug-say("WS connected" but WEBSOCKET); return supply { # Set to false when we send a heartbeat, and to true when the heartbeat is acknowledged. If # we don't get an acknowledgement then we know something is wrong. my Bool $heartbeat-acknowledged; whenever $!conn.messages -> $m { whenever $m.body -> $json { if $json<s> { $!sequence = $json<s>; } my $payload = $json<d>; my $event = $json<t>; # mnemonic: rtfm given ($json<op>) { when OPCODE::dispatch { if $event eq 'READY' { $!session-id = $payload<session_id>; emit API::Discord::WebSocket::Event::Ready.new(payload => $json); } else { # TODO: pick the right class! emit API::Discord::WebSocket::Event.new(payload => $json); } } when OPCODE::invalid-session { debug-say("Session invalid. Refreshing." but WEBSOCKET); $!session-id = Str; $!sequence = Int; # Docs say to wait a random amount of time between 1 and 5 # seconds, then re-auth Promise.in(4.rand + 1).then({ self!auth }); } when OPCODE::hello { self!auth; start-heartbeat($payload<heartbeat_interval> / 1000); } when OPCODE::reconnect { debug-say("reconnect" but WEBSOCKET); emit API::Discord::WebSocket::Event::Disconnected.new(payload => $json, session-id => $!session-id, last-sequence-number => $!sequence,); debug-say "Stopping message handler $!attempt-no"; done; } when OPCODE::heartbeat-ack { debug-print("♥ » " but PONG); $heartbeat-acknowledged = True; } default { debug-say("Unhandled opcode $_ ({ OPCODE($_) })" but WEBSOCKET); emit API::Discord::WebSocket::Event.new(payload => $json); } } } } whenever $!conn.closer -> $close { my $blob = await $close.body-blob; my $code = $blob.read-uint16(0, BigEndian); if $code ~~ /^ 100 . $/ { debug-say "Websocket closed, looks intentional ($code)" but WEBSOCKET; return; } debug-say("Websocket closed :( ($code)" but WEBSOCKET); emit API::Discord::WebSocket::Event::Disconnected.new: session-id => $!session-id, last-sequence-number => $!sequence; done; } sub start-heartbeat($interval) { whenever Supply.interval($interval) { # Handle missing acknowledgements. with $heartbeat-acknowledged { unless $heartbeat-acknowledged { debug-say('heartbeat lost' but HEARTBEAT); emit API::Discord::WebSocket::Event::Disconnected.new: session-id => $!session-id, last-sequence-number => $!sequence; $!conn.close; done; } } # Send heartbeat and set that we're awaiting an acknowledgement. debug-print("« ♥" but PONG); $!conn.send({ d => $!sequence, op => OPCODE::heartbeat.Int, }); $heartbeat-acknowledged = False; } } } } #| Resumes the session if there was one, or else sends the identify opcode. method !auth { debug-say("Auth..." but WEBSOCKET); if ($!session-id and $!sequence) { debug-say "Resuming session $!session-id at sequence $!sequence"; $!conn.send({ op => OPCODE::resume.Int, d => { token => $!token, session_id => $!session-id, seq => $!sequence, } }); return; } # TODO: There is a gateway bot bootstrap endpoint that tells you things like # how many shards to use. We should investigate this debug-say("New session..." but WEBSOCKET); $!conn.send({ op => OPCODE::identify.Int, d => { token => $!token, properties => { '$os' => $*PERL.Str, '$browser' => 'API::Discord', '$device' => 'API::Discord', }, shard => [0,1], intents => $!intents, } }); } method close { $!conn.close }
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Discord/HTTPResource.rakumod ### ---------------------------------------------------- use API::Discord::Endpoints; unit package API::Discord; =begin pod =head1 NAME API::Discord::JSONy - Role for objects that can be serialised to JSON API::Discord::RESTy - Role for objects that can be sent/received over REST API::Discord::HTTPResource - Role for objects that can be CRUD'd =head1 DESCRIPTION This file defines the three roles listed above. They are all related to one another but not necessarily all required at once. =head1 API::Discord::JSONy This role defines the methods C<from-json> and C<to-json> that must be implemented by the consuming class. Anything using this role can be sent to or produced by RESTy. =end pod role JSONy is export { #| Builds the object from a hash. The hash is made from the JSON, courtesy #| of Cro. method from-json (::?CLASS:U: $json) { ... } #| Turns the object into a hash. from-json(to-json($object)) should return #| the same object (or at least an equivalent copy). method to-json returns Hash { ... } } =begin pod =head1 API::Discord::RESTy[$base-url] This role defines C<send>, C<fetch>, and C<remove>, and is parameterised with a base URL. It abstracts over the top of an HTTP client, so requires C<get>, C<post>, C<put>, and C<delete> methods. It is intended to be applied to L<Cro::HTTP::Client>, so the aforementioned methods should match those. =end pod role RESTy[$base-url] is export { has $.base-url = $base-url; multi method get ($uri, %args) { callwith("$.base-url$uri", %args); } multi method get ($uri, *%args) { callwith("$.base-url$uri", |%args); } multi method post ($uri, %args) { callwith("$.base-url$uri", %args); } multi method post ($uri, *%args) { callwith("$.base-url$uri", |%args); } multi method patch ($uri, %args) { callwith("$.base-url$uri", %args); } multi method patch ($uri, *%args) { callwith("$.base-url$uri", |%args); } multi method put ($uri, %args) { callwith("$.base-url$uri", %args); } multi method put ($uri, *%args) { callwith("$.base-url$uri", |%args); } multi method delete ($uri, %args) { callwith("$.base-url$uri", %args); } multi method delete ($uri, *%args) { callwith("$.base-url$uri", |%args); } #| Sends a JSONy object to the given endpoint. Updates if the object has an #| ID; creates if it does not. method send(Str $endpoint, JSONy:D $object) returns Promise { if $object.can('self-send') { return $object.self-send($endpoint, self) } # TODO: does anything generate data such that we need to re-fetch after # creation? use Data::Dump; my $body = $object.to-json; if $object.can('id') and $object.id { say "PATCH $endpoint " ~ Dump $body if %*ENV<API_DISCORD_DEBUG>; self.patch: $endpoint, :$body; } else { say "POST $endpoint " ~ Dump $body if %*ENV<API_DISCORD_DEBUG>; self.post: $endpoint, :$body; } } #| Sends a PUT but no data required. Useful to avoid creating whole classes #| just so they can self-send method touch(Str $endpoint) returns Promise { self.put: $endpoint, body => {}; } #| Creates a JSONy object, given a full URL and the class. method fetch(Str $endpoint, JSONy:U $class, %data) returns Promise { start { my $b = await (await self.get($endpoint, %data)).body; $class.from-json($b); } } #| Deletes the thing with DELETE method remove(Str $endpoint) returns Promise { self.delete: $endpoint; } } =begin pod =head1 API::Discord::HTTPResource Represents an object that can be discovered via some HTTP mechanism. The consuming class is expected to have a hash called C<%.ENDPOINTS>, the purpose of which is to provide a set of URL path templates that can be filled in by the object being dealt with. Endpoint handling is not yet fully implemented. A gap in this process is that it does mean that in order to fetch an existing object by ID, it is necessary to create an empty object containing that ID, and then replace it with the response from C<read>, which will be a new object, fully-populated. Since all of the methods communicate via a RESTy object, it is currently necessary that the class consuming HTTPResource also consumes JSONy. =end pod role HTTPResource is export { #| Upload self, given a RESTy client. Returns a Promise that resolves to #| self. Not all resources can be created. method create(RESTy $rest) { my $endpoint = endpoint-for(self, 'create'); $rest.send($endpoint, self); } #| Returns a Promise that resolves to a constructed object of this type. Use #| named parameters to pass in the data that the C<read> endpoint requires; #| usually an ID. Finally, pass in a connected RESTy object. method read(::?CLASS:U: %data, RESTy $rest) { my $endpoint = endpoint-for(self, 'read', |%data); $rest.fetch($endpoint, self, %data); } #| Updates the resource. Must have an ID already. Returns a Promise for the #| operation. multi method update(RESTy $rest) { my $endpoint = endpoint-for(self, 'update'); $rest.send($endpoint, self); } #| Deletes the resource. Must have an ID already. Not all resources can be #| deleted. Returns a Promise. method delete(RESTy $rest) { my $endpoint = endpoint-for(self, 'delete'); $rest.remove($endpoint); } }
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Discord/Message.rakumod ### ---------------------------------------------------- use API::Discord::Object; use URI::Encode; use Object::Delayed; unit class API::Discord::Message does API::Discord::Object is export; class ButReal does API::Discord::DataObject { has $.id; has $.channel-id; has $.author-id; has $.nonce; has $.content; has $.is-tts; has $.mentions-everyone; has $.is-pinned; has $.webhook-id; has $.type; has $.reference; has $.mentions-role-ids; has $.mentions; # GET a message and receive embeds plural. SEND a message and you can only send # one. I do not know at this point how you can create multiple embeds. has $.embeds; has $.embed; # Coercions here are not yet implemented has DateTime $.timestamp; has DateTime $.edited; method new(*%args is copy) { %args<timestamp> = DateTime.new($_) with %args<timestamp>; %args<edited> = DateTime.new($_) with %args<edited>; self.bless(|%args); } method from-json (%json) returns ::?CLASS { my %constructor = %json<id nonce content type timestamp edited>:kv; %constructor<channel-id is-tts mentions-everyone is-pinned webhook-id mentions-role-ids embeds> = %json<channel_id tts mention_everyone pinned webhook_id mention_roles embeds>; %constructor<api> = %json<_api>; # Just store the ID. If we want the real author we can fetch it later. I # can't be bothered stitching this sort of thing together just to save a # few bytes. if ! %json<webhook_id> { %constructor<author-id> = %json<author><id>; } %constructor<mentions> = %json<mentions>.map(*<id>).Array; # %constructor<attachments> = $json<attachments>.map: self.create-attachment($_); # %constructor<reactions> = $json<reactions>.map: self.create-reaction($_); if %json<message_reference> { %constructor<reference> = API::Discord::Message.new( id => %json<message_reference><message_id>, channel-id => %json<message_reference><channel_id>, api => %json<_api>, ); } return self.new(|%constructor.Map); } #| Deflates the object back to JSON to send to Discord method to-json returns Hash { my %self := self.Capture.hash; my %json = %self<id nonce type timestamp>:kv; %json<edited_timestamp> = $_ with %self<edited>; # Can't send blank content but we might have embed with no content %json<content> = $_ with %self<content>; %json<tts mention_everyone pinned webhook_id mention_roles embed> = %self<is-tts mentions-everyone is-pinned webhook-id mentions-role-ids embed>; # I kinda don't want to update this I think # $.author andthen %json<author> = .to-json; for <mentions attachments reactions> -> $prop { %self{$prop} andthen %json{$prop} = [map *.to-json, $_.values] } if %self<reference> { %json<message_reference> = { message_id => %self<reference>.id, channel_id => %self<reference>.channel-id, }; } return %json; } } class Activity { enum Type ( 0 => 'join', 2 => 'spectate', 3 => 'listen', 5 => 'join-request', ); has Type $.type; has $.party-id; } class Reaction does API::Discord::DataObject { # This class is special because a) only Message uses it and b) it doesn't # use the default HTTP logic when sending. has $.emoji; has $.count; has $.i-reacted; has $.user; has $.message; method self-send(Str $endpoint, $resty) returns Promise { $resty.put: "$endpoint", body => {}; } method from-json($json) { # We added message because only the Message class calls this self.new(|$json); } method to-json { {} } } enum Type ( <default recipient-add> ); # Both id and channel id are required to fetch a message. # The Object role gives us id. has $.channel-id is required; has $.reference; has $.real handles < author-id nonce content is-tts mentions-everyone is-pinned webhook-id mentions-role-ids mentions type timestamp edited > = slack { await API::Discord::Message::ButReal.read({:$!channel-id, :$!id, :$!reference, :$!api}, $!api.rest) }; # Events from the API specifically for this message. has Supplier $!events = Supplier.new; has @.mentions-roles; # will lazy { ... } has @.attachments; # TODO: perhaps this should be emoji => count and we don't need the Reaction class. # (We can use Emoji objects as the keys if we want) has @.reactions; submethod BUILD (:$!id, :$!channel-id, :$!api, :$!reference, :$!real, *%real-properties is copy) { if $!real and %real-properties { die "Provided a real object, but also properties to make one!" } # Leave the whole hash unset if nothing else is provided (or $!real was already # provided), because it'll construct itself if necessary if %real-properties { %real-properties<channel-id> = $!channel-id; %real-properties<reference> = $!reference; $!real = ButReal.new(|%real-properties); } start react whenever $!api.events -> $e { my $e-mid = $e<d><message_id>; if $e-mid and $!id and $e-mid == $!id { $!events.emit($e); } } } multi method reify (::?CLASS:U: $data) { ButReal.from-json($data); } multi method reify (::?CLASS:D: $data) { my $r = ButReal.from-json($data); $!real = $r; } # TODO #has API::Discord::Activity $.activity; #has API::Discord::Application $.application; method events { $!events.Supply } method addressed returns Bool { self.mentions.first({ $.api.user.real-id == $_.real-id }).Bool } #| Asks the API for the Channel object. method channel { $.api.get-channel($.channel-id); } method add-reaction(Str $e is copy) { $e = uri_encode_component($e) unless $e ~~ /\:/; Reaction.new(:emoji($e), :user('@me'), :message(self)).create($.api.rest); } #| Pins this message to its channel. method pin returns Promise { self.channel(:now).pin(self) } method author { $.api.get-user($.author-id); } #| Send a reply, where the client knows the message that was replied to method reply($content) { $.channel.send-message($content, reference => self); } #| Send a message to the same channel, otherwise not linked to this message. method respond($content) { $.channel.send-message($content); } =begin pod =head1 NAME API::Discord::Message - Represents Discord message =head1 DESCRIPTION Represents a Discord message in a slightly tidier way than raw JSON. See L<https://discordapp.com/developers/docs/resources/channel#message-object>, unless it moves. Messages are usually created when the websocket sends us one. Each is associated with a Channel object. =head1 TYPES =head2 JSON fields See L<API::Discord::Object> for JSON fields discussion < id channel-id nonce content is-tts mentions-everyone is-pinned webhook-id mentions-role-ids type timestamp edited > =head2 Object accessors See L<API::Discord::Object> for Object properties discussion < channel author mentions mentions-roles attachments embeds reactions > =head1 METHODS =head2 new A Message can be constructed by providing any combination of the JSON accessors. If any of the object accessors are set, the corresponding ID(s) in the JSON set will be set, even if you passed that in too. This ensures that they will be consistent, at least until you break it on purpose. =head2 addressed Does the API user appear in the mentions array? =head2 add-reaction Provide a string containg the emoji to use. This is either a unicode emoji, or a fully-specified guild-specific emoji of the form C<$name:$id>, e.g. C<flask:502112742656835604> =end pod
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Discord/Intents.rakumod ### ---------------------------------------------------- unit module API::Discord::Intents; # This module mostly exists for the name - currently it doesn't do anything # special. We might start to use it for anything that requires domain knowledge # of how intents work enum INTENT is export ( guilds => 1 +< 0, guild-members => 1 +< 1, guild-bans => 1 +< 2, guild-emojis => 1 +< 3, guild-integrations => 1 +< 4, guild-webhooks => 1 +< 5, guild-invites => 1 +< 6, guild-voice-states => 1 +< 7, guild-presences => 1 +< 8, guild-messages => 1 +< 9, guild-message-reactions => 1 +< 10, guild-message-typing => 1 +< 11, direct-messages => 1 +< 12, direct-message-reactions=> 1 +< 13, direct-message-typing => 1 +< 14, message-content => 1 +< 15, guild-scheduled-events => 1 +< 16, auto-moderation-configuration => 1 +< 20, auto-moderation-execution => 1 +< 21, );
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Discord/Connection.rakumod ### ---------------------------------------------------- use API::Discord::Debug <FROM-MODULE>; use API::Discord::Exceptions; use API::Discord::HTTPResource; use API::Discord::Types; use API::Discord::WebSocket::Messages; use API::Discord::WebSocket; use Cro::HTTP::Client; unit class API::Discord::Connection; =begin pod =head1 NAME API::Discord::Connection - Combines a websocket and a REST client =head1 DESCRIPTION Discord sends us information over the websocket, and we send it stuff over the REST client. Mostly. This is used internally and probably of limited use otherwise. =head1 SYNOPSIS my $c = API::Discord::Connection.new: :url(wss://...), :$token, ; ... # other stuff =head1 PROPERTIES =end pod #| Websocket URL has Str $.ws-url is required; #| REST URL has Str $.rest-url is required; #| User's bot/API token has Str $.token is required; #| See discord docs on intents has Int $.intents is required; #| Allows multiple instances to run the same bot has Int $.shard = 0; has Int $.shards-max = 1; #| The Cro HTTP client used for REST-y stuff. has Cro::HTTP::Client $!rest; #| The Discord WebSocket object, which parses raw WebSocket messages into Discord #| messages, as well as handling protocol details such as sessions, sequences, and #| heartbeats. There may be many connections over the lifetime of this object. has API::Discord::WebSocket $!websocket .= new( :$!ws-url, :$!token, :$!intents, ); #| This Promise is kept when Discord has sent us a READY event has Promise $.ready = Promise.new; =begin pod =head1 METHODS =head2 new C<$.ws-url>, C<$.rest-url> and C<$.token> are required here. =end pod submethod TWEAK { # TODO: We should also take the user-agent URL and the REST URL as # constructor parameters $!rest = Cro::HTTP::Client.new( content-type => 'application/json', http => '1.1', headers => [ Authorization => 'Bot ' ~ $!token, User-agent => "DiscordBot (https://github.io/shuppet/p6-api-discord, 0.0.1)", Accept => 'application/json, */*', Connection => 'keep-alive', ] ) but RESTy[$!rest-url]; } #| A Supply of messages that are not handled by the protocol gubbins. When this is first #| tapped, it begins listening on the WebSocket for messages, manages the protocol, and #| so forth. Should there be a disconnect, a reconnect will be performed automatically. method messages returns Supply { supply { debug-say("Making initial connection" but CONNECTION); connect(); sub connect() { whenever $!websocket.connection-messages { when API::Discord::WebSocket::Event::Disconnected { debug-say("Connection lost; establishing a new one" but CONNECTION); connect(); } when API::Discord::WebSocket::Event::Ready { $!ready.keep unless $!ready; proceed; } default { emit .payload; } } } } } #| Gimme your REST client method rest { $!rest } method close { $!websocket.close }
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Discord/Endpoints.rakumod ### ---------------------------------------------------- # Not sure we're using this, and if we are, not properly. class X::API::Discord::Endpoint::NotEnoughArguments is Exception { has @.required is required; has $.endpoint is required; method message { return "You need to define {@.required} for endpoint {$.endpoint}"; } } module API::Discord::Endpoints { our %ENDPOINTS = User => { read => '/users/{id}', update => '/users/{id}', get-guilds => '/users/{id}/guilds', leave-guild => '/users/{id}/guilds', get-dms => '/users/{id}/channels', create-dm => '/users/{id}/channels', # This is OAuth2 stuff, so we probably won't use it get-connections => '/users/{id}/connections' }, Channel => { create => '/channels', read => '/channels/{id}', update => '/channels/{id}', delete => '/channels/{id}', get-messages => '/channels/{id}/messages', bulk-delete-messages => '/channels/{id}/messages/bulk-delete', edit-permissions => '/channels/{id}/permissions/{overwrite-id}', delete-permission => '/channels/{id}/permissions/{overwrite-id}', get-invites => '/channels/{id}/invites', create-invite => '/channels/{id}/invites', trigger-typing => '/channels/{id}/typing', pinned-messages => '/channels/{id}/pins', pinned-message => '/channels/{id}/pins/{message-id}', add-group-recipient => '/channels/{id}/recipients/{user-id}', remove-group-recipient => '/channels/{id}/recipients/{user-id}', }, Guild => { create => '/guilds', read => '/guilds/{id}', update => '/guilds/{id}', delete => '/guilds/{id}', get-channels => '/guilds/{id}/channels', create-channel => '/guilds/{id}/channels', get-member => '/guilds/{id}/members/{user-id}', list-members => '/guilds/{id}/members', add-member => '/guilds/{id}/members/{user-id}', modify-member => '/guilds/{id}/members/{user-id}', remove-member => '/guilds/{id}/members/{user-id}', list-roles => '/guilds/{id}/roles', add-role => '/guilds/{id}/roles', modify-role => '/guilds/{id}/roles/{role-id}', remove-role => '/guilds/{id}/roles/{role-id}', get-bans => '/guilds/{id}/bans', get-ban => '/guilds/{id}/bans/{user-id}', create-ban => '/guilds/{id}/bans/{user-id}', remove-ban => '/guilds/{id}/bans/{user-id}', get-prune-count => '/guilds/{id}/prune', begin-prune => '/guilds/{id}/prune', get-integrations => '/guilds/{id}/integrations', create-integration => '/guilds/{id}/integrations', modify-integration => '/guilds/{id}/integrations/{integration-id}', delete-integration => '/guilds/{id}/integrations/{integration-id}', sync-integration => '/guilds/{id}/integrations/{integration-id}/sync', get-embed => '/guilds/{id}/embed', modify-embed => '/guilds/{id}/embed', modify-nick => '/guilds/{id}/members/@me/nick', get-invites => '/guilds/{id}/invites', get-voice-regions => '/guilds/{id}/regions', audit-log => '/guilds/{id}/audit-logs', vanity-url => '/guilds/{id}/vanity-url', }, Message => { create => '/channels/{channel-id}/messages', read => '/channels/{channel-id}/messages/{id}', update => '/channels/{channel-id}/messages/{id}', delete => '/channels/{channel-id}/messages/{id}', }, Reaction => { create => '/channels/{message.channel-id}/messages/{message.id}/reactions/{emoji}/{user}', read => '/channels/{message.channel-id}/messages/{message.id}/reactions/{emoji}', delete => '/channels/{message.channel-id}/messages/{message.id}/reactions/{emoji}/{user}', } ; sub endpoint-for ($r, $method, *%args) is export { my $type = $r.WHAT.^name.split('::').grep({ ! /ButReal/ })[*-1]; my $e = %ENDPOINTS{$type}{$method} or die "No endpoint for $type and $method"; my @required-fields = $e ~~ m:g/ '{' <( .+? )> '}' /; for @required-fields -> $f { next if %args{$f}; #say '$f: ' ~ $f; my @f = $f.split('.'); #say '@f-split: ' ~ @f; my $val = reduce { $^a."$^b"() }, $r, |@f; %args{$f} = $val if $val; } unless %args{@required-fields}:exists.all { X::API::Discord::Endpoint::NotEnoughArguments.new( required => @required-fields, endpoint => "{$method.uc} $type" ).throw; } return S:g['{' ( .+? ) '}' ] = %args{$/[0]} given $e; } }
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Discord/Exceptions.rakumod ### ---------------------------------------------------- class X::API::Discord::Connection::Flatline is Exception {}
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Discord/Permissions.rakumod ### ---------------------------------------------------- unit package API::Discord::Permissions; enum PERMISSION is export ( CREATE_INSTANT_INVITE => 0x00000001, KICK_MEMBERS => 0x00000002, BAN_MEMBERS => 0x00000004, ADMINISTRATOR => 0x00000008, MANAGE_CHANNELS => 0x00000010, MANAGE_GUILD => 0x00000020, ADD_REACTIONS => 0x00000040, VIEW_AUDIT_LOG => 0x00000080, VIEW_CHANNEL => 0x00000400, SEND_MESSAGES => 0x00000800, SENT_TTS_MESSAGES => 0x00001000, MANAGE_MESSAGES => 0x00002000, EMBED_LINKS => 0x00004000, ATTACH_FILES => 0x00008000, READ_MESSAGE_HISTORY => 0x00010000, MENTION_EVERYONE => 0x00020000, USE_EXTERNAL_EMOJIS => 0x00040000, CONNECT => 0x00100000, SPEAK => 0x00200000, MUTE_MEMBERS => 0x00400000, DEAFEN_MEMBERS => 0x00800000, MOVE_MEMBERS => 0x01000000, USE_VAD => 0x02000000, PRIORITY_SPEAKER => 0x00000100, CHANGE_NICKNAME => 0x04000000, MANAGE_NICKNAMES => 0x08000000, MANAGE_ROLES => 0x10000000, MANAGE_WEBHOOKS => 0x20000000, MANAGE_EMOJIS => 0x40000000, ); our sub create-bitmap(@permissions) { [+|] @permissions } our sub has-all-permissions($perms, @permissions) { my $needed = create-bitmap(@permissions); my $intersection = $perms +& $needed; return $needed == $perms; } our sub has-any-permission($perms, @permissions) { return ($perms +& create-bitmap(@permissions)).Bool; }
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Discord/Debug.rakumod ### ---------------------------------------------------- use v6.d; =begin pod Debug output is silent by default. A user can activate it with: use API::Discord::Debug; Any module that want to output to $*STDERR can do so with: use API::Discord::Debug <FROM-MODULE> The subs C<debug-print> and C<debug-say> forward arguments to C<$*ERR.print> and C<$*ERR.say>. Debug output can be diverted to C<Supply>s of C<Str> with mixin roles for filtering. use API::Discord::Debug; react whenever debug-say().merge(debug-print()) { when HEARTBEAT { $*ERR.print: $_ } when CONNECTION { note now.Datetime.Str, ' ', $_ } when /your term here/ { .&do-stuff() } default {} } The sub C<debug-say-logfile> diverts output to a C<IO::Path> and forwards named arguments to C<IO::Handle.open>. use API::Discord::Debug; debug-say-logfile('/tmp/discord-bot-logfile.txt', :append); react whenever debug-print() { default {} } =end pod my $active = False; sub debug-print(|c) { $*ERR.print: |c if $active; } sub debug-say(|c) { $*ERR.say: |c if $active; } sub debug-print-supply(Supply $in? --> Supply:D) { my $result = $in // Supplier::Preserving.new; &debug-print.wrap(-> |c { $result.emit: |c }); $result.Supply } sub debug-say-supply(Supply $in? --> Supply:D) { my $result = $in // Supplier::Preserving.new; &debug-say.wrap(-> |c { $result.emit: |c }); $result.Supply } sub debug-say-logfile(IO::Path() $path, *%_) { my $loghandle = $path.open(|%_); &debug-say.wrap(-> |c { $loghandle.put: now.DateTime, ' ', |c; }); } multi sub EXPORT('FROM-MODULE') { %( '&debug-print' => &debug-print, '&debug-say' => &debug-say, ) } multi sub EXPORT() { $active = True; %( '&debug-print' => &debug-print-supply, '&debug-say' => &debug-say-supply, '&debug-say-logfile' => &debug-say-logfile, ) } role LogEventType is export {} role CONNECTION does LogEventType is export {} role WEBSOCKET does CONNECTION is export {} role HEARTBEAT does WEBSOCKET is export {} role PING does HEARTBEAT does LogEventType is export {} role PONG does HEARTBEAT does LogEventType is export {}
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Discord/Object.rakumod ### ---------------------------------------------------- use API::Discord::HTTPResource; role API::Discord::DataObject does HTTPResource does JSONy { } =begin pod =head1 API::Discord::Object =end pod role API::Discord::Object { has $.id; has $.api is required; # I don't know how to define this yet # has $.real = ...; method create { start { my $r = $.real.create($.api.rest).result.body.result; $!id = $r<id>; self; } } method update { start { await $.real.update($.api.rest); self; } } method delete { start { await $.real.delete($.api.rest); self; } } } =begin pod =head1 NAME API::Discord::Object - Base class for all the Discord things =head1 DESCRIPTION Object is a thin class that only contains the information required to populate its C<$.real> object on demand. For most objects this is C<$.id>; some will have additional data, like how Message also has channel ID. All consumers of this role will be responsible for constructing their own C<$.real> on demand. The key part here is that C<$.id> is the I<only> part that is not required, because a new object will not have an ID yet. Any other data (like channel ID) is required. The C<$.real> property must also do C<API::Discord::DataObject>. As a result, we can now handle the CRUD methods, proxy them to $.real, and populate the ID field from the response, where necessary. We then facade them so that their Promise now resolves to this outer Object and not the DataObject inside it. We don't need "read" on these objects, as that is done simply by accessing any of the properties of the C<$.real> object. =head1 API::Discord::DataObject This Role simply merges L<JSONy|API::Discord::JSONy> and L<HTTPResource|API::Discord::HTTPResource>. It is marshalled via L<API::Discord::Object>s. The purpose of this role is to be applied to classes whose structures mimic the actual JSON data returned from Discord's API. As a result they all have C<from-json> and C<to-json>. =end pod
### ---------------------------------------------------- ### -- API::Discord ### -- Licenses: BSD-3-Clause ### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Discord/WebSocket/Messages.rakumod ### ---------------------------------------------------- class API::Discord::WebSocket::Event { enum OPERATION ( <create update delete> ); has OPERATION $.operation; has $.payload; } class API::Discord::WebSocket::Event::Message is API::Discord::WebSocket::Event {} class API::Discord::WebSocket::Event::Message::Reaction is API::Discord::WebSocket::Event {} class API::Discord::WebSocket::Event::Guild is API::Discord::WebSocket::Event {} class API::Discord::WebSocket::Event::Guild::Member is API::Discord::WebSocket::Event {} class API::Discord::WebSocket::Event::Channel is API::Discord::WebSocket::Event {} class API::Discord::WebSocket::Event::Typing is API::Discord::WebSocket::Event {} class API::Discord::WebSocket::Event::Presence is API::Discord::WebSocket::Event {} class API::Discord::WebSocket::Event::Disconnected is API::Discord::WebSocket::Event { has $.session-id; has $.last-sequence-number; } class API::Discord::WebSocket::Event::Ready is API::Discord::WebSocket::Event {}
### ---------------------------------------------------- ### -- API::Perspective ### -- Licenses: BSD-3-Clause ### -- Authors: Kane 'kawaii' Valentine <[email protected]> ### -- File: META6.json ### ---------------------------------------------------- { "license": "BSD-3-Clause", "repo-type": "git", "source-url": "git://github.com/shuppet/raku-api-perspective.git", "auth": "github:shuppet", "provides": { "API::Perspective": "lib/API/Perspective.rakumod" }, "name": "API::Perspective", "depends": [ "Cro::HTTP::Client" ], "description": "Raku module for interacting with the Google Perspective API.", "perl": "6.d", "version": "0.3", "authors": [ "Kane 'kawaii' Valentine <[email protected]>" ] }
### ---------------------------------------------------- ### -- API::Perspective ### -- Licenses: BSD-3-Clause ### -- Authors: Kane 'kawaii' Valentine <[email protected]> ### -- File: LICENSE ### ---------------------------------------------------- BSD 3-Clause License Copyright (c) 2018, Shuppet Laboratories All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- API::Perspective ### -- Licenses: BSD-3-Clause ### -- Authors: Kane 'kawaii' Valentine <[email protected]> ### -- File: README.md ### ---------------------------------------------------- ![logo](https://user-images.githubusercontent.com/12242877/46341626-8f514d00-c630-11e8-9395-4b433154c5cc.png) `API::Perspective` is a Raku (formerly Perl 6) module for interacting with the [Google Perspective API](https://www.perspectiveapi.com/). ## Installation ### ... from zef ``` zef install API::Perspective ``` ### ... from source ``` git clone https://github.com/shuppet/raku-api-perspective cd raku-api-perspective/ && zef install ${PWD} ```
### ---------------------------------------------------- ### -- API::Perspective ### -- Licenses: BSD-3-Clause ### -- Authors: Kane 'kawaii' Valentine <[email protected]> ### -- File: examples/basic-test.raku ### ---------------------------------------------------- use API::Perspective; my $api = API::Perspective.new(:api-key(%*ENV<PERSPECTIVE_API_KEY>)); my MODEL @models = TOXICITY, SPAM; my $result = $api.analyze(:@models, :comment("hello my friend")); say @models Z=> $result<attributeScores>{@models}.map: *<summaryScore><value>;
### ---------------------------------------------------- ### -- API::Perspective ### -- Licenses: BSD-3-Clause ### -- Authors: Kane 'kawaii' Valentine <[email protected]> ### -- File: examples/suggest-score.raku ### ---------------------------------------------------- use API::Perspective; my $api = API::Perspective.new(:api-key(%*ENV<PERSPECTIVE_API_KEY>)); say $api.suggest-score(:model(MODEL::TOXICITY), :value(0.20), :comment("that wasn't very cash money of you, homie"));
### ---------------------------------------------------- ### -- API::Perspective ### -- Licenses: BSD-3-Clause ### -- Authors: Kane 'kawaii' Valentine <[email protected]> ### -- File: lib/API/Perspective.rakumod ### ---------------------------------------------------- unit class API::Perspective; use Cro::HTTP::Client; =begin pod =head1 NAME API::Perspective - Interface to Google's Perspective API =head1 DESCRIPTION ... =head1 SYNOPSIS use API::Perspective; my $api = API::Perspective.new(:api-key(%*ENV<PERSPECTIVE_API_KEY>)); my MODEL @models = TOXICITY, SPAM; my $result = $api.analyze(:@models, :comment("hello my friend")); say @models Z=> $result<attributeScores>{@models}.map: *<summaryScore><value>; =head1 EXPORTED SYMBOLS =head2 MODEL C<MODEL> is an enumeration of all known analysis models on the Perspective API. =end pod enum MODEL is export ( <TOXICITY SEVERE_TOXICITY TOXICITY_FAST IDENTITY_ATTACK INSULT PROFANITY SEXUALLY_EXPLICIT THREAT FLIRTATION ATTACK_ON_AUTHOR ATTACK_ON_COMMENTER INCOHERENT INFLAMMATORY LIKELY_TO_REJECT OBSCENE SPAM UNSUBSTANTIAL> ); =begin pod =head1 PROPERTIES =end pod has $.api-key; has $.api-base = 'https://commentanalyzer.googleapis.com/'; has $.api-version = 'v1alpha1'; has $.language = 'en'; has $.http-client = Cro::HTTP::Client.new(content-type => 'application/json', http => '1.1'); =begin pod =head1 METHODS =head2 analyze B<Named Arguments>: C<$comment>, C<MODEL @models> Submit a C<$comment> to the API for analysis, also specify the C<MODEL @models> you would like to use =end pod method analyze(:$comment, :@models where {all(|$_) ~~ MODEL}) { my $analysis = await $!http-client.post( $.api-base ~ $.api-version ~ "/comments:analyze?key={$.api-key}", body => { comment => { text => $comment }, languages => [$.language], requestedAttributes => %( @models.map: * => {} ) } ); return await $analysis.body; } =begin pod =head2 suggest-score B<Named Arguments>: C<$comment>, C<MODEL $model>, C<$value> Suggests a score C<$value> for C<$comment> using the model C<$model>. See L</MODEL> =end pod method suggest-score(:$comment, MODEL :$model, :$value) { my $suggestion = await $!http-client.post( $.api-base ~ $.api-version ~ "/comments:suggestscore?key={$.api-key}", body => { comment => { text => $comment }, languages => [$.language], attributeScores => { $model => { summaryScore => { value => $value }, }, }, clientToken => "API::Perspective-" ~ (10000..99999).rand.Int.Str; }, ); return await $suggestion.body; }
### ---------------------------------------------------- ### -- API::USNavalObservatory ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: META6.json ### ---------------------------------------------------- { "license": "Artistic-2.0", "source-url": "git://github.com/cbk/API-USNavalObservatory", "depends": [ "URI", "Cro::HTTP::Client", "JSON::Pretty" ], "author": "github:cbk", "provides": {"API::USNavalObservatory": "lib/API/USNavalObservatory.pm6"}, "name": "API::USNavalObservatory", "description": "Perl 6 interface to the U.S. Naval Observatory, Astronomical Applications API v2.2.0", "perl": "6.*", "version": "1.1.0", "tags": ["api"] }
### ---------------------------------------------------- ### -- API::USNavalObservatory ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: README.md ### ---------------------------------------------------- # perl6-API-USNavalObservatory [![Build Status](https://travis-ci.org/cbk/API-USNavalObservatory.svg?branch=master)](https://travis-ci.org/cbk/API-USNavalObservatory) ## SYNOPSIS This module is a simple **Perl 6** interface to the U.S. Naval Observatory, Astronomical Applications API v2.2.0 which can be found at http://aa.usno.navy.mil/data/docs/api.php You may choose to use an 8 character alphanumeric identifier in your forms or scripts. This API has a default of **"P6mod"** which is registered with the U.S. Naval Observatory as the default ID of this API. The 'AA' ID is used internally by the U.S. Naval Observatory and thus can not be used. It is recommended that you override the default `apiID` You may use any other identifier you want for `apiID`. Information about the ID and how to register your own can be found **[here](https://aa.usno.navy.mil/data/docs/api.php#id)**. #### Example: the following example creates a new **API::NavalObservatory** object called $webAgent and sets the apiID to 'MyID'. ``` my $webAgent = API::USNavalObservatory.new( apiID => "MyID" ); ``` ## Returns * For services which return text, you will receive an JSON formatted blob of text. * For services which produce a image, this API will save the .PNG file in the current working directory. (Overwriting any existing file with the same name.) ## Methods There are currently 9 methods which are used to interact with this API. The API uses UTC time for all time based calls. When crafting your method calls add the `.utc` method on the DateTime object to convert a local time to UTC. Below is a list of the current methods in this module: * Day and Night Across the Earth, Cylindrical Projection: `.cylindrical()` * Day and Night Across the Earth, Spherical Projection: `.spherical()` * Apparent Disk of the Solar System Object: `.apparentDisk()` * Phases of the Moon: `.moonPhase()` * Complete Sun and Moon Data for One Day: `.oneDayData()` * Sidereal Time: `.siderealTime()` * Solar Eclipse Calculator: `.solarEclipses()` * Religious Observances: `.observances()` * Earth Seasons and Apsides: `.seasons()` ### Day and Night Across the Earth - Cylindrical Projection Generates a cylindrical map of the Earth (similar to a Mercator projection) with daytime and nighttime areas appropriately shaded. #### Examples: The following example shows a request using a date only. ``` say $webAgent.cylindrical( :dateObj( Date.today ) ); ``` This example shows a request that uses both date and time. ``` say $webAgent.cylindrical( :dateTimeObj( DateTime.now ) ); ``` #### Return: This method returns a .png image in the current working directory. * NOTE: This will overwrite any file with the same name in the CWD. ### Day and Night Across the Earth - Spherical Projections Creates a .png image view of the Earth with daytime and nighttime areas shaded appropriately. The image generated is of the apparent disk you would see if you were in a spacecraft looking back at Earth. This method takes two named pramaters: `dateTimeObj` which is a DateTime object and view which is a View subset. * The value for `view` can be any one of the following: **moon, sun, north, south, east, west, rise, and set.** #### Example: ``` say $webAgent.spherical( :dateTimeObj( DateTime.now ), :view("sun") ); ``` #### Return: This method returns a .png image in the current working directory. * NOTE: This will overwrite any file with the same name in the CWD. ### Apparent Disk of a Solar System Object Produces an apparent disk of a solar system object oriented as if you were viewing it through a high-powered telescope. #### Example: ``` say $webAgent.apparentDisk( :dateTimeObj( DateTime.now ), :body('moon') ); ``` #### Return: This method returns a png image in the current working directory. ### Phases of the Moon Returns the dates and times of a list of primary moon phases. This method has two signatures: * One where a valid year is provided, and returns ALL moon phase data for that year. This is a un-named pramater. * One that has will take a `Date` object and a unsigned integer for the number of phases to include in the results. #### Examples: The following example shows a request for a given date and number of phases. ``` say $webAgent.moonPhase( :dateObj( Date.today() ), :numP( 5 ) ); ``` The following example shows a request for a given year. ``` say $webAgent.moonPhase( 2019 ); ``` #### Return: This method returns a JSON formatted text blob. ### Complete Sun and Moon Data for One Day Returns the rise, set, and transit times for the Sun and the Moon on the requested date at the specified location. #### Examples: The following example shows a request using date, coordinates, and time zone. ``` say $webAgent.oneDayData( :dateObj( Date.today() ), :coords( "41.98N, 12.48E" ), :tz(-6) ); ``` The following example shows a request using date amd location. ``` say $webAgent.oneDayData( :dateObj( Date.today()), :loc("San Diego, CA") ); ``` #### Return: This method returns a JSON formatted text blob. ### Sidereal Time Provides the greenwich mean and apparent sidereal time, local mean and apparent sidereal time, and the Equation of the Equinoxes for a given date & time. #### Examples: The following example shows a request using a location string. ``` say $webAgent.siderealTime( :dateTimeObj(DateTime.new( year => 2019, month => 2, day => 2, hour => 2, minute => 2, second => 1,)), :loc("Denver,CO"), :reps(90), :intvMag(5), :intvUnit('minutes') ); ``` The following example shows a request using coordinates. ``` say $webAgent.siderealTime( :dateTimeObj( DateTime.new( year => 2019, month => 2, day => 2, hour => 2, minute => 2, second => 1,)), :coords("41.98N, 12.48E"), :reps(90), :intvMag(5), :intvUnit('minutes') ); ``` #### Return: This method returns a JSON formatted text blob. ### Solar Eclipse Calculator This data service provides local circumstances for solar eclipses, and also provides a means for determining dates and types of eclipses in a given year. #### Examples: The following example shows a request using a U.S. based location (San Francisco CA) for the current day. * NOTE: Currently this module utilizes the URI::Encode, uri_encode method. Including a comma **,** in the string that is passed to uri_encode seams to produce a malformed URL which fails when passed to the API. Use a space instead of a comma for now. ``` say $webAgent.solarEclipses( :loc("San Francisco CA"), :dateObj( Date.today() ), :height(50), :format("json") ); ``` The following example shows a request using lat and long. ``` say $webAgent.solarEclipses( :coords("46.67N, 1.48E" ), :dateObj( Date.today() ), :height(50), :format("json") ); ``` The following example shows a request providing only the year in the range of 1800 to 2050. ``` say $webAgent.solarEclipses( 2019 ); ``` #### Return: All these method signatures return an JSON formatted text blob. ### Selected Religious Observances Single method to handle all three calender types; `christan, jewish, islamic` * For Christan calender, use years between 1583 and 9999. * For Jewish calender, use years between 360 and 9999. * For Islamic calender, use years between 622 and 9999. #### Example: ``` say $webAgent.observances( :year(2019), :cal('christian') ); ``` #### Return: This method returns a JSON formatted text blob. ### Julian Date Converter This data service converts dates between the Julian/Gregorian calendar and Julian date. Data will be provided for the years 4713 B.C. through A.D. 9999, or Julian dates of 0 through 5373484.5. To use the `.julianDate` method, you must provide a valid `DateTime` object and a valid Era OR an unsigned integer. This method returns a JSON text blob of the request converted into ether a Julian or calendar date. #### Examples: ``` say $webAgent.julianDate( 2457892.312674 ); ``` ``` say $webAgent.julianDate( :dateTimeObj(DateTime.now), :era('AD') ); ``` #### Return: Both of these methods returns an JSON formatted text blob. ### Earth's Seasons and Apsides #### Example: ``` say $webAgent.seasons( :year(2019), :tz(-6), :dst(False) ); ``` #### Return: This method returns a JSON formatted text blob. ## Sample code * The following example makes a new object and overrides the default apiID. Then calls the solarEclipses method with the year 2019 to find all eclipses for 2019. ``` use v6; use API::USNavalObservatory; my $webAgent = API::NavalObservatory.new( apiID => "MyID" ); my $output = $webAgent.solarEclipses( 2019 ); say $output; ``` OUTPUT: ``` { "error" : false, "year" : 2019, "apiversion" : "2.2.0", "eclipses_in_year" : [ { "event" : "Partial Solar Eclipse of 6 January 2019", "day" : 6, "year" : 2019, "month" : 1 }, { "event" : "Total Solar Eclipse of 2 July 2019", "month" : 7, "year" : 2019, "day" : 2 }, { "event" : "Annular Solar Eclipse of 26 December 2019", "month" : 12, "year" : 2019, "day" : 26 } ] } ``` ## AUTHOR * Michael, cbk on #perl6, https://github.com/cbk/
### ---------------------------------------------------- ### -- API::USNavalObservatory ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: _config.yml ### ---------------------------------------------------- theme: jekyll-theme-hacker
### ---------------------------------------------------- ### -- API::USNavalObservatory ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: .travis.yml ### ---------------------------------------------------- language: minimal services: - docker install: - docker pull jjmerelo/test-perl6 - docker images script: docker run -t --entrypoint="/bin/sh" -v $TRAVIS_BUILD_DIR:/test jjmerelo/test-perl6 -c "apk add --update --no-cache openssl-dev make build-base && zef install --deps-only . && zef test ."
### ---------------------------------------------------- ### -- API::USNavalObservatory ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: LICENCE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2015, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.L
### ---------------------------------------------------- ### -- API::USNavalObservatory ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: t/10-travis.t ### ---------------------------------------------------- use Test; use API::USNavalObservatory; ok(1); if (%*ENV<TRAVIS>) { diag "Running test on travis"; my $webAgent = API::USNavalObservatory.new; say $webAgent.perl; } done-testing();
### ---------------------------------------------------- ### -- API::USNavalObservatory ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: .idea/vcs.xml ### ---------------------------------------------------- <?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="VcsDirectoryMappings"> <mapping directory="$PROJECT_DIR$" vcs="Git" /> </component> </project>
### ---------------------------------------------------- ### -- API::USNavalObservatory ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: .idea/modules.xml ### ---------------------------------------------------- <?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/APIUSNavalObservatory.iml" filepath="$PROJECT_DIR$/APIUSNavalObservatory.iml" /> </modules> </component> </project>
### ---------------------------------------------------- ### -- API::USNavalObservatory ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: .idea/misc.xml ### ---------------------------------------------------- <?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectRootManager" version="2" project-jdk-name="Perl 6 v2018.11" project-jdk-type="Perl 6 SDK" /> </project>
### ---------------------------------------------------- ### -- ASCII::To::Uni ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:raku-community-modules", "author": "Alexander Kiryuhin", "build-depends": [ ], "depends": [ ], "description": "convert operators in Raku source files from ASCII to Unicode", "license": "Artistic-2.0", "name": "ASCII::To::Uni", "perl": "6.c", "provides": { "ASCII::To::Uni": "lib/ASCII/To/Uni.rakumod" }, "resources": [ ], "source-url": "https://github.com/raku-community-modules/ASCII-To-Uni.git", "tags": [ ], "test-depends": [ ], "version": "0.1.1" }
### ---------------------------------------------------- ### -- ASCII::To::Uni ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2016, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- ASCII::To::Uni ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: README.md ### ---------------------------------------------------- [![Actions Status](https://github.com/raku-community-modules/ASCII-To-Uni/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/ASCII-To-Uni/actions) [![Actions Status](https://github.com/raku-community-modules/ASCII-To-Uni/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/ASCII-To-Uni/actions) [![Actions Status](https://github.com/raku-community-modules/ASCII-To-Uni/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/ASCII-To-Uni/actions) NAME ==== ASCII::To::Uni - convert operators in Raku source files from ASCII to Unicode SYNOPSIS ======== ```raku use ASCII::To::Uni; convert-file($filename); ``` DESCRIPTION =========== The `ASCII::To::Uni` distribution provides a basic (and incomplete) way to convert operators in your Raku-related source files from an ASCII version to Unicode symbol version. It doesn't support some operators and has some limitations. SUBROUTINES =========== This distribution has two basic subroutines: convert-file ------------ The `convert-file` subroutine takes a file name and by default point s output to a new file with extension like `file-name.uni.xtension`. A different path can be set with the `:new-path` named argument. It can rewrite file if the named argument `:rewrite` was specified with a `True` value. However, rewriting is not recommended, since this distribution way still be buggy and can mess up your work. convert-string -------------- The `convert-string` subroutine takes read-write string and converts it accordingly to operator table. HISTORY ------- This distribution started as `Texas::To::Uni`, but since the use of the term "Texas" has been deprecated in favor of "ASCII", it felt like a good opportunity to change the name when reviving it as a Raku Community module. Note that the old name `Texas::To::Uni` is still available as a use target. AUTHOR ====== Alexander Kiryuhin COPYRIGHT AND LICENSE ===================== Copyright 2016 - 2017 Alexander Kiryuhin Copyright 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- ASCII::To::Uni ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: dist.ini ### ---------------------------------------------------- name = ASCII::To::Uni [ReadmeFromPod] filename = lib/ASCII/To/Uni.rakumod [UploadToZef] [Badges] provider = github-actions/linux.yml provider = github-actions/macos.yml provider = github-actions/windows.yml
### ---------------------------------------------------- ### -- ASCII::To::Uni ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: t/01-sanity.rakutest ### ---------------------------------------------------- use Test; use ASCII::To::Uni; plan 1; my Str $filename = 't/test-file1.raku'; my Str $new-name = 't/test-file1.uni.raku'; my Str $valid-output; LEAVE unlink $new-name; # Valid output. my $proc-v = Proc::Async.new('raku', $filename); $proc-v.stdout.tap(-> $v { $valid-output = $v; }); $proc-v.stderr.tap(-> $v { fail $v }); await $proc-v.start; convert-file($filename); # # # Converted output. my Str $converted; my $proc-c = Proc::Async.new('raku', $new-name); $proc-c.stdout.tap(-> $v { $converted = $v; }); $proc-c.stderr.tap(-> $v { fail $v }); await $proc-c.start; say $valid-output; say $converted; ok $valid-output eq $converted; # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- ASCII::To::Uni ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: t/test-file1.raku ### ---------------------------------------------------- my $secret = q:to/END/; This task is to implement a program for encryption and decryption of plaintext using the simple alphabet of the Baconian cipher or some other kind of representation of this alphabet (make anything signify anything). This example will work with anything in the ASCII range and even code! $r%_-^&*(){}+~ #=`/\';*1234567890"' END my $text = q:to/END/; Bah. It isn't really practical to use typeface changes to encode information, it is too easy to tell that there is something going on and will attract attention. Font changes with enough regularity to encode mesages relatively efficiently would need to happen so often it would be obvious that there was some kind of manipulation going on. Steganographic encryption where it is obvious that there has been some tampering with the carrier is not going to be very effective. Not that any of these implementations would hold up to serious scrutiny anyway. Anyway, here's a semi-bogus implementation that hides information in white space. The message is hidden in this paragraph of text. Yes, really. It requires a fairly modern file viewer to display (not display?) the hidden message, but that isn't too unlikely any more. It may be stretching things to call this a Bacon cipher, but I think it falls within the spirit of the task, if not the exact definition. END #' my @enc = "", "​"; my %dec = @enc.pairs.invert; sub encode ($c) { @enc[($c.ord).fmt("%07b").comb].join('') } sub hide ($msg is copy, $text) { $msg ~= @enc[0] x (0 - ($msg.chars % 8)).abs; my $head = $text.substr(0,$msg.chars div 8); my $tail = $text.substr($msg.chars div 8, *-1); ($head.comb «~» $msg.comb(/. ** 8/)).join('') ~ $tail; } sub reveal ($steg) { join '', map { :2(%dec{$_.comb}.join('')).chr }, $steg.subst( /\w | <punct> | " " | "\n" /, '', :g).comb(/. ** 7/); } my $hidden = join '', map { .&encode }, $secret.comb; my $steganography = hide $hidden, $text; say "Steganograpic message hidden in text:"; say $steganography; say '*' x 70; say "Hidden message revealed:"; say reveal $steganography;
### ---------------------------------------------------- ### -- ASCII::To::Uni ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ASCII/To/Uni.rakumod ### ---------------------------------------------------- # Special cases TODO: # "\"", "\“", # '\"', '\”', # "\"", "\„", # "「", "Q//", # "Q//", "」", my constant %default = "<<", "\«", ">>", "»", "\ *\ ", "×", "\ /\ ", "÷", "\ -\ ", "−", "\ o\ ", "∘", "=~=", "≅", "\ pi\ ", "π", "\ tau\ ", "τ", "\ e\ ", "𝑒", "Inf ", "∞", "...", "…", "\ +\ ", "⁺", "**0", "⁰", "**1", "¹", "**2", "²", "**3", "³", "**4", "⁴", "**5", "⁵", "**6", "⁶", "**7", "⁷", "**8", "⁸", "**9", "⁹", "set()", "∅", "(elem)", "∈", "!(elem)", "∉", "(cont)", "∋", "!(cont)", "∌", "(==)", "≡", "!(==)", "≢", "(<=)", "⊆", "!(<=)", "⊈", "(<)", "⊂", "!(<)", "⊄", "(>=)", "⊇", "!(>=)", "⊉", "(>)", "⊃", "!(>)", "⊅", "(<+)", "≼", "(>+)", "≽", "(|)", "∪", "(&)", "∩", "(-)", "∖", "(^)", "⊖", "(.)", "⊍", "(+)", "⊎" ; my sub convert-string(Str $source is rw, :%table = %default) is export { for %table.keys -> $ascii { $source.subst-mutate($ascii, %table{$ascii}, :g); } } my sub convert-file(Str $filename, Bool :$rewrite = False, Str :$new-path = "") is export { my Str $content = slurp $filename; convert-string($content); if $rewrite { spurt $filename, $content; say "$filename was converted.\n"; } else { if $new-path { spurt $new-path, $content; say "$filename was converted and written to $new-path"; } else { my @pieces = $filename.split('.'); # Splitting by extension, can be better. @pieces.splice(*-1, 0, "uni"); my $path = @pieces.join('.'); say $path; spurt $path, $content; say "$filename was converted and written to $path"; } } } =begin pod =head1 NAME ASCII::To::Uni - convert operators in Raku source files from ASCII to Unicode =head1 SYNOPSIS =begin code :lang<raku> use ASCII::To::Uni; convert-file($filename); =end code =head1 DESCRIPTION The C<ASCII::To::Uni> distribution provides a basic (and incomplete) way to convert operators in your Raku-related source files from an ASCII version to Unicode symbol version. It doesn't support some operators and has some limitations. =head1 SUBROUTINES This distribution has two basic subroutines: =head2 convert-file The C<convert-file> subroutine takes a file name and by default point s output to a new file with extension like C<file-name.uni.xtension>. A different path can be set with the C<:new-path> named argument. It can rewrite file if the named argument C<:rewrite> was specified with a C<True> value. However, rewriting is not recommended, since this distribution way still be buggy and can mess up your work. =head2 convert-string The C<convert-string> subroutine takes read-write string and converts it accordingly to operator table. =head2 HISTORY This distribution started as C<Texas::To::Uni>, but since the use of the term "Texas" has been deprecated in favor of "ASCII", it felt like a good opportunity to change the name when reviving it as a Raku Community module. Note that the old name C<Texas::To::Uni> is still available as a use target. =head1 AUTHOR Alexander Kiryuhin =head1 COPYRIGHT AND LICENSE Copyright 2016 - 2017 Alexander Kiryuhin Copyright 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. =end pod # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- ASN::BER ### -- Licenses: Artistic-2.0 ### -- Authors: Alexander Kiryuhin <[email protected]> ### -- File: META6.json ### ---------------------------------------------------- { "name": "ASN::BER", "description": "ASN.1 BER encoding and decoding tool", "version": "0.7.2.1", "perl": "6.c", "authors": [ "Alexander Kiryuhin <[email protected]>" ], "auth": "zef:Altai-man", "depends": [], "provides": { "ASN::Parser": "lib/ASN/Parser.pm6", "ASN::Parser::Async": "lib/ASN/Parser/Async.pm6", "ASN::Serializer": "lib/ASN/Serializer.pm6", "ASN::Serializer::Async": "lib/ASN/Serializer/Async.pm6", "ASN::Types": "lib/ASN/Types.pm6" }, "resources": [], "license": "Artistic-2.0", "source-url": "https://github.com/Altai-man/ASN-BER.git" }
### ---------------------------------------------------- ### -- ASN::BER ### -- Licenses: Artistic-2.0 ### -- Authors: Alexander Kiryuhin <[email protected]> ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- ASN::BER ### -- Licenses: Artistic-2.0 ### -- Authors: Alexander Kiryuhin <[email protected]> ### -- File: README.md ### ---------------------------------------------------- ### ASN::BER This module is designed to allow one make Raku types support encoding and decoding based on ASN.1-driven Basic Encoding Rules. #### Warnings * This is a beta release. Number of universal types is not even described and papercuts are possible. * Main driving power beneath this is a desire to avoid writing every LDAP type parsing and serializing code by hands. As a result, while some means to have more generic support of ASN.1 are being prepared, contributing code to support greater variety of ASN.1 definitions being expressed and handled correctly is appreciated. #### Synopsis ```perl6 #`[ World-Schema DEFINITIONS IMPLICIT TAGS ::= BEGIN Rocket ::= SEQUENCE { name UTF8String (SIZE(1..16)), message UTF8String DEFAULT "Hello World", fuel ENUMERATED {solid, liquid, gas}, speed CHOICE { mph [0] INTEGER, kmph [1] INTEGER } OPTIONAL, payload SEQUENCE OF UTF8String } END ] # Necessary imports use ASN::Types; use ASN::Serializer; use ASN::Parser; # ENUMERATED is expressed as enum enum Fuel <Solid Liquid Gas>; # Mark CHOICE type as ASNChoice class SpeedChoice does ASNChoice { method ASN-choice() { # Description of choice names, tags, types { mph => (1 => Int), kmph => (0 => Int) } } } # Mark our SEQUENCE as ASNSequence class Rocket does ASNSequence { has Str $.name is UTF8String; # UTF8String has Str $.message is default-value("Hello World") is UTF8String; # DEFAULT has Fuel $.fuel; # ENUMERATED has SpeedChoice $.speed is optional; # CHOICE + OPTIONAL has ASNSequenceOf[ASN::Types::UTF8String] $.payload # SEQUENCE OF UTF8String # `ASN-order` method is a single _necessary_ method # which describes an order of attributes of type (here - SEQUENCE) to be encoded/decoded method ASN-order() { <$!name $!message $!fuel $!speed $!payload> } } my $rocket = Rocket.new( name => 'Falcon', fuel => Solid, speed => SpeedChoice.new((mph => 18000)), payload => ASNSequenceOf[ASN::Types::UTF8String].new(seq => ["Car", "GPS"]) ); say ASN::Serializer.serialize($rocket, :mode(Implicit)); # for now only IMPLICIT tag schema is supported and flag is not really used # `ASN::Serializer.serialize($rocket, :debug)` - `debug` named argument enables printing of basic debugging messages # Result: Blob.new( # 0x30, 0x1B, # Outermost SEQUENCE # 0x0C, 0x06, 0x46, 0x61, 0x6C, 0x63, 0x6F, 0x6E, # NAME, MESSAGE is missing # 0x0A, 0x01, 0x00, # ENUMERATED # 0x81, 0x02, 0x46, 0x50, # CHOICE # 0x30, 0x0A, # SEQUENCE OF UTF8String # 0x0C, 0x03, 0x43, 0x61, 0x72, # UTF8String # 0x0C, 0x03, 0x47, 0x50, 0x53); # UTF8String # Will return an instance of Rocket class parsed from `$rocket-encoding-result` Buf say ASN::Parser.new(:type(Rocket)).parse($rocket-encoding-result, :mode(Implicit)); ``` #### ASN.1 "traits" handling rules The main concept is to avoid unnecessary creation of new types that just serve as envelopes for actual data and avoid boilerplate related to using such intermediate types. Hence, when possible, we try to use native types and traits. #### Tagging schema For now, encoding is done as if `DEFINITIONS IMPLICIT TAGS` is applied for an outermost ASN.1 unit (i.e. "module"). Setting of other schemes is expected to be able to work via named argument passed to `serialize`|`parse` methods, yet this is not yet implemented. #### Mapping from ASN.1 type to ASN::BER format Definitions of ASN.1 types are made by use of: * Universal types (`MessageID ::= INTEGER`) Universal types are mostly handled with Raku native types, currently implemented are: | ASN.1 type | Perl 6 type | |-----------------|--------------------------------| | BOOLEAN | Bool | | INTEGER | Int | | NULL | ASN-Null | | OCTET STRING | Blob or Str | | UTF8String | Str | | ENUMERATED | enum | | SEQUENCE | class implementing ASNSequence | | SEQUENCE OF Foo | ASNSequenceOf\[Foo\] | | SET OF Foo | ASNSetOf\[Foo\] | | CHOICE | ASNChoice | * User defined types (`LDAPDN ::= LDAPString`) If it is based on ASN.1 type, just use this underlying one; So: ``` LDAPString ::= OCTET STRING LDAPDN ::= LDAPString ``` results in ```perl6 has $.ldapdn is OctetString; # Ignore level of indirectness in type ``` One can inherit a class from `ASN::BER`'s types to make structure more strict if needed. * SEQUENCE elements (`LDAPMessage ::= SEQUENCE {...}`) Such elements are implemented as classes with `ASNSequence` role applied and `ASN-order` method implemented. They are handled correctly if nested, so `a ::= SEQUENCE { ..., b SEQUENCE {...} }` will translate `a` and include `b` as it's part, serializing the inner class instance. * SEQUENCE OF elements Such elements are implemented using `ASNSequenceOf` role with type parameter being type of sequence. * SET elements (`Foo ::= SET {}`) Not yet implemented, though typed `SET OF` can be done with: ```perl6 has ASNSetOf[Int] $.values; submethod BUILD(Set :$values) { self.bless(values => ASNSetOf[Int].new($values)) } ``` * CHOICE elements CHOICE elements are implemented by `ASNChoice` role applying. For same types tagging must be used to avoid ambiguity, it is usually done using context-specific tags. ``` A ::= SEQUENCE { ..., authentication AuthenticationChoice } AuthenticationChoice ::= CHOICE { simple [0] OCTET STRING, -- 1 and 2 reserved sasl [3] SaslCredentials } -- SaslCredentials begin with LDAPString, which is a OCTET STRING ``` becomes ``` class AuthChoice is ASNChoice { # This example depicts a CHOICE with context-specific tags being provided # For cases where tag has an APPLICATION class, see example below # We are returning a Hash which holds a description of the CHOICE structure, # (name => (tag => type)) method ASN-choice { { simple => (0 => ASN::Types::OctetString), sasl => (3 => Cro::LDAP::Authentication::SaslCredentials) } } } class A { ... has AuthChoice $.authentication; } A.new(..., authentication => (simple => "466F6F")); ``` `simple` is a key for the internal pair, which consists of a tag to use and a CHOICE option type. Another option, when there is no ambiguity, are usages of * Universal type - are handled using appropriate universal types for a choice value. * User-defined type with `APPLICATION`-wide tag. If ASN.1 has APPLICATION-wide tag declared, for example: ``` BindRequest ::= [APPLICATION 0] SEQUENCE { ... } ``` it might be expressed implementing `ASN-tag-value`: ``` class BindRequest does ASNSequence { method ASN-order {...} method ASN-tag-value { 0 } # [APPLICATION 0] } ``` In this case, when such type is used as a part of a CHOICE, internal pair of CHOICE values is replaced with just a type: ``` class ProtocolChoice does ASNChoice { method ASN-choice { { bindRequest => Cro::LDAP::Request::Bind, ... } } } class Request does ASNSequence { ... has ProtocolChoice $.protocol-op; } ``` `ASN-tag-value` method will be called and its result will be used as an APPLICATION class tag during encoding/decoding process. #### ASN.1 type traits ##### Optional Apply `is optional` trait to an attribute. ##### Default Apply `is default-value` trait to an attribute. It additionally sets `is default` trait with the same value. #### Debugging You can set environment variables `ASN_BER_PARSER_DEBUG` and `ASN_BER_SERIALIZER_DEBUG` to print parser's and serializer's debug output respectively.
### ---------------------------------------------------- ### -- ASN::BER ### -- Licenses: Artistic-2.0 ### -- Authors: Alexander Kiryuhin <[email protected]> ### -- File: t/02-octet-string.t ### ---------------------------------------------------- use Test; use ASN::Serializer; use ASN::Parser; use ASN::Types; class Rocket does ASNSequence { has $.name is OctetString; method ASN-order() { <$!name> } } my $rocket = Rocket.new(name => 'Falcon'); my $rocket-ber = Buf.new( 0x30, 0x08, 0x04, 0x06, 0x46, 0x61, 0x6C, 0x63, 0x6F, 0x6E); is-deeply ASN::Serializer.serialize($rocket, :mode(Implicit)), $rocket-ber, "Correctly serialized a Rocket in implicit mode"; my $parsed = ASN::Parser.new(type => Rocket).parse($rocket-ber, :mode(Implicit)); is $parsed.name, 'Falcon'.encode, 'Correctly parsed out Rocket'; $rocket = Rocket.new(name => Blob.new('Falcon'.encode)); is-deeply ASN::Serializer.serialize($rocket, :mode(Implicit)), $rocket-ber, "Correctly serialized a Rocket in implicit mode"; is-deeply ASN::Parser .new(type => Rocket) .parse($rocket-ber, :mode(Implicit)), $rocket, "Correctly parsed a Rocket in implicit mode"; done-testing;
### ---------------------------------------------------- ### -- ASN::BER ### -- Licenses: Artistic-2.0 ### -- Authors: Alexander Kiryuhin <[email protected]> ### -- File: t/03-long-integers.t ### ---------------------------------------------------- use ASN::Parser; use Test; my $buf = Buf.new(255, 255, 255, 128); is ASN::Parser.parse($buf, Int), -128, 'Parsing of a padded negative value works'; use ASN::Serializer; my @nums = 0, 127, 128, 256, -128, -129; my @results = (Buf.new(0x02, 0x01, 0x00), Buf.new(0x02, 0x01, 0x7F), Buf.new(0x02, 0x02, 0x00, 0x80), Buf.new(0x02, 0x02, 0x01, 0x00), Buf.new(0x02, 0x01, 0x80), Buf.new(0x02, 0x02, 0xFF, 0x7F)); for @nums Z @results { is-deeply $_[1], ASN::Serializer.serialize($_[0]), "Can serialize $_[0].raku() into $_[1].raku()"; } done-testing;
### ---------------------------------------------------- ### -- ASN::BER ### -- Licenses: Artistic-2.0 ### -- Authors: Alexander Kiryuhin <[email protected]> ### -- File: t/00-sanity.t ### ---------------------------------------------------- use ASN::Types; use ASN::Serializer; use ASN::Parser; use Test; enum Fuel <Solid Liquid Gas>; class SpeedChoice does ASNChoice { method ASN-choice() { { mph => (1 => Int), kmph => (0 => Int) } } } class Rocket does ASNSequence { has Str $.name is UTF8String; has Str $.message is UTF8String is default-value("Hello World") is optional; has Fuel $.fuel; has SpeedChoice $.speed is optional; has ASNSequenceOf[ASN::Types::UTF8String] $.payload; method ASN-order() { <$!name $!message $!fuel $!speed $!payload> } } # (30 1B - universal, complex, sequence(16) # (0C 06 - UTF8String type # (46 61 6C, 63 6F 6E - fal,con)) # (0A 01 (00 fuel)) - ENUMERATION type # (81 02 <- 80 + tag set # (mph 46 50 (== 18000))) - context-specific, simple, 0 because of enum index # (30 0A - universal, complex, sequence(16) # (0C 03 (43 61 72)) - <- UTF8String type # (0C 03 (47 50 53)) - <- UTF8String type # ) # ) my $rocket-ber = Buf.new( 0x30, 0x1B, 0x0C, 0x06, 0x46, 0x61, 0x6C, 0x63, 0x6F, 0x6E, 0x0A, 0x01, 0x00, 0x81, 0x02, 0x46, 0x50, 0x30, 0x0A, 0x0C, 0x03, 0x43, 0x61, 0x72, 0x0C, 0x03, 0x47, 0x50, 0x53); my $rocket = Rocket.new( name => 'Falcon', fuel => Solid, speed => SpeedChoice.new((mph => 18000)), payload => ASNSequenceOf[ASN::Types::UTF8String].new(seq => ["Car", "GPS"]) ); is-deeply ASN::Serializer.serialize($rocket, :mode(Implicit)), $rocket-ber, "Correctly serialized a Rocket in implicit mode"; is-deeply ASN::Parser .new(type => Rocket) .parse($rocket-ber, :mode(Implicit)), $rocket, "Correctly parsed a Rocket in implicit mode"; class LongSequence does ASNSequence { has Str $.long-value is UTF8String; method ASN-order { <$!long-value> } } my $sequence = LongSequence.new(long-value => "Falcon" x 101); my $long-value-ber = Blob.new(0x30, 0x82, 0x02, 0x62, 0x0C, 0x82, 0x02, 0x5E, |("Falcon" x 101).encode); is-deeply ASN::Serializer.serialize($sequence, :mode(Implicit))[0..30], $long-value-ber[0..30], "Correctly encode long defined length"; is-deeply ASN::Parser .new(type => LongSequence) .parse($long-value-ber), $sequence, "Correctly decode long defined length"; done-testing;
### ---------------------------------------------------- ### -- ASN::BER ### -- Licenses: Artistic-2.0 ### -- Authors: Alexander Kiryuhin <[email protected]> ### -- File: t/01-async.t ### ---------------------------------------------------- use ASN::Types; use ASN::Parser::Async; use Test; enum Fuel <Solid Liquid Gas>; class SpeedChoice does ASNChoice { method ASN-choice() { { mph => (1 => Int), kmph => (0 => Int) } } } class Rocket does ASNSequence { has Str $.name is UTF8String; has Str $.message is UTF8String is default-value("Hello World") is optional; has Fuel $.fuel; has SpeedChoice $.speed is optional; has ASNSequenceOf[ASN::Types::UTF8String] $.payload; method ASN-order() { <$!name $!message $!fuel $!speed $!payload> } } my $one-rocket-ber = Buf.new( 0x30, 0x1B, 0x0C, 0x06, 0x46, 0x61, 0x6C, 0x63, 0x6F, 0x6E, 0x0A, 0x01, 0x00, 0x81, 0x02, 0x46, 0x50, 0x30, 0x0A, 0x0C, 0x03, 0x43, 0x61, 0x72, 0x0C, 0x03, 0x47, 0x50, 0x53); my $one-and-a-half = $one-rocket-ber ~ Buf.new( 0x30, 0x1B, 0x0C, 0x06, 0x46, 0x61, 0x6C, 0x63, 0x6F, 0x6E, 0x0A, 0x01, 0x00, 0x81, 0x02, 0x46, 0x50, 0x30, 0x0A, 0x0C, 0x03, 0x43, 0x61, 0x72, 0x0C, 0x03, 0x47, 0x50); # Second one my $parser = ASN::Parser::Async.new(type => Rocket); my $counter = 0; my $p = Promise.new; $parser.values.tap({ $counter++; $p.keep if $counter ~~ 3 }); $parser.process($one-and-a-half); $parser.process(Buf.new(0x53)); my $long-rocket-ber = Buf.new( 0x30, 0x82, 0x01, 0x1F, # tag and length ) ~ Buf.new(0x0C, 0x82, 0x01, 0x08) ~ ([~] ("Falcon".encode xx 44)) ~ Buf.new( 0x0A, 0x01, 0x00, 0x81, 0x02, 0x46, 0x50, 0x30, 0x0A, 0x0C, 0x03, 0x43, 0x61, 0x72, 0x0C, 0x03, 0x47, 0x50, 0x53); # send a long rocket buf byte-by-byte to ensure we can # parse it however e.g. the network # can split it $parser.process(Buf.new($_)) for @$long-rocket-ber; await Promise.anyof([$p, Promise.in(5)]); $parser.close; ok $p.status ~~ Kept, "Parsed three rockets"; done-testing;
### ---------------------------------------------------- ### -- ASN::Grammar ### -- Licenses: Artistic-2.0 ### -- Authors: Alexander Kiryuhin <[email protected]> ### -- File: META6.json ### ---------------------------------------------------- { "name": "ASN::Grammar", "description": "A grammar to parse subset of ASN.1", "version": "0.3.5", "perl": "6.c", "authors": [ "Alexander Kiryuhin <[email protected]>" ], "auth": "zef:Altai-man", "depends": [], "provides": { "ASN::Grammar": "lib/ASN/Grammar.pm6" }, "resources": [], "license": "Artistic-2.0", "source-url": "https://github.com/Altai-man/ASN-Grammar.git" }
### ---------------------------------------------------- ### -- ASN::Grammar ### -- Licenses: Artistic-2.0 ### -- Authors: Alexander Kiryuhin <[email protected]> ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- ASN::Grammar ### -- Licenses: Artistic-2.0 ### -- Authors: Alexander Kiryuhin <[email protected]> ### -- File: README.md ### ---------------------------------------------------- ### ASN::Grammar This module contains a grammar for parsing [ASN.1](https://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One) specification files. #### Warnings * The module was initially started with need to parse LDAP specification, so parts of ASN.1 grammar specification were deliberately omitted. However, Pull Requests with additional rules or fixes will be gladly accepted. #### Synopsis ```perl6 my $spec = q:to/SPECEND/; WorldSchema DEFINITIONS IMPLICIT TAGS ::= BEGIN Rocket ::= SEQUENCE { name UTF8String, message UTF8String DEFAULT "Hello World", fuel ENUMERATED { solid(0), liquid(1), gas(2) }, speed CHOICE { mph [0] INTEGER, kmph [1] INTEGER } OPTIONAL, payload SEQUENCE OF UTF8String } END SPECEND use ASN::Grammar; # ASN::Module represents ASN.1 module my $module = parse-ASN($spec); say $module.name; # WorldSchema say $module.schema; # IMPLICIT # TypeAssignment and ValueAssignment represent top-level ASN.1 custom definitions my ASN::TypeAssignment $type = $module.types[0]; say $type.name; # Rocket my ASN::RawType $rocket-type = $type.type; say $rocket-type.type; # 'SEQUENCE' # `.params` method returns a hash of various # information about type, in this case, # only `fields` key that returns descriptions # of complex type (SEQUENCE) components is present for $rocket-type.params<fields><> -> $field { say $field; } # Code above results in: # Field `name` of type `UTF8String`, no parameters # ASN::RawType.new(name => "name", type => "UTF8String", params => {}) # Field `message` of type `UTF8String`, defaults to `Hello World` # ASN::RawType.new(name => "message", type => "UTF8String", params => {:default("\"Hello World\"")}) # Field `fuel` of type `ENUMERATED`, # has options presented as hash by `defs`(definitions) key # ASN::RawType.new(name => "fuel", type => "ENUMERATED", params => {:defs(${:gas(2), :liquid(1), :solid(0)})}) # Field `speed` of type `CHOICE`, has `optional` flag in params, # has choices exposed as a mapping of a textual key into ASN::Tag class and integer value # ASN::RawType.new(name => "speed", type => "CHOICE", params => {:choices(${:kmph((ASN::Tag.new(class => "CONTEXT-SPECIFIC", value => 1)) => "INTEGER"), :mph((ASN::Tag.new(class => "CONTEXT-SPECIFIC", value => 0)) => "INTEGER")}), :optional}) # Field `payload` of type `SEQUENCE OF` with `of` parameter that represents type of elements as ASN::RawType # ASN::RawType.new(name => "payload", type => "SEQUENCE OF", params => {:of(ASN::RawType.new(name => "UTF8String", type => "UTF8String", params => {}))}) ``` #### Room for improvement * Value definition part of ASN.1 * Various spacing/newline variants * Fixes
### ---------------------------------------------------- ### -- ASN::Grammar ### -- Licenses: Artistic-2.0 ### -- Authors: Alexander Kiryuhin <[email protected]> ### -- File: t/00-sanity.t ### ---------------------------------------------------- use ASN::Grammar; use Test; my $ldap-asn = q:to/LDAPEND/; -- from http://www.research.ibm.com/trl/projects/xml/xss4j/data/asn1/grammars/ldap.asn Lightweight-Directory-Access-Protocol-V3 DEFINITIONS IMPLICIT TAGS ::= BEGIN LDAPMessage ::= SEQUENCE { messageID MessageID, protocolOp CHOICE { bindRequest BindRequest, bindResponse BindResponse, unbindRequest UnbindRequest, searchRequest SearchRequest, searchResEntry SearchResultEntry, searchResDone SearchResultDone, searchResRef SearchResultReference, modifyRequest ModifyRequest, modifyResponse ModifyResponse, addRequest AddRequest, addResponse AddResponse, delRequest DelRequest, delResponse DelResponse, modDNRequest ModifyDNRequest, modDNResponse ModifyDNResponse, compareRequest CompareRequest, compareResponse CompareResponse, abandonRequest AbandonRequest, extendedReq ExtendedRequest, extendedResp ExtendedResponse }, controls [0] Controls OPTIONAL } MessageID ::= INTEGER (0 .. maxInt) maxInt INTEGER ::= 2147483647 -- (2^^31 - 1) -- LDAPString ::= OCTET STRING LDAPOID ::= OCTET STRING LDAPDN ::= LDAPString RelativeLDAPDN ::= LDAPString AttributeType ::= LDAPString AttributeDescription ::= LDAPString AttributeDescriptionList ::= SEQUENCE OF AttributeDescription AttributeValue ::= OCTET STRING AttributeValueAssertion ::= SEQUENCE { attributeDesc AttributeDescription, assertionValue AssertionValue } AssertionValue ::= OCTET STRING Attribute ::= SEQUENCE { type AttributeDescription, vals SET OF AttributeValue } MatchingRuleId ::= LDAPString LDAPResult ::= SEQUENCE { resultCode ENUMERATED { success (0), operationsError (1), protocolError (2), timeLimitExceeded (3), sizeLimitExceeded (4), compareFalse (5), compareTrue (6), authMethodNotSupported (7), strongAuthRequired (8), -- 9 reserved -- referral (10), -- new adminLimitExceeded (11), -- new unavailableCriticalExtension (12), -- new confidentialityRequired (13), -- new saslBindInProgress (14), -- new noSuchAttribute (16), undefinedAttributeType (17), inappropriateMatching (18), constraintViolation (19), attributeOrValueExists (20), invalidAttributeSyntax (21), -- 22-31 unused -- noSuchObject (32), aliasProblem (33), invalidDNSyntax (34), -- 35 reserved for undefined isLeaf -- aliasDereferencingProblem (36), -- 37-47 unused -- inappropriateAuthentication (48), invalidCredentials (49), insufficientAccessRights (50), busy (51), unavailable (52), unwillingToPerform (53), loopDetect (54), -- 55-63 unused -- namingViolation (64), objectClassViolation (65), notAllowedOnNonLeaf (66), notAllowedOnRDN (67), entryAlreadyExists (68), objectClassModsProhibited (69), -- 70 reserved for CLDAP -- affectsMultipleDSAs (71), -- new -- 72-79 unused -- other (80) }, -- 81-90 reserved for APIs -- matchedDN LDAPDN, errorMessage LDAPString, referral [3] Referral OPTIONAL } Referral ::= SEQUENCE OF LDAPURL LDAPURL ::= LDAPString -- limited to characters permitted in URLs Controls ::= SEQUENCE OF Control Control ::= SEQUENCE { controlType LDAPOID, criticality BOOLEAN DEFAULT FALSE, controlValue OCTET STRING OPTIONAL } BindRequest ::= [APPLICATION 0] SEQUENCE { version INTEGER (1 .. 127), name LDAPDN, authentication AuthenticationChoice } AuthenticationChoice ::= CHOICE { simple [0] OCTET STRING, -- 1 and 2 reserved sasl [3] SaslCredentials } SaslCredentials ::= SEQUENCE { mechanism LDAPString, credentials OCTET STRING OPTIONAL } BindResponse ::= [APPLICATION 1] SEQUENCE { resultCode ENUMERATED { success (0), operationsError (1), protocolError (2), timeLimitExceeded (3), sizeLimitExceeded (4), compareFalse (5), compareTrue (6), authMethodNotSupported (7), strongAuthRequired (8), -- 9 reserved -- referral (10), -- new adminLimitExceeded (11), -- new unavailableCriticalExtension (12), -- new confidentialityRequired (13), -- new saslBindInProgress (14), -- new noSuchAttribute (16), undefinedAttributeType (17), inappropriateMatching (18), constraintViolation (19), attributeOrValueExists (20), invalidAttributeSyntax (21), -- 22-31 unused -- noSuchObject (32), aliasProblem (33), invalidDNSyntax (34), -- 35 reserved for undefined isLeaf -- aliasDereferencingProblem (36), -- 37-47 unused -- inappropriateAuthentication (48), invalidCredentials (49), insufficientAccessRights (50), busy (51), unavailable (52), unwillingToPerform (53), loopDetect (54), -- 55-63 unused -- namingViolation (64), objectClassViolation (65), notAllowedOnNonLeaf (66), notAllowedOnRDN (67), entryAlreadyExists (68), objectClassModsProhibited (69), -- 70 reserved for CLDAP -- affectsMultipleDSAs (71), -- new -- 72-79 unused -- other (80) }, -- 81-90 reserved for APIs -- matchedDN LDAPDN, errorMessage LDAPString, referral [3] Referral OPTIONAL, -- COMPONENTS OF LDAPResult, serverSaslCreds [7] OCTET STRING OPTIONAL } UnbindRequest ::= [APPLICATION 2] NULL SearchRequest ::= [APPLICATION 3] SEQUENCE { baseObject LDAPDN, scope ENUMERATED { baseObject (0), singleLevel (1), wholeSubtree (2) }, derefAliases ENUMERATED { neverDerefAliases (0), derefInSearching (1), derefFindingBaseObj (2), derefAlways (3) }, sizeLimit INTEGER (0 .. maxInt), timeLimit INTEGER (0 .. maxInt), typesOnly BOOLEAN, filter Filter, attributes AttributeDescriptionList } Filter ::= CHOICE { and [0] SET OF Filter, or [1] SET OF Filter, not [2] Filter, equalityMatch [3] AttributeValueAssertion, substrings [4] SubstringFilter, greaterOrEqual [5] AttributeValueAssertion, lessOrEqual [6] AttributeValueAssertion, present [7] AttributeDescription, approxMatch [8] AttributeValueAssertion, extensibleMatch [9] MatchingRuleAssertion } SubstringFilter ::= SEQUENCE { type AttributeDescription, -- at least one must be present substrings SEQUENCE OF CHOICE { initial [0] LDAPString, any [1] LDAPString, final [2] LDAPString } } MatchingRuleAssertion ::= SEQUENCE { matchingRule [1] MatchingRuleId OPTIONAL, type [2] AttributeDescription OPTIONAL, matchValue [3] AssertionValue, dnAttributes [4] BOOLEAN DEFAULT FALSE } SearchResultEntry ::= [APPLICATION 4] SEQUENCE { objectName LDAPDN, attributes PartialAttributeList } PartialAttributeList ::= SEQUENCE OF SEQUENCE { type AttributeDescription, vals SET OF AttributeValue } SearchResultReference ::= [APPLICATION 19] SEQUENCE OF LDAPURL SearchResultDone ::= [APPLICATION 5] LDAPResult ModifyRequest ::= [APPLICATION 6] SEQUENCE { object LDAPDN, modification SEQUENCE OF SEQUENCE { operation ENUMERATED { add (0), delete (1), replace (2) }, modification AttributeTypeAndValues } } AttributeTypeAndValues ::= SEQUENCE { type AttributeDescription, vals SET OF AttributeValue } ModifyResponse ::= [APPLICATION 7] LDAPResult AddRequest ::= [APPLICATION 8] SEQUENCE { entry LDAPDN, attributes AttributeList } AttributeList ::= SEQUENCE OF SEQUENCE { type AttributeDescription, vals SET OF AttributeValue } AddResponse ::= [APPLICATION 9] LDAPResult DelRequest ::= [APPLICATION 10] LDAPDN DelResponse ::= [APPLICATION 11] LDAPResult ModifyDNRequest ::= [APPLICATION 12] SEQUENCE { entry LDAPDN, newrdn RelativeLDAPDN, deleteoldrdn BOOLEAN, newSuperior [0] LDAPDN OPTIONAL } ModifyDNResponse ::= [APPLICATION 13] LDAPResult CompareRequest ::= [APPLICATION 14] SEQUENCE { entry LDAPDN, ava AttributeValueAssertion } CompareResponse ::= [APPLICATION 15] LDAPResult AbandonRequest ::= [APPLICATION 16] MessageID ExtendedRequest ::= [APPLICATION 23] SEQUENCE { requestName [0] LDAPOID, requestValue [1] OCTET STRING OPTIONAL } ExtendedResponse ::= [APPLICATION 24] SEQUENCE { resultCode ENUMERATED { success (0), operationsError (1), protocolError (2), timeLimitExceeded (3), sizeLimitExceeded (4), compareFalse (5), compareTrue (6), authMethodNotSupported (7), strongAuthRequired (8), -- 9 reserved -- referral (10), -- new adminLimitExceeded (11), -- new unavailableCriticalExtension (12), -- new confidentialityRequired (13), -- new saslBindInProgress (14), -- new noSuchAttribute (16), undefinedAttributeType (17), inappropriateMatching (18), constraintViolation (19), attributeOrValueExists (20), invalidAttributeSyntax (21), -- 22-31 unused -- noSuchObject (32), aliasProblem (33), invalidDNSyntax (34), -- 35 reserved for undefined isLeaf -- aliasDereferencingProblem (36), -- 37-47 unused -- inappropriateAuthentication (48), invalidCredentials (49), insufficientAccessRights (50), busy (51), unavailable (52), unwillingToPerform (53), loopDetect (54), -- 55-63 unused -- namingViolation (64), objectClassViolation (65), notAllowedOnNonLeaf (66), notAllowedOnRDN (67), entryAlreadyExists (68), objectClassModsProhibited (69), -- 70 reserved for CLDAP -- affectsMultipleDSAs (71), -- new -- 72-79 unused -- other (80) }, -- 81-90 reserved for APIs -- matchedDN LDAPDN, errorMessage LDAPString, referral [3] Referral OPTIONAL, -- COMPONENTS OF LDAPResult, responseName [10] LDAPOID OPTIONAL, response [11] OCTET STRING OPTIONAL } END LDAPEND my $ldap = parse-ASN($ldap-asn); say $ldap; isa-ok $ldap, ASN::Module, 'LDAP spec is parsed'; is 'Lightweight-Directory-Access-Protocol-V3', $ldap.name, 'Name is parsed'; is 'IMPLICIT', $ldap.schema, 'Schema is parsed'; is $ldap.types.elems, 48, 'All types are parsed'; my $values = $ldap.types.grep(* ~~ ASN::ValueAssignment); is $values.elems, 1, 'One value is parsed'; is $values[0].name, 'maxInt', 'Value type name is parsed'; is $values[0].type, 'INTEGER', 'Value type type is parsed'; is $values[0].value, 2147483647, 'Value type value is parsed'; done-testing;
### ---------------------------------------------------- ### -- ASN::META ### -- Licenses: Artistic-2.0 ### -- Authors: Alexander Kiryuhin <[email protected]> ### -- File: META6.json ### ---------------------------------------------------- { "name": "ASN::META", "description": "A MOP-based compile-time ASN.1 spec evaluator", "version": "0.5.2", "perl": "6.c", "authors": [ "Alexander Kiryuhin <[email protected]>" ], "auth": "zef:Altai-man", "depends": [ "ASN::Grammar", "ASN::BER", "Type::EnumHOW" ], "provides": { "ASN::META": "lib/ASN/META.pm6", "ASN::META::Types": "lib/ASN/META/Types.pm6" }, "resources": [], "license": "Artistic-2.0", "source-url": "https://github.com/Altai-man/ASN-META.git" }
### ---------------------------------------------------- ### -- ASN::META ### -- Licenses: Artistic-2.0 ### -- Authors: Alexander Kiryuhin <[email protected]> ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- ASN::META ### -- Licenses: Artistic-2.0 ### -- Authors: Alexander Kiryuhin <[email protected]> ### -- File: README.md ### ---------------------------------------------------- ### ASN::META Experimental Raku module that is able to compile [ASN.1](https://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One) specification into set of Raku types. #### What ASN::META does not? * It does not generate Raku code (at least, textual form). * The module knows nothing about ASN.1 encoding means, it purely generates Raku types. For this purpose a separate module may be used. Currently, goal is to have full compatibility with [ASN::BER](https://github.com/Altai-man/ASN-BER) module. #### What ASN::META does? Main workflow is as follows: * A specification is passed to ASN::META on module `use` * (internally, `ASN::Grammar` is used to parse the specification) * ASN::META uses parsed specification to generate appropriate types with [MOP](https://docs.perl6.org/language/mop) * Generated types for particular ASN.1 specification are precompiled and exported #### What it does? #### Synopsis ```perl6 # In file `schema.asn`: WorldSchema DEFINITIONS IMPLICIT TAGS ::= BEGIN Rocket ::= SEQUENCE { name UTF8String, message UTF8String DEFAULT "Hello World", fuel ENUMERATED { solid(0), liquid(1), gas(2) }, speed CHOICE { mph [0] INTEGER, kmph [1] INTEGER } OPTIONAL, payload SEQUENCE OF UTF8String } END # In file `User.pm6`: # Note usage of BEGIN block to gather file's content at compile time use ASN::META BEGIN [ 'file', slurp 'schema.asn' }; # In case of re-compilation on dependency change, package User may be # re-built from the place where local paths are useless, in this case use %?RESOURCES: # `use ASN::META BEGIN { 'file', slurp %?RESOURCES<schema.asn> }` # `Rocket` type is exported by ASN::META my Rocket $rocket = Rocket.new(name => 'Rocker', :fuel(solid), speed => Speed.new((mph => 9001)), payload => Array[Str].new('A', 'B', 'C')); # As well as inner types being promoted to top level: say Fuel; # generated enum say solid; # value of this enum, (solid ~~ Fuel) == true say Speed; # Generated type based on ASNChoice from ASN::BER ```
### ---------------------------------------------------- ### -- ASN::META ### -- Licenses: Artistic-2.0 ### -- Authors: Alexander Kiryuhin <[email protected]> ### -- File: t/01-recursive-type.t ### ---------------------------------------------------- use ASN::META BEGIN { 'file', slurp 't/test2.asn' }; use Test; ok Filter.new((not => Filter.new((number => 15)))).defined, "Recursive type is defined"; ok A.new(b => Filter.new((number => 15))), "Parent reference is updated"; ok Top.new(a => A.new(b => Filter.new((number => 15)))), "Grand parent reference is updated"; done-testing;
### ---------------------------------------------------- ### -- ASN::META ### -- Licenses: Artistic-2.0 ### -- Authors: Alexander Kiryuhin <[email protected]> ### -- File: t/00-sanity.t ### ---------------------------------------------------- use ASN::META BEGIN { 'file', slurp 't/test.asn' }; use ASN::Types; use Test; my Rocket $rocket = Rocket.new(name => 'Rocker', :fuel(solid), speed => Speed.new((mph => 9001)), payload => ASNSequenceOf[Str].new(seq => <A B C>)); ok $rocket.speed ~~ Speed, "Subtype enum is generated"; is-deeply Speed.ASN-choice, {kmph => 1 => Int, mph => 0 => Int}, "ASN-choice is added"; is-deeply $rocket.speed.choice-value, (mph => 9001), "Choice value is correct"; ok solid ~~ Fuel, "Enum value is part of Enum"; nok Fuel ~~ solid, "Enum value is not exactly enum"; is $rocket.fuel, solid, "Enum is generated"; is-deeply $rocket.payload.seq, ('A', 'B', 'C'), "Payload is loaded"; is $rocket.message, '"Hello World"', 'Default message works'; done-testing;
### ---------------------------------------------------- ### -- ASTQuery ### -- Licenses: Artistic-2.0 ### -- Authors: Fernando Corrêa de Oliveira ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:FCO", "authors": [ "Fernando Corrêa de Oliveira" ], "build-depends": [ ], "depends": [ ], "description": "Query and manipulate Raku’s Abstract Syntax Trees (RakuAST) with an expressive syntax", "license": "Artistic-2.0", "name": "ASTQuery", "perl": "6.d", "provides": { "ASTQuery": "lib/ASTQuery.rakumod", "ASTQuery::Actions": "lib/ASTQuery/Actions.rakumod", "ASTQuery::Grammar": "lib/ASTQuery/Grammar.rakumod", "ASTQuery::HighLighter": "lib/ASTQuery/HighLighter.rakumod", "ASTQuery::Match": "lib/ASTQuery/Match.rakumod", "ASTQuery::Matcher": "lib/ASTQuery/Matcher.rakumod" }, "resources": [ ], "source-url": "https://github.com/FCO/ASTQuery.git", "tags": [ ], "test-depends": [ ], "version": "0.0.3" }
### ---------------------------------------------------- ### -- ASTQuery ### -- Licenses: Artistic-2.0 ### -- Authors: Fernando Corrêa de Oliveira ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- ASTQuery ### -- Licenses: Artistic-2.0 ### -- Authors: Fernando Corrêa de Oliveira ### -- File: README.md ### ---------------------------------------------------- [![Actions Status](https://github.com/FCO/ASTQuery/actions/workflows/test.yml/badge.svg)](https://github.com/FCO/ASTQuery/actions) NAME ==== ASTQuery - Query and manipulate Raku’s Abstract Syntax Trees (RakuAST) with an expressive syntax SYNOPSIS ======== ```raku use ASTQuery; # Sample Raku code my $code = q{ for ^10 { if $_ %% 2 { say $_ * 3; } } }; # Generate the AST my $ast = $code.AST; # Example 1: Find 'apply-op' nodes where left operand is 1 and right operand is 3 my $result1 = $ast.&ast-query('.apply-op[left=1, right=3]'); say $result1.list; # Outputs matching nodes ``` Output ------ ```raku [ RakuAST::ApplyInfix.new( left => RakuAST::IntLiteral.new(1), infix => RakuAST::Infix.new("*"), right => RakuAST::IntLiteral.new(3) ) ] ``` DESCRIPTION =========== ASTQuery simplifies querying and manipulating Raku’s ASTs using a powerful query language. It allows precise selection of nodes and relationships, enabling effective code analysis and transformation. Key Features ------------ * Expressive Query Syntax: Define complex queries to match specific AST nodes. * Node Relationships: Use operators to specify parent-child and ancestor-descendant relationships. * Named Captures: Capture matched nodes for easy retrieval. * AST Manipulation: Modify the AST for code transformations and refactoring. QUERY LANGUAGE SYNTAX ===================== Node Description ---------------- Format: `RakuAST::Class::Name.group#id[attr1, attr2=attrvalue]$name` Components: * `RakuAST::Class::Name`: (Optional) Full class name. * `.group`: (Optional) Node group (predefined). * `#id`: (Optional) Identifier attribute. * `[attributes]`: (Optional) Attributes to match. * `$name`: (Optional) Capture name. Note: Use only one $name per node. Operators --------- * `>` : Left node has the right node as a child. * `<` : Right node is the parent of the left node. * `>>>`: Left node has the right node as a descendant (any nodes can be between them). * `>>`: Left node has the right node as a descendant, with only ignorable nodes in between. * `<<<`: Right node is an ancestor of the left node (any nodes can be between them). * `<<`: Right node is an ancestor of the left node, with only ignorable nodes in between. Note: The space operator is no longer used. Ignorable Nodes --------------- Nodes skipped by `>>` and `<<` operators: * `RakuAST::Block` * `RakuAST::Blockoid` * `RakuAST::StatementList` * `RakuAST::Statement::Expression` * `RakuAST::ArgList` EXAMPLES ======== Example 1: Matching Specific Infix Operations --------------------------------------------- ```raku # Sample Raku code my $code = q{ for ^10 { if $_ %% 2 { say 1 * 3; } } }; # Generate the AST my $ast = $code.AST; # Query to find 'apply-op' nodes where left=1 and right=3 my $result = $ast.&ast-query('.apply-op[left=1, right=3]'); say $result.list; # Outputs matching 'ApplyOp' nodes ``` ### Output ```raku [ RakuAST::ApplyInfix.new( left => RakuAST::IntLiteral.new(1), infix => RakuAST::Infix.new("*"), right => RakuAST::IntLiteral.new(3) ) ] ``` Explanation: * The query `.apply-op[left=1, right=3]` matches ApplyOp nodes with left operand 1 and right operand 3. Example 2: Using the Ancestor Operator `<<<` and Named Captures --------------------------------------------------------------- ```raku # Sample Raku code my $code = q{ for ^10 { if $_ %% 2 { say $_ * 3; } } }; # Generate the AST my $ast = $code.AST; # Query to find 'Infix' nodes with any ancestor 'conditional', and capture 'IntLiteral' nodes with value 2 my $result = $ast.&ast-query('RakuAST::Infix <<< .conditional$cond .int#2$int'); say $result.list; # Outputs matching 'Infix' nodes say $result.hash; # Outputs captured nodes under 'cond' and 'int' ``` ### Output ```raku [ RakuAST::Infix.new("%%"), RakuAST::Infix.new("*") ] { cond => [ RakuAST::Statement::If.new( condition => RakuAST::ApplyInfix.new( left => RakuAST::Var::Lexical.new("$_"), infix => RakuAST::Infix.new("%%"), right => RakuAST::IntLiteral.new(2) ), then => RakuAST::Block.new(...) ) ], int => [ RakuAST::IntLiteral.new(2), RakuAST::IntLiteral.new(2) ] } ``` Explanation: * The query `RakuAST::Infix <<< .conditional$cond .int#2$int`: * Matches Infix nodes that have an ancestor matching `.conditional$cond`, regardless of intermediate nodes. * Captures IntLiteral nodes with value 2 as $int. * Access the captured nodes using $result<cond> and $result<int>. Example 3: Using the Ancestor Operator `<<` with Ignorable Nodes ---------------------------------------------------------------- ```raku # Find 'Infix' nodes with an ancestor 'conditional', skipping only ignorable nodes my $result = $ast.&ast-query('RakuAST::Infix << .conditional$cond'); say $result.list; # Outputs matching 'Infix' nodes say $result.hash; # Outputs captured 'conditional' nodes ``` Explanation: * The query RakuAST::Infix << .conditional$cond: * Matches Infix nodes that have an ancestor .conditional$cond, with only ignorable nodes between them. * Captures the conditional nodes as $cond. Example 4: Using the Parent Operator < and Capturing Nodes ---------------------------------------------------------- ```raku # Sample Raku code my $code = q{ for ^10 { if $_ %% 2 { say $_ * 2; } } }; # Generate the AST my $ast = $code.AST; # Query to find 'ApplyInfix' nodes where right operand is 2 and capture them as '$op' my $result = $ast.&ast-query('RakuAST::Infix < .apply-op[right=2]$op'); say $result<op>; # Captured 'ApplyInfix' nodes ``` ### Output ```raku [ RakuAST::ApplyInfix.new( left => RakuAST::Var::Lexical.new("$_"), infix => RakuAST::Infix.new("*"), right => RakuAST::IntLiteral.new(2) ) ] ``` Explanation: * The query `RakuAST::Infix < .apply-op[right=2]$op`: * Matches ApplyOp nodes with right operand 2 whose parent is an Infix node. * Captures the ApplyOp nodes as $op. Example 5: Using the Descendant Operator `>>>` and Capturing Variables ---------------------------------------------------------------------- ```raku # Sample Raku code my $code = q{ for ^10 { if $_ %% 2 { say $_; } } }; # Generate the AST my $ast = $code.AST; # Query to find 'call' nodes that have a descendant 'Var' node and capture the 'Var' node as '$var' my $result = $ast.&ast-query('.call >>> RakuAST::Var$var'); say $result.list; # Outputs matching 'call' nodes say $result.hash; # Outputs the 'Var' node captured as 'var' ``` ### Output ```raku [ RakuAST::Call::Name::WithoutParentheses.new( name => RakuAST::Name.from-identifier("say"), args => RakuAST::ArgList.new( RakuAST::Var::Lexical.new("$_") ) ) ] { var => RakuAST::Var::Lexical.new("$_") } ``` Explanation: * The query `.call >>> RakuAST::Var$var`: * Matches call nodes that have a descendant Var node, regardless of intermediate nodes. * Captures the Var node as $var. * Access the captured Var node using $result<var>. RETRIEVING MATCHED NODES ======================== The ast-query function returns an ASTQuery object with: * `@.list`: Matched nodes. * `%.hash`: Captured nodes. Accessing captured nodes: ```raku # Perform the query my $result = $ast.&ast-query('.call#say$call'); # Access the captured node my $call_node = $result<call>; # Access all matched nodes my @matched_nodes = $result.list; ``` THE ast-query FUNCTION ====================== Usage: :lang<raku> my $result = $ast.&ast-query('query string'); Returns an ASTQuery object with matched nodes and captures. GET INVOLVED ============ Visit the [ASTQuery repository](https://github.com/FCO/ASTQuery) on GitHub for examples, updates, and contributions. How You Can Help ---------------- * Feedback: Share your thoughts on features and usability. * Code Contributions: Add new features or fix bugs. * Documentation: Improve tutorials and guides. Note: ASTQuery is developed by Fernando Corrêa de Oliveira. DEBUG ===== For debugging, use the `ASTQUERY_DEBUG` env var. ![Trace example](./trace.png) CONCLUSION ========== ASTQuery empowers developers to effectively query and manipulate Raku’s ASTs, enhancing code analysis and transformation capabilities. DESCRIPTION =========== ASTQuery is a way to match RakuAST AUTHOR ====== Fernando Corrêa de Oliveira <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright 2024 Fernando Corrêa de Oliveira This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- ASTQuery ### -- Licenses: Artistic-2.0 ### -- Authors: Fernando Corrêa de Oliveira ### -- File: dist.ini ### ---------------------------------------------------- name = ASTQuery [ReadmeFromPod] filename = lib/ASTQuery.rakumod [UploadToZef] [Badges] provider = github-actions/test.yml
### ---------------------------------------------------- ### -- ASTQuery ### -- Licenses: Artistic-2.0 ### -- Authors: Fernando Corrêa de Oliveira ### -- File: bin/ast-query.raku ### ---------------------------------------------------- #!/usr/bin/env raku use paths; sub AST_QUERY__get-query { use ::("ASTQuery"); return ::("ASTQuery::EXPORT::ALL::&ast-query") } sub AST_QUERY__run-query($query, $file) { CATCH { default { warn "\o33[31;1m ERROR: { .message }\o33[m"; next; } } my &query := AST_QUERY__get-query; $file.slurp.AST.&query: $query } sub MAIN(Str $query, $dir?) { my &query := &AST_QUERY__run-query.assuming: $query; my @files = paths(:file(*.ends-with(any <raku rakumod rakutest rakuconfig p6 pl6 pm6>)), |($_ with $dir)); for @files -> IO() $file { CATCH { default { next } } my $match = try $file.&query; with $match { say "{ $file.relative }:"; try say .gist.indent: 2; } } }
### ---------------------------------------------------- ### -- ASTQuery ### -- Licenses: Artistic-2.0 ### -- Authors: Fernando Corrêa de Oliveira ### -- File: t/03-matcher.rakutest ### ---------------------------------------------------- use experimental :rakuast; use ASTQuery::Matcher; use ASTQuery::Match; use Test; # validate-class my \call = RakuAST::Call::Name.new( name => RakuAST::Name.from-identifier("say"), args => my \arg-list = RakuAST::ArgList.new( my \apply-infix = RakuAST::ApplyInfix.new( left => (my \l42 = RakuAST::IntLiteral.new(42)), infix => RakuAST::Infix.new("+"), right => my \l13 = RakuAST::IntLiteral.new(13) ) ) ); my \op-arg-list = arg-list.args.head.args; for [ (call, RakuAST::Name , False), (call, [RakuAST::Name] , False), (call, [RakuAST::Name xx 10], False), (call, "RakuAST::Name" , False), (call, ["RakuAST::Name"] , False), (call, ["RakuAST::Name" xx 10], False), (call, RakuAST::Call , ASTQuery::Match.new: :list[call]), (call, [RakuAST::Call] , ASTQuery::Match.new: :list[call]), (call, [RakuAST::Call xx 10] , ASTQuery::Match.new: :list[call]), ] -> @a [$node, $value, $expected] { my $got = ASTQuery::Matcher.validate-class: $node, $value; isa-ok $got, $expected.WHAT, "isa-ok: " ~ @a.gist; is-deeply $got, $expected, "is-deeply: " ~ @a.gist; } # validate-groups for [ (call, "int" , False), (call, ["int"] , False), (call, ["int" xx 10], False), (call, "call" , ASTQuery::Match.new: :list[call]), (call, ["call"] , ASTQuery::Match.new: :list[call]), (call, ["call" xx 10], ASTQuery::Match.new: :list[call]), ] -> @a [$node, $value, $expected] { my $got = ASTQuery::Matcher.validate-groups: $node, $value; isa-ok $got, $expected.WHAT, "isa-ok: " ~ @a.gist; is-deeply $got, $expected, "is-deeply: " ~ @a.gist; } # validate-ids for [ (call, "none1" , False), (call, ["none2"] , False), (call, ["none3" xx 10], False), (call, "say" , ASTQuery::Match.new: :list[call]), (call, ["say"] , ASTQuery::Match.new: :list[call]), (call, ["say" xx 10], ASTQuery::Match.new: :list[call]), ] -> @a [$node, $value, $expected] { my $got = ASTQuery::Matcher.validate-ids: $node, $value; isa-ok $got, $expected.WHAT, "isa-ok: " ~ @a.gist; is-deeply $got, $expected, "is-deeply: " ~ @a.gist; } # validate-atts for [ (call, "not-an-att", True, False), (call, "name", True, ASTQuery::Match.new: :list[call]), (call, "not-an-att", "something", False), (call, "name", "something", False), (call, "name", { "blablabla" }, False), (call, "name", "say", ASTQuery::Match.new: :list[call]), (call, "name", { <s a y>.join }, ASTQuery::Match.new: :list[call]), (call, "name", { False }, False), (call, "name", { True }, ASTQuery::Match.new: :list[call]), ] -> @a [$node, Str $name, $value, $expected] { my $got = ASTQuery::Matcher.validate-atts: $node, ($name => $value); isa-ok $got, $expected.WHAT, "isa-ok: " ~ @a.gist; is-deeply $got, $expected, "is-deeply: " ~ @a.gist; } # validate-code for [ (call, { False }, False), (call, { True }, ASTQuery::Match.new: :list[call]), (call, { .?name.?simple-identifier eq "say" }, ASTQuery::Match.new: :list[call]), (call, { say $/; .?name.?simple-identifier eq "say" }, ASTQuery::Match.new: :list[call]), ] -> @a [$node, &value, $expected] { my $got = ASTQuery::Matcher.validate-code: $node, &value; isa-ok $got, $expected.WHAT, "isa-ok: " ~ @a.gist; is-deeply $got, $expected, "is-deeply: " ~ @a.gist; } # validate-child for [ ( call, ASTQuery::Matcher.new( :classes["RakuAST::IntLiteral",] ), False ), ( call, my $m1 = ASTQuery::Matcher.new( :classes["RakuAST::ArgList",] ), ASTQuery::Match.new: :list[call.args], :matcher($m1), :ast(call) ), ] -> @a [$node, ASTQuery::Matcher $value, $expected] { my $got = ASTQuery::Matcher.validate-child: $node, $value; isa-ok $got, $expected.WHAT, "isa-ok: " ~ @a.gist; is-deeply $got, $expected, "is-deeply: " ~ @a.gist; } # validate-descendant for [ ( call, ASTQuery::Matcher.new( :classes["RakuAST::Ternary",] ), False ), ( call, my $m2 = ASTQuery::Matcher.new( :classes["RakuAST::ApplyInfix",] ), ASTQuery::Match.new: :list[apply-infix], :matcher($m2), :ast(call) ), ( call, my $m3 = ASTQuery::Matcher.new( :classes["RakuAST::IntLiteral",] ), ASTQuery::Match.new: :list[l42, l13], :matcher($m3), :ast(call) ), ] -> @a [$node, ASTQuery::Matcher $value, $expected] { my $got = ASTQuery::Matcher.validate-descendant: $node, $value; isa-ok $got, $expected.WHAT, "isa-ok: " ~ @a.gist; is-deeply $got, $expected, "is-deeply: " ~ @a.gist; } # validate-gchild for [ ( call, ASTQuery::Matcher.new( :classes["RakuAST::Ternary",] ), False ), ( call, ASTQuery::Matcher.new( :classes["RakuAST::ApplyInfix",] ), ASTQuery::Match.new: :list[apply-infix], # Should it be returning the rest of the data or should we remove it from the others? ), ( call, ASTQuery::Matcher.new( :classes["RakuAST::IntLiteral",] ), False ), ] -> @a [$node, ASTQuery::Matcher $value, $expected] { my $got = ASTQuery::Matcher.validate-gchild: $node, $value; isa-ok $got, $expected.WHAT, "isa-ok: " ~ @a.gist; is-deeply $got, $expected, "is-deeply: " ~ @a.gist; } # TODO: missing how to test the following methods: # validate-parent # validate-ascendant done-testing
### ---------------------------------------------------- ### -- ASTQuery ### -- Licenses: Artistic-2.0 ### -- Authors: Fernando Corrêa de Oliveira ### -- File: t/02-ASTQuery.rakutest ### ---------------------------------------------------- use experimental :rakuast; use ASTQuery; use ASTQuery::Matcher; use Test; ok &ast-matcher; ok &ast-query; for %( "RakuAST::Node" => %( meth => "classes", value => Array[ASTQuery::Matcher::ASTClass(Any)].new("RakuAST::Node"), ), ".conditional" => %( meth => "groups", value => Array[ASTQuery::Matcher::ASTGroup(Any)].new("conditional"), ), "#blablabla" => %( meth => "ids", value => ["blablabla", ], ), "[attribute]" => %( meth => "atts", value => %(attribute => True), ), "RakuAST::Node > RakuAST::Node" => %( meth => "child", value => ast-matcher("RakuAST::Node"), ), "RakuAST::Node >> RakuAST::Node" => %( meth => "gchild", value => ast-matcher("RakuAST::Node"), ), "RakuAST::Node >>> RakuAST::Node" => %( meth => "descendant", value => ast-matcher("RakuAST::Node"), ), "RakuAST::Node < RakuAST::Node" => %( meth => "parent", value => ast-matcher("RakuAST::Node"), ), "RakuAST::Node << RakuAST::Node" => %( meth => "gparent", value => ast-matcher("RakuAST::Node"), ), "RakuAST::Node <<< RakuAST::Node" => %( meth => "ascendant", value => ast-matcher("RakuAST::Node"), ), '$name' => %( meth => "name", value => "name", ), ).kv -> $selector, %h (Str :$meth, :$value) { my $matcher = ast-matcher($selector); isa-ok $matcher, ASTQuery::Matcher, "isa-ok: " ~ %h.gist; is-deeply $matcher."$meth"(), $value, "is-deeply: " ~ %h.gist; } for %( Q|42| => %( matcher => Q|RakuAST::IntLiteral|, list => [ RakuAST::IntLiteral.new(42) ], hash => %(), ), Q|42, 13, 3| => %( matcher => Q|RakuAST::IntLiteral|, list => [ RakuAST::IntLiteral.new(42), RakuAST::IntLiteral.new(13), RakuAST::IntLiteral.new(3), ], hash => %(), ), Q|42, 13, 3| => %( matcher => Q|.int|, list => [ RakuAST::IntLiteral.new(42), RakuAST::IntLiteral.new(13), RakuAST::IntLiteral.new(3), ], hash => %(), ), Q|42, 13, 3| => %( matcher => Q|#42|, list => [ RakuAST::IntLiteral.new(42), ], hash => %(), ), Q|42, 13, 3| => %( matcher => Q|[value=42]|, list => [ RakuAST::IntLiteral.new(42), ], hash => %(), ), Q|42, 13, 3| => %( matcher => Q|.int$test|, list => [ RakuAST::IntLiteral.new(42), RakuAST::IntLiteral.new(13), RakuAST::IntLiteral.new(3), ], hash => %( :test[ RakuAST::IntLiteral.new(42), RakuAST::IntLiteral.new(13), RakuAST::IntLiteral.new(3), ] ), ), Q|say 42| => %( matcher => Q|.call >> .int$integer|, list => [ RakuAST::Call::Name::WithoutParentheses.new( name => RakuAST::Name.from-identifier("say"), args => RakuAST::ArgList.new( RakuAST::IntLiteral.new(42), ) ) ], hash => %( :integer( RakuAST::IntLiteral.new(42) ) ), ), ).kv -> Str $ast, % (Str :$matcher, :@list, :%hash) { diag "$ast ~~ $matcher"; is-deeply ast-query($ast.AST, ast-matcher $matcher), ASTQuery::Match.new( :@list, :%hash, :matcher(ast-matcher $matcher), :ast($ast.AST), ) ; is-deeply ast-query($ast.AST, $matcher), ASTQuery::Match.new( :@list, :%hash, :matcher(ast-matcher $matcher), :ast($ast.AST), ) ; } done-testing
### ---------------------------------------------------- ### -- ASTQuery ### -- Licenses: Artistic-2.0 ### -- Authors: Fernando Corrêa de Oliveira ### -- File: t/01-basic.rakutest ### ---------------------------------------------------- use Test; use ASTQuery; pass "replace me"; done-testing;
### ---------------------------------------------------- ### -- ASTQuery ### -- Licenses: Artistic-2.0 ### -- Authors: Fernando Corrêa de Oliveira ### -- File: lib/ASTQuery.rakumod ### ---------------------------------------------------- use ASTQuery::Grammar; use ASTQuery::Actions; use ASTQuery::Matcher; use ASTQuery::Match; unit module ASTQuery; proto ast-query($, $) is export {*} multi ast-query($ast, Str $selector) { my $matcher = ast-matcher $selector; ast-query $ast, $matcher } multi ast-query($ast, $matcher) { my $match = ASTQuery::Match.new: :$ast, :$matcher, ; $match.query || Empty; } sub ast-matcher(Str $selector) is export { ASTQuery::Grammar.parse($selector, :actions(ASTQuery::Actions)).made } sub add-ast-group(|c) is export {ASTQuery::Matcher.add-ast-group: |c} sub add-to-ast-group(|c) is export {ASTQuery::Matcher.add-to-ast-group: |c} sub set-ast-id(|c) is export {ASTQuery::Matcher.set-ast-id: |c} =begin pod =head1 NAME ASTQuery - Query and manipulate Raku’s Abstract Syntax Trees (RakuAST) with an expressive syntax =head1 SYNOPSIS =begin code :lang<raku> use ASTQuery; # Sample Raku code my $code = q{ for ^10 { if $_ %% 2 { say $_ * 3; } } }; # Generate the AST my $ast = $code.AST; # Example 1: Find 'apply-op' nodes where left operand is 1 and right operand is 3 my $result1 = $ast.&ast-query('.apply-op[left=1, right=3]'); say $result1.list; # Outputs matching nodes =end code =head2 Output =begin code :lang<raku> [ RakuAST::ApplyInfix.new( left => RakuAST::IntLiteral.new(1), infix => RakuAST::Infix.new("*"), right => RakuAST::IntLiteral.new(3) ) ] =end code =head1 DESCRIPTION ASTQuery simplifies querying and manipulating Raku’s ASTs using a powerful query language. It allows precise selection of nodes and relationships, enabling effective code analysis and transformation. =head2 Key Features =item Expressive Query Syntax: Define complex queries to match specific AST nodes. =item Node Relationships: Use operators to specify parent-child and ancestor-descendant relationships. =item Named Captures: Capture matched nodes for easy retrieval. =item AST Manipulation: Modify the AST for code transformations and refactoring. =head1 QUERY LANGUAGE SYNTAX =head2 Node Description Format: C<RakuAST::Class::Name.group#id[attr1, attr2=attrvalue]$name> Components: =item C<RakuAST::Class::Name>: (Optional) Full class name. =item C<.group>: (Optional) Node group (predefined). =item C<#id>: (Optional) Identifier attribute. =item C<[attributes]>: (Optional) Attributes to match. =item C<$name>: (Optional) Capture name. Note: Use only one $name per node. =head2 Operators =item `>` : Left node has the right node as a child. =item `<` : Right node is the parent of the left node. =item `>>>`: Left node has the right node as a descendant (any nodes can be between them). =item `>>`: Left node has the right node as a descendant, with only ignorable nodes in between. =item `<<<`: Right node is an ancestor of the left node (any nodes can be between them). =item `<<`: Right node is an ancestor of the left node, with only ignorable nodes in between. Note: The space operator is no longer used. =head2 Ignorable Nodes Nodes skipped by `>>` and `<<` operators: =item C<RakuAST::Block> =item C<RakuAST::Blockoid> =item C<RakuAST::StatementList> =item C<RakuAST::Statement::Expression> =item C<RakuAST::ArgList> =head1 EXAMPLES =head2 Example 1: Matching Specific Infix Operations =begin code :lang<raku> # Sample Raku code my $code = q{ for ^10 { if $_ %% 2 { say 1 * 3; } } }; # Generate the AST my $ast = $code.AST; # Query to find 'apply-op' nodes where left=1 and right=3 my $result = $ast.&ast-query('.apply-op[left=1, right=3]'); say $result.list; # Outputs matching 'ApplyOp' nodes =end code =head3 Output =begin code :lang<raku> [ RakuAST::ApplyInfix.new( left => RakuAST::IntLiteral.new(1), infix => RakuAST::Infix.new("*"), right => RakuAST::IntLiteral.new(3) ) ] =end code Explanation: =item The query C<.apply-op[left=1, right=3]> matches ApplyOp nodes with left operand 1 and right operand 3. =head2 Example 2: Using the Ancestor Operator `<<<` and Named Captures =begin code :lang<raku> # Sample Raku code my $code = q{ for ^10 { if $_ %% 2 { say $_ * 3; } } }; # Generate the AST my $ast = $code.AST; # Query to find 'Infix' nodes with any ancestor 'conditional', and capture 'IntLiteral' nodes with value 2 my $result = $ast.&ast-query('RakuAST::Infix <<< .conditional$cond .int#2$int'); say $result.list; # Outputs matching 'Infix' nodes say $result.hash; # Outputs captured nodes under 'cond' and 'int' =end code =head3 Output =begin code :lang<raku> [ RakuAST::Infix.new("%%"), RakuAST::Infix.new("*") ] { cond => [ RakuAST::Statement::If.new( condition => RakuAST::ApplyInfix.new( left => RakuAST::Var::Lexical.new("$_"), infix => RakuAST::Infix.new("%%"), right => RakuAST::IntLiteral.new(2) ), then => RakuAST::Block.new(...) ) ], int => [ RakuAST::IntLiteral.new(2), RakuAST::IntLiteral.new(2) ] } =end code Explanation: =item The query `RakuAST::Infix <<< .conditional$cond .int#2$int`: =item Matches Infix nodes that have an ancestor matching C<.conditional$cond>, regardless of intermediate nodes. =item Captures IntLiteral nodes with value 2 as $int. =item Access the captured nodes using $result<cond> and $result<int>. =head2 Example 3: Using the Ancestor Operator `<<` with Ignorable Nodes =begin code :lang<raku> # Find 'Infix' nodes with an ancestor 'conditional', skipping only ignorable nodes my $result = $ast.&ast-query('RakuAST::Infix << .conditional$cond'); say $result.list; # Outputs matching 'Infix' nodes say $result.hash; # Outputs captured 'conditional' nodes =end code Explanation: =item The query RakuAST::Infix << .conditional$cond: =item Matches Infix nodes that have an ancestor .conditional$cond, with only ignorable nodes between them. =item Captures the conditional nodes as $cond. =head2 Example 4: Using the Parent Operator < and Capturing Nodes =begin code :lang<raku> # Sample Raku code my $code = q{ for ^10 { if $_ %% 2 { say $_ * 2; } } }; # Generate the AST my $ast = $code.AST; # Query to find 'ApplyInfix' nodes where right operand is 2 and capture them as '$op' my $result = $ast.&ast-query('RakuAST::Infix < .apply-op[right=2]$op'); say $result<op>; # Captured 'ApplyInfix' nodes =end code =head3 Output =begin code :lang<raku> [ RakuAST::ApplyInfix.new( left => RakuAST::Var::Lexical.new("$_"), infix => RakuAST::Infix.new("*"), right => RakuAST::IntLiteral.new(2) ) ] =end code Explanation: =item The query `RakuAST::Infix < .apply-op[right=2]$op`: =item Matches ApplyOp nodes with right operand 2 whose parent is an Infix node. =item Captures the ApplyOp nodes as $op. =head2 Example 5: Using the Descendant Operator `>>>` and Capturing Variables =begin code :lang<raku> # Sample Raku code my $code = q{ for ^10 { if $_ %% 2 { say $_; } } }; # Generate the AST my $ast = $code.AST; # Query to find 'call' nodes that have a descendant 'Var' node and capture the 'Var' node as '$var' my $result = $ast.&ast-query('.call >>> RakuAST::Var$var'); say $result.list; # Outputs matching 'call' nodes say $result.hash; # Outputs the 'Var' node captured as 'var' =end code =head3 Output =begin code :lang<raku> [ RakuAST::Call::Name::WithoutParentheses.new( name => RakuAST::Name.from-identifier("say"), args => RakuAST::ArgList.new( RakuAST::Var::Lexical.new("$_") ) ) ] { var => RakuAST::Var::Lexical.new("$_") } =end code Explanation: =item The query `.call >>> RakuAST::Var$var`: =item Matches call nodes that have a descendant Var node, regardless of intermediate nodes. =item Captures the Var node as $var. =item Access the captured Var node using $result<var>. =head1 RETRIEVING MATCHED NODES The ast-query function returns an ASTQuery object with: =item C<@.list>: Matched nodes. =item C<%.hash>: Captured nodes. Accessing captured nodes: =begin code :lang<raku> # Perform the query my $result = $ast.&ast-query('.call#say$call'); # Access the captured node my $call_node = $result<call>; # Access all matched nodes my @matched_nodes = $result.list; =end code =head1 THE ast-query FUNCTION Usage: =code :lang<raku> my $result = $ast.&ast-query('query string'); Returns an ASTQuery object with matched nodes and captures. =head1 GET INVOLVED Visit the L<ASTQuery repository|https://github.com/FCO/ASTQuery> on GitHub for examples, updates, and contributions. =head2 How You Can Help =item Feedback: Share your thoughts on features and usability. =item Code Contributions: Add new features or fix bugs. =item Documentation: Improve tutorials and guides. Note: ASTQuery is developed by Fernando Corrêa de Oliveira. =head1 DEBUG For debugging, use the C<ASTQUERY_DEBUG> env var. ![Trace example](./trace.png) =head1 CONCLUSION ASTQuery empowers developers to effectively query and manipulate Raku’s ASTs, enhancing code analysis and transformation capabilities. =head1 DESCRIPTION ASTQuery is a way to match RakuAST =head1 AUTHOR Fernando Corrêa de Oliveira <[email protected]> =head1 COPYRIGHT AND LICENSE Copyright 2024 Fernando Corrêa de Oliveira This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. =end pod
### ---------------------------------------------------- ### -- ASTQuery ### -- Licenses: Artistic-2.0 ### -- Authors: Fernando Corrêa de Oliveira ### -- File: lib/ASTQuery/Grammar.rakumod ### ---------------------------------------------------- #use Grammar::Tracer; unit grammar ASTQuery::Grammar; token TOP { <str-or-list> } token word { <-[\s#.\[\]=$>,~+]>+ } token ns { <[\w:-]>+ } proto token str { * } multi token str:<number> { \d+ } multi token str:<double> { '"' ~ '"' $<str>=<-["]>* } multi token str:<simple> { "'" ~ "'" $<str>=<-[']>* } proto token list { * } multi token list:<descen> { <node> \s* '>>>' \s* <str-or-list> } multi token list:<gchild> { <node> \s* '>>' \s* <str-or-list> } multi token list:<child> { <node> \s* '>' \s* <str-or-list> } multi token list:<ascend> { <node> \s* '<<<' \s* <str-or-list> } multi token list:<gparent> { <node> \s* '<<' \s* <str-or-list> } multi token list:<parent> { <node> \s* '<' \s* <str-or-list> } #multi token list:<many> { <node> \s* ',' \s* <str-or-list> } #multi token list:<after> { <node> \s+ '+' \s* <str-or-list> } #multi token list:<before> { <node> \s* '~' \s* <str-or-list> } multi token list:<simple> { <node> } proto token str-or-list {*} multi token str-or-list:<str> {<str>} multi token str-or-list:<list> {<list>} token node { <node-part>+ } proto token node-part { * } multi token node-part:<node> { <ns> } multi token node-part:<class> { '.' <word> } multi token node-part:<id> { '#' <word> } multi token node-part:<name> { '$' <word> } multi token node-part:<*> { '*' } multi token node-part:<par-simple> { ':' <word> } multi token node-part:<par-arg> { ':' <word> '(' ~ ')' \d+ } multi token node-part:<attr> { '[' ~ ']' [ <node-part-attr>+ %% [\s*","\s*] ] } multi token node-part:<code> { <code> } token code { '{' ~ '}' $<code>=.*? } proto token node-part-attr {*} multi token node-part-attr:<block> { <word> '=' <code> } multi token node-part-attr:<a-value> { <word> '=' <str-or-list> } multi token node-part-attr:<a-contains> { <word> '~=' <str-or-list> } multi token node-part-attr:<a-starts> { <word> '^=' <str-or-list> } multi token node-part-attr:<a-ends> { <word> '$=' <str-or-list> } multi token node-part-attr:<a-regex> { <word> '*=' <str-or-list> } multi token node-part-attr:<exists> { <word> }
### ---------------------------------------------------- ### -- ASTQuery ### -- Licenses: Artistic-2.0 ### -- Authors: Fernando Corrêa de Oliveira ### -- File: lib/ASTQuery/Match.rakumod ### ---------------------------------------------------- use experimental :rakuast; use ASTQuery::HighLighter; unit class ASTQuery::Match does Positional does Associative; has @.list is Array handles <AT-POS push Bool>; has %.hash is Hash handles <AT-KEY>; has $.matcher; has $.ast; has Bool $.recursive; method merge-or(*@matches) { my $new = ::?CLASS.new; for @matches.grep: ::?CLASS -> (:@list, :%hash, |) { $new.list.append: @list; for %hash.kv -> $key, $value { $new.hash.push: $key => $value } } $new || False } method merge-and(*@matches) { my $new = ::?CLASS.new; for @matches -> $m { return False unless $m; given $m -> ::?CLASS:D (:@list, :%hash, |) { $new.list.append: @list; for %hash.kv -> $key, $value { $new.hash.push: $key => $value } } } $new } method of {RakuAST::Node} multi prepare-code(@nodes) { "[\n{ do for @nodes -> $node { $node.&prepare-code }.join("\n").indent: 2 }\n]" } multi prepare-code(RakuAST::Node $node) { CATCH { default { return "\o33[31;1m{$node.^name} cannot be deparsed\o33[m" } } "\o33[1m{ $node.DEPARSE(ASTQuery::HighLighter) }\o33[m" } multi prepare-code($node) { "\o33[31;1m(NOT RakuAST($node.^name()))\o33[m \o33[1m{ $node .trans(["\n", "\t"] => ["␤", "␉"]) }\o33[m" } multi method gist(::?CLASS:U:) { self.raku } multi method gist(::?CLASS:D:) { [ |do for self.list.kv -> $i, $code { "$i => { $code.&prepare-code }", }, |do for self.hash.kv -> $key, $code { "$key => { $code.&prepare-code }", } ].join: "\n" } method Str {self.gist} sub match($match, $ast, $matcher) { if $matcher.ACCEPTS: $ast -> $m { if $m ~~ ::?CLASS { for $m.hash.kv -> $key, $value { $match.hash.push: $key => $value } } $match.list.push: $ast; $match.hash.push: $matcher.name => $ast if $matcher.?name; } } sub prepare-visitor($match, $matcher) { my UInt $position = 0; sub visitor($node, :$run-children, :$recursive = $*recursive // True, :$ignore-root = False) { $position++; my @lineage = @*LINEAGE; match $match, $node, $matcher unless $ignore-root; { my @*LINEAGE = $node, |@lineage; my $*recursive = $run-children.defined ?? !$run-children !! $recursive; $node.visit-children: &?ROUTINE if $run-children || $recursive; } $match } } method query { prepare-visitor(self, $!matcher).($!ast) } method query-descendants-only { prepare-visitor(self, $!matcher).($!ast, :ignore-root) } method query-children-only { prepare-visitor(self, $!matcher).($!ast, :run-children, :ignore-root) } method query-root-only { prepare-visitor(self, $!matcher).($!ast, :!recursive) }
### ---------------------------------------------------- ### -- ASTQuery ### -- Licenses: Artistic-2.0 ### -- Authors: Fernando Corrêa de Oliveira ### -- File: lib/ASTQuery/HighLighter.rakumod ### ---------------------------------------------------- unit role ASTQuery::HighLighter; method map(--> Map()) { adverb-q => "1", adverb-q-xxx => Str, arrow => "35;1", arrow-one => Str, arrow-two => Str, block => "35", block-xxx => Str, capture => "34;1", capture-named => Str, capture-xxx => Str, comment => "30;2", constraint => "33;2", constraint-xxx => Str, core => "33;1", core-say => Str, core-xxx => Str, doc => "30;1;3", doc-xxx => Str, infix => "33;1", infix-xxx => Str, invocant => "30;1", label => "38;1", literal => "32", markup => "3", markup-xxx => Str, meta => "31;1", meta-xxx => Str, modifier => "1", modifier-xxx => Str, multi => "32;1", multi-xxx => Str, named => "37;3", named-xxx => Str, nqp => "31;4", nqp-xxx => Str, package => "32;1;4", package-xxx => Str, param => "32;1", phaser => "30;47;1;3;4", phaser-xxx => Str, postfix => "33;1", postfix-xxx => Str, pragma => "33;1;2;3", pragma-xxx => Str, prefix => "33;1", prefix-xxx => Str, quote-lang => "33;3", quote-lang-xxx => Str, rakudoc => "37;2;3", rakudoc-xxx => Str, regex => "1;3", regex-xxx => Str, routine => "32;1", routine-xxx => Str, scope => "34;1", scope-xxx => Str, smiley => "33;1;3", smiley-xxx => Str, stmt => Str, stmt-prefix => "32;1", stmt-prefix-xxx => Str, stub => "37;2", system => "31;3;4", system-xxx => Str, term => "33;1", term-xxx => Str, ternary => "31;1;3", ternary-xxx => Str, trait-is => "3", trait-is-xxx => Str, traitmod => "1;3;4", traitmod-xxx => Str, type => "37;1", type-xxx => Str, typer => "37;1", typer-xxx => Str, use => "33;1;3;4", use-xxx => Str, var => "33;1", var-attribute => Str, var-compiler => Str, var-dynamic => Str, var-implicit => Str, var-lexical => Str, var-package => Str, var-placeholder => Str, var-rakudoc => Str, var-setting => Str, var-term => Str, version => "33;4", } method hsyn(str $type, str $content) { $.hl: $type, $content } multi method hl($type where {!$.from-map: $_}, $content) { note "<<$type>>"; $content } multi method hl($type where {$.from-map: $_ }, $content) { "\o33[{ $.from-map: $type }m$content\o33[m" } method from-map($type) { %.map{ $type.split("-") .produce(-> $agg, $item { "{$agg}-{$item}" }) .reverse } .first(*.defined) }
### ---------------------------------------------------- ### -- ASTQuery ### -- Licenses: Artistic-2.0 ### -- Authors: Fernando Corrêa de Oliveira ### -- File: lib/ASTQuery/Actions.rakumod ### ---------------------------------------------------- use ASTQuery::Matcher; unit grammar ASTQuery::Actions; method TOP($/) { make $<str-or-list>.made } method word($/) { make $/.Str } method ns($/) { make $/.Str } method str:<number>($/) { make $/.Int } method str:<double>($/) { make $<str>.Str } method str:<simple>($/) { make $<str>.Str } method list:<descen>($/) { make my $node = $<node>.made; $node.descendant = $<str-or-list>.made } method list:<gchild>($/) { make my $node = $<node>.made; $node.gchild = $<str-or-list>.made } method list:<child>($/) { make my $node = $<node>.made; $node.child = $<str-or-list>.made } method list:<ascend>($/) { make my $node = $<node>.made; $node.ascendant = $<str-or-list>.made } method list:<gparent>($/) { make my $node = $<node>.made; $node.gparent = $<str-or-list>.made } method list:<parent>($/) { make my $node = $<node>.made; $node.parent = $<str-or-list>.made } #method list:<many>($/) { <node> ',' <list> } #method list:<after>($/) { <node> '+' <list> } #method list:<before>($/) { <node> '~' <list> } method list:<simple>($/) { make $<node>.made } method str-or-list:<str>($/) { make $<str>.made } method str-or-list:<list>($/) { make $<list>.made } method node($/) { my %map := @<node-part>>>.made.classify({ .key }, :as{.value}); %map<ids> := @=.flat with %map<ids>; %map<atts> := %(|.map: { |.Map }) with %map<atts>; %map<name> = .head with %map<name>; %map<code> := @=.flat with %map<code>; #dd %map; make my $a = ASTQuery::Matcher.new: |%map.Map; #dd $a; } method node-part:<node>($/) { make (:classes($<ns>.made)) } method node-part:<class>($/) { make (:groups($<word>.made)) } method node-part:<id>($/) { make (:ids($<word>.made)) } method node-part:<name>($/) { make (:name($<word>.made)) } #method node-part:<*>($/) { '*' } #method node-part:<par-simple>($/) { ':' <word> } #method node-part:<par-arg>($/) { ':' <word> '(' ~ ')' \d+ } method node-part:<attr>($/) { make (:atts(%=|$<node-part-attr>>>.made)) } method node-part:<code>($/) { make (:code($<code>.made)) } method code($/) { my $code = Q|sub ($_?, :match($/)) { | ~ $<code>.Str ~ Q| }|; make $code.AST.EVAL } method node-part-attr:<exists>($/) { make ($<word>.made => True) } method node-part-attr:<block>($/) { make ($<word>.made => $<code>.made) } method node-part-attr:<a-value>($/) { make ($<word>.made => $<str-or-list>.made) } #method node-part-attr:<a-contains>($/) { '[' ~ ']' [ <word> '~=' [ <str> | <list> ] ] } #method node-part-attr:<a-starts>($/) { '[' ~ ']' [ <word> '^=' [ <str> | <list> ] ] } #method node-part-attr:<a-ends>($/) { '[' ~ ']' [ <word> '$=' [ <str> | <list> ] ] } #method node-part-attr:<a-regex>($/) { '[' ~ ']' [ <word> '*=' [ <str> | <list> ] ] }
### ---------------------------------------------------- ### -- ASTQuery ### -- Licenses: Artistic-2.0 ### -- Authors: Fernando Corrêa de Oliveira ### -- File: lib/ASTQuery/Matcher.rakumod ### ---------------------------------------------------- ### -- Chunk 1 of 2 use experimental :rakuast, :will-complain; use ASTQuery::Match; use ASTQuery::HighLighter; unit class ASTQuery::Matcher; my $DEBUG = %*ENV<ASTQUERY_DEBUG>; =head1 List of RakuAST classes =item RakuAST::ApplyDottyInfix =item RakuAST::ApplyInfix =item RakuAST::ApplyListInfix =item RakuAST::ApplyPostfix =item RakuAST::ApplyPrefix =item RakuAST::ArgList =item RakuAST::Assignment =item RakuAST::AttachTarget =item RakuAST::BeginTime =item RakuAST::Block =item RakuAST::BlockStatementSensitive =item RakuAST::BlockThunk =item RakuAST::Blockoid =item RakuAST::Blorst =item RakuAST::BracketedInfix =item RakuAST::CaptureSource =item RakuAST::CheckTime =item RakuAST::Circumfix =item RakuAST::Class =item RakuAST::Code =item RakuAST::ColonPair =item RakuAST::ColonPairs =item RakuAST::CompUnit =item RakuAST::CompileTimeValue =item RakuAST::ComplexLiteral =item RakuAST::Constant =item RakuAST::Contextualizable =item RakuAST::Contextualizer =item RakuAST::CurryThunk =item RakuAST::Declaration =item RakuAST::Doc =item RakuAST::DottyInfixish =item RakuAST::Expression =item RakuAST::ExpressionThunk =item RakuAST::FakeSignature =item RakuAST::FatArrow =item RakuAST::Feed =item RakuAST::FlipFlop =item RakuAST::ForLoopImplementation =item RakuAST::FunctionInfix =item RakuAST::Grammar =item RakuAST::Heredoc =item RakuAST::ImplicitBlockSemanticsProvider =item RakuAST::ImplicitDeclarations =item RakuAST::ImplicitLookups =item RakuAST::Infix =item RakuAST::Infixish =item RakuAST::Initializer =item RakuAST::IntLiteral =item RakuAST::Knowhow =item RakuAST::Label =item RakuAST::LexicalScope =item RakuAST::Literal =item RakuAST::Lookup =item RakuAST::Meta =item RakuAST::MetaInfix =item RakuAST::Method =item RakuAST::Methodish =item RakuAST::Mixin =item RakuAST::Module =item RakuAST::Name =item RakuAST::NamedArg =item RakuAST::Native =item RakuAST::Node =item RakuAST::Nqp =item RakuAST::NumLiteral =item RakuAST::OnlyStar =item RakuAST::Package =item RakuAST::Parameter =item RakuAST::ParameterDefaultThunk =item RakuAST::ParameterTarget =item RakuAST::ParseTime =item RakuAST::PlaceholderParameterOwner =item RakuAST::PointyBlock =item RakuAST::Postcircumfix =item RakuAST::Postfix =item RakuAST::Postfixish =item RakuAST::Pragma =item RakuAST::Prefix =item RakuAST::Prefixish =item RakuAST::ProducesNil =item RakuAST::QuotePair =item RakuAST::QuoteWordsAtom =item RakuAST::QuotedMatchConstruct =item RakuAST::QuotedRegex =item RakuAST::QuotedString =item RakuAST::RatLiteral =item RakuAST::Regex =item RakuAST::RegexDeclaration =item RakuAST::RegexThunk =item RakuAST::Role =item RakuAST::RoleBody =item RakuAST::Routine =item RakuAST::RuleDeclaration =item RakuAST::SemiList =item RakuAST::Signature =item RakuAST::SinkBoundary =item RakuAST::SinkPropagator =item RakuAST::Sinkable =item RakuAST::Statement =item RakuAST::StatementList =item RakuAST::StatementModifier =item RakuAST::StatementPrefix =item RakuAST::StatementSequence =item RakuAST::StrLiteral =item RakuAST::Stub =item RakuAST::StubbyMeta =item RakuAST::Sub =item RakuAST::Submethod =item RakuAST::Substitution =item RakuAST::SubstitutionReplacementThunk =item RakuAST::Term =item RakuAST::Termish =item RakuAST::Ternary =item RakuAST::TokenDeclaration =item RakuAST::Trait =item RakuAST::Type =item RakuAST::Var =item RakuAST::VersionLiteral =item RakuAST::Circumfix::ArrayComposer =item RakuAST::Circumfix::HashComposer =item RakuAST::Circumfix::Parentheses =item RakuAST::ColonPair::False =item RakuAST::ColonPair::Number =item RakuAST::ColonPair::True =item RakuAST::ColonPair::Value =item RakuAST::ColonPair::Variable =item RakuAST::Contextualizer::Hash =item RakuAST::Contextualizer::Item =item RakuAST::Contextualizer::List =item RakuAST::Declaration::External =item RakuAST::Declaration::Import =item RakuAST::Declaration::LexicalPackage =item RakuAST::Declaration::ResolvedConstant =item RakuAST::Doc::Block =item RakuAST::Doc::Declarator =item RakuAST::Doc::LegacyRow =item RakuAST::Doc::Markup =item RakuAST::Doc::Paragraph =item RakuAST::Doc::Row =item RakuAST::Heredoc::InterpolatedWhiteSpace =item RakuAST::Initializer::Assign =item RakuAST::Initializer::Bind =item RakuAST::Initializer::CallAssign =item RakuAST::Initializer::Expression =item RakuAST::MetaInfix::Assign =item RakuAST::MetaInfix::Cross =item RakuAST::MetaInfix::Hyper =item RakuAST::MetaInfix::Negate =item RakuAST::MetaInfix::Reverse =item RakuAST::MetaInfix::Sequence =item RakuAST::MetaInfix::Zip =item RakuAST::Nqp::Const =item RakuAST::Package::Attachable =item RakuAST::ParameterTarget::Term =item RakuAST::ParameterTarget::Var =item RakuAST::ParameterTarget::Whatever =item RakuAST::Postcircumfix::ArrayIndex =item RakuAST::Postcircumfix::HashIndex =item RakuAST::Postcircumfix::LiteralHashIndex =item RakuAST::Postfix::Literal =item RakuAST::Postfix::Power =item RakuAST::Postfix::Vulgar =item RakuAST::Regex::Alternation =item RakuAST::Regex::Anchor =item RakuAST::Regex::Assertion =item RakuAST::Regex::Atom =item RakuAST::Regex::BackReference =item RakuAST::Regex::Backtrack =item RakuAST::Regex::BacktrackModifiedAtom =item RakuAST::Regex::Block =item RakuAST::Regex::Branching =item RakuAST::Regex::CapturingGroup =item RakuAST::Regex::CharClass =item RakuAST::Regex::CharClassElement =item RakuAST::Regex::CharClassEnumerationElement =item RakuAST::Regex::Conjunction =item RakuAST::Regex::Group =item RakuAST::Regex::InternalModifier =item RakuAST::Regex::Interpolation =item RakuAST::Regex::Literal =item RakuAST::Regex::MatchFrom =item RakuAST::Regex::MatchTo =item RakuAST::Regex::NamedCapture =item RakuAST::Regex::Nested =item RakuAST::Regex::QuantifiedAtom =item RakuAST::Regex::Quantifier =item RakuAST::Regex::Quote =item RakuAST::Regex::Sequence =item RakuAST::Regex::SequentialAlternation =item RakuAST::Regex::SequentialConjunction =item RakuAST::Regex::Statement =item RakuAST::Regex::Term =item RakuAST::Regex::WithWhitespace =item RakuAST::Role::ResolveInstantiations =item RakuAST::Role::TypeEnvVar =item RakuAST::Statement::Catch =item RakuAST::Statement::Control =item RakuAST::Statement::Default =item RakuAST::Statement::Empty =item RakuAST::Statement::ExceptionHandler =item RakuAST::Statement::Expression =item RakuAST::Statement::For =item RakuAST::Statement::Given =item RakuAST::Statement::If =item RakuAST::Statement::IfWith =item RakuAST::Statement::Import =item RakuAST::Statement::Loop =item RakuAST::Statement::Need =item RakuAST::Statement::Require =item RakuAST::Statement::Unless =item RakuAST::Statement::Use =item RakuAST::Statement::When =item RakuAST::Statement::Whenever =item RakuAST::Statement::With =item RakuAST::Statement::Without =item RakuAST::StatementModifier::Condition =item RakuAST::StatementModifier::For =item RakuAST::StatementModifier::Given =item RakuAST::StatementModifier::If =item RakuAST::StatementModifier::Loop =item RakuAST::StatementModifier::Unless =item RakuAST::StatementModifier::Until =item RakuAST::StatementModifier::When =item RakuAST::StatementModifier::While =item RakuAST::StatementModifier::With =item RakuAST::StatementModifier::Without =item RakuAST::StatementPrefix::Blorst =item RakuAST::StatementPrefix::CallMethod =item RakuAST::StatementPrefix::Do =item RakuAST::StatementPrefix::Eager =item RakuAST::StatementPrefix::Gather =item RakuAST::StatementPrefix::Hyper =item RakuAST::StatementPrefix::Lazy =item RakuAST::StatementPrefix::Once =item RakuAST::StatementPrefix::Phaser =item RakuAST::StatementPrefix::Quietly =item RakuAST::StatementPrefix::Race =item RakuAST::StatementPrefix::React =item RakuAST::StatementPrefix::Sink =item RakuAST::StatementPrefix::Start =item RakuAST::StatementPrefix::Supply =item RakuAST::StatementPrefix::Thunky =item RakuAST::StatementPrefix::Try =item RakuAST::StatementPrefix::Wheneverable =item RakuAST::Stub::Die =item RakuAST::Stub::Fail =item RakuAST::Stub::Warn =item RakuAST::Term::Capture =item RakuAST::Term::EmptySet =item RakuAST::Term::HyperWhatever =item RakuAST::Term::Name =item RakuAST::Term::Named =item RakuAST::Term::RadixNumber =item RakuAST::Term::Rand =item RakuAST::Term::Reduce =item RakuAST::Term::Self =item RakuAST::Term::TopicCall =item RakuAST::Term::Whatever =item RakuAST::Trait::Does =item RakuAST::Trait::Handles =item RakuAST::Trait::Hides =item RakuAST::Trait::Is =item RakuAST::Trait::Of =item RakuAST::Trait::Returns =item RakuAST::Trait::Type =item RakuAST::Trait::Will =item RakuAST::Trait::WillBuild =item RakuAST::Type::Capture =item RakuAST::Type::Coercion =item RakuAST::Type::Definedness =item RakuAST::Type::Derived =item RakuAST::Type::Enum =item RakuAST::Type::Parameterized =item RakuAST::Type::Setting =item RakuAST::Type::Simple =item RakuAST::Type::Subset =item RakuAST::Var::Attribute =item RakuAST::Var::Compiler =item RakuAST::Var::Doc =item RakuAST::Var::Dynamic =item RakuAST::Var::Lexical =item RakuAST::Var::NamedCapture =item RakuAST::Var::Package =item RakuAST::Var::PositionalCapture =item RakuAST::Var::Slang =item RakuAST::Declaration::External::Constant =item RakuAST::Declaration::External::Setting =item RakuAST::Regex::Anchor::BeginningOfLine =item RakuAST::Regex::Anchor::BeginningOfString =item RakuAST::Regex::Anchor::EndOfLine =item RakuAST::Regex::Anchor::EndOfString =item RakuAST::Regex::Anchor::LeftWordBoundary =item RakuAST::Regex::Anchor::RightWordBoundary =item RakuAST::Regex::Assertion::Alias =item RakuAST::Regex::Assertion::Callable =item RakuAST::Regex::Assertion::CharClass =item RakuAST::Regex::Assertion::Fail =item RakuAST::Regex::Assertion::InterpolatedBlock =item RakuAST::Regex::Assertion::InterpolatedVar =item RakuAST::Regex::Assertion::Lookahead =item RakuAST::Regex::Assertion::Named =item RakuAST::Regex::Assertion::Pass =item RakuAST::Regex::Assertion::PredicateBlock =item RakuAST::Regex::Assertion::Recurse =item RakuAST::Regex::BackReference::Named =item RakuAST::Regex::BackReference::Positional =item RakuAST::Regex::Backtrack::Frugal =item RakuAST::Regex::Backtrack::Greedy =item RakuAST::Regex::Backtrack::Ratchet =item RakuAST::Regex::CharClass::Any =item RakuAST::Regex::CharClass::BackSpace =item RakuAST::Regex::CharClass::CarriageReturn =item RakuAST::Regex::CharClass::Digit =item RakuAST::Regex::CharClass::Escape =item RakuAST::Regex::CharClass::FormFeed =item RakuAST::Regex::CharClass::HorizontalSpace =item RakuAST::Regex::CharClass::Negatable =item RakuAST::Regex::CharClass::Newline =item RakuAST::Regex::CharClass::Nul =item RakuAST::Regex::CharClass::Space =item RakuAST::Regex::CharClass::Specified =item RakuAST::Regex::CharClass::Tab =item RakuAST::Regex::CharClass::VerticalSpace =item RakuAST::Regex::CharClass::Word =item RakuAST::Regex::CharClassElement::Enumeration =item RakuAST::Regex::CharClassElement::Property =item RakuAST::Regex::CharClassElement::Rule =item RakuAST::Regex::CharClassEnumerationElement::Character =item RakuAST::Regex::CharClassEnumerationElement::Range =item RakuAST::Regex::InternalModifier::IgnoreCase =item RakuAST::Regex::InternalModifier::IgnoreMark =item RakuAST::Regex::InternalModifier::Ratchet =item RakuAST::Regex::InternalModifier::Sigspace =item RakuAST::Regex::Quantifier::BlockRange =item RakuAST::Regex::Quantifier::OneOrMore =item RakuAST::Regex::Quantifier::Range =item RakuAST::Regex::Quantifier::ZeroOrMore =item RakuAST::Regex::Quantifier::ZeroOrOne =item RakuAST::Statement::Loop::RepeatUntil =item RakuAST::Statement::Loop::RepeatWhile =item RakuAST::Statement::Loop::Until =item RakuAST::Statement::Loop::While =item RakuAST::StatementModifier::Condition::Thunk =item RakuAST::StatementModifier::For::Thunk =item RakuAST::StatementPrefix::Phaser::Begin =item RakuAST::StatementPrefix::Phaser::Block =item RakuAST::StatementPrefix::Phaser::Check =item RakuAST::StatementPrefix::Phaser::Close =item RakuAST::StatementPrefix::Phaser::End =item RakuAST::StatementPrefix::Phaser::Enter =item RakuAST::StatementPrefix::Phaser::First =item RakuAST::StatementPrefix::Phaser::Init =item RakuAST::StatementPrefix::Phaser::Keep =item RakuAST::StatementPrefix::Phaser::Last =item RakuAST::StatementPrefix::Phaser::Leave =item RakuAST::StatementPrefix::Phaser::Next =item RakuAST::StatementPrefix::Phaser::Post =item RakuAST::StatementPrefix::Phaser::Pre =item RakuAST::StatementPrefix::Phaser::Quit =item RakuAST::StatementPrefix::Phaser::Sinky =item RakuAST::StatementPrefix::Phaser::Temp =item RakuAST::StatementPrefix::Phaser::Undo =item RakuAST::Var::Attribute::Public =item RakuAST::Var::Compiler::Block =item RakuAST::Var::Compiler::File =item RakuAST::Var::Compiler::Line =item RakuAST::Var::Compiler::Lookup =item RakuAST::Var::Compiler::Routine =item RakuAST::Var::Lexical::Constant =item RakuAST::Var::Lexical::Setting =item RakuAST::Regex::Assertion::Named::Args =item RakuAST::Regex::Assertion::Named::RegexArg my %groups is Map = ( expression => [ RakuAST::ApplyDottyInfix, RakuAST::ApplyInfix, RakuAST::ApplyListInfix, RakuAST::ApplyPostfix, RakuAST::ApplyPrefix, RakuAST::BracketedInfix, RakuAST::DottyInfixish, RakuAST::FunctionInfix, RakuAST::Infix, RakuAST::Infixish, RakuAST::MetaInfix, RakuAST::Prefixish, RakuAST::Postfixish ], literal => [ RakuAST::ComplexLiteral, RakuAST::IntLiteral, RakuAST::NumLiteral, RakuAST::StrLiteral, RakuAST::RatLiteral, RakuAST::VersionLiteral, RakuAST::Constant, RakuAST::Literal ], statement => [ RakuAST::Block, RakuAST::BlockStatementSensitive, RakuAST::BlockThunk, RakuAST::Blockoid, RakuAST::Statement, RakuAST::StatementList, RakuAST::StatementSequence, RakuAST::StatementModifier, RakuAST::StatementPrefix, RakuAST::Statement::Catch, RakuAST::Statement::Control, RakuAST::Statement::If, RakuAST::Statement::Loop ], declaration => [ RakuAST::Declaration, RakuAST::Declaration::External, RakuAST::Declaration::Import, RakuAST::Declaration::LexicalPackage, RakuAST::Var, RakuAST::NamedArg, RakuAST::Parameter, RakuAST::Signature, RakuAST::Class, RakuAST::Role, RakuAST::Module, RakuAST::Grammar ], control => [ RakuAST::ForLoopImplementation, RakuAST::FlipFlop, RakuAST::Statement::IfWith, RakuAST::Statement::Unless, RakuAST::Statement::With, RakuAST::Statement::When ], phaser => [ RakuAST::StatementPrefix::Phaser, RakuAST::StatementPrefix::Phaser::Begin, RakuAST::StatementPrefix::Phaser::End, RakuAST::BeginTime, RakuAST::CheckTime, RakuAST::ParseTime ], regex => [ RakuAST::Regex, RakuAST::RegexDeclaration, RakuAST::QuotedRegex, RakuAST::Regex::Atom, RakuAST::Regex::Sequence, RakuAST::QuotedMatchConstruct, RakuAST::QuotedString, RakuAST::Regex::Anchor, RakuAST::Regex::Assertion ], data => [ RakuAST::CaptureSource, RakuAST::ArgList, RakuAST::Postcircumfix::ArrayIndex, RakuAST::Postcircumfix::HashIndex, RakuAST::Circumfix::ArrayComposer, RakuAST::Circumfix::HashComposer ], code => [ RakuAST::Code, RakuAST::Routine, RakuAST::Method, RakuAST::Sub, RakuAST::Submethod, RakuAST::Contextualizable, RakuAST::Contextualizer, RakuAST::LexicalScope ], type => [ RakuAST::Type, RakuAST::Type::Capture, RakuAST::Type::Enum, RakuAST::Type::Parameterized, RakuAST::Trait, RakuAST::Trait::Does, RakuAST::Trait::Handles ], meta => [ RakuAST::Meta, RakuAST::MetaInfix, RakuAST::CurryThunk, RakuAST::FakeSignature, RakuAST::PlaceholderParameterOwner ], doc => [ RakuAST::Doc, RakuAST::Doc::Block, RakuAST::Doc::Markup, RakuAST::Doc::Paragraph, RakuAST::Pragma ], special => [ RakuAST::Blorst, RakuAST::Stub, RakuAST::Stub::Fail, RakuAST::Stub::Warn, RakuAST::Term, RakuAST::Termish, RakuAST::OnlyStar, RakuAST::ProducesNil ], call => [RakuAST::Call], expression => [RakuAST::Statement::Expression], statement => [RakuAST::Statement], int => [RakuAST::IntLiteral], str => [RakuAST::StrLiteral], op => [ RakuAST::Infixish, RakuAST::Prefixish, RakuAST::Postfixish, ], apply-op => [ RakuAST::ApplyInfix, RakuAST::ApplyListInfix, #RakuAST::ApplyDottyInfix, RakuAST::ApplyPostfix, RakuAST::Ternary, ], conditional => [ RakuAST::Statement::IfWith, RakuAST::Statement::Unless, RakuAST::Statement::Without, ], iterable => [ RakuAST::Statement::Loop, RakuAST::Statement::For, RakuAST::Statement::Whenever, ], ignorable => [ RakuAST::Block, RakuAST::Blockoid, RakuAST::StatementList, RakuAST::Statement::Expression, RakuAST::ArgList, ], node => [ RakuAST::Node, ], var => [ RakuAST::VarDeclaration, RakuAST::Var, ], var-usage => [ RakuAST::Var, ], var-declaration => [ #RakuAST::VarDeclaration, RakuAST::VarDeclaration::Simple, ], method-declaration => [ RakuAST::Method ], ); my %id is Map = ( "RakuAST::Call" => "name", "RakuAST::Statement::Expression" => "expression", "RakuAST::Statement::IfWith" => "condition", "RakuAST::Statement::Unless" => "condition", "RakuAST::Literal" => "value", "RakuAST::Name" => "simple-identifier", "RakuAST::Term::Name" => "name", "RakuAST::ApplyInfix" => "infix", "RakuAST::Infixish" => "infix", "RakuAST::Infix" => "operator", "RakuAST::Prefix" => "operator", "RakuAST::Postfix" => "operator", "RakuAST::ApplyInfix" => "infix", "RakuAST::ApplyListInfix" => "infix", "RakuAST::ApplyDottyInfix" => "infix", "RakuAST::ApplyPostfix" => "postfix", "RakuAST::FunctionInfix" => "function", "RakuAST::ArgList" => "args", "RakuAST::Var::Lexical" => "desigilname", "RakuAST::Statement::For" => "source", "RakuAST::Statement::Loop" => "condition", "RakuAST::VarDeclaration" => "name", ); method get-id-field($node) { for $node.^mro { .return with %id{.^name} } } subset ASTClass of Str will complain {"$_ is not a valid class"} where { !.defined || ::(.Str) !~~ Failure } subset ASTGroup of Str will complain {"$_ is not a valid group"} where { !.defined || %groups{.Str} } multi method add-ast-group(Str $name, ASTClass() @classes) { self.add-ast-group: $name, @[email protected]: { ::($_) } } multi method add-ast-group(Str $name, @classes) { %groups := {%groups, $name => @classes}.Map } multi method set-ast-id(ASTClass:D $class, Str $id where {::($class).^can($_) || fail "$class has no method $id"}) { %id := { %id, $class => $id }.Map } multi method set-ast-id(Mu:U $class, Str $id) { self.set-ast-id: $class.^name, $id } multi method add-to-ast-group(ASTGroup $name, *@classes) { my @new-classes = @classes.duckmap: -> ASTClass:D $class { ::($class) }; @new-classes.unshift: |%groups{$name}; self.add-ast-group: $name, @new-classes } has ASTClass() @.classes; has ASTGroup() @.groups; has @.ids; has %.atts; has %.params; has $.child is rw; has $.gchild is rw; has $.parent is rw; has $.gparent is rw; has $.descendant is rw; has $.ascendant is rw; has Str $.name; has Callable() @.code; multi method gist(::?CLASS:D: :$inside = False) { "{ self.^name ~ ".new(" unless $inside }{ (.Str for @!classes).join: "" }{ ('.' ~ .Str for @!groups).join: "" }{ ('#' ~ .Str for @!ids).join: "" }{ "[" ~ %!atts.kv.map(-> $k, $v { $k ~ ( $v =:= Whatever ?? "" !! "=$v.gist()" ) }).join(', ') ~ ']' if %!atts }{ ("\{{$_}}" for @!code).join: "" }{ '$' ~ .Str with $!name }{ " > " ~ .gist(:inside) with $!child }{ " >> " ~ .gist(:inside) with $!gchild }{ " >>> " ~ .gist(:inside) with $!descendant }{ " < " ~ .gist(:inside) with $!parent }{ " << " ~ .gist(:inside) with $!gparent }{ " <<< " ~ .gist(:inside) with $!ascendant }{ ")" unless $inside }" } multi add(ASTQuery::Match $base, $matcher, $node, ASTQuery::Match $match where *.so) { $base.list.push: |$match.list; for $match.hash.kv -> $key, $value { $base.hash.push: $key => $value } $match } multi add($, $, $, $ret) { $ret } my $indent = 0; sub prepare-type($value) { my $name = $value.^name; $name.subst: /(\w)\w+'::'/, {"$0::"}, :g } multi prepare-bool(Bool() $result where *.so) { "\o33[32;1mTrue\o33[m" } multi prepare-bool(Bool() $result where *.not) { "\o33[31;1mFalse\o33[m" } multi prepare-bool(Mu) {"???"} sub prepare-node($node) { "\o33[33;1m{ $node.&prepare-type }\o33[m" } my @current-caller; sub prepare-caller(Bool() :$result) { "{ !$result.defined ?? "\o33[1m" !! $result ?? "\o33[32;1m" !! "\o33[31;1m" }{ do if callframe(4).code.name -> $name { @current-caller.push: $name; "{$name}({callframe(6).code.signature.params.grep(!*.named).skip>>.gist.join: ", "})" } else { @current-caller.pop } }\o33[m" } sub prepare-indent($indent, :$end) { "\o33[1;30m{ $indent == 0 ?? "" !! join "", "│ " x $indent - 1, $end ?? "└─ " !! "├─ " }\o33[m" } sub deparse-and-format($node) { CATCH { default { return "\o33[31;1m{$node.^name} cannot be deparsed: $_\o33[m" } } my $code = $node.DEPARSE(ASTQuery::HighLighter); my $txt = $code.trans(["\n", "\t"] => ["␤", "␉"]) .subst(/\s+/, " ", :g) ; $txt.chars > 72 ?? $txt.substr(0, 72) ~ "\o33[30;1m...\o33[m" !! $txt } multi prepare-code(RakuAST::Node $node) { "\o33[1m{$node.&deparse-and-format}\o33[m" } multi prepare-code($node) { "\o33[31;1m(NOT RakuAST)\o33[m \o33[1m{ $node .trans(["\n", "\t"] => ["␤", "␉"]) }\o33[m" } sub print-validator-begin($node, $value) { return unless $DEBUG; note $indent.&prepare-indent, $node.&prepare-code, " (", $node.&prepare-node, ") - ", prepare-caller, ": ", $value; $indent++; } multi print-validator-end($, Mu, Mu $result) { True } multi print-validator-end($node, $value, $result) { return True unless $DEBUG; note $indent.&prepare-indent(:end), prepare-caller(:result($result)), " ({ $result.&prepare-bool })"; $indent--; True } method ACCEPTS($node) { print-validator-begin $node, self.gist; POST print-validator-end $node, self.gist, $_; my $match = ASTQuery::Match.new: :ast($node), :matcher(self); { my UInt $count = 0; my $ans = [ True, {:attr<classes>, :validator<validate-class> }, {:attr<groups>, :validator<validate-groups> }, {:attr<ids>, :validator<validate-ids> }, {:attr<atts>, :validator<validate-atts> }, {:attr<code>, :validator<validate-code> }, {:attr<child>, :validator<validate-child> }, {:attr<descendant>, :validator<validate-descendant>}, {:attr<gchild>, :validator<validate-gchild> }, {:attr<parent>, :validator<validate-parent> }, {:attr<ascendant>, :validator<validate-ascendant> }, ].reduce: sub (Bool() $ans, % (Str :$attr, Str :$validator)) { return False unless $ans; return True unless self."$attr"(); ++$count; my $validated = self."$validator"($node, self."$attr"()); $match.&add: self, $node, $validated; } return False unless $ans; #$match.hash.push: $!name => $node if $!name; #say $node.^name, " - ", $match.list if $DEBUG; } $match } multi method validate-code($node, @code) { print-validator-begin $node, @code; POST print-validator-end $node, @code, $_; ([&&] do for @code -> &code { self.validate-code: $node, &code; }) ?? ASTQuery::Match.new: :list[$node] !! False } multi method validate-code($node, &code) { print-validator-begin $node, &code; POST print-validator-end $node, &code, $_; code($node) ?? ASTQuery::Match.new: :list[$node] !! False } method validate-ascendant($node, $parent) { print-validator-begin $node, $parent; POST print-validator-end $node, $parent, $_; ASTQuery::Match.merge-or: |do for @*LINEAGE -> $ascendant { ASTQuery::Match.new(:ast($ascendant), :matcher($parent)) .query-root-only; } } method validate-gparent($node, $parent) { print-validator-begin $node, $parent; POST print-validator-end $node, $parent, $_; my @ignorables = %groups<ignorable><>; ASTQuery::Match.merge-or: |do for @*LINEAGE -> $ascendant { ASTQuery::Match.new(:ast($ascendant), :matcher($parent)) .query-root-only || $ascendant ~~ @ignorables.any || last } } method validate-parent($node, $parent) { print-validator-begin $node, $parent; POST print-validator-end $node, $parent, $_; ASTQuery::Match.new(:ast(@*LINEAGE.head), :matcher($parent)) .query-root-only || False } method validate-descendant($node, $child) { print-validator-begin $node, $child; POST print-validator-end $node, $child, $_; ASTQuery::Match.new(:ast($node), :matcher($child)) .query-descendants-only || False } method validate-gchild($node, $gchild) { print-validator-begin $node, $gchild; POST print-validator-end $node, $gchild, $_; my $gchild-result = self.validate-child($node, $gchild); return $gchild-result if $gchild-result; my @list = self.query-child($node, ::?CLASS.new: :groups<ignorable>).list; ASTQuery::Match.merge-or: |do for @list -> $node { self.validate-gchild: $node, $gchild } } method query-child($node, $child, *%pars) { print-validator-begin $node, $child; POST print-validator-end $node, $child, $_; ASTQuery::Match.new(:ast($node), :matcher($child)) .query-children-only; } method validate-child($node, $child) { print-validator-begin $node, $child; POST print-validator-end $node, $child, $_; self.query-child($node, $child) || False } multi method validate-groups($node, @groups) { print-validator-begin $node, @groups; POST print-validator-end $node, @groups, $_; self.validate-class: $node, %groups{@groups}.flat.unique } multi method validate-groups($node, $group) { print-validator-begin $node, $group; POST print-validator-end $node, $group, $_; self.validate-groups: $node, [$group,] } multi method validate-class($node, Str $class) { print-validator-begin $node, $class; POST print-validator-end $node, $class, $_;
### ---------------------------------------------------- ### -- ASTQuery ### -- Licenses: Artistic-2.0 ### -- Authors: Fernando Corrêa de Oliveira ### -- File: lib/ASTQuery/Matcher.rakumod ### ---------------------------------------------------- ### -- Chunk 2 of 2 self.validate-class: $node, ::($class) } multi method validate-class($node, Mu:U $class) { print-validator-begin $node, $class; POST print-validator-end $node, $class, $_; do if $node ~~ $class { ASTQuery::Match.new: :list[$node] } else { False } } multi method validate-class($node, @classes) { print-validator-begin $node, @classes; POST print-validator-end $node, @classes, $_; my %done := :{}; @classes.flatmap(-> $class { next if %done{$class}++; self.validate-class: $node, $class }).first(*.so) // False } multi method validate-ids($node, @ids) { print-validator-begin $node, @ids; POST print-validator-end $node, @ids, $_; my $key = self.get-id-field: $node; return False unless $key; @ids.unique.map(-> $id { self.validate-atts: $node, %($key => $id) }).first(*.so) // False } multi method validate-ids($node, $id) { print-validator-begin $node, $id; POST print-validator-end $node, $id, $_; self.validate-ids: $node, [$id,] } method validate-atts($node, %atts) { print-validator-begin $node, %atts; POST print-validator-end $node, %atts, $_; return ASTQuery::Match.new: :list[$node,] if ASTQuery::Match.merge-and: |%atts.kv.map: -> $key, $value is copy { $value = $value.($node) if $value ~~ Callable; self.validate-value: $node, $key, $value; } ; False } multi method validate-value($node, $key, $ where * =:= False) { print-validator-begin $node, True; POST print-validator-end $node, True, $_; False } multi method validate-value($node, $key, $ where * =:= True) { print-validator-begin $node, True; POST print-validator-end $node, True, $_; ASTQuery::Match.new: :list[$node,] } multi method validate-value($node, $key, $value) { print-validator-begin $node, $value; POST print-validator-end $node, $value, $_; do if $node.^name.starts-with("RakuAST") && $value !~~ ::?CLASS { return False unless $key; return False unless $node.^can: $key; # it can be a problem if $key is 'none', for example my Any $nnode = $node."$key"(); self.validate-value($nnode, $.get-id-field($nnode), $value) } else { $value.ACCEPTS($node) && ASTQuery::Match.new(:list[$node,]) } || False }
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: LICENSE.md ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:tbrowder", "author": "zef:tbrowder", "authors": [ "Tom Browder <[email protected]>" ], "build-depends": [ ], "depends": [ ], "description": "Provides an implementation of an AVL tree.", "license": "Artistic-2.0", "name": "AVL-Tree", "perl": "6.*", "provides": { "AVL-Tree": "lib/AVL-Tree.rakumod" }, "resources": [ ], "source-type": "git", "source-url": "git://github.com/tbrowder/AVL-Tree.git", "support": { "bugtracker": "https://github.com/tbrowder/AVL-Tree/issues" }, "tags": [ "tree", "BST", "set", "AVL" ], "test-depends": [ ], "version": "0.0.2" }
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: README.md ### ---------------------------------------------------- [![Actions Status](https://github.com/tbrowder/AVL-Tree/workflows/test/badge.svg)](https://github.com/tbrowder/AVL-Tree/actions) AVL-Tree ======== This implementation of an AVL Tree has been uploaded to [rosettacode.org](https://rosettacode.org). It was initially a translation of the Java version on Rosetta Code. In addition to the translated code, other public methods have been added as shown by the leading asterisk in the following list of all public methods: * insert node * delete node * show all node keys * show all node balances * *delete nodes by a list of node keys * *find and return node objects by key * *attach data per node * *return list of all node keys * *return list of all node objects Synopsis -------- See the example in the Github repository and on Rosetta Code. #!/usr/bin/env perl6 use AVL-Tree; # ...create a tree and some nodes... my $tree = AVL-Tree.new; $tree.insert: 1; $tree.insert: 2, :data<some important tidbit of knowledge>; $my $n = $tree.find: 2; say $n.data; some important tidbit of knowledge CREDITS ======= Thanks for help from IRC `#raku` friends: * `thundergnat` (for the idea and check of the initial version) AUTHOR ====== Tom Browder, ([email protected]) COPYRIGHT ========= & LICENSE Copyright (c) 2019-2022 Tom Browder, all rights reserved. This program is free software; you can redistribute it or modify it under the same terms as Raku itself with the following exception: The code for the methods **without a leading asterisk** in the list above are covered by the GNU Free Document License 1.2.
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: dist.ini ### ---------------------------------------------------- name = 'AVL-Tree' [ReadmeFromPod] enable = true filename = docs/README.pod [PruneFiles] ; match = ^ 'xt/' [UploadToZef] [Badges] provider = github-actions/test
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: bad/99.avl-tree.t ### ---------------------------------------------------- use v6; use Test; plan 16; use AVL-Tree; my @list = 1..10; my $tree = AVL-Tree.new; $tree.insert($_) for @list; # show keys my @keys = $tree.keys; is-deeply @keys, @list, 'get list of keys'; # delete keys my @odd = 1, 3, 5, 7, 9; my @even = 2, 4, 6, 8, 10; $tree.delete: @odd; @keys = $tree.keys; is-deeply @keys, @even, 'delete list of keys'; # show nodes my @n = $tree.nodes; for 0..3 { is @n[$_].key, @even[$_], 'test for key deletion'; } # find specific keys my $node = $tree.search: 2; is $node.key, 2, 'find existing key'; $node = $tree.search: 10; is $node.key, 10, 'find existing key'; # non-existent key $node = $tree.search: 100; nok $node, 'assure key was deleted'; # retrieve data $tree.insert: 12, :data<a>; $node = $tree.search: 12; is $node.data, 'a', 'assure key data is valid'; # find minimum key my $min = $tree.min; is $min.key, 2, 'find minimum key'; # find maximum key my $max = $tree.max; is $max.key, 12, 'find maximum key'; # find successors my $x = $tree.search: 10; my $s = $tree.successor: $x; is $s.key, 12, 'find successor'; $x = $tree.search: 12; $s = $tree.successor: $x; nok $s, 'find successor (nil) of max key'; # find predecessors $x = $tree.search: 8; $s = $tree.predecessor: $x; is $s.key, 6, 'find predecessor'; $x = $tree.search: 2; $s = $tree.predecessor: $x; nok $s, 'find predecessor (nil) of min key';
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: bad/demo-avl-tree-v1.t ### ---------------------------------------------------- use Test; use AVL-Tree; plan 1; lives-ok { my $tree = AVL-Tree.new; my @keys = 4, 2, -1, 4, 5, 9, 6, 14, 11, 20, 10; say "Keys to be inserted in the order shown (notice the two 4's):"; print " $_" for @keys; say ""; for @keys { $tree.insert: $_; } say "Keys shown in tree-in-order listing (notice no duplicates):"; $tree.show-keys; say ""; @keys = -1, 5, 9; say "Deleting odd keys:"; print " $_" for @keys; say ""; $tree.delete: @keys; $tree.delete: 11; say "Keys shown in tree-in-order listing (notice no odd keys):"; $tree.show-keys; say ""; # new stuff $tree.insert: 100, :data<some data>; $tree.show-keys; for 9, 10, 100 -> $key { my $n = $tree.find: $key; if $n { say "Found node with key '$key'"; say "Its data: '{$n.data}'"; } else { say "Found no node with key '$key'"; } } my @k = $tree.keys; say "Find all keys..."; print " $_" for @k; say(); my @n = $tree.nodes; say "Find all ..."; for @n -> $n { say "=== node key: {$n.key}"; say " data: {$n.data}"; } }
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: docs/README.pod ### ---------------------------------------------------- =begin pod =head1 AVL-Tree This implementation of an AVL Tree has been uploaded to L<rosettacode.org|https://rosettacode.org>. It was initially a translation of the Java version on Rosetta Code. In addition to the translated code, other public methods have been added as shown by the leading asterisk in the following list of all public methods: =item insert node =item delete node =item show all node keys =item show all node balances =item *delete nodes by a list of node keys =item *find and return node objects by key =item *attach data per node =item *return list of all node keys =item *return list of all node objects =head2 Synopsis See the example in the Github repository and on Rosetta Code. =begin code #!/usr/bin/env perl6 use AVL-Tree; # ...create a tree and some nodes... my $tree = AVL-Tree.new; $tree.insert: 1; $tree.insert: 2, :data<some important tidbit of knowledge>; $my $n = $tree.find: 2; say $n.data; some important tidbit of knowledge =end code =head1 CREDITS Thanks for help from IRC `#raku` friends: =item `thundergnat` (for the idea and check of the initial version) =AUTHOR Tom Browder, ([email protected]) =COPYRIGHT & LICENSE Copyright (c) 2019-2022 Tom Browder, all rights reserved. This program is free software; you can redistribute it or modify it under the same terms as Raku itself with the following exception: The code for the methods B<without a leading asterisk> in the list above are covered by the GNU Free Document License 1.2. =end pod
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: t/002-object-eq.t ### ---------------------------------------------------- use Test; use AVL-Tree; plan 1; my $tree = AVL-Tree.new; my @keys = 4, 2, -1, 4, 5, 9, 6, 14, 11, 20, 10; for @keys { $tree.insert: $_; } # new stuff $tree.insert: 100, :data<some data>; my $h1 = 0; my $h2 = 0; for 9, 10, 100 -> $key { my $n = $tree.find: $key; if $n { $h1 = $n if $key == 100; #say "Found node with key '$key'"; #say "Its data: '{$n.data}'"; } else { #say "Found no node with key '$key'"; } } for 9, 10, 100 -> $key { my $n = $tree.find: $key; if $n { $h2 = $n if $key == 100; #say "Found node with key '$key'"; #say "Its data: '{$n.data}'"; } else { #say "Found no node with key '$key'"; } } is $h1 === $h2, True, "nodes are the same object";
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: t/001-load.t ### ---------------------------------------------------- use Test; plan 1; use-ok 'AVL-Tree';
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: api2/AVL-Tree.rakumod ### ---------------------------------------------------- #|{{ This code has been translated from the Java version on <https://rosettacode.org>. Consequently, it should have the same license: GNU Free Document License 1.2. In addition to the translated code, other public methods have been added as shown by the asterisks in the following list of all public methods: + insert node + delete node + show all node keys + show all node balances + *delete nodes by a list of node keys + *search and return node objects by key + *attach data per node + *return list of all node keys + *return list of all node objects + *return node with minimum key + *return node with maximum key }} # see some solutions at: # https://mitpress.mit.edu/algorithms class AVL-Tree { has $.root is rw = 0; class Node { has $.key is rw = Nil; has $.parent is rw = 0; has $.data is rw = 0; has $.left is rw = 0; has $.right is rw = 0; has Int $.balance is rw = 0; has Int $.height is rw = 0; } #===================================================== # public methods #===================================================== #| return successor node of node x or 0 #| if x has the largest key in the tree method successor($x is copy) { die "FAILURE: Called 'successor' on a nil node." if !$x; return min($x.right) if $x.right; my $y = $x.parent; while $y && $x === $y.right { $x = $y; $y = $y.parent; } $y } #| return predecessor node of node x or 0 #| if x has the smallest key in the tree method predecessor($x is copy) { die "FAILURE: Called 'predecessor' on a nil node." if !$x; return max($x.left) if $x.left; my $y = $x.parent; while $y && $x === $y.left { $x = $y; $y = $y.parent; } $y } #| return node with minimum key in subtree of node x method min($x = $.root) { die "FATAL: Calling 'min' on a null node." if !$x; my $n = $x; while $n.left { $n = $n.left; } $n } #| return node with maximum key in subtree of node x method max($x = $.root) { die "FATAL: Calling 'max' on a null node." if !$x; my $n = $x; while $n.right { $n = $n.right; } $n } #| returns a node object or 0 if not found method search($key) { self!search: $key, $.root; } #| returns a list of tree keys method keys() { return () if !$.root; my @list; self!keys: $.root, @list; @list; } #| returns a list of tree nodes method nodes() { return () if !$.root; my @list; self!nodes: $.root, @list; @list; } #| insert a node key, optionally add data (the `parent` arg is for #| internal use only) method insert($key, :$data = 0, :$parent = 0) { # TODO don't allow dup key (default behavior) return $.root = Node.new: :$key, :$parent, :$data if !$.root; my $n = $.root; while True { return False if $n.key eq $key; my $parent = $n; my $goLeft = $n.key gt $key; $n = $goLeft ?? $n.left !! $n.right; if !$n { if $goLeft { $parent.left = Node.new: :$key, :$parent, :$data; } else { $parent.right = Node.new: :$key, :$parent, :$data; } self!rebalance: $parent; last } } True } #| delete one or more nodes by key method delete(*@del-key) { return if !$.root; for @del-key -> $del-key { return if !$.root; for @del-key -> $del-key { my $child = $.root; while $child { my $node = $child; $child = $del-key ge $node.key ?? $node.right !! $node.left; if $del-key eq $node.key { self!delete: $node; next; } } } } } #| show a list of all nodes by key method show-keys { self!show-keys: $.root; say() } #| show a list of all nodes' balances (not normally needed) method show-balances { self!show-balances: $.root; say() } #===================================================== # private methods #===================================================== method !delete($node) { if !$node.left && !$node.right { if !$node.parent { $.root = 0; } else { my $parent = $node.parent; if $parent.left === $node { $parent.left = 0; } else { $parent.right = 0; } self!rebalance: $parent; } return } if $node.left { my $child = $node.left; while $child.right { $child = $child.right; } $node.key = $child.key; self!delete: $child; } else { my $child = $node.right; while $child.left { $child = $child.left; } $node.key = $child.key; self!delete: $child; } } method !rebalance($n is copy) { self!set-balance: $n; if $n.balance == -2 { if self!height($n.left.left) >= self!height($n.left.right) { $n = self!rotate-right: $n; } else { $n = self!rotate-left'right: $n; } } elsif $n.balance == 2 { if self!height($n.right.right) >= self!height($n.right.left) { $n = self!rotate-left: $n; } else { $n = self!rotate-right'left: $n; } } if $n.parent { self!rebalance: $n.parent; } else { $.root = $n; } } method !rotate-left($a) { my $b = $a.right; $b.parent = $a.parent; $a.right = $b.left; if $a.right { $a.right.parent = $a; } $b.left = $a; $a.parent = $b; if $b.parent { if $b.parent.right === $a { $b.parent.right = $b; } else { $b.parent.left = $b; } } self!set-balance: $a, $b; $b; } method !rotate-right($a) { my $b = $a.left; $b.parent = $a.parent; $a.left = $b.right; if $a.left { $a.left.parent = $a; } $b.right = $a; $a.parent = $b; if $b.parent { if $b.parent.right === $a { $b.parent.right = $b; } else { $b.parent.left = $b; } } self!set-balance: $a, $b; $b; } method !rotate-left'right($n) { $n.left = self!rotate-left: $n.left; self!rotate-right: $n; } method !rotate-right'left($n) { $n.right = self!rotate-right: $n.right; self!rotate-left: $n; } method !height($n) { $n ?? $n.height !! -1; } method !set-balance(*@n) { for @n -> $n { self!reheight: $n; $n.balance = self!height($n.right) - self!height($n.left); } } method !show-balances($n) { if $n { self!show-balances: $n.left; printf "%s ", $n.balance; self!show-balances: $n.right; } } method !reheight($node) { if $node { $node.height = 1 + max self!height($node.left), self!height($node.right); } } method !show-keys($n) { if $n { self!show-keys: $n.left; printf "%s ", $n.key; self!show-keys: $n.right; } } method !nodes($n, @list) { return if !$n; self!nodes: $n.left, @list; @list.push: $n if $n; self!nodes: $n.right, @list; } method !keys($n, @list) { if $n { self!keys: $n.left, @list; @list.push: $n.key if $n; self!keys: $n.right, @list; } } method !search($key, $n is copy = $.root) { while $n && $key ne $n.key { if $key lt $n.key { $n = $n.left; } else { $n = $n.right; } } $n =begin comment if !$n || $key eq $n.key { return $n; } if $key lt $n.key { return self!search: $key, $n.left; } else { return self!search: $key, $n.right; } =end comment } }
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: lib/AVL-Tree.rakumod ### ---------------------------------------------------- # This is a class definition file #|{{ This code has been translated from the Java version on <https://rosettacode.org>. Consequently, it should have the same license: GNU Free Document License 1.2. In addition to the translated code, other public methods have been added as shown by the asterisks in the following list of all public methods: + insert node + delete node + show all node keys + show all node balances + *delete nodes by a list of node keys + *find and return node objects by key + *attach data per node + *return list of all node keys + *return list of all node objects }} class AVL-Tree { has $.root is rw = 0; class Node { has $.key is rw = ''; has $.parent is rw = 0; has $.data is rw = 0; has $.left is rw = 0; has $.right is rw = 0; has Int $.balance is rw = 0; has Int $.height is rw = 0; } #===================================================== # public methods #===================================================== #| returns a node object or 0 if not found method find($key) { return 0 if !$.root; self!find: $key, $.root; } #| returns a list of tree keys method keys() { return () if !$.root; my @list; self!keys: $.root, @list; @list; } #| returns a list of tree nodes method nodes() { return () if !$.root; my @list; self!nodes: $.root, @list; @list; } #| insert a node key, optionally add data (the `parent` arg is for #| internal use only) method insert($key, :$data = 0, :$parent = 0,) { return $.root = Node.new: :$key, :$parent, :$data if !$.root; my $n = $.root; while True { return False if $n.key eq $key; my $parent = $n; my $goLeft = $n.key > $key; $n = $goLeft ?? $n.left !! $n.right; if !$n { if $goLeft { $parent.left = Node.new: :$key, :$parent, :$data; } else { $parent.right = Node.new: :$key, :$parent, :$data; } self!rebalance: $parent; last } } True } #| delete one or more nodes by key method delete(*@del-key) { return if !$.root; for @del-key -> $del-key { my $child = $.root; while $child { my $node = $child; $child = $del-key >= $node.key ?? $node.right !! $node.left; if $del-key eq $node.key { self!delete: $node; next; } } } } #| show a list of all nodes by key method show-keys { self!show-keys: $.root; say() } #| show a list of all nodes' balances (not normally needed) method show-balances { self!show-balances: $.root; say() } #===================================================== # private methods #===================================================== method !delete($node) { if !$node.left && !$node.right { if !$node.parent { $.root = 0; } else { my $parent = $node.parent; if $parent.left === $node { $parent.left = 0; } else { $parent.right = 0; } self!rebalance: $parent; } return } if $node.left { my $child = $node.left; while $child.right { $child = $child.right; } $node.key = $child.key; self!delete: $child; } else { my $child = $node.right; while $child.left { $child = $child.left; } $node.key = $child.key; self!delete: $child; } } method !rebalance($n is copy) { self!set-balance: $n; if $n.balance == -2 { if self!height($n.left.left) >= self!height($n.left.right) { $n = self!rotate-right: $n; } else { $n = self!rotate-left'right: $n; } } elsif $n.balance == 2 { if self!height($n.right.right) >= self!height($n.right.left) { $n = self!rotate-left: $n; } else { $n = self!rotate-right'left: $n; } } if $n.parent { self!rebalance: $n.parent; } else { $.root = $n; } } method !rotate-left($a) { my $b = $a.right; $b.parent = $a.parent; $a.right = $b.left; if $a.right { $a.right.parent = $a; } $b.left = $a; $a.parent = $b; if $b.parent { if $b.parent.right === $a { $b.parent.right = $b; } else { $b.parent.left = $b; } } self!set-balance: $a, $b; $b; } method !rotate-right($a) { my $b = $a.left; $b.parent = $a.parent; $a.left = $b.right; if $a.left { $a.left.parent = $a; } $b.right = $a; $a.parent = $b; if $b.parent { if $b.parent.right === $a { $b.parent.right = $b; } else { $b.parent.left = $b; } } self!set-balance: $a, $b; $b; } method !rotate-left'right($n) { $n.left = self!rotate-left: $n.left; self!rotate-right: $n; } method !rotate-right'left($n) { $n.right = self!rotate-right: $n.right; self!rotate-left: $n; } method !height($n) { $n ?? $n.height !! -1; } method !set-balance(*@n) { for @n -> $n { self!reheight: $n; $n.balance = self!height($n.right) - self!height($n.left); } } method !show-balances($n) { if $n { self!show-balances: $n.left; printf "%s ", $n.balance; self!show-balances: $n.right; } } method !reheight($node) { if $node { $node.height = 1 + max self!height($node.left), self!height($node.right); } } method !show-keys($n) { if $n { self!show-keys: $n.left; printf "%s ", $n.key; self!show-keys: $n.right; } } method !nodes($n, @list) { if $n { self!nodes: $n.left, @list; @list.push: $n if $n; self!nodes: $n.right, @list; } } method !keys($n, @list) { if $n { self!keys: $n.left, @list; @list.push: $n.key if $n; self!keys: $n.right, @list; } } method !find($key, $n) { if $n { self!find: $key, $n.left; return $n if $n.key eq $key; self!find: $key, $n.right; } } }
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: dev/do.raku ### ---------------------------------------------------- use lib <./lib>; use AVL-Tree; my $tree = AVL-Tree.new; for 1..10 { $tree.insert: $_; } $tree.show-keys; my $n = $tree.find: 2; $n ?? say $n.key !! say 'not found';
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: dev/test-cmp.raku ### ---------------------------------------------------- my $a = 'a'; my $b = 1; my $c = '1'; say "$a cmp $b: {$a cmp $b}"; say "$a cmp $c: {$a cmp $c}"; say "$b cmp $a: {$b cmp $a}"; say "$b cmp $c: {$b cmp $c}"; say "$a cmp $a: {$a cmp $a}"; say "$b cmp $b: {$b cmp $b}";
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: dev/demo-avl-tree-v2.raku ### ---------------------------------------------------- # This code tracks the tests. use AVL-Tree:api<2>; my $tree = AVL-Tree.new; my @list = 1..10, 4; say "Keys to be inserted in the order shown (notice the two 4's):"; print " $_" for @list; say ""; $tree.insert($_) for @list; say "Keys shown in tree-in-order listing (notice no duplicates):"; $tree.show-keys; say ""; my @odd = 1, 3, 5, 7, 9; my @even = 2, 4, 6, 8, 10; say "Deleting odd keys:"; my @keys = $tree.keys; print " $_" for @keys; say ""; $tree.delete: @odd; say "Keys shown in tree-in-order listing (notice no odd keys):"; $tree.show-keys; say ""; # new stuff say "Entering new node with key '100' and data 'some data'"; $tree.insert: 100, :data<some data>; my @k = $tree.keys; say "Find all keys..."; print " $_" for @k; say(); my @n = $tree.nodes; say "Find all data..."; for @n -> $n { next if !$n.data; say "=== node key: {$n.key}"; say " data: '{$n.data}'"; } say "Find non-existent key 200:"; my $x = $tree.search: 200; say "Found key 200? {$x ?? $x.key !! 'not found'}"; say "Find existing key 10:"; $x = $tree.search: 10; say "Found key 200? {$x ?? $x.key !! 'not found' }"; say "Find min key:"; $x = $tree.min; say "Result: {$x ?? $x.key !! $x}"; say "Find max key:"; $x = $tree.max; say "Result: {$x ?? $x.key !! $x}";
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: eg/demo-avl-tree-v1.raku ### ---------------------------------------------------- use AVL-Tree; my $tree = AVL-Tree.new; my @keys = 4, 2, -1, 4, 5, 9, 6, 14, 11, 20, 10; say "Keys to be inserted in the order shown (notice the two 4's):"; print " $_" for @keys; say ""; for @keys { $tree.insert: $_; } say "Keys shown in tree-in-order listing (notice no duplicates):"; $tree.show-keys; say ""; @keys = -1, 5, 9; say "Deleting odd keys:"; print " $_" for @keys; say ""; $tree.delete: @keys; $tree.delete: 11; say "Keys shown in tree-in-order listing (notice no odd keys):"; $tree.show-keys; say ""; # new stuff $tree.insert: 100, :data<some data>; $tree.show-keys; for 9, 10, 100 -> $key { my $n = $tree.find: $key; if $n { say "Found node with key '$key'"; say "Its data: '{$n.data}'"; } else { say "Found no node with key '$key'"; } } my @k = $tree.keys; say "Find all keys..."; print " $_" for @k; say(); my @n = $tree.nodes; say "Find all ..."; for @n -> $n { say "=== node key: {$n.key}"; say " data: {$n.data}"; }
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: sto/demo-avl-tree.raku ### ---------------------------------------------------- #!/usr/bin/env raku # This code tracks the tests. use lib <.>; # ../lib>; use AVL-Tree; my $tree = AVL-Tree.new; my @list = 1..10, 4; say "Keys to be inserted in the order shown (notice the two 4's):"; print " $_" for @list; say ""; $tree.insert($_) for @list; say "Keys shown in tree-in-order listing (notice no duplicates):"; $tree.show-keys; say ""; my @odd = 1, 3, 5, 7, 9; my @even = 2, 4, 6, 8, 10; say "Deleting odd keys:"; my @keys = $tree.keys; print " $_" for @keys; say ""; $tree.delete: @odd; say "Keys shown in tree-in-order listing (notice no odd keys):"; $tree.show-keys; say ""; # new stuff say "Entering new node with key '100' and data 'some data'"; $tree.insert: 100, :data<some data>; # more new stuff say "Entering new node with string key 'abc' and data 'some more data'"; $tree.insert: 'abc', :data<some more data>; my @k = $tree.keys; say "Find all keys..."; print " $_" for @k; say(); my @n = $tree.nodes; say "Find all data..."; for @n -> $n { next if !$n.data; say "=== node key: {$n.key}"; say " data: '{$n.data}'"; } say "Find non-existent key 200:"; my $x = $tree.search: 200; say "Found key 200? {$x ?? $x.key !! 'not found'}"; say "Find existing key 10:"; $x = $tree.search: 10; say "Found key 10? {$x ?? $x.key !! 'not found' }"; say "Find min key:"; $x = $tree.min; say "Result: {$x ?? $x.key !! $x}"; say "Find max key:"; $x = $tree.max; say "Result: {$x ?? $x.key !! $x}";
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: sto/do.raku ### ---------------------------------------------------- use lib <. ./lib>; use AVL-Tree; my $tree = AVL-Tree.new; for 1..10 { $tree.insert: $_; } $tree.show-keys; my $n = $tree.search: 2; $n ?? say $n.key !! say 'not found';
### ---------------------------------------------------- ### -- AVL-Tree ### -- Licenses: Artistic-2.0 ### -- Authors: Tom Browder <[email protected]> ### -- File: sto/AVL-Tree.rakumod ### ---------------------------------------------------- #|{{ This code has been translated from the Java version on <https://rosettacode.org>. Consequently, it should have the same license: GNU Free Document License 1.2. In addition to the translated code, other public methods have been added as shown by the asterisks in the following list of all public methods: + insert node + delete node + show all node keys + show all node balances + *delete nodes by a list of node keys + *search and return node objects by key + *attach data per node + *return list of all node keys + *return list of all node objects + *return node with minimum key + *return node with maximum key }} # see some solutions at: # https://mitpress.mit.edu/algorithms class AVL-Tree { has $.root is rw = 0; class Node { has $.key is rw = Nil; has $.parent is rw = 0; has $.data is rw = 0; has $.left is rw = 0; has $.right is rw = 0; has Int $.balance is rw = 0; has Int $.height is rw = 0; # for types has $.type = NumStr; # uses coercion to Str for infix lt, eq, gt, etc. } #===================================================== # public methods #===================================================== #| return successor node of node x or 0 #| if x has the largest key in the tree method successor($x is copy) { die "FAILURE: Called 'successor' on a Nil node." if !$x; return min($x.right) if $x.right; my $y = $x.parent; while $y && $x === $y.right { $x = $y; $y = $y.parent; } $y } #| return predecessor node of node x or 0 #| if x has the smallest key in the tree method predecessor($x is copy) { die "FAILURE: Called 'predecessor' on a Nil node." if !$x; return max($x.left) if $x.left; my $y = $x.parent; while $y && $x === $y.left { $x = $y; $y = $y.parent; } $y } #| return node with minimum key in subtree of node x method min($x = $.root) { die "FATAL: Called 'min' on a Nil node." if not $x; my $n = $x; while $n.left { $n = $n.left; } $n } #| return node with maximum key in subtree of node x method max($x = $.root) { die "FATAL: Called 'max' on a Nil node." if not $x; my $n = $x; while $n.right { $n = $n.right; } $n } #| returns a node object or Nil if not found method search($key) { self!search: $key, $.root; } #| returns a list of tree keys method keys() { return () if not $.root; my @list; self!keys: $.root, @list; @list; } #| returns a list of tree nodes method nodes() { return () if not $.root; my @list; self!nodes: $.root, @list; @list; } #| insert a node key, optionally add data (the `parent` arg is for #| internal use only) method insert($key, :$data = 0, :$parent = 0) { # TODO don't allow dup key (default behavior) # search for an existing key return $.root = Node.new(:$key, :$parent, :$data) if not $.root; my $n = $.root; while True { return False if $n.key eq $key; my $parent = $n; my $goLeft = $n.key gt $key; $n = $goLeft ?? $n.left !! $n.right; if not $n { if $goLeft { $parent.left = Node.new: :$key, :$parent, :$data; } else { $parent.right = Node.new: :$key, :$parent, :$data; } self!rebalance: $parent; last } die "FATAL: equal keys" if $n.key eq $key; } True } #| delete one or more nodes by key method delete(*@del-key) { return if not $.root; for @del-key -> $del-key { return if not $.root; for @del-key -> $del-key { my $child = $.root; while $child { my $node = $child; $child = $del-key ge $node.key ?? $node.right !! $node.left; if $del-key eq $node.key { self!delete: $node; next; } } } } } #| show a list of all nodes by key method show-keys { self!show-keys: $.root; say() } #| show a list of all nodes' balances (not normally needed) method show-balances { self!show-balances: $.root; say() } #===================================================== # private methods #===================================================== method !delete($node) { if !$node.left && !$node.right { if !$node.parent { $.root = 0; } else { my $parent = $node.parent; if $parent.left === $node { $parent.left = 0; } else { $parent.right = 0; } self!rebalance: $parent; } return } if $node.left { my $child = $node.left; while $child.right { $child = $child.right; } $node.key = $child.key; self!delete: $child; } else { my $child = $node.right; while $child.left { $child = $child.left; } $node.key = $child.key; self!delete: $child; } } method !rebalance($n is copy) { self!set-balance: $n; if $n.balance == -2 { if self!height($n.left.left) ge self!height($n.left.right) { $n = self!rotate-right: $n; } else { $n = self!rotate-left'right: $n; } } elsif $n.balance == 2 { if self!height($n.right.right) ge self!height($n.right.left) { $n = self!rotate-left: $n; } else { $n = self!rotate-right'left: $n; } } if $n.parent { self!rebalance: $n.parent; } else { $.root = $n; } } method !rotate-left($a) { my $b = $a.right; $b.parent = $a.parent; $a.right = $b.left; if $a.right { $a.right.parent = $a; } $b.left = $a; $a.parent = $b; if $b.parent { if $b.parent.right === $a { $b.parent.right = $b; } else { $b.parent.left = $b; } } self!set-balance: $a, $b; $b; } method !rotate-right($a) { my $b = $a.left; $b.parent = $a.parent; $a.left = $b.right; if $a.left { $a.left.parent = $a; } $b.right = $a; $a.parent = $b; if $b.parent { if $b.parent.right === $a { $b.parent.right = $b; } else { $b.parent.left = $b; } } self!set-balance: $a, $b; $b; } method !rotate-left'right($n) { $n.left = self!rotate-left: $n.left; self!rotate-right: $n; } method !rotate-right'left($n) { $n.right = self!rotate-right: $n.right; self!rotate-left: $n; } method !height($n) { $n ?? $n.height !! -1; } method !set-balance(*@n) { for @n -> $n { self!reheight: $n; $n.balance = self!height($n.right) - self!height($n.left); } } method !show-balances($n) { if $n { self!show-balances: $n.left; printf "%s ", $n.balance; self!show-balances: $n.right; } } method !reheight($node) { if $node { $node.height = 1 + max self!height($node.left), self!height($node.right); } } method !show-keys($n) { if $n { self!show-keys: $n.left; printf "%s ", $n.key; self!show-keys: $n.right; } } method !nodes($n, @list) { return if !$n; self!nodes: $n.left, @list; @list.push: $n if $n; self!nodes: $n.right, @list; } method !keys($n, @list) { if $n { self!keys: $n.left, @list; @list.push: $n.key if $n; self!keys: $n.right, @list; } } method !search($key, $n is copy = $.root) { while $n && $key ne $n.key { if $key lt $n.key { $n = $n.left; } else { $n = $n.right; } } $n =begin comment if !$n || $key eq $n.key { return $n; } if $key lt $n.key { return self!search: $key, $n.left; } else { return self!search: $key, $n.right; } =end comment } }
### ---------------------------------------------------- ### -- AWS::Pricing ### -- Licenses: Artistic-2.0 ### -- Authors: Sam Morrison ### -- File: META6.json ### ---------------------------------------------------- { "perl" : "6.*", "name" : "AWS::Pricing", "version" : "0.2.3", "author" : "github:scmorrison", "license" : "Artistic-2.0", "description" : "AWS Price List API library", "build-depends" : [], "test-depends" : [ "Test" ], "provides" : { "AWS::Pricing" : "lib/AWS/Pricing.pm6", "AWS::Pricing::CLI" : "lib/AWS/Pricing/CLI.pm6" }, "depends" : [ "HTTP::Tinyish", "Test" ], "source-url" : "git://github.com/scmorrison/perl6-aws-pricing.git", "authors" : [ "Sam Morrison" ] }
### ---------------------------------------------------- ### -- AWS::Pricing ### -- Licenses: Artistic-2.0 ### -- Authors: Sam Morrison ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2015, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- AWS::Pricing ### -- Licenses: Artistic-2.0 ### -- Authors: Sam Morrison ### -- File: README.md ### ---------------------------------------------------- AWS::Pricing [![Build Status](https://travis-ci.org/scmorrison/perl6-aws-pricing.svg?branch=master)](https://travis-ci.org/scmorrison/perl6-aws-pricing) ============ Description =========== Return, and cache, current offers from the AWS Price List API. Usage ===== ```bash aws-pricing - Pull AWS Pricing data from the AWS Pricing API USAGE aws-pricing services aws-pricing service-offers <service_code>; aws-pricing service-codes aws-pricing regions aws-pricing version COMMANDS services Return Service Offer index service-offers Return Service Offers for specific service code and/or region service-codes List all valid service codes regions List all valid regions version Display aws-pricing version OPTIONS service-offers specific --format json|csv Default json --region Filter AWS region to pull offer data --header Display the CSV header. Disabled by default FLAGS --refresh Force cache_dir refresh --cache_path Path to cache path service offer files (Default ~/.aws-pricing) --quiet No output, cache only (services, service-offers) ``` CLI === ## List services ``` # Return Service Offer Index aws-pricing services # Refresh local cache aws-pricing --refresh services # Refresh local cache, no output aws-pricing --refresh --quiet services ``` ## List service offers ``` # Default json format aws-pricing service-offers AmazonEC2 # Output csv format aws-pricing --format=csv service-offers AmazonEC2 # Output csv format with headers aws-pricing --headers --format=csv service-offers AmazonEC2 # Refresh local cache aws-pricing --refresh --format=csv service-offers AmazonEC2 # Refresh local cache, no output aws-pricing --refresh --quiet --format=csv service-offers AmazonEC2 ``` ## List valid Service Codes ``` aws-pricing service-codes ``` ## List valid Regions ``` aws-pricing regions ``` ## Print aws-pricing version ``` aws-pricing version ``` Modules and utilities ===================== AWS::Pricing -------------- ```perl6 use AWS::Pricing; my $config = AWS::Pricing::config( refresh => True, cache_path => '~/.aws-pricing' # Default path ); # Service Offer Index JSON AWS::Pricing::services; # Service Offer Indexes with custom config AWS::Pricing::services config => $config; # Service Codes List AWS::Pricing::service-codes; # Regions List AWS::Pricing::regions; # Service Offers: All regions AWS::Pricing::service-offers(service_code => 'AmazonEC2'); # Service Offers: Single region AWS::Pricing::service-offers( service_code => 'AmazonEC2', region => 'us-west-1' ); # Service Offers: Single region, config, csv, region AWS::Pricing::service-offers( config => $config, service_code => 'AmazonS3', format => 'csv', region => 'eu-west-1', display_header => True ); ``` ### Valid service codes: * AmazonS3 * AmazonGlacier * AmazonSES * AmazonRDS * AmazonSimpleDB * AmazonDynamoDB * AmazonEC2 * AmazonRoute53 * AmazonRedshift * AmazonElastiCache * AmazonCloudFront * awskms * AmazonVPC ### Valid regions * us-east-1 * us-east-2 * us-west-1 * us-west-2 * eu-west-1 * ap-southeast-1 * ap-southeast-2 * ap-northeast-1 * ap-northeast-2 * sa-east-1 * eu-central-1 * us-gov-west-1 * ap-south-1 * ca-central-1 * eu-west-2 Installation ============ Install directly with zef: ``` zef install AWS::Pricing ``` Testing ======= To run tests: ``` $ prove -e "perl6 -Ilib" ``` Todo ==== * ~~Cache offer files, these are large~~ * Search offers (must cache first) * Tests See also ======== * http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/price-changes.html Authors ======= * Sam Morrison Copyright and license ===================== Copyright 2015 Sam Morrison This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- AWS::Pricing ### -- Licenses: Artistic-2.0 ### -- Authors: Sam Morrison ### -- File: .travis.yml ### ---------------------------------------------------- language: generic install: - curl -O -J -L https://github.com/nxadm/rakudo-pkg/releases/download/2017.03_03/perl6-rakudo-moarvm-ubuntu16.10_20170300-03_amd64.deb - sudo dpkg -i perl6-rakudo-moarvm-ubuntu16.10_20170300-03_amd64.deb - export PATH=/opt/rakudo/bin:~/.perl6/bin:$PATH - /opt/rakudo/bin/install_zef_as_user - ~/.perl6/bin/zef --force --/test install . script: - prove -v -e 'perl6 -Ilib' t/ sudo: sudo
### ---------------------------------------------------- ### -- AWS::Pricing ### -- Licenses: Artistic-2.0 ### -- Authors: Sam Morrison ### -- File: t/02-cache.t ### ---------------------------------------------------- use v6; use Test; use lib 'lib'; use AWS::Pricing; plan 5; # list-offers (json) my $r1_cached_offers = slurp "t/data/offers.json"; my $r1_offers = AWS::Pricing::services( config => AWS::Pricing::config(cache_path => 't/data') ); is $r1_offers, $r1_cached_offers, 'list-offers 1/1: json'; # service-offers (json) my $r2_service_code = 'AmazonS3'; my $r2_cached_service_offers = slurp "t/data/service-offers-$r2_service_code.json"; my $r2_service_offers = AWS::Pricing::service-offers( config => AWS::Pricing::config(cache_path => 't/data'), service_code => $r2_service_code ); is $r2_service_offers, $r2_cached_service_offers, 'service-offers 1/4: json'; # service-offers (json: region) my $r3_service_code = 'AmazonS3'; my $r3_region = 'eu-west-1'; my $r3_cached_service_offers = slurp "t/data/service-offers-{$r3_service_code}-{$r3_region}.json"; my $r3_service_offers = AWS::Pricing::service-offers( config => AWS::Pricing::config(cache_path => 't/data'), service_code => $r3_service_code, region => $r3_region ); is $r3_service_offers, $r3_cached_service_offers, 'service-offers 2/4: json (region)'; # service-offers (csv) my $r4_service_code = 'AmazonVPC'; my $r4_cached_service_offers = slurp "t/data/service-offers-$r4_service_code.csv"; my $r4_service_offers = AWS::Pricing::service-offers( config => AWS::Pricing::config(cache_path => 't/data'), service_code => $r4_service_code, format => 'csv' ); is $r4_service_offers, AWS::Pricing::strip-header-csv($r4_cached_service_offers), 'service-offers 3/4: csv'; # service-offers (csv: region) my $r5_service_code = 'AmazonS3'; my $r5_region = 'eu-west-1'; my $r5_cached_service_offers = slurp "t/data/service-offers-{$r5_service_code}-{$r5_region}.csv"; my $r5_service_offers = AWS::Pricing::service-offers( config => AWS::Pricing::config(cache_path => 't/data'), service_code => $r5_service_code, format => 'csv', region => $r5_region ); is $r5_service_offers, AWS::Pricing::strip-header-csv($r5_cached_service_offers), 'service-offers 4/4: csv (region)';
### ---------------------------------------------------- ### -- AWS::Pricing ### -- Licenses: Artistic-2.0 ### -- Authors: Sam Morrison ### -- File: t/01-config.t ### ---------------------------------------------------- use v6; use Test; use lib 'lib'; use AWS::Pricing; plan 3; # config my $tmp_cache_path = $*TMPDIR ~ "/aws-pricing-config-test"; my $config = AWS::Pricing::config( api_version => 'v1.0', cache_path => $tmp_cache_path, refresh => True ); is $config<api_version>, 'v1.0', 'config 1/3'; is $config<cache_path>, $tmp_cache_path, 'config 2/3'; is $config<refresh>, True, 'config 3/3';
### ---------------------------------------------------- ### -- AWS::Pricing ### -- Licenses: Artistic-2.0 ### -- Authors: Sam Morrison ### -- File: t/00-basics.t ### ---------------------------------------------------- use Test; use AWS::Pricing; plan 1; # use use-ok('AWS::Pricing');
### ---------------------------------------------------- ### -- AWS::Pricing ### -- Licenses: Artistic-2.0 ### -- Authors: Sam Morrison ### -- File: t/data/offers.json ### ---------------------------------------------------- { "formatVersion" : "v1.0", "disclaimer" : "This pricing list is for informational purposes only. All prices are subject to the additional terms included in the pricing pages on http://aws.amazon.com. All Free Tier prices are also subject to the terms included at https://aws.amazon.com/free/", "publicationDate" : "2016-06-28T05:22:49Z", "offers" : { "AmazonS3" : { "offerCode" : "AmazonS3", "versionIndexUrl" : "/offers/v1.0/aws/AmazonS3/index.json", "currentVersionUrl" : "/offers/v1.0/aws/AmazonS3/current/index.json" }, "AmazonGlacier" : { "offerCode" : "AmazonGlacier", "versionIndexUrl" : "/offers/v1.0/aws/AmazonGlacier/index.json", "currentVersionUrl" : "/offers/v1.0/aws/AmazonGlacier/current/index.json" }, "AmazonSES" : { "offerCode" : "AmazonSES", "versionIndexUrl" : "/offers/v1.0/aws/AmazonSES/index.json", "currentVersionUrl" : "/offers/v1.0/aws/AmazonSES/current/index.json" }, "AmazonRDS" : { "offerCode" : "AmazonRDS", "versionIndexUrl" : "/offers/v1.0/aws/AmazonRDS/index.json", "currentVersionUrl" : "/offers/v1.0/aws/AmazonRDS/current/index.json" }, "AmazonSimpleDB" : { "offerCode" : "AmazonSimpleDB", "versionIndexUrl" : "/offers/v1.0/aws/AmazonSimpleDB/index.json", "currentVersionUrl" : "/offers/v1.0/aws/AmazonSimpleDB/current/index.json" }, "AmazonDynamoDB" : { "offerCode" : "AmazonDynamoDB", "versionIndexUrl" : "/offers/v1.0/aws/AmazonDynamoDB/index.json", "currentVersionUrl" : "/offers/v1.0/aws/AmazonDynamoDB/current/index.json" }, "AmazonEC2" : { "offerCode" : "AmazonEC2", "versionIndexUrl" : "/offers/v1.0/aws/AmazonEC2/index.json", "currentVersionUrl" : "/offers/v1.0/aws/AmazonEC2/current/index.json" }, "AmazonRoute53" : { "offerCode" : "AmazonRoute53", "versionIndexUrl" : "/offers/v1.0/aws/AmazonRoute53/index.json", "currentVersionUrl" : "/offers/v1.0/aws/AmazonRoute53/current/index.json" }, "AmazonRedshift" : { "offerCode" : "AmazonRedshift", "versionIndexUrl" : "/offers/v1.0/aws/AmazonRedshift/index.json", "currentVersionUrl" : "/offers/v1.0/aws/AmazonRedshift/current/index.json" }, "AmazonElastiCache" : { "offerCode" : "AmazonElastiCache", "versionIndexUrl" : "/offers/v1.0/aws/AmazonElastiCache/index.json", "currentVersionUrl" : "/offers/v1.0/aws/AmazonElastiCache/current/index.json" }, "AmazonCloudFront" : { "offerCode" : "AmazonCloudFront", "versionIndexUrl" : "/offers/v1.0/aws/AmazonCloudFront/index.json", "currentVersionUrl" : "/offers/v1.0/aws/AmazonCloudFront/current/index.json" }, "awskms" : { "offerCode" : "awskms", "versionIndexUrl" : "/offers/v1.0/aws/awskms/index.json", "currentVersionUrl" : "/offers/v1.0/aws/awskms/current/index.json" }, "AmazonVPC" : { "offerCode" : "AmazonVPC", "versionIndexUrl" : "/offers/v1.0/aws/AmazonVPC/index.json", "currentVersionUrl" : "/offers/v1.0/aws/AmazonVPC/current/index.json" } } }