_id stringlengths 64 64 | repository stringlengths 6 84 | name stringlengths 4 110 | content stringlengths 0 248k | license null | download_url stringlengths 89 454 | language stringclasses 7
values | comments stringlengths 0 74.6k | code stringlengths 0 248k |
|---|---|---|---|---|---|---|---|---|
f2805556c57853652614afb1686ee7adb1a306ea5eb37ff9e8425da7aa79cea3 | wilkerlucio/pathom-connect-youtube | videos.cljs | (ns com.wsscode.pathom.connect.youtube.videos
(:require [clojure.string :as str]
[com.wsscode.common.async-cljs :refer [<? go-catch]]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom.connect.youtube.helpers :as yth]))
(def video-output
[:youtube.video.localizations.key/title
:youtube.video.localizations.key/description
:youtube.video.snippet/description
:youtube.video.snippet/tags
:youtube.video.snippet/published-at
:youtube.video.snippet/channel-id
:youtube.video.snippet/category-id
{:youtube.video.snippet.thumbnails/default [:youtube.thumbnail/url
:youtube.thumbnail/width
:youtube.thumbnail/height]}
{:youtube.video.snippet.thumbnails/medium [:youtube.thumbnail/url
:youtube.thumbnail/width
:youtube.thumbnail/height]}
{:youtube.video.snippet.thumbnails/high [:youtube.thumbnail/url
:youtube.thumbnail/width
:youtube.thumbnail/height]}
{:youtube.video.snippet.thumbnails/standard [:youtube.thumbnail/url
:youtube.thumbnail/width
:youtube.thumbnail/height]}
{:youtube.video.snippet.thumbnails/maxres [:youtube.thumbnail/url
:youtube.thumbnail/width
:youtube.thumbnail/height]}
:youtube.video.snippet/title
:youtube.video.snippet/default-audio-language
:youtube.video.snippet/live-broadcast-content
:youtube.video.snippet.localized/title
:youtube.video.snippet.localized/description
:youtube.video.snippet/channel-title
:youtube.video.snippet/default-language
:youtube.video.file-details/creation-time
:youtube.video.file-details/file-size
:youtube.video.file-details/file-type
:youtube.video.file-details/file-name
:youtube.video.file-details/bitrate-bps
{:youtube.video.file-details/video-streams [:youtube.video.file-details.video-streams/width-pixels
:youtube.video.file-details.video-streams/height-pixels
:youtube.video.file-details.video-streams/frame-rate-fps
:youtube.video.file-details.video-streams/aspect-ratio
:youtube.video.file-details.video-streams/codec
:youtube.video.file-details.video-streams/bitrate-bps
:youtube.video.file-details.video-streams/rotation
:youtube.video.file-details.video-streams/vendor]}
:youtube.video.file-details/container
:youtube.video.file-details/duration-ms
{:youtube.video.file-details/audio-streams [:youtube.video.file-details.audio-streams/channel-count
:youtube.video.file-details.audio-streams/codec
:youtube.video.file-details.audio-streams/bitrate-bps
:youtube.video.file-details.audio-streams/vendor]}
:youtube.video/etag
:youtube.video.recording-details/recording-date
:youtube.video.statistics/view-count
:youtube.video.statistics/like-count
:youtube.video.statistics/dislike-count
:youtube.video.statistics/favorite-count
:youtube.video.statistics/comment-count
:youtube.video.status/upload-status
:youtube.video.status/failure-reason
:youtube.video.status/rejection-reason
:youtube.video.status/privacy-status
:youtube.video.status/publish-at
:youtube.video.status/license
:youtube.video.status/embeddable
:youtube.video.status/public-stats-viewable
:youtube.video.processing-details/processing-status
:youtube.video.processing-details.processing-progress/parts-total
:youtube.video.processing-details.processing-progress/parts-processed
:youtube.video.processing-details.processing-progress/time-left-ms
:youtube.video.processing-details/processing-failure-reason
:youtube.video.processing-details/file-details-availability
:youtube.video.processing-details/processing-issues-availability
:youtube.video.processing-details/tag-suggestions-availability
:youtube.video.processing-details/editor-suggestions-availability
:youtube.video.processing-details/thumbnails-availability
:youtube.video/id
:youtube.video.live-streaming-details/actual-start-time
:youtube.video.live-streaming-details/actual-end-time
:youtube.video.live-streaming-details/scheduled-start-time
:youtube.video.live-streaming-details/scheduled-end-time
:youtube.video.live-streaming-details/concurrent-viewers
:youtube.video.live-streaming-details/active-live-chat-id
:youtube.video.suggestions/processing-errors
:youtube.video.suggestions/processing-warnings
:youtube.video.suggestions/processing-hints
{:youtube.video.suggestions/tag-suggestions [:youtube.video.suggestions.tag-suggestions/tag
:youtube.video.suggestions.tag-suggestions/category-restricts]}
:youtube.video.suggestions/editor-suggestions
:youtube.video.content-details/caption
:youtube.video.content-details/definition
:youtube.video.content-details/licensed-content
:youtube.video.content-details/duration
:youtube.video.content-details.content-rating/mccyp-rating
:youtube.video.content-details.content-rating/ilfilm-rating
:youtube.video.content-details.content-rating/lsf-rating
:youtube.video.content-details.content-rating/mccaa-rating
:youtube.video.content-details.content-rating/fsk-rating
:youtube.video.content-details.content-rating/mtrcb-rating
:youtube.video.content-details.content-rating/grfilm-rating
:youtube.video.content-details.content-rating/kijkwijzer-rating
:youtube.video.content-details.content-rating/czfilm-rating
:youtube.video.content-details.content-rating/incaa-rating
:youtube.video.content-details.content-rating/resorteviolencia-rating
:youtube.video.content-details.content-rating/eefilm-rating
:youtube.video.content-details.content-rating/cna-rating
:youtube.video.content-details.content-rating/moctw-rating
:youtube.video.content-details.content-rating/tvpg-rating
:youtube.video.content-details.content-rating/bfvc-rating
:youtube.video.content-details.content-rating/bmukk-rating
:youtube.video.content-details.content-rating/cce-rating
:youtube.video.content-details.content-rating/cnc-rating
:youtube.video.content-details.content-rating/fco-rating
:youtube.video.content-details.content-rating/ifco-rating
:youtube.video.content-details.content-rating/oflc-rating
:youtube.video.content-details.content-rating/chvrs-rating
:youtube.video.content-details.content-rating/cbfc-rating
:youtube.video.content-details.content-rating/csa-rating
:youtube.video.content-details.content-rating/icaa-rating
:youtube.video.content-details.content-rating/djctq-rating-reasons
:youtube.video.content-details.content-rating/fcbm-rating
:youtube.video.content-details.content-rating/pefilm-rating
:youtube.video.content-details.content-rating/yt-rating
:youtube.video.content-details.content-rating/nfvcb-rating
:youtube.video.content-details.content-rating/cscf-rating
:youtube.video.content-details.content-rating/djctq-rating
:youtube.video.content-details.content-rating/kmrb-rating
:youtube.video.content-details.content-rating/smais-rating
:youtube.video.content-details.content-rating/bbfc-rating
:youtube.video.content-details.content-rating/skfilm-rating
:youtube.video.content-details.content-rating/nbc-rating
:youtube.video.content-details.content-rating/eirin-rating
:youtube.video.content-details.content-rating/nkclv-rating
:youtube.video.content-details.content-rating/moc-rating
:youtube.video.content-details.content-rating/smsa-rating
:youtube.video.content-details.content-rating/medietilsynet-rating
:youtube.video.content-details.content-rating/mpaa-rating
:youtube.video.content-details.content-rating/meku-rating
:youtube.video.content-details.content-rating/ecbmct-rating
:youtube.video.content-details.content-rating/rte-rating
:youtube.video.content-details.content-rating/mibac-rating
:youtube.video.content-details.content-rating/mda-rating
:youtube.video.content-details.content-rating/chfilm-rating
:youtube.video.content-details.content-rating/rcnof-rating
:youtube.video.content-details.content-rating/egfilm-rating
:youtube.video.content-details.content-rating/anatel-rating
:youtube.video.content-details.content-rating/catvfr-rating
:youtube.video.content-details.content-rating/acb-rating
:youtube.video.content-details.content-rating/rtc-rating
:youtube.video.content-details.content-rating/russia-rating
:youtube.video.content-details.content-rating/ccc-rating
:youtube.video.content-details.content-rating/agcom-rating
:youtube.video.content-details.content-rating/catv-rating
:youtube.video.content-details.content-rating/kfcb-rating
:youtube.video.content-details.content-rating/cicf-rating
:youtube.video.content-details.content-rating/mcst-rating
:youtube.video.content-details.content-rating/nbcpl-rating
:youtube.video.content-details.content-rating/nfrc-rating
:youtube.video.content-details.content-rating/fpb-rating
:youtube.video.content-details.content-rating/fpb-rating-reasons
:youtube.video.content-details.content-rating/fmoc-rating
:youtube.video.content-details.content-rating/mpaat-rating
:youtube.video.content-details.region-restriction/allowed
:youtube.video.content-details.region-restriction/blocked
:youtube.video.content-details/dimension
:youtube.video.content-details/projection
:youtube.video.content-details/has-custom-thumbnail
:youtube.video.player/embed-html
:youtube.video.player/embed-height
:youtube.video.player/embed-width
:youtube.video.topic-details/topic-ids
:youtube.video.topic-details/relevant-topic-ids
:youtube.video.topic-details/topic-categories])
(defn adapt-video [video]
(yth/adapt-recursive video "youtube.video"))
(def video-by-id
(pc/resolver `video-by-id
{::pc/input #{:youtube.video/id}
::pc/output video-output
::pc/batch? true}
(pc/batch-resolver
(fn [env ids]
(go-catch
(->> (yth/youtube-api env "videos"
{:id (str/join "," (map :youtube.video/id ids))
:part (yth/request-parts env "youtube.video")}) <?
:items
(mapv adapt-video)
(pc/batch-restore-sort {::pc/inputs ids
::pc/key :youtube.video/id})))))))
(def resolvers [video-by-id])
(def video-schema
{:localizations
{:KEY
{:title "string", :description "string"}},
:snippet
{:description "string",
:tags ["string"],
:publishedAt "datetime",
:channelId "string",
:categoryId "string",
:thumbnails
{:KEY
{:url "string",
:width "unsigned integer",
:height "unsigned integer"}},
:title "string",
:defaultAudioLanguage "string",
:liveBroadcastContent "string",
:localized
{:title "string", :description "string"},
:channelTitle "string",
:defaultLanguage "string"},
:fileDetails
{:creationTime "string",
:fileSize "unsigned long",
:fileType "string",
:fileName "string",
:bitrateBps "unsigned long",
:videoStreams
[{:widthPixels "unsigned integer",
:heightPixels "unsigned integer",
:frameRateFps "double",
:aspectRatio "double",
:codec "string",
:bitrateBps "unsigned long",
:rotation "string",
:vendor "string"}],
:container "string",
:durationMs "unsigned long",
:audioStreams
[{:channelCount "unsigned integer",
:codec "string",
:bitrateBps "unsigned long",
:vendor "string"}]},
:etag "etag",
:recordingDetails {:recordingDate "datetime"},
:statistics
{:viewCount "unsigned long",
:likeCount "unsigned long",
:dislikeCount "unsigned long",
:favoriteCount "unsigned long",
:commentCount "unsigned long"},
:status
{:uploadStatus "string",
:failureReason "string",
:rejectionReason "string",
:privacyStatus "string",
:publishAt "datetime",
:license "string",
:embeddable "boolean",
:publicStatsViewable "boolean"},
:processingDetails
{:processingStatus "string",
:processingProgress
{:partsTotal "unsigned long",
:partsProcessed "unsigned long",
:timeLeftMs "unsigned long"},
:processingFailureReason "string",
:fileDetailsAvailability "string",
:processingIssuesAvailability "string",
:tagSuggestionsAvailability "string",
:editorSuggestionsAvailability "string",
:thumbnailsAvailability "string"},
:id "string",
:liveStreamingDetails
{:actualStartTime "datetime",
:actualEndTime "datetime",
:scheduledStartTime "datetime",
:scheduledEndTime "datetime",
:concurrentViewers "unsigned long",
:activeLiveChatId "string"},
:suggestions
{:processingErrors ["string"],
:processingWarnings ["string"],
:processingHints ["string"],
:tagSuggestions
[{:tag "string",
:categoryRestricts ["string"]}],
:editorSuggestions ["string"]},
:contentDetails
{:caption "string",
:definition "string",
:licensedContent "boolean",
:duration "string",
:contentRating
{:mccypRating "string",
:ilfilmRating "string",
:lsfRating "string",
:mccaaRating "string",
:fskRating "string",
:mtrcbRating "string",
:grfilmRating "string",
:kijkwijzerRating "string",
:czfilmRating "string",
:incaaRating "string",
:resorteviolenciaRating "string",
:eefilmRating "string",
:cnaRating "string",
:moctwRating "string",
:tvpgRating "string",
:bfvcRating "string",
:bmukkRating "string",
:cceRating "string",
:cncRating "string",
:fcoRating "string",
:ifcoRating "string",
:oflcRating "string",
:chvrsRating "string",
:cbfcRating "string",
:csaRating "string",
:icaaRating "string",
:djctqRatingReasons ["string"],
:fcbmRating "string",
:pefilmRating "string",
:ytRating "string",
:nfvcbRating "string",
:cscfRating "string",
:djctqRating "string",
:kmrbRating "string",
:smaisRating "string",
:bbfcRating "string",
:skfilmRating "string",
:nbcRating "string",
:eirinRating "string",
:nkclvRating "string",
:mocRating "string",
:smsaRating "string",
:medietilsynetRating "string",
:mpaaRating "string",
:mekuRating "string",
:ecbmctRating "string",
:rteRating "string",
:mibacRating "string",
:mdaRating "string",
:chfilmRating "string",
:rcnofRating "string",
:egfilmRating "string",
:anatelRating "string",
:catvfrRating "string",
:acbRating "string",
:rtcRating "string",
:russiaRating "string",
:cccRating "string",
:agcomRating "string",
:catvRating "string",
:kfcbRating "string",
:cicfRating "string",
:mcstRating "string",
:nbcplRating "string",
:nfrcRating "string",
:fpbRating "string",
:fpbRatingReasons ["string"],
:fmocRating "string",
:mpaatRating "string"},
:regionRestriction
{:allowed ["string"], :blocked ["string"]},
:dimension "string",
:projection "string",
:hasCustomThumbnail "boolean"},
:player
{:embedHtml "string",
:embedHeight "long",
:embedWidth "long"},
:topicDetails
{:topicIds ["string"],
:relevantTopicIds ["string"],
:topicCategories ["string"]}})
| null | https://raw.githubusercontent.com/wilkerlucio/pathom-connect-youtube/9415ff9ed15ab6cf098fe88f315cba19adfe9de8/src/core/com/wsscode/pathom/connect/youtube/videos.cljs | clojure | (ns com.wsscode.pathom.connect.youtube.videos
(:require [clojure.string :as str]
[com.wsscode.common.async-cljs :refer [<? go-catch]]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom.connect.youtube.helpers :as yth]))
(def video-output
[:youtube.video.localizations.key/title
:youtube.video.localizations.key/description
:youtube.video.snippet/description
:youtube.video.snippet/tags
:youtube.video.snippet/published-at
:youtube.video.snippet/channel-id
:youtube.video.snippet/category-id
{:youtube.video.snippet.thumbnails/default [:youtube.thumbnail/url
:youtube.thumbnail/width
:youtube.thumbnail/height]}
{:youtube.video.snippet.thumbnails/medium [:youtube.thumbnail/url
:youtube.thumbnail/width
:youtube.thumbnail/height]}
{:youtube.video.snippet.thumbnails/high [:youtube.thumbnail/url
:youtube.thumbnail/width
:youtube.thumbnail/height]}
{:youtube.video.snippet.thumbnails/standard [:youtube.thumbnail/url
:youtube.thumbnail/width
:youtube.thumbnail/height]}
{:youtube.video.snippet.thumbnails/maxres [:youtube.thumbnail/url
:youtube.thumbnail/width
:youtube.thumbnail/height]}
:youtube.video.snippet/title
:youtube.video.snippet/default-audio-language
:youtube.video.snippet/live-broadcast-content
:youtube.video.snippet.localized/title
:youtube.video.snippet.localized/description
:youtube.video.snippet/channel-title
:youtube.video.snippet/default-language
:youtube.video.file-details/creation-time
:youtube.video.file-details/file-size
:youtube.video.file-details/file-type
:youtube.video.file-details/file-name
:youtube.video.file-details/bitrate-bps
{:youtube.video.file-details/video-streams [:youtube.video.file-details.video-streams/width-pixels
:youtube.video.file-details.video-streams/height-pixels
:youtube.video.file-details.video-streams/frame-rate-fps
:youtube.video.file-details.video-streams/aspect-ratio
:youtube.video.file-details.video-streams/codec
:youtube.video.file-details.video-streams/bitrate-bps
:youtube.video.file-details.video-streams/rotation
:youtube.video.file-details.video-streams/vendor]}
:youtube.video.file-details/container
:youtube.video.file-details/duration-ms
{:youtube.video.file-details/audio-streams [:youtube.video.file-details.audio-streams/channel-count
:youtube.video.file-details.audio-streams/codec
:youtube.video.file-details.audio-streams/bitrate-bps
:youtube.video.file-details.audio-streams/vendor]}
:youtube.video/etag
:youtube.video.recording-details/recording-date
:youtube.video.statistics/view-count
:youtube.video.statistics/like-count
:youtube.video.statistics/dislike-count
:youtube.video.statistics/favorite-count
:youtube.video.statistics/comment-count
:youtube.video.status/upload-status
:youtube.video.status/failure-reason
:youtube.video.status/rejection-reason
:youtube.video.status/privacy-status
:youtube.video.status/publish-at
:youtube.video.status/license
:youtube.video.status/embeddable
:youtube.video.status/public-stats-viewable
:youtube.video.processing-details/processing-status
:youtube.video.processing-details.processing-progress/parts-total
:youtube.video.processing-details.processing-progress/parts-processed
:youtube.video.processing-details.processing-progress/time-left-ms
:youtube.video.processing-details/processing-failure-reason
:youtube.video.processing-details/file-details-availability
:youtube.video.processing-details/processing-issues-availability
:youtube.video.processing-details/tag-suggestions-availability
:youtube.video.processing-details/editor-suggestions-availability
:youtube.video.processing-details/thumbnails-availability
:youtube.video/id
:youtube.video.live-streaming-details/actual-start-time
:youtube.video.live-streaming-details/actual-end-time
:youtube.video.live-streaming-details/scheduled-start-time
:youtube.video.live-streaming-details/scheduled-end-time
:youtube.video.live-streaming-details/concurrent-viewers
:youtube.video.live-streaming-details/active-live-chat-id
:youtube.video.suggestions/processing-errors
:youtube.video.suggestions/processing-warnings
:youtube.video.suggestions/processing-hints
{:youtube.video.suggestions/tag-suggestions [:youtube.video.suggestions.tag-suggestions/tag
:youtube.video.suggestions.tag-suggestions/category-restricts]}
:youtube.video.suggestions/editor-suggestions
:youtube.video.content-details/caption
:youtube.video.content-details/definition
:youtube.video.content-details/licensed-content
:youtube.video.content-details/duration
:youtube.video.content-details.content-rating/mccyp-rating
:youtube.video.content-details.content-rating/ilfilm-rating
:youtube.video.content-details.content-rating/lsf-rating
:youtube.video.content-details.content-rating/mccaa-rating
:youtube.video.content-details.content-rating/fsk-rating
:youtube.video.content-details.content-rating/mtrcb-rating
:youtube.video.content-details.content-rating/grfilm-rating
:youtube.video.content-details.content-rating/kijkwijzer-rating
:youtube.video.content-details.content-rating/czfilm-rating
:youtube.video.content-details.content-rating/incaa-rating
:youtube.video.content-details.content-rating/resorteviolencia-rating
:youtube.video.content-details.content-rating/eefilm-rating
:youtube.video.content-details.content-rating/cna-rating
:youtube.video.content-details.content-rating/moctw-rating
:youtube.video.content-details.content-rating/tvpg-rating
:youtube.video.content-details.content-rating/bfvc-rating
:youtube.video.content-details.content-rating/bmukk-rating
:youtube.video.content-details.content-rating/cce-rating
:youtube.video.content-details.content-rating/cnc-rating
:youtube.video.content-details.content-rating/fco-rating
:youtube.video.content-details.content-rating/ifco-rating
:youtube.video.content-details.content-rating/oflc-rating
:youtube.video.content-details.content-rating/chvrs-rating
:youtube.video.content-details.content-rating/cbfc-rating
:youtube.video.content-details.content-rating/csa-rating
:youtube.video.content-details.content-rating/icaa-rating
:youtube.video.content-details.content-rating/djctq-rating-reasons
:youtube.video.content-details.content-rating/fcbm-rating
:youtube.video.content-details.content-rating/pefilm-rating
:youtube.video.content-details.content-rating/yt-rating
:youtube.video.content-details.content-rating/nfvcb-rating
:youtube.video.content-details.content-rating/cscf-rating
:youtube.video.content-details.content-rating/djctq-rating
:youtube.video.content-details.content-rating/kmrb-rating
:youtube.video.content-details.content-rating/smais-rating
:youtube.video.content-details.content-rating/bbfc-rating
:youtube.video.content-details.content-rating/skfilm-rating
:youtube.video.content-details.content-rating/nbc-rating
:youtube.video.content-details.content-rating/eirin-rating
:youtube.video.content-details.content-rating/nkclv-rating
:youtube.video.content-details.content-rating/moc-rating
:youtube.video.content-details.content-rating/smsa-rating
:youtube.video.content-details.content-rating/medietilsynet-rating
:youtube.video.content-details.content-rating/mpaa-rating
:youtube.video.content-details.content-rating/meku-rating
:youtube.video.content-details.content-rating/ecbmct-rating
:youtube.video.content-details.content-rating/rte-rating
:youtube.video.content-details.content-rating/mibac-rating
:youtube.video.content-details.content-rating/mda-rating
:youtube.video.content-details.content-rating/chfilm-rating
:youtube.video.content-details.content-rating/rcnof-rating
:youtube.video.content-details.content-rating/egfilm-rating
:youtube.video.content-details.content-rating/anatel-rating
:youtube.video.content-details.content-rating/catvfr-rating
:youtube.video.content-details.content-rating/acb-rating
:youtube.video.content-details.content-rating/rtc-rating
:youtube.video.content-details.content-rating/russia-rating
:youtube.video.content-details.content-rating/ccc-rating
:youtube.video.content-details.content-rating/agcom-rating
:youtube.video.content-details.content-rating/catv-rating
:youtube.video.content-details.content-rating/kfcb-rating
:youtube.video.content-details.content-rating/cicf-rating
:youtube.video.content-details.content-rating/mcst-rating
:youtube.video.content-details.content-rating/nbcpl-rating
:youtube.video.content-details.content-rating/nfrc-rating
:youtube.video.content-details.content-rating/fpb-rating
:youtube.video.content-details.content-rating/fpb-rating-reasons
:youtube.video.content-details.content-rating/fmoc-rating
:youtube.video.content-details.content-rating/mpaat-rating
:youtube.video.content-details.region-restriction/allowed
:youtube.video.content-details.region-restriction/blocked
:youtube.video.content-details/dimension
:youtube.video.content-details/projection
:youtube.video.content-details/has-custom-thumbnail
:youtube.video.player/embed-html
:youtube.video.player/embed-height
:youtube.video.player/embed-width
:youtube.video.topic-details/topic-ids
:youtube.video.topic-details/relevant-topic-ids
:youtube.video.topic-details/topic-categories])
(defn adapt-video [video]
(yth/adapt-recursive video "youtube.video"))
(def video-by-id
(pc/resolver `video-by-id
{::pc/input #{:youtube.video/id}
::pc/output video-output
::pc/batch? true}
(pc/batch-resolver
(fn [env ids]
(go-catch
(->> (yth/youtube-api env "videos"
{:id (str/join "," (map :youtube.video/id ids))
:part (yth/request-parts env "youtube.video")}) <?
:items
(mapv adapt-video)
(pc/batch-restore-sort {::pc/inputs ids
::pc/key :youtube.video/id})))))))
(def resolvers [video-by-id])
(def video-schema
{:localizations
{:KEY
{:title "string", :description "string"}},
:snippet
{:description "string",
:tags ["string"],
:publishedAt "datetime",
:channelId "string",
:categoryId "string",
:thumbnails
{:KEY
{:url "string",
:width "unsigned integer",
:height "unsigned integer"}},
:title "string",
:defaultAudioLanguage "string",
:liveBroadcastContent "string",
:localized
{:title "string", :description "string"},
:channelTitle "string",
:defaultLanguage "string"},
:fileDetails
{:creationTime "string",
:fileSize "unsigned long",
:fileType "string",
:fileName "string",
:bitrateBps "unsigned long",
:videoStreams
[{:widthPixels "unsigned integer",
:heightPixels "unsigned integer",
:frameRateFps "double",
:aspectRatio "double",
:codec "string",
:bitrateBps "unsigned long",
:rotation "string",
:vendor "string"}],
:container "string",
:durationMs "unsigned long",
:audioStreams
[{:channelCount "unsigned integer",
:codec "string",
:bitrateBps "unsigned long",
:vendor "string"}]},
:etag "etag",
:recordingDetails {:recordingDate "datetime"},
:statistics
{:viewCount "unsigned long",
:likeCount "unsigned long",
:dislikeCount "unsigned long",
:favoriteCount "unsigned long",
:commentCount "unsigned long"},
:status
{:uploadStatus "string",
:failureReason "string",
:rejectionReason "string",
:privacyStatus "string",
:publishAt "datetime",
:license "string",
:embeddable "boolean",
:publicStatsViewable "boolean"},
:processingDetails
{:processingStatus "string",
:processingProgress
{:partsTotal "unsigned long",
:partsProcessed "unsigned long",
:timeLeftMs "unsigned long"},
:processingFailureReason "string",
:fileDetailsAvailability "string",
:processingIssuesAvailability "string",
:tagSuggestionsAvailability "string",
:editorSuggestionsAvailability "string",
:thumbnailsAvailability "string"},
:id "string",
:liveStreamingDetails
{:actualStartTime "datetime",
:actualEndTime "datetime",
:scheduledStartTime "datetime",
:scheduledEndTime "datetime",
:concurrentViewers "unsigned long",
:activeLiveChatId "string"},
:suggestions
{:processingErrors ["string"],
:processingWarnings ["string"],
:processingHints ["string"],
:tagSuggestions
[{:tag "string",
:categoryRestricts ["string"]}],
:editorSuggestions ["string"]},
:contentDetails
{:caption "string",
:definition "string",
:licensedContent "boolean",
:duration "string",
:contentRating
{:mccypRating "string",
:ilfilmRating "string",
:lsfRating "string",
:mccaaRating "string",
:fskRating "string",
:mtrcbRating "string",
:grfilmRating "string",
:kijkwijzerRating "string",
:czfilmRating "string",
:incaaRating "string",
:resorteviolenciaRating "string",
:eefilmRating "string",
:cnaRating "string",
:moctwRating "string",
:tvpgRating "string",
:bfvcRating "string",
:bmukkRating "string",
:cceRating "string",
:cncRating "string",
:fcoRating "string",
:ifcoRating "string",
:oflcRating "string",
:chvrsRating "string",
:cbfcRating "string",
:csaRating "string",
:icaaRating "string",
:djctqRatingReasons ["string"],
:fcbmRating "string",
:pefilmRating "string",
:ytRating "string",
:nfvcbRating "string",
:cscfRating "string",
:djctqRating "string",
:kmrbRating "string",
:smaisRating "string",
:bbfcRating "string",
:skfilmRating "string",
:nbcRating "string",
:eirinRating "string",
:nkclvRating "string",
:mocRating "string",
:smsaRating "string",
:medietilsynetRating "string",
:mpaaRating "string",
:mekuRating "string",
:ecbmctRating "string",
:rteRating "string",
:mibacRating "string",
:mdaRating "string",
:chfilmRating "string",
:rcnofRating "string",
:egfilmRating "string",
:anatelRating "string",
:catvfrRating "string",
:acbRating "string",
:rtcRating "string",
:russiaRating "string",
:cccRating "string",
:agcomRating "string",
:catvRating "string",
:kfcbRating "string",
:cicfRating "string",
:mcstRating "string",
:nbcplRating "string",
:nfrcRating "string",
:fpbRating "string",
:fpbRatingReasons ["string"],
:fmocRating "string",
:mpaatRating "string"},
:regionRestriction
{:allowed ["string"], :blocked ["string"]},
:dimension "string",
:projection "string",
:hasCustomThumbnail "boolean"},
:player
{:embedHtml "string",
:embedHeight "long",
:embedWidth "long"},
:topicDetails
{:topicIds ["string"],
:relevantTopicIds ["string"],
:topicCategories ["string"]}})
| |
cd00e21bb83ed9c487e1c060ed98d78c2c5e285611f6a15d0e85cddcccd1c267 | sionescu/bordeaux-threads | impl-mezzano.lisp | ;;;; -*- indent-tabs-mode: nil -*-
(in-package :bordeaux-threads-2)
;;;
;;; Threads
;;;
(deftype native-thread ()
'mezzano.supervisor:thread)
(defun %make-thread (function name)
(mezzano.supervisor:make-thread function :name name))
(defun %current-thread ()
(mezzano.supervisor:current-thread))
(defun %thread-name (thread)
(mezzano.supervisor:thread-name thread))
(defun %join-thread (thread)
;; THREAD-JOIN can return non-lists if the thread was destroyed.
(let ((values (mezzano.supervisor:thread-join thread)))
(if (listp values)
(values-list values)
nil)))
(defun %thread-yield ()
(mezzano.supervisor:thread-yield))
;;;
;;; Introspection/debugging
;;;
(defun %all-threads ()
(mezzano.supervisor:all-threads))
(defun %interrupt-thread (thread function)
(mezzano.supervisor:establish-thread-foothold thread function))
(defun %destroy-thread (thread)
(mezzano.supervisor:terminate-thread thread))
(defun %thread-alive-p (thread)
(not (eql (mezzano.supervisor:thread-state thread) :dead)))
;;;
;;; Non-recursive locks
;;;
(deftype native-lock () 'mezzano.supervisor:mutex)
(defun %make-lock (name)
(mezzano.supervisor:make-mutex name))
(mark-not-implemented 'acquire-lock :timeout)
(defun %acquire-lock (lock waitp timeout)
(when timeout
(signal-not-implemented 'acquire-lock :timeout))
(mezzano.supervisor:acquire-mutex lock waitp))
(defun %release-lock (lock)
(mezzano.supervisor:release-mutex lock))
(mark-not-implemented 'with-lock-held :timeout)
(defmacro %with-lock ((place timeout) &body body)
(if timeout
`(signal-not-implemented 'with-lock-held :timeout)
`(mezzano.supervisor:with-mutex (,place) ,@body)))
;;;
;;; Recursive locks
;;;
(defstruct (%recursive-lock
(:constructor %make-recursive-lock-internal (mutex)))
mutex
(depth 0))
(deftype native-recursive-lock () '%recursive-lock)
(defun %make-recursive-lock (name)
(%make-recursive-lock-internal (%make-lock name)))
(mark-not-implemented 'acquire-recursive-lock)
(defun %acquire-recursive-lock (lock waitp timeout)
(declare (ignore lock waitp timeout))
(signal-not-implemented 'acquire-recursive-lock))
(release-not-implemented 'release-recursive-lock)
(defun %release-recursive-lock (lock)
(declare (ignore lock))
(signal-not-implemented 'release-recursive-lock))
(defun call-with-recursive-lock-held (lock function)
(cond ((mezzano.supervisor:mutex-held-p
(%recursive-lock-mutex lock))
(unwind-protect
(progn (incf (%recursive-lock-depth lock))
(funcall function))
(decf (%recursive-lock-depth lock))))
(t
(mezzano.supervisor:with-mutex ((%recursive-lock-mutex lock))
(multiple-value-prog1
(funcall function)
(assert (zerop (%recursive-lock-depth lock))))))))
(mark-not-implemented 'with-recursive-lock-held :timeout)
(defmacro %with-recursive-lock ((place timeout) &body body)
(if timeout
`(signal-not-implemented 'with-recursive-lock-held :timeout)
`(call-with-recursive-lock-held ,place (lambda () ,@body))))
;;;
;;; Semaphores
;;;
(deftype semaphore ()
'mezzano.sync:semaphore)
(defun %make-semaphore (name count)
(mezzano.sync:make-semaphore :name name :value count))
(defun %signal-semaphore (semaphore count)
(dotimes (c count) (mezzano.sync:semaphore-up semaphore)))
(defun %wait-on-semaphore (semaphore timeout)
(mezzano.supervisor:event-wait-for (semaphore :timeout timeout)
(mezzano.sync:semaphore-down semaphore :wait-p nil)))
;;;
;;; Condition variables
;;;
(deftype condition-variable ()
'mezzano.supervisor:condition-variable)
(defun %make-condition-variable (name)
(mezzano.supervisor:make-condition-variable name))
(defun %condition-wait (cv lock timeout)
(mezzano.supervisor:condition-wait cv lock timeout))
(defun %condition-notify (cv)
(mezzano.supervisor:condition-notify cv))
(mark-not-implemented 'condition-broadcast)
(defun %condition-broadcast (cv)
(declare (ignore cv))
(signal-not-implemented 'condition-broadcast))
| null | https://raw.githubusercontent.com/sionescu/bordeaux-threads/552fd4dc7490a2f05ed74123f4096fb991673ac0/apiv2/impl-mezzano.lisp | lisp | -*- indent-tabs-mode: nil -*-
Threads
THREAD-JOIN can return non-lists if the thread was destroyed.
Introspection/debugging
Non-recursive locks
Recursive locks
Semaphores
Condition variables
|
(in-package :bordeaux-threads-2)
(deftype native-thread ()
'mezzano.supervisor:thread)
(defun %make-thread (function name)
(mezzano.supervisor:make-thread function :name name))
(defun %current-thread ()
(mezzano.supervisor:current-thread))
(defun %thread-name (thread)
(mezzano.supervisor:thread-name thread))
(defun %join-thread (thread)
(let ((values (mezzano.supervisor:thread-join thread)))
(if (listp values)
(values-list values)
nil)))
(defun %thread-yield ()
(mezzano.supervisor:thread-yield))
(defun %all-threads ()
(mezzano.supervisor:all-threads))
(defun %interrupt-thread (thread function)
(mezzano.supervisor:establish-thread-foothold thread function))
(defun %destroy-thread (thread)
(mezzano.supervisor:terminate-thread thread))
(defun %thread-alive-p (thread)
(not (eql (mezzano.supervisor:thread-state thread) :dead)))
(deftype native-lock () 'mezzano.supervisor:mutex)
(defun %make-lock (name)
(mezzano.supervisor:make-mutex name))
(mark-not-implemented 'acquire-lock :timeout)
(defun %acquire-lock (lock waitp timeout)
(when timeout
(signal-not-implemented 'acquire-lock :timeout))
(mezzano.supervisor:acquire-mutex lock waitp))
(defun %release-lock (lock)
(mezzano.supervisor:release-mutex lock))
(mark-not-implemented 'with-lock-held :timeout)
(defmacro %with-lock ((place timeout) &body body)
(if timeout
`(signal-not-implemented 'with-lock-held :timeout)
`(mezzano.supervisor:with-mutex (,place) ,@body)))
(defstruct (%recursive-lock
(:constructor %make-recursive-lock-internal (mutex)))
mutex
(depth 0))
(deftype native-recursive-lock () '%recursive-lock)
(defun %make-recursive-lock (name)
(%make-recursive-lock-internal (%make-lock name)))
(mark-not-implemented 'acquire-recursive-lock)
(defun %acquire-recursive-lock (lock waitp timeout)
(declare (ignore lock waitp timeout))
(signal-not-implemented 'acquire-recursive-lock))
(release-not-implemented 'release-recursive-lock)
(defun %release-recursive-lock (lock)
(declare (ignore lock))
(signal-not-implemented 'release-recursive-lock))
(defun call-with-recursive-lock-held (lock function)
(cond ((mezzano.supervisor:mutex-held-p
(%recursive-lock-mutex lock))
(unwind-protect
(progn (incf (%recursive-lock-depth lock))
(funcall function))
(decf (%recursive-lock-depth lock))))
(t
(mezzano.supervisor:with-mutex ((%recursive-lock-mutex lock))
(multiple-value-prog1
(funcall function)
(assert (zerop (%recursive-lock-depth lock))))))))
(mark-not-implemented 'with-recursive-lock-held :timeout)
(defmacro %with-recursive-lock ((place timeout) &body body)
(if timeout
`(signal-not-implemented 'with-recursive-lock-held :timeout)
`(call-with-recursive-lock-held ,place (lambda () ,@body))))
(deftype semaphore ()
'mezzano.sync:semaphore)
(defun %make-semaphore (name count)
(mezzano.sync:make-semaphore :name name :value count))
(defun %signal-semaphore (semaphore count)
(dotimes (c count) (mezzano.sync:semaphore-up semaphore)))
(defun %wait-on-semaphore (semaphore timeout)
(mezzano.supervisor:event-wait-for (semaphore :timeout timeout)
(mezzano.sync:semaphore-down semaphore :wait-p nil)))
(deftype condition-variable ()
'mezzano.supervisor:condition-variable)
(defun %make-condition-variable (name)
(mezzano.supervisor:make-condition-variable name))
(defun %condition-wait (cv lock timeout)
(mezzano.supervisor:condition-wait cv lock timeout))
(defun %condition-notify (cv)
(mezzano.supervisor:condition-notify cv))
(mark-not-implemented 'condition-broadcast)
(defun %condition-broadcast (cv)
(declare (ignore cv))
(signal-not-implemented 'condition-broadcast))
|
508553e409f40f569a5227afc6767af51dab93b0e4ef2ba415ba38aff1b306ac | michaelmelanson/erlyweb | erltl.erl | @author < > [ ]
%% @version 0.9.3
@copyright Yariv Sadan 2006 - 2007
%%
@doc ErlTL is a simple Erlang template language .
%%
%% == Introduction ==
ErlTL is a template language used for creating Erlang modules that
programatically generate iolists ( nested lists of strings and/or binaries )
%% whose contents are mostly known at compile time.
%% ErlTL templates are generally less verbose and more readable than
the equivalent hand - written Erlang code .
A common use - case for ErlTL is the generation of
%% dynamic HTML in web applications.
%%
%% ErlTL emphasizes speed, simplicity, reusability and good error reporting.
The ErlTL compiler transforms template files into Erlang modules whose
%% whose functions are exported so they can be used in other modules.
By compiling to BEAM , ErlTL does n't add any overhead to writing a template 's
logic in pure Erlang .
%%
%% == Tag Reference ==
%%
%% An ErlTL template can be composed of the following tags:
%%
` < % [ Exprs ] % > ' < br/>Erlang expression tag . This tag contains one or more
Erlang expressions that are evaluated in runtime .
For the template to return a valid iolist , the results of embedded Erlang
%% expressions must be strings or binaries.
%%
` < % @ [ FuncDecl ] % > ' < br/>Function declaration tag .
An ErlTL template compiles into an Erlang module containing one or more
%% functions. This module always contains a function named 'render'
%% that accepts a single parameter called 'Data'. The 'render' function
%% corresponds to the area at the top of an ErlTL file, above all other
%% function declarations.
%%
%% You can use the function declaration tag to add more functions to
%% an ErlTL template.
%% ErlTL functions return the iolist described by to the template region
%% between its declaration and the next function declaration, or the end of
the file . To facilitate pattern - matching , ErlTL translates consecutive
%% function declarations with the same name and arity into a single function
%% declaration with multiple clauses, as in the following example:
%%
%% ```
< % @ volume_desc(Val ) when > = 20 % > Big
< % @ volume_desc(Val ) when > = 10 % > Medium
%% <%@ volume_desc(Val) %> Small
%% '''
%%
Function declarations have 2 possible forms : basic and full .
A full function declaration contains a complete Erlang function
%% declaration up to the '->' symbol, e.g.
%% `"<%@ my_func(A, B = [1,2 | _]) when is_integer(A) %>"'.
%%
%% A basic function declaration contains only the name of the function,
%% e.g. "`<%@ my_func %>'". This declaration is equivalent to
%% `"<%@ my_func(Data) %>"'.
%%
%% `<%~ [TopForms] %>' <br/>Top-level forms tag.
%% This tag, which may appear only at the very top of an ErlTL file, can
contain any legal top - level Erlang form . This includes module attributes ,
%% compiler directives, and even complete functions.
%%
%% `<%? [TopExprs] %>' <br/>Top-level expressions tag.
%% This tag, which may appear only at the top of ErlTL functions, contains
Erlang expressions whose result is n't part of the function 's return value .
%% This is used primarily for "unpacking" the Data parameter and binding
%% its elements to local variables prior to using them in the body of a
%% function.
%%
%% `<%! [Comment] %>' <br/>Comment tag. The contents of this tag are
%% used for documentation only. They are discarded in compile-time.
%%
Following is an sample ErlTL template that uses the ErlTL tags above
%% (you can find this code under test/erltl):
%%
%% ```
%% <%~
%% %% date: 10/21/2006
%% -author("Yariv Sadan").
-import(widgets , [ foo/1 , bar/2 , ] ) .
%% %>
%% <%! This is a sample ErlTL template that renders a list of albums %>
%% <html>
%% <body>
%% <% [album(A) || A <- Data] %>
%% </body>
%% </html>
%%
< % @ , Artist , Songs } ) % >
%% Title: <b><% Title %></b><br>
%% Artist: <b><% Artist %></b><br>
%% Songs: <br>
%% <table>
%% <% [song(Number, Name) || {Number, Name} <- Songs] %>
%% </table>
%%
< % @ song(Number , Name ) when size(Name ) > 15 % >
%% <%? <<First:13/binary, Rest/binary>> = Name %>
< % song(Number , [ First , < < " ... " > > ] ) % >
%%
%% <%@ song(Number, Name) %>
%% <%?
%% Class =
case Number rem 2 of
%% 0 -> <<"even">>;
%% 1 -> <<"odd">>
%% end
%% %>
%% <tr>
%% <td class="<% Class %>"><% integer_to_list(Number) %></td>
%% <td class="<% Class %>"><% Name %></td>
%% </tr>
%% '''
%%
%% @end
Copyright ( c ) 2006 - 2007
%%
%% Permission is hereby granted, free of charge, to any person obtaining a
%% copy of this software and associated documentation files (the
" Software " ) , to deal in the Software without restriction , including
%% without limitation the rights to use, copy, modify, merge, publish,
distribute , sublicense , and/or sell copies of the Software , and to
permit persons to whom the Software is furnished to do so , subject to
%% the following conditions:
%%
%% The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software .
%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS
%% OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT .
%% IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT ,
%% TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
%% SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-module(erltl).
-author("Yariv Sadan (, )").
-export([compile/1, compile/2, forms_for_file/1,
forms_for_file/2, forms_for_data/2, forms_for_data/3]).
-define(L(Msg), io:format("~b ~p~n", [?LINE, Msg])).
%% @doc Compile the ErlTL file with the default options:
` [ , FileDir } , report_errors , report_warnings , nowarn_unused_vars ] ' .
( FileDir is the directory of the source file . )
%%
After compilation , the resulting BEAM is loaded into the VM
%% (the old code is purged if necessary).
%%
( ) ) - > ok | { error ,
compile(FileName) ->
compile(FileName, [{outdir, filename:dirname(FileName)},
report_errors, report_warnings, nowarn_unused_vars]).
%% @doc Compile the ErlTL file with user-defined options. The options are
%% described in the documentation for the 'compile' module.
%% For more information, visit
%% [-5.5.1/lib/compiler-4.4.1/doc/html/compile.html]
%%
( ) , Options::[option ( ) ] ) - > ok | { error ,
compile(FileName, Options) ->
IncludePaths = lists:foldl(
fun({i, Path}, Acc) ->
[Path | Acc];
(_Other, Acc) ->
Acc
end, [], Options),
case forms_for_file(FileName, IncludePaths) of
{ok, Forms} ->
case compile:forms(Forms,
Options) of
{ok, Module, Bin} ->
OutDir = case lists:keysearch(outdir, 1, Options)
of
{value, {outdir, Val}} -> Val;
false -> filename:dirname(FileName)
end,
BaseName = filename:rootname(filename:basename(FileName)),
case file:write_file(OutDir ++ ['/' | BaseName] ++
".beam", Bin) of
ok ->
code:purge(Module),
case code:load_binary(
Module, atom_to_list(Module), Bin)
of
{module, _Module} ->
ok;
Err ->
Err
end;
{error, _} = Err ->
Err
end;
Err ->
Err
end;
Err -> Err
end.
%% @equiv forms_for_file(Filename, [])
forms_for_file(FileName) ->
forms_for_file(FileName, []).
@doc Parse the ErlTL file and return its representation in Erlang
%% abstract forms.
( ) ,
IncludePaths::[string ( ) ] ) - > { ok , [ form ( ) ] } | { error ,
forms_for_file(FileName, IncludePaths) ->
case file:read_file(FileName) of
{ok, Binary} ->
BaseName = filename:rootname(filename:basename(FileName)),
forms_for_data(Binary, list_to_atom(BaseName), IncludePaths);
Err ->
Err
end.
@equiv forms_form_data(Data , ModuleName , [ ] )
forms_for_data(Data, ModuleName) ->
forms_for_data(Data, ModuleName, []).
%% @doc Parse the raw text of an ErlTL template and return its
%% representation in abstract forms.
( ) | string ( ) , ( ) ,
%% IncludePaths::[string()]) ->
{ ok , [ form ( ) ] } | { error ,
forms_for_data(Data, ModuleName, IncludePaths) when is_binary(Data) ->
forms_for_data(binary_to_list(Data), ModuleName, IncludePaths);
forms_for_data(Data, ModuleName, IncludePaths) ->
Lines = make_lines(Data),
case forms(Lines, ModuleName) of
{ok, Forms} ->
case catch lists:map(
fun({attribute, _, include, Include}) ->
process_include(
Include, [[], ["."] |
IncludePaths]);
(Form) ->
Form
end, Forms)
of
{'EXIT', Err} ->
{error, Err};
Res ->
{ok, lists:flatten(Res)}
end;
Err ->
Err
end.
process_include(Include, []) ->
exit({file_not_found, Include});
process_include(Include, [Path | Rest]) ->
case epp:parse_file(Path ++ "/" ++ Include, [], []) of
{error, enoent} ->
process_include(Include, Rest);
{ok, IncludeForms} ->
lists:sublist(
IncludeForms,
2,
length(IncludeForms) - 2)
end.
make_lines(Str) ->
make_lines(Str, [], []).
make_lines([], [], Result) -> lists:reverse(Result);
make_lines([], Acc, Result) -> lists:reverse([lists:reverse(Acc) | Result]);
make_lines([10 | Tail], Acc, Result) ->
make_lines(Tail, [], [lists:reverse(Acc) | Result]);
make_lines([Head | Tail], Acc, Result) ->
make_lines(Tail, [Head | Acc], Result).
forms(Lines, Module) ->
case catch parse(Lines) of
{'EXIT', Err} ->
{error, Err};
Forms ->
{ok, [{attribute,1,module,Module},
{attribute,2,file,{atom_to_list(Module),1}},
{attribute,3,compile,export_all}] ++ lists:reverse(Forms)}
end.
parse(Lines) ->
parse(Lines, binary, 1, [], [], [], []).
parse([], _State, _LineNo, TopExprs, Exprs, AllForms, ChunkAcc) ->
[FirstForms | OtherForms] = initial_forms(AllForms),
combine_forms(
embed_exprs(FirstForms, TopExprs, last_exprs(ChunkAcc, Exprs)) ++
OtherForms);
parse([Line | OtherLines], State, LineNo, TopExprs, Exprs,
AllForms, ChunkAcc) ->
case scan(Line, State) of
more ->
Line1 = case State of
binary -> Line ++ "\n";
_ -> Line
end,
parse(OtherLines, State, LineNo+1, TopExprs, Exprs,
AllForms, [{Line1, LineNo} | ChunkAcc]);
{ok, Chunk, NextState, NextChunk} ->
Chunks = [{Chunk, LineNo} | ChunkAcc],
Result = case State of
func_decl -> {func_decl, parse_func_decl(Chunks)};
binary -> {exprs, parse_binary(Chunks)};
top_exprs -> {top_exprs, parse_exprs(Chunks)};
forms -> {forms, parse_forms(Chunks)};
erlang -> {exprs, parse_exprs(Chunks)};
comment -> comment
end,
case Result of
comment ->
{NextLines, LineDiff} =
skip_line_break([NextChunk | OtherLines]),
parse(NextLines,
NextState, LineNo + LineDiff,
TopExprs, Exprs, AllForms, []);
{func_decl, BasicForms} ->
[CurrentForms | PreviousForms] = initial_forms(AllForms),
AllForms1 =
embed_exprs(CurrentForms, TopExprs, Exprs) ++
PreviousForms,
NewForms = combine_forms(AllForms1),
{NextLines, LineDiff} =
skip_line_break([NextChunk | OtherLines]),
parse(NextLines,
NextState, LineNo + LineDiff, [], [],
[BasicForms | NewForms], []);
{exprs, []} ->
NextLineNo = case Chunk of
[] -> LineNo;
_ -> LineNo + 1
end,
parse([NextChunk | OtherLines],
NextState, NextLineNo, TopExprs,
Exprs, AllForms, []);
{exprs, Exprs1} ->
parse([NextChunk | OtherLines],
NextState, LineNo, TopExprs,
Exprs1 ++ Exprs,
initial_forms(AllForms), []);
{top_exprs, TopExprs1} ->
case Exprs of
[] ->
parse([NextChunk | OtherLines], NextState, LineNo,
TopExprs1 ++ TopExprs,
Exprs, AllForms, []);
_ ->
error(misplaced_top_exprs, LineNo, Line,
"top expressions must appear before all "
"other expressions in a function")
end;
{forms, Forms} ->
case AllForms of
[] ->
{NextLines, LineDiff} =
skip_line_break([NextChunk | OtherLines]),
parse(NextLines,
NextState, LineNo + LineDiff, [], [],
initial_forms([]) ++ Forms, []);
_ -> error(misplaced_top_declaration, LineNo, Line,
"top-level declarations must appear at the "
"top of a file")
end
end
end.
combine_forms([{function,L,FuncName,Arity,Clauses},
{function,_,LastFuncName,LastArity,LastClauses} |
PreviousForms]) when LastFuncName == FuncName,
LastArity == Arity ->
[{function,L,FuncName,Arity, LastClauses ++ Clauses} | PreviousForms];
combine_forms(Forms) -> Forms.
scan(Line, State) ->
Delim =
case State of
binary -> {"<%",
[{$@, func_decl},
{$!, comment},
{$?, top_exprs},
{$~, forms}],
erlang};
_ -> {"%>", [], binary}
end,
scan1(Line, Delim).
scan1(Line, {Delim, Options, Default}) ->
case string:str(Line, Delim) of
0 -> more;
Pos ->
{First, [_,_ | Rest]} = lists:split(Pos-1, Line),
{NextState, NextChunk} =
case Rest of
[] -> {Default, Rest};
[FirstChar | OtherChars] ->
case lists:keysearch(FirstChar, 1, Options) of
{value, {_, NextState1}} ->
{NextState1, OtherChars};
false -> {Default, Rest}
end
end,
{ok, First, NextState, NextChunk}
end.
initial_forms([]) -> [parse_func_decl([{"render", 1}])];
initial_forms(AllForms) -> AllForms.
skip_line_break([[] | Lines]) -> {Lines, 1};
skip_line_break(Lines) -> {Lines, 0}.
last_exprs([], Exprs) -> Exprs;
last_exprs(ChunkAcc, Exprs) ->
parse_binary(ChunkAcc) ++ Exprs.
parse_binary([]) -> [];
parse_binary([{[],_}]) -> [];
parse_binary(Fragments) ->
BinElems =
lists:foldl(
fun({Chars, LineNo}, Acc) ->
Elems = lists:foldl(
fun(Char, BinElems) ->
[{bin_element,LineNo,{integer,LineNo,Char},
default,default} | BinElems]
end, [], lists:reverse(Chars)),
Elems ++ Acc
end, [], Fragments),
[{bin,1,BinElems}].
parse_exprs([]) -> [];
parse_exprs(Fragments) ->
Tokens = lists:foldl(
fun({Frag, LineNo}, Acc) ->
case erl_scan:string(Frag, LineNo) of
{ok, Toks, _} -> Toks ++ Acc;
{error, Err, _} -> error(scan_error, LineNo, Frag, Err)
end
end, [{dot,1}], Fragments),
Tokens1 = Tokens,
case erl_parse:parse_exprs(Tokens1) of
{ok, Exprs} -> [{block,1, Exprs}];
{error, Msg} -> exit({parse_error, Msg})
end.
parse_forms([]) -> [];
parse_forms(Fragments) ->
FormsTokens =
lists:foldl(
fun({Frag, LineNo}, Acc) ->
case erl_scan:string(Frag, LineNo) of
{ok, Toks, _} ->
lists:foldl(
fun({dot,_} = Tok, [Form | Rest]) ->
[[Tok] | [Form | Rest]];
(Tok, [Form | Rest]) ->
[[Tok | Form] | Rest]
end, Acc, lists:reverse(Toks));
{error, Err, _} ->
error(scan_error, LineNo, Frag, Err)
end
end, [[]], Fragments),
lists:foldl(
fun([], Acc) -> Acc;
(FormTokens, Acc) ->
case erl_parse:parse_form(FormTokens) of
{ok, Form} ->
[Form | Acc];
{error, Err} -> exit({parse_error, Err})
end
end, [], FormsTokens).
parse_func_decl(Fragments) ->
{FuncDecl, LineNo} =
lists:foldl(
fun({Chars, LineNo}, {Acc, FirstLine}) ->
Elems = lists:foldl(
fun(Char, Chars1) ->
[Char | Chars1]
end, [], lists:reverse(Chars)),
FirstLine1 = case FirstLine of
undefined -> LineNo;
_ -> FirstLine
end,
{Elems ++ Acc, FirstLine1}
end, {[], undefined}, Fragments),
case erl_scan:string(FuncDecl) of
{ok, [{atom,_,FuncName}], _} ->
[{full_form,
{function, LineNo, FuncName, 0,
[{clause, LineNo, [], [],
[{call,LineNo,{atom,LineNo,FuncName},
[{atom,1,undefined}]}]
}]
}},
{empty_form,
{function, LineNo, FuncName, 1,
[{clause, LineNo, [{var,LineNo,'Data'}], [], []}]}}];
{ok, _, _} ->
case erl_scan:string(FuncDecl ++ " -> funky_func.") of
{ok, Toks, _} ->
case erl_parse:parse_form(Toks) of
{ok, Form} ->
[{empty_form,
change_line_numbers(LineNo, Form)}];
{error, Msg} ->
error(parse_error, LineNo, FuncDecl, Msg)
end;
{error, Msg, _} ->
error(scan_error, LineNo, FuncDecl, Msg)
end;
{error, Msg, _} -> error(scan_error, LineNo, FuncDecl, Msg)
end.
error(Type, Line, Chunk, Msg) ->
exit({Type, {{line, Line}, {chunk, Chunk}, {msg, Msg}}}).
embed_exprs(Forms, TopExprs, Exprs) when is_list(Forms) ->
[embed_exprs(Form, TopExprs, Exprs) || Form <- Forms];
embed_exprs({full_form, Form}, _TopExprs, _Exprs) -> Form;
embed_exprs({empty_form,
{function,Line,FuncName,Arity,
[{clause, Line1, Params, Guards, _UnusedExprs}]}},
TopExprs, Exprs) ->
{function,Line,FuncName,Arity,[{clause,Line1,Params,Guards,
lists:reverse(TopExprs) ++
[cons_exprs(lists:reverse(Exprs))]}]}.
cons_exprs([]) -> {nil,1};
cons_exprs([{bin,L,BinElems}, {bin,_,BinElems1} | Rest]) ->
cons_exprs([{bin,L,BinElems ++ BinElems1} | Rest]);
cons_exprs([Expr|Rest]) ->
{cons,1,Expr,cons_exprs(Rest)}.
change_line_numbers(L, Exprs) when is_list(Exprs) ->
lists:foldl(
fun(Expr, Acc) ->
[change_line_numbers(L, Expr) | Acc]
end, [], lists:reverse(Exprs));
change_line_numbers(L, Expr) when is_tuple(Expr) ->
Expr1 = case is_integer(element(2, Expr)) of
true -> setelement(2, Expr, L);
false -> Expr
end,
Elems = tuple_to_list(Expr1),
NewElems =
lists:foldl(
fun(Elem, Acc) ->
NewElem = change_line_numbers(L, Elem),
[NewElem | Acc]
end, [], lists:reverse(Elems)),
list_to_tuple(NewElems);
change_line_numbers(_L, Expr) ->
Expr.
| null | https://raw.githubusercontent.com/michaelmelanson/erlyweb/997df18b70459bfaaf8c3ab70ab4f54907045d0f/src/erltl/erltl.erl | erlang | @version 0.9.3
== Introduction ==
whose contents are mostly known at compile time.
ErlTL templates are generally less verbose and more readable than
dynamic HTML in web applications.
ErlTL emphasizes speed, simplicity, reusability and good error reporting.
whose functions are exported so they can be used in other modules.
== Tag Reference ==
An ErlTL template can be composed of the following tags:
[ Exprs ] % > ' < br/>Erlang expression tag . This tag contains one or more
expressions must be strings or binaries.
@ [ FuncDecl ] % > ' < br/>Function declaration tag .
functions. This module always contains a function named 'render'
that accepts a single parameter called 'Data'. The 'render' function
corresponds to the area at the top of an ErlTL file, above all other
function declarations.
You can use the function declaration tag to add more functions to
an ErlTL template.
ErlTL functions return the iolist described by to the template region
between its declaration and the next function declaration, or the end of
function declarations with the same name and arity into a single function
declaration with multiple clauses, as in the following example:
```
@ volume_desc(Val ) when > = 20 % > Big
@ volume_desc(Val ) when > = 10 % > Medium
<%@ volume_desc(Val) %> Small
'''
declaration up to the '->' symbol, e.g.
`"<%@ my_func(A, B = [1,2 | _]) when is_integer(A) %>"'.
A basic function declaration contains only the name of the function,
e.g. "`<%@ my_func %>'". This declaration is equivalent to
`"<%@ my_func(Data) %>"'.
`<%~ [TopForms] %>' <br/>Top-level forms tag.
This tag, which may appear only at the very top of an ErlTL file, can
compiler directives, and even complete functions.
`<%? [TopExprs] %>' <br/>Top-level expressions tag.
This tag, which may appear only at the top of ErlTL functions, contains
This is used primarily for "unpacking" the Data parameter and binding
its elements to local variables prior to using them in the body of a
function.
`<%! [Comment] %>' <br/>Comment tag. The contents of this tag are
used for documentation only. They are discarded in compile-time.
(you can find this code under test/erltl):
```
<%~
%% date: 10/21/2006
-author("Yariv Sadan").
%>
<%! This is a sample ErlTL template that renders a list of albums %>
<html>
<body>
<% [album(A) || A <- Data] %>
</body>
</html>
@ , Artist , Songs } ) % >
Title: <b><% Title %></b><br>
Artist: <b><% Artist %></b><br>
Songs: <br>
<table>
<% [song(Number, Name) || {Number, Name} <- Songs] %>
</table>
@ song(Number , Name ) when size(Name ) > 15 % >
<%? <<First:13/binary, Rest/binary>> = Name %>
song(Number , [ First , < < " ... " > > ] ) % >
<%@ song(Number, Name) %>
<%?
Class =
0 -> <<"even">>;
1 -> <<"odd">>
end
%>
<tr>
<td class="<% Class %>"><% integer_to_list(Number) %></td>
<td class="<% Class %>"><% Name %></td>
</tr>
'''
@end
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
without limitation the rights to use, copy, modify, merge, publish,
the following conditions:
The above copyright notice and this permission notice shall be included
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@doc Compile the ErlTL file with the default options:
(the old code is purged if necessary).
@doc Compile the ErlTL file with user-defined options. The options are
described in the documentation for the 'compile' module.
For more information, visit
[-5.5.1/lib/compiler-4.4.1/doc/html/compile.html]
@equiv forms_for_file(Filename, [])
abstract forms.
@doc Parse the raw text of an ErlTL template and return its
representation in abstract forms.
IncludePaths::[string()]) -> | @author < > [ ]
@copyright Yariv Sadan 2006 - 2007
@doc ErlTL is a simple Erlang template language .
ErlTL is a template language used for creating Erlang modules that
programatically generate iolists ( nested lists of strings and/or binaries )
the equivalent hand - written Erlang code .
A common use - case for ErlTL is the generation of
The ErlTL compiler transforms template files into Erlang modules whose
By compiling to BEAM , ErlTL does n't add any overhead to writing a template 's
logic in pure Erlang .
Erlang expressions that are evaluated in runtime .
For the template to return a valid iolist , the results of embedded Erlang
An ErlTL template compiles into an Erlang module containing one or more
the file . To facilitate pattern - matching , ErlTL translates consecutive
Function declarations have 2 possible forms : basic and full .
A full function declaration contains a complete Erlang function
contain any legal top - level Erlang form . This includes module attributes ,
Erlang expressions whose result is n't part of the function 's return value .
Following is an sample ErlTL template that uses the ErlTL tags above
-import(widgets , [ foo/1 , bar/2 , ] ) .
case Number rem 2 of
Copyright ( c ) 2006 - 2007
" Software " ) , to deal in the Software without restriction , including
distribute , sublicense , and/or sell copies of the Software , and to
permit persons to whom the Software is furnished to do so , subject to
in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS
MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT .
CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT ,
-module(erltl).
-author("Yariv Sadan (, )").
-export([compile/1, compile/2, forms_for_file/1,
forms_for_file/2, forms_for_data/2, forms_for_data/3]).
-define(L(Msg), io:format("~b ~p~n", [?LINE, Msg])).
` [ , FileDir } , report_errors , report_warnings , nowarn_unused_vars ] ' .
( FileDir is the directory of the source file . )
After compilation , the resulting BEAM is loaded into the VM
( ) ) - > ok | { error ,
compile(FileName) ->
compile(FileName, [{outdir, filename:dirname(FileName)},
report_errors, report_warnings, nowarn_unused_vars]).
( ) , Options::[option ( ) ] ) - > ok | { error ,
compile(FileName, Options) ->
IncludePaths = lists:foldl(
fun({i, Path}, Acc) ->
[Path | Acc];
(_Other, Acc) ->
Acc
end, [], Options),
case forms_for_file(FileName, IncludePaths) of
{ok, Forms} ->
case compile:forms(Forms,
Options) of
{ok, Module, Bin} ->
OutDir = case lists:keysearch(outdir, 1, Options)
of
{value, {outdir, Val}} -> Val;
false -> filename:dirname(FileName)
end,
BaseName = filename:rootname(filename:basename(FileName)),
case file:write_file(OutDir ++ ['/' | BaseName] ++
".beam", Bin) of
ok ->
code:purge(Module),
case code:load_binary(
Module, atom_to_list(Module), Bin)
of
{module, _Module} ->
ok;
Err ->
Err
end;
{error, _} = Err ->
Err
end;
Err ->
Err
end;
Err -> Err
end.
forms_for_file(FileName) ->
forms_for_file(FileName, []).
@doc Parse the ErlTL file and return its representation in Erlang
( ) ,
IncludePaths::[string ( ) ] ) - > { ok , [ form ( ) ] } | { error ,
forms_for_file(FileName, IncludePaths) ->
case file:read_file(FileName) of
{ok, Binary} ->
BaseName = filename:rootname(filename:basename(FileName)),
forms_for_data(Binary, list_to_atom(BaseName), IncludePaths);
Err ->
Err
end.
@equiv forms_form_data(Data , ModuleName , [ ] )
forms_for_data(Data, ModuleName) ->
forms_for_data(Data, ModuleName, []).
( ) | string ( ) , ( ) ,
{ ok , [ form ( ) ] } | { error ,
forms_for_data(Data, ModuleName, IncludePaths) when is_binary(Data) ->
forms_for_data(binary_to_list(Data), ModuleName, IncludePaths);
forms_for_data(Data, ModuleName, IncludePaths) ->
Lines = make_lines(Data),
case forms(Lines, ModuleName) of
{ok, Forms} ->
case catch lists:map(
fun({attribute, _, include, Include}) ->
process_include(
Include, [[], ["."] |
IncludePaths]);
(Form) ->
Form
end, Forms)
of
{'EXIT', Err} ->
{error, Err};
Res ->
{ok, lists:flatten(Res)}
end;
Err ->
Err
end.
process_include(Include, []) ->
exit({file_not_found, Include});
process_include(Include, [Path | Rest]) ->
case epp:parse_file(Path ++ "/" ++ Include, [], []) of
{error, enoent} ->
process_include(Include, Rest);
{ok, IncludeForms} ->
lists:sublist(
IncludeForms,
2,
length(IncludeForms) - 2)
end.
make_lines(Str) ->
make_lines(Str, [], []).
make_lines([], [], Result) -> lists:reverse(Result);
make_lines([], Acc, Result) -> lists:reverse([lists:reverse(Acc) | Result]);
make_lines([10 | Tail], Acc, Result) ->
make_lines(Tail, [], [lists:reverse(Acc) | Result]);
make_lines([Head | Tail], Acc, Result) ->
make_lines(Tail, [Head | Acc], Result).
forms(Lines, Module) ->
case catch parse(Lines) of
{'EXIT', Err} ->
{error, Err};
Forms ->
{ok, [{attribute,1,module,Module},
{attribute,2,file,{atom_to_list(Module),1}},
{attribute,3,compile,export_all}] ++ lists:reverse(Forms)}
end.
parse(Lines) ->
parse(Lines, binary, 1, [], [], [], []).
parse([], _State, _LineNo, TopExprs, Exprs, AllForms, ChunkAcc) ->
[FirstForms | OtherForms] = initial_forms(AllForms),
combine_forms(
embed_exprs(FirstForms, TopExprs, last_exprs(ChunkAcc, Exprs)) ++
OtherForms);
parse([Line | OtherLines], State, LineNo, TopExprs, Exprs,
AllForms, ChunkAcc) ->
case scan(Line, State) of
more ->
Line1 = case State of
binary -> Line ++ "\n";
_ -> Line
end,
parse(OtherLines, State, LineNo+1, TopExprs, Exprs,
AllForms, [{Line1, LineNo} | ChunkAcc]);
{ok, Chunk, NextState, NextChunk} ->
Chunks = [{Chunk, LineNo} | ChunkAcc],
Result = case State of
func_decl -> {func_decl, parse_func_decl(Chunks)};
binary -> {exprs, parse_binary(Chunks)};
top_exprs -> {top_exprs, parse_exprs(Chunks)};
forms -> {forms, parse_forms(Chunks)};
erlang -> {exprs, parse_exprs(Chunks)};
comment -> comment
end,
case Result of
comment ->
{NextLines, LineDiff} =
skip_line_break([NextChunk | OtherLines]),
parse(NextLines,
NextState, LineNo + LineDiff,
TopExprs, Exprs, AllForms, []);
{func_decl, BasicForms} ->
[CurrentForms | PreviousForms] = initial_forms(AllForms),
AllForms1 =
embed_exprs(CurrentForms, TopExprs, Exprs) ++
PreviousForms,
NewForms = combine_forms(AllForms1),
{NextLines, LineDiff} =
skip_line_break([NextChunk | OtherLines]),
parse(NextLines,
NextState, LineNo + LineDiff, [], [],
[BasicForms | NewForms], []);
{exprs, []} ->
NextLineNo = case Chunk of
[] -> LineNo;
_ -> LineNo + 1
end,
parse([NextChunk | OtherLines],
NextState, NextLineNo, TopExprs,
Exprs, AllForms, []);
{exprs, Exprs1} ->
parse([NextChunk | OtherLines],
NextState, LineNo, TopExprs,
Exprs1 ++ Exprs,
initial_forms(AllForms), []);
{top_exprs, TopExprs1} ->
case Exprs of
[] ->
parse([NextChunk | OtherLines], NextState, LineNo,
TopExprs1 ++ TopExprs,
Exprs, AllForms, []);
_ ->
error(misplaced_top_exprs, LineNo, Line,
"top expressions must appear before all "
"other expressions in a function")
end;
{forms, Forms} ->
case AllForms of
[] ->
{NextLines, LineDiff} =
skip_line_break([NextChunk | OtherLines]),
parse(NextLines,
NextState, LineNo + LineDiff, [], [],
initial_forms([]) ++ Forms, []);
_ -> error(misplaced_top_declaration, LineNo, Line,
"top-level declarations must appear at the "
"top of a file")
end
end
end.
combine_forms([{function,L,FuncName,Arity,Clauses},
{function,_,LastFuncName,LastArity,LastClauses} |
PreviousForms]) when LastFuncName == FuncName,
LastArity == Arity ->
[{function,L,FuncName,Arity, LastClauses ++ Clauses} | PreviousForms];
combine_forms(Forms) -> Forms.
scan(Line, State) ->
Delim =
case State of
binary -> {"<%",
[{$@, func_decl},
{$!, comment},
{$?, top_exprs},
{$~, forms}],
erlang};
_ -> {"%>", [], binary}
end,
scan1(Line, Delim).
scan1(Line, {Delim, Options, Default}) ->
case string:str(Line, Delim) of
0 -> more;
Pos ->
{First, [_,_ | Rest]} = lists:split(Pos-1, Line),
{NextState, NextChunk} =
case Rest of
[] -> {Default, Rest};
[FirstChar | OtherChars] ->
case lists:keysearch(FirstChar, 1, Options) of
{value, {_, NextState1}} ->
{NextState1, OtherChars};
false -> {Default, Rest}
end
end,
{ok, First, NextState, NextChunk}
end.
initial_forms([]) -> [parse_func_decl([{"render", 1}])];
initial_forms(AllForms) -> AllForms.
skip_line_break([[] | Lines]) -> {Lines, 1};
skip_line_break(Lines) -> {Lines, 0}.
last_exprs([], Exprs) -> Exprs;
last_exprs(ChunkAcc, Exprs) ->
parse_binary(ChunkAcc) ++ Exprs.
parse_binary([]) -> [];
parse_binary([{[],_}]) -> [];
parse_binary(Fragments) ->
BinElems =
lists:foldl(
fun({Chars, LineNo}, Acc) ->
Elems = lists:foldl(
fun(Char, BinElems) ->
[{bin_element,LineNo,{integer,LineNo,Char},
default,default} | BinElems]
end, [], lists:reverse(Chars)),
Elems ++ Acc
end, [], Fragments),
[{bin,1,BinElems}].
parse_exprs([]) -> [];
parse_exprs(Fragments) ->
Tokens = lists:foldl(
fun({Frag, LineNo}, Acc) ->
case erl_scan:string(Frag, LineNo) of
{ok, Toks, _} -> Toks ++ Acc;
{error, Err, _} -> error(scan_error, LineNo, Frag, Err)
end
end, [{dot,1}], Fragments),
Tokens1 = Tokens,
case erl_parse:parse_exprs(Tokens1) of
{ok, Exprs} -> [{block,1, Exprs}];
{error, Msg} -> exit({parse_error, Msg})
end.
parse_forms([]) -> [];
parse_forms(Fragments) ->
FormsTokens =
lists:foldl(
fun({Frag, LineNo}, Acc) ->
case erl_scan:string(Frag, LineNo) of
{ok, Toks, _} ->
lists:foldl(
fun({dot,_} = Tok, [Form | Rest]) ->
[[Tok] | [Form | Rest]];
(Tok, [Form | Rest]) ->
[[Tok | Form] | Rest]
end, Acc, lists:reverse(Toks));
{error, Err, _} ->
error(scan_error, LineNo, Frag, Err)
end
end, [[]], Fragments),
lists:foldl(
fun([], Acc) -> Acc;
(FormTokens, Acc) ->
case erl_parse:parse_form(FormTokens) of
{ok, Form} ->
[Form | Acc];
{error, Err} -> exit({parse_error, Err})
end
end, [], FormsTokens).
parse_func_decl(Fragments) ->
{FuncDecl, LineNo} =
lists:foldl(
fun({Chars, LineNo}, {Acc, FirstLine}) ->
Elems = lists:foldl(
fun(Char, Chars1) ->
[Char | Chars1]
end, [], lists:reverse(Chars)),
FirstLine1 = case FirstLine of
undefined -> LineNo;
_ -> FirstLine
end,
{Elems ++ Acc, FirstLine1}
end, {[], undefined}, Fragments),
case erl_scan:string(FuncDecl) of
{ok, [{atom,_,FuncName}], _} ->
[{full_form,
{function, LineNo, FuncName, 0,
[{clause, LineNo, [], [],
[{call,LineNo,{atom,LineNo,FuncName},
[{atom,1,undefined}]}]
}]
}},
{empty_form,
{function, LineNo, FuncName, 1,
[{clause, LineNo, [{var,LineNo,'Data'}], [], []}]}}];
{ok, _, _} ->
case erl_scan:string(FuncDecl ++ " -> funky_func.") of
{ok, Toks, _} ->
case erl_parse:parse_form(Toks) of
{ok, Form} ->
[{empty_form,
change_line_numbers(LineNo, Form)}];
{error, Msg} ->
error(parse_error, LineNo, FuncDecl, Msg)
end;
{error, Msg, _} ->
error(scan_error, LineNo, FuncDecl, Msg)
end;
{error, Msg, _} -> error(scan_error, LineNo, FuncDecl, Msg)
end.
error(Type, Line, Chunk, Msg) ->
exit({Type, {{line, Line}, {chunk, Chunk}, {msg, Msg}}}).
embed_exprs(Forms, TopExprs, Exprs) when is_list(Forms) ->
[embed_exprs(Form, TopExprs, Exprs) || Form <- Forms];
embed_exprs({full_form, Form}, _TopExprs, _Exprs) -> Form;
embed_exprs({empty_form,
{function,Line,FuncName,Arity,
[{clause, Line1, Params, Guards, _UnusedExprs}]}},
TopExprs, Exprs) ->
{function,Line,FuncName,Arity,[{clause,Line1,Params,Guards,
lists:reverse(TopExprs) ++
[cons_exprs(lists:reverse(Exprs))]}]}.
cons_exprs([]) -> {nil,1};
cons_exprs([{bin,L,BinElems}, {bin,_,BinElems1} | Rest]) ->
cons_exprs([{bin,L,BinElems ++ BinElems1} | Rest]);
cons_exprs([Expr|Rest]) ->
{cons,1,Expr,cons_exprs(Rest)}.
change_line_numbers(L, Exprs) when is_list(Exprs) ->
lists:foldl(
fun(Expr, Acc) ->
[change_line_numbers(L, Expr) | Acc]
end, [], lists:reverse(Exprs));
change_line_numbers(L, Expr) when is_tuple(Expr) ->
Expr1 = case is_integer(element(2, Expr)) of
true -> setelement(2, Expr, L);
false -> Expr
end,
Elems = tuple_to_list(Expr1),
NewElems =
lists:foldl(
fun(Elem, Acc) ->
NewElem = change_line_numbers(L, Elem),
[NewElem | Acc]
end, [], lists:reverse(Elems)),
list_to_tuple(NewElems);
change_line_numbers(_L, Expr) ->
Expr.
|
be7f85c68728b358570d98feacbed1831e3692258112eac547ca1221471bdbdd | purcell/adventofcode2016 | Day14.hs | module Main where
import AdventOfCode
import qualified Crypto.Hash as H
import Data.ByteString (ByteString)
import Data.String (fromString)
import Data.List (isInfixOf, tails)
import Control.Arrow ((&&&))
hexMD5 :: String -> String
hexMD5 = show . md5 . fromString
where
md5 :: ByteString -> H.Digest H.MD5
md5 = H.hash
hash :: Int -> String -> Int -> String
hash stretches salt n = iterate hexMD5 (salt ++ show n) !! stretches
keys :: (Int -> String) -> [(Int, String)]
keys hasher = go ((id &&& hasher) <$> [0 ..])
where
go (h@(n, s):hs) =
[ h
| c <-
take
1
[ x
| x:y:z:_ <- tails s
, x == y
, y == z ]
, any (replicate 5 c `isInfixOf`) (snd <$> take 1000 hs) ] ++
go hs
solve stretches = (!! 63) . keys . hash stretches
main =
runDay $
Day
14
(many1 letter <* newline)
(return . show . solve 1)
(return . show . solve 2017)
| null | https://raw.githubusercontent.com/purcell/adventofcode2016/081f30de4ea6b939e6c3736d83836f4dd72ab9a2/src/Day14.hs | haskell | module Main where
import AdventOfCode
import qualified Crypto.Hash as H
import Data.ByteString (ByteString)
import Data.String (fromString)
import Data.List (isInfixOf, tails)
import Control.Arrow ((&&&))
hexMD5 :: String -> String
hexMD5 = show . md5 . fromString
where
md5 :: ByteString -> H.Digest H.MD5
md5 = H.hash
hash :: Int -> String -> Int -> String
hash stretches salt n = iterate hexMD5 (salt ++ show n) !! stretches
keys :: (Int -> String) -> [(Int, String)]
keys hasher = go ((id &&& hasher) <$> [0 ..])
where
go (h@(n, s):hs) =
[ h
| c <-
take
1
[ x
| x:y:z:_ <- tails s
, x == y
, y == z ]
, any (replicate 5 c `isInfixOf`) (snd <$> take 1000 hs) ] ++
go hs
solve stretches = (!! 63) . keys . hash stretches
main =
runDay $
Day
14
(many1 letter <* newline)
(return . show . solve 1)
(return . show . solve 2017)
| |
780d79d83c93527c0f442d1dcb6a3bec0319e39c20d51845a54adc1d930b7419 | cdepillabout/servant-checked-exceptions | API.hs | {-# LANGUAGE PackageImports #-}
module Servant.Checked.Exceptions.Internal.Servant.API (
module Servant.Checked.Exceptions.Internal.Servant.API
) where
import "servant-checked-exceptions-core" Servant.Checked.Exceptions.Internal.Servant.API
| null | https://raw.githubusercontent.com/cdepillabout/servant-checked-exceptions/8ec4e831e45e51f3404790496f036a42c7349afa/servant-checked-exceptions/src/Servant/Checked/Exceptions/Internal/Servant/API.hs | haskell | # LANGUAGE PackageImports # |
module Servant.Checked.Exceptions.Internal.Servant.API (
module Servant.Checked.Exceptions.Internal.Servant.API
) where
import "servant-checked-exceptions-core" Servant.Checked.Exceptions.Internal.Servant.API
|
684f1342a85080eb114f56939a41b1007eef71e8f7bb660283e247250097aea3 | faylang/fay | List.hs | {-# OPTIONS -fno-warn-orphans #-}
{-# LANGUAGE EmptyDataDecls #-}
# LANGUAGE StandaloneDeriving #
module Data.List where
import Prelude
import Data.Maybe
| The ' isPrefixOf ' function takes two lists and returns ' True '
iff the first list is a prefix of the second .
isPrefixOf :: (Eq a) => [a] -> [a] -> Bool
isPrefixOf [] _ = True
isPrefixOf _ [] = False
isPrefixOf (x:xs) (y:ys)= x == y && isPrefixOf xs ys
| The ' isSuffixOf ' function takes two lists and returns ' True '
iff the first list is a suffix of the second .
-- Both lists must be finite.
isSuffixOf :: (Eq a) => [a] -> [a] -> Bool
isSuffixOf x y = reverse x `isPrefixOf` reverse y
| The ' ' function drops the given prefix from a list .
-- It returns 'Nothing' if the list did not start with the prefix
-- given, or 'Just' the list after the prefix, if it does.
--
> " foo " " foobar " = = Just " bar "
> " foo " " foo " = = Just " "
> " foo " " barfoo " = = Nothing
> " foo " " barfoobaz " = = Nothing
stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]
stripPrefix [] ys = Just ys
stripPrefix (x:xs) (y:ys)
| x == y = stripPrefix xs ys
stripPrefix _ _ = Nothing
| Like ' ' , but drops the given suffix from the end .
stripSuffix :: Eq a => [a] -> [a] -> Maybe [a]
stripSuffix x y = onJust reverse $ reverse x `stripPrefix` reverse y
-- | Split lists at delimiter specified by a condition
-- Drops empty groups (similar to `words`)
splitWhen :: (a -> Bool) -> [a] -> [[a]]
splitWhen p s = case dropWhile p s of
[] -> []
s' -> case break p s' of
(w, s'') -> w : splitWhen p s''
-- | Split lists at the specified delimiter
-- Drops empty groups (similar to `words`)
splitOn :: Eq a => a -> [a] -> [[a]]
splitOn c = splitWhen (==c)
-- | The 'partition' function takes a predicate a list and returns
-- the pair of lists of elements which do and do not satisfy the
-- predicate, respectively; i.e.,
--
-- > partition p xs == (filter p xs, filter (not . p) xs)
partition :: (a -> Bool) -> [a] -> ([a],[a])
partition p xs = (filter p xs, filter (not . p) xs)
-- does n't support irrefutable patterns
partition : : ( a - > Bool ) - > [ a ] - > ( [ a],[a ] )
partition p = foldr ( select p ) ( [ ] , [ ] )
where
select : : ( a - > Bool ) - > a - > ( [ a ] , [ a ] ) - > ( [ a ] , [ a ] )
select p x ~(ts , fs ) | p x = ( x : ts , fs )
| otherwise = ( ts , x : fs )
-- Fay doesn't support irrefutable patterns
partition :: (a -> Bool) -> [a] -> ([a],[a])
partition p = foldr (select p) ([],[])
where
select :: (a -> Bool) -> a -> ([a], [a]) -> ([a], [a])
select p x ~(ts,fs) | p x = (x:ts,fs)
| otherwise = (ts, x:fs)
-}
-- | The 'inits' function returns all initial segments of the argument,
shortest first . For example ,
--
> inits " abc " = = [ " " , " a","ab","abc " ]
--
-- Note that 'inits' has the following strictness property:
-- @inits _|_ = [] : _|_@
inits :: [a] -> [[a]]
inits xs = [] : case xs of
[] -> []
x : xs' -> map (x :) (inits xs')
This one /isn't/ from Data . List
groupSortBy :: (a -> a -> Ordering) -> [a] -> [[a]]
groupSortBy f = groupBy (\x y -> f x y == EQ) . sortBy f
| Classic group by .
groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy _ [] = []
groupBy eq (x:xs) = case span (eq x) xs of
(ys,zs) -> (x:ys) : groupBy eq zs
| Belongs in Control . , right ?
findM :: (a -> Fay (Maybe b)) -> [a] -> Fay (Maybe b)
findM _ [] = return Nothing
findM f (x:xs) = do
b <- f x
case b of
Nothing -> findM f xs
Just _ -> return b
| null | https://raw.githubusercontent.com/faylang/fay/8455d975f9f0db2ecc922410e43e484fbd134699/fay-base/src/Data/List.hs | haskell | # OPTIONS -fno-warn-orphans #
# LANGUAGE EmptyDataDecls #
Both lists must be finite.
It returns 'Nothing' if the list did not start with the prefix
given, or 'Just' the list after the prefix, if it does.
| Split lists at delimiter specified by a condition
Drops empty groups (similar to `words`)
| Split lists at the specified delimiter
Drops empty groups (similar to `words`)
| The 'partition' function takes a predicate a list and returns
the pair of lists of elements which do and do not satisfy the
predicate, respectively; i.e.,
> partition p xs == (filter p xs, filter (not . p) xs)
does n't support irrefutable patterns
Fay doesn't support irrefutable patterns
| The 'inits' function returns all initial segments of the argument,
Note that 'inits' has the following strictness property:
@inits _|_ = [] : _|_@ | # LANGUAGE StandaloneDeriving #
module Data.List where
import Prelude
import Data.Maybe
| The ' isPrefixOf ' function takes two lists and returns ' True '
iff the first list is a prefix of the second .
isPrefixOf :: (Eq a) => [a] -> [a] -> Bool
isPrefixOf [] _ = True
isPrefixOf _ [] = False
isPrefixOf (x:xs) (y:ys)= x == y && isPrefixOf xs ys
| The ' isSuffixOf ' function takes two lists and returns ' True '
iff the first list is a suffix of the second .
isSuffixOf :: (Eq a) => [a] -> [a] -> Bool
isSuffixOf x y = reverse x `isPrefixOf` reverse y
| The ' ' function drops the given prefix from a list .
> " foo " " foobar " = = Just " bar "
> " foo " " foo " = = Just " "
> " foo " " barfoo " = = Nothing
> " foo " " barfoobaz " = = Nothing
stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]
stripPrefix [] ys = Just ys
stripPrefix (x:xs) (y:ys)
| x == y = stripPrefix xs ys
stripPrefix _ _ = Nothing
| Like ' ' , but drops the given suffix from the end .
stripSuffix :: Eq a => [a] -> [a] -> Maybe [a]
stripSuffix x y = onJust reverse $ reverse x `stripPrefix` reverse y
splitWhen :: (a -> Bool) -> [a] -> [[a]]
splitWhen p s = case dropWhile p s of
[] -> []
s' -> case break p s' of
(w, s'') -> w : splitWhen p s''
splitOn :: Eq a => a -> [a] -> [[a]]
splitOn c = splitWhen (==c)
partition :: (a -> Bool) -> [a] -> ([a],[a])
partition p xs = (filter p xs, filter (not . p) xs)
partition : : ( a - > Bool ) - > [ a ] - > ( [ a],[a ] )
partition p = foldr ( select p ) ( [ ] , [ ] )
where
select : : ( a - > Bool ) - > a - > ( [ a ] , [ a ] ) - > ( [ a ] , [ a ] )
select p x ~(ts , fs ) | p x = ( x : ts , fs )
| otherwise = ( ts , x : fs )
partition :: (a -> Bool) -> [a] -> ([a],[a])
partition p = foldr (select p) ([],[])
where
select :: (a -> Bool) -> a -> ([a], [a]) -> ([a], [a])
select p x ~(ts,fs) | p x = (x:ts,fs)
| otherwise = (ts, x:fs)
-}
shortest first . For example ,
> inits " abc " = = [ " " , " a","ab","abc " ]
inits :: [a] -> [[a]]
inits xs = [] : case xs of
[] -> []
x : xs' -> map (x :) (inits xs')
This one /isn't/ from Data . List
groupSortBy :: (a -> a -> Ordering) -> [a] -> [[a]]
groupSortBy f = groupBy (\x y -> f x y == EQ) . sortBy f
| Classic group by .
groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy _ [] = []
groupBy eq (x:xs) = case span (eq x) xs of
(ys,zs) -> (x:ys) : groupBy eq zs
| Belongs in Control . , right ?
findM :: (a -> Fay (Maybe b)) -> [a] -> Fay (Maybe b)
findM _ [] = return Nothing
findM f (x:xs) = do
b <- f x
case b of
Nothing -> findM f xs
Just _ -> return b
|
dfb1f14ee44e998fb546e52c639adeec8cdb7ecb94b9a066914078f100a047d0 | life0fun/clojure-idiom | tweet_spout.clj | (ns trident-clj.tweet-spout
(:import [java.io FileReader]
[java.util Random Map Map$Entry List ArrayList Collection Iterator HashMap])
(:import [backtype.storm Config StormSubmitter LocalCluster LocalDRPC]
[backtype.storm.spout SchemeAsMultiScheme]
[storm.trident.operation TridentCollector Function]
[backtype.storm.tuple Fields Tuple]
[storm.trident.spout.IBatchSpout]
[backtype.storm.tuple Values])
(:require [clojure.string :as str]
[clojure.tools.logging :as log]
[clojure.contrib.io :refer [pwd]]
[clj-time.core :as clj-time :exclude [extend]] ; clj-time abbrev to core
[clj-time.format])
(:require [clj-redis.client :as redis]) ; bring in redis namespace
(:gen-class
convert this ns to class
:state state ; put serialiazable object here.
:init init ; Must return [ [superclass-constructor-args] state]
:constructors {[] [] ; empty arg constructor
[String int] []} ; a map of constructor sig to superclass construcotr signature
:implements [storm.trident.spout.IBatchSpout])) ; this ns impl Function
init always ret a vector with the first be superclass constructor arg , and
the second is instance state .
; Must return [ [superclass-constructor-args] state]
(defn -init
"init state, no this pointer, ret a global concurrent map stores all states"
empty arg constructor , use default file at current pwd is project root .
[[] {:batchsize 10 :srcfile "data/500_sentences_en.txt"}])
([srcfile batchsize]
; cant use atom, as it is not serializable
[ [ ] ( atom { : batchsize 10 : sentences [ ] : random - gen ( Random . ) } ) ] )
[[] {:batchsize batchsize :srcfile srcfile}]))
; open fn only called once, so instantiate global state here.
(defn -open ; gen-class method prefix by -
"called once when instantiate spout instance, init state here"
[this conf context]
; populate sentence vector inside atom map
( let [ state ( .state this )
sentence - vec (: sentence ) ]
( swap ! state assoc : sentence ( " this is first tweet " ) )
( swap ! state assoc : sentence ( " those are second tweet " ) ) ) )
(let [state (.state this)
srcfile (:srcfile state)]
; def namespace global mutable shared state.
(prn "spout open called : " srcfile (pwd))
(def TWEETCNT (atom 0))
(def ACTORS ["stefan" "dave" "pere" "nathan" "doug" "ted" "mary" "rose"])
(def LOCATIONS ["Spain" "USA" "Spain" "USA" "USA" "USA" "UK" "France"])
(def SUBJECTS ["berlin" "justinbieber" "hadoop" "life" "bigdata"])
; connect to rabbitmq or logstash src, abstract queue as a lazy sequence.
(def srcseq (atom (line-seq (clojure.java.io/reader srcfile))))))
(defn -ack
[this batch-id]
(prn " ack " batch-id))
(defn -close
[this])
(defn -getComponentConfiguration
[this]
(Config.)) ; just instantiate a new config object
; output stream field spec.
(defn -getOutputFields
[this]
(Fields. ["id" "actor" "text" "location" "time"]))
; feed the top with next tweet
(defn getNextTweet
"get next tweet from preload sentence vector"
[this]
(let [state (.state this)
text (first @srcseq)
idx (rand-int (count ACTORS))
actor (ACTORS idx)
location (LOCATIONS idx)
ts (clj-time.format/unparse (clj-time.format/formatters :date-time) (clj-time/now))]
text ( [ " this is first tweet " " that are second tweet " ] ( rand - int 2 ) ) ]
; for now, just simple fake random between 0 1
(swap! TWEETCNT inc)
(swap! srcseq (fn [s] (next s))) ; srcseq = (next srcseq)
;(prn "emit " text @TWEETCNT actor location ts)
(Values. (to-array [(str @TWEETCNT) actor text location ts]))))
(defn -emitBatch
"emit a batch of tuples"
[this batchId ^storm.trident.operation.TridentCollector collector]
(let [state (.state this)
sz (:batchsize state)]
(doseq [i (range sz)]
(.emit collector (getNextTweet this))))) | null | https://raw.githubusercontent.com/life0fun/clojure-idiom/481b297eeabea917a68b492b1fb78b8151408507/trident-clj/src/trident_clj/tweet_spout.clj | clojure | clj-time abbrev to core
bring in redis namespace
put serialiazable object here.
Must return [ [superclass-constructor-args] state]
empty arg constructor
a map of constructor sig to superclass construcotr signature
this ns impl Function
Must return [ [superclass-constructor-args] state]
cant use atom, as it is not serializable
open fn only called once, so instantiate global state here.
gen-class method prefix by -
populate sentence vector inside atom map
def namespace global mutable shared state.
connect to rabbitmq or logstash src, abstract queue as a lazy sequence.
just instantiate a new config object
output stream field spec.
feed the top with next tweet
for now, just simple fake random between 0 1
srcseq = (next srcseq)
(prn "emit " text @TWEETCNT actor location ts) | (ns trident-clj.tweet-spout
(:import [java.io FileReader]
[java.util Random Map Map$Entry List ArrayList Collection Iterator HashMap])
(:import [backtype.storm Config StormSubmitter LocalCluster LocalDRPC]
[backtype.storm.spout SchemeAsMultiScheme]
[storm.trident.operation TridentCollector Function]
[backtype.storm.tuple Fields Tuple]
[storm.trident.spout.IBatchSpout]
[backtype.storm.tuple Values])
(:require [clojure.string :as str]
[clojure.tools.logging :as log]
[clojure.contrib.io :refer [pwd]]
[clj-time.format])
(:gen-class
convert this ns to class
init always ret a vector with the first be superclass constructor arg , and
the second is instance state .
(defn -init
"init state, no this pointer, ret a global concurrent map stores all states"
empty arg constructor , use default file at current pwd is project root .
[[] {:batchsize 10 :srcfile "data/500_sentences_en.txt"}])
([srcfile batchsize]
[ [ ] ( atom { : batchsize 10 : sentences [ ] : random - gen ( Random . ) } ) ] )
[[] {:batchsize batchsize :srcfile srcfile}]))
"called once when instantiate spout instance, init state here"
[this conf context]
( let [ state ( .state this )
sentence - vec (: sentence ) ]
( swap ! state assoc : sentence ( " this is first tweet " ) )
( swap ! state assoc : sentence ( " those are second tweet " ) ) ) )
(let [state (.state this)
srcfile (:srcfile state)]
(prn "spout open called : " srcfile (pwd))
(def TWEETCNT (atom 0))
(def ACTORS ["stefan" "dave" "pere" "nathan" "doug" "ted" "mary" "rose"])
(def LOCATIONS ["Spain" "USA" "Spain" "USA" "USA" "USA" "UK" "France"])
(def SUBJECTS ["berlin" "justinbieber" "hadoop" "life" "bigdata"])
(def srcseq (atom (line-seq (clojure.java.io/reader srcfile))))))
(defn -ack
[this batch-id]
(prn " ack " batch-id))
(defn -close
[this])
(defn -getComponentConfiguration
[this]
(defn -getOutputFields
[this]
(Fields. ["id" "actor" "text" "location" "time"]))
(defn getNextTweet
"get next tweet from preload sentence vector"
[this]
(let [state (.state this)
text (first @srcseq)
idx (rand-int (count ACTORS))
actor (ACTORS idx)
location (LOCATIONS idx)
ts (clj-time.format/unparse (clj-time.format/formatters :date-time) (clj-time/now))]
text ( [ " this is first tweet " " that are second tweet " ] ( rand - int 2 ) ) ]
(swap! TWEETCNT inc)
(Values. (to-array [(str @TWEETCNT) actor text location ts]))))
(defn -emitBatch
"emit a batch of tuples"
[this batchId ^storm.trident.operation.TridentCollector collector]
(let [state (.state this)
sz (:batchsize state)]
(doseq [i (range sz)]
(.emit collector (getNextTweet this))))) |
57117184ce09d12a2b04736a41786af2e060f7a2efba98b3ad2ca0d9bc7f06b2 | soegaard/sketching | shape.rkt | #lang racket/base
(provide Shape
create-shape)
(require racket/class
sketching/graphics
sketching/transform)
; Shape class to represent storable shapes.
(define Shape
(class object%
(define-values (shape-struct
finalized
visible
children
child-count
vertex-count
fill-args
stroke-args
transformation-matrix) (values #f ; shape-struct
#f ; finalized
#t ; visible
'() ; children
0 ; child-count
0 ; vertex-count
#f; fill-args
#f; stroke-args
(new-matrix 1 0 0 1 0 0) ;transformation
))
(define/public (begin-shape [kind 'default])
(set! finalized #f)
(set! shape-struct (new-shape kind)))
(define/public (end-shape [closed? #t])
(set! shape-struct (finish-shape shape-struct 'end-shape closed?))
(set! finalized #t))
(define/public (vertex x y)
(if (not finalized)
(begin
(set! vertex-count (add1 vertex-count))
(set-shape-rev-points! shape-struct
(cons (cons x y) (shape-rev-points shape-struct))))
(error 'vertex "vertex can't be added to a finalized shape.")))
(define/public (get-vertex-count)
vertex-count)
(define/public (draw [x 0] [y 0])
(when (and finalized visible)
(draw-shape shape-struct x y fill-args stroke-args transformation-matrix)
(for ([c children])
(send c draw x y))))
(define/public (visible?)
visible)
(define/public (set-visible v)
(set! visible v))
(define/public (get-child-count)
child-count)
(define/public (add-child child)
(set! child-count (add1 child-count))
(set! children (cons child children)))
(define/public (get-child index)
(if (>= index child-count)
(error 'get-child "index is greater or equal than the number of children: index: ~a, child-count: ~a" index child-count)
(list-ref children index)))
(define/public (remove-children)
(set! child-count 0)
(set! children '()))
(define/public (set-fill . args)
(set! fill-args args))
(define/public (set-stroke . args)
(set! stroke-args args))
(define/public (translate dx dy)
Note : The cairo ` multiply ` flips the order of a normal multiply .
(define tra (translation-matrix dx dy))
(send transformation-matrix multiply transformation-matrix tra))
(define/public scale
Note : The cairo ` multiply ` flips the order of a normal multiply .
(case-lambda
[(s) (define sca (scaling-matrix s s))
(send transformation-matrix multiply transformation-matrix sca)]
[(sx sy) (define sca (scaling-matrix sx sy))
(send transformation-matrix multiply transformation-matrix sca)]
[else (error 'scale "incorrect arguments")]))
(define/public (rotate angle)
Note : The cairo ` multiply ` flips the order of a normal multiply .
(define rot (rotation-matrix angle))
(send transformation-matrix multiply transformation-matrix rot))
(define/public (reset-matrix)
(set! transformation-matrix (new-matrix 1 0 0 1 0 0)))
(super-new)))
(define (create-shape)
(new Shape))
| null | https://raw.githubusercontent.com/soegaard/sketching/3e846620bcb38a9aa5f5d7c7c86db889a3aadd55/sketching-lib/sketching/shape.rkt | racket | Shape class to represent storable shapes.
shape-struct
finalized
visible
children
child-count
vertex-count
fill-args
stroke-args
transformation | #lang racket/base
(provide Shape
create-shape)
(require racket/class
sketching/graphics
sketching/transform)
(define Shape
(class object%
(define-values (shape-struct
finalized
visible
children
child-count
vertex-count
fill-args
stroke-args
))
(define/public (begin-shape [kind 'default])
(set! finalized #f)
(set! shape-struct (new-shape kind)))
(define/public (end-shape [closed? #t])
(set! shape-struct (finish-shape shape-struct 'end-shape closed?))
(set! finalized #t))
(define/public (vertex x y)
(if (not finalized)
(begin
(set! vertex-count (add1 vertex-count))
(set-shape-rev-points! shape-struct
(cons (cons x y) (shape-rev-points shape-struct))))
(error 'vertex "vertex can't be added to a finalized shape.")))
(define/public (get-vertex-count)
vertex-count)
(define/public (draw [x 0] [y 0])
(when (and finalized visible)
(draw-shape shape-struct x y fill-args stroke-args transformation-matrix)
(for ([c children])
(send c draw x y))))
(define/public (visible?)
visible)
(define/public (set-visible v)
(set! visible v))
(define/public (get-child-count)
child-count)
(define/public (add-child child)
(set! child-count (add1 child-count))
(set! children (cons child children)))
(define/public (get-child index)
(if (>= index child-count)
(error 'get-child "index is greater or equal than the number of children: index: ~a, child-count: ~a" index child-count)
(list-ref children index)))
(define/public (remove-children)
(set! child-count 0)
(set! children '()))
(define/public (set-fill . args)
(set! fill-args args))
(define/public (set-stroke . args)
(set! stroke-args args))
(define/public (translate dx dy)
Note : The cairo ` multiply ` flips the order of a normal multiply .
(define tra (translation-matrix dx dy))
(send transformation-matrix multiply transformation-matrix tra))
(define/public scale
Note : The cairo ` multiply ` flips the order of a normal multiply .
(case-lambda
[(s) (define sca (scaling-matrix s s))
(send transformation-matrix multiply transformation-matrix sca)]
[(sx sy) (define sca (scaling-matrix sx sy))
(send transformation-matrix multiply transformation-matrix sca)]
[else (error 'scale "incorrect arguments")]))
(define/public (rotate angle)
Note : The cairo ` multiply ` flips the order of a normal multiply .
(define rot (rotation-matrix angle))
(send transformation-matrix multiply transformation-matrix rot))
(define/public (reset-matrix)
(set! transformation-matrix (new-matrix 1 0 0 1 0 0)))
(super-new)))
(define (create-shape)
(new Shape))
|
fbd5b8b8eb93fe0bf20be8a79153c378538af8f3c7588864be9bed4a4ce1da1f | OCamlPro/freeton_wallet | commandTokenWTONWithdraw.ml | (**************************************************************************)
(* *)
Copyright ( c ) 2021 OCamlPro SAS
(* *)
(* All rights reserved. *)
(* This file is distributed under the terms of the GNU Lesser General *)
Public License version 2.1 , with the special exception on linking
(* described in the LICENSE.md file in the root directory. *)
(* *)
(* *)
(**************************************************************************)
open Ezcmd.V2
open EZCMD.TYPES
open CommandTokenList.TYPES
open Types
let action config ~account ~amount () =
let ctxt = CommandTokenList.get_context config in
let account_key = Misc.find_key_exn ctxt.net account in
let account_contract = CommandMultisigCreate.check_key_contract account_key in
let account_address = Misc.get_key_address_exn account_key in
Printf.printf "%s (at %s, %s):\n%!" account
( ADDRESS.to_string account_address ) account_contract;
let amount = Misc.nanotokens_of_string amount in
let token = CommandTokenList.get_token_by_symbol ctxt "WTON" in
let wallet_address =
CommandTokenList.get_token_wallet_address ctxt token account_address in
let payload =
let abi = ctxt.wallet_contract_abi in
let meth = "transferToRecipient" in
let params =
Printf.sprintf {|{
"recipient_public_key": 0,
"recipient_address": "%s",
"tokens": "%s",
"deploy_grams": 0,
"transfer_grams": 0,
"send_gas_to": "%s",
"notify_receiver": true,
"payload": ""
}|}
( ADDRESS.to_string ctxt.vault_address )
( Int64.to_string amount )
( ADDRESS.to_string account_address )
in
Ton_sdk.ABI.encode_body ~abi ~meth ~params
in
let params = Printf.sprintf
{|{"dest":"%s","value":%Ld,"bounce":%b,"flags":%d,"payload":"%s"}|}
( ADDRESS.to_string wallet_address )
2_000_000_000L
true
0
payload
in
Utils.call_contract config
~contract:account_contract
~address:account_address
~meth:"sendTransaction"
~params
~local:false
~src:account_key
~wait:true
();
match CommandTokenList.get_token_balance_gas ctxt ~wallet_address with
| None ->
Printf.printf " %s\n%!" token.Types.MANIFEST.token_name ;
Printf.printf " address: %s\n%!" ( ADDRESS.to_string wallet_address );
Printf.printf " Broxus_TONTokenWallet contract not yet deployed\n%!";
| Some ( balance, gas ) ->
Printf.printf " %s\n%!" token.Types.MANIFEST.token_name ;
Printf.printf " address: %s\n%!" ( ADDRESS.to_string wallet_address );
Printf.printf " balance %s (gas %s TON)\n%!"
( CommandTokenList.string_of_amount_token balance token )
( Misc.string_of_nanoton gas )
let root_address = token . Types . MANIFEST.token_address in
let params = Printf.sprintf { | { " _ answer_id " : 1 ,
" wallet_public_key _ " : 0 ,
" owner_address _ " : " % s"}| }
address
in
let reply =
Utils.call_run config ~client ~wait ~server_url
~address : root_address
~abi : root_contract_abi
~meth:"getWalletAddress "
~params
~local : true
( )
in
let address = (
destruct " getWalletAddress reply " GETWALLETADDRESS.reply_enc reply
) .value0
in
let info = CommandAccountState.get_address_info config
( RawAddress address ) in
match info with
| None - >
Printf.printf " % s\n% ! " token . Types . MANIFEST.token_name ;
Printf.printf " address : % s\n% ! " address ;
Printf.printf " Broxus_TONTokenWallet contract not yet deployed\n% ! " ;
| Some acc - >
let gas =
match acc.acc_balance with
| None - > " 0 "
| Some n - > Misc.string_of_nanoton ( Z.to_int64 n )
in
Printf.printf " % s\n% ! " token . Types . MANIFEST.token_name ;
Printf.printf " address : % s\n% ! " address ;
let params = Printf.sprintf { | { " _ answer_id " : 1 } | } in
let reply =
Utils.call_run config ~client ~wait ~server_url
~address
~abi : wallet_contract_abi
"
~params
~local : true
( )
in
let balance = (
destruct " balance reply " GETWALLETADDRESS.reply_enc reply
) .value0
in
let balance = Int64.of_string balance in
Printf.printf " balance % s % s ( gas % s TON)\n% ! "
( Misc.string_of_nanoton balance )
token . Types . MANIFEST.token_symbol
gas
)
let root_address = token.Types.MANIFEST.token_address in
let params = Printf.sprintf {|{ "_answer_id": 1,
"wallet_public_key_": 0,
"owner_address_": "%s"}|}
address
in
let reply =
Utils.call_run config ~client ~wait ~server_url
~address:root_address
~abi:root_contract_abi
~meth:"getWalletAddress"
~params
~local:true
()
in
let address = (
destruct "getWalletAddress reply" GETWALLETADDRESS.reply_enc reply
).value0
in
let info = CommandAccountState.get_address_info config
(RawAddress address) in
match info with
| None ->
Printf.printf " %s\n%!" token.Types.MANIFEST.token_name ;
Printf.printf " address: %s\n%!" address;
Printf.printf " Broxus_TONTokenWallet contract not yet deployed\n%!";
| Some acc ->
let gas =
match acc.acc_balance with
| None -> "0"
| Some n -> Misc.string_of_nanoton ( Z.to_int64 n )
in
Printf.printf " %s\n%!" token.Types.MANIFEST.token_name ;
Printf.printf " address: %s\n%!" address;
let params = Printf.sprintf {|{ "_answer_id": 1 }|} in
let reply =
Utils.call_run config ~client ~wait ~server_url
~address
~abi:wallet_contract_abi
~meth:"balance"
~params
~local:true
()
in
let balance = (
destruct "balance reply" GETWALLETADDRESS.reply_enc reply
).value0
in
let balance = Int64.of_string balance in
Printf.printf " balance %s %s (gas %s TON)\n%!"
( Misc.string_of_nanoton balance )
token.Types.MANIFEST.token_symbol
gas
) manifest.Types.MANIFEST.tokens
*)
let cmd =
let args = ref [] in
Misc.cmd
["token"; "wton"; "withdraw"]
(fun () ->
let config = Config.config () in
match !args with
| [ account ; amount ] ->
action config ~account ~amount ()
| _ ->
Error.raise "Usage: ft token wton withdraw ACCOUNT AMOUNT"
)
~args:
[
[], Arg.Anons ( fun list -> args := list),
EZCMD.info ~docv:"ACCOUNT AMOUNT" "The associated multisig wallet";
]
~doc: "Display token wallet info"
~man:[
]
| null | https://raw.githubusercontent.com/OCamlPro/freeton_wallet/b97877379e51d96cb3544141d386d502348cfca9/src/freeton_wallet_lib/commandTokenWTONWithdraw.ml | ocaml | ************************************************************************
All rights reserved.
This file is distributed under the terms of the GNU Lesser General
described in the LICENSE.md file in the root directory.
************************************************************************ | Copyright ( c ) 2021 OCamlPro SAS
Public License version 2.1 , with the special exception on linking
open Ezcmd.V2
open EZCMD.TYPES
open CommandTokenList.TYPES
open Types
let action config ~account ~amount () =
let ctxt = CommandTokenList.get_context config in
let account_key = Misc.find_key_exn ctxt.net account in
let account_contract = CommandMultisigCreate.check_key_contract account_key in
let account_address = Misc.get_key_address_exn account_key in
Printf.printf "%s (at %s, %s):\n%!" account
( ADDRESS.to_string account_address ) account_contract;
let amount = Misc.nanotokens_of_string amount in
let token = CommandTokenList.get_token_by_symbol ctxt "WTON" in
let wallet_address =
CommandTokenList.get_token_wallet_address ctxt token account_address in
let payload =
let abi = ctxt.wallet_contract_abi in
let meth = "transferToRecipient" in
let params =
Printf.sprintf {|{
"recipient_public_key": 0,
"recipient_address": "%s",
"tokens": "%s",
"deploy_grams": 0,
"transfer_grams": 0,
"send_gas_to": "%s",
"notify_receiver": true,
"payload": ""
}|}
( ADDRESS.to_string ctxt.vault_address )
( Int64.to_string amount )
( ADDRESS.to_string account_address )
in
Ton_sdk.ABI.encode_body ~abi ~meth ~params
in
let params = Printf.sprintf
{|{"dest":"%s","value":%Ld,"bounce":%b,"flags":%d,"payload":"%s"}|}
( ADDRESS.to_string wallet_address )
2_000_000_000L
true
0
payload
in
Utils.call_contract config
~contract:account_contract
~address:account_address
~meth:"sendTransaction"
~params
~local:false
~src:account_key
~wait:true
();
match CommandTokenList.get_token_balance_gas ctxt ~wallet_address with
| None ->
Printf.printf " %s\n%!" token.Types.MANIFEST.token_name ;
Printf.printf " address: %s\n%!" ( ADDRESS.to_string wallet_address );
Printf.printf " Broxus_TONTokenWallet contract not yet deployed\n%!";
| Some ( balance, gas ) ->
Printf.printf " %s\n%!" token.Types.MANIFEST.token_name ;
Printf.printf " address: %s\n%!" ( ADDRESS.to_string wallet_address );
Printf.printf " balance %s (gas %s TON)\n%!"
( CommandTokenList.string_of_amount_token balance token )
( Misc.string_of_nanoton gas )
let root_address = token . Types . MANIFEST.token_address in
let params = Printf.sprintf { | { " _ answer_id " : 1 ,
" wallet_public_key _ " : 0 ,
" owner_address _ " : " % s"}| }
address
in
let reply =
Utils.call_run config ~client ~wait ~server_url
~address : root_address
~abi : root_contract_abi
~meth:"getWalletAddress "
~params
~local : true
( )
in
let address = (
destruct " getWalletAddress reply " GETWALLETADDRESS.reply_enc reply
) .value0
in
let info = CommandAccountState.get_address_info config
( RawAddress address ) in
match info with
| None - >
Printf.printf " % s\n% ! " token . Types . MANIFEST.token_name ;
Printf.printf " address : % s\n% ! " address ;
Printf.printf " Broxus_TONTokenWallet contract not yet deployed\n% ! " ;
| Some acc - >
let gas =
match acc.acc_balance with
| None - > " 0 "
| Some n - > Misc.string_of_nanoton ( Z.to_int64 n )
in
Printf.printf " % s\n% ! " token . Types . MANIFEST.token_name ;
Printf.printf " address : % s\n% ! " address ;
let params = Printf.sprintf { | { " _ answer_id " : 1 } | } in
let reply =
Utils.call_run config ~client ~wait ~server_url
~address
~abi : wallet_contract_abi
"
~params
~local : true
( )
in
let balance = (
destruct " balance reply " GETWALLETADDRESS.reply_enc reply
) .value0
in
let balance = Int64.of_string balance in
Printf.printf " balance % s % s ( gas % s TON)\n% ! "
( Misc.string_of_nanoton balance )
token . Types . MANIFEST.token_symbol
gas
)
let root_address = token.Types.MANIFEST.token_address in
let params = Printf.sprintf {|{ "_answer_id": 1,
"wallet_public_key_": 0,
"owner_address_": "%s"}|}
address
in
let reply =
Utils.call_run config ~client ~wait ~server_url
~address:root_address
~abi:root_contract_abi
~meth:"getWalletAddress"
~params
~local:true
()
in
let address = (
destruct "getWalletAddress reply" GETWALLETADDRESS.reply_enc reply
).value0
in
let info = CommandAccountState.get_address_info config
(RawAddress address) in
match info with
| None ->
Printf.printf " %s\n%!" token.Types.MANIFEST.token_name ;
Printf.printf " address: %s\n%!" address;
Printf.printf " Broxus_TONTokenWallet contract not yet deployed\n%!";
| Some acc ->
let gas =
match acc.acc_balance with
| None -> "0"
| Some n -> Misc.string_of_nanoton ( Z.to_int64 n )
in
Printf.printf " %s\n%!" token.Types.MANIFEST.token_name ;
Printf.printf " address: %s\n%!" address;
let params = Printf.sprintf {|{ "_answer_id": 1 }|} in
let reply =
Utils.call_run config ~client ~wait ~server_url
~address
~abi:wallet_contract_abi
~meth:"balance"
~params
~local:true
()
in
let balance = (
destruct "balance reply" GETWALLETADDRESS.reply_enc reply
).value0
in
let balance = Int64.of_string balance in
Printf.printf " balance %s %s (gas %s TON)\n%!"
( Misc.string_of_nanoton balance )
token.Types.MANIFEST.token_symbol
gas
) manifest.Types.MANIFEST.tokens
*)
let cmd =
let args = ref [] in
Misc.cmd
["token"; "wton"; "withdraw"]
(fun () ->
let config = Config.config () in
match !args with
| [ account ; amount ] ->
action config ~account ~amount ()
| _ ->
Error.raise "Usage: ft token wton withdraw ACCOUNT AMOUNT"
)
~args:
[
[], Arg.Anons ( fun list -> args := list),
EZCMD.info ~docv:"ACCOUNT AMOUNT" "The associated multisig wallet";
]
~doc: "Display token wallet info"
~man:[
]
|
ff15f42283c476bfa78e853242e325534f2e39725b815498e150cf0da0c64922 | active-group/reacl-c | macros.clj | (ns ^:no-doc reacl-c.impl.macros)
(def ^:private dom-alist '([attrs & children] [& children]))
(defn- dom-doc [tag]
(str "Returns a dom element item corresponding to
a `" tag "` tag. The `attrs` argument is an
optional map of attributes. Any attribute
starting with `on`, is expected to be a
function taking the state and an event and return
a [[reacl-c.core/return]] value. The remaining
`children` arguments must be other items or
strings."))
(defmacro defdom [tag]
`(def ~(vary-meta tag assoc
:doc (dom-doc tag)
:arglists `'~dom-alist)
(reacl-c.dom/dom-function ~(name tag))))
| null | https://raw.githubusercontent.com/active-group/reacl-c/6acdfda3fcfcf83f4e92aa75f6a09666ccb5f8b9/src/reacl_c/impl/macros.clj | clojure | (ns ^:no-doc reacl-c.impl.macros)
(def ^:private dom-alist '([attrs & children] [& children]))
(defn- dom-doc [tag]
(str "Returns a dom element item corresponding to
a `" tag "` tag. The `attrs` argument is an
optional map of attributes. Any attribute
starting with `on`, is expected to be a
function taking the state and an event and return
a [[reacl-c.core/return]] value. The remaining
`children` arguments must be other items or
strings."))
(defmacro defdom [tag]
`(def ~(vary-meta tag assoc
:doc (dom-doc tag)
:arglists `'~dom-alist)
(reacl-c.dom/dom-function ~(name tag))))
| |
38c978da56a2af9aa8bf8f16cde779f4aa11ec1c9392bfa4c9bc8b1352c36b8d | bittide/bittide-hardware | ALU.hs | SPDX - FileCopyrightText : 2022 Google LLC
SPDX - FileCopyrightText : 2020
--
SPDX - License - Identifier : Apache-2.0
# LANGUAGE NamedFieldPuns #
# LANGUAGE TypeApplications #
# LANGUAGE CPP #
module Contranomy.Core.ALU
( alu
-- * Internal
, multdiv
, multdivSim
, multdivFormal
) where
import Clash.Prelude
import Contranomy.Clash.Extra
import Contranomy.Core.Decode
import Contranomy.Core.SharedTypes
import Contranomy.Instruction
# NOINLINE alu #
-- | The ALU implements the following instructions, or at least parts of them
--
* LUI
* AUIPC
--
* ADD / SUB / ADDI
-- * SLL/SLLI
* SLT / SLTI
-- * SLTU/SLTUI
* XOR / XORI
* SRL / SRLI
-- * SRA/SRAI
* OR / ORI
-- * AND/ANDI
--
-- It is additionally used to calculate the PC after the PC of the current instruction for:
--
* JAL
-- * JALR
--
-- And it performs the address calculation for the Load and Store instructions
--
-- * LOAD
-- * STORE
alu ::
-- | Instruction
MachineWord ->
-- | Program counter
PC ->
-- | Value of RS1
MachineWord ->
-- | Value of RS2
MachineWord ->
-- | Result
MachineWord
alu instruction pc rs1Value rs2Value
| isM = multdiv rs1Value rs2Value mop
| otherwise = aluResult
where
DecodedInstruction
{opcode, iop, srla, isSub, imm12I, imm20U, imm12S, mop, isM, compressed}
= decodeInstruction instruction
aluArg1 = case opcode of
LUI -> 0
AUIPC -> pc
JAL -> pc
JALR -> pc
_ -> rs1Value
aluArg2 = case opcode of
LUI -> imm20U ++# 0
AUIPC -> imm20U ++# 0
JAL -> iLEN
JALR -> iLEN
OP -> case aluOp of
ADD | isSub -> negate rs2Value
_ -> rs2Value
STORE -> signExtend imm12S
_ -> signExtend imm12I
iLEN = if compressed then 2 else 4
aluArg2Shamt = unpack (zeroExtend (slice d4 d0 aluArg2))
aluOp = case opcode of
OP -> iop
OP_IMM -> iop
_ -> ADD
aluResult = case aluOp of
ADD -> aluArg1 + aluArg2
SLL -> aluArg1 `shiftL` aluArg2Shamt
SLT -> boolToBitVector ((unpack aluArg1 :: Signed 32) < unpack aluArg2)
SLTU -> boolToBitVector (aluArg1 < aluArg2)
XOR -> aluArg1 `xor` aluArg2
SR -> case srla of
Logical -> aluArg1 `shiftR` aluArg2Shamt
Arithmetic -> pack ((unpack aluArg1 :: Signed 32) `shiftR` aluArg2Shamt)
OR -> aluArg1 .|. aluArg2
AND -> aluArg1 .&. aluArg2
getUnsigned :: BitVector 32 -> Unsigned 64
getUnsigned = zeroExtend . unpack @(Unsigned 32)
getSigned :: BitVector 32 -> Signed 64
getSigned = signExtend . unpack @(Signed 32)
lower :: BitVector 64 -> BitVector 32
lower = slice d31 d0
upper :: BitVector 64 -> BitVector 32
upper = slice d63 d32
multdiv :: BitVector 32 -> BitVector 32 -> MOp -> BitVector 32
#ifdef FORMAL_ALTOPS
multdiv = multdivFormal
#else
multdiv = multdivSim
#endif
-- | Alternative operations for the M Extension implemented according to
-- -formal/blob/master/docs/rvfi.md#alternative-arithmetic-operations
multdivFormal :: BitVector 32 -> BitVector 32 -> MOp -> BitVector 32
multdivFormal rs1 rs2 = \case
MUL -> xor 0x5876063e $ lower $ pack $ getSigned rs1 + getSigned rs2
MULH -> xor 0xf6583fb7 $ lower $ pack $ getSigned rs1 + getSigned rs2
MULHSU -> xor 0xecfbe137 $ lower $ pack $ getSigned rs1 - unpack (zeroExtend rs2)
MULHU -> xor 0x949ce5e8 $ lower $ pack $ getUnsigned rs1 + getUnsigned rs2
DIV -> xor 0x7f8529ec $ lower $ pack $ getSigned rs1 - getSigned rs2
DIVU -> xor 0x10e8fd70 $ lower $ pack $ getUnsigned rs1 - getUnsigned rs2
REM -> xor 0x8da68fa5 $ lower $ pack $ getSigned rs1 - getSigned rs2
REMU -> xor 0x3138d0e1 $ lower $ pack $ getUnsigned rs1 - getUnsigned rs2
multdivSim :: BitVector 32 -> BitVector 32 -> MOp -> BitVector 32
multdivSim rs1 rs2 = \case
MUL -> lower $ pack $ getSigned rs1 * getSigned rs2
MULH -> upper $ pack $ getSigned rs1 * getSigned rs2
MULHSU -> upper $ pack $ getSigned rs1 * unpack (zeroExtend rs2)
MULHU -> upper $ pack $ getUnsigned rs1 * getUnsigned rs2
DIV -> lower $ pack $ getSigned rs1 `signedQuot` getSigned rs2
DIVU -> lower $ pack $ getUnsigned rs1 `unsignedQuot` getUnsigned rs2
REM -> lower $ pack $ getSigned rs1 `signedRem` getSigned rs2
REMU -> lower $ pack $ getUnsigned rs1 `unsignedRem` getUnsigned rs2
unsignedQuot :: KnownNat n => Unsigned n -> Unsigned n -> Unsigned n
unsignedQuot _ 0 = maxBound
unsignedQuot x y = x `quot` y
unsignedRem :: KnownNat n => Unsigned n -> Unsigned n -> Unsigned n
unsignedRem x 0 = x
unsignedRem x y = x `rem` y
signedQuot :: KnownNat n => Signed n -> Signed n -> Signed n
signedQuot x y
| y == 0 = -1
| x == minBound && y == -1 = x
| otherwise = x `quot` y
signedRem :: KnownNat n => Signed n -> Signed n -> Signed n
signedRem x y
| y == 0 = x
| x == minBound && y == -1 = -1
| otherwise = x `rem` y
| null | https://raw.githubusercontent.com/bittide/bittide-hardware/b44dac8ee0fb14b0c6a94fcbe830fdd8d140bec4/contranomy/src/Contranomy/Core/ALU.hs | haskell |
* Internal
| The ALU implements the following instructions, or at least parts of them
* SLL/SLLI
* SLTU/SLTUI
* SRA/SRAI
* AND/ANDI
It is additionally used to calculate the PC after the PC of the current instruction for:
* JALR
And it performs the address calculation for the Load and Store instructions
* LOAD
* STORE
| Instruction
| Program counter
| Value of RS1
| Value of RS2
| Result
| Alternative operations for the M Extension implemented according to
-formal/blob/master/docs/rvfi.md#alternative-arithmetic-operations | SPDX - FileCopyrightText : 2022 Google LLC
SPDX - FileCopyrightText : 2020
SPDX - License - Identifier : Apache-2.0
# LANGUAGE NamedFieldPuns #
# LANGUAGE TypeApplications #
# LANGUAGE CPP #
module Contranomy.Core.ALU
( alu
, multdiv
, multdivSim
, multdivFormal
) where
import Clash.Prelude
import Contranomy.Clash.Extra
import Contranomy.Core.Decode
import Contranomy.Core.SharedTypes
import Contranomy.Instruction
# NOINLINE alu #
* LUI
* AUIPC
* ADD / SUB / ADDI
* SLT / SLTI
* XOR / XORI
* SRL / SRLI
* OR / ORI
* JAL
alu ::
MachineWord ->
PC ->
MachineWord ->
MachineWord ->
MachineWord
alu instruction pc rs1Value rs2Value
| isM = multdiv rs1Value rs2Value mop
| otherwise = aluResult
where
DecodedInstruction
{opcode, iop, srla, isSub, imm12I, imm20U, imm12S, mop, isM, compressed}
= decodeInstruction instruction
aluArg1 = case opcode of
LUI -> 0
AUIPC -> pc
JAL -> pc
JALR -> pc
_ -> rs1Value
aluArg2 = case opcode of
LUI -> imm20U ++# 0
AUIPC -> imm20U ++# 0
JAL -> iLEN
JALR -> iLEN
OP -> case aluOp of
ADD | isSub -> negate rs2Value
_ -> rs2Value
STORE -> signExtend imm12S
_ -> signExtend imm12I
iLEN = if compressed then 2 else 4
aluArg2Shamt = unpack (zeroExtend (slice d4 d0 aluArg2))
aluOp = case opcode of
OP -> iop
OP_IMM -> iop
_ -> ADD
aluResult = case aluOp of
ADD -> aluArg1 + aluArg2
SLL -> aluArg1 `shiftL` aluArg2Shamt
SLT -> boolToBitVector ((unpack aluArg1 :: Signed 32) < unpack aluArg2)
SLTU -> boolToBitVector (aluArg1 < aluArg2)
XOR -> aluArg1 `xor` aluArg2
SR -> case srla of
Logical -> aluArg1 `shiftR` aluArg2Shamt
Arithmetic -> pack ((unpack aluArg1 :: Signed 32) `shiftR` aluArg2Shamt)
OR -> aluArg1 .|. aluArg2
AND -> aluArg1 .&. aluArg2
getUnsigned :: BitVector 32 -> Unsigned 64
getUnsigned = zeroExtend . unpack @(Unsigned 32)
getSigned :: BitVector 32 -> Signed 64
getSigned = signExtend . unpack @(Signed 32)
lower :: BitVector 64 -> BitVector 32
lower = slice d31 d0
upper :: BitVector 64 -> BitVector 32
upper = slice d63 d32
multdiv :: BitVector 32 -> BitVector 32 -> MOp -> BitVector 32
#ifdef FORMAL_ALTOPS
multdiv = multdivFormal
#else
multdiv = multdivSim
#endif
multdivFormal :: BitVector 32 -> BitVector 32 -> MOp -> BitVector 32
multdivFormal rs1 rs2 = \case
MUL -> xor 0x5876063e $ lower $ pack $ getSigned rs1 + getSigned rs2
MULH -> xor 0xf6583fb7 $ lower $ pack $ getSigned rs1 + getSigned rs2
MULHSU -> xor 0xecfbe137 $ lower $ pack $ getSigned rs1 - unpack (zeroExtend rs2)
MULHU -> xor 0x949ce5e8 $ lower $ pack $ getUnsigned rs1 + getUnsigned rs2
DIV -> xor 0x7f8529ec $ lower $ pack $ getSigned rs1 - getSigned rs2
DIVU -> xor 0x10e8fd70 $ lower $ pack $ getUnsigned rs1 - getUnsigned rs2
REM -> xor 0x8da68fa5 $ lower $ pack $ getSigned rs1 - getSigned rs2
REMU -> xor 0x3138d0e1 $ lower $ pack $ getUnsigned rs1 - getUnsigned rs2
multdivSim :: BitVector 32 -> BitVector 32 -> MOp -> BitVector 32
multdivSim rs1 rs2 = \case
MUL -> lower $ pack $ getSigned rs1 * getSigned rs2
MULH -> upper $ pack $ getSigned rs1 * getSigned rs2
MULHSU -> upper $ pack $ getSigned rs1 * unpack (zeroExtend rs2)
MULHU -> upper $ pack $ getUnsigned rs1 * getUnsigned rs2
DIV -> lower $ pack $ getSigned rs1 `signedQuot` getSigned rs2
DIVU -> lower $ pack $ getUnsigned rs1 `unsignedQuot` getUnsigned rs2
REM -> lower $ pack $ getSigned rs1 `signedRem` getSigned rs2
REMU -> lower $ pack $ getUnsigned rs1 `unsignedRem` getUnsigned rs2
unsignedQuot :: KnownNat n => Unsigned n -> Unsigned n -> Unsigned n
unsignedQuot _ 0 = maxBound
unsignedQuot x y = x `quot` y
unsignedRem :: KnownNat n => Unsigned n -> Unsigned n -> Unsigned n
unsignedRem x 0 = x
unsignedRem x y = x `rem` y
signedQuot :: KnownNat n => Signed n -> Signed n -> Signed n
signedQuot x y
| y == 0 = -1
| x == minBound && y == -1 = x
| otherwise = x `quot` y
signedRem :: KnownNat n => Signed n -> Signed n -> Signed n
signedRem x y
| y == 0 = x
| x == minBound && y == -1 = -1
| otherwise = x `rem` y
|
798d12d911517799344eb5e2112678d196155812c0058ce823e51848ed513896 | FreeProving/free-compiler | SimilarTests.hs | | This module contains tests for " " .
module FreeC.IR.SimilarTests ( testSimilar ) where
import Test.Hspec
import FreeC.Test.Expectations
import FreeC.Test.Parser
-- | Test group for 'FreeC.IR.Similar.similar' tests.
testSimilar :: Spec
testSimilar = describe "FreeC.IR.Similar" $ do
testSimilarTypes
testSimilarExprs
testSimilarFuncDecls
testSimilarTypeDecls
| Test group for ' . Similar ' instance of type schemes and
-- type expressions.
testSimilarTypes :: Spec
testSimilarTypes = context "types" $ do
it "type constructors are similar to themselves" $ do
foo <- expectParseTestType "Foo"
foo `shouldBeSimilarTo` foo
it "type constructors are not similar to other type constructors" $ do
foo <- expectParseTestType "Foo"
bar <- expectParseTestType "Bar"
foo `shouldNotBeSimilarTo` bar
it "type constructors are not similar to type variables" $ do
foo <- expectParseTestType "Foo"
a <- expectParseTestType "a"
foo `shouldNotBeSimilarTo` a
it "free type variables are similar to themselves" $ do
a <- expectParseTestType "a"
a `shouldBeSimilarTo` a
it "free type variables are not similar to other free type variables" $ do
a <- expectParseTestType "a"
b <- expectParseTestType "b"
a `shouldNotBeSimilarTo` b
it "bound type variables are similar to similarly bound type variables" $ do
a <- expectParseTestTypeScheme "forall a. a"
b <- expectParseTestTypeScheme "forall b. b"
a `shouldBeSimilarTo` b
it "bound type variables are not similar to unrelated bound type variables"
$ do
ab <- expectParseTestTypeScheme "forall a b. Foo a b"
ba <- expectParseTestTypeScheme "forall b a. Foo a b"
ab `shouldNotBeSimilarTo` ba
it "bound type variables are not similar to right free type variables" $ do
a <- expectParseTestTypeScheme "forall a. a"
a' <- expectParseTestTypeScheme "forall b. a"
a `shouldNotBeSimilarTo` a'
it "bound type variables are not similar to left free type variables" $ do
a <- expectParseTestTypeScheme "forall b. a"
a' <- expectParseTestTypeScheme "forall a. a"
a `shouldNotBeSimilarTo` a'
it "type applications with similar children are similar" $ do
fooA <- expectParseTestTypeScheme "forall a. Foo a"
fooB <- expectParseTestTypeScheme "forall b. Foo b"
fooA `shouldBeSimilarTo` fooB
it "type applications with dissimilar left-hand sides are dissimilar" $ do
fooA <- expectParseTestTypeScheme "forall a. Foo a"
barB <- expectParseTestTypeScheme "forall b. Bar b"
fooA `shouldNotBeSimilarTo` barB
it "type applications with dissimilar right-hand sides are dissimilar" $ do
fooA <- expectParseTestTypeScheme "forall a b. Foo a"
fooA' <- expectParseTestTypeScheme "forall b a. Foo a"
fooA `shouldNotBeSimilarTo` fooA'
it "function types with similar children are similar" $ do
f <- expectParseTestTypeScheme "forall a b. a -> b"
g <- expectParseTestTypeScheme "forall c d. c -> d"
f `shouldBeSimilarTo` g
it "function types with dissimilar right-hand sides are dissimilar" $ do
f <- expectParseTestTypeScheme "forall a. a -> Foo"
g <- expectParseTestTypeScheme "forall a. a -> Bar"
f `shouldNotBeSimilarTo` g
it "function types with dissimilar left-hand sides are dissimilar" $ do
f <- expectParseTestTypeScheme "forall a. Foo -> a"
g <- expectParseTestTypeScheme "forall a. Bar -> a"
f `shouldNotBeSimilarTo` g
| Test group for ' . Similar ' instance of expressions .
testSimilarExprs :: Spec
testSimilarExprs = context "expressions" $ do
it "constructors are similar to themselves" $ do
foo <- expectParseTestExpr "Foo"
foo `shouldBeSimilarTo` foo
it "constructors are not similar to other constructors" $ do
foo <- expectParseTestExpr "Foo"
bar <- expectParseTestExpr "Bar"
foo `shouldNotBeSimilarTo` bar
it "constructors are not similar to variables" $ do
foo <- expectParseTestExpr "Foo"
a <- expectParseTestExpr "a"
foo `shouldNotBeSimilarTo` a
it "integer literals are similar to themselves" $ do
int <- expectParseTestExpr "42"
int `shouldBeSimilarTo` int
it "integer literals are not similar to other integer literals" $ do
int1 <- expectParseTestExpr "42"
int2 <- expectParseTestExpr "1337"
int1 `shouldNotBeSimilarTo` int2
it "effect 'undefined' is similar to itself" $ do
e <- expectParseTestExpr "undefined"
e `shouldBeSimilarTo` e
it "effect 'error \"...\"' is similar to itself" $ do
e <- expectParseTestExpr "error \"...\""
e `shouldBeSimilarTo` e
it "error term is not similar to error term with different message" $ do
e1 <- expectParseTestExpr "error \"Hello\""
e2 <- expectParseTestExpr "error \"World\""
e1 `shouldNotBeSimilarTo` e2
it "effect 'trace \"...\"' is similar to itself" $ do
e <- expectParseTestExpr "trace \"...\" x"
e `shouldBeSimilarTo` e
it ("traced expression is not similar to traced expression term with"
++ "different message")
$ do
e1 <- expectParseTestExpr "trace \"Hello\" x"
e2 <- expectParseTestExpr "trace \"World\" x"
e1 `shouldNotBeSimilarTo` e2
it "free variables are similar to themselves" $ do
f <- expectParseTestExpr "f"
f `shouldBeSimilarTo` f
it "free variables are not similar to other free type variables" $ do
f <- expectParseTestExpr "f"
g <- expectParseTestExpr "g"
f `shouldNotBeSimilarTo` g
it "bound variables are similar to similarly bound variables" $ do
e1 <- expectParseTestExpr "\\x -> x"
e2 <- expectParseTestExpr "\\y -> y"
e1 `shouldBeSimilarTo` e2
it "bound variables are not similar to unrelated bound variables" $ do
e1 <- expectParseTestExpr "\\x y -> x"
e2 <- expectParseTestExpr "\\y x -> x"
e1 `shouldNotBeSimilarTo` e2
it "bound variables are not similar to right free bound variables" $ do
e1 <- expectParseTestExpr "\\x -> x"
e2 <- expectParseTestExpr "\\y -> x"
e1 `shouldNotBeSimilarTo` e2
it "bound variables are not similar to left free bound variables" $ do
e1 <- expectParseTestExpr "\\y -> x"
e2 <- expectParseTestExpr "\\x -> x"
e1 `shouldNotBeSimilarTo` e2
it "expressions with dissimilar type annotation are not similar" $ do
e1 <- expectParseTestExpr "x :: Foo"
e2 <- expectParseTestExpr "x :: Bar"
e1 `shouldNotBeSimilarTo` e2
it "expressions with and without type annotation are not similar" $ do
e1 <- expectParseTestExpr "x :: a"
e2 <- expectParseTestExpr "x"
e1 `shouldNotBeSimilarTo` e2
it "lambda abstractions with different arity are not similar" $ do
e1 <- expectParseTestExpr "\\x y -> x"
e2 <- expectParseTestExpr "\\x -> x"
e1 `shouldNotBeSimilarTo` e2
it "lambda abstractions with dissimilar argument annotations are not similar"
$ do
e1 <- expectParseTestExpr "\\(x :: Foo) -> x"
e2 <- expectParseTestExpr "\\(x :: Bar) -> x"
e1 `shouldNotBeSimilarTo` e2
it ("lambda abstractions with and without argument annotations are not "
++ "similar")
$ do
e1 <- expectParseTestExpr "\\(x :: Foo) -> x"
e2 <- expectParseTestExpr "\\x -> x"
e1 `shouldNotBeSimilarTo` e2
it "applications with similar children are similar" $ do
fooX <- expectParseTestExpr "\\x -> Foo x"
fooY <- expectParseTestExpr "\\y -> Foo y"
fooX `shouldBeSimilarTo` fooY
it "applications with dissimilar left-hand sides are dissimilar" $ do
fooX <- expectParseTestExpr "\\x -> Foo x"
barY <- expectParseTestExpr "\\y -> Bar y"
fooX `shouldNotBeSimilarTo` barY
it "applications with dissimilar right-hand sides are dissimilar" $ do
fooX <- expectParseTestExpr "\\x y -> Foo x"
fooX' <- expectParseTestExpr "\\y a -> Foo a"
fooX `shouldNotBeSimilarTo` fooX'
it "visible applications of dissimilar types are not similar" $ do
fa <- expectParseTestExpr "f @a"
fb <- expectParseTestExpr "f @b"
fa `shouldNotBeSimilarTo` fb
it "if expressions with similar children are similar" $ do
e1 <- expectParseTestExpr "\\x y z -> if x then y else z"
e2 <- expectParseTestExpr "\\c t f -> if c then t else f"
e1 `shouldBeSimilarTo` e2
it "if expressions with dissimilar conditions are not similar" $ do
e1 <- expectParseTestExpr "\\y z -> if True then y else z"
e2 <- expectParseTestExpr "\\t f -> if False then t else f"
e1 `shouldNotBeSimilarTo` e2
it "if expressions with dissimilar then branches are not similar" $ do
e1 <- expectParseTestExpr "\\x z -> if x then Foo else z"
e2 <- expectParseTestExpr "\\c f -> if c then Bar else f"
e1 `shouldNotBeSimilarTo` e2
it "if expressions with dissimilar else branches are not similar" $ do
e1 <- expectParseTestExpr "\\x y -> if x then y else Foo"
e2 <- expectParseTestExpr "\\c t -> if c then t else Bar"
e1 `shouldNotBeSimilarTo` e2
it "case expressions with similar children are similar" $ do
e1 <- expectParseTestExpr "\\xs -> case xs of { ([]) -> 0; (:) x xs' -> x }"
e2 <- expectParseTestExpr "\\ys -> case ys of { ([]) -> 0; (:) y ys' -> y }"
e1 `shouldBeSimilarTo` e2
it "case expressions with dissimilar scrutinees are not similar" $ do
e1 <- expectParseTestExpr "case xs of { ([]) -> 0; (:) x xs' -> x }"
e2 <- expectParseTestExpr "case ys of { ([]) -> 0; (:) y ys' -> y }"
e1 `shouldNotBeSimilarTo` e2
it "case expressions with unordered alternatives are not similar" $ do
e1 <- expectParseTestExpr "\\xs -> case xs of { (:) x xs' -> x; ([]) -> 0 }"
e2 <- expectParseTestExpr "\\ys -> case ys of { ([]) -> 0; (:) y ys' -> y }"
e1 `shouldNotBeSimilarTo` e2
it "case expressions with dissimilar alternatives are not similar" $ do
e1 <- expectParseTestExpr "\\xs -> case xs of { ([]) -> 0; (:) x xs' -> x }"
e2 <- expectParseTestExpr "\\ys -> case ys of { ([]) -> 1; (:) y ys' -> y }"
e1 `shouldNotBeSimilarTo` e2
it "case expressions with different number of alternatives are not similar"
$ do
e1 <- expectParseTestExpr "case xy of { (,) x y -> x }"
e2 <- expectParseTestExpr "case xy of { }"
e1 `shouldNotBeSimilarTo` e2
it "alternatives with different constructor patterns are not similar" $ do
e1 <- expectParseTestExpr "\\xs -> case xs of { ([]) -> 0; (:) x xs' -> x }"
e2 <- expectParseTestExpr "\\ys -> case ys of { Nil -> 0; Cons y ys' -> y }"
e1 `shouldNotBeSimilarTo` e2
it "alternatives with dissimilar variable type annotations are not similar"
$ do
e1 <- expectParseTestExpr "case xy of { (,) (x :: Foo) y -> x }"
e2 <- expectParseTestExpr "case xy of { (,) (x :: Bar) y -> x }"
e1 `shouldNotBeSimilarTo` e2
it "alternatives with different number of variable patterns are not similar"
$ do
e1 <- expectParseTestExpr "case xy of { (,) (x :: Foo) y -> x }"
e2 <- expectParseTestExpr "case xy of { (,) (x :: Bar) y -> x }"
e1 `shouldNotBeSimilarTo` e2
| Test group for ' . Similar ' instance of function
-- declarations.
testSimilarFuncDecls :: Spec
testSimilarFuncDecls = context "function declarations" $ do
it "nullary functions are similar" $ do
f1 <- expectParseTestFuncDecl "f = ()"
f2 <- expectParseTestFuncDecl "f = ()"
f1 `shouldBeSimilarTo` f2
it "functions with different names are not similar" $ do
f <- expectParseTestFuncDecl "f = ()"
g <- expectParseTestFuncDecl "g = ()"
f `shouldNotBeSimilarTo` g
it "functions with similar right-hand side are similar" $ do
fx <- expectParseTestFuncDecl "f x = x"
fy <- expectParseTestFuncDecl "f y = y"
fx `shouldBeSimilarTo` fy
it "functions with dissimilar right-hand side are not similar" $ do
fx <- expectParseTestFuncDecl "f x y = x"
fy <- expectParseTestFuncDecl "f y x = x"
fx `shouldNotBeSimilarTo` fy
it "functions with dissimilar argument type annotations are not similar" $ do
fx <- expectParseTestFuncDecl "f (x :: Foo) = x"
fy <- expectParseTestFuncDecl "f (y :: Bar) = y"
fx `shouldNotBeSimilarTo` fy
it "functions with and without argument type annotations are not similar" $ do
fx <- expectParseTestFuncDecl "f (x :: Foo) = x"
fy <- expectParseTestFuncDecl "f y = y"
fx `shouldNotBeSimilarTo` fy
it "functions with strict and non-strict arguments are not similar" $ do
fx <- expectParseTestFuncDecl "f !x = x"
fy <- expectParseTestFuncDecl "f y = y"
fx `shouldNotBeSimilarTo` fy
it "functions with and without return type annotations are not similar" $ do
fx <- expectParseTestFuncDecl "f x :: Foo = x"
fy <- expectParseTestFuncDecl "f y = y"
fx `shouldNotBeSimilarTo` fy
it "functions with different arities are not similar" $ do
fxz <- expectParseTestFuncDecl "f x z = x"
fy <- expectParseTestFuncDecl "f y = y"
fxz `shouldNotBeSimilarTo` fy
it "type arguments bind type variables in argument type annotations" $ do
fab <- expectParseTestFuncDecl "f @a (x :: a) = x"
fb <- expectParseTestFuncDecl "f @b (x :: b) = x"
fab `shouldBeSimilarTo` fb
it "type arguments bind type variables in return type annotations" $ do
fa <- expectParseTestFuncDecl "f @a :: a = undefined"
fb <- expectParseTestFuncDecl "f @b :: b = undefined"
fa `shouldBeSimilarTo` fb
it "type arguments bind type variables in on right-hand side" $ do
fa <- expectParseTestFuncDecl "f @a = undefined @a"
fb <- expectParseTestFuncDecl "f @b = undefined @b"
fa `shouldBeSimilarTo` fb
it "functions with different type arities are not similar" $ do
fa <- expectParseTestFuncDecl "f @a @b = undefined"
fb <- expectParseTestFuncDecl "f @a = undefined"
fa `shouldNotBeSimilarTo` fb
| Test group for ' . Similar ' instance of type - level
-- declarations.
testSimilarTypeDecls :: Spec
testSimilarTypeDecls = do
context "type synonym declarations" $ do
it "nullary type synonyms are similar" $ do
foo1 <- expectParseTestTypeDecl "type Foo = ()"
foo2 <- expectParseTestTypeDecl "type Foo = ()"
foo1 `shouldBeSimilarTo` foo2
it "type synonyms with different names are not similar" $ do
foo <- expectParseTestTypeDecl "type Foo = ()"
bar <- expectParseTestTypeDecl "type Bar = ()"
foo `shouldNotBeSimilarTo` bar
it "type synonyms with similar right-hand side are similar" $ do
foo1 <- expectParseTestTypeDecl "type Foo a = Bar a"
foo2 <- expectParseTestTypeDecl "type Foo b = Bar b"
foo1 `shouldBeSimilarTo` foo2
it "type synonyms with dissimilar right-hand side are not similar" $ do
foo1 <- expectParseTestTypeDecl "type Foo a b = Bar a"
foo2 <- expectParseTestTypeDecl "type Foo b a = Bar a"
foo1 `shouldNotBeSimilarTo` foo2
it "type synonyms with different number of type arguments are not similar"
$ do
foo1 <- expectParseTestTypeDecl "type Foo a = Bar a"
foo2 <- expectParseTestTypeDecl "type Foo a b = Bar a"
foo1 `shouldNotBeSimilarTo` foo2
context "data type declarations" $ do
it "nullary data types are similar to themselves" $ do
foo <- expectParseTestTypeDecl "data Foo"
foo `shouldBeSimilarTo` foo
it "data types with different names are not similar" $ do
foo <- expectParseTestTypeDecl "data Foo"
bar <- expectParseTestTypeDecl "data Bar"
foo `shouldNotBeSimilarTo` bar
it "data types with similar constructors are similar" $ do
foo1 <- expectParseTestTypeDecl "data Foo a = Bar a"
foo2 <- expectParseTestTypeDecl "data Foo b = Bar b"
foo1 `shouldBeSimilarTo` foo2
it "data types with dissimilar constructors are not similar" $ do
foo1 <- expectParseTestTypeDecl "data Foo a b = Bar a"
foo2 <- expectParseTestTypeDecl "data Foo b a = Bar a"
foo1 `shouldNotBeSimilarTo` foo2
it "data types with different number of type arguments are not similar" $ do
foo1 <- expectParseTestTypeDecl "data Foo a"
foo2 <- expectParseTestTypeDecl "data Foo a b"
foo1 `shouldNotBeSimilarTo` foo2
it "data types with unordered constructors are not similar" $ do
foo1 <- expectParseTestTypeDecl "data Foo = Foo | Bar"
foo2 <- expectParseTestTypeDecl "data Foo = Bar | Foo"
foo1 `shouldNotBeSimilarTo` foo2
it "constructors with different names are not similar" $ do
fooFoo <- expectParseTestTypeDecl "data Foo = Foo"
fooBar <- expectParseTestTypeDecl "data Foo = Bar"
fooFoo `shouldNotBeSimilarTo` fooBar
it "constructors with different number of fields are not similar" $ do
foo1 <- expectParseTestTypeDecl "data Foo a = Foo a"
foo2 <- expectParseTestTypeDecl "data Foo a = Foo a a"
foo1 `shouldNotBeSimilarTo` foo2
| null | https://raw.githubusercontent.com/FreeProving/free-compiler/6931b9ca652a185a92dd824373f092823aea4ea9/src/test/FreeC/IR/SimilarTests.hs | haskell | | Test group for 'FreeC.IR.Similar.similar' tests.
type expressions.
declarations.
declarations. | | This module contains tests for " " .
module FreeC.IR.SimilarTests ( testSimilar ) where
import Test.Hspec
import FreeC.Test.Expectations
import FreeC.Test.Parser
testSimilar :: Spec
testSimilar = describe "FreeC.IR.Similar" $ do
testSimilarTypes
testSimilarExprs
testSimilarFuncDecls
testSimilarTypeDecls
| Test group for ' . Similar ' instance of type schemes and
testSimilarTypes :: Spec
testSimilarTypes = context "types" $ do
it "type constructors are similar to themselves" $ do
foo <- expectParseTestType "Foo"
foo `shouldBeSimilarTo` foo
it "type constructors are not similar to other type constructors" $ do
foo <- expectParseTestType "Foo"
bar <- expectParseTestType "Bar"
foo `shouldNotBeSimilarTo` bar
it "type constructors are not similar to type variables" $ do
foo <- expectParseTestType "Foo"
a <- expectParseTestType "a"
foo `shouldNotBeSimilarTo` a
it "free type variables are similar to themselves" $ do
a <- expectParseTestType "a"
a `shouldBeSimilarTo` a
it "free type variables are not similar to other free type variables" $ do
a <- expectParseTestType "a"
b <- expectParseTestType "b"
a `shouldNotBeSimilarTo` b
it "bound type variables are similar to similarly bound type variables" $ do
a <- expectParseTestTypeScheme "forall a. a"
b <- expectParseTestTypeScheme "forall b. b"
a `shouldBeSimilarTo` b
it "bound type variables are not similar to unrelated bound type variables"
$ do
ab <- expectParseTestTypeScheme "forall a b. Foo a b"
ba <- expectParseTestTypeScheme "forall b a. Foo a b"
ab `shouldNotBeSimilarTo` ba
it "bound type variables are not similar to right free type variables" $ do
a <- expectParseTestTypeScheme "forall a. a"
a' <- expectParseTestTypeScheme "forall b. a"
a `shouldNotBeSimilarTo` a'
it "bound type variables are not similar to left free type variables" $ do
a <- expectParseTestTypeScheme "forall b. a"
a' <- expectParseTestTypeScheme "forall a. a"
a `shouldNotBeSimilarTo` a'
it "type applications with similar children are similar" $ do
fooA <- expectParseTestTypeScheme "forall a. Foo a"
fooB <- expectParseTestTypeScheme "forall b. Foo b"
fooA `shouldBeSimilarTo` fooB
it "type applications with dissimilar left-hand sides are dissimilar" $ do
fooA <- expectParseTestTypeScheme "forall a. Foo a"
barB <- expectParseTestTypeScheme "forall b. Bar b"
fooA `shouldNotBeSimilarTo` barB
it "type applications with dissimilar right-hand sides are dissimilar" $ do
fooA <- expectParseTestTypeScheme "forall a b. Foo a"
fooA' <- expectParseTestTypeScheme "forall b a. Foo a"
fooA `shouldNotBeSimilarTo` fooA'
it "function types with similar children are similar" $ do
f <- expectParseTestTypeScheme "forall a b. a -> b"
g <- expectParseTestTypeScheme "forall c d. c -> d"
f `shouldBeSimilarTo` g
it "function types with dissimilar right-hand sides are dissimilar" $ do
f <- expectParseTestTypeScheme "forall a. a -> Foo"
g <- expectParseTestTypeScheme "forall a. a -> Bar"
f `shouldNotBeSimilarTo` g
it "function types with dissimilar left-hand sides are dissimilar" $ do
f <- expectParseTestTypeScheme "forall a. Foo -> a"
g <- expectParseTestTypeScheme "forall a. Bar -> a"
f `shouldNotBeSimilarTo` g
| Test group for ' . Similar ' instance of expressions .
testSimilarExprs :: Spec
testSimilarExprs = context "expressions" $ do
it "constructors are similar to themselves" $ do
foo <- expectParseTestExpr "Foo"
foo `shouldBeSimilarTo` foo
it "constructors are not similar to other constructors" $ do
foo <- expectParseTestExpr "Foo"
bar <- expectParseTestExpr "Bar"
foo `shouldNotBeSimilarTo` bar
it "constructors are not similar to variables" $ do
foo <- expectParseTestExpr "Foo"
a <- expectParseTestExpr "a"
foo `shouldNotBeSimilarTo` a
it "integer literals are similar to themselves" $ do
int <- expectParseTestExpr "42"
int `shouldBeSimilarTo` int
it "integer literals are not similar to other integer literals" $ do
int1 <- expectParseTestExpr "42"
int2 <- expectParseTestExpr "1337"
int1 `shouldNotBeSimilarTo` int2
it "effect 'undefined' is similar to itself" $ do
e <- expectParseTestExpr "undefined"
e `shouldBeSimilarTo` e
it "effect 'error \"...\"' is similar to itself" $ do
e <- expectParseTestExpr "error \"...\""
e `shouldBeSimilarTo` e
it "error term is not similar to error term with different message" $ do
e1 <- expectParseTestExpr "error \"Hello\""
e2 <- expectParseTestExpr "error \"World\""
e1 `shouldNotBeSimilarTo` e2
it "effect 'trace \"...\"' is similar to itself" $ do
e <- expectParseTestExpr "trace \"...\" x"
e `shouldBeSimilarTo` e
it ("traced expression is not similar to traced expression term with"
++ "different message")
$ do
e1 <- expectParseTestExpr "trace \"Hello\" x"
e2 <- expectParseTestExpr "trace \"World\" x"
e1 `shouldNotBeSimilarTo` e2
it "free variables are similar to themselves" $ do
f <- expectParseTestExpr "f"
f `shouldBeSimilarTo` f
it "free variables are not similar to other free type variables" $ do
f <- expectParseTestExpr "f"
g <- expectParseTestExpr "g"
f `shouldNotBeSimilarTo` g
it "bound variables are similar to similarly bound variables" $ do
e1 <- expectParseTestExpr "\\x -> x"
e2 <- expectParseTestExpr "\\y -> y"
e1 `shouldBeSimilarTo` e2
it "bound variables are not similar to unrelated bound variables" $ do
e1 <- expectParseTestExpr "\\x y -> x"
e2 <- expectParseTestExpr "\\y x -> x"
e1 `shouldNotBeSimilarTo` e2
it "bound variables are not similar to right free bound variables" $ do
e1 <- expectParseTestExpr "\\x -> x"
e2 <- expectParseTestExpr "\\y -> x"
e1 `shouldNotBeSimilarTo` e2
it "bound variables are not similar to left free bound variables" $ do
e1 <- expectParseTestExpr "\\y -> x"
e2 <- expectParseTestExpr "\\x -> x"
e1 `shouldNotBeSimilarTo` e2
it "expressions with dissimilar type annotation are not similar" $ do
e1 <- expectParseTestExpr "x :: Foo"
e2 <- expectParseTestExpr "x :: Bar"
e1 `shouldNotBeSimilarTo` e2
it "expressions with and without type annotation are not similar" $ do
e1 <- expectParseTestExpr "x :: a"
e2 <- expectParseTestExpr "x"
e1 `shouldNotBeSimilarTo` e2
it "lambda abstractions with different arity are not similar" $ do
e1 <- expectParseTestExpr "\\x y -> x"
e2 <- expectParseTestExpr "\\x -> x"
e1 `shouldNotBeSimilarTo` e2
it "lambda abstractions with dissimilar argument annotations are not similar"
$ do
e1 <- expectParseTestExpr "\\(x :: Foo) -> x"
e2 <- expectParseTestExpr "\\(x :: Bar) -> x"
e1 `shouldNotBeSimilarTo` e2
it ("lambda abstractions with and without argument annotations are not "
++ "similar")
$ do
e1 <- expectParseTestExpr "\\(x :: Foo) -> x"
e2 <- expectParseTestExpr "\\x -> x"
e1 `shouldNotBeSimilarTo` e2
it "applications with similar children are similar" $ do
fooX <- expectParseTestExpr "\\x -> Foo x"
fooY <- expectParseTestExpr "\\y -> Foo y"
fooX `shouldBeSimilarTo` fooY
it "applications with dissimilar left-hand sides are dissimilar" $ do
fooX <- expectParseTestExpr "\\x -> Foo x"
barY <- expectParseTestExpr "\\y -> Bar y"
fooX `shouldNotBeSimilarTo` barY
it "applications with dissimilar right-hand sides are dissimilar" $ do
fooX <- expectParseTestExpr "\\x y -> Foo x"
fooX' <- expectParseTestExpr "\\y a -> Foo a"
fooX `shouldNotBeSimilarTo` fooX'
it "visible applications of dissimilar types are not similar" $ do
fa <- expectParseTestExpr "f @a"
fb <- expectParseTestExpr "f @b"
fa `shouldNotBeSimilarTo` fb
it "if expressions with similar children are similar" $ do
e1 <- expectParseTestExpr "\\x y z -> if x then y else z"
e2 <- expectParseTestExpr "\\c t f -> if c then t else f"
e1 `shouldBeSimilarTo` e2
it "if expressions with dissimilar conditions are not similar" $ do
e1 <- expectParseTestExpr "\\y z -> if True then y else z"
e2 <- expectParseTestExpr "\\t f -> if False then t else f"
e1 `shouldNotBeSimilarTo` e2
it "if expressions with dissimilar then branches are not similar" $ do
e1 <- expectParseTestExpr "\\x z -> if x then Foo else z"
e2 <- expectParseTestExpr "\\c f -> if c then Bar else f"
e1 `shouldNotBeSimilarTo` e2
it "if expressions with dissimilar else branches are not similar" $ do
e1 <- expectParseTestExpr "\\x y -> if x then y else Foo"
e2 <- expectParseTestExpr "\\c t -> if c then t else Bar"
e1 `shouldNotBeSimilarTo` e2
it "case expressions with similar children are similar" $ do
e1 <- expectParseTestExpr "\\xs -> case xs of { ([]) -> 0; (:) x xs' -> x }"
e2 <- expectParseTestExpr "\\ys -> case ys of { ([]) -> 0; (:) y ys' -> y }"
e1 `shouldBeSimilarTo` e2
it "case expressions with dissimilar scrutinees are not similar" $ do
e1 <- expectParseTestExpr "case xs of { ([]) -> 0; (:) x xs' -> x }"
e2 <- expectParseTestExpr "case ys of { ([]) -> 0; (:) y ys' -> y }"
e1 `shouldNotBeSimilarTo` e2
it "case expressions with unordered alternatives are not similar" $ do
e1 <- expectParseTestExpr "\\xs -> case xs of { (:) x xs' -> x; ([]) -> 0 }"
e2 <- expectParseTestExpr "\\ys -> case ys of { ([]) -> 0; (:) y ys' -> y }"
e1 `shouldNotBeSimilarTo` e2
it "case expressions with dissimilar alternatives are not similar" $ do
e1 <- expectParseTestExpr "\\xs -> case xs of { ([]) -> 0; (:) x xs' -> x }"
e2 <- expectParseTestExpr "\\ys -> case ys of { ([]) -> 1; (:) y ys' -> y }"
e1 `shouldNotBeSimilarTo` e2
it "case expressions with different number of alternatives are not similar"
$ do
e1 <- expectParseTestExpr "case xy of { (,) x y -> x }"
e2 <- expectParseTestExpr "case xy of { }"
e1 `shouldNotBeSimilarTo` e2
it "alternatives with different constructor patterns are not similar" $ do
e1 <- expectParseTestExpr "\\xs -> case xs of { ([]) -> 0; (:) x xs' -> x }"
e2 <- expectParseTestExpr "\\ys -> case ys of { Nil -> 0; Cons y ys' -> y }"
e1 `shouldNotBeSimilarTo` e2
it "alternatives with dissimilar variable type annotations are not similar"
$ do
e1 <- expectParseTestExpr "case xy of { (,) (x :: Foo) y -> x }"
e2 <- expectParseTestExpr "case xy of { (,) (x :: Bar) y -> x }"
e1 `shouldNotBeSimilarTo` e2
it "alternatives with different number of variable patterns are not similar"
$ do
e1 <- expectParseTestExpr "case xy of { (,) (x :: Foo) y -> x }"
e2 <- expectParseTestExpr "case xy of { (,) (x :: Bar) y -> x }"
e1 `shouldNotBeSimilarTo` e2
| Test group for ' . Similar ' instance of function
testSimilarFuncDecls :: Spec
testSimilarFuncDecls = context "function declarations" $ do
it "nullary functions are similar" $ do
f1 <- expectParseTestFuncDecl "f = ()"
f2 <- expectParseTestFuncDecl "f = ()"
f1 `shouldBeSimilarTo` f2
it "functions with different names are not similar" $ do
f <- expectParseTestFuncDecl "f = ()"
g <- expectParseTestFuncDecl "g = ()"
f `shouldNotBeSimilarTo` g
it "functions with similar right-hand side are similar" $ do
fx <- expectParseTestFuncDecl "f x = x"
fy <- expectParseTestFuncDecl "f y = y"
fx `shouldBeSimilarTo` fy
it "functions with dissimilar right-hand side are not similar" $ do
fx <- expectParseTestFuncDecl "f x y = x"
fy <- expectParseTestFuncDecl "f y x = x"
fx `shouldNotBeSimilarTo` fy
it "functions with dissimilar argument type annotations are not similar" $ do
fx <- expectParseTestFuncDecl "f (x :: Foo) = x"
fy <- expectParseTestFuncDecl "f (y :: Bar) = y"
fx `shouldNotBeSimilarTo` fy
it "functions with and without argument type annotations are not similar" $ do
fx <- expectParseTestFuncDecl "f (x :: Foo) = x"
fy <- expectParseTestFuncDecl "f y = y"
fx `shouldNotBeSimilarTo` fy
it "functions with strict and non-strict arguments are not similar" $ do
fx <- expectParseTestFuncDecl "f !x = x"
fy <- expectParseTestFuncDecl "f y = y"
fx `shouldNotBeSimilarTo` fy
it "functions with and without return type annotations are not similar" $ do
fx <- expectParseTestFuncDecl "f x :: Foo = x"
fy <- expectParseTestFuncDecl "f y = y"
fx `shouldNotBeSimilarTo` fy
it "functions with different arities are not similar" $ do
fxz <- expectParseTestFuncDecl "f x z = x"
fy <- expectParseTestFuncDecl "f y = y"
fxz `shouldNotBeSimilarTo` fy
it "type arguments bind type variables in argument type annotations" $ do
fab <- expectParseTestFuncDecl "f @a (x :: a) = x"
fb <- expectParseTestFuncDecl "f @b (x :: b) = x"
fab `shouldBeSimilarTo` fb
it "type arguments bind type variables in return type annotations" $ do
fa <- expectParseTestFuncDecl "f @a :: a = undefined"
fb <- expectParseTestFuncDecl "f @b :: b = undefined"
fa `shouldBeSimilarTo` fb
it "type arguments bind type variables in on right-hand side" $ do
fa <- expectParseTestFuncDecl "f @a = undefined @a"
fb <- expectParseTestFuncDecl "f @b = undefined @b"
fa `shouldBeSimilarTo` fb
it "functions with different type arities are not similar" $ do
fa <- expectParseTestFuncDecl "f @a @b = undefined"
fb <- expectParseTestFuncDecl "f @a = undefined"
fa `shouldNotBeSimilarTo` fb
| Test group for ' . Similar ' instance of type - level
testSimilarTypeDecls :: Spec
testSimilarTypeDecls = do
context "type synonym declarations" $ do
it "nullary type synonyms are similar" $ do
foo1 <- expectParseTestTypeDecl "type Foo = ()"
foo2 <- expectParseTestTypeDecl "type Foo = ()"
foo1 `shouldBeSimilarTo` foo2
it "type synonyms with different names are not similar" $ do
foo <- expectParseTestTypeDecl "type Foo = ()"
bar <- expectParseTestTypeDecl "type Bar = ()"
foo `shouldNotBeSimilarTo` bar
it "type synonyms with similar right-hand side are similar" $ do
foo1 <- expectParseTestTypeDecl "type Foo a = Bar a"
foo2 <- expectParseTestTypeDecl "type Foo b = Bar b"
foo1 `shouldBeSimilarTo` foo2
it "type synonyms with dissimilar right-hand side are not similar" $ do
foo1 <- expectParseTestTypeDecl "type Foo a b = Bar a"
foo2 <- expectParseTestTypeDecl "type Foo b a = Bar a"
foo1 `shouldNotBeSimilarTo` foo2
it "type synonyms with different number of type arguments are not similar"
$ do
foo1 <- expectParseTestTypeDecl "type Foo a = Bar a"
foo2 <- expectParseTestTypeDecl "type Foo a b = Bar a"
foo1 `shouldNotBeSimilarTo` foo2
context "data type declarations" $ do
it "nullary data types are similar to themselves" $ do
foo <- expectParseTestTypeDecl "data Foo"
foo `shouldBeSimilarTo` foo
it "data types with different names are not similar" $ do
foo <- expectParseTestTypeDecl "data Foo"
bar <- expectParseTestTypeDecl "data Bar"
foo `shouldNotBeSimilarTo` bar
it "data types with similar constructors are similar" $ do
foo1 <- expectParseTestTypeDecl "data Foo a = Bar a"
foo2 <- expectParseTestTypeDecl "data Foo b = Bar b"
foo1 `shouldBeSimilarTo` foo2
it "data types with dissimilar constructors are not similar" $ do
foo1 <- expectParseTestTypeDecl "data Foo a b = Bar a"
foo2 <- expectParseTestTypeDecl "data Foo b a = Bar a"
foo1 `shouldNotBeSimilarTo` foo2
it "data types with different number of type arguments are not similar" $ do
foo1 <- expectParseTestTypeDecl "data Foo a"
foo2 <- expectParseTestTypeDecl "data Foo a b"
foo1 `shouldNotBeSimilarTo` foo2
it "data types with unordered constructors are not similar" $ do
foo1 <- expectParseTestTypeDecl "data Foo = Foo | Bar"
foo2 <- expectParseTestTypeDecl "data Foo = Bar | Foo"
foo1 `shouldNotBeSimilarTo` foo2
it "constructors with different names are not similar" $ do
fooFoo <- expectParseTestTypeDecl "data Foo = Foo"
fooBar <- expectParseTestTypeDecl "data Foo = Bar"
fooFoo `shouldNotBeSimilarTo` fooBar
it "constructors with different number of fields are not similar" $ do
foo1 <- expectParseTestTypeDecl "data Foo a = Foo a"
foo2 <- expectParseTestTypeDecl "data Foo a = Foo a a"
foo1 `shouldNotBeSimilarTo` foo2
|
3e3c8a3a47b9669d38ffb45ee2d21579b2610b476ab30c40b87f8fa2e6817fed | programaker-project/Programaker-Core | automate_rest_api_ping.erl | %%% @doc
%%% REST endpoint to manage knowledge collections.
%%% @end
-module(automate_rest_api_ping).
-export([init/2]).
-export([ content_types_provided/2
]).
-export([ to_json/2
]).
-include("./records.hrl").
-spec init(_,_) -> {'cowboy_rest',_,_}.
init(Req, _Opts) ->
{cowboy_rest, Req, { }}.
%% GET handler
content_types_provided(Req, State) ->
{[{{<<"application">>, <<"json">>, []}, to_json}],
Req, State}.
-spec to_json(cowboy_req:req(), {})
-> {binary(),cowboy_req:req(), {}}.
to_json(Req, State) ->
Output = jiffy:encode(#{ success => true }),
Res1 = cowboy_req:delete_resp_header(<<"content-type">>, Req),
Res2 = cowboy_req:set_resp_header(<<"content-type">>, <<"application/json">>, Res1),
{ Output, Res2, State }.
| null | https://raw.githubusercontent.com/programaker-project/Programaker-Core/ef10fc6d2a228b2096b121170c421f5c29f9f270/backend/apps/automate_rest_api/src/automate_rest_api_ping.erl | erlang | @doc
REST endpoint to manage knowledge collections.
@end
GET handler |
-module(automate_rest_api_ping).
-export([init/2]).
-export([ content_types_provided/2
]).
-export([ to_json/2
]).
-include("./records.hrl").
-spec init(_,_) -> {'cowboy_rest',_,_}.
init(Req, _Opts) ->
{cowboy_rest, Req, { }}.
content_types_provided(Req, State) ->
{[{{<<"application">>, <<"json">>, []}, to_json}],
Req, State}.
-spec to_json(cowboy_req:req(), {})
-> {binary(),cowboy_req:req(), {}}.
to_json(Req, State) ->
Output = jiffy:encode(#{ success => true }),
Res1 = cowboy_req:delete_resp_header(<<"content-type">>, Req),
Res2 = cowboy_req:set_resp_header(<<"content-type">>, <<"application/json">>, Res1),
{ Output, Res2, State }.
|
c29e90cb9e94a52686f8d9e0a7e83c7bcb554ace6d2c45c776defea709944d5c | c-cube/ocaml-containers | containers_bencode.ml | module Str_map = Map.Make (String)
type t = Int of int64 | String of string | List of t list | Map of t Str_map.t
let rec equal t1 t2 =
match t1, t2 with
| Int i1, Int i2 -> i1 = i2
| String s1, String s2 -> s1 = s2
| List l1, List l2 ->
(try List.for_all2 equal l1 l2 with Invalid_argument _ -> false)
| Map d1, Map d2 -> Str_map.equal equal d1 d2
| (Int _ | String _ | List _ | Map _), _ -> false
let rec hash t =
let module H = CCHash in
match t with
| Int i -> H.int64 i
| String s -> H.combine2 10 (H.string s)
| List l -> H.combine2 20 (H.list hash l)
| Map l ->
H.combine2 30
( H.iter (H.pair H.string hash) @@ fun k ->
Str_map.iter (fun x y -> k (x, y)) l )
let int64 i : t = Int i
let int i : t = int64 (Int64.of_int i)
let string s : t = String s
let list l : t = List l
let map m : t = Map m
let map_of_list l : t =
map @@ List.fold_left (fun m (k, v) -> Str_map.add k v m) Str_map.empty l
let rec pp_debug out (self : t) : unit =
let fpf = Format.fprintf in
match self with
| Int i -> fpf out "%Ld" i
| String s -> fpf out "%S" s
| List l ->
fpf out "[@[<hv>";
List.iteri
(fun i v ->
if i > 0 then fpf out ";@ ";
pp_debug out v)
l;
fpf out "@]]"
| Map m ->
fpf out "{@[<hv>";
let i = ref 0 in
Str_map.iter
(fun k v ->
if !i > 0 then fpf out ";@ ";
incr i;
fpf out "@[<1>%S:@ %a@]" k pp_debug v)
m;
fpf out "@]}"
let to_string_debug self = Format.asprintf "%a" pp_debug self
module Encode = struct
let bpf = Printf.bprintf
let fpf = Printf.fprintf
let rec to_buffer (buf : Buffer.t) (self : t) : unit =
let recurse = to_buffer buf in
let addc = Buffer.add_char in
match self with
| Int i -> bpf buf "i%Lde" i
| String s -> bpf buf "%d:%s" (String.length s) s
| List l ->
addc buf 'l';
List.iter recurse l;
addc buf 'e'
| Map l ->
addc buf 'd';
Str_map.iter
(fun k v -> bpf buf "%d:%s%a" (String.length k) k to_buffer v)
l;
addc buf 'e'
let to_string (self : t) : string =
let buf = Buffer.create 32 in
to_buffer buf self;
Buffer.contents buf
let rec to_chan (oc : out_channel) (self : t) : unit =
let recurse = to_chan oc in
let addc = output_char in
match self with
| Int i -> fpf oc "i%Lde" i
| String s -> fpf oc "%d:%s" (String.length s) s
| List l ->
addc oc 'l';
List.iter recurse l;
addc oc 'e'
| Map l ->
addc oc 'd';
Str_map.iter (fun k v -> fpf oc "%d:%s%a" (String.length k) k to_chan v) l;
addc oc 'e'
let to_fmt out self = Format.pp_print_string out (to_string self)
end
module Decode = struct
exception Fail
let of_string s =
let i = ref 0 in
let[@inline] check_not_eof () =
if !i >= String.length s then raise_notrace Fail
in
let rec top () : t =
check_not_eof ();
match String.unsafe_get s !i with
| 'l' ->
incr i;
read_list []
| 'd' ->
incr i;
read_map Str_map.empty
| 'i' ->
incr i;
let n = read_int 'e' true 0 in
int n
| '0' .. '9' -> String (parse_str_len ())
| _ -> raise_notrace Fail
(* read integer until char [stop] is met, consume [stop], return int *)
and read_int stop sign n : int =
check_not_eof ();
match String.unsafe_get s !i with
| c when c == stop ->
incr i;
if sign then
n
else
-n
| '-' when stop == 'e' && sign && n = 0 ->
incr i;
read_int stop false n
| '0' .. '9' as c ->
incr i;
read_int stop sign (Char.code c - Char.code '0' + (10 * n))
| _ -> raise_notrace Fail
and parse_str_len () : string =
let n = read_int ':' true 0 in
if !i + n > String.length s then raise_notrace Fail;
let s = String.sub s !i n in
i := !i + n;
s
and read_list acc =
check_not_eof ();
match String.unsafe_get s !i with
| 'e' ->
incr i;
List (List.rev acc)
| _ ->
let x = top () in
read_list (x :: acc)
and read_map acc =
check_not_eof ();
match String.unsafe_get s !i with
| 'e' ->
incr i;
Map acc
| _ ->
let k = parse_str_len () in
let v = top () in
read_map (Str_map.add k v acc)
in
try Some (top ()) with Fail -> None
let of_string_exn s =
match of_string s with
| Some x -> x
| None -> failwith "bencode.decode: invalid string"
end
| null | https://raw.githubusercontent.com/c-cube/ocaml-containers/69f2805f1073c4ebd1063bbd58380d17e62f6324/src/bencode/containers_bencode.ml | ocaml | read integer until char [stop] is met, consume [stop], return int | module Str_map = Map.Make (String)
type t = Int of int64 | String of string | List of t list | Map of t Str_map.t
let rec equal t1 t2 =
match t1, t2 with
| Int i1, Int i2 -> i1 = i2
| String s1, String s2 -> s1 = s2
| List l1, List l2 ->
(try List.for_all2 equal l1 l2 with Invalid_argument _ -> false)
| Map d1, Map d2 -> Str_map.equal equal d1 d2
| (Int _ | String _ | List _ | Map _), _ -> false
let rec hash t =
let module H = CCHash in
match t with
| Int i -> H.int64 i
| String s -> H.combine2 10 (H.string s)
| List l -> H.combine2 20 (H.list hash l)
| Map l ->
H.combine2 30
( H.iter (H.pair H.string hash) @@ fun k ->
Str_map.iter (fun x y -> k (x, y)) l )
let int64 i : t = Int i
let int i : t = int64 (Int64.of_int i)
let string s : t = String s
let list l : t = List l
let map m : t = Map m
let map_of_list l : t =
map @@ List.fold_left (fun m (k, v) -> Str_map.add k v m) Str_map.empty l
let rec pp_debug out (self : t) : unit =
let fpf = Format.fprintf in
match self with
| Int i -> fpf out "%Ld" i
| String s -> fpf out "%S" s
| List l ->
fpf out "[@[<hv>";
List.iteri
(fun i v ->
if i > 0 then fpf out ";@ ";
pp_debug out v)
l;
fpf out "@]]"
| Map m ->
fpf out "{@[<hv>";
let i = ref 0 in
Str_map.iter
(fun k v ->
if !i > 0 then fpf out ";@ ";
incr i;
fpf out "@[<1>%S:@ %a@]" k pp_debug v)
m;
fpf out "@]}"
let to_string_debug self = Format.asprintf "%a" pp_debug self
module Encode = struct
let bpf = Printf.bprintf
let fpf = Printf.fprintf
let rec to_buffer (buf : Buffer.t) (self : t) : unit =
let recurse = to_buffer buf in
let addc = Buffer.add_char in
match self with
| Int i -> bpf buf "i%Lde" i
| String s -> bpf buf "%d:%s" (String.length s) s
| List l ->
addc buf 'l';
List.iter recurse l;
addc buf 'e'
| Map l ->
addc buf 'd';
Str_map.iter
(fun k v -> bpf buf "%d:%s%a" (String.length k) k to_buffer v)
l;
addc buf 'e'
let to_string (self : t) : string =
let buf = Buffer.create 32 in
to_buffer buf self;
Buffer.contents buf
let rec to_chan (oc : out_channel) (self : t) : unit =
let recurse = to_chan oc in
let addc = output_char in
match self with
| Int i -> fpf oc "i%Lde" i
| String s -> fpf oc "%d:%s" (String.length s) s
| List l ->
addc oc 'l';
List.iter recurse l;
addc oc 'e'
| Map l ->
addc oc 'd';
Str_map.iter (fun k v -> fpf oc "%d:%s%a" (String.length k) k to_chan v) l;
addc oc 'e'
let to_fmt out self = Format.pp_print_string out (to_string self)
end
module Decode = struct
exception Fail
let of_string s =
let i = ref 0 in
let[@inline] check_not_eof () =
if !i >= String.length s then raise_notrace Fail
in
let rec top () : t =
check_not_eof ();
match String.unsafe_get s !i with
| 'l' ->
incr i;
read_list []
| 'd' ->
incr i;
read_map Str_map.empty
| 'i' ->
incr i;
let n = read_int 'e' true 0 in
int n
| '0' .. '9' -> String (parse_str_len ())
| _ -> raise_notrace Fail
and read_int stop sign n : int =
check_not_eof ();
match String.unsafe_get s !i with
| c when c == stop ->
incr i;
if sign then
n
else
-n
| '-' when stop == 'e' && sign && n = 0 ->
incr i;
read_int stop false n
| '0' .. '9' as c ->
incr i;
read_int stop sign (Char.code c - Char.code '0' + (10 * n))
| _ -> raise_notrace Fail
and parse_str_len () : string =
let n = read_int ':' true 0 in
if !i + n > String.length s then raise_notrace Fail;
let s = String.sub s !i n in
i := !i + n;
s
and read_list acc =
check_not_eof ();
match String.unsafe_get s !i with
| 'e' ->
incr i;
List (List.rev acc)
| _ ->
let x = top () in
read_list (x :: acc)
and read_map acc =
check_not_eof ();
match String.unsafe_get s !i with
| 'e' ->
incr i;
Map acc
| _ ->
let k = parse_str_len () in
let v = top () in
read_map (Str_map.add k v acc)
in
try Some (top ()) with Fail -> None
let of_string_exn s =
match of_string s with
| Some x -> x
| None -> failwith "bencode.decode: invalid string"
end
|
11ade0136f9d708ca7b9d888cd17754ab808d4d83efcd1fbe17dbf224458aa6a | ekmett/rcu | TimeSynchronize.hs | # LANGUAGE CPP #
{-# LANGUAGE BangPatterns #-}
# LANGUAGE NamedFieldPuns #
# LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
module Main where
import Control.Concurrent
import Control.Concurrent.RCU.MODE.Internal
import Control.Concurrent.RCU.Class
import Control.DeepSeq (force)
import Control.Exception (evaluate)
import Control.Monad
import Data.Bits ((.&.), (.|.), shiftL)
import Data.List (intercalate)
#if !(MIN_VERSION_base(4,13,0))
import Data.Monoid ((<>))
#endif
import Data.Word (Word64)
import Options.Applicative (auto, execParser, fullDesc, help, info, long, metavar, option, progDesc, short)
import Prelude hiding (read)
#if UNBOUND
import Data.Time (UTCTime(..), Day(..), NominalDiffTime, diffUTCTime, getCurrentTime)
type TimeT = NominalDiffTime
timer :: IO UTCTime
timer = getCurrentTime
timerDiff :: UTCTime -> UTCTime -> TimeT
timerDiff = diffUTCTime
timeZero :: TimeT
timeZero = let t = UTCTime (ModifiedJulianDay 0) 0 in t `diffUTCTime` t
#else
import System.CPUTime.Rdtsc (rdtsc)
type TimeT = Word64
timer :: IO Word64
timer = rdtsc
timerDiff :: TimeT -> TimeT -> TimeT
timerDiff = (-)
timeZero :: TimeT
timeZero = 0
#endif
data List s a = Nil | Cons a (SRef s (List s a))
-- | Checks whether the list contains the same bit twice.
-- Does not short-circuit, so all read-side critical sections
-- have similar memory access patterns and durations.
checkForDup :: MonadReading (SRef s) (m s) => (Word64, Bool) -> List s Word64 -> m s Bool
checkForDup (_, dup) Nil = return dup
checkForDup (acc, dup) (Cons x rn) = checkForDup (acc .|. x, dup || acc .&. x /= 0) =<< readSRef rn
snapshot : : MonadReading ( SRef s ) ( m s ) = > [ a ] - > List s a - > m s [ a ]
snapshot acc Nil = return $ reverse acc
snapshot acc ( Cons x rn ) = snapshot ( x : acc ) = < < readSRef rn
reader :: SRef s Bool -> Integer -> SRef s (List s Word64) -> RCU s Integer
reader rf !acc hd = do
(acc', flag) <- reading $ do dup <- checkForDup (0, False) =<< readSRef hd
--when dup $ do
-- xs <- snapshot [] =<< readSRef hd
-- trace (show xs) $ return ()
flag <- readSRef rf
return (if dup then succ acc else acc, flag)
if flag
then return acc'
else reader rf acc' hd
writer :: Int -> WritingRCU s TimeT -> WritingRCU s TimeT
writer n m = do
#if MEASURE_SYNCHRONIZE
helper n m timeZero
where helper 0 _ !acc = return acc
helper !n' m' !acc = do d <- m'
helper (pred n') m' (acc + d)
#else
replicateM_ n m
return timeZero
#endif
moveDback :: SRef s (List s a) -> WritingRCU s TimeT
moveDback rl = WritingRCU $ \ s -> do
(rc, ne) <- flip runWritingRCU s $ do
Cons _a rb <- readSRef rl
Cons _b rc <- readSRef rb
-- duplicate pointer to B
rb' <- copySRef rb
Cons c rd <- readSRef rc
ne <- readSRef rd
-- link in a new C after A
writeSRef rb $ Cons c rb'
return (rc, ne)
#if MEASURE_SYNCHRONIZE
beg <- timer
#endif
-- any reader who starts during this grace period
sees either " ABCDE " or " ACBCDE "
runWritingRCU synchronize s
#if MEASURE_SYNCHRONIZE
end <- timer
let d = end `timerDiff` beg
#else
let d = timeZero
#endif
-- unlink the old C
flip runWritingRCU s $ do writeSRef rc ne
return d
testList :: RCU s (SRef s (List s Word64))
testList = helper 4 =<< newSRef Nil
where helper (- 1) tl = return tl
helper i tl = helper (pred i) =<< newSRef (Cons (shiftL 1 i) tl)
data Opts = Opts { nReserved :: Integer
, nUpdates :: Integer }
main :: IO ()
main = do
Opts { nReserved, nUpdates } <- execParser opts
nCaps <- getNumCapabilities
putStrLn $ "nCaps: " ++ show nCaps
let nReaders = fromIntegral nCaps - nReserved
putStrLn $ "reserved: " ++ show nReserved ++ ", readers: " ++ show nReaders ++ ", updates: " ++ show nUpdates
let nTotal = fromIntegral $ nUpdates * nReaders :: Double
(ods, _wfrd, wd, wfd) <- runOnRCU 0 $ RCU $ \ s -> do
-- initialize list
hd <- unRCU testList s
-- initialize flag writer uses to stop readers
rf <- unRCU (newSRef False) s
spawn readers , each takes snapshots of the list until the writer has finished
rts <- forM [2..fromIntegral nReaders + 1] $ \ i -> flip unRCU (s { rcuStatePinned = Just i }) $ forking $ reading $ ReadingRCU
$ \ s' -> do beg <- timer
x <- evaluate . force =<< unRCU (reader rf 0 hd) s' -- how long do the snapshots take?
mid <- timer
_ <- evaluate . force $ x -- how long does walking over the result take?
end <- timer
return ( x
, mid `timerDiff` beg
, end `timerDiff` mid )
-- spawn a writer to move a node from a later position to an earlier position nUpdates times
wt <- flip unRCU (s { rcuStatePinned = Just 1 }) $ forking $ writing $ WritingRCU
$ \ s' -> do beg <- timer
x <- evaluate . force =<< runWritingRCU (writer (fromIntegral nUpdates) (moveDback hd)) s'
runWritingRCU (writeSRef rf True) s'
mid <- timer
_ <- evaluate . force $ x
end <- timer
#if UNBOUND
let d = x
#else
let d = fromIntegral x :: Double
#endif
return ( d / fromIntegral nUpdates
, mid `timerDiff` beg
, end `timerDiff` mid )
-- wait for the readers to finish
ods <- mapM (\ rt -> unRCU (joining rt) s) rts
-- wait for the writer to finish
(wfrd, wd, wfd) <- unRCU (joining wt) s
return (ods, wfrd, wd, wfd)
let outs = map a ods
rds = map b ods :: [TimeT]
rfds = map c ods :: [TimeT]
a (x,_,_) = x
b (_,y,_) = y
c (_,_,z) = z
putStrLn $ "dups by thread:" ++ intercalate ", " (zipWith (\ i dups -> show i ++ ": " ++ show dups) [(1 :: Integer)..] outs)
putStrLn $ "average dups per update: " ++ show (fromIntegral (sum outs) / nTotal)
#if UNBOUND
putStrLn "times in SECONDS"
#else
putStrLn "times in TICKS"
#endif
putStrLn $ "reader times: " ++ show rds
putStrLn $ "reader evaluate . force times: " ++ show rfds
putStrLn $ "writer time: " ++ show wd
putStrLn $ "writer evaluate . force time: " ++ show wfd
#if UNBOUND
let wtd = wd - wfd
#else
let wtd = fromIntegral $ wd - wfd :: Double
#endif
let aud = wtd / fromIntegral nUpdates
putStrLn $ "average writer update time: " ++ show aud
#if MEASURE_SYNCHRONIZE
putStrLn $ "average synchronize time: " ++ show _wfrd
#endif
where opts = info optsParser
( fullDesc
<> progDesc "Measure writer latency for synchronize." )
optsParser = Opts <$> nReservedParser <*> nUpdatesParser
nReservedParser = option auto
( long "reserved"
<> short 'r'
<> metavar "N"
<> help "N OS threads reserved for other stuff" )
nUpdatesParser = option auto
( long "updates"
<> short 'u'
<> metavar "M"
<> help "Writer thread performs M updates" )
| null | https://raw.githubusercontent.com/ekmett/rcu/0268be375de95fea32909dfcfc4b7934c1e73ae8/examples/TimeSynchronize.hs | haskell | # LANGUAGE BangPatterns #
| Checks whether the list contains the same bit twice.
Does not short-circuit, so all read-side critical sections
have similar memory access patterns and durations.
when dup $ do
xs <- snapshot [] =<< readSRef hd
trace (show xs) $ return ()
duplicate pointer to B
link in a new C after A
any reader who starts during this grace period
unlink the old C
initialize list
initialize flag writer uses to stop readers
how long do the snapshots take?
how long does walking over the result take?
spawn a writer to move a node from a later position to an earlier position nUpdates times
wait for the readers to finish
wait for the writer to finish | # LANGUAGE CPP #
# LANGUAGE NamedFieldPuns #
# LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
module Main where
import Control.Concurrent
import Control.Concurrent.RCU.MODE.Internal
import Control.Concurrent.RCU.Class
import Control.DeepSeq (force)
import Control.Exception (evaluate)
import Control.Monad
import Data.Bits ((.&.), (.|.), shiftL)
import Data.List (intercalate)
#if !(MIN_VERSION_base(4,13,0))
import Data.Monoid ((<>))
#endif
import Data.Word (Word64)
import Options.Applicative (auto, execParser, fullDesc, help, info, long, metavar, option, progDesc, short)
import Prelude hiding (read)
#if UNBOUND
import Data.Time (UTCTime(..), Day(..), NominalDiffTime, diffUTCTime, getCurrentTime)
type TimeT = NominalDiffTime
timer :: IO UTCTime
timer = getCurrentTime
timerDiff :: UTCTime -> UTCTime -> TimeT
timerDiff = diffUTCTime
timeZero :: TimeT
timeZero = let t = UTCTime (ModifiedJulianDay 0) 0 in t `diffUTCTime` t
#else
import System.CPUTime.Rdtsc (rdtsc)
type TimeT = Word64
timer :: IO Word64
timer = rdtsc
timerDiff :: TimeT -> TimeT -> TimeT
timerDiff = (-)
timeZero :: TimeT
timeZero = 0
#endif
data List s a = Nil | Cons a (SRef s (List s a))
checkForDup :: MonadReading (SRef s) (m s) => (Word64, Bool) -> List s Word64 -> m s Bool
checkForDup (_, dup) Nil = return dup
checkForDup (acc, dup) (Cons x rn) = checkForDup (acc .|. x, dup || acc .&. x /= 0) =<< readSRef rn
snapshot : : MonadReading ( SRef s ) ( m s ) = > [ a ] - > List s a - > m s [ a ]
snapshot acc Nil = return $ reverse acc
snapshot acc ( Cons x rn ) = snapshot ( x : acc ) = < < readSRef rn
reader :: SRef s Bool -> Integer -> SRef s (List s Word64) -> RCU s Integer
reader rf !acc hd = do
(acc', flag) <- reading $ do dup <- checkForDup (0, False) =<< readSRef hd
flag <- readSRef rf
return (if dup then succ acc else acc, flag)
if flag
then return acc'
else reader rf acc' hd
writer :: Int -> WritingRCU s TimeT -> WritingRCU s TimeT
writer n m = do
#if MEASURE_SYNCHRONIZE
helper n m timeZero
where helper 0 _ !acc = return acc
helper !n' m' !acc = do d <- m'
helper (pred n') m' (acc + d)
#else
replicateM_ n m
return timeZero
#endif
moveDback :: SRef s (List s a) -> WritingRCU s TimeT
moveDback rl = WritingRCU $ \ s -> do
(rc, ne) <- flip runWritingRCU s $ do
Cons _a rb <- readSRef rl
Cons _b rc <- readSRef rb
rb' <- copySRef rb
Cons c rd <- readSRef rc
ne <- readSRef rd
writeSRef rb $ Cons c rb'
return (rc, ne)
#if MEASURE_SYNCHRONIZE
beg <- timer
#endif
sees either " ABCDE " or " ACBCDE "
runWritingRCU synchronize s
#if MEASURE_SYNCHRONIZE
end <- timer
let d = end `timerDiff` beg
#else
let d = timeZero
#endif
flip runWritingRCU s $ do writeSRef rc ne
return d
testList :: RCU s (SRef s (List s Word64))
testList = helper 4 =<< newSRef Nil
where helper (- 1) tl = return tl
helper i tl = helper (pred i) =<< newSRef (Cons (shiftL 1 i) tl)
data Opts = Opts { nReserved :: Integer
, nUpdates :: Integer }
main :: IO ()
main = do
Opts { nReserved, nUpdates } <- execParser opts
nCaps <- getNumCapabilities
putStrLn $ "nCaps: " ++ show nCaps
let nReaders = fromIntegral nCaps - nReserved
putStrLn $ "reserved: " ++ show nReserved ++ ", readers: " ++ show nReaders ++ ", updates: " ++ show nUpdates
let nTotal = fromIntegral $ nUpdates * nReaders :: Double
(ods, _wfrd, wd, wfd) <- runOnRCU 0 $ RCU $ \ s -> do
hd <- unRCU testList s
rf <- unRCU (newSRef False) s
spawn readers , each takes snapshots of the list until the writer has finished
rts <- forM [2..fromIntegral nReaders + 1] $ \ i -> flip unRCU (s { rcuStatePinned = Just i }) $ forking $ reading $ ReadingRCU
$ \ s' -> do beg <- timer
mid <- timer
end <- timer
return ( x
, mid `timerDiff` beg
, end `timerDiff` mid )
wt <- flip unRCU (s { rcuStatePinned = Just 1 }) $ forking $ writing $ WritingRCU
$ \ s' -> do beg <- timer
x <- evaluate . force =<< runWritingRCU (writer (fromIntegral nUpdates) (moveDback hd)) s'
runWritingRCU (writeSRef rf True) s'
mid <- timer
_ <- evaluate . force $ x
end <- timer
#if UNBOUND
let d = x
#else
let d = fromIntegral x :: Double
#endif
return ( d / fromIntegral nUpdates
, mid `timerDiff` beg
, end `timerDiff` mid )
ods <- mapM (\ rt -> unRCU (joining rt) s) rts
(wfrd, wd, wfd) <- unRCU (joining wt) s
return (ods, wfrd, wd, wfd)
let outs = map a ods
rds = map b ods :: [TimeT]
rfds = map c ods :: [TimeT]
a (x,_,_) = x
b (_,y,_) = y
c (_,_,z) = z
putStrLn $ "dups by thread:" ++ intercalate ", " (zipWith (\ i dups -> show i ++ ": " ++ show dups) [(1 :: Integer)..] outs)
putStrLn $ "average dups per update: " ++ show (fromIntegral (sum outs) / nTotal)
#if UNBOUND
putStrLn "times in SECONDS"
#else
putStrLn "times in TICKS"
#endif
putStrLn $ "reader times: " ++ show rds
putStrLn $ "reader evaluate . force times: " ++ show rfds
putStrLn $ "writer time: " ++ show wd
putStrLn $ "writer evaluate . force time: " ++ show wfd
#if UNBOUND
let wtd = wd - wfd
#else
let wtd = fromIntegral $ wd - wfd :: Double
#endif
let aud = wtd / fromIntegral nUpdates
putStrLn $ "average writer update time: " ++ show aud
#if MEASURE_SYNCHRONIZE
putStrLn $ "average synchronize time: " ++ show _wfrd
#endif
where opts = info optsParser
( fullDesc
<> progDesc "Measure writer latency for synchronize." )
optsParser = Opts <$> nReservedParser <*> nUpdatesParser
nReservedParser = option auto
( long "reserved"
<> short 'r'
<> metavar "N"
<> help "N OS threads reserved for other stuff" )
nUpdatesParser = option auto
( long "updates"
<> short 'u'
<> metavar "M"
<> help "Writer thread performs M updates" )
|
a400a48baed703041e1b12009ad9d716b4c40cd17f4b5b5acff2a7078611eb2d | pouyakary/Nota | Assignment.hs |
module Language.BackEnd.Renderer.Nodes.Assignment ( renderASTAssignment ) where
-- ─── IMPORTS ────────────────────────────────────────────────────────────────────
import Infrastructure.Text.Layout
import Language.FrontEnd.AST
-- ─── RENDER ─────────────────────────────────────────────────────────────────────
renderASTAssignment :: AST -> AST -> ( AST -> Bool -> SpacedBox ) -> SpacedBox
renderASTAssignment ( ASTIdentifier name ) value render = result where
result =
horizontalConcat [ renderedName, renderedValue ]
renderedName =
spacedBox $ "⟨" ++ name ++ "⟩ ≡ "
renderedValue =
render value False
-- ──────────────────────────────────────────────────────────────────────────────── | null | https://raw.githubusercontent.com/pouyakary/Nota/d5e29eca7ea34d72835a9708977fa33c030393d1/source/Language/BackEnd/Renderer/Nodes/Assignment.hs | haskell | ─── IMPORTS ────────────────────────────────────────────────────────────────────
─── RENDER ─────────────────────────────────────────────────────────────────────
──────────────────────────────────────────────────────────────────────────────── |
module Language.BackEnd.Renderer.Nodes.Assignment ( renderASTAssignment ) where
import Infrastructure.Text.Layout
import Language.FrontEnd.AST
renderASTAssignment :: AST -> AST -> ( AST -> Bool -> SpacedBox ) -> SpacedBox
renderASTAssignment ( ASTIdentifier name ) value render = result where
result =
horizontalConcat [ renderedName, renderedValue ]
renderedName =
spacedBox $ "⟨" ++ name ++ "⟩ ≡ "
renderedValue =
render value False
|
d6ecd2288c54afdea0128833d12981bebdbbca985108c8a99db1921090703192 | blarney-lang/blarney | Connectable.hs | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE FlexibleInstances #
|
Module : . Connectable
Description : Module to connect interfaces
Copyright : ( c ) , 2019
License : MIT
Maintainer :
Stability : experimental
The ' Connectable ' class provides a standard way to connect hardware modules
Module : Blarney.Connectable
Description : Module to connect interfaces
Copyright : (c) Alexandre Joannou, 2019
License : MIT
Maintainer :
Stability : experimental
The 'Connectable' class provides a standard way to connect hardware modules
-}
module Blarney.Connectable
( -- * Connectable class
Connectable(..)
) where
-- Blarney import
import Blarney
-- | 'Connectable' class
class Connectable a b where
| Connects two interfaces that can be connected
^ First interface to connect
^ Second interface to connect
-> Module () -- ^ 'Module' with no interface, implementing the
-- connection
| null | https://raw.githubusercontent.com/blarney-lang/blarney/abc7f91485e48a6013b1a05c1b5e6a71dd55f68f/Haskell/Blarney/Connectable.hs | haskell | * Connectable class
Blarney import
| 'Connectable' class
^ 'Module' with no interface, implementing the
connection | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE FlexibleInstances #
|
Module : . Connectable
Description : Module to connect interfaces
Copyright : ( c ) , 2019
License : MIT
Maintainer :
Stability : experimental
The ' Connectable ' class provides a standard way to connect hardware modules
Module : Blarney.Connectable
Description : Module to connect interfaces
Copyright : (c) Alexandre Joannou, 2019
License : MIT
Maintainer :
Stability : experimental
The 'Connectable' class provides a standard way to connect hardware modules
-}
module Blarney.Connectable
Connectable(..)
) where
import Blarney
class Connectable a b where
| Connects two interfaces that can be connected
^ First interface to connect
^ Second interface to connect
|
5cf172e8a8dd5bfcbbd440f4856d449c5daa1a198b70e348420ded0435eeafe7 | heidihoward/ocaml-raft | raft-general-ocaml.ml | This file has been auto - generated by the SPL compiler
type t = [
|`Recover
|`RestartElecton
|`StartElecton
|`Startup
|`StepDown_from_Candidate
|`StepDown_from_Leader
|`WinElecton
]
let string_of_statecall (x:t) = match x with
|`Recover -> "Recover"
|`RestartElecton -> "RestartElecton"
|`StartElecton -> "StartElecton"
|`Startup -> "Startup"
|`StepDown_from_Candidate -> "StepDown_from_Candidate"
|`StepDown_from_Leader -> "StepDown_from_Leader"
|`WinElecton -> "WinElecton"
| null | https://raw.githubusercontent.com/heidihoward/ocaml-raft/b1502ebf8c19be28270d11994abac68e5a6418be/spl/raft-general-ocaml.ml | ocaml | This file has been auto - generated by the SPL compiler
type t = [
|`Recover
|`RestartElecton
|`StartElecton
|`Startup
|`StepDown_from_Candidate
|`StepDown_from_Leader
|`WinElecton
]
let string_of_statecall (x:t) = match x with
|`Recover -> "Recover"
|`RestartElecton -> "RestartElecton"
|`StartElecton -> "StartElecton"
|`Startup -> "Startup"
|`StepDown_from_Candidate -> "StepDown_from_Candidate"
|`StepDown_from_Leader -> "StepDown_from_Leader"
|`WinElecton -> "WinElecton"
| |
4b215a448474f307b6261f4c0c1c7e1d574b5749fadb4e3ca7c6f0e9d009eff3 | chr15m/svg-animation-assistant | project.clj | (defproject inkscape-animation-assistant "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/clojurescript "1.10.520"]
[reagent "0.8.1"]
[environ "1.1.0"]
[binaryage/oops "0.7.0"]]
:plugins [[lein-cljsbuild "1.1.7"]
[lein-figwheel "0.5.19"]
[lein-environ "1.1.0"]]
:clean-targets ^{:protect false}
[:target-path
[:cljsbuild :builds :app :compiler :output-dir]
[:cljsbuild :builds :app :compiler :output-to]]
:resource-paths ["public"]
:figwheel {:http-server-root "."
:nrepl-port 7002
:nrepl-middleware [cider.piggieback/wrap-cljs-repl]
:css-dirs ["public"]}
:cljsbuild {:builds {:app
{:source-paths ["src" "env/dev/cljs"]
:compiler
{:main "inkscape-animation-assistant.dev"
:output-to "public/js/app.js"
:output-dir "public/js/out"
:asset-path "js/out"
:source-map true
:optimizations :none
:pretty-print true}
:figwheel
{:on-jsload "inkscape-animation-assistant.core/mount-root"}}
:release
{:source-paths ["src" "env/prod/cljs"]
:compiler
{:output-to "../lib/js/app.js"
:output-dir "public/js/release"
:asset-path "js/out"
:optimizations :advanced
:pretty-print false}}}}
:aliases {"package" ["with-profile" "prod" "do" "clean" ["cljsbuild" "once" "release"]]}
:profiles {:dev {:source-paths ["src" "env/dev/clj"]
:dependencies [[binaryage/devtools "0.9.10"]
[figwheel-sidecar "0.5.19"]
[nrepl "0.6.0"]
[cider/piggieback "0.4.1"]]
:env {:dev true}}
:prod {:source-paths ["src" "env/dev/clj"]
:dependencies [[binaryage/devtools "0.9.10"]
[figwheel-sidecar "0.5.19"]
[nrepl "0.6.0"]
[cider/piggieback "0.4.1"]]}})
| null | https://raw.githubusercontent.com/chr15m/svg-animation-assistant/1a64198f961820279873afb14685695e9fa01980/app-src/project.clj | clojure | (defproject inkscape-animation-assistant "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/clojurescript "1.10.520"]
[reagent "0.8.1"]
[environ "1.1.0"]
[binaryage/oops "0.7.0"]]
:plugins [[lein-cljsbuild "1.1.7"]
[lein-figwheel "0.5.19"]
[lein-environ "1.1.0"]]
:clean-targets ^{:protect false}
[:target-path
[:cljsbuild :builds :app :compiler :output-dir]
[:cljsbuild :builds :app :compiler :output-to]]
:resource-paths ["public"]
:figwheel {:http-server-root "."
:nrepl-port 7002
:nrepl-middleware [cider.piggieback/wrap-cljs-repl]
:css-dirs ["public"]}
:cljsbuild {:builds {:app
{:source-paths ["src" "env/dev/cljs"]
:compiler
{:main "inkscape-animation-assistant.dev"
:output-to "public/js/app.js"
:output-dir "public/js/out"
:asset-path "js/out"
:source-map true
:optimizations :none
:pretty-print true}
:figwheel
{:on-jsload "inkscape-animation-assistant.core/mount-root"}}
:release
{:source-paths ["src" "env/prod/cljs"]
:compiler
{:output-to "../lib/js/app.js"
:output-dir "public/js/release"
:asset-path "js/out"
:optimizations :advanced
:pretty-print false}}}}
:aliases {"package" ["with-profile" "prod" "do" "clean" ["cljsbuild" "once" "release"]]}
:profiles {:dev {:source-paths ["src" "env/dev/clj"]
:dependencies [[binaryage/devtools "0.9.10"]
[figwheel-sidecar "0.5.19"]
[nrepl "0.6.0"]
[cider/piggieback "0.4.1"]]
:env {:dev true}}
:prod {:source-paths ["src" "env/dev/clj"]
:dependencies [[binaryage/devtools "0.9.10"]
[figwheel-sidecar "0.5.19"]
[nrepl "0.6.0"]
[cider/piggieback "0.4.1"]]}})
| |
0e966beb31adef9c0e5dbf51d1a6b274320f5b566474d69fce378e6784a7df42 | baskeboler/cljs-karaoke-client | config.cljs | (ns cljs-karaoke.config)
(def ^:export config-map
{:audio-files-prefix "-karaoke"
:app-url-prefix "-player.netlify.app"
:http-timeout 15000})
| null | https://raw.githubusercontent.com/baskeboler/cljs-karaoke-client/bb6512435eaa436d35034886be99213625847ee0/src/main/cljs_karaoke/config.cljs | clojure | (ns cljs-karaoke.config)
(def ^:export config-map
{:audio-files-prefix "-karaoke"
:app-url-prefix "-player.netlify.app"
:http-timeout 15000})
| |
a31e7f2592c19b61ca7384f28f56333206dcafa5c8902f1c39ba542f2d12ee99 | hypernumbers/hypernumbers | eunit_render_str.erl | -module(eunit_render_str).
-include_lib("eunit/include/eunit.hrl").
%%--------------------
%%
%% Tests
%%
%%--------------------
%%
%% Render Test
%%
string_test_() ->
Str = "This is a test:\n" ++
"$testFun()$ followed by $testData$ and unicode characters àèìòù",
{ok, Compiled} = sgte:compile(Str),
Res = sgte:render_str(Compiled, data()),
ResultStr = "This is a test:\n" ++
"foo, bar, baz" ++
" followed by " ++
"my test data with unicode characters: àèìòù" ++
" and unicode characters àèìòù",
%% error test
Str2 = "This is a test:\n" ++
"$testFun()$ followed by $testData$ and unicode chars àèìòù",
{ok, Compiled2} = sgte:compile(Str2),
Res2 = sgte:render_str(Compiled2, []),
ResultStr2 = "This is a test:\n"++
"[SGTE Warning: template: attribute - key 'testFun()' not found on line 2]"++
" followed by "++
"[SGTE Warning: template: attribute - key testData not found on line 2]"++
" and unicode chars àèìòù",
[?_assert(Res =:= ResultStr),
?_assert(Res2 =:= ResultStr2)].
include_test_() ->
{ok, C1} = sgte:compile("bar"),
{ok, C2} = sgte:compile("foo $include tmpl$ baz"),
Res = sgte:render_str(C2, [{tmpl, C1}]),
ResultStr = "foo bar baz",
?_assert(Res =:= ResultStr).
apply_test_() ->
F = fun(L) -> lists:nth(2, L) end,
{ok, C} = sgte:compile("foo $apply second myList$ baz"),
Res = sgte:render_str(C, [{second, F}, {myList, ["1", "2", "3"]}]),
ResultStr = "foo 2 baz",
?_assert(Res =:= ResultStr).
simpleif_test_() ->
{ok, C} = sgte:compile(simple_if()),
DThen = [{test, true}],
DElse1 = [{test, false}],
DElse2 = [{test, []}],
DElse3 = [{test, ""}],
DElse4 = [{test, {}}],
DElse5 = [{test, 0}],
RThen = sgte:render_str(C, DThen),
RElse1 = sgte:render_str(C, DElse1),
RElse2 = sgte:render_str(C, DElse2),
RElse3 = sgte:render_str(C, DElse3),
RElse4 = sgte:render_str(C, DElse4),
RElse5 = sgte:render_str(C, DElse5),
ThenStr = "Start then branch",
ElseStr = "Start else branch",
[?_assert(RThen =:= ThenStr),
?_assert(RElse1 =:= ElseStr),
?_assert(RElse2 =:= ElseStr),
?_assert(RElse3 =:= ElseStr),
?_assert(RElse4 =:= ElseStr),
?_assert(RElse5 =:= ElseStr)].
simpleif_no_test_test_() ->
{ok, C} = sgte:compile(simple_if()),
RElse = sgte:render_str(C, [], [quiet]),
?_assert(RElse =:= "Start else branch").
if_test_() ->
{ok, Compiled} = sgte:compile(if_string()),
NameL = mountainList(),
Data1 = [{testNames, true},
{nameList, NameL}],
Data2 = [{testNames, false},
{noName, fun no_name/1}],
Res1 = sgte:render_str(Compiled, Data1),
Res2 = sgte:render_str(Compiled, Data2),
[?_assert(Res1 =:= "Hello! Some Mountains: "++
"Monte Bianco, Cerro Torre, Mt. Everest, Catinaccio Bye Bye."),
?_assert(Res2 =:= "Hello! No Name Found Bye Bye.")].
fif_test_() ->
{ok, Compiled} = sgte:compile(if_string()),
NameL = mountainList(),
Data = [{testNames, check_names(NameL)},
{noName, fun no_name/1},
{nameList, NameL}],
Res = sgte:render_str(Compiled, Data),
{ok, Compiled2} = sgte:compile(if_string()),
D1 = dict:new(),
D2 = dict:store('testNames', check_names([]), D1),
D3 = dict:store('noName', fun no_name/1, D2),
D4 = dict:store('nameList', mountainList(), D3),
Res2 = sgte:render_str(Compiled2, D4),
[?_assert(Res =:= "Hello! Some Mountains: "++
"Monte Bianco, Cerro Torre, Mt. Everest, Catinaccio Bye Bye."),
?_assert(Res2 =:= "Hello! No Name Found Bye Bye.")].
nested_fif_test_() ->
{ok, Compiled} = sgte:compile(nested_if_string()),
NameL = mountainList(),
D1 = dict:new(),
D2 = dict:store('testNames', check_names(NameL), D1),
D3 = dict:store('noName', fun no_name/1, D2),
D4 = dict:store('nameList', NameL, D3),
Res = sgte:render_str(Compiled, D4),
?_assert(Res =:= "Some Mountains: Monte Bianco, Cerro Torre, Mt. Everest, Catinaccio").
join_test_() ->
{ok, C} = sgte:compile("$join:{, } aList$"),
R1 = sgte:render_str(C, [{aList, ["foo", "bar", "baz"]}]),
R2 = sgte:render_str(C, [{aList, []}]),
[?_assert(R1 =:= "foo, bar, baz"),
?_assert(R2 =:= "")].
% test callable attribute
fun_test_() ->
MyF = fun(Data) ->
{ok, V} = dict:find(foo, Data),
"TEST: " ++ V
end,
{ok, CF} = sgte:compile(tmpl_fun()),
Res = sgte:render_str(CF, [{foo, "foooo"}, {callme, MyF}]),
?_assert(Res =:= "aaaa TEST: foooo bbb").
%test on a non existent file
file_test_() ->
Res = sgte:compile_file("myfile.tmpl"),
?_assert(Res =:= {error, enoent}).
js_support_test_() ->
{ok, CF} = sgte:compile("$('someId') and an $attr$ and $('anotherId')"),
Res = sgte:render_str(CF, [{attr, "attribute"}]),
?_assert(Res =:= "$('someId') and an attribute and $('anotherId')").
%%--------------------
%%
Internal functions
%%
%%--------------------
%% Template String
simple_if() ->
"Start $if test$" ++
"then branch" ++
"$else$" ++
"else branch"++
"$end if$".
if_string() ->
"Hello! $if testNames$" ++
"Some Mountains: $join:{, } nameList$" ++
"$else$" ++
"$noName$$end if$" ++ " Bye Bye.".
nested_if_string() ->
"$if testNames$" ++
"Some Mountains: $if testNames$$join:{, } nameList$$end if$" ++
"$else$" ++
"$noName$$end if$".
no_name(_Foo) ->
"No Name Found".
check_names(NameList) ->
length(NameList) > 0.
tmpl_fun() ->
"aaaa $callme$ bbb".
Test Data
data() ->
D1 = dict:new(),
D2 = dict:store('testFun()', "foo, bar, baz", D1),
dict:store('testData', "my test data with unicode characters: àèìòù", D2).
mountainList() ->
["Monte Bianco", "Cerro Torre", "Mt. Everest", "Catinaccio"].
| null | https://raw.githubusercontent.com/hypernumbers/hypernumbers/281319f60c0ac60fb009ee6d1e4826f4f2d51c4e/lib/sgte/test/src/eunit_render_str.erl | erlang | --------------------
Tests
--------------------
Render Test
error test
test callable attribute
test on a non existent file
--------------------
--------------------
Template String | -module(eunit_render_str).
-include_lib("eunit/include/eunit.hrl").
string_test_() ->
Str = "This is a test:\n" ++
"$testFun()$ followed by $testData$ and unicode characters àèìòù",
{ok, Compiled} = sgte:compile(Str),
Res = sgte:render_str(Compiled, data()),
ResultStr = "This is a test:\n" ++
"foo, bar, baz" ++
" followed by " ++
"my test data with unicode characters: àèìòù" ++
" and unicode characters àèìòù",
Str2 = "This is a test:\n" ++
"$testFun()$ followed by $testData$ and unicode chars àèìòù",
{ok, Compiled2} = sgte:compile(Str2),
Res2 = sgte:render_str(Compiled2, []),
ResultStr2 = "This is a test:\n"++
"[SGTE Warning: template: attribute - key 'testFun()' not found on line 2]"++
" followed by "++
"[SGTE Warning: template: attribute - key testData not found on line 2]"++
" and unicode chars àèìòù",
[?_assert(Res =:= ResultStr),
?_assert(Res2 =:= ResultStr2)].
include_test_() ->
{ok, C1} = sgte:compile("bar"),
{ok, C2} = sgte:compile("foo $include tmpl$ baz"),
Res = sgte:render_str(C2, [{tmpl, C1}]),
ResultStr = "foo bar baz",
?_assert(Res =:= ResultStr).
apply_test_() ->
F = fun(L) -> lists:nth(2, L) end,
{ok, C} = sgte:compile("foo $apply second myList$ baz"),
Res = sgte:render_str(C, [{second, F}, {myList, ["1", "2", "3"]}]),
ResultStr = "foo 2 baz",
?_assert(Res =:= ResultStr).
simpleif_test_() ->
{ok, C} = sgte:compile(simple_if()),
DThen = [{test, true}],
DElse1 = [{test, false}],
DElse2 = [{test, []}],
DElse3 = [{test, ""}],
DElse4 = [{test, {}}],
DElse5 = [{test, 0}],
RThen = sgte:render_str(C, DThen),
RElse1 = sgte:render_str(C, DElse1),
RElse2 = sgte:render_str(C, DElse2),
RElse3 = sgte:render_str(C, DElse3),
RElse4 = sgte:render_str(C, DElse4),
RElse5 = sgte:render_str(C, DElse5),
ThenStr = "Start then branch",
ElseStr = "Start else branch",
[?_assert(RThen =:= ThenStr),
?_assert(RElse1 =:= ElseStr),
?_assert(RElse2 =:= ElseStr),
?_assert(RElse3 =:= ElseStr),
?_assert(RElse4 =:= ElseStr),
?_assert(RElse5 =:= ElseStr)].
simpleif_no_test_test_() ->
{ok, C} = sgte:compile(simple_if()),
RElse = sgte:render_str(C, [], [quiet]),
?_assert(RElse =:= "Start else branch").
if_test_() ->
{ok, Compiled} = sgte:compile(if_string()),
NameL = mountainList(),
Data1 = [{testNames, true},
{nameList, NameL}],
Data2 = [{testNames, false},
{noName, fun no_name/1}],
Res1 = sgte:render_str(Compiled, Data1),
Res2 = sgte:render_str(Compiled, Data2),
[?_assert(Res1 =:= "Hello! Some Mountains: "++
"Monte Bianco, Cerro Torre, Mt. Everest, Catinaccio Bye Bye."),
?_assert(Res2 =:= "Hello! No Name Found Bye Bye.")].
fif_test_() ->
{ok, Compiled} = sgte:compile(if_string()),
NameL = mountainList(),
Data = [{testNames, check_names(NameL)},
{noName, fun no_name/1},
{nameList, NameL}],
Res = sgte:render_str(Compiled, Data),
{ok, Compiled2} = sgte:compile(if_string()),
D1 = dict:new(),
D2 = dict:store('testNames', check_names([]), D1),
D3 = dict:store('noName', fun no_name/1, D2),
D4 = dict:store('nameList', mountainList(), D3),
Res2 = sgte:render_str(Compiled2, D4),
[?_assert(Res =:= "Hello! Some Mountains: "++
"Monte Bianco, Cerro Torre, Mt. Everest, Catinaccio Bye Bye."),
?_assert(Res2 =:= "Hello! No Name Found Bye Bye.")].
nested_fif_test_() ->
{ok, Compiled} = sgte:compile(nested_if_string()),
NameL = mountainList(),
D1 = dict:new(),
D2 = dict:store('testNames', check_names(NameL), D1),
D3 = dict:store('noName', fun no_name/1, D2),
D4 = dict:store('nameList', NameL, D3),
Res = sgte:render_str(Compiled, D4),
?_assert(Res =:= "Some Mountains: Monte Bianco, Cerro Torre, Mt. Everest, Catinaccio").
join_test_() ->
{ok, C} = sgte:compile("$join:{, } aList$"),
R1 = sgte:render_str(C, [{aList, ["foo", "bar", "baz"]}]),
R2 = sgte:render_str(C, [{aList, []}]),
[?_assert(R1 =:= "foo, bar, baz"),
?_assert(R2 =:= "")].
fun_test_() ->
MyF = fun(Data) ->
{ok, V} = dict:find(foo, Data),
"TEST: " ++ V
end,
{ok, CF} = sgte:compile(tmpl_fun()),
Res = sgte:render_str(CF, [{foo, "foooo"}, {callme, MyF}]),
?_assert(Res =:= "aaaa TEST: foooo bbb").
file_test_() ->
Res = sgte:compile_file("myfile.tmpl"),
?_assert(Res =:= {error, enoent}).
js_support_test_() ->
{ok, CF} = sgte:compile("$('someId') and an $attr$ and $('anotherId')"),
Res = sgte:render_str(CF, [{attr, "attribute"}]),
?_assert(Res =:= "$('someId') and an attribute and $('anotherId')").
Internal functions
simple_if() ->
"Start $if test$" ++
"then branch" ++
"$else$" ++
"else branch"++
"$end if$".
if_string() ->
"Hello! $if testNames$" ++
"Some Mountains: $join:{, } nameList$" ++
"$else$" ++
"$noName$$end if$" ++ " Bye Bye.".
nested_if_string() ->
"$if testNames$" ++
"Some Mountains: $if testNames$$join:{, } nameList$$end if$" ++
"$else$" ++
"$noName$$end if$".
no_name(_Foo) ->
"No Name Found".
check_names(NameList) ->
length(NameList) > 0.
tmpl_fun() ->
"aaaa $callme$ bbb".
Test Data
data() ->
D1 = dict:new(),
D2 = dict:store('testFun()', "foo, bar, baz", D1),
dict:store('testData', "my test data with unicode characters: àèìòù", D2).
mountainList() ->
["Monte Bianco", "Cerro Torre", "Mt. Everest", "Catinaccio"].
|
755e3381ab505950e50a37c4a887c55c9cc7ce46855493abcab7280b9336571c | gsakkas/rite | 20060324-22:24:46-8ab05dd4986d17d763e509d04ea02fde.seminal.ml |
# # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # #
#################
#####################
################
*)
exception Unimplemented
exception AlreadyDone
let pi = 4.0 *. atan 1.0
(*** part a ***)
type move = Home | Forward of float | Turn of float | For of (int * (move list))
(*** part b ***)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
let makePoly sides len = For(sides, (Forward(len)::[Turn(2.0 *. pi /. float_of_int(sides))]))
(*** part c ***)
# # # # # # # # # # # # # # # # # # #
let forwardX x d f = x +. (f *. cos d)
let forwardY y d f = y +. (f *. sin d)
let turnD d1 d2 = mod_float (d1 +. d2) (2.0 *. pi)
let interpLarge (movelist : move list) : (float*float) list =
let rec loop movelist x y dir acc =
match movelist with
[] -> acc
| Home::tl -> loop tl 0.0 0.0 0.0 ((0.0,0.0)::acc)
| Forward(f)::tl -> loop
tl
(forwardX x dir f)
(forwardY y dir f)
dir
(((forwardX x dir f), (forwardY y dir f))::acc)
| Turn(f)::tl -> loop
tl
x
y
(turnD dir f)
acc
| For(0,lst)::tl -> loop tl x y dir acc
| For(i,lst)::tl -> loop (lst @ (For(i-1, lst)::tl)) x y dir acc
in List.rev (loop movelist 0.0 0.0 0.0 [(0.0,0.0)])
(*** part d ***)
let interpSmall (movelist : move list) : (float*float) list =
let interpSmallStep movelist x y dir : move list * float * float * float =
match movelist with
[] -> raise AlreadyDone
| Home::tl -> (tl, 0.0, 0.0, 0.0)
| Forward(f)::tl -> (tl, (forwardX x dir f), (forwardY y dir f), dir)
| Turn(f)::tl -> (tl, x, y, turnD dir f)
| For(0,lst)::tl -> (tl, x, y, dir)
| For(i,lst)::tl -> ((lst @ (For(i-1,lst)::tl)), x, y, dir)
in
let rec loop movelist x y dir acc =
if ([] = movelist)
then acc
else let (newlst,newx,newy,newdir) = interpSmallStep movelist x y dir in
if ((newx <> x) || (newy <> y))
# # # # # # # # # # # # # # # # # # # #
loop newlst newx newy newdir ((newx,newy)::acc)
# # # # # # # # # # # # # # # # # # # # # # # # #
loop newlst x y newdir acc
in
List.rev (loop movelist 0.0 0.0 0.0 [(0.0,0.0)])
(*** part e ***)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
###############################################################################
##################################################################
#############################################################################
###############################################################################
######################
##
################################################################################
##############################################################################
###########################################################################
###########################
##
###########################################################################
##
#############################################################################
###########################################################################
#######################################################################
###########################################################################
*)
(*** part f ***)
let rec interpTrans movelist : float->float->float-> (float * float) list * float=
let move_with_trace x y d restFun =
let (mvList, newDir) = restFun x y d in
(((x,y)::mvList),newDir) in
let move_without_trace x y d restFun =
let (mvList, newDir) = restFun x y d in
(mvList,newDir) in
let compose f1 f2 = fun x y d ->
let (mvList, myDir) = f1 x y d in
match mvList with
[] -> f2 x y myDir
| lst -> let (mvList2, newDir) = f2
(fst (List.nth lst ((List.length lst)-1)))
(snd (List.nth lst ((List.length lst)-1)))
myDir in
((mvList @ mvList2), newDir)
in
match movelist with
[] -> (fun _ _ d -> ([], d))
| Home::tl -> let f1 = interpTrans tl in
(fun _ _ _ -> move_with_trace 0.0 0.0 0.0 f1)
| Forward(f)::tl -> let f1 = interpTrans tl in
(fun x y d ->
let myX = forwardX x d f in
let myY = forwardY y d f in
move_with_trace myX myY d f1)
| Turn(f)::tl -> let f1 = interpTrans tl in
(fun x y d ->
let myD = turnD d f in
move_without_trace x y myD f1)
| For(n,body)::tl -> let f1 = interpTrans body in
let f2 = interpTrans tl in
(fun x y d ->
let rec loop i =
# # # # # # # # # # # # # # # #
then f2
else compose f1 (loop (i-1)) in
move_without_trace x y d (loop n))
(*** possibly helpful testing code ***)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
let example_logo_prog = [makePoly 10 1.0]
let ansL = interpLarge example_logo_prog
let ansS = interpSmall example_logo_prog
let ansI = (0.0,0.0)::(fst ((interpTrans example_logo_prog) 0.0 0.0 0.0))
let _ =
let compare_float_pairs acc x y =
(acc &&
((abs_float (fst x -. fst y)) < 0.0001) &&
((abs_float (snd x -. snd y)))) in
if ((List.fold_left2 compare_float_pairs true ansL ansS) &&
(List.fold_left2 compare_float_pairs true ansS ansI))
then print_string "Match!\n"
else print_string "Mismatch!\n"
let rec pr lst =
match lst with
[] -> ()
| (x,y)::tl ->
print_string("(" ^ (string_of_float x) ^ "," ^ (string_of_float y) ^ ")");
pr tl
let _ =
pr ansL; print_newline ();
pr ansS; print_newline ();
pr ansI; print_newline ();
| null | https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/features/data/seminal/20060324-22%3A24%3A46-8ab05dd4986d17d763e509d04ea02fde.seminal.ml | ocaml | ** part a **
** part b **
** part c **
** part d **
** part e **
** part f **
** possibly helpful testing code ** |
# # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # #
#################
#####################
################
*)
exception Unimplemented
exception AlreadyDone
let pi = 4.0 *. atan 1.0
type move = Home | Forward of float | Turn of float | For of (int * (move list))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
let makePoly sides len = For(sides, (Forward(len)::[Turn(2.0 *. pi /. float_of_int(sides))]))
# # # # # # # # # # # # # # # # # # #
let forwardX x d f = x +. (f *. cos d)
let forwardY y d f = y +. (f *. sin d)
let turnD d1 d2 = mod_float (d1 +. d2) (2.0 *. pi)
let interpLarge (movelist : move list) : (float*float) list =
let rec loop movelist x y dir acc =
match movelist with
[] -> acc
| Home::tl -> loop tl 0.0 0.0 0.0 ((0.0,0.0)::acc)
| Forward(f)::tl -> loop
tl
(forwardX x dir f)
(forwardY y dir f)
dir
(((forwardX x dir f), (forwardY y dir f))::acc)
| Turn(f)::tl -> loop
tl
x
y
(turnD dir f)
acc
| For(0,lst)::tl -> loop tl x y dir acc
| For(i,lst)::tl -> loop (lst @ (For(i-1, lst)::tl)) x y dir acc
in List.rev (loop movelist 0.0 0.0 0.0 [(0.0,0.0)])
let interpSmall (movelist : move list) : (float*float) list =
let interpSmallStep movelist x y dir : move list * float * float * float =
match movelist with
[] -> raise AlreadyDone
| Home::tl -> (tl, 0.0, 0.0, 0.0)
| Forward(f)::tl -> (tl, (forwardX x dir f), (forwardY y dir f), dir)
| Turn(f)::tl -> (tl, x, y, turnD dir f)
| For(0,lst)::tl -> (tl, x, y, dir)
| For(i,lst)::tl -> ((lst @ (For(i-1,lst)::tl)), x, y, dir)
in
let rec loop movelist x y dir acc =
if ([] = movelist)
then acc
else let (newlst,newx,newy,newdir) = interpSmallStep movelist x y dir in
if ((newx <> x) || (newy <> y))
# # # # # # # # # # # # # # # # # # # #
loop newlst newx newy newdir ((newx,newy)::acc)
# # # # # # # # # # # # # # # # # # # # # # # # #
loop newlst x y newdir acc
in
List.rev (loop movelist 0.0 0.0 0.0 [(0.0,0.0)])
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
###############################################################################
##################################################################
#############################################################################
###############################################################################
######################
##
################################################################################
##############################################################################
###########################################################################
###########################
##
###########################################################################
##
#############################################################################
###########################################################################
#######################################################################
###########################################################################
*)
let rec interpTrans movelist : float->float->float-> (float * float) list * float=
let move_with_trace x y d restFun =
let (mvList, newDir) = restFun x y d in
(((x,y)::mvList),newDir) in
let move_without_trace x y d restFun =
let (mvList, newDir) = restFun x y d in
(mvList,newDir) in
let compose f1 f2 = fun x y d ->
let (mvList, myDir) = f1 x y d in
match mvList with
[] -> f2 x y myDir
| lst -> let (mvList2, newDir) = f2
(fst (List.nth lst ((List.length lst)-1)))
(snd (List.nth lst ((List.length lst)-1)))
myDir in
((mvList @ mvList2), newDir)
in
match movelist with
[] -> (fun _ _ d -> ([], d))
| Home::tl -> let f1 = interpTrans tl in
(fun _ _ _ -> move_with_trace 0.0 0.0 0.0 f1)
| Forward(f)::tl -> let f1 = interpTrans tl in
(fun x y d ->
let myX = forwardX x d f in
let myY = forwardY y d f in
move_with_trace myX myY d f1)
| Turn(f)::tl -> let f1 = interpTrans tl in
(fun x y d ->
let myD = turnD d f in
move_without_trace x y myD f1)
| For(n,body)::tl -> let f1 = interpTrans body in
let f2 = interpTrans tl in
(fun x y d ->
let rec loop i =
# # # # # # # # # # # # # # # #
then f2
else compose f1 (loop (i-1)) in
move_without_trace x y d (loop n))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
let example_logo_prog = [makePoly 10 1.0]
let ansL = interpLarge example_logo_prog
let ansS = interpSmall example_logo_prog
let ansI = (0.0,0.0)::(fst ((interpTrans example_logo_prog) 0.0 0.0 0.0))
let _ =
let compare_float_pairs acc x y =
(acc &&
((abs_float (fst x -. fst y)) < 0.0001) &&
((abs_float (snd x -. snd y)))) in
if ((List.fold_left2 compare_float_pairs true ansL ansS) &&
(List.fold_left2 compare_float_pairs true ansS ansI))
then print_string "Match!\n"
else print_string "Mismatch!\n"
let rec pr lst =
match lst with
[] -> ()
| (x,y)::tl ->
print_string("(" ^ (string_of_float x) ^ "," ^ (string_of_float y) ^ ")");
pr tl
let _ =
pr ansL; print_newline ();
pr ansS; print_newline ();
pr ansI; print_newline ();
|
7ae15f77a5aa6651f6e99dc40408821d16807bb7a964d3fb506fb129ef7f3525 | shayne-fletcher/zen | print_utils.ml | let string_of_set f fold s =
let f i acc = (f i) :: acc in
"[" ^ String.concat "," (List.rev (fold f s [])) ^ "]"
let string_of_list f l =
"[" ^ String.concat ";" (List.map f l) ^ "]"
let string_of_array f arr =
"[|" ^ String.concat ";" (List.map f (Array.to_list arr)) ^ "|]"
| null | https://raw.githubusercontent.com/shayne-fletcher/zen/10a1d0b9bf261bb133918dd62fb1593c3d4d21cb/ocaml/regexp/print_utils.ml | ocaml | let string_of_set f fold s =
let f i acc = (f i) :: acc in
"[" ^ String.concat "," (List.rev (fold f s [])) ^ "]"
let string_of_list f l =
"[" ^ String.concat ";" (List.map f l) ^ "]"
let string_of_array f arr =
"[|" ^ String.concat ";" (List.map f (Array.to_list arr)) ^ "|]"
| |
ef8d77e1909311cda3f89f27791040e264e6138c90bfe0be8eda1e62fcf99ef6 | sellout/haskerwaul | One.hs | # language UndecidableSuperClasses #
module Haskerwaul.Field.Totalized.One
( module Haskerwaul.Field.Totalized.One
-- * extended modules
, module Haskerwaul.Field.Totalized
, module Haskerwaul.Meadow.NonInvolutive
) where
import Haskerwaul.Field.Totalized
import Haskerwaul.Meadow.NonInvolutive
class (NonInvolutiveMeadow c t a, TotalizedField c t a) =>
OneTotalizedField c t a
| null | https://raw.githubusercontent.com/sellout/haskerwaul/cf54bd7ce5bf4f3d1fd0d9d991dc733785b66a73/src/Haskerwaul/Field/Totalized/One.hs | haskell | * extended modules | # language UndecidableSuperClasses #
module Haskerwaul.Field.Totalized.One
( module Haskerwaul.Field.Totalized.One
, module Haskerwaul.Field.Totalized
, module Haskerwaul.Meadow.NonInvolutive
) where
import Haskerwaul.Field.Totalized
import Haskerwaul.Meadow.NonInvolutive
class (NonInvolutiveMeadow c t a, TotalizedField c t a) =>
OneTotalizedField c t a
|
4e5795cef2987eb1125275afac05f981d4af757a10c9001c630445c0a235f10b | apache/couchdb-rexi | rexi_server_sup.erl | Copyright 2010 Cloudant
%
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not
% use this file except in compliance with the License. You may obtain a copy of
% the License at
%
% -2.0
%
% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
% License for the specific language governing permissions and limitations under
% the License.
-module(rexi_server_sup).
-behaviour(supervisor).
-export([init/1]).
-export([start_link/1]).
start_link(Name) ->
supervisor:start_link({local, Name}, ?MODULE, []).
init([]) ->
{ok, {{one_for_one, 1, 1}, []}}.
| null | https://raw.githubusercontent.com/apache/couchdb-rexi/a327b7dbeb2b0050f7ca9072047bf8ef2d282833/src/rexi_server_sup.erl | erlang |
use this file except in compliance with the License. You may obtain a copy of
the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License. | Copyright 2010 Cloudant
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
-module(rexi_server_sup).
-behaviour(supervisor).
-export([init/1]).
-export([start_link/1]).
start_link(Name) ->
supervisor:start_link({local, Name}, ?MODULE, []).
init([]) ->
{ok, {{one_for_one, 1, 1}, []}}.
|
70e8cb50c564fe18862274a39bd8993a13833145147b1deb4377f1e179bf3daf | janestreet/email_message | email_lexer_state.mli | open Core
module State : sig
type t =
[ `Header (** Initial state, parsing headers *)
| `Content (** Parsing the body of the message. The details are in the body state. *)
| `Expected_eof (** The message should end here. If it doesn't, it's an error *)
]
val initial : [ `Header ]
end
module Content : sig
type t =
| Multipart of string list
| Octet_stream
val default : t
end
type t =
{ mutable state : State.t
; buf : Email_grammar.token Queue.t
}
val create : unit -> t
module Result : sig
type t =
{ new_state : State.t option
; tokens : Email_grammar.token list
}
end
val combine : t -> Result.t -> unit
val return : ?new_state:State.t -> Email_grammar.token list -> Result.t
val return_eof : Result.t
val return_error : string -> Result.t
module Error : sig
val unexpected_char : char -> string
val unexpected_eof : string
end
| null | https://raw.githubusercontent.com/janestreet/email_message/c88d38b850fce23bb5eb4f772211a4368324b1f7/src/email_lexer_state.mli | ocaml | * Initial state, parsing headers
* Parsing the body of the message. The details are in the body state.
* The message should end here. If it doesn't, it's an error | open Core
module State : sig
type t =
]
val initial : [ `Header ]
end
module Content : sig
type t =
| Multipart of string list
| Octet_stream
val default : t
end
type t =
{ mutable state : State.t
; buf : Email_grammar.token Queue.t
}
val create : unit -> t
module Result : sig
type t =
{ new_state : State.t option
; tokens : Email_grammar.token list
}
end
val combine : t -> Result.t -> unit
val return : ?new_state:State.t -> Email_grammar.token list -> Result.t
val return_eof : Result.t
val return_error : string -> Result.t
module Error : sig
val unexpected_char : char -> string
val unexpected_eof : string
end
|
e96da48af6aebf76b08e3b3af7dabf7a185e27d1a22e8ad3a63bc17a7b3f472e | Soonad/Formality-Haskell | SimplerCore.hs | module SimplerCore where
type Name = String
data Term
= Var Int
| Typ
| Val Int
| Num
| Lam Name Term Term
| App Term Term
| All Name Term Term
| Mu Name Term
| Any -- Type of any term
| Rec Int
| Slf Name Term
deriving (Eq, Show, Ord)
hasFreeVar :: Term -> Int -> Bool
hasFreeVar term n = case term of
Var i -> i == n
All _ h b -> hasFreeVar h n || hasFreeVar b (n + 1)
Lam _ h b -> hasFreeVar h n || hasFreeVar b (n + 1)
App f a -> hasFreeVar f n || hasFreeVar a n
Slf _ t -> hasFreeVar t (n + 1)
Mu _ t -> hasFreeVar t n
_ -> False
pretty t = putStrLn $ go t [] []
where
go :: Term -> [String] -> [String] -> String
go t vs rs = case t of
Var i -> if i < length vs then vs !! i else concat ["^", show i]
Rec i -> if i < length rs then rs !! i else concat ["#", show i]
Typ -> "Type"
All n h@Typ b -> concat ["∀(", n, "). ", go b (n : vs) rs]
All n h@(All _ _ _) b -> if hasFreeVar b 0 then concat ["(", n, " : ", go h vs rs, ") -> ", go b (n : vs) rs] else concat ["(", go h vs rs, ") -> ", go b (n : vs) rs]
All n h b -> if hasFreeVar b 0 then concat ["(", n, " : ", go h vs rs, ") -> ", go b (n : vs) rs] else concat [go h vs rs, " -> ", go b (n : vs) rs]
Lam n h@Any b@(Lam _ _ _) -> concat ["(", n, ", ", tail $ go b (n : vs) rs]
Lam n h@Any b -> concat ["(", n, ") => ", go b (n : vs) rs]
Lam n h b@(Lam _ _ _) -> concat ["(", n, " : ", go h vs rs, ", ", tail $ go b (n : vs) rs]
Lam n h b -> concat ["(", n, " : ", go h vs rs, ") => ", go b (n : vs) rs]
App f@(App _ _) a ->
concat [init $ go f vs rs, " ", go a vs rs, ")"]
App f@(Lam _ _ _) a ->
concat ["((", go f vs rs, ") " , go a vs rs, ")"]
App f@(Mu _ _) a ->
concat ["((", go f vs rs, ") " , go a vs rs, ")"]
App f a -> concat ["(", go f vs rs, " ", go a vs rs, ")"]
Slf n t -> concat ["${", n, "} (", go t (n : vs) rs, ")"]
Mu n t -> concat ["μ(", n, "). ", go t vs (n : rs)]
Num -> "Number"
Val i -> show i
Any -> "Any"
shiftVar :: Term -> Int -> Int -> Term
shiftVar term inc dep = case term of
Var i -> Var (if i < dep then i else (i + inc))
All n h b -> All n (shiftVar h inc dep) (shiftVar b inc (dep + 1))
Lam n h b -> Lam n (shiftVar h inc dep) (shiftVar b inc (dep + 1))
App f a -> App (shiftVar f inc dep) (shiftVar a inc dep)
Slf n t -> Slf n (shiftVar t inc (dep + 1))
Mu n t -> Mu n (shiftVar t inc dep)
x -> x
shiftRec :: Term -> Int -> Int -> Term
shiftRec term inc dep = case term of
Lam n h b -> Lam n (shiftRec h inc dep) (shiftRec b inc dep)
All n h b -> All n (shiftRec h inc dep) (shiftRec b inc dep)
App f a -> App (shiftRec f inc dep) (shiftRec a inc dep)
Mu n t -> Mu n (shiftRec t inc (dep + 1))
Slf n t -> Slf n (shiftRec t inc dep)
Rec i -> Rec (if i < dep then i else (i + inc))
x -> x
substVar :: Term -> Term -> Int -> Term
substVar term v dep = case term of
Var i -> if i == dep then v else Var (i - if i > dep then 1 else 0)
All n h b -> All n (substVar h v dep) (substVar b vV (dep + 1))
Lam n h b -> Lam n (substVar h v dep) (substVar b vV (dep + 1))
App f a -> App (substVar f v dep) (substVar a v dep)
Mu n t -> Mu n (substVar t vR dep)
Slf n t -> Slf n (substVar t vV (dep + 1))
x -> x
where
vV = shiftVar v 1 0
vR = shiftRec v 1 0
substRec :: Term -> Term -> Int -> Term
substRec term v dep = case term of
All n h b -> All n (substRec h v dep) (substRec b vV dep)
Lam n h b -> Lam n (substRec h v dep) (substRec b vV dep)
App f a -> App (substRec f v dep) (substRec a v dep)
Mu n t -> Mu n (substRec t vR (dep + 1))
Slf n t -> Slf n (substRec t vV dep)
Rec i -> if i == dep then v else Rec (i - if i > dep then 1 else 0)
x -> x
where
vV = shiftVar v 1 0
vR = shiftRec v 1 0
maxFreeVar :: Term -> Int
maxFreeVar term = go term 0 where
go term n = case term of
Var i -> if i < n then 0 else i-n
All _ h b -> go h n `max` go b (n + 1)
Lam _ h b -> go h n `max` go b (n + 1)
App f a -> go f n `max` go a n
Slf _ t -> go t (n + 1)
Mu _ t -> go t n
_ -> 0
substManyVar :: Term -> [Term] -> Int -> Term
substManyVar t vals d = go t vals d 0
where
l = length vals - 1
go t (v:vs) d i =
go (substVar t (shiftVar v (l - i) 0) (d + l - i)) vs d (i + 1)
go t [] d i = t
eval :: Term -> Term
eval term = case term of
All n h b -> All n (eval h) (eval b)
Lam n h b -> Lam n (eval h) (eval b)
App f a ->
let a' = eval a
in case eval f of
Lam _ _ b -> eval (substVar b a' 0)
f -> App f a'
Mu n t -> Mu n (eval t)
Slf n t -> Slf n (eval t)
_ -> term
unroll :: Term -> Term
unroll term = case term of
All n h b -> All n (unroll h) (unroll b)
Lam n h b -> Lam n (unroll h) (unroll b)
App f a -> App (unroll f) (unroll a)
Mu n t -> substRec t (Mu n t) 0
Slf n t -> Slf n (unroll t)
_ -> term
contractibleSubst :: Term -> Int -> Bool
contractibleSubst t n = case t of
Var i -> i /= n
Mu _ t -> contractibleSubst t (n + 1)
Lam _ _ _ -> False
App _ _ -> False
_ -> True
The and App cases could potentially be , instead
_ t b - > contractibleSubst t n || contractibleSubst b ( n + 1 )
-- App f a -> contractibleSubst f n || contractibleSubst a n
However , a contractible term T would lose the useful property that if it is normalized , then is also normalized ,
for any power n , where means substitute variable 0 in T by itself n times , that is ,
` T^0 = Var 0 ` and ` T^(n+1 ) = subst T 0 ` . This means in particular that if T is contractible ,
-- then `Mu "X" T` is normalized no matter how many times we unroll it.
Examples of substitutions which are not contractible when you consider evaluation of terms , which rule out ` Lam ` and ` App ` as guards for recursion
notcontractible1 = Mu "X" (Lam "a" Typ (App (Rec 0) (Var 0)))
notcontractible2 = Mu "X" (App (Lam "a" Typ (Var 0)) (Rec 0))
isBohmRec :: Term -> Int -> Bool
isBohmRec t n = case t of
Var i -> i /= n
Mu _ t -> isBohmRec t (n + 1)
_ -> True
isBohm :: Term -> Bool
isBohm t = case t of
App f a -> isBohm f && isBohm a
Lam _ h b -> isBohm h && isBohm b
All _ h b -> isBohm h && isBohm b
Mu _ t -> isBohmRec t 0 && isBohm t
Slf _ t -> isBohm t
_ -> True
evalBohm :: Term -> Term
evalBohm term = case term of
All n h b -> All n (evalBohm h) (evalBohm b)
Lam n h b -> Lam n (evalBohm h) (evalBohm b)
App f a -> case (evalBohm f, evalBohm a) of
(Mu n t@(Lam _ _ _), Var i) -> App (Mu n t) (Var i)
(Mu n t@(Lam _ _ _), Rec i) -> App (Mu n t) (Rec i)
(Mu n t@(Lam _ _ _), a') -> evalBohm $ App (substRec t (Mu n t) 0) a'
(Lam _ _ b, a') -> evalBohm (substVar b a' 0)
(f', a') -> App f' a'
Mu n t -> Mu n (evalBohm t)
Slf n t -> Slf n (evalBohm t)
_ -> term
-- Examples of evaluation
zero = Lam "Z" Any (Lam "S" Any (Var 1))
suc = Lam "n" Any (Lam "Z" Any (Lam "S" Any (App (Var 0) (Var 2))))
double = Mu "double" $ Lam "n" Any $ App (App (Var 0) zero) $ Lam "x" Any $ App suc $ App suc $ App (Rec 0) (Var 0)
double' = Lam "n" Any $ App (App (Var 0) zero) $ Mu "Rec" $ Lam "x" Any $ App suc $ App suc $ App (App (Var 0) zero) (Rec 0)
two = evalBohm $ App double $ App suc zero
four = evalBohm $ App double two
| null | https://raw.githubusercontent.com/Soonad/Formality-Haskell/c2aebe3daeb1031399fd33986729722906520e89/src/SimplerCore.hs | haskell | Type of any term
App f a -> contractibleSubst f n || contractibleSubst a n
then `Mu "X" T` is normalized no matter how many times we unroll it.
Examples of evaluation | module SimplerCore where
type Name = String
data Term
= Var Int
| Typ
| Val Int
| Num
| Lam Name Term Term
| App Term Term
| All Name Term Term
| Mu Name Term
| Rec Int
| Slf Name Term
deriving (Eq, Show, Ord)
hasFreeVar :: Term -> Int -> Bool
hasFreeVar term n = case term of
Var i -> i == n
All _ h b -> hasFreeVar h n || hasFreeVar b (n + 1)
Lam _ h b -> hasFreeVar h n || hasFreeVar b (n + 1)
App f a -> hasFreeVar f n || hasFreeVar a n
Slf _ t -> hasFreeVar t (n + 1)
Mu _ t -> hasFreeVar t n
_ -> False
pretty t = putStrLn $ go t [] []
where
go :: Term -> [String] -> [String] -> String
go t vs rs = case t of
Var i -> if i < length vs then vs !! i else concat ["^", show i]
Rec i -> if i < length rs then rs !! i else concat ["#", show i]
Typ -> "Type"
All n h@Typ b -> concat ["∀(", n, "). ", go b (n : vs) rs]
All n h@(All _ _ _) b -> if hasFreeVar b 0 then concat ["(", n, " : ", go h vs rs, ") -> ", go b (n : vs) rs] else concat ["(", go h vs rs, ") -> ", go b (n : vs) rs]
All n h b -> if hasFreeVar b 0 then concat ["(", n, " : ", go h vs rs, ") -> ", go b (n : vs) rs] else concat [go h vs rs, " -> ", go b (n : vs) rs]
Lam n h@Any b@(Lam _ _ _) -> concat ["(", n, ", ", tail $ go b (n : vs) rs]
Lam n h@Any b -> concat ["(", n, ") => ", go b (n : vs) rs]
Lam n h b@(Lam _ _ _) -> concat ["(", n, " : ", go h vs rs, ", ", tail $ go b (n : vs) rs]
Lam n h b -> concat ["(", n, " : ", go h vs rs, ") => ", go b (n : vs) rs]
App f@(App _ _) a ->
concat [init $ go f vs rs, " ", go a vs rs, ")"]
App f@(Lam _ _ _) a ->
concat ["((", go f vs rs, ") " , go a vs rs, ")"]
App f@(Mu _ _) a ->
concat ["((", go f vs rs, ") " , go a vs rs, ")"]
App f a -> concat ["(", go f vs rs, " ", go a vs rs, ")"]
Slf n t -> concat ["${", n, "} (", go t (n : vs) rs, ")"]
Mu n t -> concat ["μ(", n, "). ", go t vs (n : rs)]
Num -> "Number"
Val i -> show i
Any -> "Any"
shiftVar :: Term -> Int -> Int -> Term
shiftVar term inc dep = case term of
Var i -> Var (if i < dep then i else (i + inc))
All n h b -> All n (shiftVar h inc dep) (shiftVar b inc (dep + 1))
Lam n h b -> Lam n (shiftVar h inc dep) (shiftVar b inc (dep + 1))
App f a -> App (shiftVar f inc dep) (shiftVar a inc dep)
Slf n t -> Slf n (shiftVar t inc (dep + 1))
Mu n t -> Mu n (shiftVar t inc dep)
x -> x
shiftRec :: Term -> Int -> Int -> Term
shiftRec term inc dep = case term of
Lam n h b -> Lam n (shiftRec h inc dep) (shiftRec b inc dep)
All n h b -> All n (shiftRec h inc dep) (shiftRec b inc dep)
App f a -> App (shiftRec f inc dep) (shiftRec a inc dep)
Mu n t -> Mu n (shiftRec t inc (dep + 1))
Slf n t -> Slf n (shiftRec t inc dep)
Rec i -> Rec (if i < dep then i else (i + inc))
x -> x
substVar :: Term -> Term -> Int -> Term
substVar term v dep = case term of
Var i -> if i == dep then v else Var (i - if i > dep then 1 else 0)
All n h b -> All n (substVar h v dep) (substVar b vV (dep + 1))
Lam n h b -> Lam n (substVar h v dep) (substVar b vV (dep + 1))
App f a -> App (substVar f v dep) (substVar a v dep)
Mu n t -> Mu n (substVar t vR dep)
Slf n t -> Slf n (substVar t vV (dep + 1))
x -> x
where
vV = shiftVar v 1 0
vR = shiftRec v 1 0
substRec :: Term -> Term -> Int -> Term
substRec term v dep = case term of
All n h b -> All n (substRec h v dep) (substRec b vV dep)
Lam n h b -> Lam n (substRec h v dep) (substRec b vV dep)
App f a -> App (substRec f v dep) (substRec a v dep)
Mu n t -> Mu n (substRec t vR (dep + 1))
Slf n t -> Slf n (substRec t vV dep)
Rec i -> if i == dep then v else Rec (i - if i > dep then 1 else 0)
x -> x
where
vV = shiftVar v 1 0
vR = shiftRec v 1 0
maxFreeVar :: Term -> Int
maxFreeVar term = go term 0 where
go term n = case term of
Var i -> if i < n then 0 else i-n
All _ h b -> go h n `max` go b (n + 1)
Lam _ h b -> go h n `max` go b (n + 1)
App f a -> go f n `max` go a n
Slf _ t -> go t (n + 1)
Mu _ t -> go t n
_ -> 0
substManyVar :: Term -> [Term] -> Int -> Term
substManyVar t vals d = go t vals d 0
where
l = length vals - 1
go t (v:vs) d i =
go (substVar t (shiftVar v (l - i) 0) (d + l - i)) vs d (i + 1)
go t [] d i = t
eval :: Term -> Term
eval term = case term of
All n h b -> All n (eval h) (eval b)
Lam n h b -> Lam n (eval h) (eval b)
App f a ->
let a' = eval a
in case eval f of
Lam _ _ b -> eval (substVar b a' 0)
f -> App f a'
Mu n t -> Mu n (eval t)
Slf n t -> Slf n (eval t)
_ -> term
unroll :: Term -> Term
unroll term = case term of
All n h b -> All n (unroll h) (unroll b)
Lam n h b -> Lam n (unroll h) (unroll b)
App f a -> App (unroll f) (unroll a)
Mu n t -> substRec t (Mu n t) 0
Slf n t -> Slf n (unroll t)
_ -> term
contractibleSubst :: Term -> Int -> Bool
contractibleSubst t n = case t of
Var i -> i /= n
Mu _ t -> contractibleSubst t (n + 1)
Lam _ _ _ -> False
App _ _ -> False
_ -> True
The and App cases could potentially be , instead
_ t b - > contractibleSubst t n || contractibleSubst b ( n + 1 )
However , a contractible term T would lose the useful property that if it is normalized , then is also normalized ,
for any power n , where means substitute variable 0 in T by itself n times , that is ,
` T^0 = Var 0 ` and ` T^(n+1 ) = subst T 0 ` . This means in particular that if T is contractible ,
Examples of substitutions which are not contractible when you consider evaluation of terms , which rule out ` Lam ` and ` App ` as guards for recursion
notcontractible1 = Mu "X" (Lam "a" Typ (App (Rec 0) (Var 0)))
notcontractible2 = Mu "X" (App (Lam "a" Typ (Var 0)) (Rec 0))
isBohmRec :: Term -> Int -> Bool
isBohmRec t n = case t of
Var i -> i /= n
Mu _ t -> isBohmRec t (n + 1)
_ -> True
isBohm :: Term -> Bool
isBohm t = case t of
App f a -> isBohm f && isBohm a
Lam _ h b -> isBohm h && isBohm b
All _ h b -> isBohm h && isBohm b
Mu _ t -> isBohmRec t 0 && isBohm t
Slf _ t -> isBohm t
_ -> True
evalBohm :: Term -> Term
evalBohm term = case term of
All n h b -> All n (evalBohm h) (evalBohm b)
Lam n h b -> Lam n (evalBohm h) (evalBohm b)
App f a -> case (evalBohm f, evalBohm a) of
(Mu n t@(Lam _ _ _), Var i) -> App (Mu n t) (Var i)
(Mu n t@(Lam _ _ _), Rec i) -> App (Mu n t) (Rec i)
(Mu n t@(Lam _ _ _), a') -> evalBohm $ App (substRec t (Mu n t) 0) a'
(Lam _ _ b, a') -> evalBohm (substVar b a' 0)
(f', a') -> App f' a'
Mu n t -> Mu n (evalBohm t)
Slf n t -> Slf n (evalBohm t)
_ -> term
zero = Lam "Z" Any (Lam "S" Any (Var 1))
suc = Lam "n" Any (Lam "Z" Any (Lam "S" Any (App (Var 0) (Var 2))))
double = Mu "double" $ Lam "n" Any $ App (App (Var 0) zero) $ Lam "x" Any $ App suc $ App suc $ App (Rec 0) (Var 0)
double' = Lam "n" Any $ App (App (Var 0) zero) $ Mu "Rec" $ Lam "x" Any $ App suc $ App suc $ App (App (Var 0) zero) (Rec 0)
two = evalBohm $ App double $ App suc zero
four = evalBohm $ App double two
|
5102f4e17989af158dc29c5215d8bc46ec9f40a64f9e1cc85ffefe618df8cb8a | pascal-knodel/haskell-craft | E'3'19.hs | --
--
--
-----------------
Exercise 3.19 .
-----------------
--
--
--
module E'3'19 where
romanDigit :: Char -> String
romanDigit aChar
| '1' == aChar = "I"
| '2' == aChar = "II"
| '3' == aChar = "III"
| '4' == aChar = "IV"
| '5' == aChar = "V"
| '6' == aChar = "VI"
| '7' == aChar = "VII"
| '8' == aChar = "VIII"
| '9' == aChar = "IX"
| otherwise = error "Characters that don't represent a number from 1 to 10\
\can't be expressed in Roman numerals."
| null | https://raw.githubusercontent.com/pascal-knodel/haskell-craft/c03d6eb857abd8b4785b6de075b094ec3653c968/_/links/E'3'19.hs | haskell |
---------------
---------------
| Exercise 3.19 .
module E'3'19 where
romanDigit :: Char -> String
romanDigit aChar
| '1' == aChar = "I"
| '2' == aChar = "II"
| '3' == aChar = "III"
| '4' == aChar = "IV"
| '5' == aChar = "V"
| '6' == aChar = "VI"
| '7' == aChar = "VII"
| '8' == aChar = "VIII"
| '9' == aChar = "IX"
| otherwise = error "Characters that don't represent a number from 1 to 10\
\can't be expressed in Roman numerals."
|
07e0c8bcc40bef0f47e24bdd72b3af9822760a0ebb4e77dfb846027591c81bba | amitnh/Erlang-Final-Batman | moveSimulator.erl | %%%-------------------------------------------------------------------
@author amit and kapelnik
( C ) 2020 , < COMPANY >
%%% @doc
%%%
%%% @end
Created : 01 . Aug 2020 12:36 PM
%%%-------------------------------------------------------------------
-module(moveSimulator).
-author("amit and kapelnik").
-behaviour(gen_server).
%% API
-export([start_link/1]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, getPidsInCircle/5,
code_change/3, castPlease/1, robinsInRadiusForRemote/3]).
-define(SERVER, ?MODULE).
-define(updateEts ,20). %how many time per second to update the ETS's
-define(velMax , 30 ) . % range of the random velocity of the node in meter / milisec
range of the random time to change direction of the node in milisec
-define(radius , 300 ) .
-record(moveSimulator_state, {startX,endX,startY,endY,demiZone,radius,velMax,myX,myY,time,velocity,direction,myBatman,pcPid,tokill}).
test TODO delete
castPlease(MSG)-> gen_server:cast({global, tal@ubuntu},{test,MSG}).
%%%===================================================================
%%% API
%%%===================================================================
%% @doc Spawns the server and registers the local name (unique)
-spec(start_link(List::term()) ->
{ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
start_link([Area,Specs,PCPid]) ->
{ok,Pid} = gen_server:start_link( ?MODULE, [Area,Specs,PCPid,{0,0,0,0}], []),%{debug,[trace]}
Pid1 = spawn(fun()->etsTimer(Pid) end) ,
Pid2 = spawn(fun()->vectorTimer(Pid,Specs) end),
gen_server:cast(Pid,{tokillonshutdown,[Pid1,Pid2]});
%if a batman is switching computer
start_link([Area,Specs,PCPid,{X,Y,Dir,Vel}]) ->
{ok,Pid} = gen_server:start_link( ?MODULE, [Area,Specs,PCPid,{X,Y,Dir,Vel}], []),%{debug,[trace]}
Pid1 = spawn_link(fun()->etsTimer(Pid) end),
Pid2 = spawn_link(fun()->vectorTimer(Pid,Specs) end),
gen_server:cast(PCPid,{monitorMe,Pid}),
gen_server:cast(Pid,{tokillonshutdown,[Pid1,Pid2]}).
send a cast to update the main ets 's every ?
time to wait for sending ? updateEts msgs in 1 sec
receive
_-> castPlease({etsTimerTerminating}) , exit(normal)
after TimeToWait ->
gen_server:cast(Pid,{updateEts}),
etsTimer(Pid)
end.
update the random velocity , direction and updatetime to update
vectorTimer(Pid,Specs)->
{_Radius,_NumofRobins, _DemiZone,_OGMTime,MaxVelocity,_WindowSize,_TTL} = Specs,
{Min,Max} = ?timeRange,
TimeToWait = Min + rand:uniform(Max-Min),
receive
_-> castPlease(vectortimerTerminating), exit(normal)
after TimeToWait ->
this 3 are going to the vector ( in the record ):
CurrTime = erlang:system_time(millisecond),
Velocity = rand:uniform(MaxVelocity*1000)/1000,
Direction = rand:uniform(360), % in degrees
gen_server:cast(Pid,{updateMovementVector,CurrTime,Velocity,Direction}),
vectorTimer(Pid,Specs)
end .
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
@private
%% @doc Initializes the server
-spec(init(Args :: term()) ->
{ok, State :: #moveSimulator_state{}} | {ok, State :: #moveSimulator_state{}, timeout() | hibernate} |
{stop, Reason :: term()} | ignore).
init([{StartX , EndX , StartY , EndY},DemiZone , PCPid ] ) - >
{ ok , } = : start_link(self ( ) ) , % creates and link it to this process
%% {X,Y} = startLocation(StartX,EndX,StartY,EndY), % put my new random location in the etsX and etsY
{ ok , # moveSimulator_state{startX = StartX , endX = EndX , startY = StartY , endY = EndY ,
demiZone = DemiZone , , myY = Y , time = erlang : system_time(millisecond),velocity=0,direction=0,myBatman , pcPid = PCPid } } ;
%if a batman is switching computer with specific X,Y locations
init([{StartX,EndX,StartY,EndY},{Radius,_NumofRobins,DemiZone,OGMTime,MaxVelocity,WindowSize,TTL},PCPid,{X,Y,Dir,Vel}]) ->
creates and link it to this process
if( {X,Y,Dir,Vel} == {0,0,0,0} )->%%initiating field
{Xnew,Ynew} = startLocation(StartX,EndX,StartY,EndY), % put my new random location in the etsX and etsY
{ok, #moveSimulator_state{startX = StartX,endX = EndX,startY = StartY,endY = EndY,
demiZone = DemiZone,radius = Radius,velMax = MaxVelocity, myX = Xnew,myY = Ynew,time = erlang:system_time(millisecond),velocity=0,direction=0,myBatman = MyBatman,pcPid = PCPid}};
true -> %receiving a new batman from another computer
ListX = listToUpdate(ets:lookup(etsX,X),X),
ListY = listToUpdate(ets:lookup(etsY,Y),Y),
ets:insert(etsX,ListX),
ets:insert(etsY,ListY),
{ok, #moveSimulator_state{startX = StartX,endX = EndX,startY = StartY,endY = EndY,
demiZone = DemiZone,radius = Radius,velMax = MaxVelocity, myX = X,myY = Y,time = erlang:system_time(millisecond),velocity=Vel,direction=Dir,myBatman = MyBatman,pcPid = PCPid}}
end;
init(_A)-> castPlease({initMovSimError,_A}).
%%---------------------------------------------------------------------------------------------------
startLocation , insert a new location in the etsX and etsY maps
startLocation(StartX,EndX,StartY,EndY)->
returns a random integer in the computer Area
LocationY = StartY + rand:uniform(EndY-StartY),
ListX = listToUpdate(ets:lookup(etsX,LocationX),LocationX),
ListY = listToUpdate(ets:lookup(etsY,LocationY),LocationY),
ets:insert(etsX,ListX),
ets:insert(etsY,ListY),
{LocationX,LocationY}. %return {X,Y} value
checks if the i m the first one on that list in the ETS or not .
%the ETS is build like this: [{Location1,[pid1,pid2...]},{Location2,[pid1,pid2...]},....]
listToUpdate([],Location)-> [{Location,[self()]}];
listToUpdate([{Location,List}],_Location)->[{Location,List ++ [self()]}].
%%---------------------------------------------------------------------------------------------------
%% calculate the new locations of X and Y based on the random vector
%%---------------------------------------------------------------------------------------------------
updatedXYlocations(State)->
X0 = State#moveSimulator_state.myX,
Y0 = State#moveSimulator_state.myY,
Vel = State#moveSimulator_state.velocity,
Dir = State#moveSimulator_state.direction,
PCPid = State#moveSimulator_state.pcPid,
CurrTime = erlang:system_time(millisecond),
DeltaTime = CurrTime - State#moveSimulator_state.time,
StartX = State#moveSimulator_state.startX,
StartY = State#moveSimulator_state.startY,
EndX = State#moveSimulator_state.endX,
EndY = State#moveSimulator_state.endY,
DemilitarizedZone = State#moveSimulator_state.demiZone,
x = vt , trigo
Y = Y0 + math:sin(Dir * math:pi() / 180)*Vel*DeltaTime/1000,
%boarders check:
if ((X < 0) or (X > 2000) or (Y < 0) or (Y > 2000)) ->
{X0,Y0,CurrTime,false};
true -> %if X or Y are out of bounds, need to check if theres a new border or if a terminate is necessary
if ((X>EndX+DemilitarizedZone) or (X<StartX-DemilitarizedZone) or (Y>EndY+DemilitarizedZone) or (Y<StartY-DemilitarizedZone)) ->
try %wait for the computerServer to bring back an answer about the borders
{NewStartX,NewEndX,NewStartY,NewEndY,ToTerminate} = gen_server:call(PCPid,{updateBorders,{round(X),round(Y),State#moveSimulator_state.direction,State#moveSimulator_state.velocity}}),
if ToTerminate ->ok;
%% gen_server:cast(self(),stop);
gen_server : stop(self());%Shut down MoveSimulator Server
gen_server : stop(self ( ) , { normal , round(X),round(Y)},infinity);%Shut down MoveSimulator Server
true -> gen_server:cast(self(),{updateBorders,NewStartX,NewEndX,NewStartY,NewEndY})
end, {X,Y,CurrTime,true}
catch _:_-> castPlease(innerConnectionError)
end;
true -> {X,Y,CurrTime,false}
end
end.
%%---------------------------------------------------------------------------------------------------
, startX = NewStartX , startY = NewStartY , endX = , endY =
@private
%% @doc Handling call messages
-spec(handle_call(Request :: term(), From :: {pid(), Tag :: term()},
State :: #moveSimulator_state{}) ->
{reply, Reply :: term(), NewState :: #moveSimulator_state{}} |
{reply, Reply :: term(), NewState :: #moveSimulator_state{}, timeout() | hibernate} |
{noreply, NewState :: #moveSimulator_state{}} |
{noreply, NewState :: #moveSimulator_state{}, timeout() | hibernate} |
{stop, Reason :: term(), Reply :: term(), NewState :: #moveSimulator_state{}} |
{stop, Reason :: term(), NewState :: #moveSimulator_state{}}).
handle_call({receiveMsg,To,Msg,MoveSimFrom}, {FromPid,_Ref}, State = #moveSimulator_state{}) ->
castPlease({receiveMsg , from , FromPid } ) ,
gen_server:cast(State#moveSimulator_state.pcPid,{msgSent, MoveSimFrom, {self(),node()}}),
if (To == {self(),node()}) -> castPlease(Msg); % case the msg is for me -> cast it
true-> gen_server:cast(self(),{sendMsg,To, {FromPid,node()},Msg}) % case the msg is not for me -> pass it on
end,
{reply, sent, State};
handle_call({getKnownFrom}, _From, State = #moveSimulator_state{}) ->
try
{PidTo,NodeTo} = gen_server:call(State#moveSimulator_state.myBatman,{getKnownFrom}),
{reply, {PidTo,NodeTo}, State}
catch _:_ -> {reply, {notfound,notfound}, State}
end;
handle_call(stop, _From, State = #moveSimulator_state{}) ->
{stop, normal, State};
handle_call(_Request, _From, State = #moveSimulator_state{}) ->
castPlease({missedCallMovSim, request, _Request, from, _From}),
{reply, ok, State}.
@private
%% @doc Handling cast messages
-spec(handle_cast(Request :: term(), State :: #moveSimulator_state{}) ->
{noreply, NewState :: #moveSimulator_state{}} |
{noreply, NewState :: #moveSimulator_state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #moveSimulator_state{}}).
% if i was close to the border, but the border changed, the computerServer will update us by sending
% updateArea cast msg, as following:
%%handle_cast({updateArea,NewArea}, _) -> todo later
{ noreply , # moveSimulator_state{myArea = NewArea } } ;
%%============================================================================================
send MSG to someone using the BATMAN Protocol
handle_cast({sendMsg,To,To,_Msg}, State = #moveSimulator_state{}) -> % case someone tell me to send Msg to myself
{noreply, State#moveSimulator_state{}};
handle_cast({tokillonshutdown,Pids}, State = #moveSimulator_state{}) -> %case the batman has no neighbors
{noreply, State#moveSimulator_state{tokill = Pids}};
handle_cast({sendMsg,To,From,Msg}, State = #moveSimulator_state{}) ->
castPlease({firstSendMsgMoveSimulator , to , To , from , From , msg , ) ,
MyBatman = State#moveSimulator_state.myBatman,
BestLink = gen_server:call(MyBatman, {findBestLink, To}),
%% castPlease({bestLink,BestLink}),
there where no problems , Best Link was found
{BestLinkPid,BestLinkNode}= BestLink,
Node = node(),
try %if the call fails
if
(From == BestLink) -> % im not sending the msg back to the one that sent it to me, infinite loop
1.delete the neighbor 2.send the msg again to the next best link
gen_server:cast(MyBatman, {deleteNeighbor, BestLink,To,Msg});
(Node == BestLinkNode) -> % if the node is in my pc send it to him directly
Reply = gen_server:call(BestLinkPid,{receiveMsg,To,Msg,{self(),node()}}),
if
(Reply == sent) ->ok;
{ noreply , State } ;
true-> % if neighbor didn't received the msg (Out Of Range / died for some reason) then
1.delete the neighbor 2.send the msg again to the next best link
gen_server:cast(MyBatman, {deleteNeighbor, BestLink,To,Msg}),
gen_server:cast(self(),{sendMsg,To,{self(),node()},Msg}),% send the MSG again
{noreply, State}
end;
{ noreply , State } ;
true -> % if the neighbor is on other computer and not the one that sent me the msg
PcPid = State#moveSimulator_state.pcPid,
Reply = gen_server:call(PcPid,{sendMsg,To,BestLink,Msg,{self(),node()}}),
if
(Reply == sent) -> ok;
{ noreply , State } ;
true-> % if neighbor didn't received the msg (Out Of Range / died for some reason) then
1.delete the neighbor 2.send the msg again to the next best link
gen_server:cast(MyBatman, {deleteNeighbor, BestLink,To,Msg}),
gen_server:cast(self(),{sendMsg,To,{self(),node()},Msg})% send the MSG again
{ noreply , State }
end
{ noreply , State }
end
catch % if Msg didn't sent
_:_-> % if neighbor didn't received the msg (Out Of Range / died for some reason) then
1.delete the neighbor 2.send the msg again to the next best link
gen_server:cast(MyBatman, {deleteNeighbor, BestLink,To,Msg})
end;
true-> ok %i dont know "To", cant reach him
end,
{noreply, State};
%=======================================================================================================
%%============================================================================================
handle_cast({updateBorders,NewStartX,NewEndX,NewStartY,NewEndY}, State = #moveSimulator_state{}) ->
%% castPlease(updateMovementVector),
{noreply, State#moveSimulator_state{startX = NewStartX,endX = NewEndX,startY = NewStartY,endY = NewEndY}};
handle_cast({updateMovementVector,CurrTime,Velocity,Direction}, State = #moveSimulator_state{}) ->
%% castPlease(updateMovementVector),
{noreply, State#moveSimulator_state{time = CurrTime,velocity = Velocity, direction = Direction}};
handle_cast({changeDir}, State = #moveSimulator_state{}) ->
Direction = State#moveSimulator_state.direction,
NewDirection = (0 - Direction),
{noreply, State#moveSimulator_state{direction = NewDirection}};
%updateEts updates the location of my PID in the etsX and etsY
handle_cast({updateEts}, State = #moveSimulator_state{}) ->
try
{X,Y,CurrTime,ToTerminate} = updatedXYlocations(State), %also checks if the borders are ok or should i terminate and move to another nearby PC
if ToTerminate -> {stop, normal, State};
true ->
X in ets is rounded . not in myX record
RoundedOldY = round(State#moveSimulator_state.myY),
try
[{_Keyx,Tempx}] = ets:lookup(etsX,RoundedOldX),
[{_Keyy,Tempy}] = ets:lookup(etsY,RoundedOldY),
if (length(Tempx)>0) ->
ListX= Tempx; %check if lookup is empty
true-> ListX =[]
end,
if (length(Tempy)>0) ->
ListY= Tempy;
true-> ListY =[]
end,
OldListX = ListX -- [self()],% remove the pid from the old location
OldListY = ListY -- [self()],
if (length(OldListX) > 0) -> ets:insert(etsX,[{RoundedOldX,OldListX}]);%put back the old Locations lists if not empty
true-> ets:delete(etsX,RoundedOldX) % delete if empty
end, %
if (length(OldListY) > 0) -> ets:insert(etsY,[{RoundedOldY,OldListY}]);%put back the old Locations lists if not empty
true-> ets:delete(etsY,RoundedOldY) % delete if empty
end,
RoundedNewX = round(X),
RoundedNewY = round(Y),
[{_,NewListX}] = listToUpdate(ets:lookup(etsX,RoundedNewX),RoundedNewX),
[{_,NewListY}] = listToUpdate(ets:lookup(etsY,RoundedNewY),RoundedNewY),
ets:insert(etsX,[{RoundedNewX,NewListX}]), %insert the new Locations lists
ets:insert(etsY,[{RoundedNewY,NewListY}]),
{noreply, State#moveSimulator_state{myX = X,myY = Y,time = CurrTime}}
catch _:_ -> {stop, normal, State}
end
end
catch _:_ ->{stop, normal, State}
end;
%%============sendToNeighbors=============================
sends OGM to radius pids
Msg usually is OGM
ListOfRobins = robinsInRadius(State,OGM),
castPlease({ListOfRobins,{ogm , ( ) } } } ) ,
sends the OGM and the sender address to all the neighbors
{noreply, State};
= = = = = = = = = = = = = = = OGM recieved=================================
send it to the Batman
handle_cast({ogm,OGM,{Pid,Node}}, State = #moveSimulator_state{}) ->
Batman =State#moveSimulator_state.myBatman,
gen_server:cast(Batman,{ogm,OGM,{Pid,Node}}),
{noreply, State};
handle_cast(stop, State = #moveSimulator_state{}) ->
{stop, shutdown, State};
handle_cast(Request, State = #moveSimulator_state{}) ->
castPlease({missedcastMOVESIM,request,Request}),
{noreply, State}.
@private
%% @doc Handling all non call/cast messages
-spec(handle_info(Info :: timeout() | term(), State :: #moveSimulator_state{}) ->
{noreply, NewState :: #moveSimulator_state{}} |
{noreply, NewState :: #moveSimulator_state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #moveSimulator_state{}}).
handle_info(_Info, State = #moveSimulator_state{}) ->
castPlease({movSimInfo, _Info}),
{noreply, State}.
@private
%% @doc This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any
%% necessary cleaning up. When it returns, the gen_server terminates
with . The return value is ignored .
-spec(terminate(Reason :: (normal | shutdown | {shutdown, term()} | term()),
State :: #moveSimulator_state{}) -> term()).
terminate(Reason, State = #moveSimulator_state{}) ->
Batman = State#moveSimulator_state.myBatman,
Tokills = State#moveSimulator_state.tokill,
try
if (Reason == normal) ->
X = round(State#moveSimulator_state.myX),
Y = round(State#moveSimulator_state.myY),
Pid = self(),
ObjectX = ets:lookup(etsX,X),
ObjectY= ets:lookup(etsY,Y),
if ((ObjectX == []) or (ObjectY == [])) -> ok;
true->
[{_, TempX}] = ObjectX,
[{_, TempY}] = ObjectY,
ListX = TempX -- [Pid],% remove the pid from the old location
ListY = TempY -- [Pid],
if (length(ListX)>0 )->ets:insert(etsX,[{X,ListX}]);
true-> ets:delete(etsX,X)
end,
if (length(ListY)>0) ->ets:insert(etsY,[{Y,ListY}]);
true-> ets:delete(etsY,Y)
end
end;
true -> ok
end
catch _:_ -> ok
end,
try
[Tokill!exit_please||Tokill<-Tokills]
catch
_:_ ->ok
end ,
gen_server:cast(State#moveSimulator_state.pcPid,{removeRobin, self()}),
gen_server:cast(Batman, {stop,Reason}),
receive
after 50 -> ok
end.
@private
%% @doc Convert process state when code is changed
-spec(code_change(OldVsn :: term() | {down, term()}, State :: #moveSimulator_state{},
Extra :: term()) ->
{ok, NewState :: #moveSimulator_state{}} | {error, Reason :: term()}).
code_change(_OldVsn, State = #moveSimulator_state{}, _Extra) ->
{ok, State}.
%%%===================================================================
Internal functions
%%%===================================================================
%%====================================================================
%%robinsInRadius -> return all the {pid,node} of all the pids that in my radius
%%====================================================================
robinsInRadius(State,OGM) ->
MyX = round(State#moveSimulator_state.myX),
MyY = round(State#moveSimulator_state.myY),
EndX = State#moveSimulator_state.endX,
EndY = State#moveSimulator_state.endY,
StartX = State#moveSimulator_state.startX,
StartY = State#moveSimulator_state.startY,
DemiZone = State#moveSimulator_state.demiZone,
PCPid = State#moveSimulator_state.pcPid,
Radius = State#moveSimulator_state.radius,
Xlist and Ylist are all the pids in square of radius x radius
Xlist = getLineInRadius(etsX,MyX,Radius),
Ylist = getLineInRadius(etsY,MyY,Radius),
case i m close to the border , i will send a request to computerServer to look for neighbors in other computers
if ((MyX + Radius > EndX - DemiZone) or (MyX - Radius > StartX + DemiZone)) ->
tell the computer to send OGM to the nodes in other computer
true->ok
end,
if ((MyY + Radius > EndY - DemiZone) or (MyY - Radius > StartY + DemiZone) )->
gen_server:cast(PCPid,{sendOGMtoNeighborsY,MyX,MyY,OGM,{self(),node()}}); %
true->ok
end,
[Add||Add<-getPidsInCircle(MyX,MyY,Xlist,Ylist,Radius),Add /= {self(),node()}]. % deletes myself from neighbors and return the list of pids in my radius
%%===========================================================
%%===========================================================
%%help other computer just find the pids in the radius
robinsInRadiusForRemote(X,Y,Radius) ->
Xlist and Ylist are all the pids in square of ( radius x radius )
Xlist = getLineInRadius(etsX,X,Radius),
Ylist = getLineInRadius(etsY,Y,Radius),
getPidsInCircle(X,Y,Xlist,Ylist,Radius).
%%===========================================================
getPidsInCircle - >
input : my x , y location and 2 lists as follows :
Xlist = [ { Xlocation,{Pid , node } } , .... ] and Ylist and return only the pids that are in the radius
%%
output : is 1 list with all the Addresses in my radius - > [ { Pid1,Node1},{Pid2,Node1},{Pid3,Node2 } , ... ]
%%===========================================================
getPidsInCircle(X,Y,Xlist,Ylist,Radius)->
Square = getSquare(Xlist,Ylist),
Circle =getCircle(X,Y,Square,Radius), % Square -> [{x,y,address},...]
[Address||{_X,_Y,Address}<-Circle]. % returns only the Addresses back
%%getSquare returns {x,y,address},...] withing a square of radiusXradius
getSquare(Xlist,Ylist) -> getSquare(Xlist,Ylist,[]).
getSquare([],_,List)-> lists:filter(fun(X) -> X /= {} end, List); %removes all empty tuples from the list
%for each X we will lookup a similar Y withing the square
getSquare([{X,Xaddr}|T],Ylist,List) -> getSquare(T,Ylist,[getY(X,Xaddr,Ylist)] ++ List).
getY(_,_,[])-> {};
found a member in Ylist with the same address as X address
getY(X,Xaddr,[_H|T])->getY(X,Xaddr,T);
getY(_,_,_)-> {}.
getCircle(MyX,MyY,Square,Radius) ->
[{X,Y,Add}||{X,Y,Add}<-Square, ((X-MyX)*(X-MyX) + (Y-MyY)*(Y-MyY)) < Radius*Radius].% Square -> [{x,y,address},...]
lists : filter(fun({X , Y,_Address } ) - > ( ( ( X*X)+(Y*Y ) ) < ( ? radius*?radius ) ) end , Square ) .
%%===========================================================
getLineInRadius(ETSLIST , OriginX , ) return all robins at radius - x < x < radius+x
getLineInRadius(ETS,X,Radius) -> lists:flatten([[{RobinX,{Pid,node()}}||Pid<-Pids]|| {RobinX,Pids}<- ets:tab2list(ETS),((RobinX<X+Radius) or(RobinX>X-Radius)) ]).
| null | https://raw.githubusercontent.com/amitnh/Erlang-Final-Batman/3d62d266f4528c7ff94ca867e38f1c375bb63d62/src/moveSimulator.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API
gen_server callbacks
how many time per second to update the ETS's
range of the random velocity of the node in meter / milisec
===================================================================
API
===================================================================
@doc Spawns the server and registers the local name (unique)
{debug,[trace]}
if a batman is switching computer
{debug,[trace]}
in degrees
===================================================================
gen_server callbacks
===================================================================
@doc Initializes the server
creates and link it to this process
{X,Y} = startLocation(StartX,EndX,StartY,EndY), % put my new random location in the etsX and etsY
if a batman is switching computer with specific X,Y locations
initiating field
put my new random location in the etsX and etsY
receiving a new batman from another computer
---------------------------------------------------------------------------------------------------
return {X,Y} value
the ETS is build like this: [{Location1,[pid1,pid2...]},{Location2,[pid1,pid2...]},....]
---------------------------------------------------------------------------------------------------
calculate the new locations of X and Y based on the random vector
---------------------------------------------------------------------------------------------------
boarders check:
if X or Y are out of bounds, need to check if theres a new border or if a terminate is necessary
wait for the computerServer to bring back an answer about the borders
gen_server:cast(self(),stop);
Shut down MoveSimulator Server
Shut down MoveSimulator Server
---------------------------------------------------------------------------------------------------
@doc Handling call messages
case the msg is for me -> cast it
case the msg is not for me -> pass it on
@doc Handling cast messages
if i was close to the border, but the border changed, the computerServer will update us by sending
updateArea cast msg, as following:
handle_cast({updateArea,NewArea}, _) -> todo later
============================================================================================
case someone tell me to send Msg to myself
case the batman has no neighbors
castPlease({bestLink,BestLink}),
if the call fails
im not sending the msg back to the one that sent it to me, infinite loop
if the node is in my pc send it to him directly
if neighbor didn't received the msg (Out Of Range / died for some reason) then
send the MSG again
if the neighbor is on other computer and not the one that sent me the msg
if neighbor didn't received the msg (Out Of Range / died for some reason) then
send the MSG again
if Msg didn't sent
if neighbor didn't received the msg (Out Of Range / died for some reason) then
i dont know "To", cant reach him
=======================================================================================================
============================================================================================
castPlease(updateMovementVector),
castPlease(updateMovementVector),
updateEts updates the location of my PID in the etsX and etsY
also checks if the borders are ok or should i terminate and move to another nearby PC
check if lookup is empty
remove the pid from the old location
put back the old Locations lists if not empty
delete if empty
put back the old Locations lists if not empty
delete if empty
insert the new Locations lists
============sendToNeighbors=============================
@doc Handling all non call/cast messages
@doc This function is called by a gen_server when it is about to
terminate. It should be the opposite of Module:init/1 and do any
necessary cleaning up. When it returns, the gen_server terminates
remove the pid from the old location
@doc Convert process state when code is changed
===================================================================
===================================================================
====================================================================
robinsInRadius -> return all the {pid,node} of all the pids that in my radius
====================================================================
deletes myself from neighbors and return the list of pids in my radius
===========================================================
===========================================================
help other computer just find the pids in the radius
===========================================================
===========================================================
Square -> [{x,y,address},...]
returns only the Addresses back
getSquare returns {x,y,address},...] withing a square of radiusXradius
removes all empty tuples from the list
for each X we will lookup a similar Y withing the square
Square -> [{x,y,address},...]
=========================================================== | @author amit and kapelnik
( C ) 2020 , < COMPANY >
Created : 01 . Aug 2020 12:36 PM
-module(moveSimulator).
-author("amit and kapelnik").
-behaviour(gen_server).
-export([start_link/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, getPidsInCircle/5,
code_change/3, castPlease/1, robinsInRadiusForRemote/3]).
-define(SERVER, ?MODULE).
range of the random time to change direction of the node in milisec
-define(radius , 300 ) .
-record(moveSimulator_state, {startX,endX,startY,endY,demiZone,radius,velMax,myX,myY,time,velocity,direction,myBatman,pcPid,tokill}).
test TODO delete
castPlease(MSG)-> gen_server:cast({global, tal@ubuntu},{test,MSG}).
-spec(start_link(List::term()) ->
{ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
start_link([Area,Specs,PCPid]) ->
Pid1 = spawn(fun()->etsTimer(Pid) end) ,
Pid2 = spawn(fun()->vectorTimer(Pid,Specs) end),
gen_server:cast(Pid,{tokillonshutdown,[Pid1,Pid2]});
start_link([Area,Specs,PCPid,{X,Y,Dir,Vel}]) ->
Pid1 = spawn_link(fun()->etsTimer(Pid) end),
Pid2 = spawn_link(fun()->vectorTimer(Pid,Specs) end),
gen_server:cast(PCPid,{monitorMe,Pid}),
gen_server:cast(Pid,{tokillonshutdown,[Pid1,Pid2]}).
send a cast to update the main ets 's every ?
time to wait for sending ? updateEts msgs in 1 sec
receive
_-> castPlease({etsTimerTerminating}) , exit(normal)
after TimeToWait ->
gen_server:cast(Pid,{updateEts}),
etsTimer(Pid)
end.
update the random velocity , direction and updatetime to update
vectorTimer(Pid,Specs)->
{_Radius,_NumofRobins, _DemiZone,_OGMTime,MaxVelocity,_WindowSize,_TTL} = Specs,
{Min,Max} = ?timeRange,
TimeToWait = Min + rand:uniform(Max-Min),
receive
_-> castPlease(vectortimerTerminating), exit(normal)
after TimeToWait ->
this 3 are going to the vector ( in the record ):
CurrTime = erlang:system_time(millisecond),
Velocity = rand:uniform(MaxVelocity*1000)/1000,
gen_server:cast(Pid,{updateMovementVector,CurrTime,Velocity,Direction}),
vectorTimer(Pid,Specs)
end .
@private
-spec(init(Args :: term()) ->
{ok, State :: #moveSimulator_state{}} | {ok, State :: #moveSimulator_state{}, timeout() | hibernate} |
{stop, Reason :: term()} | ignore).
init([{StartX , EndX , StartY , EndY},DemiZone , PCPid ] ) - >
{ ok , # moveSimulator_state{startX = StartX , endX = EndX , startY = StartY , endY = EndY ,
demiZone = DemiZone , , myY = Y , time = erlang : system_time(millisecond),velocity=0,direction=0,myBatman , pcPid = PCPid } } ;
init([{StartX,EndX,StartY,EndY},{Radius,_NumofRobins,DemiZone,OGMTime,MaxVelocity,WindowSize,TTL},PCPid,{X,Y,Dir,Vel}]) ->
creates and link it to this process
{ok, #moveSimulator_state{startX = StartX,endX = EndX,startY = StartY,endY = EndY,
demiZone = DemiZone,radius = Radius,velMax = MaxVelocity, myX = Xnew,myY = Ynew,time = erlang:system_time(millisecond),velocity=0,direction=0,myBatman = MyBatman,pcPid = PCPid}};
ListX = listToUpdate(ets:lookup(etsX,X),X),
ListY = listToUpdate(ets:lookup(etsY,Y),Y),
ets:insert(etsX,ListX),
ets:insert(etsY,ListY),
{ok, #moveSimulator_state{startX = StartX,endX = EndX,startY = StartY,endY = EndY,
demiZone = DemiZone,radius = Radius,velMax = MaxVelocity, myX = X,myY = Y,time = erlang:system_time(millisecond),velocity=Vel,direction=Dir,myBatman = MyBatman,pcPid = PCPid}}
end;
init(_A)-> castPlease({initMovSimError,_A}).
startLocation , insert a new location in the etsX and etsY maps
startLocation(StartX,EndX,StartY,EndY)->
returns a random integer in the computer Area
LocationY = StartY + rand:uniform(EndY-StartY),
ListX = listToUpdate(ets:lookup(etsX,LocationX),LocationX),
ListY = listToUpdate(ets:lookup(etsY,LocationY),LocationY),
ets:insert(etsX,ListX),
ets:insert(etsY,ListY),
checks if the i m the first one on that list in the ETS or not .
listToUpdate([],Location)-> [{Location,[self()]}];
listToUpdate([{Location,List}],_Location)->[{Location,List ++ [self()]}].
updatedXYlocations(State)->
X0 = State#moveSimulator_state.myX,
Y0 = State#moveSimulator_state.myY,
Vel = State#moveSimulator_state.velocity,
Dir = State#moveSimulator_state.direction,
PCPid = State#moveSimulator_state.pcPid,
CurrTime = erlang:system_time(millisecond),
DeltaTime = CurrTime - State#moveSimulator_state.time,
StartX = State#moveSimulator_state.startX,
StartY = State#moveSimulator_state.startY,
EndX = State#moveSimulator_state.endX,
EndY = State#moveSimulator_state.endY,
DemilitarizedZone = State#moveSimulator_state.demiZone,
x = vt , trigo
Y = Y0 + math:sin(Dir * math:pi() / 180)*Vel*DeltaTime/1000,
if ((X < 0) or (X > 2000) or (Y < 0) or (Y > 2000)) ->
{X0,Y0,CurrTime,false};
if ((X>EndX+DemilitarizedZone) or (X<StartX-DemilitarizedZone) or (Y>EndY+DemilitarizedZone) or (Y<StartY-DemilitarizedZone)) ->
{NewStartX,NewEndX,NewStartY,NewEndY,ToTerminate} = gen_server:call(PCPid,{updateBorders,{round(X),round(Y),State#moveSimulator_state.direction,State#moveSimulator_state.velocity}}),
if ToTerminate ->ok;
true -> gen_server:cast(self(),{updateBorders,NewStartX,NewEndX,NewStartY,NewEndY})
end, {X,Y,CurrTime,true}
catch _:_-> castPlease(innerConnectionError)
end;
true -> {X,Y,CurrTime,false}
end
end.
, startX = NewStartX , startY = NewStartY , endX = , endY =
@private
-spec(handle_call(Request :: term(), From :: {pid(), Tag :: term()},
State :: #moveSimulator_state{}) ->
{reply, Reply :: term(), NewState :: #moveSimulator_state{}} |
{reply, Reply :: term(), NewState :: #moveSimulator_state{}, timeout() | hibernate} |
{noreply, NewState :: #moveSimulator_state{}} |
{noreply, NewState :: #moveSimulator_state{}, timeout() | hibernate} |
{stop, Reason :: term(), Reply :: term(), NewState :: #moveSimulator_state{}} |
{stop, Reason :: term(), NewState :: #moveSimulator_state{}}).
handle_call({receiveMsg,To,Msg,MoveSimFrom}, {FromPid,_Ref}, State = #moveSimulator_state{}) ->
castPlease({receiveMsg , from , FromPid } ) ,
gen_server:cast(State#moveSimulator_state.pcPid,{msgSent, MoveSimFrom, {self(),node()}}),
end,
{reply, sent, State};
handle_call({getKnownFrom}, _From, State = #moveSimulator_state{}) ->
try
{PidTo,NodeTo} = gen_server:call(State#moveSimulator_state.myBatman,{getKnownFrom}),
{reply, {PidTo,NodeTo}, State}
catch _:_ -> {reply, {notfound,notfound}, State}
end;
handle_call(stop, _From, State = #moveSimulator_state{}) ->
{stop, normal, State};
handle_call(_Request, _From, State = #moveSimulator_state{}) ->
castPlease({missedCallMovSim, request, _Request, from, _From}),
{reply, ok, State}.
@private
-spec(handle_cast(Request :: term(), State :: #moveSimulator_state{}) ->
{noreply, NewState :: #moveSimulator_state{}} |
{noreply, NewState :: #moveSimulator_state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #moveSimulator_state{}}).
{ noreply , # moveSimulator_state{myArea = NewArea } } ;
send MSG to someone using the BATMAN Protocol
{noreply, State#moveSimulator_state{}};
{noreply, State#moveSimulator_state{tokill = Pids}};
handle_cast({sendMsg,To,From,Msg}, State = #moveSimulator_state{}) ->
castPlease({firstSendMsgMoveSimulator , to , To , from , From , msg , ) ,
MyBatman = State#moveSimulator_state.myBatman,
BestLink = gen_server:call(MyBatman, {findBestLink, To}),
there where no problems , Best Link was found
{BestLinkPid,BestLinkNode}= BestLink,
Node = node(),
if
1.delete the neighbor 2.send the msg again to the next best link
gen_server:cast(MyBatman, {deleteNeighbor, BestLink,To,Msg});
Reply = gen_server:call(BestLinkPid,{receiveMsg,To,Msg,{self(),node()}}),
if
(Reply == sent) ->ok;
{ noreply , State } ;
1.delete the neighbor 2.send the msg again to the next best link
gen_server:cast(MyBatman, {deleteNeighbor, BestLink,To,Msg}),
{noreply, State}
end;
{ noreply , State } ;
PcPid = State#moveSimulator_state.pcPid,
Reply = gen_server:call(PcPid,{sendMsg,To,BestLink,Msg,{self(),node()}}),
if
(Reply == sent) -> ok;
{ noreply , State } ;
1.delete the neighbor 2.send the msg again to the next best link
gen_server:cast(MyBatman, {deleteNeighbor, BestLink,To,Msg}),
{ noreply , State }
end
{ noreply , State }
end
1.delete the neighbor 2.send the msg again to the next best link
gen_server:cast(MyBatman, {deleteNeighbor, BestLink,To,Msg})
end;
end,
{noreply, State};
handle_cast({updateBorders,NewStartX,NewEndX,NewStartY,NewEndY}, State = #moveSimulator_state{}) ->
{noreply, State#moveSimulator_state{startX = NewStartX,endX = NewEndX,startY = NewStartY,endY = NewEndY}};
handle_cast({updateMovementVector,CurrTime,Velocity,Direction}, State = #moveSimulator_state{}) ->
{noreply, State#moveSimulator_state{time = CurrTime,velocity = Velocity, direction = Direction}};
handle_cast({changeDir}, State = #moveSimulator_state{}) ->
Direction = State#moveSimulator_state.direction,
NewDirection = (0 - Direction),
{noreply, State#moveSimulator_state{direction = NewDirection}};
handle_cast({updateEts}, State = #moveSimulator_state{}) ->
try
if ToTerminate -> {stop, normal, State};
true ->
X in ets is rounded . not in myX record
RoundedOldY = round(State#moveSimulator_state.myY),
try
[{_Keyx,Tempx}] = ets:lookup(etsX,RoundedOldX),
[{_Keyy,Tempy}] = ets:lookup(etsY,RoundedOldY),
if (length(Tempx)>0) ->
true-> ListX =[]
end,
if (length(Tempy)>0) ->
ListY= Tempy;
true-> ListY =[]
end,
OldListY = ListY -- [self()],
end,
RoundedNewX = round(X),
RoundedNewY = round(Y),
[{_,NewListX}] = listToUpdate(ets:lookup(etsX,RoundedNewX),RoundedNewX),
[{_,NewListY}] = listToUpdate(ets:lookup(etsY,RoundedNewY),RoundedNewY),
ets:insert(etsY,[{RoundedNewY,NewListY}]),
{noreply, State#moveSimulator_state{myX = X,myY = Y,time = CurrTime}}
catch _:_ -> {stop, normal, State}
end
end
catch _:_ ->{stop, normal, State}
end;
sends OGM to radius pids
Msg usually is OGM
ListOfRobins = robinsInRadius(State,OGM),
castPlease({ListOfRobins,{ogm , ( ) } } } ) ,
sends the OGM and the sender address to all the neighbors
{noreply, State};
= = = = = = = = = = = = = = = OGM recieved=================================
send it to the Batman
handle_cast({ogm,OGM,{Pid,Node}}, State = #moveSimulator_state{}) ->
Batman =State#moveSimulator_state.myBatman,
gen_server:cast(Batman,{ogm,OGM,{Pid,Node}}),
{noreply, State};
handle_cast(stop, State = #moveSimulator_state{}) ->
{stop, shutdown, State};
handle_cast(Request, State = #moveSimulator_state{}) ->
castPlease({missedcastMOVESIM,request,Request}),
{noreply, State}.
@private
-spec(handle_info(Info :: timeout() | term(), State :: #moveSimulator_state{}) ->
{noreply, NewState :: #moveSimulator_state{}} |
{noreply, NewState :: #moveSimulator_state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #moveSimulator_state{}}).
handle_info(_Info, State = #moveSimulator_state{}) ->
castPlease({movSimInfo, _Info}),
{noreply, State}.
@private
with . The return value is ignored .
-spec(terminate(Reason :: (normal | shutdown | {shutdown, term()} | term()),
State :: #moveSimulator_state{}) -> term()).
terminate(Reason, State = #moveSimulator_state{}) ->
Batman = State#moveSimulator_state.myBatman,
Tokills = State#moveSimulator_state.tokill,
try
if (Reason == normal) ->
X = round(State#moveSimulator_state.myX),
Y = round(State#moveSimulator_state.myY),
Pid = self(),
ObjectX = ets:lookup(etsX,X),
ObjectY= ets:lookup(etsY,Y),
if ((ObjectX == []) or (ObjectY == [])) -> ok;
true->
[{_, TempX}] = ObjectX,
[{_, TempY}] = ObjectY,
ListY = TempY -- [Pid],
if (length(ListX)>0 )->ets:insert(etsX,[{X,ListX}]);
true-> ets:delete(etsX,X)
end,
if (length(ListY)>0) ->ets:insert(etsY,[{Y,ListY}]);
true-> ets:delete(etsY,Y)
end
end;
true -> ok
end
catch _:_ -> ok
end,
try
[Tokill!exit_please||Tokill<-Tokills]
catch
_:_ ->ok
end ,
gen_server:cast(State#moveSimulator_state.pcPid,{removeRobin, self()}),
gen_server:cast(Batman, {stop,Reason}),
receive
after 50 -> ok
end.
@private
-spec(code_change(OldVsn :: term() | {down, term()}, State :: #moveSimulator_state{},
Extra :: term()) ->
{ok, NewState :: #moveSimulator_state{}} | {error, Reason :: term()}).
code_change(_OldVsn, State = #moveSimulator_state{}, _Extra) ->
{ok, State}.
Internal functions
robinsInRadius(State,OGM) ->
MyX = round(State#moveSimulator_state.myX),
MyY = round(State#moveSimulator_state.myY),
EndX = State#moveSimulator_state.endX,
EndY = State#moveSimulator_state.endY,
StartX = State#moveSimulator_state.startX,
StartY = State#moveSimulator_state.startY,
DemiZone = State#moveSimulator_state.demiZone,
PCPid = State#moveSimulator_state.pcPid,
Radius = State#moveSimulator_state.radius,
Xlist and Ylist are all the pids in square of radius x radius
Xlist = getLineInRadius(etsX,MyX,Radius),
Ylist = getLineInRadius(etsY,MyY,Radius),
case i m close to the border , i will send a request to computerServer to look for neighbors in other computers
if ((MyX + Radius > EndX - DemiZone) or (MyX - Radius > StartX + DemiZone)) ->
tell the computer to send OGM to the nodes in other computer
true->ok
end,
if ((MyY + Radius > EndY - DemiZone) or (MyY - Radius > StartY + DemiZone) )->
true->ok
end,
robinsInRadiusForRemote(X,Y,Radius) ->
Xlist and Ylist are all the pids in square of ( radius x radius )
Xlist = getLineInRadius(etsX,X,Radius),
Ylist = getLineInRadius(etsY,Y,Radius),
getPidsInCircle(X,Y,Xlist,Ylist,Radius).
getPidsInCircle - >
input : my x , y location and 2 lists as follows :
Xlist = [ { Xlocation,{Pid , node } } , .... ] and Ylist and return only the pids that are in the radius
output : is 1 list with all the Addresses in my radius - > [ { Pid1,Node1},{Pid2,Node1},{Pid3,Node2 } , ... ]
getPidsInCircle(X,Y,Xlist,Ylist,Radius)->
Square = getSquare(Xlist,Ylist),
getSquare(Xlist,Ylist) -> getSquare(Xlist,Ylist,[]).
getSquare([{X,Xaddr}|T],Ylist,List) -> getSquare(T,Ylist,[getY(X,Xaddr,Ylist)] ++ List).
getY(_,_,[])-> {};
found a member in Ylist with the same address as X address
getY(X,Xaddr,[_H|T])->getY(X,Xaddr,T);
getY(_,_,_)-> {}.
getCircle(MyX,MyY,Square,Radius) ->
lists : filter(fun({X , Y,_Address } ) - > ( ( ( X*X)+(Y*Y ) ) < ( ? radius*?radius ) ) end , Square ) .
getLineInRadius(ETSLIST , OriginX , ) return all robins at radius - x < x < radius+x
getLineInRadius(ETS,X,Radius) -> lists:flatten([[{RobinX,{Pid,node()}}||Pid<-Pids]|| {RobinX,Pids}<- ets:tab2list(ETS),((RobinX<X+Radius) or(RobinX>X-Radius)) ]).
|
a84764033d9ea65dc0bfb5705fdbdccb8a2d64b7958f195f5ac521fa3c7d67ac | processone/xmpp | xep0045.erl | Created automatically by XML generator ( fxml_gen.erl )
%% Source: xmpp_codec.spec
-module(xep0045).
-compile(export_all).
do_decode(<<"unique">>,
<<"#unique">>, El,
Opts) ->
decode_muc_unique(<<"#unique">>,
Opts,
El);
do_decode(<<"x">>, <<"">>,
El, Opts) ->
decode_muc(<<"">>,
Opts,
El);
do_decode(<<"query">>,
<<"#admin">>, El, Opts) ->
decode_muc_admin(<<"#admin">>,
Opts,
El);
do_decode(<<"continue">>,
<<"#admin">>, El, Opts) ->
decode_muc_admin_continue(<<"#admin">>,
Opts,
El);
do_decode(<<"actor">>,
<<"#admin">>, El, Opts) ->
decode_muc_admin_actor(<<"#admin">>,
Opts,
El);
do_decode(<<"item">>,
<<"#admin">>, El, Opts) ->
decode_muc_admin_item(<<"#admin">>,
Opts,
El);
do_decode(<<"item">>,
<<"#owner">>, El, Opts) ->
decode_muc_owner_item(<<"#owner">>,
Opts,
El);
do_decode(<<"query">>,
<<"#owner">>, El, Opts) ->
decode_muc_owner(<<"#owner">>,
Opts,
El);
do_decode(<<"password">>,
<<"#owner">>, El, Opts) ->
decode_muc_password(<<"#owner">>,
Opts,
El);
do_decode(<<"password">>,
<<"#user">>, El, Opts) ->
decode_muc_password(<<"#user">>,
Opts,
El);
do_decode(<<"password">>,
<<"">>, El, Opts) ->
decode_muc_password(<<"">>,
Opts,
El);
do_decode(<<"x">>,
<<"#user">>, El, Opts) ->
decode_muc_user(<<"#user">>,
Opts,
El);
do_decode(<<"item">>,
<<"#user">>, El, Opts) ->
decode_muc_user_item(<<"#user">>,
Opts,
El);
do_decode(<<"status">>,
<<"#user">>, El, Opts) ->
decode_muc_user_status(<<"#user">>,
Opts,
El);
do_decode(<<"continue">>,
<<"#user">>, El, Opts) ->
decode_muc_user_continue(<<"#user">>,
Opts,
El);
do_decode(<<"actor">>,
<<"#user">>, El, Opts) ->
decode_muc_user_actor(<<"#user">>,
Opts,
El);
do_decode(<<"invite">>,
<<"#user">>, El, Opts) ->
decode_muc_user_invite(<<"#user">>,
Opts,
El);
do_decode(<<"destroy">>,
<<"#user">>, El, Opts) ->
decode_muc_destroy(<<"#user">>,
Opts,
El);
do_decode(<<"destroy">>,
<<"#owner">>, El, Opts) ->
decode_muc_destroy(<<"#owner">>,
Opts,
El);
do_decode(<<"decline">>,
<<"#user">>, El, Opts) ->
decode_muc_user_decline(<<"#user">>,
Opts,
El);
do_decode(<<"reason">>,
<<"#user">>, El, Opts) ->
decode_muc_reason(<<"#user">>,
Opts,
El);
do_decode(<<"reason">>,
<<"#admin">>, El, Opts) ->
decode_muc_reason(<<"#admin">>,
Opts,
El);
do_decode(<<"reason">>,
<<"#owner">>, El, Opts) ->
decode_muc_reason(<<"#owner">>,
Opts,
El);
do_decode(<<"history">>,
<<"">>, El, Opts) ->
decode_muc_history(<<"">>,
Opts,
El);
do_decode(Name, <<>>, _, _) ->
erlang:error({xmpp_codec, {missing_tag_xmlns, Name}});
do_decode(Name, XMLNS, _, _) ->
erlang:error({xmpp_codec, {unknown_tag, Name, XMLNS}}).
tags() ->
[{<<"unique">>,
<<"#unique">>},
{<<"x">>, <<"">>},
{<<"query">>,
<<"#admin">>},
{<<"continue">>,
<<"#admin">>},
{<<"actor">>,
<<"#admin">>},
{<<"item">>,
<<"#admin">>},
{<<"item">>,
<<"#owner">>},
{<<"query">>,
<<"#owner">>},
{<<"password">>,
<<"#owner">>},
{<<"password">>,
<<"#user">>},
{<<"password">>, <<"">>},
{<<"x">>, <<"#user">>},
{<<"item">>, <<"#user">>},
{<<"status">>,
<<"#user">>},
{<<"continue">>,
<<"#user">>},
{<<"actor">>,
<<"#user">>},
{<<"invite">>,
<<"#user">>},
{<<"destroy">>,
<<"#user">>},
{<<"destroy">>,
<<"#owner">>},
{<<"decline">>,
<<"#user">>},
{<<"reason">>,
<<"#user">>},
{<<"reason">>,
<<"#admin">>},
{<<"reason">>,
<<"#owner">>},
{<<"history">>, <<"">>}].
do_encode({muc_history, _, _, _, _} = History,
TopXMLNS) ->
encode_muc_history(History, TopXMLNS);
do_encode({muc_decline, _, _, _} = Decline, TopXMLNS) ->
encode_muc_user_decline(Decline, TopXMLNS);
do_encode({muc_destroy, _, _, _, _} = Destroy,
TopXMLNS) ->
encode_muc_destroy(Destroy, TopXMLNS);
do_encode({muc_invite, _, _, _, _} = Invite,
TopXMLNS) ->
encode_muc_user_invite(Invite, TopXMLNS);
do_encode({muc_user, _, _, _, _, _, _} = X, TopXMLNS) ->
encode_muc_user(X, TopXMLNS);
do_encode({muc_owner, _, _, _} = Query, TopXMLNS) ->
encode_muc_owner(Query, TopXMLNS);
do_encode({muc_item, _, _, _, _, _, _, _} = Item,
TopXMLNS) ->
encode_muc_admin_item(Item, TopXMLNS);
do_encode({muc_actor, _, _} = Actor, TopXMLNS) ->
encode_muc_admin_actor(Actor, TopXMLNS);
do_encode({muc_admin, _} = Query, TopXMLNS) ->
encode_muc_admin(Query, TopXMLNS);
do_encode({muc, _, _} = X, TopXMLNS) ->
encode_muc(X, TopXMLNS);
do_encode({muc_unique, _} = Unique, TopXMLNS) ->
encode_muc_unique(Unique, TopXMLNS).
do_get_name({muc, _, _}) -> <<"x">>;
do_get_name({muc_actor, _, _}) -> <<"actor">>;
do_get_name({muc_admin, _}) -> <<"query">>;
do_get_name({muc_decline, _, _, _}) -> <<"decline">>;
do_get_name({muc_destroy, _, _, _, _}) -> <<"destroy">>;
do_get_name({muc_history, _, _, _, _}) -> <<"history">>;
do_get_name({muc_invite, _, _, _, _}) -> <<"invite">>;
do_get_name({muc_item, _, _, _, _, _, _, _}) ->
<<"item">>;
do_get_name({muc_owner, _, _, _}) -> <<"query">>;
do_get_name({muc_unique, _}) -> <<"unique">>;
do_get_name({muc_user, _, _, _, _, _, _}) -> <<"x">>.
do_get_ns({muc, _, _}) ->
<<"">>;
do_get_ns({muc_admin, _}) ->
<<"#admin">>;
do_get_ns({muc_decline, _, _, _}) ->
<<"#user">>;
do_get_ns({muc_destroy, Xmlns, _, _, _}) -> Xmlns;
do_get_ns({muc_history, _, _, _, _}) ->
<<"">>;
do_get_ns({muc_invite, _, _, _, _}) ->
<<"#user">>;
do_get_ns({muc_owner, _, _, _}) ->
<<"#owner">>;
do_get_ns({muc_unique, _}) ->
<<"#unique">>;
do_get_ns({muc_user, _, _, _, _, _, _}) ->
<<"#user">>.
pp(muc_history, 4) ->
[maxchars, maxstanzas, seconds, since];
pp(muc_decline, 3) -> [reason, from, to];
pp(muc_destroy, 4) -> [xmlns, jid, reason, password];
pp(muc_invite, 4) -> [reason, from, to, continue];
pp(muc_user, 6) ->
[decline,
destroy,
invites,
items,
status_codes,
password];
pp(muc_owner, 3) -> [destroy, config, items];
pp(muc_item, 7) ->
[actor, continue, reason, affiliation, role, jid, nick];
pp(muc_actor, 2) -> [jid, nick];
pp(muc_admin, 1) -> [items];
pp(muc, 2) -> [history, password];
pp(muc_unique, 1) -> [name];
pp(_, _) -> no.
records() ->
[{muc_history, 4},
{muc_decline, 3},
{muc_destroy, 4},
{muc_invite, 4},
{muc_user, 6},
{muc_owner, 3},
{muc_item, 7},
{muc_actor, 2},
{muc_admin, 1},
{muc, 2},
{muc_unique, 1}].
dec_enum(Val, Enums) ->
AtomVal = erlang:binary_to_existing_atom(Val, utf8),
case lists:member(AtomVal, Enums) of
true -> AtomVal
end.
dec_int(Val, Min, Max) ->
case erlang:binary_to_integer(Val) of
Int when Int =< Max, Min == infinity -> Int;
Int when Int =< Max, Int >= Min -> Int
end.
dec_utc(Val) -> xmpp_util:decode_timestamp(Val).
enc_enum(Atom) -> erlang:atom_to_binary(Atom, utf8).
enc_int(Int) -> erlang:integer_to_binary(Int).
enc_utc(Val) -> xmpp_util:encode_timestamp(Val).
decode_muc_unique(__TopXMLNS, __Opts,
{xmlel, <<"unique">>, _attrs, _els}) ->
Name = decode_muc_unique_els(__TopXMLNS,
__Opts,
_els,
<<>>),
{muc_unique, Name}.
decode_muc_unique_els(__TopXMLNS, __Opts, [], Name) ->
decode_muc_unique_cdata(__TopXMLNS, Name);
decode_muc_unique_els(__TopXMLNS, __Opts,
[{xmlcdata, _data} | _els], Name) ->
decode_muc_unique_els(__TopXMLNS,
__Opts,
_els,
<<Name/binary, _data/binary>>);
decode_muc_unique_els(__TopXMLNS, __Opts, [_ | _els],
Name) ->
decode_muc_unique_els(__TopXMLNS, __Opts, _els, Name).
encode_muc_unique({muc_unique, Name}, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#unique">>,
[],
__TopXMLNS),
_els = encode_muc_unique_cdata(Name, []),
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"unique">>, _attrs, _els}.
decode_muc_unique_cdata(__TopXMLNS, <<>>) -> <<>>;
decode_muc_unique_cdata(__TopXMLNS, _val) -> _val.
encode_muc_unique_cdata(<<>>, _acc) -> _acc;
encode_muc_unique_cdata(_val, _acc) ->
[{xmlcdata, _val} | _acc].
decode_muc(__TopXMLNS, __Opts,
{xmlel, <<"x">>, _attrs, _els}) ->
{Password, History} = decode_muc_els(__TopXMLNS,
__Opts,
_els,
undefined,
undefined),
{muc, History, Password}.
decode_muc_els(__TopXMLNS, __Opts, [], Password,
History) ->
{Password, History};
decode_muc_els(__TopXMLNS, __Opts,
[{xmlel, <<"history">>, _attrs, _} = _el | _els],
Password, History) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"">> ->
decode_muc_els(__TopXMLNS,
__Opts,
_els,
Password,
decode_muc_history(<<"">>,
__Opts,
_el));
_ ->
decode_muc_els(__TopXMLNS,
__Opts,
_els,
Password,
History)
end;
decode_muc_els(__TopXMLNS, __Opts,
[{xmlel, <<"password">>, _attrs, _} = _el | _els],
Password, History) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#owner">> ->
decode_muc_els(__TopXMLNS,
__Opts,
_els,
decode_muc_password(<<"#owner">>,
__Opts,
_el),
History);
<<"#user">> ->
decode_muc_els(__TopXMLNS,
__Opts,
_els,
decode_muc_password(<<"#user">>,
__Opts,
_el),
History);
<<"">> ->
decode_muc_els(__TopXMLNS,
__Opts,
_els,
decode_muc_password(<<"">>,
__Opts,
_el),
History);
_ ->
decode_muc_els(__TopXMLNS,
__Opts,
_els,
Password,
History)
end;
decode_muc_els(__TopXMLNS, __Opts, [_ | _els], Password,
History) ->
decode_muc_els(__TopXMLNS,
__Opts,
_els,
Password,
History).
encode_muc({muc, History, Password}, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"">>,
[],
__TopXMLNS),
_els = lists:reverse('encode_muc_$password'(Password,
__NewTopXMLNS,
'encode_muc_$history'(History,
__NewTopXMLNS,
[]))),
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"x">>, _attrs, _els}.
'encode_muc_$password'(undefined, __TopXMLNS, _acc) ->
_acc;
'encode_muc_$password'(Password, __TopXMLNS, _acc) ->
[encode_muc_password(Password, __TopXMLNS) | _acc].
'encode_muc_$history'(undefined, __TopXMLNS, _acc) ->
_acc;
'encode_muc_$history'(History, __TopXMLNS, _acc) ->
[encode_muc_history(History, __TopXMLNS) | _acc].
decode_muc_admin(__TopXMLNS, __Opts,
{xmlel, <<"query">>, _attrs, _els}) ->
Items = decode_muc_admin_els(__TopXMLNS,
__Opts,
_els,
[]),
{muc_admin, Items}.
decode_muc_admin_els(__TopXMLNS, __Opts, [], Items) ->
lists:reverse(Items);
decode_muc_admin_els(__TopXMLNS, __Opts,
[{xmlel, <<"item">>, _attrs, _} = _el | _els], Items) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#admin">> ->
decode_muc_admin_els(__TopXMLNS,
__Opts,
_els,
[decode_muc_admin_item(<<"#admin">>,
__Opts,
_el)
| Items]);
_ ->
decode_muc_admin_els(__TopXMLNS, __Opts, _els, Items)
end;
decode_muc_admin_els(__TopXMLNS, __Opts, [_ | _els],
Items) ->
decode_muc_admin_els(__TopXMLNS, __Opts, _els, Items).
encode_muc_admin({muc_admin, Items}, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#admin">>,
[],
__TopXMLNS),
_els = lists:reverse('encode_muc_admin_$items'(Items,
__NewTopXMLNS,
[])),
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"query">>, _attrs, _els}.
'encode_muc_admin_$items'([], __TopXMLNS, _acc) -> _acc;
'encode_muc_admin_$items'([Items | _els], __TopXMLNS,
_acc) ->
'encode_muc_admin_$items'(_els,
__TopXMLNS,
[encode_muc_admin_item(Items, __TopXMLNS)
| _acc]).
decode_muc_admin_continue(__TopXMLNS, __Opts,
{xmlel, <<"continue">>, _attrs, _els}) ->
Thread = decode_muc_admin_continue_attrs(__TopXMLNS,
_attrs,
undefined),
Thread.
decode_muc_admin_continue_attrs(__TopXMLNS,
[{<<"thread">>, _val} | _attrs], _Thread) ->
decode_muc_admin_continue_attrs(__TopXMLNS,
_attrs,
_val);
decode_muc_admin_continue_attrs(__TopXMLNS,
[_ | _attrs], Thread) ->
decode_muc_admin_continue_attrs(__TopXMLNS,
_attrs,
Thread);
decode_muc_admin_continue_attrs(__TopXMLNS, [],
Thread) ->
decode_muc_admin_continue_attr_thread(__TopXMLNS,
Thread).
encode_muc_admin_continue(Thread, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#admin">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_muc_admin_continue_attr_thread(Thread,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS)),
{xmlel, <<"continue">>, _attrs, _els}.
decode_muc_admin_continue_attr_thread(__TopXMLNS,
undefined) ->
<<>>;
decode_muc_admin_continue_attr_thread(__TopXMLNS,
_val) ->
_val.
encode_muc_admin_continue_attr_thread(<<>>, _acc) ->
_acc;
encode_muc_admin_continue_attr_thread(_val, _acc) ->
[{<<"thread">>, _val} | _acc].
decode_muc_admin_actor(__TopXMLNS, __Opts,
{xmlel, <<"actor">>, _attrs, _els}) ->
{Jid, Nick} = decode_muc_admin_actor_attrs(__TopXMLNS,
_attrs,
undefined,
undefined),
{muc_actor, Jid, Nick}.
decode_muc_admin_actor_attrs(__TopXMLNS,
[{<<"jid">>, _val} | _attrs], _Jid, Nick) ->
decode_muc_admin_actor_attrs(__TopXMLNS,
_attrs,
_val,
Nick);
decode_muc_admin_actor_attrs(__TopXMLNS,
[{<<"nick">>, _val} | _attrs], Jid, _Nick) ->
decode_muc_admin_actor_attrs(__TopXMLNS,
_attrs,
Jid,
_val);
decode_muc_admin_actor_attrs(__TopXMLNS, [_ | _attrs],
Jid, Nick) ->
decode_muc_admin_actor_attrs(__TopXMLNS,
_attrs,
Jid,
Nick);
decode_muc_admin_actor_attrs(__TopXMLNS, [], Jid,
Nick) ->
{decode_muc_admin_actor_attr_jid(__TopXMLNS, Jid),
decode_muc_admin_actor_attr_nick(__TopXMLNS, Nick)}.
encode_muc_admin_actor({muc_actor, Jid, Nick},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#admin">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_muc_admin_actor_attr_nick(Nick,
encode_muc_admin_actor_attr_jid(Jid,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))),
{xmlel, <<"actor">>, _attrs, _els}.
decode_muc_admin_actor_attr_jid(__TopXMLNS,
undefined) ->
undefined;
decode_muc_admin_actor_attr_jid(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"jid">>,
<<"actor">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_admin_actor_attr_jid(undefined, _acc) ->
_acc;
encode_muc_admin_actor_attr_jid(_val, _acc) ->
[{<<"jid">>, jid:encode(_val)} | _acc].
decode_muc_admin_actor_attr_nick(__TopXMLNS,
undefined) ->
<<>>;
decode_muc_admin_actor_attr_nick(__TopXMLNS, _val) ->
_val.
encode_muc_admin_actor_attr_nick(<<>>, _acc) -> _acc;
encode_muc_admin_actor_attr_nick(_val, _acc) ->
[{<<"nick">>, _val} | _acc].
decode_muc_admin_item(__TopXMLNS, __Opts,
{xmlel, <<"item">>, _attrs, _els}) ->
{Actor, Continue, Reason} =
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
undefined,
undefined,
<<>>),
{Affiliation, Role, Jid, Nick} =
decode_muc_admin_item_attrs(__TopXMLNS,
_attrs,
undefined,
undefined,
undefined,
undefined),
{muc_item,
Actor,
Continue,
Reason,
Affiliation,
Role,
Jid,
Nick}.
decode_muc_admin_item_els(__TopXMLNS, __Opts, [], Actor,
Continue, Reason) ->
{Actor, Continue, Reason};
decode_muc_admin_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"actor">>, _attrs, _} = _el | _els], Actor,
Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#admin">> ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
decode_muc_admin_actor(<<"#admin">>,
__Opts,
_el),
Continue,
Reason);
_ ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_admin_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"continue">>, _attrs, _} = _el | _els],
Actor, Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#admin">> ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
decode_muc_admin_continue(<<"#admin">>,
__Opts,
_el),
Reason);
_ ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_admin_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"reason">>, _attrs, _} = _el | _els],
Actor, Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#user">>,
__Opts,
_el));
<<"#admin">> ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#admin">>,
__Opts,
_el));
<<"#owner">> ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#owner">>,
__Opts,
_el));
_ ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_admin_item_els(__TopXMLNS, __Opts,
[_ | _els], Actor, Continue, Reason) ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason).
decode_muc_admin_item_attrs(__TopXMLNS,
[{<<"affiliation">>, _val} | _attrs], _Affiliation,
Role, Jid, Nick) ->
decode_muc_admin_item_attrs(__TopXMLNS,
_attrs,
_val,
Role,
Jid,
Nick);
decode_muc_admin_item_attrs(__TopXMLNS,
[{<<"role">>, _val} | _attrs], Affiliation, _Role,
Jid, Nick) ->
decode_muc_admin_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
_val,
Jid,
Nick);
decode_muc_admin_item_attrs(__TopXMLNS,
[{<<"jid">>, _val} | _attrs], Affiliation, Role,
_Jid, Nick) ->
decode_muc_admin_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
_val,
Nick);
decode_muc_admin_item_attrs(__TopXMLNS,
[{<<"nick">>, _val} | _attrs], Affiliation, Role,
Jid, _Nick) ->
decode_muc_admin_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
Jid,
_val);
decode_muc_admin_item_attrs(__TopXMLNS, [_ | _attrs],
Affiliation, Role, Jid, Nick) ->
decode_muc_admin_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
Jid,
Nick);
decode_muc_admin_item_attrs(__TopXMLNS, [], Affiliation,
Role, Jid, Nick) ->
{decode_muc_admin_item_attr_affiliation(__TopXMLNS,
Affiliation),
decode_muc_admin_item_attr_role(__TopXMLNS, Role),
decode_muc_admin_item_attr_jid(__TopXMLNS, Jid),
decode_muc_admin_item_attr_nick(__TopXMLNS, Nick)}.
encode_muc_admin_item({muc_item,
Actor,
Continue,
Reason,
Affiliation,
Role,
Jid,
Nick},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#admin">>,
[],
__TopXMLNS),
_els =
lists:reverse('encode_muc_admin_item_$actor'(Actor,
__NewTopXMLNS,
'encode_muc_admin_item_$continue'(Continue,
__NewTopXMLNS,
'encode_muc_admin_item_$reason'(Reason,
__NewTopXMLNS,
[])))),
_attrs = encode_muc_admin_item_attr_nick(Nick,
encode_muc_admin_item_attr_jid(Jid,
encode_muc_admin_item_attr_role(Role,
encode_muc_admin_item_attr_affiliation(Affiliation,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))))),
{xmlel, <<"item">>, _attrs, _els}.
'encode_muc_admin_item_$actor'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_admin_item_$actor'(Actor, __TopXMLNS,
_acc) ->
[encode_muc_admin_actor(Actor, __TopXMLNS) | _acc].
'encode_muc_admin_item_$continue'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_admin_item_$continue'(Continue, __TopXMLNS,
_acc) ->
[encode_muc_admin_continue(Continue, __TopXMLNS)
| _acc].
'encode_muc_admin_item_$reason'(<<>>, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_admin_item_$reason'(Reason, __TopXMLNS,
_acc) ->
[encode_muc_reason(Reason, __TopXMLNS) | _acc].
decode_muc_admin_item_attr_affiliation(__TopXMLNS,
undefined) ->
undefined;
decode_muc_admin_item_attr_affiliation(__TopXMLNS,
_val) ->
case catch dec_enum(_val,
[admin, member, none, outcast, owner])
of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"affiliation">>,
<<"item">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_admin_item_attr_affiliation(undefined,
_acc) ->
_acc;
encode_muc_admin_item_attr_affiliation(_val, _acc) ->
[{<<"affiliation">>, enc_enum(_val)} | _acc].
decode_muc_admin_item_attr_role(__TopXMLNS,
undefined) ->
undefined;
decode_muc_admin_item_attr_role(__TopXMLNS, _val) ->
case catch dec_enum(_val,
[moderator, none, participant, visitor])
of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"role">>,
<<"item">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_admin_item_attr_role(undefined, _acc) ->
_acc;
encode_muc_admin_item_attr_role(_val, _acc) ->
[{<<"role">>, enc_enum(_val)} | _acc].
decode_muc_admin_item_attr_jid(__TopXMLNS, undefined) ->
undefined;
decode_muc_admin_item_attr_jid(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value, <<"jid">>, <<"item">>, __TopXMLNS}});
_res -> _res
end.
encode_muc_admin_item_attr_jid(undefined, _acc) -> _acc;
encode_muc_admin_item_attr_jid(_val, _acc) ->
[{<<"jid">>, jid:encode(_val)} | _acc].
decode_muc_admin_item_attr_nick(__TopXMLNS,
undefined) ->
<<>>;
decode_muc_admin_item_attr_nick(__TopXMLNS, _val) ->
_val.
encode_muc_admin_item_attr_nick(<<>>, _acc) -> _acc;
encode_muc_admin_item_attr_nick(_val, _acc) ->
[{<<"nick">>, _val} | _acc].
decode_muc_owner_item(__TopXMLNS, __Opts,
{xmlel, <<"item">>, _attrs, _els}) ->
{Actor, Continue, Reason} =
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
undefined,
undefined,
<<>>),
{Affiliation, Role, Jid, Nick} =
decode_muc_owner_item_attrs(__TopXMLNS,
_attrs,
undefined,
undefined,
undefined,
undefined),
{muc_item,
Actor,
Continue,
Reason,
Affiliation,
Role,
Jid,
Nick}.
decode_muc_owner_item_els(__TopXMLNS, __Opts, [], Actor,
Continue, Reason) ->
{Actor, Continue, Reason};
decode_muc_owner_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"actor">>, _attrs, _} = _el | _els], Actor,
Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#admin">> ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
decode_muc_admin_actor(<<"#admin">>,
__Opts,
_el),
Continue,
Reason);
_ ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_owner_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"continue">>, _attrs, _} = _el | _els],
Actor, Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#admin">> ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
decode_muc_admin_continue(<<"#admin">>,
__Opts,
_el),
Reason);
_ ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_owner_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"reason">>, _attrs, _} = _el | _els],
Actor, Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#user">>,
__Opts,
_el));
<<"#admin">> ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#admin">>,
__Opts,
_el));
<<"#owner">> ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#owner">>,
__Opts,
_el));
_ ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_owner_item_els(__TopXMLNS, __Opts,
[_ | _els], Actor, Continue, Reason) ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason).
decode_muc_owner_item_attrs(__TopXMLNS,
[{<<"affiliation">>, _val} | _attrs], _Affiliation,
Role, Jid, Nick) ->
decode_muc_owner_item_attrs(__TopXMLNS,
_attrs,
_val,
Role,
Jid,
Nick);
decode_muc_owner_item_attrs(__TopXMLNS,
[{<<"role">>, _val} | _attrs], Affiliation, _Role,
Jid, Nick) ->
decode_muc_owner_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
_val,
Jid,
Nick);
decode_muc_owner_item_attrs(__TopXMLNS,
[{<<"jid">>, _val} | _attrs], Affiliation, Role,
_Jid, Nick) ->
decode_muc_owner_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
_val,
Nick);
decode_muc_owner_item_attrs(__TopXMLNS,
[{<<"nick">>, _val} | _attrs], Affiliation, Role,
Jid, _Nick) ->
decode_muc_owner_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
Jid,
_val);
decode_muc_owner_item_attrs(__TopXMLNS, [_ | _attrs],
Affiliation, Role, Jid, Nick) ->
decode_muc_owner_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
Jid,
Nick);
decode_muc_owner_item_attrs(__TopXMLNS, [], Affiliation,
Role, Jid, Nick) ->
{decode_muc_owner_item_attr_affiliation(__TopXMLNS,
Affiliation),
decode_muc_owner_item_attr_role(__TopXMLNS, Role),
decode_muc_owner_item_attr_jid(__TopXMLNS, Jid),
decode_muc_owner_item_attr_nick(__TopXMLNS, Nick)}.
encode_muc_owner_item({muc_item,
Actor,
Continue,
Reason,
Affiliation,
Role,
Jid,
Nick},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#owner">>,
[],
__TopXMLNS),
_els =
lists:reverse('encode_muc_owner_item_$actor'(Actor,
__NewTopXMLNS,
'encode_muc_owner_item_$continue'(Continue,
__NewTopXMLNS,
'encode_muc_owner_item_$reason'(Reason,
__NewTopXMLNS,
[])))),
_attrs = encode_muc_owner_item_attr_nick(Nick,
encode_muc_owner_item_attr_jid(Jid,
encode_muc_owner_item_attr_role(Role,
encode_muc_owner_item_attr_affiliation(Affiliation,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))))),
{xmlel, <<"item">>, _attrs, _els}.
'encode_muc_owner_item_$actor'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_owner_item_$actor'(Actor, __TopXMLNS,
_acc) ->
[encode_muc_admin_actor(Actor, __TopXMLNS) | _acc].
'encode_muc_owner_item_$continue'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_owner_item_$continue'(Continue, __TopXMLNS,
_acc) ->
[encode_muc_admin_continue(Continue, __TopXMLNS)
| _acc].
'encode_muc_owner_item_$reason'(<<>>, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_owner_item_$reason'(Reason, __TopXMLNS,
_acc) ->
[encode_muc_reason(Reason, __TopXMLNS) | _acc].
decode_muc_owner_item_attr_affiliation(__TopXMLNS,
undefined) ->
undefined;
decode_muc_owner_item_attr_affiliation(__TopXMLNS,
_val) ->
case catch dec_enum(_val,
[admin, member, none, outcast, owner])
of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"affiliation">>,
<<"item">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_owner_item_attr_affiliation(undefined,
_acc) ->
_acc;
encode_muc_owner_item_attr_affiliation(_val, _acc) ->
[{<<"affiliation">>, enc_enum(_val)} | _acc].
decode_muc_owner_item_attr_role(__TopXMLNS,
undefined) ->
undefined;
decode_muc_owner_item_attr_role(__TopXMLNS, _val) ->
case catch dec_enum(_val,
[moderator, none, participant, visitor])
of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"role">>,
<<"item">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_owner_item_attr_role(undefined, _acc) ->
_acc;
encode_muc_owner_item_attr_role(_val, _acc) ->
[{<<"role">>, enc_enum(_val)} | _acc].
decode_muc_owner_item_attr_jid(__TopXMLNS, undefined) ->
undefined;
decode_muc_owner_item_attr_jid(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value, <<"jid">>, <<"item">>, __TopXMLNS}});
_res -> _res
end.
encode_muc_owner_item_attr_jid(undefined, _acc) -> _acc;
encode_muc_owner_item_attr_jid(_val, _acc) ->
[{<<"jid">>, jid:encode(_val)} | _acc].
decode_muc_owner_item_attr_nick(__TopXMLNS,
undefined) ->
<<>>;
decode_muc_owner_item_attr_nick(__TopXMLNS, _val) ->
_val.
encode_muc_owner_item_attr_nick(<<>>, _acc) -> _acc;
encode_muc_owner_item_attr_nick(_val, _acc) ->
[{<<"nick">>, _val} | _acc].
decode_muc_owner(__TopXMLNS, __Opts,
{xmlel, <<"query">>, _attrs, _els}) ->
{Items, Config, Destroy} =
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
[],
undefined,
undefined),
{muc_owner, Destroy, Config, Items}.
decode_muc_owner_els(__TopXMLNS, __Opts, [], Items,
Config, Destroy) ->
{lists:reverse(Items), Config, Destroy};
decode_muc_owner_els(__TopXMLNS, __Opts,
[{xmlel, <<"destroy">>, _attrs, _} = _el | _els], Items,
Config, Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
Items,
Config,
decode_muc_destroy(<<"#user">>,
__Opts,
_el));
<<"#owner">> ->
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
Items,
Config,
decode_muc_destroy(<<"#owner">>,
__Opts,
_el));
_ ->
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
Items,
Config,
Destroy)
end;
decode_muc_owner_els(__TopXMLNS, __Opts,
[{xmlel, <<"x">>, _attrs, _} = _el | _els], Items,
Config, Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"jabber:x:data">> ->
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
Items,
xep0004:decode_xdata(<<"jabber:x:data">>,
__Opts,
_el),
Destroy);
_ ->
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
Items,
Config,
Destroy)
end;
decode_muc_owner_els(__TopXMLNS, __Opts,
[{xmlel, <<"item">>, _attrs, _} = _el | _els], Items,
Config, Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#owner">> ->
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
[decode_muc_owner_item(<<"#owner">>,
__Opts,
_el)
| Items],
Config,
Destroy);
_ ->
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
Items,
Config,
Destroy)
end;
decode_muc_owner_els(__TopXMLNS, __Opts, [_ | _els],
Items, Config, Destroy) ->
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
Items,
Config,
Destroy).
encode_muc_owner({muc_owner, Destroy, Config, Items},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#owner">>,
[],
__TopXMLNS),
_els = lists:reverse('encode_muc_owner_$items'(Items,
__NewTopXMLNS,
'encode_muc_owner_$config'(Config,
__NewTopXMLNS,
'encode_muc_owner_$destroy'(Destroy,
__NewTopXMLNS,
[])))),
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"query">>, _attrs, _els}.
'encode_muc_owner_$items'([], __TopXMLNS, _acc) -> _acc;
'encode_muc_owner_$items'([Items | _els], __TopXMLNS,
_acc) ->
'encode_muc_owner_$items'(_els,
__TopXMLNS,
[encode_muc_owner_item(Items, __TopXMLNS)
| _acc]).
'encode_muc_owner_$config'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_owner_$config'(Config, __TopXMLNS, _acc) ->
[xep0004:encode_xdata(Config, __TopXMLNS) | _acc].
'encode_muc_owner_$destroy'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_owner_$destroy'(Destroy, __TopXMLNS,
_acc) ->
[encode_muc_destroy(Destroy, __TopXMLNS) | _acc].
decode_muc_password(__TopXMLNS, __Opts,
{xmlel, <<"password">>, _attrs, _els}) ->
Cdata = decode_muc_password_els(__TopXMLNS,
__Opts,
_els,
<<>>),
Cdata.
decode_muc_password_els(__TopXMLNS, __Opts, [],
Cdata) ->
decode_muc_password_cdata(__TopXMLNS, Cdata);
decode_muc_password_els(__TopXMLNS, __Opts,
[{xmlcdata, _data} | _els], Cdata) ->
decode_muc_password_els(__TopXMLNS,
__Opts,
_els,
<<Cdata/binary, _data/binary>>);
decode_muc_password_els(__TopXMLNS, __Opts, [_ | _els],
Cdata) ->
decode_muc_password_els(__TopXMLNS,
__Opts,
_els,
Cdata).
encode_muc_password(Cdata, __TopXMLNS) ->
__NewTopXMLNS = xmpp_codec:choose_top_xmlns(<<>>,
[<<"#owner">>,
<<"#user">>,
<<"">>],
__TopXMLNS),
_els = encode_muc_password_cdata(Cdata, []),
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"password">>, _attrs, _els}.
decode_muc_password_cdata(__TopXMLNS, <<>>) -> <<>>;
decode_muc_password_cdata(__TopXMLNS, _val) -> _val.
encode_muc_password_cdata(<<>>, _acc) -> _acc;
encode_muc_password_cdata(_val, _acc) ->
[{xmlcdata, _val} | _acc].
decode_muc_user(__TopXMLNS, __Opts,
{xmlel, <<"x">>, _attrs, _els}) ->
{Status_codes,
Items,
Invites,
Password,
Decline,
Destroy} =
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
[],
[],
[],
undefined,
undefined,
undefined),
{muc_user,
Decline,
Destroy,
Invites,
Items,
Status_codes,
Password}.
decode_muc_user_els(__TopXMLNS, __Opts, [],
Status_codes, Items, Invites, Password, Decline,
Destroy) ->
{lists:reverse(Status_codes),
lists:reverse(Items),
lists:reverse(Invites),
Password,
Decline,
Destroy};
decode_muc_user_els(__TopXMLNS, __Opts,
[{xmlel, <<"decline">>, _attrs, _} = _el | _els],
Status_codes, Items, Invites, Password, Decline,
Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
decode_muc_user_decline(<<"#user">>,
__Opts,
_el),
Destroy);
_ ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
Destroy)
end;
decode_muc_user_els(__TopXMLNS, __Opts,
[{xmlel, <<"destroy">>, _attrs, _} = _el | _els],
Status_codes, Items, Invites, Password, Decline,
Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
decode_muc_destroy(<<"#user">>,
__Opts,
_el));
<<"#owner">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
decode_muc_destroy(<<"#owner">>,
__Opts,
_el));
_ ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
Destroy)
end;
decode_muc_user_els(__TopXMLNS, __Opts,
[{xmlel, <<"password">>, _attrs, _} = _el | _els],
Status_codes, Items, Invites, Password, Decline,
Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#owner">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
decode_muc_password(<<"#owner">>,
__Opts,
_el),
Decline,
Destroy);
<<"#user">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
decode_muc_password(<<"#user">>,
__Opts,
_el),
Decline,
Destroy);
<<"">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
decode_muc_password(<<"">>,
__Opts,
_el),
Decline,
Destroy);
_ ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
Destroy)
end;
decode_muc_user_els(__TopXMLNS, __Opts,
[{xmlel, <<"invite">>, _attrs, _} = _el | _els],
Status_codes, Items, Invites, Password, Decline,
Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
[decode_muc_user_invite(<<"#user">>,
__Opts,
_el)
| Invites],
Password,
Decline,
Destroy);
_ ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
Destroy)
end;
decode_muc_user_els(__TopXMLNS, __Opts,
[{xmlel, <<"item">>, _attrs, _} = _el | _els],
Status_codes, Items, Invites, Password, Decline,
Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
[decode_muc_user_item(<<"#user">>,
__Opts,
_el)
| Items],
Invites,
Password,
Decline,
Destroy);
_ ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
Destroy)
end;
decode_muc_user_els(__TopXMLNS, __Opts,
[{xmlel, <<"status">>, _attrs, _} = _el | _els],
Status_codes, Items, Invites, Password, Decline,
Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
case
decode_muc_user_status(<<"#user">>,
__Opts,
_el)
of
undefined -> Status_codes;
_new_el -> [_new_el | Status_codes]
end,
Items,
Invites,
Password,
Decline,
Destroy);
_ ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
Destroy)
end;
decode_muc_user_els(__TopXMLNS, __Opts, [_ | _els],
Status_codes, Items, Invites, Password, Decline,
Destroy) ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
Destroy).
encode_muc_user({muc_user,
Decline,
Destroy,
Invites,
Items,
Status_codes,
Password},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#user">>,
[],
__TopXMLNS),
_els =
lists:reverse('encode_muc_user_$status_codes'(Status_codes,
__NewTopXMLNS,
'encode_muc_user_$items'(Items,
__NewTopXMLNS,
'encode_muc_user_$invites'(Invites,
__NewTopXMLNS,
'encode_muc_user_$password'(Password,
__NewTopXMLNS,
'encode_muc_user_$decline'(Decline,
__NewTopXMLNS,
'encode_muc_user_$destroy'(Destroy,
__NewTopXMLNS,
[]))))))),
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"x">>, _attrs, _els}.
'encode_muc_user_$status_codes'([], __TopXMLNS, _acc) ->
_acc;
'encode_muc_user_$status_codes'([Status_codes | _els],
__TopXMLNS, _acc) ->
'encode_muc_user_$status_codes'(_els,
__TopXMLNS,
[encode_muc_user_status(Status_codes,
__TopXMLNS)
| _acc]).
'encode_muc_user_$items'([], __TopXMLNS, _acc) -> _acc;
'encode_muc_user_$items'([Items | _els], __TopXMLNS,
_acc) ->
'encode_muc_user_$items'(_els,
__TopXMLNS,
[encode_muc_user_item(Items, __TopXMLNS) | _acc]).
'encode_muc_user_$invites'([], __TopXMLNS, _acc) ->
_acc;
'encode_muc_user_$invites'([Invites | _els], __TopXMLNS,
_acc) ->
'encode_muc_user_$invites'(_els,
__TopXMLNS,
[encode_muc_user_invite(Invites, __TopXMLNS)
| _acc]).
'encode_muc_user_$password'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_user_$password'(Password, __TopXMLNS,
_acc) ->
[encode_muc_password(Password, __TopXMLNS) | _acc].
'encode_muc_user_$decline'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_user_$decline'(Decline, __TopXMLNS, _acc) ->
[encode_muc_user_decline(Decline, __TopXMLNS) | _acc].
'encode_muc_user_$destroy'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_user_$destroy'(Destroy, __TopXMLNS, _acc) ->
[encode_muc_destroy(Destroy, __TopXMLNS) | _acc].
decode_muc_user_item(__TopXMLNS, __Opts,
{xmlel, <<"item">>, _attrs, _els}) ->
{Actor, Continue, Reason} =
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
undefined,
undefined,
<<>>),
{Affiliation, Role, Jid, Nick} =
decode_muc_user_item_attrs(__TopXMLNS,
_attrs,
undefined,
undefined,
undefined,
undefined),
{muc_item,
Actor,
Continue,
Reason,
Affiliation,
Role,
Jid,
Nick}.
decode_muc_user_item_els(__TopXMLNS, __Opts, [], Actor,
Continue, Reason) ->
{Actor, Continue, Reason};
decode_muc_user_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"actor">>, _attrs, _} = _el | _els], Actor,
Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
decode_muc_user_actor(<<"#user">>,
__Opts,
_el),
Continue,
Reason);
_ ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_user_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"continue">>, _attrs, _} = _el | _els],
Actor, Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
decode_muc_user_continue(<<"#user">>,
__Opts,
_el),
Reason);
_ ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_user_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"reason">>, _attrs, _} = _el | _els], Actor,
Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#user">>,
__Opts,
_el));
<<"#admin">> ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#admin">>,
__Opts,
_el));
<<"#owner">> ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#owner">>,
__Opts,
_el));
_ ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_user_item_els(__TopXMLNS, __Opts, [_ | _els],
Actor, Continue, Reason) ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason).
decode_muc_user_item_attrs(__TopXMLNS,
[{<<"affiliation">>, _val} | _attrs], _Affiliation,
Role, Jid, Nick) ->
decode_muc_user_item_attrs(__TopXMLNS,
_attrs,
_val,
Role,
Jid,
Nick);
decode_muc_user_item_attrs(__TopXMLNS,
[{<<"role">>, _val} | _attrs], Affiliation, _Role,
Jid, Nick) ->
decode_muc_user_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
_val,
Jid,
Nick);
decode_muc_user_item_attrs(__TopXMLNS,
[{<<"jid">>, _val} | _attrs], Affiliation, Role,
_Jid, Nick) ->
decode_muc_user_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
_val,
Nick);
decode_muc_user_item_attrs(__TopXMLNS,
[{<<"nick">>, _val} | _attrs], Affiliation, Role,
Jid, _Nick) ->
decode_muc_user_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
Jid,
_val);
decode_muc_user_item_attrs(__TopXMLNS, [_ | _attrs],
Affiliation, Role, Jid, Nick) ->
decode_muc_user_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
Jid,
Nick);
decode_muc_user_item_attrs(__TopXMLNS, [], Affiliation,
Role, Jid, Nick) ->
{decode_muc_user_item_attr_affiliation(__TopXMLNS,
Affiliation),
decode_muc_user_item_attr_role(__TopXMLNS, Role),
decode_muc_user_item_attr_jid(__TopXMLNS, Jid),
decode_muc_user_item_attr_nick(__TopXMLNS, Nick)}.
encode_muc_user_item({muc_item,
Actor,
Continue,
Reason,
Affiliation,
Role,
Jid,
Nick},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#user">>,
[],
__TopXMLNS),
_els =
lists:reverse('encode_muc_user_item_$actor'(Actor,
__NewTopXMLNS,
'encode_muc_user_item_$continue'(Continue,
__NewTopXMLNS,
'encode_muc_user_item_$reason'(Reason,
__NewTopXMLNS,
[])))),
_attrs = encode_muc_user_item_attr_nick(Nick,
encode_muc_user_item_attr_jid(Jid,
encode_muc_user_item_attr_role(Role,
encode_muc_user_item_attr_affiliation(Affiliation,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))))),
{xmlel, <<"item">>, _attrs, _els}.
'encode_muc_user_item_$actor'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_user_item_$actor'(Actor, __TopXMLNS,
_acc) ->
[encode_muc_user_actor(Actor, __TopXMLNS) | _acc].
'encode_muc_user_item_$continue'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_user_item_$continue'(Continue, __TopXMLNS,
_acc) ->
[encode_muc_user_continue(Continue, __TopXMLNS) | _acc].
'encode_muc_user_item_$reason'(<<>>, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_user_item_$reason'(Reason, __TopXMLNS,
_acc) ->
[encode_muc_reason(Reason, __TopXMLNS) | _acc].
decode_muc_user_item_attr_affiliation(__TopXMLNS,
undefined) ->
undefined;
decode_muc_user_item_attr_affiliation(__TopXMLNS,
_val) ->
case catch dec_enum(_val,
[admin, member, none, outcast, owner])
of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"affiliation">>,
<<"item">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_user_item_attr_affiliation(undefined,
_acc) ->
_acc;
encode_muc_user_item_attr_affiliation(_val, _acc) ->
[{<<"affiliation">>, enc_enum(_val)} | _acc].
decode_muc_user_item_attr_role(__TopXMLNS, undefined) ->
undefined;
decode_muc_user_item_attr_role(__TopXMLNS, _val) ->
case catch dec_enum(_val,
[moderator, none, participant, visitor])
of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"role">>,
<<"item">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_user_item_attr_role(undefined, _acc) -> _acc;
encode_muc_user_item_attr_role(_val, _acc) ->
[{<<"role">>, enc_enum(_val)} | _acc].
decode_muc_user_item_attr_jid(__TopXMLNS, undefined) ->
undefined;
decode_muc_user_item_attr_jid(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value, <<"jid">>, <<"item">>, __TopXMLNS}});
_res -> _res
end.
encode_muc_user_item_attr_jid(undefined, _acc) -> _acc;
encode_muc_user_item_attr_jid(_val, _acc) ->
[{<<"jid">>, jid:encode(_val)} | _acc].
decode_muc_user_item_attr_nick(__TopXMLNS, undefined) ->
<<>>;
decode_muc_user_item_attr_nick(__TopXMLNS, _val) ->
_val.
encode_muc_user_item_attr_nick(<<>>, _acc) -> _acc;
encode_muc_user_item_attr_nick(_val, _acc) ->
[{<<"nick">>, _val} | _acc].
decode_muc_user_status(__TopXMLNS, __Opts,
{xmlel, <<"status">>, _attrs, _els}) ->
Code = decode_muc_user_status_attrs(__TopXMLNS,
_attrs,
undefined),
Code.
decode_muc_user_status_attrs(__TopXMLNS,
[{<<"code">>, _val} | _attrs], _Code) ->
decode_muc_user_status_attrs(__TopXMLNS, _attrs, _val);
decode_muc_user_status_attrs(__TopXMLNS, [_ | _attrs],
Code) ->
decode_muc_user_status_attrs(__TopXMLNS, _attrs, Code);
decode_muc_user_status_attrs(__TopXMLNS, [], Code) ->
decode_muc_user_status_attr_code(__TopXMLNS, Code).
encode_muc_user_status(Code, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#user">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_muc_user_status_attr_code(Code,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS)),
{xmlel, <<"status">>, _attrs, _els}.
decode_muc_user_status_attr_code(__TopXMLNS,
undefined) ->
undefined;
decode_muc_user_status_attr_code(__TopXMLNS, _val) ->
case catch dec_int(_val, 100, 999) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"code">>,
<<"status">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_user_status_attr_code(undefined, _acc) ->
_acc;
encode_muc_user_status_attr_code(_val, _acc) ->
[{<<"code">>, enc_int(_val)} | _acc].
decode_muc_user_continue(__TopXMLNS, __Opts,
{xmlel, <<"continue">>, _attrs, _els}) ->
Thread = decode_muc_user_continue_attrs(__TopXMLNS,
_attrs,
undefined),
Thread.
decode_muc_user_continue_attrs(__TopXMLNS,
[{<<"thread">>, _val} | _attrs], _Thread) ->
decode_muc_user_continue_attrs(__TopXMLNS,
_attrs,
_val);
decode_muc_user_continue_attrs(__TopXMLNS, [_ | _attrs],
Thread) ->
decode_muc_user_continue_attrs(__TopXMLNS,
_attrs,
Thread);
decode_muc_user_continue_attrs(__TopXMLNS, [],
Thread) ->
decode_muc_user_continue_attr_thread(__TopXMLNS,
Thread).
encode_muc_user_continue(Thread, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#user">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_muc_user_continue_attr_thread(Thread,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS)),
{xmlel, <<"continue">>, _attrs, _els}.
decode_muc_user_continue_attr_thread(__TopXMLNS,
undefined) ->
<<>>;
decode_muc_user_continue_attr_thread(__TopXMLNS,
_val) ->
_val.
encode_muc_user_continue_attr_thread(<<>>, _acc) ->
_acc;
encode_muc_user_continue_attr_thread(_val, _acc) ->
[{<<"thread">>, _val} | _acc].
decode_muc_user_actor(__TopXMLNS, __Opts,
{xmlel, <<"actor">>, _attrs, _els}) ->
{Jid, Nick} = decode_muc_user_actor_attrs(__TopXMLNS,
_attrs,
undefined,
undefined),
{muc_actor, Jid, Nick}.
decode_muc_user_actor_attrs(__TopXMLNS,
[{<<"jid">>, _val} | _attrs], _Jid, Nick) ->
decode_muc_user_actor_attrs(__TopXMLNS,
_attrs,
_val,
Nick);
decode_muc_user_actor_attrs(__TopXMLNS,
[{<<"nick">>, _val} | _attrs], Jid, _Nick) ->
decode_muc_user_actor_attrs(__TopXMLNS,
_attrs,
Jid,
_val);
decode_muc_user_actor_attrs(__TopXMLNS, [_ | _attrs],
Jid, Nick) ->
decode_muc_user_actor_attrs(__TopXMLNS,
_attrs,
Jid,
Nick);
decode_muc_user_actor_attrs(__TopXMLNS, [], Jid,
Nick) ->
{decode_muc_user_actor_attr_jid(__TopXMLNS, Jid),
decode_muc_user_actor_attr_nick(__TopXMLNS, Nick)}.
encode_muc_user_actor({muc_actor, Jid, Nick},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#user">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_muc_user_actor_attr_nick(Nick,
encode_muc_user_actor_attr_jid(Jid,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))),
{xmlel, <<"actor">>, _attrs, _els}.
decode_muc_user_actor_attr_jid(__TopXMLNS, undefined) ->
undefined;
decode_muc_user_actor_attr_jid(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"jid">>,
<<"actor">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_user_actor_attr_jid(undefined, _acc) -> _acc;
encode_muc_user_actor_attr_jid(_val, _acc) ->
[{<<"jid">>, jid:encode(_val)} | _acc].
decode_muc_user_actor_attr_nick(__TopXMLNS,
undefined) ->
<<>>;
decode_muc_user_actor_attr_nick(__TopXMLNS, _val) ->
_val.
encode_muc_user_actor_attr_nick(<<>>, _acc) -> _acc;
encode_muc_user_actor_attr_nick(_val, _acc) ->
[{<<"nick">>, _val} | _acc].
decode_muc_user_invite(__TopXMLNS, __Opts,
{xmlel, <<"invite">>, _attrs, _els}) ->
{Continue, Reason} =
decode_muc_user_invite_els(__TopXMLNS,
__Opts,
_els,
undefined,
<<>>),
{To, From} = decode_muc_user_invite_attrs(__TopXMLNS,
_attrs,
undefined,
undefined),
{muc_invite, Reason, From, To, Continue}.
decode_muc_user_invite_els(__TopXMLNS, __Opts, [],
Continue, Reason) ->
{Continue, Reason};
decode_muc_user_invite_els(__TopXMLNS, __Opts,
[{xmlel, <<"reason">>, _attrs, _} = _el | _els],
Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_invite_els(__TopXMLNS,
__Opts,
_els,
Continue,
decode_muc_reason(<<"#user">>,
__Opts,
_el));
<<"#admin">> ->
decode_muc_user_invite_els(__TopXMLNS,
__Opts,
_els,
Continue,
decode_muc_reason(<<"#admin">>,
__Opts,
_el));
<<"#owner">> ->
decode_muc_user_invite_els(__TopXMLNS,
__Opts,
_els,
Continue,
decode_muc_reason(<<"#owner">>,
__Opts,
_el));
_ ->
decode_muc_user_invite_els(__TopXMLNS,
__Opts,
_els,
Continue,
Reason)
end;
decode_muc_user_invite_els(__TopXMLNS, __Opts,
[{xmlel, <<"continue">>, _attrs, _} = _el | _els],
Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_invite_els(__TopXMLNS,
__Opts,
_els,
decode_muc_user_continue(<<"#user">>,
__Opts,
_el),
Reason);
_ ->
decode_muc_user_invite_els(__TopXMLNS,
__Opts,
_els,
Continue,
Reason)
end;
decode_muc_user_invite_els(__TopXMLNS, __Opts,
[_ | _els], Continue, Reason) ->
decode_muc_user_invite_els(__TopXMLNS,
__Opts,
_els,
Continue,
Reason).
decode_muc_user_invite_attrs(__TopXMLNS,
[{<<"to">>, _val} | _attrs], _To, From) ->
decode_muc_user_invite_attrs(__TopXMLNS,
_attrs,
_val,
From);
decode_muc_user_invite_attrs(__TopXMLNS,
[{<<"from">>, _val} | _attrs], To, _From) ->
decode_muc_user_invite_attrs(__TopXMLNS,
_attrs,
To,
_val);
decode_muc_user_invite_attrs(__TopXMLNS, [_ | _attrs],
To, From) ->
decode_muc_user_invite_attrs(__TopXMLNS,
_attrs,
To,
From);
decode_muc_user_invite_attrs(__TopXMLNS, [], To,
From) ->
{decode_muc_user_invite_attr_to(__TopXMLNS, To),
decode_muc_user_invite_attr_from(__TopXMLNS, From)}.
encode_muc_user_invite({muc_invite,
Reason,
From,
To,
Continue},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#user">>,
[],
__TopXMLNS),
_els =
lists:reverse('encode_muc_user_invite_$continue'(Continue,
__NewTopXMLNS,
'encode_muc_user_invite_$reason'(Reason,
__NewTopXMLNS,
[]))),
_attrs = encode_muc_user_invite_attr_from(From,
encode_muc_user_invite_attr_to(To,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))),
{xmlel, <<"invite">>, _attrs, _els}.
'encode_muc_user_invite_$continue'(undefined,
__TopXMLNS, _acc) ->
_acc;
'encode_muc_user_invite_$continue'(Continue, __TopXMLNS,
_acc) ->
[encode_muc_user_continue(Continue, __TopXMLNS) | _acc].
'encode_muc_user_invite_$reason'(<<>>, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_user_invite_$reason'(Reason, __TopXMLNS,
_acc) ->
[encode_muc_reason(Reason, __TopXMLNS) | _acc].
decode_muc_user_invite_attr_to(__TopXMLNS, undefined) ->
undefined;
decode_muc_user_invite_attr_to(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"to">>,
<<"invite">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_user_invite_attr_to(undefined, _acc) -> _acc;
encode_muc_user_invite_attr_to(_val, _acc) ->
[{<<"to">>, jid:encode(_val)} | _acc].
decode_muc_user_invite_attr_from(__TopXMLNS,
undefined) ->
undefined;
decode_muc_user_invite_attr_from(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"from">>,
<<"invite">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_user_invite_attr_from(undefined, _acc) ->
_acc;
encode_muc_user_invite_attr_from(_val, _acc) ->
[{<<"from">>, jid:encode(_val)} | _acc].
decode_muc_destroy(__TopXMLNS, __Opts,
{xmlel, <<"destroy">>, _attrs, _els}) ->
{Password, Reason} = decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
undefined,
<<>>),
{Jid, Xmlns} = decode_muc_destroy_attrs(__TopXMLNS,
_attrs,
undefined,
undefined),
{muc_destroy, Xmlns, Jid, Reason, Password}.
decode_muc_destroy_els(__TopXMLNS, __Opts, [], Password,
Reason) ->
{Password, Reason};
decode_muc_destroy_els(__TopXMLNS, __Opts,
[{xmlel, <<"reason">>, _attrs, _} = _el | _els],
Password, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
Password,
decode_muc_reason(<<"#user">>,
__Opts,
_el));
<<"#admin">> ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
Password,
decode_muc_reason(<<"#admin">>,
__Opts,
_el));
<<"#owner">> ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
Password,
decode_muc_reason(<<"#owner">>,
__Opts,
_el));
_ ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
Password,
Reason)
end;
decode_muc_destroy_els(__TopXMLNS, __Opts,
[{xmlel, <<"password">>, _attrs, _} = _el | _els],
Password, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#owner">> ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
decode_muc_password(<<"#owner">>,
__Opts,
_el),
Reason);
<<"#user">> ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
decode_muc_password(<<"#user">>,
__Opts,
_el),
Reason);
<<"">> ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
decode_muc_password(<<"">>,
__Opts,
_el),
Reason);
_ ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
Password,
Reason)
end;
decode_muc_destroy_els(__TopXMLNS, __Opts, [_ | _els],
Password, Reason) ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
Password,
Reason).
decode_muc_destroy_attrs(__TopXMLNS,
[{<<"jid">>, _val} | _attrs], _Jid, Xmlns) ->
decode_muc_destroy_attrs(__TopXMLNS,
_attrs,
_val,
Xmlns);
decode_muc_destroy_attrs(__TopXMLNS,
[{<<"xmlns">>, _val} | _attrs], Jid, _Xmlns) ->
decode_muc_destroy_attrs(__TopXMLNS, _attrs, Jid, _val);
decode_muc_destroy_attrs(__TopXMLNS, [_ | _attrs], Jid,
Xmlns) ->
decode_muc_destroy_attrs(__TopXMLNS,
_attrs,
Jid,
Xmlns);
decode_muc_destroy_attrs(__TopXMLNS, [], Jid, Xmlns) ->
{decode_muc_destroy_attr_jid(__TopXMLNS, Jid),
decode_muc_destroy_attr_xmlns(__TopXMLNS, Xmlns)}.
encode_muc_destroy({muc_destroy,
Xmlns,
Jid,
Reason,
Password},
__TopXMLNS) ->
__NewTopXMLNS = xmpp_codec:choose_top_xmlns(Xmlns,
[<<"#user">>,
<<"#owner">>],
__TopXMLNS),
_els =
lists:reverse('encode_muc_destroy_$password'(Password,
__NewTopXMLNS,
'encode_muc_destroy_$reason'(Reason,
__NewTopXMLNS,
[]))),
_attrs = encode_muc_destroy_attr_jid(Jid,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS)),
{xmlel, <<"destroy">>, _attrs, _els}.
'encode_muc_destroy_$password'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_destroy_$password'(Password, __TopXMLNS,
_acc) ->
[encode_muc_password(Password, __TopXMLNS) | _acc].
'encode_muc_destroy_$reason'(<<>>, __TopXMLNS, _acc) ->
_acc;
'encode_muc_destroy_$reason'(Reason, __TopXMLNS,
_acc) ->
[encode_muc_reason(Reason, __TopXMLNS) | _acc].
decode_muc_destroy_attr_jid(__TopXMLNS, undefined) ->
undefined;
decode_muc_destroy_attr_jid(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"jid">>,
<<"destroy">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_destroy_attr_jid(undefined, _acc) -> _acc;
encode_muc_destroy_attr_jid(_val, _acc) ->
[{<<"jid">>, jid:encode(_val)} | _acc].
decode_muc_destroy_attr_xmlns(__TopXMLNS, undefined) ->
<<>>;
decode_muc_destroy_attr_xmlns(__TopXMLNS, _val) -> _val.
decode_muc_user_decline(__TopXMLNS, __Opts,
{xmlel, <<"decline">>, _attrs, _els}) ->
Reason = decode_muc_user_decline_els(__TopXMLNS,
__Opts,
_els,
<<>>),
{To, From} = decode_muc_user_decline_attrs(__TopXMLNS,
_attrs,
undefined,
undefined),
{muc_decline, Reason, From, To}.
decode_muc_user_decline_els(__TopXMLNS, __Opts, [],
Reason) ->
Reason;
decode_muc_user_decline_els(__TopXMLNS, __Opts,
[{xmlel, <<"reason">>, _attrs, _} = _el | _els],
Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_decline_els(__TopXMLNS,
__Opts,
_els,
decode_muc_reason(<<"#user">>,
__Opts,
_el));
<<"#admin">> ->
decode_muc_user_decline_els(__TopXMLNS,
__Opts,
_els,
decode_muc_reason(<<"#admin">>,
__Opts,
_el));
<<"#owner">> ->
decode_muc_user_decline_els(__TopXMLNS,
__Opts,
_els,
decode_muc_reason(<<"#owner">>,
__Opts,
_el));
_ ->
decode_muc_user_decline_els(__TopXMLNS,
__Opts,
_els,
Reason)
end;
decode_muc_user_decline_els(__TopXMLNS, __Opts,
[_ | _els], Reason) ->
decode_muc_user_decline_els(__TopXMLNS,
__Opts,
_els,
Reason).
decode_muc_user_decline_attrs(__TopXMLNS,
[{<<"to">>, _val} | _attrs], _To, From) ->
decode_muc_user_decline_attrs(__TopXMLNS,
_attrs,
_val,
From);
decode_muc_user_decline_attrs(__TopXMLNS,
[{<<"from">>, _val} | _attrs], To, _From) ->
decode_muc_user_decline_attrs(__TopXMLNS,
_attrs,
To,
_val);
decode_muc_user_decline_attrs(__TopXMLNS, [_ | _attrs],
To, From) ->
decode_muc_user_decline_attrs(__TopXMLNS,
_attrs,
To,
From);
decode_muc_user_decline_attrs(__TopXMLNS, [], To,
From) ->
{decode_muc_user_decline_attr_to(__TopXMLNS, To),
decode_muc_user_decline_attr_from(__TopXMLNS, From)}.
encode_muc_user_decline({muc_decline, Reason, From, To},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#user">>,
[],
__TopXMLNS),
_els =
lists:reverse('encode_muc_user_decline_$reason'(Reason,
__NewTopXMLNS,
[])),
_attrs = encode_muc_user_decline_attr_from(From,
encode_muc_user_decline_attr_to(To,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))),
{xmlel, <<"decline">>, _attrs, _els}.
'encode_muc_user_decline_$reason'(<<>>, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_user_decline_$reason'(Reason, __TopXMLNS,
_acc) ->
[encode_muc_reason(Reason, __TopXMLNS) | _acc].
decode_muc_user_decline_attr_to(__TopXMLNS,
undefined) ->
undefined;
decode_muc_user_decline_attr_to(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"to">>,
<<"decline">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_user_decline_attr_to(undefined, _acc) ->
_acc;
encode_muc_user_decline_attr_to(_val, _acc) ->
[{<<"to">>, jid:encode(_val)} | _acc].
decode_muc_user_decline_attr_from(__TopXMLNS,
undefined) ->
undefined;
decode_muc_user_decline_attr_from(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"from">>,
<<"decline">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_user_decline_attr_from(undefined, _acc) ->
_acc;
encode_muc_user_decline_attr_from(_val, _acc) ->
[{<<"from">>, jid:encode(_val)} | _acc].
decode_muc_reason(__TopXMLNS, __Opts,
{xmlel, <<"reason">>, _attrs, _els}) ->
Cdata = decode_muc_reason_els(__TopXMLNS,
__Opts,
_els,
<<>>),
Cdata.
decode_muc_reason_els(__TopXMLNS, __Opts, [], Cdata) ->
decode_muc_reason_cdata(__TopXMLNS, Cdata);
decode_muc_reason_els(__TopXMLNS, __Opts,
[{xmlcdata, _data} | _els], Cdata) ->
decode_muc_reason_els(__TopXMLNS,
__Opts,
_els,
<<Cdata/binary, _data/binary>>);
decode_muc_reason_els(__TopXMLNS, __Opts, [_ | _els],
Cdata) ->
decode_muc_reason_els(__TopXMLNS, __Opts, _els, Cdata).
encode_muc_reason(Cdata, __TopXMLNS) ->
__NewTopXMLNS = xmpp_codec:choose_top_xmlns(<<>>,
[<<"#user">>,
<<"#admin">>,
<<"#owner">>],
__TopXMLNS),
_els = encode_muc_reason_cdata(Cdata, []),
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"reason">>, _attrs, _els}.
decode_muc_reason_cdata(__TopXMLNS, <<>>) -> <<>>;
decode_muc_reason_cdata(__TopXMLNS, _val) -> _val.
encode_muc_reason_cdata(<<>>, _acc) -> _acc;
encode_muc_reason_cdata(_val, _acc) ->
[{xmlcdata, _val} | _acc].
decode_muc_history(__TopXMLNS, __Opts,
{xmlel, <<"history">>, _attrs, _els}) ->
{Maxchars, Maxstanzas, Seconds, Since} =
decode_muc_history_attrs(__TopXMLNS,
_attrs,
undefined,
undefined,
undefined,
undefined),
{muc_history, Maxchars, Maxstanzas, Seconds, Since}.
decode_muc_history_attrs(__TopXMLNS,
[{<<"maxchars">>, _val} | _attrs], _Maxchars,
Maxstanzas, Seconds, Since) ->
decode_muc_history_attrs(__TopXMLNS,
_attrs,
_val,
Maxstanzas,
Seconds,
Since);
decode_muc_history_attrs(__TopXMLNS,
[{<<"maxstanzas">>, _val} | _attrs], Maxchars,
_Maxstanzas, Seconds, Since) ->
decode_muc_history_attrs(__TopXMLNS,
_attrs,
Maxchars,
_val,
Seconds,
Since);
decode_muc_history_attrs(__TopXMLNS,
[{<<"seconds">>, _val} | _attrs], Maxchars, Maxstanzas,
_Seconds, Since) ->
decode_muc_history_attrs(__TopXMLNS,
_attrs,
Maxchars,
Maxstanzas,
_val,
Since);
decode_muc_history_attrs(__TopXMLNS,
[{<<"since">>, _val} | _attrs], Maxchars, Maxstanzas,
Seconds, _Since) ->
decode_muc_history_attrs(__TopXMLNS,
_attrs,
Maxchars,
Maxstanzas,
Seconds,
_val);
decode_muc_history_attrs(__TopXMLNS, [_ | _attrs],
Maxchars, Maxstanzas, Seconds, Since) ->
decode_muc_history_attrs(__TopXMLNS,
_attrs,
Maxchars,
Maxstanzas,
Seconds,
Since);
decode_muc_history_attrs(__TopXMLNS, [], Maxchars,
Maxstanzas, Seconds, Since) ->
{decode_muc_history_attr_maxchars(__TopXMLNS, Maxchars),
decode_muc_history_attr_maxstanzas(__TopXMLNS,
Maxstanzas),
decode_muc_history_attr_seconds(__TopXMLNS, Seconds),
decode_muc_history_attr_since(__TopXMLNS, Since)}.
encode_muc_history({muc_history,
Maxchars,
Maxstanzas,
Seconds,
Since},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_muc_history_attr_since(Since,
encode_muc_history_attr_seconds(Seconds,
encode_muc_history_attr_maxstanzas(Maxstanzas,
encode_muc_history_attr_maxchars(Maxchars,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))))),
{xmlel, <<"history">>, _attrs, _els}.
decode_muc_history_attr_maxchars(__TopXMLNS,
undefined) ->
undefined;
decode_muc_history_attr_maxchars(__TopXMLNS, _val) ->
case catch dec_int(_val, 0, infinity) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"maxchars">>,
<<"history">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_history_attr_maxchars(undefined, _acc) ->
_acc;
encode_muc_history_attr_maxchars(_val, _acc) ->
[{<<"maxchars">>, enc_int(_val)} | _acc].
decode_muc_history_attr_maxstanzas(__TopXMLNS,
undefined) ->
undefined;
decode_muc_history_attr_maxstanzas(__TopXMLNS, _val) ->
case catch dec_int(_val, 0, infinity) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"maxstanzas">>,
<<"history">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_history_attr_maxstanzas(undefined, _acc) ->
_acc;
encode_muc_history_attr_maxstanzas(_val, _acc) ->
[{<<"maxstanzas">>, enc_int(_val)} | _acc].
decode_muc_history_attr_seconds(__TopXMLNS,
undefined) ->
undefined;
decode_muc_history_attr_seconds(__TopXMLNS, _val) ->
case catch dec_int(_val, 0, infinity) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"seconds">>,
<<"history">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_history_attr_seconds(undefined, _acc) ->
_acc;
encode_muc_history_attr_seconds(_val, _acc) ->
[{<<"seconds">>, enc_int(_val)} | _acc].
decode_muc_history_attr_since(__TopXMLNS, undefined) ->
undefined;
decode_muc_history_attr_since(__TopXMLNS, _val) ->
case catch dec_utc(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"since">>,
<<"history">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_history_attr_since(undefined, _acc) -> _acc;
encode_muc_history_attr_since(_val, _acc) ->
[{<<"since">>, enc_utc(_val)} | _acc].
| null | https://raw.githubusercontent.com/processone/xmpp/88c43c3cf5843a8a0f76eac390980a3a39c972dd/src/xep0045.erl | erlang | Source: xmpp_codec.spec | Created automatically by XML generator ( fxml_gen.erl )
-module(xep0045).
-compile(export_all).
do_decode(<<"unique">>,
<<"#unique">>, El,
Opts) ->
decode_muc_unique(<<"#unique">>,
Opts,
El);
do_decode(<<"x">>, <<"">>,
El, Opts) ->
decode_muc(<<"">>,
Opts,
El);
do_decode(<<"query">>,
<<"#admin">>, El, Opts) ->
decode_muc_admin(<<"#admin">>,
Opts,
El);
do_decode(<<"continue">>,
<<"#admin">>, El, Opts) ->
decode_muc_admin_continue(<<"#admin">>,
Opts,
El);
do_decode(<<"actor">>,
<<"#admin">>, El, Opts) ->
decode_muc_admin_actor(<<"#admin">>,
Opts,
El);
do_decode(<<"item">>,
<<"#admin">>, El, Opts) ->
decode_muc_admin_item(<<"#admin">>,
Opts,
El);
do_decode(<<"item">>,
<<"#owner">>, El, Opts) ->
decode_muc_owner_item(<<"#owner">>,
Opts,
El);
do_decode(<<"query">>,
<<"#owner">>, El, Opts) ->
decode_muc_owner(<<"#owner">>,
Opts,
El);
do_decode(<<"password">>,
<<"#owner">>, El, Opts) ->
decode_muc_password(<<"#owner">>,
Opts,
El);
do_decode(<<"password">>,
<<"#user">>, El, Opts) ->
decode_muc_password(<<"#user">>,
Opts,
El);
do_decode(<<"password">>,
<<"">>, El, Opts) ->
decode_muc_password(<<"">>,
Opts,
El);
do_decode(<<"x">>,
<<"#user">>, El, Opts) ->
decode_muc_user(<<"#user">>,
Opts,
El);
do_decode(<<"item">>,
<<"#user">>, El, Opts) ->
decode_muc_user_item(<<"#user">>,
Opts,
El);
do_decode(<<"status">>,
<<"#user">>, El, Opts) ->
decode_muc_user_status(<<"#user">>,
Opts,
El);
do_decode(<<"continue">>,
<<"#user">>, El, Opts) ->
decode_muc_user_continue(<<"#user">>,
Opts,
El);
do_decode(<<"actor">>,
<<"#user">>, El, Opts) ->
decode_muc_user_actor(<<"#user">>,
Opts,
El);
do_decode(<<"invite">>,
<<"#user">>, El, Opts) ->
decode_muc_user_invite(<<"#user">>,
Opts,
El);
do_decode(<<"destroy">>,
<<"#user">>, El, Opts) ->
decode_muc_destroy(<<"#user">>,
Opts,
El);
do_decode(<<"destroy">>,
<<"#owner">>, El, Opts) ->
decode_muc_destroy(<<"#owner">>,
Opts,
El);
do_decode(<<"decline">>,
<<"#user">>, El, Opts) ->
decode_muc_user_decline(<<"#user">>,
Opts,
El);
do_decode(<<"reason">>,
<<"#user">>, El, Opts) ->
decode_muc_reason(<<"#user">>,
Opts,
El);
do_decode(<<"reason">>,
<<"#admin">>, El, Opts) ->
decode_muc_reason(<<"#admin">>,
Opts,
El);
do_decode(<<"reason">>,
<<"#owner">>, El, Opts) ->
decode_muc_reason(<<"#owner">>,
Opts,
El);
do_decode(<<"history">>,
<<"">>, El, Opts) ->
decode_muc_history(<<"">>,
Opts,
El);
do_decode(Name, <<>>, _, _) ->
erlang:error({xmpp_codec, {missing_tag_xmlns, Name}});
do_decode(Name, XMLNS, _, _) ->
erlang:error({xmpp_codec, {unknown_tag, Name, XMLNS}}).
tags() ->
[{<<"unique">>,
<<"#unique">>},
{<<"x">>, <<"">>},
{<<"query">>,
<<"#admin">>},
{<<"continue">>,
<<"#admin">>},
{<<"actor">>,
<<"#admin">>},
{<<"item">>,
<<"#admin">>},
{<<"item">>,
<<"#owner">>},
{<<"query">>,
<<"#owner">>},
{<<"password">>,
<<"#owner">>},
{<<"password">>,
<<"#user">>},
{<<"password">>, <<"">>},
{<<"x">>, <<"#user">>},
{<<"item">>, <<"#user">>},
{<<"status">>,
<<"#user">>},
{<<"continue">>,
<<"#user">>},
{<<"actor">>,
<<"#user">>},
{<<"invite">>,
<<"#user">>},
{<<"destroy">>,
<<"#user">>},
{<<"destroy">>,
<<"#owner">>},
{<<"decline">>,
<<"#user">>},
{<<"reason">>,
<<"#user">>},
{<<"reason">>,
<<"#admin">>},
{<<"reason">>,
<<"#owner">>},
{<<"history">>, <<"">>}].
do_encode({muc_history, _, _, _, _} = History,
TopXMLNS) ->
encode_muc_history(History, TopXMLNS);
do_encode({muc_decline, _, _, _} = Decline, TopXMLNS) ->
encode_muc_user_decline(Decline, TopXMLNS);
do_encode({muc_destroy, _, _, _, _} = Destroy,
TopXMLNS) ->
encode_muc_destroy(Destroy, TopXMLNS);
do_encode({muc_invite, _, _, _, _} = Invite,
TopXMLNS) ->
encode_muc_user_invite(Invite, TopXMLNS);
do_encode({muc_user, _, _, _, _, _, _} = X, TopXMLNS) ->
encode_muc_user(X, TopXMLNS);
do_encode({muc_owner, _, _, _} = Query, TopXMLNS) ->
encode_muc_owner(Query, TopXMLNS);
do_encode({muc_item, _, _, _, _, _, _, _} = Item,
TopXMLNS) ->
encode_muc_admin_item(Item, TopXMLNS);
do_encode({muc_actor, _, _} = Actor, TopXMLNS) ->
encode_muc_admin_actor(Actor, TopXMLNS);
do_encode({muc_admin, _} = Query, TopXMLNS) ->
encode_muc_admin(Query, TopXMLNS);
do_encode({muc, _, _} = X, TopXMLNS) ->
encode_muc(X, TopXMLNS);
do_encode({muc_unique, _} = Unique, TopXMLNS) ->
encode_muc_unique(Unique, TopXMLNS).
do_get_name({muc, _, _}) -> <<"x">>;
do_get_name({muc_actor, _, _}) -> <<"actor">>;
do_get_name({muc_admin, _}) -> <<"query">>;
do_get_name({muc_decline, _, _, _}) -> <<"decline">>;
do_get_name({muc_destroy, _, _, _, _}) -> <<"destroy">>;
do_get_name({muc_history, _, _, _, _}) -> <<"history">>;
do_get_name({muc_invite, _, _, _, _}) -> <<"invite">>;
do_get_name({muc_item, _, _, _, _, _, _, _}) ->
<<"item">>;
do_get_name({muc_owner, _, _, _}) -> <<"query">>;
do_get_name({muc_unique, _}) -> <<"unique">>;
do_get_name({muc_user, _, _, _, _, _, _}) -> <<"x">>.
do_get_ns({muc, _, _}) ->
<<"">>;
do_get_ns({muc_admin, _}) ->
<<"#admin">>;
do_get_ns({muc_decline, _, _, _}) ->
<<"#user">>;
do_get_ns({muc_destroy, Xmlns, _, _, _}) -> Xmlns;
do_get_ns({muc_history, _, _, _, _}) ->
<<"">>;
do_get_ns({muc_invite, _, _, _, _}) ->
<<"#user">>;
do_get_ns({muc_owner, _, _, _}) ->
<<"#owner">>;
do_get_ns({muc_unique, _}) ->
<<"#unique">>;
do_get_ns({muc_user, _, _, _, _, _, _}) ->
<<"#user">>.
pp(muc_history, 4) ->
[maxchars, maxstanzas, seconds, since];
pp(muc_decline, 3) -> [reason, from, to];
pp(muc_destroy, 4) -> [xmlns, jid, reason, password];
pp(muc_invite, 4) -> [reason, from, to, continue];
pp(muc_user, 6) ->
[decline,
destroy,
invites,
items,
status_codes,
password];
pp(muc_owner, 3) -> [destroy, config, items];
pp(muc_item, 7) ->
[actor, continue, reason, affiliation, role, jid, nick];
pp(muc_actor, 2) -> [jid, nick];
pp(muc_admin, 1) -> [items];
pp(muc, 2) -> [history, password];
pp(muc_unique, 1) -> [name];
pp(_, _) -> no.
records() ->
[{muc_history, 4},
{muc_decline, 3},
{muc_destroy, 4},
{muc_invite, 4},
{muc_user, 6},
{muc_owner, 3},
{muc_item, 7},
{muc_actor, 2},
{muc_admin, 1},
{muc, 2},
{muc_unique, 1}].
dec_enum(Val, Enums) ->
AtomVal = erlang:binary_to_existing_atom(Val, utf8),
case lists:member(AtomVal, Enums) of
true -> AtomVal
end.
dec_int(Val, Min, Max) ->
case erlang:binary_to_integer(Val) of
Int when Int =< Max, Min == infinity -> Int;
Int when Int =< Max, Int >= Min -> Int
end.
dec_utc(Val) -> xmpp_util:decode_timestamp(Val).
enc_enum(Atom) -> erlang:atom_to_binary(Atom, utf8).
enc_int(Int) -> erlang:integer_to_binary(Int).
enc_utc(Val) -> xmpp_util:encode_timestamp(Val).
decode_muc_unique(__TopXMLNS, __Opts,
{xmlel, <<"unique">>, _attrs, _els}) ->
Name = decode_muc_unique_els(__TopXMLNS,
__Opts,
_els,
<<>>),
{muc_unique, Name}.
decode_muc_unique_els(__TopXMLNS, __Opts, [], Name) ->
decode_muc_unique_cdata(__TopXMLNS, Name);
decode_muc_unique_els(__TopXMLNS, __Opts,
[{xmlcdata, _data} | _els], Name) ->
decode_muc_unique_els(__TopXMLNS,
__Opts,
_els,
<<Name/binary, _data/binary>>);
decode_muc_unique_els(__TopXMLNS, __Opts, [_ | _els],
Name) ->
decode_muc_unique_els(__TopXMLNS, __Opts, _els, Name).
encode_muc_unique({muc_unique, Name}, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#unique">>,
[],
__TopXMLNS),
_els = encode_muc_unique_cdata(Name, []),
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"unique">>, _attrs, _els}.
decode_muc_unique_cdata(__TopXMLNS, <<>>) -> <<>>;
decode_muc_unique_cdata(__TopXMLNS, _val) -> _val.
encode_muc_unique_cdata(<<>>, _acc) -> _acc;
encode_muc_unique_cdata(_val, _acc) ->
[{xmlcdata, _val} | _acc].
decode_muc(__TopXMLNS, __Opts,
{xmlel, <<"x">>, _attrs, _els}) ->
{Password, History} = decode_muc_els(__TopXMLNS,
__Opts,
_els,
undefined,
undefined),
{muc, History, Password}.
decode_muc_els(__TopXMLNS, __Opts, [], Password,
History) ->
{Password, History};
decode_muc_els(__TopXMLNS, __Opts,
[{xmlel, <<"history">>, _attrs, _} = _el | _els],
Password, History) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"">> ->
decode_muc_els(__TopXMLNS,
__Opts,
_els,
Password,
decode_muc_history(<<"">>,
__Opts,
_el));
_ ->
decode_muc_els(__TopXMLNS,
__Opts,
_els,
Password,
History)
end;
decode_muc_els(__TopXMLNS, __Opts,
[{xmlel, <<"password">>, _attrs, _} = _el | _els],
Password, History) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#owner">> ->
decode_muc_els(__TopXMLNS,
__Opts,
_els,
decode_muc_password(<<"#owner">>,
__Opts,
_el),
History);
<<"#user">> ->
decode_muc_els(__TopXMLNS,
__Opts,
_els,
decode_muc_password(<<"#user">>,
__Opts,
_el),
History);
<<"">> ->
decode_muc_els(__TopXMLNS,
__Opts,
_els,
decode_muc_password(<<"">>,
__Opts,
_el),
History);
_ ->
decode_muc_els(__TopXMLNS,
__Opts,
_els,
Password,
History)
end;
decode_muc_els(__TopXMLNS, __Opts, [_ | _els], Password,
History) ->
decode_muc_els(__TopXMLNS,
__Opts,
_els,
Password,
History).
encode_muc({muc, History, Password}, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"">>,
[],
__TopXMLNS),
_els = lists:reverse('encode_muc_$password'(Password,
__NewTopXMLNS,
'encode_muc_$history'(History,
__NewTopXMLNS,
[]))),
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"x">>, _attrs, _els}.
'encode_muc_$password'(undefined, __TopXMLNS, _acc) ->
_acc;
'encode_muc_$password'(Password, __TopXMLNS, _acc) ->
[encode_muc_password(Password, __TopXMLNS) | _acc].
'encode_muc_$history'(undefined, __TopXMLNS, _acc) ->
_acc;
'encode_muc_$history'(History, __TopXMLNS, _acc) ->
[encode_muc_history(History, __TopXMLNS) | _acc].
decode_muc_admin(__TopXMLNS, __Opts,
{xmlel, <<"query">>, _attrs, _els}) ->
Items = decode_muc_admin_els(__TopXMLNS,
__Opts,
_els,
[]),
{muc_admin, Items}.
decode_muc_admin_els(__TopXMLNS, __Opts, [], Items) ->
lists:reverse(Items);
decode_muc_admin_els(__TopXMLNS, __Opts,
[{xmlel, <<"item">>, _attrs, _} = _el | _els], Items) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#admin">> ->
decode_muc_admin_els(__TopXMLNS,
__Opts,
_els,
[decode_muc_admin_item(<<"#admin">>,
__Opts,
_el)
| Items]);
_ ->
decode_muc_admin_els(__TopXMLNS, __Opts, _els, Items)
end;
decode_muc_admin_els(__TopXMLNS, __Opts, [_ | _els],
Items) ->
decode_muc_admin_els(__TopXMLNS, __Opts, _els, Items).
encode_muc_admin({muc_admin, Items}, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#admin">>,
[],
__TopXMLNS),
_els = lists:reverse('encode_muc_admin_$items'(Items,
__NewTopXMLNS,
[])),
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"query">>, _attrs, _els}.
'encode_muc_admin_$items'([], __TopXMLNS, _acc) -> _acc;
'encode_muc_admin_$items'([Items | _els], __TopXMLNS,
_acc) ->
'encode_muc_admin_$items'(_els,
__TopXMLNS,
[encode_muc_admin_item(Items, __TopXMLNS)
| _acc]).
decode_muc_admin_continue(__TopXMLNS, __Opts,
{xmlel, <<"continue">>, _attrs, _els}) ->
Thread = decode_muc_admin_continue_attrs(__TopXMLNS,
_attrs,
undefined),
Thread.
decode_muc_admin_continue_attrs(__TopXMLNS,
[{<<"thread">>, _val} | _attrs], _Thread) ->
decode_muc_admin_continue_attrs(__TopXMLNS,
_attrs,
_val);
decode_muc_admin_continue_attrs(__TopXMLNS,
[_ | _attrs], Thread) ->
decode_muc_admin_continue_attrs(__TopXMLNS,
_attrs,
Thread);
decode_muc_admin_continue_attrs(__TopXMLNS, [],
Thread) ->
decode_muc_admin_continue_attr_thread(__TopXMLNS,
Thread).
encode_muc_admin_continue(Thread, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#admin">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_muc_admin_continue_attr_thread(Thread,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS)),
{xmlel, <<"continue">>, _attrs, _els}.
decode_muc_admin_continue_attr_thread(__TopXMLNS,
undefined) ->
<<>>;
decode_muc_admin_continue_attr_thread(__TopXMLNS,
_val) ->
_val.
encode_muc_admin_continue_attr_thread(<<>>, _acc) ->
_acc;
encode_muc_admin_continue_attr_thread(_val, _acc) ->
[{<<"thread">>, _val} | _acc].
decode_muc_admin_actor(__TopXMLNS, __Opts,
{xmlel, <<"actor">>, _attrs, _els}) ->
{Jid, Nick} = decode_muc_admin_actor_attrs(__TopXMLNS,
_attrs,
undefined,
undefined),
{muc_actor, Jid, Nick}.
decode_muc_admin_actor_attrs(__TopXMLNS,
[{<<"jid">>, _val} | _attrs], _Jid, Nick) ->
decode_muc_admin_actor_attrs(__TopXMLNS,
_attrs,
_val,
Nick);
decode_muc_admin_actor_attrs(__TopXMLNS,
[{<<"nick">>, _val} | _attrs], Jid, _Nick) ->
decode_muc_admin_actor_attrs(__TopXMLNS,
_attrs,
Jid,
_val);
decode_muc_admin_actor_attrs(__TopXMLNS, [_ | _attrs],
Jid, Nick) ->
decode_muc_admin_actor_attrs(__TopXMLNS,
_attrs,
Jid,
Nick);
decode_muc_admin_actor_attrs(__TopXMLNS, [], Jid,
Nick) ->
{decode_muc_admin_actor_attr_jid(__TopXMLNS, Jid),
decode_muc_admin_actor_attr_nick(__TopXMLNS, Nick)}.
encode_muc_admin_actor({muc_actor, Jid, Nick},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#admin">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_muc_admin_actor_attr_nick(Nick,
encode_muc_admin_actor_attr_jid(Jid,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))),
{xmlel, <<"actor">>, _attrs, _els}.
decode_muc_admin_actor_attr_jid(__TopXMLNS,
undefined) ->
undefined;
decode_muc_admin_actor_attr_jid(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"jid">>,
<<"actor">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_admin_actor_attr_jid(undefined, _acc) ->
_acc;
encode_muc_admin_actor_attr_jid(_val, _acc) ->
[{<<"jid">>, jid:encode(_val)} | _acc].
decode_muc_admin_actor_attr_nick(__TopXMLNS,
undefined) ->
<<>>;
decode_muc_admin_actor_attr_nick(__TopXMLNS, _val) ->
_val.
encode_muc_admin_actor_attr_nick(<<>>, _acc) -> _acc;
encode_muc_admin_actor_attr_nick(_val, _acc) ->
[{<<"nick">>, _val} | _acc].
decode_muc_admin_item(__TopXMLNS, __Opts,
{xmlel, <<"item">>, _attrs, _els}) ->
{Actor, Continue, Reason} =
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
undefined,
undefined,
<<>>),
{Affiliation, Role, Jid, Nick} =
decode_muc_admin_item_attrs(__TopXMLNS,
_attrs,
undefined,
undefined,
undefined,
undefined),
{muc_item,
Actor,
Continue,
Reason,
Affiliation,
Role,
Jid,
Nick}.
decode_muc_admin_item_els(__TopXMLNS, __Opts, [], Actor,
Continue, Reason) ->
{Actor, Continue, Reason};
decode_muc_admin_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"actor">>, _attrs, _} = _el | _els], Actor,
Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#admin">> ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
decode_muc_admin_actor(<<"#admin">>,
__Opts,
_el),
Continue,
Reason);
_ ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_admin_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"continue">>, _attrs, _} = _el | _els],
Actor, Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#admin">> ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
decode_muc_admin_continue(<<"#admin">>,
__Opts,
_el),
Reason);
_ ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_admin_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"reason">>, _attrs, _} = _el | _els],
Actor, Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#user">>,
__Opts,
_el));
<<"#admin">> ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#admin">>,
__Opts,
_el));
<<"#owner">> ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#owner">>,
__Opts,
_el));
_ ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_admin_item_els(__TopXMLNS, __Opts,
[_ | _els], Actor, Continue, Reason) ->
decode_muc_admin_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason).
decode_muc_admin_item_attrs(__TopXMLNS,
[{<<"affiliation">>, _val} | _attrs], _Affiliation,
Role, Jid, Nick) ->
decode_muc_admin_item_attrs(__TopXMLNS,
_attrs,
_val,
Role,
Jid,
Nick);
decode_muc_admin_item_attrs(__TopXMLNS,
[{<<"role">>, _val} | _attrs], Affiliation, _Role,
Jid, Nick) ->
decode_muc_admin_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
_val,
Jid,
Nick);
decode_muc_admin_item_attrs(__TopXMLNS,
[{<<"jid">>, _val} | _attrs], Affiliation, Role,
_Jid, Nick) ->
decode_muc_admin_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
_val,
Nick);
decode_muc_admin_item_attrs(__TopXMLNS,
[{<<"nick">>, _val} | _attrs], Affiliation, Role,
Jid, _Nick) ->
decode_muc_admin_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
Jid,
_val);
decode_muc_admin_item_attrs(__TopXMLNS, [_ | _attrs],
Affiliation, Role, Jid, Nick) ->
decode_muc_admin_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
Jid,
Nick);
decode_muc_admin_item_attrs(__TopXMLNS, [], Affiliation,
Role, Jid, Nick) ->
{decode_muc_admin_item_attr_affiliation(__TopXMLNS,
Affiliation),
decode_muc_admin_item_attr_role(__TopXMLNS, Role),
decode_muc_admin_item_attr_jid(__TopXMLNS, Jid),
decode_muc_admin_item_attr_nick(__TopXMLNS, Nick)}.
encode_muc_admin_item({muc_item,
Actor,
Continue,
Reason,
Affiliation,
Role,
Jid,
Nick},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#admin">>,
[],
__TopXMLNS),
_els =
lists:reverse('encode_muc_admin_item_$actor'(Actor,
__NewTopXMLNS,
'encode_muc_admin_item_$continue'(Continue,
__NewTopXMLNS,
'encode_muc_admin_item_$reason'(Reason,
__NewTopXMLNS,
[])))),
_attrs = encode_muc_admin_item_attr_nick(Nick,
encode_muc_admin_item_attr_jid(Jid,
encode_muc_admin_item_attr_role(Role,
encode_muc_admin_item_attr_affiliation(Affiliation,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))))),
{xmlel, <<"item">>, _attrs, _els}.
'encode_muc_admin_item_$actor'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_admin_item_$actor'(Actor, __TopXMLNS,
_acc) ->
[encode_muc_admin_actor(Actor, __TopXMLNS) | _acc].
'encode_muc_admin_item_$continue'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_admin_item_$continue'(Continue, __TopXMLNS,
_acc) ->
[encode_muc_admin_continue(Continue, __TopXMLNS)
| _acc].
'encode_muc_admin_item_$reason'(<<>>, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_admin_item_$reason'(Reason, __TopXMLNS,
_acc) ->
[encode_muc_reason(Reason, __TopXMLNS) | _acc].
decode_muc_admin_item_attr_affiliation(__TopXMLNS,
undefined) ->
undefined;
decode_muc_admin_item_attr_affiliation(__TopXMLNS,
_val) ->
case catch dec_enum(_val,
[admin, member, none, outcast, owner])
of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"affiliation">>,
<<"item">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_admin_item_attr_affiliation(undefined,
_acc) ->
_acc;
encode_muc_admin_item_attr_affiliation(_val, _acc) ->
[{<<"affiliation">>, enc_enum(_val)} | _acc].
decode_muc_admin_item_attr_role(__TopXMLNS,
undefined) ->
undefined;
decode_muc_admin_item_attr_role(__TopXMLNS, _val) ->
case catch dec_enum(_val,
[moderator, none, participant, visitor])
of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"role">>,
<<"item">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_admin_item_attr_role(undefined, _acc) ->
_acc;
encode_muc_admin_item_attr_role(_val, _acc) ->
[{<<"role">>, enc_enum(_val)} | _acc].
decode_muc_admin_item_attr_jid(__TopXMLNS, undefined) ->
undefined;
decode_muc_admin_item_attr_jid(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value, <<"jid">>, <<"item">>, __TopXMLNS}});
_res -> _res
end.
encode_muc_admin_item_attr_jid(undefined, _acc) -> _acc;
encode_muc_admin_item_attr_jid(_val, _acc) ->
[{<<"jid">>, jid:encode(_val)} | _acc].
decode_muc_admin_item_attr_nick(__TopXMLNS,
undefined) ->
<<>>;
decode_muc_admin_item_attr_nick(__TopXMLNS, _val) ->
_val.
encode_muc_admin_item_attr_nick(<<>>, _acc) -> _acc;
encode_muc_admin_item_attr_nick(_val, _acc) ->
[{<<"nick">>, _val} | _acc].
decode_muc_owner_item(__TopXMLNS, __Opts,
{xmlel, <<"item">>, _attrs, _els}) ->
{Actor, Continue, Reason} =
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
undefined,
undefined,
<<>>),
{Affiliation, Role, Jid, Nick} =
decode_muc_owner_item_attrs(__TopXMLNS,
_attrs,
undefined,
undefined,
undefined,
undefined),
{muc_item,
Actor,
Continue,
Reason,
Affiliation,
Role,
Jid,
Nick}.
decode_muc_owner_item_els(__TopXMLNS, __Opts, [], Actor,
Continue, Reason) ->
{Actor, Continue, Reason};
decode_muc_owner_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"actor">>, _attrs, _} = _el | _els], Actor,
Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#admin">> ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
decode_muc_admin_actor(<<"#admin">>,
__Opts,
_el),
Continue,
Reason);
_ ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_owner_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"continue">>, _attrs, _} = _el | _els],
Actor, Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#admin">> ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
decode_muc_admin_continue(<<"#admin">>,
__Opts,
_el),
Reason);
_ ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_owner_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"reason">>, _attrs, _} = _el | _els],
Actor, Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#user">>,
__Opts,
_el));
<<"#admin">> ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#admin">>,
__Opts,
_el));
<<"#owner">> ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#owner">>,
__Opts,
_el));
_ ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_owner_item_els(__TopXMLNS, __Opts,
[_ | _els], Actor, Continue, Reason) ->
decode_muc_owner_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason).
decode_muc_owner_item_attrs(__TopXMLNS,
[{<<"affiliation">>, _val} | _attrs], _Affiliation,
Role, Jid, Nick) ->
decode_muc_owner_item_attrs(__TopXMLNS,
_attrs,
_val,
Role,
Jid,
Nick);
decode_muc_owner_item_attrs(__TopXMLNS,
[{<<"role">>, _val} | _attrs], Affiliation, _Role,
Jid, Nick) ->
decode_muc_owner_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
_val,
Jid,
Nick);
decode_muc_owner_item_attrs(__TopXMLNS,
[{<<"jid">>, _val} | _attrs], Affiliation, Role,
_Jid, Nick) ->
decode_muc_owner_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
_val,
Nick);
decode_muc_owner_item_attrs(__TopXMLNS,
[{<<"nick">>, _val} | _attrs], Affiliation, Role,
Jid, _Nick) ->
decode_muc_owner_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
Jid,
_val);
decode_muc_owner_item_attrs(__TopXMLNS, [_ | _attrs],
Affiliation, Role, Jid, Nick) ->
decode_muc_owner_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
Jid,
Nick);
decode_muc_owner_item_attrs(__TopXMLNS, [], Affiliation,
Role, Jid, Nick) ->
{decode_muc_owner_item_attr_affiliation(__TopXMLNS,
Affiliation),
decode_muc_owner_item_attr_role(__TopXMLNS, Role),
decode_muc_owner_item_attr_jid(__TopXMLNS, Jid),
decode_muc_owner_item_attr_nick(__TopXMLNS, Nick)}.
encode_muc_owner_item({muc_item,
Actor,
Continue,
Reason,
Affiliation,
Role,
Jid,
Nick},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#owner">>,
[],
__TopXMLNS),
_els =
lists:reverse('encode_muc_owner_item_$actor'(Actor,
__NewTopXMLNS,
'encode_muc_owner_item_$continue'(Continue,
__NewTopXMLNS,
'encode_muc_owner_item_$reason'(Reason,
__NewTopXMLNS,
[])))),
_attrs = encode_muc_owner_item_attr_nick(Nick,
encode_muc_owner_item_attr_jid(Jid,
encode_muc_owner_item_attr_role(Role,
encode_muc_owner_item_attr_affiliation(Affiliation,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))))),
{xmlel, <<"item">>, _attrs, _els}.
'encode_muc_owner_item_$actor'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_owner_item_$actor'(Actor, __TopXMLNS,
_acc) ->
[encode_muc_admin_actor(Actor, __TopXMLNS) | _acc].
'encode_muc_owner_item_$continue'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_owner_item_$continue'(Continue, __TopXMLNS,
_acc) ->
[encode_muc_admin_continue(Continue, __TopXMLNS)
| _acc].
'encode_muc_owner_item_$reason'(<<>>, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_owner_item_$reason'(Reason, __TopXMLNS,
_acc) ->
[encode_muc_reason(Reason, __TopXMLNS) | _acc].
decode_muc_owner_item_attr_affiliation(__TopXMLNS,
undefined) ->
undefined;
decode_muc_owner_item_attr_affiliation(__TopXMLNS,
_val) ->
case catch dec_enum(_val,
[admin, member, none, outcast, owner])
of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"affiliation">>,
<<"item">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_owner_item_attr_affiliation(undefined,
_acc) ->
_acc;
encode_muc_owner_item_attr_affiliation(_val, _acc) ->
[{<<"affiliation">>, enc_enum(_val)} | _acc].
decode_muc_owner_item_attr_role(__TopXMLNS,
undefined) ->
undefined;
decode_muc_owner_item_attr_role(__TopXMLNS, _val) ->
case catch dec_enum(_val,
[moderator, none, participant, visitor])
of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"role">>,
<<"item">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_owner_item_attr_role(undefined, _acc) ->
_acc;
encode_muc_owner_item_attr_role(_val, _acc) ->
[{<<"role">>, enc_enum(_val)} | _acc].
decode_muc_owner_item_attr_jid(__TopXMLNS, undefined) ->
undefined;
decode_muc_owner_item_attr_jid(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value, <<"jid">>, <<"item">>, __TopXMLNS}});
_res -> _res
end.
encode_muc_owner_item_attr_jid(undefined, _acc) -> _acc;
encode_muc_owner_item_attr_jid(_val, _acc) ->
[{<<"jid">>, jid:encode(_val)} | _acc].
decode_muc_owner_item_attr_nick(__TopXMLNS,
undefined) ->
<<>>;
decode_muc_owner_item_attr_nick(__TopXMLNS, _val) ->
_val.
encode_muc_owner_item_attr_nick(<<>>, _acc) -> _acc;
encode_muc_owner_item_attr_nick(_val, _acc) ->
[{<<"nick">>, _val} | _acc].
decode_muc_owner(__TopXMLNS, __Opts,
{xmlel, <<"query">>, _attrs, _els}) ->
{Items, Config, Destroy} =
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
[],
undefined,
undefined),
{muc_owner, Destroy, Config, Items}.
decode_muc_owner_els(__TopXMLNS, __Opts, [], Items,
Config, Destroy) ->
{lists:reverse(Items), Config, Destroy};
decode_muc_owner_els(__TopXMLNS, __Opts,
[{xmlel, <<"destroy">>, _attrs, _} = _el | _els], Items,
Config, Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
Items,
Config,
decode_muc_destroy(<<"#user">>,
__Opts,
_el));
<<"#owner">> ->
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
Items,
Config,
decode_muc_destroy(<<"#owner">>,
__Opts,
_el));
_ ->
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
Items,
Config,
Destroy)
end;
decode_muc_owner_els(__TopXMLNS, __Opts,
[{xmlel, <<"x">>, _attrs, _} = _el | _els], Items,
Config, Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"jabber:x:data">> ->
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
Items,
xep0004:decode_xdata(<<"jabber:x:data">>,
__Opts,
_el),
Destroy);
_ ->
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
Items,
Config,
Destroy)
end;
decode_muc_owner_els(__TopXMLNS, __Opts,
[{xmlel, <<"item">>, _attrs, _} = _el | _els], Items,
Config, Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#owner">> ->
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
[decode_muc_owner_item(<<"#owner">>,
__Opts,
_el)
| Items],
Config,
Destroy);
_ ->
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
Items,
Config,
Destroy)
end;
decode_muc_owner_els(__TopXMLNS, __Opts, [_ | _els],
Items, Config, Destroy) ->
decode_muc_owner_els(__TopXMLNS,
__Opts,
_els,
Items,
Config,
Destroy).
encode_muc_owner({muc_owner, Destroy, Config, Items},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#owner">>,
[],
__TopXMLNS),
_els = lists:reverse('encode_muc_owner_$items'(Items,
__NewTopXMLNS,
'encode_muc_owner_$config'(Config,
__NewTopXMLNS,
'encode_muc_owner_$destroy'(Destroy,
__NewTopXMLNS,
[])))),
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"query">>, _attrs, _els}.
'encode_muc_owner_$items'([], __TopXMLNS, _acc) -> _acc;
'encode_muc_owner_$items'([Items | _els], __TopXMLNS,
_acc) ->
'encode_muc_owner_$items'(_els,
__TopXMLNS,
[encode_muc_owner_item(Items, __TopXMLNS)
| _acc]).
'encode_muc_owner_$config'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_owner_$config'(Config, __TopXMLNS, _acc) ->
[xep0004:encode_xdata(Config, __TopXMLNS) | _acc].
'encode_muc_owner_$destroy'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_owner_$destroy'(Destroy, __TopXMLNS,
_acc) ->
[encode_muc_destroy(Destroy, __TopXMLNS) | _acc].
decode_muc_password(__TopXMLNS, __Opts,
{xmlel, <<"password">>, _attrs, _els}) ->
Cdata = decode_muc_password_els(__TopXMLNS,
__Opts,
_els,
<<>>),
Cdata.
decode_muc_password_els(__TopXMLNS, __Opts, [],
Cdata) ->
decode_muc_password_cdata(__TopXMLNS, Cdata);
decode_muc_password_els(__TopXMLNS, __Opts,
[{xmlcdata, _data} | _els], Cdata) ->
decode_muc_password_els(__TopXMLNS,
__Opts,
_els,
<<Cdata/binary, _data/binary>>);
decode_muc_password_els(__TopXMLNS, __Opts, [_ | _els],
Cdata) ->
decode_muc_password_els(__TopXMLNS,
__Opts,
_els,
Cdata).
encode_muc_password(Cdata, __TopXMLNS) ->
__NewTopXMLNS = xmpp_codec:choose_top_xmlns(<<>>,
[<<"#owner">>,
<<"#user">>,
<<"">>],
__TopXMLNS),
_els = encode_muc_password_cdata(Cdata, []),
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"password">>, _attrs, _els}.
decode_muc_password_cdata(__TopXMLNS, <<>>) -> <<>>;
decode_muc_password_cdata(__TopXMLNS, _val) -> _val.
encode_muc_password_cdata(<<>>, _acc) -> _acc;
encode_muc_password_cdata(_val, _acc) ->
[{xmlcdata, _val} | _acc].
decode_muc_user(__TopXMLNS, __Opts,
{xmlel, <<"x">>, _attrs, _els}) ->
{Status_codes,
Items,
Invites,
Password,
Decline,
Destroy} =
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
[],
[],
[],
undefined,
undefined,
undefined),
{muc_user,
Decline,
Destroy,
Invites,
Items,
Status_codes,
Password}.
decode_muc_user_els(__TopXMLNS, __Opts, [],
Status_codes, Items, Invites, Password, Decline,
Destroy) ->
{lists:reverse(Status_codes),
lists:reverse(Items),
lists:reverse(Invites),
Password,
Decline,
Destroy};
decode_muc_user_els(__TopXMLNS, __Opts,
[{xmlel, <<"decline">>, _attrs, _} = _el | _els],
Status_codes, Items, Invites, Password, Decline,
Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
decode_muc_user_decline(<<"#user">>,
__Opts,
_el),
Destroy);
_ ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
Destroy)
end;
decode_muc_user_els(__TopXMLNS, __Opts,
[{xmlel, <<"destroy">>, _attrs, _} = _el | _els],
Status_codes, Items, Invites, Password, Decline,
Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
decode_muc_destroy(<<"#user">>,
__Opts,
_el));
<<"#owner">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
decode_muc_destroy(<<"#owner">>,
__Opts,
_el));
_ ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
Destroy)
end;
decode_muc_user_els(__TopXMLNS, __Opts,
[{xmlel, <<"password">>, _attrs, _} = _el | _els],
Status_codes, Items, Invites, Password, Decline,
Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#owner">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
decode_muc_password(<<"#owner">>,
__Opts,
_el),
Decline,
Destroy);
<<"#user">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
decode_muc_password(<<"#user">>,
__Opts,
_el),
Decline,
Destroy);
<<"">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
decode_muc_password(<<"">>,
__Opts,
_el),
Decline,
Destroy);
_ ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
Destroy)
end;
decode_muc_user_els(__TopXMLNS, __Opts,
[{xmlel, <<"invite">>, _attrs, _} = _el | _els],
Status_codes, Items, Invites, Password, Decline,
Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
[decode_muc_user_invite(<<"#user">>,
__Opts,
_el)
| Invites],
Password,
Decline,
Destroy);
_ ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
Destroy)
end;
decode_muc_user_els(__TopXMLNS, __Opts,
[{xmlel, <<"item">>, _attrs, _} = _el | _els],
Status_codes, Items, Invites, Password, Decline,
Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
[decode_muc_user_item(<<"#user">>,
__Opts,
_el)
| Items],
Invites,
Password,
Decline,
Destroy);
_ ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
Destroy)
end;
decode_muc_user_els(__TopXMLNS, __Opts,
[{xmlel, <<"status">>, _attrs, _} = _el | _els],
Status_codes, Items, Invites, Password, Decline,
Destroy) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
case
decode_muc_user_status(<<"#user">>,
__Opts,
_el)
of
undefined -> Status_codes;
_new_el -> [_new_el | Status_codes]
end,
Items,
Invites,
Password,
Decline,
Destroy);
_ ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
Destroy)
end;
decode_muc_user_els(__TopXMLNS, __Opts, [_ | _els],
Status_codes, Items, Invites, Password, Decline,
Destroy) ->
decode_muc_user_els(__TopXMLNS,
__Opts,
_els,
Status_codes,
Items,
Invites,
Password,
Decline,
Destroy).
encode_muc_user({muc_user,
Decline,
Destroy,
Invites,
Items,
Status_codes,
Password},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#user">>,
[],
__TopXMLNS),
_els =
lists:reverse('encode_muc_user_$status_codes'(Status_codes,
__NewTopXMLNS,
'encode_muc_user_$items'(Items,
__NewTopXMLNS,
'encode_muc_user_$invites'(Invites,
__NewTopXMLNS,
'encode_muc_user_$password'(Password,
__NewTopXMLNS,
'encode_muc_user_$decline'(Decline,
__NewTopXMLNS,
'encode_muc_user_$destroy'(Destroy,
__NewTopXMLNS,
[]))))))),
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"x">>, _attrs, _els}.
'encode_muc_user_$status_codes'([], __TopXMLNS, _acc) ->
_acc;
'encode_muc_user_$status_codes'([Status_codes | _els],
__TopXMLNS, _acc) ->
'encode_muc_user_$status_codes'(_els,
__TopXMLNS,
[encode_muc_user_status(Status_codes,
__TopXMLNS)
| _acc]).
'encode_muc_user_$items'([], __TopXMLNS, _acc) -> _acc;
'encode_muc_user_$items'([Items | _els], __TopXMLNS,
_acc) ->
'encode_muc_user_$items'(_els,
__TopXMLNS,
[encode_muc_user_item(Items, __TopXMLNS) | _acc]).
'encode_muc_user_$invites'([], __TopXMLNS, _acc) ->
_acc;
'encode_muc_user_$invites'([Invites | _els], __TopXMLNS,
_acc) ->
'encode_muc_user_$invites'(_els,
__TopXMLNS,
[encode_muc_user_invite(Invites, __TopXMLNS)
| _acc]).
'encode_muc_user_$password'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_user_$password'(Password, __TopXMLNS,
_acc) ->
[encode_muc_password(Password, __TopXMLNS) | _acc].
'encode_muc_user_$decline'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_user_$decline'(Decline, __TopXMLNS, _acc) ->
[encode_muc_user_decline(Decline, __TopXMLNS) | _acc].
'encode_muc_user_$destroy'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_user_$destroy'(Destroy, __TopXMLNS, _acc) ->
[encode_muc_destroy(Destroy, __TopXMLNS) | _acc].
decode_muc_user_item(__TopXMLNS, __Opts,
{xmlel, <<"item">>, _attrs, _els}) ->
{Actor, Continue, Reason} =
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
undefined,
undefined,
<<>>),
{Affiliation, Role, Jid, Nick} =
decode_muc_user_item_attrs(__TopXMLNS,
_attrs,
undefined,
undefined,
undefined,
undefined),
{muc_item,
Actor,
Continue,
Reason,
Affiliation,
Role,
Jid,
Nick}.
decode_muc_user_item_els(__TopXMLNS, __Opts, [], Actor,
Continue, Reason) ->
{Actor, Continue, Reason};
decode_muc_user_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"actor">>, _attrs, _} = _el | _els], Actor,
Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
decode_muc_user_actor(<<"#user">>,
__Opts,
_el),
Continue,
Reason);
_ ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_user_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"continue">>, _attrs, _} = _el | _els],
Actor, Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
decode_muc_user_continue(<<"#user">>,
__Opts,
_el),
Reason);
_ ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_user_item_els(__TopXMLNS, __Opts,
[{xmlel, <<"reason">>, _attrs, _} = _el | _els], Actor,
Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#user">>,
__Opts,
_el));
<<"#admin">> ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#admin">>,
__Opts,
_el));
<<"#owner">> ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
decode_muc_reason(<<"#owner">>,
__Opts,
_el));
_ ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason)
end;
decode_muc_user_item_els(__TopXMLNS, __Opts, [_ | _els],
Actor, Continue, Reason) ->
decode_muc_user_item_els(__TopXMLNS,
__Opts,
_els,
Actor,
Continue,
Reason).
decode_muc_user_item_attrs(__TopXMLNS,
[{<<"affiliation">>, _val} | _attrs], _Affiliation,
Role, Jid, Nick) ->
decode_muc_user_item_attrs(__TopXMLNS,
_attrs,
_val,
Role,
Jid,
Nick);
decode_muc_user_item_attrs(__TopXMLNS,
[{<<"role">>, _val} | _attrs], Affiliation, _Role,
Jid, Nick) ->
decode_muc_user_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
_val,
Jid,
Nick);
decode_muc_user_item_attrs(__TopXMLNS,
[{<<"jid">>, _val} | _attrs], Affiliation, Role,
_Jid, Nick) ->
decode_muc_user_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
_val,
Nick);
decode_muc_user_item_attrs(__TopXMLNS,
[{<<"nick">>, _val} | _attrs], Affiliation, Role,
Jid, _Nick) ->
decode_muc_user_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
Jid,
_val);
decode_muc_user_item_attrs(__TopXMLNS, [_ | _attrs],
Affiliation, Role, Jid, Nick) ->
decode_muc_user_item_attrs(__TopXMLNS,
_attrs,
Affiliation,
Role,
Jid,
Nick);
decode_muc_user_item_attrs(__TopXMLNS, [], Affiliation,
Role, Jid, Nick) ->
{decode_muc_user_item_attr_affiliation(__TopXMLNS,
Affiliation),
decode_muc_user_item_attr_role(__TopXMLNS, Role),
decode_muc_user_item_attr_jid(__TopXMLNS, Jid),
decode_muc_user_item_attr_nick(__TopXMLNS, Nick)}.
encode_muc_user_item({muc_item,
Actor,
Continue,
Reason,
Affiliation,
Role,
Jid,
Nick},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#user">>,
[],
__TopXMLNS),
_els =
lists:reverse('encode_muc_user_item_$actor'(Actor,
__NewTopXMLNS,
'encode_muc_user_item_$continue'(Continue,
__NewTopXMLNS,
'encode_muc_user_item_$reason'(Reason,
__NewTopXMLNS,
[])))),
_attrs = encode_muc_user_item_attr_nick(Nick,
encode_muc_user_item_attr_jid(Jid,
encode_muc_user_item_attr_role(Role,
encode_muc_user_item_attr_affiliation(Affiliation,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))))),
{xmlel, <<"item">>, _attrs, _els}.
'encode_muc_user_item_$actor'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_user_item_$actor'(Actor, __TopXMLNS,
_acc) ->
[encode_muc_user_actor(Actor, __TopXMLNS) | _acc].
'encode_muc_user_item_$continue'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_user_item_$continue'(Continue, __TopXMLNS,
_acc) ->
[encode_muc_user_continue(Continue, __TopXMLNS) | _acc].
'encode_muc_user_item_$reason'(<<>>, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_user_item_$reason'(Reason, __TopXMLNS,
_acc) ->
[encode_muc_reason(Reason, __TopXMLNS) | _acc].
decode_muc_user_item_attr_affiliation(__TopXMLNS,
undefined) ->
undefined;
decode_muc_user_item_attr_affiliation(__TopXMLNS,
_val) ->
case catch dec_enum(_val,
[admin, member, none, outcast, owner])
of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"affiliation">>,
<<"item">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_user_item_attr_affiliation(undefined,
_acc) ->
_acc;
encode_muc_user_item_attr_affiliation(_val, _acc) ->
[{<<"affiliation">>, enc_enum(_val)} | _acc].
decode_muc_user_item_attr_role(__TopXMLNS, undefined) ->
undefined;
decode_muc_user_item_attr_role(__TopXMLNS, _val) ->
case catch dec_enum(_val,
[moderator, none, participant, visitor])
of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"role">>,
<<"item">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_user_item_attr_role(undefined, _acc) -> _acc;
encode_muc_user_item_attr_role(_val, _acc) ->
[{<<"role">>, enc_enum(_val)} | _acc].
decode_muc_user_item_attr_jid(__TopXMLNS, undefined) ->
undefined;
decode_muc_user_item_attr_jid(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value, <<"jid">>, <<"item">>, __TopXMLNS}});
_res -> _res
end.
encode_muc_user_item_attr_jid(undefined, _acc) -> _acc;
encode_muc_user_item_attr_jid(_val, _acc) ->
[{<<"jid">>, jid:encode(_val)} | _acc].
decode_muc_user_item_attr_nick(__TopXMLNS, undefined) ->
<<>>;
decode_muc_user_item_attr_nick(__TopXMLNS, _val) ->
_val.
encode_muc_user_item_attr_nick(<<>>, _acc) -> _acc;
encode_muc_user_item_attr_nick(_val, _acc) ->
[{<<"nick">>, _val} | _acc].
decode_muc_user_status(__TopXMLNS, __Opts,
{xmlel, <<"status">>, _attrs, _els}) ->
Code = decode_muc_user_status_attrs(__TopXMLNS,
_attrs,
undefined),
Code.
decode_muc_user_status_attrs(__TopXMLNS,
[{<<"code">>, _val} | _attrs], _Code) ->
decode_muc_user_status_attrs(__TopXMLNS, _attrs, _val);
decode_muc_user_status_attrs(__TopXMLNS, [_ | _attrs],
Code) ->
decode_muc_user_status_attrs(__TopXMLNS, _attrs, Code);
decode_muc_user_status_attrs(__TopXMLNS, [], Code) ->
decode_muc_user_status_attr_code(__TopXMLNS, Code).
encode_muc_user_status(Code, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#user">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_muc_user_status_attr_code(Code,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS)),
{xmlel, <<"status">>, _attrs, _els}.
decode_muc_user_status_attr_code(__TopXMLNS,
undefined) ->
undefined;
decode_muc_user_status_attr_code(__TopXMLNS, _val) ->
case catch dec_int(_val, 100, 999) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"code">>,
<<"status">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_user_status_attr_code(undefined, _acc) ->
_acc;
encode_muc_user_status_attr_code(_val, _acc) ->
[{<<"code">>, enc_int(_val)} | _acc].
decode_muc_user_continue(__TopXMLNS, __Opts,
{xmlel, <<"continue">>, _attrs, _els}) ->
Thread = decode_muc_user_continue_attrs(__TopXMLNS,
_attrs,
undefined),
Thread.
decode_muc_user_continue_attrs(__TopXMLNS,
[{<<"thread">>, _val} | _attrs], _Thread) ->
decode_muc_user_continue_attrs(__TopXMLNS,
_attrs,
_val);
decode_muc_user_continue_attrs(__TopXMLNS, [_ | _attrs],
Thread) ->
decode_muc_user_continue_attrs(__TopXMLNS,
_attrs,
Thread);
decode_muc_user_continue_attrs(__TopXMLNS, [],
Thread) ->
decode_muc_user_continue_attr_thread(__TopXMLNS,
Thread).
encode_muc_user_continue(Thread, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#user">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_muc_user_continue_attr_thread(Thread,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS)),
{xmlel, <<"continue">>, _attrs, _els}.
decode_muc_user_continue_attr_thread(__TopXMLNS,
undefined) ->
<<>>;
decode_muc_user_continue_attr_thread(__TopXMLNS,
_val) ->
_val.
encode_muc_user_continue_attr_thread(<<>>, _acc) ->
_acc;
encode_muc_user_continue_attr_thread(_val, _acc) ->
[{<<"thread">>, _val} | _acc].
decode_muc_user_actor(__TopXMLNS, __Opts,
{xmlel, <<"actor">>, _attrs, _els}) ->
{Jid, Nick} = decode_muc_user_actor_attrs(__TopXMLNS,
_attrs,
undefined,
undefined),
{muc_actor, Jid, Nick}.
decode_muc_user_actor_attrs(__TopXMLNS,
[{<<"jid">>, _val} | _attrs], _Jid, Nick) ->
decode_muc_user_actor_attrs(__TopXMLNS,
_attrs,
_val,
Nick);
decode_muc_user_actor_attrs(__TopXMLNS,
[{<<"nick">>, _val} | _attrs], Jid, _Nick) ->
decode_muc_user_actor_attrs(__TopXMLNS,
_attrs,
Jid,
_val);
decode_muc_user_actor_attrs(__TopXMLNS, [_ | _attrs],
Jid, Nick) ->
decode_muc_user_actor_attrs(__TopXMLNS,
_attrs,
Jid,
Nick);
decode_muc_user_actor_attrs(__TopXMLNS, [], Jid,
Nick) ->
{decode_muc_user_actor_attr_jid(__TopXMLNS, Jid),
decode_muc_user_actor_attr_nick(__TopXMLNS, Nick)}.
encode_muc_user_actor({muc_actor, Jid, Nick},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#user">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_muc_user_actor_attr_nick(Nick,
encode_muc_user_actor_attr_jid(Jid,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))),
{xmlel, <<"actor">>, _attrs, _els}.
decode_muc_user_actor_attr_jid(__TopXMLNS, undefined) ->
undefined;
decode_muc_user_actor_attr_jid(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"jid">>,
<<"actor">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_user_actor_attr_jid(undefined, _acc) -> _acc;
encode_muc_user_actor_attr_jid(_val, _acc) ->
[{<<"jid">>, jid:encode(_val)} | _acc].
decode_muc_user_actor_attr_nick(__TopXMLNS,
undefined) ->
<<>>;
decode_muc_user_actor_attr_nick(__TopXMLNS, _val) ->
_val.
encode_muc_user_actor_attr_nick(<<>>, _acc) -> _acc;
encode_muc_user_actor_attr_nick(_val, _acc) ->
[{<<"nick">>, _val} | _acc].
decode_muc_user_invite(__TopXMLNS, __Opts,
{xmlel, <<"invite">>, _attrs, _els}) ->
{Continue, Reason} =
decode_muc_user_invite_els(__TopXMLNS,
__Opts,
_els,
undefined,
<<>>),
{To, From} = decode_muc_user_invite_attrs(__TopXMLNS,
_attrs,
undefined,
undefined),
{muc_invite, Reason, From, To, Continue}.
decode_muc_user_invite_els(__TopXMLNS, __Opts, [],
Continue, Reason) ->
{Continue, Reason};
decode_muc_user_invite_els(__TopXMLNS, __Opts,
[{xmlel, <<"reason">>, _attrs, _} = _el | _els],
Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_invite_els(__TopXMLNS,
__Opts,
_els,
Continue,
decode_muc_reason(<<"#user">>,
__Opts,
_el));
<<"#admin">> ->
decode_muc_user_invite_els(__TopXMLNS,
__Opts,
_els,
Continue,
decode_muc_reason(<<"#admin">>,
__Opts,
_el));
<<"#owner">> ->
decode_muc_user_invite_els(__TopXMLNS,
__Opts,
_els,
Continue,
decode_muc_reason(<<"#owner">>,
__Opts,
_el));
_ ->
decode_muc_user_invite_els(__TopXMLNS,
__Opts,
_els,
Continue,
Reason)
end;
decode_muc_user_invite_els(__TopXMLNS, __Opts,
[{xmlel, <<"continue">>, _attrs, _} = _el | _els],
Continue, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_invite_els(__TopXMLNS,
__Opts,
_els,
decode_muc_user_continue(<<"#user">>,
__Opts,
_el),
Reason);
_ ->
decode_muc_user_invite_els(__TopXMLNS,
__Opts,
_els,
Continue,
Reason)
end;
decode_muc_user_invite_els(__TopXMLNS, __Opts,
[_ | _els], Continue, Reason) ->
decode_muc_user_invite_els(__TopXMLNS,
__Opts,
_els,
Continue,
Reason).
decode_muc_user_invite_attrs(__TopXMLNS,
[{<<"to">>, _val} | _attrs], _To, From) ->
decode_muc_user_invite_attrs(__TopXMLNS,
_attrs,
_val,
From);
decode_muc_user_invite_attrs(__TopXMLNS,
[{<<"from">>, _val} | _attrs], To, _From) ->
decode_muc_user_invite_attrs(__TopXMLNS,
_attrs,
To,
_val);
decode_muc_user_invite_attrs(__TopXMLNS, [_ | _attrs],
To, From) ->
decode_muc_user_invite_attrs(__TopXMLNS,
_attrs,
To,
From);
decode_muc_user_invite_attrs(__TopXMLNS, [], To,
From) ->
{decode_muc_user_invite_attr_to(__TopXMLNS, To),
decode_muc_user_invite_attr_from(__TopXMLNS, From)}.
encode_muc_user_invite({muc_invite,
Reason,
From,
To,
Continue},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#user">>,
[],
__TopXMLNS),
_els =
lists:reverse('encode_muc_user_invite_$continue'(Continue,
__NewTopXMLNS,
'encode_muc_user_invite_$reason'(Reason,
__NewTopXMLNS,
[]))),
_attrs = encode_muc_user_invite_attr_from(From,
encode_muc_user_invite_attr_to(To,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))),
{xmlel, <<"invite">>, _attrs, _els}.
'encode_muc_user_invite_$continue'(undefined,
__TopXMLNS, _acc) ->
_acc;
'encode_muc_user_invite_$continue'(Continue, __TopXMLNS,
_acc) ->
[encode_muc_user_continue(Continue, __TopXMLNS) | _acc].
'encode_muc_user_invite_$reason'(<<>>, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_user_invite_$reason'(Reason, __TopXMLNS,
_acc) ->
[encode_muc_reason(Reason, __TopXMLNS) | _acc].
decode_muc_user_invite_attr_to(__TopXMLNS, undefined) ->
undefined;
decode_muc_user_invite_attr_to(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"to">>,
<<"invite">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_user_invite_attr_to(undefined, _acc) -> _acc;
encode_muc_user_invite_attr_to(_val, _acc) ->
[{<<"to">>, jid:encode(_val)} | _acc].
decode_muc_user_invite_attr_from(__TopXMLNS,
undefined) ->
undefined;
decode_muc_user_invite_attr_from(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"from">>,
<<"invite">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_user_invite_attr_from(undefined, _acc) ->
_acc;
encode_muc_user_invite_attr_from(_val, _acc) ->
[{<<"from">>, jid:encode(_val)} | _acc].
decode_muc_destroy(__TopXMLNS, __Opts,
{xmlel, <<"destroy">>, _attrs, _els}) ->
{Password, Reason} = decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
undefined,
<<>>),
{Jid, Xmlns} = decode_muc_destroy_attrs(__TopXMLNS,
_attrs,
undefined,
undefined),
{muc_destroy, Xmlns, Jid, Reason, Password}.
decode_muc_destroy_els(__TopXMLNS, __Opts, [], Password,
Reason) ->
{Password, Reason};
decode_muc_destroy_els(__TopXMLNS, __Opts,
[{xmlel, <<"reason">>, _attrs, _} = _el | _els],
Password, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
Password,
decode_muc_reason(<<"#user">>,
__Opts,
_el));
<<"#admin">> ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
Password,
decode_muc_reason(<<"#admin">>,
__Opts,
_el));
<<"#owner">> ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
Password,
decode_muc_reason(<<"#owner">>,
__Opts,
_el));
_ ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
Password,
Reason)
end;
decode_muc_destroy_els(__TopXMLNS, __Opts,
[{xmlel, <<"password">>, _attrs, _} = _el | _els],
Password, Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#owner">> ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
decode_muc_password(<<"#owner">>,
__Opts,
_el),
Reason);
<<"#user">> ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
decode_muc_password(<<"#user">>,
__Opts,
_el),
Reason);
<<"">> ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
decode_muc_password(<<"">>,
__Opts,
_el),
Reason);
_ ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
Password,
Reason)
end;
decode_muc_destroy_els(__TopXMLNS, __Opts, [_ | _els],
Password, Reason) ->
decode_muc_destroy_els(__TopXMLNS,
__Opts,
_els,
Password,
Reason).
decode_muc_destroy_attrs(__TopXMLNS,
[{<<"jid">>, _val} | _attrs], _Jid, Xmlns) ->
decode_muc_destroy_attrs(__TopXMLNS,
_attrs,
_val,
Xmlns);
decode_muc_destroy_attrs(__TopXMLNS,
[{<<"xmlns">>, _val} | _attrs], Jid, _Xmlns) ->
decode_muc_destroy_attrs(__TopXMLNS, _attrs, Jid, _val);
decode_muc_destroy_attrs(__TopXMLNS, [_ | _attrs], Jid,
Xmlns) ->
decode_muc_destroy_attrs(__TopXMLNS,
_attrs,
Jid,
Xmlns);
decode_muc_destroy_attrs(__TopXMLNS, [], Jid, Xmlns) ->
{decode_muc_destroy_attr_jid(__TopXMLNS, Jid),
decode_muc_destroy_attr_xmlns(__TopXMLNS, Xmlns)}.
encode_muc_destroy({muc_destroy,
Xmlns,
Jid,
Reason,
Password},
__TopXMLNS) ->
__NewTopXMLNS = xmpp_codec:choose_top_xmlns(Xmlns,
[<<"#user">>,
<<"#owner">>],
__TopXMLNS),
_els =
lists:reverse('encode_muc_destroy_$password'(Password,
__NewTopXMLNS,
'encode_muc_destroy_$reason'(Reason,
__NewTopXMLNS,
[]))),
_attrs = encode_muc_destroy_attr_jid(Jid,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS)),
{xmlel, <<"destroy">>, _attrs, _els}.
'encode_muc_destroy_$password'(undefined, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_destroy_$password'(Password, __TopXMLNS,
_acc) ->
[encode_muc_password(Password, __TopXMLNS) | _acc].
'encode_muc_destroy_$reason'(<<>>, __TopXMLNS, _acc) ->
_acc;
'encode_muc_destroy_$reason'(Reason, __TopXMLNS,
_acc) ->
[encode_muc_reason(Reason, __TopXMLNS) | _acc].
decode_muc_destroy_attr_jid(__TopXMLNS, undefined) ->
undefined;
decode_muc_destroy_attr_jid(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"jid">>,
<<"destroy">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_destroy_attr_jid(undefined, _acc) -> _acc;
encode_muc_destroy_attr_jid(_val, _acc) ->
[{<<"jid">>, jid:encode(_val)} | _acc].
decode_muc_destroy_attr_xmlns(__TopXMLNS, undefined) ->
<<>>;
decode_muc_destroy_attr_xmlns(__TopXMLNS, _val) -> _val.
decode_muc_user_decline(__TopXMLNS, __Opts,
{xmlel, <<"decline">>, _attrs, _els}) ->
Reason = decode_muc_user_decline_els(__TopXMLNS,
__Opts,
_els,
<<>>),
{To, From} = decode_muc_user_decline_attrs(__TopXMLNS,
_attrs,
undefined,
undefined),
{muc_decline, Reason, From, To}.
decode_muc_user_decline_els(__TopXMLNS, __Opts, [],
Reason) ->
Reason;
decode_muc_user_decline_els(__TopXMLNS, __Opts,
[{xmlel, <<"reason">>, _attrs, _} = _el | _els],
Reason) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"#user">> ->
decode_muc_user_decline_els(__TopXMLNS,
__Opts,
_els,
decode_muc_reason(<<"#user">>,
__Opts,
_el));
<<"#admin">> ->
decode_muc_user_decline_els(__TopXMLNS,
__Opts,
_els,
decode_muc_reason(<<"#admin">>,
__Opts,
_el));
<<"#owner">> ->
decode_muc_user_decline_els(__TopXMLNS,
__Opts,
_els,
decode_muc_reason(<<"#owner">>,
__Opts,
_el));
_ ->
decode_muc_user_decline_els(__TopXMLNS,
__Opts,
_els,
Reason)
end;
decode_muc_user_decline_els(__TopXMLNS, __Opts,
[_ | _els], Reason) ->
decode_muc_user_decline_els(__TopXMLNS,
__Opts,
_els,
Reason).
decode_muc_user_decline_attrs(__TopXMLNS,
[{<<"to">>, _val} | _attrs], _To, From) ->
decode_muc_user_decline_attrs(__TopXMLNS,
_attrs,
_val,
From);
decode_muc_user_decline_attrs(__TopXMLNS,
[{<<"from">>, _val} | _attrs], To, _From) ->
decode_muc_user_decline_attrs(__TopXMLNS,
_attrs,
To,
_val);
decode_muc_user_decline_attrs(__TopXMLNS, [_ | _attrs],
To, From) ->
decode_muc_user_decline_attrs(__TopXMLNS,
_attrs,
To,
From);
decode_muc_user_decline_attrs(__TopXMLNS, [], To,
From) ->
{decode_muc_user_decline_attr_to(__TopXMLNS, To),
decode_muc_user_decline_attr_from(__TopXMLNS, From)}.
encode_muc_user_decline({muc_decline, Reason, From, To},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"#user">>,
[],
__TopXMLNS),
_els =
lists:reverse('encode_muc_user_decline_$reason'(Reason,
__NewTopXMLNS,
[])),
_attrs = encode_muc_user_decline_attr_from(From,
encode_muc_user_decline_attr_to(To,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))),
{xmlel, <<"decline">>, _attrs, _els}.
'encode_muc_user_decline_$reason'(<<>>, __TopXMLNS,
_acc) ->
_acc;
'encode_muc_user_decline_$reason'(Reason, __TopXMLNS,
_acc) ->
[encode_muc_reason(Reason, __TopXMLNS) | _acc].
decode_muc_user_decline_attr_to(__TopXMLNS,
undefined) ->
undefined;
decode_muc_user_decline_attr_to(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"to">>,
<<"decline">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_user_decline_attr_to(undefined, _acc) ->
_acc;
encode_muc_user_decline_attr_to(_val, _acc) ->
[{<<"to">>, jid:encode(_val)} | _acc].
decode_muc_user_decline_attr_from(__TopXMLNS,
undefined) ->
undefined;
decode_muc_user_decline_attr_from(__TopXMLNS, _val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"from">>,
<<"decline">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_user_decline_attr_from(undefined, _acc) ->
_acc;
encode_muc_user_decline_attr_from(_val, _acc) ->
[{<<"from">>, jid:encode(_val)} | _acc].
decode_muc_reason(__TopXMLNS, __Opts,
{xmlel, <<"reason">>, _attrs, _els}) ->
Cdata = decode_muc_reason_els(__TopXMLNS,
__Opts,
_els,
<<>>),
Cdata.
decode_muc_reason_els(__TopXMLNS, __Opts, [], Cdata) ->
decode_muc_reason_cdata(__TopXMLNS, Cdata);
decode_muc_reason_els(__TopXMLNS, __Opts,
[{xmlcdata, _data} | _els], Cdata) ->
decode_muc_reason_els(__TopXMLNS,
__Opts,
_els,
<<Cdata/binary, _data/binary>>);
decode_muc_reason_els(__TopXMLNS, __Opts, [_ | _els],
Cdata) ->
decode_muc_reason_els(__TopXMLNS, __Opts, _els, Cdata).
encode_muc_reason(Cdata, __TopXMLNS) ->
__NewTopXMLNS = xmpp_codec:choose_top_xmlns(<<>>,
[<<"#user">>,
<<"#admin">>,
<<"#owner">>],
__TopXMLNS),
_els = encode_muc_reason_cdata(Cdata, []),
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"reason">>, _attrs, _els}.
decode_muc_reason_cdata(__TopXMLNS, <<>>) -> <<>>;
decode_muc_reason_cdata(__TopXMLNS, _val) -> _val.
encode_muc_reason_cdata(<<>>, _acc) -> _acc;
encode_muc_reason_cdata(_val, _acc) ->
[{xmlcdata, _val} | _acc].
decode_muc_history(__TopXMLNS, __Opts,
{xmlel, <<"history">>, _attrs, _els}) ->
{Maxchars, Maxstanzas, Seconds, Since} =
decode_muc_history_attrs(__TopXMLNS,
_attrs,
undefined,
undefined,
undefined,
undefined),
{muc_history, Maxchars, Maxstanzas, Seconds, Since}.
decode_muc_history_attrs(__TopXMLNS,
[{<<"maxchars">>, _val} | _attrs], _Maxchars,
Maxstanzas, Seconds, Since) ->
decode_muc_history_attrs(__TopXMLNS,
_attrs,
_val,
Maxstanzas,
Seconds,
Since);
decode_muc_history_attrs(__TopXMLNS,
[{<<"maxstanzas">>, _val} | _attrs], Maxchars,
_Maxstanzas, Seconds, Since) ->
decode_muc_history_attrs(__TopXMLNS,
_attrs,
Maxchars,
_val,
Seconds,
Since);
decode_muc_history_attrs(__TopXMLNS,
[{<<"seconds">>, _val} | _attrs], Maxchars, Maxstanzas,
_Seconds, Since) ->
decode_muc_history_attrs(__TopXMLNS,
_attrs,
Maxchars,
Maxstanzas,
_val,
Since);
decode_muc_history_attrs(__TopXMLNS,
[{<<"since">>, _val} | _attrs], Maxchars, Maxstanzas,
Seconds, _Since) ->
decode_muc_history_attrs(__TopXMLNS,
_attrs,
Maxchars,
Maxstanzas,
Seconds,
_val);
decode_muc_history_attrs(__TopXMLNS, [_ | _attrs],
Maxchars, Maxstanzas, Seconds, Since) ->
decode_muc_history_attrs(__TopXMLNS,
_attrs,
Maxchars,
Maxstanzas,
Seconds,
Since);
decode_muc_history_attrs(__TopXMLNS, [], Maxchars,
Maxstanzas, Seconds, Since) ->
{decode_muc_history_attr_maxchars(__TopXMLNS, Maxchars),
decode_muc_history_attr_maxstanzas(__TopXMLNS,
Maxstanzas),
decode_muc_history_attr_seconds(__TopXMLNS, Seconds),
decode_muc_history_attr_since(__TopXMLNS, Since)}.
encode_muc_history({muc_history,
Maxchars,
Maxstanzas,
Seconds,
Since},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_muc_history_attr_since(Since,
encode_muc_history_attr_seconds(Seconds,
encode_muc_history_attr_maxstanzas(Maxstanzas,
encode_muc_history_attr_maxchars(Maxchars,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))))),
{xmlel, <<"history">>, _attrs, _els}.
decode_muc_history_attr_maxchars(__TopXMLNS,
undefined) ->
undefined;
decode_muc_history_attr_maxchars(__TopXMLNS, _val) ->
case catch dec_int(_val, 0, infinity) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"maxchars">>,
<<"history">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_history_attr_maxchars(undefined, _acc) ->
_acc;
encode_muc_history_attr_maxchars(_val, _acc) ->
[{<<"maxchars">>, enc_int(_val)} | _acc].
decode_muc_history_attr_maxstanzas(__TopXMLNS,
undefined) ->
undefined;
decode_muc_history_attr_maxstanzas(__TopXMLNS, _val) ->
case catch dec_int(_val, 0, infinity) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"maxstanzas">>,
<<"history">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_history_attr_maxstanzas(undefined, _acc) ->
_acc;
encode_muc_history_attr_maxstanzas(_val, _acc) ->
[{<<"maxstanzas">>, enc_int(_val)} | _acc].
decode_muc_history_attr_seconds(__TopXMLNS,
undefined) ->
undefined;
decode_muc_history_attr_seconds(__TopXMLNS, _val) ->
case catch dec_int(_val, 0, infinity) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"seconds">>,
<<"history">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_history_attr_seconds(undefined, _acc) ->
_acc;
encode_muc_history_attr_seconds(_val, _acc) ->
[{<<"seconds">>, enc_int(_val)} | _acc].
decode_muc_history_attr_since(__TopXMLNS, undefined) ->
undefined;
decode_muc_history_attr_since(__TopXMLNS, _val) ->
case catch dec_utc(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"since">>,
<<"history">>,
__TopXMLNS}});
_res -> _res
end.
encode_muc_history_attr_since(undefined, _acc) -> _acc;
encode_muc_history_attr_since(_val, _acc) ->
[{<<"since">>, enc_utc(_val)} | _acc].
|
76197eb4ac16bc34b3ded069ab228c11d2b9b0c8bf2857b4762974af0d794b25 | tezos/tezos-mirror | test_conflict_handler.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2022 Nomadic Labs , < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
* Testing
-------
Component : Plugin . Mempool
Invocation : dune exec src / proto_alpha / lib_plugin / test / test_conflict_handler.exe
Subject : Unit tests the Mempool.conflict_handler fonction of the plugin
-------
Component: Plugin.Mempool
Invocation: dune exec src/proto_alpha/lib_plugin/test/test_conflict_handler.exe
Subject: Unit tests the Mempool.conflict_handler fonction of the plugin
*)
let pp_answer fmt = function
| `Keep -> Format.fprintf fmt "Keep"
| `Replace -> Format.fprintf fmt "Replace"
let check_answer ?__LOC__ expected actual =
assert
(Qcheck2_helpers.qcheck_eq ~pp:pp_answer ?__LOC__ expected actual : bool)
let is_manager_op ((_ : Operation_hash.t), op) =
This is implemented differently from
[ Plugin . Mempool.is_manager_operation ] ( which relies on
[ Alpha_context . ] ) , used in
[ Plugin . Mempool.conflict_handler ] , to avoid the test being just a
copy of the code .
[Plugin.Mempool.is_manager_operation] (which relies on
[Alpha_context.Operation.acceptable_pass]), used in
[Plugin.Mempool.conflict_handler], to avoid the test being just a
copy of the code. *)
let {Alpha_context.protocol_data = Operation_data proto_data; _} = op in
match proto_data.contents with
| Single (Manager_operation _) | Cons (Manager_operation _, _) -> true
| _ -> false
(** Test that when the operations are not both manager operations, the
conflict handler picks the higher operation according to
[Operation.compare]. *)
let test_random_ops () =
let ops =
let open Operation_generator in
QCheck2.Gen.(generate ~n:100 (pair generate_operation generate_operation))
in
List.iter
(fun ((_, op1), (_, op2)) ->
let answer =
Plugin.Mempool.conflict_handler
Plugin.Mempool.default_config
~existing_operation:op1
~new_operation:op2
in
if is_manager_op op1 && is_manager_op op2 then
(* When both operations are manager operations, the result is
complicated and depends on the [config]. Testing it here
would mean basically reimplementing
[conflict_handler]. Instead, we test this case in
[test_manager_ops] below. *)
()
else if
When there is at least one non - manager operation , the
conflict handler defers to [ Operation.compare ] : the higher
operation is selected .
conflict handler defers to [Operation.compare]: the higher
operation is selected. *)
Alpha_context.Operation.compare op1 op2 >= 0
then check_answer ~__LOC__ `Keep answer
else check_answer ~__LOC__ `Replace answer)
ops ;
return_unit
(** Generator for a manager batch with the specified total fee and gas. *)
let generate_manager_op_with_fee_and_gas ~fee_in_mutez ~gas =
let open Alpha_context in
let open QCheck2.Gen in
let rec set_fee_and_gas :
type kind. _ -> _ -> kind contents_list -> kind contents_list t =
fun desired_total_fee desired_total_gas -> function
| Single (Manager_operation data) ->
let fee = Tez.of_mutez_exn (Int64.of_int desired_total_fee) in
let gas_limit = Gas.Arith.integral_of_int_exn desired_total_gas in
return (Single (Manager_operation {data with fee; gas_limit}))
| Cons (Manager_operation data, tail) ->
let* local_fee =
We generate some corner cases where some individual
operations in the batch have zero fees .
operations in the batch have zero fees. *)
let* r = frequencyl [(7, `Random); (2, `Zero); (1, `All)] in
match r with
| `Random -> int_range 0 desired_total_fee
| `Zero -> return 0
| `All -> return desired_total_fee
in
let* local_gas = int_range 0 desired_total_gas in
let fee = Tez.of_mutez_exn (Int64.of_int local_fee) in
let gas_limit = Gas.Arith.integral_of_int_exn local_gas in
let* tail =
set_fee_and_gas
(desired_total_fee - local_fee)
(desired_total_gas - local_gas)
tail
in
return (Cons (Manager_operation {data with fee; gas_limit}, tail))
| Single _ ->
(* This function is only called on a manager operation. *) assert false
in
(* Generate a random manager operation. *)
let* batch_size = int_range 1 Operation_generator.max_batch_size in
let* op = Operation_generator.generate_manager_operation batch_size in
Modify its fee and gas to match the [ fee_in_mutez ] and [ gas ] inputs .
let {shell = _; protocol_data = Operation_data protocol_data} = op in
let* contents = set_fee_and_gas fee_in_mutez gas protocol_data.contents in
let protocol_data = {protocol_data with contents} in
let op = {op with protocol_data = Operation_data protocol_data} in
return (Operation.hash_packed op, op)
let check_conflict_handler ~__LOC__ config ~old ~nw expected =
let answer =
Plugin.Mempool.conflict_handler
config
~existing_operation:old
~new_operation:nw
in
check_answer ~__LOC__ expected answer
(** Test the semantics of the conflict handler on manager operations,
with either hand-picked or carefully generated fee and gas. *)
let test_manager_ops () =
let make_op ~fee_in_mutez ~gas =
QCheck2.Gen.generate1
(generate_manager_op_with_fee_and_gas ~fee_in_mutez ~gas)
in
Test operations with specific fee and gas , using the default
configuration . This configuration replaces the old operation when
the new one is at least 5 % better , in terms of both fees and
fee / gas ratios .
configuration. This configuration replaces the old operation when
the new one is at least 5% better, in terms of both fees and
fee/gas ratios. *)
let default = Plugin.Mempool.default_config in
let ref_fee = 10_000_000 in
let ref_gas = 2100 in
Reference operation arbitrarily has 10 tez of fees and 2100
gas . The gas is chosen to still give an integer when multiplied
by 100/105 .
gas. The gas is chosen to still give an integer when multiplied
by 100/105. *)
let old = make_op ~fee_in_mutez:ref_fee ~gas:ref_gas in
(* Operation with same fee and ratio. *)
let op_same = make_op ~fee_in_mutez:ref_fee ~gas:ref_gas in
check_conflict_handler ~__LOC__ default ~old ~nw:op_same `Keep ;
5 % better fee but same ratio ( because gas is also 5 % more ) .
let more5 = Q.make (Z.of_int 105) (Z.of_int 100) in
let fee_more5 = Q.(to_int (mul more5 (of_int ref_fee))) in
let gas_more5 = Q.(to_int (mul more5 (of_int ref_gas))) in
let op_fee5 = make_op ~fee_in_mutez:fee_more5 ~gas:gas_more5 in
check_conflict_handler ~__LOC__ default ~old ~nw:op_fee5 `Keep ;
5 % better ratio but same fee ( because gas is multiplied by 100/105 ) .
let less5 = Q.make (Z.of_int 100) (Z.of_int 105) in
let gas_less5 = Q.(to_int (mul less5 (of_int ref_gas))) in
let op_ratio5 = make_op ~fee_in_mutez:ref_fee ~gas:gas_less5 in
check_conflict_handler ~__LOC__ default ~old ~nw:op_ratio5 `Keep ;
Both 5 % better fee and 5 % better ratio .
let op_both5 = make_op ~fee_in_mutez:fee_more5 ~gas:ref_gas in
check_conflict_handler ~__LOC__ default ~old ~nw:op_both5 `Replace ;
Config that requires 10 % better fee and ratio to replace .
let config10 =
{
Plugin.Mempool.default_config with
replace_by_fee_factor = Q.make (Z.of_int 11) (Z.of_int 10);
}
in
check_conflict_handler ~__LOC__ config10 ~old ~nw:op_same `Keep ;
check_conflict_handler ~__LOC__ config10 ~old ~nw:op_fee5 `Keep ;
check_conflict_handler ~__LOC__ config10 ~old ~nw:op_ratio5 `Keep ;
check_conflict_handler ~__LOC__ config10 ~old ~nw:op_both5 `Keep ;
(* Config that replaces when the new op has at least as much fee and ratio. *)
let config0 =
{Plugin.Mempool.default_config with replace_by_fee_factor = Q.one}
in
check_conflict_handler ~__LOC__ config0 ~old ~nw:op_same `Replace ;
check_conflict_handler ~__LOC__ config0 ~old ~nw:op_fee5 `Replace ;
check_conflict_handler ~__LOC__ config0 ~old ~nw:op_ratio5 `Replace ;
check_conflict_handler ~__LOC__ config0 ~old ~nw:op_both5 `Replace ;
(* This config does not replace when the new operation has worse
fees (even when the ratio is higher). *)
let op_less_fee = make_op ~fee_in_mutez:(ref_fee - 1) ~gas:(ref_gas - 1) in
check_conflict_handler ~__LOC__ default ~old ~nw:op_less_fee `Keep ;
(* This config does not replace either when the ratio is smaller. *)
let op_worse_ratio = make_op ~fee_in_mutez:ref_fee ~gas:(ref_gas + 1) in
check_conflict_handler ~__LOC__ default ~old ~nw:op_worse_ratio `Keep ;
Generate random operations which do not have 5 % better fees than
the reference [ op ] : they should not replace [ op ] when using the
default config .
the reference [op]: they should not replace [op] when using the
default config. *)
let open QCheck2.Gen in
let repeat = 30 in
let max_gas = 5 * ref_gas in
let generator_not_5more_fee =
let* fee_in_mutez = int_range 0 (fee_more5 - 1) in
let* gas = int_range 0 max_gas in
Format.eprintf "op_not_fee5: fee = %d; gas = %d@." fee_in_mutez gas ;
generate_manager_op_with_fee_and_gas ~fee_in_mutez ~gas
in
let ops_not_5more_fee = generate ~n:repeat generator_not_5more_fee in
List.iter
(fun nw -> check_conflict_handler ~__LOC__ default ~old ~nw `Keep)
ops_not_5more_fee ;
Generate random operations which do not have 5 % better ratio than
the reference [ op ] : they should not replace [ op ] when using the
default config .
the reference [op]: they should not replace [op] when using the
default config. *)
let ratio_5more =
Q.(mul more5 (make (Z.of_int ref_fee) (Z.of_int ref_gas)))
in
let generator_not_5more_ratio =
let* gas = int_range 0 max_gas in
let fee_for_5more_ratio = Q.(mul (of_int gas) ratio_5more) in
let fee_upper_bound = Q.to_int fee_for_5more_ratio - 1 in
let* fee_in_mutez = int_range 0 (max 0 fee_upper_bound) in
Format.eprintf "op_not_ratio5: fee = %d; gas = %d@." fee_in_mutez gas ;
generate_manager_op_with_fee_and_gas ~fee_in_mutez ~gas
in
let ops_not_5more_ratio = generate ~n:repeat generator_not_5more_ratio in
List.iter
(fun nw -> check_conflict_handler ~__LOC__ default ~old ~nw `Keep)
ops_not_5more_ratio ;
Generate random operations which have both 5 % higher fees and 5 %
better ratio than the reference [ op ] : they should replace [ op ]
when using the default config .
better ratio than the reference [op]: they should replace [op]
when using the default config. *)
let max_fee =
We use a significantly higher factor to define [ max_fee ] from
[ ref_fee ] than [ max_gas ] from [ ref_gas ] . Therefore , even if we
generate a gas equal to [ max_gas ] , we can still generate a fee
that makes the ratio at least 5 % better than the reference
operation 's .
[ref_fee] than [max_gas] from [ref_gas]. Therefore, even if we
generate a gas equal to [max_gas], we can still generate a fee
that makes the ratio at least 5% better than the reference
operation's. *)
10 * ref_fee
in
let generator_both_5more =
let* gas = int_range 0 max_gas in
let fee_for_5more_ratio = Q.(mul (of_int gas) ratio_5more) in
let fee_lower_bound = max fee_more5 (Q.to_int fee_for_5more_ratio + 1) in
let* fee_in_mutez = int_range fee_lower_bound max_fee in
Format.eprintf "op_both_better: fee = %d; gas = %d@." fee_in_mutez gas ;
generate_manager_op_with_fee_and_gas ~fee_in_mutez ~gas
in
let ops_both_5more = generate ~n:repeat generator_both_5more in
List.iter
(fun nw -> check_conflict_handler ~__LOC__ default ~old ~nw `Replace)
ops_both_5more ;
return_unit
let () =
Alcotest_lwt.run
"conflict_handler"
[
( Protocol.name ^ ": conflict_handler",
[
Tztest.tztest
"Random operations (not both manager)"
`Quick
test_random_ops;
Tztest.tztest "Manager operations" `Quick test_manager_ops;
] );
]
|> Lwt_main.run
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/b7f14148a61a8afec9bdb3c16de8f197ee6b8cff/src/proto_alpha/lib_plugin/test/test_conflict_handler.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
* Test that when the operations are not both manager operations, the
conflict handler picks the higher operation according to
[Operation.compare].
When both operations are manager operations, the result is
complicated and depends on the [config]. Testing it here
would mean basically reimplementing
[conflict_handler]. Instead, we test this case in
[test_manager_ops] below.
* Generator for a manager batch with the specified total fee and gas.
This function is only called on a manager operation.
Generate a random manager operation.
* Test the semantics of the conflict handler on manager operations,
with either hand-picked or carefully generated fee and gas.
Operation with same fee and ratio.
Config that replaces when the new op has at least as much fee and ratio.
This config does not replace when the new operation has worse
fees (even when the ratio is higher).
This config does not replace either when the ratio is smaller. | Copyright ( c ) 2022 Nomadic Labs , < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
* Testing
-------
Component : Plugin . Mempool
Invocation : dune exec src / proto_alpha / lib_plugin / test / test_conflict_handler.exe
Subject : Unit tests the Mempool.conflict_handler fonction of the plugin
-------
Component: Plugin.Mempool
Invocation: dune exec src/proto_alpha/lib_plugin/test/test_conflict_handler.exe
Subject: Unit tests the Mempool.conflict_handler fonction of the plugin
*)
let pp_answer fmt = function
| `Keep -> Format.fprintf fmt "Keep"
| `Replace -> Format.fprintf fmt "Replace"
let check_answer ?__LOC__ expected actual =
assert
(Qcheck2_helpers.qcheck_eq ~pp:pp_answer ?__LOC__ expected actual : bool)
let is_manager_op ((_ : Operation_hash.t), op) =
This is implemented differently from
[ Plugin . Mempool.is_manager_operation ] ( which relies on
[ Alpha_context . ] ) , used in
[ Plugin . Mempool.conflict_handler ] , to avoid the test being just a
copy of the code .
[Plugin.Mempool.is_manager_operation] (which relies on
[Alpha_context.Operation.acceptable_pass]), used in
[Plugin.Mempool.conflict_handler], to avoid the test being just a
copy of the code. *)
let {Alpha_context.protocol_data = Operation_data proto_data; _} = op in
match proto_data.contents with
| Single (Manager_operation _) | Cons (Manager_operation _, _) -> true
| _ -> false
let test_random_ops () =
let ops =
let open Operation_generator in
QCheck2.Gen.(generate ~n:100 (pair generate_operation generate_operation))
in
List.iter
(fun ((_, op1), (_, op2)) ->
let answer =
Plugin.Mempool.conflict_handler
Plugin.Mempool.default_config
~existing_operation:op1
~new_operation:op2
in
if is_manager_op op1 && is_manager_op op2 then
()
else if
When there is at least one non - manager operation , the
conflict handler defers to [ Operation.compare ] : the higher
operation is selected .
conflict handler defers to [Operation.compare]: the higher
operation is selected. *)
Alpha_context.Operation.compare op1 op2 >= 0
then check_answer ~__LOC__ `Keep answer
else check_answer ~__LOC__ `Replace answer)
ops ;
return_unit
let generate_manager_op_with_fee_and_gas ~fee_in_mutez ~gas =
let open Alpha_context in
let open QCheck2.Gen in
let rec set_fee_and_gas :
type kind. _ -> _ -> kind contents_list -> kind contents_list t =
fun desired_total_fee desired_total_gas -> function
| Single (Manager_operation data) ->
let fee = Tez.of_mutez_exn (Int64.of_int desired_total_fee) in
let gas_limit = Gas.Arith.integral_of_int_exn desired_total_gas in
return (Single (Manager_operation {data with fee; gas_limit}))
| Cons (Manager_operation data, tail) ->
let* local_fee =
We generate some corner cases where some individual
operations in the batch have zero fees .
operations in the batch have zero fees. *)
let* r = frequencyl [(7, `Random); (2, `Zero); (1, `All)] in
match r with
| `Random -> int_range 0 desired_total_fee
| `Zero -> return 0
| `All -> return desired_total_fee
in
let* local_gas = int_range 0 desired_total_gas in
let fee = Tez.of_mutez_exn (Int64.of_int local_fee) in
let gas_limit = Gas.Arith.integral_of_int_exn local_gas in
let* tail =
set_fee_and_gas
(desired_total_fee - local_fee)
(desired_total_gas - local_gas)
tail
in
return (Cons (Manager_operation {data with fee; gas_limit}, tail))
| Single _ ->
in
let* batch_size = int_range 1 Operation_generator.max_batch_size in
let* op = Operation_generator.generate_manager_operation batch_size in
Modify its fee and gas to match the [ fee_in_mutez ] and [ gas ] inputs .
let {shell = _; protocol_data = Operation_data protocol_data} = op in
let* contents = set_fee_and_gas fee_in_mutez gas protocol_data.contents in
let protocol_data = {protocol_data with contents} in
let op = {op with protocol_data = Operation_data protocol_data} in
return (Operation.hash_packed op, op)
let check_conflict_handler ~__LOC__ config ~old ~nw expected =
let answer =
Plugin.Mempool.conflict_handler
config
~existing_operation:old
~new_operation:nw
in
check_answer ~__LOC__ expected answer
let test_manager_ops () =
let make_op ~fee_in_mutez ~gas =
QCheck2.Gen.generate1
(generate_manager_op_with_fee_and_gas ~fee_in_mutez ~gas)
in
Test operations with specific fee and gas , using the default
configuration . This configuration replaces the old operation when
the new one is at least 5 % better , in terms of both fees and
fee / gas ratios .
configuration. This configuration replaces the old operation when
the new one is at least 5% better, in terms of both fees and
fee/gas ratios. *)
let default = Plugin.Mempool.default_config in
let ref_fee = 10_000_000 in
let ref_gas = 2100 in
Reference operation arbitrarily has 10 tez of fees and 2100
gas . The gas is chosen to still give an integer when multiplied
by 100/105 .
gas. The gas is chosen to still give an integer when multiplied
by 100/105. *)
let old = make_op ~fee_in_mutez:ref_fee ~gas:ref_gas in
let op_same = make_op ~fee_in_mutez:ref_fee ~gas:ref_gas in
check_conflict_handler ~__LOC__ default ~old ~nw:op_same `Keep ;
5 % better fee but same ratio ( because gas is also 5 % more ) .
let more5 = Q.make (Z.of_int 105) (Z.of_int 100) in
let fee_more5 = Q.(to_int (mul more5 (of_int ref_fee))) in
let gas_more5 = Q.(to_int (mul more5 (of_int ref_gas))) in
let op_fee5 = make_op ~fee_in_mutez:fee_more5 ~gas:gas_more5 in
check_conflict_handler ~__LOC__ default ~old ~nw:op_fee5 `Keep ;
5 % better ratio but same fee ( because gas is multiplied by 100/105 ) .
let less5 = Q.make (Z.of_int 100) (Z.of_int 105) in
let gas_less5 = Q.(to_int (mul less5 (of_int ref_gas))) in
let op_ratio5 = make_op ~fee_in_mutez:ref_fee ~gas:gas_less5 in
check_conflict_handler ~__LOC__ default ~old ~nw:op_ratio5 `Keep ;
Both 5 % better fee and 5 % better ratio .
let op_both5 = make_op ~fee_in_mutez:fee_more5 ~gas:ref_gas in
check_conflict_handler ~__LOC__ default ~old ~nw:op_both5 `Replace ;
Config that requires 10 % better fee and ratio to replace .
let config10 =
{
Plugin.Mempool.default_config with
replace_by_fee_factor = Q.make (Z.of_int 11) (Z.of_int 10);
}
in
check_conflict_handler ~__LOC__ config10 ~old ~nw:op_same `Keep ;
check_conflict_handler ~__LOC__ config10 ~old ~nw:op_fee5 `Keep ;
check_conflict_handler ~__LOC__ config10 ~old ~nw:op_ratio5 `Keep ;
check_conflict_handler ~__LOC__ config10 ~old ~nw:op_both5 `Keep ;
let config0 =
{Plugin.Mempool.default_config with replace_by_fee_factor = Q.one}
in
check_conflict_handler ~__LOC__ config0 ~old ~nw:op_same `Replace ;
check_conflict_handler ~__LOC__ config0 ~old ~nw:op_fee5 `Replace ;
check_conflict_handler ~__LOC__ config0 ~old ~nw:op_ratio5 `Replace ;
check_conflict_handler ~__LOC__ config0 ~old ~nw:op_both5 `Replace ;
let op_less_fee = make_op ~fee_in_mutez:(ref_fee - 1) ~gas:(ref_gas - 1) in
check_conflict_handler ~__LOC__ default ~old ~nw:op_less_fee `Keep ;
let op_worse_ratio = make_op ~fee_in_mutez:ref_fee ~gas:(ref_gas + 1) in
check_conflict_handler ~__LOC__ default ~old ~nw:op_worse_ratio `Keep ;
Generate random operations which do not have 5 % better fees than
the reference [ op ] : they should not replace [ op ] when using the
default config .
the reference [op]: they should not replace [op] when using the
default config. *)
let open QCheck2.Gen in
let repeat = 30 in
let max_gas = 5 * ref_gas in
let generator_not_5more_fee =
let* fee_in_mutez = int_range 0 (fee_more5 - 1) in
let* gas = int_range 0 max_gas in
Format.eprintf "op_not_fee5: fee = %d; gas = %d@." fee_in_mutez gas ;
generate_manager_op_with_fee_and_gas ~fee_in_mutez ~gas
in
let ops_not_5more_fee = generate ~n:repeat generator_not_5more_fee in
List.iter
(fun nw -> check_conflict_handler ~__LOC__ default ~old ~nw `Keep)
ops_not_5more_fee ;
Generate random operations which do not have 5 % better ratio than
the reference [ op ] : they should not replace [ op ] when using the
default config .
the reference [op]: they should not replace [op] when using the
default config. *)
let ratio_5more =
Q.(mul more5 (make (Z.of_int ref_fee) (Z.of_int ref_gas)))
in
let generator_not_5more_ratio =
let* gas = int_range 0 max_gas in
let fee_for_5more_ratio = Q.(mul (of_int gas) ratio_5more) in
let fee_upper_bound = Q.to_int fee_for_5more_ratio - 1 in
let* fee_in_mutez = int_range 0 (max 0 fee_upper_bound) in
Format.eprintf "op_not_ratio5: fee = %d; gas = %d@." fee_in_mutez gas ;
generate_manager_op_with_fee_and_gas ~fee_in_mutez ~gas
in
let ops_not_5more_ratio = generate ~n:repeat generator_not_5more_ratio in
List.iter
(fun nw -> check_conflict_handler ~__LOC__ default ~old ~nw `Keep)
ops_not_5more_ratio ;
Generate random operations which have both 5 % higher fees and 5 %
better ratio than the reference [ op ] : they should replace [ op ]
when using the default config .
better ratio than the reference [op]: they should replace [op]
when using the default config. *)
let max_fee =
We use a significantly higher factor to define [ max_fee ] from
[ ref_fee ] than [ max_gas ] from [ ref_gas ] . Therefore , even if we
generate a gas equal to [ max_gas ] , we can still generate a fee
that makes the ratio at least 5 % better than the reference
operation 's .
[ref_fee] than [max_gas] from [ref_gas]. Therefore, even if we
generate a gas equal to [max_gas], we can still generate a fee
that makes the ratio at least 5% better than the reference
operation's. *)
10 * ref_fee
in
let generator_both_5more =
let* gas = int_range 0 max_gas in
let fee_for_5more_ratio = Q.(mul (of_int gas) ratio_5more) in
let fee_lower_bound = max fee_more5 (Q.to_int fee_for_5more_ratio + 1) in
let* fee_in_mutez = int_range fee_lower_bound max_fee in
Format.eprintf "op_both_better: fee = %d; gas = %d@." fee_in_mutez gas ;
generate_manager_op_with_fee_and_gas ~fee_in_mutez ~gas
in
let ops_both_5more = generate ~n:repeat generator_both_5more in
List.iter
(fun nw -> check_conflict_handler ~__LOC__ default ~old ~nw `Replace)
ops_both_5more ;
return_unit
let () =
Alcotest_lwt.run
"conflict_handler"
[
( Protocol.name ^ ": conflict_handler",
[
Tztest.tztest
"Random operations (not both manager)"
`Quick
test_random_ops;
Tztest.tztest "Manager operations" `Quick test_manager_ops;
] );
]
|> Lwt_main.run
|
443615c6339afd77730c04205263f6b1078efccccbe1642e051b1b9c353095dd | chrisdone/prana | Const.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE Trustworthy #
-----------------------------------------------------------------------------
-- |
-- Module : Data.Functor.Const
Copyright : and 2005
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer :
-- Stability : experimental
-- Portability : portable
-- The 'Const' functor.
--
@since 4.9.0.0
module Data.Functor.Const (Const(..)) where
import Data.Bits (Bits, FiniteBits)
import Data.Foldable (Foldable(foldMap))
import Foreign.Storable (Storable)
import GHC.Arr (Ix)
import GHC.Base
import GHC.Enum (Bounded, Enum)
import GHC.Float (Floating, RealFloat)
import GHC.Generics (Generic, Generic1)
import GHC.Num (Num)
import GHC.Real (Fractional, Integral, Real, RealFrac)
import GHC.Read (Read(readsPrec), readParen, lex)
import GHC.Show (Show(showsPrec), showParen, showString)
-- | The 'Const' functor.
newtype Const a b = Const { getConst :: a }
deriving ( Bits, Bounded, Enum, Eq, FiniteBits, Floating, Fractional
, Generic, Generic1, Integral, Ix, Semigroup, Monoid, Num, Ord
, Real, RealFrac, RealFloat, Storable)
-- | This instance would be equivalent to the derived instances of the
-- 'Const' newtype if the 'runConst' field were removed
--
@since 4.8.0.0
instance Read a => Read (Const a b) where
readsPrec d = readParen (d > 10)
$ \r -> [(Const x,t) | ("Const", s) <- lex r, (x, t) <- readsPrec 11 s]
-- | This instance would be equivalent to the derived instances of the
-- 'Const' newtype if the 'runConst' field were removed
--
@since 4.8.0.0
instance Show a => Show (Const a b) where
showsPrec d (Const x) = showParen (d > 10) $
showString "Const " . showsPrec 11 x
| @since 4.7.0.0
instance Foldable (Const m) where
foldMap _ _ = mempty
| @since 2.01
instance Functor (Const m) where
fmap _ (Const v) = Const v
| @since 2.0.1
instance Monoid m => Applicative (Const m) where
pure _ = Const mempty
liftA2 _ (Const x) (Const y) = Const (x `mappend` y)
(<*>) = coerce (mappend :: m -> m -> m)
-- This is pretty much the same as
-- Const f <*> Const v = Const (f `mappend` v)
-- but guarantees that mappend for Const a b will have the same arity
-- as the one for a; it won't create a closure to raise the arity
to 2 .
| null | https://raw.githubusercontent.com/chrisdone/prana/f2e45538937d326aff562b6d49296eaedd015662/prana-boot/packages/base-4.11.1.0/Data/Functor/Const.hs | haskell | ---------------------------------------------------------------------------
|
Module : Data.Functor.Const
License : BSD-style (see the LICENSE file in the distribution)
Maintainer :
Stability : experimental
Portability : portable
The 'Const' functor.
| The 'Const' functor.
| This instance would be equivalent to the derived instances of the
'Const' newtype if the 'runConst' field were removed
| This instance would be equivalent to the derived instances of the
'Const' newtype if the 'runConst' field were removed
This is pretty much the same as
Const f <*> Const v = Const (f `mappend` v)
but guarantees that mappend for Const a b will have the same arity
as the one for a; it won't create a closure to raise the arity | # LANGUAGE DeriveGeneric #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE Trustworthy #
Copyright : and 2005
@since 4.9.0.0
module Data.Functor.Const (Const(..)) where
import Data.Bits (Bits, FiniteBits)
import Data.Foldable (Foldable(foldMap))
import Foreign.Storable (Storable)
import GHC.Arr (Ix)
import GHC.Base
import GHC.Enum (Bounded, Enum)
import GHC.Float (Floating, RealFloat)
import GHC.Generics (Generic, Generic1)
import GHC.Num (Num)
import GHC.Real (Fractional, Integral, Real, RealFrac)
import GHC.Read (Read(readsPrec), readParen, lex)
import GHC.Show (Show(showsPrec), showParen, showString)
newtype Const a b = Const { getConst :: a }
deriving ( Bits, Bounded, Enum, Eq, FiniteBits, Floating, Fractional
, Generic, Generic1, Integral, Ix, Semigroup, Monoid, Num, Ord
, Real, RealFrac, RealFloat, Storable)
@since 4.8.0.0
instance Read a => Read (Const a b) where
readsPrec d = readParen (d > 10)
$ \r -> [(Const x,t) | ("Const", s) <- lex r, (x, t) <- readsPrec 11 s]
@since 4.8.0.0
instance Show a => Show (Const a b) where
showsPrec d (Const x) = showParen (d > 10) $
showString "Const " . showsPrec 11 x
| @since 4.7.0.0
instance Foldable (Const m) where
foldMap _ _ = mempty
| @since 2.01
instance Functor (Const m) where
fmap _ (Const v) = Const v
| @since 2.0.1
instance Monoid m => Applicative (Const m) where
pure _ = Const mempty
liftA2 _ (Const x) (Const y) = Const (x `mappend` y)
(<*>) = coerce (mappend :: m -> m -> m)
to 2 .
|
1d93b2e257004ea4ffdcaa29327814c24bcac522b5ffc12d80eec69dcd58db01 | racket/compatibility | trace.rkt | #lang racket/base
(require racket/trace)
(provide (all-from-out racket/trace))
| null | https://raw.githubusercontent.com/racket/compatibility/492030dac6f095045ce8a13dca75204dd5f34e32/compatibility-lib/mzlib/trace.rkt | racket | #lang racket/base
(require racket/trace)
(provide (all-from-out racket/trace))
| |
f67efac4e4c2d68ee56726007db3193c0e6827828edd271b8382964365d5742f | jacekschae/learn-reitit-course-files | project.clj | (defproject cheffy "1.0.0"
:description "Cheffy REST API"
:url ""
:min-lein-version "2.0.0"
:dependencies [[org.clojure/clojure "1.10.1"]
[ring "1.8.1"]
[integrant "0.8.0"]
[environ "1.2.0"]
[metosin/reitit "0.5.5"]
[seancorfield/next.jdbc "1.1.582"]
[org.postgresql/postgresql "42.2.14"]
[clj-http "3.10.0"]
[ovotech/ring-jwt "1.3.0"]
[camel-snake-kebab "0.4.1"]
[com.zaxxer/HikariCP "3.4.5"]]
:profiles {:uberjar {:aot :all}
:dev {:source-paths ["dev/src"]
:resource-paths ["dev/resources"]
:dependencies [[ring/ring-mock "0.4.0"]
[integrant/repl "0.3.1"]]}}
:uberjar-name "cheffy.jar")
| null | https://raw.githubusercontent.com/jacekschae/learn-reitit-course-files/c13a8eb622a371ad719d3d9023f1b4eff9392e4c/increments/complete/project.clj | clojure | (defproject cheffy "1.0.0"
:description "Cheffy REST API"
:url ""
:min-lein-version "2.0.0"
:dependencies [[org.clojure/clojure "1.10.1"]
[ring "1.8.1"]
[integrant "0.8.0"]
[environ "1.2.0"]
[metosin/reitit "0.5.5"]
[seancorfield/next.jdbc "1.1.582"]
[org.postgresql/postgresql "42.2.14"]
[clj-http "3.10.0"]
[ovotech/ring-jwt "1.3.0"]
[camel-snake-kebab "0.4.1"]
[com.zaxxer/HikariCP "3.4.5"]]
:profiles {:uberjar {:aot :all}
:dev {:source-paths ["dev/src"]
:resource-paths ["dev/resources"]
:dependencies [[ring/ring-mock "0.4.0"]
[integrant/repl "0.3.1"]]}}
:uberjar-name "cheffy.jar")
| |
920eb55c89409e0718fad60ceb18598874077308fae009df2b7283360f2abf75 | clojurebook/ClojureProgramming | beanstalk.clj | (ns com.clojurebook.url-shortener.beanstalk
(:use [compojure.core :only (HEAD defroutes)])
(:require [com.clojurebook.url-shortener :as shortener]
[compojure.core :as compojure]))
(compojure/defroutes app
This HEAD route is here because Amazon 's Elastic Beanstalk determines if
; your application is up by whether it responds successfully to a
; HEAD request at /
(compojure/HEAD "/" [] "")
shortener/app)
| null | https://raw.githubusercontent.com/clojurebook/ClojureProgramming/bcc7c58862982a5793e22788fc11a9ed7ffc548f/ch16-web-leiningen/src/com/clojurebook/url_shortener/beanstalk.clj | clojure | your application is up by whether it responds successfully to a
HEAD request at / | (ns com.clojurebook.url-shortener.beanstalk
(:use [compojure.core :only (HEAD defroutes)])
(:require [com.clojurebook.url-shortener :as shortener]
[compojure.core :as compojure]))
(compojure/defroutes app
This HEAD route is here because Amazon 's Elastic Beanstalk determines if
(compojure/HEAD "/" [] "")
shortener/app)
|
44cb7e5154e0aa2f3254c7f511e306014af661212dbf087499b51915c85c5809 | runtimeverification/haskell-backend | MockMetadataTools.hs | module Test.Kore.IndexedModule.MockMetadataTools (
makeMetadataTools,
constructorTotalAttributes,
constructorAttributes,
defaultAttributes,
functionAttributes,
totalAttributes,
injectiveAttributes,
sortInjectionAttributes,
) where
import Data.Map.Strict qualified as Map
import GHC.Generics qualified as GHC
import Kore.Attribute.Constructor
import Kore.Attribute.Function
import Kore.Attribute.Injective
import Kore.Attribute.Sort qualified as Attribute
import Kore.Attribute.Sort.Constructors qualified as Attribute (
Constructors,
)
import Kore.Attribute.SortInjection
import Kore.Attribute.Symbol
import Kore.IndexedModule.MetadataTools (
ExtractSyntax (..),
MetadataSyntaxData (..),
MetadataTools (MetadataTools),
SmtMetadataTools,
)
import Kore.IndexedModule.MetadataTools qualified as MetadataTools (
MetadataTools (..),
)
import Kore.Internal.ApplicationSorts (
ApplicationSorts,
)
import Kore.Rewrite.SMT.AST qualified as SMT.AST (
SmtDeclarations,
)
import Kore.Sort (
Sort,
)
import Kore.Syntax.Application (
SymbolOrAlias (..),
)
import Kore.Syntax.Id (
Id,
)
import Prelude.Kore
data MockSyntaxData attributes = MockSyntaxData
{ sortAttributes :: [(Sort, Attribute.Sort)]
, applicationSorts :: [(SymbolOrAlias, ApplicationSorts)]
, symbolAttributes :: [(SymbolOrAlias, attributes)]
}
deriving stock (GHC.Generic)
deriving anyclass (NFData)
instance ExtractSyntax MockSyntaxData where
extractSortAttributes sdata = caseBasedFunction $ sortAttributes sdata
extractApplicationSorts sdata = caseBasedFunction $ applicationSorts sdata
extractSymbolAttributes sdata =
caseBasedFunction
( map
( \(SymbolOrAlias{symbolOrAliasConstructor}, a) ->
(symbolOrAliasConstructor, a)
)
(symbolAttributes sdata)
)
makeMetadataTools ::
[(SymbolOrAlias, StepperAttributes)] ->
[(Sort, Attribute.Sort)] ->
[(SymbolOrAlias, ApplicationSorts)] ->
SMT.AST.SmtDeclarations ->
Map.Map Id Attribute.Constructors ->
SmtMetadataTools StepperAttributes
makeMetadataTools attr sortTypes sorts declarations sortConstructors =
MetadataTools
{ syntax =
MetadataSyntaxDataExtension $
MockSyntaxData
{ sortAttributes = sortTypes
, -- TODO(Vladimir): fix the inconsistency that both 'subsorts' and
-- 'isSubsortOf' only work with direct (non-transitive) relationships.
-- For now, we can manually add the relationships for tests.
applicationSorts = sorts
, symbolAttributes = attr
}
, smtData = declarations
, sortConstructors
}
caseBasedFunction ::
(Eq a, Show a, HasCallStack) =>
[(a, b)] ->
a ->
b
caseBasedFunction cases arg =
fromMaybe
(error ("Unknown argument: " ++ show arg))
(lookup arg cases)
functionAttributes :: StepperAttributes
functionAttributes = defaultAttributes{function = Function True}
totalAttributes :: StepperAttributes
totalAttributes = defaultAttributes{total = Total True}
constructorAttributes :: StepperAttributes
constructorAttributes =
defaultSymbolAttributes
{ constructor = Constructor True
}
constructorTotalAttributes :: StepperAttributes
constructorTotalAttributes =
constructorAttributes{total = Total True}
injectiveAttributes :: StepperAttributes
injectiveAttributes = defaultAttributes{injective = Injective True}
sortInjectionAttributes :: StepperAttributes
sortInjectionAttributes =
defaultAttributes
{ injective = Injective True
, sortInjection = SortInjection True
}
defaultAttributes :: StepperAttributes
defaultAttributes = defaultSymbolAttributes
| null | https://raw.githubusercontent.com/runtimeverification/haskell-backend/93a705112305a2d7e084e98dca93ec33e0d661d5/kore/test/Test/Kore/IndexedModule/MockMetadataTools.hs | haskell | TODO(Vladimir): fix the inconsistency that both 'subsorts' and
'isSubsortOf' only work with direct (non-transitive) relationships.
For now, we can manually add the relationships for tests. | module Test.Kore.IndexedModule.MockMetadataTools (
makeMetadataTools,
constructorTotalAttributes,
constructorAttributes,
defaultAttributes,
functionAttributes,
totalAttributes,
injectiveAttributes,
sortInjectionAttributes,
) where
import Data.Map.Strict qualified as Map
import GHC.Generics qualified as GHC
import Kore.Attribute.Constructor
import Kore.Attribute.Function
import Kore.Attribute.Injective
import Kore.Attribute.Sort qualified as Attribute
import Kore.Attribute.Sort.Constructors qualified as Attribute (
Constructors,
)
import Kore.Attribute.SortInjection
import Kore.Attribute.Symbol
import Kore.IndexedModule.MetadataTools (
ExtractSyntax (..),
MetadataSyntaxData (..),
MetadataTools (MetadataTools),
SmtMetadataTools,
)
import Kore.IndexedModule.MetadataTools qualified as MetadataTools (
MetadataTools (..),
)
import Kore.Internal.ApplicationSorts (
ApplicationSorts,
)
import Kore.Rewrite.SMT.AST qualified as SMT.AST (
SmtDeclarations,
)
import Kore.Sort (
Sort,
)
import Kore.Syntax.Application (
SymbolOrAlias (..),
)
import Kore.Syntax.Id (
Id,
)
import Prelude.Kore
data MockSyntaxData attributes = MockSyntaxData
{ sortAttributes :: [(Sort, Attribute.Sort)]
, applicationSorts :: [(SymbolOrAlias, ApplicationSorts)]
, symbolAttributes :: [(SymbolOrAlias, attributes)]
}
deriving stock (GHC.Generic)
deriving anyclass (NFData)
instance ExtractSyntax MockSyntaxData where
extractSortAttributes sdata = caseBasedFunction $ sortAttributes sdata
extractApplicationSorts sdata = caseBasedFunction $ applicationSorts sdata
extractSymbolAttributes sdata =
caseBasedFunction
( map
( \(SymbolOrAlias{symbolOrAliasConstructor}, a) ->
(symbolOrAliasConstructor, a)
)
(symbolAttributes sdata)
)
makeMetadataTools ::
[(SymbolOrAlias, StepperAttributes)] ->
[(Sort, Attribute.Sort)] ->
[(SymbolOrAlias, ApplicationSorts)] ->
SMT.AST.SmtDeclarations ->
Map.Map Id Attribute.Constructors ->
SmtMetadataTools StepperAttributes
makeMetadataTools attr sortTypes sorts declarations sortConstructors =
MetadataTools
{ syntax =
MetadataSyntaxDataExtension $
MockSyntaxData
{ sortAttributes = sortTypes
applicationSorts = sorts
, symbolAttributes = attr
}
, smtData = declarations
, sortConstructors
}
caseBasedFunction ::
(Eq a, Show a, HasCallStack) =>
[(a, b)] ->
a ->
b
caseBasedFunction cases arg =
fromMaybe
(error ("Unknown argument: " ++ show arg))
(lookup arg cases)
functionAttributes :: StepperAttributes
functionAttributes = defaultAttributes{function = Function True}
totalAttributes :: StepperAttributes
totalAttributes = defaultAttributes{total = Total True}
constructorAttributes :: StepperAttributes
constructorAttributes =
defaultSymbolAttributes
{ constructor = Constructor True
}
constructorTotalAttributes :: StepperAttributes
constructorTotalAttributes =
constructorAttributes{total = Total True}
injectiveAttributes :: StepperAttributes
injectiveAttributes = defaultAttributes{injective = Injective True}
sortInjectionAttributes :: StepperAttributes
sortInjectionAttributes =
defaultAttributes
{ injective = Injective True
, sortInjection = SortInjection True
}
defaultAttributes :: StepperAttributes
defaultAttributes = defaultSymbolAttributes
|
8ff5838b2726afddab8c63a83c14d77cf39e14cefa784e60e54aad417cf7f7ec | phoe-trash/gateway | package.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; GATEWAY
" phoe " Herda 2016
sql / package.lisp
(uiop:define-package #:gateway/sql
(:use #:common-lisp
#:alexandria
#:cl-yesql
#:phoe-toolbox
#:gateway/protocol
#:gateway/utils
#:gateway/config)
(:export #:with-db
#:with-test-db))
| null | https://raw.githubusercontent.com/phoe-trash/gateway/a8d579ccbafcaee8678caf59d365ec2eab0b1a7e/sql/package.lisp | lisp |
GATEWAY | " phoe " Herda 2016
sql / package.lisp
(uiop:define-package #:gateway/sql
(:use #:common-lisp
#:alexandria
#:cl-yesql
#:phoe-toolbox
#:gateway/protocol
#:gateway/utils
#:gateway/config)
(:export #:with-db
#:with-test-db))
|
e9e603835ea0fb855437a3c607f10114882a3dacc43135b80ba8effa8fc56e80 | jserot/lascar | fsm_ppxs.ml | (**********************************************************************)
(* *)
LASCAr
(* *)
Copyright ( c ) 2017 - present , . All rights reserved .
(* *)
(* This source code is licensed under the license found in the *)
(* LICENSE file in the root directory of this source tree. *)
(* *)
(**********************************************************************)
open Ppxlib
open Lascar
let string_of_token t =
let open Genlex in
match t with
| Int n -> "Int<" ^ string_of_int n ^ ">"
| Float n -> "Float<" ^ string_of_float n ^ ">"
| Char n -> "Char<" ^ String.make 1 n ^ ">"
| String n -> "String<" ^ n ^ ">"
| Ident n -> "Ident<" ^ n ^ ">"
| Kwd n -> "Kwd<" ^ n ^ ">"
exception Parse_error of string * string option
let expand parser_name parser_fn ~loc ~path:_ (s:_) =
let _ =
try
parser_fn s
with
| Utils.Parsing.Parse_error (s, Some tok) -> raise (Parse_error (s, Some (string_of_token tok)))
| Utils.Parsing.Parse_error (s, None) -> raise (Parse_error (s, None)) in
let f = Ast_builder.Default.evar ~loc parser_name in
let e = Ast_builder.Default.estring ~loc s in
[%expr [%e f] [%e e]]
let mk_ext ext_name parser_name parser_fn =
Extension.declare
ext_name
Extension.Context.expression
Ast_pattern.(single_expr_payload (estring __))
(expand parser_name parser_fn)
let () = Ppxlib.Driver.register_transformation "fsm_action" ~extensions:[mk_ext "fsm_action" "Fsm_action.Int.of_string" Fsm_action.Int.of_string]
let () = Ppxlib.Driver.register_transformation "fsm_trans" ~extensions:[mk_ext "fsm_trans" "Fsm_transition.Int.of_string" Fsm_transition.Int.of_string]
| null | https://raw.githubusercontent.com/jserot/lascar/79bd11cd0d47545bccfc3a3571f37af065915c83/src/lib/fsm_ppxs.ml | ocaml | ********************************************************************
This source code is licensed under the license found in the
LICENSE file in the root directory of this source tree.
******************************************************************** | LASCAr
Copyright ( c ) 2017 - present , . All rights reserved .
open Ppxlib
open Lascar
let string_of_token t =
let open Genlex in
match t with
| Int n -> "Int<" ^ string_of_int n ^ ">"
| Float n -> "Float<" ^ string_of_float n ^ ">"
| Char n -> "Char<" ^ String.make 1 n ^ ">"
| String n -> "String<" ^ n ^ ">"
| Ident n -> "Ident<" ^ n ^ ">"
| Kwd n -> "Kwd<" ^ n ^ ">"
exception Parse_error of string * string option
let expand parser_name parser_fn ~loc ~path:_ (s:_) =
let _ =
try
parser_fn s
with
| Utils.Parsing.Parse_error (s, Some tok) -> raise (Parse_error (s, Some (string_of_token tok)))
| Utils.Parsing.Parse_error (s, None) -> raise (Parse_error (s, None)) in
let f = Ast_builder.Default.evar ~loc parser_name in
let e = Ast_builder.Default.estring ~loc s in
[%expr [%e f] [%e e]]
let mk_ext ext_name parser_name parser_fn =
Extension.declare
ext_name
Extension.Context.expression
Ast_pattern.(single_expr_payload (estring __))
(expand parser_name parser_fn)
let () = Ppxlib.Driver.register_transformation "fsm_action" ~extensions:[mk_ext "fsm_action" "Fsm_action.Int.of_string" Fsm_action.Int.of_string]
let () = Ppxlib.Driver.register_transformation "fsm_trans" ~extensions:[mk_ext "fsm_trans" "Fsm_transition.Int.of_string" Fsm_transition.Int.of_string]
|
96bec5a14231fdb20adbec1152035b254765c3f83a736a04a6a1bdfeb4dd9c3c | RunOrg/RunOrg | treeMapView.mli | (* © 2014 RunOrg *)
type ('key, 'id, 'value) t
type ('id,'value) node = <
time : Time.t ;
id : 'id ;
count : int ;
value : 'value ;
subtree : ('id, 'value) node list
>
val make : Projection.t -> string -> int ->
(module Fmt.FMT with type t = 'key) ->
(module Fmt.FMT with type t = 'id) ->
(module Fmt.FMT with type t = 'value) ->
Projection.view * ('key, 'id, 'value) t
val update : ('key, 'id, 'value) t -> 'key -> 'id ->
((Time.t * 'id option * 'value) option -> [ `Keep | `Put of (Time.t * 'id option * 'value) | `Delete]) ->
# Common.ctx Run.effect
val delete : ('key, 'id, 'value) t -> 'key -> # Common.ctx Run.effect
val exists : ('key, 'id, 'value) t -> 'key -> 'id -> (#Common.ctx, bool) Run.t
val get : ('key, 'id, 'value) t -> 'key -> 'id -> (# Common.ctx, ('id,'value) node option) Run.t
val stats : ('key, 'id, 'value) t -> 'key -> (#Common.ctx, <
count : int ;
root : int ;
first : Time.t option ;
last : Time.t option ;
>) Run.t
val list :
('key, 'id, 'value) t ->
?depth:int ->
?limit:int ->
?offset:int ->
?parent:'id ->
'key ->
(#Common.ctx, ('id,'value) node list) Run.t
val ticker :
?limit:int ->
?since:('key * 'id) ->
('key, 'id, 'value) t ->
(#Common.ctx, ('key * 'id * Time.t) list) Run.t
| null | https://raw.githubusercontent.com/RunOrg/RunOrg/b53ee2357f4bcb919ac48577426d632dffc25062/server/cqrsLib/treeMapView.mli | ocaml | © 2014 RunOrg |
type ('key, 'id, 'value) t
type ('id,'value) node = <
time : Time.t ;
id : 'id ;
count : int ;
value : 'value ;
subtree : ('id, 'value) node list
>
val make : Projection.t -> string -> int ->
(module Fmt.FMT with type t = 'key) ->
(module Fmt.FMT with type t = 'id) ->
(module Fmt.FMT with type t = 'value) ->
Projection.view * ('key, 'id, 'value) t
val update : ('key, 'id, 'value) t -> 'key -> 'id ->
((Time.t * 'id option * 'value) option -> [ `Keep | `Put of (Time.t * 'id option * 'value) | `Delete]) ->
# Common.ctx Run.effect
val delete : ('key, 'id, 'value) t -> 'key -> # Common.ctx Run.effect
val exists : ('key, 'id, 'value) t -> 'key -> 'id -> (#Common.ctx, bool) Run.t
val get : ('key, 'id, 'value) t -> 'key -> 'id -> (# Common.ctx, ('id,'value) node option) Run.t
val stats : ('key, 'id, 'value) t -> 'key -> (#Common.ctx, <
count : int ;
root : int ;
first : Time.t option ;
last : Time.t option ;
>) Run.t
val list :
('key, 'id, 'value) t ->
?depth:int ->
?limit:int ->
?offset:int ->
?parent:'id ->
'key ->
(#Common.ctx, ('id,'value) node list) Run.t
val ticker :
?limit:int ->
?since:('key * 'id) ->
('key, 'id, 'value) t ->
(#Common.ctx, ('key * 'id * Time.t) list) Run.t
|
55aea07048d41ce7d8c80ac2cd0ceb7bd01149449b09ac9841209441b065a802 | berberman/arch-hs | Local.hs | | Copyright : ( c ) 2020 - 2021 berberman
SPDX - License - Identifier : MIT
Maintainer : < >
-- Stability: experimental
-- Portability: portable
This module maintains names of packages which are need special treatments during dependency resolving or PKGBUILD generating .
module Distribution.ArchHs.Local
( ignoreList,
ghcLibList,
)
where
import Distribution.ArchHs.Types
import Distribution.Types.PackageName
-- | Packages should be dropped in dependency resolving.
ignoreList :: PkgList
ignoreList =
mkPackageName
<$> [ "unbuildable",
"invalid-cabal-flag-settings",
"par-classes",
"fail",
"integer-simple",
"bytestring-builder",
"nats",
"integer",
"unsupported-ghc-version",
"rts",
"ghc-prim",
"ghc-bignum",
"hans",
"Win32",
"ghc-heap",
"ghc-byteorder",
-- a build-tools of "zip-archive", which is not haskell package
"unzip"
]
| Packages already provided by < -libs/ ghc - libs > .
ghcLibList :: PkgList
ghcLibList =
mkPackageName
<$> [ "array",
"base",
"binary",
"bytestring",
"Cabal",
"containers",
"deepseq",
"directory",
"exceptions",
"filepath",
"ghc-bignum",
"ghc-boot",
"ghc-boot-th",
"ghc-compact",
"ghc-heap",
"ghci",
"ghc-prim",
"haskeline",
"hpc",
"integer-gmp",
"libiserv",
"mtl",
"parsec",
"pretty",
"process",
"stm",
"template-haskell",
"terminfo",
"text",
"time",
"transformers",
"unix",
"xhtml"
]
| null | https://raw.githubusercontent.com/berberman/arch-hs/693bb9eb751285e4e40dfa7c76104e3f16e4702f/src/Distribution/ArchHs/Local.hs | haskell | Stability: experimental
Portability: portable
| Packages should be dropped in dependency resolving.
a build-tools of "zip-archive", which is not haskell package | | Copyright : ( c ) 2020 - 2021 berberman
SPDX - License - Identifier : MIT
Maintainer : < >
This module maintains names of packages which are need special treatments during dependency resolving or PKGBUILD generating .
module Distribution.ArchHs.Local
( ignoreList,
ghcLibList,
)
where
import Distribution.ArchHs.Types
import Distribution.Types.PackageName
ignoreList :: PkgList
ignoreList =
mkPackageName
<$> [ "unbuildable",
"invalid-cabal-flag-settings",
"par-classes",
"fail",
"integer-simple",
"bytestring-builder",
"nats",
"integer",
"unsupported-ghc-version",
"rts",
"ghc-prim",
"ghc-bignum",
"hans",
"Win32",
"ghc-heap",
"ghc-byteorder",
"unzip"
]
| Packages already provided by < -libs/ ghc - libs > .
ghcLibList :: PkgList
ghcLibList =
mkPackageName
<$> [ "array",
"base",
"binary",
"bytestring",
"Cabal",
"containers",
"deepseq",
"directory",
"exceptions",
"filepath",
"ghc-bignum",
"ghc-boot",
"ghc-boot-th",
"ghc-compact",
"ghc-heap",
"ghci",
"ghc-prim",
"haskeline",
"hpc",
"integer-gmp",
"libiserv",
"mtl",
"parsec",
"pretty",
"process",
"stm",
"template-haskell",
"terminfo",
"text",
"time",
"transformers",
"unix",
"xhtml"
]
|
6adf93fb449711448536cc9cef058b32df48003f962b88f4bfb82252a5fab686 | Javran/advent-of-code | TestAll.hs | module Javran.AdventOfCode.Cli.TestAll (
testAllCommand,
) where
import Filesystem.Path.CurrentOS
import Javran.AdventOfCode.Infra
import System.Environment
import System.Exit
import Turtle.Prelude
testAllCommand :: SubCmdContext -> IO ()
testAllCommand _ = do
projectHome <- getEnv "PROJECT_HOME"
cd (decodeString projectHome)
ec <- proc "stack" ["test", "advent-of-code:test:hspec"] ""
exitWith ec
| null | https://raw.githubusercontent.com/Javran/advent-of-code/676ef13c2f9d341cf7de0f383335a1cf577bd73d/src/Javran/AdventOfCode/Cli/TestAll.hs | haskell | module Javran.AdventOfCode.Cli.TestAll (
testAllCommand,
) where
import Filesystem.Path.CurrentOS
import Javran.AdventOfCode.Infra
import System.Environment
import System.Exit
import Turtle.Prelude
testAllCommand :: SubCmdContext -> IO ()
testAllCommand _ = do
projectHome <- getEnv "PROJECT_HOME"
cd (decodeString projectHome)
ec <- proc "stack" ["test", "advent-of-code:test:hspec"] ""
exitWith ec
| |
57030f9561e7925e7aa4fae937c582175b0d25a8ec78a026b01557da6a99db3f | janegca/htdp2e | Exercise-437-triangulation.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname Exercise-437-triangulation) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ())))
Exercise 437 .
;
; Check that the following system of equations:
;
2x + 3y + 2z = 10
3y + 9z = 21
; - 3y - 8z = -19
; has the same solution as the one labeled with (). Again do so by hand and
with check - solution from exercise 435 .
; examples:
(define M
(list (list 2 2 3 10)
(list 2 5 12 31)
(list 4 1 -2 1)))
(define S '(1 1 2))
; Equation -> [List-of Number]
; extracts the left-hand side from a row in a matrix
(check-expect (lhs (first M)) '(2 2 3))
(define (lhs e)
(reverse (rest (reverse e))))
; Equation -> Number
; extracts the right-hand side from a row in a matrix
(check-expect (rhs (first M)) 10)
(define (rhs e)
(first (reverse e)))
; Equation Solution -> Number
; plug's the solutions into the equation returning a result
(check-expect (plug-in (lhs (first M)) S) 10)
(define (plug-in eq s)
(cond [(empty? eq) 0]
[else (+ (* (first eq) (first s))
(plug-in (rest eq) (rest s)))]))
; SOE Solution -> Boolean
# true if the solution satisfies alle equation in the SOE
(check-expect (check-solution M S) #true)
(define (check-solution soe s)
(cond [(empty? soe) #true]
[else (and (= (plug-in (lhs (first soe)) s) (rhs (first soe)))
(check-solution (rest soe) s))]))
(define N
(list (list 2 2 3 10)
(list 0 3 9 21)
(list 0 -3 -8 -19)))
(check-solution N S)
| null | https://raw.githubusercontent.com/janegca/htdp2e/2d50378135edc2b8b1816204021f8763f8b2707b/05-GenerativeRecursion/Exercise-437-triangulation.rkt | racket | about the language level of this file in a form that our tools can easily process.
Check that the following system of equations:
- 3y - 8z = -19
has the same solution as the one labeled with (). Again do so by hand and
examples:
Equation -> [List-of Number]
extracts the left-hand side from a row in a matrix
Equation -> Number
extracts the right-hand side from a row in a matrix
Equation Solution -> Number
plug's the solutions into the equation returning a result
SOE Solution -> Boolean | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname Exercise-437-triangulation) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ())))
Exercise 437 .
2x + 3y + 2z = 10
3y + 9z = 21
with check - solution from exercise 435 .
(define M
(list (list 2 2 3 10)
(list 2 5 12 31)
(list 4 1 -2 1)))
(define S '(1 1 2))
(check-expect (lhs (first M)) '(2 2 3))
(define (lhs e)
(reverse (rest (reverse e))))
(check-expect (rhs (first M)) 10)
(define (rhs e)
(first (reverse e)))
(check-expect (plug-in (lhs (first M)) S) 10)
(define (plug-in eq s)
(cond [(empty? eq) 0]
[else (+ (* (first eq) (first s))
(plug-in (rest eq) (rest s)))]))
# true if the solution satisfies alle equation in the SOE
(check-expect (check-solution M S) #true)
(define (check-solution soe s)
(cond [(empty? soe) #true]
[else (and (= (plug-in (lhs (first soe)) s) (rhs (first soe)))
(check-solution (rest soe) s))]))
(define N
(list (list 2 2 3 10)
(list 0 3 9 21)
(list 0 -3 -8 -19)))
(check-solution N S)
|
85bd7e1f9b26812c544b1924ad3a1d51c7baf18906938ed19f71c0e8207b8746 | RunOrg/RunOrg | auth.mli | (* © 2014 RunOrg *)
open Std
val auth_persona : String.Url.t -> string ->
(# O.ctx, [ `OK of [`Person] Token.I.id * Queries.short * Cqrs.Clock.t
| `BadAudience of String.Url.t
| `InvalidAssertion ]) Run.t
| null | https://raw.githubusercontent.com/RunOrg/RunOrg/b53ee2357f4bcb919ac48577426d632dffc25062/server/personLib/auth.mli | ocaml | © 2014 RunOrg |
open Std
val auth_persona : String.Url.t -> string ->
(# O.ctx, [ `OK of [`Person] Token.I.id * Queries.short * Cqrs.Clock.t
| `BadAudience of String.Url.t
| `InvalidAssertion ]) Run.t
|
4e78844cf0d4849f8dc1b4099e1324ec5fef8698a3c6c2d8d96af04ce105f755 | MastodonC/kixi.hecuba | parser.clj | (ns kixi.hecuba.api.parser
(:require [clojure.string :as string]
[clojure.java.io :as io]
[clojure.data.csv :as csv]
[clojure.tools.logging :as log]
[cheshire.core :as json]))
(defn attribute-type [attr]
(if (keyword? attr)
:attribute
(:type attr)))
(defn explode-nested-item [association item]
"Explodes a nested item, that is represented in the object coming from
the datastore as a json encoded string. Returns a list of vectors of
two elements, the first being the attribute key, and the second the value.
The key is expanded to <nested item name>_<attribute name>"
(when item
(let [association-name (:name association)
association-schema (:schema association)]
(map
(fn [attr]
[(str (name association-name) "_" (name attr)) (attr item)])
association-schema))))
(defn explode-associated-items [association items]
"Explodes the elements of a (one to many) association, that is represented
in the object coming from the datastore as a list of json encoded strings.
Returns a list of vectors of two elements, the first being the attribute key,
and the second the value.
The keys are expanded like <association name>_<associated item index>_<attribute name>"
(let [association-name (name (:name association))
association-schema (:schema association)]
(apply concat
(keep-indexed
(fn [index item]
(let [item-name (str association-name "_" index)
named-association (assoc association :name item-name)]
(if (empty? association-schema)
[item-name item]
(explode-nested-item named-association item))))
items))))
(defn explode-and-sort-by-schema [item schema]
"Take a (profile) item from the datastore and converts into a list
of pairs (represented as a vector) where the first element is the
exploded key for the attribute and the second is the value"
(let [exploded-item
(mapcat
(fn [attr]
(let [t (attribute-type attr)]
(case t
:attribute (list [(name attr) (item attr)])
:nested-item (explode-nested-item attr (item (:name attr)))
:associated-items (explode-associated-items attr (item (:name attr))))))
schema)]
exploded-item))
(defn extract-attribute [attr-key input]
"Extracts a hash-map containing a single key and its value from the input.
The key is expected to be a keyword, while input is supposed to be a hash-map
with strings as keys"
(let [attr-name (name attr-key)
attr-value (input attr-name)]
(if (seq attr-value)
{attr-key attr-value}
nil)))
(defn extract-nested-item [attr input]
"Extracts a nested item from input, returning a hashmap with a single pair,
where the key is the nested item association name, and the value is a json
string representing all the attributes of the nested item.
attr is expected to be a hash-map with at least :name and :schema keys,
while input is expected to be a hash-map representing the profile, with strings as keys"
(let [association-name (:name attr)
association-schema (:schema attr)
nested-item (reduce
(fn [nested-item nested-attr]
(let [nested-attr-name (name nested-attr)
exploded-attr-name (str (name association-name) "_" nested-attr-name)
exploded-attr-value (input exploded-attr-name)]
(if (seq exploded-attr-value)
(conj nested-item { nested-attr exploded-attr-value})
nested-item)))
{}
association-schema)]
(when (seq nested-item)
{association-name nested-item})))
(defn extract-associated-item [association-name association-schema input index]
"Extracts the item belonging to a 'has many' association from input, at position index."
(reduce
(fn [associated-item associated-item-attr]
(let [associated-item-attr-name (name associated-item-attr)
exploded-attr-name (str (name association-name) "_" index "_" associated-item-attr-name)
exploded-attr-value (input exploded-attr-name)]
(if (seq exploded-attr-value)
(conj associated-item {associated-item-attr exploded-attr-value})
associated-item)))
{}
association-schema))
(defn extract-associated-items [attr input]
"Extracts a collection representing a 'has many' association from input.
It returns a list of hash-maps, each representing one of the items from
the association.
attr is expected to be a hash-map with at least :name and :schema keys,
while input is expected to be a hash-map representing the whole profile, with strings as keys"
(let [association-name (:name attr)
association-schema (:schema attr)
attribute-names (doall (keys input))
items-id-pattern (re-pattern (str (name association-name) "_(\\d+)_"))
items-ids (into #{} (->> attribute-names
(map #(when-some [x (re-find items-id-pattern %)] (last x)))
(filter #(not (nil? %)))))
associated-items (->> items-ids
(map #(extract-associated-item association-name association-schema input %))
(filter seq))]
(when (seq associated-items)
{association-name associated-items})))
(defn parse-by-schema [input schema]
"Parses input according to schema, assuming it was shaped as a
'tall' CSV profile.
This means that the first column contains attribute names, and the
second column contains values. Attribute names are presented in
'exploded' format, in order to properly address associations and
nesting.
Example:
attribute type | attribute name | exploded name |
standard | timestamp | timestamp |
nested item | profile_data, bedroom_count | profile_data_bedroom_count |
association | storeys, first storey_type | storeys_0_storey_type |"
(try
(let [parsed-data (reduce
(fn [item attr]
(let [t (attribute-type attr)
imploded-attribute (case t
:attribute (extract-attribute attr input)
:nested-item (extract-nested-item attr input)
:associated-items (extract-associated-items attr input))]
(if (seq imploded-attribute)
(conj item imploded-attribute)
item)))
{}
schema)]
parsed-data)
(catch Throwable t
(log/error t "Received malformed CSV.")
(throw t))))
(defn rows->columns [rows]
(apply map vector rows))
(defn data-header? [^String c]
(or (.startsWith c "values")
(.startsWith c "keys")))
(defn csv->maps [parse-schema rows]
(try
(let [[k & data] (->> rows
rows->columns
(filter #(-> % first string/lower-case data-header?)))
dirty-maps (map #(zipmap k (if (nil? %) "" %)) data)
maps (map #(parse-by-schema % parse-schema) dirty-maps)]
maps)
(catch Throwable t
(log/error t "Received malformed CSV.")
nil)))
(defn temp-file->rows [file-data]
(let [tempfile (:tempfile file-data)
dir (.getParent tempfile)
filename (.getName tempfile)
in-file (io/file dir filename)]
(with-open [in (io/reader in-file)]
(try
(-> (slurp in)
csv/read-csv)
(catch Throwable t
(log/error t "IOError on csv temp file.")
nil)))))
| null | https://raw.githubusercontent.com/MastodonC/kixi.hecuba/467400bbe670e74420a2711f7d49e869ab2b3e21/src/clj/kixi/hecuba/api/parser.clj | clojure | (ns kixi.hecuba.api.parser
(:require [clojure.string :as string]
[clojure.java.io :as io]
[clojure.data.csv :as csv]
[clojure.tools.logging :as log]
[cheshire.core :as json]))
(defn attribute-type [attr]
(if (keyword? attr)
:attribute
(:type attr)))
(defn explode-nested-item [association item]
"Explodes a nested item, that is represented in the object coming from
the datastore as a json encoded string. Returns a list of vectors of
two elements, the first being the attribute key, and the second the value.
The key is expanded to <nested item name>_<attribute name>"
(when item
(let [association-name (:name association)
association-schema (:schema association)]
(map
(fn [attr]
[(str (name association-name) "_" (name attr)) (attr item)])
association-schema))))
(defn explode-associated-items [association items]
"Explodes the elements of a (one to many) association, that is represented
in the object coming from the datastore as a list of json encoded strings.
Returns a list of vectors of two elements, the first being the attribute key,
and the second the value.
The keys are expanded like <association name>_<associated item index>_<attribute name>"
(let [association-name (name (:name association))
association-schema (:schema association)]
(apply concat
(keep-indexed
(fn [index item]
(let [item-name (str association-name "_" index)
named-association (assoc association :name item-name)]
(if (empty? association-schema)
[item-name item]
(explode-nested-item named-association item))))
items))))
(defn explode-and-sort-by-schema [item schema]
"Take a (profile) item from the datastore and converts into a list
of pairs (represented as a vector) where the first element is the
exploded key for the attribute and the second is the value"
(let [exploded-item
(mapcat
(fn [attr]
(let [t (attribute-type attr)]
(case t
:attribute (list [(name attr) (item attr)])
:nested-item (explode-nested-item attr (item (:name attr)))
:associated-items (explode-associated-items attr (item (:name attr))))))
schema)]
exploded-item))
(defn extract-attribute [attr-key input]
"Extracts a hash-map containing a single key and its value from the input.
The key is expected to be a keyword, while input is supposed to be a hash-map
with strings as keys"
(let [attr-name (name attr-key)
attr-value (input attr-name)]
(if (seq attr-value)
{attr-key attr-value}
nil)))
(defn extract-nested-item [attr input]
"Extracts a nested item from input, returning a hashmap with a single pair,
where the key is the nested item association name, and the value is a json
string representing all the attributes of the nested item.
attr is expected to be a hash-map with at least :name and :schema keys,
while input is expected to be a hash-map representing the profile, with strings as keys"
(let [association-name (:name attr)
association-schema (:schema attr)
nested-item (reduce
(fn [nested-item nested-attr]
(let [nested-attr-name (name nested-attr)
exploded-attr-name (str (name association-name) "_" nested-attr-name)
exploded-attr-value (input exploded-attr-name)]
(if (seq exploded-attr-value)
(conj nested-item { nested-attr exploded-attr-value})
nested-item)))
{}
association-schema)]
(when (seq nested-item)
{association-name nested-item})))
(defn extract-associated-item [association-name association-schema input index]
"Extracts the item belonging to a 'has many' association from input, at position index."
(reduce
(fn [associated-item associated-item-attr]
(let [associated-item-attr-name (name associated-item-attr)
exploded-attr-name (str (name association-name) "_" index "_" associated-item-attr-name)
exploded-attr-value (input exploded-attr-name)]
(if (seq exploded-attr-value)
(conj associated-item {associated-item-attr exploded-attr-value})
associated-item)))
{}
association-schema))
(defn extract-associated-items [attr input]
"Extracts a collection representing a 'has many' association from input.
It returns a list of hash-maps, each representing one of the items from
the association.
attr is expected to be a hash-map with at least :name and :schema keys,
while input is expected to be a hash-map representing the whole profile, with strings as keys"
(let [association-name (:name attr)
association-schema (:schema attr)
attribute-names (doall (keys input))
items-id-pattern (re-pattern (str (name association-name) "_(\\d+)_"))
items-ids (into #{} (->> attribute-names
(map #(when-some [x (re-find items-id-pattern %)] (last x)))
(filter #(not (nil? %)))))
associated-items (->> items-ids
(map #(extract-associated-item association-name association-schema input %))
(filter seq))]
(when (seq associated-items)
{association-name associated-items})))
(defn parse-by-schema [input schema]
"Parses input according to schema, assuming it was shaped as a
'tall' CSV profile.
This means that the first column contains attribute names, and the
second column contains values. Attribute names are presented in
'exploded' format, in order to properly address associations and
nesting.
Example:
attribute type | attribute name | exploded name |
standard | timestamp | timestamp |
nested item | profile_data, bedroom_count | profile_data_bedroom_count |
association | storeys, first storey_type | storeys_0_storey_type |"
(try
(let [parsed-data (reduce
(fn [item attr]
(let [t (attribute-type attr)
imploded-attribute (case t
:attribute (extract-attribute attr input)
:nested-item (extract-nested-item attr input)
:associated-items (extract-associated-items attr input))]
(if (seq imploded-attribute)
(conj item imploded-attribute)
item)))
{}
schema)]
parsed-data)
(catch Throwable t
(log/error t "Received malformed CSV.")
(throw t))))
(defn rows->columns [rows]
(apply map vector rows))
(defn data-header? [^String c]
(or (.startsWith c "values")
(.startsWith c "keys")))
(defn csv->maps [parse-schema rows]
(try
(let [[k & data] (->> rows
rows->columns
(filter #(-> % first string/lower-case data-header?)))
dirty-maps (map #(zipmap k (if (nil? %) "" %)) data)
maps (map #(parse-by-schema % parse-schema) dirty-maps)]
maps)
(catch Throwable t
(log/error t "Received malformed CSV.")
nil)))
(defn temp-file->rows [file-data]
(let [tempfile (:tempfile file-data)
dir (.getParent tempfile)
filename (.getName tempfile)
in-file (io/file dir filename)]
(with-open [in (io/reader in-file)]
(try
(-> (slurp in)
csv/read-csv)
(catch Throwable t
(log/error t "IOError on csv temp file.")
nil)))))
| |
c545615b62250f41e61cb02454ceb5dad8ad6ccfff108272e1780b7f1a78dd9d | Haskell-Things/ImplicitCAD | StateC.hs | {- ORMOLU_DISABLE -}
Implicit CAD . Copyright ( C ) 2011 , ( )
Copyright 2016 , ( )
-- Released under the GNU AGPLV3+, see LICENSE
module Graphics.Implicit.ExtOpenScad.Util.StateC (addMessage, getVarLookup, modifyVarLookup, lookupVar, pushVals, getVals, putVals, withPathShiftedBy, getPath, getRelPath, errorC, warnC, scadOptions) where
import Prelude(FilePath, Maybe, ($), (<>), pure)
import Graphics.Implicit.ExtOpenScad.Definitions(VarLookup(VarLookup), OVal, Symbol, SourcePosition, Message(Message), MessageType(Error, Warning), ScadOpts, StateC, CompState(scadVars, oVals, sourceDir))
import Data.Map (lookup)
import Data.Text.Lazy (Text)
import Control.Monad.State (modify, gets)
import System.FilePath((</>))
import Control.Monad.Writer (tell)
import Control.Monad.Reader.Class (ask)
getVarLookup :: StateC VarLookup
getVarLookup = gets scadVars
modifyVarLookup :: (VarLookup -> VarLookup) -> StateC ()
modifyVarLookup f = modify $ \c -> c { scadVars = f $ scadVars c }
-- | Perform a variable lookup
-- FIXME: generate a warning when we look up a variable that is not present.
lookupVar :: Symbol -> StateC (Maybe OVal)
lookupVar name = do
(VarLookup varlookup) <- getVarLookup
pure $ lookup name varlookup
pushVals :: [OVal] -> StateC ()
pushVals vals = modify $ \c -> c { oVals = vals <> oVals c }
getVals :: StateC [OVal]
getVals = gets oVals
putVals :: [OVal] -> StateC ()
putVals vals = modify $ \c -> c { oVals = vals }
withPathShiftedBy :: FilePath -> StateC a -> StateC a
withPathShiftedBy pathShift s = do
path <- getPath
modify $ \c -> c { sourceDir = path </> pathShift }
x <- s
modify $ \c -> c { sourceDir = path }
pure x
-- | Pure the path stored in the state.
getPath :: StateC FilePath
getPath = gets sourceDir
getRelPath :: FilePath -> StateC FilePath
getRelPath relPath = do
path <- getPath
pure $ path </> relPath
-- Add a single message to the list of messages being returned
addMesg :: Message -> StateC ()
addMesg m = tell [m]
addMessage :: MessageType -> SourcePosition -> Text -> StateC ()
addMessage mtype pos text = addMesg $ Message mtype pos text
errorC :: SourcePosition -> Text -> StateC ()
errorC = addMessage Error
# INLINABLE errorC #
warnC :: SourcePosition -> Text -> StateC ()
warnC = addMessage Warning
# INLINABLE warnC #
Get the ScadOpts from the Reader in ImplicitCadM
scadOptions :: StateC ScadOpts
scadOptions = ask | null | https://raw.githubusercontent.com/Haskell-Things/ImplicitCAD/0b3a4544b72074d3df77e8dd3502d05f5db75a21/Graphics/Implicit/ExtOpenScad/Util/StateC.hs | haskell | ORMOLU_DISABLE
Released under the GNU AGPLV3+, see LICENSE
| Perform a variable lookup
FIXME: generate a warning when we look up a variable that is not present.
| Pure the path stored in the state.
Add a single message to the list of messages being returned | Implicit CAD . Copyright ( C ) 2011 , ( )
Copyright 2016 , ( )
module Graphics.Implicit.ExtOpenScad.Util.StateC (addMessage, getVarLookup, modifyVarLookup, lookupVar, pushVals, getVals, putVals, withPathShiftedBy, getPath, getRelPath, errorC, warnC, scadOptions) where
import Prelude(FilePath, Maybe, ($), (<>), pure)
import Graphics.Implicit.ExtOpenScad.Definitions(VarLookup(VarLookup), OVal, Symbol, SourcePosition, Message(Message), MessageType(Error, Warning), ScadOpts, StateC, CompState(scadVars, oVals, sourceDir))
import Data.Map (lookup)
import Data.Text.Lazy (Text)
import Control.Monad.State (modify, gets)
import System.FilePath((</>))
import Control.Monad.Writer (tell)
import Control.Monad.Reader.Class (ask)
getVarLookup :: StateC VarLookup
getVarLookup = gets scadVars
modifyVarLookup :: (VarLookup -> VarLookup) -> StateC ()
modifyVarLookup f = modify $ \c -> c { scadVars = f $ scadVars c }
lookupVar :: Symbol -> StateC (Maybe OVal)
lookupVar name = do
(VarLookup varlookup) <- getVarLookup
pure $ lookup name varlookup
pushVals :: [OVal] -> StateC ()
pushVals vals = modify $ \c -> c { oVals = vals <> oVals c }
getVals :: StateC [OVal]
getVals = gets oVals
putVals :: [OVal] -> StateC ()
putVals vals = modify $ \c -> c { oVals = vals }
withPathShiftedBy :: FilePath -> StateC a -> StateC a
withPathShiftedBy pathShift s = do
path <- getPath
modify $ \c -> c { sourceDir = path </> pathShift }
x <- s
modify $ \c -> c { sourceDir = path }
pure x
getPath :: StateC FilePath
getPath = gets sourceDir
getRelPath :: FilePath -> StateC FilePath
getRelPath relPath = do
path <- getPath
pure $ path </> relPath
addMesg :: Message -> StateC ()
addMesg m = tell [m]
addMessage :: MessageType -> SourcePosition -> Text -> StateC ()
addMessage mtype pos text = addMesg $ Message mtype pos text
errorC :: SourcePosition -> Text -> StateC ()
errorC = addMessage Error
# INLINABLE errorC #
warnC :: SourcePosition -> Text -> StateC ()
warnC = addMessage Warning
# INLINABLE warnC #
Get the ScadOpts from the Reader in ImplicitCadM
scadOptions :: StateC ScadOpts
scadOptions = ask |
1695c1da62a3d5e888282b65f71f51b6706e5a6cb3f90ce9ab647104f9a69bbe | jarvinet/scheme | cont.scm | (define a
(call-with-current-continuation
(lambda (exit)
(for-each (lambda (x)
(if (< x 0)
(exit x)))
'(54 0 37 -3 245 19))
#t)))
;(define list-length
; (lambda (obj)
; (call-with-current-continuation
; (lambda (return)
; (letrec ((r
; (lambda (obj)
; (cond ((null? obj) 0)
; ((pair? obj)
( + ( r ( cdr obj ) ) 1 ) )
; (else (return #f))))))
; (r obj))))))
(define list-length
(lambda (obj)
(call-with-current-continuation
(lambda (return)
(define (r obj)
(cond ((null? obj) 0)
((pair? obj)
(+ (r (cdr obj)) 1))
(else (return #f))))
(r obj)))))
| null | https://raw.githubusercontent.com/jarvinet/scheme/47633d7fc4d82d739a62ceec75c111f6549b1650/bin/test/cont.scm | scheme | (define list-length
(lambda (obj)
(call-with-current-continuation
(lambda (return)
(letrec ((r
(lambda (obj)
(cond ((null? obj) 0)
((pair? obj)
(else (return #f))))))
(r obj)))))) | (define a
(call-with-current-continuation
(lambda (exit)
(for-each (lambda (x)
(if (< x 0)
(exit x)))
'(54 0 37 -3 245 19))
#t)))
( + ( r ( cdr obj ) ) 1 ) )
(define list-length
(lambda (obj)
(call-with-current-continuation
(lambda (return)
(define (r obj)
(cond ((null? obj) 0)
((pair? obj)
(+ (r (cdr obj)) 1))
(else (return #f))))
(r obj)))))
|
8d475bda5e904b9113b56febb52a0ccd7265d793d6969f0f4fb4c992cd64b945 | ashinkarov/heh | test_env.ml | open OUnit
open Ast
open Env
let test_env () =
let e = env_new () in
let e = env_add e "x" "p1" in
assert_equal ~msg:"environment lookup of `x'"
(env_lookup e "x") "p1";
let e = env_add e "x" "p2" in
let try_lookup () =
env_lookup e "y" in
assert_raises (EnvFailure "lookup of variable `y' failed") try_lookup;
assert_equal ~msg:"environment size should be 2"
( List.length e) 2
| null | https://raw.githubusercontent.com/ashinkarov/heh/42866803b2ffacdc42b8f06203bf4e5bd18e03b0/tests/test_env.ml | ocaml | open OUnit
open Ast
open Env
let test_env () =
let e = env_new () in
let e = env_add e "x" "p1" in
assert_equal ~msg:"environment lookup of `x'"
(env_lookup e "x") "p1";
let e = env_add e "x" "p2" in
let try_lookup () =
env_lookup e "y" in
assert_raises (EnvFailure "lookup of variable `y' failed") try_lookup;
assert_equal ~msg:"environment size should be 2"
( List.length e) 2
| |
ef1f6e4e62da630be4434fad2060ef580697472154e096b83ccf2292fc2f0dbc | epiccastle/bbssh | core.clj | (ns bb-test.core
(:require [babashka.pods :as pods]
[babashka.process :as process]
[babashka.wait :as wait]
[clojure.string :as string]
[clojure.test :as test]
[bb-test.docker :as docker]
)
(:import [java.lang.ref WeakReference]))
(def class-path
(-> "clojure -Spath -m bbssh.core"
process/sh
:out
string/trim
(str ":src/c/jni")))
(case (System/getenv "BBSSH_TEST_TARGET")
"native-image"
;; run pod process from native-image to test
(pods/load-pod "build/bbssh" {:transport :socket})
by default : run pod process under java in dev
(pods/load-pod ["java"
"-Djava.library.path=build"
"-cp"
class-path
"clojure.main"
"-m"
"bbssh.core"] {:transport :socket}))
(require '[bb-test.test-utils]
'[bb-test.test-scp]
'[bb-test.test-password-exec]
'[bb-test.test-user-info]
'[bb-test.test-garbage-collection]
'[bb-test.test-key-pair]
'[bb-test.test-identity-repository]
'[bb-test.test-host-key]
'[bb-test.test-known-hosts]
'[bb-test.test-openssh-config]
'[bb-test.test-port-forward]
'[bb-test.test-proxy-support])
(defn -main [& args]
(let [result
(test/run-tests
'bb-test.test-scp
'bb-test.test-utils
'bb-test.test-password-exec
'bb-test.test-user-info
'bb-test.test-garbage-collection
'bb-test.test-key-pair
'bb-test.test-identity-repository
'bb-test.test-host-key
'bb-test.test-known-hosts
'bb-test.test-openssh-config
'bb-test.test-port-forward
'bb-test.test-proxy-support)]
(prn result)
(when (or
(pos? (:fail result))
(pos? (:error result)))
(System/exit 1))))
| null | https://raw.githubusercontent.com/epiccastle/bbssh/497111a18610641566d764401d2ee6e83523c96e/test/bb_test/core.clj | clojure | run pod process from native-image to test | (ns bb-test.core
(:require [babashka.pods :as pods]
[babashka.process :as process]
[babashka.wait :as wait]
[clojure.string :as string]
[clojure.test :as test]
[bb-test.docker :as docker]
)
(:import [java.lang.ref WeakReference]))
(def class-path
(-> "clojure -Spath -m bbssh.core"
process/sh
:out
string/trim
(str ":src/c/jni")))
(case (System/getenv "BBSSH_TEST_TARGET")
"native-image"
(pods/load-pod "build/bbssh" {:transport :socket})
by default : run pod process under java in dev
(pods/load-pod ["java"
"-Djava.library.path=build"
"-cp"
class-path
"clojure.main"
"-m"
"bbssh.core"] {:transport :socket}))
(require '[bb-test.test-utils]
'[bb-test.test-scp]
'[bb-test.test-password-exec]
'[bb-test.test-user-info]
'[bb-test.test-garbage-collection]
'[bb-test.test-key-pair]
'[bb-test.test-identity-repository]
'[bb-test.test-host-key]
'[bb-test.test-known-hosts]
'[bb-test.test-openssh-config]
'[bb-test.test-port-forward]
'[bb-test.test-proxy-support])
(defn -main [& args]
(let [result
(test/run-tests
'bb-test.test-scp
'bb-test.test-utils
'bb-test.test-password-exec
'bb-test.test-user-info
'bb-test.test-garbage-collection
'bb-test.test-key-pair
'bb-test.test-identity-repository
'bb-test.test-host-key
'bb-test.test-known-hosts
'bb-test.test-openssh-config
'bb-test.test-port-forward
'bb-test.test-proxy-support)]
(prn result)
(when (or
(pos? (:fail result))
(pos? (:error result)))
(System/exit 1))))
|
b3f4b83364ec947bd2623eb7e8607c3e52f54a0cb7a083e09bc43ef4f8810885 | unison-code/uni-instr-sel | InstructionSynthesizer.hs | |
Copyright : Copyright ( c ) 2012 - 2017 , < >
License : BSD3 ( see the LICENSE file )
Maintainer :
Copyright : Copyright (c) 2012-2017, Gabriel Hjort Blindell <>
License : BSD3 (see the LICENSE file)
Maintainer :
-}
Main authors :
< >
Main authors:
Gabriel Hjort Blindell <>
-}
module Language.InstrSel.TargetMachines.Generators.InstructionSynthesizer
( addDualTargetBranchInstructions
, addEntryTargetBranchInstructions
, mkDualTargetBranchInstructions
, mkEntryTargetBranchInstructions
)
where
import Language.InstrSel.Constraints
import Language.InstrSel.Graphs
import Language.InstrSel.OpStructures
import Language.InstrSel.PrettyShow
import Language.InstrSel.TargetMachines.Base
import Language.InstrSel.TargetMachines.Generators.GenericInstructions
( reassignInstrIDs )
import Language.InstrSel.TargetMachines.Generators.PatternAnalysis
( isInstructionCondBranch
, isInstructionCondBranchWithFallthrough
, isInstructionUncondBranch
)
import Data.Maybe
( catMaybes
, fromJust
, isJust
)
-------------
-- Functions
-------------
-- | From a given target machine, constructs a new target machine that contains
-- synthesized branch instructions that can jump to both the true and the false
-- branch. These are synthesized using the conditional and unconditional branch
-- instructions already in the target machine. This assumes that all
-- unconditional branch instructions are equally suitable.
addDualTargetBranchInstructions :: TargetMachine -> Either String TargetMachine
addDualTargetBranchInstructions tm =
do let is = getAllInstructions tm
dual_br_is <- mkDualTargetBranchInstructions is
let new_is = reassignInstrIDs 0 (is ++ dual_br_is)
return $ replaceAllInstructions new_is tm
-- | From a given list of instructions, constructs new branch instructions that
-- can jump to both the true and the false branch. These are synthesized using
-- the branch instructions already in the list of instructions.
mkDualTargetBranchInstructions
:: [Instruction]
-- ^ List of existing instructions.
-> Either String [Instruction]
-- ^ The synthesized instructions if successful, otherwise an error
-- message.
mkDualTargetBranchInstructions is =
do let br_instrs = filter isInstructionUncondBranch is
br_instr <- if length br_instrs > 0
then Right $ head br_instrs
else Left "No unconditional branch instruction found"
let cbr_instrs = filter isInstructionCondBranchWithFallthrough is
dual_cbr_instrs <- mapM (convertFallthroughToBranch br_instr) cbr_instrs
return dual_cbr_instrs
convertFallthroughToBranch
:: Instruction
-- ^ An unconditional branch instruction.
-> Instruction
-- ^ The conditional branch instruction with fall-through to convert.
-> Either String Instruction
-- ^ The new instruction if successful, otherwise an error message.
convertFallthroughToBranch br_instr cond_br_instr =
do let mkEmitString ft_b_node =
do let br_emit_str = instrEmitString br_instr
os = instrOS br_instr
g = osGraph os
br_b_node <- let error_head = "In instruction with emit " ++
"string:\n" ++ pShow br_emit_str ++
":\n"
ns = filter ( \n ->
isBlockNode n &&
not (hasAnySuccessors g n)
) $
getAllNodes g
in if length ns == 1
then Right $ getNodeID $ head ns
else if length ns == 0
then Left $ error_head ++
"Has no block node without " ++
"successors"
else Left $ error_head ++ "Has multiple " ++
"block node without successors"
let new_br_emit_str = updateNodeInEmitStrTemplate ft_b_node
br_b_node
br_emit_str
return $ (instrEmitString cond_br_instr)
`concatEmitStrings`
new_br_emit_str
let error_head = "In instruction with emit string:\n" ++
pShow (instrEmitString cond_br_instr) ++ ":\n"
os = instrOS cond_br_instr
cs = osConstraints os
ft_c <- let c = filter isFallThroughConstraint cs
in if length c == 1
then Right $ head c
else if length c == 0
then Left $ error_head ++
"No fall-through constraint found"
else Left $ error_head ++ "Multiple " ++
"fall-through constraints found"
let getNode ( FallThroughFromMatchToBlockConstraint
( BlockOfBlockNodeExpr
( ANodeIDExpr n )
)
) = Right n
getNode _ = Left $ error_head ++
"Unexpected fall-through constraint structure"
ft_b_node <- getNode ft_c
let new_cs = filter (not . isFallThroughConstraint) cs
new_os = os { osConstraints = new_cs }
new_emit_str <- mkEmitString ft_b_node
let mkInstrProps =
let br_props = instrProps br_instr
cond_br_props = instrProps cond_br_instr
in cond_br_props { instrCodeSize = instrCodeSize cond_br_props +
instrCodeSize br_props
, instrLatency = instrLatency cond_br_props +
instrLatency br_props
}
return $ cond_br_instr { instrID = 0
, instrOS = new_os
, instrEmitString = new_emit_str
, instrProps = mkInstrProps
}
-- | From a given target machine, constructs a new target machine that contains
-- synthesized branch instructions that can jump back to the current block.
-- These are synthesized using the branch instructions already in the target
-- machine.
addEntryTargetBranchInstructions :: TargetMachine -> Either String TargetMachine
addEntryTargetBranchInstructions tm =
do let is = getAllInstructions tm
entry_br_is <- mkEntryTargetBranchInstructions is
let new_is = reassignInstrIDs 0 (is ++ entry_br_is)
return $ replaceAllInstructions new_is tm
-- | From a given list of instructions, constructs new branch instructions that
-- can jump back to the current block. These are synthesized using the branch
-- instructions already in the list of instructions.
mkEntryTargetBranchInstructions
:: [Instruction]
-- ^ List of existing instructions.
-> Either String [Instruction]
-- ^ The synthesized instructions if successful, otherwise an error
-- message.
mkEntryTargetBranchInstructions is =
do let br_instrs = filter ( \i -> isInstructionUncondBranch i ||
isInstructionCondBranch i
) $
is
new_br_instrs <- mapM redirectTargetBlockToEntry br_instrs
return $ concat new_br_instrs
redirectTargetBlockToEntry
:: Instruction
-- ^ The branch instruction from which to synthesize new instructions.
-> Either String [Instruction]
-- ^ The set of new instructions if successful, otherwise an error message.
redirectTargetBlockToEntry i =
do let error_head = "In instruction with emit string:\n" ++
pShow (instrEmitString i) ++ ":\n"
os = instrOS i
g = osGraph os
cs = osConstraints os
ft_cs = filter isFallThroughConstraint cs
let getNode ( FallThroughFromMatchToBlockConstraint
( BlockOfBlockNodeExpr
( ANodeIDExpr n )
)
) = Right $ Just n
getNode (FallThroughFromMatchToBlockConstraint _) =
Left $ error_head ++ "Unexpected fall-through constraint structure"
getNode _ = Right $ Nothing
ft_b_nodes_in_cs <- mapM getNode ft_cs
let ft_b_nodes = catMaybes ft_b_nodes_in_cs
entry_b <- if isJust (entryBlockNode g)
then Right $ fromJust $ entryBlockNode g
else Left $ error_head ++ "Has no entry block node"
let b_ns = [ n | n <- filter isBlockNode $ getAllNodes g
, getNodeID n `notElem` ft_b_nodes
, length (getCtrlFlowOutEdges g n) == 0
]
mkNewInstruction n =
let new_g = mergeNodes entry_b n g
new_os = os { osGraph = new_g }
new_emit_str = updateNodeInEmitStrTemplate (getNodeID entry_b)
(getNodeID n)
(instrEmitString i)
in i { instrID = 0
, instrOS = new_os
, instrEmitString = new_emit_str
}
return $ map mkNewInstruction b_ns
| null | https://raw.githubusercontent.com/unison-code/uni-instr-sel/2edb2f3399ea43e75f33706261bd6b93bedc6762/hlib/instr-sel/Language/InstrSel/TargetMachines/Generators/InstructionSynthesizer.hs | haskell | -----------
Functions
-----------
| From a given target machine, constructs a new target machine that contains
synthesized branch instructions that can jump to both the true and the false
branch. These are synthesized using the conditional and unconditional branch
instructions already in the target machine. This assumes that all
unconditional branch instructions are equally suitable.
| From a given list of instructions, constructs new branch instructions that
can jump to both the true and the false branch. These are synthesized using
the branch instructions already in the list of instructions.
^ List of existing instructions.
^ The synthesized instructions if successful, otherwise an error
message.
^ An unconditional branch instruction.
^ The conditional branch instruction with fall-through to convert.
^ The new instruction if successful, otherwise an error message.
| From a given target machine, constructs a new target machine that contains
synthesized branch instructions that can jump back to the current block.
These are synthesized using the branch instructions already in the target
machine.
| From a given list of instructions, constructs new branch instructions that
can jump back to the current block. These are synthesized using the branch
instructions already in the list of instructions.
^ List of existing instructions.
^ The synthesized instructions if successful, otherwise an error
message.
^ The branch instruction from which to synthesize new instructions.
^ The set of new instructions if successful, otherwise an error message. | |
Copyright : Copyright ( c ) 2012 - 2017 , < >
License : BSD3 ( see the LICENSE file )
Maintainer :
Copyright : Copyright (c) 2012-2017, Gabriel Hjort Blindell <>
License : BSD3 (see the LICENSE file)
Maintainer :
-}
Main authors :
< >
Main authors:
Gabriel Hjort Blindell <>
-}
module Language.InstrSel.TargetMachines.Generators.InstructionSynthesizer
( addDualTargetBranchInstructions
, addEntryTargetBranchInstructions
, mkDualTargetBranchInstructions
, mkEntryTargetBranchInstructions
)
where
import Language.InstrSel.Constraints
import Language.InstrSel.Graphs
import Language.InstrSel.OpStructures
import Language.InstrSel.PrettyShow
import Language.InstrSel.TargetMachines.Base
import Language.InstrSel.TargetMachines.Generators.GenericInstructions
( reassignInstrIDs )
import Language.InstrSel.TargetMachines.Generators.PatternAnalysis
( isInstructionCondBranch
, isInstructionCondBranchWithFallthrough
, isInstructionUncondBranch
)
import Data.Maybe
( catMaybes
, fromJust
, isJust
)
addDualTargetBranchInstructions :: TargetMachine -> Either String TargetMachine
addDualTargetBranchInstructions tm =
do let is = getAllInstructions tm
dual_br_is <- mkDualTargetBranchInstructions is
let new_is = reassignInstrIDs 0 (is ++ dual_br_is)
return $ replaceAllInstructions new_is tm
mkDualTargetBranchInstructions
:: [Instruction]
-> Either String [Instruction]
mkDualTargetBranchInstructions is =
do let br_instrs = filter isInstructionUncondBranch is
br_instr <- if length br_instrs > 0
then Right $ head br_instrs
else Left "No unconditional branch instruction found"
let cbr_instrs = filter isInstructionCondBranchWithFallthrough is
dual_cbr_instrs <- mapM (convertFallthroughToBranch br_instr) cbr_instrs
return dual_cbr_instrs
convertFallthroughToBranch
:: Instruction
-> Instruction
-> Either String Instruction
convertFallthroughToBranch br_instr cond_br_instr =
do let mkEmitString ft_b_node =
do let br_emit_str = instrEmitString br_instr
os = instrOS br_instr
g = osGraph os
br_b_node <- let error_head = "In instruction with emit " ++
"string:\n" ++ pShow br_emit_str ++
":\n"
ns = filter ( \n ->
isBlockNode n &&
not (hasAnySuccessors g n)
) $
getAllNodes g
in if length ns == 1
then Right $ getNodeID $ head ns
else if length ns == 0
then Left $ error_head ++
"Has no block node without " ++
"successors"
else Left $ error_head ++ "Has multiple " ++
"block node without successors"
let new_br_emit_str = updateNodeInEmitStrTemplate ft_b_node
br_b_node
br_emit_str
return $ (instrEmitString cond_br_instr)
`concatEmitStrings`
new_br_emit_str
let error_head = "In instruction with emit string:\n" ++
pShow (instrEmitString cond_br_instr) ++ ":\n"
os = instrOS cond_br_instr
cs = osConstraints os
ft_c <- let c = filter isFallThroughConstraint cs
in if length c == 1
then Right $ head c
else if length c == 0
then Left $ error_head ++
"No fall-through constraint found"
else Left $ error_head ++ "Multiple " ++
"fall-through constraints found"
let getNode ( FallThroughFromMatchToBlockConstraint
( BlockOfBlockNodeExpr
( ANodeIDExpr n )
)
) = Right n
getNode _ = Left $ error_head ++
"Unexpected fall-through constraint structure"
ft_b_node <- getNode ft_c
let new_cs = filter (not . isFallThroughConstraint) cs
new_os = os { osConstraints = new_cs }
new_emit_str <- mkEmitString ft_b_node
let mkInstrProps =
let br_props = instrProps br_instr
cond_br_props = instrProps cond_br_instr
in cond_br_props { instrCodeSize = instrCodeSize cond_br_props +
instrCodeSize br_props
, instrLatency = instrLatency cond_br_props +
instrLatency br_props
}
return $ cond_br_instr { instrID = 0
, instrOS = new_os
, instrEmitString = new_emit_str
, instrProps = mkInstrProps
}
addEntryTargetBranchInstructions :: TargetMachine -> Either String TargetMachine
addEntryTargetBranchInstructions tm =
do let is = getAllInstructions tm
entry_br_is <- mkEntryTargetBranchInstructions is
let new_is = reassignInstrIDs 0 (is ++ entry_br_is)
return $ replaceAllInstructions new_is tm
mkEntryTargetBranchInstructions
:: [Instruction]
-> Either String [Instruction]
mkEntryTargetBranchInstructions is =
do let br_instrs = filter ( \i -> isInstructionUncondBranch i ||
isInstructionCondBranch i
) $
is
new_br_instrs <- mapM redirectTargetBlockToEntry br_instrs
return $ concat new_br_instrs
redirectTargetBlockToEntry
:: Instruction
-> Either String [Instruction]
redirectTargetBlockToEntry i =
do let error_head = "In instruction with emit string:\n" ++
pShow (instrEmitString i) ++ ":\n"
os = instrOS i
g = osGraph os
cs = osConstraints os
ft_cs = filter isFallThroughConstraint cs
let getNode ( FallThroughFromMatchToBlockConstraint
( BlockOfBlockNodeExpr
( ANodeIDExpr n )
)
) = Right $ Just n
getNode (FallThroughFromMatchToBlockConstraint _) =
Left $ error_head ++ "Unexpected fall-through constraint structure"
getNode _ = Right $ Nothing
ft_b_nodes_in_cs <- mapM getNode ft_cs
let ft_b_nodes = catMaybes ft_b_nodes_in_cs
entry_b <- if isJust (entryBlockNode g)
then Right $ fromJust $ entryBlockNode g
else Left $ error_head ++ "Has no entry block node"
let b_ns = [ n | n <- filter isBlockNode $ getAllNodes g
, getNodeID n `notElem` ft_b_nodes
, length (getCtrlFlowOutEdges g n) == 0
]
mkNewInstruction n =
let new_g = mergeNodes entry_b n g
new_os = os { osGraph = new_g }
new_emit_str = updateNodeInEmitStrTemplate (getNodeID entry_b)
(getNodeID n)
(instrEmitString i)
in i { instrID = 0
, instrOS = new_os
, instrEmitString = new_emit_str
}
return $ map mkNewInstruction b_ns
|
12997149e4dce75636d82e01b2abfc8a7a9b1b92ea56ebfa67efe8ce000ec049 | zk/nsfw | css.cljc | (ns nsfw.devbus.css
(:require [nsfw.css :as ncss]))
(def spec {:sizes {:xs 5 :sm 10 :md 20 :lg 50 :xl 100}
:fonts {:header "'Helvetica Neue', Arial, sans-serif"
:copy "'Helvetica Neue', Arial, sans-serif"
:impact "'Helvetica Neue', Arial, sans-serif"
:monospace "'Source Code Pro', monospace"}})
(ncss/inject-css-defs spec)
(def rules
(vec
(concat
(ncss/gen-all-rules spec)
[])))
(def rules-string
(ncss/compile-to-string rules))
| null | https://raw.githubusercontent.com/zk/nsfw/ea07ba20cc5453b34a56b34c9d8738bf9bf8e92f/src/cljc/nsfw/devbus/css.cljc | clojure | (ns nsfw.devbus.css
(:require [nsfw.css :as ncss]))
(def spec {:sizes {:xs 5 :sm 10 :md 20 :lg 50 :xl 100}
:fonts {:header "'Helvetica Neue', Arial, sans-serif"
:copy "'Helvetica Neue', Arial, sans-serif"
:impact "'Helvetica Neue', Arial, sans-serif"
:monospace "'Source Code Pro', monospace"}})
(ncss/inject-css-defs spec)
(def rules
(vec
(concat
(ncss/gen-all-rules spec)
[])))
(def rules-string
(ncss/compile-to-string rules))
| |
86762ca431dd0366306577426e83d534adc76f83e3248dc3f5412f5574204513 | clojurecup2014/parade-route | api.clj | Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.test-clojure.api
(:require [clojure.test.generative :refer (defspec)]
[clojure.test-clojure.generators :as cgen])
(:import clojure.lang.IFn
clojure.clr.api.Clojure ;;; clojure.java.api.Clojure
clojure.lang.Var))
(set! *warn-on-reflection* true)
(defn roundtrip
"Print an object and read it back with Clojure/read"
[o]
(binding [*print-length* nil
*print-dup* nil
*print-level* nil]
(Clojure/read (pr-str o))))
(defn api-var-str
[^Var v]
(Clojure/var (str (.Name (.ns v))) ;;; .name
(str (.sym v))))
(defn api-var
[^Var v]
(Clojure/var (.Name (.ns v)) ;;; .name
(.sym v)))
(defspec api-can-read
roundtrip
[^{:tag cgen/ednable} o]
(when-not (= o %)
(throw (ex-info "Value cannot roundtrip with Clojure/read" {:printed o :read %}))))
(defspec api-can-find-var
api-var
[^{:tag cgen/var} v]
(when-not (= v %)
(throw (ex-info "Var cannot roundtrip through Clojure/var" {:from v :to %}))))
(defspec api-can-find-var-str
api-var-str
[^{:tag cgen/var} v]
(when-not (= v %)
(throw (ex-info "Var cannot roundtrip strings through Clojure/var" {:from v :to %}))))
| null | https://raw.githubusercontent.com/clojurecup2014/parade-route/adb2e1ea202228e3da07902849dee08f0bb8d81c/Assets/Clojure/Internal/Plugins/clojure/test_clojure/api.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
clojure.java.api.Clojure
.name
.name | Copyright ( c ) . All rights reserved .
(ns clojure.test-clojure.api
(:require [clojure.test.generative :refer (defspec)]
[clojure.test-clojure.generators :as cgen])
(:import clojure.lang.IFn
clojure.lang.Var))
(set! *warn-on-reflection* true)
(defn roundtrip
"Print an object and read it back with Clojure/read"
[o]
(binding [*print-length* nil
*print-dup* nil
*print-level* nil]
(Clojure/read (pr-str o))))
(defn api-var-str
[^Var v]
(str (.sym v))))
(defn api-var
[^Var v]
(.sym v)))
(defspec api-can-read
roundtrip
[^{:tag cgen/ednable} o]
(when-not (= o %)
(throw (ex-info "Value cannot roundtrip with Clojure/read" {:printed o :read %}))))
(defspec api-can-find-var
api-var
[^{:tag cgen/var} v]
(when-not (= v %)
(throw (ex-info "Var cannot roundtrip through Clojure/var" {:from v :to %}))))
(defspec api-can-find-var-str
api-var-str
[^{:tag cgen/var} v]
(when-not (= v %)
(throw (ex-info "Var cannot roundtrip strings through Clojure/var" {:from v :to %}))))
|
df5b86b1e318b798f0003daba8d5321ded6236f8dcfe40d23721e54e44c00782 | yuanqing/code-problems | odd_occurring_element.ml | let odd_occurring_element (xs:'a list) : 'a =
let ht = Hashtbl.create (List.length xs) in
let rec aux xs =
match xs with
| [] ->
Unpack the odd - occurring element from ` ht ` .
let fn elem _ _ = [elem] in
begin match Hashtbl.fold fn ht [] with
| x::_ -> x
| _ -> failwith "No odd-occurring element"
end
| x::xs ->
let () =
if not (Hashtbl.mem ht x) then
(* Element not encountered before, or occurred an even number of
times so far. *)
Hashtbl.add ht x ()
else
(* Element encountered before an odd number of times, so remove
it from `ht`. *)
Hashtbl.remove ht x in
aux xs in
aux xs
| null | https://raw.githubusercontent.com/yuanqing/code-problems/30eb34ad616146306cddc50594a47deff111f341/src/odd_occurring_element/odd_occurring_element.ml | ocaml | Element not encountered before, or occurred an even number of
times so far.
Element encountered before an odd number of times, so remove
it from `ht`. | let odd_occurring_element (xs:'a list) : 'a =
let ht = Hashtbl.create (List.length xs) in
let rec aux xs =
match xs with
| [] ->
Unpack the odd - occurring element from ` ht ` .
let fn elem _ _ = [elem] in
begin match Hashtbl.fold fn ht [] with
| x::_ -> x
| _ -> failwith "No odd-occurring element"
end
| x::xs ->
let () =
if not (Hashtbl.mem ht x) then
Hashtbl.add ht x ()
else
Hashtbl.remove ht x in
aux xs in
aux xs
|
d6ddd7736fd41aaaa9d13bdca00465a8b75f3ef4462eb780790e0ee632c92e7e | mclumd/Meta-AQUA | learner.lisp | -*- Mode : LISP ; Syntax : Common - lisp ; Package : Meta - aqua ; Base : 10 -*-
(in-package :metaaqua)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
;;;; The Meta-AQUA Introspective Multistrategy Learning System
;;;; Version 6
;;;;
Copyright ( C ) 1996 ( )
;;;;
;;;;
;;;; File: learner.lisp
;;;;
;;;;
;;;; *******************************************************
;;;
;;; This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation ; either version 1 , or ( at your option ) any later
;;; version.
;;;
;;; This program is distributed in the hope that it will be useful, but WITHOUT
;;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
;;; FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
;;; more details.
;;;
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. , 675
Mass Ave , Cambridge , , USA . In emacs type C - h C - w to view license .
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
;;;; LEARN AND REVIEW PHASE
;;;; AND LEARNING STRATEGIES
;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Support Functions
;;;
;;;
;;; Predicate not-trivial-frame-p returns t if the input frame is a trivial
;;; frame, nil otherwise. A frame is trivial if it has only a status slot and a
;;; truth slot. Many (most?) entity frames suit this characterization. This
predicate is used during EBG .
;;;
(defun not-trivial-frame-p (frame)
(if (remove
*status-slot*
(remove
*truth-slot*
(f.role-list frame)))
t)
)
(defun test-p (list)
(if (not (equal 'instance-of (first list)))
(let ((found nil))
(dolist (each-item (rest list))
(if (and (not (not-trivial-frame-p each-item))
(not (attribute-value-p each-item)))
(setf found t)))
found))
)
;;;
;;; Function remove-truth removes truth-slot value fillers from all decendents
;;; of the given frame. The use of this function above may not be necessary
;;; because of the conditional check of not-trivial-frame-p.
;;;
(defun remove-truth (frame)
(f.traverse-frame
frame
(lambda (current-frame parent role facet-name level)
(if (and (not (visited-p current-frame *traverse-marker*))
(equal role *truth-slot*)
(equal facet-name *value-facet*))
(f.remove-filler! parent *truth-slot*))))
frame
)
;;;
;;; Function change-status alters the status slot of fillers from all
;;; decendents of the given frame. The argument new-status replaces the old
;;; value if there was one. A frame's status changes when it is acquired as a
;;; case, generalized, or otherwise brought into a program from input. The
;;; changes is usually from story-instance to learned.
;;;
;;; |||||| Should we change the status if a frame is a predefined instance?
;;; Or an attribute value?
;;;
(defun change-status (frame new-status)
(f.traverse-frame
frame
(lambda (current-frame parent role facet-name level)
(if (and (non-attribute-val-status-p
current-frame
role
facet-name)
(not (equal current-frame *question*)))
(f.put! new-status parent *status-slot*))))
frame
)
;;;
Predicate non - attribute - status - filler - p returns t when the current - frame is
;;; a filler for a status slot other than the status-slot filler
;;; 'attribute-value.0 (which signifies that the parent is an attribute filler
itself , such as in.0 or learned.0 ) . Such values are not subject to change .
;;; Visited frames have already been changed.
;;;
(defun non-attribute-val-status-p (current-frame role facet-name)
(do-break non-attribute-val-status-p)
(and (not (visited-p current-frame *traverse-marker*))
(equal role *status-slot*)
(equal facet-name *value-facet*)
(not (equal *attribute-value*
current-frame)))
)
(defun remove-status (frame)
(f.traverse-frame
frame
(lambda (current-frame parent role facet-name level)
(if (and
(non-attribute-val-status-p
current-frame
role
facet-name)
(not (equal current-frame *question*)))
(f.remove-filler! parent *status-slot*))))
frame
)
;;;
;;; ||||| Note that funcall may be appropriate to use
;;; because of the problems encountered below.
;(defun test (p1 p2)
; (format t "~%The number is ~s." (eval p2))
; )
;
( dolist ( each - num ' ( 1 2 3 4 ) ) ( test each - num ' ( + 1 p1 ) ) )
; |||||
; Function old-review used this. What will be done?
;
(defun retrieve-case-from-META-XP (concept)
(first (get-model *World-Model*))
)
;;;
;;; Function adjust-path changes the path-list so that as f.traverse-frame
;;; traverses the node network, the path-list contracts to remain pointing
;;; into the net. A call of f.chase-path will then be able to get to the
;;; current node being operated on.
;;;
(defun adjust-path (path-list level)
(cond ((equal level *prev-level*)
(butlast path-list))
((> level *prev-level*)
path-list)
((< level *prev-level*)
(dotimes (x (+ 1 (- *prev-level* level)))
(setf path-list (butlast path-list)))
path-list))
)
;;;
;;; Explanation-Based Generalization (EBG) Learning Strategy
;;;
;;;
;;; |||||Note that in the current version this will produce extra slots if the
;;; ones in the xp do not have as many slots as the definition of a frame.
;;;
;;; NOTE that this is not the current definition used by the program. Look
;;; below for the right one.
;;;
;(defun generalize-node (current-frame parent role facet-name level parent-struct)
; (cond ((not (equal level 0))
( setf * path - list * ( append
; (adjust-path *path-list* level)
; `((,role ,facet-name)) ))
( setf * prev - level * level )
; (when (and (not (visited-p current-frame))
; ;; The frame-body call makes sure that this is not a terminal.
; (frame-body current-frame)
; (not-trivial-frame-p current-frame))
; (f.unify current-frame
; ;; |||||Literals are not handled properly below.
; (let ((new-frame
; (frame-def
; (apply #'f.chase-path
; *new-struct*
; *path-list*))))
; (if (or (null new-frame)
; ; |||||| Eventually we want to unify all items in a list .
; (frame-list-p (f.get parent role facet-name)))
; *nil*
( if ( listp new - frame )
; (if (attribute-value-p (frame-type new-frame))
; new-frame
; (if (literal-p (frame-type new-frame))
; (f.set-literal
; (f.instantiate-frame (*FRAME* *literal*))
; (symbol-value new-frame))
; (f.instantiate-frame new-frame)))
; (f.instantiate-frame (list new-frame))))))
; (format-if
; (and *Debug-On* (f.where-bound current-frame))
; t
" ~%Backpointers of ~s is ~s.~%Location is ~s-~s-~s.~% "
; current-frame
; (f.where-bound current-frame)
; parent role facet-name)
; )))
; (when *Debug-On*
; (format t "~%*path-list*: ~s." *path-list*)
; (format t "~%*prev-level*: ~s.~%" *prev-level*))
; )
(defun generalize-node (current-frame parent role facet-name level parent-struct)
( if ( isa - p ' fridge ( list current - frame ) )
;;; (do-break generalize-node))
(cond ((not (equal level 0))
(setf *path-list* (append
(adjust-path *path-list* level)
`((,role ,facet-name)) ))
(setf *prev-level* level)
(when (and (not (visited-p current-frame *traverse-marker*))
;;; (not (tmxp-filter current-frame))
;; The frame-body call makes sure that this is not a terminal.
(frame-body current-frame)
(not-trivial-frame-p current-frame))
(f.unify
(apply #'f.chase-path *new-struct* *path-list*)
;; ||||||Literals are not handled properly below.
||||||Is it because f.set - literal returns the value rather than the literal ? [ cox 24apr94 ]
(let ((new-frame (frame-def current-frame)))
(if (or (null new-frame)
;; |||||| Eventually we want to unify all items in a list.
(frame-list-p (f.get parent role facet-name)))
*nil*
(if (listp new-frame)
(if (attribute-value-p (frame-type new-frame))
new-frame
(if (literal-p (frame-type new-frame))
(f.set-literal
(f.instantiate-frame (*FRAME* *literal*))
(symbol-value new-frame))
(f.instantiate-frame new-frame)))
(f.instantiate-frame (list new-frame)))))
:notify-but-no-break)
(if (and *Debug-On* (f.where-bound current-frame))
(format t "~%Backpointers of ~s is ~s.~%Location is ~s-~s-~s.~%"
current-frame
(f.where-bound current-frame)
parent role facet-name))
)))
(when *Debug-On*
(format t "~%*path-list*: ~s." *path-list*)
(format t "~%*prev-level*: ~s.~%" *prev-level*))
)
;;;
;;; Function do-ebg should really be doing this.
;;;
(defun perform-EBG-on (xp)
;; Set-up for function generalize-node.
;; |||||Why is this not done with let?
(setf *path-list* nil)
(setf *prev-level* 0)
( setf * new - struct *
;;; (f.instantiate-frame (*FRAME* (frame-type xp))))
(setf *new-struct* xp)
(do-break perform-EBG-on)
(f.traverse-frame
(f.instantiate-frame (*FRAME* (frame-type xp)))
#'generalize-node nil)
;; ||||| Really need to just make sure that tokens are unified
;; after fixing backptr problem, instead of the following hack.
(f.unify (f.chase-path *new-struct* 'consequent 'object)
(f.chase-path *new-struct*
'main-precondition
*co-domain-slot*
*co-domain-slot*
*co-domain-slot*))
(remove-truth *new-struct*)
)
;(defun count-nodes (current-frame parent role facet-name level)
; (if (not (visited-p current-frame *traverse-marker*))
( setf * x * ( + 1 * x * ) ) )
; )
;
;(defun find-it (current-frame parent role facet-name level)
; (if (equal 'drug (frame-type current-frame))
; (break))
; )
;
;
( setf * x * 0 )
(defvar *path-list* nil)
(defvar *prev-level* 0)
(defvar *new-struct* nil)
(defun perform-EBG-on (xp)
; (with-character-style (*Style*)
(format
*aqua-window*
"~%~%Performing EBG on explanation ~s."
xp)
;; Set-up for function generalize-node.
;; |||||Why is this not done with let?
(setf *path-list* nil)
(setf *prev-level* 0)
(setf *new-struct*
(f.instantiate-frame (frame-def xp)))
(do-break perform-EBG-on)
(f.traverse-frame xp #'generalize-node nil)
;; ||||| Really need to just make sure that tokens are unified
;; after fixing backptr problem, instead of the following hack.
(f.unify (f.chase-path *new-struct* 'conseq 'object)
(f.chase-path *new-struct*
'main-precondition
*co-domain-slot*
*co-domain-slot*
*co-domain-slot*)
:notify-but-no-break)
(let ((generalized-xp
(change-status
(remove-truth *new-struct*)
*learned*)))
(format
*aqua-window*
"~% resulting in general explanation ~s.~%"
generalized-xp)
generalized-xp)
; )
)
;;;;
;;;; Review - Learn Phase
;;;;
;;;
||||| NOTE the perform - EBG - on function that really does the EBG in
function specialize . Change soon . 18 May 93 .
;;;
(defun do-EBG (concept)
(format
*aqua-window*
"~%Execute EBG on ~s."
concept)
)
;;; ||||||Must complete.
(defun new-concept (concept)
t)
;;;
|||||| WIll this involve a differentiate plan ?
;;;
;;; Function differentiate creates subgoals to achieve a given
;;; knowledge-differentiation-goal. If either of the objects to be
;;; differentiated are new concepts, then we spawn a sub-goal to expand them.
The subgoal will have a higher priority than the following organization
;;; goal so that the concepts will be ready to be indexed.
;;;
(defun differentiate (differentiate-goal)
(let* ((g-actor (goal-actor differentiate-goal))
(g-object (goal-object differentiate-goal))
(obj1 (f.get *domain-slot* g-object))
(obj2 (f.get *co-domain-slot* g-object))
(goal-priority (f.get differentiate-goal 'priority))
(higher-priority
(inverse-trans
(+ 2 (trans goal-priority))))
)
(do-break differentiate)
(if (new-concept obj1)
(spawn-sub-goal
g-actor
obj1
knowledge-expansion-goal.0
higher-priority
differentiate-goal))
(if (new-concept obj2)
(spawn-sub-goal
g-actor
obj2
knowledge-expansion-goal.0
higher-priority
differentiate-goal))
(spawn-sub-goal
g-actor
`(reindex-with-respect-to
(,*domain-slot* (,*value-facet* ,obj1))
(,*co-domain-slot* (,*value-facet* ,obj2)))
knowledge-reorganization-goal.0
(inverse-trans
(- (trans higher-priority)
1))
differentiate-goal)
Also need to place these subgoals on the subgoal slot of the differentiation goal .
)
)
;(defun generalize (xp-token imxp role-literal)
; (let ((generalized-xp (perform-ebg-on xp-token)))
; (break)
; (f.unify generalized-xp
; (f.get imxp
; (symbol-value
; role-literal))))
; )
;;;
Function generalize calls ebg on the xp token . The resultant generalized
;;; explanation is then unified with m-prime. M-prime is the node in the imxp
;;; that registers the new explanation created during learning.
;;;
;;; If various generalization routine were available to choose from, this
;;; function might decide which was most appropriate. At least it would have
;;; the appropriate algorithm passed to it.
;;;
(defun generalize (xp-token memory-item)
the token
using EBG .
xp-token)))
(do-break generalize)
Reversed order or arguments below [ cox 30jun95 ]
(f.unify
with the imxp node m ' or
generalized-xp ;Unify the result
))
)
;;;
;;; Function abstract currently is used to handle the bad constraints on the
;;; value of at-locations on a bark. This is done by abstracting to the common
;;; parents of what was expected (the constraint) to happen and what actually
;;; happened.
;;;
||||||Note that this is passed = A1 and = Anomaly as sibling1 and sibling2
respectively . Which - sibling will then be assigned from sibling2 and
( sibling1 ) will never be used in the function .
;;;
(defun abstract (sibling1 sibling2)
(let ((which-sibling ;Find the parameter which
(cond ((isa-p 'anomaly ;represents the original anomaly.
(list sibling1))
sibling1)
((isa-p 'anomaly
(list sibling2))
sibling2)
)))
(do-break abstract)
(if which-sibling
(let* ((action (f.get which-sibling 'action))
(path (first (symbol-value (f.get which-sibling 'paths))))
;; ||||| Hack: f.chase-path needs to be modified rather than having the
;; following conditional. See comments on f.chase-path.
(constraint (let ((temp
(if (listp path)
(apply #'f.chase-path
(frame-def action)
path))))
(if (var-binding-p temp)
(f.get (frame-def action)
(var->role temp))
temp)))
(actual
(f.get which-sibling 'actual-outcome)
( if ( path )
; (apply #'f.chase-path
; (cons
; action
; path)))
)
(common-parent (f.lowest-common-ancestor
(frame-type constraint)
(frame-type actual))))
; (format
; *aqua-window*
" ~%~%Concept : ~s~%Slots : ~s~%Constraint : ~s~% "
( first ( get - abstraction action ) )
; (symbol-value (f.get which-sibling 'paths))
; constraint)
; (format
; *aqua-window*
; (str-concat
; "Actual Filler: ~s "
" = ~s~%Common - Parent : ~s~% " )
; actual
; (get-abstraction
( first
; (get-abstraction
( first ( get - abstraction actual ) ) ) ) )
; common-parent)
(if (listp path)
; (with-character-style (*Style*)
(cond (common-parent
(format
*aqua-window*
"~%Perform abstraction to ~s~% on conceptual definition of ~s.~%"
common-parent
(first (get-abstraction action))
)
(set (frame-type action)
(apply #'f.modify
`(,(frame-type action)
,common-parent
,@path)))
;; The action this learning was about is interesting,
;; because it is newly learned.
(setf
(get (first (get-abstraction action))
'personally-interesting)
t)
common-parent) ; return value if successful.
(t
(format
*aqua-window*
"Abstraction fails: No common parent.")))
; )
(format *aqua-window*
"~%Error in function ABSTRACT.~%")))))
)
;;;
;;; Predicate current-frame-more-general-than returns t if the current frame is
;;; more general than the frame it is compared to, nil otherwise.
;;;
(defun current-frame-more-general-than (frame-compared-to current-frame)
(and (not (eq (frame-type
frame-compared-to)
(frame-type
current-frame)))
(isa-p (frame-type
current-frame)
(list
frame-compared-to)))
)
;;;
;;; Function get-corresponding-frame returns the frame in the new structure
;;; being created by function replace-with-general-filler corresponding to the
;;; corresponding-filler argument. If the corresponding-filler is nil or a
;;; non-list, then it is returned. The real problem solved by this function is
;;; the case when corresponding-filler is a list. That is, the current-frame
;;; may be a list element in a filler of a role of the parent frame. So the
;;; problem is to find the location in the list where the current frame exists,
;;; and then to return the corresponding frame from the list represented by
;;; corresponding filler.
;;;
;;; parent -> (frame (role (facet-name (q current-frame r s))))
;;; corresponding-filler -> (a b c d)
;;; (get-corresponding-frame
;;; current-frame parent role facet-name corresponding-filler)
;;; -> b
;;;
(defun get-corresponding-frame
(current-frame parent role facet-name corresponding-filler)
(cond ((null corresponding-filler)
nil)
((not (listp corresponding-filler))
corresponding-filler)
(t
(let ((list-filler (f.get parent role facet-name)))
(nth (- (length list-filler)
(length (member current-frame
list-filler)))
corresponding-filler))))
)
;;;
;;; Function replace-with-general-filler is the function passed to
;;; f.traverse-frame by function merge-concepts. As each sub-frame (the
;;; current-frame parameter) is encountered during the traversal, it checks to
;;; see if the sub-frame is more general than the corresponding sub-frame in
;;; the new concept (global *new-struct*) being constructed. If this is true,
;;; it replaces the more specific frame with the more general one. This is
;;; performed, not only on the current frame, but all locations where the
;;; current frame is bound. This information is obtained from the specific
;;; frame's back-pointer list by calling f.where-bound.
;;;
(defun replace-with-general-filler (current-frame parent role facet-name level parent-struct)
(cond ((not (equal level 0))
(setf *path-list* (append
(adjust-path *path-list* level)
`((,role ,facet-name)) ))
(setf *prev-level* level)
(let ((corresponding-frame
(get-corresponding-frame
current-frame parent role facet-name
(apply #'f.chase-path
*new-struct*
*path-list*))))
(when (and (not (visited-p
current-frame
*traverse-marker*))
(current-frame-more-general-than
corresponding-frame
current-frame))
(let ((general-frame
(f.copy-instantiated-frame
current-frame
;;; #'tmxp-filter
)))
(dolist (each-back-ptr
(f.where-bound
corresponding-frame))
(f.put!
general-frame
(first each-back-ptr)
(second each-back-ptr)
(third each-back-ptr))
))))
))
)
;;;
Function merge - concepts takes two concepts and returns the most general
unification of the two . It works by unifying copies of the two in order to
;;; produce a copy that is guaranteed to contain all slots and facets of both
;;; concepts. Subsequently, the new concept is traversed twice; once for each
;;; parent concept, and any facet that is more general than a corresponding
;;; filler in the unified concept is put on the new frame in its place.
;;; Finally, all truth slots are removed. The global variables *path-list*,
;;; *prev-level*, and *new-struct* are used by function
;;; replace-with-general-filler to manipulate the new frame as the traversal is
;;; performed.
;;;
(defun merge-concepts (concept1 concept2)
(do-break merge-concepts)
(setf *path-list* nil)
(setf *prev-level* 0)
(setf *new-struct*
(f.unify (f.copy-instantiated-frame
(remove-status concept1)
;;; #'tmxp-filter
)
(f.copy-instantiated-frame
(remove-status concept2)
;;; #'tmxp-filter
)))
(f.traverse-frame concept1 #'replace-with-general-filler nil)
(f.traverse-frame concept2 #'replace-with-general-filler nil)
(let ((generalized-xp
(change-status
(remove-truth *new-struct*)
*learned*)))
(format
*aqua-window*
"~% resulting in general explanation ~s.~%"
generalized-xp)
generalized-xp)
)
;;;
;;; Function index-new-xp indexes a newly generalized explanation pattern in
;;; memory.
;;;
;;; The function do-index will return an index to the memory when it stores the
;;; item, unless a similar item already exists in memory. If this occurs,
do - index will return the similar item . Therefore , the first cond clause
represents a successful store of a new memory ; whereas , the second clause
;;; is the case of finding the item already in memory. This case is covered in
Cox ( 1994 ) , when Meta - AQUA forgets the detection explanation , but is
;;; reminded of it as it tries to store a newly generalized explanation from
;;; the story.
;;;
(defun index-new-xp (generalized-xp)
(let ((new-index
(do-index generalized-xp ;Index the because-xp off dogs barking at containers.
'xp-type.0
(f.get generalized-xp
*explains-node*)
t
)))
(do-break index-new-xp)
(cond ((isa-p 'index (list new-index))
(format
*aqua-window*
(str-concat
"~%~%Indexing new explanation "
"with index ~s.~%")
new-index)
new-index)
(t
(format
*aqua-window*
"~%Indexing aborted because of reminding.~%")
(format
*aqua-window*
(str-concat
"~%Generalizing the similar memories "
"instead of storing separate items.~%"))
;;; (break "index-new-xp")
(let ((merged-xp
(merge-concepts generalized-xp new-index)))
;; Otherwise new-index is the conflicting memory item from the memory-list.
(do-index merged-xp
'xp-type.0
(f.get merged-xp
*explains-node*)
t
t ; Forced indexing true
(list
(f.chase-path
merged-xp
'explains
'domain '(to relation))))
)
)) )
)
;;;
;;; Function list-relations returns a list of relation frames along a path list
starting at the current frame . The first element in the path list provides
;;; a pointer into the current frame, determining the slot from which to
;;; extract the current relation. The filler of this slot then provides the
;;; next frame from which to recursively extract more relations.
;;;
(defun list-relations (current-frame path-list)
"Extract a list of relations along a path list starting with the current frame."
(cond ((null path-list)
nil)
(t
(cons
(f.make-relation
current-frame
(first path-list))
(list-relations
(f.get current-frame
(first path-list))
(rest path-list)))))
)
;;;
;;; Function specialize is currently used to learn from the expectation
;;; failure. It differentiates the indices used to retrieved the incorrectly
;;; expected explanation and the actual explanation for the dog barking events.
;;; The differentiation is accomplished by indexing the generalized-xp using
;;; relations obtained from the anomaly path. Then the function removes the
;;; index for the old-xp. Finally, with the help of a small hack, the old-xp is
;;; reindexed using the anomaly path.
;;;
;;; The old-index parameter is the overly general index that incorrectly
;;; retrieved the defensive-bark explanation (local variable old-xp). The
;;; generalized version of the proper explanation is passed to the function as
parameter generalized - xp . The last three function parameters are from the
;;; IMXP: (=i =anomaly =m-prime)
;;;
;;; ||||||To perform the index differentiation, an algorithm must be developed
that reindexes the two explanations with respect to each other and the
;;; existing indexes (in the case of a novel situation there is no index
though ) . The current algorithm depends on the anomaly , rather than the xps
;;; themselves. The small hack mentioned above must go.
;;;
(defun specialize (learning-node old-index anomaly generalized-xp)
(let* ((anomalous-concept ; e.g., Copy of dog-barks or hit.
(f.copy-instantiated-frame
(f.get anomaly 'action)))
(anomaly-path ; e.g., (TO DOMAIN) or
(second ; (INSTRUMENTAL-SCENE TO DOMAIN)
(symbol-value
(f.get anomaly 'paths))))
(index-type (f.get old-index 'type)) ; e.g., xp-type.0
(index-relation (f.get old-index ; e.g., an actor frame
'relation)))
(do-break specialize)
(setf (get (frame-type anomalous-concept) ; The action this learning was about is
'personally-interesting) ; interesting because it is newly learned.
|||||| But need to make this more principled .
;; Index the xp off dogs barking at
;; containers or people hitting what?
(print-indexing-event
(do-index generalized-xp
index-type
(f.get generalized-xp
*explains-node*) ; Pass some explained relation
t ; Non-destructive as true
nil ; Forced-indexing as false
(list-relations
(f.chase-path generalized-xp
*explains-node*
*domain-slot*)
(butlast anomaly-path))))
(print-specialization-event old-index) ; Simple program feedback.
(do-index nil index-type index-relation) ; Removes the current indexing of old-xp.
;; ||||| Hack to get old threaten-xp indexed off
;; animate objects in the "to" slot.
(f.put-all!
Filler
(f.get anomalous-concept 'to) ; Frame
*domain-slot*) ; Slot
;; The old threatening bark explanation is indexed off
;; dogs barking at animate objects.
(do-index (first ; Old-xp, e.g., xp-defensive-bark.X or xp-injury-hit.Y
(f.get old-index
*co-domain-slot*))
index-type
(f.get anomalous-concept
*actor-slot*
*relation-facet*)
t
t ; Forced indexing [cox 27jun95]
(list-relations anomalous-concept
(butlast anomaly-path)))
)
)
(defun print-indexing-event (memory-index
&optional
(stream *aqua-window*))
"Program feedback during re-indexing."
; (with-character-style (*Style*)
(format
stream
"~%~%Indexing new explanation with index ~s.~%"
memory-index)
; )
)
(defun print-specialization-event (memory-index
&optional
(stream *aqua-window*))
"Program feedback during re-indexing."
; (with-character-style (*Style*)
(format
stream
"~%~%Execute specialize on ~s.~%"
memory-index)
; )
)
;;;
;;; BLAME ASSIGNMENT
;;;
;;;
Function l.strategy - decision uses the outcome of the verify stage ( ||||||
;;; NOTE that it may also use the outcome of the generation-phase) as an index
;;; to retrieve an introspective explanation of the reasoning trace. If the
;;; memory retrieval is successful, then the index is formally represented as a
;;; frame and then stored in a newly created knowledge state frame. This state
;;; frame is then recorded as the decision basis for the learning strategy
;;; decision. Since many strategies may be chosen as part of an overall
;;; learning plan, the function does not choose a meaningful value to return as
the result of the function . Explanation.0 is returned as a generic value . I
;;; suppose that we are using introspective explanation with the IMXP in
;;; further learning steps, so the value is appropriate, but many algorithms
;;; may be selected at a lower level, so it may be misleading too..
;;;
(defun l.strategy-decision (decision-basis reasoning-failure learning-node k-goal)
(let* ((imxp-candidates
(retrieve-xps
reasoning-failure))
(k-state (f.instantiate-frame
knowledge-state)))
(do-break l.strategy-decision)
(cond (imxp-candidates
(f.unify
(make-index reasoning-failure ; Result should be of xp-type.0
imxp-candidates)
(f.get k-state
'believed-item)))
(t
(format *aqua-window*
"~%No introspective XP retrieved.~%")))
(f.put! (list k-state)
(f.get
decision-basis
'knowledge)
'members))
'explanation.0) ; Return value
;;;
;;; STRATEGY EXECUTION
;;;
;;;
;;; ||||| Because l.runstrategy is performed multiple times, only the last
;;; f.put! will have an effect. Should add each one to a list instead.
;;;
(defun l.runstrategy (learning-node strategy-choice parameters &optional add-break?)
(do-break l.runstrategy)
(case strategy-choice
(generalization.0
(if add-break?
(add-break generalize))
(f.put! (list (apply #'generalize
parameters))
(f.get learning-node
'main-result)
'members)
(if add-break?
(un-break generalize))
'generalize.0)
(abstraction.0
(if add-break?
(add-break abstract))
(f.put! (list (apply #'abstract
parameters))
(f.get learning-node
'main-result)
'members)
(if add-break?
(un-break abstract))
'abstract.0)
(specialization.0
(if add-break?
(add-break specialize))
(f.put! (list (apply #'specialize
(cons learning-node parameters)))
(f.get learning-node
'main-result)
'members)
(if add-break?
(un-break specialize))
'specialize.0)
(conditionalization.0
(if add-break?
(add-break index-new-xp))
(f.put! (list (apply #'index-new-xp
parameters))
(f.get learning-node
'main-result)
'members)
(if add-break?
(un-break index-new-xp))
'index-new-xp.0)
||||||The following is redundant . Remove . [ 5dec93 ]
(EBG.0
(if add-break?
(add-break do-EBG))
(f.put! (list (do-EBG parameters))
(f.get learning-node
'main-result)
'members)
(format *aqua-window*
"Performing do-EBG. Is this correct?")
(if add-break?
(un-break do-EBG))
(break)
'Do-EBG.0)
( t (format
*aqua-window*
(str-concat
"ERROR: unknown learning strategy - "
"~s." )
strategy-choice)))
)
;;;
;;; Function execute-strategies runs the learning algorithms chosen by function
;;; select-learning-strategies. The learning-type is the algorithm selection
;;; whereas the credit-blame slot is the arguments to the strategy.
;;;
(defun execute-strategies (strategy-list imxp learning-node)
(do-break execute-strategies)
; (with-character-style (*Style*)
(cond (strategy-list
(format
*aqua-window*
"~%~%~%Executing strategies.~%")
(dolist (each-learning-strategy
strategy-list)
;; ||||| The following code is currently dependent on the order of parameters. ??
(l.runstrategy learning-node
(f.get each-learning-strategy
'learning-type)
(f.get each-learning-strategy
'credit-blame))))
(t
(format
*aqua-window*
"~%~%~%No learning performed.~%")
))
; )
)
;;;
;;; STRATEGY SELECTION
;;;
;;;
;;; Strategy selection: Take as input a trace of how and why a failure occurred
;;; and a list of learning goals along with their dependencies; produce as
;;; output an ordered set of learning strategies to apply in order to
;;; accomplish the goals along with updated dependencies on the set of goals.
;;; These learning strategies are organized as plans to accomplish the goals.
;;; The plans are sequences of steps representing calls to specific learning
;;; algorithms.
;;;
;;; The function returns the ordered list of learning strategies. At the
;;; current time [cox 8jun95], this function does not support partial ordering.
;;; The list returned is considered a fully ordered list.
;;;
;;; NOTE that if the optional argument randomize is true, then the order is
;;; random. This parameter is used in order to empirically demonstrate the
;;; advantage of mediation by learning goals.
;;;
(defun select-learning-strategies (learning-goal-list
imxp
&optional randomize ; T -> shuffle strategies local var
)
(do-break select-learning-strategies)
; (with-character-style (*Style*)
(cond (learning-goal-list
(format
*aqua-window*
"~%~%~%Selecting learning strategies.~%")
(let ((strategies
(f.get
imxp
'learning-algorithm)))
(format
*aqua-window*
(str-concat
"~%The following algorithms "
"are selected:~% ~s")
(if randomize
(setf strategies
(shuffle strategies))
strategies))
strategies))
(t
(format
*aqua-window*
"~%~%~%Cannot choose a strategy.~%")))
; )
)
;;;
;;; Initialized by function init-aqua.
;;;
(defvar *shuffle-state* nil
"Random state variable used by the function shuffle.")
;;;
;;; Function shuffle returns a list with the elements in random order. this
;;; task is accomplished by choosing a random element of the list to be the new
first element , and shuffling the remainder . [ cox 6jun95 ]
;;;
;;;
;;; The random function call uses a separate random state variable so that the
;;; system random state variable is not changed. If it was to be changed, then
;;; the behavior of the system under replication conditions (i.e., when
;;; re-running stories generated in previous experiemtns) would not be the same.
;;;
;;; ||||| Need to save random state so that we can recreate the random bahavior
;;; for replication purposes.
;;;
(defun shuffle (list)
(if (null list)
nil
(let ((random-position (random (length list)
*shuffle-state*)))
(cons
(nth random-position list)
(shuffle
(append
(subseq list
0
random-position)
(subseq list
(+ 1 random-position)
(length list)))))))
)
;;;
;;; DECIDING WHAT TO LEARN
;;;
;;;
;;; Predicate passes-similarity-criteria-p is used to test for similarity of
;;; objects being reconciled or differentiated during learning.
;;;
(defun passes-similarity-criteria-p (goal-object)
(do-break passes-similarity-criteria-p)
(let* ((object1 (f.get goal-object *domain-slot*))
(object1 (f.get goal-object *co-domain-slot*)))
t)
)
;;;
;;; Predicate reasonable-goals-p determines whether or not the learning goals
suggested by the IMXP created in blame assignment are indeed the proper
;;; goals to pursue. The currents tests are on binary goals. Reconciliation
;;; goals demand that the objects to be reconcilable are fairly similar,
;;; whereas a differentiation goal requires that they be somewhat different.
;;; The similarity criteria is in predicate passes-similarity-criteria-p.
;;;
(defun reasonable-goals-p (learning-goals)
(do-break reasonable-goals-p)
(every
#'(lambda (each-goal)
(case (f.get each-goal 'goal-type)
(knowledge-differentiation-goal-0
(not
(passes-similarity-criteria-p
(f.get each-goal
'goal-object)))
;;||||| For now must make certain this goes thru. Change after completing criteria
;;predicate.
t
)
(knowledge-reconciliation-goal-0
(passes-similarity-criteria-p
(f.get each-goal
'goal-object)))
(t
t)))
learning-goals)
)
(defun announce-new-goals (new-goals)
(format
*aqua-window*
(str-concat
"~%Goals are adjusted to better "
"reflect what needs to be learned."
"~%New Goals: ~s~%")
new-goals)
)
;;;
;;; Function change-goals is invoked if the goals contained in the given imxp
;;; are not reasonable. The goals are adjusted and the changes are announced.
;;; The new goals are returned.
;;;
|||||| Still needs to be finished .
;;;
(defun change-goals (learning-goals imxp)
(announce-new-goals learning-goals)
learning-goals
)
;;;
;;; Function announce-preliminary-goal prints a message listing the goals input
;;; into the decide what to learn stage. It also lists the corresponding
;;; priorities associated with each.
;;;
(defun announce-preliminary-goals (learning-goals)
(format
*aqua-window*
(str-concat
"~%Posting the following"
" learning goals:~% ~s~%"
" with priorities ~s")
learning-goals
(mapcar
#'(lambda (each-goal) ;Run down list of learning goals
(f.get each-goal ;and collect a list of priorities.
'priority))
learning-goals))
)
;;;
;;; Deciding what to learn: Take as input a causal explanation of how and why a
;;; failure occurred; generate as output a list of learning goals which, if
;;; achieved, can reduce the likelihood of the failure repeating. The
;;; previously instantiated explanation-pattern assists in this process by
;;; specifying points in the reasoning trace most likely to be responsible for
;;; the failure. Include with the output both tentative goal-dependencies and
;;; priority orderings on the goals.
;;;
(defun decide-what-2-learn (imxp)
(do-break decide-what-2-learn)
; (with-character-style (*Style*)
(cond
(imxp
(format
*aqua-window*
"~%~%Deciding what to learn.~%")
(let ((l-goals (f.get imxp 'potential-learning-goals)))
(announce-preliminary-goals l-goals)
(if (not (reasonable-goals-p l-goals))
(change-goals l-goals imxp)
l-goals)))
(t
(format
*aqua-window*
"~%~%Cannot decide what to learn.~%")
nil))
; )
)
;;;
;;; |||||| Should rewrite this so that it traverses the phases of the trace
;;; until it finds an failure-type (or non sucessful-prediction) or hits the
;;; phase equal to current-phase.
;;;
(defun return-failure (trace)
(do-break return-failure)
(let ((verify-outcome ; verification phase outcome
(first (f.chase-path
trace
'examination
'main-result
'members))))
(if (equal 'successful-prediction
(frame-type
(f.get verify-outcome
*co-domain-slot*)))
(let ((generate-outcome ; generation phase outcome
(first (f.chase-path
trace
'generation
'main-result
'members))))
(if (equal 'retrieval-failure
(frame-type
(f.get generate-outcome
*co-domain-slot*)))
generate-outcome ; Recovered Impasse
verify-outcome))
verify-outcome))
)
;;;
Function learn ( previously called function review ) performs step 2 of the
;;; following learning algorithm:
;;;
;;; 0. Perform and Record Reasoning in TMXP
1 . Failure Detection on Reasoning Trace
2 . If Failure Then
;;; Learn from Mistake:
;;; Blame Assignment
;;; Compute index as characterization of failure
Retrieve Introspective Meta - XP
Apply IMXP to trace of reasoning in TMXP
If Successful XP - Application then
;;; Check XP-ASSERTED-NODES
If one or more nodes not believed then
;;; Introspective questioning
GOTO step 0
Else GOTO step 0
Post Learning Goals
;;; Choose Learning Algorithm(s)
;;; Apply Learning Algorithm(s)
( 3 . If Learning Then
;;; Evaluate Learning)
;;;
;;;
;;; ||||| Need to unify the interdiction-act of the bust-act with the
interdiction - act that the sniff is related to off the precondition XP .
;;;
||||| Change the sniff1 binding . The HACK can be removed by implementing
;;; the review process.
;;;
;;; How to handle the problem of which actor relation to explain. The specific
;;; dog sniffing the luggage or the more general dog being the actor of the
detection MOP .
;;;
;;; ||||| Need to put the results of each learning strategy applied in the
;;; main-result slot of the learning-node.
;;;
;;; Because this function performs a f.unify on the parameter, it must return
the correct value of trace , and the calling function must setf the return
;;; value to the returned value.
;;;
(defun learn (k-goal learning-node &aux (dummy-var (f.instantiate-frame dummy)))
(do-break learn)
(set-learning-episodes *Current-Result-Record*)
;; The k-goal is saved on an arbitrary slot of this dummy frame so that it will remain updated.
;; Otherwise the blame-assignment phase will change the value when it performs a f.unify
;; operation and the remove-achieved-goal call at the end will not work. [cox 27jun95]
(f.put k-goal dummy-var 'goal-var)
; (with-character-style (*Style*)
(format *aqua-window* "~%~%LEARNING PHASE . . .~%")
; )
(let* ((trace (goal-state k-goal))
(reasoning-failure
(return-failure trace))
(imxp nil))
(f.unify (f.get learning-node 'strategy-choice)
Automatically returns explanation.0
(l.strategy-decision ; Looks for an IMXP & sets index if found.
(return-decision-basis
learning-node)
reasoning-failure
learning-node
k-goal))
(f.unify (f.get learning-node 'main-result)
(f.instantiate-frame outcome))
; ((imxp (f.unify (explain reasoning-failure
; learning-node
; k-goal)
; (f.get trace 'introspection))))
;; Unify the Introspective-Meta-XP with the result of the verify phase.
;; This result was the mentally-initiates from <> to expectation-failure.
;; The following action also binds the A & E nodes to the rest of the imxp structure.
|||||| This is now part of the IMXP structures and need not be done . Will check to make sure before deleting
altogether [ 29dec93 ]
; (f.unify
; (f.get imxp 'link4)
( first ( return - result
; (return-d-c-node
; trace
; 'examination))))
( setf trace ( f.unify ( f.get imxp ' rc ) trace ) )
(execute-strategies
(select-learning-strategies
(decide-what-2-learn
(setf imxp (blame-assignment reasoning-failure
learning-node
k-goal
trace)))
imxp)
imxp
learning-node)
(set-model
*Reasoning-Model*
(cons imxp (get-model *Reasoning-Model*)))
(remove-achieved-goal (f.get dummy-var 'goal-var))
trace)
)
;;;
;;; Function blame-assignment explains the reasoning failure with the imxp
;;; retrieved during l.strategy-decision. Just as with explanation of pyhsical
;;; events in the world, the explain function binds the imxp to the
;;; representation of the reasoning failure to produce an instantiated causal
;;; pattern for the mental events leading up to the reasoning failure. The
;;; instantiated imxp is returned as the value of the function.
;;;
(defun blame-assignment (reasoning-failure learning-node k-goal trace)
(let* ((explanation (explain (f.get reasoning-failure *co-domain-slot*)
learning-node
k-goal))
(imxp (if explanation
(f.unify explanation
(f.get trace 'introspection)))))
(do-break blame-assignment)
(format *aqua-window* "~%~s" (eval *goal-Queue*))
(f.unify (f.get k-goal 'mxp)
(f.get imxp 'rc))
(format *aqua-window* "~%~s" (eval *goal-Queue*))
(cond (imxp
(format
*aqua-window*
(str-concat
"~%~%Blame assignment has produced "
"explanation of reasoning failure:~% ~s~%")
imxp)
)
(t
(format
*aqua-window*
"~%~%Blame assignment cannot explain reasoning failure.~%")))
imxp)
)
(defun oldreview (learning-node)
(let* ((xp nil)
(current-case (retrieve-case-from-META-XP nil))
;HACK. See below.
(sniff1 (return-last-element (get-model *World-Model*)))
(old-xps (f.get current-case *explanations-slot*))
(merged-node nil)
(failures nil))
; (with-character-style (*Style*)
(cond (current-case
(cond ((not (multiple-value-setq
(merged-node failures)
(f.unify sniff1
(get-scene
1
current-case))))
(format *aqua-window*
"~%Match fails.~%~s and ~s would not unify"
sniff1 (get-scene 1 current-case))
(format *aqua-window*
"~%because incompatibility in subnodes ~s."
failures)
(cond ((similar-p failures)
(tweak failures)
; (f.put! (cons instantiated-xp
; (f.get instance
; *explanations-slot*))
; instance
; *explanations-slot*)
))
And here is the rest of the HACK .
(format *aqua-window*
"~%~%Found a better explanation for action of ~s"
(f.get sniff1 *actor-slot* *relation-facet*))
(format *aqua-window* "~%because ~s is a ~s.~%"
(second
(f.get (f.get sniff1 *actor-slot* *relation-facet*)
*explanations-slot*))
(get-abstraction
(frame-type
(first
(f.get (f.get sniff1
*actor-slot*
*relation-facet*)
*explanations-slot*))))
)
(f.put! old-xps
(f.get sniff1 *actor-slot* *relation-facet*)
*explanations-slot*)
(format *aqua-window* "~%New explanation is ~s.~%"
(say-xp (first old-xps)))
(format *aqua-window* "~%~%Removing old explanation.~%"))
))
(t
(if (null xp)
(format *aqua-window* "~%No action taken on review." )
(format *aqua-window* "~%New XP: ~s." xp))))
; )
))
;;; Used to be major part of inner cond statement in the review function above.
( ( setf xp ( apply - xp ( frame - type ( first old - xps ) )
Here comes a major HACK .
; (f.get sniff1 *actor-slot* *relation-facet*)))
; (format *aqua-window* "~%Just before the unify.")
; (break)
; ;; Another major hack here: How does this know that the interdiction-acts
; ;; must be unified?
; ;; Also this is the location that f.unify fails because of attempt on
; ;; dog-authority merging.
( f.unify ( f.get current - case ' instrumental - scene )
; (f.get xp 'main-action))
; (manage-hypotheses (f.get xp *explains-node*)) ;manage-hypotheses is now
; gen-questions.
; )
| null | https://raw.githubusercontent.com/mclumd/Meta-AQUA/e4d4f83330fd07d1354aec245a49bde9e246c618/learner.lisp | lisp | Syntax : Common - lisp ; Package : Meta - aqua ; Base : 10 -*-
The Meta-AQUA Introspective Multistrategy Learning System
Version 6
File: learner.lisp
*******************************************************
This program is free software; you can redistribute it and/or modify it
either version 1 , or ( at your option ) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
if not , write to the Free Software Foundation , Inc. , 675
LEARN AND REVIEW PHASE
AND LEARNING STRATEGIES
Support Functions
Predicate not-trivial-frame-p returns t if the input frame is a trivial
frame, nil otherwise. A frame is trivial if it has only a status slot and a
truth slot. Many (most?) entity frames suit this characterization. This
Function remove-truth removes truth-slot value fillers from all decendents
of the given frame. The use of this function above may not be necessary
because of the conditional check of not-trivial-frame-p.
Function change-status alters the status slot of fillers from all
decendents of the given frame. The argument new-status replaces the old
value if there was one. A frame's status changes when it is acquired as a
case, generalized, or otherwise brought into a program from input. The
changes is usually from story-instance to learned.
|||||| Should we change the status if a frame is a predefined instance?
Or an attribute value?
a filler for a status slot other than the status-slot filler
'attribute-value.0 (which signifies that the parent is an attribute filler
Visited frames have already been changed.
||||| Note that funcall may be appropriate to use
because of the problems encountered below.
(defun test (p1 p2)
(format t "~%The number is ~s." (eval p2))
)
|||||
Function old-review used this. What will be done?
Function adjust-path changes the path-list so that as f.traverse-frame
traverses the node network, the path-list contracts to remain pointing
into the net. A call of f.chase-path will then be able to get to the
current node being operated on.
Explanation-Based Generalization (EBG) Learning Strategy
|||||Note that in the current version this will produce extra slots if the
ones in the xp do not have as many slots as the definition of a frame.
NOTE that this is not the current definition used by the program. Look
below for the right one.
(defun generalize-node (current-frame parent role facet-name level parent-struct)
(cond ((not (equal level 0))
(adjust-path *path-list* level)
`((,role ,facet-name)) ))
(when (and (not (visited-p current-frame))
;; The frame-body call makes sure that this is not a terminal.
(frame-body current-frame)
(not-trivial-frame-p current-frame))
(f.unify current-frame
;; |||||Literals are not handled properly below.
(let ((new-frame
(frame-def
(apply #'f.chase-path
*new-struct*
*path-list*))))
(if (or (null new-frame)
; |||||| Eventually we want to unify all items in a list .
(frame-list-p (f.get parent role facet-name)))
*nil*
(if (attribute-value-p (frame-type new-frame))
new-frame
(if (literal-p (frame-type new-frame))
(f.set-literal
(f.instantiate-frame (*FRAME* *literal*))
(symbol-value new-frame))
(f.instantiate-frame new-frame)))
(f.instantiate-frame (list new-frame))))))
(format-if
(and *Debug-On* (f.where-bound current-frame))
t
current-frame
(f.where-bound current-frame)
parent role facet-name)
)))
(when *Debug-On*
(format t "~%*path-list*: ~s." *path-list*)
(format t "~%*prev-level*: ~s.~%" *prev-level*))
)
(do-break generalize-node))
(not (tmxp-filter current-frame))
The frame-body call makes sure that this is not a terminal.
||||||Literals are not handled properly below.
|||||| Eventually we want to unify all items in a list.
Function do-ebg should really be doing this.
Set-up for function generalize-node.
|||||Why is this not done with let?
(f.instantiate-frame (*FRAME* (frame-type xp))))
||||| Really need to just make sure that tokens are unified
after fixing backptr problem, instead of the following hack.
(defun count-nodes (current-frame parent role facet-name level)
(if (not (visited-p current-frame *traverse-marker*))
)
(defun find-it (current-frame parent role facet-name level)
(if (equal 'drug (frame-type current-frame))
(break))
)
(with-character-style (*Style*)
Set-up for function generalize-node.
|||||Why is this not done with let?
||||| Really need to just make sure that tokens are unified
after fixing backptr problem, instead of the following hack.
)
Review - Learn Phase
||||||Must complete.
Function differentiate creates subgoals to achieve a given
knowledge-differentiation-goal. If either of the objects to be
differentiated are new concepts, then we spawn a sub-goal to expand them.
goal so that the concepts will be ready to be indexed.
(defun generalize (xp-token imxp role-literal)
(let ((generalized-xp (perform-ebg-on xp-token)))
(break)
(f.unify generalized-xp
(f.get imxp
(symbol-value
role-literal))))
)
explanation is then unified with m-prime. M-prime is the node in the imxp
that registers the new explanation created during learning.
If various generalization routine were available to choose from, this
function might decide which was most appropriate. At least it would have
the appropriate algorithm passed to it.
Unify the result
Function abstract currently is used to handle the bad constraints on the
value of at-locations on a bark. This is done by abstracting to the common
parents of what was expected (the constraint) to happen and what actually
happened.
Find the parameter which
represents the original anomaly.
||||| Hack: f.chase-path needs to be modified rather than having the
following conditional. See comments on f.chase-path.
(apply #'f.chase-path
(cons
action
path)))
(format
*aqua-window*
(symbol-value (f.get which-sibling 'paths))
constraint)
(format
*aqua-window*
(str-concat
"Actual Filler: ~s "
actual
(get-abstraction
(get-abstraction
common-parent)
(with-character-style (*Style*)
The action this learning was about is interesting,
because it is newly learned.
return value if successful.
)
Predicate current-frame-more-general-than returns t if the current frame is
more general than the frame it is compared to, nil otherwise.
Function get-corresponding-frame returns the frame in the new structure
being created by function replace-with-general-filler corresponding to the
corresponding-filler argument. If the corresponding-filler is nil or a
non-list, then it is returned. The real problem solved by this function is
the case when corresponding-filler is a list. That is, the current-frame
may be a list element in a filler of a role of the parent frame. So the
problem is to find the location in the list where the current frame exists,
and then to return the corresponding frame from the list represented by
corresponding filler.
parent -> (frame (role (facet-name (q current-frame r s))))
corresponding-filler -> (a b c d)
(get-corresponding-frame
current-frame parent role facet-name corresponding-filler)
-> b
Function replace-with-general-filler is the function passed to
f.traverse-frame by function merge-concepts. As each sub-frame (the
current-frame parameter) is encountered during the traversal, it checks to
see if the sub-frame is more general than the corresponding sub-frame in
the new concept (global *new-struct*) being constructed. If this is true,
it replaces the more specific frame with the more general one. This is
performed, not only on the current frame, but all locations where the
current frame is bound. This information is obtained from the specific
frame's back-pointer list by calling f.where-bound.
#'tmxp-filter
produce a copy that is guaranteed to contain all slots and facets of both
concepts. Subsequently, the new concept is traversed twice; once for each
parent concept, and any facet that is more general than a corresponding
filler in the unified concept is put on the new frame in its place.
Finally, all truth slots are removed. The global variables *path-list*,
*prev-level*, and *new-struct* are used by function
replace-with-general-filler to manipulate the new frame as the traversal is
performed.
#'tmxp-filter
#'tmxp-filter
Function index-new-xp indexes a newly generalized explanation pattern in
memory.
The function do-index will return an index to the memory when it stores the
item, unless a similar item already exists in memory. If this occurs,
whereas , the second clause
is the case of finding the item already in memory. This case is covered in
reminded of it as it tries to store a newly generalized explanation from
the story.
Index the because-xp off dogs barking at containers.
(break "index-new-xp")
Otherwise new-index is the conflicting memory item from the memory-list.
Forced indexing true
Function list-relations returns a list of relation frames along a path list
a pointer into the current frame, determining the slot from which to
extract the current relation. The filler of this slot then provides the
next frame from which to recursively extract more relations.
Function specialize is currently used to learn from the expectation
failure. It differentiates the indices used to retrieved the incorrectly
expected explanation and the actual explanation for the dog barking events.
The differentiation is accomplished by indexing the generalized-xp using
relations obtained from the anomaly path. Then the function removes the
index for the old-xp. Finally, with the help of a small hack, the old-xp is
reindexed using the anomaly path.
The old-index parameter is the overly general index that incorrectly
retrieved the defensive-bark explanation (local variable old-xp). The
generalized version of the proper explanation is passed to the function as
IMXP: (=i =anomaly =m-prime)
||||||To perform the index differentiation, an algorithm must be developed
existing indexes (in the case of a novel situation there is no index
themselves. The small hack mentioned above must go.
e.g., Copy of dog-barks or hit.
e.g., (TO DOMAIN) or
(INSTRUMENTAL-SCENE TO DOMAIN)
e.g., xp-type.0
e.g., an actor frame
The action this learning was about is
interesting because it is newly learned.
Index the xp off dogs barking at
containers or people hitting what?
Pass some explained relation
Non-destructive as true
Forced-indexing as false
Simple program feedback.
Removes the current indexing of old-xp.
||||| Hack to get old threaten-xp indexed off
animate objects in the "to" slot.
Frame
Slot
The old threatening bark explanation is indexed off
dogs barking at animate objects.
Old-xp, e.g., xp-defensive-bark.X or xp-injury-hit.Y
Forced indexing [cox 27jun95]
(with-character-style (*Style*)
)
(with-character-style (*Style*)
)
BLAME ASSIGNMENT
NOTE that it may also use the outcome of the generation-phase) as an index
to retrieve an introspective explanation of the reasoning trace. If the
memory retrieval is successful, then the index is formally represented as a
frame and then stored in a newly created knowledge state frame. This state
frame is then recorded as the decision basis for the learning strategy
decision. Since many strategies may be chosen as part of an overall
learning plan, the function does not choose a meaningful value to return as
suppose that we are using introspective explanation with the IMXP in
further learning steps, so the value is appropriate, but many algorithms
may be selected at a lower level, so it may be misleading too..
Result should be of xp-type.0
Return value
STRATEGY EXECUTION
||||| Because l.runstrategy is performed multiple times, only the last
f.put! will have an effect. Should add each one to a list instead.
Function execute-strategies runs the learning algorithms chosen by function
select-learning-strategies. The learning-type is the algorithm selection
whereas the credit-blame slot is the arguments to the strategy.
(with-character-style (*Style*)
||||| The following code is currently dependent on the order of parameters. ??
)
STRATEGY SELECTION
Strategy selection: Take as input a trace of how and why a failure occurred
and a list of learning goals along with their dependencies; produce as
output an ordered set of learning strategies to apply in order to
accomplish the goals along with updated dependencies on the set of goals.
These learning strategies are organized as plans to accomplish the goals.
The plans are sequences of steps representing calls to specific learning
algorithms.
The function returns the ordered list of learning strategies. At the
current time [cox 8jun95], this function does not support partial ordering.
The list returned is considered a fully ordered list.
NOTE that if the optional argument randomize is true, then the order is
random. This parameter is used in order to empirically demonstrate the
advantage of mediation by learning goals.
T -> shuffle strategies local var
(with-character-style (*Style*)
)
Initialized by function init-aqua.
Function shuffle returns a list with the elements in random order. this
task is accomplished by choosing a random element of the list to be the new
The random function call uses a separate random state variable so that the
system random state variable is not changed. If it was to be changed, then
the behavior of the system under replication conditions (i.e., when
re-running stories generated in previous experiemtns) would not be the same.
||||| Need to save random state so that we can recreate the random bahavior
for replication purposes.
DECIDING WHAT TO LEARN
Predicate passes-similarity-criteria-p is used to test for similarity of
objects being reconciled or differentiated during learning.
Predicate reasonable-goals-p determines whether or not the learning goals
goals to pursue. The currents tests are on binary goals. Reconciliation
goals demand that the objects to be reconcilable are fairly similar,
whereas a differentiation goal requires that they be somewhat different.
The similarity criteria is in predicate passes-similarity-criteria-p.
||||| For now must make certain this goes thru. Change after completing criteria
predicate.
Function change-goals is invoked if the goals contained in the given imxp
are not reasonable. The goals are adjusted and the changes are announced.
The new goals are returned.
Function announce-preliminary-goal prints a message listing the goals input
into the decide what to learn stage. It also lists the corresponding
priorities associated with each.
Run down list of learning goals
and collect a list of priorities.
Deciding what to learn: Take as input a causal explanation of how and why a
failure occurred; generate as output a list of learning goals which, if
achieved, can reduce the likelihood of the failure repeating. The
previously instantiated explanation-pattern assists in this process by
specifying points in the reasoning trace most likely to be responsible for
the failure. Include with the output both tentative goal-dependencies and
priority orderings on the goals.
(with-character-style (*Style*)
)
|||||| Should rewrite this so that it traverses the phases of the trace
until it finds an failure-type (or non sucessful-prediction) or hits the
phase equal to current-phase.
verification phase outcome
generation phase outcome
Recovered Impasse
following learning algorithm:
0. Perform and Record Reasoning in TMXP
Learn from Mistake:
Blame Assignment
Compute index as characterization of failure
Check XP-ASSERTED-NODES
Introspective questioning
Choose Learning Algorithm(s)
Apply Learning Algorithm(s)
Evaluate Learning)
||||| Need to unify the interdiction-act of the bust-act with the
the review process.
How to handle the problem of which actor relation to explain. The specific
dog sniffing the luggage or the more general dog being the actor of the
||||| Need to put the results of each learning strategy applied in the
main-result slot of the learning-node.
Because this function performs a f.unify on the parameter, it must return
value to the returned value.
The k-goal is saved on an arbitrary slot of this dummy frame so that it will remain updated.
Otherwise the blame-assignment phase will change the value when it performs a f.unify
operation and the remove-achieved-goal call at the end will not work. [cox 27jun95]
(with-character-style (*Style*)
)
Looks for an IMXP & sets index if found.
((imxp (f.unify (explain reasoning-failure
learning-node
k-goal)
(f.get trace 'introspection))))
Unify the Introspective-Meta-XP with the result of the verify phase.
This result was the mentally-initiates from <> to expectation-failure.
The following action also binds the A & E nodes to the rest of the imxp structure.
(f.unify
(f.get imxp 'link4)
(return-d-c-node
trace
'examination))))
Function blame-assignment explains the reasoning failure with the imxp
retrieved during l.strategy-decision. Just as with explanation of pyhsical
events in the world, the explain function binds the imxp to the
representation of the reasoning failure to produce an instantiated causal
pattern for the mental events leading up to the reasoning failure. The
instantiated imxp is returned as the value of the function.
HACK. See below.
(with-character-style (*Style*)
(f.put! (cons instantiated-xp
(f.get instance
*explanations-slot*))
instance
*explanations-slot*)
)
Used to be major part of inner cond statement in the review function above.
(f.get sniff1 *actor-slot* *relation-facet*)))
(format *aqua-window* "~%Just before the unify.")
(break)
;; Another major hack here: How does this know that the interdiction-acts
;; must be unified?
;; Also this is the location that f.unify fails because of attempt on
;; dog-authority merging.
(f.get xp 'main-action))
(manage-hypotheses (f.get xp *explains-node*)) ;manage-hypotheses is now
gen-questions.
)
|
(in-package :metaaqua)
Copyright ( C ) 1996 ( )
under the terms of the GNU General Public License as published by the Free
You should have received a copy of the GNU General Public License along
Mass Ave , Cambridge , , USA . In emacs type C - h C - w to view license .
predicate is used during EBG .
(defun not-trivial-frame-p (frame)
(if (remove
*status-slot*
(remove
*truth-slot*
(f.role-list frame)))
t)
)
(defun test-p (list)
(if (not (equal 'instance-of (first list)))
(let ((found nil))
(dolist (each-item (rest list))
(if (and (not (not-trivial-frame-p each-item))
(not (attribute-value-p each-item)))
(setf found t)))
found))
)
(defun remove-truth (frame)
(f.traverse-frame
frame
(lambda (current-frame parent role facet-name level)
(if (and (not (visited-p current-frame *traverse-marker*))
(equal role *truth-slot*)
(equal facet-name *value-facet*))
(f.remove-filler! parent *truth-slot*))))
frame
)
(defun change-status (frame new-status)
(f.traverse-frame
frame
(lambda (current-frame parent role facet-name level)
(if (and (non-attribute-val-status-p
current-frame
role
facet-name)
(not (equal current-frame *question*)))
(f.put! new-status parent *status-slot*))))
frame
)
Predicate non - attribute - status - filler - p returns t when the current - frame is
itself , such as in.0 or learned.0 ) . Such values are not subject to change .
(defun non-attribute-val-status-p (current-frame role facet-name)
(do-break non-attribute-val-status-p)
(and (not (visited-p current-frame *traverse-marker*))
(equal role *status-slot*)
(equal facet-name *value-facet*)
(not (equal *attribute-value*
current-frame)))
)
(defun remove-status (frame)
(f.traverse-frame
frame
(lambda (current-frame parent role facet-name level)
(if (and
(non-attribute-val-status-p
current-frame
role
facet-name)
(not (equal current-frame *question*)))
(f.remove-filler! parent *status-slot*))))
frame
)
( dolist ( each - num ' ( 1 2 3 4 ) ) ( test each - num ' ( + 1 p1 ) ) )
(defun retrieve-case-from-META-XP (concept)
(first (get-model *World-Model*))
)
(defun adjust-path (path-list level)
(cond ((equal level *prev-level*)
(butlast path-list))
((> level *prev-level*)
path-list)
((< level *prev-level*)
(dotimes (x (+ 1 (- *prev-level* level)))
(setf path-list (butlast path-list)))
path-list))
)
( setf * path - list * ( append
( setf * prev - level * level )
( if ( listp new - frame )
" ~%Backpointers of ~s is ~s.~%Location is ~s-~s-~s.~% "
(defun generalize-node (current-frame parent role facet-name level parent-struct)
( if ( isa - p ' fridge ( list current - frame ) )
(cond ((not (equal level 0))
(setf *path-list* (append
(adjust-path *path-list* level)
`((,role ,facet-name)) ))
(setf *prev-level* level)
(when (and (not (visited-p current-frame *traverse-marker*))
(frame-body current-frame)
(not-trivial-frame-p current-frame))
(f.unify
(apply #'f.chase-path *new-struct* *path-list*)
||||||Is it because f.set - literal returns the value rather than the literal ? [ cox 24apr94 ]
(let ((new-frame (frame-def current-frame)))
(if (or (null new-frame)
(frame-list-p (f.get parent role facet-name)))
*nil*
(if (listp new-frame)
(if (attribute-value-p (frame-type new-frame))
new-frame
(if (literal-p (frame-type new-frame))
(f.set-literal
(f.instantiate-frame (*FRAME* *literal*))
(symbol-value new-frame))
(f.instantiate-frame new-frame)))
(f.instantiate-frame (list new-frame)))))
:notify-but-no-break)
(if (and *Debug-On* (f.where-bound current-frame))
(format t "~%Backpointers of ~s is ~s.~%Location is ~s-~s-~s.~%"
current-frame
(f.where-bound current-frame)
parent role facet-name))
)))
(when *Debug-On*
(format t "~%*path-list*: ~s." *path-list*)
(format t "~%*prev-level*: ~s.~%" *prev-level*))
)
(defun perform-EBG-on (xp)
(setf *path-list* nil)
(setf *prev-level* 0)
( setf * new - struct *
(setf *new-struct* xp)
(do-break perform-EBG-on)
(f.traverse-frame
(f.instantiate-frame (*FRAME* (frame-type xp)))
#'generalize-node nil)
(f.unify (f.chase-path *new-struct* 'consequent 'object)
(f.chase-path *new-struct*
'main-precondition
*co-domain-slot*
*co-domain-slot*
*co-domain-slot*))
(remove-truth *new-struct*)
)
( setf * x * ( + 1 * x * ) ) )
( setf * x * 0 )
(defvar *path-list* nil)
(defvar *prev-level* 0)
(defvar *new-struct* nil)
(defun perform-EBG-on (xp)
(format
*aqua-window*
"~%~%Performing EBG on explanation ~s."
xp)
(setf *path-list* nil)
(setf *prev-level* 0)
(setf *new-struct*
(f.instantiate-frame (frame-def xp)))
(do-break perform-EBG-on)
(f.traverse-frame xp #'generalize-node nil)
(f.unify (f.chase-path *new-struct* 'conseq 'object)
(f.chase-path *new-struct*
'main-precondition
*co-domain-slot*
*co-domain-slot*
*co-domain-slot*)
:notify-but-no-break)
(let ((generalized-xp
(change-status
(remove-truth *new-struct*)
*learned*)))
(format
*aqua-window*
"~% resulting in general explanation ~s.~%"
generalized-xp)
generalized-xp)
)
||||| NOTE the perform - EBG - on function that really does the EBG in
function specialize . Change soon . 18 May 93 .
(defun do-EBG (concept)
(format
*aqua-window*
"~%Execute EBG on ~s."
concept)
)
(defun new-concept (concept)
t)
|||||| WIll this involve a differentiate plan ?
The subgoal will have a higher priority than the following organization
(defun differentiate (differentiate-goal)
(let* ((g-actor (goal-actor differentiate-goal))
(g-object (goal-object differentiate-goal))
(obj1 (f.get *domain-slot* g-object))
(obj2 (f.get *co-domain-slot* g-object))
(goal-priority (f.get differentiate-goal 'priority))
(higher-priority
(inverse-trans
(+ 2 (trans goal-priority))))
)
(do-break differentiate)
(if (new-concept obj1)
(spawn-sub-goal
g-actor
obj1
knowledge-expansion-goal.0
higher-priority
differentiate-goal))
(if (new-concept obj2)
(spawn-sub-goal
g-actor
obj2
knowledge-expansion-goal.0
higher-priority
differentiate-goal))
(spawn-sub-goal
g-actor
`(reindex-with-respect-to
(,*domain-slot* (,*value-facet* ,obj1))
(,*co-domain-slot* (,*value-facet* ,obj2)))
knowledge-reorganization-goal.0
(inverse-trans
(- (trans higher-priority)
1))
differentiate-goal)
Also need to place these subgoals on the subgoal slot of the differentiation goal .
)
)
Function generalize calls ebg on the xp token . The resultant generalized
(defun generalize (xp-token memory-item)
the token
using EBG .
xp-token)))
(do-break generalize)
Reversed order or arguments below [ cox 30jun95 ]
(f.unify
with the imxp node m ' or
))
)
||||||Note that this is passed = A1 and = Anomaly as sibling1 and sibling2
respectively . Which - sibling will then be assigned from sibling2 and
( sibling1 ) will never be used in the function .
(defun abstract (sibling1 sibling2)
(list sibling1))
sibling1)
((isa-p 'anomaly
(list sibling2))
sibling2)
)))
(do-break abstract)
(if which-sibling
(let* ((action (f.get which-sibling 'action))
(path (first (symbol-value (f.get which-sibling 'paths))))
(constraint (let ((temp
(if (listp path)
(apply #'f.chase-path
(frame-def action)
path))))
(if (var-binding-p temp)
(f.get (frame-def action)
(var->role temp))
temp)))
(actual
(f.get which-sibling 'actual-outcome)
( if ( path )
)
(common-parent (f.lowest-common-ancestor
(frame-type constraint)
(frame-type actual))))
" ~%~%Concept : ~s~%Slots : ~s~%Constraint : ~s~% "
( first ( get - abstraction action ) )
" = ~s~%Common - Parent : ~s~% " )
( first
( first ( get - abstraction actual ) ) ) ) )
(if (listp path)
(cond (common-parent
(format
*aqua-window*
"~%Perform abstraction to ~s~% on conceptual definition of ~s.~%"
common-parent
(first (get-abstraction action))
)
(set (frame-type action)
(apply #'f.modify
`(,(frame-type action)
,common-parent
,@path)))
(setf
(get (first (get-abstraction action))
'personally-interesting)
t)
(t
(format
*aqua-window*
"Abstraction fails: No common parent.")))
(format *aqua-window*
"~%Error in function ABSTRACT.~%")))))
)
(defun current-frame-more-general-than (frame-compared-to current-frame)
(and (not (eq (frame-type
frame-compared-to)
(frame-type
current-frame)))
(isa-p (frame-type
current-frame)
(list
frame-compared-to)))
)
(defun get-corresponding-frame
(current-frame parent role facet-name corresponding-filler)
(cond ((null corresponding-filler)
nil)
((not (listp corresponding-filler))
corresponding-filler)
(t
(let ((list-filler (f.get parent role facet-name)))
(nth (- (length list-filler)
(length (member current-frame
list-filler)))
corresponding-filler))))
)
(defun replace-with-general-filler (current-frame parent role facet-name level parent-struct)
(cond ((not (equal level 0))
(setf *path-list* (append
(adjust-path *path-list* level)
`((,role ,facet-name)) ))
(setf *prev-level* level)
(let ((corresponding-frame
(get-corresponding-frame
current-frame parent role facet-name
(apply #'f.chase-path
*new-struct*
*path-list*))))
(when (and (not (visited-p
current-frame
*traverse-marker*))
(current-frame-more-general-than
corresponding-frame
current-frame))
(let ((general-frame
(f.copy-instantiated-frame
current-frame
)))
(dolist (each-back-ptr
(f.where-bound
corresponding-frame))
(f.put!
general-frame
(first each-back-ptr)
(second each-back-ptr)
(third each-back-ptr))
))))
))
)
Function merge - concepts takes two concepts and returns the most general
unification of the two . It works by unifying copies of the two in order to
(defun merge-concepts (concept1 concept2)
(do-break merge-concepts)
(setf *path-list* nil)
(setf *prev-level* 0)
(setf *new-struct*
(f.unify (f.copy-instantiated-frame
(remove-status concept1)
)
(f.copy-instantiated-frame
(remove-status concept2)
)))
(f.traverse-frame concept1 #'replace-with-general-filler nil)
(f.traverse-frame concept2 #'replace-with-general-filler nil)
(let ((generalized-xp
(change-status
(remove-truth *new-struct*)
*learned*)))
(format
*aqua-window*
"~% resulting in general explanation ~s.~%"
generalized-xp)
generalized-xp)
)
do - index will return the similar item . Therefore , the first cond clause
Cox ( 1994 ) , when Meta - AQUA forgets the detection explanation , but is
(defun index-new-xp (generalized-xp)
(let ((new-index
'xp-type.0
(f.get generalized-xp
*explains-node*)
t
)))
(do-break index-new-xp)
(cond ((isa-p 'index (list new-index))
(format
*aqua-window*
(str-concat
"~%~%Indexing new explanation "
"with index ~s.~%")
new-index)
new-index)
(t
(format
*aqua-window*
"~%Indexing aborted because of reminding.~%")
(format
*aqua-window*
(str-concat
"~%Generalizing the similar memories "
"instead of storing separate items.~%"))
(let ((merged-xp
(merge-concepts generalized-xp new-index)))
(do-index merged-xp
'xp-type.0
(f.get merged-xp
*explains-node*)
t
(list
(f.chase-path
merged-xp
'explains
'domain '(to relation))))
)
)) )
)
starting at the current frame . The first element in the path list provides
(defun list-relations (current-frame path-list)
"Extract a list of relations along a path list starting with the current frame."
(cond ((null path-list)
nil)
(t
(cons
(f.make-relation
current-frame
(first path-list))
(list-relations
(f.get current-frame
(first path-list))
(rest path-list)))))
)
parameter generalized - xp . The last three function parameters are from the
that reindexes the two explanations with respect to each other and the
though ) . The current algorithm depends on the anomaly , rather than the xps
(defun specialize (learning-node old-index anomaly generalized-xp)
(f.copy-instantiated-frame
(f.get anomaly 'action)))
(symbol-value
(f.get anomaly 'paths))))
'relation)))
(do-break specialize)
|||||| But need to make this more principled .
(print-indexing-event
(do-index generalized-xp
index-type
(f.get generalized-xp
(list-relations
(f.chase-path generalized-xp
*explains-node*
*domain-slot*)
(butlast anomaly-path))))
(f.put-all!
Filler
(f.get old-index
*co-domain-slot*))
index-type
(f.get anomalous-concept
*actor-slot*
*relation-facet*)
t
(list-relations anomalous-concept
(butlast anomaly-path)))
)
)
(defun print-indexing-event (memory-index
&optional
(stream *aqua-window*))
"Program feedback during re-indexing."
(format
stream
"~%~%Indexing new explanation with index ~s.~%"
memory-index)
)
(defun print-specialization-event (memory-index
&optional
(stream *aqua-window*))
"Program feedback during re-indexing."
(format
stream
"~%~%Execute specialize on ~s.~%"
memory-index)
)
Function l.strategy - decision uses the outcome of the verify stage ( ||||||
the result of the function . Explanation.0 is returned as a generic value . I
(defun l.strategy-decision (decision-basis reasoning-failure learning-node k-goal)
(let* ((imxp-candidates
(retrieve-xps
reasoning-failure))
(k-state (f.instantiate-frame
knowledge-state)))
(do-break l.strategy-decision)
(cond (imxp-candidates
(f.unify
imxp-candidates)
(f.get k-state
'believed-item)))
(t
(format *aqua-window*
"~%No introspective XP retrieved.~%")))
(f.put! (list k-state)
(f.get
decision-basis
'knowledge)
'members))
(defun l.runstrategy (learning-node strategy-choice parameters &optional add-break?)
(do-break l.runstrategy)
(case strategy-choice
(generalization.0
(if add-break?
(add-break generalize))
(f.put! (list (apply #'generalize
parameters))
(f.get learning-node
'main-result)
'members)
(if add-break?
(un-break generalize))
'generalize.0)
(abstraction.0
(if add-break?
(add-break abstract))
(f.put! (list (apply #'abstract
parameters))
(f.get learning-node
'main-result)
'members)
(if add-break?
(un-break abstract))
'abstract.0)
(specialization.0
(if add-break?
(add-break specialize))
(f.put! (list (apply #'specialize
(cons learning-node parameters)))
(f.get learning-node
'main-result)
'members)
(if add-break?
(un-break specialize))
'specialize.0)
(conditionalization.0
(if add-break?
(add-break index-new-xp))
(f.put! (list (apply #'index-new-xp
parameters))
(f.get learning-node
'main-result)
'members)
(if add-break?
(un-break index-new-xp))
'index-new-xp.0)
||||||The following is redundant . Remove . [ 5dec93 ]
(EBG.0
(if add-break?
(add-break do-EBG))
(f.put! (list (do-EBG parameters))
(f.get learning-node
'main-result)
'members)
(format *aqua-window*
"Performing do-EBG. Is this correct?")
(if add-break?
(un-break do-EBG))
(break)
'Do-EBG.0)
( t (format
*aqua-window*
(str-concat
"ERROR: unknown learning strategy - "
"~s." )
strategy-choice)))
)
(defun execute-strategies (strategy-list imxp learning-node)
(do-break execute-strategies)
(cond (strategy-list
(format
*aqua-window*
"~%~%~%Executing strategies.~%")
(dolist (each-learning-strategy
strategy-list)
(l.runstrategy learning-node
(f.get each-learning-strategy
'learning-type)
(f.get each-learning-strategy
'credit-blame))))
(t
(format
*aqua-window*
"~%~%~%No learning performed.~%")
))
)
(defun select-learning-strategies (learning-goal-list
imxp
)
(do-break select-learning-strategies)
(cond (learning-goal-list
(format
*aqua-window*
"~%~%~%Selecting learning strategies.~%")
(let ((strategies
(f.get
imxp
'learning-algorithm)))
(format
*aqua-window*
(str-concat
"~%The following algorithms "
"are selected:~% ~s")
(if randomize
(setf strategies
(shuffle strategies))
strategies))
strategies))
(t
(format
*aqua-window*
"~%~%~%Cannot choose a strategy.~%")))
)
(defvar *shuffle-state* nil
"Random state variable used by the function shuffle.")
first element , and shuffling the remainder . [ cox 6jun95 ]
(defun shuffle (list)
(if (null list)
nil
(let ((random-position (random (length list)
*shuffle-state*)))
(cons
(nth random-position list)
(shuffle
(append
(subseq list
0
random-position)
(subseq list
(+ 1 random-position)
(length list)))))))
)
(defun passes-similarity-criteria-p (goal-object)
(do-break passes-similarity-criteria-p)
(let* ((object1 (f.get goal-object *domain-slot*))
(object1 (f.get goal-object *co-domain-slot*)))
t)
)
suggested by the IMXP created in blame assignment are indeed the proper
(defun reasonable-goals-p (learning-goals)
(do-break reasonable-goals-p)
(every
#'(lambda (each-goal)
(case (f.get each-goal 'goal-type)
(knowledge-differentiation-goal-0
(not
(passes-similarity-criteria-p
(f.get each-goal
'goal-object)))
t
)
(knowledge-reconciliation-goal-0
(passes-similarity-criteria-p
(f.get each-goal
'goal-object)))
(t
t)))
learning-goals)
)
(defun announce-new-goals (new-goals)
(format
*aqua-window*
(str-concat
"~%Goals are adjusted to better "
"reflect what needs to be learned."
"~%New Goals: ~s~%")
new-goals)
)
|||||| Still needs to be finished .
(defun change-goals (learning-goals imxp)
(announce-new-goals learning-goals)
learning-goals
)
(defun announce-preliminary-goals (learning-goals)
(format
*aqua-window*
(str-concat
"~%Posting the following"
" learning goals:~% ~s~%"
" with priorities ~s")
learning-goals
(mapcar
'priority))
learning-goals))
)
(defun decide-what-2-learn (imxp)
(do-break decide-what-2-learn)
(cond
(imxp
(format
*aqua-window*
"~%~%Deciding what to learn.~%")
(let ((l-goals (f.get imxp 'potential-learning-goals)))
(announce-preliminary-goals l-goals)
(if (not (reasonable-goals-p l-goals))
(change-goals l-goals imxp)
l-goals)))
(t
(format
*aqua-window*
"~%~%Cannot decide what to learn.~%")
nil))
)
(defun return-failure (trace)
(do-break return-failure)
(first (f.chase-path
trace
'examination
'main-result
'members))))
(if (equal 'successful-prediction
(frame-type
(f.get verify-outcome
*co-domain-slot*)))
(first (f.chase-path
trace
'generation
'main-result
'members))))
(if (equal 'retrieval-failure
(frame-type
(f.get generate-outcome
*co-domain-slot*)))
verify-outcome))
verify-outcome))
)
Function learn ( previously called function review ) performs step 2 of the
1 . Failure Detection on Reasoning Trace
2 . If Failure Then
Retrieve Introspective Meta - XP
Apply IMXP to trace of reasoning in TMXP
If Successful XP - Application then
If one or more nodes not believed then
GOTO step 0
Else GOTO step 0
Post Learning Goals
( 3 . If Learning Then
interdiction - act that the sniff is related to off the precondition XP .
||||| Change the sniff1 binding . The HACK can be removed by implementing
detection MOP .
the correct value of trace , and the calling function must setf the return
(defun learn (k-goal learning-node &aux (dummy-var (f.instantiate-frame dummy)))
(do-break learn)
(set-learning-episodes *Current-Result-Record*)
(f.put k-goal dummy-var 'goal-var)
(format *aqua-window* "~%~%LEARNING PHASE . . .~%")
(let* ((trace (goal-state k-goal))
(reasoning-failure
(return-failure trace))
(imxp nil))
(f.unify (f.get learning-node 'strategy-choice)
Automatically returns explanation.0
(return-decision-basis
learning-node)
reasoning-failure
learning-node
k-goal))
(f.unify (f.get learning-node 'main-result)
(f.instantiate-frame outcome))
|||||| This is now part of the IMXP structures and need not be done . Will check to make sure before deleting
altogether [ 29dec93 ]
( first ( return - result
( setf trace ( f.unify ( f.get imxp ' rc ) trace ) )
(execute-strategies
(select-learning-strategies
(decide-what-2-learn
(setf imxp (blame-assignment reasoning-failure
learning-node
k-goal
trace)))
imxp)
imxp
learning-node)
(set-model
*Reasoning-Model*
(cons imxp (get-model *Reasoning-Model*)))
(remove-achieved-goal (f.get dummy-var 'goal-var))
trace)
)
(defun blame-assignment (reasoning-failure learning-node k-goal trace)
(let* ((explanation (explain (f.get reasoning-failure *co-domain-slot*)
learning-node
k-goal))
(imxp (if explanation
(f.unify explanation
(f.get trace 'introspection)))))
(do-break blame-assignment)
(format *aqua-window* "~%~s" (eval *goal-Queue*))
(f.unify (f.get k-goal 'mxp)
(f.get imxp 'rc))
(format *aqua-window* "~%~s" (eval *goal-Queue*))
(cond (imxp
(format
*aqua-window*
(str-concat
"~%~%Blame assignment has produced "
"explanation of reasoning failure:~% ~s~%")
imxp)
)
(t
(format
*aqua-window*
"~%~%Blame assignment cannot explain reasoning failure.~%")))
imxp)
)
(defun oldreview (learning-node)
(let* ((xp nil)
(current-case (retrieve-case-from-META-XP nil))
(sniff1 (return-last-element (get-model *World-Model*)))
(old-xps (f.get current-case *explanations-slot*))
(merged-node nil)
(failures nil))
(cond (current-case
(cond ((not (multiple-value-setq
(merged-node failures)
(f.unify sniff1
(get-scene
1
current-case))))
(format *aqua-window*
"~%Match fails.~%~s and ~s would not unify"
sniff1 (get-scene 1 current-case))
(format *aqua-window*
"~%because incompatibility in subnodes ~s."
failures)
(cond ((similar-p failures)
(tweak failures)
))
And here is the rest of the HACK .
(format *aqua-window*
"~%~%Found a better explanation for action of ~s"
(f.get sniff1 *actor-slot* *relation-facet*))
(format *aqua-window* "~%because ~s is a ~s.~%"
(second
(f.get (f.get sniff1 *actor-slot* *relation-facet*)
*explanations-slot*))
(get-abstraction
(frame-type
(first
(f.get (f.get sniff1
*actor-slot*
*relation-facet*)
*explanations-slot*))))
)
(f.put! old-xps
(f.get sniff1 *actor-slot* *relation-facet*)
*explanations-slot*)
(format *aqua-window* "~%New explanation is ~s.~%"
(say-xp (first old-xps)))
(format *aqua-window* "~%~%Removing old explanation.~%"))
))
(t
(if (null xp)
(format *aqua-window* "~%No action taken on review." )
(format *aqua-window* "~%New XP: ~s." xp))))
))
( ( setf xp ( apply - xp ( frame - type ( first old - xps ) )
Here comes a major HACK .
( f.unify ( f.get current - case ' instrumental - scene )
|
cf2d0fbaaafe9a97c596d09ca6feeacabb3a45a6cecb01f3f301a8662ca923b7 | tschady/advent-of-code | d10_test.clj | (ns aoc.2016.d10-test
(:require [aoc.2016.d10 :as sut]
[clojure.test :refer :all]))
(deftest challenge
(is (= "bot 56" (sut/part-1 sut/input)))
(is (= 7847 (sut/part-2 sut/input))))
| null | https://raw.githubusercontent.com/tschady/advent-of-code/1e4a95ef580c3bf635837eff52aa998b0acfc666/test/aoc/2016/d10_test.clj | clojure | (ns aoc.2016.d10-test
(:require [aoc.2016.d10 :as sut]
[clojure.test :refer :all]))
(deftest challenge
(is (= "bot 56" (sut/part-1 sut/input)))
(is (= 7847 (sut/part-2 sut/input))))
| |
d921460bed1f5d67bed8f90da3b3ace3fced0dd4749f1fd68e0cb998412dab17 | sampou-org/pfad | Code28_Tupling.hs | # OPTIONS_GHC -cpp #
module Code28_Tupling where
(□) :: [a] -> [a] -> [a]
xs □ ys = mix xs (ys, reverse ys)
mix :: [a] -> ([a],[a]) -> [a]
mix [] (ys,_) = ys
mix (x:xs) (ys,sy) = ys ++ [x] ++ mix xs (sy,ys)
boxall :: [[a]] -> [a]
boxall = foldr (□) []
op :: [a] -> ([a], [a]) -> ([a], [a])
op xs (ys,sy) = (xs □ ys, xs ⊠ sy)
(⊠) :: [a] -> [a] -> [a]
#ifdef SPEC_OF_BOXTIMES
xs ⊠ sy = reverse (xs □ (reverse sy))
#else
[] ⊠ sy = sy
(x:xs) ⊠ sy = (xs ⊠ (reverse sy)) ++ [x] ++ sy
#endif
op1 :: [a] -> ([a], [a]) -> ([a], [a])
op1 [] (ys,sy) = (ys,sy)
op1 (x:xs) (ys,sy) = (ys ++ [x] ++ zs,sz ++ [x] ++ sy)
where (zs,sz) = op1 xs (sy,ys)
op2 :: [a] -> ([a], [a]) -> ([a], [a])
op2 xs (ys,sy) = if even (length xs)
then (mix xs (ys,sy), mix (reverse xs) (sy,ys))
else (mix xs (ys,sy), mix (reverse xs) (ys,sy))
| null | https://raw.githubusercontent.com/sampou-org/pfad/3c2e0847bea9eac80672e1fbccb86ca5a6b09415/Code/Code28_Tupling.hs | haskell | # OPTIONS_GHC -cpp #
module Code28_Tupling where
(□) :: [a] -> [a] -> [a]
xs □ ys = mix xs (ys, reverse ys)
mix :: [a] -> ([a],[a]) -> [a]
mix [] (ys,_) = ys
mix (x:xs) (ys,sy) = ys ++ [x] ++ mix xs (sy,ys)
boxall :: [[a]] -> [a]
boxall = foldr (□) []
op :: [a] -> ([a], [a]) -> ([a], [a])
op xs (ys,sy) = (xs □ ys, xs ⊠ sy)
(⊠) :: [a] -> [a] -> [a]
#ifdef SPEC_OF_BOXTIMES
xs ⊠ sy = reverse (xs □ (reverse sy))
#else
[] ⊠ sy = sy
(x:xs) ⊠ sy = (xs ⊠ (reverse sy)) ++ [x] ++ sy
#endif
op1 :: [a] -> ([a], [a]) -> ([a], [a])
op1 [] (ys,sy) = (ys,sy)
op1 (x:xs) (ys,sy) = (ys ++ [x] ++ zs,sz ++ [x] ++ sy)
where (zs,sz) = op1 xs (sy,ys)
op2 :: [a] -> ([a], [a]) -> ([a], [a])
op2 xs (ys,sy) = if even (length xs)
then (mix xs (ys,sy), mix (reverse xs) (sy,ys))
else (mix xs (ys,sy), mix (reverse xs) (ys,sy))
| |
48771e952fa8ff660db1581bf329945fa50afd33f863a795bdc05dc968858d4c | gfngfn/otfed | decodeTtfMaxp.ml |
open Basic
open DecodeBasic
let d_maxp =
let open DecodeOperation in
d_uint32 >>= fun version ->
if version = !%% 0x00005000L then
err @@ Error.TtfContainsCffMaxpTable
else if version = !%% 0x00010000L then
d_uint16 >>= fun num_glyphs ->
d_uint16 >>= fun max_points ->
d_uint16 >>= fun max_contours ->
d_uint16 >>= fun max_composite_points ->
d_uint16 >>= fun max_composite_contours ->
d_uint16 >>= fun max_zones ->
d_uint16 >>= fun max_twilight_points ->
d_uint16 >>= fun max_storage ->
d_uint16 >>= fun max_function_defs ->
d_uint16 >>= fun max_instruction_defs ->
d_uint16 >>= fun max_stack_elements ->
d_uint16 >>= fun max_size_of_instructions ->
d_uint16 >>= fun max_component_elements ->
d_uint16 >>= fun max_component_depth ->
return Intermediate.Ttf.Maxp.{
num_glyphs;
max_points;
max_contours;
max_composite_points;
max_composite_contours;
max_zones;
max_twilight_points;
max_storage;
max_function_defs;
max_instruction_defs;
max_stack_elements;
max_size_of_instructions;
max_component_elements;
max_component_depth;
}
else
err @@ Error.UnknownTableVersion(version)
let get (ttf : ttf_source) : Intermediate.Ttf.Maxp.t ok =
let open ResultMonad in
let common = ttf.ttf_common in
DecodeOperation.seek_required_table common.table_directory Value.Tag.table_maxp >>= fun (offset, _length) ->
DecodeOperation.run common.core offset d_maxp
| null | https://raw.githubusercontent.com/gfngfn/otfed/cdda496214b971393fa49cac9916f99858c75b41/src/decodeTtfMaxp.ml | ocaml |
open Basic
open DecodeBasic
let d_maxp =
let open DecodeOperation in
d_uint32 >>= fun version ->
if version = !%% 0x00005000L then
err @@ Error.TtfContainsCffMaxpTable
else if version = !%% 0x00010000L then
d_uint16 >>= fun num_glyphs ->
d_uint16 >>= fun max_points ->
d_uint16 >>= fun max_contours ->
d_uint16 >>= fun max_composite_points ->
d_uint16 >>= fun max_composite_contours ->
d_uint16 >>= fun max_zones ->
d_uint16 >>= fun max_twilight_points ->
d_uint16 >>= fun max_storage ->
d_uint16 >>= fun max_function_defs ->
d_uint16 >>= fun max_instruction_defs ->
d_uint16 >>= fun max_stack_elements ->
d_uint16 >>= fun max_size_of_instructions ->
d_uint16 >>= fun max_component_elements ->
d_uint16 >>= fun max_component_depth ->
return Intermediate.Ttf.Maxp.{
num_glyphs;
max_points;
max_contours;
max_composite_points;
max_composite_contours;
max_zones;
max_twilight_points;
max_storage;
max_function_defs;
max_instruction_defs;
max_stack_elements;
max_size_of_instructions;
max_component_elements;
max_component_depth;
}
else
err @@ Error.UnknownTableVersion(version)
let get (ttf : ttf_source) : Intermediate.Ttf.Maxp.t ok =
let open ResultMonad in
let common = ttf.ttf_common in
DecodeOperation.seek_required_table common.table_directory Value.Tag.table_maxp >>= fun (offset, _length) ->
DecodeOperation.run common.core offset d_maxp
| |
20c59d12d49fccce28d55f8ff16873c478b37b6c3bbdf881fdbbaded9dacb76a | reifyhealth/src-munch | parse.cljs | (ns reifyhealth.src-munch.gallery.colors.parse
"Parses color data from our scss artifacts to provide it for display
in the gallery."
(:require [clojure.string :as str]
[goog.object :as go]
[reifyhealth.src-munch.util :refer [slurp spit delete-if-exists format]]))
(require '[cljs.pprint :refer [pprint]])
(def symbols-parser (js/require "scss-symbols-parser"))
(def cp (js/require "child_process"))
(def spawnSync (go/get cp "spawnSync"))
(def css (js/require "css"))
;; ---------
;; Node based helpers
;; ---------
(defn- parse-scss
"Use the scss parser to parse a file, return a clojure hash-map instead of json"
[f]
(as-> f $
(slurp $)
(.parseSymbols symbols-parser $)
(js->clj $ :keywordize-keys true)))
;; ---------
;; Pipeline functions (using accumulator to capture state)
;; ---------
(defn- parse-variables-scss
"Use the scss parser to parse _variables.scss"
[{:keys [variables-filepath] :as acc}]
(assoc acc :color-imports (:imports (parse-scss variables-filepath))))
(defn- parse-colors-scss
"Use the imported colors to parse the actual color scss files"
[{:keys [scss-main-dir color-imports] :as acc}]
(->> color-imports
(map :filepath)
(map #(let [{:keys [variables]} (parse-scss (str scss-main-dir "/" %))]
{:filename %
:colors variables}))
(assoc acc :parsed-colors)))
(defn- generate-color-scss
"Uses parsed colors to create a scss file
This is needed in order to calculate the scss values in isolation"
[{:keys [gallery-color-scss-filepath parsed-colors] :as acc}]
(->> parsed-colors
(map-indexed (fn [idx {:keys [colors]}]
(map (fn [{:keys [name]}]
(format ".%d .%s { color: %s;}" idx (subs name 1) name))
colors)))
flatten
(clojure.string/join \newline)
(str "@import \"main/variables\";" \newline)
(spit gallery-color-scss-filepath))
acc)
(defn- compile-color-scss
"Runs the scss-compiler to produce a css file with the color values we need."
[{:keys [verbose scss-compiler scss-compiler-source scss-compiler-css-output-dir] :as acc}]
;; Use the scss-compiler directly
(let [args (clj->js [scss-compiler-source
"--recursive"
"--follow"
"--source-map" "true"
"--source-map-contents"
"--output"
scss-compiler-css-output-dir])
process (as-> args $
(spawnSync scss-compiler $)
(js->clj $ :keywordize-keys true))]
(when verbose (pprint process))
(if (-> process :status zero?)
acc
(assoc acc :errors [{:msg (str "Unable to compile " scss-compiler-source)
:info process}]))))
(defn- get-selectors
[stylesheet-rule]
(-> stylesheet-rule
(go/get "selectors")
first))
(defn- parse-color-css
"Parse the css to produce the color edn data"
[{:keys [css-filename parsed-colors] :as acc}]
(let [filename-map (->> parsed-colors
(map-indexed (fn [idx {:keys [filename]}] {(str idx) filename}))
(apply merge))
input (slurp css-filename)
ast (.parse css input nil)
output (->> (-> ast (go/get "stylesheet") (go/get "rules"))
(filter #(some? (get-selectors %)))
(map #(let [selectors (get-selectors %)
[file-index-class name-class] (clojure.string/split selectors " ")
file-index (when file-index-class (subs file-index-class 1))
name (when name-class (str "$" (subs name-class 1)))]
(-> %
(go/get "declarations")
(first)
(js->clj :keywordize-keys true)
(select-keys [:value])
(assoc :name name :file (filename-map file-index))))))
color-edn (->> output
(partition-by :file)
(mapv (fn [colors]
{:color-group-name (-> colors first :file)
:colors (mapv #(select-keys % [:name :value]) colors)})))]
(assoc acc :color-edn color-edn)))
(defn- spit-color-edn
"Creates resources/public/gallery-color-data.edn, to be used directly by the gallery
to generate the color swatches."
[{:keys [color-edn-filepath color-edn] :as acc}]
(spit color-edn-filepath (with-out-str (pprint color-edn)))
acc)
(defn- cleanup
"Remove intermediate files created by this script"
[{:keys [gallery-color-scss-filepath css-filename] :as acc}]
(doseq [path [gallery-color-scss-filepath
css-filename
(str css-filename ".map")]]
(delete-if-exists path))
acc)
(defn- has-errors?
"At the acc level, determine if the pipeline currently has any errors"
[{:keys [errors]}]
(seq errors))
(defn- report-errors
"Display pipeline errors to the user"
[{:keys [errors] :as acc}]
(println "The state of the accumulator when error occurred:")
(pprint acc)
(println "ERRORS OCCURED:")
(doseq [e errors] (println (:msg e))))
(defn- process-parser-pipeline
"Handles the steps to produce the color edn used by the gallery"
[init pipeline-fns]
(->> pipeline-fns
(reduce (fn [acc pipeline-fn]
(let [results (pipeline-fn acc)]
(if (has-errors? results)
(do (report-errors results)
(reduced results))
results)))
init)
cleanup))
(defn parse
"Parse scss resources to produce color edn data"
[init]
(let [{:keys [color-edn color-edn-filepath]} (process-parser-pipeline (select-keys init [:variables-filepath
:scss-main-dir
:gallery-color-scss-filepath
:compile-scss-filepath
:css-filename
:color-edn-filepath
:verbose
:scss-compiler
:scss-compiler-source
:scss-compiler-css-output-dir])
[parse-variables-scss
parse-colors-scss
generate-color-scss
compile-color-scss
parse-color-css
spit-color-edn])]
(when color-edn
(println (str "The following was written to " color-edn-filepath))
(pprint color-edn))))
| null | https://raw.githubusercontent.com/reifyhealth/src-munch/aae08f87aded89750ea8c53cc92754d16dd906ac/src/reifyhealth/src_munch/gallery/colors/parse.cljs | clojure | ---------
Node based helpers
---------
---------
Pipeline functions (using accumulator to capture state)
---------
Use the scss-compiler directly | (ns reifyhealth.src-munch.gallery.colors.parse
"Parses color data from our scss artifacts to provide it for display
in the gallery."
(:require [clojure.string :as str]
[goog.object :as go]
[reifyhealth.src-munch.util :refer [slurp spit delete-if-exists format]]))
(require '[cljs.pprint :refer [pprint]])
(def symbols-parser (js/require "scss-symbols-parser"))
(def cp (js/require "child_process"))
(def spawnSync (go/get cp "spawnSync"))
(def css (js/require "css"))
(defn- parse-scss
"Use the scss parser to parse a file, return a clojure hash-map instead of json"
[f]
(as-> f $
(slurp $)
(.parseSymbols symbols-parser $)
(js->clj $ :keywordize-keys true)))
(defn- parse-variables-scss
"Use the scss parser to parse _variables.scss"
[{:keys [variables-filepath] :as acc}]
(assoc acc :color-imports (:imports (parse-scss variables-filepath))))
(defn- parse-colors-scss
"Use the imported colors to parse the actual color scss files"
[{:keys [scss-main-dir color-imports] :as acc}]
(->> color-imports
(map :filepath)
(map #(let [{:keys [variables]} (parse-scss (str scss-main-dir "/" %))]
{:filename %
:colors variables}))
(assoc acc :parsed-colors)))
(defn- generate-color-scss
"Uses parsed colors to create a scss file
This is needed in order to calculate the scss values in isolation"
[{:keys [gallery-color-scss-filepath parsed-colors] :as acc}]
(->> parsed-colors
(map-indexed (fn [idx {:keys [colors]}]
(map (fn [{:keys [name]}]
(format ".%d .%s { color: %s;}" idx (subs name 1) name))
colors)))
flatten
(clojure.string/join \newline)
(str "@import \"main/variables\";" \newline)
(spit gallery-color-scss-filepath))
acc)
(defn- compile-color-scss
"Runs the scss-compiler to produce a css file with the color values we need."
[{:keys [verbose scss-compiler scss-compiler-source scss-compiler-css-output-dir] :as acc}]
(let [args (clj->js [scss-compiler-source
"--recursive"
"--follow"
"--source-map" "true"
"--source-map-contents"
"--output"
scss-compiler-css-output-dir])
process (as-> args $
(spawnSync scss-compiler $)
(js->clj $ :keywordize-keys true))]
(when verbose (pprint process))
(if (-> process :status zero?)
acc
(assoc acc :errors [{:msg (str "Unable to compile " scss-compiler-source)
:info process}]))))
(defn- get-selectors
[stylesheet-rule]
(-> stylesheet-rule
(go/get "selectors")
first))
(defn- parse-color-css
"Parse the css to produce the color edn data"
[{:keys [css-filename parsed-colors] :as acc}]
(let [filename-map (->> parsed-colors
(map-indexed (fn [idx {:keys [filename]}] {(str idx) filename}))
(apply merge))
input (slurp css-filename)
ast (.parse css input nil)
output (->> (-> ast (go/get "stylesheet") (go/get "rules"))
(filter #(some? (get-selectors %)))
(map #(let [selectors (get-selectors %)
[file-index-class name-class] (clojure.string/split selectors " ")
file-index (when file-index-class (subs file-index-class 1))
name (when name-class (str "$" (subs name-class 1)))]
(-> %
(go/get "declarations")
(first)
(js->clj :keywordize-keys true)
(select-keys [:value])
(assoc :name name :file (filename-map file-index))))))
color-edn (->> output
(partition-by :file)
(mapv (fn [colors]
{:color-group-name (-> colors first :file)
:colors (mapv #(select-keys % [:name :value]) colors)})))]
(assoc acc :color-edn color-edn)))
(defn- spit-color-edn
"Creates resources/public/gallery-color-data.edn, to be used directly by the gallery
to generate the color swatches."
[{:keys [color-edn-filepath color-edn] :as acc}]
(spit color-edn-filepath (with-out-str (pprint color-edn)))
acc)
(defn- cleanup
"Remove intermediate files created by this script"
[{:keys [gallery-color-scss-filepath css-filename] :as acc}]
(doseq [path [gallery-color-scss-filepath
css-filename
(str css-filename ".map")]]
(delete-if-exists path))
acc)
(defn- has-errors?
"At the acc level, determine if the pipeline currently has any errors"
[{:keys [errors]}]
(seq errors))
(defn- report-errors
"Display pipeline errors to the user"
[{:keys [errors] :as acc}]
(println "The state of the accumulator when error occurred:")
(pprint acc)
(println "ERRORS OCCURED:")
(doseq [e errors] (println (:msg e))))
(defn- process-parser-pipeline
"Handles the steps to produce the color edn used by the gallery"
[init pipeline-fns]
(->> pipeline-fns
(reduce (fn [acc pipeline-fn]
(let [results (pipeline-fn acc)]
(if (has-errors? results)
(do (report-errors results)
(reduced results))
results)))
init)
cleanup))
(defn parse
"Parse scss resources to produce color edn data"
[init]
(let [{:keys [color-edn color-edn-filepath]} (process-parser-pipeline (select-keys init [:variables-filepath
:scss-main-dir
:gallery-color-scss-filepath
:compile-scss-filepath
:css-filename
:color-edn-filepath
:verbose
:scss-compiler
:scss-compiler-source
:scss-compiler-css-output-dir])
[parse-variables-scss
parse-colors-scss
generate-color-scss
compile-color-scss
parse-color-css
spit-color-edn])]
(when color-edn
(println (str "The following was written to " color-edn-filepath))
(pprint color-edn))))
|
af5f148ceeda4f2260268e0c4d340a812b1850d62341bb952c38e054e17ce88c | odo/revolver | revolver.erl | -module (revolver).
-behaviour (gen_server).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([balance/2, balance/3, map/2, start_link/3, pid/1, release/2, connect/1, transaction/2, transaction/3]).
-define(DEFAULTMINALIVERATIO, 1.0).
-define(DEFAULRECONNECTDELAY, 1000). % ms
-define(DEFAULTCONNECTATSTART, true).
-define(DEFAULTMAXMESSAGEQUEUELENGTH, undefined).
-define(DEFAULTRELOADEVERY, 1).
-type sup_ref() :: {atom(), atom()}.
-record(state, {
backend :: atom(),
backend_state :: any,
connected :: boolean(),
supervisor :: sup_ref(),
pids_count_original :: integer(),
min_alive_ratio :: float(),
reload_every :: integer(),
down_count :: integer(),
reconnect_delay :: integer()
}).
start_link(Supervisor, ServerName, Options) when is_map(Options) ->
gen_server:start_link({local, ServerName}, ?MODULE, {Supervisor, Options}, []).
balance(Supervisor, BalancerName) ->
revolver_sup:start_link(Supervisor, BalancerName, #{}).
balance(Supervisor, BalancerName, Options) ->
revolver_sup:start_link(Supervisor, BalancerName, Options).
pid(PoolName) ->
gen_server:call(PoolName, pid).
release(PoolName, Pid) ->
gen_server:cast(PoolName, {release, Pid}).
transaction(PoolName, Fun) ->
transaction(PoolName, Fun, false).
transaction(PoolName, Fun, KillOnError) ->
case ?MODULE:pid(PoolName) of
Pid when is_pid(Pid) ->
try
Reply = Fun(Pid),
ok = ?MODULE:release(PoolName, Pid),
Reply
catch
Class:Reason ->
case KillOnError of
false ->
ok = ?MODULE:release(PoolName, Pid);
true ->
dead = kill(Pid)
end,
erlang:raise(Class, Reason, erlang:get_stacktrace())
end;
{error, Error} ->
{error, Error}
end.
map(ServerName, Fun) ->
gen_server:call(ServerName, {map, Fun}).
connect(PoolName) ->
gen_server:call(PoolName, connect).
init({Supervisor, Options}) ->
MinAliveRatio = maps:get(min_alive_ratio, Options, ?DEFAULTMINALIVERATIO),
ReloadEvery = maps:get(reload_every, Options, ?DEFAULTRELOADEVERY),
ReconnectDelay = maps:get(reconnect_delay, Options, ?DEFAULRECONNECTDELAY),
ConnectAtStart = maps:get(connect_at_start, Options, ?DEFAULTCONNECTATSTART),
MaxMessageQueueLength = maps:get(max_message_queue_length, Options, ?DEFAULTMAXMESSAGEQUEUELENGTH),
Backend = case MaxMessageQueueLength of
lease -> revolver_lease;
_ -> revolver_roundrobin
end,
BackendState = apply(Backend, init_state, [MaxMessageQueueLength]),
State = #state{
backend = Backend,
backend_state = BackendState,
connected = false,
supervisor = Supervisor,
pids_count_original = undefined,
min_alive_ratio = MinAliveRatio,
reload_every = ReloadEvery,
down_count = 0,
reconnect_delay = ReconnectDelay
},
maybe_connect(ConnectAtStart),
{ok, State}.
maybe_connect(true) ->
self() ! connect;
maybe_connect(_) ->
noop.
% revolver is disconnected
handle_call(pid, _From, State = #state{connected = false}) ->
{reply, {error, disconnected}, State};
handle_call(pid, _From, State = #state{ backend = Backend, backend_state = BackendState}) ->
{Pid, NextBackendState} = apply(Backend, next_pid, [BackendState]),
NextState = State#state{backend_state = NextBackendState},
% under high load, the pid might have died in the meantime
case is_pid(Pid) andalso not revolver_utils:alive(Pid) of
true ->
{ok, NextBackendState2} = apply(Backend, pid_down, [Pid, NextBackendState]),
NextState2 = NextState#state{backend_state = NextBackendState2},
handle_call(pid, internal, NextState2);
false ->
{reply, Pid, NextState}
end;
handle_call({release, Pid}, _From, State = #state{ backend = Backend, backend_state = BackendState}) ->
{Reply, NextBackendState} =
case revolver_utils:alive(Pid) of
true ->
apply(Backend, release, [Pid, BackendState]);
false ->
apply(Backend, pid_down, [Pid, BackendState])
end,
NextState = State#state{backend_state = NextBackendState},
{reply, Reply, NextState};
handle_call({map, Fun}, _From, State = #state{ backend = Backend, backend_state = BackendState }) ->
ConnectedSate = connect_internal(State),
{{ok, Pids}, NextBackendState} = apply(Backend, pids, [BackendState]),
Reply = lists:map(Fun, Pids),
NextState = ConnectedSate#state{backend_state = NextBackendState},
{reply, Reply, NextState};
handle_call(connect, _From, State) ->
NewSate = connect_internal(State),
Reply =
case NewSate#state.connected of
true ->
ok;
false ->
{error, not_connected}
end,
{reply, Reply, NewSate}.
handle_cast({release, Pid}, State) ->
{reply, _, NextState} = handle_call({release, Pid}, internal, State),
{noreply, NextState};
handle_cast(_, State) ->
throw("not implemented"),
{noreply, State}.
handle_info(connect, State) ->
{noreply, connect_internal(State)};
handle_info({pids, Pids}, State) ->
{noreply, connect_internal(Pids, State)};
handle_info({'DOWN', _, _, Pid, Reason}, State = #state{supervisor = Supervisor, pids_count_original = PidsCountOriginal, backend = Backend, backend_state = BackendState, min_alive_ratio = MinAliveRatio, down_count = DownCount , reload_every = ReloadEvery}) ->
error_logger:info_msg("~p: The process ~p (child of ~p) died for reason ~p.\n", [?MODULE, Pid, Supervisor, Reason]),
{ok, NextBackendState} = apply(Backend, pid_down, [Pid, BackendState]),
{{ok, Pids}, NextBackendState2} = apply(Backend, pids, [NextBackendState]),
Connected = Pids =/= [],
NewDownCount = DownCount + 1,
case ((NewDownCount rem ReloadEvery) == 0) andalso too_few_pids(Pids, PidsCountOriginal, MinAliveRatio) of
true ->
error_logger:warning_msg("~p: Reloading children from supervisor ~p (connected: ~p).\n", [?MODULE, Supervisor, Connected]),
connect_async(State);
false ->
noop
end,
{noreply, State#state{ connected = Connected, backend_state = NextBackendState2, down_count = NewDownCount }}.
terminate(_Reason, _State) -> ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.
too_few_pids(Pids, PidsCountOriginal, MinAliveRatio) ->
length(Pids) / PidsCountOriginal < MinAliveRatio.
connect_async(#state{ supervisor = Supervisor}) ->
Self = self(),
spawn_link(fun() -> Self ! {pids, revolver_utils:child_pids(Supervisor)} end).
connect_internal(State = #state{ supervisor = Supervisor}) ->
connect_internal(revolver_utils:child_pids(Supervisor), State).
connect_internal({error, supervisor_not_running}, State = #state{ reconnect_delay = ReconnectDelay, backend = Backend, backend_state = BackendState}) ->
{ok, NextBackendState} = apply(Backend, delete_all_pids, [BackendState]),
schedule_reconnect(ReconnectDelay),
State#state{ connected = false, backend_state = NextBackendState };
connect_internal(Pids, State = #state{ supervisor = Supervisor, reconnect_delay = ReconnectDelay, backend = Backend, backend_state = BackendState }) ->
{ok, NewPids, NextBackendState} = apply(Backend, new_pids, [Pids, BackendState]),
[revolver_utils:monitor(NewPid) || NewPid <- NewPids],
case length(Pids) of
0 ->
error_logger:error_msg(
"~p zero PIDs for ~p, disconnected.\n",
[?MODULE, Supervisor]),
schedule_reconnect(ReconnectDelay),
State#state{ connected = false, backend_state = NextBackendState };
PidCount ->
State#state{ connected = true, backend_state = NextBackendState, pids_count_original = PidCount}
end.
schedule_reconnect(Delay) ->
error_logger:error_msg("~p trying to reconnect in ~p ms.\n", [?MODULE, Delay]),
erlang:send_after(Delay, self(), connect).
kill(Pid) ->
kill(Pid, normal).
kill(Pid, Reason) ->
case process_info(Pid) == undefined of
true ->
dead;
false ->
exit(Pid, Reason),
timer:sleep(10),
kill(Pid, kill)
end.
| null | https://raw.githubusercontent.com/odo/revolver/f9378f382d76c0af20081e558af882efa1c3f66d/src/revolver.erl | erlang | ms
revolver is disconnected
under high load, the pid might have died in the meantime | -module (revolver).
-behaviour (gen_server).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([balance/2, balance/3, map/2, start_link/3, pid/1, release/2, connect/1, transaction/2, transaction/3]).
-define(DEFAULTMINALIVERATIO, 1.0).
-define(DEFAULTCONNECTATSTART, true).
-define(DEFAULTMAXMESSAGEQUEUELENGTH, undefined).
-define(DEFAULTRELOADEVERY, 1).
-type sup_ref() :: {atom(), atom()}.
-record(state, {
backend :: atom(),
backend_state :: any,
connected :: boolean(),
supervisor :: sup_ref(),
pids_count_original :: integer(),
min_alive_ratio :: float(),
reload_every :: integer(),
down_count :: integer(),
reconnect_delay :: integer()
}).
start_link(Supervisor, ServerName, Options) when is_map(Options) ->
gen_server:start_link({local, ServerName}, ?MODULE, {Supervisor, Options}, []).
balance(Supervisor, BalancerName) ->
revolver_sup:start_link(Supervisor, BalancerName, #{}).
balance(Supervisor, BalancerName, Options) ->
revolver_sup:start_link(Supervisor, BalancerName, Options).
pid(PoolName) ->
gen_server:call(PoolName, pid).
release(PoolName, Pid) ->
gen_server:cast(PoolName, {release, Pid}).
transaction(PoolName, Fun) ->
transaction(PoolName, Fun, false).
transaction(PoolName, Fun, KillOnError) ->
case ?MODULE:pid(PoolName) of
Pid when is_pid(Pid) ->
try
Reply = Fun(Pid),
ok = ?MODULE:release(PoolName, Pid),
Reply
catch
Class:Reason ->
case KillOnError of
false ->
ok = ?MODULE:release(PoolName, Pid);
true ->
dead = kill(Pid)
end,
erlang:raise(Class, Reason, erlang:get_stacktrace())
end;
{error, Error} ->
{error, Error}
end.
map(ServerName, Fun) ->
gen_server:call(ServerName, {map, Fun}).
connect(PoolName) ->
gen_server:call(PoolName, connect).
init({Supervisor, Options}) ->
MinAliveRatio = maps:get(min_alive_ratio, Options, ?DEFAULTMINALIVERATIO),
ReloadEvery = maps:get(reload_every, Options, ?DEFAULTRELOADEVERY),
ReconnectDelay = maps:get(reconnect_delay, Options, ?DEFAULRECONNECTDELAY),
ConnectAtStart = maps:get(connect_at_start, Options, ?DEFAULTCONNECTATSTART),
MaxMessageQueueLength = maps:get(max_message_queue_length, Options, ?DEFAULTMAXMESSAGEQUEUELENGTH),
Backend = case MaxMessageQueueLength of
lease -> revolver_lease;
_ -> revolver_roundrobin
end,
BackendState = apply(Backend, init_state, [MaxMessageQueueLength]),
State = #state{
backend = Backend,
backend_state = BackendState,
connected = false,
supervisor = Supervisor,
pids_count_original = undefined,
min_alive_ratio = MinAliveRatio,
reload_every = ReloadEvery,
down_count = 0,
reconnect_delay = ReconnectDelay
},
maybe_connect(ConnectAtStart),
{ok, State}.
maybe_connect(true) ->
self() ! connect;
maybe_connect(_) ->
noop.
handle_call(pid, _From, State = #state{connected = false}) ->
{reply, {error, disconnected}, State};
handle_call(pid, _From, State = #state{ backend = Backend, backend_state = BackendState}) ->
{Pid, NextBackendState} = apply(Backend, next_pid, [BackendState]),
NextState = State#state{backend_state = NextBackendState},
case is_pid(Pid) andalso not revolver_utils:alive(Pid) of
true ->
{ok, NextBackendState2} = apply(Backend, pid_down, [Pid, NextBackendState]),
NextState2 = NextState#state{backend_state = NextBackendState2},
handle_call(pid, internal, NextState2);
false ->
{reply, Pid, NextState}
end;
handle_call({release, Pid}, _From, State = #state{ backend = Backend, backend_state = BackendState}) ->
{Reply, NextBackendState} =
case revolver_utils:alive(Pid) of
true ->
apply(Backend, release, [Pid, BackendState]);
false ->
apply(Backend, pid_down, [Pid, BackendState])
end,
NextState = State#state{backend_state = NextBackendState},
{reply, Reply, NextState};
handle_call({map, Fun}, _From, State = #state{ backend = Backend, backend_state = BackendState }) ->
ConnectedSate = connect_internal(State),
{{ok, Pids}, NextBackendState} = apply(Backend, pids, [BackendState]),
Reply = lists:map(Fun, Pids),
NextState = ConnectedSate#state{backend_state = NextBackendState},
{reply, Reply, NextState};
handle_call(connect, _From, State) ->
NewSate = connect_internal(State),
Reply =
case NewSate#state.connected of
true ->
ok;
false ->
{error, not_connected}
end,
{reply, Reply, NewSate}.
handle_cast({release, Pid}, State) ->
{reply, _, NextState} = handle_call({release, Pid}, internal, State),
{noreply, NextState};
handle_cast(_, State) ->
throw("not implemented"),
{noreply, State}.
handle_info(connect, State) ->
{noreply, connect_internal(State)};
handle_info({pids, Pids}, State) ->
{noreply, connect_internal(Pids, State)};
handle_info({'DOWN', _, _, Pid, Reason}, State = #state{supervisor = Supervisor, pids_count_original = PidsCountOriginal, backend = Backend, backend_state = BackendState, min_alive_ratio = MinAliveRatio, down_count = DownCount , reload_every = ReloadEvery}) ->
error_logger:info_msg("~p: The process ~p (child of ~p) died for reason ~p.\n", [?MODULE, Pid, Supervisor, Reason]),
{ok, NextBackendState} = apply(Backend, pid_down, [Pid, BackendState]),
{{ok, Pids}, NextBackendState2} = apply(Backend, pids, [NextBackendState]),
Connected = Pids =/= [],
NewDownCount = DownCount + 1,
case ((NewDownCount rem ReloadEvery) == 0) andalso too_few_pids(Pids, PidsCountOriginal, MinAliveRatio) of
true ->
error_logger:warning_msg("~p: Reloading children from supervisor ~p (connected: ~p).\n", [?MODULE, Supervisor, Connected]),
connect_async(State);
false ->
noop
end,
{noreply, State#state{ connected = Connected, backend_state = NextBackendState2, down_count = NewDownCount }}.
terminate(_Reason, _State) -> ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.
too_few_pids(Pids, PidsCountOriginal, MinAliveRatio) ->
length(Pids) / PidsCountOriginal < MinAliveRatio.
connect_async(#state{ supervisor = Supervisor}) ->
Self = self(),
spawn_link(fun() -> Self ! {pids, revolver_utils:child_pids(Supervisor)} end).
connect_internal(State = #state{ supervisor = Supervisor}) ->
connect_internal(revolver_utils:child_pids(Supervisor), State).
connect_internal({error, supervisor_not_running}, State = #state{ reconnect_delay = ReconnectDelay, backend = Backend, backend_state = BackendState}) ->
{ok, NextBackendState} = apply(Backend, delete_all_pids, [BackendState]),
schedule_reconnect(ReconnectDelay),
State#state{ connected = false, backend_state = NextBackendState };
connect_internal(Pids, State = #state{ supervisor = Supervisor, reconnect_delay = ReconnectDelay, backend = Backend, backend_state = BackendState }) ->
{ok, NewPids, NextBackendState} = apply(Backend, new_pids, [Pids, BackendState]),
[revolver_utils:monitor(NewPid) || NewPid <- NewPids],
case length(Pids) of
0 ->
error_logger:error_msg(
"~p zero PIDs for ~p, disconnected.\n",
[?MODULE, Supervisor]),
schedule_reconnect(ReconnectDelay),
State#state{ connected = false, backend_state = NextBackendState };
PidCount ->
State#state{ connected = true, backend_state = NextBackendState, pids_count_original = PidCount}
end.
schedule_reconnect(Delay) ->
error_logger:error_msg("~p trying to reconnect in ~p ms.\n", [?MODULE, Delay]),
erlang:send_after(Delay, self(), connect).
kill(Pid) ->
kill(Pid, normal).
kill(Pid, Reason) ->
case process_info(Pid) == undefined of
true ->
dead;
false ->
exit(Pid, Reason),
timer:sleep(10),
kill(Pid, kill)
end.
|
3b0d346a0fbe5d6bf5315b1048779d3a0f6c951cbdb12c9dc68c465ef468dfbb | samsergey/formica | type-checking.rkt | #lang racket/base
;;______________________________________________________________
;; ______
;; ( // _____ ____ . __ __
;; ~//~ ((_)// // / / // ((_ ((_/_
;; (_//
;;..............................................................
;; Provides contract based type system.
;;==============================================================
(require racket/contract
(for-syntax racket/base))
(provide
is check-result check-argument check-type)
(define-for-syntax (parse-infix-contract stx)
(syntax-case stx (.->.)
[(x ... .->. y) #`(.->. #,@(parse-infix-contract #'(x ...)) #,(parse-infix-contract #'y))]
[(x y ...) #`(#,(parse-infix-contract #'x) #,@(parse-infix-contract #'(y ...)))]
[x #'x]))
;;;=================================================================
;;; Safe type checking
;;;=================================================================
(define-syntax is
(make-set!-transformer
(lambda (stx)
(syntax-case stx ()
[(is x type)
(with-syntax ([c (parse-infix-contract #'type)])
(syntax-protect
#'(cond
[(contract? c)
(with-handlers ([exn:fail? (lambda (exn) #f)])
(contract-first-order-passes? c x))]
[else (raise-type-error 'is "predicate" 1 x type)])))]
[is (syntax-protect
#'(λ (x t) (is x t)))]))))
(define check-type (make-parameter #t))
(define-syntax-rule (check-result id type expr text ...)
(let ([res expr])
(if (or (not (check-type)) (is res type))
res
(raise-arguments-error
id
(format "the result should have type ~a" (build-compound-type-name type))
"received" res
text ...))))
(define-syntax-rule (check-argument id type x text ...)
(unless (or (not (check-type)) (is x type))
(raise-arguments-error
id
(format "the argument should have type ~a" (build-compound-type-name type))
"given" x
text ...)))
| null | https://raw.githubusercontent.com/samsergey/formica/b4410b4b6da63ecb15b4c25080951a7ba4d90d2c/private/types/type-checking.rkt | racket | ______________________________________________________________
______
( // _____ ____ . __ __
~//~ ((_)// // / / // ((_ ((_/_
(_//
..............................................................
Provides contract based type system.
==============================================================
=================================================================
Safe type checking
================================================================= | #lang racket/base
(require racket/contract
(for-syntax racket/base))
(provide
is check-result check-argument check-type)
(define-for-syntax (parse-infix-contract stx)
(syntax-case stx (.->.)
[(x ... .->. y) #`(.->. #,@(parse-infix-contract #'(x ...)) #,(parse-infix-contract #'y))]
[(x y ...) #`(#,(parse-infix-contract #'x) #,@(parse-infix-contract #'(y ...)))]
[x #'x]))
(define-syntax is
(make-set!-transformer
(lambda (stx)
(syntax-case stx ()
[(is x type)
(with-syntax ([c (parse-infix-contract #'type)])
(syntax-protect
#'(cond
[(contract? c)
(with-handlers ([exn:fail? (lambda (exn) #f)])
(contract-first-order-passes? c x))]
[else (raise-type-error 'is "predicate" 1 x type)])))]
[is (syntax-protect
#'(λ (x t) (is x t)))]))))
(define check-type (make-parameter #t))
(define-syntax-rule (check-result id type expr text ...)
(let ([res expr])
(if (or (not (check-type)) (is res type))
res
(raise-arguments-error
id
(format "the result should have type ~a" (build-compound-type-name type))
"received" res
text ...))))
(define-syntax-rule (check-argument id type x text ...)
(unless (or (not (check-type)) (is x type))
(raise-arguments-error
id
(format "the argument should have type ~a" (build-compound-type-name type))
"given" x
text ...)))
|
c9de36ad017ce6422748bf011f66f1a8d0fd1852845c2a50993253d406d48575 | ocaml-sf/learn-ocaml-corpus | correct_no_path_compression.ml | (* This code does no path compression, but does perform balancing
based on ranks. So, its complexity should be O(log n). *)
let make () : elem =
ref (Root 0)
let rec find (x : elem) : elem =
match !x with
| Root _ ->
x
| Link y ->
let z = find y in
(* x := Link z; *)
z
let eq (x : elem) (y : elem) : bool =
find x == find y
let link (x : elem) (y : elem) : unit =
if x != y then
match !x, !y with
| Root rx, Root ry ->
if rx < ry then begin
x := Link y
end else if rx > ry then begin
y := Link x
end else begin
y := Link x; x := Root (rx+1)
end
| Root _, Link _
| Link _, Root _
| Link _, Link _ ->
assert false
let union (x : elem) (y : elem) : unit =
link (find x) (find y)
| null | https://raw.githubusercontent.com/ocaml-sf/learn-ocaml-corpus/7dcf4d72b49863a3e37e41b3c3097aa4c6101a69/exercises/fpottier/unionfind/wrong/correct_no_path_compression.ml | ocaml | This code does no path compression, but does perform balancing
based on ranks. So, its complexity should be O(log n).
x := Link z; |
let make () : elem =
ref (Root 0)
let rec find (x : elem) : elem =
match !x with
| Root _ ->
x
| Link y ->
let z = find y in
z
let eq (x : elem) (y : elem) : bool =
find x == find y
let link (x : elem) (y : elem) : unit =
if x != y then
match !x, !y with
| Root rx, Root ry ->
if rx < ry then begin
x := Link y
end else if rx > ry then begin
y := Link x
end else begin
y := Link x; x := Root (rx+1)
end
| Root _, Link _
| Link _, Root _
| Link _, Link _ ->
assert false
let union (x : elem) (y : elem) : unit =
link (find x) (find y)
|
1cebd2766c61ecbe19d591e1c25a30ec9d9a8fd9388c348ba3f599cb796a8c35 | ocaml/dune | dune_rpc_diagnostics.ml | open Stdune
open Fiber.O
module Client = Dune_rpc_client.Client
open Dune_rpc_e2e
module Dune_rpc = Dune_rpc_private
module Sub = Dune_rpc.Sub
module Diagnostic = Dune_rpc.Diagnostic
module Request = Dune_rpc.Public.Request
module Response = Dune_rpc.Response
let%expect_test "turn on and shutdown" =
let test () =
with_dune_watch (fun _pid ->
run_client (fun client ->
let+ () = dune_build client "." in
printfn "shutting down"))
in
run test;
[%expect {|
Building .
Build . succeeded
shutting down |}]
let files =
List.iter ~f:(fun (f, contents) -> Io.String_path.write_file f contents)
let on_diagnostic_event diagnostics =
let cwd = Sys.getcwd () in
let sanitize_path path =
match String.drop_prefix path ~prefix:cwd with
| None -> path
| Some s -> "$CWD" ^ s
in
let sanitize_pp pp = Pp.verbatim (Format.asprintf "%a@." Pp.to_fmt pp) in
let sanitize_loc =
let sanitize_position (p : Lexing.position) =
{ p with pos_fname = sanitize_path p.pos_fname }
in
fun (loc : Loc.t) ->
{ Loc.start = sanitize_position loc.start
; stop = sanitize_position loc.stop
}
in
(* function to remove remove pp tags and hide junk from paths *)
let map_event (d : Diagnostic.Event.t) f : Diagnostic.Event.t =
match d with
| Remove e -> Remove (f e)
| Add e -> Add (f e)
in
let sanitize (d : Diagnostic.t) =
let directory = Option.map d.directory ~f:sanitize_path in
let promotion =
List.map d.promotion ~f:(fun (p : Diagnostic.Promotion.t) ->
let in_build = sanitize_path p.in_build in
let in_source = sanitize_path p.in_source in
{ Diagnostic.Promotion.in_build; in_source })
in
let related =
List.map d.related ~f:(fun (related : Diagnostic.Related.t) ->
let loc = sanitize_loc related.loc in
let message = sanitize_pp related.message in
{ Diagnostic.Related.message; loc })
in
{ d with
message = sanitize_pp d.message
; loc = Option.map d.loc ~f:sanitize_loc
; directory
; promotion
; related
}
in
if List.is_empty diagnostics then print_endline "<no diagnostics>"
else
List.iter diagnostics ~f:(fun (e : Diagnostic.Event.t) ->
(match e with
| Remove _ -> ()
| Add e ->
Diagnostic.promotion e
|> List.iter ~f:(fun promotion ->
let path = Diagnostic.Promotion.in_build promotion in
if not (Sys.file_exists path) then
printfn "FAILURE: promotion file %s does not exist"
(sanitize_path path)));
let e = map_event e sanitize in
printfn "%s" (Dyn.to_string (Diagnostic.Event.to_dyn e)))
let setup_diagnostics f =
let exec _pid =
run_client (fun client ->
(* First we test for regular errors *)
files [ ("dune-project", "(lang dune 3.0)") ];
f client)
in
run (fun () -> with_dune_watch exec)
let poll_exn client decl =
let+ poll = Client.poll client decl in
match poll with
| Ok p -> p
| Error e -> raise (Dune_rpc.Version_error.E e)
let print_diagnostics poll =
let+ res = Client.Stream.next poll in
match res with
| None -> printfn "client: no more diagnostics"
| Some diag -> on_diagnostic_event diag
let diagnostic_with_build setup target =
let exec _pid =
run_client (fun client ->
(* First we test for regular errors *)
files (("dune-project", "(lang dune 3.0)") :: setup);
let* () = dune_build client target in
let* poll = poll_exn client Dune_rpc.Public.Sub.diagnostic in
let* () = print_diagnostics poll in
Client.Stream.cancel poll)
in
run (fun () -> with_dune_watch exec)
let%expect_test "error in dune file" =
diagnostic_with_build [ ("dune", "(library (name foo))") ] "foo.cma";
[%expect
{|
Building foo.cma
Build foo.cma succeeded
<no diagnostics> |}]
let%expect_test "related error" =
diagnostic_with_build
[ ("dune", "(library (name foo))")
; ("foo.mli", "val x : int")
; ("foo.ml", "let x = true")
]
"foo.cma";
[%expect
{|
Building foo.cma
Build foo.cma failed
[ "Add"
; [ [ "directory"; "$CWD" ]
; [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"
; [ "Verbatim"
; "The implementation foo.ml\n\
does not match the interface .foo.objs/byte/foo.cmi: \n\
Values do not match: val x : bool is not included in val x : int\n\
The type bool is not compatible with the type int\n\
"
]
]
; [ "promotion"; [] ]
; [ "related"
; [ [ [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/foo.mli" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "11" ]
; [ "pos_fname"; "$CWD/foo.mli" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"; [ "Verbatim"; "Expected declaration\n\
" ] ]
]
; [ [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "4" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "5" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"; [ "Verbatim"; "Actual declaration\n\
" ] ]
]
]
]
; [ "targets"; [] ]
]
] |}];
diagnostic_with_build
[ ("dune", "(library (name foo)) (executable (name foo))"); ("foo.ml", "") ]
"@check";
[%expect
{|
Building @check
Build @check failed
[ "Add"
; [ [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/dune" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "20" ]
; [ "pos_fname"; "$CWD/dune" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"
; [ "Verbatim"; "Module \"Foo\" is used in several\n\
stanzas:\n\
" ]
]
; [ "promotion"; [] ]
; [ "related"
; [ [ [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "21" ]
; [ "pos_fname"; "$CWD/dune" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "44" ]
; [ "pos_fname"; "$CWD/dune" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"; [ "Verbatim"; "Used in this\n\
stanza\n\
" ] ]
]
]
]
; [ "targets"; [] ]
]
] |}]
let%expect_test "promotion" =
diagnostic_with_build
[ ( "dune"
, {|
(rule (alias foo) (action (diff x x.gen)))
(rule (with-stdout-to x.gen (echo "toto")))
|}
)
; ("x", "titi")
]
"(alias foo)";
[%expect
{|
Building (alias foo)
Build (alias foo) failed
[ "Add"
; [ [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/x" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/x" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"
; [ "Verbatim"
; "Error: Files _build/default/x and _build/default/x.gen\n\
differ.\n\
"
]
]
; [ "promotion"
; [ [ [ "in_build"; "$CWD/_build/default/x.gen" ]
; [ "in_source"; "$CWD/x" ]
]
]
]
; [ "related"; [] ]
; [ "targets"; [] ]
]
] |}]
let%expect_test "optional promotion" =
diagnostic_with_build
[ ( "dune"
, {|
(rule
(alias foo)
(action
(progn
(with-stdout-to output.expected (echo "foo"))
(with-stdout-to output.actual (echo "bar"))
(diff? output.expected output.actual))))
|}
)
]
"(alias foo)";
[%expect
{|
Building (alias foo)
Build (alias foo) failed
FAILURE: promotion file $CWD/_build/default/output.actual does not exist
[ "Add"
; [ [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/output.expected" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/output.expected" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"
; [ "Verbatim"
; "Error: Files _build/default/output.expected and _build/default/output.actual\n\
differ.\n\
"
]
]
; [ "promotion"
; [ [ [ "in_build"; "$CWD/_build/default/output.actual" ]
; [ "in_source"; "$CWD/output.expected" ]
]
]
]
; [ "related"; [] ]
; [ "targets"; [] ]
]
] |}]
let%expect_test "warning detection" =
diagnostic_with_build
[ ("dune", "(executable (flags -w +26) (name foo))")
; ("foo.ml", "let () = let x = 10 in ()")
]
"./foo.exe";
[%expect
{|
Building ./foo.exe
Build ./foo.exe succeeded
<no diagnostics> |}]
let%expect_test "error from user rule" =
diagnostic_with_build
[ ("dune", "(rule (target foo) (action (bash \"echo foobar\")))") ]
"./foo";
[%expect
{|
Building ./foo
Build ./foo failed
[ "Add"
; [ [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/dune" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "49" ]
; [ "pos_fname"; "$CWD/dune" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"
; [ "Verbatim"
; "Error: Rule failed to generate the following\n\
targets:- foo\n\
"
]
]
; [ "promotion"; [] ]
; [ "related"; [] ]
; [ "targets"; [] ]
]
] |}]
let%expect_test "library error location" =
diagnostic_with_build
[ ("dune", "(library (name foo) (libraries fake-library))")
; ("foo.ml", "")
]
"./foo.cma";
[%expect
{|
Building ./foo.cma
Build ./foo.cma failed
[ "Add"
; [ [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "31" ]
; [ "pos_fname"; "$CWD/dune" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "43" ]
; [ "pos_fname"; "$CWD/dune" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"
; [ "Verbatim"; "Error: Library \"fake-library\" not\n\
found.\n\
" ]
]
; [ "promotion"; [] ]
; [ "related"; [] ]
; [ "targets"; [] ]
]
] |}]
let%expect_test "create and fix error" =
setup_diagnostics (fun client ->
files
[ ("dune", "(executable (name foo))")
; ("foo.ml", "let () = print_endline 123")
];
let* poll = poll_exn client Dune_rpc.Public.Sub.diagnostic in
let* () = print_diagnostics poll in
[%expect {|
<no diagnostics> |}];
let* () = dune_build client "./foo.exe" in
[%expect {|
Building ./foo.exe
Build ./foo.exe failed |}];
let* () = print_diagnostics poll in
[%expect
{|
[ "Add"
; [ [ "directory"; "$CWD" ]
; [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "23" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "26" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"
; [ "Verbatim"
; "This expression has type int but an expression was expected of type\n\
\ string\n\
"
]
]
; [ "promotion"; [] ]
; [ "related"; [] ]
; [ "targets"; [] ]
]
] |}];
files [ ("foo.ml", "let () = print_endline \"foo\"") ];
let* () = dune_build client "./foo.exe" in
[%expect
{|
Building ./foo.exe
Build ./foo.exe succeeded |}];
let+ () = print_diagnostics poll in
[%expect
{|
[ "Remove"
; [ [ "directory"; "$CWD" ]
; [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "23" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "26" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"
; [ "Verbatim"
; "This expression has type int but an expression was expected of type\n\
\ string\n\
"
]
]
; [ "promotion"; [] ]
; [ "related"; [] ]
; [ "targets"; [] ]
]
] |}]);
[%expect {| |}]
let request_exn client req n =
let* staged = Client.Versioned.prepare_request client req in
match staged with
| Ok req -> Client.request client req n
| Error e -> raise (Dune_rpc.Version_error.E e)
let%expect_test "formatting dune files" =
let exec _pid =
run_client (fun client ->
(* First we test for regular errors *)
files [ ("dune-project", "(lang dune 3.0)") ];
let unformatted = "(\nlibrary (name foo\n))" in
printfn "Unformatted:\n%s" unformatted;
let run uri what =
let+ res =
request_exn client Request.format_dune_file
(uri, `Contents unformatted)
in
match res with
| Ok s -> printfn "Formatted (%s):\n%s" what s
| Error e ->
Format.eprintf "Error formatting:@.%s@."
(Dyn.to_string (Response.Error.to_dyn e))
in
let* () = run Dune_rpc.Path.(relative dune_root "dune") "relative" in
[%expect
{|
Unformatted:
(
library (name foo
))
Formatted (relative):
(library
(name foo)) |}];
let+ () =
run
(Dune_rpc.Path.absolute (Filename.concat (Sys.getcwd ()) "dune"))
"absolute"
in
[%expect
{|
Formatted (absolute):
(library
(name foo)) |}])
in
run (fun () -> with_dune_watch exec);
[%expect {| |}]
let%expect_test "promoting dune files" =
let exec _pid =
run_client (fun client ->
(* First we test for regular errors *)
let fname = "x" in
let promoted = "x.gen" in
files
[ ("dune-project", "(lang dune 3.0)")
; ("x", "titi")
; ( "dune"
, sprintf
{|
(rule (alias foo) (action (diff %s %s)))
(rule (with-stdout-to %s (echo "toto")))
|}
fname promoted promoted )
];
let* () = dune_build client "(alias foo)" in
[%expect
{|
Building (alias foo)
Build (alias foo) failed |}];
print_endline "attempting to promote";
let+ res =
request_exn client Request.promote
Dune_rpc.Path.(relative dune_root fname)
in
(match res with
| Ok () ->
let contents = Io.String_path.read_file fname in
printfn "promoted file contents:\n%s" contents
| Error e ->
Format.eprintf "Error formatting:@.%s@."
(Dyn.to_string (Dune_rpc.Response.Error.to_dyn e)));
[%expect
{|
attempting to promote
promoted file contents:
toto |}])
in
run (fun () -> with_dune_watch exec);
[%expect {| |}]
let%expect_test "multiple errors in one file" =
let source =
{|
module A : sig
val f : unit
[@@alert foo "foobar"]
end = struct
let f = ()
end
let f = A.f
let g = A.f
|}
in
setup_diagnostics (fun client ->
files [ ("dune", "(executable (name foo))"); ("foo.ml", source) ];
let* poll = poll_exn client Dune_rpc.Public.Sub.diagnostic in
let* () = print_diagnostics poll in
[%expect {|
<no diagnostics> |}];
let* () = dune_build client "./foo.exe" in
[%expect {|
Building ./foo.exe
Build ./foo.exe failed |}];
let+ () = print_diagnostics poll in
[%expect
{|
[ "Add"
; [ [ "directory"; "$CWD" ]
; [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "8" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "11" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "11" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "11" ]
]
]
]
]
; [ "message"; [ "Verbatim"; "foobar\n\
" ] ]
; [ "promotion"; [] ]
; [ "related"; [] ]
; [ "targets"; [] ]
]
]
[ "Add"
; [ [ "directory"; "$CWD" ]
; [ "id"; "1" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "8" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "12" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "11" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "12" ]
]
]
]
]
; [ "message"; [ "Verbatim"; "foobar\n\
" ] ]
; [ "promotion"; [] ]
; [ "related"; [] ]
; [ "targets"; [] ]
]
]
[ "Add"
; [ [ "directory"; "$CWD" ]
; [ "id"; "2" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "4" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "11" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "5" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "11" ]
]
]
]
]
; [ "message"; [ "Verbatim"; "unused value f.\n\
" ] ]
; [ "promotion"; [] ]
; [ "related"; [] ]
; [ "targets"; [] ]
]
]
[ "Add"
; [ [ "directory"; "$CWD" ]
; [ "id"; "3" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "4" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "12" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "5" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "12" ]
]
]
]
]
; [ "message"; [ "Verbatim"; "unused value g.\n\
" ] ]
; [ "promotion"; [] ]
; [ "related"; [] ]
; [ "targets"; [] ]
]
] |}]);
[%expect {||}]
| null | https://raw.githubusercontent.com/ocaml/dune/20180d12149343d073cdea5860d01dc181702e6a/test/expect-tests/dune_rpc_e2e/dune_rpc_diagnostics.ml | ocaml | function to remove remove pp tags and hide junk from paths
First we test for regular errors
First we test for regular errors
First we test for regular errors
First we test for regular errors | open Stdune
open Fiber.O
module Client = Dune_rpc_client.Client
open Dune_rpc_e2e
module Dune_rpc = Dune_rpc_private
module Sub = Dune_rpc.Sub
module Diagnostic = Dune_rpc.Diagnostic
module Request = Dune_rpc.Public.Request
module Response = Dune_rpc.Response
let%expect_test "turn on and shutdown" =
let test () =
with_dune_watch (fun _pid ->
run_client (fun client ->
let+ () = dune_build client "." in
printfn "shutting down"))
in
run test;
[%expect {|
Building .
Build . succeeded
shutting down |}]
let files =
List.iter ~f:(fun (f, contents) -> Io.String_path.write_file f contents)
let on_diagnostic_event diagnostics =
let cwd = Sys.getcwd () in
let sanitize_path path =
match String.drop_prefix path ~prefix:cwd with
| None -> path
| Some s -> "$CWD" ^ s
in
let sanitize_pp pp = Pp.verbatim (Format.asprintf "%a@." Pp.to_fmt pp) in
let sanitize_loc =
let sanitize_position (p : Lexing.position) =
{ p with pos_fname = sanitize_path p.pos_fname }
in
fun (loc : Loc.t) ->
{ Loc.start = sanitize_position loc.start
; stop = sanitize_position loc.stop
}
in
let map_event (d : Diagnostic.Event.t) f : Diagnostic.Event.t =
match d with
| Remove e -> Remove (f e)
| Add e -> Add (f e)
in
let sanitize (d : Diagnostic.t) =
let directory = Option.map d.directory ~f:sanitize_path in
let promotion =
List.map d.promotion ~f:(fun (p : Diagnostic.Promotion.t) ->
let in_build = sanitize_path p.in_build in
let in_source = sanitize_path p.in_source in
{ Diagnostic.Promotion.in_build; in_source })
in
let related =
List.map d.related ~f:(fun (related : Diagnostic.Related.t) ->
let loc = sanitize_loc related.loc in
let message = sanitize_pp related.message in
{ Diagnostic.Related.message; loc })
in
{ d with
message = sanitize_pp d.message
; loc = Option.map d.loc ~f:sanitize_loc
; directory
; promotion
; related
}
in
if List.is_empty diagnostics then print_endline "<no diagnostics>"
else
List.iter diagnostics ~f:(fun (e : Diagnostic.Event.t) ->
(match e with
| Remove _ -> ()
| Add e ->
Diagnostic.promotion e
|> List.iter ~f:(fun promotion ->
let path = Diagnostic.Promotion.in_build promotion in
if not (Sys.file_exists path) then
printfn "FAILURE: promotion file %s does not exist"
(sanitize_path path)));
let e = map_event e sanitize in
printfn "%s" (Dyn.to_string (Diagnostic.Event.to_dyn e)))
let setup_diagnostics f =
let exec _pid =
run_client (fun client ->
files [ ("dune-project", "(lang dune 3.0)") ];
f client)
in
run (fun () -> with_dune_watch exec)
let poll_exn client decl =
let+ poll = Client.poll client decl in
match poll with
| Ok p -> p
| Error e -> raise (Dune_rpc.Version_error.E e)
let print_diagnostics poll =
let+ res = Client.Stream.next poll in
match res with
| None -> printfn "client: no more diagnostics"
| Some diag -> on_diagnostic_event diag
let diagnostic_with_build setup target =
let exec _pid =
run_client (fun client ->
files (("dune-project", "(lang dune 3.0)") :: setup);
let* () = dune_build client target in
let* poll = poll_exn client Dune_rpc.Public.Sub.diagnostic in
let* () = print_diagnostics poll in
Client.Stream.cancel poll)
in
run (fun () -> with_dune_watch exec)
let%expect_test "error in dune file" =
diagnostic_with_build [ ("dune", "(library (name foo))") ] "foo.cma";
[%expect
{|
Building foo.cma
Build foo.cma succeeded
<no diagnostics> |}]
let%expect_test "related error" =
diagnostic_with_build
[ ("dune", "(library (name foo))")
; ("foo.mli", "val x : int")
; ("foo.ml", "let x = true")
]
"foo.cma";
[%expect
{|
Building foo.cma
Build foo.cma failed
[ "Add"
; [ [ "directory"; "$CWD" ]
; [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"
; [ "Verbatim"
; "The implementation foo.ml\n\
does not match the interface .foo.objs/byte/foo.cmi: \n\
Values do not match: val x : bool is not included in val x : int\n\
The type bool is not compatible with the type int\n\
"
]
]
; [ "promotion"; [] ]
; [ "related"
; [ [ [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/foo.mli" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "11" ]
; [ "pos_fname"; "$CWD/foo.mli" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"; [ "Verbatim"; "Expected declaration\n\
" ] ]
]
; [ [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "4" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "5" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"; [ "Verbatim"; "Actual declaration\n\
" ] ]
]
]
]
; [ "targets"; [] ]
]
] |}];
diagnostic_with_build
[ ("dune", "(library (name foo)) (executable (name foo))"); ("foo.ml", "") ]
"@check";
[%expect
{|
Building @check
Build @check failed
[ "Add"
; [ [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/dune" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "20" ]
; [ "pos_fname"; "$CWD/dune" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"
; [ "Verbatim"; "Module \"Foo\" is used in several\n\
stanzas:\n\
" ]
]
; [ "promotion"; [] ]
; [ "related"
; [ [ [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "21" ]
; [ "pos_fname"; "$CWD/dune" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "44" ]
; [ "pos_fname"; "$CWD/dune" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"; [ "Verbatim"; "Used in this\n\
stanza\n\
" ] ]
]
]
]
; [ "targets"; [] ]
]
] |}]
let%expect_test "promotion" =
diagnostic_with_build
[ ( "dune"
, {|
(rule (alias foo) (action (diff x x.gen)))
(rule (with-stdout-to x.gen (echo "toto")))
|}
)
; ("x", "titi")
]
"(alias foo)";
[%expect
{|
Building (alias foo)
Build (alias foo) failed
[ "Add"
; [ [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/x" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/x" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"
; [ "Verbatim"
; "Error: Files _build/default/x and _build/default/x.gen\n\
differ.\n\
"
]
]
; [ "promotion"
; [ [ [ "in_build"; "$CWD/_build/default/x.gen" ]
; [ "in_source"; "$CWD/x" ]
]
]
]
; [ "related"; [] ]
; [ "targets"; [] ]
]
] |}]
let%expect_test "optional promotion" =
diagnostic_with_build
[ ( "dune"
, {|
(rule
(alias foo)
(action
(progn
(with-stdout-to output.expected (echo "foo"))
(with-stdout-to output.actual (echo "bar"))
(diff? output.expected output.actual))))
|}
)
]
"(alias foo)";
[%expect
{|
Building (alias foo)
Build (alias foo) failed
FAILURE: promotion file $CWD/_build/default/output.actual does not exist
[ "Add"
; [ [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/output.expected" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/output.expected" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"
; [ "Verbatim"
; "Error: Files _build/default/output.expected and _build/default/output.actual\n\
differ.\n\
"
]
]
; [ "promotion"
; [ [ [ "in_build"; "$CWD/_build/default/output.actual" ]
; [ "in_source"; "$CWD/output.expected" ]
]
]
]
; [ "related"; [] ]
; [ "targets"; [] ]
]
] |}]
let%expect_test "warning detection" =
diagnostic_with_build
[ ("dune", "(executable (flags -w +26) (name foo))")
; ("foo.ml", "let () = let x = 10 in ()")
]
"./foo.exe";
[%expect
{|
Building ./foo.exe
Build ./foo.exe succeeded
<no diagnostics> |}]
let%expect_test "error from user rule" =
diagnostic_with_build
[ ("dune", "(rule (target foo) (action (bash \"echo foobar\")))") ]
"./foo";
[%expect
{|
Building ./foo
Build ./foo failed
[ "Add"
; [ [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "0" ]
; [ "pos_fname"; "$CWD/dune" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "49" ]
; [ "pos_fname"; "$CWD/dune" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"
; [ "Verbatim"
; "Error: Rule failed to generate the following\n\
targets:- foo\n\
"
]
]
; [ "promotion"; [] ]
; [ "related"; [] ]
; [ "targets"; [] ]
]
] |}]
let%expect_test "library error location" =
diagnostic_with_build
[ ("dune", "(library (name foo) (libraries fake-library))")
; ("foo.ml", "")
]
"./foo.cma";
[%expect
{|
Building ./foo.cma
Build ./foo.cma failed
[ "Add"
; [ [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "31" ]
; [ "pos_fname"; "$CWD/dune" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "43" ]
; [ "pos_fname"; "$CWD/dune" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"
; [ "Verbatim"; "Error: Library \"fake-library\" not\n\
found.\n\
" ]
]
; [ "promotion"; [] ]
; [ "related"; [] ]
; [ "targets"; [] ]
]
] |}]
let%expect_test "create and fix error" =
setup_diagnostics (fun client ->
files
[ ("dune", "(executable (name foo))")
; ("foo.ml", "let () = print_endline 123")
];
let* poll = poll_exn client Dune_rpc.Public.Sub.diagnostic in
let* () = print_diagnostics poll in
[%expect {|
<no diagnostics> |}];
let* () = dune_build client "./foo.exe" in
[%expect {|
Building ./foo.exe
Build ./foo.exe failed |}];
let* () = print_diagnostics poll in
[%expect
{|
[ "Add"
; [ [ "directory"; "$CWD" ]
; [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "23" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "26" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"
; [ "Verbatim"
; "This expression has type int but an expression was expected of type\n\
\ string\n\
"
]
]
; [ "promotion"; [] ]
; [ "related"; [] ]
; [ "targets"; [] ]
]
] |}];
files [ ("foo.ml", "let () = print_endline \"foo\"") ];
let* () = dune_build client "./foo.exe" in
[%expect
{|
Building ./foo.exe
Build ./foo.exe succeeded |}];
let+ () = print_diagnostics poll in
[%expect
{|
[ "Remove"
; [ [ "directory"; "$CWD" ]
; [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "23" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "1" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "26" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "1" ]
]
]
]
]
; [ "message"
; [ "Verbatim"
; "This expression has type int but an expression was expected of type\n\
\ string\n\
"
]
]
; [ "promotion"; [] ]
; [ "related"; [] ]
; [ "targets"; [] ]
]
] |}]);
[%expect {| |}]
let request_exn client req n =
let* staged = Client.Versioned.prepare_request client req in
match staged with
| Ok req -> Client.request client req n
| Error e -> raise (Dune_rpc.Version_error.E e)
let%expect_test "formatting dune files" =
let exec _pid =
run_client (fun client ->
files [ ("dune-project", "(lang dune 3.0)") ];
let unformatted = "(\nlibrary (name foo\n))" in
printfn "Unformatted:\n%s" unformatted;
let run uri what =
let+ res =
request_exn client Request.format_dune_file
(uri, `Contents unformatted)
in
match res with
| Ok s -> printfn "Formatted (%s):\n%s" what s
| Error e ->
Format.eprintf "Error formatting:@.%s@."
(Dyn.to_string (Response.Error.to_dyn e))
in
let* () = run Dune_rpc.Path.(relative dune_root "dune") "relative" in
[%expect
{|
Unformatted:
(
library (name foo
))
Formatted (relative):
(library
(name foo)) |}];
let+ () =
run
(Dune_rpc.Path.absolute (Filename.concat (Sys.getcwd ()) "dune"))
"absolute"
in
[%expect
{|
Formatted (absolute):
(library
(name foo)) |}])
in
run (fun () -> with_dune_watch exec);
[%expect {| |}]
let%expect_test "promoting dune files" =
let exec _pid =
run_client (fun client ->
let fname = "x" in
let promoted = "x.gen" in
files
[ ("dune-project", "(lang dune 3.0)")
; ("x", "titi")
; ( "dune"
, sprintf
{|
(rule (alias foo) (action (diff %s %s)))
(rule (with-stdout-to %s (echo "toto")))
|}
fname promoted promoted )
];
let* () = dune_build client "(alias foo)" in
[%expect
{|
Building (alias foo)
Build (alias foo) failed |}];
print_endline "attempting to promote";
let+ res =
request_exn client Request.promote
Dune_rpc.Path.(relative dune_root fname)
in
(match res with
| Ok () ->
let contents = Io.String_path.read_file fname in
printfn "promoted file contents:\n%s" contents
| Error e ->
Format.eprintf "Error formatting:@.%s@."
(Dyn.to_string (Dune_rpc.Response.Error.to_dyn e)));
[%expect
{|
attempting to promote
promoted file contents:
toto |}])
in
run (fun () -> with_dune_watch exec);
[%expect {| |}]
let%expect_test "multiple errors in one file" =
let source =
{|
module A : sig
val f : unit
[@@alert foo "foobar"]
end = struct
let f = ()
end
let f = A.f
let g = A.f
|}
in
setup_diagnostics (fun client ->
files [ ("dune", "(executable (name foo))"); ("foo.ml", source) ];
let* poll = poll_exn client Dune_rpc.Public.Sub.diagnostic in
let* () = print_diagnostics poll in
[%expect {|
<no diagnostics> |}];
let* () = dune_build client "./foo.exe" in
[%expect {|
Building ./foo.exe
Build ./foo.exe failed |}];
let+ () = print_diagnostics poll in
[%expect
{|
[ "Add"
; [ [ "directory"; "$CWD" ]
; [ "id"; "0" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "8" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "11" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "11" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "11" ]
]
]
]
]
; [ "message"; [ "Verbatim"; "foobar\n\
" ] ]
; [ "promotion"; [] ]
; [ "related"; [] ]
; [ "targets"; [] ]
]
]
[ "Add"
; [ [ "directory"; "$CWD" ]
; [ "id"; "1" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "8" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "12" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "11" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "12" ]
]
]
]
]
; [ "message"; [ "Verbatim"; "foobar\n\
" ] ]
; [ "promotion"; [] ]
; [ "related"; [] ]
; [ "targets"; [] ]
]
]
[ "Add"
; [ [ "directory"; "$CWD" ]
; [ "id"; "2" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "4" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "11" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "5" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "11" ]
]
]
]
]
; [ "message"; [ "Verbatim"; "unused value f.\n\
" ] ]
; [ "promotion"; [] ]
; [ "related"; [] ]
; [ "targets"; [] ]
]
]
[ "Add"
; [ [ "directory"; "$CWD" ]
; [ "id"; "3" ]
; [ "loc"
; [ [ "start"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "4" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "12" ]
]
]
; [ "stop"
; [ [ "pos_bol"; "0" ]
; [ "pos_cnum"; "5" ]
; [ "pos_fname"; "$CWD/foo.ml" ]
; [ "pos_lnum"; "12" ]
]
]
]
]
; [ "message"; [ "Verbatim"; "unused value g.\n\
" ] ]
; [ "promotion"; [] ]
; [ "related"; [] ]
; [ "targets"; [] ]
]
] |}]);
[%expect {||}]
|
8f709a6f606733ef72760c0b36c5d561a4f7bcec6f357947577506e342a595bc | suprematic/otplike | e6_pmap.clj | (ns otplike.example.e6-pmap
"A naive example of pmap using processes. See question in issue #30."
(:require [otplike.process :as process :refer [!]]))
(process/proc-defn
worker [f parent]
(process/receive!
[idx v]
(try
(! parent [(process/self) [idx (f v)]])
(catch Throwable e
(! parent [(process/self) [idx [:error [:exception e]]]]))))
(recur f parent))
(process/proc-defn
parent [result-promise f n-workers coll]
(let [idx-coll (map-indexed vector coll)
initial-jobs (take n-workers idx-coll)]
(doseq [idx-v initial-jobs]
(let [pid (process/spawn-link worker [f (process/self)])]
(! pid idx-v)))
(loop [active-workers (count initial-jobs)
idx-coll (drop n-workers idx-coll)
results (sorted-map)]
(process/receive!
[from [idx result]]
(if (empty? idx-coll)
(let [active-workers (dec active-workers)]
(if (> active-workers 0)
(recur active-workers idx-coll (assoc results idx result))
(deliver result-promise (vals (assoc results idx result)))))
(do
(! from (first idx-coll))
(recur
active-workers (rest idx-coll) (assoc results idx result))))))))
(defn my-pmap [f n-workers coll]
(if (empty? coll)
coll
(let [result-promise (promise)]
(process/spawn parent [result-promise f n-workers coll])
@result-promise)))
#_(my-pmap #(do (Thread/sleep (* % 100)) (inc %)) 3 (range 1 (inc 4)))
| null | https://raw.githubusercontent.com/suprematic/otplike/bc9d4e82c14053fac8a0ec141eaca897dd2cfe9b/examples/otplike/example/e6_pmap.clj | clojure | (ns otplike.example.e6-pmap
"A naive example of pmap using processes. See question in issue #30."
(:require [otplike.process :as process :refer [!]]))
(process/proc-defn
worker [f parent]
(process/receive!
[idx v]
(try
(! parent [(process/self) [idx (f v)]])
(catch Throwable e
(! parent [(process/self) [idx [:error [:exception e]]]]))))
(recur f parent))
(process/proc-defn
parent [result-promise f n-workers coll]
(let [idx-coll (map-indexed vector coll)
initial-jobs (take n-workers idx-coll)]
(doseq [idx-v initial-jobs]
(let [pid (process/spawn-link worker [f (process/self)])]
(! pid idx-v)))
(loop [active-workers (count initial-jobs)
idx-coll (drop n-workers idx-coll)
results (sorted-map)]
(process/receive!
[from [idx result]]
(if (empty? idx-coll)
(let [active-workers (dec active-workers)]
(if (> active-workers 0)
(recur active-workers idx-coll (assoc results idx result))
(deliver result-promise (vals (assoc results idx result)))))
(do
(! from (first idx-coll))
(recur
active-workers (rest idx-coll) (assoc results idx result))))))))
(defn my-pmap [f n-workers coll]
(if (empty? coll)
coll
(let [result-promise (promise)]
(process/spawn parent [result-promise f n-workers coll])
@result-promise)))
#_(my-pmap #(do (Thread/sleep (* % 100)) (inc %)) 3 (range 1 (inc 4)))
| |
3782b7eba75c3461181fda119ca3dddf34492058d3027da77dea6c2e93c239bd | parenthesin/microservice-boilerplate-malli | db.clj | (ns microservice-boilerplate.schemas.db
(:require [malli.util :as mu]))
(def wallet
[:map
[:wallet/id uuid?]
[:wallet/btc_amount [:double {:gen/NaN? false :gen/infinite? false}]]
[:wallet/usd_amount_at [:double {:gen/NaN? false :gen/infinite? false}]]
[:wallet/created_at inst?]])
(def WalletTransaction
(mu/select-keys wallet [:wallet/id
:wallet/btc_amount
:wallet/usd_amount_at]))
(def WalletEntry
(mu/select-keys wallet [:wallet/id
:wallet/btc_amount
:wallet/usd_amount_at
:wallet/created_at]))
| null | https://raw.githubusercontent.com/parenthesin/microservice-boilerplate-malli/b4bd9fa95f3457dfac47b7b64e00e4f14ba7060c/src/microservice_boilerplate/schemas/db.clj | clojure | (ns microservice-boilerplate.schemas.db
(:require [malli.util :as mu]))
(def wallet
[:map
[:wallet/id uuid?]
[:wallet/btc_amount [:double {:gen/NaN? false :gen/infinite? false}]]
[:wallet/usd_amount_at [:double {:gen/NaN? false :gen/infinite? false}]]
[:wallet/created_at inst?]])
(def WalletTransaction
(mu/select-keys wallet [:wallet/id
:wallet/btc_amount
:wallet/usd_amount_at]))
(def WalletEntry
(mu/select-keys wallet [:wallet/id
:wallet/btc_amount
:wallet/usd_amount_at
:wallet/created_at]))
| |
edf118dd4788ca17b2d72fea86ba8d585aead26650c0cf48a3593187ce14ec34 | tvirolai/blurhash | util_test.cljc | (ns blurhash.util-test
#?(:cljs (:require-macros [blurhash.util :as util]))
(:require [clojure.test :refer [deftest testing is]]
[blurhash.util :as util]))
; Testing that the functions work as expected by using some inputs
from from other BH implementations .
(deftest srgb->linear-test
(is (= 0.8631572134541023 (util/srgb->linear 239)))
(is (= 0.003035269835488375 (util/srgb->linear 10))))
(deftest linear->srgb-test
(is (= 170 (util/linear->srgb 0.4)))
(is (= 239 (util/linear->srgb (util/srgb->linear 239)))))
(deftest signed->unsigned-test
(is (= 227 (util/signed->unsigned -29)))
(is (= 100 (util/signed->unsigned 100))))
(deftest forv-macro
(testing "The forv macro works should work in all environments"
(is (= (vec (for [i (range 5)] i))
(util/forv [i (range 5)] i)))))
#?(:cljs
(deftest uint8-conversion
(testing "Conversion to Uint8ClampedArray format in CLJS"
(is (= (.reduce (new js/Uint8ClampedArray [125 244 421 255]) +)
(.reduce (js->clj (util/->Uint8ClampedArray (list [[125 244 421]]))) +))))))
| null | https://raw.githubusercontent.com/tvirolai/blurhash/f50748b3944d8d7df34435d8c4024a1ebc3e6646/test/cljc/blurhash/util_test.cljc | clojure | Testing that the functions work as expected by using some inputs | (ns blurhash.util-test
#?(:cljs (:require-macros [blurhash.util :as util]))
(:require [clojure.test :refer [deftest testing is]]
[blurhash.util :as util]))
from from other BH implementations .
(deftest srgb->linear-test
(is (= 0.8631572134541023 (util/srgb->linear 239)))
(is (= 0.003035269835488375 (util/srgb->linear 10))))
(deftest linear->srgb-test
(is (= 170 (util/linear->srgb 0.4)))
(is (= 239 (util/linear->srgb (util/srgb->linear 239)))))
(deftest signed->unsigned-test
(is (= 227 (util/signed->unsigned -29)))
(is (= 100 (util/signed->unsigned 100))))
(deftest forv-macro
(testing "The forv macro works should work in all environments"
(is (= (vec (for [i (range 5)] i))
(util/forv [i (range 5)] i)))))
#?(:cljs
(deftest uint8-conversion
(testing "Conversion to Uint8ClampedArray format in CLJS"
(is (= (.reduce (new js/Uint8ClampedArray [125 244 421 255]) +)
(.reduce (js->clj (util/->Uint8ClampedArray (list [[125 244 421]]))) +))))))
|
9822e73de26b0f2a8f29f13730bfcd8a01736d8f125ce50d25050416d633fecd | ucsd-progsys/nate | text.ml | (***********************************************************************)
(* *)
MLTk , Tcl / Tk interface of Objective Caml
(* *)
, , and
projet Cristal , INRIA Rocquencourt
, Kyoto University RIMS
(* *)
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
General Public License , with the special exception on linking
(* described in file LICENSE found in the Objective Caml source tree. *)
(* *)
(***********************************************************************)
open Tk
let top = opentk ()
let scroll_link sb tx =
Text.configure tx [YScrollCommand (Scrollbar.set sb)];
Scrollbar.configure sb [ScrollCommand (Text.yview tx)]
let f = Frame.create top []
let text = Text.create f []
let scrollbar = Scrollbar.create f []
let buffer = ref ""
let kill () =
buffer :=
Text.get text (TextIndex (Insert, []))
(TextIndex (Insert, [LineEnd]));
Text.delete text (TextIndex (Insert, []))
(TextIndex (Insert, [LineEnd]))
;;
let yank () =
Text.insert text (TextIndex (Insert, [])) !buffer []
let _ = bind text [[Control], KeyPressDetail "y"] (BindSet ([], fun _ ->
yank () ))
;;
let _ = bind text [[Control], KeyPressDetail "k"] (BindSet ([], fun _ ->
kill () ))
;;
let _ =
scroll_link scrollbar text;
pack [text;f][];
pack [f][];
mainLoop ()
;;
| null | https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/otherlibs/labltk/examples_camltk/text.ml | ocaml | *********************************************************************
described in file LICENSE found in the Objective Caml source tree.
********************************************************************* | MLTk , Tcl / Tk interface of Objective Caml
, , and
projet Cristal , INRIA Rocquencourt
, Kyoto University RIMS
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
General Public License , with the special exception on linking
open Tk
let top = opentk ()
let scroll_link sb tx =
Text.configure tx [YScrollCommand (Scrollbar.set sb)];
Scrollbar.configure sb [ScrollCommand (Text.yview tx)]
let f = Frame.create top []
let text = Text.create f []
let scrollbar = Scrollbar.create f []
let buffer = ref ""
let kill () =
buffer :=
Text.get text (TextIndex (Insert, []))
(TextIndex (Insert, [LineEnd]));
Text.delete text (TextIndex (Insert, []))
(TextIndex (Insert, [LineEnd]))
;;
let yank () =
Text.insert text (TextIndex (Insert, [])) !buffer []
let _ = bind text [[Control], KeyPressDetail "y"] (BindSet ([], fun _ ->
yank () ))
;;
let _ = bind text [[Control], KeyPressDetail "k"] (BindSet ([], fun _ ->
kill () ))
;;
let _ =
scroll_link scrollbar text;
pack [text;f][];
pack [f][];
mainLoop ()
;;
|
a9c63a61b4e343d152996edee450bda81f44150d1d525cb4b0691ead1d3e16f8 | hidaris/thinking-dumps | tests.rkt | #lang racket
(provide test-list)
;;;;;;;;;;;;;;;; tests ;;;;;;;;;;;;;;;;
(define test-list
'(
;; simple arithmetic
(positive-const "11" 11)
(negative-const "-33" -33)
(simple-arith-1 "(- 44 33)" 11)
;; nested arithmetic
(nested-arith-left "(- (- 44 33) 22)" -11)
(nested-arith-right "(- 55 (- 22 11))" 44)
;; simple variables
(test-var-1 "x" 10)
(test-var-2 "(- x 1)" 9)
(test-var-3 "(- 1 x)" -9)
;; simple unbound variables
(test-unbound-var-1 "foo" error)
(test-unbound-var-2 "(- x foo)" error)
;; simple conditionals
(if-true "(if (zero? 0) 3 4)" 3)
(if-false "(if (zero? 1) 3 4)" 4)
;; test dynamic typechecking
(no-bool-to-diff-1 "(- (zero? 0) 1)" error)
(no-bool-to-diff-2 "(- 1 (zero? 0))" error)
(no-int-to-if "(if 1 2 3)" error)
;; make sure that the test and both arms get evaluated
;; properly.
(if-eval-test-true "(if (zero? (- 11 11)) 3 4)" 3)
(if-eval-test-false "(if (zero? (- 11 12)) 3 4)" 4)
;; and make sure the other arm doesn't get evaluated.
(if-eval-test-true-2 "(if (zero? (- 11 11)) 3 foo)" 3)
(if-eval-test-false-2 "(if (zero? (- 11 12)) foo 4)" 4)
;; simple let
(simple-let-1 "(let x 3 in x)" 3)
make sure the body and rhs get evaluated
(eval-let-body "(let x 3 in (- x 1))" 2)
(eval-let-rhs "(let x (- 4 1) in (- x 1))" 2)
;; check nested let and shadowing
(simple-nested-let "(let x 3 in (let y 4 in (- x y)))" -1)
(check-shadowing-in-body "(let x 3 in (let x 4 in x))" 4)
(check-shadowing-in-rhs "(let x 3 in (let x (- x 1) in x))" 2)
(negative-exp "(- 33)" -33)
;; check arith * + /
(simple-arith-2 "(+ 44 33)" 77)
(simple-arith-3 "(* 4 3)" 12)
(simple-arith-4 "(/ 44 4)" 11)
))
| null | https://raw.githubusercontent.com/hidaris/thinking-dumps/3fceaf9e6195ab99c8315749814a7377ef8baf86/eopl-solutions/chap3/3-07/tests.rkt | racket | tests ;;;;;;;;;;;;;;;;
simple arithmetic
nested arithmetic
simple variables
simple unbound variables
simple conditionals
test dynamic typechecking
make sure that the test and both arms get evaluated
properly.
and make sure the other arm doesn't get evaluated.
simple let
check nested let and shadowing
check arith * + / | #lang racket
(provide test-list)
(define test-list
'(
(positive-const "11" 11)
(negative-const "-33" -33)
(simple-arith-1 "(- 44 33)" 11)
(nested-arith-left "(- (- 44 33) 22)" -11)
(nested-arith-right "(- 55 (- 22 11))" 44)
(test-var-1 "x" 10)
(test-var-2 "(- x 1)" 9)
(test-var-3 "(- 1 x)" -9)
(test-unbound-var-1 "foo" error)
(test-unbound-var-2 "(- x foo)" error)
(if-true "(if (zero? 0) 3 4)" 3)
(if-false "(if (zero? 1) 3 4)" 4)
(no-bool-to-diff-1 "(- (zero? 0) 1)" error)
(no-bool-to-diff-2 "(- 1 (zero? 0))" error)
(no-int-to-if "(if 1 2 3)" error)
(if-eval-test-true "(if (zero? (- 11 11)) 3 4)" 3)
(if-eval-test-false "(if (zero? (- 11 12)) 3 4)" 4)
(if-eval-test-true-2 "(if (zero? (- 11 11)) 3 foo)" 3)
(if-eval-test-false-2 "(if (zero? (- 11 12)) foo 4)" 4)
(simple-let-1 "(let x 3 in x)" 3)
make sure the body and rhs get evaluated
(eval-let-body "(let x 3 in (- x 1))" 2)
(eval-let-rhs "(let x (- 4 1) in (- x 1))" 2)
(simple-nested-let "(let x 3 in (let y 4 in (- x y)))" -1)
(check-shadowing-in-body "(let x 3 in (let x 4 in x))" 4)
(check-shadowing-in-rhs "(let x 3 in (let x (- x 1) in x))" 2)
(negative-exp "(- 33)" -33)
(simple-arith-2 "(+ 44 33)" 77)
(simple-arith-3 "(* 4 3)" 12)
(simple-arith-4 "(/ 44 4)" 11)
))
|
8779148fe50b17be5970179fcbfe16d49418d7401dddcac7d2e9c6e001751d8b | jordwalke/rehp | jstable.mli | Js_of_ocaml library
* /
* Copyright Pierre Chambart 2012 .
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* /
* Copyright Pierre Chambart 2012.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
* A minimal table implementation specialized for { ! Js.js_string } keys .
This is faster than regular OCaml hashtables .
This implementation does not emulate the backtracking behavior of { ! } .
This is faster than regular OCaml hashtables.
This implementation does not emulate the backtracking behavior of {!Hashtbl}.
*)
type 'a t
val create : unit -> 'a t
val add : 'a t -> Js.js_string Js.t -> 'a -> unit
val remove : 'a t -> Js.js_string Js.t -> unit
val find : 'a t -> Js.js_string Js.t -> 'a Js.optdef
val keys : 'a t -> Js.js_string Js.t list
| null | https://raw.githubusercontent.com/jordwalke/rehp/f122b94f0a3f06410ddba59e3c9c603b33aadabf/lib/js_of_ocaml/jstable.mli | ocaml | Js_of_ocaml library
* /
* Copyright Pierre Chambart 2012 .
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* /
* Copyright Pierre Chambart 2012.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
* A minimal table implementation specialized for { ! Js.js_string } keys .
This is faster than regular OCaml hashtables .
This implementation does not emulate the backtracking behavior of { ! } .
This is faster than regular OCaml hashtables.
This implementation does not emulate the backtracking behavior of {!Hashtbl}.
*)
type 'a t
val create : unit -> 'a t
val add : 'a t -> Js.js_string Js.t -> 'a -> unit
val remove : 'a t -> Js.js_string Js.t -> unit
val find : 'a t -> Js.js_string Js.t -> 'a Js.optdef
val keys : 'a t -> Js.js_string Js.t list
| |
e341b450fb3c8f22293dd3866210c74e4004433a2c98284ee2387386c08e0ea7 | ocsigen/ocaml-eliom | packed1.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, LexiFi
(* *)
Copyright 2007 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
let () =
Api.reg_mod "Packed1"
let bla = Sys.argv.(0) ^ "XXX"
let mykey = Sys.argv.(0)
| null | https://raw.githubusercontent.com/ocsigen/ocaml-eliom/497c6707f477cb3086dc6d8124384e74a8c379ae/testsuite/tests/lib-dynlink-native/packed1.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************ | , LexiFi
Copyright 2007 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
let () =
Api.reg_mod "Packed1"
let bla = Sys.argv.(0) ^ "XXX"
let mykey = Sys.argv.(0)
|
24a1bef3b1b2dcb602701766092ec45afd6250b44fa0233ade832a546814f660 | tmattio/js-bindings | vscode_languageclient_type_definition.ml | [@@@js.dummy "!! This code has been generated by gen_js_api !!"]
[@@@ocaml.warning "-7-32-39"]
[@@@ocaml.warning "-7-11-32-33-39"]
open Es5
module ProvideTypeDefinitionSignature =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x2 : Ojs.t) -> x2
and t_to_js : t -> Ojs.t = fun (x1 : Ojs.t) -> x1
let (apply :
t ->
this:unit ->
document:TextDocument.t ->
position:VPosition.t ->
token:CancellationToken.t ->
(VDefinition.t, VDefinitionLink.t) or_array ProviderResult.t)
=
fun (x7 : t) ->
fun ~this:(x3 : unit) ->
fun ~document:(x4 : TextDocument.t) ->
fun ~position:(x5 : VPosition.t) ->
fun ~token:(x6 : CancellationToken.t) ->
ProviderResult.t_of_js
(fun (x8 : Ojs.t) ->
or_array_of_js VDefinition.t_of_js
VDefinitionLink.t_of_js x8)
(Ojs.apply (t_to_js x7)
[|(Ojs.unit_to_js x3);(TextDocument.t_to_js x4);(
VPosition.t_to_js x5);(CancellationToken.t_to_js x6)|])
end
module TypeDefinitionMiddleware =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x12 : Ojs.t) -> x12
and t_to_js : t -> Ojs.t = fun (x11 : Ojs.t) -> x11
let (provide_type_definition :
t ->
this:unit ->
document:TextDocument.t ->
position:VPosition.t ->
token:CancellationToken.t ->
next:ProvideTypeDefinitionSignature.t ->
(VDefinition.t, VDefinitionLink.t) or_array
ProviderResult.t)
=
fun (x18 : t) ->
fun ~this:(x13 : unit) ->
fun ~document:(x14 : TextDocument.t) ->
fun ~position:(x15 : VPosition.t) ->
fun ~token:(x16 : CancellationToken.t) ->
fun ~next:(x17 : ProvideTypeDefinitionSignature.t) ->
ProviderResult.t_of_js
(fun (x19 : Ojs.t) ->
or_array_of_js VDefinition.t_of_js
VDefinitionLink.t_of_js x19)
(Ojs.call (t_to_js x18) "provideTypeDefinition"
[|(Ojs.unit_to_js x13);(TextDocument.t_to_js x14);(
VPosition.t_to_js x15);(CancellationToken.t_to_js
x16);(ProvideTypeDefinitionSignature.t_to_js
x17)|])
end
module TypeDefinitionFeature =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x23 : Ojs.t) -> x23
and t_to_js : t -> Ojs.t = fun (x22 : Ojs.t) -> x22
let (create : client:BaseLanguageClient.t -> t) =
fun ~client:(x24 : BaseLanguageClient.t) ->
t_of_js
(Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "TypeDefinitionFeature")
[|(BaseLanguageClient.t_to_js x24)|])
let (fill_client_capabilities :
t -> capabilities:ClientCapabilities.t -> unit) =
fun (x26 : t) ->
fun ~capabilities:(x25 : ClientCapabilities.t) ->
ignore
(Ojs.call (t_to_js x26) "fillClientCapabilities"
[|(ClientCapabilities.t_to_js x25)|])
let (initialize :
t ->
capabilities:ServerCapabilities.t ->
document_selector:DocumentSelector.t -> unit)
=
fun (x29 : t) ->
fun ~capabilities:(x27 : ServerCapabilities.t) ->
fun ~document_selector:(x28 : DocumentSelector.t) ->
ignore
(Ojs.call (t_to_js x29) "initialize"
[|(ServerCapabilities.t_to_js x27);(DocumentSelector.t_to_js
x28)|])
let (register_language_provider :
t ->
options:TypeDefinitionRegistrationOptions.t ->
(Disposable.t * TypeDefinitionProvider.t))
=
fun (x31 : t) ->
fun ~options:(x30 : TypeDefinitionRegistrationOptions.t) ->
let x32 =
Ojs.call (t_to_js x31) "registerLanguageProvider"
[|(TypeDefinitionRegistrationOptions.t_to_js x30)|] in
((Disposable.t_of_js (Ojs.array_get x32 0)),
(TypeDefinitionProvider.t_of_js (Ojs.array_get x32 1)))
let (cast :
t ->
(TypeDefinitionOptions.t or_boolean,
TypeDefinitionRegistrationOptions.t, TypeDefinitionProvider.t)
TextDocumentFeature.t)
=
fun (x33 : t) ->
TextDocumentFeature.t_of_js
(fun (x34 : Ojs.t) ->
or_boolean_of_js TypeDefinitionOptions.t_of_js x34)
TypeDefinitionRegistrationOptions.t_of_js
TypeDefinitionProvider.t_of_js (t_to_js x33)
end
| null | https://raw.githubusercontent.com/tmattio/js-bindings/ca3bd6a12db519c8de7f41b303f14cf70cfd4c5f/lib/vscode-languageclient/vscode_languageclient_type_definition.ml | ocaml | [@@@js.dummy "!! This code has been generated by gen_js_api !!"]
[@@@ocaml.warning "-7-32-39"]
[@@@ocaml.warning "-7-11-32-33-39"]
open Es5
module ProvideTypeDefinitionSignature =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x2 : Ojs.t) -> x2
and t_to_js : t -> Ojs.t = fun (x1 : Ojs.t) -> x1
let (apply :
t ->
this:unit ->
document:TextDocument.t ->
position:VPosition.t ->
token:CancellationToken.t ->
(VDefinition.t, VDefinitionLink.t) or_array ProviderResult.t)
=
fun (x7 : t) ->
fun ~this:(x3 : unit) ->
fun ~document:(x4 : TextDocument.t) ->
fun ~position:(x5 : VPosition.t) ->
fun ~token:(x6 : CancellationToken.t) ->
ProviderResult.t_of_js
(fun (x8 : Ojs.t) ->
or_array_of_js VDefinition.t_of_js
VDefinitionLink.t_of_js x8)
(Ojs.apply (t_to_js x7)
[|(Ojs.unit_to_js x3);(TextDocument.t_to_js x4);(
VPosition.t_to_js x5);(CancellationToken.t_to_js x6)|])
end
module TypeDefinitionMiddleware =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x12 : Ojs.t) -> x12
and t_to_js : t -> Ojs.t = fun (x11 : Ojs.t) -> x11
let (provide_type_definition :
t ->
this:unit ->
document:TextDocument.t ->
position:VPosition.t ->
token:CancellationToken.t ->
next:ProvideTypeDefinitionSignature.t ->
(VDefinition.t, VDefinitionLink.t) or_array
ProviderResult.t)
=
fun (x18 : t) ->
fun ~this:(x13 : unit) ->
fun ~document:(x14 : TextDocument.t) ->
fun ~position:(x15 : VPosition.t) ->
fun ~token:(x16 : CancellationToken.t) ->
fun ~next:(x17 : ProvideTypeDefinitionSignature.t) ->
ProviderResult.t_of_js
(fun (x19 : Ojs.t) ->
or_array_of_js VDefinition.t_of_js
VDefinitionLink.t_of_js x19)
(Ojs.call (t_to_js x18) "provideTypeDefinition"
[|(Ojs.unit_to_js x13);(TextDocument.t_to_js x14);(
VPosition.t_to_js x15);(CancellationToken.t_to_js
x16);(ProvideTypeDefinitionSignature.t_to_js
x17)|])
end
module TypeDefinitionFeature =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x23 : Ojs.t) -> x23
and t_to_js : t -> Ojs.t = fun (x22 : Ojs.t) -> x22
let (create : client:BaseLanguageClient.t -> t) =
fun ~client:(x24 : BaseLanguageClient.t) ->
t_of_js
(Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "TypeDefinitionFeature")
[|(BaseLanguageClient.t_to_js x24)|])
let (fill_client_capabilities :
t -> capabilities:ClientCapabilities.t -> unit) =
fun (x26 : t) ->
fun ~capabilities:(x25 : ClientCapabilities.t) ->
ignore
(Ojs.call (t_to_js x26) "fillClientCapabilities"
[|(ClientCapabilities.t_to_js x25)|])
let (initialize :
t ->
capabilities:ServerCapabilities.t ->
document_selector:DocumentSelector.t -> unit)
=
fun (x29 : t) ->
fun ~capabilities:(x27 : ServerCapabilities.t) ->
fun ~document_selector:(x28 : DocumentSelector.t) ->
ignore
(Ojs.call (t_to_js x29) "initialize"
[|(ServerCapabilities.t_to_js x27);(DocumentSelector.t_to_js
x28)|])
let (register_language_provider :
t ->
options:TypeDefinitionRegistrationOptions.t ->
(Disposable.t * TypeDefinitionProvider.t))
=
fun (x31 : t) ->
fun ~options:(x30 : TypeDefinitionRegistrationOptions.t) ->
let x32 =
Ojs.call (t_to_js x31) "registerLanguageProvider"
[|(TypeDefinitionRegistrationOptions.t_to_js x30)|] in
((Disposable.t_of_js (Ojs.array_get x32 0)),
(TypeDefinitionProvider.t_of_js (Ojs.array_get x32 1)))
let (cast :
t ->
(TypeDefinitionOptions.t or_boolean,
TypeDefinitionRegistrationOptions.t, TypeDefinitionProvider.t)
TextDocumentFeature.t)
=
fun (x33 : t) ->
TextDocumentFeature.t_of_js
(fun (x34 : Ojs.t) ->
or_boolean_of_js TypeDefinitionOptions.t_of_js x34)
TypeDefinitionRegistrationOptions.t_of_js
TypeDefinitionProvider.t_of_js (t_to_js x33)
end
| |
b8d72426c14acf33d16f073b5dbdfecf8fab2d1a9d1d32be9a5fa865ea17b6c8 | NoRedInk/haskell-libraries | Observability.hs | {-# LANGUAGE GADTs #-}
-- | A module dedicated to observability, that is reporting information about
-- what the program is doing in production to help us debugging it.
--
-- Specifically this module is dedicated to sending information that's already
been collected to external monitoring platforms , such as and
-- Honeycomb. To learn more about how this information is collected check out the
` Platform . Internal ` module in the ` nri - prelude ` package . That module also
defines and documents the ` TracingSpan ` type , which is the data structure we use to
-- contain observability data we have collected.
module Observability
( report,
Handler,
Settings (..),
Reporter (..),
decoder,
handler,
)
where
import qualified Conduit
import qualified Control.Exception.Safe as Exception
import qualified Data.Aeson as Aeson
import qualified Environment
import qualified List
import qualified Platform
import qualified Reporter.Bugsnag as Bugsnag
import qualified Reporter.Dev as Dev
import qualified Reporter.File as File
import qualified Reporter.Honeycomb as Honeycomb
import qualified Set
import qualified Text
import Prelude (pure, traverse)
import qualified Prelude
-- | A handler for reporting to logging/monitoring/observability platforms.
newtype Handler = Handler
{ -- | `report` takes a span containing all the tracing information we
-- collected for a single request and then reports it to all platforms we
-- enabled when creating this handler.
report :: Text -> Platform.TracingSpan -> Prelude.IO ()
}
deriving (Prelude.Semigroup, Prelude.Monoid)
-- | Function for creating an observability handler. The settings we pass in
-- determine which platforms we'll report information to.
handler :: Settings -> Conduit.Acquire Handler
handler settings = do
case enabledReporters settings of
[] -> Prelude.pure reportNothingHandler
firstReporter : otherReporters -> do
firstHandler <- toHandler reportNothingHandler settings firstReporter
otherHandlers <- traverse (toHandler firstHandler settings) otherReporters
Prelude.pure (Prelude.mconcat (firstHandler : otherHandlers))
reportNothingHandler :: Handler
reportNothingHandler = Handler (\_ _ -> Prelude.pure ())
-- | Initialize a reporter from settings, to get a handler for sending reports.
--
-- If a reporter fails with an exception here's what we'd like to be true:
-- - It doesn't affect other reporters (they don't get aborted or anything).
-- - The reporting error gets itself reported _somewhere_ in a way that's
-- relatively likely to succeed.
toHandler :: Handler -> Settings -> Reporter -> Conduit.Acquire Handler
toHandler backup settings Reporter {reporterName, reporterSettings, reporterHandler, reporterReport} = do
handler' <-
reporterSettings settings
|> reporterHandler
|> map (Handler << reporterReport)
Prelude.pure
( Handler
( \requestId span ->
report handler' requestId span
-- If any error sync or async is thrown during reporting, report
-- the failure to the 'backup reporter'.
|> ( \io ->
Exception.withException
io
( \err ->
err
|> reporterExceptionToTracingSpan reporterName span
|> report backup requestId
)
)
-- If this reporter fails with a sync exception we do not want it
-- to abort other reporters, so we catch those exceptions. We've
-- already tried to report on the exception above so there's
-- nothing more we could be doing with the exception anyway.
|> Exception.handleAny (\_ -> Prelude.pure ())
)
)
-- | If a reporter fails with an exception we'd like to report that exception in
-- turn to a reporter. Because reporters take spans we turn the exception into a
-- span here.
reporterExceptionToTracingSpan :: Text -> Platform.TracingSpan -> Exception.SomeException -> Platform.TracingSpan
reporterExceptionToTracingSpan reporterName originalTracingSpan exceptionDuringReporting =
Platform.emptyTracingSpan
{ Platform.name = "Failed to report span to " ++ reporterName,
Platform.succeeded = Platform.FailedWith exceptionDuringReporting,
Platform.started = Platform.finished originalTracingSpan,
Platform.finished = Platform.finished originalTracingSpan,
Platform.frame = Nothing,
Platform.details =
FailedToReportTracingSpan
(Platform.name originalTracingSpan)
(Platform.details originalTracingSpan)
|> Platform.toTracingSpanDetails
|> Just,
Platform.allocated = 0,
Platform.children = []
}
-- | Some details about the span we were attempting to report when a reporting
-- failure happened. We're conservative with the information from the original
-- span we copy over here, in case some complexity somewhere in the original
-- span caused the report of it to fail. It's entirely likely the reporting
-- failure is unrelated to the reported span though. For example, reporting to
might fail if is down .
data FailedToReportTracingSpan = FailedToReportTracingSpan
{ originalTracingSpanName :: Text,
originalTracingSpanDetails :: Maybe Platform.SomeTracingSpanDetails
}
deriving (Generic)
instance Aeson.ToJSON FailedToReportTracingSpan
instance Platform.TracingSpanDetails FailedToReportTracingSpan
-- | A helper type that combines all the different functions a specific reporter
-- must implement in a single record.
--
-- We've defined this as a GADT so we don't need to expose the `handler` and
-- `settings` parameters on the type, meaning this type is defined as `Reporter`
-- rather than `Reporter settings handler`. This allows us to combine multiple
-- reporters in a list.
data Reporter where
Reporter ::
{ reporterName :: Text,
-- | Pick the reporter-specific settings from the global `Settings` type
-- defined in this module.
reporterSettings :: Settings -> settings,
-- | Create a handler for this reporter. This function will be called
-- once when the application starts for each enabled reporter.
reporterHandler :: settings -> Conduit.Acquire handler,
-- | Report a span to this reporter.
reporterReport :: handler -> Text -> Platform.TracingSpan -> Prelude.IO ()
} ->
Reporter
-- | A list containing all the reporters we support. Reporters are ordered in
-- increasing chance of failure, so we can pick the safest one for reporting on
-- failures in other reporters.
supportedReporters :: [Reporter]
supportedReporters =
[ Reporter "stdout" stdout fileHandler File.report,
Reporter "stdout-pretty" dev devHandler Dev.report,
Reporter "file" file fileHandler File.report,
Reporter "bugsnag" bugsnag bugsnagHandler Bugsnag.report,
Reporter "honeycomb" honeycomb honeycombHandler Honeycomb.report
]
fileHandler :: File.Settings -> Conduit.Acquire File.Handler
fileHandler settings = Conduit.mkAcquire (File.handler settings) File.cleanup
devHandler :: () -> Conduit.Acquire Dev.Handler
devHandler _ = Conduit.mkAcquire Dev.handler Dev.cleanup
bugsnagHandler :: Bugsnag.Settings -> Conduit.Acquire Bugsnag.Handler
bugsnagHandler settings = Conduit.liftIO (Bugsnag.handler settings)
honeycombHandler :: Honeycomb.Settings -> Conduit.Acquire Honeycomb.Handler
honeycombHandler settings = Conduit.liftIO (Honeycomb.handler settings)
-- | Settings for all supported reporters.
data Settings = Settings
| The reporters that we send debugging information to . The first
-- reporter in the list is treated special: it will also report on
-- failures that take place while running any of the other reporters.
Because of this its best if the first reporter is one that has a
-- high likelihood of succeeding, for example because it logs to stdout
-- or a file.
enabledReporters :: [Reporter],
-- | Each supported reporter has a settings entry below. We parse
-- settings even for reporters that aren't enabled. Because our
-- environment parser insists all variables have default values it's not
-- necessary to make up values for reporters we don't want enabled.
file :: File.Settings,
bugsnag :: Bugsnag.Settings,
honeycomb :: Honeycomb.Settings,
dev :: ()
}
stdout :: Settings -> File.Settings
stdout settings = (file settings) {File.logFile = "/dev/stdout"}
-- | Read 'Settings' from environment variables. Default variables will be used
-- in case no environment variable is set for an option.
decoder :: Environment.Decoder Settings
decoder =
pure Settings
|> andMap reportersDecoder
|> andMap File.decoder
|> andMap Bugsnag.decoder
|> andMap Honeycomb.decoder
|> andMap (Prelude.pure ())
reportersDecoder :: Environment.Decoder [Reporter]
reportersDecoder =
Environment.variable
Environment.Variable
{ Environment.name = "LOG_ENABLED_LOGGERS",
Environment.description = "Comma-separated list of logging destinations.",
Environment.defaultValue = "stdout-pretty"
}
(Environment.custom Environment.text reportersParser)
Parses reporters , maintaining the same order of reporters as the
-- `supportedReporters` list.
reportersParser :: Text -> Result Text [Reporter]
reportersParser reportersString = do
names <-
reportersString
|> Text.split ","
|> traverse parseLogger
|> map Set.fromList
supportedReporters
|> List.filter (\reporter -> Set.member (reporterName reporter) names)
|> Ok
parseLogger :: Text -> Result Text Text
parseLogger name =
let normalizedName = Text.trim (Text.toLower name)
supportedNames =
supportedReporters
|> map reporterName
|> Set.fromList
in if Set.member normalizedName supportedNames
then Ok normalizedName
else Err ("Unknown reporter: " ++ normalizedName)
| null | https://raw.githubusercontent.com/NoRedInk/haskell-libraries/b1a9bf27ba82c213b5ccee33abdee9b9896fdff5/nri-observability/src/Observability.hs | haskell | # LANGUAGE GADTs #
| A module dedicated to observability, that is reporting information about
what the program is doing in production to help us debugging it.
Specifically this module is dedicated to sending information that's already
Honeycomb. To learn more about how this information is collected check out the
contain observability data we have collected.
| A handler for reporting to logging/monitoring/observability platforms.
| `report` takes a span containing all the tracing information we
collected for a single request and then reports it to all platforms we
enabled when creating this handler.
| Function for creating an observability handler. The settings we pass in
determine which platforms we'll report information to.
| Initialize a reporter from settings, to get a handler for sending reports.
If a reporter fails with an exception here's what we'd like to be true:
- It doesn't affect other reporters (they don't get aborted or anything).
- The reporting error gets itself reported _somewhere_ in a way that's
relatively likely to succeed.
If any error sync or async is thrown during reporting, report
the failure to the 'backup reporter'.
If this reporter fails with a sync exception we do not want it
to abort other reporters, so we catch those exceptions. We've
already tried to report on the exception above so there's
nothing more we could be doing with the exception anyway.
| If a reporter fails with an exception we'd like to report that exception in
turn to a reporter. Because reporters take spans we turn the exception into a
span here.
| Some details about the span we were attempting to report when a reporting
failure happened. We're conservative with the information from the original
span we copy over here, in case some complexity somewhere in the original
span caused the report of it to fail. It's entirely likely the reporting
failure is unrelated to the reported span though. For example, reporting to
| A helper type that combines all the different functions a specific reporter
must implement in a single record.
We've defined this as a GADT so we don't need to expose the `handler` and
`settings` parameters on the type, meaning this type is defined as `Reporter`
rather than `Reporter settings handler`. This allows us to combine multiple
reporters in a list.
| Pick the reporter-specific settings from the global `Settings` type
defined in this module.
| Create a handler for this reporter. This function will be called
once when the application starts for each enabled reporter.
| Report a span to this reporter.
| A list containing all the reporters we support. Reporters are ordered in
increasing chance of failure, so we can pick the safest one for reporting on
failures in other reporters.
| Settings for all supported reporters.
reporter in the list is treated special: it will also report on
failures that take place while running any of the other reporters.
high likelihood of succeeding, for example because it logs to stdout
or a file.
| Each supported reporter has a settings entry below. We parse
settings even for reporters that aren't enabled. Because our
environment parser insists all variables have default values it's not
necessary to make up values for reporters we don't want enabled.
| Read 'Settings' from environment variables. Default variables will be used
in case no environment variable is set for an option.
`supportedReporters` list. |
been collected to external monitoring platforms , such as and
` Platform . Internal ` module in the ` nri - prelude ` package . That module also
defines and documents the ` TracingSpan ` type , which is the data structure we use to
module Observability
( report,
Handler,
Settings (..),
Reporter (..),
decoder,
handler,
)
where
import qualified Conduit
import qualified Control.Exception.Safe as Exception
import qualified Data.Aeson as Aeson
import qualified Environment
import qualified List
import qualified Platform
import qualified Reporter.Bugsnag as Bugsnag
import qualified Reporter.Dev as Dev
import qualified Reporter.File as File
import qualified Reporter.Honeycomb as Honeycomb
import qualified Set
import qualified Text
import Prelude (pure, traverse)
import qualified Prelude
newtype Handler = Handler
report :: Text -> Platform.TracingSpan -> Prelude.IO ()
}
deriving (Prelude.Semigroup, Prelude.Monoid)
handler :: Settings -> Conduit.Acquire Handler
handler settings = do
case enabledReporters settings of
[] -> Prelude.pure reportNothingHandler
firstReporter : otherReporters -> do
firstHandler <- toHandler reportNothingHandler settings firstReporter
otherHandlers <- traverse (toHandler firstHandler settings) otherReporters
Prelude.pure (Prelude.mconcat (firstHandler : otherHandlers))
reportNothingHandler :: Handler
reportNothingHandler = Handler (\_ _ -> Prelude.pure ())
toHandler :: Handler -> Settings -> Reporter -> Conduit.Acquire Handler
toHandler backup settings Reporter {reporterName, reporterSettings, reporterHandler, reporterReport} = do
handler' <-
reporterSettings settings
|> reporterHandler
|> map (Handler << reporterReport)
Prelude.pure
( Handler
( \requestId span ->
report handler' requestId span
|> ( \io ->
Exception.withException
io
( \err ->
err
|> reporterExceptionToTracingSpan reporterName span
|> report backup requestId
)
)
|> Exception.handleAny (\_ -> Prelude.pure ())
)
)
reporterExceptionToTracingSpan :: Text -> Platform.TracingSpan -> Exception.SomeException -> Platform.TracingSpan
reporterExceptionToTracingSpan reporterName originalTracingSpan exceptionDuringReporting =
Platform.emptyTracingSpan
{ Platform.name = "Failed to report span to " ++ reporterName,
Platform.succeeded = Platform.FailedWith exceptionDuringReporting,
Platform.started = Platform.finished originalTracingSpan,
Platform.finished = Platform.finished originalTracingSpan,
Platform.frame = Nothing,
Platform.details =
FailedToReportTracingSpan
(Platform.name originalTracingSpan)
(Platform.details originalTracingSpan)
|> Platform.toTracingSpanDetails
|> Just,
Platform.allocated = 0,
Platform.children = []
}
might fail if is down .
data FailedToReportTracingSpan = FailedToReportTracingSpan
{ originalTracingSpanName :: Text,
originalTracingSpanDetails :: Maybe Platform.SomeTracingSpanDetails
}
deriving (Generic)
instance Aeson.ToJSON FailedToReportTracingSpan
instance Platform.TracingSpanDetails FailedToReportTracingSpan
data Reporter where
Reporter ::
{ reporterName :: Text,
reporterSettings :: Settings -> settings,
reporterHandler :: settings -> Conduit.Acquire handler,
reporterReport :: handler -> Text -> Platform.TracingSpan -> Prelude.IO ()
} ->
Reporter
supportedReporters :: [Reporter]
supportedReporters =
[ Reporter "stdout" stdout fileHandler File.report,
Reporter "stdout-pretty" dev devHandler Dev.report,
Reporter "file" file fileHandler File.report,
Reporter "bugsnag" bugsnag bugsnagHandler Bugsnag.report,
Reporter "honeycomb" honeycomb honeycombHandler Honeycomb.report
]
fileHandler :: File.Settings -> Conduit.Acquire File.Handler
fileHandler settings = Conduit.mkAcquire (File.handler settings) File.cleanup
devHandler :: () -> Conduit.Acquire Dev.Handler
devHandler _ = Conduit.mkAcquire Dev.handler Dev.cleanup
bugsnagHandler :: Bugsnag.Settings -> Conduit.Acquire Bugsnag.Handler
bugsnagHandler settings = Conduit.liftIO (Bugsnag.handler settings)
honeycombHandler :: Honeycomb.Settings -> Conduit.Acquire Honeycomb.Handler
honeycombHandler settings = Conduit.liftIO (Honeycomb.handler settings)
data Settings = Settings
| The reporters that we send debugging information to . The first
Because of this its best if the first reporter is one that has a
enabledReporters :: [Reporter],
file :: File.Settings,
bugsnag :: Bugsnag.Settings,
honeycomb :: Honeycomb.Settings,
dev :: ()
}
stdout :: Settings -> File.Settings
stdout settings = (file settings) {File.logFile = "/dev/stdout"}
decoder :: Environment.Decoder Settings
decoder =
pure Settings
|> andMap reportersDecoder
|> andMap File.decoder
|> andMap Bugsnag.decoder
|> andMap Honeycomb.decoder
|> andMap (Prelude.pure ())
reportersDecoder :: Environment.Decoder [Reporter]
reportersDecoder =
Environment.variable
Environment.Variable
{ Environment.name = "LOG_ENABLED_LOGGERS",
Environment.description = "Comma-separated list of logging destinations.",
Environment.defaultValue = "stdout-pretty"
}
(Environment.custom Environment.text reportersParser)
Parses reporters , maintaining the same order of reporters as the
reportersParser :: Text -> Result Text [Reporter]
reportersParser reportersString = do
names <-
reportersString
|> Text.split ","
|> traverse parseLogger
|> map Set.fromList
supportedReporters
|> List.filter (\reporter -> Set.member (reporterName reporter) names)
|> Ok
parseLogger :: Text -> Result Text Text
parseLogger name =
let normalizedName = Text.trim (Text.toLower name)
supportedNames =
supportedReporters
|> map reporterName
|> Set.fromList
in if Set.member normalizedName supportedNames
then Ok normalizedName
else Err ("Unknown reporter: " ++ normalizedName)
|
3513c364281e144a30be76f1c85576ee3adeeb326d2e00598dfbfecca37c1a9e | c-cube/indexed-set | test.ml | #!/usr/bin/env ocaml
#use "topfind";;
#directory "_build";;
#load "indexed_set.cma";;
#require "ppx_deriving.std";;
#require "sequence";;
type person = { id: int; age: int; name: string } [@@deriving ord];;
module S = IxSet.Make(struct
type t = person
let compare = compare_person
end)
let idx_id = S.def_idx_int ~project:(fun {id}->id) ;;
let idx_age = S.def_idx_int ~project:(fun {age}->age) ;;
let idx_name = S.def_idx_string ~project:(fun {name}->name) ;;
let empty = S.make S.(Cons (idx_id, Cons (idx_age, Cons (idx_name, Nil)))) ;;
let p1 = {id=1; name="Jean-Charles Édouard" ; age=18} ;;
let p2 = {id=2; name="Chocolatine qui parle"; age=3};;
let set = S.of_list empty [p1; p2] ;;
assert (S.find ~idx:S.k0 1 set |> Sequence.to_list = [p1]);;
assert (S.find ~idx:S.k0 2 set |> Sequence.to_list = [p2]);;
assert (S.find ~idx:S.k1 3 set |> Sequence.to_list = [p2]);;
| null | https://raw.githubusercontent.com/c-cube/indexed-set/f8471bd546fa9a8e845041963dac38d19e0dbc29/test.ml | ocaml | #!/usr/bin/env ocaml
#use "topfind";;
#directory "_build";;
#load "indexed_set.cma";;
#require "ppx_deriving.std";;
#require "sequence";;
type person = { id: int; age: int; name: string } [@@deriving ord];;
module S = IxSet.Make(struct
type t = person
let compare = compare_person
end)
let idx_id = S.def_idx_int ~project:(fun {id}->id) ;;
let idx_age = S.def_idx_int ~project:(fun {age}->age) ;;
let idx_name = S.def_idx_string ~project:(fun {name}->name) ;;
let empty = S.make S.(Cons (idx_id, Cons (idx_age, Cons (idx_name, Nil)))) ;;
let p1 = {id=1; name="Jean-Charles Édouard" ; age=18} ;;
let p2 = {id=2; name="Chocolatine qui parle"; age=3};;
let set = S.of_list empty [p1; p2] ;;
assert (S.find ~idx:S.k0 1 set |> Sequence.to_list = [p1]);;
assert (S.find ~idx:S.k0 2 set |> Sequence.to_list = [p2]);;
assert (S.find ~idx:S.k1 3 set |> Sequence.to_list = [p2]);;
| |
d30ee44c4c17ba85e8effe46ab2d2b5219fbaf3f12d4f1360efa0e63d017b06c | PeterDWhite/Osker | Whence.hs | Copyright ( C ) , 2002 , 2003
Copyright ( c ) OHSU , 2002 , 2003
offset from whence
----------------------------------------------------------------------
offset from whence , i.e. a base for an offset
----------------------------------------------------------------------
-- Local imports
data Whence
= SeekSet -- Base is beginning of file
| SeedEnd -- Set position to end of file
| SeekCur -- Base is the current position
deriving (Eq, Ord, Enum, Show)
| null | https://raw.githubusercontent.com/PeterDWhite/Osker/301e1185f7c08c62c2929171cc0469a159ea802f/Posix/Whence.hs | haskell | --------------------------------------------------------------------
--------------------------------------------------------------------
Local imports
Base is beginning of file
Set position to end of file
Base is the current position | Copyright ( C ) , 2002 , 2003
Copyright ( c ) OHSU , 2002 , 2003
offset from whence
offset from whence , i.e. a base for an offset
data Whence
deriving (Eq, Ord, Enum, Show)
|
5b0c13ef7bc69050734a606f4c0b87b848e2be53c711511c3e9798d0ee80c72f | haskell-openal/OpenAL | Format.hs | {-# OPTIONS_HADDOCK hide #-}
--------------------------------------------------------------------------------
-- |
-- Module : Sound.OpenAL.AL.Format
Copyright : ( c ) 2003 - 2016
-- License : BSD3
--
Maintainer : < >
-- Stability : stable
-- Portability : portable
--
This is a purely internal module for ( un-)marshaling Format .
--
--------------------------------------------------------------------------------
module Sound.OpenAL.AL.Format (
Format(..), marshalFormat, unmarshalFormat
) where
import Sound.OpenAL.AL.BasicTypes
import Sound.OpenAL.Constants
--------------------------------------------------------------------------------
-- | Valid sound formats. An implementation may expose other formats, see
" Sound . " for information on determining if additional
-- formats are supported.
data Format =
Mono8
| Mono16
| Stereo8
| Stereo16
deriving ( Eq, Ord, Show )
marshalFormat :: Format -> ALenum
marshalFormat x = case x of
Mono8 -> al_FORMAT_MONO8
Mono16 -> al_FORMAT_MONO16
Stereo8 -> al_FORMAT_STEREO8
Stereo16 -> al_FORMAT_STEREO16
unmarshalFormat :: ALenum -> Format
unmarshalFormat x
| x == al_FORMAT_MONO8 = Mono8
| x == al_FORMAT_MONO16 = Mono16
| x == al_FORMAT_STEREO8 = Stereo8
| x == al_FORMAT_STEREO16 = Stereo16
| otherwise = error ("unmarshalFormat: illegal value " ++ show x)
| null | https://raw.githubusercontent.com/haskell-openal/OpenAL/5131984f172dffc43ca8b482f215d120523fb137/src/Sound/OpenAL/AL/Format.hs | haskell | # OPTIONS_HADDOCK hide #
------------------------------------------------------------------------------
|
Module : Sound.OpenAL.AL.Format
License : BSD3
Stability : stable
Portability : portable
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Valid sound formats. An implementation may expose other formats, see
formats are supported. | Copyright : ( c ) 2003 - 2016
Maintainer : < >
This is a purely internal module for ( un-)marshaling Format .
module Sound.OpenAL.AL.Format (
Format(..), marshalFormat, unmarshalFormat
) where
import Sound.OpenAL.AL.BasicTypes
import Sound.OpenAL.Constants
" Sound . " for information on determining if additional
data Format =
Mono8
| Mono16
| Stereo8
| Stereo16
deriving ( Eq, Ord, Show )
marshalFormat :: Format -> ALenum
marshalFormat x = case x of
Mono8 -> al_FORMAT_MONO8
Mono16 -> al_FORMAT_MONO16
Stereo8 -> al_FORMAT_STEREO8
Stereo16 -> al_FORMAT_STEREO16
unmarshalFormat :: ALenum -> Format
unmarshalFormat x
| x == al_FORMAT_MONO8 = Mono8
| x == al_FORMAT_MONO16 = Mono16
| x == al_FORMAT_STEREO8 = Stereo8
| x == al_FORMAT_STEREO16 = Stereo16
| otherwise = error ("unmarshalFormat: illegal value " ++ show x)
|
878f8d19485d56132431d6758a0b33f7b6c18d4852970956ba8e3f5c4b54f533 | input-output-hk/hydra | Main.hs | import Hydra.Prelude hiding (catch)
import Data.ByteString (hPut)
import Data.Fixed (Centi)
import Hydra.Cardano.Api (Lovelace (Lovelace), serialiseToRawBytesHexText)
import Hydra.Contract (ScriptInfo (..), scriptInfo)
import Hydra.Ledger.Cardano.Evaluate (maxCpu, maxMem, maxTxSize)
import Options.Applicative (
Parser,
ParserInfo,
execParser,
fullDesc,
header,
help,
helper,
info,
long,
metavar,
progDesc,
short,
strOption,
)
import Plutus.Orphans ()
import System.Directory (createDirectoryIfMissing, doesDirectoryExist)
import System.FilePath ((</>))
import System.IO.Unsafe (unsafePerformIO)
import TxCost (
computeAbortCost,
computeCloseCost,
computeCollectComCost,
computeCommitCost,
computeContestCost,
computeFanOutCost,
computeInitCost,
)
newtype Options = Options {outputDirectory :: Maybe FilePath}
txCostOptionsParser :: Parser Options
txCostOptionsParser =
Options
<$> optional
( strOption
( long "output-directory"
<> short 'o'
<> metavar "DIR"
<> help
"Directory where benchmark files should be output to. \
\ If none is given, output is sent to stdout"
)
)
logFilterOptions :: ParserInfo Options
logFilterOptions =
info
(txCostOptionsParser <**> helper)
( fullDesc
<> progDesc
"Runs benchmarks assessing the execution cost of various on-chain \
\ constructs: Some specific Plutus code, all OCV transactions,... \
\ The output is valid markdown that can be used as is to be processed \
\ and published."
<> header "tx-cost - Hydra OCV Code Benchmarks"
)
main :: IO ()
main =
execParser logFilterOptions >>= \case
Options{outputDirectory = Nothing} -> writeTransactionCostMarkdown stdout
Options{outputDirectory = Just outputDir} -> do
unlessM (doesDirectoryExist outputDir) $ createDirectoryIfMissing True outputDir
withFile (outputDir </> "transaction-cost.md") WriteMode writeTransactionCostMarkdown
writeTransactionCostMarkdown :: Handle -> IO ()
writeTransactionCostMarkdown hdl = do
initC <- costOfInit
commitC <- costOfCommit
collectComC <- costOfCollectCom
closeC <- costOfClose
contestC <- costOfContest
abortC <- costOfAbort
fanoutC <- costOfFanOut
hPut hdl $
encodeUtf8 $
unlines $
pageHeader
<> scriptSizes
<> intersperse
""
[ initC
, commitC
, collectComC
, closeC
, contestC
, abortC
, fanoutC
]
-- NOTE: Github Actions CI depends on the number of header lines, see
-- .github/workflows/ci.yaml
pageHeader :: [Text]
pageHeader =
[ "--- "
, "sidebar_label: 'Transactions Costs' "
, "sidebar_position: 3 "
, "--- "
, ""
, "# Transactions Costs "
, ""
, "Sizes and execution budgets for Hydra protocol transactions. Note that unlisted parameters are currently using `arbitrary` values and results are not fully deterministic and comparable to previous runs."
, ""
, "| Metadata | |"
, "| :--- | :--- |"
, "| _Generated at_ | " <> show now <> " |"
, "| _Max. memory units_ | " <> show maxMem <> " |"
, "| _Max. CPU units_ | " <> show maxCpu <> " |"
, "| _Max. tx size (kB)_ | " <> show maxTxSize <> " |"
, ""
]
# NOINLINE now #
now :: UTCTime
now = unsafePerformIO getCurrentTime
scriptSizes :: [Text]
scriptSizes =
[ "## Script summary"
, ""
, "| Name | Hash | Size (Bytes) "
, "| :----- | :--- | -----------: "
, "| " <> "μHead" <> " | N/A | " <> show mintingScriptSize <> " | "
, "| " <> "νInitial" <> " | " <> serialiseToRawBytesHexText initialScriptHash <> " | " <> show initialScriptSize <> " | "
, "| " <> "νCommit" <> " | " <> serialiseToRawBytesHexText commitScriptHash <> " | " <> show commitScriptSize <> " | "
, "| " <> "νHead" <> " | " <> serialiseToRawBytesHexText headScriptHash <> " | " <> show headScriptSize <> " | "
]
where
ScriptInfo
{ mintingScriptSize
, initialScriptHash
, initialScriptSize
, commitScriptHash
, commitScriptSize
, headScriptHash
, headScriptSize
} = scriptInfo
costOfInit :: IO Text
costOfInit = markdownInitCost <$> computeInitCost
where
markdownInitCost stats =
unlines $
[ "## Cost of Init Transaction"
, ""
, "| Parties | Tx size | % max Mem | % max CPU | Min fee ₳ |"
, "| :------ | ------: | --------: | --------: | --------: |"
]
<> fmap
( \(numParties, txSize, mem, cpu, Lovelace minFee) ->
"| " <> show numParties
<> "| "
<> show txSize
<> " | "
<> show (mem `percentOf` maxMem)
<> " | "
<> show (cpu `percentOf` maxCpu)
<> " | "
<> show (realToFrac minFee / 1_000_000 :: Centi)
<> " |"
)
stats
costOfCommit :: IO Text
costOfCommit = markdownCommitCost <$> computeCommitCost
where
markdownCommitCost stats =
unlines $
[ "## Cost of Commit Transaction"
, " Currently only one UTxO per commit allowed (this is about to change soon)"
, ""
, "| UTxO | Tx size | % max Mem | % max CPU | Min fee ₳ |"
, "| :--- | ------: | --------: | --------: | --------: |"
]
<> map
( \(ulen, txSize, mem, cpu, Lovelace minFee) ->
"| " <> show ulen
<> "| "
<> show txSize
<> " | "
<> show (mem `percentOf` maxMem)
<> " | "
<> show (cpu `percentOf` maxCpu)
<> " | "
<> show (realToFrac minFee / 1_000_000 :: Centi)
<> " |"
)
stats
costOfCollectCom :: IO Text
costOfCollectCom = markdownCollectComCost <$> computeCollectComCost
where
markdownCollectComCost stats =
unlines $
[ "## Cost of CollectCom Transaction"
, ""
, "| Parties | UTxO (bytes) |Tx size | % max Mem | % max CPU | Min fee ₳ |"
, "| :------ | :----------- |------: | --------: | --------: | --------: |"
]
<> fmap
( \(numParties, utxoSize, txSize, mem, cpu, Lovelace minFee) ->
"| " <> show numParties
<> " | "
<> show utxoSize
<> " | "
<> show txSize
<> " | "
<> show (mem `percentOf` maxMem)
<> " | "
<> show (cpu `percentOf` maxCpu)
<> " | "
<> show (realToFrac minFee / 1_000_000 :: Centi)
<> " |"
)
stats
costOfClose :: IO Text
costOfClose = markdownClose <$> computeCloseCost
where
markdownClose stats =
unlines $
[ "## Cost of Close Transaction"
, ""
, "| Parties | Tx size | % max Mem | % max CPU | Min fee ₳ |"
, "| :------ | ------: | --------: | --------: | --------: |"
]
<> fmap
( \(numParties, txSize, mem, cpu, Lovelace minFee) ->
"| " <> show numParties
<> "| "
<> show txSize
<> " | "
<> show (mem `percentOf` maxMem)
<> " | "
<> show (cpu `percentOf` maxCpu)
<> " | "
<> show (realToFrac minFee / 1_000_000 :: Centi)
<> " |"
)
stats
costOfContest :: IO Text
costOfContest = markdownContest <$> computeContestCost
where
markdownContest stats =
unlines $
[ "## Cost of Contest Transaction"
, ""
, "| Parties | Tx size | % max Mem | % max CPU | Min fee ₳ |"
, "| :------ | ------: | --------: | --------: | --------: |"
]
<> fmap
( \(numParties, txSize, mem, cpu, Lovelace minFee) ->
"| " <> show numParties
<> "| "
<> show txSize
<> " | "
<> show (mem `percentOf` maxMem)
<> " | "
<> show (cpu `percentOf` maxCpu)
<> " | "
<> show (realToFrac minFee / 1_000_000 :: Centi)
<> " |"
)
stats
costOfAbort :: IO Text
costOfAbort = markdownAbortCost <$> computeAbortCost
where
markdownAbortCost stats =
unlines $
[ "## Cost of Abort Transaction"
, "Some variation because of random mixture of still initial and already committed outputs."
, ""
, "| Parties | Tx size | % max Mem | % max CPU | Min fee ₳ |"
, "| :------ | ------: | --------: | --------: | --------: |"
]
<> fmap
( \(numParties, txSize, mem, cpu, Lovelace minFee) ->
"| " <> show numParties
<> "| "
<> show txSize
<> " | "
<> show (mem `percentOf` maxMem)
<> " | "
<> show (cpu `percentOf` maxCpu)
<> " | "
<> show (realToFrac minFee / 1_000_000 :: Centi)
<> " |"
)
stats
costOfFanOut :: IO Text
costOfFanOut = markdownFanOutCost <$> computeFanOutCost
where
markdownFanOutCost stats =
unlines $
[ "## Cost of FanOut Transaction"
, "Involves spending head output and burning head tokens. Uses ada-only UTxO for better comparability."
, ""
, "| Parties | UTxO | UTxO (bytes) | Tx size | % max Mem | % max CPU | Min fee ₳ |"
, "| :------ | :---- | :----------- | ------: | --------: | --------: | --------: |"
]
<> fmap
( \(parties, numElems, utxoSize, txSize, mem, cpu, Lovelace minFee) ->
"| " <> show parties
<> " | "
<> show numElems
<> " | "
<> show utxoSize
<> " | "
<> show txSize
<> " | "
<> show (mem `percentOf` maxMem)
<> " | "
<> show (cpu `percentOf` maxCpu)
<> " | "
<> show (realToFrac minFee / 1_000_000 :: Centi)
<> " |"
)
stats
percentOf :: (Real a, Real b) => a -> b -> Centi
part `percentOf` total =
100 * realToFrac part / realToFrac total
| null | https://raw.githubusercontent.com/input-output-hk/hydra/130301c7f30a39d6d3419fed08864be0e34960e1/hydra-node/exe/tx-cost/Main.hs | haskell | NOTE: Github Actions CI depends on the number of header lines, see
.github/workflows/ci.yaml | import Hydra.Prelude hiding (catch)
import Data.ByteString (hPut)
import Data.Fixed (Centi)
import Hydra.Cardano.Api (Lovelace (Lovelace), serialiseToRawBytesHexText)
import Hydra.Contract (ScriptInfo (..), scriptInfo)
import Hydra.Ledger.Cardano.Evaluate (maxCpu, maxMem, maxTxSize)
import Options.Applicative (
Parser,
ParserInfo,
execParser,
fullDesc,
header,
help,
helper,
info,
long,
metavar,
progDesc,
short,
strOption,
)
import Plutus.Orphans ()
import System.Directory (createDirectoryIfMissing, doesDirectoryExist)
import System.FilePath ((</>))
import System.IO.Unsafe (unsafePerformIO)
import TxCost (
computeAbortCost,
computeCloseCost,
computeCollectComCost,
computeCommitCost,
computeContestCost,
computeFanOutCost,
computeInitCost,
)
newtype Options = Options {outputDirectory :: Maybe FilePath}
txCostOptionsParser :: Parser Options
txCostOptionsParser =
Options
<$> optional
( strOption
( long "output-directory"
<> short 'o'
<> metavar "DIR"
<> help
"Directory where benchmark files should be output to. \
\ If none is given, output is sent to stdout"
)
)
logFilterOptions :: ParserInfo Options
logFilterOptions =
info
(txCostOptionsParser <**> helper)
( fullDesc
<> progDesc
"Runs benchmarks assessing the execution cost of various on-chain \
\ constructs: Some specific Plutus code, all OCV transactions,... \
\ The output is valid markdown that can be used as is to be processed \
\ and published."
<> header "tx-cost - Hydra OCV Code Benchmarks"
)
main :: IO ()
main =
execParser logFilterOptions >>= \case
Options{outputDirectory = Nothing} -> writeTransactionCostMarkdown stdout
Options{outputDirectory = Just outputDir} -> do
unlessM (doesDirectoryExist outputDir) $ createDirectoryIfMissing True outputDir
withFile (outputDir </> "transaction-cost.md") WriteMode writeTransactionCostMarkdown
writeTransactionCostMarkdown :: Handle -> IO ()
writeTransactionCostMarkdown hdl = do
initC <- costOfInit
commitC <- costOfCommit
collectComC <- costOfCollectCom
closeC <- costOfClose
contestC <- costOfContest
abortC <- costOfAbort
fanoutC <- costOfFanOut
hPut hdl $
encodeUtf8 $
unlines $
pageHeader
<> scriptSizes
<> intersperse
""
[ initC
, commitC
, collectComC
, closeC
, contestC
, abortC
, fanoutC
]
pageHeader :: [Text]
pageHeader =
[ "--- "
, "sidebar_label: 'Transactions Costs' "
, "sidebar_position: 3 "
, "--- "
, ""
, "# Transactions Costs "
, ""
, "Sizes and execution budgets for Hydra protocol transactions. Note that unlisted parameters are currently using `arbitrary` values and results are not fully deterministic and comparable to previous runs."
, ""
, "| Metadata | |"
, "| :--- | :--- |"
, "| _Generated at_ | " <> show now <> " |"
, "| _Max. memory units_ | " <> show maxMem <> " |"
, "| _Max. CPU units_ | " <> show maxCpu <> " |"
, "| _Max. tx size (kB)_ | " <> show maxTxSize <> " |"
, ""
]
# NOINLINE now #
now :: UTCTime
now = unsafePerformIO getCurrentTime
scriptSizes :: [Text]
scriptSizes =
[ "## Script summary"
, ""
, "| Name | Hash | Size (Bytes) "
, "| :----- | :--- | -----------: "
, "| " <> "μHead" <> " | N/A | " <> show mintingScriptSize <> " | "
, "| " <> "νInitial" <> " | " <> serialiseToRawBytesHexText initialScriptHash <> " | " <> show initialScriptSize <> " | "
, "| " <> "νCommit" <> " | " <> serialiseToRawBytesHexText commitScriptHash <> " | " <> show commitScriptSize <> " | "
, "| " <> "νHead" <> " | " <> serialiseToRawBytesHexText headScriptHash <> " | " <> show headScriptSize <> " | "
]
where
ScriptInfo
{ mintingScriptSize
, initialScriptHash
, initialScriptSize
, commitScriptHash
, commitScriptSize
, headScriptHash
, headScriptSize
} = scriptInfo
costOfInit :: IO Text
costOfInit = markdownInitCost <$> computeInitCost
where
markdownInitCost stats =
unlines $
[ "## Cost of Init Transaction"
, ""
, "| Parties | Tx size | % max Mem | % max CPU | Min fee ₳ |"
, "| :------ | ------: | --------: | --------: | --------: |"
]
<> fmap
( \(numParties, txSize, mem, cpu, Lovelace minFee) ->
"| " <> show numParties
<> "| "
<> show txSize
<> " | "
<> show (mem `percentOf` maxMem)
<> " | "
<> show (cpu `percentOf` maxCpu)
<> " | "
<> show (realToFrac minFee / 1_000_000 :: Centi)
<> " |"
)
stats
costOfCommit :: IO Text
costOfCommit = markdownCommitCost <$> computeCommitCost
where
markdownCommitCost stats =
unlines $
[ "## Cost of Commit Transaction"
, " Currently only one UTxO per commit allowed (this is about to change soon)"
, ""
, "| UTxO | Tx size | % max Mem | % max CPU | Min fee ₳ |"
, "| :--- | ------: | --------: | --------: | --------: |"
]
<> map
( \(ulen, txSize, mem, cpu, Lovelace minFee) ->
"| " <> show ulen
<> "| "
<> show txSize
<> " | "
<> show (mem `percentOf` maxMem)
<> " | "
<> show (cpu `percentOf` maxCpu)
<> " | "
<> show (realToFrac minFee / 1_000_000 :: Centi)
<> " |"
)
stats
costOfCollectCom :: IO Text
costOfCollectCom = markdownCollectComCost <$> computeCollectComCost
where
markdownCollectComCost stats =
unlines $
[ "## Cost of CollectCom Transaction"
, ""
, "| Parties | UTxO (bytes) |Tx size | % max Mem | % max CPU | Min fee ₳ |"
, "| :------ | :----------- |------: | --------: | --------: | --------: |"
]
<> fmap
( \(numParties, utxoSize, txSize, mem, cpu, Lovelace minFee) ->
"| " <> show numParties
<> " | "
<> show utxoSize
<> " | "
<> show txSize
<> " | "
<> show (mem `percentOf` maxMem)
<> " | "
<> show (cpu `percentOf` maxCpu)
<> " | "
<> show (realToFrac minFee / 1_000_000 :: Centi)
<> " |"
)
stats
costOfClose :: IO Text
costOfClose = markdownClose <$> computeCloseCost
where
markdownClose stats =
unlines $
[ "## Cost of Close Transaction"
, ""
, "| Parties | Tx size | % max Mem | % max CPU | Min fee ₳ |"
, "| :------ | ------: | --------: | --------: | --------: |"
]
<> fmap
( \(numParties, txSize, mem, cpu, Lovelace minFee) ->
"| " <> show numParties
<> "| "
<> show txSize
<> " | "
<> show (mem `percentOf` maxMem)
<> " | "
<> show (cpu `percentOf` maxCpu)
<> " | "
<> show (realToFrac minFee / 1_000_000 :: Centi)
<> " |"
)
stats
costOfContest :: IO Text
costOfContest = markdownContest <$> computeContestCost
where
markdownContest stats =
unlines $
[ "## Cost of Contest Transaction"
, ""
, "| Parties | Tx size | % max Mem | % max CPU | Min fee ₳ |"
, "| :------ | ------: | --------: | --------: | --------: |"
]
<> fmap
( \(numParties, txSize, mem, cpu, Lovelace minFee) ->
"| " <> show numParties
<> "| "
<> show txSize
<> " | "
<> show (mem `percentOf` maxMem)
<> " | "
<> show (cpu `percentOf` maxCpu)
<> " | "
<> show (realToFrac minFee / 1_000_000 :: Centi)
<> " |"
)
stats
costOfAbort :: IO Text
costOfAbort = markdownAbortCost <$> computeAbortCost
where
markdownAbortCost stats =
unlines $
[ "## Cost of Abort Transaction"
, "Some variation because of random mixture of still initial and already committed outputs."
, ""
, "| Parties | Tx size | % max Mem | % max CPU | Min fee ₳ |"
, "| :------ | ------: | --------: | --------: | --------: |"
]
<> fmap
( \(numParties, txSize, mem, cpu, Lovelace minFee) ->
"| " <> show numParties
<> "| "
<> show txSize
<> " | "
<> show (mem `percentOf` maxMem)
<> " | "
<> show (cpu `percentOf` maxCpu)
<> " | "
<> show (realToFrac minFee / 1_000_000 :: Centi)
<> " |"
)
stats
costOfFanOut :: IO Text
costOfFanOut = markdownFanOutCost <$> computeFanOutCost
where
markdownFanOutCost stats =
unlines $
[ "## Cost of FanOut Transaction"
, "Involves spending head output and burning head tokens. Uses ada-only UTxO for better comparability."
, ""
, "| Parties | UTxO | UTxO (bytes) | Tx size | % max Mem | % max CPU | Min fee ₳ |"
, "| :------ | :---- | :----------- | ------: | --------: | --------: | --------: |"
]
<> fmap
( \(parties, numElems, utxoSize, txSize, mem, cpu, Lovelace minFee) ->
"| " <> show parties
<> " | "
<> show numElems
<> " | "
<> show utxoSize
<> " | "
<> show txSize
<> " | "
<> show (mem `percentOf` maxMem)
<> " | "
<> show (cpu `percentOf` maxCpu)
<> " | "
<> show (realToFrac minFee / 1_000_000 :: Centi)
<> " |"
)
stats
percentOf :: (Real a, Real b) => a -> b -> Centi
part `percentOf` total =
100 * realToFrac part / realToFrac total
|
71ba0751e7439e91e15b239339ecf7098c34d47ca0fff168870aeaafa460a612 | spechub/Hets | HTkGenericATP.hs | # LANGUAGE FlexibleContexts #
|
Module : ./GUI / HTkGenericATP.hs
Description : Generic Prover GUI .
Copyright : ( c ) , , Uni Bremen 2006
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : needs POSIX
Generic GUI for automatic theorem provers . Based upon former SPASS Prover GUI .
Module : ./GUI/HTkGenericATP.hs
Description : Generic Prover GUI.
Copyright : (c) Klaus Luettich, Rainer Grabbe, Uni Bremen 2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : needs POSIX
Generic GUI for automatic theorem provers. Based upon former SPASS Prover GUI.
-}
module GUI.HTkGenericATP (genericATPgui) where
import Logic.Prover
import qualified Common.AS_Annotation as AS_Anno
import qualified Data.Map as Map
import Common.Utils (getEnvSave, readMaybe)
import Common.Result
import Data.List
import Data.Maybe
import qualified Control.Exception as Exception
import qualified Control.Concurrent as Conc
import qualified Control.Monad.Fail as Fail
import HTk.Toolkit.SpinButton
import HTk.Toolkit.Separator
import HTk.Devices.XSelection
import HTk.Widgets.Space
import GUI.Utils
import GUI.HTkUtils hiding (createTextSaveDisplay, createTextDisplay)
import Interfaces.GenericATPState
import Proofs.BatchProcessing
{- |
Utility function to set the time limit of a Config.
For values <= 0 a default value is used.
-}
setTimeLimit :: Int -> GenericConfig proofTree -> GenericConfig proofTree
setTimeLimit n c = c { timeLimit = if n > 0 then Just n else Nothing }
{- |
Utility function to set the extra options of a Config.
-}
setExtraOpts :: [String] -> GenericConfig proofTree -> GenericConfig proofTree
setExtraOpts opts c = c { extraOpts = opts }
-- ** Constants
-- ** Defining the view
{- |
Colors used by the GUI to indicate the status of a goal.
-}
data ProofStatusColour
-- | Proved
= Green
-- | Proved, but theory is inconsistent
| Brown
-- | Disproved
| Red
-- | Open
| Black
-- | Running
| Blue
deriving (Bounded, Enum, Show)
{- |
Generates a ('ProofStatusColour', 'String') tuple representing a Proved proof
status.
-}
statusProved :: (ProofStatusColour, String)
statusProved = (Green, "Proved")
{- |
Generates a ('ProofStatusColour', 'String') tuple representing a Proved
(but inconsistent) proof status.
-}
statusProvedButInconsistent :: (ProofStatusColour, String)
statusProvedButInconsistent = (Brown, "Proved/Inconsistent")
{- |
Generates a ('ProofStatusColour', 'String') tuple representing a Disproved
proof status.
-}
statusDisproved :: (ProofStatusColour, String)
statusDisproved = (Red, "Disproved")
|
Generates a ( ' ProofStatusColour ' , ' String ' ) tuple representing an Open proof
status .
Generates a ('ProofStatusColour', 'String') tuple representing an Open proof
status.
-}
statusOpen :: (ProofStatusColour, String)
statusOpen = (Black, "Open")
|
Generates a ( ' ProofStatusColour ' , ' String ' ) tuple representing an Open proof
status in case the time limit has been exceeded .
Generates a ('ProofStatusColour', 'String') tuple representing an Open proof
status in case the time limit has been exceeded.
-}
statusOpenTExceeded :: (ProofStatusColour, String)
statusOpenTExceeded = (Black, "Open (Time is up!)")
{- |
Generates a ('ProofStatusColour', 'String') tuple representing a Running proof
status.
-}
statusRunning :: (ProofStatusColour, String)
statusRunning = (Blue, "Running")
|
Converts a ' ProofStatus ' into a ( ' ProofStatusColour ' , ' String ' ) tuple to be
displayed by the GUI .
Converts a 'ProofStatus' into a ('ProofStatusColour', 'String') tuple to be
displayed by the GUI.
-}
toGuiStatus :: GenericConfig proofTree -- ^ current prover configuration
-> ProofStatus a -- ^ status to convert
-> (ProofStatusColour, String)
toGuiStatus cf st = case goalStatus st of
Proved c -> if c then statusProved else statusProvedButInconsistent
Disproved -> statusDisproved
_ -> if timeLimitExceeded cf
then statusOpenTExceeded
else statusOpen
-- | stores widgets of an options frame and the frame itself
data OpFrame = OpFrame { ofFrame :: Frame
, ofTimeSpinner :: SpinButton
, ofTimeEntry :: Entry Int
, ofOptionsEntry :: Entry String
}
|
Generates a list of ' GUI.HTkUtils . LBGoalView ' representations of all goals
from a ' GenericATPState . ' .
Generates a list of 'GUI.HTkUtils.LBGoalView' representations of all goals
from a 'GenericATPState.GenericState'.
-}
goalsView
:: GenericState sentence proofTree pst -- ^ current global prover state
-> [LBGoalView] -- ^ resulting ['LBGoalView'] list
goalsView s = map ((\ g ->
let cfg = Map.lookup g (configsMap s)
statind = maybe LBIndicatorOpen
(indicatorFromProofStatus . proofStatus)
cfg
in
LBGoalView {statIndicator = statind,
goalDescription = g})
. AS_Anno.senAttr) $ goalsList s
-- * GUI Implementation
-- ** Utility Functions
{- |
Retrieves the value of the time limit 'Entry'. Ignores invalid input.
-}
getValueSafe
^ default time limt
-> Entry Int -- ^ time limit 'Entry'
-> IO Int -- ^ user-requested time limit or default for errors
getValueSafe defaultTimeLimit timeEntry =
Exception.catch (getValue timeEntry :: IO Int)
$ \ e -> do
putStrLn $ "Warning: Error " ++ show (e :: Exception.SomeException)
++ " was ignored"
return defaultTimeLimit
{- |
reads passed ENV-variable and if it exists and has an Int-value this value is
returned otherwise the value of 'batchTimeLimit' is returned.
-}
getBatchTimeLimit :: String -- ^ ENV-variable containing batch time limit
-> IO Int
getBatchTimeLimit env =
getEnvSave batchTimeLimit env readMaybe
{- |
Text displayed by the batch mode window.
-}
^ batch time limt
-> Int -- ^ total number of goals
-> Int -- ^ number of that have been processed
-> String
batchInfoText tl gTotal gDone =
let totalSecs = (gTotal - gDone) * tl
(remMins, secs) = divMod totalSecs 60
(hours, mins) = divMod remMins 60
in
"Batch mode running.\n" ++
show gDone ++ "/" ++ show gTotal ++ " goals processed.\n" ++
"At most " ++ show hours ++ "h " ++ show mins ++ "m " ++ show secs
++ "s remaining."
-- ** Callbacks
{- |
Updates the display of the status of the current goal.
-}
updateDisplay
:: GenericState sentence proofTree pst
-- ^ current global prover state
^ set to ' True ' if you want the ' ListBox ' to be updated
-> ListBox String
^ ' ListBox ' displaying the status of all goals ( see ' goalsView ' )
-> Label
{- ^ 'Label' displaying the status of the currently selected goal
(see 'toGuiStatus') -}
-> Entry Int -- ^ 'Entry' containing the time limit of the current goal
-> Entry String -- ^ 'Entry' containing the extra options
-> ListBox String
^ ' ListBox ' displaying all axioms used to prove a goal ( if any )
-> IO ()
updateDisplay st updateLb goalsLb statusLabel timeEntry optionsEntry axiomsLb =
the code in comments only works with an updated uni version that
will be installed when switching to
will be installed when switching to ghc-6.6.1 -}
do
when updateLb (do
(offScreen, _) <- view Vertical goalsLb
populateGoalsListBox goalsLb (goalsView st)
moveto Vertical goalsLb offScreen
)
maybe (return ())
(\ go ->
let mprfst = Map.lookup go (configsMap st)
cf = Map.findWithDefault
(error "GUI.GenericATP.updateDisplay")
go (configsMap st)
t' = fromMaybe guiDefaultTimeLimit (timeLimit cf)
opts' = unwords (extraOpts cf)
(color, label) = maybe statusOpen
(toGuiStatus cf . proofStatus)
mprfst
usedAxs = maybe [] (usedAxioms . proofStatus) mprfst
in do
statusLabel # text label
statusLabel # foreground (show color)
timeEntry # value t'
optionsEntry # value opts'
axiomsLb # value (usedAxs :: [String])
return ())
(currentGoal st)
newOptionsFrame
:: Container par
=> par -- ^ the parent container
-> (Entry Int -> Spin -> IO a)
^ Function called by pressing one spin button
-> Bool -- ^ extra options input line
-> IO OpFrame
newOptionsFrame con updateFn isExtraOps = do
right <- newFrame con []
-- contents of newOptionsFrame
l1 <- newLabel right [text "Options:"]
pack l1 [Anchor NorthWest]
opFrame <- newFrame right []
pack opFrame [Expand On, Fill X, Anchor North]
spacer <- newLabel opFrame [text " "]
pack spacer [Side AtLeft]
opFrame2 <- newVBox opFrame []
pack opFrame2 [Expand On, Fill X, Anchor NorthWest]
timeLimitFrame <- newFrame opFrame2 []
pack timeLimitFrame [Expand On, Fill X, Anchor West]
l2 <- newLabel timeLimitFrame [text "TimeLimit"]
pack l2 [Side AtLeft]
extra HBox for time limit display
timeLimitLine <- newHBox timeLimitFrame []
pack timeLimitLine [Expand On, Side AtRight, Anchor East]
timeEntry <- newEntry timeLimitLine [width 18,
value guiDefaultTimeLimit]
pack (timeEntry :: Entry Int) []
timeSpinner <- newSpinButton timeLimitLine (updateFn timeEntry) []
pack timeSpinner []
l3 <- newLabel opFrame2 [text "Extra Options:"]
when isExtraOps $
pack l3 [Anchor West]
optionsEntry <- newEntry opFrame2 [width 37]
when isExtraOps $
pack (optionsEntry :: Entry String) [Fill X, PadX (cm 0.1)]
return OpFrame
{ ofFrame = right
, ofTimeSpinner = timeSpinner
, ofTimeEntry = timeEntry
, ofOptionsEntry = optionsEntry }
-- ** Main GUI
|
Invokes the prover GUI . Users may start the batch prover run on all goals ,
or use a detailed GUI for proving each goal manually .
Invokes the prover GUI. Users may start the batch prover run on all goals,
or use a detailed GUI for proving each goal manually.
-}
genericATPgui
:: (Show sentence, Ord proofTree, Ord sentence)
=> ATPFunctions sign sentence mor proofTree pst
-- ^ prover specific functions
-> Bool -- ^ prover supports extra options
-> String -- ^ prover name
-> String -- ^ theory name
-> Theory sign sentence proofTree
-- ^ theory with signature and sentences
-> [FreeDefMorphism sentence mor] -- ^ freeness constraints
-> proofTree -- ^ initial empty proofTree
-> IO [ProofStatus proofTree] -- ^ proof status for each goal
genericATPgui atpFun isExtraOptions prName thName th freedefs pt = do
-- create initial backing data structure
let initState = initialGenericState prName
(initialProverState atpFun)
(atpTransSenName atpFun) th freedefs pt
stateMVar <- Conc.newMVar initState
batchTLimit <- getBatchTimeLimit $ batchTimeEnv atpFun
-- main window
main <- createToplevel [text $ thName ++ " - " ++ prName ++ " Prover"]
pack main [Expand On, Fill Both]
-- VBox for the whole window
b <- newVBox main []
pack b [Expand On, Fill Both]
HBox for the upper part ( goals on the left , options / results on the right )
b2 <- newHBox b []
pack b2 [Expand On, Fill Both]
-- left frame (goals)
left <- newFrame b2 []
pack left [Expand On, Fill Both]
b3 <- newVBox left []
pack b3 [Expand On, Fill Both]
l0 <- newLabel b3 [text "Goals:"]
pack l0 [Anchor NorthWest]
lbFrame <- newFrame b3 []
pack lbFrame [Expand On, Fill Both]
lb <- newListBox lbFrame [bg "white", exportSelection False,
selectMode Single, height 15] :: IO (ListBox String)
pack lb [Expand On, Side AtLeft, Fill Both]
sb <- newScrollBar lbFrame []
pack sb [Expand On, Side AtRight, Fill Y, Anchor West]
lb # scrollbar Vertical sb
-- right frame (options/results)
OpFrame { ofFrame = right
, ofTimeSpinner = timeSpinner
, ofTimeEntry = timeEntry
, ofOptionsEntry = optionsEntry}
<- newOptionsFrame b2
(\ timeEntry sp -> synchronize main
(do
st <- Conc.readMVar stateMVar
maybe noGoalSelected
(\ goal ->
do
curEntTL <- getValueSafe guiDefaultTimeLimit timeEntry
s <- Conc.takeMVar stateMVar
let sEnt = s {configsMap =
adjustOrSetConfig
(setTimeLimit curEntTL)
prName goal pt (configsMap s)}
cfg = getConfig prName goal pt (configsMap sEnt)
t = timeLimit cfg
t' = case sp of
Up -> maybe (guiDefaultTimeLimit + 10)
(+ 10)
t
_ -> maybe (guiDefaultTimeLimit - 10)
(subtract 10)
t
s' = sEnt {configsMap =
adjustOrSetConfig
(setTimeLimit t')
prName goal pt (configsMap sEnt)}
Conc.putMVar stateMVar s'
timeEntry # value
(fromMaybe guiDefaultTimeLimit
$ timeLimit $ getConfig prName goal pt
$ configsMap s')
done)
(currentGoal st)))
isExtraOptions
pack right [Expand On, Fill Both, Anchor NorthWest]
-- buttons for options
buttonsHb1 <- newHBox right []
pack buttonsHb1 [Anchor NorthEast]
saveProbButton <- newButton buttonsHb1 [text $ "Save "
++ removeFirstDot (problemOutput $ fileExtensions atpFun)
++ " File"]
pack saveProbButton [Side AtLeft]
proveButton <- newButton buttonsHb1 [text "Prove"]
pack proveButton [Side AtRight]
-- result frame
resultFrame <- newFrame right []
pack resultFrame [Expand On, Fill Both]
l4 <- newLabel resultFrame [text ("Results:" ++ replicate 70 ' ')]
pack l4 [Anchor NorthWest]
spacer <- newLabel resultFrame [text " "]
pack spacer [Side AtLeft]
resultContentBox <- newHBox resultFrame []
pack resultContentBox [Expand On, Anchor West, Fill Both]
-- labels on the left side
rc1 <- newVBox resultContentBox []
pack rc1 [Expand Off, Anchor North]
l5 <- newLabel rc1 [text "Status"]
pack l5 [Anchor West]
l6 <- newLabel rc1 [text "Used Axioms"]
pack l6 [Anchor West]
-- contents on the right side
rc2 <- newVBox resultContentBox []
pack rc2 [Expand On, Fill Both, Anchor North]
statusLabel <- newLabel rc2 [text " -- "]
pack statusLabel [Anchor West]
axiomsFrame <- newFrame rc2 []
pack axiomsFrame [Expand On, Anchor West, Fill Both]
axiomsLb <- newListBox axiomsFrame [value ([] :: [String]),
bg "white", exportSelection False,
selectMode Browse,
height 6, width 19] :: IO (ListBox String)
pack axiomsLb [Side AtLeft, Expand On, Fill Both]
axiomsSb <- newScrollBar axiomsFrame []
pack axiomsSb [Side AtRight, Fill Y, Anchor West]
axiomsLb # scrollbar Vertical axiomsSb
detailsButton <- newButton resultFrame [text "Show Details"]
pack detailsButton [Anchor NorthEast]
-- separator
sp1 <- newSpace b (cm 0.15) []
pack sp1 [Expand Off, Fill X, Side AtBottom]
newHSeparator b
sp2 <- newSpace b (cm 0.15) []
pack sp2 [Expand Off, Fill X, Side AtBottom]
-- batch mode frame
batch <- newFrame b []
pack batch [Expand Off, Fill X]
batchTitle <- newLabel batch [text $ prName ++ " Batch Mode:"]
pack batchTitle [Side AtTop]
batchIFrame <- newFrame batch []
pack batchIFrame [Expand On, Fill X]
batchRight <- newVBox batchIFrame []
pack batchRight [Expand On, Fill X, Side AtRight]
batchBtnBox <- newHBox batchRight []
pack batchBtnBox [Expand On, Fill X, Side AtRight]
stopBatchButton <- newButton batchBtnBox [text "Stop"]
pack stopBatchButton []
runBatchButton <- newButton batchBtnBox [text "Run"]
pack runBatchButton []
batchSpacer <- newSpace batchRight (pp 150) [orient Horizontal]
pack batchSpacer [Side AtRight]
batchStatusLabel <- newLabel batchRight [text "\n\n"]
pack batchStatusLabel []
OpFrame { ofFrame = batchLeft
, ofTimeSpinner = batchTimeSpinner
, ofTimeEntry = batchTimeEntry
, ofOptionsEntry = batchOptionsEntry}
<- newOptionsFrame batchIFrame
(\ tEntry sp -> synchronize main
(do
curEntTL <- getValueSafe batchTLimit tEntry
let t' = case sp of
Up -> curEntTL + 10
_ -> max batchTLimit (curEntTL - 10)
tEntry # value t'
done))
isExtraOptions
pack batchLeft [Expand On, Fill X, Anchor NorthWest, Side AtLeft]
batchGoal <- newHBox batch []
pack batchGoal [Expand On, Fill X, Anchor West, Side AtBottom]
batchCurrentGoalTitle <- newLabel batchGoal [text "Current goal:"]
pack batchCurrentGoalTitle []
batchCurrentGoalLabel <- newLabel batchGoal [text "--"]
pack batchCurrentGoalLabel []
saveProblem_batch <- createTkVariable False
saveProblem_batch_checkBox <-
newCheckButton batchLeft
[variable saveProblem_batch,
text $ "Save "
++ removeFirstDot (problemOutput $ fileExtensions atpFun)]
enableSaveCheckBox <- getEnvSave False "HETS_ENABLE_BATCH_SAVE" readMaybe
when enableSaveCheckBox $
pack saveProblem_batch_checkBox [Expand Off, Fill None, Side AtBottom]
batchTimeEntry # value batchTLimit
separator 2
sp1_2 <- newSpace b (cm 0.15) []
pack sp1_2 [Expand Off, Fill X, Side AtBottom]
newHSeparator b
sp2_2 <- newSpace b (cm 0.15) []
pack sp2_2 [Expand Off, Fill X, Side AtBottom]
-- global options frame
globalOptsFr <- newFrame b []
pack globalOptsFr [Expand Off, Fill Both]
gOptsTitle <- newLabel globalOptsFr [text "Global Options:"]
pack gOptsTitle [Side AtTop]
inclProvedThsTK <- createTkVariable True
inclProvedThsCheckButton <-
newCheckButton globalOptsFr
[variable inclProvedThsTK,
text ("include preceding proven therorems"
++ " in next proof attempt")]
pack inclProvedThsCheckButton [Side AtLeft]
separator 3
sp1_3 <- newSpace b (cm 0.15) []
pack sp1_3 [Expand Off, Fill X, Side AtBottom]
newHSeparator b
sp2_3 <- newSpace b (cm 0.15) []
pack sp2_3 [Expand Off, Fill X, Side AtBottom]
-- bottom frame (help/save/exit buttons)
bottom <- newHBox b []
pack bottom [Expand Off, Fill Both]
helpButton <- newButton bottom [text "Help"]
pack helpButton [PadX (cm 0.3), IPadX (cm 0.1)] -- wider "Help" button
saveButton <- newButton bottom [text "Save Prover Configuration"]
pack saveButton [PadX (cm 0.3)]
exitButton <- newButton bottom [text "Exit Prover"]
pack exitButton [PadX (cm 0.3)]
populateGoalsListBox lb (goalsView initState)
putWinOnTop main
-- MVars for thread-safe communication
mVar_batchId <- Conc.newEmptyMVar :: IO (Conc.MVar Conc.ThreadId)
windowDestroyedMVar <- Conc.newEmptyMVar :: IO (Conc.MVar ())
-- events
(selectGoal, _) <- bindSimple lb (ButtonPress (Just 1))
doProve <- clicked proveButton
saveProb <- clicked saveProbButton
showDetails <- clicked detailsButton
runBatch <- clicked runBatchButton
stopBatch <- clicked stopBatchButton
help <- clicked helpButton
saveConfiguration <- clicked saveButton
exit <- clicked exitButton
(closeWindow, _) <- bindSimple main Destroy
let goalSpecificWids = [EnW timeEntry, EnW timeSpinner, EnW optionsEntry] ++
map EnW [proveButton, detailsButton, saveProbButton]
wids = EnW lb : goalSpecificWids ++
[EnW batchTimeEntry, EnW batchTimeSpinner,
EnW saveProblem_batch_checkBox,
EnW batchOptionsEntry, EnW inclProvedThsCheckButton] ++
map EnW [helpButton, saveButton, exitButton, runBatchButton]
disableWids goalSpecificWids
disable stopBatchButton
-- event handlers
_ <- spawnEvent $ forever
$ selectGoal >>> do
s <- Conc.takeMVar stateMVar
let oldGoal = currentGoal s
curEntTL <- getValueSafe guiDefaultTimeLimit timeEntry :: IO Int
let s' = maybe s
(\ og -> s
{configsMap =
adjustOrSetConfig (setTimeLimit curEntTL)
prName og pt
(configsMap s)})
oldGoal
sel <- getSelection lb :: IO (Maybe [Int])
let s'' = maybe s' (\ sg -> s' {currentGoal =
Just $ AS_Anno.senAttr
(goalsList s' !! head sg)})
sel
Conc.putMVar stateMVar s''
batchModeRunning <- isBatchModeRunning mVar_batchId
when (isJust sel && not batchModeRunning)
(enableWids goalSpecificWids)
when (isJust sel) $ enableWids [EnW detailsButton, EnW saveProbButton]
updateDisplay s'' False lb statusLabel timeEntry optionsEntry axiomsLb
done
+> saveProb >>> do
rs <- Conc.readMVar stateMVar
curEntTL <- getValueSafe guiDefaultTimeLimit
timeEntry :: IO Int
inclProvedThs <- readTkVariable inclProvedThsTK
maybe (return ())
(\ goal -> do
let (nGoal, lp') =
prepareLP (proverState rs)
rs goal inclProvedThs
s = rs {configsMap = adjustOrSetConfig
(setTimeLimit curEntTL)
prName goal pt
(configsMap rs)}
extraOptions <- getValue optionsEntry :: IO String
let s' = s {configsMap = adjustOrSetConfig
(setExtraOpts (words extraOptions))
prName goal pt
(configsMap s)}
prob <- goalOutput atpFun lp' nGoal $
createProverOptions atpFun
(getConfig prName goal pt $ configsMap s')
createTextSaveDisplay
(prName ++ " Problem for Goal " ++ goal)
(thName ++ '_' : goal
++ problemOutput (fileExtensions atpFun))
prob)
$ currentGoal rs
done
+> doProve >>> do
rs <- Conc.readMVar stateMVar
case currentGoal rs of
Nothing -> noGoalSelected >> done
Just goal -> do
curEntTL <- getValueSafe guiDefaultTimeLimit
timeEntry :: IO Int
inclProvedThs <- readTkVariable inclProvedThsTK
let s = rs {configsMap = adjustOrSetConfig
(setTimeLimit curEntTL)
prName goal pt
(configsMap rs)}
(nGoal, lp') = prepareLP (proverState rs)
rs goal inclProvedThs
extraOptions <- getValue optionsEntry :: IO String
let s' = s {configsMap = adjustOrSetConfig
(setExtraOpts (words extraOptions))
prName goal pt
(configsMap s)}
statusLabel # text (snd statusRunning)
statusLabel # foreground (show $ fst statusRunning)
disableWids wids
(retval, cfg) <- runProver atpFun lp'
(getConfig prName goal pt $ configsMap s') False
thName nGoal
-- check if window was closed
wDestroyed <- windowDestroyed windowDestroyedMVar
if wDestroyed
then done
else do
case retval of
ATPError m -> errorDialog "Error" m
_ -> return ()
let s'' = s' {
configsMap =
adjustOrSetConfig
(\ c -> c {timeLimitExceeded = isTimeLimitExceeded
retval,
proofStatus = (proofStatus cfg)
{usedTime = timeUsed cfg},
resultOutput = resultOutput cfg,
timeUsed = timeUsed cfg})
prName goal pt (configsMap s')}
Conc.modifyMVar_ stateMVar (return . const s'')
-- check again if window was closed
wDestroyed2 <- windowDestroyed windowDestroyedMVar
if wDestroyed2
then done
else do
enable lb
enable axiomsLb
updateDisplay s'' True lb statusLabel timeEntry
optionsEntry axiomsLb
enableWids wids
done
+> showDetails >>> do
Conc.yield
s <- Conc.readMVar stateMVar
case currentGoal s of
Nothing -> noGoalSelected >> done
Just goal -> do
let result = Map.lookup goal (configsMap s)
output = maybe ["This goal hasn't been run through " ++
"the prover yet."]
resultOutput
result
detailsText = concatMap ('\n' :) output
createTextSaveDisplay (prName ++ " Output for Goal " ++ goal)
(goal ++ proverOutput (fileExtensions atpFun))
(seq (length detailsText) detailsText)
done
+> runBatch >>> do
s <- Conc.readMVar stateMVar
-- get options for this batch run
curEntTL <- getValueSafe batchTLimit batchTimeEntry :: IO Int
let tLimit = if curEntTL > 0 then curEntTL else batchTLimit
batchTimeEntry # value tLimit
extOpts <- getValue batchOptionsEntry :: IO String
let extOpts' = words extOpts
openGoalsMap = filterOpenGoals $ configsMap s
numGoals = Map.size openGoalsMap
firstGoalName = fromMaybe "--" $
find (`Map.member` openGoalsMap) $
map AS_Anno.senAttr (goalsList s)
if numGoals > 0
then do
let afterEachProofAttempt gPSF nSen nextSen cfg@(retval, _) = do
{- this function is called after the prover returns from a
proof attempt (... -> IO Bool) -}
cont <- goalProcessed stateMVar tLimit extOpts'
numGoals prName gPSF nSen False cfg
Conc.tryTakeMVar mVar_batchId >>=
maybe (return False) (\ tId -> do
stored <- Conc.tryPutMVar
mVar_batchId
tId
if not stored
then Fail.fail $ "GenericATP: Thread " ++
"run check failed"
else do
wDestroyed <- windowDestroyed windowDestroyedMVar
if wDestroyed
then return False
else do
batchStatusLabel #
text (if cont
then batchInfoText tLimit numGoals gPSF
else "Batch mode finished\n\n")
setCurrentGoalLabel batchCurrentGoalLabel
(if cont
then maybe "--" AS_Anno.senAttr nextSen
else "--")
st <- Conc.readMVar stateMVar
updateDisplay st True lb statusLabel timeEntry
optionsEntry axiomsLb
case retval of
ATPError m -> errorDialog "Error" m
_ -> return ()
batchModeRunning <-
isBatchModeRunning mVar_batchId
let cont' = cont && batchModeRunning
unless cont $ do
disable stopBatchButton
enableWids wids
enableWidsUponSelection lb goalSpecificWids
cleanupThread mVar_batchId
return cont')
-- END of afterEachProofAttempt
batchStatusLabel # text (batchInfoText tLimit numGoals 0)
setCurrentGoalLabel batchCurrentGoalLabel firstGoalName
disableWids wids
enable stopBatchButton
enableWidsUponSelection lb [EnW detailsButton, EnW saveProbButton]
enable lb
inclProvedThs <- readTkVariable inclProvedThsTK
saveProblem_F <- readTkVariable saveProblem_batch
batchProverId <- Conc.forkIO $
genericProveBatch False tLimit extOpts' inclProvedThs
saveProblem_F
afterEachProofAttempt
(atpInsertSentence atpFun) (runProver atpFun)
prName thName s Nothing
>> return ()
stored <- Conc.tryPutMVar mVar_batchId batchProverId
if stored
then done
else Fail.fail "GenericATP: MVar for batchProverId already taken!!"
numGoals < 1
batchStatusLabel # text "No further open goals\n\n"
batchCurrentGoalLabel # text "--"
done
+> stopBatch >>> do
cleanupThread mVar_batchId
wDestroyed <- windowDestroyed windowDestroyedMVar
if wDestroyed
then done
else do
disable stopBatchButton
enableWids wids
enableWidsUponSelection lb goalSpecificWids
batchStatusLabel # text "Batch mode stopped\n\n"
batchCurrentGoalLabel # text "--"
st <- Conc.readMVar stateMVar
updateDisplay st True lb statusLabel timeEntry
optionsEntry axiomsLb
done
+> help >>> do
createTextDisplay (prName ++ " Help")
(proverHelpText atpFun)
done
+> saveConfiguration >>> do
s <- Conc.readMVar stateMVar
let cfgText = show $ printCfgText $ configsMap s
createTextSaveDisplay
(prName ++ " Configuration for Theory " ++ thName)
(thName ++ theoryConfiguration (fileExtensions atpFun))
cfgText
done
sync $ exit >>> destroy main
+> closeWindow >>> do
Conc.putMVar windowDestroyedMVar ()
cleanupThread mVar_batchId
destroy main
s <- Conc.takeMVar stateMVar
let Result _ proofstats = revertRenamingOfLabels s $
map ((\ g -> let
res = Map.lookup g (configsMap s)
g' = Map.findWithDefault
(error ("Lookup of name failed: (1) "
++ "should not happen \""
++ g ++ "\""))
g (namesMap s)
in maybe (openProofStatus g' prName $ currentProofTree s)
proofStatus res) . AS_Anno.senAttr)
$ goalsList s
-- diags should not be plainly shown by putStrLn here
maybe (Fail.fail "reverse translation of names failed") return proofstats
where
cleanupThread mVar_TId =
Conc.tryTakeMVar mVar_TId >>= maybe (return ()) Conc.killThread
windowDestroyed sMVar =
Conc.yield >>
Conc.tryTakeMVar sMVar >>=
maybe (return False) (\ un -> Conc.putMVar sMVar un >> return True)
isBatchModeRunning tIdMVar =
Conc.tryTakeMVar tIdMVar >>=
maybe (return False) (\ tId -> Conc.putMVar tIdMVar tId >> return True)
noGoalSelected = errorDialog "Error" "Please select a goal first."
prepareLP prS s goal inclProvedThs =
let (beforeThis, afterThis) =
splitAt (fromMaybe (error "GUI.GenericATP: goal shoud be found")
$ findIndex ((== goal) . AS_Anno.senAttr)
$ goalsList s) $ goalsList s
proved = filter (checkGoal (configsMap s) . AS_Anno.senAttr)
beforeThis
in if inclProvedThs
then (head afterThis,
foldl (\ lp provedGoal ->
atpInsertSentence atpFun
lp provedGoal {AS_Anno.isAxiom = True})
prS
(reverse proved))
else (fromMaybe (error ("GUI.GenericATP.prepareLP: Goal "
++ goal ++ " not found!!"))
(find ((== goal) . AS_Anno.senAttr) (goalsList s)),
prS)
setCurrentGoalLabel batchLabel s = batchLabel # text (take 65 s)
removeFirstDot [] = error "GenericATP: no extension given"
removeFirstDot e@(h : ext) =
case h of
'.' -> ext
_ -> e
| null | https://raw.githubusercontent.com/spechub/Hets/f582640a174df08d4c965d7c0a1ab24d1a31000d/GUI/HTkGenericATP.hs | haskell | |
Utility function to set the time limit of a Config.
For values <= 0 a default value is used.
|
Utility function to set the extra options of a Config.
** Constants
** Defining the view
|
Colors used by the GUI to indicate the status of a goal.
| Proved
| Proved, but theory is inconsistent
| Disproved
| Open
| Running
|
Generates a ('ProofStatusColour', 'String') tuple representing a Proved proof
status.
|
Generates a ('ProofStatusColour', 'String') tuple representing a Proved
(but inconsistent) proof status.
|
Generates a ('ProofStatusColour', 'String') tuple representing a Disproved
proof status.
|
Generates a ('ProofStatusColour', 'String') tuple representing a Running proof
status.
^ current prover configuration
^ status to convert
| stores widgets of an options frame and the frame itself
^ current global prover state
^ resulting ['LBGoalView'] list
* GUI Implementation
** Utility Functions
|
Retrieves the value of the time limit 'Entry'. Ignores invalid input.
^ time limit 'Entry'
^ user-requested time limit or default for errors
|
reads passed ENV-variable and if it exists and has an Int-value this value is
returned otherwise the value of 'batchTimeLimit' is returned.
^ ENV-variable containing batch time limit
|
Text displayed by the batch mode window.
^ total number of goals
^ number of that have been processed
** Callbacks
|
Updates the display of the status of the current goal.
^ current global prover state
^ 'Label' displaying the status of the currently selected goal
(see 'toGuiStatus')
^ 'Entry' containing the time limit of the current goal
^ 'Entry' containing the extra options
^ the parent container
^ extra options input line
contents of newOptionsFrame
** Main GUI
^ prover specific functions
^ prover supports extra options
^ prover name
^ theory name
^ theory with signature and sentences
^ freeness constraints
^ initial empty proofTree
^ proof status for each goal
create initial backing data structure
main window
VBox for the whole window
left frame (goals)
right frame (options/results)
buttons for options
result frame
labels on the left side
contents on the right side
separator
batch mode frame
global options frame
bottom frame (help/save/exit buttons)
wider "Help" button
MVars for thread-safe communication
events
event handlers
check if window was closed
check again if window was closed
get options for this batch run
this function is called after the prover returns from a
proof attempt (... -> IO Bool)
END of afterEachProofAttempt
diags should not be plainly shown by putStrLn here | # LANGUAGE FlexibleContexts #
|
Module : ./GUI / HTkGenericATP.hs
Description : Generic Prover GUI .
Copyright : ( c ) , , Uni Bremen 2006
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : needs POSIX
Generic GUI for automatic theorem provers . Based upon former SPASS Prover GUI .
Module : ./GUI/HTkGenericATP.hs
Description : Generic Prover GUI.
Copyright : (c) Klaus Luettich, Rainer Grabbe, Uni Bremen 2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : needs POSIX
Generic GUI for automatic theorem provers. Based upon former SPASS Prover GUI.
-}
module GUI.HTkGenericATP (genericATPgui) where
import Logic.Prover
import qualified Common.AS_Annotation as AS_Anno
import qualified Data.Map as Map
import Common.Utils (getEnvSave, readMaybe)
import Common.Result
import Data.List
import Data.Maybe
import qualified Control.Exception as Exception
import qualified Control.Concurrent as Conc
import qualified Control.Monad.Fail as Fail
import HTk.Toolkit.SpinButton
import HTk.Toolkit.Separator
import HTk.Devices.XSelection
import HTk.Widgets.Space
import GUI.Utils
import GUI.HTkUtils hiding (createTextSaveDisplay, createTextDisplay)
import Interfaces.GenericATPState
import Proofs.BatchProcessing
setTimeLimit :: Int -> GenericConfig proofTree -> GenericConfig proofTree
setTimeLimit n c = c { timeLimit = if n > 0 then Just n else Nothing }
setExtraOpts :: [String] -> GenericConfig proofTree -> GenericConfig proofTree
setExtraOpts opts c = c { extraOpts = opts }
data ProofStatusColour
= Green
| Brown
| Red
| Black
| Blue
deriving (Bounded, Enum, Show)
statusProved :: (ProofStatusColour, String)
statusProved = (Green, "Proved")
statusProvedButInconsistent :: (ProofStatusColour, String)
statusProvedButInconsistent = (Brown, "Proved/Inconsistent")
statusDisproved :: (ProofStatusColour, String)
statusDisproved = (Red, "Disproved")
|
Generates a ( ' ProofStatusColour ' , ' String ' ) tuple representing an Open proof
status .
Generates a ('ProofStatusColour', 'String') tuple representing an Open proof
status.
-}
statusOpen :: (ProofStatusColour, String)
statusOpen = (Black, "Open")
|
Generates a ( ' ProofStatusColour ' , ' String ' ) tuple representing an Open proof
status in case the time limit has been exceeded .
Generates a ('ProofStatusColour', 'String') tuple representing an Open proof
status in case the time limit has been exceeded.
-}
statusOpenTExceeded :: (ProofStatusColour, String)
statusOpenTExceeded = (Black, "Open (Time is up!)")
statusRunning :: (ProofStatusColour, String)
statusRunning = (Blue, "Running")
|
Converts a ' ProofStatus ' into a ( ' ProofStatusColour ' , ' String ' ) tuple to be
displayed by the GUI .
Converts a 'ProofStatus' into a ('ProofStatusColour', 'String') tuple to be
displayed by the GUI.
-}
-> (ProofStatusColour, String)
toGuiStatus cf st = case goalStatus st of
Proved c -> if c then statusProved else statusProvedButInconsistent
Disproved -> statusDisproved
_ -> if timeLimitExceeded cf
then statusOpenTExceeded
else statusOpen
data OpFrame = OpFrame { ofFrame :: Frame
, ofTimeSpinner :: SpinButton
, ofTimeEntry :: Entry Int
, ofOptionsEntry :: Entry String
}
|
Generates a list of ' GUI.HTkUtils . LBGoalView ' representations of all goals
from a ' GenericATPState . ' .
Generates a list of 'GUI.HTkUtils.LBGoalView' representations of all goals
from a 'GenericATPState.GenericState'.
-}
goalsView
goalsView s = map ((\ g ->
let cfg = Map.lookup g (configsMap s)
statind = maybe LBIndicatorOpen
(indicatorFromProofStatus . proofStatus)
cfg
in
LBGoalView {statIndicator = statind,
goalDescription = g})
. AS_Anno.senAttr) $ goalsList s
getValueSafe
^ default time limt
getValueSafe defaultTimeLimit timeEntry =
Exception.catch (getValue timeEntry :: IO Int)
$ \ e -> do
putStrLn $ "Warning: Error " ++ show (e :: Exception.SomeException)
++ " was ignored"
return defaultTimeLimit
-> IO Int
getBatchTimeLimit env =
getEnvSave batchTimeLimit env readMaybe
^ batch time limt
-> String
batchInfoText tl gTotal gDone =
let totalSecs = (gTotal - gDone) * tl
(remMins, secs) = divMod totalSecs 60
(hours, mins) = divMod remMins 60
in
"Batch mode running.\n" ++
show gDone ++ "/" ++ show gTotal ++ " goals processed.\n" ++
"At most " ++ show hours ++ "h " ++ show mins ++ "m " ++ show secs
++ "s remaining."
updateDisplay
:: GenericState sentence proofTree pst
^ set to ' True ' if you want the ' ListBox ' to be updated
-> ListBox String
^ ' ListBox ' displaying the status of all goals ( see ' goalsView ' )
-> Label
-> ListBox String
^ ' ListBox ' displaying all axioms used to prove a goal ( if any )
-> IO ()
updateDisplay st updateLb goalsLb statusLabel timeEntry optionsEntry axiomsLb =
the code in comments only works with an updated uni version that
will be installed when switching to
will be installed when switching to ghc-6.6.1 -}
do
when updateLb (do
(offScreen, _) <- view Vertical goalsLb
populateGoalsListBox goalsLb (goalsView st)
moveto Vertical goalsLb offScreen
)
maybe (return ())
(\ go ->
let mprfst = Map.lookup go (configsMap st)
cf = Map.findWithDefault
(error "GUI.GenericATP.updateDisplay")
go (configsMap st)
t' = fromMaybe guiDefaultTimeLimit (timeLimit cf)
opts' = unwords (extraOpts cf)
(color, label) = maybe statusOpen
(toGuiStatus cf . proofStatus)
mprfst
usedAxs = maybe [] (usedAxioms . proofStatus) mprfst
in do
statusLabel # text label
statusLabel # foreground (show color)
timeEntry # value t'
optionsEntry # value opts'
axiomsLb # value (usedAxs :: [String])
return ())
(currentGoal st)
newOptionsFrame
:: Container par
-> (Entry Int -> Spin -> IO a)
^ Function called by pressing one spin button
-> IO OpFrame
newOptionsFrame con updateFn isExtraOps = do
right <- newFrame con []
l1 <- newLabel right [text "Options:"]
pack l1 [Anchor NorthWest]
opFrame <- newFrame right []
pack opFrame [Expand On, Fill X, Anchor North]
spacer <- newLabel opFrame [text " "]
pack spacer [Side AtLeft]
opFrame2 <- newVBox opFrame []
pack opFrame2 [Expand On, Fill X, Anchor NorthWest]
timeLimitFrame <- newFrame opFrame2 []
pack timeLimitFrame [Expand On, Fill X, Anchor West]
l2 <- newLabel timeLimitFrame [text "TimeLimit"]
pack l2 [Side AtLeft]
extra HBox for time limit display
timeLimitLine <- newHBox timeLimitFrame []
pack timeLimitLine [Expand On, Side AtRight, Anchor East]
timeEntry <- newEntry timeLimitLine [width 18,
value guiDefaultTimeLimit]
pack (timeEntry :: Entry Int) []
timeSpinner <- newSpinButton timeLimitLine (updateFn timeEntry) []
pack timeSpinner []
l3 <- newLabel opFrame2 [text "Extra Options:"]
when isExtraOps $
pack l3 [Anchor West]
optionsEntry <- newEntry opFrame2 [width 37]
when isExtraOps $
pack (optionsEntry :: Entry String) [Fill X, PadX (cm 0.1)]
return OpFrame
{ ofFrame = right
, ofTimeSpinner = timeSpinner
, ofTimeEntry = timeEntry
, ofOptionsEntry = optionsEntry }
|
Invokes the prover GUI . Users may start the batch prover run on all goals ,
or use a detailed GUI for proving each goal manually .
Invokes the prover GUI. Users may start the batch prover run on all goals,
or use a detailed GUI for proving each goal manually.
-}
genericATPgui
:: (Show sentence, Ord proofTree, Ord sentence)
=> ATPFunctions sign sentence mor proofTree pst
-> Theory sign sentence proofTree
genericATPgui atpFun isExtraOptions prName thName th freedefs pt = do
let initState = initialGenericState prName
(initialProverState atpFun)
(atpTransSenName atpFun) th freedefs pt
stateMVar <- Conc.newMVar initState
batchTLimit <- getBatchTimeLimit $ batchTimeEnv atpFun
main <- createToplevel [text $ thName ++ " - " ++ prName ++ " Prover"]
pack main [Expand On, Fill Both]
b <- newVBox main []
pack b [Expand On, Fill Both]
HBox for the upper part ( goals on the left , options / results on the right )
b2 <- newHBox b []
pack b2 [Expand On, Fill Both]
left <- newFrame b2 []
pack left [Expand On, Fill Both]
b3 <- newVBox left []
pack b3 [Expand On, Fill Both]
l0 <- newLabel b3 [text "Goals:"]
pack l0 [Anchor NorthWest]
lbFrame <- newFrame b3 []
pack lbFrame [Expand On, Fill Both]
lb <- newListBox lbFrame [bg "white", exportSelection False,
selectMode Single, height 15] :: IO (ListBox String)
pack lb [Expand On, Side AtLeft, Fill Both]
sb <- newScrollBar lbFrame []
pack sb [Expand On, Side AtRight, Fill Y, Anchor West]
lb # scrollbar Vertical sb
OpFrame { ofFrame = right
, ofTimeSpinner = timeSpinner
, ofTimeEntry = timeEntry
, ofOptionsEntry = optionsEntry}
<- newOptionsFrame b2
(\ timeEntry sp -> synchronize main
(do
st <- Conc.readMVar stateMVar
maybe noGoalSelected
(\ goal ->
do
curEntTL <- getValueSafe guiDefaultTimeLimit timeEntry
s <- Conc.takeMVar stateMVar
let sEnt = s {configsMap =
adjustOrSetConfig
(setTimeLimit curEntTL)
prName goal pt (configsMap s)}
cfg = getConfig prName goal pt (configsMap sEnt)
t = timeLimit cfg
t' = case sp of
Up -> maybe (guiDefaultTimeLimit + 10)
(+ 10)
t
_ -> maybe (guiDefaultTimeLimit - 10)
(subtract 10)
t
s' = sEnt {configsMap =
adjustOrSetConfig
(setTimeLimit t')
prName goal pt (configsMap sEnt)}
Conc.putMVar stateMVar s'
timeEntry # value
(fromMaybe guiDefaultTimeLimit
$ timeLimit $ getConfig prName goal pt
$ configsMap s')
done)
(currentGoal st)))
isExtraOptions
pack right [Expand On, Fill Both, Anchor NorthWest]
buttonsHb1 <- newHBox right []
pack buttonsHb1 [Anchor NorthEast]
saveProbButton <- newButton buttonsHb1 [text $ "Save "
++ removeFirstDot (problemOutput $ fileExtensions atpFun)
++ " File"]
pack saveProbButton [Side AtLeft]
proveButton <- newButton buttonsHb1 [text "Prove"]
pack proveButton [Side AtRight]
resultFrame <- newFrame right []
pack resultFrame [Expand On, Fill Both]
l4 <- newLabel resultFrame [text ("Results:" ++ replicate 70 ' ')]
pack l4 [Anchor NorthWest]
spacer <- newLabel resultFrame [text " "]
pack spacer [Side AtLeft]
resultContentBox <- newHBox resultFrame []
pack resultContentBox [Expand On, Anchor West, Fill Both]
rc1 <- newVBox resultContentBox []
pack rc1 [Expand Off, Anchor North]
l5 <- newLabel rc1 [text "Status"]
pack l5 [Anchor West]
l6 <- newLabel rc1 [text "Used Axioms"]
pack l6 [Anchor West]
rc2 <- newVBox resultContentBox []
pack rc2 [Expand On, Fill Both, Anchor North]
statusLabel <- newLabel rc2 [text " -- "]
pack statusLabel [Anchor West]
axiomsFrame <- newFrame rc2 []
pack axiomsFrame [Expand On, Anchor West, Fill Both]
axiomsLb <- newListBox axiomsFrame [value ([] :: [String]),
bg "white", exportSelection False,
selectMode Browse,
height 6, width 19] :: IO (ListBox String)
pack axiomsLb [Side AtLeft, Expand On, Fill Both]
axiomsSb <- newScrollBar axiomsFrame []
pack axiomsSb [Side AtRight, Fill Y, Anchor West]
axiomsLb # scrollbar Vertical axiomsSb
detailsButton <- newButton resultFrame [text "Show Details"]
pack detailsButton [Anchor NorthEast]
sp1 <- newSpace b (cm 0.15) []
pack sp1 [Expand Off, Fill X, Side AtBottom]
newHSeparator b
sp2 <- newSpace b (cm 0.15) []
pack sp2 [Expand Off, Fill X, Side AtBottom]
batch <- newFrame b []
pack batch [Expand Off, Fill X]
batchTitle <- newLabel batch [text $ prName ++ " Batch Mode:"]
pack batchTitle [Side AtTop]
batchIFrame <- newFrame batch []
pack batchIFrame [Expand On, Fill X]
batchRight <- newVBox batchIFrame []
pack batchRight [Expand On, Fill X, Side AtRight]
batchBtnBox <- newHBox batchRight []
pack batchBtnBox [Expand On, Fill X, Side AtRight]
stopBatchButton <- newButton batchBtnBox [text "Stop"]
pack stopBatchButton []
runBatchButton <- newButton batchBtnBox [text "Run"]
pack runBatchButton []
batchSpacer <- newSpace batchRight (pp 150) [orient Horizontal]
pack batchSpacer [Side AtRight]
batchStatusLabel <- newLabel batchRight [text "\n\n"]
pack batchStatusLabel []
OpFrame { ofFrame = batchLeft
, ofTimeSpinner = batchTimeSpinner
, ofTimeEntry = batchTimeEntry
, ofOptionsEntry = batchOptionsEntry}
<- newOptionsFrame batchIFrame
(\ tEntry sp -> synchronize main
(do
curEntTL <- getValueSafe batchTLimit tEntry
let t' = case sp of
Up -> curEntTL + 10
_ -> max batchTLimit (curEntTL - 10)
tEntry # value t'
done))
isExtraOptions
pack batchLeft [Expand On, Fill X, Anchor NorthWest, Side AtLeft]
batchGoal <- newHBox batch []
pack batchGoal [Expand On, Fill X, Anchor West, Side AtBottom]
batchCurrentGoalTitle <- newLabel batchGoal [text "Current goal:"]
pack batchCurrentGoalTitle []
batchCurrentGoalLabel <- newLabel batchGoal [text "--"]
pack batchCurrentGoalLabel []
saveProblem_batch <- createTkVariable False
saveProblem_batch_checkBox <-
newCheckButton batchLeft
[variable saveProblem_batch,
text $ "Save "
++ removeFirstDot (problemOutput $ fileExtensions atpFun)]
enableSaveCheckBox <- getEnvSave False "HETS_ENABLE_BATCH_SAVE" readMaybe
when enableSaveCheckBox $
pack saveProblem_batch_checkBox [Expand Off, Fill None, Side AtBottom]
batchTimeEntry # value batchTLimit
separator 2
sp1_2 <- newSpace b (cm 0.15) []
pack sp1_2 [Expand Off, Fill X, Side AtBottom]
newHSeparator b
sp2_2 <- newSpace b (cm 0.15) []
pack sp2_2 [Expand Off, Fill X, Side AtBottom]
globalOptsFr <- newFrame b []
pack globalOptsFr [Expand Off, Fill Both]
gOptsTitle <- newLabel globalOptsFr [text "Global Options:"]
pack gOptsTitle [Side AtTop]
inclProvedThsTK <- createTkVariable True
inclProvedThsCheckButton <-
newCheckButton globalOptsFr
[variable inclProvedThsTK,
text ("include preceding proven therorems"
++ " in next proof attempt")]
pack inclProvedThsCheckButton [Side AtLeft]
separator 3
sp1_3 <- newSpace b (cm 0.15) []
pack sp1_3 [Expand Off, Fill X, Side AtBottom]
newHSeparator b
sp2_3 <- newSpace b (cm 0.15) []
pack sp2_3 [Expand Off, Fill X, Side AtBottom]
bottom <- newHBox b []
pack bottom [Expand Off, Fill Both]
helpButton <- newButton bottom [text "Help"]
saveButton <- newButton bottom [text "Save Prover Configuration"]
pack saveButton [PadX (cm 0.3)]
exitButton <- newButton bottom [text "Exit Prover"]
pack exitButton [PadX (cm 0.3)]
populateGoalsListBox lb (goalsView initState)
putWinOnTop main
mVar_batchId <- Conc.newEmptyMVar :: IO (Conc.MVar Conc.ThreadId)
windowDestroyedMVar <- Conc.newEmptyMVar :: IO (Conc.MVar ())
(selectGoal, _) <- bindSimple lb (ButtonPress (Just 1))
doProve <- clicked proveButton
saveProb <- clicked saveProbButton
showDetails <- clicked detailsButton
runBatch <- clicked runBatchButton
stopBatch <- clicked stopBatchButton
help <- clicked helpButton
saveConfiguration <- clicked saveButton
exit <- clicked exitButton
(closeWindow, _) <- bindSimple main Destroy
let goalSpecificWids = [EnW timeEntry, EnW timeSpinner, EnW optionsEntry] ++
map EnW [proveButton, detailsButton, saveProbButton]
wids = EnW lb : goalSpecificWids ++
[EnW batchTimeEntry, EnW batchTimeSpinner,
EnW saveProblem_batch_checkBox,
EnW batchOptionsEntry, EnW inclProvedThsCheckButton] ++
map EnW [helpButton, saveButton, exitButton, runBatchButton]
disableWids goalSpecificWids
disable stopBatchButton
_ <- spawnEvent $ forever
$ selectGoal >>> do
s <- Conc.takeMVar stateMVar
let oldGoal = currentGoal s
curEntTL <- getValueSafe guiDefaultTimeLimit timeEntry :: IO Int
let s' = maybe s
(\ og -> s
{configsMap =
adjustOrSetConfig (setTimeLimit curEntTL)
prName og pt
(configsMap s)})
oldGoal
sel <- getSelection lb :: IO (Maybe [Int])
let s'' = maybe s' (\ sg -> s' {currentGoal =
Just $ AS_Anno.senAttr
(goalsList s' !! head sg)})
sel
Conc.putMVar stateMVar s''
batchModeRunning <- isBatchModeRunning mVar_batchId
when (isJust sel && not batchModeRunning)
(enableWids goalSpecificWids)
when (isJust sel) $ enableWids [EnW detailsButton, EnW saveProbButton]
updateDisplay s'' False lb statusLabel timeEntry optionsEntry axiomsLb
done
+> saveProb >>> do
rs <- Conc.readMVar stateMVar
curEntTL <- getValueSafe guiDefaultTimeLimit
timeEntry :: IO Int
inclProvedThs <- readTkVariable inclProvedThsTK
maybe (return ())
(\ goal -> do
let (nGoal, lp') =
prepareLP (proverState rs)
rs goal inclProvedThs
s = rs {configsMap = adjustOrSetConfig
(setTimeLimit curEntTL)
prName goal pt
(configsMap rs)}
extraOptions <- getValue optionsEntry :: IO String
let s' = s {configsMap = adjustOrSetConfig
(setExtraOpts (words extraOptions))
prName goal pt
(configsMap s)}
prob <- goalOutput atpFun lp' nGoal $
createProverOptions atpFun
(getConfig prName goal pt $ configsMap s')
createTextSaveDisplay
(prName ++ " Problem for Goal " ++ goal)
(thName ++ '_' : goal
++ problemOutput (fileExtensions atpFun))
prob)
$ currentGoal rs
done
+> doProve >>> do
rs <- Conc.readMVar stateMVar
case currentGoal rs of
Nothing -> noGoalSelected >> done
Just goal -> do
curEntTL <- getValueSafe guiDefaultTimeLimit
timeEntry :: IO Int
inclProvedThs <- readTkVariable inclProvedThsTK
let s = rs {configsMap = adjustOrSetConfig
(setTimeLimit curEntTL)
prName goal pt
(configsMap rs)}
(nGoal, lp') = prepareLP (proverState rs)
rs goal inclProvedThs
extraOptions <- getValue optionsEntry :: IO String
let s' = s {configsMap = adjustOrSetConfig
(setExtraOpts (words extraOptions))
prName goal pt
(configsMap s)}
statusLabel # text (snd statusRunning)
statusLabel # foreground (show $ fst statusRunning)
disableWids wids
(retval, cfg) <- runProver atpFun lp'
(getConfig prName goal pt $ configsMap s') False
thName nGoal
wDestroyed <- windowDestroyed windowDestroyedMVar
if wDestroyed
then done
else do
case retval of
ATPError m -> errorDialog "Error" m
_ -> return ()
let s'' = s' {
configsMap =
adjustOrSetConfig
(\ c -> c {timeLimitExceeded = isTimeLimitExceeded
retval,
proofStatus = (proofStatus cfg)
{usedTime = timeUsed cfg},
resultOutput = resultOutput cfg,
timeUsed = timeUsed cfg})
prName goal pt (configsMap s')}
Conc.modifyMVar_ stateMVar (return . const s'')
wDestroyed2 <- windowDestroyed windowDestroyedMVar
if wDestroyed2
then done
else do
enable lb
enable axiomsLb
updateDisplay s'' True lb statusLabel timeEntry
optionsEntry axiomsLb
enableWids wids
done
+> showDetails >>> do
Conc.yield
s <- Conc.readMVar stateMVar
case currentGoal s of
Nothing -> noGoalSelected >> done
Just goal -> do
let result = Map.lookup goal (configsMap s)
output = maybe ["This goal hasn't been run through " ++
"the prover yet."]
resultOutput
result
detailsText = concatMap ('\n' :) output
createTextSaveDisplay (prName ++ " Output for Goal " ++ goal)
(goal ++ proverOutput (fileExtensions atpFun))
(seq (length detailsText) detailsText)
done
+> runBatch >>> do
s <- Conc.readMVar stateMVar
curEntTL <- getValueSafe batchTLimit batchTimeEntry :: IO Int
let tLimit = if curEntTL > 0 then curEntTL else batchTLimit
batchTimeEntry # value tLimit
extOpts <- getValue batchOptionsEntry :: IO String
let extOpts' = words extOpts
openGoalsMap = filterOpenGoals $ configsMap s
numGoals = Map.size openGoalsMap
firstGoalName = fromMaybe "--" $
find (`Map.member` openGoalsMap) $
map AS_Anno.senAttr (goalsList s)
if numGoals > 0
then do
let afterEachProofAttempt gPSF nSen nextSen cfg@(retval, _) = do
cont <- goalProcessed stateMVar tLimit extOpts'
numGoals prName gPSF nSen False cfg
Conc.tryTakeMVar mVar_batchId >>=
maybe (return False) (\ tId -> do
stored <- Conc.tryPutMVar
mVar_batchId
tId
if not stored
then Fail.fail $ "GenericATP: Thread " ++
"run check failed"
else do
wDestroyed <- windowDestroyed windowDestroyedMVar
if wDestroyed
then return False
else do
batchStatusLabel #
text (if cont
then batchInfoText tLimit numGoals gPSF
else "Batch mode finished\n\n")
setCurrentGoalLabel batchCurrentGoalLabel
(if cont
then maybe "--" AS_Anno.senAttr nextSen
else "--")
st <- Conc.readMVar stateMVar
updateDisplay st True lb statusLabel timeEntry
optionsEntry axiomsLb
case retval of
ATPError m -> errorDialog "Error" m
_ -> return ()
batchModeRunning <-
isBatchModeRunning mVar_batchId
let cont' = cont && batchModeRunning
unless cont $ do
disable stopBatchButton
enableWids wids
enableWidsUponSelection lb goalSpecificWids
cleanupThread mVar_batchId
return cont')
batchStatusLabel # text (batchInfoText tLimit numGoals 0)
setCurrentGoalLabel batchCurrentGoalLabel firstGoalName
disableWids wids
enable stopBatchButton
enableWidsUponSelection lb [EnW detailsButton, EnW saveProbButton]
enable lb
inclProvedThs <- readTkVariable inclProvedThsTK
saveProblem_F <- readTkVariable saveProblem_batch
batchProverId <- Conc.forkIO $
genericProveBatch False tLimit extOpts' inclProvedThs
saveProblem_F
afterEachProofAttempt
(atpInsertSentence atpFun) (runProver atpFun)
prName thName s Nothing
>> return ()
stored <- Conc.tryPutMVar mVar_batchId batchProverId
if stored
then done
else Fail.fail "GenericATP: MVar for batchProverId already taken!!"
numGoals < 1
batchStatusLabel # text "No further open goals\n\n"
batchCurrentGoalLabel # text "--"
done
+> stopBatch >>> do
cleanupThread mVar_batchId
wDestroyed <- windowDestroyed windowDestroyedMVar
if wDestroyed
then done
else do
disable stopBatchButton
enableWids wids
enableWidsUponSelection lb goalSpecificWids
batchStatusLabel # text "Batch mode stopped\n\n"
batchCurrentGoalLabel # text "--"
st <- Conc.readMVar stateMVar
updateDisplay st True lb statusLabel timeEntry
optionsEntry axiomsLb
done
+> help >>> do
createTextDisplay (prName ++ " Help")
(proverHelpText atpFun)
done
+> saveConfiguration >>> do
s <- Conc.readMVar stateMVar
let cfgText = show $ printCfgText $ configsMap s
createTextSaveDisplay
(prName ++ " Configuration for Theory " ++ thName)
(thName ++ theoryConfiguration (fileExtensions atpFun))
cfgText
done
sync $ exit >>> destroy main
+> closeWindow >>> do
Conc.putMVar windowDestroyedMVar ()
cleanupThread mVar_batchId
destroy main
s <- Conc.takeMVar stateMVar
let Result _ proofstats = revertRenamingOfLabels s $
map ((\ g -> let
res = Map.lookup g (configsMap s)
g' = Map.findWithDefault
(error ("Lookup of name failed: (1) "
++ "should not happen \""
++ g ++ "\""))
g (namesMap s)
in maybe (openProofStatus g' prName $ currentProofTree s)
proofStatus res) . AS_Anno.senAttr)
$ goalsList s
maybe (Fail.fail "reverse translation of names failed") return proofstats
where
cleanupThread mVar_TId =
Conc.tryTakeMVar mVar_TId >>= maybe (return ()) Conc.killThread
windowDestroyed sMVar =
Conc.yield >>
Conc.tryTakeMVar sMVar >>=
maybe (return False) (\ un -> Conc.putMVar sMVar un >> return True)
isBatchModeRunning tIdMVar =
Conc.tryTakeMVar tIdMVar >>=
maybe (return False) (\ tId -> Conc.putMVar tIdMVar tId >> return True)
noGoalSelected = errorDialog "Error" "Please select a goal first."
prepareLP prS s goal inclProvedThs =
let (beforeThis, afterThis) =
splitAt (fromMaybe (error "GUI.GenericATP: goal shoud be found")
$ findIndex ((== goal) . AS_Anno.senAttr)
$ goalsList s) $ goalsList s
proved = filter (checkGoal (configsMap s) . AS_Anno.senAttr)
beforeThis
in if inclProvedThs
then (head afterThis,
foldl (\ lp provedGoal ->
atpInsertSentence atpFun
lp provedGoal {AS_Anno.isAxiom = True})
prS
(reverse proved))
else (fromMaybe (error ("GUI.GenericATP.prepareLP: Goal "
++ goal ++ " not found!!"))
(find ((== goal) . AS_Anno.senAttr) (goalsList s)),
prS)
setCurrentGoalLabel batchLabel s = batchLabel # text (take 65 s)
removeFirstDot [] = error "GenericATP: no extension given"
removeFirstDot e@(h : ext) =
case h of
'.' -> ext
_ -> e
|
72c14171af7c1e26fe9a339fe6b9b801cdafddd44a6fc818fa31bb44cd28c738 | aumouvantsillage/Virgule-CPU | hello.rkt | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
#lang racket
(require
(except-in hydromel/support zero)
"../virgule/asm/assembler.rkt"
"../virgule/devices/memory.rkt"
"system.mel")
(define-values (hello-len hello-data)
(asm->memory
(LI t0 text_address)
(LA t1 'str) ; The address of the string
'loop
(LBU t2 t1) ; Read a character from the string
If zero , loop indefinitely
(SB t2 t0 4) ; Send the current character
(ADDI t1 t1 1) ; Move to the next location in the string
(J 'loop) ; Loop
'str
(bytes->words #:asciiz #t
#"Virgule says\n<< Hello! >>\n")))
(define sys (system hello-len hello-data))
(define disp (signal-take (instance-ref sys '(text disp)) 500))
| null | https://raw.githubusercontent.com/aumouvantsillage/Virgule-CPU/1be168c9740795e6f0bdac23d23dc26250e8a7d3/virgule-demos/hello.rkt | racket | The address of the string
Read a character from the string
Send the current character
Move to the next location in the string
Loop | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
#lang racket
(require
(except-in hydromel/support zero)
"../virgule/asm/assembler.rkt"
"../virgule/devices/memory.rkt"
"system.mel")
(define-values (hello-len hello-data)
(asm->memory
(LI t0 text_address)
'loop
If zero , loop indefinitely
'str
(bytes->words #:asciiz #t
#"Virgule says\n<< Hello! >>\n")))
(define sys (system hello-len hello-data))
(define disp (signal-take (instance-ref sys '(text disp)) 500))
|
ab7279fcadb9f28eff0572572abb8ce31e97fcaa8c259dee9b7ff5d9f8bdd366 | 8c6794b6/guile-tjit | srfi-43.scm | srfi-43.scm -- SRFI 43 Vector library
Copyright ( C ) 2014 Free Software Foundation , Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 3 of the License , or ( at your option ) any later version .
;;
;; This library is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; Lesser General Public License for more details.
;;
You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA
Author : < >
(define-module (srfi srfi-43)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-8)
#:re-export (make-vector vector vector? vector-ref vector-set!
vector-length)
#:replace (vector-copy vector-fill! list->vector vector->list)
#:export (vector-empty? vector= vector-unfold vector-unfold-right
vector-reverse-copy
vector-append vector-concatenate
vector-fold vector-fold-right
vector-map vector-map!
vector-for-each vector-count
vector-index vector-index-right
vector-skip vector-skip-right
vector-binary-search
vector-any vector-every
vector-swap! vector-reverse!
vector-copy! vector-reverse-copy!
reverse-vector->list
reverse-list->vector))
(cond-expand-provide (current-module) '(srfi-43))
(define (error-from who msg . args)
(apply error
(string-append (symbol->string who) ": " msg)
args))
(define-syntax-rule (assert-nonneg-exact-integer k who)
(unless (and (exact-integer? k)
(not (negative? k)))
(error-from who "expected non-negative exact integer, got" k)))
(define-syntax-rule (assert-procedure f who)
(unless (procedure? f)
(error-from who "expected procedure, got" f)))
(define-syntax-rule (assert-vector v who)
(unless (vector? v)
(error-from who "expected vector, got" v)))
(define-syntax-rule (assert-valid-index i len who)
(unless (and (exact-integer? i)
(<= 0 i len))
(error-from who "invalid index" i)))
(define-syntax-rule (assert-valid-start start len who)
(unless (and (exact-integer? start)
(<= 0 start len))
(error-from who "invalid start index" start)))
(define-syntax-rule (assert-valid-range start end len who)
(unless (and (exact-integer? start)
(exact-integer? end)
(<= 0 start end len))
(error-from who "invalid index range" start end)))
(define-syntax-rule (assert-vectors vs who)
(let loop ((vs vs))
(unless (null? vs)
(assert-vector (car vs) who)
(loop (cdr vs)))))
Return the length of the shortest vector in VS .
VS must have at least one element .
(define (min-length vs)
(let loop ((vs (cdr vs))
(result (vector-length (car vs))))
(if (null? vs)
result
(loop (cdr vs) (min result (vector-length (car vs)))))))
Return a list of the Ith elements of the vectors in VS .
(define (vectors-ref vs i)
(let loop ((vs vs) (xs '()))
(if (null? vs)
(reverse! xs)
(loop (cdr vs) (cons (vector-ref (car vs) i)
xs)))))
(define vector-unfold
(case-lambda
"(vector-unfold f length initial-seed ...) -> vector
The fundamental vector constructor. Create a vector whose length is
LENGTH and iterates across each index k from 0 up to LENGTH - 1,
applying F at each iteration to the current index and current seeds, in
that order, to receive n + 1 values: the element to put in the kth slot
of the new vector, and n new seeds for the next iteration. It is an
error for the number of seeds to vary between iterations."
((f len)
(assert-procedure f 'vector-unfold)
(assert-nonneg-exact-integer len 'vector-unfold)
(let ((v (make-vector len)))
(let loop ((i 0))
(unless (= i len)
(vector-set! v i (f i))
(loop (+ i 1))))
v))
((f len seed)
(assert-procedure f 'vector-unfold)
(assert-nonneg-exact-integer len 'vector-unfold)
(let ((v (make-vector len)))
(let loop ((i 0) (seed seed))
(unless (= i len)
(receive (x seed) (f i seed)
(vector-set! v i x)
(loop (+ i 1) seed))))
v))
((f len seed1 seed2)
(assert-procedure f 'vector-unfold)
(assert-nonneg-exact-integer len 'vector-unfold)
(let ((v (make-vector len)))
(let loop ((i 0) (seed1 seed1) (seed2 seed2))
(unless (= i len)
(receive (x seed1 seed2) (f i seed1 seed2)
(vector-set! v i x)
(loop (+ i 1) seed1 seed2))))
v))
((f len . seeds)
(assert-procedure f 'vector-unfold)
(assert-nonneg-exact-integer len 'vector-unfold)
(let ((v (make-vector len)))
(let loop ((i 0) (seeds seeds))
(unless (= i len)
(receive (x . seeds) (apply f i seeds)
(vector-set! v i x)
(loop (+ i 1) seeds))))
v))))
(define vector-unfold-right
(case-lambda
"(vector-unfold-right f length initial-seed ...) -> vector
The fundamental vector constructor. Create a vector whose length is
LENGTH and iterates across each index k from LENGTH - 1 down to 0,
applying F at each iteration to the current index and current seeds, in
that order, to receive n + 1 values: the element to put in the kth slot
of the new vector, and n new seeds for the next iteration. It is an
error for the number of seeds to vary between iterations."
((f len)
(assert-procedure f 'vector-unfold-right)
(assert-nonneg-exact-integer len 'vector-unfold-right)
(let ((v (make-vector len)))
(let loop ((i (- len 1)))
(unless (negative? i)
(vector-set! v i (f i))
(loop (- i 1))))
v))
((f len seed)
(assert-procedure f 'vector-unfold-right)
(assert-nonneg-exact-integer len 'vector-unfold-right)
(let ((v (make-vector len)))
(let loop ((i (- len 1)) (seed seed))
(unless (negative? i)
(receive (x seed) (f i seed)
(vector-set! v i x)
(loop (- i 1) seed))))
v))
((f len seed1 seed2)
(assert-procedure f 'vector-unfold-right)
(assert-nonneg-exact-integer len 'vector-unfold-right)
(let ((v (make-vector len)))
(let loop ((i (- len 1)) (seed1 seed1) (seed2 seed2))
(unless (negative? i)
(receive (x seed1 seed2) (f i seed1 seed2)
(vector-set! v i x)
(loop (- i 1) seed1 seed2))))
v))
((f len . seeds)
(assert-procedure f 'vector-unfold-right)
(assert-nonneg-exact-integer len 'vector-unfold-right)
(let ((v (make-vector len)))
(let loop ((i (- len 1)) (seeds seeds))
(unless (negative? i)
(receive (x . seeds) (apply f i seeds)
(vector-set! v i x)
(loop (- i 1) seeds))))
v))))
(define guile-vector-copy (@ (guile) vector-copy))
TODO : Enhance core ' vector - copy ' to do this .
(define vector-copy
(case-lambda*
"(vector-copy vec [start [end [fill]]]) -> vector
Allocate a new vector whose length is END - START and fills it with
elements from vec, taking elements from vec starting at index START
and stopping at index END. START defaults to 0 and END defaults to
the value of (vector-length VEC). If END extends beyond the length of
VEC, the slots in the new vector that obviously cannot be filled by
elements from VEC are filled with FILL, whose default value is
unspecified."
((v) (guile-vector-copy v))
((v start)
(assert-vector v 'vector-copy)
(let ((len (vector-length v)))
(assert-valid-start start len 'vector-copy)
(let ((result (make-vector (- len start))))
(vector-move-left! v start len result 0)
result)))
((v start end #:optional (fill *unspecified*))
(assert-vector v 'vector-copy)
(let ((len (vector-length v)))
(unless (and (exact-integer? start)
(exact-integer? end)
(<= 0 start end))
(error-from 'vector-copy "invalid index range" start end))
(let ((result (make-vector (- end start) fill)))
(vector-move-left! v start (min end len) result 0)
result)))))
(define vector-reverse-copy
(let ()
(define (%vector-reverse-copy vec start end)
(let* ((len (- end start))
(result (make-vector len)))
(let loop ((i 0) (j (- end 1)))
(unless (= i len)
(vector-set! result i (vector-ref vec j))
(loop (+ i 1) (- j 1))))
result))
(case-lambda
"(vector-reverse-copy vec [start [end]]) -> vector
Allocate a new vector whose length is END - START and fills it with
elements from vec, taking elements from vec in reverse order starting
at index START and stopping at index END. START defaults to 0 and END
defaults to the value of (vector-length VEC)."
((vec)
(assert-vector vec 'vector-reverse-copy)
(%vector-reverse-copy vec 0 (vector-length vec)))
((vec start)
(assert-vector vec 'vector-reverse-copy)
(let ((len (vector-length vec)))
(assert-valid-start start len 'vector-reverse-copy)
(%vector-reverse-copy vec start len)))
((vec start end)
(assert-vector vec 'vector-reverse-copy)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'vector-reverse-copy)
(%vector-reverse-copy vec start end))))))
(define (%vector-concatenate vs)
(let* ((result-len (let loop ((vs vs) (len 0))
(if (null? vs)
len
(loop (cdr vs) (+ len (vector-length (car vs)))))))
(result (make-vector result-len)))
(let loop ((vs vs) (pos 0))
(unless (null? vs)
(let* ((v (car vs))
(len (vector-length v)))
(vector-move-left! v 0 len result pos)
(loop (cdr vs) (+ pos len)))))
result))
(define vector-append
(case-lambda
"(vector-append vec ...) -> vector
Return a newly allocated vector that contains all elements in order
from the subsequent locations in VEC ..."
(() (vector))
((v)
(assert-vector v 'vector-append)
(guile-vector-copy v))
((v1 v2)
(assert-vector v1 'vector-append)
(assert-vector v2 'vector-append)
(let ((len1 (vector-length v1))
(len2 (vector-length v2)))
(let ((result (make-vector (+ len1 len2))))
(vector-move-left! v1 0 len1 result 0)
(vector-move-left! v2 0 len2 result len1)
result)))
(vs
(assert-vectors vs 'vector-append)
(%vector-concatenate vs))))
(define (vector-concatenate vs)
"(vector-concatenate list-of-vectors) -> vector
Append each vector in LIST-OF-VECTORS. Equivalent to:
(apply vector-append LIST-OF-VECTORS)"
(assert-vectors vs 'vector-concatenate)
(%vector-concatenate vs))
(define (vector-empty? vec)
"(vector-empty? vec) -> boolean
Return true if VEC is empty, i.e. its length is 0, and false if not."
(assert-vector vec 'vector-empty?)
(zero? (vector-length vec)))
(define vector=
(let ()
(define (all-of-length? len vs)
(or (null? vs)
(and (= len (vector-length (car vs)))
(all-of-length? len (cdr vs)))))
(define (=up-to? i elt=? v1 v2)
(or (negative? i)
(let ((x1 (vector-ref v1 i))
(x2 (vector-ref v2 i)))
(and (or (eq? x1 x2) (elt=? x1 x2))
(=up-to? (- i 1) elt=? v1 v2)))))
(case-lambda
"(vector= elt=? vec ...) -> boolean
Return true if the vectors VEC ... have equal lengths and equal
elements according to ELT=?. ELT=? is always applied to two
arguments. Element comparison must be consistent with eq?, in the
following sense: if (eq? a b) returns true, then (elt=? a b) must also
return true. The order in which comparisons are performed is
unspecified."
((elt=?)
(assert-procedure elt=? 'vector=)
#t)
((elt=? v)
(assert-procedure elt=? 'vector=)
(assert-vector v 'vector=)
#t)
((elt=? v1 v2)
(assert-procedure elt=? 'vector=)
(assert-vector v1 'vector=)
(assert-vector v2 'vector=)
(let ((len (vector-length v1)))
(and (= len (vector-length v2))
(=up-to? (- len 1) elt=? v1 v2))))
((elt=? v1 . vs)
(assert-procedure elt=? 'vector=)
(assert-vector v1 'vector=)
(assert-vectors vs 'vector=)
(let ((len (vector-length v1)))
(and (all-of-length? len vs)
(let loop ((vs vs))
(or (null? vs)
(and (=up-to? (- len 1) elt=? v1 (car vs))
(loop (cdr vs)))))))))))
(define vector-fold
(case-lambda
"(vector-fold kons knil vec1 vec2 ...) -> value
The fundamental vector iterator. KONS is iterated over each index in
all of the vectors, stopping at the end of the shortest; KONS is
applied as (KONS i state (vector-ref VEC1 i) (vector-ref VEC2 i) ...)
where STATE is the current state value, and I is the current index.
The current state value begins with KNIL, and becomes whatever KONS
returned at the respective iteration. The iteration is strictly
left-to-right."
((kcons knil v)
(assert-procedure kcons 'vector-fold)
(assert-vector v 'vector-fold)
(let ((len (vector-length v)))
(let loop ((i 0) (state knil))
(if (= i len)
state
(loop (+ i 1) (kcons i state (vector-ref v i)))))))
((kcons knil v1 v2)
(assert-procedure kcons 'vector-fold)
(assert-vector v1 'vector-fold)
(assert-vector v2 'vector-fold)
(let ((len (min (vector-length v1) (vector-length v2))))
(let loop ((i 0) (state knil))
(if (= i len)
state
(loop (+ i 1)
(kcons i state (vector-ref v1 i) (vector-ref v2 i)))))))
((kcons knil . vs)
(assert-procedure kcons 'vector-fold)
(assert-vectors vs 'vector-fold)
(let ((len (min-length vs)))
(let loop ((i 0) (state knil))
(if (= i len)
state
(loop (+ i 1) (apply kcons i state (vectors-ref vs i)))))))))
(define vector-fold-right
(case-lambda
"(vector-fold-right kons knil vec1 vec2 ...) -> value
The fundamental vector iterator. KONS is iterated over each index in
all of the vectors, starting at the end of the shortest; KONS is
applied as (KONS i state (vector-ref VEC1 i) (vector-ref VEC2 i) ...)
where STATE is the current state value, and I is the current index.
The current state value begins with KNIL, and becomes whatever KONS
returned at the respective iteration. The iteration is strictly
right-to-left."
((kcons knil v)
(assert-procedure kcons 'vector-fold-right)
(assert-vector v 'vector-fold-right)
(let ((len (vector-length v)))
(let loop ((i (- len 1)) (state knil))
(if (negative? i)
state
(loop (- i 1) (kcons i state (vector-ref v i)))))))
((kcons knil v1 v2)
(assert-procedure kcons 'vector-fold-right)
(assert-vector v1 'vector-fold-right)
(assert-vector v2 'vector-fold-right)
(let ((len (min (vector-length v1) (vector-length v2))))
(let loop ((i (- len 1)) (state knil))
(if (negative? i)
state
(loop (- i 1)
(kcons i state (vector-ref v1 i) (vector-ref v2 i)))))))
((kcons knil . vs)
(assert-procedure kcons 'vector-fold-right)
(assert-vectors vs 'vector-fold-right)
(let ((len (min-length vs)))
(let loop ((i (- len 1)) (state knil))
(if (negative? i)
state
(loop (- i 1) (apply kcons i state (vectors-ref vs i)))))))))
(define vector-map
(case-lambda
"(vector-map f vec2 vec2 ...) -> vector
Return a new vector of the shortest size of the vector arguments.
Each element at index i of the new vector is mapped from the old
vectors by (F i (vector-ref VEC1 i) (vector-ref VEC2 i) ...). The
dynamic order of application of F is unspecified."
((f v)
(assert-procedure f 'vector-map)
(assert-vector v 'vector-map)
(let* ((len (vector-length v))
(result (make-vector len)))
(let loop ((i 0))
(unless (= i len)
(vector-set! result i (f i (vector-ref v i)))
(loop (+ i 1))))
result))
((f v1 v2)
(assert-procedure f 'vector-map)
(assert-vector v1 'vector-map)
(assert-vector v2 'vector-map)
(let* ((len (min (vector-length v1) (vector-length v2)))
(result (make-vector len)))
(let loop ((i 0))
(unless (= i len)
(vector-set! result i (f i (vector-ref v1 i) (vector-ref v2 i)))
(loop (+ i 1))))
result))
((f . vs)
(assert-procedure f 'vector-map)
(assert-vectors vs 'vector-map)
(let* ((len (min-length vs))
(result (make-vector len)))
(let loop ((i 0))
(unless (= i len)
(vector-set! result i (apply f i (vectors-ref vs i)))
(loop (+ i 1))))
result))))
(define vector-map!
(case-lambda
"(vector-map! f vec2 vec2 ...) -> unspecified
Similar to vector-map, but rather than mapping the new elements into a
new vector, the new mapped elements are destructively inserted into
VEC1. The dynamic order of application of F is unspecified."
((f v)
(assert-procedure f 'vector-map!)
(assert-vector v 'vector-map!)
(let ((len (vector-length v)))
(let loop ((i 0))
(unless (= i len)
(vector-set! v i (f i (vector-ref v i)))
(loop (+ i 1))))))
((f v1 v2)
(assert-procedure f 'vector-map!)
(assert-vector v1 'vector-map!)
(assert-vector v2 'vector-map!)
(let ((len (min (vector-length v1) (vector-length v2))))
(let loop ((i 0))
(unless (= i len)
(vector-set! v1 i (f i (vector-ref v1 i) (vector-ref v2 i)))
(loop (+ i 1))))))
((f . vs)
(assert-procedure f 'vector-map!)
(assert-vectors vs 'vector-map!)
(let ((len (min-length vs))
(v1 (car vs)))
(let loop ((i 0))
(unless (= i len)
(vector-set! v1 i (apply f i (vectors-ref vs i)))
(loop (+ i 1))))))))
(define vector-for-each
(case-lambda
"(vector-for-each f vec1 vec2 ...) -> unspecified
Call (F i VEC1[i] VEC2[i] ...) for each index i less than the length
of the shortest vector passed. The iteration is strictly
left-to-right."
((f v)
(assert-procedure f 'vector-for-each)
(assert-vector v 'vector-for-each)
(let ((len (vector-length v)))
(let loop ((i 0))
(unless (= i len)
(f i (vector-ref v i))
(loop (+ i 1))))))
((f v1 v2)
(assert-procedure f 'vector-for-each)
(assert-vector v1 'vector-for-each)
(assert-vector v2 'vector-for-each)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i 0))
(unless (= i len)
(f i (vector-ref v1 i) (vector-ref v2 i))
(loop (+ i 1))))))
((f . vs)
(assert-procedure f 'vector-for-each)
(assert-vectors vs 'vector-for-each)
(let ((len (min-length vs)))
(let loop ((i 0))
(unless (= i len)
(apply f i (vectors-ref vs i))
(loop (+ i 1))))))))
(define vector-count
(case-lambda
"(vector-count pred? vec1 vec2 ...) -> exact nonnegative integer
Count the number of indices i for which (PRED? VEC1[i] VEC2[i] ...)
returns true, where i is less than the length of the shortest vector
passed."
((pred? v)
(assert-procedure pred? 'vector-count)
(assert-vector v 'vector-count)
(let ((len (vector-length v)))
(let loop ((i 0) (count 0))
(cond ((= i len) count)
((pred? i (vector-ref v i))
(loop (+ i 1) (+ count 1)))
(else
(loop (+ i 1) count))))))
((pred? v1 v2)
(assert-procedure pred? 'vector-count)
(assert-vector v1 'vector-count)
(assert-vector v2 'vector-count)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i 0) (count 0))
(cond ((= i len) count)
((pred? i (vector-ref v1 i) (vector-ref v2 i))
(loop (+ i 1) (+ count 1)))
(else
(loop (+ i 1) count))))))
((pred? . vs)
(assert-procedure pred? 'vector-count)
(assert-vectors vs 'vector-count)
(let ((len (min-length vs)))
(let loop ((i 0) (count 0))
(cond ((= i len) count)
((apply pred? i (vectors-ref vs i))
(loop (+ i 1) (+ count 1)))
(else
(loop (+ i 1) count))))))))
(define vector-index
(case-lambda
"(vector-index pred? vec1 vec2 ...) -> exact nonnegative integer or #f
Find and return the index of the first elements in VEC1 VEC2 ... that
satisfy PRED?. If no matching element is found by the end of the
shortest vector, return #f."
((pred? v)
(assert-procedure pred? 'vector-index)
(assert-vector v 'vector-index)
(let ((len (vector-length v)))
(let loop ((i 0))
(and (< i len)
(if (pred? (vector-ref v i))
i
(loop (+ i 1)))))))
((pred? v1 v2)
(assert-procedure pred? 'vector-index)
(assert-vector v1 'vector-index)
(assert-vector v2 'vector-index)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i 0))
(and (< i len)
(if (pred? (vector-ref v1 i)
(vector-ref v2 i))
i
(loop (+ i 1)))))))
((pred? . vs)
(assert-procedure pred? 'vector-index)
(assert-vectors vs 'vector-index)
(let ((len (min-length vs)))
(let loop ((i 0))
(and (< i len)
(if (apply pred? (vectors-ref vs i))
i
(loop (+ i 1)))))))))
(define vector-index-right
(case-lambda
"(vector-index-right pred? vec1 vec2 ...) -> exact nonnegative integer or #f
Find and return the index of the last elements in VEC1 VEC2 ... that
satisfy PRED?, searching from right-to-left. If no matching element
is found before the end of the shortest vector, return #f."
((pred? v)
(assert-procedure pred? 'vector-index-right)
(assert-vector v 'vector-index-right)
(let ((len (vector-length v)))
(let loop ((i (- len 1)))
(and (>= i 0)
(if (pred? (vector-ref v i))
i
(loop (- i 1)))))))
((pred? v1 v2)
(assert-procedure pred? 'vector-index-right)
(assert-vector v1 'vector-index-right)
(assert-vector v2 'vector-index-right)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i (- len 1)))
(and (>= i 0)
(if (pred? (vector-ref v1 i)
(vector-ref v2 i))
i
(loop (- i 1)))))))
((pred? . vs)
(assert-procedure pred? 'vector-index-right)
(assert-vectors vs 'vector-index-right)
(let ((len (min-length vs)))
(let loop ((i (- len 1)))
(and (>= i 0)
(if (apply pred? (vectors-ref vs i))
i
(loop (- i 1)))))))))
(define vector-skip
(case-lambda
"(vector-skip pred? vec1 vec2 ...) -> exact nonnegative integer or #f
Find and return the index of the first elements in VEC1 VEC2 ... that
do not satisfy PRED?. If no matching element is found by the end of
the shortest vector, return #f."
((pred? v)
(assert-procedure pred? 'vector-skip)
(assert-vector v 'vector-skip)
(let ((len (vector-length v)))
(let loop ((i 0))
(and (< i len)
(if (pred? (vector-ref v i))
(loop (+ i 1))
i)))))
((pred? v1 v2)
(assert-procedure pred? 'vector-skip)
(assert-vector v1 'vector-skip)
(assert-vector v2 'vector-skip)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i 0))
(and (< i len)
(if (pred? (vector-ref v1 i)
(vector-ref v2 i))
(loop (+ i 1))
i)))))
((pred? . vs)
(assert-procedure pred? 'vector-skip)
(assert-vectors vs 'vector-skip)
(let ((len (min-length vs)))
(let loop ((i 0))
(and (< i len)
(if (apply pred? (vectors-ref vs i))
(loop (+ i 1))
i)))))))
(define vector-skip-right
(case-lambda
"(vector-skip-right pred? vec1 vec2 ...) -> exact nonnegative integer or #f
Find and return the index of the last elements in VEC1 VEC2 ... that
do not satisfy PRED?, searching from right-to-left. If no matching
element is found before the end of the shortest vector, return #f."
((pred? v)
(assert-procedure pred? 'vector-skip-right)
(assert-vector v 'vector-skip-right)
(let ((len (vector-length v)))
(let loop ((i (- len 1)))
(and (not (negative? i))
(if (pred? (vector-ref v i))
(loop (- i 1))
i)))))
((pred? v1 v2)
(assert-procedure pred? 'vector-skip-right)
(assert-vector v1 'vector-skip-right)
(assert-vector v2 'vector-skip-right)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i (- len 1)))
(and (not (negative? i))
(if (pred? (vector-ref v1 i)
(vector-ref v2 i))
(loop (- i 1))
i)))))
((pred? . vs)
(assert-procedure pred? 'vector-skip-right)
(assert-vectors vs 'vector-skip-right)
(let ((len (min-length vs)))
(let loop ((i (- len 1)))
(and (not (negative? i))
(if (apply pred? (vectors-ref vs i))
(loop (- i 1))
i)))))))
(define vector-binary-search
(let ()
(define (%vector-binary-search vec value cmp start end)
(let loop ((lo start) (hi end))
(and (< lo hi)
(let* ((i (quotient (+ lo hi) 2))
(x (vector-ref vec i))
(c (cmp x value)))
(cond ((zero? c) i)
((positive? c) (loop lo i))
((negative? c) (loop (+ i 1) hi)))))))
(case-lambda
"(vector-binary-search vec value cmp [start [end]]) -> exact nonnegative integer or #f
Find and return an index of VEC between START and END whose value is
VALUE using a binary search. If no matching element is found, return
#f. The default START is 0 and the default END is the length of VEC.
CMP must be a procedure of two arguments such that (CMP A B) returns
a negative integer if A < B, a positive integer if A > B, or zero if
A = B. The elements of VEC must be sorted in non-decreasing order
according to CMP."
((vec value cmp)
(assert-vector vec 'vector-binary-search)
(assert-procedure cmp 'vector-binary-search)
(%vector-binary-search vec value cmp 0 (vector-length vec)))
((vec value cmp start)
(assert-vector vec 'vector-binary-search)
(let ((len (vector-length vec)))
(assert-valid-start start len 'vector-binary-search)
(%vector-binary-search vec value cmp start len)))
((vec value cmp start end)
(assert-vector vec 'vector-binary-search)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'vector-binary-search)
(%vector-binary-search vec value cmp start end))))))
(define vector-any
(case-lambda
"(vector-any pred? vec1 vec2 ...) -> value or #f
Find the first parallel set of elements from VEC1 VEC2 ... for which
PRED? returns a true value. If such a parallel set of elements
exists, vector-any returns the value that PRED? returned for that set
of elements. The iteration is strictly left-to-right."
((pred? v)
(assert-procedure pred? 'vector-any)
(assert-vector v 'vector-any)
(let ((len (vector-length v)))
(let loop ((i 0))
(and (< i len)
(or (pred? (vector-ref v i))
(loop (+ i 1)))))))
((pred? v1 v2)
(assert-procedure pred? 'vector-any)
(assert-vector v1 'vector-any)
(assert-vector v2 'vector-any)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i 0))
(and (< i len)
(or (pred? (vector-ref v1 i)
(vector-ref v2 i))
(loop (+ i 1)))))))
((pred? . vs)
(assert-procedure pred? 'vector-any)
(assert-vectors vs 'vector-any)
(let ((len (min-length vs)))
(let loop ((i 0))
(and (< i len)
(or (apply pred? (vectors-ref vs i))
(loop (+ i 1)))))))))
(define vector-every
(case-lambda
"(vector-every pred? vec1 vec2 ...) -> value or #f
If, for every index i less than the length of the shortest vector
argument, the set of elements VEC1[i] VEC2[i] ... satisfies PRED?,
vector-every returns the value that PRED? returned for the last set of
elements, at the last index of the shortest vector. The iteration is
strictly left-to-right."
((pred? v)
(assert-procedure pred? 'vector-every)
(assert-vector v 'vector-every)
(let ((len (vector-length v)))
(or (zero? len)
(let loop ((i 0))
(let ((val (pred? (vector-ref v i)))
(next-i (+ i 1)))
(if (or (not val) (= next-i len))
val
(loop next-i)))))))
((pred? v1 v2)
(assert-procedure pred? 'vector-every)
(assert-vector v1 'vector-every)
(assert-vector v2 'vector-every)
(let ((len (min (vector-length v1)
(vector-length v2))))
(or (zero? len)
(let loop ((i 0))
(let ((val (pred? (vector-ref v1 i)
(vector-ref v2 i)))
(next-i (+ i 1)))
(if (or (not val) (= next-i len))
val
(loop next-i)))))))
((pred? . vs)
(assert-procedure pred? 'vector-every)
(assert-vectors vs 'vector-every)
(let ((len (min-length vs)))
(or (zero? len)
(let loop ((i 0))
(let ((val (apply pred? (vectors-ref vs i)))
(next-i (+ i 1)))
(if (or (not val) (= next-i len))
val
(loop next-i)))))))))
(define (vector-swap! vec i j)
"(vector-swap! vec i j) -> unspecified
Swap the values of the locations in VEC at I and J."
(assert-vector vec 'vector-swap!)
(let ((len (vector-length vec)))
(assert-valid-index i len 'vector-swap!)
(assert-valid-index j len 'vector-swap!)
(let ((tmp (vector-ref vec i)))
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j tmp))))
TODO : Enhance core ' vector - fill ! ' to do this .
(define vector-fill!
(let ()
(define guile-vector-fill!
(@ (guile) vector-fill!))
(define (%vector-fill! vec fill start end)
(let loop ((i start))
(when (< i end)
(vector-set! vec i fill)
(loop (+ i 1)))))
(case-lambda
"(vector-fill! vec fill [start [end]]) -> unspecified
Assign the value of every location in VEC between START and END to
FILL. START defaults to 0 and END defaults to the length of VEC."
((vec fill)
(guile-vector-fill! vec fill))
((vec fill start)
(assert-vector vec 'vector-fill!)
(let ((len (vector-length vec)))
(assert-valid-start start len 'vector-fill!)
(%vector-fill! vec fill start len)))
((vec fill start end)
(assert-vector vec 'vector-fill!)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'vector-fill!)
(%vector-fill! vec fill start end))))))
(define (%vector-reverse! vec start end)
(let loop ((i start) (j (- end 1)))
(when (< i j)
(let ((tmp (vector-ref vec i)))
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j tmp)
(loop (+ i 1) (- j 1))))))
(define vector-reverse!
(case-lambda
"(vector-reverse! vec [start [end]]) -> unspecified
Destructively reverse the contents of VEC between START and END.
START defaults to 0 and END defaults to the length of VEC."
((vec)
(assert-vector vec 'vector-reverse!)
(%vector-reverse! vec 0 (vector-length vec)))
((vec start)
(assert-vector vec 'vector-reverse!)
(let ((len (vector-length vec)))
(assert-valid-start start len 'vector-reverse!)
(%vector-reverse! vec start len)))
((vec start end)
(assert-vector vec 'vector-reverse!)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'vector-reverse!)
(%vector-reverse! vec start end)))))
(define-syntax-rule (define-vector-copier! copy! docstring inner-proc)
(define copy!
(let ((%copy! inner-proc))
(case-lambda
docstring
((target tstart source)
(assert-vector target 'copy!)
(assert-vector source 'copy!)
(let ((tlen (vector-length target))
(slen (vector-length source)))
(assert-valid-start tstart tlen 'copy!)
(unless (>= tlen (+ tstart slen))
(error-from 'copy! "would write past end of target"))
(%copy! target tstart source 0 slen)))
((target tstart source sstart)
(assert-vector target 'copy!)
(assert-vector source 'copy!)
(let ((tlen (vector-length target))
(slen (vector-length source)))
(assert-valid-start tstart tlen 'copy!)
(assert-valid-start sstart slen 'copy!)
(unless (>= tlen (+ tstart (- slen sstart)))
(error-from 'copy! "would write past end of target"))
(%copy! target tstart source sstart slen)))
((target tstart source sstart send)
(assert-vector target 'copy!)
(assert-vector source 'copy!)
(let ((tlen (vector-length target))
(slen (vector-length source)))
(assert-valid-start tstart tlen 'copy!)
(assert-valid-range sstart send slen 'copy!)
(unless (>= tlen (+ tstart (- send sstart)))
(error-from 'copy! "would write past end of target"))
(%copy! target tstart source sstart send)))))))
(define-vector-copier! vector-copy!
"(vector-copy! target tstart source [sstart [send]]) -> unspecified
Copy a block of elements from SOURCE to TARGET, both of which must be
vectors, starting in TARGET at TSTART and starting in SOURCE at
SSTART, ending when SEND - SSTART elements have been copied. It is an
error for TARGET to have a length less than TSTART + (SEND - SSTART).
SSTART defaults to 0 and SEND defaults to the length of SOURCE."
(lambda (target tstart source sstart send)
(if (< tstart sstart)
(vector-move-left! source sstart send target tstart)
(vector-move-right! source sstart send target tstart))))
(define-vector-copier! vector-reverse-copy!
"(vector-reverse-copy! target tstart source [sstart [send]]) -> unspecified
Like vector-copy!, but copy the elements in the reverse order. It is
an error if TARGET and SOURCE are identical vectors and the TARGET and
however , if TSTART = SSTART ,
vector-reverse-copy! behaves as (vector-reverse! TARGET TSTART SEND)
would."
(lambda (target tstart source sstart send)
(if (and (eq? target source) (= tstart sstart))
(%vector-reverse! target sstart send)
(let loop ((i tstart) (j (- send 1)))
(when (>= j sstart)
(vector-set! target i (vector-ref source j))
(loop (+ i 1) (- j 1)))))))
(define vector->list
(let ()
(define (%vector->list vec start end)
(let loop ((i (- end 1))
(result '()))
(if (< i start)
result
(loop (- i 1) (cons (vector-ref vec i) result)))))
(case-lambda
"(vector->list vec [start [end]]) -> proper-list
Return a newly allocated list containing the elements in VEC between
START and END. START defaults to 0 and END defaults to the length of
VEC."
((vec)
(assert-vector vec 'vector->list)
(%vector->list vec 0 (vector-length vec)))
((vec start)
(assert-vector vec 'vector->list)
(let ((len (vector-length vec)))
(assert-valid-start start len 'vector->list)
(%vector->list vec start len)))
((vec start end)
(assert-vector vec 'vector->list)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'vector->list)
(%vector->list vec start end))))))
(define reverse-vector->list
(let ()
(define (%reverse-vector->list vec start end)
(let loop ((i start)
(result '()))
(if (>= i end)
result
(loop (+ i 1) (cons (vector-ref vec i) result)))))
(case-lambda
"(reverse-vector->list vec [start [end]]) -> proper-list
Return a newly allocated list containing the elements in VEC between
START and END in reverse order. START defaults to 0 and END defaults
to the length of VEC."
((vec)
(assert-vector vec 'reverse-vector->list)
(%reverse-vector->list vec 0 (vector-length vec)))
((vec start)
(assert-vector vec 'reverse-vector->list)
(let ((len (vector-length vec)))
(assert-valid-start start len 'reverse-vector->list)
(%reverse-vector->list vec start len)))
((vec start end)
(assert-vector vec 'reverse-vector->list)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'reverse-vector->list)
(%reverse-vector->list vec start end))))))
;; TODO: change to use 'case-lambda' and improve error checking.
(define* (list->vector lst #:optional (start 0) (end (length lst)))
"(list->vector proper-list [start [end]]) -> vector
Return a newly allocated vector of the elements from PROPER-LIST with
indices between START and END. START defaults to 0 and END defaults
to the length of PROPER-LIST."
(let* ((len (- end start))
(result (make-vector len)))
(let loop ((i 0) (lst (drop lst start)))
(if (= i len)
result
(begin (vector-set! result i (car lst))
(loop (+ i 1) (cdr lst)))))))
;; TODO: change to use 'case-lambda' and improve error checking.
(define* (reverse-list->vector lst #:optional (start 0) (end (length lst)))
"(reverse-list->vector proper-list [start [end]]) -> vector
Return a newly allocated vector of the elements from PROPER-LIST with
indices between START and END, in reverse order. START defaults to 0
and END defaults to the length of PROPER-LIST."
(let* ((len (- end start))
(result (make-vector len)))
(let loop ((i (- len 1)) (lst (drop lst start)))
(if (negative? i)
result
(begin (vector-set! result i (car lst))
(loop (- i 1) (cdr lst)))))))
| null | https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/module/srfi/srfi-43.scm | scheme |
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
either
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
License along with this library; if not, write to the Free Software
KONS is
KONS is
TODO: change to use 'case-lambda' and improve error checking.
TODO: change to use 'case-lambda' and improve error checking. | srfi-43.scm -- SRFI 43 Vector library
Copyright ( C ) 2014 Free Software Foundation , Inc.
version 3 of the License , or ( at your option ) any later version .
You should have received a copy of the GNU Lesser General Public
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA
Author : < >
(define-module (srfi srfi-43)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-8)
#:re-export (make-vector vector vector? vector-ref vector-set!
vector-length)
#:replace (vector-copy vector-fill! list->vector vector->list)
#:export (vector-empty? vector= vector-unfold vector-unfold-right
vector-reverse-copy
vector-append vector-concatenate
vector-fold vector-fold-right
vector-map vector-map!
vector-for-each vector-count
vector-index vector-index-right
vector-skip vector-skip-right
vector-binary-search
vector-any vector-every
vector-swap! vector-reverse!
vector-copy! vector-reverse-copy!
reverse-vector->list
reverse-list->vector))
(cond-expand-provide (current-module) '(srfi-43))
(define (error-from who msg . args)
(apply error
(string-append (symbol->string who) ": " msg)
args))
(define-syntax-rule (assert-nonneg-exact-integer k who)
(unless (and (exact-integer? k)
(not (negative? k)))
(error-from who "expected non-negative exact integer, got" k)))
(define-syntax-rule (assert-procedure f who)
(unless (procedure? f)
(error-from who "expected procedure, got" f)))
(define-syntax-rule (assert-vector v who)
(unless (vector? v)
(error-from who "expected vector, got" v)))
(define-syntax-rule (assert-valid-index i len who)
(unless (and (exact-integer? i)
(<= 0 i len))
(error-from who "invalid index" i)))
(define-syntax-rule (assert-valid-start start len who)
(unless (and (exact-integer? start)
(<= 0 start len))
(error-from who "invalid start index" start)))
(define-syntax-rule (assert-valid-range start end len who)
(unless (and (exact-integer? start)
(exact-integer? end)
(<= 0 start end len))
(error-from who "invalid index range" start end)))
(define-syntax-rule (assert-vectors vs who)
(let loop ((vs vs))
(unless (null? vs)
(assert-vector (car vs) who)
(loop (cdr vs)))))
Return the length of the shortest vector in VS .
VS must have at least one element .
(define (min-length vs)
(let loop ((vs (cdr vs))
(result (vector-length (car vs))))
(if (null? vs)
result
(loop (cdr vs) (min result (vector-length (car vs)))))))
Return a list of the Ith elements of the vectors in VS .
(define (vectors-ref vs i)
(let loop ((vs vs) (xs '()))
(if (null? vs)
(reverse! xs)
(loop (cdr vs) (cons (vector-ref (car vs) i)
xs)))))
(define vector-unfold
(case-lambda
"(vector-unfold f length initial-seed ...) -> vector
The fundamental vector constructor. Create a vector whose length is
LENGTH and iterates across each index k from 0 up to LENGTH - 1,
applying F at each iteration to the current index and current seeds, in
that order, to receive n + 1 values: the element to put in the kth slot
of the new vector, and n new seeds for the next iteration. It is an
error for the number of seeds to vary between iterations."
((f len)
(assert-procedure f 'vector-unfold)
(assert-nonneg-exact-integer len 'vector-unfold)
(let ((v (make-vector len)))
(let loop ((i 0))
(unless (= i len)
(vector-set! v i (f i))
(loop (+ i 1))))
v))
((f len seed)
(assert-procedure f 'vector-unfold)
(assert-nonneg-exact-integer len 'vector-unfold)
(let ((v (make-vector len)))
(let loop ((i 0) (seed seed))
(unless (= i len)
(receive (x seed) (f i seed)
(vector-set! v i x)
(loop (+ i 1) seed))))
v))
((f len seed1 seed2)
(assert-procedure f 'vector-unfold)
(assert-nonneg-exact-integer len 'vector-unfold)
(let ((v (make-vector len)))
(let loop ((i 0) (seed1 seed1) (seed2 seed2))
(unless (= i len)
(receive (x seed1 seed2) (f i seed1 seed2)
(vector-set! v i x)
(loop (+ i 1) seed1 seed2))))
v))
((f len . seeds)
(assert-procedure f 'vector-unfold)
(assert-nonneg-exact-integer len 'vector-unfold)
(let ((v (make-vector len)))
(let loop ((i 0) (seeds seeds))
(unless (= i len)
(receive (x . seeds) (apply f i seeds)
(vector-set! v i x)
(loop (+ i 1) seeds))))
v))))
(define vector-unfold-right
(case-lambda
"(vector-unfold-right f length initial-seed ...) -> vector
The fundamental vector constructor. Create a vector whose length is
LENGTH and iterates across each index k from LENGTH - 1 down to 0,
applying F at each iteration to the current index and current seeds, in
that order, to receive n + 1 values: the element to put in the kth slot
of the new vector, and n new seeds for the next iteration. It is an
error for the number of seeds to vary between iterations."
((f len)
(assert-procedure f 'vector-unfold-right)
(assert-nonneg-exact-integer len 'vector-unfold-right)
(let ((v (make-vector len)))
(let loop ((i (- len 1)))
(unless (negative? i)
(vector-set! v i (f i))
(loop (- i 1))))
v))
((f len seed)
(assert-procedure f 'vector-unfold-right)
(assert-nonneg-exact-integer len 'vector-unfold-right)
(let ((v (make-vector len)))
(let loop ((i (- len 1)) (seed seed))
(unless (negative? i)
(receive (x seed) (f i seed)
(vector-set! v i x)
(loop (- i 1) seed))))
v))
((f len seed1 seed2)
(assert-procedure f 'vector-unfold-right)
(assert-nonneg-exact-integer len 'vector-unfold-right)
(let ((v (make-vector len)))
(let loop ((i (- len 1)) (seed1 seed1) (seed2 seed2))
(unless (negative? i)
(receive (x seed1 seed2) (f i seed1 seed2)
(vector-set! v i x)
(loop (- i 1) seed1 seed2))))
v))
((f len . seeds)
(assert-procedure f 'vector-unfold-right)
(assert-nonneg-exact-integer len 'vector-unfold-right)
(let ((v (make-vector len)))
(let loop ((i (- len 1)) (seeds seeds))
(unless (negative? i)
(receive (x . seeds) (apply f i seeds)
(vector-set! v i x)
(loop (- i 1) seeds))))
v))))
(define guile-vector-copy (@ (guile) vector-copy))
TODO : Enhance core ' vector - copy ' to do this .
(define vector-copy
(case-lambda*
"(vector-copy vec [start [end [fill]]]) -> vector
Allocate a new vector whose length is END - START and fills it with
elements from vec, taking elements from vec starting at index START
and stopping at index END. START defaults to 0 and END defaults to
the value of (vector-length VEC). If END extends beyond the length of
VEC, the slots in the new vector that obviously cannot be filled by
elements from VEC are filled with FILL, whose default value is
unspecified."
((v) (guile-vector-copy v))
((v start)
(assert-vector v 'vector-copy)
(let ((len (vector-length v)))
(assert-valid-start start len 'vector-copy)
(let ((result (make-vector (- len start))))
(vector-move-left! v start len result 0)
result)))
((v start end #:optional (fill *unspecified*))
(assert-vector v 'vector-copy)
(let ((len (vector-length v)))
(unless (and (exact-integer? start)
(exact-integer? end)
(<= 0 start end))
(error-from 'vector-copy "invalid index range" start end))
(let ((result (make-vector (- end start) fill)))
(vector-move-left! v start (min end len) result 0)
result)))))
(define vector-reverse-copy
(let ()
(define (%vector-reverse-copy vec start end)
(let* ((len (- end start))
(result (make-vector len)))
(let loop ((i 0) (j (- end 1)))
(unless (= i len)
(vector-set! result i (vector-ref vec j))
(loop (+ i 1) (- j 1))))
result))
(case-lambda
"(vector-reverse-copy vec [start [end]]) -> vector
Allocate a new vector whose length is END - START and fills it with
elements from vec, taking elements from vec in reverse order starting
at index START and stopping at index END. START defaults to 0 and END
defaults to the value of (vector-length VEC)."
((vec)
(assert-vector vec 'vector-reverse-copy)
(%vector-reverse-copy vec 0 (vector-length vec)))
((vec start)
(assert-vector vec 'vector-reverse-copy)
(let ((len (vector-length vec)))
(assert-valid-start start len 'vector-reverse-copy)
(%vector-reverse-copy vec start len)))
((vec start end)
(assert-vector vec 'vector-reverse-copy)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'vector-reverse-copy)
(%vector-reverse-copy vec start end))))))
(define (%vector-concatenate vs)
(let* ((result-len (let loop ((vs vs) (len 0))
(if (null? vs)
len
(loop (cdr vs) (+ len (vector-length (car vs)))))))
(result (make-vector result-len)))
(let loop ((vs vs) (pos 0))
(unless (null? vs)
(let* ((v (car vs))
(len (vector-length v)))
(vector-move-left! v 0 len result pos)
(loop (cdr vs) (+ pos len)))))
result))
(define vector-append
(case-lambda
"(vector-append vec ...) -> vector
Return a newly allocated vector that contains all elements in order
from the subsequent locations in VEC ..."
(() (vector))
((v)
(assert-vector v 'vector-append)
(guile-vector-copy v))
((v1 v2)
(assert-vector v1 'vector-append)
(assert-vector v2 'vector-append)
(let ((len1 (vector-length v1))
(len2 (vector-length v2)))
(let ((result (make-vector (+ len1 len2))))
(vector-move-left! v1 0 len1 result 0)
(vector-move-left! v2 0 len2 result len1)
result)))
(vs
(assert-vectors vs 'vector-append)
(%vector-concatenate vs))))
(define (vector-concatenate vs)
"(vector-concatenate list-of-vectors) -> vector
Append each vector in LIST-OF-VECTORS. Equivalent to:
(apply vector-append LIST-OF-VECTORS)"
(assert-vectors vs 'vector-concatenate)
(%vector-concatenate vs))
(define (vector-empty? vec)
"(vector-empty? vec) -> boolean
Return true if VEC is empty, i.e. its length is 0, and false if not."
(assert-vector vec 'vector-empty?)
(zero? (vector-length vec)))
(define vector=
(let ()
(define (all-of-length? len vs)
(or (null? vs)
(and (= len (vector-length (car vs)))
(all-of-length? len (cdr vs)))))
(define (=up-to? i elt=? v1 v2)
(or (negative? i)
(let ((x1 (vector-ref v1 i))
(x2 (vector-ref v2 i)))
(and (or (eq? x1 x2) (elt=? x1 x2))
(=up-to? (- i 1) elt=? v1 v2)))))
(case-lambda
"(vector= elt=? vec ...) -> boolean
Return true if the vectors VEC ... have equal lengths and equal
elements according to ELT=?. ELT=? is always applied to two
arguments. Element comparison must be consistent with eq?, in the
following sense: if (eq? a b) returns true, then (elt=? a b) must also
return true. The order in which comparisons are performed is
unspecified."
((elt=?)
(assert-procedure elt=? 'vector=)
#t)
((elt=? v)
(assert-procedure elt=? 'vector=)
(assert-vector v 'vector=)
#t)
((elt=? v1 v2)
(assert-procedure elt=? 'vector=)
(assert-vector v1 'vector=)
(assert-vector v2 'vector=)
(let ((len (vector-length v1)))
(and (= len (vector-length v2))
(=up-to? (- len 1) elt=? v1 v2))))
((elt=? v1 . vs)
(assert-procedure elt=? 'vector=)
(assert-vector v1 'vector=)
(assert-vectors vs 'vector=)
(let ((len (vector-length v1)))
(and (all-of-length? len vs)
(let loop ((vs vs))
(or (null? vs)
(and (=up-to? (- len 1) elt=? v1 (car vs))
(loop (cdr vs)))))))))))
(define vector-fold
(case-lambda
"(vector-fold kons knil vec1 vec2 ...) -> value
The fundamental vector iterator. KONS is iterated over each index in
applied as (KONS i state (vector-ref VEC1 i) (vector-ref VEC2 i) ...)
where STATE is the current state value, and I is the current index.
The current state value begins with KNIL, and becomes whatever KONS
returned at the respective iteration. The iteration is strictly
left-to-right."
((kcons knil v)
(assert-procedure kcons 'vector-fold)
(assert-vector v 'vector-fold)
(let ((len (vector-length v)))
(let loop ((i 0) (state knil))
(if (= i len)
state
(loop (+ i 1) (kcons i state (vector-ref v i)))))))
((kcons knil v1 v2)
(assert-procedure kcons 'vector-fold)
(assert-vector v1 'vector-fold)
(assert-vector v2 'vector-fold)
(let ((len (min (vector-length v1) (vector-length v2))))
(let loop ((i 0) (state knil))
(if (= i len)
state
(loop (+ i 1)
(kcons i state (vector-ref v1 i) (vector-ref v2 i)))))))
((kcons knil . vs)
(assert-procedure kcons 'vector-fold)
(assert-vectors vs 'vector-fold)
(let ((len (min-length vs)))
(let loop ((i 0) (state knil))
(if (= i len)
state
(loop (+ i 1) (apply kcons i state (vectors-ref vs i)))))))))
(define vector-fold-right
(case-lambda
"(vector-fold-right kons knil vec1 vec2 ...) -> value
The fundamental vector iterator. KONS is iterated over each index in
applied as (KONS i state (vector-ref VEC1 i) (vector-ref VEC2 i) ...)
where STATE is the current state value, and I is the current index.
The current state value begins with KNIL, and becomes whatever KONS
returned at the respective iteration. The iteration is strictly
right-to-left."
((kcons knil v)
(assert-procedure kcons 'vector-fold-right)
(assert-vector v 'vector-fold-right)
(let ((len (vector-length v)))
(let loop ((i (- len 1)) (state knil))
(if (negative? i)
state
(loop (- i 1) (kcons i state (vector-ref v i)))))))
((kcons knil v1 v2)
(assert-procedure kcons 'vector-fold-right)
(assert-vector v1 'vector-fold-right)
(assert-vector v2 'vector-fold-right)
(let ((len (min (vector-length v1) (vector-length v2))))
(let loop ((i (- len 1)) (state knil))
(if (negative? i)
state
(loop (- i 1)
(kcons i state (vector-ref v1 i) (vector-ref v2 i)))))))
((kcons knil . vs)
(assert-procedure kcons 'vector-fold-right)
(assert-vectors vs 'vector-fold-right)
(let ((len (min-length vs)))
(let loop ((i (- len 1)) (state knil))
(if (negative? i)
state
(loop (- i 1) (apply kcons i state (vectors-ref vs i)))))))))
(define vector-map
(case-lambda
"(vector-map f vec2 vec2 ...) -> vector
Return a new vector of the shortest size of the vector arguments.
Each element at index i of the new vector is mapped from the old
vectors by (F i (vector-ref VEC1 i) (vector-ref VEC2 i) ...). The
dynamic order of application of F is unspecified."
((f v)
(assert-procedure f 'vector-map)
(assert-vector v 'vector-map)
(let* ((len (vector-length v))
(result (make-vector len)))
(let loop ((i 0))
(unless (= i len)
(vector-set! result i (f i (vector-ref v i)))
(loop (+ i 1))))
result))
((f v1 v2)
(assert-procedure f 'vector-map)
(assert-vector v1 'vector-map)
(assert-vector v2 'vector-map)
(let* ((len (min (vector-length v1) (vector-length v2)))
(result (make-vector len)))
(let loop ((i 0))
(unless (= i len)
(vector-set! result i (f i (vector-ref v1 i) (vector-ref v2 i)))
(loop (+ i 1))))
result))
((f . vs)
(assert-procedure f 'vector-map)
(assert-vectors vs 'vector-map)
(let* ((len (min-length vs))
(result (make-vector len)))
(let loop ((i 0))
(unless (= i len)
(vector-set! result i (apply f i (vectors-ref vs i)))
(loop (+ i 1))))
result))))
(define vector-map!
(case-lambda
"(vector-map! f vec2 vec2 ...) -> unspecified
Similar to vector-map, but rather than mapping the new elements into a
new vector, the new mapped elements are destructively inserted into
VEC1. The dynamic order of application of F is unspecified."
((f v)
(assert-procedure f 'vector-map!)
(assert-vector v 'vector-map!)
(let ((len (vector-length v)))
(let loop ((i 0))
(unless (= i len)
(vector-set! v i (f i (vector-ref v i)))
(loop (+ i 1))))))
((f v1 v2)
(assert-procedure f 'vector-map!)
(assert-vector v1 'vector-map!)
(assert-vector v2 'vector-map!)
(let ((len (min (vector-length v1) (vector-length v2))))
(let loop ((i 0))
(unless (= i len)
(vector-set! v1 i (f i (vector-ref v1 i) (vector-ref v2 i)))
(loop (+ i 1))))))
((f . vs)
(assert-procedure f 'vector-map!)
(assert-vectors vs 'vector-map!)
(let ((len (min-length vs))
(v1 (car vs)))
(let loop ((i 0))
(unless (= i len)
(vector-set! v1 i (apply f i (vectors-ref vs i)))
(loop (+ i 1))))))))
(define vector-for-each
(case-lambda
"(vector-for-each f vec1 vec2 ...) -> unspecified
Call (F i VEC1[i] VEC2[i] ...) for each index i less than the length
of the shortest vector passed. The iteration is strictly
left-to-right."
((f v)
(assert-procedure f 'vector-for-each)
(assert-vector v 'vector-for-each)
(let ((len (vector-length v)))
(let loop ((i 0))
(unless (= i len)
(f i (vector-ref v i))
(loop (+ i 1))))))
((f v1 v2)
(assert-procedure f 'vector-for-each)
(assert-vector v1 'vector-for-each)
(assert-vector v2 'vector-for-each)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i 0))
(unless (= i len)
(f i (vector-ref v1 i) (vector-ref v2 i))
(loop (+ i 1))))))
((f . vs)
(assert-procedure f 'vector-for-each)
(assert-vectors vs 'vector-for-each)
(let ((len (min-length vs)))
(let loop ((i 0))
(unless (= i len)
(apply f i (vectors-ref vs i))
(loop (+ i 1))))))))
(define vector-count
(case-lambda
"(vector-count pred? vec1 vec2 ...) -> exact nonnegative integer
Count the number of indices i for which (PRED? VEC1[i] VEC2[i] ...)
returns true, where i is less than the length of the shortest vector
passed."
((pred? v)
(assert-procedure pred? 'vector-count)
(assert-vector v 'vector-count)
(let ((len (vector-length v)))
(let loop ((i 0) (count 0))
(cond ((= i len) count)
((pred? i (vector-ref v i))
(loop (+ i 1) (+ count 1)))
(else
(loop (+ i 1) count))))))
((pred? v1 v2)
(assert-procedure pred? 'vector-count)
(assert-vector v1 'vector-count)
(assert-vector v2 'vector-count)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i 0) (count 0))
(cond ((= i len) count)
((pred? i (vector-ref v1 i) (vector-ref v2 i))
(loop (+ i 1) (+ count 1)))
(else
(loop (+ i 1) count))))))
((pred? . vs)
(assert-procedure pred? 'vector-count)
(assert-vectors vs 'vector-count)
(let ((len (min-length vs)))
(let loop ((i 0) (count 0))
(cond ((= i len) count)
((apply pred? i (vectors-ref vs i))
(loop (+ i 1) (+ count 1)))
(else
(loop (+ i 1) count))))))))
(define vector-index
(case-lambda
"(vector-index pred? vec1 vec2 ...) -> exact nonnegative integer or #f
Find and return the index of the first elements in VEC1 VEC2 ... that
satisfy PRED?. If no matching element is found by the end of the
shortest vector, return #f."
((pred? v)
(assert-procedure pred? 'vector-index)
(assert-vector v 'vector-index)
(let ((len (vector-length v)))
(let loop ((i 0))
(and (< i len)
(if (pred? (vector-ref v i))
i
(loop (+ i 1)))))))
((pred? v1 v2)
(assert-procedure pred? 'vector-index)
(assert-vector v1 'vector-index)
(assert-vector v2 'vector-index)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i 0))
(and (< i len)
(if (pred? (vector-ref v1 i)
(vector-ref v2 i))
i
(loop (+ i 1)))))))
((pred? . vs)
(assert-procedure pred? 'vector-index)
(assert-vectors vs 'vector-index)
(let ((len (min-length vs)))
(let loop ((i 0))
(and (< i len)
(if (apply pred? (vectors-ref vs i))
i
(loop (+ i 1)))))))))
(define vector-index-right
(case-lambda
"(vector-index-right pred? vec1 vec2 ...) -> exact nonnegative integer or #f
Find and return the index of the last elements in VEC1 VEC2 ... that
satisfy PRED?, searching from right-to-left. If no matching element
is found before the end of the shortest vector, return #f."
((pred? v)
(assert-procedure pred? 'vector-index-right)
(assert-vector v 'vector-index-right)
(let ((len (vector-length v)))
(let loop ((i (- len 1)))
(and (>= i 0)
(if (pred? (vector-ref v i))
i
(loop (- i 1)))))))
((pred? v1 v2)
(assert-procedure pred? 'vector-index-right)
(assert-vector v1 'vector-index-right)
(assert-vector v2 'vector-index-right)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i (- len 1)))
(and (>= i 0)
(if (pred? (vector-ref v1 i)
(vector-ref v2 i))
i
(loop (- i 1)))))))
((pred? . vs)
(assert-procedure pred? 'vector-index-right)
(assert-vectors vs 'vector-index-right)
(let ((len (min-length vs)))
(let loop ((i (- len 1)))
(and (>= i 0)
(if (apply pred? (vectors-ref vs i))
i
(loop (- i 1)))))))))
(define vector-skip
(case-lambda
"(vector-skip pred? vec1 vec2 ...) -> exact nonnegative integer or #f
Find and return the index of the first elements in VEC1 VEC2 ... that
do not satisfy PRED?. If no matching element is found by the end of
the shortest vector, return #f."
((pred? v)
(assert-procedure pred? 'vector-skip)
(assert-vector v 'vector-skip)
(let ((len (vector-length v)))
(let loop ((i 0))
(and (< i len)
(if (pred? (vector-ref v i))
(loop (+ i 1))
i)))))
((pred? v1 v2)
(assert-procedure pred? 'vector-skip)
(assert-vector v1 'vector-skip)
(assert-vector v2 'vector-skip)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i 0))
(and (< i len)
(if (pred? (vector-ref v1 i)
(vector-ref v2 i))
(loop (+ i 1))
i)))))
((pred? . vs)
(assert-procedure pred? 'vector-skip)
(assert-vectors vs 'vector-skip)
(let ((len (min-length vs)))
(let loop ((i 0))
(and (< i len)
(if (apply pred? (vectors-ref vs i))
(loop (+ i 1))
i)))))))
(define vector-skip-right
(case-lambda
"(vector-skip-right pred? vec1 vec2 ...) -> exact nonnegative integer or #f
Find and return the index of the last elements in VEC1 VEC2 ... that
do not satisfy PRED?, searching from right-to-left. If no matching
element is found before the end of the shortest vector, return #f."
((pred? v)
(assert-procedure pred? 'vector-skip-right)
(assert-vector v 'vector-skip-right)
(let ((len (vector-length v)))
(let loop ((i (- len 1)))
(and (not (negative? i))
(if (pred? (vector-ref v i))
(loop (- i 1))
i)))))
((pred? v1 v2)
(assert-procedure pred? 'vector-skip-right)
(assert-vector v1 'vector-skip-right)
(assert-vector v2 'vector-skip-right)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i (- len 1)))
(and (not (negative? i))
(if (pred? (vector-ref v1 i)
(vector-ref v2 i))
(loop (- i 1))
i)))))
((pred? . vs)
(assert-procedure pred? 'vector-skip-right)
(assert-vectors vs 'vector-skip-right)
(let ((len (min-length vs)))
(let loop ((i (- len 1)))
(and (not (negative? i))
(if (apply pred? (vectors-ref vs i))
(loop (- i 1))
i)))))))
(define vector-binary-search
(let ()
(define (%vector-binary-search vec value cmp start end)
(let loop ((lo start) (hi end))
(and (< lo hi)
(let* ((i (quotient (+ lo hi) 2))
(x (vector-ref vec i))
(c (cmp x value)))
(cond ((zero? c) i)
((positive? c) (loop lo i))
((negative? c) (loop (+ i 1) hi)))))))
(case-lambda
"(vector-binary-search vec value cmp [start [end]]) -> exact nonnegative integer or #f
Find and return an index of VEC between START and END whose value is
VALUE using a binary search. If no matching element is found, return
#f. The default START is 0 and the default END is the length of VEC.
CMP must be a procedure of two arguments such that (CMP A B) returns
a negative integer if A < B, a positive integer if A > B, or zero if
A = B. The elements of VEC must be sorted in non-decreasing order
according to CMP."
((vec value cmp)
(assert-vector vec 'vector-binary-search)
(assert-procedure cmp 'vector-binary-search)
(%vector-binary-search vec value cmp 0 (vector-length vec)))
((vec value cmp start)
(assert-vector vec 'vector-binary-search)
(let ((len (vector-length vec)))
(assert-valid-start start len 'vector-binary-search)
(%vector-binary-search vec value cmp start len)))
((vec value cmp start end)
(assert-vector vec 'vector-binary-search)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'vector-binary-search)
(%vector-binary-search vec value cmp start end))))))
(define vector-any
(case-lambda
"(vector-any pred? vec1 vec2 ...) -> value or #f
Find the first parallel set of elements from VEC1 VEC2 ... for which
PRED? returns a true value. If such a parallel set of elements
exists, vector-any returns the value that PRED? returned for that set
of elements. The iteration is strictly left-to-right."
((pred? v)
(assert-procedure pred? 'vector-any)
(assert-vector v 'vector-any)
(let ((len (vector-length v)))
(let loop ((i 0))
(and (< i len)
(or (pred? (vector-ref v i))
(loop (+ i 1)))))))
((pred? v1 v2)
(assert-procedure pred? 'vector-any)
(assert-vector v1 'vector-any)
(assert-vector v2 'vector-any)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i 0))
(and (< i len)
(or (pred? (vector-ref v1 i)
(vector-ref v2 i))
(loop (+ i 1)))))))
((pred? . vs)
(assert-procedure pred? 'vector-any)
(assert-vectors vs 'vector-any)
(let ((len (min-length vs)))
(let loop ((i 0))
(and (< i len)
(or (apply pred? (vectors-ref vs i))
(loop (+ i 1)))))))))
(define vector-every
(case-lambda
"(vector-every pred? vec1 vec2 ...) -> value or #f
If, for every index i less than the length of the shortest vector
argument, the set of elements VEC1[i] VEC2[i] ... satisfies PRED?,
vector-every returns the value that PRED? returned for the last set of
elements, at the last index of the shortest vector. The iteration is
strictly left-to-right."
((pred? v)
(assert-procedure pred? 'vector-every)
(assert-vector v 'vector-every)
(let ((len (vector-length v)))
(or (zero? len)
(let loop ((i 0))
(let ((val (pred? (vector-ref v i)))
(next-i (+ i 1)))
(if (or (not val) (= next-i len))
val
(loop next-i)))))))
((pred? v1 v2)
(assert-procedure pred? 'vector-every)
(assert-vector v1 'vector-every)
(assert-vector v2 'vector-every)
(let ((len (min (vector-length v1)
(vector-length v2))))
(or (zero? len)
(let loop ((i 0))
(let ((val (pred? (vector-ref v1 i)
(vector-ref v2 i)))
(next-i (+ i 1)))
(if (or (not val) (= next-i len))
val
(loop next-i)))))))
((pred? . vs)
(assert-procedure pred? 'vector-every)
(assert-vectors vs 'vector-every)
(let ((len (min-length vs)))
(or (zero? len)
(let loop ((i 0))
(let ((val (apply pred? (vectors-ref vs i)))
(next-i (+ i 1)))
(if (or (not val) (= next-i len))
val
(loop next-i)))))))))
(define (vector-swap! vec i j)
"(vector-swap! vec i j) -> unspecified
Swap the values of the locations in VEC at I and J."
(assert-vector vec 'vector-swap!)
(let ((len (vector-length vec)))
(assert-valid-index i len 'vector-swap!)
(assert-valid-index j len 'vector-swap!)
(let ((tmp (vector-ref vec i)))
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j tmp))))
TODO : Enhance core ' vector - fill ! ' to do this .
(define vector-fill!
(let ()
(define guile-vector-fill!
(@ (guile) vector-fill!))
(define (%vector-fill! vec fill start end)
(let loop ((i start))
(when (< i end)
(vector-set! vec i fill)
(loop (+ i 1)))))
(case-lambda
"(vector-fill! vec fill [start [end]]) -> unspecified
Assign the value of every location in VEC between START and END to
FILL. START defaults to 0 and END defaults to the length of VEC."
((vec fill)
(guile-vector-fill! vec fill))
((vec fill start)
(assert-vector vec 'vector-fill!)
(let ((len (vector-length vec)))
(assert-valid-start start len 'vector-fill!)
(%vector-fill! vec fill start len)))
((vec fill start end)
(assert-vector vec 'vector-fill!)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'vector-fill!)
(%vector-fill! vec fill start end))))))
(define (%vector-reverse! vec start end)
(let loop ((i start) (j (- end 1)))
(when (< i j)
(let ((tmp (vector-ref vec i)))
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j tmp)
(loop (+ i 1) (- j 1))))))
(define vector-reverse!
(case-lambda
"(vector-reverse! vec [start [end]]) -> unspecified
Destructively reverse the contents of VEC between START and END.
START defaults to 0 and END defaults to the length of VEC."
((vec)
(assert-vector vec 'vector-reverse!)
(%vector-reverse! vec 0 (vector-length vec)))
((vec start)
(assert-vector vec 'vector-reverse!)
(let ((len (vector-length vec)))
(assert-valid-start start len 'vector-reverse!)
(%vector-reverse! vec start len)))
((vec start end)
(assert-vector vec 'vector-reverse!)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'vector-reverse!)
(%vector-reverse! vec start end)))))
(define-syntax-rule (define-vector-copier! copy! docstring inner-proc)
(define copy!
(let ((%copy! inner-proc))
(case-lambda
docstring
((target tstart source)
(assert-vector target 'copy!)
(assert-vector source 'copy!)
(let ((tlen (vector-length target))
(slen (vector-length source)))
(assert-valid-start tstart tlen 'copy!)
(unless (>= tlen (+ tstart slen))
(error-from 'copy! "would write past end of target"))
(%copy! target tstart source 0 slen)))
((target tstart source sstart)
(assert-vector target 'copy!)
(assert-vector source 'copy!)
(let ((tlen (vector-length target))
(slen (vector-length source)))
(assert-valid-start tstart tlen 'copy!)
(assert-valid-start sstart slen 'copy!)
(unless (>= tlen (+ tstart (- slen sstart)))
(error-from 'copy! "would write past end of target"))
(%copy! target tstart source sstart slen)))
((target tstart source sstart send)
(assert-vector target 'copy!)
(assert-vector source 'copy!)
(let ((tlen (vector-length target))
(slen (vector-length source)))
(assert-valid-start tstart tlen 'copy!)
(assert-valid-range sstart send slen 'copy!)
(unless (>= tlen (+ tstart (- send sstart)))
(error-from 'copy! "would write past end of target"))
(%copy! target tstart source sstart send)))))))
(define-vector-copier! vector-copy!
"(vector-copy! target tstart source [sstart [send]]) -> unspecified
Copy a block of elements from SOURCE to TARGET, both of which must be
vectors, starting in TARGET at TSTART and starting in SOURCE at
SSTART, ending when SEND - SSTART elements have been copied. It is an
error for TARGET to have a length less than TSTART + (SEND - SSTART).
SSTART defaults to 0 and SEND defaults to the length of SOURCE."
(lambda (target tstart source sstart send)
(if (< tstart sstart)
(vector-move-left! source sstart send target tstart)
(vector-move-right! source sstart send target tstart))))
(define-vector-copier! vector-reverse-copy!
"(vector-reverse-copy! target tstart source [sstart [send]]) -> unspecified
Like vector-copy!, but copy the elements in the reverse order. It is
an error if TARGET and SOURCE are identical vectors and the TARGET and
however , if TSTART = SSTART ,
vector-reverse-copy! behaves as (vector-reverse! TARGET TSTART SEND)
would."
(lambda (target tstart source sstart send)
(if (and (eq? target source) (= tstart sstart))
(%vector-reverse! target sstart send)
(let loop ((i tstart) (j (- send 1)))
(when (>= j sstart)
(vector-set! target i (vector-ref source j))
(loop (+ i 1) (- j 1)))))))
(define vector->list
(let ()
(define (%vector->list vec start end)
(let loop ((i (- end 1))
(result '()))
(if (< i start)
result
(loop (- i 1) (cons (vector-ref vec i) result)))))
(case-lambda
"(vector->list vec [start [end]]) -> proper-list
Return a newly allocated list containing the elements in VEC between
START and END. START defaults to 0 and END defaults to the length of
VEC."
((vec)
(assert-vector vec 'vector->list)
(%vector->list vec 0 (vector-length vec)))
((vec start)
(assert-vector vec 'vector->list)
(let ((len (vector-length vec)))
(assert-valid-start start len 'vector->list)
(%vector->list vec start len)))
((vec start end)
(assert-vector vec 'vector->list)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'vector->list)
(%vector->list vec start end))))))
(define reverse-vector->list
(let ()
(define (%reverse-vector->list vec start end)
(let loop ((i start)
(result '()))
(if (>= i end)
result
(loop (+ i 1) (cons (vector-ref vec i) result)))))
(case-lambda
"(reverse-vector->list vec [start [end]]) -> proper-list
Return a newly allocated list containing the elements in VEC between
START and END in reverse order. START defaults to 0 and END defaults
to the length of VEC."
((vec)
(assert-vector vec 'reverse-vector->list)
(%reverse-vector->list vec 0 (vector-length vec)))
((vec start)
(assert-vector vec 'reverse-vector->list)
(let ((len (vector-length vec)))
(assert-valid-start start len 'reverse-vector->list)
(%reverse-vector->list vec start len)))
((vec start end)
(assert-vector vec 'reverse-vector->list)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'reverse-vector->list)
(%reverse-vector->list vec start end))))))
(define* (list->vector lst #:optional (start 0) (end (length lst)))
"(list->vector proper-list [start [end]]) -> vector
Return a newly allocated vector of the elements from PROPER-LIST with
indices between START and END. START defaults to 0 and END defaults
to the length of PROPER-LIST."
(let* ((len (- end start))
(result (make-vector len)))
(let loop ((i 0) (lst (drop lst start)))
(if (= i len)
result
(begin (vector-set! result i (car lst))
(loop (+ i 1) (cdr lst)))))))
(define* (reverse-list->vector lst #:optional (start 0) (end (length lst)))
"(reverse-list->vector proper-list [start [end]]) -> vector
Return a newly allocated vector of the elements from PROPER-LIST with
indices between START and END, in reverse order. START defaults to 0
and END defaults to the length of PROPER-LIST."
(let* ((len (- end start))
(result (make-vector len)))
(let loop ((i (- len 1)) (lst (drop lst start)))
(if (negative? i)
result
(begin (vector-set! result i (car lst))
(loop (- i 1) (cdr lst)))))))
|
a6242df7d1c778e073a6f027446aad85a54c0d5870aa6a2972b9c72dca3af47c | dimitri/pgcharts | dburi.lisp | ;;;
Parse database connection string
;;;
(in-package #:pgcharts.dburi)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun getenv-default (name &optional default)
"Return the value of the NAME variable as found in the environment, or
DEFAULT if that variable isn't set"
(or (uiop:getenv name) default)))
(defrule punct (or #\, #\- #\_)
(:text t))
(defrule namestring (* (or (alpha-char-p character)
(digit-char-p character)
punct))
(:text t))
(defrule dsn-port (and ":" (* (digit-char-p character)))
(:destructure (colon digits)
(declare (ignore colon))
(list :port (if (null digits) digits
(parse-integer (coerce digits 'string))))))
(defrule doubled-at-sign (and "@@") (:constant "@"))
(defrule doubled-colon (and "::") (:constant ":"))
(defrule password (+ (or (not "@") doubled-at-sign)) (:text t))
(defrule username (+ (or (not (or ":" "@")) doubled-at-sign doubled-colon))
(:text t))
(defrule dsn-user-password (and username
(? (and ":" (? password)))
"@")
(:lambda (args)
(destructuring-bind (username &optional password)
(butlast args)
;; password looks like '(":" "password")
(list :user username :password (cadr password)))))
(defun hexdigit-char-p (character)
(member character #. (quote (coerce "0123456789abcdefABCDEF" 'list))))
(defrule ipv4-part (and (digit-char-p character)
(? (digit-char-p character))
(? (digit-char-p character))))
(defrule ipv4 (and ipv4-part "." ipv4-part "." ipv4-part "." ipv4-part)
(:lambda (ipv4)
(list :ipv4 (text ipv4))))
;;; socket directory is unix only, so we can forbid ":" on the parsing
(defun socket-directory-character-p (char)
(or (member char #.(quote (coerce "/.-_" 'list)))
(alphanumericp char)))
(defrule socket-directory (and "unix:" (* (socket-directory-character-p character)))
(:destructure (unix socket-directory)
(declare (ignore unix))
(list :unix (when socket-directory (text socket-directory)))))
(defrule network-name (and namestring (* (and "." namestring)))
(:lambda (name)
(let ((host (text name)))
(list :host (unless (string= "" host) host)))))
(defrule hostname (or ipv4 socket-directory network-name)
(:identity t))
(defrule dsn-hostname (and (? hostname) (? dsn-port))
(:destructure (hostname &optional port)
(append (list :host hostname) port)))
(defrule dsn-dbname (and "/" (? namestring))
(:destructure (slash dbname)
(declare (ignore slash))
(list :dbname dbname)))
(defrule dsn-option-ssl-disable "disable" (:constant :no))
(defrule dsn-option-ssl-allow "allow" (:constant :try))
(defrule dsn-option-ssl-prefer "prefer" (:constant :try))
(defrule dsn-option-ssl-require "require" (:constant :yes))
(defrule dsn-option-ssl (and "sslmode" "=" (or dsn-option-ssl-disable
dsn-option-ssl-allow
dsn-option-ssl-prefer
dsn-option-ssl-require))
(:lambda (ssl)
(destructuring-bind (key e val) ssl
(declare (ignore key e))
(cons :use-ssl val))))
(defrule dsn-option (or dsn-option-ssl))
(defrule dsn-options (and "?" (* dsn-option))
(:lambda (options)
(destructuring-bind (qm opts) options
(declare (ignore qm))
(alexandria:alist-plist opts))))
(defrule dsn-prefix (or "pgsql://" "postgresql://") (:constant nil))
(defrule db-connection-uri (and dsn-prefix
(? dsn-user-password)
(? dsn-hostname)
dsn-dbname
(? dsn-options))
(:lambda (uri)
(destructuring-bind (&key type
user
password
host
port
dbname
(use-ssl :no))
(apply #'append uri)
(declare (ignore type))
;;
;; Default to environment variables as described in
-psql.html
;; -variables.html
;;
(list (or dbname (getenv-default "PGDATABASE" user))
(or user (getenv-default "PGUSER" (getenv-default "USER")))
(or password (getenv-default "PGPASSWORD"))
(or (when host
(destructuring-bind (type &optional name) host
(ecase type
(:unix (or name :unix))
(:ipv4 name)
(:host name))))
(getenv-default "PGHOST"
#+unix :unix
#-unix "localhost"))
:port (or port
(parse-integer (getenv-default "PGPORT" "5432")))
:use-ssl use-ssl))))
;;;
;;; Parsing a connection string
;;;
(defun parse-pgsql-connection-string (connection-string)
"Parse given CONNECTION-STRING and return a Postmodern suitable connection
spec.
Examples:
IN: postgresql@localhost:54393/pginstall
OUT: '(\"pginstall\" \"dim\" nil \"localhost\" :port 54393 :use-ssl :no)
The default port, when omitted, comes from the environment variable PGPORT."
(parse 'db-connection-uri connection-string))
(defmacro with-pgsql-connection ((connection-string) &body body)
"Runs BODY within an established PostgreSQL connection."
`(with-connection (parse-pgsql-connection-string ,connection-string)
,@body))
;;;
;;; Validating a connection string
;;;
(defun validate-dburi (connection-string)
"Signal an error when CONNECTION-STRING either can't be parsed or if we
can't connect to a PostgreSQL server when using it."
(with-pgsql-connection (connection-string)
(query "SELECT 1" :single))
;; make sure to return the valid connection-string
connection-string)
| null | https://raw.githubusercontent.com/dimitri/pgcharts/9b9549c53cca77039e8aaca18bce939ecb2b6549/src/utils/dburi.lisp | lisp |
password looks like '(":" "password")
socket directory is unix only, so we can forbid ":" on the parsing
Default to environment variables as described in
-variables.html
Parsing a connection string
Validating a connection string
make sure to return the valid connection-string | Parse database connection string
(in-package #:pgcharts.dburi)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun getenv-default (name &optional default)
"Return the value of the NAME variable as found in the environment, or
DEFAULT if that variable isn't set"
(or (uiop:getenv name) default)))
(defrule punct (or #\, #\- #\_)
(:text t))
(defrule namestring (* (or (alpha-char-p character)
(digit-char-p character)
punct))
(:text t))
(defrule dsn-port (and ":" (* (digit-char-p character)))
(:destructure (colon digits)
(declare (ignore colon))
(list :port (if (null digits) digits
(parse-integer (coerce digits 'string))))))
(defrule doubled-at-sign (and "@@") (:constant "@"))
(defrule doubled-colon (and "::") (:constant ":"))
(defrule password (+ (or (not "@") doubled-at-sign)) (:text t))
(defrule username (+ (or (not (or ":" "@")) doubled-at-sign doubled-colon))
(:text t))
(defrule dsn-user-password (and username
(? (and ":" (? password)))
"@")
(:lambda (args)
(destructuring-bind (username &optional password)
(butlast args)
(list :user username :password (cadr password)))))
(defun hexdigit-char-p (character)
(member character #. (quote (coerce "0123456789abcdefABCDEF" 'list))))
(defrule ipv4-part (and (digit-char-p character)
(? (digit-char-p character))
(? (digit-char-p character))))
(defrule ipv4 (and ipv4-part "." ipv4-part "." ipv4-part "." ipv4-part)
(:lambda (ipv4)
(list :ipv4 (text ipv4))))
(defun socket-directory-character-p (char)
(or (member char #.(quote (coerce "/.-_" 'list)))
(alphanumericp char)))
(defrule socket-directory (and "unix:" (* (socket-directory-character-p character)))
(:destructure (unix socket-directory)
(declare (ignore unix))
(list :unix (when socket-directory (text socket-directory)))))
(defrule network-name (and namestring (* (and "." namestring)))
(:lambda (name)
(let ((host (text name)))
(list :host (unless (string= "" host) host)))))
(defrule hostname (or ipv4 socket-directory network-name)
(:identity t))
(defrule dsn-hostname (and (? hostname) (? dsn-port))
(:destructure (hostname &optional port)
(append (list :host hostname) port)))
(defrule dsn-dbname (and "/" (? namestring))
(:destructure (slash dbname)
(declare (ignore slash))
(list :dbname dbname)))
(defrule dsn-option-ssl-disable "disable" (:constant :no))
(defrule dsn-option-ssl-allow "allow" (:constant :try))
(defrule dsn-option-ssl-prefer "prefer" (:constant :try))
(defrule dsn-option-ssl-require "require" (:constant :yes))
(defrule dsn-option-ssl (and "sslmode" "=" (or dsn-option-ssl-disable
dsn-option-ssl-allow
dsn-option-ssl-prefer
dsn-option-ssl-require))
(:lambda (ssl)
(destructuring-bind (key e val) ssl
(declare (ignore key e))
(cons :use-ssl val))))
(defrule dsn-option (or dsn-option-ssl))
(defrule dsn-options (and "?" (* dsn-option))
(:lambda (options)
(destructuring-bind (qm opts) options
(declare (ignore qm))
(alexandria:alist-plist opts))))
(defrule dsn-prefix (or "pgsql://" "postgresql://") (:constant nil))
(defrule db-connection-uri (and dsn-prefix
(? dsn-user-password)
(? dsn-hostname)
dsn-dbname
(? dsn-options))
(:lambda (uri)
(destructuring-bind (&key type
user
password
host
port
dbname
(use-ssl :no))
(apply #'append uri)
(declare (ignore type))
-psql.html
(list (or dbname (getenv-default "PGDATABASE" user))
(or user (getenv-default "PGUSER" (getenv-default "USER")))
(or password (getenv-default "PGPASSWORD"))
(or (when host
(destructuring-bind (type &optional name) host
(ecase type
(:unix (or name :unix))
(:ipv4 name)
(:host name))))
(getenv-default "PGHOST"
#+unix :unix
#-unix "localhost"))
:port (or port
(parse-integer (getenv-default "PGPORT" "5432")))
:use-ssl use-ssl))))
(defun parse-pgsql-connection-string (connection-string)
"Parse given CONNECTION-STRING and return a Postmodern suitable connection
spec.
Examples:
IN: postgresql@localhost:54393/pginstall
OUT: '(\"pginstall\" \"dim\" nil \"localhost\" :port 54393 :use-ssl :no)
The default port, when omitted, comes from the environment variable PGPORT."
(parse 'db-connection-uri connection-string))
(defmacro with-pgsql-connection ((connection-string) &body body)
"Runs BODY within an established PostgreSQL connection."
`(with-connection (parse-pgsql-connection-string ,connection-string)
,@body))
(defun validate-dburi (connection-string)
"Signal an error when CONNECTION-STRING either can't be parsed or if we
can't connect to a PostgreSQL server when using it."
(with-pgsql-connection (connection-string)
(query "SELECT 1" :single))
connection-string)
|
e98d74e32230a6eceda18ba08f511de8ab609797e91319b26abe8f1696647a39 | albertoruiz/easyVision | Parameters.hs | # LANGUAGE TypeSynonymInstances , TemplateHaskell , FlexibleInstances #
-----------------------------------------------------------------------------
|
Module : Vision . GUI.Parameters
Copyright : ( c ) 2006 - 12
License : GPL - style
Maintainer : ( aruiz at um dot es )
Stability : provisional
A \'global\ ' parameter list with its own control window . See the example warp.hs .
Module : Vision.GUI.Parameters
Copyright : (c) Alberto Ruiz 2006-12
License : GPL-style
Maintainer : Alberto Ruiz (aruiz at um dot es)
Stability : provisional
A \'global\' parameter list with its own control window. See the example warp.hs.
-}
-----------------------------------------------------------------------------
module Vision.GUI.Parameters (
listParam, realParam, floatParam, percent, intParam, stringParam, boolParam,
autoParam, MkParam, ParamRecord(..)
) where
import Image hiding (RGB)
import Vision.GUI.Types
import Vision.GUI.Interface
import Graphics.UI.GLUT hiding (RGB, Matrix, Size)
import Data.IORef
import qualified Data.Map as Map
import Data.Map hiding (map)
import GHC.Float
import Numeric
import Data.List as L
import Control.Monad(ap,join)
import Control.Applicative((<$>),(<*>))
import Util.Options(getOption,optionString)
import Util.LazyIO(Generator)
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
sizePar :: Int
sizePar = 35
-- | Given an assoc list of names and initial values of some \'global\' application parameters, it creates a window for controlling them and returns a function to get the current value of the desired parameter. There are several types of parameters.
createParameters :: String -- ^ window name
^ prefix for command line options ( e.g. \"\ " , or "
-> [(String, Parameter)] -- ^ names and types
-> IO (EVWindow (Map String Parameter))
createParameters winname pref ops = do
ops' <- zip (map fst ops) `fmap` mapM (uncurry (defcomlin pref)) ops
let sz@(Size ih iw) = Size (2+length ops * sizePar) 200
nops = length ops - 1
which h y = (fromIntegral y `div` round (fromIntegral sizePar * fromIntegral h / fromIntegral ih)) `min` nops
w <- evWindow (Map.fromList ops') winname sz (kbdopts which kbdQuit)
displayCallback $= do
clear [ColorBuffer]
f (evSt w)
swapBuffers
join . get . evAfterD $ w
return w
where
f o = do
m <- readIORef o
let els = Map.elems m
pixelCoordinates (Size (2+length els * sizePar) 200)
sequence_ $ zipWith bar [0..] (assocs m)
return ()
bar p (s,e) = do
setColor 0 0 0.5
renderPrimitive Polygon (mapM_ vertex [Pixel r1 c1,
Pixel r1 c2,
Pixel r2 c2,
Pixel r2 c1])
setColor 1 1 1
rasterPos (Vertex2 (5::GLfloat) (4+fromIntegral r1/2+fromIntegral r2/2))
renderString Helvetica12 (s++" = "++info e)
where r1 = 2+p*sizePar
r2 = 2+p*sizePar+(sizePar -2)
c1 = 1
c2 = 2*k
k = posi e
kbdopts which def opts = kbd where
kbd (MouseButton WheelUp) Down _ (Position _x y) = do
Size h w <- evSize <$> get windowSize
m <- getW opts
let s' = keys m
let s = (s' !! which h y)
let v = m!s
let m' = Map.insert s (incre v) m
putW opts m'
postRedisplay Nothing
kbd (MouseButton WheelDown) Down _ (Position _x y) = do
Size h w <- evSize <$> get windowSize
m <- getW opts
let s' = keys m
let s = (s' !! which h y)
let v = m!s
let m' = Map.insert s (decre v) m
putW opts m'
postRedisplay Nothing
kbd (MouseButton LeftButton) Down _ (Position x y) = do
Size h w <- evSize <$> get windowSize
m <- getW opts
let s' = keys m
let s = (s' !! which h y)
let v = m!s
let m' = Map.insert s (setpo (round (fromIntegral x * 200 / fromIntegral w)) v) m
putW opts m'
postRedisplay Nothing
kbd a b c d = def a b c d
type Parameters = IORef (Map String Parameter)
data Parameter = Percent Int
| RealParam Double Double Double
| FlagParam Bool
| IntParam Int Int Int
| StringParam { sPos :: Int, sVal :: String, sList :: [String] }
| RLParam { rVal:: Double,
rPos :: Int,
rMin,rMax :: Double,
rList :: [Double],
rLength :: Int }
deriving Show
-- | Creates a 'Parameter' of type Double, with initial value and a list of allowed values (in ascending order).
listParam :: Double -> [Double] -> Parameter
listParam v list = RLParam {rVal = list!!k,
rPos = k,
rMin = head list,
rMax = last list,
rList = list,
rLength = length list}
where k = (length $ fst $ span (< v) list)
-- | Creates a 'Parameter' of type String, with initial value index and a list of allowed values.
stringParam :: String -> [String] -> Parameter
stringParam s list = StringParam { sVal = s
, sPos = k
, sList = list}
where k = case elemIndex s list of
Nothing -> error $ "option "++s++" is not in the list "++ show list
Just p -> p
| Creates a ' Parameter ' of type Int between 0 and 100 .
percent :: Int -> Parameter
percent = Percent
| Creates a ' Parameter ' of type Double , between a minimum and maximum value , with 100 divisions .
realParam :: Double -> Double -> Double -> Parameter
realParam = RealParam
| Creates a ' Parameter ' of type Double ( from float types ) , between a minimum and maximum value , with 100 divisions .
floatParam :: Float -> Float -> Float -> Parameter
floatParam a b c = realParam (float2Double a) (float2Double b) (float2Double c)
-- | Creates a 'Parameter' of type Int, between a minimum and maximum value
intParam :: Int -> Int -> Int -> Parameter
intParam = IntParam
boolParam :: Bool -> Parameter
boolParam = FlagParam
incre :: Parameter -> Parameter
incre (Percent v) = Percent (min 100 (v+1))
incre (RealParam v a b) = RealParam (min b (v+(b-a)/100)) a b
incre (IntParam v a b) = IntParam (min b (v+1)) a b
incre (x@RLParam {}) = x {rVal = rList x !! k, rPos = k}
where k = min (rLength x -1) (rPos x + 1)
incre (x@StringParam {}) = x {sVal = sList x !! k, sPos = k}
where k = (sPos x + 1) `rem` length (sList x)
incre (FlagParam v) = FlagParam (not v)
decre :: Parameter -> Parameter
decre (Percent v) = Percent (max 0 (v-1))
decre (RealParam v a b) = RealParam (max a (v-(b-a)/100)) a b
decre (IntParam v a b) = IntParam (max a (v-1)) a b
decre (x@RLParam {}) = x {rVal = rList x !! k, rPos = k}
where k = max 0 (rPos x - 1)
decre (x@StringParam {}) = x {sVal = sList x !! k, sPos = k}
where k = max 0 (sPos x - 1)
decre (FlagParam v) = FlagParam (not v)
setpo :: GLint -> Parameter -> Parameter
setpo p (Percent _) = Percent (fromIntegral p `div` 2)
setpo p (RealParam _v a b) = RealParam (a+(b-a)/100*fromIntegral p / 2) a b
setpo p (IntParam _v a b) = IntParam (a+ round (fromIntegral (b-a)*fromIntegral p / (200::Double))) a b
setpo p (x@RLParam {}) = x {rVal = rList x !! k, rPos = k}
where k = round $ (fromIntegral $ rLength x) * fromIntegral p / (200::Double)
setpo p (x@StringParam {}) = x {sVal = sList x !! k, sPos = k}
where k = round $ (fromIntegral $ length $ sList x) * fromIntegral p / (200::Double)
setpo _ (FlagParam v) = FlagParam (not v)
posi :: Parameter -> Int
posi (Percent v) = v
posi (RealParam v a b) = round $ 100*(v-a)/(b-a)
posi (IntParam v a b) = round $ 100*fromIntegral (v-a)/(fromIntegral(b-a) :: Double)
posi (RLParam {rPos = i, rLength = l}) = (200*i) `div` (2*(l-1))
posi (StringParam {sPos = i, sList = list}) = (200*i) `div` (2*(l-1))
where l = length list
posi (FlagParam v) = if v then 100 else 0
info :: Parameter -> String
info (Percent v) = show v ++ "%"
info (RealParam v _ _) = showFFloat (Just 2) v ""
info (RLParam {rVal = v}) = showFFloat (Just 2) v ""
info (IntParam v _ _) = show v
info (StringParam {sVal = s}) = s
info (FlagParam v) = show v
class Param a where
param :: Parameter -> a
-- | Extracts a parameter given its name.
getParam :: EVWindow (Map String Parameter) -> String -> IO a
getParam w s = do
m <- getW w
return $ param $ m!s
instance Param Int where
param (Percent v) = v
param (IntParam v _ _) = v
param (StringParam {sPos = k}) = k
param v = error $ "wrong param conversion from "++ show v ++ " to Int"
instance Param Bool where
param (FlagParam v) = v
param v = error $ "wrong param conversion from "++ show v ++ " to Bool"
instance Param Double where
param (RealParam v _ _) = v
param (RLParam {rVal = v}) = v
param v = error $ "wrong param conversion from "++ show v ++ " to Double"
instance Param Float where
param (RealParam v _ _) = double2Float v
param (RLParam {rVal = v}) = double2Float v
param v = error $ "wrong param conversion from "++ show v ++ " to Float"
instance Param String where
param (StringParam {sVal = s}) = s
param v = error $ "wrong param conversion from "++ show v ++ " to String"
-------------------------------------------------------
defcomlin :: String -> String -> Parameter -> IO Parameter
defcomlin pref name (Percent x) = Percent <$> getOption ("--"++pref++name) x
defcomlin pref name (RealParam x a b) = RealParam <$> getOption ("--"++pref++name) x <*> return a <*> return b
defcomlin pref name (FlagParam b) = FlagParam <$> getOption ("--"++pref++name) b
defcomlin pref name (IntParam x a b) = IntParam <$> getOption ("--"++pref++name) x <*> return a <*> return b
defcomlin pref name (RLParam v _p mn mx l n) = do
v' <- getOption ("--"++pref++name) v
let k = length $ fst $ span (< v') l
return $ RLParam (l!!k) k mn mx l n
defcomlin pref name (StringParam _p s list) = do
s' <- optionString ("--"++pref++name) s
let k = case elemIndex s' list of
Nothing -> error $ "option "++s'++" is not in the list "++ show list
Just q -> q
return $ StringParam k s' list
Warning : check RLParam and StrinParam
-------------------------------------------------------
instance Lift Double where
lift = liftD
liftD :: Double -> ExpQ
liftD = litE . rationalL . toRational
instance Lift Parameter where
lift (Percent x) = conE 'Percent `appE` lift x
lift (RealParam v a b) = conE 'RealParam `appE` lift v `appE` lift a `appE` lift b
lift (FlagParam x) = conE 'FlagParam `appE` lift x
lift (IntParam v x y) = conE 'IntParam `appE` lift v `appE` lift x `appE` lift y
lift (StringParam p v l) = conE 'StringParam `appE` lift p `appE` lift v `appE` lift l
lift (RLParam v p mn mx l n) = conE 'RLParam
`appE` lift v `appE` lift p `appE` lift mn `appE` lift mx
`appE` lift l `appE` lift n
val :: Parameter -> ExpQ
val (Percent x) = lift x
val (FlagParam x) = lift x
val (RealParam x _a _b) = lift x
val (IntParam x _a _b) = lift x
val (RLParam v _p _mn _mx _l _n) = lift v
val (StringParam _p s _list) = lift s
optfun :: String -> String -> Parameter -> ExpQ
optfun pref name (Percent x) = varE 'getOption `appE` lp pref name `appE` lift x
optfun pref name (FlagParam x) = varE 'getOption `appE` lp pref name `appE` lift x
optfun pref name (RealParam x _a _b) = varE 'getOption `appE` lp pref name `appE` lift x
optfun pref name (IntParam x _a _b) = varE 'getOption `appE` lp pref name `appE` lift x
optfun pref name (RLParam v _p _mn _mx _l _n) = varE 'getOption `appE` lp pref name `appE` lift v
optfun pref name (StringParam _p s _list) = varE 'optionString `appE` lp pref name `appE` lift s
lp :: String -> String -> ExpQ
lp pref name = litE (stringL ("--"++pref++name))
---------------------------------------------------------
mkField :: (String, String) -> VarStrictTypeQ
mkField (n,t) = varStrictType (mkName n) $ strictType notStrict (conT (mkName t))
createRec :: String -> [(String, String)] -> DecQ
createRec name fields = dataD (cxt[]) (mkName name) [] [recC (mkName name) (map mkField fields)] [mkName "Show"]
| automatically create a data type intended to hold parameters for a certain computation .
from a list of field names , field types and parameter type with initial value , max , min , etc .
We create the data type , a default value , and functions to get the default values modified
by command line arguments and using a graphical window .
from a list of field names, field types and parameter type with initial value, max , min, etc.
We create the data type, a default value, and functions to get the default values modified
by command line arguments and using a graphical window.
-}
autoParam :: String -> String -> [(String, String, Parameter)] -> Q [Dec]
autoParam name pref defpar = sequence [
createRec name fields,
valD (varP funname)
(normalB (doE [ bindS (varP (mkName "o")) (appE crea (lift x))
, noBindS (appE (varE 'return) (tupE [varE (mkName "o"), f]))
])) [],
valD (varP defname) (normalB defval) [],
valD (varP argname) (normalB argval) [],
instanceD (cxt []) (appT (conT (mkName "ParamRecord")) (conT (mkName name))) [
(valD (varP (mkName "defParam")) (normalB (varE defname)) []),
(valD (varP (mkName "argParam")) (normalB (varE argname)) []),
(valD (varP (mkName "mkParam")) (normalB (varE funname)) [])]
]
where p = mkName name
funname = mkName $ "mk"++name
defname = mkName $ "def"++name
argname = mkName $ "arg"++name
winname = name
retPar = appE (varE 'return) (conE p)
f = L.foldl' appp retPar args
args = map (g.lift.fst) x
g = appE (appE (varE 'getParam) (varE (mkName "o")))
x = map s13 defpar
fields = map s12 defpar
s12 (a,b,_c) = (a,b)
s13 (a,_b,c) = (a,c)
s3 (_a,_b,c) = c
s1 (a,_b,_c) = a
crea = (varE 'createParameters) `appE` (lift winname) `appE` (lift pref)
defval = L.foldl' appE (conE p) (map (val.s3) defpar)
argval = L.foldl' appp retPar (zipWith (optfun pref) (map s1 defpar) (map s3 defpar))
( varE ' fmap ) ` appE ` ( varE ' snd ) ` appE `
appp :: ExpQ -> ExpQ -> ExpQ
appp f x = appE (appE (varE 'ap) f) x
--------------------------------------------------------------------------------
type MkParam p = IO(EVWindow(Map String Parameter),IO p)
class ParamRecord r where
defParam :: r -- ^ default value
argParam :: IO r -- ^ default value modified by command line arguments
mkParam :: MkParam r -- ^ parameter window with window control
winParam :: Generator r -- ^ parameter window constructor
winParam = (fmap Just . snd) <$> mkParam
| null | https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/packages/gui/src/Vision/GUI/Parameters.hs | haskell | ---------------------------------------------------------------------------
---------------------------------------------------------------------------
| Given an assoc list of names and initial values of some \'global\' application parameters, it creates a window for controlling them and returns a function to get the current value of the desired parameter. There are several types of parameters.
^ window name
^ names and types
| Creates a 'Parameter' of type Double, with initial value and a list of allowed values (in ascending order).
| Creates a 'Parameter' of type String, with initial value index and a list of allowed values.
| Creates a 'Parameter' of type Int, between a minimum and maximum value
| Extracts a parameter given its name.
-----------------------------------------------------
-----------------------------------------------------
-------------------------------------------------------
------------------------------------------------------------------------------
^ default value
^ default value modified by command line arguments
^ parameter window with window control
^ parameter window constructor | # LANGUAGE TypeSynonymInstances , TemplateHaskell , FlexibleInstances #
|
Module : Vision . GUI.Parameters
Copyright : ( c ) 2006 - 12
License : GPL - style
Maintainer : ( aruiz at um dot es )
Stability : provisional
A \'global\ ' parameter list with its own control window . See the example warp.hs .
Module : Vision.GUI.Parameters
Copyright : (c) Alberto Ruiz 2006-12
License : GPL-style
Maintainer : Alberto Ruiz (aruiz at um dot es)
Stability : provisional
A \'global\' parameter list with its own control window. See the example warp.hs.
-}
module Vision.GUI.Parameters (
listParam, realParam, floatParam, percent, intParam, stringParam, boolParam,
autoParam, MkParam, ParamRecord(..)
) where
import Image hiding (RGB)
import Vision.GUI.Types
import Vision.GUI.Interface
import Graphics.UI.GLUT hiding (RGB, Matrix, Size)
import Data.IORef
import qualified Data.Map as Map
import Data.Map hiding (map)
import GHC.Float
import Numeric
import Data.List as L
import Control.Monad(ap,join)
import Control.Applicative((<$>),(<*>))
import Util.Options(getOption,optionString)
import Util.LazyIO(Generator)
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
sizePar :: Int
sizePar = 35
^ prefix for command line options ( e.g. \"\ " , or "
-> IO (EVWindow (Map String Parameter))
createParameters winname pref ops = do
ops' <- zip (map fst ops) `fmap` mapM (uncurry (defcomlin pref)) ops
let sz@(Size ih iw) = Size (2+length ops * sizePar) 200
nops = length ops - 1
which h y = (fromIntegral y `div` round (fromIntegral sizePar * fromIntegral h / fromIntegral ih)) `min` nops
w <- evWindow (Map.fromList ops') winname sz (kbdopts which kbdQuit)
displayCallback $= do
clear [ColorBuffer]
f (evSt w)
swapBuffers
join . get . evAfterD $ w
return w
where
f o = do
m <- readIORef o
let els = Map.elems m
pixelCoordinates (Size (2+length els * sizePar) 200)
sequence_ $ zipWith bar [0..] (assocs m)
return ()
bar p (s,e) = do
setColor 0 0 0.5
renderPrimitive Polygon (mapM_ vertex [Pixel r1 c1,
Pixel r1 c2,
Pixel r2 c2,
Pixel r2 c1])
setColor 1 1 1
rasterPos (Vertex2 (5::GLfloat) (4+fromIntegral r1/2+fromIntegral r2/2))
renderString Helvetica12 (s++" = "++info e)
where r1 = 2+p*sizePar
r2 = 2+p*sizePar+(sizePar -2)
c1 = 1
c2 = 2*k
k = posi e
kbdopts which def opts = kbd where
kbd (MouseButton WheelUp) Down _ (Position _x y) = do
Size h w <- evSize <$> get windowSize
m <- getW opts
let s' = keys m
let s = (s' !! which h y)
let v = m!s
let m' = Map.insert s (incre v) m
putW opts m'
postRedisplay Nothing
kbd (MouseButton WheelDown) Down _ (Position _x y) = do
Size h w <- evSize <$> get windowSize
m <- getW opts
let s' = keys m
let s = (s' !! which h y)
let v = m!s
let m' = Map.insert s (decre v) m
putW opts m'
postRedisplay Nothing
kbd (MouseButton LeftButton) Down _ (Position x y) = do
Size h w <- evSize <$> get windowSize
m <- getW opts
let s' = keys m
let s = (s' !! which h y)
let v = m!s
let m' = Map.insert s (setpo (round (fromIntegral x * 200 / fromIntegral w)) v) m
putW opts m'
postRedisplay Nothing
kbd a b c d = def a b c d
type Parameters = IORef (Map String Parameter)
data Parameter = Percent Int
| RealParam Double Double Double
| FlagParam Bool
| IntParam Int Int Int
| StringParam { sPos :: Int, sVal :: String, sList :: [String] }
| RLParam { rVal:: Double,
rPos :: Int,
rMin,rMax :: Double,
rList :: [Double],
rLength :: Int }
deriving Show
listParam :: Double -> [Double] -> Parameter
listParam v list = RLParam {rVal = list!!k,
rPos = k,
rMin = head list,
rMax = last list,
rList = list,
rLength = length list}
where k = (length $ fst $ span (< v) list)
stringParam :: String -> [String] -> Parameter
stringParam s list = StringParam { sVal = s
, sPos = k
, sList = list}
where k = case elemIndex s list of
Nothing -> error $ "option "++s++" is not in the list "++ show list
Just p -> p
| Creates a ' Parameter ' of type Int between 0 and 100 .
percent :: Int -> Parameter
percent = Percent
| Creates a ' Parameter ' of type Double , between a minimum and maximum value , with 100 divisions .
realParam :: Double -> Double -> Double -> Parameter
realParam = RealParam
| Creates a ' Parameter ' of type Double ( from float types ) , between a minimum and maximum value , with 100 divisions .
floatParam :: Float -> Float -> Float -> Parameter
floatParam a b c = realParam (float2Double a) (float2Double b) (float2Double c)
intParam :: Int -> Int -> Int -> Parameter
intParam = IntParam
boolParam :: Bool -> Parameter
boolParam = FlagParam
incre :: Parameter -> Parameter
incre (Percent v) = Percent (min 100 (v+1))
incre (RealParam v a b) = RealParam (min b (v+(b-a)/100)) a b
incre (IntParam v a b) = IntParam (min b (v+1)) a b
incre (x@RLParam {}) = x {rVal = rList x !! k, rPos = k}
where k = min (rLength x -1) (rPos x + 1)
incre (x@StringParam {}) = x {sVal = sList x !! k, sPos = k}
where k = (sPos x + 1) `rem` length (sList x)
incre (FlagParam v) = FlagParam (not v)
decre :: Parameter -> Parameter
decre (Percent v) = Percent (max 0 (v-1))
decre (RealParam v a b) = RealParam (max a (v-(b-a)/100)) a b
decre (IntParam v a b) = IntParam (max a (v-1)) a b
decre (x@RLParam {}) = x {rVal = rList x !! k, rPos = k}
where k = max 0 (rPos x - 1)
decre (x@StringParam {}) = x {sVal = sList x !! k, sPos = k}
where k = max 0 (sPos x - 1)
decre (FlagParam v) = FlagParam (not v)
setpo :: GLint -> Parameter -> Parameter
setpo p (Percent _) = Percent (fromIntegral p `div` 2)
setpo p (RealParam _v a b) = RealParam (a+(b-a)/100*fromIntegral p / 2) a b
setpo p (IntParam _v a b) = IntParam (a+ round (fromIntegral (b-a)*fromIntegral p / (200::Double))) a b
setpo p (x@RLParam {}) = x {rVal = rList x !! k, rPos = k}
where k = round $ (fromIntegral $ rLength x) * fromIntegral p / (200::Double)
setpo p (x@StringParam {}) = x {sVal = sList x !! k, sPos = k}
where k = round $ (fromIntegral $ length $ sList x) * fromIntegral p / (200::Double)
setpo _ (FlagParam v) = FlagParam (not v)
posi :: Parameter -> Int
posi (Percent v) = v
posi (RealParam v a b) = round $ 100*(v-a)/(b-a)
posi (IntParam v a b) = round $ 100*fromIntegral (v-a)/(fromIntegral(b-a) :: Double)
posi (RLParam {rPos = i, rLength = l}) = (200*i) `div` (2*(l-1))
posi (StringParam {sPos = i, sList = list}) = (200*i) `div` (2*(l-1))
where l = length list
posi (FlagParam v) = if v then 100 else 0
info :: Parameter -> String
info (Percent v) = show v ++ "%"
info (RealParam v _ _) = showFFloat (Just 2) v ""
info (RLParam {rVal = v}) = showFFloat (Just 2) v ""
info (IntParam v _ _) = show v
info (StringParam {sVal = s}) = s
info (FlagParam v) = show v
class Param a where
param :: Parameter -> a
getParam :: EVWindow (Map String Parameter) -> String -> IO a
getParam w s = do
m <- getW w
return $ param $ m!s
instance Param Int where
param (Percent v) = v
param (IntParam v _ _) = v
param (StringParam {sPos = k}) = k
param v = error $ "wrong param conversion from "++ show v ++ " to Int"
instance Param Bool where
param (FlagParam v) = v
param v = error $ "wrong param conversion from "++ show v ++ " to Bool"
instance Param Double where
param (RealParam v _ _) = v
param (RLParam {rVal = v}) = v
param v = error $ "wrong param conversion from "++ show v ++ " to Double"
instance Param Float where
param (RealParam v _ _) = double2Float v
param (RLParam {rVal = v}) = double2Float v
param v = error $ "wrong param conversion from "++ show v ++ " to Float"
instance Param String where
param (StringParam {sVal = s}) = s
param v = error $ "wrong param conversion from "++ show v ++ " to String"
defcomlin :: String -> String -> Parameter -> IO Parameter
defcomlin pref name (Percent x) = Percent <$> getOption ("--"++pref++name) x
defcomlin pref name (RealParam x a b) = RealParam <$> getOption ("--"++pref++name) x <*> return a <*> return b
defcomlin pref name (FlagParam b) = FlagParam <$> getOption ("--"++pref++name) b
defcomlin pref name (IntParam x a b) = IntParam <$> getOption ("--"++pref++name) x <*> return a <*> return b
defcomlin pref name (RLParam v _p mn mx l n) = do
v' <- getOption ("--"++pref++name) v
let k = length $ fst $ span (< v') l
return $ RLParam (l!!k) k mn mx l n
defcomlin pref name (StringParam _p s list) = do
s' <- optionString ("--"++pref++name) s
let k = case elemIndex s' list of
Nothing -> error $ "option "++s'++" is not in the list "++ show list
Just q -> q
return $ StringParam k s' list
Warning : check RLParam and StrinParam
instance Lift Double where
lift = liftD
liftD :: Double -> ExpQ
liftD = litE . rationalL . toRational
instance Lift Parameter where
lift (Percent x) = conE 'Percent `appE` lift x
lift (RealParam v a b) = conE 'RealParam `appE` lift v `appE` lift a `appE` lift b
lift (FlagParam x) = conE 'FlagParam `appE` lift x
lift (IntParam v x y) = conE 'IntParam `appE` lift v `appE` lift x `appE` lift y
lift (StringParam p v l) = conE 'StringParam `appE` lift p `appE` lift v `appE` lift l
lift (RLParam v p mn mx l n) = conE 'RLParam
`appE` lift v `appE` lift p `appE` lift mn `appE` lift mx
`appE` lift l `appE` lift n
val :: Parameter -> ExpQ
val (Percent x) = lift x
val (FlagParam x) = lift x
val (RealParam x _a _b) = lift x
val (IntParam x _a _b) = lift x
val (RLParam v _p _mn _mx _l _n) = lift v
val (StringParam _p s _list) = lift s
optfun :: String -> String -> Parameter -> ExpQ
optfun pref name (Percent x) = varE 'getOption `appE` lp pref name `appE` lift x
optfun pref name (FlagParam x) = varE 'getOption `appE` lp pref name `appE` lift x
optfun pref name (RealParam x _a _b) = varE 'getOption `appE` lp pref name `appE` lift x
optfun pref name (IntParam x _a _b) = varE 'getOption `appE` lp pref name `appE` lift x
optfun pref name (RLParam v _p _mn _mx _l _n) = varE 'getOption `appE` lp pref name `appE` lift v
optfun pref name (StringParam _p s _list) = varE 'optionString `appE` lp pref name `appE` lift s
lp :: String -> String -> ExpQ
lp pref name = litE (stringL ("--"++pref++name))
mkField :: (String, String) -> VarStrictTypeQ
mkField (n,t) = varStrictType (mkName n) $ strictType notStrict (conT (mkName t))
createRec :: String -> [(String, String)] -> DecQ
createRec name fields = dataD (cxt[]) (mkName name) [] [recC (mkName name) (map mkField fields)] [mkName "Show"]
| automatically create a data type intended to hold parameters for a certain computation .
from a list of field names , field types and parameter type with initial value , max , min , etc .
We create the data type , a default value , and functions to get the default values modified
by command line arguments and using a graphical window .
from a list of field names, field types and parameter type with initial value, max , min, etc.
We create the data type, a default value, and functions to get the default values modified
by command line arguments and using a graphical window.
-}
autoParam :: String -> String -> [(String, String, Parameter)] -> Q [Dec]
autoParam name pref defpar = sequence [
createRec name fields,
valD (varP funname)
(normalB (doE [ bindS (varP (mkName "o")) (appE crea (lift x))
, noBindS (appE (varE 'return) (tupE [varE (mkName "o"), f]))
])) [],
valD (varP defname) (normalB defval) [],
valD (varP argname) (normalB argval) [],
instanceD (cxt []) (appT (conT (mkName "ParamRecord")) (conT (mkName name))) [
(valD (varP (mkName "defParam")) (normalB (varE defname)) []),
(valD (varP (mkName "argParam")) (normalB (varE argname)) []),
(valD (varP (mkName "mkParam")) (normalB (varE funname)) [])]
]
where p = mkName name
funname = mkName $ "mk"++name
defname = mkName $ "def"++name
argname = mkName $ "arg"++name
winname = name
retPar = appE (varE 'return) (conE p)
f = L.foldl' appp retPar args
args = map (g.lift.fst) x
g = appE (appE (varE 'getParam) (varE (mkName "o")))
x = map s13 defpar
fields = map s12 defpar
s12 (a,b,_c) = (a,b)
s13 (a,_b,c) = (a,c)
s3 (_a,_b,c) = c
s1 (a,_b,_c) = a
crea = (varE 'createParameters) `appE` (lift winname) `appE` (lift pref)
defval = L.foldl' appE (conE p) (map (val.s3) defpar)
argval = L.foldl' appp retPar (zipWith (optfun pref) (map s1 defpar) (map s3 defpar))
( varE ' fmap ) ` appE ` ( varE ' snd ) ` appE `
appp :: ExpQ -> ExpQ -> ExpQ
appp f x = appE (appE (varE 'ap) f) x
type MkParam p = IO(EVWindow(Map String Parameter),IO p)
class ParamRecord r where
winParam = (fmap Just . snd) <$> mkParam
|
282c6a8723452c4937f38f726c4fa328d255eb1ba8d6115db1310e81b1f9af08 | yrashk/erlang | snmpa_usm.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1999 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
-module(snmpa_usm).
-export([
process_incoming_msg/4,
generate_outgoing_msg/5,
generate_discovery_msg/5, generate_discovery_msg/6
]).
-define(SNMP_USE_V3, true).
-include("snmp_types.hrl").
-include("SNMP-USER-BASED-SM-MIB.hrl").
-include("SNMP-USM-AES-MIB.hrl").
-include("SNMPv2-TC.hrl").
-define(VMODULE,"A-USM").
-include("snmp_verbosity.hrl").
%%-----------------------------------------------------------------
%% This module implements the User Based Security Model for SNMP,
%% as defined in rfc2274.
%%-----------------------------------------------------------------
%% Columns not accessible via SNMP
-define(usmUserAuthKey, 14).
-define(usmUserPrivKey, 15).
-define(i32(Int), (Int bsr 24) band 255, (Int bsr 16) band 255, (Int bsr 8) band 255, Int band 255).
-define(i64(Int), (Int bsr 56) band 255, (Int bsr 48) band 255, (Int bsr 40) band 255, (Int bsr 32) band 255, (Int bsr 24) band 255, (Int bsr 16) band 255, (Int bsr 8) band 255, Int band 255).
%%-----------------------------------------------------------------
Func : process_incoming_msg(Packet , Data , SecParams , ) - >
{ ok , { SecEngineID , SecName , ScopedPDUBytes , SecData } } |
{ error , Reason } | { error , , ErrorInfo }
%% Return value may be throwed.
%% Types: Reason -> term()
%% Purpose:
%%-----------------------------------------------------------------
process_incoming_msg(Packet, Data, SecParams, SecLevel) ->
TermDiscoEnabled = is_terminating_discovery_enabled(),
3.2.1
?vtrace("process_incoming_msg -> check security parms: 3.2.1",[]),
UsmSecParams =
case catch snmp_pdus:dec_usm_security_parameters(SecParams) of
{'EXIT', Reason} ->
inc(snmpInASNParseErrs),
error({parseError, Reason}, []);
Res ->
Res
end,
case UsmSecParams of
#usmSecurityParameters{msgAuthoritativeEngineID = MsgAuthEngineID,
msgUserName = ""} when TermDiscoEnabled =:= true ->
Step 1 discovery message
?vtrace("process_incoming_msg -> discovery step 1", []),
process_discovery_msg(MsgAuthEngineID, Data, SecLevel);
#usmSecurityParameters{msgAuthoritativeEngineID = MsgAuthEngineID,
msgUserName = "initial"} when TermDiscoEnabled =:= true ->
Step 1 discovery message
?vtrace("process_incoming_msg -> [initial] discovery step 1", []),
process_discovery_msg(MsgAuthEngineID, Data, SecLevel);
#usmSecurityParameters{msgAuthoritativeEngineID = MsgAuthEngineID,
msgUserName = MsgUserName} ->
?vlog("process_incoming_msg -> USM security parms: "
"~n authEngineID: \"~s\""
"~n userName: \"~s\"", [MsgAuthEngineID, MsgUserName]),
3.2.3
?vtrace("process_incoming_msg -> check engine id: 3.2.3",[]),
case snmp_user_based_sm_mib:is_engine_id_known(MsgAuthEngineID) of
true ->
ok;
false ->
SecData1 = [MsgUserName],
error(usmStatsUnknownEngineIDs,
OTP-3542
undefined, [{sec_data, SecData1}])
end,
3.2.4
?vtrace("process_incoming_msg -> retrieve usm user: 3.2.4",[]),
UsmUser =
case snmp_user_based_sm_mib:get_user(MsgAuthEngineID,
MsgUserName) of
User when element(?usmUserStatus, User) =:= ?'RowStatus_active' ->
User;
{_, Name,_,_,_,_,_,_,_,_,_,_,_, RowStatus,_,_} ->
?vdebug("process_incoming_msg -> "
"found user ~p with wrong row status: ~p",
[Name, RowStatus]),
SecData2 = [MsgUserName],
error(usmStatsUnknownUserNames,
OTP-3542
undefined, [{sec_data, SecData2}]);
_ -> % undefined or not active user
SecData2 = [MsgUserName],
error(usmStatsUnknownUserNames,
OTP-3542
undefined, [{sec_data, SecData2}])
end,
SecName = element(?usmUserSecurityName, UsmUser),
?vtrace("process_incoming_msg -> securityName: ~p",[SecName]),
3.2.5 - implicit in following checks
3.2.6 - 3.2.7
?vtrace("process_incoming_msg -> "
"authenticate incoming: 3.2.5 - 3.2.7"
"~n ~p",[UsmUser]),
DiscoOrPlain = authenticate_incoming(Packet,
UsmSecParams, UsmUser,
SecLevel),
3.2.8
?vtrace("process_incoming_msg -> "
"decrypt scoped data: 3.2.8",[]),
ScopedPDUBytes =
decrypt(Data, UsmUser, UsmSecParams, SecLevel),
3.2.9
Means that if AuthKey / PrivKey are changed ;
%% the old values will be used.
?vtrace("process_incoming_msg -> "
"AuthKey/PrivKey are changed - "
"use old values: 3.2.9",[]),
CachedSecData = {MsgUserName,
element(?usmUserAuthProtocol, UsmUser),
element(?usmUserPrivProtocol, UsmUser),
element(?usmUserAuthKey, UsmUser),
element(?usmUserPrivKey, UsmUser)},
{ok, {MsgAuthEngineID, SecName, ScopedPDUBytes,
CachedSecData, DiscoOrPlain}}
end.
Process a step 1 discovery message
process_discovery_msg(MsgAuthEngineID, Data, SecLevel) ->
?vtrace("process_discovery_msg -> entry with"
"~n Data: ~p"
"~n SecLevel: ~p", [Data, SecLevel]),
case (not snmp_misc:is_priv(SecLevel)) of
noAuthNoPriv
?vtrace("process_discovery_msg -> noAuthNoPriv", []),
ScopedPDUBytes = Data,
SecData = {"", usmNoAuthProtocol, "", usmNoPrivProtocol, ""},
NewData = {SecData,
?usmStatsUnknownEngineIDs_instance,
get_counter(usmStatsUnknownEngineIDs)},
{ok, {MsgAuthEngineID, "", ScopedPDUBytes, NewData, discovery}};
false ->
error(usmStatsUnknownEngineIDs,
?usmStatsUnknownEngineIDs_instance,
undefined, [{sec_data, ""}])
end.
authenticate_incoming(Packet, UsmSecParams, UsmUser, SecLevel) ->
3.2.6
?vtrace("authenticate_incoming -> 3.2.6",[]),
AuthProtocol = element(?usmUserAuthProtocol, UsmUser),
#usmSecurityParameters{msgAuthoritativeEngineID = MsgAuthEngineID,
msgAuthoritativeEngineBoots = MsgAuthEngineBoots,
msgAuthoritativeEngineTime = MsgAuthEngineTime,
msgAuthenticationParameters = MsgAuthParams} =
UsmSecParams,
?vtrace("authenticate_incoming -> Sec params: "
"~n MsgAuthEngineID: ~p"
"~n MsgAuthEngineBoots: ~p"
"~n MsgAuthEngineTime: ~p",
[MsgAuthEngineID, MsgAuthEngineBoots, MsgAuthEngineTime]),
case snmp_misc:is_auth(SecLevel) of
true ->
SecName = element(?usmUserSecurityName, UsmUser),
case is_auth(AuthProtocol,
element(?usmUserAuthKey, UsmUser),
MsgAuthParams,
Packet,
SecName,
MsgAuthEngineID,
MsgAuthEngineBoots,
MsgAuthEngineTime) of
discovery ->
discovery;
true ->
plain;
false ->
error(usmStatsWrongDigests,
?usmStatsWrongDigests_instance, % OTP-5464
SecName)
end;
false -> % noAuth
plain
end.
authoritative(SecName, MsgAuthEngineBoots, MsgAuthEngineTime) ->
?vtrace("authoritative -> entry with"
"~n SecName: ~p"
"~n MsgAuthEngineBoots: ~p"
"~n MsgAuthEngineTime: ~p",
[SecName, MsgAuthEngineBoots, MsgAuthEngineTime]),
SnmpEngineBoots = snmp_framework_mib:get_engine_boots(),
?vtrace("authoritative -> SnmpEngineBoots: ~p", [SnmpEngineBoots]),
SnmpEngineTime = snmp_framework_mib:get_engine_time(),
?vtrace("authoritative -> SnmpEngineTime: ~p", [SnmpEngineTime]),
InTimeWindow =
if
SnmpEngineBoots =:= 2147483647 -> false;
MsgAuthEngineBoots =/= SnmpEngineBoots -> false;
MsgAuthEngineTime + 150 < SnmpEngineTime -> false;
MsgAuthEngineTime - 150 > SnmpEngineTime -> false;
true -> true
end,
case InTimeWindow of
true ->
true;
false ->
OTP-4090 ( OTP-3542 )
?vinfo("NOT in time window: "
"~n SecName: ~p"
"~n SnmpEngineBoots: ~p"
"~n MsgAuthEngineBoots: ~p"
"~n SnmpEngineTime: ~p"
"~n MsgAuthEngineTime: ~p",
[SecName,
SnmpEngineBoots, MsgAuthEngineBoots,
SnmpEngineTime, MsgAuthEngineTime]),
error(usmStatsNotInTimeWindows,
?usmStatsNotInTimeWindows_instance,
SecName,
[{securityLevel, 1}]) % authNoPriv
end.
non_authoritative(SecName,
MsgAuthEngineID, MsgAuthEngineBoots, MsgAuthEngineTime) ->
?vtrace("non_authoritative -> entry with"
"~n SecName: ~p"
"~n MsgAuthEngineID: ~p"
"~n MsgAuthEngineBoots: ~p"
"~n MsgAuthEngineTime: ~p",
[SecName,
MsgAuthEngineID, MsgAuthEngineBoots, MsgAuthEngineTime]),
SnmpEngineBoots = get_engine_boots(MsgAuthEngineID),
?vtrace("non_authoritative -> SnmpEngineBoots: ~p", [SnmpEngineBoots]),
SnmpEngineTime = get_engine_time(MsgAuthEngineID),
LatestRecvTime = get_engine_latest_time(MsgAuthEngineID),
UpdateLCD =
if
MsgAuthEngineBoots > SnmpEngineBoots -> true;
((MsgAuthEngineBoots =:= SnmpEngineBoots) andalso
(MsgAuthEngineTime > LatestRecvTime)) -> true;
true -> false
end,
case UpdateLCD of
true -> %% 3.2.7b1
?vtrace("non_authoritative -> "
"update msgAuthoritativeEngineID: 3.2.7b1",
[]),
set_engine_boots(MsgAuthEngineID, MsgAuthEngineBoots),
set_engine_time(MsgAuthEngineID, MsgAuthEngineTime),
set_engine_latest_time(MsgAuthEngineID, MsgAuthEngineTime);
false ->
ok
end,
3.2.7.b2
?vtrace("non_authoritative -> "
"check if message is outside time window: 3.2.7b2",
[]),
InTimeWindow =
if
SnmpEngineBoots == 2147483647 ->
false;
MsgAuthEngineBoots < SnmpEngineBoots ->
false;
MsgAuthEngineBoots =:= SnmpEngineBoots,
MsgAuthEngineTime < (SnmpEngineTime - 150) ->
false;
true -> true
end,
case InTimeWindow of
false ->
?vinfo("NOT in time window: "
"~n SecName: ~p"
"~n SnmpEngineBoots: ~p"
"~n MsgAuthEngineBoots: ~p"
"~n SnmpEngineTime: ~p"
"~n MsgAuthEngineTime: ~p",
[SecName,
SnmpEngineBoots, MsgAuthEngineBoots,
SnmpEngineTime, MsgAuthEngineTime]),
error(notInTimeWindow, []);
true ->
ok
end,
true.
3.2.5
error(usmStatsUnsupportedSecLevels,
?usmStatsUnsupportedSecLevels_instance, SecName); % OTP-5464
is_auth(AuthProtocol, AuthKey, AuthParams, Packet, SecName,
MsgAuthEngineID, MsgAuthEngineBoots, MsgAuthEngineTime) ->
TermDiscoEnabled = is_terminating_discovery_enabled(),
TermDiscoStage2 = terminating_discovery_stage2(),
IsAuth = auth_in(AuthProtocol, AuthKey, AuthParams, Packet),
case IsAuth of
true ->
3.2.7
?vtrace("is_auth -> "
"retrieve EngineBoots and EngineTime: 3.2.7",[]),
SnmpEngineID = snmp_framework_mib:get_engine_id(),
?vtrace("is_auth -> SnmpEngineID: ~p", [SnmpEngineID]),
case MsgAuthEngineID of
SnmpEngineID when ((MsgAuthEngineBoots =:= 0) andalso
(MsgAuthEngineTime =:= 0) andalso
(TermDiscoEnabled =:= true) andalso
3.2.7a
?vtrace("is_auth -> discovery stage 2 - discovery",[]),
discovery;
SnmpEngineID when ((MsgAuthEngineBoots =:= 0) andalso
(MsgAuthEngineTime =:= 0) andalso
(TermDiscoEnabled =:= true) andalso
3.2.7a
?vtrace("is_auth -> discovery stage 2 - plain",[]),
%% This will *always* result in the manager *not*
%% beeing in timewindow
authoritative(SecName,
MsgAuthEngineBoots, MsgAuthEngineTime);
3.2.7a
?vtrace("is_auth -> we are authoritative: 3.2.7a", []),
authoritative(SecName,
MsgAuthEngineBoots, MsgAuthEngineTime);
3.2.7b - we 're non - authoritative
?vtrace("is_auth -> we are non-authoritative: 3.2.7b",[]),
non_authoritative(SecName,
MsgAuthEngineID,
MsgAuthEngineBoots, MsgAuthEngineTime)
end;
false ->
false
end.
decrypt(Data, UsmUser, UsmSecParams, SecLevel) ->
case snmp_misc:is_priv(SecLevel) of
true ->
do_decrypt(Data, UsmUser, UsmSecParams);
false ->
Data
end.
do_decrypt(Data, UsmUser, UsmSecParams) ->
EncryptedPDU = snmp_pdus:dec_scoped_pdu_data(Data),
SecName = element(?usmUserSecurityName, UsmUser),
PrivP = element(?usmUserPrivProtocol, UsmUser),
PrivKey = element(?usmUserPrivKey, UsmUser),
?vtrace("do_decrypt -> try decrypt with: "
"~n SecName: ~p"
"~n PrivP: ~p", [SecName, PrivP]),
try_decrypt(PrivP, PrivKey, UsmSecParams, EncryptedPDU, SecName).
3.2.5
error(usmStatsUnsupportedSecLevels,
?usmStatsUnsupportedSecLevels_instance, SecName); % OTP-5464
try_decrypt(?usmDESPrivProtocol,
PrivKey, UsmSecParams, EncryptedPDU, SecName) ->
case (catch des_decrypt(PrivKey, UsmSecParams, EncryptedPDU)) of
{ok, DecryptedData} ->
DecryptedData;
_ ->
error(usmStatsDecryptionErrors,
?usmStatsDecryptionErrors_instance, % OTP-5464
SecName)
end;
try_decrypt(?usmAesCfb128Protocol,
PrivKey, UsmSecParams, EncryptedPDU, SecName) ->
case (catch aes_decrypt(PrivKey, UsmSecParams, EncryptedPDU)) of
{ok, DecryptedData} ->
DecryptedData;
_ ->
error(usmStatsDecryptionErrors,
?usmStatsDecryptionErrors_instance, % OTP-5464
SecName)
end.
generate_outgoing_msg(Message, SecEngineID, SecName, SecData, SecLevel) ->
3.1.1
?vtrace("generate_outgoing_msg -> [3.1.1] entry with"
"~n SecEngineID: ~p"
"~n SecName: ~p"
"~n SecLevel: ~w",
[SecEngineID, SecName, SecLevel]),
{UserName, AuthProtocol, PrivProtocol, AuthKey, PrivKey} =
case SecData of
3.1.1b
%% Not a response - read from LCD
case snmp_user_based_sm_mib:get_user_from_security_name(
SecEngineID, SecName) of
User when element(?usmUserStatus, User) =:=
?'RowStatus_active' ->
{element(?usmUserName, User),
element(?usmUserAuthProtocol, User),
element(?usmUserPrivProtocol, User),
element(?usmUserAuthKey, User),
element(?usmUserPrivKey, User)};
{_, Name,_,_,_,_,_,_,_,_,_,_,_, RowStatus,_,_} ->
?vdebug("generate_outgoing_msg -> "
"found user ~p with wrong row status: ~p",
[Name, RowStatus]),
error(unknownSecurityName);
_ ->
error(unknownSecurityName)
end;
[MsgUserName] ->
%% This means the user at the engine is unknown
{MsgUserName, ?usmNoAuthProtocol, ?usmNoPrivProtocol, "", ""};
3.1.1a
SecData
end,
3.1.4
?vtrace("generate_outgoing_msg -> [3.1.4]"
"~n UserName: ~p"
"~n AuthProtocol: ~p"
"~n PrivProtocol: ~p",
[UserName, AuthProtocol, PrivProtocol]),
ScopedPduBytes = Message#message.data,
{ScopedPduData, MsgPrivParams} =
encrypt(ScopedPduBytes, PrivProtocol, PrivKey, SecLevel),
SnmpEngineID = snmp_framework_mib:get_engine_id(),
?vtrace("generate_outgoing_msg -> SnmpEngineID: ~p [3.1.6]",
[SnmpEngineID]),
3.1.6
{MsgAuthEngineBoots, MsgAuthEngineTime} =
case snmp_misc:is_auth(SecLevel) of
false when SecData =:= [] -> % not a response
{0, 0};
reply ( report ) to discovery step 1
{0, 0};
true when SecEngineID =/= SnmpEngineID ->
{get_engine_boots(SecEngineID),
get_engine_time(SecEngineID)};
_ ->
{snmp_framework_mib:get_engine_boots(),
snmp_framework_mib:get_engine_time()}
end,
3.1.5 - 3.1.7
?vtrace("generate_outgoing_msg -> [3.1.5 - 3.1.7]",[]),
UsmSecParams =
#usmSecurityParameters{msgAuthoritativeEngineID = SecEngineID,
msgAuthoritativeEngineBoots = MsgAuthEngineBoots,
msgAuthoritativeEngineTime = MsgAuthEngineTime,
msgUserName = UserName,
msgPrivacyParameters = MsgPrivParams},
Message2 = Message#message{data = ScopedPduData},
%% 3.1.8
?vtrace("generate_outgoing_msg -> [3.1.8]",[]),
authenticate_outgoing(Message2, UsmSecParams,
AuthKey, AuthProtocol, SecLevel).
generate_discovery_msg(Message, SecEngineID, ManagerEngineID,
SecName, SecLevel) ->
generate_discovery_msg(Message, SecEngineID, ManagerEngineID,
SecName, SecLevel, "").
generate_discovery_msg(Message, SecEngineID, ManagerEngineID,
SecName, SecLevel, InitialUserName) ->
?vtrace("generate_discovery_msg -> entry with"
"~n SecEngineID: ~p"
"~n ManagerEngineID: ~p"
"~n SecName: ~p"
"~n SecLevel: ~p"
"~n InitialUserName: ~p",
[SecEngineID, ManagerEngineID, SecName, SecLevel,
InitialUserName]),
{UserName, AuthProtocol, AuthKey, PrivProtocol, PrivKey} =
case ManagerEngineID of
"" ->
Discovery step 1
%% Nothing except the user name will be used in this
%% tuple in this step, but since we need some values,
%% we fill in proper ones just in case
%% {"initial", usmNoAuthProtocol, "", usmNoPrivProtocol, ""};
%% {"", usmNoAuthProtocol, "", usmNoPrivProtocol, ""};
{InitialUserName,
usmNoAuthProtocol, "", usmNoPrivProtocol, ""};
%% _ ->
% % Discovery step 2
%% case snmp_user_based_sm_mib:get_user_from_security_name(
SecEngineID , SecName ) of
%% User when element(?usmUserStatus, User) =:=
%% ?'RowStatus_active' ->
%% {element(?usmUserName, User),
%% element(?usmUserAuthProtocol, User),
%% element(?usmUserAuthKey, User),
%% usmNoPrivProtocol, ""};
{ _ , Name , _ , _ , _ , _ , _ , _ , _ , _ , _ , _ , _ , RowStatus , _ , _ } - >
%% ?vdebug("generate_discovery_msg -> "
%% "found user ~p with wrong row status: ~p",
[ Name , RowStatus ] ) ,
%% error(unknownSecurityName);
%% _ ->
%% error(unknownSecurityName)
%% end
_ ->
Discovery step 2
case snmp_user_based_sm_mib:get_user_from_security_name(
SecEngineID, SecName) of
User when element(?usmUserStatus, User) =:=
?'RowStatus_active' ->
{element(?usmUserName, User),
element(?usmUserAuthProtocol, User),
element(?usmUserAuthKey, User),
element(?usmUserPrivProtocol, User),
element(?usmUserPrivKey, User)};
{_, Name,_,_,_,_,_,_,_,_,_,_,_, RowStatus,_,_} ->
?vdebug("generate_discovery_msg -> "
"found user ~p with wrong row status: ~p",
[Name, RowStatus]),
error(unknownSecurityName);
_ ->
error(unknownSecurityName)
end
end,
ScopedPduBytes = Message#message.data,
{ScopedPduData, MsgPrivParams} =
encrypt(ScopedPduBytes, PrivProtocol, PrivKey, SecLevel),
UsmSecParams =
#usmSecurityParameters{msgAuthoritativeEngineID = ManagerEngineID,
msgAuthoritativeEngineBoots = 0, % Boots,
Time ,
msgUserName = UserName,
msgPrivacyParameters = MsgPrivParams},
Message2 = Message#message{data = ScopedPduData},
authenticate_outgoing(Message2, UsmSecParams,
AuthKey, AuthProtocol, SecLevel).
Ret : { ScopedPDU , MsgPrivParams } - both are already encoded as OCTET STRINGs
encrypt(Data, PrivProtocol, PrivKey, SecLevel) ->
case snmp_misc:is_priv(SecLevel) of
3.1.4b
?vtrace("encrypt -> 3.1.4b",[]),
{Data, []};
true -> % 3.1.4a
?vtrace("encrypt -> 3.1.4a",[]),
case (catch try_encrypt(PrivProtocol, PrivKey, Data)) of
{ok, ScopedPduData, MsgPrivParams} ->
?vtrace("encrypt -> encode tag",[]),
{snmp_pdus:enc_oct_str_tag(ScopedPduData), MsgPrivParams};
{error, Reason} ->
error(Reason);
_Error ->
error(encryptionError)
end
end.
try_encrypt(?usmNoPrivProtocol, _PrivKey, _Data) -> % 3.1.2
error(unsupportedSecurityLevel);
try_encrypt(?usmDESPrivProtocol, PrivKey, Data) ->
des_encrypt(PrivKey, Data);
try_encrypt(?usmAesCfb128Protocol, PrivKey, Data) ->
aes_encrypt(PrivKey, Data).
authenticate_outgoing(Message, UsmSecParams,
AuthKey, AuthProtocol, SecLevel) ->
Message2 =
case snmp_misc:is_auth(SecLevel) of
true ->
auth_out(AuthProtocol, AuthKey, Message, UsmSecParams);
false ->
set_msg_auth_params(Message, UsmSecParams)
end,
?vtrace("authenticate_outgoing -> encode message only",[]),
snmp_pdus:enc_message_only(Message2).
%%-----------------------------------------------------------------
Auth and priv algorithms
%%-----------------------------------------------------------------
auth_in(AuthProtocol, AuthKey, AuthParams, Packet) ->
snmp_usm:auth_in(AuthProtocol, AuthKey, AuthParams, Packet).
auth_out(AuthProtocol, AuthKey, Message, UsmSecParams) ->
snmp_usm:auth_out(AuthProtocol, AuthKey, Message, UsmSecParams).
set_msg_auth_params(Message, UsmSecParams) ->
snmp_usm:set_msg_auth_params(Message, UsmSecParams, []).
des_encrypt(PrivKey, Data) ->
snmp_usm:des_encrypt(PrivKey, Data, fun get_des_salt/0).
des_decrypt(PrivKey, UsmSecParams, EncData) ->
#usmSecurityParameters{msgPrivacyParameters = PrivParms} = UsmSecParams,
snmp_usm:des_decrypt(PrivKey, PrivParms, EncData).
get_des_salt() ->
SaltInt =
case catch ets:update_counter(snmp_agent_table, usm_des_salt, 1) of
N when N =< 4294967295 ->
N;
N when is_integer(N) -> % wrap
ets:insert(snmp_agent_table, {usm_des_salt, 0}),
0;
_ -> % it doesn't exist, initialize
{A1,A2,A3} = erlang:now(),
random:seed(A1,A2,A3),
R = random:uniform(4294967295),
ets:insert(snmp_agent_table, {usm_des_salt, R}),
R
end,
EngineBoots = snmp_framework_mib:get_engine_boots(),
[?i32(EngineBoots), ?i32(SaltInt)].
aes_encrypt(PrivKey, Data) ->
snmp_usm:aes_encrypt(PrivKey, Data, fun get_aes_salt/0).
aes_decrypt(PrivKey, UsmSecParams, EncData) ->
#usmSecurityParameters{msgPrivacyParameters = PrivParams,
msgAuthoritativeEngineTime = EngineTime,
msgAuthoritativeEngineBoots = EngineBoots} =
UsmSecParams,
snmp_usm:aes_decrypt(PrivKey, PrivParams, EncData,
EngineBoots, EngineTime).
get_aes_salt() ->
SaltInt =
case catch ets:update_counter(snmp_agent_table, usm_aes_salt, 1) of
N when N =< 36893488147419103231 ->
N;
N when is_integer(N) -> % wrap
ets:insert(snmp_agent_table, {usm_aes_salt, 0}),
0;
_ -> % it doesn't exist, initialize
{A1,A2,A3} = erlang:now(),
random:seed(A1,A2,A3),
R = random:uniform(36893488147419103231),
ets:insert(snmp_agent_table, {usm_aes_salt, R}),
R
end,
[?i64(SaltInt)].
%%-----------------------------------------------------------------
Discovery wrapper functions
%%-----------------------------------------------------------------
is_terminating_discovery_enabled() ->
snmpa_agent:is_terminating_discovery_enabled().
terminating_discovery_stage2() ->
snmpa_agent:terminating_discovery_stage2().
%%-----------------------------------------------------------------
%% We cache the local values of all non-auth engines we know.
%% Keep the values in the snmp_agent_table.
See section 2.3 of the RFC .
%%-----------------------------------------------------------------
get_engine_boots(SnmpEngineID) ->
case ets:lookup(snmp_agent_table, {usm_eboots, SnmpEngineID}) of
[{_Key, Boots}] -> Boots;
_ -> 0
end.
get_engine_time(SnmpEngineID) ->
case ets:lookup(snmp_agent_table, {usm_etime, SnmpEngineID}) of
[{_Key, Diff}] -> snmp_misc:now(sec) - Diff;
_ -> 0
end.
get_engine_latest_time(SnmpEngineID) ->
case ets:lookup(snmp_agent_table, {usm_eltime, SnmpEngineID}) of
[{_Key, Time}] -> Time;
_ -> 0
end.
set_engine_boots(SnmpEngineID, EngineBoots) ->
ets:insert(snmp_agent_table, {{usm_eboots, SnmpEngineID}, EngineBoots}).
set_engine_time(SnmpEngineID, EngineTime) ->
Diff = snmp_misc:now(sec) - EngineTime,
ets:insert(snmp_agent_table, {{usm_etime, SnmpEngineID}, Diff}).
set_engine_latest_time(SnmpEngineID, EngineTime) ->
ets:insert(snmp_agent_table, {{usm_eltime, SnmpEngineID}, EngineTime}).
%%-----------------------------------------------------------------
%% Utility functions
%%-----------------------------------------------------------------
error(Reason) ->
throw({error, Reason}).
error(Reason, ErrorInfo) ->
throw({error, Reason, ErrorInfo}).
error(Variable, Oid, SecName) ->
error(Variable, Oid, SecName, []).
error(Variable, Oid, SecName, Opts) ->
Val = inc(Variable),
ErrorInfo = {#varbind{oid = Oid,
variabletype = 'Counter32',
value = Val},
SecName,
Opts},
throw({error, Variable, ErrorInfo}).
inc(Name) -> ets:update_counter(snmp_agent_table, Name, 1).
get_counter(Name) ->
case (catch ets:lookup(snmp_agent_table, Name)) of
[{_, Val}] ->
Val;
_ ->
0
end.
| null | https://raw.githubusercontent.com/yrashk/erlang/e1282325ed75e52a98d58f5bd9fb0fa27896173f/lib/snmp/src/agent/snmpa_usm.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
-----------------------------------------------------------------
This module implements the User Based Security Model for SNMP,
as defined in rfc2274.
-----------------------------------------------------------------
Columns not accessible via SNMP
-----------------------------------------------------------------
Return value may be throwed.
Types: Reason -> term()
Purpose:
-----------------------------------------------------------------
undefined or not active user
the old values will be used.
OTP-5464
noAuth
authNoPriv
3.2.7b1
OTP-5464
This will *always* result in the manager *not*
beeing in timewindow
OTP-5464
OTP-5464
OTP-5464
Not a response - read from LCD
This means the user at the engine is unknown
not a response
3.1.8
Nothing except the user name will be used in this
tuple in this step, but since we need some values,
we fill in proper ones just in case
{"initial", usmNoAuthProtocol, "", usmNoPrivProtocol, ""};
{"", usmNoAuthProtocol, "", usmNoPrivProtocol, ""};
_ ->
% Discovery step 2
case snmp_user_based_sm_mib:get_user_from_security_name(
User when element(?usmUserStatus, User) =:=
?'RowStatus_active' ->
{element(?usmUserName, User),
element(?usmUserAuthProtocol, User),
element(?usmUserAuthKey, User),
usmNoPrivProtocol, ""};
?vdebug("generate_discovery_msg -> "
"found user ~p with wrong row status: ~p",
error(unknownSecurityName);
_ ->
error(unknownSecurityName)
end
Boots,
3.1.4a
3.1.2
-----------------------------------------------------------------
-----------------------------------------------------------------
wrap
it doesn't exist, initialize
wrap
it doesn't exist, initialize
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
We cache the local values of all non-auth engines we know.
Keep the values in the snmp_agent_table.
-----------------------------------------------------------------
-----------------------------------------------------------------
Utility functions
----------------------------------------------------------------- | Copyright Ericsson AB 1999 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(snmpa_usm).
-export([
process_incoming_msg/4,
generate_outgoing_msg/5,
generate_discovery_msg/5, generate_discovery_msg/6
]).
-define(SNMP_USE_V3, true).
-include("snmp_types.hrl").
-include("SNMP-USER-BASED-SM-MIB.hrl").
-include("SNMP-USM-AES-MIB.hrl").
-include("SNMPv2-TC.hrl").
-define(VMODULE,"A-USM").
-include("snmp_verbosity.hrl").
-define(usmUserAuthKey, 14).
-define(usmUserPrivKey, 15).
-define(i32(Int), (Int bsr 24) band 255, (Int bsr 16) band 255, (Int bsr 8) band 255, Int band 255).
-define(i64(Int), (Int bsr 56) band 255, (Int bsr 48) band 255, (Int bsr 40) band 255, (Int bsr 32) band 255, (Int bsr 24) band 255, (Int bsr 16) band 255, (Int bsr 8) band 255, Int band 255).
Func : process_incoming_msg(Packet , Data , SecParams , ) - >
{ ok , { SecEngineID , SecName , ScopedPDUBytes , SecData } } |
{ error , Reason } | { error , , ErrorInfo }
process_incoming_msg(Packet, Data, SecParams, SecLevel) ->
TermDiscoEnabled = is_terminating_discovery_enabled(),
3.2.1
?vtrace("process_incoming_msg -> check security parms: 3.2.1",[]),
UsmSecParams =
case catch snmp_pdus:dec_usm_security_parameters(SecParams) of
{'EXIT', Reason} ->
inc(snmpInASNParseErrs),
error({parseError, Reason}, []);
Res ->
Res
end,
case UsmSecParams of
#usmSecurityParameters{msgAuthoritativeEngineID = MsgAuthEngineID,
msgUserName = ""} when TermDiscoEnabled =:= true ->
Step 1 discovery message
?vtrace("process_incoming_msg -> discovery step 1", []),
process_discovery_msg(MsgAuthEngineID, Data, SecLevel);
#usmSecurityParameters{msgAuthoritativeEngineID = MsgAuthEngineID,
msgUserName = "initial"} when TermDiscoEnabled =:= true ->
Step 1 discovery message
?vtrace("process_incoming_msg -> [initial] discovery step 1", []),
process_discovery_msg(MsgAuthEngineID, Data, SecLevel);
#usmSecurityParameters{msgAuthoritativeEngineID = MsgAuthEngineID,
msgUserName = MsgUserName} ->
?vlog("process_incoming_msg -> USM security parms: "
"~n authEngineID: \"~s\""
"~n userName: \"~s\"", [MsgAuthEngineID, MsgUserName]),
3.2.3
?vtrace("process_incoming_msg -> check engine id: 3.2.3",[]),
case snmp_user_based_sm_mib:is_engine_id_known(MsgAuthEngineID) of
true ->
ok;
false ->
SecData1 = [MsgUserName],
error(usmStatsUnknownEngineIDs,
OTP-3542
undefined, [{sec_data, SecData1}])
end,
3.2.4
?vtrace("process_incoming_msg -> retrieve usm user: 3.2.4",[]),
UsmUser =
case snmp_user_based_sm_mib:get_user(MsgAuthEngineID,
MsgUserName) of
User when element(?usmUserStatus, User) =:= ?'RowStatus_active' ->
User;
{_, Name,_,_,_,_,_,_,_,_,_,_,_, RowStatus,_,_} ->
?vdebug("process_incoming_msg -> "
"found user ~p with wrong row status: ~p",
[Name, RowStatus]),
SecData2 = [MsgUserName],
error(usmStatsUnknownUserNames,
OTP-3542
undefined, [{sec_data, SecData2}]);
SecData2 = [MsgUserName],
error(usmStatsUnknownUserNames,
OTP-3542
undefined, [{sec_data, SecData2}])
end,
SecName = element(?usmUserSecurityName, UsmUser),
?vtrace("process_incoming_msg -> securityName: ~p",[SecName]),
3.2.5 - implicit in following checks
3.2.6 - 3.2.7
?vtrace("process_incoming_msg -> "
"authenticate incoming: 3.2.5 - 3.2.7"
"~n ~p",[UsmUser]),
DiscoOrPlain = authenticate_incoming(Packet,
UsmSecParams, UsmUser,
SecLevel),
3.2.8
?vtrace("process_incoming_msg -> "
"decrypt scoped data: 3.2.8",[]),
ScopedPDUBytes =
decrypt(Data, UsmUser, UsmSecParams, SecLevel),
3.2.9
Means that if AuthKey / PrivKey are changed ;
?vtrace("process_incoming_msg -> "
"AuthKey/PrivKey are changed - "
"use old values: 3.2.9",[]),
CachedSecData = {MsgUserName,
element(?usmUserAuthProtocol, UsmUser),
element(?usmUserPrivProtocol, UsmUser),
element(?usmUserAuthKey, UsmUser),
element(?usmUserPrivKey, UsmUser)},
{ok, {MsgAuthEngineID, SecName, ScopedPDUBytes,
CachedSecData, DiscoOrPlain}}
end.
Process a step 1 discovery message
process_discovery_msg(MsgAuthEngineID, Data, SecLevel) ->
?vtrace("process_discovery_msg -> entry with"
"~n Data: ~p"
"~n SecLevel: ~p", [Data, SecLevel]),
case (not snmp_misc:is_priv(SecLevel)) of
noAuthNoPriv
?vtrace("process_discovery_msg -> noAuthNoPriv", []),
ScopedPDUBytes = Data,
SecData = {"", usmNoAuthProtocol, "", usmNoPrivProtocol, ""},
NewData = {SecData,
?usmStatsUnknownEngineIDs_instance,
get_counter(usmStatsUnknownEngineIDs)},
{ok, {MsgAuthEngineID, "", ScopedPDUBytes, NewData, discovery}};
false ->
error(usmStatsUnknownEngineIDs,
?usmStatsUnknownEngineIDs_instance,
undefined, [{sec_data, ""}])
end.
authenticate_incoming(Packet, UsmSecParams, UsmUser, SecLevel) ->
3.2.6
?vtrace("authenticate_incoming -> 3.2.6",[]),
AuthProtocol = element(?usmUserAuthProtocol, UsmUser),
#usmSecurityParameters{msgAuthoritativeEngineID = MsgAuthEngineID,
msgAuthoritativeEngineBoots = MsgAuthEngineBoots,
msgAuthoritativeEngineTime = MsgAuthEngineTime,
msgAuthenticationParameters = MsgAuthParams} =
UsmSecParams,
?vtrace("authenticate_incoming -> Sec params: "
"~n MsgAuthEngineID: ~p"
"~n MsgAuthEngineBoots: ~p"
"~n MsgAuthEngineTime: ~p",
[MsgAuthEngineID, MsgAuthEngineBoots, MsgAuthEngineTime]),
case snmp_misc:is_auth(SecLevel) of
true ->
SecName = element(?usmUserSecurityName, UsmUser),
case is_auth(AuthProtocol,
element(?usmUserAuthKey, UsmUser),
MsgAuthParams,
Packet,
SecName,
MsgAuthEngineID,
MsgAuthEngineBoots,
MsgAuthEngineTime) of
discovery ->
discovery;
true ->
plain;
false ->
error(usmStatsWrongDigests,
SecName)
end;
plain
end.
authoritative(SecName, MsgAuthEngineBoots, MsgAuthEngineTime) ->
?vtrace("authoritative -> entry with"
"~n SecName: ~p"
"~n MsgAuthEngineBoots: ~p"
"~n MsgAuthEngineTime: ~p",
[SecName, MsgAuthEngineBoots, MsgAuthEngineTime]),
SnmpEngineBoots = snmp_framework_mib:get_engine_boots(),
?vtrace("authoritative -> SnmpEngineBoots: ~p", [SnmpEngineBoots]),
SnmpEngineTime = snmp_framework_mib:get_engine_time(),
?vtrace("authoritative -> SnmpEngineTime: ~p", [SnmpEngineTime]),
InTimeWindow =
if
SnmpEngineBoots =:= 2147483647 -> false;
MsgAuthEngineBoots =/= SnmpEngineBoots -> false;
MsgAuthEngineTime + 150 < SnmpEngineTime -> false;
MsgAuthEngineTime - 150 > SnmpEngineTime -> false;
true -> true
end,
case InTimeWindow of
true ->
true;
false ->
OTP-4090 ( OTP-3542 )
?vinfo("NOT in time window: "
"~n SecName: ~p"
"~n SnmpEngineBoots: ~p"
"~n MsgAuthEngineBoots: ~p"
"~n SnmpEngineTime: ~p"
"~n MsgAuthEngineTime: ~p",
[SecName,
SnmpEngineBoots, MsgAuthEngineBoots,
SnmpEngineTime, MsgAuthEngineTime]),
error(usmStatsNotInTimeWindows,
?usmStatsNotInTimeWindows_instance,
SecName,
end.
non_authoritative(SecName,
MsgAuthEngineID, MsgAuthEngineBoots, MsgAuthEngineTime) ->
?vtrace("non_authoritative -> entry with"
"~n SecName: ~p"
"~n MsgAuthEngineID: ~p"
"~n MsgAuthEngineBoots: ~p"
"~n MsgAuthEngineTime: ~p",
[SecName,
MsgAuthEngineID, MsgAuthEngineBoots, MsgAuthEngineTime]),
SnmpEngineBoots = get_engine_boots(MsgAuthEngineID),
?vtrace("non_authoritative -> SnmpEngineBoots: ~p", [SnmpEngineBoots]),
SnmpEngineTime = get_engine_time(MsgAuthEngineID),
LatestRecvTime = get_engine_latest_time(MsgAuthEngineID),
UpdateLCD =
if
MsgAuthEngineBoots > SnmpEngineBoots -> true;
((MsgAuthEngineBoots =:= SnmpEngineBoots) andalso
(MsgAuthEngineTime > LatestRecvTime)) -> true;
true -> false
end,
case UpdateLCD of
?vtrace("non_authoritative -> "
"update msgAuthoritativeEngineID: 3.2.7b1",
[]),
set_engine_boots(MsgAuthEngineID, MsgAuthEngineBoots),
set_engine_time(MsgAuthEngineID, MsgAuthEngineTime),
set_engine_latest_time(MsgAuthEngineID, MsgAuthEngineTime);
false ->
ok
end,
3.2.7.b2
?vtrace("non_authoritative -> "
"check if message is outside time window: 3.2.7b2",
[]),
InTimeWindow =
if
SnmpEngineBoots == 2147483647 ->
false;
MsgAuthEngineBoots < SnmpEngineBoots ->
false;
MsgAuthEngineBoots =:= SnmpEngineBoots,
MsgAuthEngineTime < (SnmpEngineTime - 150) ->
false;
true -> true
end,
case InTimeWindow of
false ->
?vinfo("NOT in time window: "
"~n SecName: ~p"
"~n SnmpEngineBoots: ~p"
"~n MsgAuthEngineBoots: ~p"
"~n SnmpEngineTime: ~p"
"~n MsgAuthEngineTime: ~p",
[SecName,
SnmpEngineBoots, MsgAuthEngineBoots,
SnmpEngineTime, MsgAuthEngineTime]),
error(notInTimeWindow, []);
true ->
ok
end,
true.
3.2.5
error(usmStatsUnsupportedSecLevels,
is_auth(AuthProtocol, AuthKey, AuthParams, Packet, SecName,
MsgAuthEngineID, MsgAuthEngineBoots, MsgAuthEngineTime) ->
TermDiscoEnabled = is_terminating_discovery_enabled(),
TermDiscoStage2 = terminating_discovery_stage2(),
IsAuth = auth_in(AuthProtocol, AuthKey, AuthParams, Packet),
case IsAuth of
true ->
3.2.7
?vtrace("is_auth -> "
"retrieve EngineBoots and EngineTime: 3.2.7",[]),
SnmpEngineID = snmp_framework_mib:get_engine_id(),
?vtrace("is_auth -> SnmpEngineID: ~p", [SnmpEngineID]),
case MsgAuthEngineID of
SnmpEngineID when ((MsgAuthEngineBoots =:= 0) andalso
(MsgAuthEngineTime =:= 0) andalso
(TermDiscoEnabled =:= true) andalso
3.2.7a
?vtrace("is_auth -> discovery stage 2 - discovery",[]),
discovery;
SnmpEngineID when ((MsgAuthEngineBoots =:= 0) andalso
(MsgAuthEngineTime =:= 0) andalso
(TermDiscoEnabled =:= true) andalso
3.2.7a
?vtrace("is_auth -> discovery stage 2 - plain",[]),
authoritative(SecName,
MsgAuthEngineBoots, MsgAuthEngineTime);
3.2.7a
?vtrace("is_auth -> we are authoritative: 3.2.7a", []),
authoritative(SecName,
MsgAuthEngineBoots, MsgAuthEngineTime);
3.2.7b - we 're non - authoritative
?vtrace("is_auth -> we are non-authoritative: 3.2.7b",[]),
non_authoritative(SecName,
MsgAuthEngineID,
MsgAuthEngineBoots, MsgAuthEngineTime)
end;
false ->
false
end.
decrypt(Data, UsmUser, UsmSecParams, SecLevel) ->
case snmp_misc:is_priv(SecLevel) of
true ->
do_decrypt(Data, UsmUser, UsmSecParams);
false ->
Data
end.
do_decrypt(Data, UsmUser, UsmSecParams) ->
EncryptedPDU = snmp_pdus:dec_scoped_pdu_data(Data),
SecName = element(?usmUserSecurityName, UsmUser),
PrivP = element(?usmUserPrivProtocol, UsmUser),
PrivKey = element(?usmUserPrivKey, UsmUser),
?vtrace("do_decrypt -> try decrypt with: "
"~n SecName: ~p"
"~n PrivP: ~p", [SecName, PrivP]),
try_decrypt(PrivP, PrivKey, UsmSecParams, EncryptedPDU, SecName).
3.2.5
error(usmStatsUnsupportedSecLevels,
try_decrypt(?usmDESPrivProtocol,
PrivKey, UsmSecParams, EncryptedPDU, SecName) ->
case (catch des_decrypt(PrivKey, UsmSecParams, EncryptedPDU)) of
{ok, DecryptedData} ->
DecryptedData;
_ ->
error(usmStatsDecryptionErrors,
SecName)
end;
try_decrypt(?usmAesCfb128Protocol,
PrivKey, UsmSecParams, EncryptedPDU, SecName) ->
case (catch aes_decrypt(PrivKey, UsmSecParams, EncryptedPDU)) of
{ok, DecryptedData} ->
DecryptedData;
_ ->
error(usmStatsDecryptionErrors,
SecName)
end.
generate_outgoing_msg(Message, SecEngineID, SecName, SecData, SecLevel) ->
3.1.1
?vtrace("generate_outgoing_msg -> [3.1.1] entry with"
"~n SecEngineID: ~p"
"~n SecName: ~p"
"~n SecLevel: ~w",
[SecEngineID, SecName, SecLevel]),
{UserName, AuthProtocol, PrivProtocol, AuthKey, PrivKey} =
case SecData of
3.1.1b
case snmp_user_based_sm_mib:get_user_from_security_name(
SecEngineID, SecName) of
User when element(?usmUserStatus, User) =:=
?'RowStatus_active' ->
{element(?usmUserName, User),
element(?usmUserAuthProtocol, User),
element(?usmUserPrivProtocol, User),
element(?usmUserAuthKey, User),
element(?usmUserPrivKey, User)};
{_, Name,_,_,_,_,_,_,_,_,_,_,_, RowStatus,_,_} ->
?vdebug("generate_outgoing_msg -> "
"found user ~p with wrong row status: ~p",
[Name, RowStatus]),
error(unknownSecurityName);
_ ->
error(unknownSecurityName)
end;
[MsgUserName] ->
{MsgUserName, ?usmNoAuthProtocol, ?usmNoPrivProtocol, "", ""};
3.1.1a
SecData
end,
3.1.4
?vtrace("generate_outgoing_msg -> [3.1.4]"
"~n UserName: ~p"
"~n AuthProtocol: ~p"
"~n PrivProtocol: ~p",
[UserName, AuthProtocol, PrivProtocol]),
ScopedPduBytes = Message#message.data,
{ScopedPduData, MsgPrivParams} =
encrypt(ScopedPduBytes, PrivProtocol, PrivKey, SecLevel),
SnmpEngineID = snmp_framework_mib:get_engine_id(),
?vtrace("generate_outgoing_msg -> SnmpEngineID: ~p [3.1.6]",
[SnmpEngineID]),
3.1.6
{MsgAuthEngineBoots, MsgAuthEngineTime} =
case snmp_misc:is_auth(SecLevel) of
{0, 0};
reply ( report ) to discovery step 1
{0, 0};
true when SecEngineID =/= SnmpEngineID ->
{get_engine_boots(SecEngineID),
get_engine_time(SecEngineID)};
_ ->
{snmp_framework_mib:get_engine_boots(),
snmp_framework_mib:get_engine_time()}
end,
3.1.5 - 3.1.7
?vtrace("generate_outgoing_msg -> [3.1.5 - 3.1.7]",[]),
UsmSecParams =
#usmSecurityParameters{msgAuthoritativeEngineID = SecEngineID,
msgAuthoritativeEngineBoots = MsgAuthEngineBoots,
msgAuthoritativeEngineTime = MsgAuthEngineTime,
msgUserName = UserName,
msgPrivacyParameters = MsgPrivParams},
Message2 = Message#message{data = ScopedPduData},
?vtrace("generate_outgoing_msg -> [3.1.8]",[]),
authenticate_outgoing(Message2, UsmSecParams,
AuthKey, AuthProtocol, SecLevel).
generate_discovery_msg(Message, SecEngineID, ManagerEngineID,
SecName, SecLevel) ->
generate_discovery_msg(Message, SecEngineID, ManagerEngineID,
SecName, SecLevel, "").
generate_discovery_msg(Message, SecEngineID, ManagerEngineID,
SecName, SecLevel, InitialUserName) ->
?vtrace("generate_discovery_msg -> entry with"
"~n SecEngineID: ~p"
"~n ManagerEngineID: ~p"
"~n SecName: ~p"
"~n SecLevel: ~p"
"~n InitialUserName: ~p",
[SecEngineID, ManagerEngineID, SecName, SecLevel,
InitialUserName]),
{UserName, AuthProtocol, AuthKey, PrivProtocol, PrivKey} =
case ManagerEngineID of
"" ->
Discovery step 1
{InitialUserName,
usmNoAuthProtocol, "", usmNoPrivProtocol, ""};
SecEngineID , SecName ) of
{ _ , Name , _ , _ , _ , _ , _ , _ , _ , _ , _ , _ , _ , RowStatus , _ , _ } - >
[ Name , RowStatus ] ) ,
_ ->
Discovery step 2
case snmp_user_based_sm_mib:get_user_from_security_name(
SecEngineID, SecName) of
User when element(?usmUserStatus, User) =:=
?'RowStatus_active' ->
{element(?usmUserName, User),
element(?usmUserAuthProtocol, User),
element(?usmUserAuthKey, User),
element(?usmUserPrivProtocol, User),
element(?usmUserPrivKey, User)};
{_, Name,_,_,_,_,_,_,_,_,_,_,_, RowStatus,_,_} ->
?vdebug("generate_discovery_msg -> "
"found user ~p with wrong row status: ~p",
[Name, RowStatus]),
error(unknownSecurityName);
_ ->
error(unknownSecurityName)
end
end,
ScopedPduBytes = Message#message.data,
{ScopedPduData, MsgPrivParams} =
encrypt(ScopedPduBytes, PrivProtocol, PrivKey, SecLevel),
UsmSecParams =
#usmSecurityParameters{msgAuthoritativeEngineID = ManagerEngineID,
Time ,
msgUserName = UserName,
msgPrivacyParameters = MsgPrivParams},
Message2 = Message#message{data = ScopedPduData},
authenticate_outgoing(Message2, UsmSecParams,
AuthKey, AuthProtocol, SecLevel).
Ret : { ScopedPDU , MsgPrivParams } - both are already encoded as OCTET STRINGs
encrypt(Data, PrivProtocol, PrivKey, SecLevel) ->
case snmp_misc:is_priv(SecLevel) of
3.1.4b
?vtrace("encrypt -> 3.1.4b",[]),
{Data, []};
?vtrace("encrypt -> 3.1.4a",[]),
case (catch try_encrypt(PrivProtocol, PrivKey, Data)) of
{ok, ScopedPduData, MsgPrivParams} ->
?vtrace("encrypt -> encode tag",[]),
{snmp_pdus:enc_oct_str_tag(ScopedPduData), MsgPrivParams};
{error, Reason} ->
error(Reason);
_Error ->
error(encryptionError)
end
end.
error(unsupportedSecurityLevel);
try_encrypt(?usmDESPrivProtocol, PrivKey, Data) ->
des_encrypt(PrivKey, Data);
try_encrypt(?usmAesCfb128Protocol, PrivKey, Data) ->
aes_encrypt(PrivKey, Data).
authenticate_outgoing(Message, UsmSecParams,
AuthKey, AuthProtocol, SecLevel) ->
Message2 =
case snmp_misc:is_auth(SecLevel) of
true ->
auth_out(AuthProtocol, AuthKey, Message, UsmSecParams);
false ->
set_msg_auth_params(Message, UsmSecParams)
end,
?vtrace("authenticate_outgoing -> encode message only",[]),
snmp_pdus:enc_message_only(Message2).
Auth and priv algorithms
auth_in(AuthProtocol, AuthKey, AuthParams, Packet) ->
snmp_usm:auth_in(AuthProtocol, AuthKey, AuthParams, Packet).
auth_out(AuthProtocol, AuthKey, Message, UsmSecParams) ->
snmp_usm:auth_out(AuthProtocol, AuthKey, Message, UsmSecParams).
set_msg_auth_params(Message, UsmSecParams) ->
snmp_usm:set_msg_auth_params(Message, UsmSecParams, []).
des_encrypt(PrivKey, Data) ->
snmp_usm:des_encrypt(PrivKey, Data, fun get_des_salt/0).
des_decrypt(PrivKey, UsmSecParams, EncData) ->
#usmSecurityParameters{msgPrivacyParameters = PrivParms} = UsmSecParams,
snmp_usm:des_decrypt(PrivKey, PrivParms, EncData).
get_des_salt() ->
SaltInt =
case catch ets:update_counter(snmp_agent_table, usm_des_salt, 1) of
N when N =< 4294967295 ->
N;
ets:insert(snmp_agent_table, {usm_des_salt, 0}),
0;
{A1,A2,A3} = erlang:now(),
random:seed(A1,A2,A3),
R = random:uniform(4294967295),
ets:insert(snmp_agent_table, {usm_des_salt, R}),
R
end,
EngineBoots = snmp_framework_mib:get_engine_boots(),
[?i32(EngineBoots), ?i32(SaltInt)].
aes_encrypt(PrivKey, Data) ->
snmp_usm:aes_encrypt(PrivKey, Data, fun get_aes_salt/0).
aes_decrypt(PrivKey, UsmSecParams, EncData) ->
#usmSecurityParameters{msgPrivacyParameters = PrivParams,
msgAuthoritativeEngineTime = EngineTime,
msgAuthoritativeEngineBoots = EngineBoots} =
UsmSecParams,
snmp_usm:aes_decrypt(PrivKey, PrivParams, EncData,
EngineBoots, EngineTime).
get_aes_salt() ->
SaltInt =
case catch ets:update_counter(snmp_agent_table, usm_aes_salt, 1) of
N when N =< 36893488147419103231 ->
N;
ets:insert(snmp_agent_table, {usm_aes_salt, 0}),
0;
{A1,A2,A3} = erlang:now(),
random:seed(A1,A2,A3),
R = random:uniform(36893488147419103231),
ets:insert(snmp_agent_table, {usm_aes_salt, R}),
R
end,
[?i64(SaltInt)].
Discovery wrapper functions
is_terminating_discovery_enabled() ->
snmpa_agent:is_terminating_discovery_enabled().
terminating_discovery_stage2() ->
snmpa_agent:terminating_discovery_stage2().
See section 2.3 of the RFC .
get_engine_boots(SnmpEngineID) ->
case ets:lookup(snmp_agent_table, {usm_eboots, SnmpEngineID}) of
[{_Key, Boots}] -> Boots;
_ -> 0
end.
get_engine_time(SnmpEngineID) ->
case ets:lookup(snmp_agent_table, {usm_etime, SnmpEngineID}) of
[{_Key, Diff}] -> snmp_misc:now(sec) - Diff;
_ -> 0
end.
get_engine_latest_time(SnmpEngineID) ->
case ets:lookup(snmp_agent_table, {usm_eltime, SnmpEngineID}) of
[{_Key, Time}] -> Time;
_ -> 0
end.
set_engine_boots(SnmpEngineID, EngineBoots) ->
ets:insert(snmp_agent_table, {{usm_eboots, SnmpEngineID}, EngineBoots}).
set_engine_time(SnmpEngineID, EngineTime) ->
Diff = snmp_misc:now(sec) - EngineTime,
ets:insert(snmp_agent_table, {{usm_etime, SnmpEngineID}, Diff}).
set_engine_latest_time(SnmpEngineID, EngineTime) ->
ets:insert(snmp_agent_table, {{usm_eltime, SnmpEngineID}, EngineTime}).
error(Reason) ->
throw({error, Reason}).
error(Reason, ErrorInfo) ->
throw({error, Reason, ErrorInfo}).
error(Variable, Oid, SecName) ->
error(Variable, Oid, SecName, []).
error(Variable, Oid, SecName, Opts) ->
Val = inc(Variable),
ErrorInfo = {#varbind{oid = Oid,
variabletype = 'Counter32',
value = Val},
SecName,
Opts},
throw({error, Variable, ErrorInfo}).
inc(Name) -> ets:update_counter(snmp_agent_table, Name, 1).
get_counter(Name) ->
case (catch ets:lookup(snmp_agent_table, Name)) of
[{_, Val}] ->
Val;
_ ->
0
end.
|
51402beb868b47c415429950e426ea378cdf9811f5a30b0b1b6d95793812afc6 | PearsonEducation/subpub | sgte_dict.erl | %%%-------------------------------------------------------------------
%%% File : sgte_dict
Author : < >
%%% License :
The contents of this file are subject to the Mozilla Public
%%% License Version 1.1 (the "License"); you may not use this file
%%% except in compliance with the License. You may obtain a copy of
the License at /
%%%
Software distributed under the License is distributed on an " AS IS "
%%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%%% the License for the specific language governing rights and
%%% limitations under the License.
The Initial Developer of the Original Code is S.G. Consulting
srl . Portions created by S.G. Consulting s.r.l . are Copyright ( C )
2007 S.G. Consulting srl . All Rights Reserved .
%%%
%%% @doc
%%% <p>Implements a dictionary and a record like data structure.
%%% Uses the dict module and extends it to support nested dicts.</p>
%%%
%%% <p>This module is the interface used to access data in the
%%% render phase.</p>
%%% @end
%%%
Created : 3 Sep 2007 by < >
%%%-------------------------------------------------------------------
-module(sgte_dict).
-ifdef(ERLHIVE).
-import(.lists). % erlhive uses package notation
-import(.dict). % ditto
-endif.
-export([rfind/2,
find/2,
store/3,
merge/3,
from_list/1,
rec_to_name_kv/2,
rec_to_kv/2]).
%% recursive find
rfind([Key], Dict) ->
case dict:find(Key, Dict) of
error ->
{error, Key};
{ok, V} ->
{ok, V}
end;
rfind([H|T], Dict) ->
case dict:find(H, Dict) of
error ->
{error, H};
{ok, D} when is_list(D) ->
?MODULE:rfind(T, dict:from_list(D));
{ok, D} ->
?MODULE:rfind(T, D)
end.
find(Key, Dict) when is_list(Dict) ->
dict:find(Key, dict:from_list(Dict));
find(Key, Dict) ->
dict:find(Key, Dict).
store(Key, Value, Dict) ->
dict:store(Key, Value, Dict).
merge(Fun, Dict1, Dict2) ->
dict:merge(Fun, Dict1, Dict2).
from_list(List) ->
dict:from_list(List).
rec_to_name_kv(RecordTuple, Keys) ->
[Name|Values] = tuple_to_list(RecordTuple),
case length(Values) =:= length(Keys) of
true ->
{Name, lists:zip(Keys, Values)};
false ->
case length(Values) > length(Keys) of
true ->
{error, not_enough_keys};
_ ->
{error, too_much_keys}
end
end.
rec_to_kv(RecordTuple, Keys) ->
[_Name|Values] = tuple_to_list(RecordTuple),
case length(Values) =:= length(Keys) of
true ->
lists:zip(Keys, Values);
false ->
case length(Values) > length(Keys) of
true ->
{error, not_enough_keys};
_ ->
{error, too_much_keys}
end
end.
| null | https://raw.githubusercontent.com/PearsonEducation/subpub/f2275c5da24d8860d206cff81d1ce87ecd956c72/deps/erlang/sgte-0.7.1/src/sgte_dict.erl | erlang | -------------------------------------------------------------------
File : sgte_dict
License :
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and
limitations under the License.
@doc
<p>Implements a dictionary and a record like data structure.
Uses the dict module and extends it to support nested dicts.</p>
<p>This module is the interface used to access data in the
render phase.</p>
@end
-------------------------------------------------------------------
erlhive uses package notation
ditto
recursive find | Author : < >
The contents of this file are subject to the Mozilla Public
the License at /
Software distributed under the License is distributed on an " AS IS "
The Initial Developer of the Original Code is S.G. Consulting
srl . Portions created by S.G. Consulting s.r.l . are Copyright ( C )
2007 S.G. Consulting srl . All Rights Reserved .
Created : 3 Sep 2007 by < >
-module(sgte_dict).
-ifdef(ERLHIVE).
-endif.
-export([rfind/2,
find/2,
store/3,
merge/3,
from_list/1,
rec_to_name_kv/2,
rec_to_kv/2]).
rfind([Key], Dict) ->
case dict:find(Key, Dict) of
error ->
{error, Key};
{ok, V} ->
{ok, V}
end;
rfind([H|T], Dict) ->
case dict:find(H, Dict) of
error ->
{error, H};
{ok, D} when is_list(D) ->
?MODULE:rfind(T, dict:from_list(D));
{ok, D} ->
?MODULE:rfind(T, D)
end.
find(Key, Dict) when is_list(Dict) ->
dict:find(Key, dict:from_list(Dict));
find(Key, Dict) ->
dict:find(Key, Dict).
store(Key, Value, Dict) ->
dict:store(Key, Value, Dict).
merge(Fun, Dict1, Dict2) ->
dict:merge(Fun, Dict1, Dict2).
from_list(List) ->
dict:from_list(List).
rec_to_name_kv(RecordTuple, Keys) ->
[Name|Values] = tuple_to_list(RecordTuple),
case length(Values) =:= length(Keys) of
true ->
{Name, lists:zip(Keys, Values)};
false ->
case length(Values) > length(Keys) of
true ->
{error, not_enough_keys};
_ ->
{error, too_much_keys}
end
end.
rec_to_kv(RecordTuple, Keys) ->
[_Name|Values] = tuple_to_list(RecordTuple),
case length(Values) =:= length(Keys) of
true ->
lists:zip(Keys, Values);
false ->
case length(Values) > length(Keys) of
true ->
{error, not_enough_keys};
_ ->
{error, too_much_keys}
end
end.
|
6fdbb8945f94b66ca2050e4dcf7f58a75d5b84bb4e0c0bce3b3958192c30478d | grin-compiler/ghc-wpc-sample-programs | Match.hs | # LANGUAGE NondecreasingIndentation #
-- | Pattern matcher used in the reducer for clauses that
-- have not been compiled to case trees yet.
module Agda.TypeChecking.Patterns.Match where
import Prelude hiding (null)
import Control.Monad
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Traversable (traverse)
import Agda.Syntax.Common
import Agda.Syntax.Internal
import Agda.Syntax.Internal.Pattern
import Agda.TypeChecking.Reduce
import Agda.TypeChecking.Reduce.Monad
import Agda.TypeChecking.Substitute
import Agda.TypeChecking.Monad hiding (constructorForm)
import Agda.TypeChecking.Pretty
import Agda.TypeChecking.Records
import Agda.Utils.Empty
import Agda.Utils.Functor (for, ($>))
import Agda.Utils.Maybe
import Agda.Utils.Monad
import Agda.Utils.Null
import Agda.Utils.Singleton
import Agda.Utils.Size
import Agda.Utils.Tuple
import Agda.Utils.Impossible
| If matching is inconclusive ( ) we want to know whether
-- it is due to a particular meta variable.
data Match a = Yes Simplification (IntMap (Arg a))
| No
| DontKnow (Blocked ())
deriving Functor
instance Null (Match a) where
empty = Yes empty empty
null (Yes simpl as) = null simpl && null as
null _ = False
matchedArgs :: Empty -> Int -> IntMap (Arg a) -> [Arg a]
matchedArgs err n vs = map get [0..n-1]
where
get k = fromMaybe (absurd err) $ IntMap.lookup k vs
| Builds a proper substitution from an IntMap produced by match(Co)patterns
buildSubstitution :: (DeBruijn a)
=> Empty -> Int -> IntMap (Arg a) -> Substitution' a
buildSubstitution err n vs = parallelS $ map unArg $ matchedArgs err n vs
instance Semigroup (Match a) where
-- @NotBlocked (StuckOn e)@ means blocked by a variable.
-- In this case, no instantiation of meta-variables will make progress.
DontKnow b <> DontKnow b' = DontKnow $ b <> b'
DontKnow m <> _ = DontKnow m
_ <> DontKnow m = DontKnow m
-- One could imagine DontKnow _ <> No = No, but would break the
equivalence to case - trees ( Issue 2964 ) .
No <> _ = No
_ <> No = No
Yes s us <> Yes s' vs = Yes (s <> s') (us <> vs)
instance Monoid (Match a) where
mempty = empty
mappend = (<>)
-- | Instead of 'zipWithM', we need to use this lazy version
-- of combining pattern matching computations.
, 2014 - 05 - 08 , see Issue 1124 :
--
Due to a bug in TypeChecking . Patterns . Match
-- a failed match of (C n b) against (C O unit)
-- turned into (C n unit).
-- This was because all patterns were matched in
-- parallel, and evaluations of successfull matches
-- (and a record constructor like unit can always
-- be successfully matched) were returned, leading
-- to a reassembly of (C n b) as (C n unit) which is
-- illtyped.
-- Now patterns are matched left to right and
-- upon failure, no further matching is performed.
foldMatch
:: forall p v . IsProjP p => (p -> v -> ReduceM (Match Term, v))
-> [p] -> [v] -> ReduceM (Match Term, [v])
foldMatch match = loop where
loop :: [p] -> [v] -> ReduceM (Match Term, [v])
loop ps0 vs0 = do
case (ps0, vs0) of
([], []) -> return (empty, [])
(p : ps, v : vs) -> do
(r, v') <- match p v
case r of
No | Just{} <- isProjP p -> return (No, v' : vs)
No -> do
Issue 2964 : Even when the first pattern does n't match we should
-- continue to the next patterns (and potentially block on them)
-- because the splitting order in the case tree may not be
-- left-to-right.
(r', _vs') <- loop ps vs
Issue 2968 : do not use vs ' here , because it might
-- contain ill-typed terms due to eta-expansion at wrong
-- type.
return (r <> r', v' : vs)
DontKnow m -> return (DontKnow m, v' : vs)
Yes{} -> do
(r', vs') <- loop ps vs
return (r <> r', v' : vs')
_ -> __IMPOSSIBLE__
TODO refactor matchPattern * to work with Elim instead .
mergeElim :: Elim -> Arg Term -> Elim
mergeElim Apply{} arg = Apply arg
mergeElim (IApply x y _) arg = IApply x y (unArg arg)
mergeElim Proj{} _ = __IMPOSSIBLE__
mergeElims :: [Elim] -> [Arg Term] -> [Elim]
mergeElims = zipWith mergeElim
| @matchCopatterns ps es@ matches spine @es@ against copattern spine @ps@.
--
-- Returns 'Yes' and a substitution for the pattern variables
( in form of IntMap Term ) if matching was successful .
--
-- Returns 'No' if there was a constructor or projection mismatch.
--
-- Returns 'DontKnow' if an argument could not be evaluated to
-- constructor form because of a blocking meta variable.
--
In any case , also returns in reduced form
-- (with all the weak head reductions performed that were necessary
-- to come to a decision).
matchCopatterns :: [NamedArg DeBruijnPattern]
-> [Elim]
-> ReduceM (Match Term, [Elim])
matchCopatterns ps vs = do
traceSDoc "tc.match" 50
(vcat [ "matchCopatterns"
, nest 2 $ "ps =" <+> fsep (punctuate comma $ map (prettyTCM . namedArg) ps)
, nest 2 $ "vs =" <+> fsep (punctuate comma $ map prettyTCM vs)
]) $ do
Buggy , see issue 1124 :
. unzip < $ > zipWithM ' ( matchCopattern . namedArg ) ps vs
foldMatch (matchCopattern . namedArg) ps vs
-- | Match a single copattern.
matchCopattern :: DeBruijnPattern
-> Elim
-> ReduceM (Match Term, Elim)
matchCopattern pat@ProjP{} elim@(Proj _ q) = do
ProjP _ p <- normaliseProjP pat
q <- getOriginalProjection q
return $ if p == q then (Yes YesSimplification empty, elim)
else (No, elim)
The following two cases are not impossible , see # 2964
matchCopattern ProjP{} elim@Apply{} = return (No , elim)
matchCopattern _ elim@Proj{} = return (No , elim)
matchCopattern p (Apply v) = mapSnd Apply <$> matchPattern p v
matchCopattern p e@(IApply x y r) = mapSnd (mergeElim e) <$> matchPattern p (defaultArg r)
matchPatterns :: [NamedArg DeBruijnPattern]
-> [Arg Term]
-> ReduceM (Match Term, [Arg Term])
matchPatterns ps vs = do
reportSDoc "tc.match" 20 $
vcat [ "matchPatterns"
, nest 2 $ "ps =" <+> prettyTCMPatternList ps
, nest 2 $ "vs =" <+> fsep (punctuate comma $ map prettyTCM vs)
]
traceSDoc "tc.match" 50
(vcat [ "matchPatterns"
, nest 2 $ "ps =" <+> fsep (punctuate comma $ map (text . show) ps)
, nest 2 $ "vs =" <+> fsep (punctuate comma $ map prettyTCM vs)
]) $ do
Buggy , see issue 1124 :
-- (ms,vs) <- unzip <$> zipWithM' (matchPattern . namedArg) ps vs
return ( mconcat ms , vs )
foldMatch (matchPattern . namedArg) ps vs
-- | Match a single pattern.
matchPattern :: DeBruijnPattern
-> Arg Term
-> ReduceM (Match Term, Arg Term)
matchPattern p u = case (p, u) of
(ProjP{}, _ ) -> __IMPOSSIBLE__
(IApplyP _ _ _ x , arg ) -> return (Yes NoSimplification entry, arg)
where entry = singleton (dbPatVarIndex x, arg)
(VarP _ x , arg ) -> return (Yes NoSimplification entry, arg)
where entry = singleton (dbPatVarIndex x, arg)
(DotP _ _ , arg@(Arg _ v)) -> return (Yes NoSimplification empty, arg)
(LitP _ l , arg@(Arg _ v)) -> do
w <- reduceB' v
let arg' = arg $> ignoreBlocking w
case w of
NotBlocked _ (Lit l')
| l == l' -> return (Yes YesSimplification empty , arg')
| otherwise -> return (No , arg')
NotBlocked _ (MetaV x _) -> return (DontKnow $ Blocked x () , arg')
Blocked x _ -> return (DontKnow $ Blocked x () , arg')
NotBlocked r t -> return (DontKnow $ NotBlocked r' () , arg')
where r' = stuckOn (Apply arg') r
-- Case constructor pattern.
(ConP c cpi ps, Arg info v) -> do
if not (conPRecord cpi) then fallback c ps (Arg info v) else do
isEtaRecordCon (conName c) >>= \case
Nothing -> fallback c ps (Arg info v)
Just fs -> do
Case : Eta record constructor .
-- This case is necessary if we want to use the clauses before
record pattern translation ( e.g. , in type - checking definitions by copatterns ) .
unless (size fs == size ps) __IMPOSSIBLE__
mapSnd (Arg info . Con c (fromConPatternInfo cpi) . map Apply) <$> do
matchPatterns ps $ for fs $ \ (Arg ai f) -> Arg ai $ v `applyE` [Proj ProjSystem f]
where
isEtaRecordCon :: QName -> ReduceM (Maybe [Arg QName])
isEtaRecordCon c = do
(theDef <$> getConstInfo c) >>= \case
Constructor{ conData = d } -> do
(theDef <$> getConstInfo d) >>= \case
r@Record{ recFields = fs } | YesEta <- recEtaEquality r -> return $ Just $ map argFromDom fs
_ -> return Nothing
_ -> __IMPOSSIBLE__
(DefP o q ps, v) -> do
let f (Def q' vs) | q == q' = Just (Def q, vs)
f _ = Nothing
fallback' f ps v
where
-- Default: not an eta record constructor.
fallback c ps v = do
isMatchable <- isMatchable'
let f (Con c' ci' vs) | c == c' = Just (Con c' ci',vs)
f _ = Nothing
fallback' f ps v
-- Regardless of blocking, constructors and a properly applied @hcomp@
-- can be matched on.
isMatchable' = do
mhcomp <- getName' builtinHComp
return $ \ r ->
case ignoreBlocking r of
t@Con{} -> Just t
t@(Def q [l,a,phi,u,u0]) | Just q == mhcomp
-> Just t
_ -> Nothing
-- DefP hcomp and ConP matching.
fallback' mtc ps (Arg info v) = do
isMatchable <- isMatchable'
w <- reduceB' v
Unfold delayed ( corecursive ) definitions one step . This is
-- only necessary if c is a coinductive constructor, but
-- 1) it does not hurt to do it all the time, and
2 ) whatInduction c sometimes crashes because c may point to
-- an axiom at this stage (if we are checking the
-- projection functions for a record type).
w < - case w of
NotBlocked r ( Def f es ) - > -- , 2014 - 06 - 12 TODO : r = = ReallyNotBlocked sufficient ?
unfoldDefinitionE True reduceB ' ( Def f [ ] ) f es
-- reduceB is used here because some constructors
-- are actually definitions which need to be
-- unfolded ( due to open public ) .
_ - > return w
w <- case w of
NotBlocked r (Def f es) -> -- Andreas, 2014-06-12 TODO: r == ReallyNotBlocked sufficient?
unfoldDefinitionE True reduceB' (Def f []) f es
-- reduceB is used here because some constructors
-- are actually definitions which need to be
-- unfolded (due to open public).
_ -> return w
-}
Jesper , 23 - 06 - 2016 : Note that unfoldCorecursion may destroy
-- constructor forms, so we only call constructorForm after.
w <- traverse constructorForm =<< case w of
, 2014 - 06 - 12 TODO : r = = ReallyNotBlocked sufficient ?
_ -> return w
let v = ignoreBlocking w
arg = Arg info v -- the reduced argument
case w of
b | Just t <- isMatchable b ->
case mtc t of
Just (bld, vs) -> do
(m, vs1) <- yesSimplification <$> matchPatterns ps (fromMaybe __IMPOSSIBLE__ $ allApplyElims vs)
return (m, Arg info $ bld (mergeElims vs vs1))
Nothing
-> return (No , arg)
NotBlocked _ (MetaV x vs) -> return (DontKnow $ Blocked x () , arg)
Blocked x _ -> return (DontKnow $ Blocked x () , arg)
NotBlocked r _ -> return (DontKnow $ NotBlocked r' () , arg)
where r' = stuckOn (Apply arg) r
ASR ( 08 November 2014 ) . The type of the function could be
--
-- @(Match Term, [Arg Term]) -> (Match Term, [Arg Term])@.
yesSimplification :: (Match a, b) -> (Match a, b)
yesSimplification (Yes _ vs, us) = (Yes YesSimplification vs, us)
yesSimplification r = r
-- Matching patterns against patterns -------------------------------------
-- | Match a single pattern.
matchPatternP :: DeBruijnPattern
-> Arg DeBruijnPattern
-> ReduceM (Match DeBruijnPattern)
matchPatternP p (Arg info (DotP _ v)) = do
(m, arg) <- matchPattern p (Arg info v)
return $ fmap (DotP defaultPatternInfo) m
matchPatternP p arg@(Arg info q) = do
let varMatch x = return $ Yes NoSimplification $ singleton (dbPatVarIndex x, arg)
termMatch = do
(m, arg) <- matchPattern p (fmap patternToTerm arg)
return $ fmap (DotP defaultPatternInfo) m
case p of
ProjP{} -> __IMPOSSIBLE__
IApplyP _ _ _ x -> varMatch x
VarP _ x -> varMatch x
DotP _ _ -> return $ Yes NoSimplification empty
LitP{} -> termMatch -- Literal patterns bind no variables so we can fall back to the Term version.
DefP{} -> termMatch
ConP c cpi ps ->
case q of
ConP c' _ qs | c == c' -> matchPatternsP ps ((map . fmap) namedThing qs)
| otherwise -> return No
LitP{} -> fmap toLitP <$> termMatch
where toLitP (DotP _ (Lit l)) = litP l -- All bindings should be to literals
toLitP _ = __IMPOSSIBLE__
_ -> termMatch
matchPatternsP :: [NamedArg DeBruijnPattern]
-> [Arg DeBruijnPattern]
-> ReduceM (Match DeBruijnPattern)
matchPatternsP ps qs = do
mconcat <$> zipWithM matchPatternP (map namedArg ps) qs
| null | https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/Agda-2.6.1/src/full/Agda/TypeChecking/Patterns/Match.hs | haskell | | Pattern matcher used in the reducer for clauses that
have not been compiled to case trees yet.
it is due to a particular meta variable.
@NotBlocked (StuckOn e)@ means blocked by a variable.
In this case, no instantiation of meta-variables will make progress.
One could imagine DontKnow _ <> No = No, but would break the
| Instead of 'zipWithM', we need to use this lazy version
of combining pattern matching computations.
a failed match of (C n b) against (C O unit)
turned into (C n unit).
This was because all patterns were matched in
parallel, and evaluations of successfull matches
(and a record constructor like unit can always
be successfully matched) were returned, leading
to a reassembly of (C n b) as (C n unit) which is
illtyped.
Now patterns are matched left to right and
upon failure, no further matching is performed.
continue to the next patterns (and potentially block on them)
because the splitting order in the case tree may not be
left-to-right.
contain ill-typed terms due to eta-expansion at wrong
type.
Returns 'Yes' and a substitution for the pattern variables
Returns 'No' if there was a constructor or projection mismatch.
Returns 'DontKnow' if an argument could not be evaluated to
constructor form because of a blocking meta variable.
(with all the weak head reductions performed that were necessary
to come to a decision).
| Match a single copattern.
(ms,vs) <- unzip <$> zipWithM' (matchPattern . namedArg) ps vs
| Match a single pattern.
Case constructor pattern.
This case is necessary if we want to use the clauses before
Default: not an eta record constructor.
Regardless of blocking, constructors and a properly applied @hcomp@
can be matched on.
DefP hcomp and ConP matching.
only necessary if c is a coinductive constructor, but
1) it does not hurt to do it all the time, and
an axiom at this stage (if we are checking the
projection functions for a record type).
, 2014 - 06 - 12 TODO : r = = ReallyNotBlocked sufficient ?
reduceB is used here because some constructors
are actually definitions which need to be
unfolded ( due to open public ) .
Andreas, 2014-06-12 TODO: r == ReallyNotBlocked sufficient?
reduceB is used here because some constructors
are actually definitions which need to be
unfolded (due to open public).
constructor forms, so we only call constructorForm after.
the reduced argument
@(Match Term, [Arg Term]) -> (Match Term, [Arg Term])@.
Matching patterns against patterns -------------------------------------
| Match a single pattern.
Literal patterns bind no variables so we can fall back to the Term version.
All bindings should be to literals | # LANGUAGE NondecreasingIndentation #
module Agda.TypeChecking.Patterns.Match where
import Prelude hiding (null)
import Control.Monad
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Traversable (traverse)
import Agda.Syntax.Common
import Agda.Syntax.Internal
import Agda.Syntax.Internal.Pattern
import Agda.TypeChecking.Reduce
import Agda.TypeChecking.Reduce.Monad
import Agda.TypeChecking.Substitute
import Agda.TypeChecking.Monad hiding (constructorForm)
import Agda.TypeChecking.Pretty
import Agda.TypeChecking.Records
import Agda.Utils.Empty
import Agda.Utils.Functor (for, ($>))
import Agda.Utils.Maybe
import Agda.Utils.Monad
import Agda.Utils.Null
import Agda.Utils.Singleton
import Agda.Utils.Size
import Agda.Utils.Tuple
import Agda.Utils.Impossible
| If matching is inconclusive ( ) we want to know whether
data Match a = Yes Simplification (IntMap (Arg a))
| No
| DontKnow (Blocked ())
deriving Functor
instance Null (Match a) where
empty = Yes empty empty
null (Yes simpl as) = null simpl && null as
null _ = False
matchedArgs :: Empty -> Int -> IntMap (Arg a) -> [Arg a]
matchedArgs err n vs = map get [0..n-1]
where
get k = fromMaybe (absurd err) $ IntMap.lookup k vs
| Builds a proper substitution from an IntMap produced by match(Co)patterns
buildSubstitution :: (DeBruijn a)
=> Empty -> Int -> IntMap (Arg a) -> Substitution' a
buildSubstitution err n vs = parallelS $ map unArg $ matchedArgs err n vs
instance Semigroup (Match a) where
DontKnow b <> DontKnow b' = DontKnow $ b <> b'
DontKnow m <> _ = DontKnow m
_ <> DontKnow m = DontKnow m
equivalence to case - trees ( Issue 2964 ) .
No <> _ = No
_ <> No = No
Yes s us <> Yes s' vs = Yes (s <> s') (us <> vs)
instance Monoid (Match a) where
mempty = empty
mappend = (<>)
, 2014 - 05 - 08 , see Issue 1124 :
Due to a bug in TypeChecking . Patterns . Match
foldMatch
:: forall p v . IsProjP p => (p -> v -> ReduceM (Match Term, v))
-> [p] -> [v] -> ReduceM (Match Term, [v])
foldMatch match = loop where
loop :: [p] -> [v] -> ReduceM (Match Term, [v])
loop ps0 vs0 = do
case (ps0, vs0) of
([], []) -> return (empty, [])
(p : ps, v : vs) -> do
(r, v') <- match p v
case r of
No | Just{} <- isProjP p -> return (No, v' : vs)
No -> do
Issue 2964 : Even when the first pattern does n't match we should
(r', _vs') <- loop ps vs
Issue 2968 : do not use vs ' here , because it might
return (r <> r', v' : vs)
DontKnow m -> return (DontKnow m, v' : vs)
Yes{} -> do
(r', vs') <- loop ps vs
return (r <> r', v' : vs')
_ -> __IMPOSSIBLE__
TODO refactor matchPattern * to work with Elim instead .
mergeElim :: Elim -> Arg Term -> Elim
mergeElim Apply{} arg = Apply arg
mergeElim (IApply x y _) arg = IApply x y (unArg arg)
mergeElim Proj{} _ = __IMPOSSIBLE__
mergeElims :: [Elim] -> [Arg Term] -> [Elim]
mergeElims = zipWith mergeElim
| @matchCopatterns ps es@ matches spine @es@ against copattern spine @ps@.
( in form of IntMap Term ) if matching was successful .
In any case , also returns in reduced form
matchCopatterns :: [NamedArg DeBruijnPattern]
-> [Elim]
-> ReduceM (Match Term, [Elim])
matchCopatterns ps vs = do
traceSDoc "tc.match" 50
(vcat [ "matchCopatterns"
, nest 2 $ "ps =" <+> fsep (punctuate comma $ map (prettyTCM . namedArg) ps)
, nest 2 $ "vs =" <+> fsep (punctuate comma $ map prettyTCM vs)
]) $ do
Buggy , see issue 1124 :
. unzip < $ > zipWithM ' ( matchCopattern . namedArg ) ps vs
foldMatch (matchCopattern . namedArg) ps vs
matchCopattern :: DeBruijnPattern
-> Elim
-> ReduceM (Match Term, Elim)
matchCopattern pat@ProjP{} elim@(Proj _ q) = do
ProjP _ p <- normaliseProjP pat
q <- getOriginalProjection q
return $ if p == q then (Yes YesSimplification empty, elim)
else (No, elim)
The following two cases are not impossible , see # 2964
matchCopattern ProjP{} elim@Apply{} = return (No , elim)
matchCopattern _ elim@Proj{} = return (No , elim)
matchCopattern p (Apply v) = mapSnd Apply <$> matchPattern p v
matchCopattern p e@(IApply x y r) = mapSnd (mergeElim e) <$> matchPattern p (defaultArg r)
matchPatterns :: [NamedArg DeBruijnPattern]
-> [Arg Term]
-> ReduceM (Match Term, [Arg Term])
matchPatterns ps vs = do
reportSDoc "tc.match" 20 $
vcat [ "matchPatterns"
, nest 2 $ "ps =" <+> prettyTCMPatternList ps
, nest 2 $ "vs =" <+> fsep (punctuate comma $ map prettyTCM vs)
]
traceSDoc "tc.match" 50
(vcat [ "matchPatterns"
, nest 2 $ "ps =" <+> fsep (punctuate comma $ map (text . show) ps)
, nest 2 $ "vs =" <+> fsep (punctuate comma $ map prettyTCM vs)
]) $ do
Buggy , see issue 1124 :
return ( mconcat ms , vs )
foldMatch (matchPattern . namedArg) ps vs
matchPattern :: DeBruijnPattern
-> Arg Term
-> ReduceM (Match Term, Arg Term)
matchPattern p u = case (p, u) of
(ProjP{}, _ ) -> __IMPOSSIBLE__
(IApplyP _ _ _ x , arg ) -> return (Yes NoSimplification entry, arg)
where entry = singleton (dbPatVarIndex x, arg)
(VarP _ x , arg ) -> return (Yes NoSimplification entry, arg)
where entry = singleton (dbPatVarIndex x, arg)
(DotP _ _ , arg@(Arg _ v)) -> return (Yes NoSimplification empty, arg)
(LitP _ l , arg@(Arg _ v)) -> do
w <- reduceB' v
let arg' = arg $> ignoreBlocking w
case w of
NotBlocked _ (Lit l')
| l == l' -> return (Yes YesSimplification empty , arg')
| otherwise -> return (No , arg')
NotBlocked _ (MetaV x _) -> return (DontKnow $ Blocked x () , arg')
Blocked x _ -> return (DontKnow $ Blocked x () , arg')
NotBlocked r t -> return (DontKnow $ NotBlocked r' () , arg')
where r' = stuckOn (Apply arg') r
(ConP c cpi ps, Arg info v) -> do
if not (conPRecord cpi) then fallback c ps (Arg info v) else do
isEtaRecordCon (conName c) >>= \case
Nothing -> fallback c ps (Arg info v)
Just fs -> do
Case : Eta record constructor .
record pattern translation ( e.g. , in type - checking definitions by copatterns ) .
unless (size fs == size ps) __IMPOSSIBLE__
mapSnd (Arg info . Con c (fromConPatternInfo cpi) . map Apply) <$> do
matchPatterns ps $ for fs $ \ (Arg ai f) -> Arg ai $ v `applyE` [Proj ProjSystem f]
where
isEtaRecordCon :: QName -> ReduceM (Maybe [Arg QName])
isEtaRecordCon c = do
(theDef <$> getConstInfo c) >>= \case
Constructor{ conData = d } -> do
(theDef <$> getConstInfo d) >>= \case
r@Record{ recFields = fs } | YesEta <- recEtaEquality r -> return $ Just $ map argFromDom fs
_ -> return Nothing
_ -> __IMPOSSIBLE__
(DefP o q ps, v) -> do
let f (Def q' vs) | q == q' = Just (Def q, vs)
f _ = Nothing
fallback' f ps v
where
fallback c ps v = do
isMatchable <- isMatchable'
let f (Con c' ci' vs) | c == c' = Just (Con c' ci',vs)
f _ = Nothing
fallback' f ps v
isMatchable' = do
mhcomp <- getName' builtinHComp
return $ \ r ->
case ignoreBlocking r of
t@Con{} -> Just t
t@(Def q [l,a,phi,u,u0]) | Just q == mhcomp
-> Just t
_ -> Nothing
fallback' mtc ps (Arg info v) = do
isMatchable <- isMatchable'
w <- reduceB' v
Unfold delayed ( corecursive ) definitions one step . This is
2 ) whatInduction c sometimes crashes because c may point to
w < - case w of
unfoldDefinitionE True reduceB ' ( Def f [ ] ) f es
_ - > return w
w <- case w of
unfoldDefinitionE True reduceB' (Def f []) f es
_ -> return w
-}
Jesper , 23 - 06 - 2016 : Note that unfoldCorecursion may destroy
w <- traverse constructorForm =<< case w of
, 2014 - 06 - 12 TODO : r = = ReallyNotBlocked sufficient ?
_ -> return w
let v = ignoreBlocking w
case w of
b | Just t <- isMatchable b ->
case mtc t of
Just (bld, vs) -> do
(m, vs1) <- yesSimplification <$> matchPatterns ps (fromMaybe __IMPOSSIBLE__ $ allApplyElims vs)
return (m, Arg info $ bld (mergeElims vs vs1))
Nothing
-> return (No , arg)
NotBlocked _ (MetaV x vs) -> return (DontKnow $ Blocked x () , arg)
Blocked x _ -> return (DontKnow $ Blocked x () , arg)
NotBlocked r _ -> return (DontKnow $ NotBlocked r' () , arg)
where r' = stuckOn (Apply arg) r
ASR ( 08 November 2014 ) . The type of the function could be
yesSimplification :: (Match a, b) -> (Match a, b)
yesSimplification (Yes _ vs, us) = (Yes YesSimplification vs, us)
yesSimplification r = r
matchPatternP :: DeBruijnPattern
-> Arg DeBruijnPattern
-> ReduceM (Match DeBruijnPattern)
matchPatternP p (Arg info (DotP _ v)) = do
(m, arg) <- matchPattern p (Arg info v)
return $ fmap (DotP defaultPatternInfo) m
matchPatternP p arg@(Arg info q) = do
let varMatch x = return $ Yes NoSimplification $ singleton (dbPatVarIndex x, arg)
termMatch = do
(m, arg) <- matchPattern p (fmap patternToTerm arg)
return $ fmap (DotP defaultPatternInfo) m
case p of
ProjP{} -> __IMPOSSIBLE__
IApplyP _ _ _ x -> varMatch x
VarP _ x -> varMatch x
DotP _ _ -> return $ Yes NoSimplification empty
DefP{} -> termMatch
ConP c cpi ps ->
case q of
ConP c' _ qs | c == c' -> matchPatternsP ps ((map . fmap) namedThing qs)
| otherwise -> return No
LitP{} -> fmap toLitP <$> termMatch
toLitP _ = __IMPOSSIBLE__
_ -> termMatch
matchPatternsP :: [NamedArg DeBruijnPattern]
-> [Arg DeBruijnPattern]
-> ReduceM (Match DeBruijnPattern)
matchPatternsP ps qs = do
mconcat <$> zipWithM matchPatternP (map namedArg ps) qs
|
7298eafcca587e442ae1eb803cdf45f97e56ba4ee2c091298388d3841fe7f62a | sids/nerchuko | classify.clj | (ns nerchuko.examples.newsgroups.classify
(:use nerchuko.examples.newsgroups.helpers)
(:use [nerchuko helpers classification])
(:use [clojure.contrib command-line pprint]))
(defn -main [& args]
(with-command-line (if (seq args) args ["--help"])
"Classify a single file.
Prints the scores for each class in the model.
USAGE: test [options] <file-to-classify>"
[[model-file "File to load the learned model from." "/tmp/nerchuko.examples.newsgroups.model"]
file]
(if (seq file)
(let [model (read-string (slurp model-file))]
(->> (first file)
load-doc
(scores model)
pprint))
(println "Error: File arguments missing."))))
| null | https://raw.githubusercontent.com/sids/nerchuko/8aa56497dd8e93e868713dd542667a56215522fb/src/nerchuko/examples/newsgroups/classify.clj | clojure | (ns nerchuko.examples.newsgroups.classify
(:use nerchuko.examples.newsgroups.helpers)
(:use [nerchuko helpers classification])
(:use [clojure.contrib command-line pprint]))
(defn -main [& args]
(with-command-line (if (seq args) args ["--help"])
"Classify a single file.
Prints the scores for each class in the model.
USAGE: test [options] <file-to-classify>"
[[model-file "File to load the learned model from." "/tmp/nerchuko.examples.newsgroups.model"]
file]
(if (seq file)
(let [model (read-string (slurp model-file))]
(->> (first file)
load-doc
(scores model)
pprint))
(println "Error: File arguments missing."))))
| |
f5f96c24b6f7ef74edeab47019ac1e96c61b55dd6a089f6385c7a2ef2ef4fea4 | argp/bap | myocamlbuild.ml | open Ocamlbuild_plugin
no longer needed for OCaml > = 3.10.2
(**
Overview of tags:
- [pkg_batteries] to use Batteries as a library, without syntax extensions
- [use_batteries] and [use_batteries_r] to use both Batteries and all the non-destructive syntax extensions
- [pkg_sexplib.syntax] with [syntax_camlp4o] or [syntax_camlp4r] for sexplib
*)
(**
{1 OCamlFind}
*)
let run_and_read = Ocamlbuild_pack.My_unix.run_and_read
let blank_sep_strings = Ocamlbuild_pack.Lexers.blank_sep_strings
module OCamlFind =
struct
(* this lists all supported packages *)
let find_packages () =
blank_sep_strings &
Lexing.from_string &
run_and_read "ocamlfind list | cut -d' ' -f1"
(* this is supposed to list available syntaxes, but I don't know how to do it. *)
let find_syntaxes () = ["camlp4o"; "camlp4r"]
(* ocamlfind command *)
let ocamlfind x = S[A"ocamlfind"; x]
let before_options () =
(* by using Before_options one let command line options have an higher priority *)
(* on the contrary using After_options will guarantee to have the higher priority *)
(* override default commands by ocamlfind ones *)
Options.ocamlc := ocamlfind & A"ocamlc";
Options.ocamlopt := ocamlfind & A"ocamlopt";
Options.ocamldep := ocamlfind & A"ocamldep";
Options.ocamldoc := ocamlfind & A"ocamldoc";
Options.ocamlmktop := ocamlfind & A"ocamlmktop"
let get_ocamldoc_directory () =
let ocamldoc_directory = run_and_read "ocamlfind ocamldoc -customdir" in
let length = String.length ocamldoc_directory in
assert (length != 0);
let char = ocamldoc_directory.[length - 1] in
if (char = '\n') || (char = '\r') then String.sub ocamldoc_directory 0 (length - 1)
else ocamldoc_directory
let after_rules () =
When one link an OCaml library / binary / package , one should use -linkpkg
flag ["ocaml"; "byte"; "link"; "program"] & A"-linkpkg";
flag ["ocaml"; "native"; "link"; "program"] & A"-linkpkg";
flag ["ocaml"; "native"; "link"; "toplevel"] & A"-linkpkg";
For each ocamlfind package one inject the -package option when
* compiling , computing dependencies , generating documentation and
* linking .
* compiling, computing dependencies, generating documentation and
* linking. *)
List.iter begin fun pkg ->
flag ["ocaml"; "compile"; "pkg_"^pkg] & S[A"-package"; A pkg];
flag ["ocaml"; "ocamldep"; "pkg_"^pkg] & S[A"-package"; A pkg];
flag ["ocaml"; "doc"; "pkg_"^pkg] & S[A"-package"; A pkg];
flag ["ocaml"; "link"; "pkg_"^pkg] & S[A"-package"; A pkg];
end (find_packages ());
Like -package but for extensions syntax . -syntax is useless
* when linking .
* when linking. *)
List.iter begin fun syntax ->
flag ["ocaml"; "compile"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
flag ["ocaml"; "ocamldep"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
flag ["ocaml"; "doc"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
end (find_syntaxes ());
The default " thread " tag is not compatible with ocamlfind .
Indeed , the default rules add the " threads.cma " or " threads.cmxa "
options when using this tag . When using the " -linkpkg " option with
ocamlfind , this module will then be added twice on the command line .
To solve this , one approach is to add the " -thread " option when using
the " threads " package using the previous plugin .
Indeed, the default rules add the "threads.cma" or "threads.cmxa"
options when using this tag. When using the "-linkpkg" option with
ocamlfind, this module will then be added twice on the command line.
To solve this, one approach is to add the "-thread" option when using
the "threads" package using the previous plugin.
*)
flag ["ocaml"; "pkg_threads"; "compile"] (S[A "-thread"]);
flag ["ocaml"; "pkg_threads"; "link"] (S[A "-thread"]);
end
(**
{1 OCaml Batteries Included}
*)
module Batteries =
struct
let before_options () = ()
let after_rules () =
flag ["ocaml"; "link"; "byte"; "use_ocamldoc_info"] (S[A "-I"; A "+ocamldoc"; A "odoc_info.cma"]);
flag ["ocaml"; "link"; "native"; "use_ocamldoc_info"] (S[A "-I"; A "+ocamldoc"(*; A "odoc_info.cmxa"*)]);
flag ["ocaml"; "docfile"; "use_ocamldoc_info"] (S[A "-I"; A "+ocamldoc"]);
flag ["ocaml"; "docdir"; "use_ocamldoc_info"] (S[A "-I"; A "+ocamldoc"]);
flag ["ocaml"; "doc"; "use_ocamldoc_info"] (S[A "-I"; A "+ocamldoc"]);
(*The command-line for [use_batteries] and [use_batteries_r]*)
let cl_use_boilerplate = [A "-package"; A "batteries"]
and cl_use_batteries = [A "-package"; A "batteries"]
and cl_use_batteries_o = []
(*[cl_use_batteries_o]: extensions which only make sense in original syntax*)
and cl_camlp4o = [A"-syntax"; A "camlp4o"]
and cl_camlp4r = [A"-syntax"; A "camlp4r"] in
let cl_boilerplate_original = cl_use_boilerplate @ cl_camlp4o
and cl_boilerplate_revised = cl_use_boilerplate @ cl_camlp4r
and cl_batteries_original = cl_use_batteries @ cl_use_batteries_o @ cl_camlp4o
and cl_batteries_revised = cl_use_batteries @ cl_camlp4r in
(** Tag [use_boilerplate] provides boilerplate syntax extensions,
in original syntax*)
flag ["ocaml"; "compile"; "use_boilerplate"] & S cl_boilerplate_original ;
flag ["ocaml"; "ocamldep"; "use_boilerplate"] & S cl_boilerplate_original ;
flag ["ocaml"; "doc"; "use_boilerplate"] & S cl_boilerplate_original ;
flag ["ocaml"; "link"; "use_boilerplate"] & S cl_boilerplate_original ;
(** Tag [use_boilerplate_r] provides boilerplate syntax extensions,
in original syntax*)
flag ["ocaml"; "compile"; "use_boilerplate_r"] & S cl_boilerplate_revised ;
flag ["ocaml"; "ocamldep"; "use_boilerplate_r"] & S cl_boilerplate_revised ;
flag ["ocaml"; "doc"; "use_boilerplate_r"] & S cl_boilerplate_revised ;
flag ["ocaml"; "link"; "use_boilerplate_r"] & S cl_boilerplate_revised ;
(** Tag [use_batteries] provides both package [batteries]
and all syntax extensions, in original syntax. *)
flag ["ocaml"; "compile"; "use_batteries"] & S cl_batteries_original ;
flag ["ocaml"; "ocamldep"; "use_batteries"] & S cl_batteries_original ;
flag ["ocaml"; "doc"; "use_batteries"] & S cl_batteries_original ;
flag ["ocaml"; "link"; "use_batteries"] & S cl_batteries_original ;
(** Tag [use_batteries_r] provides both package [batteries]
and all syntax extensions, in revised syntax. *)
flag ["ocaml"; "compile"; "use_batteries_r"] & S cl_batteries_revised;
flag ["ocaml"; "ocamldep"; "use_batteries_r"] & S cl_batteries_revised;
flag ["ocaml"; "doc"; "use_batteries_r"] & S cl_batteries_revised;
flag ["ocaml"; "link"; "use_batteries_r"] & S cl_batteries_revised
flag [ " ocaml " ; " compile " ; " use_batteries " ] & S[A " -verbose " ;
A"-package " ; A " batteries.syntax.full " ;
A"-syntax " ; A " batteries.syntax.full " ] ;
flag [ " ocaml " ; " ocamldep " ; " use_batteries " ] & S[A " -verbose " ;
A"-package " ; A " batteries.syntax.full " ;
A"-syntax " ; A " batteries.syntax.full " ] ;
flag [ " ocaml " ; " doc " ; " use_batteries " ] & S[A " -verbose " ;
A"-package " ; A " batteries.syntax.full " ;
A"-syntax " ; A " batteries.syntax.full " ] ;
flag [ " ocaml " ; " link " ; " use_batteries " ] & S[A " -verbose " ;
A"-package " ; A " batteries.syntax.full " ;
A"-syntax " ; A " batteries.syntax.full " ] ;
A"-package"; A "batteries.syntax.full";
A"-syntax"; A "batteries.syntax.full"];
flag ["ocaml"; "ocamldep"; "use_batteries"] & S[A "-verbose";
A"-package"; A "batteries.syntax.full";
A"-syntax"; A "batteries.syntax.full"];
flag ["ocaml"; "doc"; "use_batteries"] & S[A "-verbose";
A"-package"; A "batteries.syntax.full";
A"-syntax"; A "batteries.syntax.full"];
flag ["ocaml"; "link"; "use_batteries"] & S[A "-verbose";
A"-package"; A "batteries.syntax.full";
A"-syntax"; A "batteries.syntax.full"];*)
end
let _ = dispatch begin function
| Before_options ->
OCamlFind.before_options ();
Batteries.before_options ()
| After_rules ->
OCamlFind.after_rules ();
Batteries.after_rules ()
| _ -> ()
end
*
which ocamlrun - > header
print_backtrace - > ajouter " -b " après le header
*
which ocamlrun -> header
print_backtrace -> ajouter "-b" après le header
**)
| null | https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/batteries/examples/benchmark/myocamlbuild.ml | ocaml | *
Overview of tags:
- [pkg_batteries] to use Batteries as a library, without syntax extensions
- [use_batteries] and [use_batteries_r] to use both Batteries and all the non-destructive syntax extensions
- [pkg_sexplib.syntax] with [syntax_camlp4o] or [syntax_camlp4r] for sexplib
*
{1 OCamlFind}
this lists all supported packages
this is supposed to list available syntaxes, but I don't know how to do it.
ocamlfind command
by using Before_options one let command line options have an higher priority
on the contrary using After_options will guarantee to have the higher priority
override default commands by ocamlfind ones
*
{1 OCaml Batteries Included}
; A "odoc_info.cmxa"
The command-line for [use_batteries] and [use_batteries_r]
[cl_use_batteries_o]: extensions which only make sense in original syntax
* Tag [use_boilerplate] provides boilerplate syntax extensions,
in original syntax
* Tag [use_boilerplate_r] provides boilerplate syntax extensions,
in original syntax
* Tag [use_batteries] provides both package [batteries]
and all syntax extensions, in original syntax.
* Tag [use_batteries_r] provides both package [batteries]
and all syntax extensions, in revised syntax. | open Ocamlbuild_plugin
no longer needed for OCaml > = 3.10.2
let run_and_read = Ocamlbuild_pack.My_unix.run_and_read
let blank_sep_strings = Ocamlbuild_pack.Lexers.blank_sep_strings
module OCamlFind =
struct
let find_packages () =
blank_sep_strings &
Lexing.from_string &
run_and_read "ocamlfind list | cut -d' ' -f1"
let find_syntaxes () = ["camlp4o"; "camlp4r"]
let ocamlfind x = S[A"ocamlfind"; x]
let before_options () =
Options.ocamlc := ocamlfind & A"ocamlc";
Options.ocamlopt := ocamlfind & A"ocamlopt";
Options.ocamldep := ocamlfind & A"ocamldep";
Options.ocamldoc := ocamlfind & A"ocamldoc";
Options.ocamlmktop := ocamlfind & A"ocamlmktop"
let get_ocamldoc_directory () =
let ocamldoc_directory = run_and_read "ocamlfind ocamldoc -customdir" in
let length = String.length ocamldoc_directory in
assert (length != 0);
let char = ocamldoc_directory.[length - 1] in
if (char = '\n') || (char = '\r') then String.sub ocamldoc_directory 0 (length - 1)
else ocamldoc_directory
let after_rules () =
When one link an OCaml library / binary / package , one should use -linkpkg
flag ["ocaml"; "byte"; "link"; "program"] & A"-linkpkg";
flag ["ocaml"; "native"; "link"; "program"] & A"-linkpkg";
flag ["ocaml"; "native"; "link"; "toplevel"] & A"-linkpkg";
For each ocamlfind package one inject the -package option when
* compiling , computing dependencies , generating documentation and
* linking .
* compiling, computing dependencies, generating documentation and
* linking. *)
List.iter begin fun pkg ->
flag ["ocaml"; "compile"; "pkg_"^pkg] & S[A"-package"; A pkg];
flag ["ocaml"; "ocamldep"; "pkg_"^pkg] & S[A"-package"; A pkg];
flag ["ocaml"; "doc"; "pkg_"^pkg] & S[A"-package"; A pkg];
flag ["ocaml"; "link"; "pkg_"^pkg] & S[A"-package"; A pkg];
end (find_packages ());
Like -package but for extensions syntax . -syntax is useless
* when linking .
* when linking. *)
List.iter begin fun syntax ->
flag ["ocaml"; "compile"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
flag ["ocaml"; "ocamldep"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
flag ["ocaml"; "doc"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
end (find_syntaxes ());
The default " thread " tag is not compatible with ocamlfind .
Indeed , the default rules add the " threads.cma " or " threads.cmxa "
options when using this tag . When using the " -linkpkg " option with
ocamlfind , this module will then be added twice on the command line .
To solve this , one approach is to add the " -thread " option when using
the " threads " package using the previous plugin .
Indeed, the default rules add the "threads.cma" or "threads.cmxa"
options when using this tag. When using the "-linkpkg" option with
ocamlfind, this module will then be added twice on the command line.
To solve this, one approach is to add the "-thread" option when using
the "threads" package using the previous plugin.
*)
flag ["ocaml"; "pkg_threads"; "compile"] (S[A "-thread"]);
flag ["ocaml"; "pkg_threads"; "link"] (S[A "-thread"]);
end
module Batteries =
struct
let before_options () = ()
let after_rules () =
flag ["ocaml"; "link"; "byte"; "use_ocamldoc_info"] (S[A "-I"; A "+ocamldoc"; A "odoc_info.cma"]);
flag ["ocaml"; "docfile"; "use_ocamldoc_info"] (S[A "-I"; A "+ocamldoc"]);
flag ["ocaml"; "docdir"; "use_ocamldoc_info"] (S[A "-I"; A "+ocamldoc"]);
flag ["ocaml"; "doc"; "use_ocamldoc_info"] (S[A "-I"; A "+ocamldoc"]);
let cl_use_boilerplate = [A "-package"; A "batteries"]
and cl_use_batteries = [A "-package"; A "batteries"]
and cl_use_batteries_o = []
and cl_camlp4o = [A"-syntax"; A "camlp4o"]
and cl_camlp4r = [A"-syntax"; A "camlp4r"] in
let cl_boilerplate_original = cl_use_boilerplate @ cl_camlp4o
and cl_boilerplate_revised = cl_use_boilerplate @ cl_camlp4r
and cl_batteries_original = cl_use_batteries @ cl_use_batteries_o @ cl_camlp4o
and cl_batteries_revised = cl_use_batteries @ cl_camlp4r in
flag ["ocaml"; "compile"; "use_boilerplate"] & S cl_boilerplate_original ;
flag ["ocaml"; "ocamldep"; "use_boilerplate"] & S cl_boilerplate_original ;
flag ["ocaml"; "doc"; "use_boilerplate"] & S cl_boilerplate_original ;
flag ["ocaml"; "link"; "use_boilerplate"] & S cl_boilerplate_original ;
flag ["ocaml"; "compile"; "use_boilerplate_r"] & S cl_boilerplate_revised ;
flag ["ocaml"; "ocamldep"; "use_boilerplate_r"] & S cl_boilerplate_revised ;
flag ["ocaml"; "doc"; "use_boilerplate_r"] & S cl_boilerplate_revised ;
flag ["ocaml"; "link"; "use_boilerplate_r"] & S cl_boilerplate_revised ;
flag ["ocaml"; "compile"; "use_batteries"] & S cl_batteries_original ;
flag ["ocaml"; "ocamldep"; "use_batteries"] & S cl_batteries_original ;
flag ["ocaml"; "doc"; "use_batteries"] & S cl_batteries_original ;
flag ["ocaml"; "link"; "use_batteries"] & S cl_batteries_original ;
flag ["ocaml"; "compile"; "use_batteries_r"] & S cl_batteries_revised;
flag ["ocaml"; "ocamldep"; "use_batteries_r"] & S cl_batteries_revised;
flag ["ocaml"; "doc"; "use_batteries_r"] & S cl_batteries_revised;
flag ["ocaml"; "link"; "use_batteries_r"] & S cl_batteries_revised
flag [ " ocaml " ; " compile " ; " use_batteries " ] & S[A " -verbose " ;
A"-package " ; A " batteries.syntax.full " ;
A"-syntax " ; A " batteries.syntax.full " ] ;
flag [ " ocaml " ; " ocamldep " ; " use_batteries " ] & S[A " -verbose " ;
A"-package " ; A " batteries.syntax.full " ;
A"-syntax " ; A " batteries.syntax.full " ] ;
flag [ " ocaml " ; " doc " ; " use_batteries " ] & S[A " -verbose " ;
A"-package " ; A " batteries.syntax.full " ;
A"-syntax " ; A " batteries.syntax.full " ] ;
flag [ " ocaml " ; " link " ; " use_batteries " ] & S[A " -verbose " ;
A"-package " ; A " batteries.syntax.full " ;
A"-syntax " ; A " batteries.syntax.full " ] ;
A"-package"; A "batteries.syntax.full";
A"-syntax"; A "batteries.syntax.full"];
flag ["ocaml"; "ocamldep"; "use_batteries"] & S[A "-verbose";
A"-package"; A "batteries.syntax.full";
A"-syntax"; A "batteries.syntax.full"];
flag ["ocaml"; "doc"; "use_batteries"] & S[A "-verbose";
A"-package"; A "batteries.syntax.full";
A"-syntax"; A "batteries.syntax.full"];
flag ["ocaml"; "link"; "use_batteries"] & S[A "-verbose";
A"-package"; A "batteries.syntax.full";
A"-syntax"; A "batteries.syntax.full"];*)
end
let _ = dispatch begin function
| Before_options ->
OCamlFind.before_options ();
Batteries.before_options ()
| After_rules ->
OCamlFind.after_rules ();
Batteries.after_rules ()
| _ -> ()
end
*
which ocamlrun - > header
print_backtrace - > ajouter " -b " après le header
*
which ocamlrun -> header
print_backtrace -> ajouter "-b" après le header
**)
|
7b056c68395ba583f078eb005104aa3ec1886d7f656c65f20cb13caef0d707bc | ocaml/ocaml | intext.ml | (* TEST
modules = "intextaux.c"
*)
(* Test for output_value / input_value *)
let max_data_depth = 500000
type t = A | B of int | C of float | D of string | E of char
| F of t | G of t * t | H of int * t | I of t * float | J
let longstring =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
let verylongstring =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
let bigint = Int64.to_int 0x123456789ABCDEF0L
let rec fib n =
if n < 2 then 1 else fib(n-1) + fib(n-2)
let test_out ?(flags = []) filename =
let oc = open_out_bin filename in
Marshal.to_channel oc 1 flags;
Marshal.to_channel oc (-1) flags;
Marshal.to_channel oc 258 flags;
Marshal.to_channel oc 20000 flags;
Marshal.to_channel oc 0x12345678 flags;
Marshal.to_channel oc bigint flags;
Marshal.to_channel oc "foobargeebuz" flags;
Marshal.to_channel oc longstring flags;
Marshal.to_channel oc verylongstring flags;
Marshal.to_channel oc 3.141592654 flags;
Marshal.to_channel oc () flags;
Marshal.to_channel oc A flags;
Marshal.to_channel oc (B 1) flags;
Marshal.to_channel oc (C 2.718) flags;
Marshal.to_channel oc (D "hello, world!") flags;
Marshal.to_channel oc (E 'l') flags;
Marshal.to_channel oc (F(B 1)) flags;
Marshal.to_channel oc (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) flags;
Marshal.to_channel oc (H(1, A)) flags;
Marshal.to_channel oc (I(B 2, 1e-6)) flags;
let x = D "sharing" in
let y = G(x, x) in
let z = G(y, G(x, y)) in
Marshal.to_channel oc z flags;
Marshal.to_channel oc [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|] flags;
let rec big n = if n <= 0 then A else H(n, big(n-1)) in
Marshal.to_channel oc (big 1000) flags;
Marshal.to_channel oc y (Marshal.No_sharing :: flags);
Marshal.to_channel oc fib (Marshal.Closures :: flags);
Marshal.to_channel oc (Int32.of_string "0") flags;
Marshal.to_channel oc (Int32.of_string "123456") flags;
Marshal.to_channel oc (Int32.of_string "-123456") flags;
Marshal.to_channel oc (Int64.of_string "0") flags;
Marshal.to_channel oc (Int64.of_string "123456789123456") flags;
Marshal.to_channel oc (Int64.of_string "-123456789123456") flags;
Marshal.to_channel oc (Nativeint.of_string "0") flags;
Marshal.to_channel oc (Nativeint.of_string "123456") flags;
Marshal.to_channel oc (Nativeint.of_string "-123456") flags;
Marshal.to_channel oc
(Nativeint.shift_left (Nativeint.of_string "123456789") 32) flags;
Marshal.to_channel oc
(Nativeint.shift_left (Nativeint.of_string "-123456789") 32) flags;
let i = Int64.of_string "123456789123456" in
Marshal.to_channel oc (i,i) flags;
close_out oc
let test n b =
print_string "Test "; print_int n;
if b then print_string " passed.\n" else print_string " FAILED.\n";
flush stderr
let test_in filename =
let ic = open_in_bin filename in
test 1 (input_value ic = 1);
test 2 (input_value ic = (-1));
test 3 (input_value ic = 258);
test 4 (input_value ic = 20000);
test 5 (input_value ic = 0x12345678);
test 6 (input_value ic = bigint);
test 7 (input_value ic = "foobargeebuz");
test 8 (input_value ic = longstring);
test 9 (input_value ic = verylongstring);
test 10 (input_value ic = 3.141592654);
test 11 (input_value ic = ());
test 12 (match input_value ic with
A -> true
| _ -> false);
test 13 (match input_value ic with
(B 1) -> true
| _ -> false);
test 14 (match input_value ic with
(C f) -> f = 2.718
| _ -> false);
test 15 (match input_value ic with
(D "hello, world!") -> true
| _ -> false);
test 16 (match input_value ic with
(E 'l') -> true
| _ -> false);
test 17 (match input_value ic with
(F(B 1)) -> true
| _ -> false);
test 18 (match input_value ic with
(G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) -> true
| _ -> false);
test 19 (match input_value ic with
(H(1, A)) -> true
| _ -> false);
test 20 (match input_value ic with
(I(B 2, 1e-6)) -> true
| _ -> false);
test 21 (match input_value ic with
G((G((D "sharing" as t1), t2) as t3), G(t4, t5)) ->
t1 == t2 && t3 == t5 && t4 == t1
| _ -> false);
test 22 (input_value ic = [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|]);
let rec check_big n t =
if n <= 0 then
test 23 (match t with A -> true | _ -> false)
else
match t with H(m, s) -> if m = n then check_big (n-1) s
else test 23 false
| _ -> test 23 false
in
check_big 1000 (input_value ic);
test 24 (match input_value ic with
G((D "sharing" as t1), (D "sharing" as t2)) -> t1 != t2
| _ -> false);
test 25 (let fib = (input_value ic : int -> int) in fib 5 = 8 && fib 10 = 89);
test 26 (input_value ic = Int32.of_string "0");
test 27 (input_value ic = Int32.of_string "123456");
test 28 (input_value ic = Int32.of_string "-123456");
test 29 (input_value ic = Int64.of_string "0");
test 30 (input_value ic = Int64.of_string "123456789123456");
test 31 (input_value ic = Int64.of_string "-123456789123456");
test 32 (input_value ic = Nativeint.of_string "0");
test 33 (input_value ic = Nativeint.of_string "123456");
test 34 (input_value ic = Nativeint.of_string "-123456");
test 35 (input_value ic =
Nativeint.shift_left (Nativeint.of_string "123456789") 32);
test 36 (input_value ic =
Nativeint.shift_left (Nativeint.of_string "-123456789") 32);
let ((i, j) : int64 * int64) = input_value ic in
test 37 (i = Int64.of_string "123456789123456");
test 38 (j = Int64.of_string "123456789123456");
test 39 (i == j);
close_in ic
let test_string () =
let s = Marshal.to_string 1 [] in
test 101 (Marshal.from_string s 0 = 1);
let s = Marshal.to_string (-1) [] in
test 102 (Marshal.from_string s 0 = (-1));
let s = Marshal.to_string 258 [] in
test 103 (Marshal.from_string s 0 = 258);
let s = Marshal.to_string 20000 [] in
test 104 (Marshal.from_string s 0 = 20000);
let s = Marshal.to_string 0x12345678 [] in
test 105 (Marshal.from_string s 0 = 0x12345678);
let s = Marshal.to_string bigint [] in
test 106 (Marshal.from_string s 0 = bigint);
let s = Marshal.to_string "foobargeebuz" [] in
test 107 (Marshal.from_string s 0 = "foobargeebuz");
let s = Marshal.to_string longstring [] in
test 108 (Marshal.from_string s 0 = longstring);
let s = Marshal.to_string verylongstring [] in
test 109 (Marshal.from_string s 0 = verylongstring);
let s = Marshal.to_string 3.141592654 [] in
test 110 (Marshal.from_string s 0 = 3.141592654);
let s = Marshal.to_string () [] in
test 111 (Marshal.from_string s 0 = ());
let s = Marshal.to_string A [] in
test 112 (match Marshal.from_string s 0 with
A -> true
| _ -> false);
let s = Marshal.to_string (B 1) [] in
test 113 (match Marshal.from_string s 0 with
(B 1) -> true
| _ -> false);
let s = Marshal.to_string (C 2.718) [] in
test 114 (match Marshal.from_string s 0 with
(C f) -> f = 2.718
| _ -> false);
let s = Marshal.to_string (D "hello, world!") [] in
test 115 (match Marshal.from_string s 0 with
(D "hello, world!") -> true
| _ -> false);
let s = Marshal.to_string (E 'l') [] in
test 116 (match Marshal.from_string s 0 with
(E 'l') -> true
| _ -> false);
let s = Marshal.to_string (F(B 1)) [] in
test 117 (match Marshal.from_string s 0 with
(F(B 1)) -> true
| _ -> false);
let s = Marshal.to_string (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) [] in
test 118 (match Marshal.from_string s 0 with
(G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) -> true
| _ -> false);
let s = Marshal.to_string (H(1, A)) [] in
test 119 (match Marshal.from_string s 0 with
(H(1, A)) -> true
| _ -> false);
let s = Marshal.to_string (I(B 2, 1e-6)) [] in
test 120 (match Marshal.from_string s 0 with
(I(B 2, 1e-6)) -> true
| _ -> false);
let x = D "sharing" in
let y = G(x, x) in
let z = G(y, G(x, y)) in
let s = Marshal.to_string z [] in
test 121 (match Marshal.from_string s 0 with
G((G((D "sharing" as t1), t2) as t3), G(t4, t5)) ->
t1 == t2 && t3 == t5 && t4 == t1
| _ -> false);
let s = Marshal.to_string [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|] [] in
test 122
(Marshal.from_string s 0 = [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|]);
let rec big n = if n <= 0 then A else H(n, big(n-1)) in
let s = Marshal.to_string (big 1000) [] in
let rec check_big n t =
if n <= 0 then
test 123 (match t with A -> true | _ -> false)
else
match t with H(m, s) -> if m = n then check_big (n-1) s
else test 123 false
| _ -> test 123 false
in
check_big 1000 (Marshal.from_string s 0)
let marshal_to_buffer s start len v flags =
ignore (Marshal.to_buffer s start len v flags)
let test_buffer () =
let s = Bytes.create 512 in
marshal_to_buffer s 0 512 1 [];
test 201 (Marshal.from_bytes s 0 = 1);
marshal_to_buffer s 0 512 (-1) [];
test 202 (Marshal.from_bytes s 0 = (-1));
marshal_to_buffer s 0 512 258 [];
test 203 (Marshal.from_bytes s 0 = 258);
marshal_to_buffer s 0 512 20000 [];
test 204 (Marshal.from_bytes s 0 = 20000);
marshal_to_buffer s 0 512 0x12345678 [];
test 205 (Marshal.from_bytes s 0 = 0x12345678);
marshal_to_buffer s 0 512 bigint [];
test 206 (Marshal.from_bytes s 0 = bigint);
marshal_to_buffer s 0 512 "foobargeebuz" [];
test 207 (Marshal.from_bytes s 0 = "foobargeebuz");
marshal_to_buffer s 0 512 longstring [];
test 208 (Marshal.from_bytes s 0 = longstring);
test 209
(try marshal_to_buffer s 0 512 verylongstring []; false
with Failure s when s = "Marshal.to_buffer: buffer overflow" -> true);
marshal_to_buffer s 0 512 3.141592654 [];
test 210 (Marshal.from_bytes s 0 = 3.141592654);
marshal_to_buffer s 0 512 () [];
test 211 (Marshal.from_bytes s 0 = ());
marshal_to_buffer s 0 512 A [];
test 212 (match Marshal.from_bytes s 0 with
A -> true
| _ -> false);
marshal_to_buffer s 0 512 (B 1) [];
test 213 (match Marshal.from_bytes s 0 with
(B 1) -> true
| _ -> false);
marshal_to_buffer s 0 512 (C 2.718) [];
test 214 (match Marshal.from_bytes s 0 with
(C f) -> f = 2.718
| _ -> false);
marshal_to_buffer s 0 512 (D "hello, world!") [];
test 215 (match Marshal.from_bytes s 0 with
(D "hello, world!") -> true
| _ -> false);
marshal_to_buffer s 0 512 (E 'l') [];
test 216 (match Marshal.from_bytes s 0 with
(E 'l') -> true
| _ -> false);
marshal_to_buffer s 0 512 (F(B 1)) [];
test 217 (match Marshal.from_bytes s 0 with
(F(B 1)) -> true
| _ -> false);
marshal_to_buffer s 0 512 (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) [];
test 218 (match Marshal.from_bytes s 0 with
(G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) -> true
| _ -> false);
marshal_to_buffer s 0 512 (H(1, A)) [];
test 219 (match Marshal.from_bytes s 0 with
(H(1, A)) -> true
| _ -> false);
marshal_to_buffer s 0 512 (I(B 2, 1e-6)) [];
test 220 (match Marshal.from_bytes s 0 with
(I(B 2, 1e-6)) -> true
| _ -> false);
let x = D "sharing" in
let y = G(x, x) in
let z = G(y, G(x, y)) in
marshal_to_buffer s 0 512 z [];
test 221 (match Marshal.from_bytes s 0 with
G((G((D "sharing" as t1), t2) as t3), G(t4, t5)) ->
t1 == t2 && t3 == t5 && t4 == t1
| _ -> false);
marshal_to_buffer s 0 512 [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|] [];
test 222
(Marshal.from_bytes s 0 = [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|]);
let rec big n = if n <= 0 then A else H(n, big(n-1)) in
test 223
(try marshal_to_buffer s 0 512 (big 1000) []; false
with Failure s when s = "Marshal.to_buffer: buffer overflow" -> true)
(* Test bounds checking and the [Marshal.data_size] primitive *)
let test_size() =
let test_one n flags =
let s =
Marshal.to_bytes (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) flags in
test n (Marshal.header_size + Marshal.data_size s 0 = Bytes.length s) in
test_one 300 [];
test_one 301 [Marshal.Compression]
let test_bounds_checking () =
let test_one n v flags =
let s = Marshal.to_string v flags in
assert (String.length s > 20);
test n
(try ignore (Marshal.from_string (String.sub s 0 10) 0); false
with Invalid_argument _ -> true);
test (n+1)
(try ignore (Marshal.from_string (String.sub s 0 20) 0); false
with Invalid_argument _ -> true);
test (n+2)
(Marshal.from_string (s ^ "silly padding") 0 = v) in
test_one 310 longstring [];
test_one 320 longstring [Marshal.Compression]
external marshal_to_block : int -> 'a -> Marshal.extern_flags list -> unit
= "marshal_to_block"
external marshal_from_block : int -> 'a = "marshal_from_block"
let test_block () =
marshal_to_block 512 1 [];
test 401 (marshal_from_block 512 = 1);
marshal_to_block 512 (-1) [];
test 402 (marshal_from_block 512 = (-1));
marshal_to_block 512 258 [];
test 403 (marshal_from_block 512 = 258);
marshal_to_block 512 20000 [];
test 404 (marshal_from_block 512 = 20000);
marshal_to_block 512 0x12345678 [];
test 405 (marshal_from_block 512 = 0x12345678);
marshal_to_block 512 bigint [];
test 406 (marshal_from_block 512 = bigint);
marshal_to_block 512 "foobargeebuz" [];
test 407 (marshal_from_block 512 = "foobargeebuz");
marshal_to_block 512 longstring [];
test 408 (marshal_from_block 512 = longstring);
test 409
(try marshal_to_block 512 verylongstring []; false
with Failure s when s = "Marshal.to_buffer: buffer overflow" -> true);
marshal_to_block 512 3.141592654 [];
test 410 (marshal_from_block 512 = 3.141592654);
marshal_to_block 512 () [];
test 411 (marshal_from_block 512 = ());
marshal_to_block 512 A [];
test 412 (match marshal_from_block 512 with
A -> true
| _ -> false);
marshal_to_block 512 (B 1) [];
test 413 (match marshal_from_block 512 with
(B 1) -> true
| _ -> false);
marshal_to_block 512 (C 2.718) [];
test 414 (match marshal_from_block 512 with
(C f) -> f = 2.718
| _ -> false);
marshal_to_block 512 (D "hello, world!") [];
test 415 (match marshal_from_block 512 with
(D "hello, world!") -> true
| _ -> false);
marshal_to_block 512 (E 'l') [];
test 416 (match marshal_from_block 512 with
(E 'l') -> true
| _ -> false);
marshal_to_block 512 (F(B 1)) [];
test 417 (match marshal_from_block 512 with
(F(B 1)) -> true
| _ -> false);
marshal_to_block 512 (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) [];
test 418 (match marshal_from_block 512 with
(G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) -> true
| _ -> false);
marshal_to_block 512 (H(1, A)) [];
test 419 (match marshal_from_block 512 with
(H(1, A)) -> true
| _ -> false);
marshal_to_block 512 (I(B 2, 1e-6)) [];
test 420 (match marshal_from_block 512 with
(I(B 2, 1e-6)) -> true
| _ -> false);
let x = D "sharing" in
let y = G(x, x) in
let z = G(y, G(x, y)) in
marshal_to_block 512 z [];
test 421 (match marshal_from_block 512 with
G((G((D "sharing" as t1), t2) as t3), G(t4, t5)) ->
t1 == t2 && t3 == t5 && t4 == t1
| _ -> false);
marshal_to_block 512 [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|] [];
test 422 (marshal_from_block 512 =
[|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|]);
let rec big n = if n <= 0 then A else H(n, big(n-1)) in
test 423
(try marshal_to_block 512 (big 1000) []; false
with Failure _ -> true);
test 424
(try marshal_to_block 512 "Hello, world!" [];
ignore (marshal_from_block 8);
false
with Failure _ -> true)
(* Test for really big objects *)
let counter = ref 0
let rec make_big n =
if n <= 0 then begin
incr counter; B !counter
end else begin
let l = make_big (n-1) in
let r = make_big (n-1) in
G(l, r)
end
let rec check_big n x =
if n <= 0 then begin
match x with
B k -> incr counter; k = !counter
| _ -> false
end else begin
match x with
G(l, r) -> check_big (n-1) l && check_big (n-1) r
| _ -> false
end
(* Test for really deep data structures *)
let test_deep () =
(* Right-leaning *)
let rec loop acc i =
if i < max_data_depth
then loop (i :: acc) (i+1)
else acc in
let x = loop [] 0 in
let s = Marshal.to_string x [] in
test 425 (Marshal.from_string s 0 = x);
(* Left-leaning *)
let rec loop acc i =
if i < max_data_depth
then loop (G(acc, B i)) (i+1)
else acc in
let x = loop A 0 in
let s = Marshal.to_string x [] in
test 426 (Marshal.from_string s 0 = x)
(* Test for objects *)
class foo = object (self : 'self)
val data1 = "foo"
val data2 = "bar"
val data3 = 42L
method test1 = data1 ^ data2
method test2 = false
method test3 = self#test1
method test4 = data3
end
class bar = object (self : 'self)
inherit foo as super
val! data2 = "test5"
val data4 = "test3"
val data5 = "test4"
method test1 =
data1
^ data2
^ data4
^ data5
^ Int64.to_string self#test4
end
class foobar = object (self : 'self)
inherit foo as super
inherit! bar
end
(* Test for objects *)
let test_objects () =
let x = new foo in
let s = Marshal.to_string x [Marshal.Closures] in
let x = Marshal.from_string s 0 in
test 500 (x#test1 = "foobar");
test 501 (x#test2 = false);
test 502 (x#test3 = "foobar");
test 503 (x#test4 = 42L);
let x = new bar in
let s = Marshal.to_string x [Marshal.Closures] in
let x = Marshal.from_string s 0 in
test 504 (x#test1 = "footest5test3test442");
test 505 (x#test2 = false);
test 506 (x#test3 = "footest5test3test442");
test 507 (x#test4 = 42L);
let x0 = new foobar in
let s = Marshal.to_string x0 [Marshal.Closures] in
let x = Marshal.from_string s 0 in
test 508 (x#test1 = "footest5test3test442");
test 509 (x#test2 = false);
test 510 (x#test3 = "footest5test3test442");
test 511 (x#test4 = 42L);
PR#5610
(* Test for infix pointers *)
let test_infix () =
let t = true and
f = false in
let rec odd n =
if n = 0
then f
else even (n-1)
and even n =
if n = 0
then t
else odd (n-1)
in
let s = Marshal.to_string (odd, even) [Marshal.Closures] in
let (odd', even': (int -> bool) * (int -> bool)) = Marshal.from_string s 0 in
test 600 (odd' 41 = true);
test 601 (odd' 41 = odd 41);
test 602 (odd' 142 = false);
test 603 (odd' 142 = odd 142);
test 604 (even' 41 = false);
test 605 (even' 41 = even 41);
test 606 (even' 142 = true);
test 607 (even' 142 = even 142)
let test_mutual_rec_regression () =
this regression was reported by in PR#5772
let rec test_one q x = x > 3
and test_list q = List.for_all (test_one q) q in
let g () = () in
let f q = if test_list q then g () in
test 700 (try ignore (Marshal.to_string f [Marshal.Closures]); true
with _ -> false)
let test_end_of_file_regression () =
See PR#7142
let write oc n =
for k = 0 to n - 1 do
Marshal.to_channel oc k []
done
in
let read ic n =
let k = ref 0 in
try
while true do
if Marshal.from_channel ic != !k then
failwith "unexpected integer";
incr k
done
with
| End_of_file when !k != n -> failwith "missing integer"
| End_of_file -> ()
in
test 800 (
try
let n = 100 in
let oc = open_out_bin "intext.data" in
write oc n;
close_out oc;
let ic = open_in_bin "intext.data" in
try
read ic n;
close_in ic;
true
with _ ->
close_in ic;
false
with _ -> false
)
external init_buggy_custom_ops : unit -> unit =
"init_buggy_custom_ops"
let () = init_buggy_custom_ops ()
type buggy
external value_with_buggy_serialiser : unit -> buggy =
"value_with_buggy_serialiser"
let test_buggy_serialisers () =
let x = value_with_buggy_serialiser () in
let s = Marshal.to_string x [] in
match Marshal.from_string s 0 with
| exception (Failure _) -> ()
| _ ->
failwith "Marshalling should not have succeeded with a bad serialiser!"
let main() =
if Array.length Sys.argv <= 2 then begin
print_string "Default flags\n";
test_out "intext.data"; test_in "intext.data";
print_string "Default flags (again)\n";
test_out "intext.data"; test_in "intext.data";
print_string "[Compression] flags\n";
test_out ~flags:[Marshal.Compression] "intext.data"; test_in "intext.data";
print_string "Marshal.to_string\n";
test_string();
print_string "Marshal.to_buffer\n";
test_buffer();
print_string "Marshal.{header_size,data_size}\n";
test_size();
test_bounds_checking();
print_string "Marshaling to a block\n";
test_block();
print_string "Miscellaneous tests\n";
test_deep();
test_objects();
test_infix ();
test_mutual_rec_regression ();
test_end_of_file_regression ();
test_buggy_serialisers ();
Sys.remove "intext.data";
end else
if Sys.argv.(1) = "make" then begin
let n = int_of_string Sys.argv.(2) in
let oc = open_out_bin "intext.data" in
counter := 0;
output_value oc (make_big n);
close_out oc
end else
if Sys.argv.(1) = "test" then begin
let n = int_of_string Sys.argv.(2) in
let ic = open_in_bin "intext.data" in
let b = (input_value ic : t) in
Gc.full_major();
close_in ic;
counter := 0;
if check_big n b then
Printf.printf "Test big %d passed" n
else
Printf.printf "Test big %d FAILED" n;
print_newline()
end
let _ = main (); exit 0
| null | https://raw.githubusercontent.com/ocaml/ocaml/fd6e6e0c9cf636f69cc90f4590834f77efaa5b95/testsuite/tests/lib-marshal/intext.ml | ocaml | TEST
modules = "intextaux.c"
Test for output_value / input_value
Test bounds checking and the [Marshal.data_size] primitive
Test for really big objects
Test for really deep data structures
Right-leaning
Left-leaning
Test for objects
Test for objects
Test for infix pointers |
let max_data_depth = 500000
type t = A | B of int | C of float | D of string | E of char
| F of t | G of t * t | H of int * t | I of t * float | J
let longstring =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
let verylongstring =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
let bigint = Int64.to_int 0x123456789ABCDEF0L
let rec fib n =
if n < 2 then 1 else fib(n-1) + fib(n-2)
let test_out ?(flags = []) filename =
let oc = open_out_bin filename in
Marshal.to_channel oc 1 flags;
Marshal.to_channel oc (-1) flags;
Marshal.to_channel oc 258 flags;
Marshal.to_channel oc 20000 flags;
Marshal.to_channel oc 0x12345678 flags;
Marshal.to_channel oc bigint flags;
Marshal.to_channel oc "foobargeebuz" flags;
Marshal.to_channel oc longstring flags;
Marshal.to_channel oc verylongstring flags;
Marshal.to_channel oc 3.141592654 flags;
Marshal.to_channel oc () flags;
Marshal.to_channel oc A flags;
Marshal.to_channel oc (B 1) flags;
Marshal.to_channel oc (C 2.718) flags;
Marshal.to_channel oc (D "hello, world!") flags;
Marshal.to_channel oc (E 'l') flags;
Marshal.to_channel oc (F(B 1)) flags;
Marshal.to_channel oc (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) flags;
Marshal.to_channel oc (H(1, A)) flags;
Marshal.to_channel oc (I(B 2, 1e-6)) flags;
let x = D "sharing" in
let y = G(x, x) in
let z = G(y, G(x, y)) in
Marshal.to_channel oc z flags;
Marshal.to_channel oc [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|] flags;
let rec big n = if n <= 0 then A else H(n, big(n-1)) in
Marshal.to_channel oc (big 1000) flags;
Marshal.to_channel oc y (Marshal.No_sharing :: flags);
Marshal.to_channel oc fib (Marshal.Closures :: flags);
Marshal.to_channel oc (Int32.of_string "0") flags;
Marshal.to_channel oc (Int32.of_string "123456") flags;
Marshal.to_channel oc (Int32.of_string "-123456") flags;
Marshal.to_channel oc (Int64.of_string "0") flags;
Marshal.to_channel oc (Int64.of_string "123456789123456") flags;
Marshal.to_channel oc (Int64.of_string "-123456789123456") flags;
Marshal.to_channel oc (Nativeint.of_string "0") flags;
Marshal.to_channel oc (Nativeint.of_string "123456") flags;
Marshal.to_channel oc (Nativeint.of_string "-123456") flags;
Marshal.to_channel oc
(Nativeint.shift_left (Nativeint.of_string "123456789") 32) flags;
Marshal.to_channel oc
(Nativeint.shift_left (Nativeint.of_string "-123456789") 32) flags;
let i = Int64.of_string "123456789123456" in
Marshal.to_channel oc (i,i) flags;
close_out oc
let test n b =
print_string "Test "; print_int n;
if b then print_string " passed.\n" else print_string " FAILED.\n";
flush stderr
let test_in filename =
let ic = open_in_bin filename in
test 1 (input_value ic = 1);
test 2 (input_value ic = (-1));
test 3 (input_value ic = 258);
test 4 (input_value ic = 20000);
test 5 (input_value ic = 0x12345678);
test 6 (input_value ic = bigint);
test 7 (input_value ic = "foobargeebuz");
test 8 (input_value ic = longstring);
test 9 (input_value ic = verylongstring);
test 10 (input_value ic = 3.141592654);
test 11 (input_value ic = ());
test 12 (match input_value ic with
A -> true
| _ -> false);
test 13 (match input_value ic with
(B 1) -> true
| _ -> false);
test 14 (match input_value ic with
(C f) -> f = 2.718
| _ -> false);
test 15 (match input_value ic with
(D "hello, world!") -> true
| _ -> false);
test 16 (match input_value ic with
(E 'l') -> true
| _ -> false);
test 17 (match input_value ic with
(F(B 1)) -> true
| _ -> false);
test 18 (match input_value ic with
(G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) -> true
| _ -> false);
test 19 (match input_value ic with
(H(1, A)) -> true
| _ -> false);
test 20 (match input_value ic with
(I(B 2, 1e-6)) -> true
| _ -> false);
test 21 (match input_value ic with
G((G((D "sharing" as t1), t2) as t3), G(t4, t5)) ->
t1 == t2 && t3 == t5 && t4 == t1
| _ -> false);
test 22 (input_value ic = [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|]);
let rec check_big n t =
if n <= 0 then
test 23 (match t with A -> true | _ -> false)
else
match t with H(m, s) -> if m = n then check_big (n-1) s
else test 23 false
| _ -> test 23 false
in
check_big 1000 (input_value ic);
test 24 (match input_value ic with
G((D "sharing" as t1), (D "sharing" as t2)) -> t1 != t2
| _ -> false);
test 25 (let fib = (input_value ic : int -> int) in fib 5 = 8 && fib 10 = 89);
test 26 (input_value ic = Int32.of_string "0");
test 27 (input_value ic = Int32.of_string "123456");
test 28 (input_value ic = Int32.of_string "-123456");
test 29 (input_value ic = Int64.of_string "0");
test 30 (input_value ic = Int64.of_string "123456789123456");
test 31 (input_value ic = Int64.of_string "-123456789123456");
test 32 (input_value ic = Nativeint.of_string "0");
test 33 (input_value ic = Nativeint.of_string "123456");
test 34 (input_value ic = Nativeint.of_string "-123456");
test 35 (input_value ic =
Nativeint.shift_left (Nativeint.of_string "123456789") 32);
test 36 (input_value ic =
Nativeint.shift_left (Nativeint.of_string "-123456789") 32);
let ((i, j) : int64 * int64) = input_value ic in
test 37 (i = Int64.of_string "123456789123456");
test 38 (j = Int64.of_string "123456789123456");
test 39 (i == j);
close_in ic
let test_string () =
let s = Marshal.to_string 1 [] in
test 101 (Marshal.from_string s 0 = 1);
let s = Marshal.to_string (-1) [] in
test 102 (Marshal.from_string s 0 = (-1));
let s = Marshal.to_string 258 [] in
test 103 (Marshal.from_string s 0 = 258);
let s = Marshal.to_string 20000 [] in
test 104 (Marshal.from_string s 0 = 20000);
let s = Marshal.to_string 0x12345678 [] in
test 105 (Marshal.from_string s 0 = 0x12345678);
let s = Marshal.to_string bigint [] in
test 106 (Marshal.from_string s 0 = bigint);
let s = Marshal.to_string "foobargeebuz" [] in
test 107 (Marshal.from_string s 0 = "foobargeebuz");
let s = Marshal.to_string longstring [] in
test 108 (Marshal.from_string s 0 = longstring);
let s = Marshal.to_string verylongstring [] in
test 109 (Marshal.from_string s 0 = verylongstring);
let s = Marshal.to_string 3.141592654 [] in
test 110 (Marshal.from_string s 0 = 3.141592654);
let s = Marshal.to_string () [] in
test 111 (Marshal.from_string s 0 = ());
let s = Marshal.to_string A [] in
test 112 (match Marshal.from_string s 0 with
A -> true
| _ -> false);
let s = Marshal.to_string (B 1) [] in
test 113 (match Marshal.from_string s 0 with
(B 1) -> true
| _ -> false);
let s = Marshal.to_string (C 2.718) [] in
test 114 (match Marshal.from_string s 0 with
(C f) -> f = 2.718
| _ -> false);
let s = Marshal.to_string (D "hello, world!") [] in
test 115 (match Marshal.from_string s 0 with
(D "hello, world!") -> true
| _ -> false);
let s = Marshal.to_string (E 'l') [] in
test 116 (match Marshal.from_string s 0 with
(E 'l') -> true
| _ -> false);
let s = Marshal.to_string (F(B 1)) [] in
test 117 (match Marshal.from_string s 0 with
(F(B 1)) -> true
| _ -> false);
let s = Marshal.to_string (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) [] in
test 118 (match Marshal.from_string s 0 with
(G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) -> true
| _ -> false);
let s = Marshal.to_string (H(1, A)) [] in
test 119 (match Marshal.from_string s 0 with
(H(1, A)) -> true
| _ -> false);
let s = Marshal.to_string (I(B 2, 1e-6)) [] in
test 120 (match Marshal.from_string s 0 with
(I(B 2, 1e-6)) -> true
| _ -> false);
let x = D "sharing" in
let y = G(x, x) in
let z = G(y, G(x, y)) in
let s = Marshal.to_string z [] in
test 121 (match Marshal.from_string s 0 with
G((G((D "sharing" as t1), t2) as t3), G(t4, t5)) ->
t1 == t2 && t3 == t5 && t4 == t1
| _ -> false);
let s = Marshal.to_string [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|] [] in
test 122
(Marshal.from_string s 0 = [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|]);
let rec big n = if n <= 0 then A else H(n, big(n-1)) in
let s = Marshal.to_string (big 1000) [] in
let rec check_big n t =
if n <= 0 then
test 123 (match t with A -> true | _ -> false)
else
match t with H(m, s) -> if m = n then check_big (n-1) s
else test 123 false
| _ -> test 123 false
in
check_big 1000 (Marshal.from_string s 0)
let marshal_to_buffer s start len v flags =
ignore (Marshal.to_buffer s start len v flags)
let test_buffer () =
let s = Bytes.create 512 in
marshal_to_buffer s 0 512 1 [];
test 201 (Marshal.from_bytes s 0 = 1);
marshal_to_buffer s 0 512 (-1) [];
test 202 (Marshal.from_bytes s 0 = (-1));
marshal_to_buffer s 0 512 258 [];
test 203 (Marshal.from_bytes s 0 = 258);
marshal_to_buffer s 0 512 20000 [];
test 204 (Marshal.from_bytes s 0 = 20000);
marshal_to_buffer s 0 512 0x12345678 [];
test 205 (Marshal.from_bytes s 0 = 0x12345678);
marshal_to_buffer s 0 512 bigint [];
test 206 (Marshal.from_bytes s 0 = bigint);
marshal_to_buffer s 0 512 "foobargeebuz" [];
test 207 (Marshal.from_bytes s 0 = "foobargeebuz");
marshal_to_buffer s 0 512 longstring [];
test 208 (Marshal.from_bytes s 0 = longstring);
test 209
(try marshal_to_buffer s 0 512 verylongstring []; false
with Failure s when s = "Marshal.to_buffer: buffer overflow" -> true);
marshal_to_buffer s 0 512 3.141592654 [];
test 210 (Marshal.from_bytes s 0 = 3.141592654);
marshal_to_buffer s 0 512 () [];
test 211 (Marshal.from_bytes s 0 = ());
marshal_to_buffer s 0 512 A [];
test 212 (match Marshal.from_bytes s 0 with
A -> true
| _ -> false);
marshal_to_buffer s 0 512 (B 1) [];
test 213 (match Marshal.from_bytes s 0 with
(B 1) -> true
| _ -> false);
marshal_to_buffer s 0 512 (C 2.718) [];
test 214 (match Marshal.from_bytes s 0 with
(C f) -> f = 2.718
| _ -> false);
marshal_to_buffer s 0 512 (D "hello, world!") [];
test 215 (match Marshal.from_bytes s 0 with
(D "hello, world!") -> true
| _ -> false);
marshal_to_buffer s 0 512 (E 'l') [];
test 216 (match Marshal.from_bytes s 0 with
(E 'l') -> true
| _ -> false);
marshal_to_buffer s 0 512 (F(B 1)) [];
test 217 (match Marshal.from_bytes s 0 with
(F(B 1)) -> true
| _ -> false);
marshal_to_buffer s 0 512 (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) [];
test 218 (match Marshal.from_bytes s 0 with
(G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) -> true
| _ -> false);
marshal_to_buffer s 0 512 (H(1, A)) [];
test 219 (match Marshal.from_bytes s 0 with
(H(1, A)) -> true
| _ -> false);
marshal_to_buffer s 0 512 (I(B 2, 1e-6)) [];
test 220 (match Marshal.from_bytes s 0 with
(I(B 2, 1e-6)) -> true
| _ -> false);
let x = D "sharing" in
let y = G(x, x) in
let z = G(y, G(x, y)) in
marshal_to_buffer s 0 512 z [];
test 221 (match Marshal.from_bytes s 0 with
G((G((D "sharing" as t1), t2) as t3), G(t4, t5)) ->
t1 == t2 && t3 == t5 && t4 == t1
| _ -> false);
marshal_to_buffer s 0 512 [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|] [];
test 222
(Marshal.from_bytes s 0 = [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|]);
let rec big n = if n <= 0 then A else H(n, big(n-1)) in
test 223
(try marshal_to_buffer s 0 512 (big 1000) []; false
with Failure s when s = "Marshal.to_buffer: buffer overflow" -> true)
let test_size() =
let test_one n flags =
let s =
Marshal.to_bytes (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) flags in
test n (Marshal.header_size + Marshal.data_size s 0 = Bytes.length s) in
test_one 300 [];
test_one 301 [Marshal.Compression]
let test_bounds_checking () =
let test_one n v flags =
let s = Marshal.to_string v flags in
assert (String.length s > 20);
test n
(try ignore (Marshal.from_string (String.sub s 0 10) 0); false
with Invalid_argument _ -> true);
test (n+1)
(try ignore (Marshal.from_string (String.sub s 0 20) 0); false
with Invalid_argument _ -> true);
test (n+2)
(Marshal.from_string (s ^ "silly padding") 0 = v) in
test_one 310 longstring [];
test_one 320 longstring [Marshal.Compression]
external marshal_to_block : int -> 'a -> Marshal.extern_flags list -> unit
= "marshal_to_block"
external marshal_from_block : int -> 'a = "marshal_from_block"
let test_block () =
marshal_to_block 512 1 [];
test 401 (marshal_from_block 512 = 1);
marshal_to_block 512 (-1) [];
test 402 (marshal_from_block 512 = (-1));
marshal_to_block 512 258 [];
test 403 (marshal_from_block 512 = 258);
marshal_to_block 512 20000 [];
test 404 (marshal_from_block 512 = 20000);
marshal_to_block 512 0x12345678 [];
test 405 (marshal_from_block 512 = 0x12345678);
marshal_to_block 512 bigint [];
test 406 (marshal_from_block 512 = bigint);
marshal_to_block 512 "foobargeebuz" [];
test 407 (marshal_from_block 512 = "foobargeebuz");
marshal_to_block 512 longstring [];
test 408 (marshal_from_block 512 = longstring);
test 409
(try marshal_to_block 512 verylongstring []; false
with Failure s when s = "Marshal.to_buffer: buffer overflow" -> true);
marshal_to_block 512 3.141592654 [];
test 410 (marshal_from_block 512 = 3.141592654);
marshal_to_block 512 () [];
test 411 (marshal_from_block 512 = ());
marshal_to_block 512 A [];
test 412 (match marshal_from_block 512 with
A -> true
| _ -> false);
marshal_to_block 512 (B 1) [];
test 413 (match marshal_from_block 512 with
(B 1) -> true
| _ -> false);
marshal_to_block 512 (C 2.718) [];
test 414 (match marshal_from_block 512 with
(C f) -> f = 2.718
| _ -> false);
marshal_to_block 512 (D "hello, world!") [];
test 415 (match marshal_from_block 512 with
(D "hello, world!") -> true
| _ -> false);
marshal_to_block 512 (E 'l') [];
test 416 (match marshal_from_block 512 with
(E 'l') -> true
| _ -> false);
marshal_to_block 512 (F(B 1)) [];
test 417 (match marshal_from_block 512 with
(F(B 1)) -> true
| _ -> false);
marshal_to_block 512 (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) [];
test 418 (match marshal_from_block 512 with
(G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) -> true
| _ -> false);
marshal_to_block 512 (H(1, A)) [];
test 419 (match marshal_from_block 512 with
(H(1, A)) -> true
| _ -> false);
marshal_to_block 512 (I(B 2, 1e-6)) [];
test 420 (match marshal_from_block 512 with
(I(B 2, 1e-6)) -> true
| _ -> false);
let x = D "sharing" in
let y = G(x, x) in
let z = G(y, G(x, y)) in
marshal_to_block 512 z [];
test 421 (match marshal_from_block 512 with
G((G((D "sharing" as t1), t2) as t3), G(t4, t5)) ->
t1 == t2 && t3 == t5 && t4 == t1
| _ -> false);
marshal_to_block 512 [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|] [];
test 422 (marshal_from_block 512 =
[|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|]);
let rec big n = if n <= 0 then A else H(n, big(n-1)) in
test 423
(try marshal_to_block 512 (big 1000) []; false
with Failure _ -> true);
test 424
(try marshal_to_block 512 "Hello, world!" [];
ignore (marshal_from_block 8);
false
with Failure _ -> true)
let counter = ref 0
let rec make_big n =
if n <= 0 then begin
incr counter; B !counter
end else begin
let l = make_big (n-1) in
let r = make_big (n-1) in
G(l, r)
end
let rec check_big n x =
if n <= 0 then begin
match x with
B k -> incr counter; k = !counter
| _ -> false
end else begin
match x with
G(l, r) -> check_big (n-1) l && check_big (n-1) r
| _ -> false
end
let test_deep () =
let rec loop acc i =
if i < max_data_depth
then loop (i :: acc) (i+1)
else acc in
let x = loop [] 0 in
let s = Marshal.to_string x [] in
test 425 (Marshal.from_string s 0 = x);
let rec loop acc i =
if i < max_data_depth
then loop (G(acc, B i)) (i+1)
else acc in
let x = loop A 0 in
let s = Marshal.to_string x [] in
test 426 (Marshal.from_string s 0 = x)
class foo = object (self : 'self)
val data1 = "foo"
val data2 = "bar"
val data3 = 42L
method test1 = data1 ^ data2
method test2 = false
method test3 = self#test1
method test4 = data3
end
class bar = object (self : 'self)
inherit foo as super
val! data2 = "test5"
val data4 = "test3"
val data5 = "test4"
method test1 =
data1
^ data2
^ data4
^ data5
^ Int64.to_string self#test4
end
class foobar = object (self : 'self)
inherit foo as super
inherit! bar
end
let test_objects () =
let x = new foo in
let s = Marshal.to_string x [Marshal.Closures] in
let x = Marshal.from_string s 0 in
test 500 (x#test1 = "foobar");
test 501 (x#test2 = false);
test 502 (x#test3 = "foobar");
test 503 (x#test4 = 42L);
let x = new bar in
let s = Marshal.to_string x [Marshal.Closures] in
let x = Marshal.from_string s 0 in
test 504 (x#test1 = "footest5test3test442");
test 505 (x#test2 = false);
test 506 (x#test3 = "footest5test3test442");
test 507 (x#test4 = 42L);
let x0 = new foobar in
let s = Marshal.to_string x0 [Marshal.Closures] in
let x = Marshal.from_string s 0 in
test 508 (x#test1 = "footest5test3test442");
test 509 (x#test2 = false);
test 510 (x#test3 = "footest5test3test442");
test 511 (x#test4 = 42L);
PR#5610
let test_infix () =
let t = true and
f = false in
let rec odd n =
if n = 0
then f
else even (n-1)
and even n =
if n = 0
then t
else odd (n-1)
in
let s = Marshal.to_string (odd, even) [Marshal.Closures] in
let (odd', even': (int -> bool) * (int -> bool)) = Marshal.from_string s 0 in
test 600 (odd' 41 = true);
test 601 (odd' 41 = odd 41);
test 602 (odd' 142 = false);
test 603 (odd' 142 = odd 142);
test 604 (even' 41 = false);
test 605 (even' 41 = even 41);
test 606 (even' 142 = true);
test 607 (even' 142 = even 142)
let test_mutual_rec_regression () =
this regression was reported by in PR#5772
let rec test_one q x = x > 3
and test_list q = List.for_all (test_one q) q in
let g () = () in
let f q = if test_list q then g () in
test 700 (try ignore (Marshal.to_string f [Marshal.Closures]); true
with _ -> false)
let test_end_of_file_regression () =
See PR#7142
let write oc n =
for k = 0 to n - 1 do
Marshal.to_channel oc k []
done
in
let read ic n =
let k = ref 0 in
try
while true do
if Marshal.from_channel ic != !k then
failwith "unexpected integer";
incr k
done
with
| End_of_file when !k != n -> failwith "missing integer"
| End_of_file -> ()
in
test 800 (
try
let n = 100 in
let oc = open_out_bin "intext.data" in
write oc n;
close_out oc;
let ic = open_in_bin "intext.data" in
try
read ic n;
close_in ic;
true
with _ ->
close_in ic;
false
with _ -> false
)
external init_buggy_custom_ops : unit -> unit =
"init_buggy_custom_ops"
let () = init_buggy_custom_ops ()
type buggy
external value_with_buggy_serialiser : unit -> buggy =
"value_with_buggy_serialiser"
let test_buggy_serialisers () =
let x = value_with_buggy_serialiser () in
let s = Marshal.to_string x [] in
match Marshal.from_string s 0 with
| exception (Failure _) -> ()
| _ ->
failwith "Marshalling should not have succeeded with a bad serialiser!"
let main() =
if Array.length Sys.argv <= 2 then begin
print_string "Default flags\n";
test_out "intext.data"; test_in "intext.data";
print_string "Default flags (again)\n";
test_out "intext.data"; test_in "intext.data";
print_string "[Compression] flags\n";
test_out ~flags:[Marshal.Compression] "intext.data"; test_in "intext.data";
print_string "Marshal.to_string\n";
test_string();
print_string "Marshal.to_buffer\n";
test_buffer();
print_string "Marshal.{header_size,data_size}\n";
test_size();
test_bounds_checking();
print_string "Marshaling to a block\n";
test_block();
print_string "Miscellaneous tests\n";
test_deep();
test_objects();
test_infix ();
test_mutual_rec_regression ();
test_end_of_file_regression ();
test_buggy_serialisers ();
Sys.remove "intext.data";
end else
if Sys.argv.(1) = "make" then begin
let n = int_of_string Sys.argv.(2) in
let oc = open_out_bin "intext.data" in
counter := 0;
output_value oc (make_big n);
close_out oc
end else
if Sys.argv.(1) = "test" then begin
let n = int_of_string Sys.argv.(2) in
let ic = open_in_bin "intext.data" in
let b = (input_value ic : t) in
Gc.full_major();
close_in ic;
counter := 0;
if check_big n b then
Printf.printf "Test big %d passed" n
else
Printf.printf "Test big %d FAILED" n;
print_newline()
end
let _ = main (); exit 0
|
6fb6cc1ef29e7ce4ba8fa8016c9953d94ee9b71f8b72aa9e2d509339a540d29a | clearwater-analytics/pdf-transforms | core.clj | (ns pdf-transforms.components.core
"Higher level namespace which contains the function for composing blocks on a page into components."
(:require [pdf-transforms.components.text :as txt]
[pdf-transforms.components.tables :as tbl]
[pdf-transforms.common :as cmn]))
(defn- blocks->components [page fncs blocks]
(->> fncs
(reduce (fn [{:keys [components raw-blocks] :as state} fnc]
(let [comps (fnc raw-blocks page)]
(assoc state :components (apply conj components comps)
:raw-blocks (reduce #(remove (partial cmn/within? %2) %1) raw-blocks comps))))
{:components [] :raw-blocks blocks})
((fn [{:keys [components raw-blocks]}]
(concat components (map txt/->text raw-blocks))))))
TODO Does this really need page and blocks as arguments or can it be rewritten to just use blocks ?
(defn ->components
"Converts a page and its blocks into "
[page blocks]
(->> blocks
(blocks->components (remove :horizontal-bar? page) [tbl/->standard-tables
txt/->labels-with-data])
cmn/sort-blocks)) | null | https://raw.githubusercontent.com/clearwater-analytics/pdf-transforms/8f15d9855d4c641bf49045bb3aa303beae06c7fd/src/pdf_transforms/components/core.clj | clojure | (ns pdf-transforms.components.core
"Higher level namespace which contains the function for composing blocks on a page into components."
(:require [pdf-transforms.components.text :as txt]
[pdf-transforms.components.tables :as tbl]
[pdf-transforms.common :as cmn]))
(defn- blocks->components [page fncs blocks]
(->> fncs
(reduce (fn [{:keys [components raw-blocks] :as state} fnc]
(let [comps (fnc raw-blocks page)]
(assoc state :components (apply conj components comps)
:raw-blocks (reduce #(remove (partial cmn/within? %2) %1) raw-blocks comps))))
{:components [] :raw-blocks blocks})
((fn [{:keys [components raw-blocks]}]
(concat components (map txt/->text raw-blocks))))))
TODO Does this really need page and blocks as arguments or can it be rewritten to just use blocks ?
(defn ->components
"Converts a page and its blocks into "
[page blocks]
(->> blocks
(blocks->components (remove :horizontal-bar? page) [tbl/->standard-tables
txt/->labels-with-data])
cmn/sort-blocks)) | |
7e865229694b9a935a85598f1c107d5ae19803a3e469e5d9093b042bb42163f5 | 2600hz/kazoo | edr_be_amqp.erl | %%%-----------------------------------------------------------------------------
( C ) 2017 , Conversant Ltd
@doc Relays EDR messages to via { @link } .
@author
%%%
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%%
%%% @end
%%%-----------------------------------------------------------------------------
-module(edr_be_amqp).
-behaviour(gen_edr_backend).
-include("../edr.hrl").
-export([start_link/1]).
-export([push/2
,init/1
,stop/2
,async_response_handler/1
]).
-record(state, {}).
-type state() :: #state{}.
-spec start_link(backend()) -> kz_types:startlink_ret().
start_link(Args) ->
gen_edr_backend:start_link(?MODULE, Args).
-spec init(backend())-> init_ret(state()).
init(#backend{})->
lager:info("starting edr_be_amqp"),
{'ok', #state{}};
init(_Other)->
'ignore'.
-spec push(state(), edr_event()) -> 'ok'.
push(_State, Event=#edr_event{})->
kapi_edr_amqp:publish_event(Event).
-spec stop(state(), any()) -> 'ok'.
stop(_State, _Reason)->
'ok'.
-spec async_response_handler(any()) -> work_result().
async_response_handler(_Response)->
'ok'.
| null | https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/applications/edr/src/backends/edr_be_amqp.erl | erlang | -----------------------------------------------------------------------------
@end
----------------------------------------------------------------------------- | ( C ) 2017 , Conversant Ltd
@doc Relays EDR messages to via { @link } .
@author
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
-module(edr_be_amqp).
-behaviour(gen_edr_backend).
-include("../edr.hrl").
-export([start_link/1]).
-export([push/2
,init/1
,stop/2
,async_response_handler/1
]).
-record(state, {}).
-type state() :: #state{}.
-spec start_link(backend()) -> kz_types:startlink_ret().
start_link(Args) ->
gen_edr_backend:start_link(?MODULE, Args).
-spec init(backend())-> init_ret(state()).
init(#backend{})->
lager:info("starting edr_be_amqp"),
{'ok', #state{}};
init(_Other)->
'ignore'.
-spec push(state(), edr_event()) -> 'ok'.
push(_State, Event=#edr_event{})->
kapi_edr_amqp:publish_event(Event).
-spec stop(state(), any()) -> 'ok'.
stop(_State, _Reason)->
'ok'.
-spec async_response_handler(any()) -> work_result().
async_response_handler(_Response)->
'ok'.
|
131c1920992fef0137b3025d57c638b4dd8f55e34bb24208e1191d7198aae692 | josephwilk/musical-creativity | gradus.clj | (ns musical-creativity.composers.gradus
(:require
[clojure.math.numeric-tower :as math]
[musical-creativity.events :as events]
[musical-creativity.util :refer :all]
[overtone.music.pitch :as music]))
(load-file "data/gradus.clj")
(def logging? true)
(def major-scale
(->> (music/scale-field :C :major)
(drop-last 46)
(take-last 36)))
(def default-seed-notes '(:E3 :D3 :B2 :A2 :G2 :C3))
(def default-cantus-firmus (map music/note [:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3]))
(def default-seed-note (music/note :C3))
(def default-illegal-verticals '(0 1 2 5 6 10 11 13 14 17 18 22 23 25 26 29 30 34 35 -1 -2 -3 -4 -5 -6 -7 -8))
(def default-illegal-parallel-motions '((7 7) (12 12) (19 19) (24 24)))
(def default-illegal-double-skips '((3 3) (3 4) (3 -3) (3 -4) (-3 -3) (-3 -4) (-3 3) (-3 4)
(4 3) (4 4) (4 -3) (4 -4) (-4 -3) (-4 -4) (-4 3) (-4 4)))
(def default-direct-fifths-and-octaves '((9 7) (8 7) (21 19) (20 19)))
(def illegal-verticals (atom []))
(def illegal-parallel-motions (atom []))
(def illegal-double-skips (atom []))
(def direct-fifths-and-octaves (atom []))
(def rules (atom []))
(def temporary-rules (atom []))
(def *seed-note* (atom default-seed-note))
(def *cantus-firmus* (atom default-cantus-firmus))
(def seed-notes (atom default-seed-notes))
(def new-line (atom []))
(def *auto-goals* (atom false))
(def *look-ahead* (atom false))
(def saved-templates (atom []))
(def last-cantus-firmus (atom []))
(def past-model-count (atom []))
(def models
(atom
'(((:C4 :B3 :D4 :C4 :B3 :A3 :G3 :A3) (:E3 :G3 :F3 :E3 :D3 :F3 :E3 :C3))
((:C4 :B3 :D4 :C4 :B3 :A3 :G3 :A3) (:A2 :G2 :F2 :A2 :G2 :F2 :G2 :F2))
((:C4 :B3 :D4 :C4 :B3 :A3 :G3 :A3) (:A2 :G2 :F2 :E2 :D2 :F2 :E2 :C2))
((:C4 :B3 :D4 :C4 :B3 :A3 :G3 :A3) (:E3 :G3 :F3 :E3 :G3 :F3 :E3 :C3))
((:A3 :B3 :C4 :A3 :B3 :C4 :D4 :F4 :E4 :D4 :C4) (:A2 :G2 :E2 :F2 :G2 :A2 :G2 :A2 :G2 :B2 :A2))
((:A3 :B3 :C4 :A3 :B3 :C4 :D4 :F4 :E4 :D4 :C4) (:A2 :G2 :E2 :F2 :G2 :A2 :G2 :F2 :G2 :F2 :E2))
((:A3 :B3 :C4 :A3 :B3 :C4 :D4 :F4 :E4 :D4 :C4) (:A2 :G2 :E2 :F2 :G2 :A2 :G2 :F2 :G2 :B2 :A2))
((:A3 :B3 :C4 :A3 :B3 :C4 :D4 :F4 :E4 :D4 :C4) (:A2 :G2 :E2 :F2 :G2 :A2 :G2 :A2 :C3 :B2 :C3))
((:A3 :B3 :C4 :A3 :B3 :C4 :D4 :F4 :E4 :D4 :C4) (:A2 :G2 :E2 :F2 :G2 :A2 :G2 :A2 :C3 :B2 :A2))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :D3 :C3 :E3 :D3 :C3 :D3 :E3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :D3 :F3 :E3 :F3 :E3 :G3 :F3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:A2 :B2 :C3 :E3 :D3 :C3 :D3 :E3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:A2 :G2 :F2 :G2 :F2 :E2 :D2 :C2))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :D3 :F3 :E3 :F3 :E3 :D3 :E3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :G3 :F3 :E3 :D3 :C3 :D3 :E3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:A2 :B2 :C3 :E3 :D3 :E3 :G3 :F3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:A2 :G2 :F2 :G2 :F2 :E2 :G2 :F2))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :D3 :F3 :E3 :D3 :C3 :D3 :C3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :D3 :C3 :E3 :D3 :E3 :G3 :F3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :G3 :F3 :E3 :D3 :E3 :G3 :F3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:A2 :G2 :F2 :G2 :F2 :E2 :D2 :E2))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :G3 :F3 :E3 :D3 :E3 :D3 :C3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :G3 :F3 :E3 :D3 :C3 :D3 :C3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :D3 :C3 :E3 :D3 :E3 :D3 :C3))
((:A3 :B3 :C4 :E4 :D4 :C4 :B3 :C4 :D4 :C4) (:A2 :G2 :A2 :G2 :F2 :A2 :G2 :A2 :G2 :A2))
((:A3 :B3 :C4 :E4 :D4 :C4 :B3 :C4 :D4 :C4) (:A2 :G2 :A2 :G2 :F2 :A2 :G2 :E2 :F2 :A2))
((:A3 :B3 :C4 :E4 :D4 :C4 :B3 :C4 :D4 :C4) (:A2 :G2 :A2 :G2 :F2 :A2 :G2 :F2 :D2 :E2))
((:A3 :B3 :C4 :E4 :D4 :C4 :B3 :C4 :D4 :C4) (:A2 :G2 :A2 :G2 :B2 :A2 :B2 :A2 :B2 :A2))
((:A3 :B3 :C4 :E4 :D4 :C4 :B3 :C4 :D4 :C4) (:A2 :G2 :A2 :G2 :B2 :A2 :B2 :A2 :G2 :E2))
((:A3 :B3 :C4 :E4 :D4 :C4 :B3 :C4 :D4 :C4) (:A2 :G2 :F2 :E2 :F2 :E2 :D2 :C2 :B1 :A1))
((:A3 :B3 :C4 :E4 :D4 :C4 :B3 :C4 :D4 :C4) (:A2 :G2 :A2 :G2 :F2 :E2 :G2 :F2 :D2 :E2))
((:A3 :B3 :A3 :C4 :B3 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :E2 :G2 :F2 :A2 :G2 :A2))
((:A3 :B3 :A3 :C4 :B3 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :E2 :G2 :F2 :A2 :G2 :F2))
((:A3 :B3 :A3 :C4 :B3 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :E2 :G2 :F2 :E2 :D2 :F2))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :G2 :F2 :A2 :G2 :A2 :B2 :C3))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :A2 :G2 :F2 :E2 :D2 :E2 :D2 :F2))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :G2 :F2 :A2 :G2 :A2 :B2 :D3))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :E2 :F2 :E2 :F2 :A2 :G2 :A2))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :G2 :B2 :A2 :G2 :A2 :B2 :D3))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :E2 :F2 :E2 :D2 :E2 :G2 :F2))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :A2 :G2 :F2 :E2 :D2 :E2 :G2 :F2))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :E2 :F2 :A2 :G2 :A2 :G2 :A2))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :G2 :F2 :A2 :G2 :A2 :G2 :F2))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :G2 :B2 :A2 :G2 :A2 :G2 :F2))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :A2 :G2 :B2 :A2 :B2 :C3 :D3 :F3))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :A2 :G2 :B2 :A2 :B2 :C3 :D3 :C3))
((:A3 :B3 :A3 :C4 :B3 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :E2 :G2 :F2 :E2 :G2 :F2))
((:A3 :B3 :C4 :E4 :D4 :C4 :B3 :C4 :D4 :C4) (:A2 :G2 :A2 :G2 :B2 :A2 :G2 :F2 :D2 :E2))
((:A3 :B3 :C4 :D4 :B3 :C4 :D4 :C4) (:A2 :G2 :A2 :F2 :G2 :F2 :D2 :E2))
((:A3 :B3 :C4 :A3 :B3 :C4 :D4 :F4 :E4 :D4 :C4) (:A2 :G2 :E2 :F2 :G2 :A2 :G2 :F2 :G2 :F2 :A2)))))
(defn set-default-goals!
"sets the default goals for the program."
[]
(reset! illegal-verticals default-illegal-verticals)
(reset! illegal-parallel-motions default-illegal-parallel-motions)
(reset! illegal-double-skips default-illegal-double-skips)
(reset! direct-fifths-and-octaves default-direct-fifths-and-octaves))
(defn very-second [list]
(first (second list)))
(defn second-to-last [list]
(last-first (butlast list)))
(defn third-to-last [list]
(nth (butlast list) (- (count list) 3)))
(defn opposite-sign? [numbers]
(if (or (and
(neg? (first numbers))
(pos? (second numbers)))
(and
(pos? (first numbers))
(neg? (second numbers))))
true))
(defn sort-by-first-element [lists]
(sort (fn [[x & _] [y & _]] (> x y)) lists))
(defn pair
[[list1 list2]]
(map vector list1 list2))
(defn swap-unless-includes [reference data]
(when-not (some #{data} @reference)
(swap! reference conj data)))
(defn translate-into-pitchnames [list-of-midi-note-numbers]
"used to translate midi note numbers into note names."
(map music/find-note-name list-of-midi-note-numbers))
(defn get-diatonic-note [current-note interval scale]
"a simple variant of choose-from-scale which uses a diatonic interval as its second arg."
(cond
(nil? interval)
[]
(pos? interval)
(nth (member current-note scale) interval)
:else
(nth (member current-note (reverse scale)) (math/abs interval))))
(defn translate-notes
"translates interval lists into note names for readability."
[first-note intervals]
(if (empty? intervals)
(translate-into-pitchnames (list first-note))
(let [test (get-diatonic-note first-note (first intervals) major-scale)]
(concat (translate-into-pitchnames (list first-note))
(translate-notes test (rest intervals))))))
(defn translate-rule-into-pitches
"translates rules into more readable pitch names."
[first-note rule]
(list (translate-notes first-note (second rule))
(translate-notes (get-diatonic-note first-note (first rule) major-scale) (third rule))))
(defn evaluate-pitch-names
"evaluates the pitch names of its arg into midi note numbers."
[voices]
(map (fn [voice] (map music/note voice)) voices))
(defn print-working
[cantus-firmus last-notes]
(let [notes (translate-into-pitchnames cantus-firmus)
last-notes (translate-into-pitchnames last-notes)]
(println "cantus firmus:" notes "notes:" last-notes)))
(defn print-backtracking
"simple printing function to show backtracking."
[seed-note rules]
(let [rules-as-notes (doall (map #(translate-rule-into-pitches seed-note %) rules))]
(println (str "backtracking.....there are now " (count rules) " rules."))
(println " rules: " rules-as-notes)))
(defn return-counts
"simply adds the count of occurances to the beginning of each member of its arg."
[templates]
(letfn [(occurences [template templates]
(count (filter #(= template %) templates)))]
(map (fn [template]
[(occurences template templates) template]) templates)))
(defn collect-all
"collects all of the occurances of each member of its arg."
[item templates]
(filter #(= item (second %)) templates))
(defn find-scale-intervals
"returns the diatonic intervals between the notes according to the scale."
[notes scale]
(cond
(empty? (rest notes))
[]
(nil? (second notes))
(cons nil (find-scale-intervals (rest notes) scale))
:else
(cons (let [first-note-test (member (first notes) scale)
second-note-test (member (second notes) scale)]
(if (< (first notes) (second notes))
(count
(drop-last (count second-note-test) first-note-test))
(-
(count
(drop-last (count first-note-test) second-note-test)))))
(find-scale-intervals (rest notes) scale))))
(defn get-tessitura
"gets the tessitura or highest/lowest interval of a note list."
[cantus-firmus scale]
(let [scale-intervals-max (find-scale-intervals (list (first cantus-firmus) (apply max cantus-firmus)) scale)
scale-intervals-min (find-scale-intervals (list (first cantus-firmus) (apply min cantus-firmus)) scale)
up (math/abs (first scale-intervals-max))
down (math/abs (first scale-intervals-min))]
(if (> up down)
up
(- down))))
(defn get-map-part-of-template
"returns the map part of the template."
[cantus-firmus scale]
(let [tessitura (get-tessitura cantus-firmus scale)
scale-intervals (find-scale-intervals (list (first cantus-firmus) (last-first cantus-firmus)) scale)]
[tessitura (first scale-intervals)]))
(defn select-new-seed-note
"select a logical new seed note."
[cantus-firmus scale saved-templates]
(let [map-template (get-map-part-of-template cantus-firmus scale)
templates (collect-all map-template saved-templates)
counts (return-counts templates)
sorted-counts (sort-by-first-element counts)
interval (first (second (first sorted-counts)))]
(when interval
(get-diatonic-note (first cantus-firmus) interval scale))))
(defn get-complement
"incrementally returns all of the intervals not in the verticals arg."
([verticals] (get-complement verticals 0))
([verticals number]
(cond
(empty? verticals)
[]
(member number verticals)
(get-complement (rest verticals) (inc number))
:else
(cons number (get-complement verticals (inc number))))))
(defn project-octaves [numbers]
(letfn [(octaves-out-from [number]
(if (> number 12)
(list (- number 12) number (+ number 12))
(list number (+ number 12)(+ number 24))))]
(mapcat octaves-out-from numbers)))
(defn make-voices
"makes lists of the cantus firmus and accompanying line pitches."
[models]
[(mapcat first models) (mapcat second models)])
(defn get-the-verticals
"collects the vertical intervals from the models used."
[models]
(sort < (distinct
(project-octaves
(let [voiced-music (pair (make-voices models))]
(map (fn [pair] (- (music/note (first pair)) (music/note (second pair)))) voiced-music))))))
(defn get-illegal-verticals
"returns all of the vertical intervals not in the models."
[models]
(get-complement (get-the-verticals models)))
(defn find-first-args-also-in-second-arg [find-list target-list]
(first
(filter
(fn [find] (when (member find target-list) find))
find-list)))
(defn remove-illegal-verticals
"removes the illegal verticals in its second arg."
[illegal-verticals all-verticals]
(remove #(find-first-args-also-in-second-arg illegal-verticals %) all-verticals))
(defn find-motions [extent value]
(map #(list extent %) (range value 0 -1)))
(defn find-all-possible-motions
"returns all possible motions to its extent arg."
([extend] (find-all-possible-motions extend extend))
([extent save-extent]
(mapcat #(find-motions % save-extent) (range extent 0 -1))))
(defn- motions [[model1 model2]]
(list (- (music/note (first model1)) (music/note (second model1)))
(- (music/note (first model2)) (music/note (second model2)))))
(defn find-the-legals
"discovers the legal motions in its arg."
[paired-model]
(let [partitioned-paired-models (partition 2 1 paired-model)]
(map motions partitioned-paired-models)))
(defn find-legals [models]
"collects the legal motions in its arg."
(mapcat #(find-the-legals (pair %)) models))
(defn remove-legal-motions
"removes the legal motions from the motions arg."
[legal-motions motions]
(remove #(some #{%} legal-motions) motions))
(defn find-illegal-parallels
"returns the non-used parallels in the models which are assumed to be illegal."
[models]
(let [illegal-verticals (get-illegal-verticals models)
legal-verticals (remove-illegal-verticals illegal-verticals (find-all-possible-motions 24))
model-verticals (find-legals models)]
(remove-legal-motions model-verticals legal-verticals)))
(defn combinations [object list]
(map (fn [item] [object item]) list))
(defn possible-combinations
"returns all possible combinations of its list arg."
([list] (possible-combinations list list))
([list save-list]
(mapcat #(combinations % save-list) list)))
(defn all-first-notes-conflict-rules? [choices rules]
"checking to see if all possible first notes produce rule-conflicting problems."
(every? #(member (list % nil nil) rules) choices))
(defn reduce-to-within-octave [interval]
"reduces diatonic intervals to within the octave."
(cond
(and (> (math/abs interval) 7)
(neg? interval))
(reduce-to-within-octave (+ interval 7))
(> (math/abs interval) 7)
(- interval 7)
(zero? interval)
-7
:else
interval))
(defn get-diatonic-interval [interval-class]
"translates interval-classes into diatonic-interval classes."
(case interval-class
1 1
2 1
3 2
4 2
-1 -1
-2 -1
-3 -2
-4 -2
:else
1))
(defn choose-from-scale
"gets the appropriate pitch from the current scale based on the interval class."
[current-note interval-class scale]
(if (pos? interval-class)
(nth (member current-note scale) (get-diatonic-interval interval-class))
(let [interval (math/abs (get-diatonic-interval interval-class))
notes (member current-note (reverse scale))]
(nth notes interval))))
(defn create-choices [scale last-choice]
"creates four possible choices - seconds and thirds - from a previous pitch choice."
[(choose-from-scale last-choice 1 scale)
(choose-from-scale last-choice 3 scale)
(choose-from-scale last-choice -1 scale)
(choose-from-scale last-choice -3 scale)])
(defn no-solution-exists?
"for stopping if no solution exists."
[seed-note cantus-firmus rules]
(all-first-notes-conflict-rules?
(map (fn [x]
(reduce-to-within-octave
(first (find-scale-intervals (list (first cantus-firmus) x)
major-scale))))
(create-choices major-scale seed-note)) rules))
(defn consult-rules [rule]
"calling (consult-rules (-9 (2 -1 -1) (-1 2 -2))) consult-rules returned nil"
(or (member rule @rules)
(member rule @temporary-rules)))
(defn create-interval-rule [rule]
"creates the interval rule as in (-7 (2 2 2)(-1 1 2))."
(list (first (find-scale-intervals (list (ffirst rule)
(first (second rule)))
major-scale))
(find-scale-intervals (first rule) major-scale)
(find-scale-intervals (second rule) major-scale)))
(defn create-rule [cantus-firmus new-notes]
"creates rules for the rules variable"
(let [the-list (take-last 4 new-notes)]
(create-interval-rule
(list (take-last (count the-list)
(drop-last (- (count cantus-firmus)(count new-notes)) cantus-firmus)) the-list))))
(defn skip? [notes]
"returns true if its two-number arg is a skip."
(if (> (math/abs (- (second notes) (first notes))) 2) true))
(defn get-verticals
"returns the intervals between two lines of counterpoint."
[cantus-firmus new-line]
(if (empty? cantus-firmus) []
(cons (- (first cantus-firmus)(first new-line))
(get-verticals (rest cantus-firmus)(rest new-line)))))
(defn get-intervals
"returns a list of intervals one short of its pitch-list arg."
[notes]
(let [partitioned-notes (partition 2 1 notes)]
(map (fn [[note1 note2]] (- note2 note1)) partitioned-notes)))
(defn vertical-dissonance?
"tests to ensure vertical dissonance"
[cantus-firmus-note choice]
(when (member (- cantus-firmus-note choice) @illegal-verticals)
choice))
(defn simultaneous-leaps? [cantus-firmus choice last-notes]
"tests for the presence of simultaneous leaps."
(let [cantus-firmus-to-here (take (inc (count last-notes)) cantus-firmus)]
(cond
(or (not (>= (count cantus-firmus-to-here) 2))
(not (>= (count last-notes) 1)))
nil
(and (skip? (take-last 2 cantus-firmus-to-here))
(skip? (take-last 2 (concat last-notes (list choice)))))
true
:else
nil)))
(defn parallel-octaves-and-fifths?
"tests for parallel octaves and fifths."
[cantus-firmus choice last-notes]
(let [next-position (inc (count last-notes))
cantus-firmus-to-here (take next-position cantus-firmus)]
(cond
(or (not (>= (count cantus-firmus-to-here) 2))
(not (>= (count last-notes) 1)))
nil
(member (list (math/abs (- (second-to-last cantus-firmus-to-here)
(last-first last-notes)))
(math/abs (- (last-first cantus-firmus-to-here) choice)))
@illegal-parallel-motions)
true
:else
nil)))
(defn leaps?
"tests for leaps and avoids two in row and ensures that leaps are followed by contrary motion steps."
[extended-last-notes]
(cond
(not (>= (count extended-last-notes) 3))
nil
(member (list (- (second-to-last extended-last-notes)
(last-first extended-last-notes))
(- (third-to-last extended-last-notes)
(second-to-last extended-last-notes)))
@illegal-double-skips)
true
(and (> (math/abs (- (third-to-last extended-last-notes)
(second-to-last extended-last-notes)))
2)
(not (opposite-sign? (list (- (second-to-last extended-last-notes)(last-first extended-last-notes))
(- (third-to-last extended-last-notes)(second-to-last extended-last-notes))))))
true
:else
nil))
(defn direct-fifths?
"tests for direct fifths between the two lines."
[cantus-firmus choice last-notes]
(let [cantus-firmus-to-here (take (inc (count last-notes)) cantus-firmus)]
(cond
(or (not (>= (count cantus-firmus-to-here) 2))
(not (>= (count last-notes) 1)))
nil
(member (get-verticals (take-last 2 cantus-firmus-to-here)
(take-last 2 (concat last-notes (list choice))))
@direct-fifths-and-octaves)
true
:else
nil)))
(defn consecutive-motions?
"tests to see if there are more than two consecutive save-direction motions."
[cantus-firmus choice last-notes]
(let [cantus-firmus-to-here (take (inc (count last-notes)) cantus-firmus)]
(cond
(or (not (> (count cantus-firmus-to-here) 3))
(not (> (count last-notes) 2)))
nil
(let [last-four-cf (take-last 4 cantus-firmus-to-here)
last-four-newline (take-last 4 (concat last-notes (list choice)))]
(not (or (opposite-sign? (list (first (get-intervals (take 2 last-four-cf)))
(first (get-intervals (take 2 last-four-newline)))))
(opposite-sign? (list (first (get-intervals (take 2 (rest last-four-cf))))
(first (get-intervals (take 2 (rest last-four-newline))))))
(opposite-sign? (list (first (get-intervals (take-last 2 last-four-cf)))
(first (get-intervals (take-last 2 last-four-newline))))))))
true
:else
nil)))
(defn choice-fits-goals-and-current-rules? [choice cantus-firmus last-notes]
(let [current-rule (create-rule cantus-firmus (concat last-notes (list choice)))
next-position (inc (count last-notes))
current-cantus-firmus (take next-position cantus-firmus)]
(and (not (consult-rules current-rule))
(not (vertical-dissonance? (nth cantus-firmus (count last-notes)) choice))
(not (parallel-octaves-and-fifths? current-cantus-firmus choice last-notes))
(not (leaps? (concat last-notes (list choice))))
(not (simultaneous-leaps? current-cantus-firmus choice last-notes))
(not (direct-fifths? current-cantus-firmus choice last-notes))
(not (consecutive-motions? current-cantus-firmus choice last-notes)))))
(defn evaluate
"evaluates the various choices for a next note based on the goals and current rules"
[cantus-firmus choices last-notes]
(filter #(choice-fits-goals-and-current-rules? % cantus-firmus last-notes) choices))
(defn match-rule [rule-for-matching rule]
"matches the freer rule to the rule from rules."
(cond
(and (nil? (first (rest rule-for-matching)))(nil? (first (rest rule))))
true
(or (and (= (ffirst (rest rule-for-matching))(ffirst (rest rule)))
(= (very-second (rest rule-for-matching))(very-second (rest rule))))
(and (= (ffirst (rest rule-for-matching))(ffirst (rest rule)))
(nil? (very-second (rest rule-for-matching)))))
(match-rule (cons (first rule-for-matching)(map rest (rest rule-for-matching)))
(cons (first rule)(map rest (rest rule))))
:else
nil))
(defn match-interval-rule [rule-for-matching rule]
"matches the freer rule to the rule from rules."
(cond
(and (empty? (first rule-for-matching))
(empty? (first rule)))
true
(or (and (= (ffirst rule-for-matching) (ffirst rule))
(= (very-second rule-for-matching) (very-second rule)))
(and (= (ffirst rule-for-matching) (ffirst rule))
(nil? (very-second rule-for-matching))))
(match-interval-rule (map rest rule-for-matching) (map rest rule))
:else
nil))
(defn match-rules-freely [rule rules]
"runs the match-rule function through the rules."
(cond
(empty? rules)
nil
(and (= (first rule)
(ffirst rules))
(match-interval-rule (rest rule) (rest (first rules))))
true
(and (= (first rule)
(ffirst rules))
(= (count (second rule))
(count (second (first rules))))
(match-rule rule (first rules)))
true
:else
(match-rules-freely rule (rest rules))))
(defn reduce-rule [rule]
"reduces the front-end of the look-ahead rule."
(if (<= (count (second rule)) 3)
rule
(let [amount (- (count (second rule)) 3)]
(cons (+ (first rule)
(- (first (second rule)))
(first (third rule)))
(map rest (rest rule))))))
(defn make-freer-rule [amount cf-notes rule]
"adds the appropriate number of nils to the new line for look-ahead matching."
(if (zero? amount) rule
(make-freer-rule (dec amount)
(rest cf-notes)
(list (first rule)
(concat (second rule)(list (first cf-notes)))
(concat (third rule)(list nil))))))
(defn create-relevant-cf-notes [last-notes cantus-firmus]
"creates the set of forward reaching cf notes."
(take 2 (drop (dec (count last-notes)) cantus-firmus)))
(defn look-ahead [amount cantus-firmus last-notes rule rules]
"the top-level function for looking ahead."
(let [cf-notes (create-relevant-cf-notes last-notes cantus-firmus)
scale-intervals (find-scale-intervals cf-notes major-scale)
freer-rule (make-freer-rule amount scale-intervals rule)]
(match-rules-freely (reduce-rule freer-rule) rules)))
(defn- look-ahead-filter-fn [cantus-firmus last-notes]
(fn [choice]
(let [new-choice (list choice)
new-last-notes (concat last-notes new-choice)
new-rule (create-rule cantus-firmus new-last-notes)]
(not (look-ahead 1 cantus-firmus new-last-notes new-rule @rules)))))
(defn look-ahead-for-best-choice [cantus-firmus last-notes correct-choices]
"looks ahead for the best choice"
(first
(filter (look-ahead-filter-fn cantus-firmus last-notes) correct-choices)))
(defn evaluate-choices
"runs the evaluate and look-ahead functions through the various choices."
[cantus-firmus choices last-notes]
(let [correct-choices (evaluate cantus-firmus choices last-notes)]
(if correct-choices
(reset! *look-ahead* true)
(reset! *look-ahead* false))
(if (pos? (count correct-choices))
(look-ahead-for-best-choice cantus-firmus last-notes correct-choices)
(first correct-choices))))
(defn get-new-starting-point
"for backtracking - starts 2 earlier or nil"
[last-notes]
(cond
(<= (count last-notes) 1)
[]
:else
(drop-last 1 last-notes)))
(declare create-new-line)
(defn- create-line-from-choices [cantus-firmus scale choices last-notes length]
(let [new-rule (create-rule cantus-firmus (concat last-notes (list (first choices))))]
(if @*look-ahead*
(swap-unless-includes rules new-rule)
(swap-unless-includes temporary-rules new-rule)))
(print-backtracking @*seed-note* @rules)
(let [new-last-notes (get-new-starting-point last-notes)
seed-note (if (empty? new-last-notes) @*seed-note* (last-first new-last-notes))
choices (shuffle (create-choices major-scale seed-note))
new-choices (remove #(= % (last-first last-notes)) choices)
line (drop-last (- (count last-notes) (count new-last-notes)) @new-line)
new-length (+ length (- (count last-notes) (count new-last-notes)))]
(reset! new-line line)
(create-new-line cantus-firmus scale new-choices new-last-notes new-length)))
(defn- create-line-from-new-choices [test cantus-firmus scale last-notes length]
(reset! new-line (concat @new-line (list test)))
(when logging?
(print-working cantus-firmus @new-line))
(let [new-choices (shuffle (create-choices major-scale test))
new-length (dec length)
new-last-notes (concat last-notes (list test))]
(create-new-line cantus-firmus scale new-choices new-last-notes new-length)))
(defn create-new-line
"creates a new line with the cantus firmus."
([cantus-firmus scale choices last-notes] (create-new-line cantus-firmus scale choices last-notes (count cantus-firmus)))
([cantus-firmus scale choices last-notes length]
(if (no-solution-exists? @*seed-note* @*cantus-firmus* @rules)
(println "i can find no solution for this cantus firmus.")
(if (<= length 0)
@new-line
(let [new-note-choices (evaluate-choices cantus-firmus choices last-notes)]
(if new-note-choices
(create-line-from-new-choices new-note-choices cantus-firmus scale last-notes length)
(create-line-from-choices cantus-firmus scale choices last-notes length)))))))
(defn analyze-for-template [seed-note cantus-firmus scale]
"returns the complete template (seed interval and map) for saving."
(let [cantus-firmus-note (first cantus-firmus)
cantus-firmus-note-and-seed (list cantus-firmus-note seed-note)
scale-intervals (find-scale-intervals cantus-firmus-note-and-seed scale)]
(list (first scale-intervals) (get-map-part-of-template cantus-firmus scale))))
(defn set-goals!
"sets the goals for the gradus program."
[models]
(reset! illegal-verticals (get-illegal-verticals models))
(reset! illegal-parallel-motions (find-illegal-parallels models))
(reset! direct-fifths-and-octaves (find-illegal-parallels models))
(reset! illegal-double-skips (possible-combinations '(3 4 -3 -4))))
(defn replenish-seed-notes! []
"replenishes the seednotes when when they have all been used."
(reset! seed-notes (map music/note '(:C3 :F3 :E3 :D3 :B2 :A2 :G2 :F2))))
(defn models-changed? []
(not= (count @models) @past-model-count))
(defn cantus-firmus-changed? [cantus-firmus]
(not= last-cantus-firmus cantus-firmus))
(defn voices-from-solution [solution cantus-firmus]
(let [voices (list (take (count solution) cantus-firmus) solution)
voices-as-pitches (map translate-into-pitchnames voices)]
voices-as-pitches))
(defn template-complete? [voices cantus-firmus]
(= (count cantus-firmus)
(count (second voices))))
(defn use-auto-goals? []
@*auto-goals*)
(defn find-voices
([] (find-voices @*auto-goals* nil default-cantus-firmus))
([auto-goals seed-note cantus-firmus]
(let [seed-note (or seed-note
(select-new-seed-note cantus-firmus major-scale @saved-templates)
@*seed-note*)]
(when (cantus-firmus-changed? cantus-firmus)
(reset! temporary-rules [])
(reset! last-cantus-firmus cantus-firmus))
(reset! *seed-note* seed-note)
(reset! *auto-goals* auto-goals)
(reset! *cantus-firmus* cantus-firmus)
(if (use-auto-goals?)
(do
(set-goals! @models)
(reset! *auto-goals* nil)
(reset! past-model-count (count @models)))
(set-default-goals!))
(when (models-changed?) (set-goals! @models))
(reset! past-model-count (count @models))
(reset! new-line [])
(let [choices (shuffle (create-choices major-scale seed-note))
solution (create-new-line cantus-firmus major-scale choices nil)
voices (voices-from-solution solution cantus-firmus)]
(when (template-complete? voices cantus-firmus)
(swap! saved-templates conj (analyze-for-template seed-note cantus-firmus major-scale)))
voices))))
(defn counterpoint
([] (counterpoint @*auto-goals* nil default-cantus-firmus))
([auto-goals seed-note cantus-firmus]
(let [voices (find-voices auto-goals seed-note cantus-firmus)]
(events/make-pairs (pair voices)))))
(defn create-canon
"creates a simple canon in two voices."
[cantus-firmus]
(let [difference 12
seed-note (- (last-first cantus-firmus) difference)
voices (find-voices false seed-note cantus-firmus)
voices-as-pitches (evaluate-pitch-names voices)
theme (concat cantus-firmus (map (fn [x] (+ x difference)) (second voices-as-pitches)))
lower-voice (map #(- % difference) theme)
dont-play (vec (repeat (count cantus-firmus) 0))]
(events/make-pairs
(pair (list (concat theme theme theme dont-play)
(concat dont-play lower-voice lower-voice lower-voice))))))
(defn compose-canon [& [cantus-firmus]]
(set-default-goals!)
(let [cantus-firmus (or cantus-firmus (map music/note '(:A3 :B3 :C4 :E4 :D4 :C4 :B3)))]
(reset! illegal-verticals '(0 1 2 5 6 7 10 11 13 14 17 18 19 22 23 25 26 29 30 34 35 -1 -2 -3 -4 -5 -6 -7 -8))
(create-canon cantus-firmus)))
(defn compose-contemporary []
(set-default-goals!)
(reset! models '(((:C4 :B3 :D4 :C4 :B3 :A3 :G3 :A3)
(:B3 :A3 :G3 :F3 :A3 :G3 :F3 :D3))
((:C4 :B3 :D4 :C4 :B3 :A3 :G3 :A3)
(:F3 :E3 :C3 :D3 :E3 :G3 :F3 :G3))
((:A3 :B3 :A3 :C4 :B3 :D4 :C4 :B3 :A3)
(:D3 :E3 :G3 :F3 :E3 :C3 :D3 :E3 :D3))))
(reset! seed-notes (map music/note '(:G3 :E3 :B2 :A2 :G2 :D3)))
(reset! *auto-goals* nil)
(create-canon (map music/note '(:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4))))
(defn compose-as-chords []
(set-default-goals!)
(let [events (counterpoint)
events-as-notes (map #(assoc % :pitch (music/find-note-name (:pitch %))) events)]
(events/as-chords events-as-notes)))
(defn compose []
(set-default-goals!)
(counterpoint))
| null | https://raw.githubusercontent.com/josephwilk/musical-creativity/c2e6aab2a26d69ee2e51f4fad84fa3a71805e6ca/src/musical_creativity/composers/gradus.clj | clojure | (ns musical-creativity.composers.gradus
(:require
[clojure.math.numeric-tower :as math]
[musical-creativity.events :as events]
[musical-creativity.util :refer :all]
[overtone.music.pitch :as music]))
(load-file "data/gradus.clj")
(def logging? true)
(def major-scale
(->> (music/scale-field :C :major)
(drop-last 46)
(take-last 36)))
(def default-seed-notes '(:E3 :D3 :B2 :A2 :G2 :C3))
(def default-cantus-firmus (map music/note [:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3]))
(def default-seed-note (music/note :C3))
(def default-illegal-verticals '(0 1 2 5 6 10 11 13 14 17 18 22 23 25 26 29 30 34 35 -1 -2 -3 -4 -5 -6 -7 -8))
(def default-illegal-parallel-motions '((7 7) (12 12) (19 19) (24 24)))
(def default-illegal-double-skips '((3 3) (3 4) (3 -3) (3 -4) (-3 -3) (-3 -4) (-3 3) (-3 4)
(4 3) (4 4) (4 -3) (4 -4) (-4 -3) (-4 -4) (-4 3) (-4 4)))
(def default-direct-fifths-and-octaves '((9 7) (8 7) (21 19) (20 19)))
(def illegal-verticals (atom []))
(def illegal-parallel-motions (atom []))
(def illegal-double-skips (atom []))
(def direct-fifths-and-octaves (atom []))
(def rules (atom []))
(def temporary-rules (atom []))
(def *seed-note* (atom default-seed-note))
(def *cantus-firmus* (atom default-cantus-firmus))
(def seed-notes (atom default-seed-notes))
(def new-line (atom []))
(def *auto-goals* (atom false))
(def *look-ahead* (atom false))
(def saved-templates (atom []))
(def last-cantus-firmus (atom []))
(def past-model-count (atom []))
(def models
(atom
'(((:C4 :B3 :D4 :C4 :B3 :A3 :G3 :A3) (:E3 :G3 :F3 :E3 :D3 :F3 :E3 :C3))
((:C4 :B3 :D4 :C4 :B3 :A3 :G3 :A3) (:A2 :G2 :F2 :A2 :G2 :F2 :G2 :F2))
((:C4 :B3 :D4 :C4 :B3 :A3 :G3 :A3) (:A2 :G2 :F2 :E2 :D2 :F2 :E2 :C2))
((:C4 :B3 :D4 :C4 :B3 :A3 :G3 :A3) (:E3 :G3 :F3 :E3 :G3 :F3 :E3 :C3))
((:A3 :B3 :C4 :A3 :B3 :C4 :D4 :F4 :E4 :D4 :C4) (:A2 :G2 :E2 :F2 :G2 :A2 :G2 :A2 :G2 :B2 :A2))
((:A3 :B3 :C4 :A3 :B3 :C4 :D4 :F4 :E4 :D4 :C4) (:A2 :G2 :E2 :F2 :G2 :A2 :G2 :F2 :G2 :F2 :E2))
((:A3 :B3 :C4 :A3 :B3 :C4 :D4 :F4 :E4 :D4 :C4) (:A2 :G2 :E2 :F2 :G2 :A2 :G2 :F2 :G2 :B2 :A2))
((:A3 :B3 :C4 :A3 :B3 :C4 :D4 :F4 :E4 :D4 :C4) (:A2 :G2 :E2 :F2 :G2 :A2 :G2 :A2 :C3 :B2 :C3))
((:A3 :B3 :C4 :A3 :B3 :C4 :D4 :F4 :E4 :D4 :C4) (:A2 :G2 :E2 :F2 :G2 :A2 :G2 :A2 :C3 :B2 :A2))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :D3 :C3 :E3 :D3 :C3 :D3 :E3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :D3 :F3 :E3 :F3 :E3 :G3 :F3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:A2 :B2 :C3 :E3 :D3 :C3 :D3 :E3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:A2 :G2 :F2 :G2 :F2 :E2 :D2 :C2))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :D3 :F3 :E3 :F3 :E3 :D3 :E3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :G3 :F3 :E3 :D3 :C3 :D3 :E3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:A2 :B2 :C3 :E3 :D3 :E3 :G3 :F3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:A2 :G2 :F2 :G2 :F2 :E2 :G2 :F2))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :D3 :F3 :E3 :D3 :C3 :D3 :C3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :D3 :C3 :E3 :D3 :E3 :G3 :F3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :G3 :F3 :E3 :D3 :E3 :G3 :F3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:A2 :G2 :F2 :G2 :F2 :E2 :D2 :E2))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :G3 :F3 :E3 :D3 :E3 :D3 :C3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :G3 :F3 :E3 :D3 :C3 :D3 :C3))
((:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4) (:E3 :D3 :C3 :E3 :D3 :E3 :D3 :C3))
((:A3 :B3 :C4 :E4 :D4 :C4 :B3 :C4 :D4 :C4) (:A2 :G2 :A2 :G2 :F2 :A2 :G2 :A2 :G2 :A2))
((:A3 :B3 :C4 :E4 :D4 :C4 :B3 :C4 :D4 :C4) (:A2 :G2 :A2 :G2 :F2 :A2 :G2 :E2 :F2 :A2))
((:A3 :B3 :C4 :E4 :D4 :C4 :B3 :C4 :D4 :C4) (:A2 :G2 :A2 :G2 :F2 :A2 :G2 :F2 :D2 :E2))
((:A3 :B3 :C4 :E4 :D4 :C4 :B3 :C4 :D4 :C4) (:A2 :G2 :A2 :G2 :B2 :A2 :B2 :A2 :B2 :A2))
((:A3 :B3 :C4 :E4 :D4 :C4 :B3 :C4 :D4 :C4) (:A2 :G2 :A2 :G2 :B2 :A2 :B2 :A2 :G2 :E2))
((:A3 :B3 :C4 :E4 :D4 :C4 :B3 :C4 :D4 :C4) (:A2 :G2 :F2 :E2 :F2 :E2 :D2 :C2 :B1 :A1))
((:A3 :B3 :C4 :E4 :D4 :C4 :B3 :C4 :D4 :C4) (:A2 :G2 :A2 :G2 :F2 :E2 :G2 :F2 :D2 :E2))
((:A3 :B3 :A3 :C4 :B3 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :E2 :G2 :F2 :A2 :G2 :A2))
((:A3 :B3 :A3 :C4 :B3 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :E2 :G2 :F2 :A2 :G2 :F2))
((:A3 :B3 :A3 :C4 :B3 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :E2 :G2 :F2 :E2 :D2 :F2))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :G2 :F2 :A2 :G2 :A2 :B2 :C3))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :A2 :G2 :F2 :E2 :D2 :E2 :D2 :F2))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :G2 :F2 :A2 :G2 :A2 :B2 :D3))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :E2 :F2 :E2 :F2 :A2 :G2 :A2))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :G2 :B2 :A2 :G2 :A2 :B2 :D3))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :E2 :F2 :E2 :D2 :E2 :G2 :F2))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :A2 :G2 :F2 :E2 :D2 :E2 :G2 :F2))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :E2 :F2 :A2 :G2 :A2 :G2 :A2))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :G2 :F2 :A2 :G2 :A2 :G2 :F2))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :G2 :B2 :A2 :G2 :A2 :G2 :F2))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :A2 :G2 :B2 :A2 :B2 :C3 :D3 :F3))
((:A3 :B3 :C4 :E4 :D4 :C4 :D4 :C4 :B3 :A3) (:A2 :G2 :A2 :G2 :B2 :A2 :B2 :C3 :D3 :C3))
((:A3 :B3 :A3 :C4 :B3 :D4 :C4 :B3 :A3) (:A2 :G2 :F2 :E2 :G2 :F2 :E2 :G2 :F2))
((:A3 :B3 :C4 :E4 :D4 :C4 :B3 :C4 :D4 :C4) (:A2 :G2 :A2 :G2 :B2 :A2 :G2 :F2 :D2 :E2))
((:A3 :B3 :C4 :D4 :B3 :C4 :D4 :C4) (:A2 :G2 :A2 :F2 :G2 :F2 :D2 :E2))
((:A3 :B3 :C4 :A3 :B3 :C4 :D4 :F4 :E4 :D4 :C4) (:A2 :G2 :E2 :F2 :G2 :A2 :G2 :F2 :G2 :F2 :A2)))))
(defn set-default-goals!
"sets the default goals for the program."
[]
(reset! illegal-verticals default-illegal-verticals)
(reset! illegal-parallel-motions default-illegal-parallel-motions)
(reset! illegal-double-skips default-illegal-double-skips)
(reset! direct-fifths-and-octaves default-direct-fifths-and-octaves))
(defn very-second [list]
(first (second list)))
(defn second-to-last [list]
(last-first (butlast list)))
(defn third-to-last [list]
(nth (butlast list) (- (count list) 3)))
(defn opposite-sign? [numbers]
(if (or (and
(neg? (first numbers))
(pos? (second numbers)))
(and
(pos? (first numbers))
(neg? (second numbers))))
true))
(defn sort-by-first-element [lists]
(sort (fn [[x & _] [y & _]] (> x y)) lists))
(defn pair
[[list1 list2]]
(map vector list1 list2))
(defn swap-unless-includes [reference data]
(when-not (some #{data} @reference)
(swap! reference conj data)))
(defn translate-into-pitchnames [list-of-midi-note-numbers]
"used to translate midi note numbers into note names."
(map music/find-note-name list-of-midi-note-numbers))
(defn get-diatonic-note [current-note interval scale]
"a simple variant of choose-from-scale which uses a diatonic interval as its second arg."
(cond
(nil? interval)
[]
(pos? interval)
(nth (member current-note scale) interval)
:else
(nth (member current-note (reverse scale)) (math/abs interval))))
(defn translate-notes
"translates interval lists into note names for readability."
[first-note intervals]
(if (empty? intervals)
(translate-into-pitchnames (list first-note))
(let [test (get-diatonic-note first-note (first intervals) major-scale)]
(concat (translate-into-pitchnames (list first-note))
(translate-notes test (rest intervals))))))
(defn translate-rule-into-pitches
"translates rules into more readable pitch names."
[first-note rule]
(list (translate-notes first-note (second rule))
(translate-notes (get-diatonic-note first-note (first rule) major-scale) (third rule))))
(defn evaluate-pitch-names
"evaluates the pitch names of its arg into midi note numbers."
[voices]
(map (fn [voice] (map music/note voice)) voices))
(defn print-working
[cantus-firmus last-notes]
(let [notes (translate-into-pitchnames cantus-firmus)
last-notes (translate-into-pitchnames last-notes)]
(println "cantus firmus:" notes "notes:" last-notes)))
(defn print-backtracking
"simple printing function to show backtracking."
[seed-note rules]
(let [rules-as-notes (doall (map #(translate-rule-into-pitches seed-note %) rules))]
(println (str "backtracking.....there are now " (count rules) " rules."))
(println " rules: " rules-as-notes)))
(defn return-counts
"simply adds the count of occurances to the beginning of each member of its arg."
[templates]
(letfn [(occurences [template templates]
(count (filter #(= template %) templates)))]
(map (fn [template]
[(occurences template templates) template]) templates)))
(defn collect-all
"collects all of the occurances of each member of its arg."
[item templates]
(filter #(= item (second %)) templates))
(defn find-scale-intervals
"returns the diatonic intervals between the notes according to the scale."
[notes scale]
(cond
(empty? (rest notes))
[]
(nil? (second notes))
(cons nil (find-scale-intervals (rest notes) scale))
:else
(cons (let [first-note-test (member (first notes) scale)
second-note-test (member (second notes) scale)]
(if (< (first notes) (second notes))
(count
(drop-last (count second-note-test) first-note-test))
(-
(count
(drop-last (count first-note-test) second-note-test)))))
(find-scale-intervals (rest notes) scale))))
(defn get-tessitura
"gets the tessitura or highest/lowest interval of a note list."
[cantus-firmus scale]
(let [scale-intervals-max (find-scale-intervals (list (first cantus-firmus) (apply max cantus-firmus)) scale)
scale-intervals-min (find-scale-intervals (list (first cantus-firmus) (apply min cantus-firmus)) scale)
up (math/abs (first scale-intervals-max))
down (math/abs (first scale-intervals-min))]
(if (> up down)
up
(- down))))
(defn get-map-part-of-template
"returns the map part of the template."
[cantus-firmus scale]
(let [tessitura (get-tessitura cantus-firmus scale)
scale-intervals (find-scale-intervals (list (first cantus-firmus) (last-first cantus-firmus)) scale)]
[tessitura (first scale-intervals)]))
(defn select-new-seed-note
"select a logical new seed note."
[cantus-firmus scale saved-templates]
(let [map-template (get-map-part-of-template cantus-firmus scale)
templates (collect-all map-template saved-templates)
counts (return-counts templates)
sorted-counts (sort-by-first-element counts)
interval (first (second (first sorted-counts)))]
(when interval
(get-diatonic-note (first cantus-firmus) interval scale))))
(defn get-complement
"incrementally returns all of the intervals not in the verticals arg."
([verticals] (get-complement verticals 0))
([verticals number]
(cond
(empty? verticals)
[]
(member number verticals)
(get-complement (rest verticals) (inc number))
:else
(cons number (get-complement verticals (inc number))))))
(defn project-octaves [numbers]
(letfn [(octaves-out-from [number]
(if (> number 12)
(list (- number 12) number (+ number 12))
(list number (+ number 12)(+ number 24))))]
(mapcat octaves-out-from numbers)))
(defn make-voices
"makes lists of the cantus firmus and accompanying line pitches."
[models]
[(mapcat first models) (mapcat second models)])
(defn get-the-verticals
"collects the vertical intervals from the models used."
[models]
(sort < (distinct
(project-octaves
(let [voiced-music (pair (make-voices models))]
(map (fn [pair] (- (music/note (first pair)) (music/note (second pair)))) voiced-music))))))
(defn get-illegal-verticals
"returns all of the vertical intervals not in the models."
[models]
(get-complement (get-the-verticals models)))
(defn find-first-args-also-in-second-arg [find-list target-list]
(first
(filter
(fn [find] (when (member find target-list) find))
find-list)))
(defn remove-illegal-verticals
"removes the illegal verticals in its second arg."
[illegal-verticals all-verticals]
(remove #(find-first-args-also-in-second-arg illegal-verticals %) all-verticals))
(defn find-motions [extent value]
(map #(list extent %) (range value 0 -1)))
(defn find-all-possible-motions
"returns all possible motions to its extent arg."
([extend] (find-all-possible-motions extend extend))
([extent save-extent]
(mapcat #(find-motions % save-extent) (range extent 0 -1))))
(defn- motions [[model1 model2]]
(list (- (music/note (first model1)) (music/note (second model1)))
(- (music/note (first model2)) (music/note (second model2)))))
(defn find-the-legals
"discovers the legal motions in its arg."
[paired-model]
(let [partitioned-paired-models (partition 2 1 paired-model)]
(map motions partitioned-paired-models)))
(defn find-legals [models]
"collects the legal motions in its arg."
(mapcat #(find-the-legals (pair %)) models))
(defn remove-legal-motions
"removes the legal motions from the motions arg."
[legal-motions motions]
(remove #(some #{%} legal-motions) motions))
(defn find-illegal-parallels
"returns the non-used parallels in the models which are assumed to be illegal."
[models]
(let [illegal-verticals (get-illegal-verticals models)
legal-verticals (remove-illegal-verticals illegal-verticals (find-all-possible-motions 24))
model-verticals (find-legals models)]
(remove-legal-motions model-verticals legal-verticals)))
(defn combinations [object list]
(map (fn [item] [object item]) list))
(defn possible-combinations
"returns all possible combinations of its list arg."
([list] (possible-combinations list list))
([list save-list]
(mapcat #(combinations % save-list) list)))
(defn all-first-notes-conflict-rules? [choices rules]
"checking to see if all possible first notes produce rule-conflicting problems."
(every? #(member (list % nil nil) rules) choices))
(defn reduce-to-within-octave [interval]
"reduces diatonic intervals to within the octave."
(cond
(and (> (math/abs interval) 7)
(neg? interval))
(reduce-to-within-octave (+ interval 7))
(> (math/abs interval) 7)
(- interval 7)
(zero? interval)
-7
:else
interval))
(defn get-diatonic-interval [interval-class]
"translates interval-classes into diatonic-interval classes."
(case interval-class
1 1
2 1
3 2
4 2
-1 -1
-2 -1
-3 -2
-4 -2
:else
1))
(defn choose-from-scale
"gets the appropriate pitch from the current scale based on the interval class."
[current-note interval-class scale]
(if (pos? interval-class)
(nth (member current-note scale) (get-diatonic-interval interval-class))
(let [interval (math/abs (get-diatonic-interval interval-class))
notes (member current-note (reverse scale))]
(nth notes interval))))
(defn create-choices [scale last-choice]
"creates four possible choices - seconds and thirds - from a previous pitch choice."
[(choose-from-scale last-choice 1 scale)
(choose-from-scale last-choice 3 scale)
(choose-from-scale last-choice -1 scale)
(choose-from-scale last-choice -3 scale)])
(defn no-solution-exists?
"for stopping if no solution exists."
[seed-note cantus-firmus rules]
(all-first-notes-conflict-rules?
(map (fn [x]
(reduce-to-within-octave
(first (find-scale-intervals (list (first cantus-firmus) x)
major-scale))))
(create-choices major-scale seed-note)) rules))
(defn consult-rules [rule]
"calling (consult-rules (-9 (2 -1 -1) (-1 2 -2))) consult-rules returned nil"
(or (member rule @rules)
(member rule @temporary-rules)))
(defn create-interval-rule [rule]
"creates the interval rule as in (-7 (2 2 2)(-1 1 2))."
(list (first (find-scale-intervals (list (ffirst rule)
(first (second rule)))
major-scale))
(find-scale-intervals (first rule) major-scale)
(find-scale-intervals (second rule) major-scale)))
(defn create-rule [cantus-firmus new-notes]
"creates rules for the rules variable"
(let [the-list (take-last 4 new-notes)]
(create-interval-rule
(list (take-last (count the-list)
(drop-last (- (count cantus-firmus)(count new-notes)) cantus-firmus)) the-list))))
(defn skip? [notes]
"returns true if its two-number arg is a skip."
(if (> (math/abs (- (second notes) (first notes))) 2) true))
(defn get-verticals
"returns the intervals between two lines of counterpoint."
[cantus-firmus new-line]
(if (empty? cantus-firmus) []
(cons (- (first cantus-firmus)(first new-line))
(get-verticals (rest cantus-firmus)(rest new-line)))))
(defn get-intervals
"returns a list of intervals one short of its pitch-list arg."
[notes]
(let [partitioned-notes (partition 2 1 notes)]
(map (fn [[note1 note2]] (- note2 note1)) partitioned-notes)))
(defn vertical-dissonance?
"tests to ensure vertical dissonance"
[cantus-firmus-note choice]
(when (member (- cantus-firmus-note choice) @illegal-verticals)
choice))
(defn simultaneous-leaps? [cantus-firmus choice last-notes]
"tests for the presence of simultaneous leaps."
(let [cantus-firmus-to-here (take (inc (count last-notes)) cantus-firmus)]
(cond
(or (not (>= (count cantus-firmus-to-here) 2))
(not (>= (count last-notes) 1)))
nil
(and (skip? (take-last 2 cantus-firmus-to-here))
(skip? (take-last 2 (concat last-notes (list choice)))))
true
:else
nil)))
(defn parallel-octaves-and-fifths?
"tests for parallel octaves and fifths."
[cantus-firmus choice last-notes]
(let [next-position (inc (count last-notes))
cantus-firmus-to-here (take next-position cantus-firmus)]
(cond
(or (not (>= (count cantus-firmus-to-here) 2))
(not (>= (count last-notes) 1)))
nil
(member (list (math/abs (- (second-to-last cantus-firmus-to-here)
(last-first last-notes)))
(math/abs (- (last-first cantus-firmus-to-here) choice)))
@illegal-parallel-motions)
true
:else
nil)))
(defn leaps?
"tests for leaps and avoids two in row and ensures that leaps are followed by contrary motion steps."
[extended-last-notes]
(cond
(not (>= (count extended-last-notes) 3))
nil
(member (list (- (second-to-last extended-last-notes)
(last-first extended-last-notes))
(- (third-to-last extended-last-notes)
(second-to-last extended-last-notes)))
@illegal-double-skips)
true
(and (> (math/abs (- (third-to-last extended-last-notes)
(second-to-last extended-last-notes)))
2)
(not (opposite-sign? (list (- (second-to-last extended-last-notes)(last-first extended-last-notes))
(- (third-to-last extended-last-notes)(second-to-last extended-last-notes))))))
true
:else
nil))
(defn direct-fifths?
"tests for direct fifths between the two lines."
[cantus-firmus choice last-notes]
(let [cantus-firmus-to-here (take (inc (count last-notes)) cantus-firmus)]
(cond
(or (not (>= (count cantus-firmus-to-here) 2))
(not (>= (count last-notes) 1)))
nil
(member (get-verticals (take-last 2 cantus-firmus-to-here)
(take-last 2 (concat last-notes (list choice))))
@direct-fifths-and-octaves)
true
:else
nil)))
(defn consecutive-motions?
"tests to see if there are more than two consecutive save-direction motions."
[cantus-firmus choice last-notes]
(let [cantus-firmus-to-here (take (inc (count last-notes)) cantus-firmus)]
(cond
(or (not (> (count cantus-firmus-to-here) 3))
(not (> (count last-notes) 2)))
nil
(let [last-four-cf (take-last 4 cantus-firmus-to-here)
last-four-newline (take-last 4 (concat last-notes (list choice)))]
(not (or (opposite-sign? (list (first (get-intervals (take 2 last-four-cf)))
(first (get-intervals (take 2 last-four-newline)))))
(opposite-sign? (list (first (get-intervals (take 2 (rest last-four-cf))))
(first (get-intervals (take 2 (rest last-four-newline))))))
(opposite-sign? (list (first (get-intervals (take-last 2 last-four-cf)))
(first (get-intervals (take-last 2 last-four-newline))))))))
true
:else
nil)))
(defn choice-fits-goals-and-current-rules? [choice cantus-firmus last-notes]
(let [current-rule (create-rule cantus-firmus (concat last-notes (list choice)))
next-position (inc (count last-notes))
current-cantus-firmus (take next-position cantus-firmus)]
(and (not (consult-rules current-rule))
(not (vertical-dissonance? (nth cantus-firmus (count last-notes)) choice))
(not (parallel-octaves-and-fifths? current-cantus-firmus choice last-notes))
(not (leaps? (concat last-notes (list choice))))
(not (simultaneous-leaps? current-cantus-firmus choice last-notes))
(not (direct-fifths? current-cantus-firmus choice last-notes))
(not (consecutive-motions? current-cantus-firmus choice last-notes)))))
(defn evaluate
"evaluates the various choices for a next note based on the goals and current rules"
[cantus-firmus choices last-notes]
(filter #(choice-fits-goals-and-current-rules? % cantus-firmus last-notes) choices))
(defn match-rule [rule-for-matching rule]
"matches the freer rule to the rule from rules."
(cond
(and (nil? (first (rest rule-for-matching)))(nil? (first (rest rule))))
true
(or (and (= (ffirst (rest rule-for-matching))(ffirst (rest rule)))
(= (very-second (rest rule-for-matching))(very-second (rest rule))))
(and (= (ffirst (rest rule-for-matching))(ffirst (rest rule)))
(nil? (very-second (rest rule-for-matching)))))
(match-rule (cons (first rule-for-matching)(map rest (rest rule-for-matching)))
(cons (first rule)(map rest (rest rule))))
:else
nil))
(defn match-interval-rule [rule-for-matching rule]
"matches the freer rule to the rule from rules."
(cond
(and (empty? (first rule-for-matching))
(empty? (first rule)))
true
(or (and (= (ffirst rule-for-matching) (ffirst rule))
(= (very-second rule-for-matching) (very-second rule)))
(and (= (ffirst rule-for-matching) (ffirst rule))
(nil? (very-second rule-for-matching))))
(match-interval-rule (map rest rule-for-matching) (map rest rule))
:else
nil))
(defn match-rules-freely [rule rules]
"runs the match-rule function through the rules."
(cond
(empty? rules)
nil
(and (= (first rule)
(ffirst rules))
(match-interval-rule (rest rule) (rest (first rules))))
true
(and (= (first rule)
(ffirst rules))
(= (count (second rule))
(count (second (first rules))))
(match-rule rule (first rules)))
true
:else
(match-rules-freely rule (rest rules))))
(defn reduce-rule [rule]
"reduces the front-end of the look-ahead rule."
(if (<= (count (second rule)) 3)
rule
(let [amount (- (count (second rule)) 3)]
(cons (+ (first rule)
(- (first (second rule)))
(first (third rule)))
(map rest (rest rule))))))
(defn make-freer-rule [amount cf-notes rule]
"adds the appropriate number of nils to the new line for look-ahead matching."
(if (zero? amount) rule
(make-freer-rule (dec amount)
(rest cf-notes)
(list (first rule)
(concat (second rule)(list (first cf-notes)))
(concat (third rule)(list nil))))))
(defn create-relevant-cf-notes [last-notes cantus-firmus]
"creates the set of forward reaching cf notes."
(take 2 (drop (dec (count last-notes)) cantus-firmus)))
(defn look-ahead [amount cantus-firmus last-notes rule rules]
"the top-level function for looking ahead."
(let [cf-notes (create-relevant-cf-notes last-notes cantus-firmus)
scale-intervals (find-scale-intervals cf-notes major-scale)
freer-rule (make-freer-rule amount scale-intervals rule)]
(match-rules-freely (reduce-rule freer-rule) rules)))
(defn- look-ahead-filter-fn [cantus-firmus last-notes]
(fn [choice]
(let [new-choice (list choice)
new-last-notes (concat last-notes new-choice)
new-rule (create-rule cantus-firmus new-last-notes)]
(not (look-ahead 1 cantus-firmus new-last-notes new-rule @rules)))))
(defn look-ahead-for-best-choice [cantus-firmus last-notes correct-choices]
"looks ahead for the best choice"
(first
(filter (look-ahead-filter-fn cantus-firmus last-notes) correct-choices)))
(defn evaluate-choices
"runs the evaluate and look-ahead functions through the various choices."
[cantus-firmus choices last-notes]
(let [correct-choices (evaluate cantus-firmus choices last-notes)]
(if correct-choices
(reset! *look-ahead* true)
(reset! *look-ahead* false))
(if (pos? (count correct-choices))
(look-ahead-for-best-choice cantus-firmus last-notes correct-choices)
(first correct-choices))))
(defn get-new-starting-point
"for backtracking - starts 2 earlier or nil"
[last-notes]
(cond
(<= (count last-notes) 1)
[]
:else
(drop-last 1 last-notes)))
(declare create-new-line)
(defn- create-line-from-choices [cantus-firmus scale choices last-notes length]
(let [new-rule (create-rule cantus-firmus (concat last-notes (list (first choices))))]
(if @*look-ahead*
(swap-unless-includes rules new-rule)
(swap-unless-includes temporary-rules new-rule)))
(print-backtracking @*seed-note* @rules)
(let [new-last-notes (get-new-starting-point last-notes)
seed-note (if (empty? new-last-notes) @*seed-note* (last-first new-last-notes))
choices (shuffle (create-choices major-scale seed-note))
new-choices (remove #(= % (last-first last-notes)) choices)
line (drop-last (- (count last-notes) (count new-last-notes)) @new-line)
new-length (+ length (- (count last-notes) (count new-last-notes)))]
(reset! new-line line)
(create-new-line cantus-firmus scale new-choices new-last-notes new-length)))
(defn- create-line-from-new-choices [test cantus-firmus scale last-notes length]
(reset! new-line (concat @new-line (list test)))
(when logging?
(print-working cantus-firmus @new-line))
(let [new-choices (shuffle (create-choices major-scale test))
new-length (dec length)
new-last-notes (concat last-notes (list test))]
(create-new-line cantus-firmus scale new-choices new-last-notes new-length)))
(defn create-new-line
"creates a new line with the cantus firmus."
([cantus-firmus scale choices last-notes] (create-new-line cantus-firmus scale choices last-notes (count cantus-firmus)))
([cantus-firmus scale choices last-notes length]
(if (no-solution-exists? @*seed-note* @*cantus-firmus* @rules)
(println "i can find no solution for this cantus firmus.")
(if (<= length 0)
@new-line
(let [new-note-choices (evaluate-choices cantus-firmus choices last-notes)]
(if new-note-choices
(create-line-from-new-choices new-note-choices cantus-firmus scale last-notes length)
(create-line-from-choices cantus-firmus scale choices last-notes length)))))))
(defn analyze-for-template [seed-note cantus-firmus scale]
"returns the complete template (seed interval and map) for saving."
(let [cantus-firmus-note (first cantus-firmus)
cantus-firmus-note-and-seed (list cantus-firmus-note seed-note)
scale-intervals (find-scale-intervals cantus-firmus-note-and-seed scale)]
(list (first scale-intervals) (get-map-part-of-template cantus-firmus scale))))
(defn set-goals!
"sets the goals for the gradus program."
[models]
(reset! illegal-verticals (get-illegal-verticals models))
(reset! illegal-parallel-motions (find-illegal-parallels models))
(reset! direct-fifths-and-octaves (find-illegal-parallels models))
(reset! illegal-double-skips (possible-combinations '(3 4 -3 -4))))
(defn replenish-seed-notes! []
"replenishes the seednotes when when they have all been used."
(reset! seed-notes (map music/note '(:C3 :F3 :E3 :D3 :B2 :A2 :G2 :F2))))
(defn models-changed? []
(not= (count @models) @past-model-count))
(defn cantus-firmus-changed? [cantus-firmus]
(not= last-cantus-firmus cantus-firmus))
(defn voices-from-solution [solution cantus-firmus]
(let [voices (list (take (count solution) cantus-firmus) solution)
voices-as-pitches (map translate-into-pitchnames voices)]
voices-as-pitches))
(defn template-complete? [voices cantus-firmus]
(= (count cantus-firmus)
(count (second voices))))
(defn use-auto-goals? []
@*auto-goals*)
(defn find-voices
([] (find-voices @*auto-goals* nil default-cantus-firmus))
([auto-goals seed-note cantus-firmus]
(let [seed-note (or seed-note
(select-new-seed-note cantus-firmus major-scale @saved-templates)
@*seed-note*)]
(when (cantus-firmus-changed? cantus-firmus)
(reset! temporary-rules [])
(reset! last-cantus-firmus cantus-firmus))
(reset! *seed-note* seed-note)
(reset! *auto-goals* auto-goals)
(reset! *cantus-firmus* cantus-firmus)
(if (use-auto-goals?)
(do
(set-goals! @models)
(reset! *auto-goals* nil)
(reset! past-model-count (count @models)))
(set-default-goals!))
(when (models-changed?) (set-goals! @models))
(reset! past-model-count (count @models))
(reset! new-line [])
(let [choices (shuffle (create-choices major-scale seed-note))
solution (create-new-line cantus-firmus major-scale choices nil)
voices (voices-from-solution solution cantus-firmus)]
(when (template-complete? voices cantus-firmus)
(swap! saved-templates conj (analyze-for-template seed-note cantus-firmus major-scale)))
voices))))
(defn counterpoint
([] (counterpoint @*auto-goals* nil default-cantus-firmus))
([auto-goals seed-note cantus-firmus]
(let [voices (find-voices auto-goals seed-note cantus-firmus)]
(events/make-pairs (pair voices)))))
(defn create-canon
"creates a simple canon in two voices."
[cantus-firmus]
(let [difference 12
seed-note (- (last-first cantus-firmus) difference)
voices (find-voices false seed-note cantus-firmus)
voices-as-pitches (evaluate-pitch-names voices)
theme (concat cantus-firmus (map (fn [x] (+ x difference)) (second voices-as-pitches)))
lower-voice (map #(- % difference) theme)
dont-play (vec (repeat (count cantus-firmus) 0))]
(events/make-pairs
(pair (list (concat theme theme theme dont-play)
(concat dont-play lower-voice lower-voice lower-voice))))))
(defn compose-canon [& [cantus-firmus]]
(set-default-goals!)
(let [cantus-firmus (or cantus-firmus (map music/note '(:A3 :B3 :C4 :E4 :D4 :C4 :B3)))]
(reset! illegal-verticals '(0 1 2 5 6 7 10 11 13 14 17 18 19 22 23 25 26 29 30 34 35 -1 -2 -3 -4 -5 -6 -7 -8))
(create-canon cantus-firmus)))
(defn compose-contemporary []
(set-default-goals!)
(reset! models '(((:C4 :B3 :D4 :C4 :B3 :A3 :G3 :A3)
(:B3 :A3 :G3 :F3 :A3 :G3 :F3 :D3))
((:C4 :B3 :D4 :C4 :B3 :A3 :G3 :A3)
(:F3 :E3 :C3 :D3 :E3 :G3 :F3 :G3))
((:A3 :B3 :A3 :C4 :B3 :D4 :C4 :B3 :A3)
(:D3 :E3 :G3 :F3 :E3 :C3 :D3 :E3 :D3))))
(reset! seed-notes (map music/note '(:G3 :E3 :B2 :A2 :G2 :D3)))
(reset! *auto-goals* nil)
(create-canon (map music/note '(:C4 :B3 :A3 :G3 :A3 :C4 :B3 :C4))))
(defn compose-as-chords []
(set-default-goals!)
(let [events (counterpoint)
events-as-notes (map #(assoc % :pitch (music/find-note-name (:pitch %))) events)]
(events/as-chords events-as-notes)))
(defn compose []
(set-default-goals!)
(counterpoint))
| |
c1694f61ac7280c1de296dc855ab8f2643dc7847907fa224d43a719580847660 | SnootyMonkey/posthere.io | delete.clj | (ns posthere.integration.delete
"Test DELETE API request handling by the POSThere.io service."
(:require [midje.sweet :refer :all]
[ring.mock.request :refer (request)]
[posthere.util.uuid :refer (uuid)]
[posthere.app :refer (app)]
[posthere.storage :refer (save-request requests-for)]))
(defn- url-for [url-uuid]
(str "/" url-uuid))
(facts "about DELETE API responses"
(fact "default response status is provided"
(let [url-uuid (uuid)
url (url-for url-uuid)
request (request :delete url)
response (app request)]
(:status response) => 204))
(fact "default response status is provided for a URL with multiple segments"
(let [url-uuid "foo/bar/blat/bloo"
url (url-for url-uuid)
request (request :delete url)
response (app request)]
(:status response) => 204)))
(fact "about the effect of a DELETE API request"
(let [url-uuid (uuid)
url (url-for url-uuid)]
;; Store some requests
(save-request url-uuid {:headers {:foo :bar}})
(save-request url-uuid {:headers {:bar :foo}})
;; Verify they are there
(requests-for url-uuid) => [{:headers {:bar :foo}}{:headers {:foo :bar}}]
;; Delete the requests
(app (request :delete url))
;; Verify they are gone
(requests-for url-uuid) => [])) | null | https://raw.githubusercontent.com/SnootyMonkey/posthere.io/698b46c917d7f74a5fb06c13beae49ded1ca1705/test/posthere/integration/delete.clj | clojure | Store some requests
Verify they are there
Delete the requests
Verify they are gone | (ns posthere.integration.delete
"Test DELETE API request handling by the POSThere.io service."
(:require [midje.sweet :refer :all]
[ring.mock.request :refer (request)]
[posthere.util.uuid :refer (uuid)]
[posthere.app :refer (app)]
[posthere.storage :refer (save-request requests-for)]))
(defn- url-for [url-uuid]
(str "/" url-uuid))
(facts "about DELETE API responses"
(fact "default response status is provided"
(let [url-uuid (uuid)
url (url-for url-uuid)
request (request :delete url)
response (app request)]
(:status response) => 204))
(fact "default response status is provided for a URL with multiple segments"
(let [url-uuid "foo/bar/blat/bloo"
url (url-for url-uuid)
request (request :delete url)
response (app request)]
(:status response) => 204)))
(fact "about the effect of a DELETE API request"
(let [url-uuid (uuid)
url (url-for url-uuid)]
(save-request url-uuid {:headers {:foo :bar}})
(save-request url-uuid {:headers {:bar :foo}})
(requests-for url-uuid) => [{:headers {:bar :foo}}{:headers {:foo :bar}}]
(app (request :delete url))
(requests-for url-uuid) => [])) |
65a197bef5e60d0e46f72194a9dc0d7da41a9aa8919f0f2a5fb45dd2a0eb6df9 | sharplispers/slitch | netlib-constants.lisp | ;; Networking constants, derived from RFCs.
(in-package :netlib)
;; Ethernet
(defconstant ethtype-arp #x0806)
(defconstant ethtype-rarp #x8035)
(defconstant ethtype-ip #x0800)
(defconstant broadcast-mac #e"FF:FF:FF:FF:FF:FF"
"The ethernet broadcast address.")
ARP
(defconstant arp-operation-request 1)
(defconstant arp-operation-response 2)
IPv4
(defconstant ip-protocol-icmp 1)
(defconstant ip-protocol-tcp 6)
(defconstant ip-protocol-udp 17)
;; IP options: control class
(defconstant ipopt-end-of-options 0)
(defconstant ipopt-nop 1)
(defconstant ipopt-security 2)
(defconstant ipopt-loose-source-routing 3)
(defconstant ipopt-strict-source-routing 9)
(defconstant ipopt-record-route 7)
(defconstant ipopt-stream-id 4)
;; IP options: debugging class
(defconstant ipopt-timestamp 4)
;; ICMP
(defconstant icmp-type-echo-request 8)
(defconstant icmp-type-echo-reply 0)
(defconstant icmp-type-port-unreachable 3)
;; TCP
(defconstant tcpopt-end-of-options 0)
(defconstant tcpopt-nop 1)
(defconstant tcpopt-mss 2)
| null | https://raw.githubusercontent.com/sharplispers/slitch/edd96fde7722ed4ce4678d7041aad69eb0762c9f/src/netlib-constants.lisp | lisp | Networking constants, derived from RFCs.
Ethernet
IP options: control class
IP options: debugging class
ICMP
TCP |
(in-package :netlib)
(defconstant ethtype-arp #x0806)
(defconstant ethtype-rarp #x8035)
(defconstant ethtype-ip #x0800)
(defconstant broadcast-mac #e"FF:FF:FF:FF:FF:FF"
"The ethernet broadcast address.")
ARP
(defconstant arp-operation-request 1)
(defconstant arp-operation-response 2)
IPv4
(defconstant ip-protocol-icmp 1)
(defconstant ip-protocol-tcp 6)
(defconstant ip-protocol-udp 17)
(defconstant ipopt-end-of-options 0)
(defconstant ipopt-nop 1)
(defconstant ipopt-security 2)
(defconstant ipopt-loose-source-routing 3)
(defconstant ipopt-strict-source-routing 9)
(defconstant ipopt-record-route 7)
(defconstant ipopt-stream-id 4)
(defconstant ipopt-timestamp 4)
(defconstant icmp-type-echo-request 8)
(defconstant icmp-type-echo-reply 0)
(defconstant icmp-type-port-unreachable 3)
(defconstant tcpopt-end-of-options 0)
(defconstant tcpopt-nop 1)
(defconstant tcpopt-mss 2)
|
57493780c2e08d43888450a3439289b3a6849d86371d33e4e487dda3eba68c9d | synduce/Synduce | exists_equal_elems.ml | * @synduce -NB --no - lifting
type two_list = TwoLists of list * list
and list =
| Elt of int
| Cons of int * list
(* Invariant: sorted in decreasing order. *)
let rec is_sorted = function
| TwoLists (x, y) -> is_sorted_l x && is_sorted_l y
and is_sorted_l = function
| Elt x -> true
| Cons (hd, tl) -> aux hd tl
and aux prev = function
| Elt x -> prev >= x
| Cons (hd, tl) -> prev >= hd && aux hd tl
;;
(* Reference function in quadratic time. *)
let rec is_intersection_nonempty = function
| TwoLists (x, y) -> seek_common_elt x y
and seek_common_elt y = function
| Elt a -> find a y
| Cons (hd, tl) -> find hd y || is_intersection_nonempty (TwoLists (tl, y))
and find a = function
| Elt b -> b = a
| Cons (hd, tl) -> hd = a || find a tl
;;
Target assumes that lsits are sorted and takes advantage of it .
let rec target = function
| TwoLists (x, y) -> seek x y
[@@requires is_sorted]
and seek y = function
| Elt a -> find2 a y
| Cons (hd, tl) -> aux hd tl y
and aux a l = function
| Elt b -> a = b
| Cons (b, l2) ->
if a < b
then target (TwoLists (Cons (b, l2), l))
else target (TwoLists (l2, Cons (a, l)))
and find2 a = function
| Elt b -> [%synt base_case] a b
| Cons (hd, tl) ->
if a > hd then [%synt fstop] a hd else [%synt fcontinue] hd a (find2 a tl)
;;
assert (target = is_intersection_nonempty)
| null | https://raw.githubusercontent.com/synduce/Synduce/d453b04cfb507395908a270b1906f5ac34298d29/benchmarks/constraints/sortedlist/exists_equal_elems.ml | ocaml | Invariant: sorted in decreasing order.
Reference function in quadratic time. | * @synduce -NB --no - lifting
type two_list = TwoLists of list * list
and list =
| Elt of int
| Cons of int * list
let rec is_sorted = function
| TwoLists (x, y) -> is_sorted_l x && is_sorted_l y
and is_sorted_l = function
| Elt x -> true
| Cons (hd, tl) -> aux hd tl
and aux prev = function
| Elt x -> prev >= x
| Cons (hd, tl) -> prev >= hd && aux hd tl
;;
let rec is_intersection_nonempty = function
| TwoLists (x, y) -> seek_common_elt x y
and seek_common_elt y = function
| Elt a -> find a y
| Cons (hd, tl) -> find hd y || is_intersection_nonempty (TwoLists (tl, y))
and find a = function
| Elt b -> b = a
| Cons (hd, tl) -> hd = a || find a tl
;;
Target assumes that lsits are sorted and takes advantage of it .
let rec target = function
| TwoLists (x, y) -> seek x y
[@@requires is_sorted]
and seek y = function
| Elt a -> find2 a y
| Cons (hd, tl) -> aux hd tl y
and aux a l = function
| Elt b -> a = b
| Cons (b, l2) ->
if a < b
then target (TwoLists (Cons (b, l2), l))
else target (TwoLists (l2, Cons (a, l)))
and find2 a = function
| Elt b -> [%synt base_case] a b
| Cons (hd, tl) ->
if a > hd then [%synt fstop] a hd else [%synt fcontinue] hd a (find2 a tl)
;;
assert (target = is_intersection_nonempty)
|
710912baeee92d25527d3b06323674f5f80465b67ec472f0ad8eb8d5604aeb7d | paurkedal/ocaml-mediawiki-api | mwapi_parse.ml | Copyright ( C ) 2013 - -2017 Petter A. Urkedal < >
*
* This library is free software ; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , either version 3 of the License , or ( at your
* option ) any later version , with the OCaml static compilation exception .
*
* This library is distributed in the hope that it will be useful , but WITHOUT
* ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public
* License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library . If not , see < / > .
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version, with the OCaml static compilation exception.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see </>.
*)
open Kojson_pattern
open Mwapi
open Mwapi_prereq
open Unprime
type 'a prop = {
prop_names : string;
prop_decode : Kojson.jain -> 'a * Kojson.jain;
}
let (&) a b =
let prop_decode jain =
let x, jain = a.prop_decode jain in
let y, jain = b.prop_decode jain in
((x, y), jain) in
let prop_names =
match a.prop_names, b.prop_names with
| "", pn | pn, "" -> pn
| pna, pnb -> pna ^ "|" ^ pnb in
{ prop_names; prop_decode }
let prim_parse params {prop_names; prop_decode} =
let request_params = ("action", "parse") :: ("prop", prop_names) :: params in
let request_decode =
"parse"^:
K.assoc begin
prop_decode %> fun (x, rest) -> Ka.stop x rest
end %> pair in
{request_method = `GET; request_params; request_decode}
let parse ?(disablepp = false) ?(redirects = false) ?contentformat ?contentmodel
~page ?section prop =
let params = []
|> pass_if "disablepp" disablepp
|> pass_if "redirects" redirects
|> pass_opt string_of_int "section" section
|> pass_opt ident "contentformat" contentformat
|> pass_opt ident "contentmodel" contentmodel
|> (match page with
| `Title s -> pass ident "page" s
| `Id i -> pass string_of_int "pageid" i
| `Rev i -> pass string_of_int "oldid" i) in
prim_parse params prop
let title =
let prop_decode = "title"^: K.string %> fun title rest -> (title, rest) in
{prop_names = ""; prop_decode}
let revid =
let prop_decode = "revid"^: K.int %> fun revid rest -> (revid, rest) in
{prop_names = "revid"; prop_decode}
let text =
let prop_decode = "text"^: K.assoc ("*"^: K.string %> Ka.stop) %> pair in
{prop_names = "text"; prop_decode}
let wikitext =
let prop_decode = "wikitext"^: K.assoc ("*"^: K.string %> Ka.stop) %> pair in
{prop_names = "wikitext"; prop_decode}
type section = {
section_toclevel : int;
section_level : int;
section_line : string;
section_number : string;
section_index : string;
section_fromtitle : string;
section_byteoffset : int;
section_anchor : string;
}
let sections =
let prop_decode =
"sections"^:
K.list (K.assoc
begin
"toclevel"^: K.int %> fun section_toclevel ->
"level"^: K_repair.int %> fun section_level ->
"line"^: K.string %> fun section_line ->
"number"^: K.string %> fun section_number ->
"index"^: K.string %> fun section_index ->
"fromtitle"^: K.string %> fun section_fromtitle ->
"byteoffset"^: K.int %> fun section_byteoffset ->
"anchor"^: K.string %> fun section_anchor ->
Ka.stop {
section_toclevel; section_level; section_line; section_number;
section_index; section_fromtitle;
section_byteoffset; section_anchor
}
end) %> fun sections rest -> (sections, rest) in
{prop_names = "sections"; prop_decode}
| null | https://raw.githubusercontent.com/paurkedal/ocaml-mediawiki-api/6a1c1043a8ad578ea321a314fbe0a12a8d0933cf/lib/mwapi_parse.ml | ocaml | Copyright ( C ) 2013 - -2017 Petter A. Urkedal < >
*
* This library is free software ; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , either version 3 of the License , or ( at your
* option ) any later version , with the OCaml static compilation exception .
*
* This library is distributed in the hope that it will be useful , but WITHOUT
* ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public
* License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library . If not , see < / > .
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version, with the OCaml static compilation exception.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see </>.
*)
open Kojson_pattern
open Mwapi
open Mwapi_prereq
open Unprime
type 'a prop = {
prop_names : string;
prop_decode : Kojson.jain -> 'a * Kojson.jain;
}
let (&) a b =
let prop_decode jain =
let x, jain = a.prop_decode jain in
let y, jain = b.prop_decode jain in
((x, y), jain) in
let prop_names =
match a.prop_names, b.prop_names with
| "", pn | pn, "" -> pn
| pna, pnb -> pna ^ "|" ^ pnb in
{ prop_names; prop_decode }
let prim_parse params {prop_names; prop_decode} =
let request_params = ("action", "parse") :: ("prop", prop_names) :: params in
let request_decode =
"parse"^:
K.assoc begin
prop_decode %> fun (x, rest) -> Ka.stop x rest
end %> pair in
{request_method = `GET; request_params; request_decode}
let parse ?(disablepp = false) ?(redirects = false) ?contentformat ?contentmodel
~page ?section prop =
let params = []
|> pass_if "disablepp" disablepp
|> pass_if "redirects" redirects
|> pass_opt string_of_int "section" section
|> pass_opt ident "contentformat" contentformat
|> pass_opt ident "contentmodel" contentmodel
|> (match page with
| `Title s -> pass ident "page" s
| `Id i -> pass string_of_int "pageid" i
| `Rev i -> pass string_of_int "oldid" i) in
prim_parse params prop
let title =
let prop_decode = "title"^: K.string %> fun title rest -> (title, rest) in
{prop_names = ""; prop_decode}
let revid =
let prop_decode = "revid"^: K.int %> fun revid rest -> (revid, rest) in
{prop_names = "revid"; prop_decode}
let text =
let prop_decode = "text"^: K.assoc ("*"^: K.string %> Ka.stop) %> pair in
{prop_names = "text"; prop_decode}
let wikitext =
let prop_decode = "wikitext"^: K.assoc ("*"^: K.string %> Ka.stop) %> pair in
{prop_names = "wikitext"; prop_decode}
type section = {
section_toclevel : int;
section_level : int;
section_line : string;
section_number : string;
section_index : string;
section_fromtitle : string;
section_byteoffset : int;
section_anchor : string;
}
let sections =
let prop_decode =
"sections"^:
K.list (K.assoc
begin
"toclevel"^: K.int %> fun section_toclevel ->
"level"^: K_repair.int %> fun section_level ->
"line"^: K.string %> fun section_line ->
"number"^: K.string %> fun section_number ->
"index"^: K.string %> fun section_index ->
"fromtitle"^: K.string %> fun section_fromtitle ->
"byteoffset"^: K.int %> fun section_byteoffset ->
"anchor"^: K.string %> fun section_anchor ->
Ka.stop {
section_toclevel; section_level; section_line; section_number;
section_index; section_fromtitle;
section_byteoffset; section_anchor
}
end) %> fun sections rest -> (sections, rest) in
{prop_names = "sections"; prop_decode}
| |
15728d88b9739ea3d135112758fb8cb09c81473300024cb03b40f06079b1589d | let-def/lrgrep | reduction.ml | open Fix.Indexing
open Utils
open Misc
module Make(Redgraph : Sigs.REDGRAPH) :
Sigs.REDUCTION with module Info = Redgraph.Info =
struct
module Info = Redgraph.Info
open Info
module type DERIVABLE = sig
type t
val derive : t -> t partial_derivative list
val merge : t list -> t
val compare : t -> t -> int
val cmon : t -> Cmon.t
end
module Cache (D : DERIVABLE) = struct
type t = {
d: D.t;
mutable tr: t partial_derivative list option;
}
let lift d = {d; tr=None}
let unlift t = t.d
let derive t =
match t.tr with
| Some tr -> tr
| None ->
let dir = D.derive t.d in
let tr = List.map (fun (sg, d) -> (sg, lift d)) dir in
t.tr <- Some tr;
tr
let merge = function
| [x] -> x
| xs -> lift (D.merge (List.map unlift xs))
let compare t1 t2 =
D.compare t1.d t2.d
let cmon t =
Cmon.constructor "Cache" (D.cmon t.d)
end
module Make (D : DERIVABLE) = struct
module DMap = Map.Make(D)
type compilation = {
source: D.t;
(** The derivable object that was compiled *)
continuations: D.t Lr1.map;
* [ continuations ] is the map [ lr1 - > d ' ] of derivations of [ source ]
( obtained by deriving one or more times ) , that applies when the LR
automaton reaches state [ lr1 ] .
Either because [ lr1 ] is the current state or because we reached a
goto transition targeting [ lr1 ] .
[ d ' ] has already been derived by [ lr1 ] . Only non - empty [ d ' ] are kept
in the map .
(obtained by deriving one or more times), that applies when the LR
automaton reaches state [lr1].
Either because [lr1] is the current state or because we reached a
goto transition targeting [lr1].
[d'] has already been derived by [lr1]. Only non-empty [d'] are kept
in the map. *)
domain: Lr1.set;
(** The domain of [continuations], used to speed-up the case where none
of the continuations applies. *)
}
type compilation_cache = compilation DMap.t ref
let make_compilation_cache () = ref DMap.empty
let compile source =
let find_tr lr1 (lr1s, x) =
if IndexSet.mem lr1 lr1s then Some x else None
in
let continuations =
Redgraph.derive
~root:source
~step:(fun d lr1 -> List.find_map (find_tr lr1) (D.derive d))
~join:D.merge
in
{source; continuations; domain = IndexMap.domain continuations}
let compile cache source =
match DMap.find_opt source !cache with
| Some c -> c
| None ->
let result = compile source in
cache := DMap.add source result !cache;
result
let cmon compiled =
IndexMap.fold
(fun lr1 d acc ->
Cmon.tuple [Cmon.constant (Lr1.to_string lr1); D.cmon d] :: acc)
compiled.continuations []
|> List.rev
|> Cmon.list
type t = {
derivations: compilation;
state: Redgraph.State.n index;
lookahead: Terminal.set;
}
type transitions = D.t partial_derivative list * t partial_derivative list
let compare t1 t2 =
let c = compare_index t1.state t2.state in
if c <> 0 then c else
let c = IndexSet.compare t1.lookahead t2.lookahead in
if c <> 0 then c else
D.compare t1.derivations.source t2.derivations.source
let add_abstract_state derivations lookahead sg state xs =
if IndexSet.disjoint (Redgraph.state_reachable state) derivations.domain
then xs
else (sg, {derivations; state; lookahead}) :: xs
let initial derivations =
let add_direct lr1 d xs = (IndexSet.singleton lr1, d) :: xs in
let add_reducible lr1 xs =
add_abstract_state derivations Terminal.all
(IndexSet.singleton lr1) (Redgraph.State.of_lr1 lr1) xs
in
let direct = IndexMap.fold add_direct derivations.continuations [] in
let reducible = index_fold Lr1.n [] add_reducible in
(direct, reducible)
let filter_tr sg1 (sg2, v) =
let sg' = IndexSet.inter sg1 sg2 in
if IndexSet.is_empty sg' then
None
else
Some (sg', v)
let derive t =
let direct = ref [] in
let reducible = ref (
match Redgraph.state_parent t.state with
| None -> []
| Some state ->
add_abstract_state t.derivations Terminal.all Lr1.all state []
)
in
let visit_goto {Redgraph. sources; targets; lookahead} =
let lookahead = IndexSet.inter lookahead t.lookahead in
if not (IndexSet.is_empty lookahead) then
IndexSet.iter begin fun target ->
begin match IndexMap.find_opt target t.derivations.continuations with
| None -> ()
| Some d ->
List.iter
(fun tr -> Option.iter (push direct) (filter_tr sources tr))
(D.derive d)
end;
begin match Redgraph.state_parent (Redgraph.State.of_lr1 target) with
| None -> ()
| Some st ->
reducible :=
add_abstract_state t.derivations lookahead sources st !reducible
end;
end targets;
in
List.iter visit_goto (Redgraph.state_goto_closure t.state);
(!direct, !reducible)
end
end
| null | https://raw.githubusercontent.com/let-def/lrgrep/3f7166b1a3f880f26af0e553460673ba136d484d/src/mid/reduction.ml | ocaml | * The derivable object that was compiled
* The domain of [continuations], used to speed-up the case where none
of the continuations applies. | open Fix.Indexing
open Utils
open Misc
module Make(Redgraph : Sigs.REDGRAPH) :
Sigs.REDUCTION with module Info = Redgraph.Info =
struct
module Info = Redgraph.Info
open Info
module type DERIVABLE = sig
type t
val derive : t -> t partial_derivative list
val merge : t list -> t
val compare : t -> t -> int
val cmon : t -> Cmon.t
end
module Cache (D : DERIVABLE) = struct
type t = {
d: D.t;
mutable tr: t partial_derivative list option;
}
let lift d = {d; tr=None}
let unlift t = t.d
let derive t =
match t.tr with
| Some tr -> tr
| None ->
let dir = D.derive t.d in
let tr = List.map (fun (sg, d) -> (sg, lift d)) dir in
t.tr <- Some tr;
tr
let merge = function
| [x] -> x
| xs -> lift (D.merge (List.map unlift xs))
let compare t1 t2 =
D.compare t1.d t2.d
let cmon t =
Cmon.constructor "Cache" (D.cmon t.d)
end
module Make (D : DERIVABLE) = struct
module DMap = Map.Make(D)
type compilation = {
source: D.t;
continuations: D.t Lr1.map;
* [ continuations ] is the map [ lr1 - > d ' ] of derivations of [ source ]
( obtained by deriving one or more times ) , that applies when the LR
automaton reaches state [ lr1 ] .
Either because [ lr1 ] is the current state or because we reached a
goto transition targeting [ lr1 ] .
[ d ' ] has already been derived by [ lr1 ] . Only non - empty [ d ' ] are kept
in the map .
(obtained by deriving one or more times), that applies when the LR
automaton reaches state [lr1].
Either because [lr1] is the current state or because we reached a
goto transition targeting [lr1].
[d'] has already been derived by [lr1]. Only non-empty [d'] are kept
in the map. *)
domain: Lr1.set;
}
type compilation_cache = compilation DMap.t ref
let make_compilation_cache () = ref DMap.empty
let compile source =
let find_tr lr1 (lr1s, x) =
if IndexSet.mem lr1 lr1s then Some x else None
in
let continuations =
Redgraph.derive
~root:source
~step:(fun d lr1 -> List.find_map (find_tr lr1) (D.derive d))
~join:D.merge
in
{source; continuations; domain = IndexMap.domain continuations}
let compile cache source =
match DMap.find_opt source !cache with
| Some c -> c
| None ->
let result = compile source in
cache := DMap.add source result !cache;
result
let cmon compiled =
IndexMap.fold
(fun lr1 d acc ->
Cmon.tuple [Cmon.constant (Lr1.to_string lr1); D.cmon d] :: acc)
compiled.continuations []
|> List.rev
|> Cmon.list
type t = {
derivations: compilation;
state: Redgraph.State.n index;
lookahead: Terminal.set;
}
type transitions = D.t partial_derivative list * t partial_derivative list
let compare t1 t2 =
let c = compare_index t1.state t2.state in
if c <> 0 then c else
let c = IndexSet.compare t1.lookahead t2.lookahead in
if c <> 0 then c else
D.compare t1.derivations.source t2.derivations.source
let add_abstract_state derivations lookahead sg state xs =
if IndexSet.disjoint (Redgraph.state_reachable state) derivations.domain
then xs
else (sg, {derivations; state; lookahead}) :: xs
let initial derivations =
let add_direct lr1 d xs = (IndexSet.singleton lr1, d) :: xs in
let add_reducible lr1 xs =
add_abstract_state derivations Terminal.all
(IndexSet.singleton lr1) (Redgraph.State.of_lr1 lr1) xs
in
let direct = IndexMap.fold add_direct derivations.continuations [] in
let reducible = index_fold Lr1.n [] add_reducible in
(direct, reducible)
let filter_tr sg1 (sg2, v) =
let sg' = IndexSet.inter sg1 sg2 in
if IndexSet.is_empty sg' then
None
else
Some (sg', v)
let derive t =
let direct = ref [] in
let reducible = ref (
match Redgraph.state_parent t.state with
| None -> []
| Some state ->
add_abstract_state t.derivations Terminal.all Lr1.all state []
)
in
let visit_goto {Redgraph. sources; targets; lookahead} =
let lookahead = IndexSet.inter lookahead t.lookahead in
if not (IndexSet.is_empty lookahead) then
IndexSet.iter begin fun target ->
begin match IndexMap.find_opt target t.derivations.continuations with
| None -> ()
| Some d ->
List.iter
(fun tr -> Option.iter (push direct) (filter_tr sources tr))
(D.derive d)
end;
begin match Redgraph.state_parent (Redgraph.State.of_lr1 target) with
| None -> ()
| Some st ->
reducible :=
add_abstract_state t.derivations lookahead sources st !reducible
end;
end targets;
in
List.iter visit_goto (Redgraph.state_goto_closure t.state);
(!direct, !reducible)
end
end
|
fa8339076f4ca2f9fb377c598cc226e9374386a7ab73257fc18d4a6a9034a198 | informatimago/lisp | csv.lisp | -*- coding : utf-8 -*-
;;;;****************************************************************************
FILE : csv.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
USER - INTERFACE :
;;;;DESCRIPTION
;;;;
;;;; This package reads and writes CSV files.
;;;;
< PJB > < >
MODIFICATIONS
2010 - 05 - 20 < PJB > Corrected csv - parse - record .
2005 - 09 - 01 < PJB > Made use of iso6429 .
2004 - 09 - 06 < PJB > Created .
;;;; See also: #hsublogo
;;;;LEGAL
AGPL3
;;;;
Copyright 2004 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details .
;;;;
You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see </>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COMMON-LISP-USER")
(declaim (declaration also-use-packages))
(declaim (also-use-packages "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ECMA048"))
(defpackage "COM.INFORMATIMAGO.COMMON-LISP.CSV.CSV"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.PEEK-STREAM")
(:export "LOAD-RECORDS" "WRITE-RECORD")
(:import-from "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY" "UNTIL" "WHILE")
(:documentation
"
This package reads and writes CSV files.
License:
AGPL3
Copyright Pascal J. Bourguignon 2003 - 2015
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program.
If not, see </>
"))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.CSV.CSV")
;; -scheme.org/docs/neil/csv.plt/1/0/doc.txt
;; The CSV File Format
;;
* Each record is one line ... but A record separator may consist
;; of a line feed (ASCII/LF=0x0A), or a carriage return and line
;; feed pair (ASCII/CRLF=0x0D 0x0A). ...but: fields may contain
;; embedded line-breaks (see below) so a record may span more than
one line .
;;
* Fields are separated with commas . Example , Doe,120 any
st . ,"Anytown , WW",08123
;;
;; * Leading and trailing space-characters adjacent to comma field
separators are ignored . So , Doe , ... resolves to
" " and " Doe " , etc . Space characters can be spaces , or tabs .
;;
;; * Fields with embedded commas must be delimited with double-quote
characters . In the above example . " Anytown , WW " had to be
;; delimited in double quotes because it had an embedded comma.
;;
;; * Fields that contain double quote characters must be surounded by
;; double-quotes, and the embedded double-quotes must each be
represented by a pair of consecutive double quotes . So ,
" Da Man " Doe would convert to " " " Da Man""",Doe , 120 any
;; st.,...
;;
;; * A field that contains embedded line-breaks must be surounded by
;; double-quotes
;; So:
Field 1 : Conference room 1
Field 2 :
,
Please bring the M. Mathers file for review
;; -J.L.
Field 3 : 10/18/2002
;; ...
;;
;; would convert to:
Conference room 1 , " ,
Please bring the M. Mathers file for review
;; ",10/18/2002,...
;;
;; Note that this is a single CSV record, even though it takes up
more than one line in the CSV file . This works because the line
;; breaks are embedded inside the double quotes of the field.
;;
;; * Fields with leading or trailing spaces must be delimited with
;; double-quote characters. So to preserve the leading and
trailing spaces around the last name above : , " Doe " , ...
;;
;; o Usage note: Some applications will insist on helping you
;; by removing leading and trailing spaces from all fields
;; regardless of whether the CSV used quotes to preserve
them . They may also insist on removing leading zeros from
all fields regardless of whether you need them . One such
application is Excel . :-(
;;
;; * Fields may always be delimited with double quotes.
;; The delimiters will always be discarded.
;;
;; o Implementation note: When importing CSV, do not reach down
;; a layer and try to use the quotes to impart type
;; information to fields. Also, when exporting CSV, you may
;; want to be defensive of apps that improperly try to do
;; this. Though, to be honest, I have not found any examples
;; of applications that try to do this. If you have
;; encountered any apps that attempt to use the quotes to
;; glean type information from CSV files (like assuming
;; quoted fields are strings even if they are numeric),
;; please let me know about it.
;;
* The first record in a CSV file may be a header record containing
;; column (field) names There is no mechanism for automatically
discerning if the first record is a header row , so in the
;; general case, this will have to be provided by an outside
;; process (such as prompting the user). The header row is encoded
;; just like any other CSV record in accordance with the rules
;; above. A header row for the multi-line example above, might be:
;; Location, Notes, "Start Date", ...
;; field-names
;;
;; " --> ""
;; " --> \"
;; " --> empty
;;
~% -- > NL
;; ~% --> \n
;; ~% --> empty
(defgeneric newline (scanner))
(defgeneric scan-newline (scanner ch))
(defgeneric get-token (scanner))
(defgeneric advance (parser))
(defgeneric report-error (parser message &rest args))
(defgeneric csv-parse-file (self))
(defgeneric csv-parse-record (self))
(defun escape-field (field)
(setf field (cond
((null field) "")
((stringp field) field)
(t (format nil "~A" field))))
(if (position (character "\"") field)
(do ((result (make-string (+ (length field)
(count (character "\"") field))))
(i 0 (1+ i))
(j 0))
((>= i (length field)) result)
(setf (char result j) (char field i))
(incf j)
(when (char= (character "\"") (char field i))
(setf (char result j) (char field i))
(incf j)))
field))
(defun write-record (fields &optional (out *standard-output*))
"
DO: write the record FIELDS to the stream OUT (default
*STANDARD-OUTPUT*).
"
(let ((*print-pretty* nil))
(format out "~{\"~A\"~^,~}~%" (mapcar (function escape-field) fields))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Scanner
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; text ::= { any-char-but-coma-new-line-and-dblquote } .
;; quoted-text ::= { any-char-but-coma-new-line-and-dblquote
;; | "\"\"" | "," | CR | LF } .
;; coma
;; new-line (cr, lf, cr-lf)
(defparameter +c+cr+ (code-char #+mocl 13 #-mocl com.informatimago.common-lisp.cesarum.ecma048:cr))
(defparameter +c+lf+ (code-char #+mocl 10 #-mocl com.informatimago.common-lisp.cesarum.ecma048:lf))
(defparameter +newline+ (format nil "~%"))
(defparameter +crlf+ (format nil "~C~C" +c+cr+ +c+lf+))
(defparameter +cr+ (format nil "~C" +c+cr+))
(defparameter +lf+ (format nil "~C" +c+lf+))
(defparameter +spaces+ (format nil " ~C" (code-char #+mocl 9 #-mocl com.informatimago.common-lisp.cesarum.ecma048:ht)))
(defclass scanner ()
((source :type peek-stream
:initarg :source :accessor scanner-source)
(newline :initform nil :type symbol :accessor scanner-newline)
(crcnt :initform 0 :type integer
:accessor scanner-crcnt)
(lfcnt :initform 0 :type integer
:accessor scanner-lfcnt)
(crlfcnt :initform 0 :type integer
:accessor scanner-crlfcnt)
(field-separator
:initarg :field-separator
:initform #\,
:accessor field-separator)
(decimal-point
:initarg :decimal-point
:initform #\.
:accessor decimal-point))
(:documentation "A scanner.
If not set newline is automatically determined from statistics on newlines
found in the source. At the beginning of the file, or when newlines are
inconsistent, a default newline = LF is used. This imports for \ escapes."))
(defun make-scanner (&key
(source *standard-input*)
(field-separator #\,)
(decimal-point #\.))
(make-instance 'scanner
:source (make-instance 'peek-stream :stream source)
:field-separator field-separator
:decimal-point decimal-point))
(defmethod print-object ((self scanner) out)
(format out "#<~A nl=~S cr=~D lf=~D crlf=~D sep=#\\~C dec=#\\~C source=~S>"
(class-name (class-of self))
(scanner-newline self)
(scanner-crcnt self)
(scanner-lfcnt self)
(scanner-crlfcnt self)
(field-separator self)
(decimal-point self)
(scanner-source self))
self)
(defgeneric text-term (scanner))
(defmethod text-term ((scanner scanner))
(format nil "~A~A" (field-separator scanner) +crlf+))
(defmethod newline ((scanner scanner))
"
RETURN: The newline string determined by the heuristic:
{crlfcnt,lfcnt} << crcnt ==> +cr+
{crlfcnt,crcnt} << lfcnt ==> +lf+
{crcnt,lfcnt} << crlfcnt ==> +crlf+
otherwise ==> +lf+
"
(flet ((<< (a b) (< (* 2 a) b))
(small (a) (<= a 2)))
(macrolet
((trans (nl knl fnl k1 f1 k2 f2 &key warn)
`(case (scanner-newline scanner)
((nil)
(setf (scanner-newline scanner) :lf)
+lf+)
((,knl)
,(when warn
`(warn "Newline is perhaps ~A. (~A=~D, ~A=~D, ~A=~D).~%"
',knl ,knl (,fnl scanner)
,k1 (,f1 scanner) ,k2 (,f2 scanner)))
,nl)
(otherwise
(warn "Newline changed from ~A to ~A (~A=~D, ~A=~D, ~A=~D).~%"
(scanner-newline scanner) ,knl
,knl (,fnl scanner) ,k1 (,f1 scanner) ,k2 (,f2 scanner))
(setf (scanner-newline scanner) ,knl)
,nl))))
(cond
((and (small (scanner-crcnt scanner))
(small (scanner-lfcnt scanner))
(small (scanner-crlfcnt scanner))) +lf+)
((and (<< (scanner-crcnt scanner) (scanner-lfcnt scanner))
(<< (scanner-crlfcnt scanner) (scanner-lfcnt scanner)))
(trans +lf+
:lf scanner-lfcnt :cr scanner-crcnt :crlf scanner-crlfcnt))
((and (<< (scanner-lfcnt scanner) (scanner-crcnt scanner))
(<< (scanner-crlfcnt scanner) (scanner-crcnt scanner)))
(trans +cr+
:cr scanner-crcnt :lf scanner-lfcnt :crlf scanner-crlfcnt))
((and (<< (scanner-lfcnt scanner) (scanner-crlfcnt scanner))
(<< (scanner-crcnt scanner) (scanner-crlfcnt scanner)))
(trans +crlf+
:crlf scanner-crlfcnt :lf scanner-lfcnt :cr scanner-crcnt))
((and (< (scanner-crcnt scanner) (scanner-lfcnt scanner))
(< (scanner-crlfcnt scanner) (scanner-lfcnt scanner)))
(trans +lf+
:lf scanner-lfcnt :cr scanner-crcnt :crlf scanner-crlfcnt
:warn t))
((and (< (scanner-lfcnt scanner) (scanner-crcnt scanner))
(< (scanner-crlfcnt scanner) (scanner-crcnt scanner)))
(trans +cr+
:cr scanner-crcnt :lf scanner-lfcnt :crlf scanner-crlfcnt
:warn t))
((and (< (scanner-lfcnt scanner) (scanner-crlfcnt scanner))
(< (scanner-crcnt scanner) (scanner-crlfcnt scanner)))
(trans +crlf+
:crlf scanner-crlfcnt :lf scanner-lfcnt :cr scanner-crcnt
:warn t))
(t
(warn "Newline is completely random! (~A=~D, ~A=~D, ~A=~D).~%"
:lf (scanner-lfcnt scanner)
:cr (scanner-crcnt scanner)
:crlf (scanner-crlfcnt scanner))
+lf+)))))
(defmethod scan-newline ((scanner scanner) (ch character))
(cond
((char= +c+cr+ ch)
(if (char= +c+lf+ (nextchar (scanner-source scanner)))
(progn
(getchar (scanner-source scanner))
(incf (scanner-crlfcnt scanner)))
(incf (scanner-crcnt scanner)))
t)
((char= +c+lf+ ch)
(incf (scanner-lfcnt scanner))
t)
(t
nil)))
(defmethod get-token ((scanner scanner))
"
NOTE: Multiline values are returned as a list of lines.
BUG: Line termination should be determined once for the whole file.
'\' cr lf could mean cr, end of line, or newline
"
(macrolet
((getch () `(getchar (scanner-source scanner)))
(nextch () `(nextchar (scanner-source scanner)))
(eat-escape
(ch value)
`(if (nextch)
(progn
(setf ,ch (getch))
(if (char= +c+cr+ ,ch)
(if (eq +crlf+ (newline scanner))
(if (char= +c+lf+ (nextch))
(progn
(vector-push-extend +c+cr+ ,value)
(vector-push-extend (getch) ,value))
(vector-push-extend +c+cr+ ,value))
(vector-push-extend +c+cr+ ,value))
(vector-push-extend ,ch ,value)))
(error "Found a '\\' at end of file."))))
(let ((ch (getch)))
(while (and ch (position ch +spaces+) (setf ch (getch))))
(cond
((null ch) (values :eof nil))
((char= ch (field-separator scanner)) (values :coma ch))
((char= ch (character "\""))
;; quoted-text ::= { any-char-but-coma-new-line-and-dblquote
;; | "\"\"" | "," | CR | LF } .
(let ((lines '())
(value (make-array '(16) :fill-pointer 0 :adjustable t
:element-type 'character)))
(do* ((ch (getch) (or eos (getch)))
(eos (null ch) (or eos (null ch))))
(eos
(if lines
(progn (push value lines)
(values :quoted-text (nreverse lines)))
(values :quoted-text value)))
(cond
((char= ch (character "\""))
(if (char= ch (nextch))
(progn (vector-push-extend ch value)
(getch))
(setf eos t)))
((char= ch (character "\\"))
(eat-escape ch value))
((scan-newline scanner ch)
(push value lines)
(setf value (make-array '(16) :fill-pointer 0 :adjustable t
:element-type 'character)))
(t (vector-push-extend ch value))))))
((scan-newline scanner ch)
(values :newline (newline scanner)))
(t
;; text ::= { any-char-but-coma-new-line-and-dblquote } .
(let ((value (make-array '(16) :fill-pointer 0 :adjustable t
:element-type 'character)))
(until (or (null ch) (position ch (text-term scanner)))
(if (char= ch (character "\\"))
(eat-escape ch value)
(vector-push-extend ch value))
(setf ch (getch)))
(when ch (ungetchar (scanner-source scanner) ch))
(values :text (string-trim +spaces+ value))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Parser
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass parser ()
((scanner :accessor parser-scanner :initform nil :initarg :scanner)
(token :accessor parser-token :initform nil)
(value :accessor parser-value :initform nil)
(next-token :accessor parser-next-token :initform nil)
(next-value :accessor parser-next-value :initform nil))
(:documentation "A parser."))
(defmethod print-object ((self parser) out)
(format out "#<~A :scanner ~S :token (~S ~S) :next (~S ~S)>"
(class-name (class-of self)) (parser-scanner self)
(parser-token self) (parser-value self)
(parser-next-token self) (parser-next-value self))
self)
(defmethod advance ((parser parser))
(multiple-value-bind (tok val) (get-token (parser-scanner parser))
(setf (parser-token parser) (parser-next-token parser)
(parser-value parser) (parser-next-value parser)
(parser-next-token parser) tok
(parser-next-value parser) val))
parser)
(defmethod report-error ((parser parser) message &rest arguments)
(error "~A; (~S ~S) (~S ~S)" (apply (function format) nil message arguments)
(parser-token parser)
(parser-value parser)
(parser-next-token parser)
(parser-next-value parser)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; csv-parser
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; file ::= { record newline } .
;; record ::= field { "," field } .
;; field ::= | data .
;; data ::= text | "\"" quoted-text "\"" .
(defclass csv-parser (parser)
((if-end-of-file-in-last-record
:initarg :if-end-of-file-in-last-record
:initform :error
:type (member :error :ignore)
:accessor if-end-of-file-in-last-record)))
(defmethod csv-parse-file ((self csv-parser))
;; file ::= { record newline } .
(while (null (parser-token self)) (advance self))
(let ((records '()))
(until (eq :eof (parser-token self))
(let ((record (csv-parse-record self)))
(if (eq :newline (parser-token self))
(advance self)
(if (eq :eof (parser-token self))
(ecase (if-end-of-file-in-last-record self)
((:error) (report-error
self "Last record ends with end-of-file instead of end-of-line."))
((:ignore) (advance self)))
(report-error
self
"INTERNAL: csv-parse-record left a token than end-of-line.")))
(when record (push record records))))
(nreverse records)))
(defmethod csv-parse-record ((self csv-parser))
;; record ::= field { "," field } .
;; field ::= | data .
;; data ::= text | "\"" quoted-text "\"" .
(let ((fields '()))
(loop
:initially (case (parser-token self)
((:coma)
(push nil fields))
((:quoted-text :text)
(push (parser-value self) fields)
(advance self))
(otherwise
(report-error self "A record should start with a field or a coma, not ~S ~S."
(parser-token self) (parser-value self))))
:while (eq (parser-token self) :coma)
:do (advance self)
:do (case (parser-token self)
((:coma)
(push nil fields))
((:quoted-text :text)
(push (parser-value self) fields)
(advance self))
(otherwise
(return-from csv-parse-record (nreverse fields))))
:finally (if (member (parser-token self) '(:quoted-text :text))
(report-error self "Missing a coma between two fields ~S and ~S."
(car fields) (parser-value self))
(return-from csv-parse-record (nreverse fields))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Reading CVS file
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun load-records (path &key
(external-format :default)
(element-type 'character)
(if-end-of-file-in-last-record :error)
(field-separator #\,)
(decimal-point #\.))
"
RETURN: A list of rows, each row being a list of cells.
PATH: A pathname designator of the CSV file to read.
EXTERNAL-FORMAT: The external format.
ELEMENT-TYPE: The type of element of the file (should be
CHARACTER or a subtype of CHARACTER).
IF-END-OF-FILE-IN-LAST-RECORD: :ERROR or :IGNORE.
default : # \ ,
DECIMAL-POINT: The decimal point; default: #\.
"
(with-open-file (input path :direction :input
:external-format external-format
:element-type element-type)
(csv-parse-file (make-instance 'csv-parser
:scanner (make-scanner :source input
:field-separator field-separator
:decimal-point decimal-point)
:if-end-of-file-in-last-record if-end-of-file-in-last-record))))
;;;; THE END ;;;;
| null | https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/common-lisp/csv/csv.lisp | lisp | ****************************************************************************
LANGUAGE: Common-Lisp
SYSTEM: Common-Lisp
DESCRIPTION
This package reads and writes CSV files.
See also: #hsublogo
LEGAL
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see </>
****************************************************************************
without even the implied warranty of
-scheme.org/docs/neil/csv.plt/1/0/doc.txt
The CSV File Format
of a line feed (ASCII/LF=0x0A), or a carriage return and line
feed pair (ASCII/CRLF=0x0D 0x0A). ...but: fields may contain
embedded line-breaks (see below) so a record may span more than
* Leading and trailing space-characters adjacent to comma field
* Fields with embedded commas must be delimited with double-quote
delimited in double quotes because it had an embedded comma.
* Fields that contain double quote characters must be surounded by
double-quotes, and the embedded double-quotes must each be
st.,...
* A field that contains embedded line-breaks must be surounded by
double-quotes
So:
-J.L.
...
would convert to:
",10/18/2002,...
Note that this is a single CSV record, even though it takes up
breaks are embedded inside the double quotes of the field.
* Fields with leading or trailing spaces must be delimited with
double-quote characters. So to preserve the leading and
o Usage note: Some applications will insist on helping you
by removing leading and trailing spaces from all fields
regardless of whether the CSV used quotes to preserve
* Fields may always be delimited with double quotes.
The delimiters will always be discarded.
o Implementation note: When importing CSV, do not reach down
a layer and try to use the quotes to impart type
information to fields. Also, when exporting CSV, you may
want to be defensive of apps that improperly try to do
this. Though, to be honest, I have not found any examples
of applications that try to do this. If you have
encountered any apps that attempt to use the quotes to
glean type information from CSV files (like assuming
quoted fields are strings even if they are numeric),
please let me know about it.
column (field) names There is no mechanism for automatically
general case, this will have to be provided by an outside
process (such as prompting the user). The header row is encoded
just like any other CSV record in accordance with the rules
above. A header row for the multi-line example above, might be:
Location, Notes, "Start Date", ...
field-names
" --> ""
" --> \"
" --> empty
~% --> \n
~% --> empty
text ::= { any-char-but-coma-new-line-and-dblquote } .
quoted-text ::= { any-char-but-coma-new-line-and-dblquote
| "\"\"" | "," | CR | LF } .
coma
new-line (cr, lf, cr-lf)
quoted-text ::= { any-char-but-coma-new-line-and-dblquote
| "\"\"" | "," | CR | LF } .
text ::= { any-char-but-coma-new-line-and-dblquote } .
csv-parser
file ::= { record newline } .
record ::= field { "," field } .
field ::= | data .
data ::= text | "\"" quoted-text "\"" .
file ::= { record newline } .
record ::= field { "," field } .
field ::= | data .
data ::= text | "\"" quoted-text "\"" .
Reading CVS file
default: #\.
THE END ;;;; | -*- coding : utf-8 -*-
FILE : csv.lisp
USER - INTERFACE :
< PJB > < >
MODIFICATIONS
2010 - 05 - 20 < PJB > Corrected csv - parse - record .
2005 - 09 - 01 < PJB > Made use of iso6429 .
2004 - 09 - 06 < PJB > Created .
AGPL3
Copyright 2004 - 2016
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
GNU Affero General Public License for more details .
You should have received a copy of the GNU Affero General Public License
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COMMON-LISP-USER")
(declaim (declaration also-use-packages))
(declaim (also-use-packages "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ECMA048"))
(defpackage "COM.INFORMATIMAGO.COMMON-LISP.CSV.CSV"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.PEEK-STREAM")
(:export "LOAD-RECORDS" "WRITE-RECORD")
(:import-from "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY" "UNTIL" "WHILE")
(:documentation
"
This package reads and writes CSV files.
License:
AGPL3
Copyright Pascal J. Bourguignon 2003 - 2015
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program.
If not, see </>
"))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.CSV.CSV")
* Each record is one line ... but A record separator may consist
one line .
* Fields are separated with commas . Example , Doe,120 any
st . ,"Anytown , WW",08123
separators are ignored . So , Doe , ... resolves to
" " and " Doe " , etc . Space characters can be spaces , or tabs .
characters . In the above example . " Anytown , WW " had to be
represented by a pair of consecutive double quotes . So ,
" Da Man " Doe would convert to " " " Da Man""",Doe , 120 any
Field 1 : Conference room 1
Field 2 :
,
Please bring the M. Mathers file for review
Field 3 : 10/18/2002
Conference room 1 , " ,
Please bring the M. Mathers file for review
more than one line in the CSV file . This works because the line
trailing spaces around the last name above : , " Doe " , ...
them . They may also insist on removing leading zeros from
all fields regardless of whether you need them . One such
application is Excel . :-(
* The first record in a CSV file may be a header record containing
discerning if the first record is a header row , so in the
~% -- > NL
(defgeneric newline (scanner))
(defgeneric scan-newline (scanner ch))
(defgeneric get-token (scanner))
(defgeneric advance (parser))
(defgeneric report-error (parser message &rest args))
(defgeneric csv-parse-file (self))
(defgeneric csv-parse-record (self))
(defun escape-field (field)
(setf field (cond
((null field) "")
((stringp field) field)
(t (format nil "~A" field))))
(if (position (character "\"") field)
(do ((result (make-string (+ (length field)
(count (character "\"") field))))
(i 0 (1+ i))
(j 0))
((>= i (length field)) result)
(setf (char result j) (char field i))
(incf j)
(when (char= (character "\"") (char field i))
(setf (char result j) (char field i))
(incf j)))
field))
(defun write-record (fields &optional (out *standard-output*))
"
DO: write the record FIELDS to the stream OUT (default
*STANDARD-OUTPUT*).
"
(let ((*print-pretty* nil))
(format out "~{\"~A\"~^,~}~%" (mapcar (function escape-field) fields))))
Scanner
(defparameter +c+cr+ (code-char #+mocl 13 #-mocl com.informatimago.common-lisp.cesarum.ecma048:cr))
(defparameter +c+lf+ (code-char #+mocl 10 #-mocl com.informatimago.common-lisp.cesarum.ecma048:lf))
(defparameter +newline+ (format nil "~%"))
(defparameter +crlf+ (format nil "~C~C" +c+cr+ +c+lf+))
(defparameter +cr+ (format nil "~C" +c+cr+))
(defparameter +lf+ (format nil "~C" +c+lf+))
(defparameter +spaces+ (format nil " ~C" (code-char #+mocl 9 #-mocl com.informatimago.common-lisp.cesarum.ecma048:ht)))
(defclass scanner ()
((source :type peek-stream
:initarg :source :accessor scanner-source)
(newline :initform nil :type symbol :accessor scanner-newline)
(crcnt :initform 0 :type integer
:accessor scanner-crcnt)
(lfcnt :initform 0 :type integer
:accessor scanner-lfcnt)
(crlfcnt :initform 0 :type integer
:accessor scanner-crlfcnt)
(field-separator
:initarg :field-separator
:initform #\,
:accessor field-separator)
(decimal-point
:initarg :decimal-point
:initform #\.
:accessor decimal-point))
(:documentation "A scanner.
If not set newline is automatically determined from statistics on newlines
found in the source. At the beginning of the file, or when newlines are
inconsistent, a default newline = LF is used. This imports for \ escapes."))
(defun make-scanner (&key
(source *standard-input*)
(field-separator #\,)
(decimal-point #\.))
(make-instance 'scanner
:source (make-instance 'peek-stream :stream source)
:field-separator field-separator
:decimal-point decimal-point))
(defmethod print-object ((self scanner) out)
(format out "#<~A nl=~S cr=~D lf=~D crlf=~D sep=#\\~C dec=#\\~C source=~S>"
(class-name (class-of self))
(scanner-newline self)
(scanner-crcnt self)
(scanner-lfcnt self)
(scanner-crlfcnt self)
(field-separator self)
(decimal-point self)
(scanner-source self))
self)
(defgeneric text-term (scanner))
(defmethod text-term ((scanner scanner))
(format nil "~A~A" (field-separator scanner) +crlf+))
(defmethod newline ((scanner scanner))
"
RETURN: The newline string determined by the heuristic:
{crlfcnt,lfcnt} << crcnt ==> +cr+
{crlfcnt,crcnt} << lfcnt ==> +lf+
{crcnt,lfcnt} << crlfcnt ==> +crlf+
otherwise ==> +lf+
"
(flet ((<< (a b) (< (* 2 a) b))
(small (a) (<= a 2)))
(macrolet
((trans (nl knl fnl k1 f1 k2 f2 &key warn)
`(case (scanner-newline scanner)
((nil)
(setf (scanner-newline scanner) :lf)
+lf+)
((,knl)
,(when warn
`(warn "Newline is perhaps ~A. (~A=~D, ~A=~D, ~A=~D).~%"
',knl ,knl (,fnl scanner)
,k1 (,f1 scanner) ,k2 (,f2 scanner)))
,nl)
(otherwise
(warn "Newline changed from ~A to ~A (~A=~D, ~A=~D, ~A=~D).~%"
(scanner-newline scanner) ,knl
,knl (,fnl scanner) ,k1 (,f1 scanner) ,k2 (,f2 scanner))
(setf (scanner-newline scanner) ,knl)
,nl))))
(cond
((and (small (scanner-crcnt scanner))
(small (scanner-lfcnt scanner))
(small (scanner-crlfcnt scanner))) +lf+)
((and (<< (scanner-crcnt scanner) (scanner-lfcnt scanner))
(<< (scanner-crlfcnt scanner) (scanner-lfcnt scanner)))
(trans +lf+
:lf scanner-lfcnt :cr scanner-crcnt :crlf scanner-crlfcnt))
((and (<< (scanner-lfcnt scanner) (scanner-crcnt scanner))
(<< (scanner-crlfcnt scanner) (scanner-crcnt scanner)))
(trans +cr+
:cr scanner-crcnt :lf scanner-lfcnt :crlf scanner-crlfcnt))
((and (<< (scanner-lfcnt scanner) (scanner-crlfcnt scanner))
(<< (scanner-crcnt scanner) (scanner-crlfcnt scanner)))
(trans +crlf+
:crlf scanner-crlfcnt :lf scanner-lfcnt :cr scanner-crcnt))
((and (< (scanner-crcnt scanner) (scanner-lfcnt scanner))
(< (scanner-crlfcnt scanner) (scanner-lfcnt scanner)))
(trans +lf+
:lf scanner-lfcnt :cr scanner-crcnt :crlf scanner-crlfcnt
:warn t))
((and (< (scanner-lfcnt scanner) (scanner-crcnt scanner))
(< (scanner-crlfcnt scanner) (scanner-crcnt scanner)))
(trans +cr+
:cr scanner-crcnt :lf scanner-lfcnt :crlf scanner-crlfcnt
:warn t))
((and (< (scanner-lfcnt scanner) (scanner-crlfcnt scanner))
(< (scanner-crcnt scanner) (scanner-crlfcnt scanner)))
(trans +crlf+
:crlf scanner-crlfcnt :lf scanner-lfcnt :cr scanner-crcnt
:warn t))
(t
(warn "Newline is completely random! (~A=~D, ~A=~D, ~A=~D).~%"
:lf (scanner-lfcnt scanner)
:cr (scanner-crcnt scanner)
:crlf (scanner-crlfcnt scanner))
+lf+)))))
(defmethod scan-newline ((scanner scanner) (ch character))
(cond
((char= +c+cr+ ch)
(if (char= +c+lf+ (nextchar (scanner-source scanner)))
(progn
(getchar (scanner-source scanner))
(incf (scanner-crlfcnt scanner)))
(incf (scanner-crcnt scanner)))
t)
((char= +c+lf+ ch)
(incf (scanner-lfcnt scanner))
t)
(t
nil)))
(defmethod get-token ((scanner scanner))
"
NOTE: Multiline values are returned as a list of lines.
BUG: Line termination should be determined once for the whole file.
'\' cr lf could mean cr, end of line, or newline
"
(macrolet
((getch () `(getchar (scanner-source scanner)))
(nextch () `(nextchar (scanner-source scanner)))
(eat-escape
(ch value)
`(if (nextch)
(progn
(setf ,ch (getch))
(if (char= +c+cr+ ,ch)
(if (eq +crlf+ (newline scanner))
(if (char= +c+lf+ (nextch))
(progn
(vector-push-extend +c+cr+ ,value)
(vector-push-extend (getch) ,value))
(vector-push-extend +c+cr+ ,value))
(vector-push-extend +c+cr+ ,value))
(vector-push-extend ,ch ,value)))
(error "Found a '\\' at end of file."))))
(let ((ch (getch)))
(while (and ch (position ch +spaces+) (setf ch (getch))))
(cond
((null ch) (values :eof nil))
((char= ch (field-separator scanner)) (values :coma ch))
((char= ch (character "\""))
(let ((lines '())
(value (make-array '(16) :fill-pointer 0 :adjustable t
:element-type 'character)))
(do* ((ch (getch) (or eos (getch)))
(eos (null ch) (or eos (null ch))))
(eos
(if lines
(progn (push value lines)
(values :quoted-text (nreverse lines)))
(values :quoted-text value)))
(cond
((char= ch (character "\""))
(if (char= ch (nextch))
(progn (vector-push-extend ch value)
(getch))
(setf eos t)))
((char= ch (character "\\"))
(eat-escape ch value))
((scan-newline scanner ch)
(push value lines)
(setf value (make-array '(16) :fill-pointer 0 :adjustable t
:element-type 'character)))
(t (vector-push-extend ch value))))))
((scan-newline scanner ch)
(values :newline (newline scanner)))
(t
(let ((value (make-array '(16) :fill-pointer 0 :adjustable t
:element-type 'character)))
(until (or (null ch) (position ch (text-term scanner)))
(if (char= ch (character "\\"))
(eat-escape ch value)
(vector-push-extend ch value))
(setf ch (getch)))
(when ch (ungetchar (scanner-source scanner) ch))
(values :text (string-trim +spaces+ value))))))))
Parser
(defclass parser ()
((scanner :accessor parser-scanner :initform nil :initarg :scanner)
(token :accessor parser-token :initform nil)
(value :accessor parser-value :initform nil)
(next-token :accessor parser-next-token :initform nil)
(next-value :accessor parser-next-value :initform nil))
(:documentation "A parser."))
(defmethod print-object ((self parser) out)
(format out "#<~A :scanner ~S :token (~S ~S) :next (~S ~S)>"
(class-name (class-of self)) (parser-scanner self)
(parser-token self) (parser-value self)
(parser-next-token self) (parser-next-value self))
self)
(defmethod advance ((parser parser))
(multiple-value-bind (tok val) (get-token (parser-scanner parser))
(setf (parser-token parser) (parser-next-token parser)
(parser-value parser) (parser-next-value parser)
(parser-next-token parser) tok
(parser-next-value parser) val))
parser)
(defmethod report-error ((parser parser) message &rest arguments)
(error "~A; (~S ~S) (~S ~S)" (apply (function format) nil message arguments)
(parser-token parser)
(parser-value parser)
(parser-next-token parser)
(parser-next-value parser)))
(defclass csv-parser (parser)
((if-end-of-file-in-last-record
:initarg :if-end-of-file-in-last-record
:initform :error
:type (member :error :ignore)
:accessor if-end-of-file-in-last-record)))
(defmethod csv-parse-file ((self csv-parser))
(while (null (parser-token self)) (advance self))
(let ((records '()))
(until (eq :eof (parser-token self))
(let ((record (csv-parse-record self)))
(if (eq :newline (parser-token self))
(advance self)
(if (eq :eof (parser-token self))
(ecase (if-end-of-file-in-last-record self)
((:error) (report-error
self "Last record ends with end-of-file instead of end-of-line."))
((:ignore) (advance self)))
(report-error
self
"INTERNAL: csv-parse-record left a token than end-of-line.")))
(when record (push record records))))
(nreverse records)))
(defmethod csv-parse-record ((self csv-parser))
(let ((fields '()))
(loop
:initially (case (parser-token self)
((:coma)
(push nil fields))
((:quoted-text :text)
(push (parser-value self) fields)
(advance self))
(otherwise
(report-error self "A record should start with a field or a coma, not ~S ~S."
(parser-token self) (parser-value self))))
:while (eq (parser-token self) :coma)
:do (advance self)
:do (case (parser-token self)
((:coma)
(push nil fields))
((:quoted-text :text)
(push (parser-value self) fields)
(advance self))
(otherwise
(return-from csv-parse-record (nreverse fields))))
:finally (if (member (parser-token self) '(:quoted-text :text))
(report-error self "Missing a coma between two fields ~S and ~S."
(car fields) (parser-value self))
(return-from csv-parse-record (nreverse fields))))))
(defun load-records (path &key
(external-format :default)
(element-type 'character)
(if-end-of-file-in-last-record :error)
(field-separator #\,)
(decimal-point #\.))
"
RETURN: A list of rows, each row being a list of cells.
PATH: A pathname designator of the CSV file to read.
EXTERNAL-FORMAT: The external format.
ELEMENT-TYPE: The type of element of the file (should be
CHARACTER or a subtype of CHARACTER).
IF-END-OF-FILE-IN-LAST-RECORD: :ERROR or :IGNORE.
default : # \ ,
"
(with-open-file (input path :direction :input
:external-format external-format
:element-type element-type)
(csv-parse-file (make-instance 'csv-parser
:scanner (make-scanner :source input
:field-separator field-separator
:decimal-point decimal-point)
:if-end-of-file-in-last-record if-end-of-file-in-last-record))))
|
7ff7d803eec9a96b45a2aeafc573add273ca58cafccea6517f0c1e3c393b2ebf | heroku/logplex | logplex_api_v3_SUITE.erl | -module(logplex_api_v3_SUITE).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-compile(export_all).
all() ->
[{group, channels}
, {group, drains}
, {group, tokens}
, {group, channel_logs}
, {group, sessions}
, {group, healthcheck}
].
groups() ->
[{channels,
[channel_service_unavailable
, channel_method_not_allowed
, channel_not_authorized
, create_channel_without_tokens
, create_channel_with_tokens
, update_channel_with_tokens
, update_channel_and_remove_some_tokens
, update_channel_and_nuke_tokens
, get_channel_without_tokens
, get_channel_with_tokens
, delete_channel
, reject_invalid_channel_payload
, retain_flags_on_channel_update
]},
{drains,
[drains_service_unavailable
, drains_not_authorized
, reserve_drain_without_drainurl
, reserve_drain_with_drainurl
, update_drain_url
, cannot_update_invalid_drain_url
, get_channel_with_drain
, cannot_add_duplicate_drain
, cannot_add_more_drains
, cannot_update_non_existing_drain
, cannot_create_drain_for_non_existing_channel
, cannot_update_drain_for_non_existing_channel
, delete_existing_drain
, cannot_delete_non_existing_drain
]},
{tokens,
[tokens_service_unavailable
, tokens_not_authorized
, create_new_token
, cannot_create_token_without_name
, cannot_create_token_for_non_existing_channel
]},
{channel_logs,
[channel_logs_service_unavailable
, channel_logs_not_authorized
, fetch_channel_logs
, channel_logs_format
, channel_logs_bad_syslog_message
, channel_logs_with_num_query_string
, channel_logs_with_malformed_query_string
]},
{sessions,
[sessions_service_unavailable
, create_session_for_existing_channel
, cannot_create_session_for_non_existing_channel
]},
{healthcheck,
[healthy,
unhealthy
]}
].
%% -----------------------------------------------------------------------------
%% setup functions
%% -----------------------------------------------------------------------------
init_per_suite(Config) ->
set_os_vars(),
ok = logplex_app:a_start(logplex, temporary),
[{api_v3_url, logplex_app:config(http_v3_url)}
, {auth, "Basic " ++ logplex_app:config(auth_key)}
| Config].
end_per_suite(Config) ->
application:stop(logplex),
Config.
init_per_testcase(Testcase , Config)
when Testcase == channel_service_unavailable;
Testcase == drains_service_unavailable;
Testcase == tokens_service_unavailable;
Testcase == channel_logs_service_unavailable ->
logplex_api_v3:set_status(disabled),
Config;
init_per_testcase(Testcase , Config)
when Testcase == channel_not_authorized;
Testcase == drains_not_authorized;
Testcase == tokens_not_authorized;
Testcase == channel_logs_not_authorized ->
[{auth, "Basic bad-token"}
| Config];
init_per_testcase(cannot_add_more_drains, Config) ->
OldLimit = logplex_app:config(max_drains_per_channel),
logplex_app:set_config(max_drains_per_channel, 1),
[{old_max_drains_per_channel, OldLimit}
| Config];
init_per_testcase(unhealthy, Config) ->
logplex_app:set_config(nsync_loaded, false),
Config;
init_per_testcase(sessions_service_unavailable, Config) ->
logplex_app:set_config(deny_tail_sessions, true),
Config;
init_per_testcase(_, Config) ->
Config.
end_per_testcase(Testcase, Config)
when Testcase == channel_service_unavailable;
Testcase == drains_service_unavailable;
Testcase == tokens_service_unavailable;
Testcase == channel_logs_service_unavailable ->
logplex_api_v3:set_status(normal),
Config;
end_per_testcase(cannot_add_more_drains, Config) ->
OldLimit = ?config(old_max_drains_per_channel, Config),
logplex_app:set_config(max_drains_per_channel, OldLimit),
Config;
end_per_testcase(unhealthy, Config) ->
logplex_app:set_config(nsync_loaded, true),
Config;
end_per_testcase(sessions_service_unavailable, Config) ->
logplex_app:set_config(deny_tail_sessions, false),
Config;
end_per_testcase(_, Config) ->
Config.
%% -----------------------------------------------------------------------------
%% channels tests
%% -----------------------------------------------------------------------------
channel_service_unavailable(Config) ->
Channel = new_channel(),
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel,
Props = logplex_api_SUITE:request(get, Url, []),
?assertEqual(503, proplists:get_value(status_code, Props)),
?assertEqual("Service Unavailable", proplists:get_value(http_reason, Props)),
Config.
channel_method_not_allowed(Config) ->
Channel = new_channel(),
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel,
[begin
Props = logplex_api_SUITE:request(Method, Url, []),
?assertEqual(405, proplists:get_value(status_code, Props)),
?assertEqual("Method Not Allowed", proplists:get_value(http_reason, Props))
end || Method <- [post, head, options]],
Config.
channel_not_authorized(Config) ->
Channel = new_channel(),
Props = get_channel(Channel, Config),
?assertEqual(401, proplists:get_value(status_code, Props)),
?assertEqual("Unauthorized", proplists:get_value(http_reason, Props)),
Config.
create_channel_without_tokens(Config) ->
Channel = new_channel(),
Props = put_channel(Channel, [], Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
?assertMatch(Channel, binary_to_list(maps:get(<<"channel">>, Resp))),
?assertEqual(201, proplists:get_value(status_code, Props)),
?assertEqual("Created", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
[{channel, Channel} | Config].
create_channel_with_tokens(Config) ->
Channel = new_channel(),
Tokens = new_tokens(),
Props = put_channel(Channel, Tokens, Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
ReceivedTokens = maps:to_list(maps:get(<<"tokens">>, Resp)),
assert_tokens(Tokens, ReceivedTokens),
?assertMatch(Channel, binary_to_list(maps:get(<<"channel">>, Resp))),
?assertEqual(201, proplists:get_value(status_code, Props)),
?assertEqual("Created", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
[{channel, Channel}
, {tokens, ReceivedTokens}
| Config].
update_channel_with_tokens(Config0) ->
Config = create_channel_without_tokens(Config0),
Channel = ?config(channel, Config),
Tokens = new_tokens(),
Props = put_channel(Channel, Tokens, Config),
ct:pal("put channel resp: ~p~n", [Props]),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
ReceivedTokens = maps:to_list(maps:get(<<"tokens">>, Resp)),
assert_tokens(Tokens, ReceivedTokens),
?assertMatch(Channel, binary_to_list(maps:get(<<"channel">>, Resp))),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
[{tokens, ReceivedTokens} | Config].
update_channel_and_remove_some_tokens(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
Tokens = lists:nthtail(2, ?config(tokens, Config)),
Props = put_channel(Channel, Tokens, Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
ReceivedTokens = maps:to_list(maps:get(<<"tokens">>, Resp)),
assert_tokens(Tokens, ReceivedTokens),
?assertMatch(Channel, binary_to_list(maps:get(<<"channel">>, Resp))),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
[{tokens, ReceivedTokens} | Config].
update_channel_and_nuke_tokens(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
Props = put_channel(Channel, [], Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
?assertMatch(Channel, binary_to_list(maps:get(<<"channel">>, Resp))),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
?assert(not maps:is_key(<<"tokens">>, Resp)),
Config.
get_channel_without_tokens(Config0) ->
Config = create_channel_without_tokens(Config0),
Channel = ?config(channel, Config),
Props = get_channel(Channel, Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
?assertMatch(Channel, binary_to_list(maps:get(<<"channel">>, Resp))),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
get_channel_with_tokens(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
Tokens = ?config(tokens, Config),
Props = get_channel(Channel, Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
ReceivedTokens = maps:to_list(maps:get(<<"tokens">>, Resp)),
assert_tokens(Tokens, ReceivedTokens),
?assertMatch(Channel, binary_to_list(maps:get(<<"channel">>, Resp))),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
delete_channel(Config0) ->
Config = create_channel_without_tokens(Config0),
Channel = ?config(channel, Config),
Props = delete_channel(Channel, Config),
ct:pal("delete channel resp: ~p~n", [Props]),
?assertEqual(204, proplists:get_value(status_code, Props)),
?assertEqual("No Content", proplists:get_value(http_reason, Props)).
reject_invalid_channel_payload(Config) ->
Channel = new_channel(),
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel,
Headers = [{"Authorization", ?config(auth, Config)}],
JSON = jsx:encode([<<"asdf">>, 123, [<<"test">>]]),
Opts = [{headers, Headers}, {body, JSON}, {timeout, timer:seconds(10)}],
Props = logplex_api_SUITE:put_(Url, Opts),
Body = proplists:get_value(body, Props),
RespHeaders = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
?assertEqual(<<"invalid payload">>, maps:get(<<"error">>, Resp)),
?assertEqual(400, proplists:get_value(status_code, Props)),
?assertEqual("Bad Request", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", RespHeaders)),
?assert(is_list(proplists:get_value("request-id", RespHeaders))),
Config.
retain_flags_on_channel_update(Config0) ->
Config = create_channel_without_tokens(Config0),
Channel = ?config(channel, Config),
ChanRec = logplex_channel:poll(list_to_binary(Channel), timer:seconds(1)),
ChanRecWithFlag = logplex_channel:set_flag(no_redis, ChanRec),
?assertEqual(ok, logplex_channel:store(ChanRecWithFlag)),
Props = put_channel(Channel, [], Config),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual(ChanRecWithFlag, logplex_channel:poll(list_to_binary(Channel), timer:seconds(1))),
Config.
%% -----------------------------------------------------------------------------
%% drains tests
%% -----------------------------------------------------------------------------
drains_service_unavailable(Config) ->
Channel = new_channel(),
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/drains",
Props = logplex_api_SUITE:post( Url, []),
?assertEqual(503, proplists:get_value(status_code, Props)),
?assertEqual("Service Unavailable", proplists:get_value(http_reason, Props)),
Config.
drains_not_authorized(Config) ->
Channel = new_channel(),
Props = create_drain(Channel, undefined, Config),
?assertEqual(401, proplists:get_value(status_code, Props)),
?assertEqual("Unauthorized", proplists:get_value(http_reason, Props)),
Config.
reserve_drain_without_drainurl(Config0) ->
Config = create_channel_without_tokens(Config0),
Channel = ?config(channel, Config),
Props = create_drain(Channel, undefined, Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
DrainId = maps:get(<<"id">>, Resp),
DrainToken = maps:get(<<"token">>, Resp),
?assert(is_integer(DrainId)),
?assert(is_binary(DrainToken)),
?assert(not maps:is_key(<<"url">>, Resp)),
?assertEqual(201, proplists:get_value(status_code, Props)),
?assertEqual("Created", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
?assertMatch(":8002/v3/channels/"++_, proplists:get_value("location", Headers)),
[{drain, {DrainId, DrainToken, undefined}}
| Config].
reserve_drain_with_drainurl(Config0) ->
Config = create_channel_without_tokens(Config0),
Channel = ?config(channel, Config),
DrainUrl = new_drain_url(),
Props = create_drain(Channel, DrainUrl, Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
DrainId = maps:get(<<"id">>, Resp),
DrainToken = maps:get(<<"token">>, Resp),
?assert(is_integer(DrainId)),
?assert(is_binary(DrainToken)),
?assertEqual(DrainUrl, maps:get(<<"url">>, Resp)),
?assertEqual(201, proplists:get_value(status_code, Props)),
?assertEqual("Created", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
?assertMatch(":8002/v3/channels/"++_, proplists:get_value("location", Headers)),
[{drain, {DrainId, DrainToken, DrainUrl}}
| Config].
update_drain_url(Config0) ->
Config = reserve_drain_without_drainurl(Config0),
Channel = ?config(channel, Config),
{DrainId, DrainToken, _} = proplists:get_value(drain, Config),
DrainUrl = new_drain_url(),
Props = update_drain(Channel, DrainId, DrainUrl, Config),
ct:pal("~p~n", [Props]),
Headers = proplists:get_value(headers, Props),
Body = proplists:get_value(body, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
?assertEqual(DrainId, maps:get(<<"id">>, Resp)),
?assertEqual(DrainToken, maps:get(<<"token">>, Resp)),
?assertEqual(DrainUrl, maps:get(<<"url">>, Resp)),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
?assert(not proplists:is_defined("location", Headers)),
[{drain, {DrainId, DrainToken, DrainUrl}}
| Config].
cannot_update_invalid_drain_url(Config0) ->
Config = reserve_drain_without_drainurl(Config0),
Channel = ?config(channel, Config),
{DrainId, _, _} = proplists:get_value(drain, Config),
DrainUrl = <<"i am not a url">>,
Props = update_drain(Channel, DrainId, DrainUrl, Config),
?assertEqual(400, proplists:get_value(status_code, Props)),
?assertEqual("Bad Request", proplists:get_value(http_reason, Props)),
Config.
get_channel_with_drain(Config0) ->
Config = reserve_drain_with_drainurl(Config0),
Channel = ?config(channel, Config),
{DrainId, DrainToken, DrainUrl} = proplists:get_value(drain, Config),
Props = get_channel(Channel, Config),
ct:pal("~p~n", [Props]),
Headers = proplists:get_value(headers, Props),
Body = proplists:get_value(body, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
?assertMatch(Channel, binary_to_list(maps:get(<<"channel">>, Resp))),
?assertMatch([#{<<"id">> := DrainId, <<"token">> := DrainToken, <<"url">> := DrainUrl}],
maps:get(<<"drains">>, Resp)),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
cannot_add_duplicate_drain(Config0) ->
Config = reserve_drain_with_drainurl(Config0),
Channel = ?config(channel, Config),
{_, _, DrainUrl} = proplists:get_value(drain, Config),
Props = create_drain(Channel, DrainUrl, Config),
Headers = proplists:get_value(headers, Props),
ct:pal("~p~n", [Props]),
?assertEqual(409, proplists:get_value(status_code, Props)),
?assertEqual("Conflict", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
cannot_add_more_drains(Config0) ->
Config = reserve_drain_with_drainurl(Config0),
Channel = ?config(channel, Config),
DrainUrl = new_drain_url(),
Props = create_drain(Channel, DrainUrl, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(422, proplists:get_value(status_code, Props)),
?assertEqual("Unprocessable Entity", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
cannot_update_non_existing_drain(Config0) ->
Config = create_channel_without_tokens(Config0),
Channel = ?config(channel, Config),
DrainUrl = new_drain_url(),
FakeDrainId = 123123123123123123123123,
Props = update_drain(Channel, FakeDrainId, DrainUrl, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(404, proplists:get_value(status_code, Props)),
?assertEqual("Not Found", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
cannot_create_drain_for_non_existing_channel(Config) ->
FakeChannel = new_channel(),
DrainUrl = new_drain_url(),
Props = create_drain(FakeChannel, DrainUrl, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(404, proplists:get_value(status_code, Props)),
?assertEqual("Not Found", proplists:get_value(http_reason, Props)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
cannot_update_drain_for_non_existing_channel(Config) ->
FakeChannel = new_channel(),
FakeDrainId = 123123123123123123123123,
DrainUrl = new_drain_url(),
Props = update_drain(FakeChannel, FakeDrainId, DrainUrl, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(404, proplists:get_value(status_code, Props)),
?assertEqual("Not Found", proplists:get_value(http_reason, Props)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
delete_existing_drain(Config0) ->
Config = reserve_drain_with_drainurl(Config0),
Channel = ?config(channel, Config),
{DrainId, _, _} = ?config(drain, Config),
Props = delete_drain(Channel, DrainId, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(204, proplists:get_value(status_code, Props)),
?assertEqual("No Content", proplists:get_value(http_reason, Props)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
cannot_delete_non_existing_drain(Config0) ->
Config = create_channel_without_tokens(Config0),
Channel = ?config(channel, Config),
FakeDrainId = 123123123123123123123123,
Props = delete_drain(Channel, FakeDrainId, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(404, proplists:get_value(status_code, Props)),
?assertEqual("Not Found", proplists:get_value(http_reason, Props)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
%% -----------------------------------------------------------------------------
%% tokens tests
%% -----------------------------------------------------------------------------
tokens_service_unavailable(Config) ->
Channel = new_channel(),
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/tokens",
Props = logplex_api_SUITE:post(Url, []),
?assertEqual(503, proplists:get_value(status_code, Props)),
?assertEqual("Service Unavailable", proplists:get_value(http_reason, Props)),
Config.
tokens_not_authorized(Config) ->
Channel = new_channel(),
TokenName = new_token_name(),
Props = create_token(Channel, TokenName, Config),
?assertEqual(401, proplists:get_value(status_code, Props)),
?assertEqual("Unauthorized", proplists:get_value(http_reason, Props)),
Config.
create_new_token(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
TokenName = new_token_name(),
Props = create_token(Channel, TokenName, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
cannot_create_token_without_name(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
TokenName = undefined,
Props = create_token(Channel, TokenName, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(400, proplists:get_value(status_code, Props)),
?assertEqual("Bad Request", proplists:get_value(http_reason, Props)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
cannot_create_token_for_non_existing_channel(Config) ->
FakeChannel = new_channel(),
TokenName = new_token_name(),
Props = create_token(FakeChannel, TokenName, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(404, proplists:get_value(status_code, Props)),
?assertEqual("Not Found", proplists:get_value(http_reason, Props)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
%% -----------------------------------------------------------------------------
%% channel logs
%% -----------------------------------------------------------------------------
channel_logs_service_unavailable(Config) ->
Channel = new_channel(),
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/logs",
Props = logplex_api_SUITE:post(Url, []),
?assertEqual(503, proplists:get_value(status_code, Props)),
?assertEqual("Service Unavailable", proplists:get_value(http_reason, Props)),
Config.
channel_logs_not_authorized(Config) ->
Channel = new_channel(),
Props = get_channel_logs(Channel, Config),
?assertEqual(401, proplists:get_value(status_code, Props)),
?assertEqual("Unauthorized", proplists:get_value(http_reason, Props)),
Config.
fetch_channel_logs(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
[{TokenName, TokenId} | _] = ?config(tokens, Config),
ExpectedLogMsgs = [{N, uuid:to_string(uuid:v4())} || N <- lists:seq(1, 5)],
LogMsgs = [{msg, new_log_msg(N, Msg)} || {N, Msg} <- ExpectedLogMsgs],
logplex_message:process_msgs(LogMsgs, list_to_binary(Channel), TokenId, TokenName),
Props = stream_channel_logs(Channel, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual("application/logplex-1", proplists:get_value("content-type", Headers)),
?assertEqual("5", proplists:get_value("logplex-msg-count", Headers)),
?assertEqual("chunked", proplists:get_value("transfer-encoding", Headers)),
?assertEqual("close", proplists:get_value("connection", Headers)),
Lines = re:split(proplists:get_value(body, Props), "\n", [trim]),
[begin
?assertEqual(match, re:run(Line, Expected, [{capture, none}])),
NBin = list_to_binary(integer_to_list(N)),
?assertMatch(<<"64 <", NBin:1/binary, _/binary>>, Line)
end || {{N, Expected}, Line} <- lists:zip(ExpectedLogMsgs, Lines)],
Config.
channel_logs_format(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
[{TokenName, TokenId} | _] = ?config(tokens, Config),
InputMsg = <<"<158>1 2018-03-02T23:22:34.901697+00:00 heroku router - - at=info code=H81 desc=\"Blank app\" method=GET path=\"/\" host=direwolf-d99daa9eda.staging.herokuappdev.com request_id=56a11b1c-1f68-4658-80e4-8213a09a81c2 fwd=\"54.163.94.153\" dyno= connect= service= status=502 bytes= protocol=https">>,
ExpectedMsg = "290 <158>1 2018-03-02T23:22:34.901697+00:00 host heroku router - at=info code=H81 desc=\"Blank app\" method=GET path=\"/\" host=direwolf-d99daa9eda.staging.herokuappdev.com request_id=56a11b1c-1f68-4658-80e4-8213a09a81c2 fwd=\"54.163.94.153\" dyno= connect= service= status=502 bytes= protocol=https\n",
logplex_message:process_msgs([{msg, InputMsg}], list_to_binary(Channel), TokenId, TokenName),
Props = stream_channel_logs(Channel, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual("application/logplex-1", proplists:get_value("content-type", Headers)),
?assertEqual("1", proplists:get_value("logplex-msg-count", Headers)),
?assertEqual("chunked", proplists:get_value("transfer-encoding", Headers)),
?assertEqual("close", proplists:get_value("connection", Headers)),
?assertMatch(ExpectedMsg, proplists:get_value(body, Props)).
channel_logs_bad_syslog_message(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
[{TokenName, TokenId} | _] = ?config(tokens, Config),
Uuid = uuid:to_string(uuid:v4()),
GoodMsg = new_log_msg(1, Uuid),
BadMsg = <<"<42> blafasel">>,
logplex_message:process_msgs([{msg, GoodMsg}], list_to_binary(Channel), TokenId, TokenName),
logplex_message:process_msgs([{msg, BadMsg}], list_to_binary(Channel), TokenId, TokenName),
Props = stream_channel_logs(Channel, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual("application/logplex-1", proplists:get_value("content-type", Headers)),
?assertEqual("2", proplists:get_value("logplex-msg-count", Headers)),
?assertEqual("chunked", proplists:get_value("transfer-encoding", Headers)),
?assertEqual("close", proplists:get_value("connection", Headers)),
Body = proplists:get_value(body, Props),
Lines = re:split(Body, "\n", [trim]),
%% ensure bad message is dropped
?assertEqual(1, length(Lines)),
?assertEqual("64 <1>1 aaaa host cccc dddd - " ++ Uuid ++ "\n", Body).
channel_logs_with_num_query_string(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
[{TokenName, TokenId} | _] = ?config(tokens, Config),
NumLogs = 5,
ExpectedLogMsgs = [{N, uuid:to_string(uuid:v4())} || N <- lists:seq(1, 3)],
LogMsgs = [{msg, new_log_msg(N, Msg)} || {N, Msg} <- ExpectedLogMsgs],
logplex_message:process_msgs(LogMsgs, list_to_binary(Channel), TokenId, TokenName),
Props = stream_channel_logs(Channel, [{num_logs, NumLogs} | Config]),
Headers = proplists:get_value(headers, Props),
?assertEqual("application/logplex-1", proplists:get_value("content-type", Headers)),
?assertEqual("3", proplists:get_value("logplex-msg-count", Headers)),
?assertEqual("chunked", proplists:get_value("transfer-encoding", Headers)),
?assertEqual("close", proplists:get_value("connection", Headers)),
Lines = re:split(proplists:get_value(body, Props), "\n", [trim]),
[begin
?assertEqual(match, re:run(Line, Expected, [{capture, none}])),
NBin = list_to_binary(integer_to_list(N)),
?assertMatch(<<"64 <", NBin:1/binary, _/binary>>, Line)
end || {{N, Expected}, Line} <- lists:zip(ExpectedLogMsgs, Lines)],
Config.
channel_logs_with_num_query_limit(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
[{TokenName, TokenId} | _] = ?config(tokens, Config),
NumLogs = 3,
ExpectedLogMsgs = [{N, uuid:to_string(uuid:v4())} || N <- lists:seq(1, 5)],
LogMsgs = [{msg, new_log_msg(N, Msg)} || {N, Msg} <- ExpectedLogMsgs],
logplex_message:process_msgs(LogMsgs, list_to_binary(Channel), TokenId, TokenName),
Props = stream_channel_logs(Channel, [{num_logs, NumLogs} | Config]),
Headers = proplists:get_value(headers, Props),
?assertEqual("application/logplex-1", proplists:get_value("content-type", Headers)),
note : spits out one more line to indicate there 's more line than requested in the buffer
?assertEqual("4", proplists:get_value("logplex-msg-count", Headers)),
?assertEqual("chunked", proplists:get_value("transfer-encoding", Headers)),
?assertEqual("close", proplists:get_value("connection", Headers)),
Lines = re:split(proplists:get_value(body, Props), "\n", [trim]),
[begin
?assertEqual(match, re:run(Line, Expected, [{capture, none}])),
NBin = list_to_binary(integer_to_list(N)),
?assertMatch(<<"64 <", NBin:1/binary, _/binary>>, Line)
end || {{N, Expected}, Line} <- lists:zip(ExpectedLogMsgs, Lines), N > 1],
Config.
channel_logs_with_malformed_query_string(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
[{TokenName, TokenId} | _] = ?config(tokens, Config),
ExpectedLogMsgs = [{N, uuid:to_string(uuid:v4())} || N <- lists:seq(1, 5)],
LogMsgs = [{msg, new_log_msg(N, Msg)} || {N, Msg} <- ExpectedLogMsgs],
logplex_message:process_msgs(LogMsgs, list_to_binary(Channel), TokenId, TokenName),
Props = stream_channel_logs(Channel, [{num_logs, "invalid"} | Config]),
Headers = proplists:get_value(headers, Props),
?assertEqual("application/logplex-1", proplists:get_value("content-type", Headers)),
?assertEqual("5", proplists:get_value("logplex-msg-count", Headers)),
?assertEqual("chunked", proplists:get_value("transfer-encoding", Headers)),
?assertEqual("close", proplists:get_value("connection", Headers)),
Lines = re:split(proplists:get_value(body, Props), "\n", [trim]),
[begin
ct:pal("~p -- ~p~n", [Line, Expected]),
?assertEqual(match, re:run(Line, Expected, [{capture, none}])),
NBin = list_to_binary(integer_to_list(N)),
?assertMatch(<<"64 <", NBin:1/binary, _/binary>>, Line)
end || {{N, Expected}, Line} <- lists:zip(ExpectedLogMsgs, Lines)],
Config.
%% -----------------------------------------------------------------------------
%% sessions
%% -----------------------------------------------------------------------------
sessions_service_unavailable(Config) ->
SessionId = new_session(),
Url = ?config(api_v3_url, Config) ++ "/v3/sessions/" ++ SessionId,
Props = logplex_api_SUITE:post( Url, []),
?assertEqual(503, proplists:get_value(status_code, Props)),
?assertEqual("Service Unavailable", proplists:get_value(http_reason, Props)),
Config.
create_session_for_existing_channel(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
Props = create_session(Channel, Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
URL = maps:get(<<"url">>, Resp),
Location = proplists:get_value("location", Headers),
?assertEqual(201, proplists:get_value(status_code, Props)),
?assertEqual("Created", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
?assertMatch(":8001/sessions/"++_, Location), %% note: old api URL
?assertEqual(Location, binary_to_list(URL)),
Props1 = get_session(Location, Config),
?assertEqual(200, proplists:get_value(status_code, Props1)),
?assertEqual("OK", proplists:get_value(http_reason, Props1)),
Config.
cannot_create_session_for_non_existing_channel(Config) ->
FakeChannel = new_channel(),
Props = create_session(FakeChannel, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(422, proplists:get_value(status_code, Props)),
?assertEqual("Unprocessable Entity", proplists:get_value(http_reason, Props)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
%% -----------------------------------------------------------------------------
%% healtchecks
%% -----------------------------------------------------------------------------
healthy(Config) ->
Props = check_health(Config),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
Config.
unhealthy(Config) ->
Props = check_health(Config),
?assertEqual(503, proplists:get_value(status_code, Props)),
?assertEqual("Service Unavailable", proplists:get_value(http_reason, Props)),
?assertEqual("SYSTEM BOOTING", proplists:get_value(body, Props)),
Config.
%% -----------------------------------------------------------------------------
%% helper functions
%% -----------------------------------------------------------------------------
put_channel(Channel, Tokens, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel,
Headers = [{"Authorization", ?config(auth, Config)}],
TokenList = [to_binary(TokenName) || {TokenName, _TokenId} <- Tokens],
JSON = jsx:encode(maps:from_list([{<<"tokens">>, TokenList} || length(TokenList) > 0])),
Opts = [{headers, Headers}, {body, JSON}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:put_(Url, Opts).
get_channel(Channel, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel,
Headers = [{"Authorization", ?config(auth, Config)}],
Opts = [{headers, Headers}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:get_(Url, Opts).
delete_channel(Channel, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel,
Headers = [{"Authorization", ?config(auth, Config)}],
Opts = [{headers, Headers}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:request(delete, Url, Opts).
create_drain(Channel, DrainUrl, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/drains",
Headers = [{"Authorization", ?config(auth, Config)}],
JSON = jsx:encode(maps:from_list([{<<"url">>, DrainUrl} || DrainUrl =/= undefined])),
Opts = [{headers, Headers}, {body, JSON}, {http_opts, [{autoredirect, false}]},
{timeout, timer:seconds(10)}],
logplex_api_SUITE:post(Url, Opts).
update_drain(Channel, DrainId, DrainUrl, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/drains/" ++ integer_to_list(DrainId),
Headers = [{"Authorization", ?config(auth, Config)}],
JSON = jsx:encode(maps:from_list([{<<"url">>, DrainUrl} || DrainUrl =/= undefined])),
Opts = [{headers, Headers}, {body, JSON}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:put_(Url, Opts).
delete_drain(Channel, DrainId, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/drains/" ++ integer_to_list(DrainId),
Headers = [{"Authorization", ?config(auth, Config)}],
Opts = [{headers, Headers}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:request(delete, Url, Opts).
create_token(Channel, TokenName, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/tokens",
Headers = [{"Authorization", ?config(auth, Config)}],
JSON = jsx:encode(maps:from_list([{<<"name">>, list_to_binary(TokenName)} || TokenName =/= undefined])),
Opts = [{headers, Headers}, {body, JSON}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:post(Url, Opts).
get_channel_logs(Channel, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/logs",
Headers = [{"Authorization", ?config(auth, Config)}],
Opts = [{headers, Headers}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:get_(Url, Opts).
stream_channel_logs(Channel, Config) ->
NumLogs = ?config(num_logs, Config),
QueryString = case NumLogs of
undefined -> "";
_ when is_integer(NumLogs) ->
"?num=" ++ integer_to_list(NumLogs);
_ when is_list(NumLogs) ->
"?num=" ++ NumLogs
end,
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/logs" ++ QueryString,
Headers = [{"Authorization", ?config(auth, Config)}],
Opts = [{headers, Headers},
{timeout, timer:seconds(10)},
%% we want to stream the results
{opts, [{sync, false},
{stream, self}]}
],
logplex_api_SUITE:get_(Url, Opts).
create_session(Channel, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/sessions",
Headers = [{"Authorization", ?config(auth, Config)}],
JSON = jsx:encode(maps:from_list([{<<"channel_id">>, list_to_binary(Channel)} || Channel =/= undefined])),
Opts = [{headers, Headers}, {body, JSON}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:post(Url, Opts).
get_session(URL, _Config) ->
Opts = [{timeout, timer:seconds(10)}],
logplex_api_SUITE:get_(URL, Opts).
check_health(Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/healthcheck",
Headers = [{"Authorization", ?config(auth, Config)}],
Opts = [{headers, Headers}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:get_(Url, Opts).
new_channel() ->
"app-" ++ uuid:to_string(uuid:v4()).
new_tokens() ->
[{new_token_name(), Ignored} || Ignored <- lists:seq(1,5)].
new_token_name() ->
"token-" ++ uuid:to_string(uuid:v4()).
new_session() ->
"session-" ++ uuid:to_string(uuid:v4()).
new_drain_url() ->
list_to_binary([<<"/">>, uuid:to_binary(uuid:v4())]).
new_log_msg(N, Msg) when is_integer(N) ->
list_to_binary(["<", integer_to_list(N), ">1 ", "aaaa bbbb cccc dddd eeee - ", Msg]).
to_binary(L) when is_list(L) -> list_to_binary(L);
to_binary(Bin) when is_binary(Bin) -> Bin.
assert_tokens(Tokens, ReceivedTokens) ->
BinTokens = [{to_binary(Tok), V} || {Tok, V} <- Tokens],
?assertEqual(length(Tokens), length(ReceivedTokens)),
?assert(lists:all(fun(Token) -> lists:keymember(Token, 1, BinTokens) end,
[to_binary(Token) || {Token, _} <- ReceivedTokens])).
set_os_vars() ->
[os:putenv(Key,Val) || {Key,Val} <-
[{"INSTANCE_NAME", net_adm:localhost()},
{"LOCAL_IP", "localhost"},
{"CLOUD_DOMAIN", "localhost"},
{"LOGPLEX_AUTH_KEY", uuid:to_string(uuid:v4())},
{"LOGPLEX_COOKIE", "ct test"},
{"LOGPLEX_NODE_NAME", atom_to_list(node())},
{"LOGPLEX_API_ENDPOINT_URL", ":8001"}
]].
| null | https://raw.githubusercontent.com/heroku/logplex/fc520c44cf4687726d5d51464d3264ddc6abb0ba/test/logplex_api_v3_SUITE.erl | erlang | -----------------------------------------------------------------------------
setup functions
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
channels tests
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
drains tests
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
tokens tests
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
channel logs
-----------------------------------------------------------------------------
ensure bad message is dropped
-----------------------------------------------------------------------------
sessions
-----------------------------------------------------------------------------
note: old api URL
-----------------------------------------------------------------------------
healtchecks
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
helper functions
-----------------------------------------------------------------------------
we want to stream the results | -module(logplex_api_v3_SUITE).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-compile(export_all).
all() ->
[{group, channels}
, {group, drains}
, {group, tokens}
, {group, channel_logs}
, {group, sessions}
, {group, healthcheck}
].
groups() ->
[{channels,
[channel_service_unavailable
, channel_method_not_allowed
, channel_not_authorized
, create_channel_without_tokens
, create_channel_with_tokens
, update_channel_with_tokens
, update_channel_and_remove_some_tokens
, update_channel_and_nuke_tokens
, get_channel_without_tokens
, get_channel_with_tokens
, delete_channel
, reject_invalid_channel_payload
, retain_flags_on_channel_update
]},
{drains,
[drains_service_unavailable
, drains_not_authorized
, reserve_drain_without_drainurl
, reserve_drain_with_drainurl
, update_drain_url
, cannot_update_invalid_drain_url
, get_channel_with_drain
, cannot_add_duplicate_drain
, cannot_add_more_drains
, cannot_update_non_existing_drain
, cannot_create_drain_for_non_existing_channel
, cannot_update_drain_for_non_existing_channel
, delete_existing_drain
, cannot_delete_non_existing_drain
]},
{tokens,
[tokens_service_unavailable
, tokens_not_authorized
, create_new_token
, cannot_create_token_without_name
, cannot_create_token_for_non_existing_channel
]},
{channel_logs,
[channel_logs_service_unavailable
, channel_logs_not_authorized
, fetch_channel_logs
, channel_logs_format
, channel_logs_bad_syslog_message
, channel_logs_with_num_query_string
, channel_logs_with_malformed_query_string
]},
{sessions,
[sessions_service_unavailable
, create_session_for_existing_channel
, cannot_create_session_for_non_existing_channel
]},
{healthcheck,
[healthy,
unhealthy
]}
].
init_per_suite(Config) ->
set_os_vars(),
ok = logplex_app:a_start(logplex, temporary),
[{api_v3_url, logplex_app:config(http_v3_url)}
, {auth, "Basic " ++ logplex_app:config(auth_key)}
| Config].
end_per_suite(Config) ->
application:stop(logplex),
Config.
init_per_testcase(Testcase , Config)
when Testcase == channel_service_unavailable;
Testcase == drains_service_unavailable;
Testcase == tokens_service_unavailable;
Testcase == channel_logs_service_unavailable ->
logplex_api_v3:set_status(disabled),
Config;
init_per_testcase(Testcase , Config)
when Testcase == channel_not_authorized;
Testcase == drains_not_authorized;
Testcase == tokens_not_authorized;
Testcase == channel_logs_not_authorized ->
[{auth, "Basic bad-token"}
| Config];
init_per_testcase(cannot_add_more_drains, Config) ->
OldLimit = logplex_app:config(max_drains_per_channel),
logplex_app:set_config(max_drains_per_channel, 1),
[{old_max_drains_per_channel, OldLimit}
| Config];
init_per_testcase(unhealthy, Config) ->
logplex_app:set_config(nsync_loaded, false),
Config;
init_per_testcase(sessions_service_unavailable, Config) ->
logplex_app:set_config(deny_tail_sessions, true),
Config;
init_per_testcase(_, Config) ->
Config.
end_per_testcase(Testcase, Config)
when Testcase == channel_service_unavailable;
Testcase == drains_service_unavailable;
Testcase == tokens_service_unavailable;
Testcase == channel_logs_service_unavailable ->
logplex_api_v3:set_status(normal),
Config;
end_per_testcase(cannot_add_more_drains, Config) ->
OldLimit = ?config(old_max_drains_per_channel, Config),
logplex_app:set_config(max_drains_per_channel, OldLimit),
Config;
end_per_testcase(unhealthy, Config) ->
logplex_app:set_config(nsync_loaded, true),
Config;
end_per_testcase(sessions_service_unavailable, Config) ->
logplex_app:set_config(deny_tail_sessions, false),
Config;
end_per_testcase(_, Config) ->
Config.
channel_service_unavailable(Config) ->
Channel = new_channel(),
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel,
Props = logplex_api_SUITE:request(get, Url, []),
?assertEqual(503, proplists:get_value(status_code, Props)),
?assertEqual("Service Unavailable", proplists:get_value(http_reason, Props)),
Config.
channel_method_not_allowed(Config) ->
Channel = new_channel(),
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel,
[begin
Props = logplex_api_SUITE:request(Method, Url, []),
?assertEqual(405, proplists:get_value(status_code, Props)),
?assertEqual("Method Not Allowed", proplists:get_value(http_reason, Props))
end || Method <- [post, head, options]],
Config.
channel_not_authorized(Config) ->
Channel = new_channel(),
Props = get_channel(Channel, Config),
?assertEqual(401, proplists:get_value(status_code, Props)),
?assertEqual("Unauthorized", proplists:get_value(http_reason, Props)),
Config.
create_channel_without_tokens(Config) ->
Channel = new_channel(),
Props = put_channel(Channel, [], Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
?assertMatch(Channel, binary_to_list(maps:get(<<"channel">>, Resp))),
?assertEqual(201, proplists:get_value(status_code, Props)),
?assertEqual("Created", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
[{channel, Channel} | Config].
create_channel_with_tokens(Config) ->
Channel = new_channel(),
Tokens = new_tokens(),
Props = put_channel(Channel, Tokens, Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
ReceivedTokens = maps:to_list(maps:get(<<"tokens">>, Resp)),
assert_tokens(Tokens, ReceivedTokens),
?assertMatch(Channel, binary_to_list(maps:get(<<"channel">>, Resp))),
?assertEqual(201, proplists:get_value(status_code, Props)),
?assertEqual("Created", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
[{channel, Channel}
, {tokens, ReceivedTokens}
| Config].
update_channel_with_tokens(Config0) ->
Config = create_channel_without_tokens(Config0),
Channel = ?config(channel, Config),
Tokens = new_tokens(),
Props = put_channel(Channel, Tokens, Config),
ct:pal("put channel resp: ~p~n", [Props]),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
ReceivedTokens = maps:to_list(maps:get(<<"tokens">>, Resp)),
assert_tokens(Tokens, ReceivedTokens),
?assertMatch(Channel, binary_to_list(maps:get(<<"channel">>, Resp))),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
[{tokens, ReceivedTokens} | Config].
update_channel_and_remove_some_tokens(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
Tokens = lists:nthtail(2, ?config(tokens, Config)),
Props = put_channel(Channel, Tokens, Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
ReceivedTokens = maps:to_list(maps:get(<<"tokens">>, Resp)),
assert_tokens(Tokens, ReceivedTokens),
?assertMatch(Channel, binary_to_list(maps:get(<<"channel">>, Resp))),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
[{tokens, ReceivedTokens} | Config].
update_channel_and_nuke_tokens(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
Props = put_channel(Channel, [], Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
?assertMatch(Channel, binary_to_list(maps:get(<<"channel">>, Resp))),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
?assert(not maps:is_key(<<"tokens">>, Resp)),
Config.
get_channel_without_tokens(Config0) ->
Config = create_channel_without_tokens(Config0),
Channel = ?config(channel, Config),
Props = get_channel(Channel, Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
?assertMatch(Channel, binary_to_list(maps:get(<<"channel">>, Resp))),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
get_channel_with_tokens(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
Tokens = ?config(tokens, Config),
Props = get_channel(Channel, Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
ReceivedTokens = maps:to_list(maps:get(<<"tokens">>, Resp)),
assert_tokens(Tokens, ReceivedTokens),
?assertMatch(Channel, binary_to_list(maps:get(<<"channel">>, Resp))),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
delete_channel(Config0) ->
Config = create_channel_without_tokens(Config0),
Channel = ?config(channel, Config),
Props = delete_channel(Channel, Config),
ct:pal("delete channel resp: ~p~n", [Props]),
?assertEqual(204, proplists:get_value(status_code, Props)),
?assertEqual("No Content", proplists:get_value(http_reason, Props)).
reject_invalid_channel_payload(Config) ->
Channel = new_channel(),
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel,
Headers = [{"Authorization", ?config(auth, Config)}],
JSON = jsx:encode([<<"asdf">>, 123, [<<"test">>]]),
Opts = [{headers, Headers}, {body, JSON}, {timeout, timer:seconds(10)}],
Props = logplex_api_SUITE:put_(Url, Opts),
Body = proplists:get_value(body, Props),
RespHeaders = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
?assertEqual(<<"invalid payload">>, maps:get(<<"error">>, Resp)),
?assertEqual(400, proplists:get_value(status_code, Props)),
?assertEqual("Bad Request", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", RespHeaders)),
?assert(is_list(proplists:get_value("request-id", RespHeaders))),
Config.
retain_flags_on_channel_update(Config0) ->
Config = create_channel_without_tokens(Config0),
Channel = ?config(channel, Config),
ChanRec = logplex_channel:poll(list_to_binary(Channel), timer:seconds(1)),
ChanRecWithFlag = logplex_channel:set_flag(no_redis, ChanRec),
?assertEqual(ok, logplex_channel:store(ChanRecWithFlag)),
Props = put_channel(Channel, [], Config),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual(ChanRecWithFlag, logplex_channel:poll(list_to_binary(Channel), timer:seconds(1))),
Config.
drains_service_unavailable(Config) ->
Channel = new_channel(),
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/drains",
Props = logplex_api_SUITE:post( Url, []),
?assertEqual(503, proplists:get_value(status_code, Props)),
?assertEqual("Service Unavailable", proplists:get_value(http_reason, Props)),
Config.
drains_not_authorized(Config) ->
Channel = new_channel(),
Props = create_drain(Channel, undefined, Config),
?assertEqual(401, proplists:get_value(status_code, Props)),
?assertEqual("Unauthorized", proplists:get_value(http_reason, Props)),
Config.
reserve_drain_without_drainurl(Config0) ->
Config = create_channel_without_tokens(Config0),
Channel = ?config(channel, Config),
Props = create_drain(Channel, undefined, Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
DrainId = maps:get(<<"id">>, Resp),
DrainToken = maps:get(<<"token">>, Resp),
?assert(is_integer(DrainId)),
?assert(is_binary(DrainToken)),
?assert(not maps:is_key(<<"url">>, Resp)),
?assertEqual(201, proplists:get_value(status_code, Props)),
?assertEqual("Created", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
?assertMatch(":8002/v3/channels/"++_, proplists:get_value("location", Headers)),
[{drain, {DrainId, DrainToken, undefined}}
| Config].
reserve_drain_with_drainurl(Config0) ->
Config = create_channel_without_tokens(Config0),
Channel = ?config(channel, Config),
DrainUrl = new_drain_url(),
Props = create_drain(Channel, DrainUrl, Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
DrainId = maps:get(<<"id">>, Resp),
DrainToken = maps:get(<<"token">>, Resp),
?assert(is_integer(DrainId)),
?assert(is_binary(DrainToken)),
?assertEqual(DrainUrl, maps:get(<<"url">>, Resp)),
?assertEqual(201, proplists:get_value(status_code, Props)),
?assertEqual("Created", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
?assertMatch(":8002/v3/channels/"++_, proplists:get_value("location", Headers)),
[{drain, {DrainId, DrainToken, DrainUrl}}
| Config].
update_drain_url(Config0) ->
Config = reserve_drain_without_drainurl(Config0),
Channel = ?config(channel, Config),
{DrainId, DrainToken, _} = proplists:get_value(drain, Config),
DrainUrl = new_drain_url(),
Props = update_drain(Channel, DrainId, DrainUrl, Config),
ct:pal("~p~n", [Props]),
Headers = proplists:get_value(headers, Props),
Body = proplists:get_value(body, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
?assertEqual(DrainId, maps:get(<<"id">>, Resp)),
?assertEqual(DrainToken, maps:get(<<"token">>, Resp)),
?assertEqual(DrainUrl, maps:get(<<"url">>, Resp)),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
?assert(not proplists:is_defined("location", Headers)),
[{drain, {DrainId, DrainToken, DrainUrl}}
| Config].
cannot_update_invalid_drain_url(Config0) ->
Config = reserve_drain_without_drainurl(Config0),
Channel = ?config(channel, Config),
{DrainId, _, _} = proplists:get_value(drain, Config),
DrainUrl = <<"i am not a url">>,
Props = update_drain(Channel, DrainId, DrainUrl, Config),
?assertEqual(400, proplists:get_value(status_code, Props)),
?assertEqual("Bad Request", proplists:get_value(http_reason, Props)),
Config.
get_channel_with_drain(Config0) ->
Config = reserve_drain_with_drainurl(Config0),
Channel = ?config(channel, Config),
{DrainId, DrainToken, DrainUrl} = proplists:get_value(drain, Config),
Props = get_channel(Channel, Config),
ct:pal("~p~n", [Props]),
Headers = proplists:get_value(headers, Props),
Body = proplists:get_value(body, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
?assertMatch(Channel, binary_to_list(maps:get(<<"channel">>, Resp))),
?assertMatch([#{<<"id">> := DrainId, <<"token">> := DrainToken, <<"url">> := DrainUrl}],
maps:get(<<"drains">>, Resp)),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
cannot_add_duplicate_drain(Config0) ->
Config = reserve_drain_with_drainurl(Config0),
Channel = ?config(channel, Config),
{_, _, DrainUrl} = proplists:get_value(drain, Config),
Props = create_drain(Channel, DrainUrl, Config),
Headers = proplists:get_value(headers, Props),
ct:pal("~p~n", [Props]),
?assertEqual(409, proplists:get_value(status_code, Props)),
?assertEqual("Conflict", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
cannot_add_more_drains(Config0) ->
Config = reserve_drain_with_drainurl(Config0),
Channel = ?config(channel, Config),
DrainUrl = new_drain_url(),
Props = create_drain(Channel, DrainUrl, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(422, proplists:get_value(status_code, Props)),
?assertEqual("Unprocessable Entity", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
cannot_update_non_existing_drain(Config0) ->
Config = create_channel_without_tokens(Config0),
Channel = ?config(channel, Config),
DrainUrl = new_drain_url(),
FakeDrainId = 123123123123123123123123,
Props = update_drain(Channel, FakeDrainId, DrainUrl, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(404, proplists:get_value(status_code, Props)),
?assertEqual("Not Found", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
cannot_create_drain_for_non_existing_channel(Config) ->
FakeChannel = new_channel(),
DrainUrl = new_drain_url(),
Props = create_drain(FakeChannel, DrainUrl, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(404, proplists:get_value(status_code, Props)),
?assertEqual("Not Found", proplists:get_value(http_reason, Props)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
cannot_update_drain_for_non_existing_channel(Config) ->
FakeChannel = new_channel(),
FakeDrainId = 123123123123123123123123,
DrainUrl = new_drain_url(),
Props = update_drain(FakeChannel, FakeDrainId, DrainUrl, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(404, proplists:get_value(status_code, Props)),
?assertEqual("Not Found", proplists:get_value(http_reason, Props)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
delete_existing_drain(Config0) ->
Config = reserve_drain_with_drainurl(Config0),
Channel = ?config(channel, Config),
{DrainId, _, _} = ?config(drain, Config),
Props = delete_drain(Channel, DrainId, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(204, proplists:get_value(status_code, Props)),
?assertEqual("No Content", proplists:get_value(http_reason, Props)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
cannot_delete_non_existing_drain(Config0) ->
Config = create_channel_without_tokens(Config0),
Channel = ?config(channel, Config),
FakeDrainId = 123123123123123123123123,
Props = delete_drain(Channel, FakeDrainId, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(404, proplists:get_value(status_code, Props)),
?assertEqual("Not Found", proplists:get_value(http_reason, Props)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
tokens_service_unavailable(Config) ->
Channel = new_channel(),
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/tokens",
Props = logplex_api_SUITE:post(Url, []),
?assertEqual(503, proplists:get_value(status_code, Props)),
?assertEqual("Service Unavailable", proplists:get_value(http_reason, Props)),
Config.
tokens_not_authorized(Config) ->
Channel = new_channel(),
TokenName = new_token_name(),
Props = create_token(Channel, TokenName, Config),
?assertEqual(401, proplists:get_value(status_code, Props)),
?assertEqual("Unauthorized", proplists:get_value(http_reason, Props)),
Config.
create_new_token(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
TokenName = new_token_name(),
Props = create_token(Channel, TokenName, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
cannot_create_token_without_name(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
TokenName = undefined,
Props = create_token(Channel, TokenName, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(400, proplists:get_value(status_code, Props)),
?assertEqual("Bad Request", proplists:get_value(http_reason, Props)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
cannot_create_token_for_non_existing_channel(Config) ->
FakeChannel = new_channel(),
TokenName = new_token_name(),
Props = create_token(FakeChannel, TokenName, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(404, proplists:get_value(status_code, Props)),
?assertEqual("Not Found", proplists:get_value(http_reason, Props)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
channel_logs_service_unavailable(Config) ->
Channel = new_channel(),
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/logs",
Props = logplex_api_SUITE:post(Url, []),
?assertEqual(503, proplists:get_value(status_code, Props)),
?assertEqual("Service Unavailable", proplists:get_value(http_reason, Props)),
Config.
channel_logs_not_authorized(Config) ->
Channel = new_channel(),
Props = get_channel_logs(Channel, Config),
?assertEqual(401, proplists:get_value(status_code, Props)),
?assertEqual("Unauthorized", proplists:get_value(http_reason, Props)),
Config.
fetch_channel_logs(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
[{TokenName, TokenId} | _] = ?config(tokens, Config),
ExpectedLogMsgs = [{N, uuid:to_string(uuid:v4())} || N <- lists:seq(1, 5)],
LogMsgs = [{msg, new_log_msg(N, Msg)} || {N, Msg} <- ExpectedLogMsgs],
logplex_message:process_msgs(LogMsgs, list_to_binary(Channel), TokenId, TokenName),
Props = stream_channel_logs(Channel, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual("application/logplex-1", proplists:get_value("content-type", Headers)),
?assertEqual("5", proplists:get_value("logplex-msg-count", Headers)),
?assertEqual("chunked", proplists:get_value("transfer-encoding", Headers)),
?assertEqual("close", proplists:get_value("connection", Headers)),
Lines = re:split(proplists:get_value(body, Props), "\n", [trim]),
[begin
?assertEqual(match, re:run(Line, Expected, [{capture, none}])),
NBin = list_to_binary(integer_to_list(N)),
?assertMatch(<<"64 <", NBin:1/binary, _/binary>>, Line)
end || {{N, Expected}, Line} <- lists:zip(ExpectedLogMsgs, Lines)],
Config.
channel_logs_format(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
[{TokenName, TokenId} | _] = ?config(tokens, Config),
InputMsg = <<"<158>1 2018-03-02T23:22:34.901697+00:00 heroku router - - at=info code=H81 desc=\"Blank app\" method=GET path=\"/\" host=direwolf-d99daa9eda.staging.herokuappdev.com request_id=56a11b1c-1f68-4658-80e4-8213a09a81c2 fwd=\"54.163.94.153\" dyno= connect= service= status=502 bytes= protocol=https">>,
ExpectedMsg = "290 <158>1 2018-03-02T23:22:34.901697+00:00 host heroku router - at=info code=H81 desc=\"Blank app\" method=GET path=\"/\" host=direwolf-d99daa9eda.staging.herokuappdev.com request_id=56a11b1c-1f68-4658-80e4-8213a09a81c2 fwd=\"54.163.94.153\" dyno= connect= service= status=502 bytes= protocol=https\n",
logplex_message:process_msgs([{msg, InputMsg}], list_to_binary(Channel), TokenId, TokenName),
Props = stream_channel_logs(Channel, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual("application/logplex-1", proplists:get_value("content-type", Headers)),
?assertEqual("1", proplists:get_value("logplex-msg-count", Headers)),
?assertEqual("chunked", proplists:get_value("transfer-encoding", Headers)),
?assertEqual("close", proplists:get_value("connection", Headers)),
?assertMatch(ExpectedMsg, proplists:get_value(body, Props)).
channel_logs_bad_syslog_message(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
[{TokenName, TokenId} | _] = ?config(tokens, Config),
Uuid = uuid:to_string(uuid:v4()),
GoodMsg = new_log_msg(1, Uuid),
BadMsg = <<"<42> blafasel">>,
logplex_message:process_msgs([{msg, GoodMsg}], list_to_binary(Channel), TokenId, TokenName),
logplex_message:process_msgs([{msg, BadMsg}], list_to_binary(Channel), TokenId, TokenName),
Props = stream_channel_logs(Channel, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual("application/logplex-1", proplists:get_value("content-type", Headers)),
?assertEqual("2", proplists:get_value("logplex-msg-count", Headers)),
?assertEqual("chunked", proplists:get_value("transfer-encoding", Headers)),
?assertEqual("close", proplists:get_value("connection", Headers)),
Body = proplists:get_value(body, Props),
Lines = re:split(Body, "\n", [trim]),
?assertEqual(1, length(Lines)),
?assertEqual("64 <1>1 aaaa host cccc dddd - " ++ Uuid ++ "\n", Body).
channel_logs_with_num_query_string(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
[{TokenName, TokenId} | _] = ?config(tokens, Config),
NumLogs = 5,
ExpectedLogMsgs = [{N, uuid:to_string(uuid:v4())} || N <- lists:seq(1, 3)],
LogMsgs = [{msg, new_log_msg(N, Msg)} || {N, Msg} <- ExpectedLogMsgs],
logplex_message:process_msgs(LogMsgs, list_to_binary(Channel), TokenId, TokenName),
Props = stream_channel_logs(Channel, [{num_logs, NumLogs} | Config]),
Headers = proplists:get_value(headers, Props),
?assertEqual("application/logplex-1", proplists:get_value("content-type", Headers)),
?assertEqual("3", proplists:get_value("logplex-msg-count", Headers)),
?assertEqual("chunked", proplists:get_value("transfer-encoding", Headers)),
?assertEqual("close", proplists:get_value("connection", Headers)),
Lines = re:split(proplists:get_value(body, Props), "\n", [trim]),
[begin
?assertEqual(match, re:run(Line, Expected, [{capture, none}])),
NBin = list_to_binary(integer_to_list(N)),
?assertMatch(<<"64 <", NBin:1/binary, _/binary>>, Line)
end || {{N, Expected}, Line} <- lists:zip(ExpectedLogMsgs, Lines)],
Config.
channel_logs_with_num_query_limit(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
[{TokenName, TokenId} | _] = ?config(tokens, Config),
NumLogs = 3,
ExpectedLogMsgs = [{N, uuid:to_string(uuid:v4())} || N <- lists:seq(1, 5)],
LogMsgs = [{msg, new_log_msg(N, Msg)} || {N, Msg} <- ExpectedLogMsgs],
logplex_message:process_msgs(LogMsgs, list_to_binary(Channel), TokenId, TokenName),
Props = stream_channel_logs(Channel, [{num_logs, NumLogs} | Config]),
Headers = proplists:get_value(headers, Props),
?assertEqual("application/logplex-1", proplists:get_value("content-type", Headers)),
note : spits out one more line to indicate there 's more line than requested in the buffer
?assertEqual("4", proplists:get_value("logplex-msg-count", Headers)),
?assertEqual("chunked", proplists:get_value("transfer-encoding", Headers)),
?assertEqual("close", proplists:get_value("connection", Headers)),
Lines = re:split(proplists:get_value(body, Props), "\n", [trim]),
[begin
?assertEqual(match, re:run(Line, Expected, [{capture, none}])),
NBin = list_to_binary(integer_to_list(N)),
?assertMatch(<<"64 <", NBin:1/binary, _/binary>>, Line)
end || {{N, Expected}, Line} <- lists:zip(ExpectedLogMsgs, Lines), N > 1],
Config.
channel_logs_with_malformed_query_string(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
[{TokenName, TokenId} | _] = ?config(tokens, Config),
ExpectedLogMsgs = [{N, uuid:to_string(uuid:v4())} || N <- lists:seq(1, 5)],
LogMsgs = [{msg, new_log_msg(N, Msg)} || {N, Msg} <- ExpectedLogMsgs],
logplex_message:process_msgs(LogMsgs, list_to_binary(Channel), TokenId, TokenName),
Props = stream_channel_logs(Channel, [{num_logs, "invalid"} | Config]),
Headers = proplists:get_value(headers, Props),
?assertEqual("application/logplex-1", proplists:get_value("content-type", Headers)),
?assertEqual("5", proplists:get_value("logplex-msg-count", Headers)),
?assertEqual("chunked", proplists:get_value("transfer-encoding", Headers)),
?assertEqual("close", proplists:get_value("connection", Headers)),
Lines = re:split(proplists:get_value(body, Props), "\n", [trim]),
[begin
ct:pal("~p -- ~p~n", [Line, Expected]),
?assertEqual(match, re:run(Line, Expected, [{capture, none}])),
NBin = list_to_binary(integer_to_list(N)),
?assertMatch(<<"64 <", NBin:1/binary, _/binary>>, Line)
end || {{N, Expected}, Line} <- lists:zip(ExpectedLogMsgs, Lines)],
Config.
sessions_service_unavailable(Config) ->
SessionId = new_session(),
Url = ?config(api_v3_url, Config) ++ "/v3/sessions/" ++ SessionId,
Props = logplex_api_SUITE:post( Url, []),
?assertEqual(503, proplists:get_value(status_code, Props)),
?assertEqual("Service Unavailable", proplists:get_value(http_reason, Props)),
Config.
create_session_for_existing_channel(Config0) ->
Config = create_channel_with_tokens(Config0),
Channel = ?config(channel, Config),
Props = create_session(Channel, Config),
Body = proplists:get_value(body, Props),
Headers = proplists:get_value(headers, Props),
Resp = jsx:decode(list_to_binary(Body), [return_maps]),
URL = maps:get(<<"url">>, Resp),
Location = proplists:get_value("location", Headers),
?assertEqual(201, proplists:get_value(status_code, Props)),
?assertEqual("Created", proplists:get_value(http_reason, Props)),
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
?assert(is_list(proplists:get_value("request-id", Headers))),
?assertEqual(Location, binary_to_list(URL)),
Props1 = get_session(Location, Config),
?assertEqual(200, proplists:get_value(status_code, Props1)),
?assertEqual("OK", proplists:get_value(http_reason, Props1)),
Config.
cannot_create_session_for_non_existing_channel(Config) ->
FakeChannel = new_channel(),
Props = create_session(FakeChannel, Config),
Headers = proplists:get_value(headers, Props),
?assertEqual(422, proplists:get_value(status_code, Props)),
?assertEqual("Unprocessable Entity", proplists:get_value(http_reason, Props)),
?assert(is_list(proplists:get_value("request-id", Headers))),
Config.
healthy(Config) ->
Props = check_health(Config),
?assertEqual(200, proplists:get_value(status_code, Props)),
?assertEqual("OK", proplists:get_value(http_reason, Props)),
Config.
unhealthy(Config) ->
Props = check_health(Config),
?assertEqual(503, proplists:get_value(status_code, Props)),
?assertEqual("Service Unavailable", proplists:get_value(http_reason, Props)),
?assertEqual("SYSTEM BOOTING", proplists:get_value(body, Props)),
Config.
put_channel(Channel, Tokens, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel,
Headers = [{"Authorization", ?config(auth, Config)}],
TokenList = [to_binary(TokenName) || {TokenName, _TokenId} <- Tokens],
JSON = jsx:encode(maps:from_list([{<<"tokens">>, TokenList} || length(TokenList) > 0])),
Opts = [{headers, Headers}, {body, JSON}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:put_(Url, Opts).
get_channel(Channel, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel,
Headers = [{"Authorization", ?config(auth, Config)}],
Opts = [{headers, Headers}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:get_(Url, Opts).
delete_channel(Channel, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel,
Headers = [{"Authorization", ?config(auth, Config)}],
Opts = [{headers, Headers}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:request(delete, Url, Opts).
create_drain(Channel, DrainUrl, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/drains",
Headers = [{"Authorization", ?config(auth, Config)}],
JSON = jsx:encode(maps:from_list([{<<"url">>, DrainUrl} || DrainUrl =/= undefined])),
Opts = [{headers, Headers}, {body, JSON}, {http_opts, [{autoredirect, false}]},
{timeout, timer:seconds(10)}],
logplex_api_SUITE:post(Url, Opts).
update_drain(Channel, DrainId, DrainUrl, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/drains/" ++ integer_to_list(DrainId),
Headers = [{"Authorization", ?config(auth, Config)}],
JSON = jsx:encode(maps:from_list([{<<"url">>, DrainUrl} || DrainUrl =/= undefined])),
Opts = [{headers, Headers}, {body, JSON}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:put_(Url, Opts).
delete_drain(Channel, DrainId, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/drains/" ++ integer_to_list(DrainId),
Headers = [{"Authorization", ?config(auth, Config)}],
Opts = [{headers, Headers}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:request(delete, Url, Opts).
create_token(Channel, TokenName, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/tokens",
Headers = [{"Authorization", ?config(auth, Config)}],
JSON = jsx:encode(maps:from_list([{<<"name">>, list_to_binary(TokenName)} || TokenName =/= undefined])),
Opts = [{headers, Headers}, {body, JSON}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:post(Url, Opts).
get_channel_logs(Channel, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/logs",
Headers = [{"Authorization", ?config(auth, Config)}],
Opts = [{headers, Headers}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:get_(Url, Opts).
stream_channel_logs(Channel, Config) ->
NumLogs = ?config(num_logs, Config),
QueryString = case NumLogs of
undefined -> "";
_ when is_integer(NumLogs) ->
"?num=" ++ integer_to_list(NumLogs);
_ when is_list(NumLogs) ->
"?num=" ++ NumLogs
end,
Url = ?config(api_v3_url, Config) ++ "/v3/channels/" ++ Channel ++ "/logs" ++ QueryString,
Headers = [{"Authorization", ?config(auth, Config)}],
Opts = [{headers, Headers},
{timeout, timer:seconds(10)},
{opts, [{sync, false},
{stream, self}]}
],
logplex_api_SUITE:get_(Url, Opts).
create_session(Channel, Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/sessions",
Headers = [{"Authorization", ?config(auth, Config)}],
JSON = jsx:encode(maps:from_list([{<<"channel_id">>, list_to_binary(Channel)} || Channel =/= undefined])),
Opts = [{headers, Headers}, {body, JSON}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:post(Url, Opts).
get_session(URL, _Config) ->
Opts = [{timeout, timer:seconds(10)}],
logplex_api_SUITE:get_(URL, Opts).
check_health(Config) ->
Url = ?config(api_v3_url, Config) ++ "/v3/healthcheck",
Headers = [{"Authorization", ?config(auth, Config)}],
Opts = [{headers, Headers}, {timeout, timer:seconds(10)}],
logplex_api_SUITE:get_(Url, Opts).
new_channel() ->
"app-" ++ uuid:to_string(uuid:v4()).
new_tokens() ->
[{new_token_name(), Ignored} || Ignored <- lists:seq(1,5)].
new_token_name() ->
"token-" ++ uuid:to_string(uuid:v4()).
new_session() ->
"session-" ++ uuid:to_string(uuid:v4()).
new_drain_url() ->
list_to_binary([<<"/">>, uuid:to_binary(uuid:v4())]).
new_log_msg(N, Msg) when is_integer(N) ->
list_to_binary(["<", integer_to_list(N), ">1 ", "aaaa bbbb cccc dddd eeee - ", Msg]).
to_binary(L) when is_list(L) -> list_to_binary(L);
to_binary(Bin) when is_binary(Bin) -> Bin.
assert_tokens(Tokens, ReceivedTokens) ->
BinTokens = [{to_binary(Tok), V} || {Tok, V} <- Tokens],
?assertEqual(length(Tokens), length(ReceivedTokens)),
?assert(lists:all(fun(Token) -> lists:keymember(Token, 1, BinTokens) end,
[to_binary(Token) || {Token, _} <- ReceivedTokens])).
set_os_vars() ->
[os:putenv(Key,Val) || {Key,Val} <-
[{"INSTANCE_NAME", net_adm:localhost()},
{"LOCAL_IP", "localhost"},
{"CLOUD_DOMAIN", "localhost"},
{"LOGPLEX_AUTH_KEY", uuid:to_string(uuid:v4())},
{"LOGPLEX_COOKIE", "ct test"},
{"LOGPLEX_NODE_NAME", atom_to_list(node())},
{"LOGPLEX_API_ENDPOINT_URL", ":8001"}
]].
|
6108fea70221967e3fc271c2e12a75c48b38d6413c4b541c76cadfe3afeb3f13 | tezos/tezos-mirror | tx_hash.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2023 Nomadic Labs < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
module Hash =
Tezos_crypto.Blake2B.Make
(Tezos_crypto.Base58)
(struct
let name = "tx_hash"
let title = "A transaction hash"
let b58check_prefix = "\001\095\045" (* tx(52) *)
let size = Some 32
end)
let () = Tezos_crypto.Base58.check_encoded_prefix Hash.b58check_encoding "tx" 52
include Hash
let to_string = Data_encoding.Binary.to_string_exn encoding
let hash_to_string s = hash_string [s] |> to_string
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/1a825cb1e7d8a4c1e3cdab206d9b45d05b452db9/src/bin_evm_proxy/tx_hash.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
tx(52) | Copyright ( c ) 2023 Nomadic Labs < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
module Hash =
Tezos_crypto.Blake2B.Make
(Tezos_crypto.Base58)
(struct
let name = "tx_hash"
let title = "A transaction hash"
let size = Some 32
end)
let () = Tezos_crypto.Base58.check_encoded_prefix Hash.b58check_encoding "tx" 52
include Hash
let to_string = Data_encoding.Binary.to_string_exn encoding
let hash_to_string s = hash_string [s] |> to_string
|
e2e13fe141efae0c5ffe980df270ab5e20e582e8013e70663a17045552653705 | sondresl/AdventOfCode | Day11-lazy.hs | import Data.List.Extra
import Data.Bits
import Data.Char
import Data.Bool
import Data.Complex
import Data.Map.Strict (Map)
import Debug.Trace
import qualified Data.Map.Strict as M
import Text.ParserCombinators.Parsec
-- Parsing the input (comma separated ints)
parser :: String -> Memory
parser = either (error "Bad parse") (M.fromList . zip [0..]) . parse numbers "Opcodes"
where numbers = map read <$> sepBy (minus <|> num) (char ',')
num = many1 digit
minus = (:) <$> char '-' <*> num
-- Intcode computer
type Memory = M.Map Int Int
type Hull = M.Map Pos Int
type Facing = Complex Float
type Pos = (Int, Int)
data ProgramState = Wait Int Int [Int] [Int] Memory
| Halt [Int]
deriving Show
data RobotState = Hold Hull Pos Facing
| Fin Hull
index :: Int -> Memory -> Int
index = M.findWithDefault 0
args :: Int -> Int -> Memory -> (Int, Int, Int)
args i rel mem =
let mode x = div (M.findWithDefault 0 i mem) x `rem` 10
f x = case mode (10^(x+1)) of
0 -> index (index (i + x) mem) mem
1 -> index (i + x) mem
2 -> index (rel + (index (i + x) mem)) mem
g = case div (index i mem) 10000 `rem` 10 of
2 -> rel + (index (i + 3) mem)
_ -> index (i + 3) mem
in (f 1, f 2, g)
compute :: Int -> Int -> [Int] -> Memory -> [Int]
compute i rel input memory =
let (a, b, c) = args i rel memory
in case rem (M.findWithDefault 0 i memory) 100 of
1 -> compute (i + 4) rel input (M.insert c (a + b) memory)
2 -> compute (i + 4) rel input (M.insert c (a * b) memory)
3 -> let ix = case div (index i memory) 100 `rem` 10 of
2 -> rel + (index (i + 1) memory)
_ -> index (i + 1) memory
in compute (i + 2) rel (tail input) (M.insert ix (head input) memory)
4 -> a : compute (i + 2) rel input memory
5 -> compute (bool (i + 3) b (0 /= a)) rel input memory
6 -> compute (bool (i + 3) b (0 == a)) rel input memory
7 -> compute (i + 4) rel input (M.insert c (bool 0 1 (a < b)) memory)
8 -> compute (i + 4) rel input (M.insert c (bool 0 1 (a == b)) memory)
9 -> compute (i + 2) (rel + a) input memory
99 -> []
i -> error ("Invalid opcode: " ++ show i)
-- Paint robot
runRobot :: Int -> Memory -> Hull
runRobot init memory =
let input = compute 0 0 (map g states) memory
states = scanl f (M.fromList [((0,0), init)], (0, 0), (1:+1)) . chunksOf 2 $ input
f (hull, pos, dir) [col, ddir] =
let hull' = M.insert pos col hull
dir' = newDir dir ddir
pos' = move pos dir'
in (hull', pos', dir')
g (m, p, _) = M.findWithDefault 0 p m
(hull, _, _) = last states
in hull
newDir :: Facing -> Int -> Facing
newDir c 1 = c * (0:+1)
newDir c 0 = c * (0:+(-1))
move :: Pos -> Facing -> Pos
move (x, y) (1:+1) = (x, y + 1) -- Up
move (x, y) (1:+(-1)) = (x - 1, y) -- Left
move (x, y) ((-1):+1) = (x + 1, y) -- Right
move (x, y) ((-1):+(-1)) = (x, y - 1) -- Down
printHull :: Hull -> IO ()
printHull positions =
let ks = M.keys positions
xs = map fst ks
ys = map snd ks
(topX, botX) = (maximum xs, minimum xs)
(topY, botY) = (maximum ys, minimum ys)
lines = map (mkLine positions botX topX) [botY..topY]
in mapM_ putStrLn $ reverse lines
where mkLine hull from to row
| from > to = ""
| otherwise = toChar (M.findWithDefault 0 (from, row) hull) : mkLine hull (from + 1) to row
toChar x = if (x == 1) then '🔴' else '🖤'
solveA :: Memory -> Int
solveA mem = length . M.keys $ runRobot 0 mem
solveB :: Memory -> IO ()
solveB mem = printHull $ runRobot 1 mem
main = do
contents <- parser <$> readFile "data/input-2019-11.txt"
print $ solveA contents
solveB contents
1747
ZCGRHKLB
| null | https://raw.githubusercontent.com/sondresl/AdventOfCode/51525441795417f31b3eb67a690aa5534d1e699b/2019/Haskell/src/Day11-lazy.hs | haskell | Parsing the input (comma separated ints)
Intcode computer
Paint robot
Up
Left
Right
Down | import Data.List.Extra
import Data.Bits
import Data.Char
import Data.Bool
import Data.Complex
import Data.Map.Strict (Map)
import Debug.Trace
import qualified Data.Map.Strict as M
import Text.ParserCombinators.Parsec
parser :: String -> Memory
parser = either (error "Bad parse") (M.fromList . zip [0..]) . parse numbers "Opcodes"
where numbers = map read <$> sepBy (minus <|> num) (char ',')
num = many1 digit
minus = (:) <$> char '-' <*> num
type Memory = M.Map Int Int
type Hull = M.Map Pos Int
type Facing = Complex Float
type Pos = (Int, Int)
data ProgramState = Wait Int Int [Int] [Int] Memory
| Halt [Int]
deriving Show
data RobotState = Hold Hull Pos Facing
| Fin Hull
index :: Int -> Memory -> Int
index = M.findWithDefault 0
args :: Int -> Int -> Memory -> (Int, Int, Int)
args i rel mem =
let mode x = div (M.findWithDefault 0 i mem) x `rem` 10
f x = case mode (10^(x+1)) of
0 -> index (index (i + x) mem) mem
1 -> index (i + x) mem
2 -> index (rel + (index (i + x) mem)) mem
g = case div (index i mem) 10000 `rem` 10 of
2 -> rel + (index (i + 3) mem)
_ -> index (i + 3) mem
in (f 1, f 2, g)
compute :: Int -> Int -> [Int] -> Memory -> [Int]
compute i rel input memory =
let (a, b, c) = args i rel memory
in case rem (M.findWithDefault 0 i memory) 100 of
1 -> compute (i + 4) rel input (M.insert c (a + b) memory)
2 -> compute (i + 4) rel input (M.insert c (a * b) memory)
3 -> let ix = case div (index i memory) 100 `rem` 10 of
2 -> rel + (index (i + 1) memory)
_ -> index (i + 1) memory
in compute (i + 2) rel (tail input) (M.insert ix (head input) memory)
4 -> a : compute (i + 2) rel input memory
5 -> compute (bool (i + 3) b (0 /= a)) rel input memory
6 -> compute (bool (i + 3) b (0 == a)) rel input memory
7 -> compute (i + 4) rel input (M.insert c (bool 0 1 (a < b)) memory)
8 -> compute (i + 4) rel input (M.insert c (bool 0 1 (a == b)) memory)
9 -> compute (i + 2) (rel + a) input memory
99 -> []
i -> error ("Invalid opcode: " ++ show i)
runRobot :: Int -> Memory -> Hull
runRobot init memory =
let input = compute 0 0 (map g states) memory
states = scanl f (M.fromList [((0,0), init)], (0, 0), (1:+1)) . chunksOf 2 $ input
f (hull, pos, dir) [col, ddir] =
let hull' = M.insert pos col hull
dir' = newDir dir ddir
pos' = move pos dir'
in (hull', pos', dir')
g (m, p, _) = M.findWithDefault 0 p m
(hull, _, _) = last states
in hull
newDir :: Facing -> Int -> Facing
newDir c 1 = c * (0:+1)
newDir c 0 = c * (0:+(-1))
move :: Pos -> Facing -> Pos
printHull :: Hull -> IO ()
printHull positions =
let ks = M.keys positions
xs = map fst ks
ys = map snd ks
(topX, botX) = (maximum xs, minimum xs)
(topY, botY) = (maximum ys, minimum ys)
lines = map (mkLine positions botX topX) [botY..topY]
in mapM_ putStrLn $ reverse lines
where mkLine hull from to row
| from > to = ""
| otherwise = toChar (M.findWithDefault 0 (from, row) hull) : mkLine hull (from + 1) to row
toChar x = if (x == 1) then '🔴' else '🖤'
solveA :: Memory -> Int
solveA mem = length . M.keys $ runRobot 0 mem
solveB :: Memory -> IO ()
solveB mem = printHull $ runRobot 1 mem
main = do
contents <- parser <$> readFile "data/input-2019-11.txt"
print $ solveA contents
solveB contents
1747
ZCGRHKLB
|
95778f777274bec9650ae4267e398fe63606fd8f4943d6d85d997c76e7b80382 | priornix/antizer | reagent.cljs | (ns antizer-examples.reagent
(:require [clojure.string :as string]
[antizer.reagent :as ant]
[antizer-examples.common :as common]
;; each language has to be required seperately
;; in order for the display to be correct
[cljsjs.moment]
[cljsjs.moment.locale.es]
[cljsjs.moment.locale.de]
[cljsjs.moment.locale.ja]
[cljsjs.moment.locale.ru]
[cljsjs.moment.locale.zh-cn]
[reagent.core :as r]))
(defn auto-complete []
(let [data (r/atom [])]
(fn []
[:div
[:h2 (str "Autocomplete")]
[ant/auto-complete
we need to use dataSource instead of data - source , see README.MD
{:style {:width "80%"} :dataSource @data
:on-search
(fn [x]
(reset! data
(if (empty? x)
[]
(take 3 (iterate #(str % (string/reverse %)) x)))))
:placeholder "Enter something"}]])))
(defn avatar []
[:div.avatar
[:h2 "Avatar"]
[:div
[ant/avatar {:style {:background-color "#87d068"} :icon "user" :class "va-middle"}]
[ant/avatar {:style {:color "#f56a00" :background-color "#fde3cf"} :class "va-middle"} "U"]
[ant/avatar {:style {:background-color "#ffbf00"} :class "va-middle"} "John"]
[ant/badge {:count 10} [ant/avatar {:style {:background-color "#108ee9"} :shape "square" :icon "user"}]]]])
(defn buttons []
[:div.example-button
[:h2 "Buttons"]
[ant/button {:type "primary"} "Primary"]
[ant/button "Default"]
[ant/button {:type "danger"} "Warning"]
[ant/button {:icon "shopping-cart" :type "primary"} "With icon"]
[ant/button {:icon "edit" :type "primary"}]])
(defn card []
[:div
[:h2 "Cards"]
[ant/card {:title "Title" :bordered true :class "card"}
[:p "Not the usual lorem ipsum"]] [:br]
[ant/card {:bordered true :class "card-photo"}
[:div [:img {:src ""}]]
[ant/col {:span 12} [:div [:h3 "Please rate me"]]]
[ant/col {:span 12} [ant/rate]]] [:br]
[ant/card {:style {:width "300"}
:cover (r/as-element
[:img {:alt "example" :src ""}])
:actions [(r/as-element [ant/icon {:type "setting"}])
(r/as-element [ant/icon {:type "edit"}])
(r/as-element [ant/icon {:type "ellipsis"}])]}
[ant/card-meta {:avatar (r/as-element [ant/avatar {:src ""}])
:title "Card title"
:description "This is the description"}]]])
(defn carousel []
[:div
[:h2 "Carousel"]
[ant/carousel {:autoplay true :dots true}
(for [i (range 3)]
[:div {:key i} [:img {:src (str "=" i)}]])]])
(defn add-actions-column [columns data-atom]
(conj columns
{:title "Actions"
:render
#(r/as-element
[ant/button {:icon "delete" :type "danger"
:on-click
(fn []
(reset! data-atom
(remove (fn [d] (= (get (js->clj %2) "id")
(:id d))) @data-atom)))}])}))
(defn datatable []
(let [data (r/atom common/people)]
(fn []
[:div
[:h2 "Data Table"]
[ant/table
{:columns (add-actions-column common/columns data)
:dataSource @data :pagination common/pagination :row-key "id"
:row-selection
{:on-change
#(let [selected (js->clj %2 :keywordize-keys true)]
(ant/message-info (str "You have selected: " (map :name selected))))}}]])))
(defn user-form [display-buttons?]
(fn [props]
(let [form (ant/get-form)]
[ant/form {:layout "horizontal"}
[ant/form-item (merge common/form-style {:label "Name"})
(ant/decorate-field form "name" {:rules [{:required true}]}
[ant/input])]
[ant/form-item (merge common/form-style {:label "Email"})
(ant/decorate-field form "email" {:rules [{:required true} {:type "email"}]}
[ant/input])]
[ant/form-item (merge common/form-style {:label "Address"})
(ant/decorate-field form "address" {:initial-value "Some initial value" :rules [{:required true}]}
[ant/input])]
[ant/form-item (merge common/form-style {:label "Years of Experience"})
(ant/decorate-field form "experience" {:rules [{:required true}]}
[ant/radio-group
[ant/radio {:value 1} "1-10"]
[ant/radio {:value 10} "10-30"]
[ant/radio {:value 30} "30-50"]
[ant/radio {:value 50} "> 50"]])]
[ant/form-item (merge common/form-style {:label "Start Date"})
(ant/decorate-field form "date" {:initial-value (js/moment) :rules [{:required true}]}
[ant/date-picker {:format "MMM Do YYYY"}])]
[ant/form-item (merge common/form-style {:label "Accept Terms?"})
(ant/decorate-field form "accept-terms"
[ant/switch])]
(if display-buttons?
[ant/form-item {:wrapper-col {:offset 6}}
[ant/row
[ant/col {:span 4}
[ant/button {:type "primary" :on-click #(ant/validate-fields form)}
"Submit"]]
[ant/col {:offset 1}
[ant/button {:on-click #(ant/reset-fields form)}
"Reset"]]]])])))
(defn form-example []
[:div
[:h2 "Form"]
(ant/create-form (user-form true))])
(defn localization []
(let [locale-atom (r/atom "en_US")]
(fn []
[ant/locale-provider {:locale (ant/locales @locale-atom)}
[:div
[:h2 "Localization"]
[:span "Choose a language:"
[ant/select {:default-value "en_US" :on-change #(common/set-locale %1 locale-atom) :style {:padding "10px"}}
[ant/select-option {:value "en_US"} "English"]
[ant/select-option {:value "es_ES"} "Español"]
[ant/select-option {:value "de_DE"} "Deutsch"]
[ant/select-option {:value "ru_RU"} "Русский"]
[ant/select-option {:value "zh_CN"} "中文"]
[ant/select-option {:value "ja_JP"} "日本語"]
[ant/select-option {:value "tlh" :disabled true} "Klingon"]]]
[ant/pagination {:total 40 :show-size-changer true}] [:br]
[ant/date-picker {:format "ddd MMM Do YYYY" :default-value (js/moment) :style {:width "60%"} :show-today false}] [:br] [:br]
[ant/time-picker {:style {:width "60%"}}] [:br] [:br]
[ant/calendar {:fullscreen false :default-value (js/moment)}]
[ant/table {:columns common/columns}]]])))
(defn messages []
[:div.example-button
[:h2 "Messages"]
[ant/button {:on-click #(ant/message-info "Normal message")} "Normal"]
[ant/button {:on-click #(ant/message-success "Success message")} "Success"]
[ant/button {:on-click #(ant/message-warning "Warning message")} "Warning"]
[ant/button {:on-click #(ant/message-error "Error message")} "Error"]
[ant/button {:on-click #(ant/message-loading "This message will disappear in 10 seconds" 10)} "Timed"]])
(defn modal []
(let [modal1 (r/atom false)
modal-form (r/atom false)]
(fn []
[:div.example-button
[:h2 "Modal"]
[ant/button {:on-click #(reset! modal1 true)} "Modal Dialog"]
[ant/modal {:visible @modal1 :title "Title of modal"
:on-ok #(reset! modal1 false) :on-cancel #(reset! modal1 false)}
(r/as-element [:p "Some content 1"])]
[ant/button {:on-click #(ant/modal-confirm {:title "Are you sure?" :content "Some content"})} "Confirmation Modal"]
[ant/button {:on-click #(reset! modal-form true)} "Modal Form"]
[ant/modal {:visible @modal-form :title "Modal Form" :width 600
:on-ok #(reset! modal-form false) :on-cancel #(reset! modal-form false)}
(ant/create-form (user-form false))]])))
(defn notifications []
[:div.example-button
[:h2 "Notifications"]
[ant/button {:on-click #(ant/notification-open
{:message "Timed Notification"
:description "This notification will close after 4.5 seconds"})}
"Notification"]
[ant/button {:on-click
#(let [key (random-uuid)]
(ant/notification-open
{:message "Popup Notification"
:duration 0
:btn (r/as-element
[ant/button {:type "primary"
:on-click (fn [] (ant/notification-close key))}
"Click to dismiss"])
:key key
:description "This notification will not close until it is dismissed"}))}
"Popup Notification"]])
(defn progress []
(let [percent (r/atom 50)]
(fn []
(let [operate (fn [operation]
(if (= :plus operation)
(if (< @percent 100) (swap! percent + 10))
(if (>= @percent 0) (swap! percent - 10))))
status (cond
(< @percent 42) "exception"
(= @percent 100) "success"
:else "active")]
[:div.progress
[:h2 "Progress"]
[ant/progress {:type "circle" :percent @percent :status status}]
[ant/button-group
[ant/button {:icon "plus" :on-click #(operate :plus)}]
[ant/button {:icon "minus" :on-click #(operate :minus)}]]
[ant/progress {:percent @percent :status status
:style {:width "42%"}}]]))))
(defn timeline []
[:div
[:h2 "Timeline"]
[ant/timeline
[ant/timeline-item {:color "red"} "6th June Project created"]
[ant/timeline-item {:color "blue"} "8th June Initial prototype done"]
[ant/timeline-item {:color "green"} "26th June Final Release"]]])
(defn tooltip []
[:div.example-button
[:h2 "Tooltips and Popups " [ant/tooltip {:title "Found me!"}
[ant/icon {:type "question-circle-o" :style {:font-size 13}}]]]
[ant/tooltip {:title "Tooltip"} [ant/button "Tooltip"]]
[ant/popover {:content "Dum dee dee dum dee dee dum" :title "Deedee dum"} [ant/button "Popover"]]
[ant/popconfirm {:title "Are you sure?"
:on-confirm #(ant/message-success "You clicked OK")
:on-cancel #(ant/message-error "You clicked Cancel")}
[ant/button "Click to confirm"]]])
(defn tree []
[:div
[:h2 "Tree"]
[ant/tree {:checkable true :default-expanded-keys ["functional" "clr" "jvm" "javascript" "nodejs"]
:default-checked-keys ["clojure" "clojure-clr" "cljs" "lumo" "planck"]}
[ant/tree-tree-node {:title "Functional Languages" :key "functional"}
[ant/tree-tree-node {:title "CLR" :key "clr"}
[ant/tree-tree-node {:title "Clojure CLR" :key "clojure-clr"}]]
[ant/tree-tree-node {:title "Haskell" :key "haskell"}]
[ant/tree-tree-node {:title "JVM" :key "jvm"}
[ant/tree-tree-node {:title "Clojure" :key "clojure"}]
[ant/tree-tree-node {:title "Frege" :key "frege"}]
[ant/tree-tree-node {:title "Scala" :disable-checkbox true}]]
[ant/tree-tree-node {:title "JavaScript Engine" :key "javascript"}
[ant/tree-tree-node {:title "ClojureScript" :key "cljs"}]]
[ant/tree-tree-node {:title "Node.js" :key "nodejs"}
[ant/tree-tree-node {:title "Lumo" :key "lumo"}]]
[ant/tree-tree-node {:title "Planck" :key "planck"}]]]])
(defn render-example
"Render each example within a bordered box"
[examples]
;; we need to generate a different key for each react element
[ant/col {:span 12}
(for [example examples]
[:div.box {:key (random-uuid)}
[:div.box-content
[example]]])])
(defn render-full-row [example]
[ant/col {:span 24}
[:div.box {:key (random-uuid)}
[:div.box-content
[example]]]])
(defn content-area []
[ant/layout-content {:class "content-area"}
[ant/row {:gutter 12}
(render-example [carousel buttons messages tooltip notifications timeline tree progress])
(render-example [card auto-complete localization modal avatar])
(render-full-row form-example)
(render-full-row datatable)]])
(defn side-menu []
[ant/menu {:mode "inline" :theme "dark" :style {:height "100%"}}
[ant/menu-item {:disabled true} "Menu without icons"]
[ant/menu-item "Menu Item"]
[ant/menu-sub-menu {:title "Sub Menu"}
[ant/menu-item "Item 1"]
[ant/menu-item "Item 2"]]
[ant/menu-item {:disabled true} "Menu with Icons"]
[ant/menu-item (r/as-element [:span [ant/icon {:type "home"}] "Menu Item"])]
[ant/menu-sub-menu {:title (r/as-element [:span [ant/icon {:type "setting"}] "Sub Menu"])}
[ant/menu-item (r/as-element [:span [ant/icon {:type "user"}] "Item 1"])]
[ant/menu-item (r/as-element [:span [ant/icon {:type "notification"}] "Item 2"])]]])
(defn render-layout []
(fn []
[ant/locale-provider {:locale (ant/locales "en_US")}
[ant/layout
[ant/affix
[ant/layout-header {:class "banner"}
(r/as-element
[ant/row
[ant/col {:span 12} [:h2.banner-header "Antizer Reagent Example"]]
[ant/col {:span 1 :offset 11}
[:a {:href ""}
[ant/icon {:class "banner-logo" :type "github"}]]]])]]
[ant/layout
[ant/layout-sider [side-menu]]
[ant/layout {:style {:width "60%"}}
[content-area]]]]]))
(defn init! []
(r/render [render-layout]
(js/document.getElementById "app")))
| null | https://raw.githubusercontent.com/priornix/antizer/bf5ca3344e8604e63c0214e377681434ee1b1597/examples/src/antizer_examples/reagent.cljs | clojure | each language has to be required seperately
in order for the display to be correct
we need to generate a different key for each react element | (ns antizer-examples.reagent
(:require [clojure.string :as string]
[antizer.reagent :as ant]
[antizer-examples.common :as common]
[cljsjs.moment]
[cljsjs.moment.locale.es]
[cljsjs.moment.locale.de]
[cljsjs.moment.locale.ja]
[cljsjs.moment.locale.ru]
[cljsjs.moment.locale.zh-cn]
[reagent.core :as r]))
(defn auto-complete []
(let [data (r/atom [])]
(fn []
[:div
[:h2 (str "Autocomplete")]
[ant/auto-complete
we need to use dataSource instead of data - source , see README.MD
{:style {:width "80%"} :dataSource @data
:on-search
(fn [x]
(reset! data
(if (empty? x)
[]
(take 3 (iterate #(str % (string/reverse %)) x)))))
:placeholder "Enter something"}]])))
(defn avatar []
[:div.avatar
[:h2 "Avatar"]
[:div
[ant/avatar {:style {:background-color "#87d068"} :icon "user" :class "va-middle"}]
[ant/avatar {:style {:color "#f56a00" :background-color "#fde3cf"} :class "va-middle"} "U"]
[ant/avatar {:style {:background-color "#ffbf00"} :class "va-middle"} "John"]
[ant/badge {:count 10} [ant/avatar {:style {:background-color "#108ee9"} :shape "square" :icon "user"}]]]])
(defn buttons []
[:div.example-button
[:h2 "Buttons"]
[ant/button {:type "primary"} "Primary"]
[ant/button "Default"]
[ant/button {:type "danger"} "Warning"]
[ant/button {:icon "shopping-cart" :type "primary"} "With icon"]
[ant/button {:icon "edit" :type "primary"}]])
(defn card []
[:div
[:h2 "Cards"]
[ant/card {:title "Title" :bordered true :class "card"}
[:p "Not the usual lorem ipsum"]] [:br]
[ant/card {:bordered true :class "card-photo"}
[:div [:img {:src ""}]]
[ant/col {:span 12} [:div [:h3 "Please rate me"]]]
[ant/col {:span 12} [ant/rate]]] [:br]
[ant/card {:style {:width "300"}
:cover (r/as-element
[:img {:alt "example" :src ""}])
:actions [(r/as-element [ant/icon {:type "setting"}])
(r/as-element [ant/icon {:type "edit"}])
(r/as-element [ant/icon {:type "ellipsis"}])]}
[ant/card-meta {:avatar (r/as-element [ant/avatar {:src ""}])
:title "Card title"
:description "This is the description"}]]])
(defn carousel []
[:div
[:h2 "Carousel"]
[ant/carousel {:autoplay true :dots true}
(for [i (range 3)]
[:div {:key i} [:img {:src (str "=" i)}]])]])
(defn add-actions-column [columns data-atom]
(conj columns
{:title "Actions"
:render
#(r/as-element
[ant/button {:icon "delete" :type "danger"
:on-click
(fn []
(reset! data-atom
(remove (fn [d] (= (get (js->clj %2) "id")
(:id d))) @data-atom)))}])}))
(defn datatable []
(let [data (r/atom common/people)]
(fn []
[:div
[:h2 "Data Table"]
[ant/table
{:columns (add-actions-column common/columns data)
:dataSource @data :pagination common/pagination :row-key "id"
:row-selection
{:on-change
#(let [selected (js->clj %2 :keywordize-keys true)]
(ant/message-info (str "You have selected: " (map :name selected))))}}]])))
(defn user-form [display-buttons?]
(fn [props]
(let [form (ant/get-form)]
[ant/form {:layout "horizontal"}
[ant/form-item (merge common/form-style {:label "Name"})
(ant/decorate-field form "name" {:rules [{:required true}]}
[ant/input])]
[ant/form-item (merge common/form-style {:label "Email"})
(ant/decorate-field form "email" {:rules [{:required true} {:type "email"}]}
[ant/input])]
[ant/form-item (merge common/form-style {:label "Address"})
(ant/decorate-field form "address" {:initial-value "Some initial value" :rules [{:required true}]}
[ant/input])]
[ant/form-item (merge common/form-style {:label "Years of Experience"})
(ant/decorate-field form "experience" {:rules [{:required true}]}
[ant/radio-group
[ant/radio {:value 1} "1-10"]
[ant/radio {:value 10} "10-30"]
[ant/radio {:value 30} "30-50"]
[ant/radio {:value 50} "> 50"]])]
[ant/form-item (merge common/form-style {:label "Start Date"})
(ant/decorate-field form "date" {:initial-value (js/moment) :rules [{:required true}]}
[ant/date-picker {:format "MMM Do YYYY"}])]
[ant/form-item (merge common/form-style {:label "Accept Terms?"})
(ant/decorate-field form "accept-terms"
[ant/switch])]
(if display-buttons?
[ant/form-item {:wrapper-col {:offset 6}}
[ant/row
[ant/col {:span 4}
[ant/button {:type "primary" :on-click #(ant/validate-fields form)}
"Submit"]]
[ant/col {:offset 1}
[ant/button {:on-click #(ant/reset-fields form)}
"Reset"]]]])])))
(defn form-example []
[:div
[:h2 "Form"]
(ant/create-form (user-form true))])
(defn localization []
(let [locale-atom (r/atom "en_US")]
(fn []
[ant/locale-provider {:locale (ant/locales @locale-atom)}
[:div
[:h2 "Localization"]
[:span "Choose a language:"
[ant/select {:default-value "en_US" :on-change #(common/set-locale %1 locale-atom) :style {:padding "10px"}}
[ant/select-option {:value "en_US"} "English"]
[ant/select-option {:value "es_ES"} "Español"]
[ant/select-option {:value "de_DE"} "Deutsch"]
[ant/select-option {:value "ru_RU"} "Русский"]
[ant/select-option {:value "zh_CN"} "中文"]
[ant/select-option {:value "ja_JP"} "日本語"]
[ant/select-option {:value "tlh" :disabled true} "Klingon"]]]
[ant/pagination {:total 40 :show-size-changer true}] [:br]
[ant/date-picker {:format "ddd MMM Do YYYY" :default-value (js/moment) :style {:width "60%"} :show-today false}] [:br] [:br]
[ant/time-picker {:style {:width "60%"}}] [:br] [:br]
[ant/calendar {:fullscreen false :default-value (js/moment)}]
[ant/table {:columns common/columns}]]])))
(defn messages []
[:div.example-button
[:h2 "Messages"]
[ant/button {:on-click #(ant/message-info "Normal message")} "Normal"]
[ant/button {:on-click #(ant/message-success "Success message")} "Success"]
[ant/button {:on-click #(ant/message-warning "Warning message")} "Warning"]
[ant/button {:on-click #(ant/message-error "Error message")} "Error"]
[ant/button {:on-click #(ant/message-loading "This message will disappear in 10 seconds" 10)} "Timed"]])
(defn modal []
(let [modal1 (r/atom false)
modal-form (r/atom false)]
(fn []
[:div.example-button
[:h2 "Modal"]
[ant/button {:on-click #(reset! modal1 true)} "Modal Dialog"]
[ant/modal {:visible @modal1 :title "Title of modal"
:on-ok #(reset! modal1 false) :on-cancel #(reset! modal1 false)}
(r/as-element [:p "Some content 1"])]
[ant/button {:on-click #(ant/modal-confirm {:title "Are you sure?" :content "Some content"})} "Confirmation Modal"]
[ant/button {:on-click #(reset! modal-form true)} "Modal Form"]
[ant/modal {:visible @modal-form :title "Modal Form" :width 600
:on-ok #(reset! modal-form false) :on-cancel #(reset! modal-form false)}
(ant/create-form (user-form false))]])))
(defn notifications []
[:div.example-button
[:h2 "Notifications"]
[ant/button {:on-click #(ant/notification-open
{:message "Timed Notification"
:description "This notification will close after 4.5 seconds"})}
"Notification"]
[ant/button {:on-click
#(let [key (random-uuid)]
(ant/notification-open
{:message "Popup Notification"
:duration 0
:btn (r/as-element
[ant/button {:type "primary"
:on-click (fn [] (ant/notification-close key))}
"Click to dismiss"])
:key key
:description "This notification will not close until it is dismissed"}))}
"Popup Notification"]])
(defn progress []
(let [percent (r/atom 50)]
(fn []
(let [operate (fn [operation]
(if (= :plus operation)
(if (< @percent 100) (swap! percent + 10))
(if (>= @percent 0) (swap! percent - 10))))
status (cond
(< @percent 42) "exception"
(= @percent 100) "success"
:else "active")]
[:div.progress
[:h2 "Progress"]
[ant/progress {:type "circle" :percent @percent :status status}]
[ant/button-group
[ant/button {:icon "plus" :on-click #(operate :plus)}]
[ant/button {:icon "minus" :on-click #(operate :minus)}]]
[ant/progress {:percent @percent :status status
:style {:width "42%"}}]]))))
(defn timeline []
[:div
[:h2 "Timeline"]
[ant/timeline
[ant/timeline-item {:color "red"} "6th June Project created"]
[ant/timeline-item {:color "blue"} "8th June Initial prototype done"]
[ant/timeline-item {:color "green"} "26th June Final Release"]]])
(defn tooltip []
[:div.example-button
[:h2 "Tooltips and Popups " [ant/tooltip {:title "Found me!"}
[ant/icon {:type "question-circle-o" :style {:font-size 13}}]]]
[ant/tooltip {:title "Tooltip"} [ant/button "Tooltip"]]
[ant/popover {:content "Dum dee dee dum dee dee dum" :title "Deedee dum"} [ant/button "Popover"]]
[ant/popconfirm {:title "Are you sure?"
:on-confirm #(ant/message-success "You clicked OK")
:on-cancel #(ant/message-error "You clicked Cancel")}
[ant/button "Click to confirm"]]])
(defn tree []
[:div
[:h2 "Tree"]
[ant/tree {:checkable true :default-expanded-keys ["functional" "clr" "jvm" "javascript" "nodejs"]
:default-checked-keys ["clojure" "clojure-clr" "cljs" "lumo" "planck"]}
[ant/tree-tree-node {:title "Functional Languages" :key "functional"}
[ant/tree-tree-node {:title "CLR" :key "clr"}
[ant/tree-tree-node {:title "Clojure CLR" :key "clojure-clr"}]]
[ant/tree-tree-node {:title "Haskell" :key "haskell"}]
[ant/tree-tree-node {:title "JVM" :key "jvm"}
[ant/tree-tree-node {:title "Clojure" :key "clojure"}]
[ant/tree-tree-node {:title "Frege" :key "frege"}]
[ant/tree-tree-node {:title "Scala" :disable-checkbox true}]]
[ant/tree-tree-node {:title "JavaScript Engine" :key "javascript"}
[ant/tree-tree-node {:title "ClojureScript" :key "cljs"}]]
[ant/tree-tree-node {:title "Node.js" :key "nodejs"}
[ant/tree-tree-node {:title "Lumo" :key "lumo"}]]
[ant/tree-tree-node {:title "Planck" :key "planck"}]]]])
(defn render-example
"Render each example within a bordered box"
[examples]
[ant/col {:span 12}
(for [example examples]
[:div.box {:key (random-uuid)}
[:div.box-content
[example]]])])
(defn render-full-row [example]
[ant/col {:span 24}
[:div.box {:key (random-uuid)}
[:div.box-content
[example]]]])
(defn content-area []
[ant/layout-content {:class "content-area"}
[ant/row {:gutter 12}
(render-example [carousel buttons messages tooltip notifications timeline tree progress])
(render-example [card auto-complete localization modal avatar])
(render-full-row form-example)
(render-full-row datatable)]])
(defn side-menu []
[ant/menu {:mode "inline" :theme "dark" :style {:height "100%"}}
[ant/menu-item {:disabled true} "Menu without icons"]
[ant/menu-item "Menu Item"]
[ant/menu-sub-menu {:title "Sub Menu"}
[ant/menu-item "Item 1"]
[ant/menu-item "Item 2"]]
[ant/menu-item {:disabled true} "Menu with Icons"]
[ant/menu-item (r/as-element [:span [ant/icon {:type "home"}] "Menu Item"])]
[ant/menu-sub-menu {:title (r/as-element [:span [ant/icon {:type "setting"}] "Sub Menu"])}
[ant/menu-item (r/as-element [:span [ant/icon {:type "user"}] "Item 1"])]
[ant/menu-item (r/as-element [:span [ant/icon {:type "notification"}] "Item 2"])]]])
(defn render-layout []
(fn []
[ant/locale-provider {:locale (ant/locales "en_US")}
[ant/layout
[ant/affix
[ant/layout-header {:class "banner"}
(r/as-element
[ant/row
[ant/col {:span 12} [:h2.banner-header "Antizer Reagent Example"]]
[ant/col {:span 1 :offset 11}
[:a {:href ""}
[ant/icon {:class "banner-logo" :type "github"}]]]])]]
[ant/layout
[ant/layout-sider [side-menu]]
[ant/layout {:style {:width "60%"}}
[content-area]]]]]))
(defn init! []
(r/render [render-layout]
(js/document.getElementById "app")))
|
4edbec75f3b8be8aa24edbda709ad2506ccd70c221f7ed2c3525a5406a608202 | bmeurer/ocaml-arm | unix.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../../LICENSE. *)
(* *)
(***********************************************************************)
$ Id$
type error =
E2BIG
| EACCES
| EAGAIN
| EBADF
| EBUSY
| ECHILD
| EDEADLK
| EDOM
| EEXIST
| EFAULT
| EFBIG
| EINTR
| EINVAL
| EIO
| EISDIR
| EMFILE
| EMLINK
| ENAMETOOLONG
| ENFILE
| ENODEV
| ENOENT
| ENOEXEC
| ENOLCK
| ENOMEM
| ENOSPC
| ENOSYS
| ENOTDIR
| ENOTEMPTY
| ENOTTY
| ENXIO
| EPERM
| EPIPE
| ERANGE
| EROFS
| ESPIPE
| ESRCH
| EXDEV
| EWOULDBLOCK
| EINPROGRESS
| EALREADY
| ENOTSOCK
| EDESTADDRREQ
| EMSGSIZE
| EPROTOTYPE
| ENOPROTOOPT
| EPROTONOSUPPORT
| ESOCKTNOSUPPORT
| EOPNOTSUPP
| EPFNOSUPPORT
| EAFNOSUPPORT
| EADDRINUSE
| EADDRNOTAVAIL
| ENETDOWN
| ENETUNREACH
| ENETRESET
| ECONNABORTED
| ECONNRESET
| ENOBUFS
| EISCONN
| ENOTCONN
| ESHUTDOWN
| ETOOMANYREFS
| ETIMEDOUT
| ECONNREFUSED
| EHOSTDOWN
| EHOSTUNREACH
| ELOOP
| EOVERFLOW
| EUNKNOWNERR of int
exception Unix_error of error * string * string
let _ = Callback.register_exception "Unix.Unix_error"
(Unix_error(E2BIG, "", ""))
external error_message : error -> string = "unix_error_message"
let handle_unix_error f arg =
try
f arg
with Unix_error(err, fun_name, arg) ->
prerr_string Sys.argv.(0);
prerr_string ": \"";
prerr_string fun_name;
prerr_string "\" failed";
if String.length arg > 0 then begin
prerr_string " on \"";
prerr_string arg;
prerr_string "\""
end;
prerr_string ": ";
prerr_endline (error_message err);
exit 2
external environment : unit -> string array = "unix_environment"
external getenv: string -> string = "caml_sys_getenv"
external putenv: string -> string -> unit = "unix_putenv"
type process_status =
WEXITED of int
| WSIGNALED of int
| WSTOPPED of int
type wait_flag =
WNOHANG
| WUNTRACED
external execv : string -> string array -> 'a = "unix_execv"
external execve : string -> string array -> string array -> 'a = "unix_execve"
external execvp : string -> string array -> 'a = "unix_execvp"
external execvpe : string -> string array -> string array -> 'a = "unix_execvpe"
external fork : unit -> int = "unix_fork"
external wait : unit -> int * process_status = "unix_wait"
external waitpid : wait_flag list -> int -> int * process_status = "unix_waitpid"
external getpid : unit -> int = "unix_getpid"
external getppid : unit -> int = "unix_getppid"
external nice : int -> int = "unix_nice"
type file_descr = int
let stdin = 0
let stdout = 1
let stderr = 2
type open_flag =
O_RDONLY
| O_WRONLY
| O_RDWR
| O_NONBLOCK
| O_APPEND
| O_CREAT
| O_TRUNC
| O_EXCL
| O_NOCTTY
| O_DSYNC
| O_SYNC
| O_RSYNC
| O_SHARE_DELETE
type file_perm = int
external openfile : string -> open_flag list -> file_perm -> file_descr
= "unix_open"
external close : file_descr -> unit = "unix_close"
external unsafe_read : file_descr -> string -> int -> int -> int = "unix_read"
external unsafe_write : file_descr -> string -> int -> int -> int = "unix_write"
external unsafe_single_write : file_descr -> string -> int -> int -> int = "unix_single_write"
let read fd buf ofs len =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "Unix.read"
else unsafe_read fd buf ofs len
let write fd buf ofs len =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "Unix.write"
else unsafe_write fd buf ofs len
write misbehaves because it attempts to write all data by making repeated
calls to the Unix write function ( see comment in write.c and unix.mli ) .
partial_write fixes this by never calling write twice .
calls to the Unix write function (see comment in write.c and unix.mli).
partial_write fixes this by never calling write twice. *)
let single_write fd buf ofs len =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "Unix.single_write"
else unsafe_single_write fd buf ofs len
external in_channel_of_descr : file_descr -> in_channel
= "caml_ml_open_descriptor_in"
external out_channel_of_descr : file_descr -> out_channel
= "caml_ml_open_descriptor_out"
external descr_of_in_channel : in_channel -> file_descr
= "caml_channel_descriptor"
external descr_of_out_channel : out_channel -> file_descr
= "caml_channel_descriptor"
type seek_command =
SEEK_SET
| SEEK_CUR
| SEEK_END
external lseek : file_descr -> int -> seek_command -> int = "unix_lseek"
external truncate : string -> int -> unit = "unix_truncate"
external ftruncate : file_descr -> int -> unit = "unix_ftruncate"
type file_kind =
S_REG
| S_DIR
| S_CHR
| S_BLK
| S_LNK
| S_FIFO
| S_SOCK
type stats =
{ st_dev : int;
st_ino : int;
st_kind : file_kind;
st_perm : file_perm;
st_nlink : int;
st_uid : int;
st_gid : int;
st_rdev : int;
st_size : int;
st_atime : float;
st_mtime : float;
st_ctime : float }
external stat : string -> stats = "unix_stat"
external lstat : string -> stats = "unix_lstat"
external fstat : file_descr -> stats = "unix_fstat"
external isatty : file_descr -> bool = "unix_isatty"
external unlink : string -> unit = "unix_unlink"
external rename : string -> string -> unit = "unix_rename"
external link : string -> string -> unit = "unix_link"
module LargeFile =
struct
external lseek : file_descr -> int64 -> seek_command -> int64 = "unix_lseek_64"
external truncate : string -> int64 -> unit = "unix_truncate_64"
external ftruncate : file_descr -> int64 -> unit = "unix_ftruncate_64"
type stats =
{ st_dev : int;
st_ino : int;
st_kind : file_kind;
st_perm : file_perm;
st_nlink : int;
st_uid : int;
st_gid : int;
st_rdev : int;
st_size : int64;
st_atime : float;
st_mtime : float;
st_ctime : float;
}
external stat : string -> stats = "unix_stat_64"
external lstat : string -> stats = "unix_lstat_64"
external fstat : file_descr -> stats = "unix_fstat_64"
end
type access_permission =
R_OK
| W_OK
| X_OK
| F_OK
external chmod : string -> file_perm -> unit = "unix_chmod"
external fchmod : file_descr -> file_perm -> unit = "unix_fchmod"
external chown : string -> int -> int -> unit = "unix_chown"
external fchown : file_descr -> int -> int -> unit = "unix_fchown"
external umask : int -> int = "unix_umask"
external access : string -> access_permission list -> unit = "unix_access"
external dup : file_descr -> file_descr = "unix_dup"
external dup2 : file_descr -> file_descr -> unit = "unix_dup2"
external set_nonblock : file_descr -> unit = "unix_set_nonblock"
external clear_nonblock : file_descr -> unit = "unix_clear_nonblock"
external set_close_on_exec : file_descr -> unit = "unix_set_close_on_exec"
external clear_close_on_exec : file_descr -> unit = "unix_clear_close_on_exec"
FD_CLOEXEC should be supported on all Unix systems these days ,
but just in case ...
but just in case... *)
let try_set_close_on_exec fd =
try set_close_on_exec fd; true with Invalid_argument _ -> false
external mkdir : string -> file_perm -> unit = "unix_mkdir"
external rmdir : string -> unit = "unix_rmdir"
external chdir : string -> unit = "unix_chdir"
external getcwd : unit -> string = "unix_getcwd"
external chroot : string -> unit = "unix_chroot"
type dir_handle
external opendir : string -> dir_handle = "unix_opendir"
external readdir : dir_handle -> string = "unix_readdir"
external rewinddir : dir_handle -> unit = "unix_rewinddir"
external closedir : dir_handle -> unit = "unix_closedir"
external pipe : unit -> file_descr * file_descr = "unix_pipe"
external symlink : string -> string -> unit = "unix_symlink"
external readlink : string -> string = "unix_readlink"
external mkfifo : string -> file_perm -> unit = "unix_mkfifo"
external select :
file_descr list -> file_descr list -> file_descr list -> float ->
file_descr list * file_descr list * file_descr list = "unix_select"
type lock_command =
F_ULOCK
| F_LOCK
| F_TLOCK
| F_TEST
| F_RLOCK
| F_TRLOCK
external lockf : file_descr -> lock_command -> int -> unit = "unix_lockf"
external kill : int -> int -> unit = "unix_kill"
type sigprocmask_command = SIG_SETMASK | SIG_BLOCK | SIG_UNBLOCK
external sigprocmask: sigprocmask_command -> int list -> int list
= "unix_sigprocmask"
external sigpending: unit -> int list = "unix_sigpending"
external sigsuspend: int list -> unit = "unix_sigsuspend"
let pause() =
let sigs = sigprocmask SIG_BLOCK [] in sigsuspend sigs
type process_times =
{ tms_utime : float;
tms_stime : float;
tms_cutime : float;
tms_cstime : float }
type tm =
{ tm_sec : int;
tm_min : int;
tm_hour : int;
tm_mday : int;
tm_mon : int;
tm_year : int;
tm_wday : int;
tm_yday : int;
tm_isdst : bool }
external time : unit -> float = "unix_time"
external gettimeofday : unit -> float = "unix_gettimeofday"
external gmtime : float -> tm = "unix_gmtime"
external localtime : float -> tm = "unix_localtime"
external mktime : tm -> float * tm = "unix_mktime"
external alarm : int -> int = "unix_alarm"
external sleep : int -> unit = "unix_sleep"
external times : unit -> process_times = "unix_times"
external utimes : string -> float -> float -> unit = "unix_utimes"
type interval_timer =
ITIMER_REAL
| ITIMER_VIRTUAL
| ITIMER_PROF
type interval_timer_status =
{ it_interval: float; (* Period *)
it_value: float } (* Current value of the timer *)
external getitimer: interval_timer -> interval_timer_status = "unix_getitimer"
external setitimer:
interval_timer -> interval_timer_status -> interval_timer_status
= "unix_setitimer"
external getuid : unit -> int = "unix_getuid"
external geteuid : unit -> int = "unix_geteuid"
external setuid : int -> unit = "unix_setuid"
external getgid : unit -> int = "unix_getgid"
external getegid : unit -> int = "unix_getegid"
external setgid : int -> unit = "unix_setgid"
external getgroups : unit -> int array = "unix_getgroups"
external setgroups : int array -> unit = "unix_setgroups"
external initgroups : string -> int -> unit = "unix_initgroups"
type passwd_entry =
{ pw_name : string;
pw_passwd : string;
pw_uid : int;
pw_gid : int;
pw_gecos : string;
pw_dir : string;
pw_shell : string }
type group_entry =
{ gr_name : string;
gr_passwd : string;
gr_gid : int;
gr_mem : string array }
external getlogin : unit -> string = "unix_getlogin"
external getpwnam : string -> passwd_entry = "unix_getpwnam"
external getgrnam : string -> group_entry = "unix_getgrnam"
external getpwuid : int -> passwd_entry = "unix_getpwuid"
external getgrgid : int -> group_entry = "unix_getgrgid"
type inet_addr = string
let is_inet6_addr s = String.length s = 16
external inet_addr_of_string : string -> inet_addr
= "unix_inet_addr_of_string"
external string_of_inet_addr : inet_addr -> string
= "unix_string_of_inet_addr"
let inet_addr_any = inet_addr_of_string "0.0.0.0"
let inet_addr_loopback = inet_addr_of_string "127.0.0.1"
let inet6_addr_any =
try inet_addr_of_string "::" with Failure _ -> inet_addr_any
let inet6_addr_loopback =
try inet_addr_of_string "::1" with Failure _ -> inet_addr_loopback
type socket_domain =
PF_UNIX
| PF_INET
| PF_INET6
type socket_type =
SOCK_STREAM
| SOCK_DGRAM
| SOCK_RAW
| SOCK_SEQPACKET
type sockaddr =
ADDR_UNIX of string
| ADDR_INET of inet_addr * int
let domain_of_sockaddr = function
ADDR_UNIX _ -> PF_UNIX
| ADDR_INET(a, _) -> if is_inet6_addr a then PF_INET6 else PF_INET
type shutdown_command =
SHUTDOWN_RECEIVE
| SHUTDOWN_SEND
| SHUTDOWN_ALL
type msg_flag =
MSG_OOB
| MSG_DONTROUTE
| MSG_PEEK
external socket : socket_domain -> socket_type -> int -> file_descr
= "unix_socket"
external socketpair :
socket_domain -> socket_type -> int -> file_descr * file_descr
= "unix_socketpair"
external accept : file_descr -> file_descr * sockaddr = "unix_accept"
external bind : file_descr -> sockaddr -> unit = "unix_bind"
external connect : file_descr -> sockaddr -> unit = "unix_connect"
external listen : file_descr -> int -> unit = "unix_listen"
external shutdown : file_descr -> shutdown_command -> unit = "unix_shutdown"
external getsockname : file_descr -> sockaddr = "unix_getsockname"
external getpeername : file_descr -> sockaddr = "unix_getpeername"
external unsafe_recv :
file_descr -> string -> int -> int -> msg_flag list -> int
= "unix_recv"
external unsafe_recvfrom :
file_descr -> string -> int -> int -> msg_flag list -> int * sockaddr
= "unix_recvfrom"
external unsafe_send :
file_descr -> string -> int -> int -> msg_flag list -> int
= "unix_send"
external unsafe_sendto :
file_descr -> string -> int -> int -> msg_flag list -> sockaddr -> int
= "unix_sendto" "unix_sendto_native"
let recv fd buf ofs len flags =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "Unix.recv"
else unsafe_recv fd buf ofs len flags
let recvfrom fd buf ofs len flags =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "Unix.recvfrom"
else unsafe_recvfrom fd buf ofs len flags
let send fd buf ofs len flags =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "Unix.send"
else unsafe_send fd buf ofs len flags
let sendto fd buf ofs len flags addr =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "Unix.sendto"
else unsafe_sendto fd buf ofs len flags addr
type socket_bool_option =
SO_DEBUG
| SO_BROADCAST
| SO_REUSEADDR
| SO_KEEPALIVE
| SO_DONTROUTE
| SO_OOBINLINE
| SO_ACCEPTCONN
| TCP_NODELAY
| IPV6_ONLY
type socket_int_option =
SO_SNDBUF
| SO_RCVBUF
| SO_ERROR
| SO_TYPE
| SO_RCVLOWAT
| SO_SNDLOWAT
type socket_optint_option = SO_LINGER
type socket_float_option =
SO_RCVTIMEO
| SO_SNDTIMEO
type socket_error_option = SO_ERROR
module SO: sig
type ('opt, 'v) t
val bool: (socket_bool_option, bool) t
val int: (socket_int_option, int) t
val optint: (socket_optint_option, int option) t
val float: (socket_float_option, float) t
val error: (socket_error_option, error option) t
val get: ('opt, 'v) t -> file_descr -> 'opt -> 'v
val set: ('opt, 'v) t -> file_descr -> 'opt -> 'v -> unit
end = struct
type ('opt, 'v) t = int
let bool = 0
let int = 1
let optint = 2
let float = 3
let error = 4
external get: ('opt, 'v) t -> file_descr -> 'opt -> 'v
= "unix_getsockopt"
external set: ('opt, 'v) t -> file_descr -> 'opt -> 'v -> unit
= "unix_setsockopt"
end
let getsockopt fd opt = SO.get SO.bool fd opt
let setsockopt fd opt v = SO.set SO.bool fd opt v
let getsockopt_int fd opt = SO.get SO.int fd opt
let setsockopt_int fd opt v = SO.set SO.int fd opt v
let getsockopt_optint fd opt = SO.get SO.optint fd opt
let setsockopt_optint fd opt v = SO.set SO.optint fd opt v
let getsockopt_float fd opt = SO.get SO.float fd opt
let setsockopt_float fd opt v = SO.set SO.float fd opt v
let getsockopt_error fd = SO.get SO.error fd SO_ERROR
type host_entry =
{ h_name : string;
h_aliases : string array;
h_addrtype : socket_domain;
h_addr_list : inet_addr array }
type protocol_entry =
{ p_name : string;
p_aliases : string array;
p_proto : int }
type service_entry =
{ s_name : string;
s_aliases : string array;
s_port : int;
s_proto : string }
external gethostname : unit -> string = "unix_gethostname"
external gethostbyname : string -> host_entry = "unix_gethostbyname"
external gethostbyaddr : inet_addr -> host_entry = "unix_gethostbyaddr"
external getprotobyname : string -> protocol_entry
= "unix_getprotobyname"
external getprotobynumber : int -> protocol_entry
= "unix_getprotobynumber"
external getservbyname : string -> string -> service_entry
= "unix_getservbyname"
external getservbyport : int -> string -> service_entry
= "unix_getservbyport"
type addr_info =
{ ai_family : socket_domain;
ai_socktype : socket_type;
ai_protocol : int;
ai_addr : sockaddr;
ai_canonname : string }
type getaddrinfo_option =
AI_FAMILY of socket_domain
| AI_SOCKTYPE of socket_type
| AI_PROTOCOL of int
| AI_NUMERICHOST
| AI_CANONNAME
| AI_PASSIVE
external getaddrinfo_system
: string -> string -> getaddrinfo_option list -> addr_info list
= "unix_getaddrinfo"
let getaddrinfo_emulation node service opts =
Parse options
let opt_socktype = ref None
and opt_protocol = ref 0
and opt_passive = ref false in
List.iter
(function AI_SOCKTYPE s -> opt_socktype := Some s
| AI_PROTOCOL p -> opt_protocol := p
| AI_PASSIVE -> opt_passive := true
| _ -> ())
opts;
(* Determine socket types and port numbers *)
let get_port ty kind =
if service = "" then [ty, 0] else
try
[ty, int_of_string service]
with Failure _ ->
try
[ty, (getservbyname service kind).s_port]
with Not_found -> []
in
let ports =
match !opt_socktype with
| None ->
get_port SOCK_STREAM "tcp" @ get_port SOCK_DGRAM "udp"
| Some SOCK_STREAM ->
get_port SOCK_STREAM "tcp"
| Some SOCK_DGRAM ->
get_port SOCK_DGRAM "udp"
| Some ty ->
if service = "" then [ty, 0] else [] in
(* Determine IP addresses *)
let addresses =
if node = "" then
if List.mem AI_PASSIVE opts
then [inet_addr_any, "0.0.0.0"]
else [inet_addr_loopback, "127.0.0.1"]
else
try
[inet_addr_of_string node, node]
with Failure _ ->
try
let he = gethostbyname node in
List.map
(fun a -> (a, he.h_name))
(Array.to_list he.h_addr_list)
with Not_found ->
[] in
(* Cross-product of addresses and ports *)
List.flatten
(List.map
(fun (ty, port) ->
List.map
(fun (addr, name) ->
{ ai_family = PF_INET;
ai_socktype = ty;
ai_protocol = !opt_protocol;
ai_addr = ADDR_INET(addr, port);
ai_canonname = name })
addresses)
ports)
let getaddrinfo node service opts =
try
List.rev(getaddrinfo_system node service opts)
with Invalid_argument _ ->
getaddrinfo_emulation node service opts
type name_info =
{ ni_hostname : string;
ni_service : string }
type getnameinfo_option =
NI_NOFQDN
| NI_NUMERICHOST
| NI_NAMEREQD
| NI_NUMERICSERV
| NI_DGRAM
external getnameinfo_system
: sockaddr -> getnameinfo_option list -> name_info
= "unix_getnameinfo"
let getnameinfo_emulation addr opts =
match addr with
| ADDR_UNIX f ->
{ ni_hostname = ""; ni_service = f } (* why not? *)
| ADDR_INET(a, p) ->
let hostname =
try
if List.mem NI_NUMERICHOST opts then raise Not_found;
(gethostbyaddr a).h_name
with Not_found ->
if List.mem NI_NAMEREQD opts then raise Not_found;
string_of_inet_addr a in
let service =
try
if List.mem NI_NUMERICSERV opts then raise Not_found;
let kind = if List.mem NI_DGRAM opts then "udp" else "tcp" in
(getservbyport p kind).s_name
with Not_found ->
string_of_int p in
{ ni_hostname = hostname; ni_service = service }
let getnameinfo addr opts =
try
getnameinfo_system addr opts
with Invalid_argument _ ->
getnameinfo_emulation addr opts
type terminal_io = {
mutable c_ignbrk: bool;
mutable c_brkint: bool;
mutable c_ignpar: bool;
mutable c_parmrk: bool;
mutable c_inpck: bool;
mutable c_istrip: bool;
mutable c_inlcr: bool;
mutable c_igncr: bool;
mutable c_icrnl: bool;
mutable c_ixon: bool;
mutable c_ixoff: bool;
mutable c_opost: bool;
mutable c_obaud: int;
mutable c_ibaud: int;
mutable c_csize: int;
mutable c_cstopb: int;
mutable c_cread: bool;
mutable c_parenb: bool;
mutable c_parodd: bool;
mutable c_hupcl: bool;
mutable c_clocal: bool;
mutable c_isig: bool;
mutable c_icanon: bool;
mutable c_noflsh: bool;
mutable c_echo: bool;
mutable c_echoe: bool;
mutable c_echok: bool;
mutable c_echonl: bool;
mutable c_vintr: char;
mutable c_vquit: char;
mutable c_verase: char;
mutable c_vkill: char;
mutable c_veof: char;
mutable c_veol: char;
mutable c_vmin: int;
mutable c_vtime: int;
mutable c_vstart: char;
mutable c_vstop: char
}
external tcgetattr: file_descr -> terminal_io = "unix_tcgetattr"
type setattr_when = TCSANOW | TCSADRAIN | TCSAFLUSH
external tcsetattr: file_descr -> setattr_when -> terminal_io -> unit
= "unix_tcsetattr"
external tcsendbreak: file_descr -> int -> unit = "unix_tcsendbreak"
external tcdrain: file_descr -> unit = "unix_tcdrain"
type flush_queue = TCIFLUSH | TCOFLUSH | TCIOFLUSH
external tcflush: file_descr -> flush_queue -> unit = "unix_tcflush"
type flow_action = TCOOFF | TCOON | TCIOFF | TCION
external tcflow: file_descr -> flow_action -> unit = "unix_tcflow"
external setsid : unit -> int = "unix_setsid"
(* High-level process management (system, popen) *)
let system cmd =
match fork() with
0 -> begin try
execv "/bin/sh" [| "/bin/sh"; "-c"; cmd |]
with _ ->
exit 127
end
| id -> snd(waitpid [] id)
let rec safe_dup fd =
let new_fd = dup fd in
if new_fd >= 3 then
new_fd
else begin
let res = safe_dup fd in
close new_fd;
res
end
let safe_close fd =
try close fd with Unix_error(_,_,_) -> ()
let perform_redirections new_stdin new_stdout new_stderr =
let newnewstdin = safe_dup new_stdin in
let newnewstdout = safe_dup new_stdout in
let newnewstderr = safe_dup new_stderr in
safe_close new_stdin;
safe_close new_stdout;
safe_close new_stderr;
dup2 newnewstdin stdin; close newnewstdin;
dup2 newnewstdout stdout; close newnewstdout;
dup2 newnewstderr stderr; close newnewstderr
let create_process cmd args new_stdin new_stdout new_stderr =
match fork() with
0 ->
begin try
perform_redirections new_stdin new_stdout new_stderr;
execvp cmd args
with _ ->
exit 127
end
| id -> id
let create_process_env cmd args env new_stdin new_stdout new_stderr =
match fork() with
0 ->
begin try
perform_redirections new_stdin new_stdout new_stderr;
execvpe cmd args env
with _ ->
exit 127
end
| id -> id
type popen_process =
Process of in_channel * out_channel
| Process_in of in_channel
| Process_out of out_channel
| Process_full of in_channel * out_channel * in_channel
let popen_processes = (Hashtbl.create 7 : (popen_process, int) Hashtbl.t)
let open_proc cmd proc input output toclose =
let cloexec = List.for_all try_set_close_on_exec toclose in
match fork() with
0 -> if input <> stdin then begin dup2 input stdin; close input end;
if output <> stdout then begin dup2 output stdout; close output end;
if not cloexec then List.iter close toclose;
begin try execv "/bin/sh" [| "/bin/sh"; "-c"; cmd |]
with _ -> exit 127
end
| id -> Hashtbl.add popen_processes proc id
let open_process_in cmd =
let (in_read, in_write) = pipe() in
let inchan = in_channel_of_descr in_read in
begin
try
open_proc cmd (Process_in inchan) stdin in_write [in_read];
with e ->
close_in inchan;
close in_write;
raise e
end;
close in_write;
inchan
let open_process_out cmd =
let (out_read, out_write) = pipe() in
let outchan = out_channel_of_descr out_write in
begin
try
open_proc cmd (Process_out outchan) out_read stdout [out_write];
with e ->
close_out outchan;
close out_read;
raise e
end;
close out_read;
outchan
let open_process cmd =
let (in_read, in_write) = pipe() in
let fds_to_close = ref [in_read;in_write] in
try
let (out_read, out_write) = pipe() in
fds_to_close := [in_read;in_write;out_read;out_write];
let inchan = in_channel_of_descr in_read in
let outchan = out_channel_of_descr out_write in
open_proc cmd (Process(inchan, outchan)) out_read in_write
[in_read; out_write];
close out_read;
close in_write;
(inchan, outchan)
with e ->
List.iter close !fds_to_close;
raise e
let open_proc_full cmd env proc input output error toclose =
let cloexec = List.for_all try_set_close_on_exec toclose in
match fork() with
0 -> dup2 input stdin; close input;
dup2 output stdout; close output;
dup2 error stderr; close error;
if not cloexec then List.iter close toclose;
begin try execve "/bin/sh" [| "/bin/sh"; "-c"; cmd |] env
with _ -> exit 127
end
| id -> Hashtbl.add popen_processes proc id
let open_process_full cmd env =
let (in_read, in_write) = pipe() in
let fds_to_close = ref [in_read;in_write] in
try
let (out_read, out_write) = pipe() in
fds_to_close := out_read::out_write:: !fds_to_close;
let (err_read, err_write) = pipe() in
fds_to_close := err_read::err_write:: !fds_to_close;
let inchan = in_channel_of_descr in_read in
let outchan = out_channel_of_descr out_write in
let errchan = in_channel_of_descr err_read in
open_proc_full cmd env (Process_full(inchan, outchan, errchan))
out_read in_write err_write [in_read; out_write; err_read];
close out_read;
close in_write;
close err_write;
(inchan, outchan, errchan)
with e ->
List.iter close !fds_to_close;
raise e
let find_proc_id fun_name proc =
try
let pid = Hashtbl.find popen_processes proc in
Hashtbl.remove popen_processes proc;
pid
with Not_found ->
raise(Unix_error(EBADF, fun_name, ""))
let rec waitpid_non_intr pid =
try waitpid [] pid
with Unix_error (EINTR, _, _) -> waitpid_non_intr pid
let close_process_in inchan =
let pid = find_proc_id "close_process_in" (Process_in inchan) in
close_in inchan;
snd(waitpid_non_intr pid)
let close_process_out outchan =
let pid = find_proc_id "close_process_out" (Process_out outchan) in
close_out outchan;
snd(waitpid_non_intr pid)
let close_process (inchan, outchan) =
let pid = find_proc_id "close_process" (Process(inchan, outchan)) in
close_in inchan;
begin try close_out outchan with Sys_error _ -> () end;
snd(waitpid_non_intr pid)
let close_process_full (inchan, outchan, errchan) =
let pid =
find_proc_id "close_process_full"
(Process_full(inchan, outchan, errchan)) in
close_in inchan;
begin try close_out outchan with Sys_error _ -> () end;
close_in errchan;
snd(waitpid_non_intr pid)
(* High-level network functions *)
let open_connection sockaddr =
let sock =
socket (domain_of_sockaddr sockaddr) SOCK_STREAM 0 in
try
connect sock sockaddr;
ignore(try_set_close_on_exec sock);
(in_channel_of_descr sock, out_channel_of_descr sock)
with exn ->
close sock; raise exn
let shutdown_connection inchan =
shutdown (descr_of_in_channel inchan) SHUTDOWN_SEND
let rec accept_non_intr s =
try accept s
with Unix_error (EINTR, _, _) -> accept_non_intr s
let establish_server server_fun sockaddr =
let sock =
socket (domain_of_sockaddr sockaddr) SOCK_STREAM 0 in
setsockopt sock SO_REUSEADDR true;
bind sock sockaddr;
listen sock 5;
while true do
let (s, caller) = accept_non_intr sock in
The " double fork " trick , the process which calls server_fun will not
leave a zombie process
leave a zombie process *)
match fork() with
0 -> if fork() <> 0 then exit 0; (* The son exits, the grandson works *)
close sock;
ignore(try_set_close_on_exec s);
let inchan = in_channel_of_descr s in
let outchan = out_channel_of_descr s in
server_fun inchan outchan;
Do not close inchan nor outchan , as the server_fun could
have done it already , and we are about to exit anyway
( PR#3794 )
have done it already, and we are about to exit anyway
(PR#3794) *)
exit 0
| id -> close s; ignore(waitpid_non_intr id) (* Reclaim the son *)
done
| null | https://raw.githubusercontent.com/bmeurer/ocaml-arm/43f7689c76a349febe3d06ae7a4fc1d52984fd8b/otherlibs/unix/unix.ml | ocaml | *********************************************************************
OCaml
the special exception on linking described in file ../../LICENSE.
*********************************************************************
Period
Current value of the timer
Determine socket types and port numbers
Determine IP addresses
Cross-product of addresses and ports
why not?
High-level process management (system, popen)
High-level network functions
The son exits, the grandson works
Reclaim the son | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ Id$
type error =
E2BIG
| EACCES
| EAGAIN
| EBADF
| EBUSY
| ECHILD
| EDEADLK
| EDOM
| EEXIST
| EFAULT
| EFBIG
| EINTR
| EINVAL
| EIO
| EISDIR
| EMFILE
| EMLINK
| ENAMETOOLONG
| ENFILE
| ENODEV
| ENOENT
| ENOEXEC
| ENOLCK
| ENOMEM
| ENOSPC
| ENOSYS
| ENOTDIR
| ENOTEMPTY
| ENOTTY
| ENXIO
| EPERM
| EPIPE
| ERANGE
| EROFS
| ESPIPE
| ESRCH
| EXDEV
| EWOULDBLOCK
| EINPROGRESS
| EALREADY
| ENOTSOCK
| EDESTADDRREQ
| EMSGSIZE
| EPROTOTYPE
| ENOPROTOOPT
| EPROTONOSUPPORT
| ESOCKTNOSUPPORT
| EOPNOTSUPP
| EPFNOSUPPORT
| EAFNOSUPPORT
| EADDRINUSE
| EADDRNOTAVAIL
| ENETDOWN
| ENETUNREACH
| ENETRESET
| ECONNABORTED
| ECONNRESET
| ENOBUFS
| EISCONN
| ENOTCONN
| ESHUTDOWN
| ETOOMANYREFS
| ETIMEDOUT
| ECONNREFUSED
| EHOSTDOWN
| EHOSTUNREACH
| ELOOP
| EOVERFLOW
| EUNKNOWNERR of int
exception Unix_error of error * string * string
let _ = Callback.register_exception "Unix.Unix_error"
(Unix_error(E2BIG, "", ""))
external error_message : error -> string = "unix_error_message"
let handle_unix_error f arg =
try
f arg
with Unix_error(err, fun_name, arg) ->
prerr_string Sys.argv.(0);
prerr_string ": \"";
prerr_string fun_name;
prerr_string "\" failed";
if String.length arg > 0 then begin
prerr_string " on \"";
prerr_string arg;
prerr_string "\""
end;
prerr_string ": ";
prerr_endline (error_message err);
exit 2
external environment : unit -> string array = "unix_environment"
external getenv: string -> string = "caml_sys_getenv"
external putenv: string -> string -> unit = "unix_putenv"
type process_status =
WEXITED of int
| WSIGNALED of int
| WSTOPPED of int
type wait_flag =
WNOHANG
| WUNTRACED
external execv : string -> string array -> 'a = "unix_execv"
external execve : string -> string array -> string array -> 'a = "unix_execve"
external execvp : string -> string array -> 'a = "unix_execvp"
external execvpe : string -> string array -> string array -> 'a = "unix_execvpe"
external fork : unit -> int = "unix_fork"
external wait : unit -> int * process_status = "unix_wait"
external waitpid : wait_flag list -> int -> int * process_status = "unix_waitpid"
external getpid : unit -> int = "unix_getpid"
external getppid : unit -> int = "unix_getppid"
external nice : int -> int = "unix_nice"
type file_descr = int
let stdin = 0
let stdout = 1
let stderr = 2
type open_flag =
O_RDONLY
| O_WRONLY
| O_RDWR
| O_NONBLOCK
| O_APPEND
| O_CREAT
| O_TRUNC
| O_EXCL
| O_NOCTTY
| O_DSYNC
| O_SYNC
| O_RSYNC
| O_SHARE_DELETE
type file_perm = int
external openfile : string -> open_flag list -> file_perm -> file_descr
= "unix_open"
external close : file_descr -> unit = "unix_close"
external unsafe_read : file_descr -> string -> int -> int -> int = "unix_read"
external unsafe_write : file_descr -> string -> int -> int -> int = "unix_write"
external unsafe_single_write : file_descr -> string -> int -> int -> int = "unix_single_write"
let read fd buf ofs len =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "Unix.read"
else unsafe_read fd buf ofs len
let write fd buf ofs len =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "Unix.write"
else unsafe_write fd buf ofs len
write misbehaves because it attempts to write all data by making repeated
calls to the Unix write function ( see comment in write.c and unix.mli ) .
partial_write fixes this by never calling write twice .
calls to the Unix write function (see comment in write.c and unix.mli).
partial_write fixes this by never calling write twice. *)
let single_write fd buf ofs len =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "Unix.single_write"
else unsafe_single_write fd buf ofs len
external in_channel_of_descr : file_descr -> in_channel
= "caml_ml_open_descriptor_in"
external out_channel_of_descr : file_descr -> out_channel
= "caml_ml_open_descriptor_out"
external descr_of_in_channel : in_channel -> file_descr
= "caml_channel_descriptor"
external descr_of_out_channel : out_channel -> file_descr
= "caml_channel_descriptor"
type seek_command =
SEEK_SET
| SEEK_CUR
| SEEK_END
external lseek : file_descr -> int -> seek_command -> int = "unix_lseek"
external truncate : string -> int -> unit = "unix_truncate"
external ftruncate : file_descr -> int -> unit = "unix_ftruncate"
type file_kind =
S_REG
| S_DIR
| S_CHR
| S_BLK
| S_LNK
| S_FIFO
| S_SOCK
type stats =
{ st_dev : int;
st_ino : int;
st_kind : file_kind;
st_perm : file_perm;
st_nlink : int;
st_uid : int;
st_gid : int;
st_rdev : int;
st_size : int;
st_atime : float;
st_mtime : float;
st_ctime : float }
external stat : string -> stats = "unix_stat"
external lstat : string -> stats = "unix_lstat"
external fstat : file_descr -> stats = "unix_fstat"
external isatty : file_descr -> bool = "unix_isatty"
external unlink : string -> unit = "unix_unlink"
external rename : string -> string -> unit = "unix_rename"
external link : string -> string -> unit = "unix_link"
module LargeFile =
struct
external lseek : file_descr -> int64 -> seek_command -> int64 = "unix_lseek_64"
external truncate : string -> int64 -> unit = "unix_truncate_64"
external ftruncate : file_descr -> int64 -> unit = "unix_ftruncate_64"
type stats =
{ st_dev : int;
st_ino : int;
st_kind : file_kind;
st_perm : file_perm;
st_nlink : int;
st_uid : int;
st_gid : int;
st_rdev : int;
st_size : int64;
st_atime : float;
st_mtime : float;
st_ctime : float;
}
external stat : string -> stats = "unix_stat_64"
external lstat : string -> stats = "unix_lstat_64"
external fstat : file_descr -> stats = "unix_fstat_64"
end
type access_permission =
R_OK
| W_OK
| X_OK
| F_OK
external chmod : string -> file_perm -> unit = "unix_chmod"
external fchmod : file_descr -> file_perm -> unit = "unix_fchmod"
external chown : string -> int -> int -> unit = "unix_chown"
external fchown : file_descr -> int -> int -> unit = "unix_fchown"
external umask : int -> int = "unix_umask"
external access : string -> access_permission list -> unit = "unix_access"
external dup : file_descr -> file_descr = "unix_dup"
external dup2 : file_descr -> file_descr -> unit = "unix_dup2"
external set_nonblock : file_descr -> unit = "unix_set_nonblock"
external clear_nonblock : file_descr -> unit = "unix_clear_nonblock"
external set_close_on_exec : file_descr -> unit = "unix_set_close_on_exec"
external clear_close_on_exec : file_descr -> unit = "unix_clear_close_on_exec"
FD_CLOEXEC should be supported on all Unix systems these days ,
but just in case ...
but just in case... *)
let try_set_close_on_exec fd =
try set_close_on_exec fd; true with Invalid_argument _ -> false
external mkdir : string -> file_perm -> unit = "unix_mkdir"
external rmdir : string -> unit = "unix_rmdir"
external chdir : string -> unit = "unix_chdir"
external getcwd : unit -> string = "unix_getcwd"
external chroot : string -> unit = "unix_chroot"
type dir_handle
external opendir : string -> dir_handle = "unix_opendir"
external readdir : dir_handle -> string = "unix_readdir"
external rewinddir : dir_handle -> unit = "unix_rewinddir"
external closedir : dir_handle -> unit = "unix_closedir"
external pipe : unit -> file_descr * file_descr = "unix_pipe"
external symlink : string -> string -> unit = "unix_symlink"
external readlink : string -> string = "unix_readlink"
external mkfifo : string -> file_perm -> unit = "unix_mkfifo"
external select :
file_descr list -> file_descr list -> file_descr list -> float ->
file_descr list * file_descr list * file_descr list = "unix_select"
type lock_command =
F_ULOCK
| F_LOCK
| F_TLOCK
| F_TEST
| F_RLOCK
| F_TRLOCK
external lockf : file_descr -> lock_command -> int -> unit = "unix_lockf"
external kill : int -> int -> unit = "unix_kill"
type sigprocmask_command = SIG_SETMASK | SIG_BLOCK | SIG_UNBLOCK
external sigprocmask: sigprocmask_command -> int list -> int list
= "unix_sigprocmask"
external sigpending: unit -> int list = "unix_sigpending"
external sigsuspend: int list -> unit = "unix_sigsuspend"
let pause() =
let sigs = sigprocmask SIG_BLOCK [] in sigsuspend sigs
type process_times =
{ tms_utime : float;
tms_stime : float;
tms_cutime : float;
tms_cstime : float }
type tm =
{ tm_sec : int;
tm_min : int;
tm_hour : int;
tm_mday : int;
tm_mon : int;
tm_year : int;
tm_wday : int;
tm_yday : int;
tm_isdst : bool }
external time : unit -> float = "unix_time"
external gettimeofday : unit -> float = "unix_gettimeofday"
external gmtime : float -> tm = "unix_gmtime"
external localtime : float -> tm = "unix_localtime"
external mktime : tm -> float * tm = "unix_mktime"
external alarm : int -> int = "unix_alarm"
external sleep : int -> unit = "unix_sleep"
external times : unit -> process_times = "unix_times"
external utimes : string -> float -> float -> unit = "unix_utimes"
type interval_timer =
ITIMER_REAL
| ITIMER_VIRTUAL
| ITIMER_PROF
type interval_timer_status =
external getitimer: interval_timer -> interval_timer_status = "unix_getitimer"
external setitimer:
interval_timer -> interval_timer_status -> interval_timer_status
= "unix_setitimer"
external getuid : unit -> int = "unix_getuid"
external geteuid : unit -> int = "unix_geteuid"
external setuid : int -> unit = "unix_setuid"
external getgid : unit -> int = "unix_getgid"
external getegid : unit -> int = "unix_getegid"
external setgid : int -> unit = "unix_setgid"
external getgroups : unit -> int array = "unix_getgroups"
external setgroups : int array -> unit = "unix_setgroups"
external initgroups : string -> int -> unit = "unix_initgroups"
type passwd_entry =
{ pw_name : string;
pw_passwd : string;
pw_uid : int;
pw_gid : int;
pw_gecos : string;
pw_dir : string;
pw_shell : string }
type group_entry =
{ gr_name : string;
gr_passwd : string;
gr_gid : int;
gr_mem : string array }
external getlogin : unit -> string = "unix_getlogin"
external getpwnam : string -> passwd_entry = "unix_getpwnam"
external getgrnam : string -> group_entry = "unix_getgrnam"
external getpwuid : int -> passwd_entry = "unix_getpwuid"
external getgrgid : int -> group_entry = "unix_getgrgid"
type inet_addr = string
let is_inet6_addr s = String.length s = 16
external inet_addr_of_string : string -> inet_addr
= "unix_inet_addr_of_string"
external string_of_inet_addr : inet_addr -> string
= "unix_string_of_inet_addr"
let inet_addr_any = inet_addr_of_string "0.0.0.0"
let inet_addr_loopback = inet_addr_of_string "127.0.0.1"
let inet6_addr_any =
try inet_addr_of_string "::" with Failure _ -> inet_addr_any
let inet6_addr_loopback =
try inet_addr_of_string "::1" with Failure _ -> inet_addr_loopback
type socket_domain =
PF_UNIX
| PF_INET
| PF_INET6
type socket_type =
SOCK_STREAM
| SOCK_DGRAM
| SOCK_RAW
| SOCK_SEQPACKET
type sockaddr =
ADDR_UNIX of string
| ADDR_INET of inet_addr * int
let domain_of_sockaddr = function
ADDR_UNIX _ -> PF_UNIX
| ADDR_INET(a, _) -> if is_inet6_addr a then PF_INET6 else PF_INET
type shutdown_command =
SHUTDOWN_RECEIVE
| SHUTDOWN_SEND
| SHUTDOWN_ALL
type msg_flag =
MSG_OOB
| MSG_DONTROUTE
| MSG_PEEK
external socket : socket_domain -> socket_type -> int -> file_descr
= "unix_socket"
external socketpair :
socket_domain -> socket_type -> int -> file_descr * file_descr
= "unix_socketpair"
external accept : file_descr -> file_descr * sockaddr = "unix_accept"
external bind : file_descr -> sockaddr -> unit = "unix_bind"
external connect : file_descr -> sockaddr -> unit = "unix_connect"
external listen : file_descr -> int -> unit = "unix_listen"
external shutdown : file_descr -> shutdown_command -> unit = "unix_shutdown"
external getsockname : file_descr -> sockaddr = "unix_getsockname"
external getpeername : file_descr -> sockaddr = "unix_getpeername"
external unsafe_recv :
file_descr -> string -> int -> int -> msg_flag list -> int
= "unix_recv"
external unsafe_recvfrom :
file_descr -> string -> int -> int -> msg_flag list -> int * sockaddr
= "unix_recvfrom"
external unsafe_send :
file_descr -> string -> int -> int -> msg_flag list -> int
= "unix_send"
external unsafe_sendto :
file_descr -> string -> int -> int -> msg_flag list -> sockaddr -> int
= "unix_sendto" "unix_sendto_native"
let recv fd buf ofs len flags =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "Unix.recv"
else unsafe_recv fd buf ofs len flags
let recvfrom fd buf ofs len flags =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "Unix.recvfrom"
else unsafe_recvfrom fd buf ofs len flags
let send fd buf ofs len flags =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "Unix.send"
else unsafe_send fd buf ofs len flags
let sendto fd buf ofs len flags addr =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "Unix.sendto"
else unsafe_sendto fd buf ofs len flags addr
type socket_bool_option =
SO_DEBUG
| SO_BROADCAST
| SO_REUSEADDR
| SO_KEEPALIVE
| SO_DONTROUTE
| SO_OOBINLINE
| SO_ACCEPTCONN
| TCP_NODELAY
| IPV6_ONLY
type socket_int_option =
SO_SNDBUF
| SO_RCVBUF
| SO_ERROR
| SO_TYPE
| SO_RCVLOWAT
| SO_SNDLOWAT
type socket_optint_option = SO_LINGER
type socket_float_option =
SO_RCVTIMEO
| SO_SNDTIMEO
type socket_error_option = SO_ERROR
module SO: sig
type ('opt, 'v) t
val bool: (socket_bool_option, bool) t
val int: (socket_int_option, int) t
val optint: (socket_optint_option, int option) t
val float: (socket_float_option, float) t
val error: (socket_error_option, error option) t
val get: ('opt, 'v) t -> file_descr -> 'opt -> 'v
val set: ('opt, 'v) t -> file_descr -> 'opt -> 'v -> unit
end = struct
type ('opt, 'v) t = int
let bool = 0
let int = 1
let optint = 2
let float = 3
let error = 4
external get: ('opt, 'v) t -> file_descr -> 'opt -> 'v
= "unix_getsockopt"
external set: ('opt, 'v) t -> file_descr -> 'opt -> 'v -> unit
= "unix_setsockopt"
end
let getsockopt fd opt = SO.get SO.bool fd opt
let setsockopt fd opt v = SO.set SO.bool fd opt v
let getsockopt_int fd opt = SO.get SO.int fd opt
let setsockopt_int fd opt v = SO.set SO.int fd opt v
let getsockopt_optint fd opt = SO.get SO.optint fd opt
let setsockopt_optint fd opt v = SO.set SO.optint fd opt v
let getsockopt_float fd opt = SO.get SO.float fd opt
let setsockopt_float fd opt v = SO.set SO.float fd opt v
let getsockopt_error fd = SO.get SO.error fd SO_ERROR
type host_entry =
{ h_name : string;
h_aliases : string array;
h_addrtype : socket_domain;
h_addr_list : inet_addr array }
type protocol_entry =
{ p_name : string;
p_aliases : string array;
p_proto : int }
type service_entry =
{ s_name : string;
s_aliases : string array;
s_port : int;
s_proto : string }
external gethostname : unit -> string = "unix_gethostname"
external gethostbyname : string -> host_entry = "unix_gethostbyname"
external gethostbyaddr : inet_addr -> host_entry = "unix_gethostbyaddr"
external getprotobyname : string -> protocol_entry
= "unix_getprotobyname"
external getprotobynumber : int -> protocol_entry
= "unix_getprotobynumber"
external getservbyname : string -> string -> service_entry
= "unix_getservbyname"
external getservbyport : int -> string -> service_entry
= "unix_getservbyport"
type addr_info =
{ ai_family : socket_domain;
ai_socktype : socket_type;
ai_protocol : int;
ai_addr : sockaddr;
ai_canonname : string }
type getaddrinfo_option =
AI_FAMILY of socket_domain
| AI_SOCKTYPE of socket_type
| AI_PROTOCOL of int
| AI_NUMERICHOST
| AI_CANONNAME
| AI_PASSIVE
external getaddrinfo_system
: string -> string -> getaddrinfo_option list -> addr_info list
= "unix_getaddrinfo"
let getaddrinfo_emulation node service opts =
Parse options
let opt_socktype = ref None
and opt_protocol = ref 0
and opt_passive = ref false in
List.iter
(function AI_SOCKTYPE s -> opt_socktype := Some s
| AI_PROTOCOL p -> opt_protocol := p
| AI_PASSIVE -> opt_passive := true
| _ -> ())
opts;
let get_port ty kind =
if service = "" then [ty, 0] else
try
[ty, int_of_string service]
with Failure _ ->
try
[ty, (getservbyname service kind).s_port]
with Not_found -> []
in
let ports =
match !opt_socktype with
| None ->
get_port SOCK_STREAM "tcp" @ get_port SOCK_DGRAM "udp"
| Some SOCK_STREAM ->
get_port SOCK_STREAM "tcp"
| Some SOCK_DGRAM ->
get_port SOCK_DGRAM "udp"
| Some ty ->
if service = "" then [ty, 0] else [] in
let addresses =
if node = "" then
if List.mem AI_PASSIVE opts
then [inet_addr_any, "0.0.0.0"]
else [inet_addr_loopback, "127.0.0.1"]
else
try
[inet_addr_of_string node, node]
with Failure _ ->
try
let he = gethostbyname node in
List.map
(fun a -> (a, he.h_name))
(Array.to_list he.h_addr_list)
with Not_found ->
[] in
List.flatten
(List.map
(fun (ty, port) ->
List.map
(fun (addr, name) ->
{ ai_family = PF_INET;
ai_socktype = ty;
ai_protocol = !opt_protocol;
ai_addr = ADDR_INET(addr, port);
ai_canonname = name })
addresses)
ports)
let getaddrinfo node service opts =
try
List.rev(getaddrinfo_system node service opts)
with Invalid_argument _ ->
getaddrinfo_emulation node service opts
type name_info =
{ ni_hostname : string;
ni_service : string }
type getnameinfo_option =
NI_NOFQDN
| NI_NUMERICHOST
| NI_NAMEREQD
| NI_NUMERICSERV
| NI_DGRAM
external getnameinfo_system
: sockaddr -> getnameinfo_option list -> name_info
= "unix_getnameinfo"
let getnameinfo_emulation addr opts =
match addr with
| ADDR_UNIX f ->
| ADDR_INET(a, p) ->
let hostname =
try
if List.mem NI_NUMERICHOST opts then raise Not_found;
(gethostbyaddr a).h_name
with Not_found ->
if List.mem NI_NAMEREQD opts then raise Not_found;
string_of_inet_addr a in
let service =
try
if List.mem NI_NUMERICSERV opts then raise Not_found;
let kind = if List.mem NI_DGRAM opts then "udp" else "tcp" in
(getservbyport p kind).s_name
with Not_found ->
string_of_int p in
{ ni_hostname = hostname; ni_service = service }
let getnameinfo addr opts =
try
getnameinfo_system addr opts
with Invalid_argument _ ->
getnameinfo_emulation addr opts
type terminal_io = {
mutable c_ignbrk: bool;
mutable c_brkint: bool;
mutable c_ignpar: bool;
mutable c_parmrk: bool;
mutable c_inpck: bool;
mutable c_istrip: bool;
mutable c_inlcr: bool;
mutable c_igncr: bool;
mutable c_icrnl: bool;
mutable c_ixon: bool;
mutable c_ixoff: bool;
mutable c_opost: bool;
mutable c_obaud: int;
mutable c_ibaud: int;
mutable c_csize: int;
mutable c_cstopb: int;
mutable c_cread: bool;
mutable c_parenb: bool;
mutable c_parodd: bool;
mutable c_hupcl: bool;
mutable c_clocal: bool;
mutable c_isig: bool;
mutable c_icanon: bool;
mutable c_noflsh: bool;
mutable c_echo: bool;
mutable c_echoe: bool;
mutable c_echok: bool;
mutable c_echonl: bool;
mutable c_vintr: char;
mutable c_vquit: char;
mutable c_verase: char;
mutable c_vkill: char;
mutable c_veof: char;
mutable c_veol: char;
mutable c_vmin: int;
mutable c_vtime: int;
mutable c_vstart: char;
mutable c_vstop: char
}
external tcgetattr: file_descr -> terminal_io = "unix_tcgetattr"
type setattr_when = TCSANOW | TCSADRAIN | TCSAFLUSH
external tcsetattr: file_descr -> setattr_when -> terminal_io -> unit
= "unix_tcsetattr"
external tcsendbreak: file_descr -> int -> unit = "unix_tcsendbreak"
external tcdrain: file_descr -> unit = "unix_tcdrain"
type flush_queue = TCIFLUSH | TCOFLUSH | TCIOFLUSH
external tcflush: file_descr -> flush_queue -> unit = "unix_tcflush"
type flow_action = TCOOFF | TCOON | TCIOFF | TCION
external tcflow: file_descr -> flow_action -> unit = "unix_tcflow"
external setsid : unit -> int = "unix_setsid"
let system cmd =
match fork() with
0 -> begin try
execv "/bin/sh" [| "/bin/sh"; "-c"; cmd |]
with _ ->
exit 127
end
| id -> snd(waitpid [] id)
let rec safe_dup fd =
let new_fd = dup fd in
if new_fd >= 3 then
new_fd
else begin
let res = safe_dup fd in
close new_fd;
res
end
let safe_close fd =
try close fd with Unix_error(_,_,_) -> ()
let perform_redirections new_stdin new_stdout new_stderr =
let newnewstdin = safe_dup new_stdin in
let newnewstdout = safe_dup new_stdout in
let newnewstderr = safe_dup new_stderr in
safe_close new_stdin;
safe_close new_stdout;
safe_close new_stderr;
dup2 newnewstdin stdin; close newnewstdin;
dup2 newnewstdout stdout; close newnewstdout;
dup2 newnewstderr stderr; close newnewstderr
let create_process cmd args new_stdin new_stdout new_stderr =
match fork() with
0 ->
begin try
perform_redirections new_stdin new_stdout new_stderr;
execvp cmd args
with _ ->
exit 127
end
| id -> id
let create_process_env cmd args env new_stdin new_stdout new_stderr =
match fork() with
0 ->
begin try
perform_redirections new_stdin new_stdout new_stderr;
execvpe cmd args env
with _ ->
exit 127
end
| id -> id
type popen_process =
Process of in_channel * out_channel
| Process_in of in_channel
| Process_out of out_channel
| Process_full of in_channel * out_channel * in_channel
let popen_processes = (Hashtbl.create 7 : (popen_process, int) Hashtbl.t)
let open_proc cmd proc input output toclose =
let cloexec = List.for_all try_set_close_on_exec toclose in
match fork() with
0 -> if input <> stdin then begin dup2 input stdin; close input end;
if output <> stdout then begin dup2 output stdout; close output end;
if not cloexec then List.iter close toclose;
begin try execv "/bin/sh" [| "/bin/sh"; "-c"; cmd |]
with _ -> exit 127
end
| id -> Hashtbl.add popen_processes proc id
let open_process_in cmd =
let (in_read, in_write) = pipe() in
let inchan = in_channel_of_descr in_read in
begin
try
open_proc cmd (Process_in inchan) stdin in_write [in_read];
with e ->
close_in inchan;
close in_write;
raise e
end;
close in_write;
inchan
let open_process_out cmd =
let (out_read, out_write) = pipe() in
let outchan = out_channel_of_descr out_write in
begin
try
open_proc cmd (Process_out outchan) out_read stdout [out_write];
with e ->
close_out outchan;
close out_read;
raise e
end;
close out_read;
outchan
let open_process cmd =
let (in_read, in_write) = pipe() in
let fds_to_close = ref [in_read;in_write] in
try
let (out_read, out_write) = pipe() in
fds_to_close := [in_read;in_write;out_read;out_write];
let inchan = in_channel_of_descr in_read in
let outchan = out_channel_of_descr out_write in
open_proc cmd (Process(inchan, outchan)) out_read in_write
[in_read; out_write];
close out_read;
close in_write;
(inchan, outchan)
with e ->
List.iter close !fds_to_close;
raise e
let open_proc_full cmd env proc input output error toclose =
let cloexec = List.for_all try_set_close_on_exec toclose in
match fork() with
0 -> dup2 input stdin; close input;
dup2 output stdout; close output;
dup2 error stderr; close error;
if not cloexec then List.iter close toclose;
begin try execve "/bin/sh" [| "/bin/sh"; "-c"; cmd |] env
with _ -> exit 127
end
| id -> Hashtbl.add popen_processes proc id
let open_process_full cmd env =
let (in_read, in_write) = pipe() in
let fds_to_close = ref [in_read;in_write] in
try
let (out_read, out_write) = pipe() in
fds_to_close := out_read::out_write:: !fds_to_close;
let (err_read, err_write) = pipe() in
fds_to_close := err_read::err_write:: !fds_to_close;
let inchan = in_channel_of_descr in_read in
let outchan = out_channel_of_descr out_write in
let errchan = in_channel_of_descr err_read in
open_proc_full cmd env (Process_full(inchan, outchan, errchan))
out_read in_write err_write [in_read; out_write; err_read];
close out_read;
close in_write;
close err_write;
(inchan, outchan, errchan)
with e ->
List.iter close !fds_to_close;
raise e
let find_proc_id fun_name proc =
try
let pid = Hashtbl.find popen_processes proc in
Hashtbl.remove popen_processes proc;
pid
with Not_found ->
raise(Unix_error(EBADF, fun_name, ""))
let rec waitpid_non_intr pid =
try waitpid [] pid
with Unix_error (EINTR, _, _) -> waitpid_non_intr pid
let close_process_in inchan =
let pid = find_proc_id "close_process_in" (Process_in inchan) in
close_in inchan;
snd(waitpid_non_intr pid)
let close_process_out outchan =
let pid = find_proc_id "close_process_out" (Process_out outchan) in
close_out outchan;
snd(waitpid_non_intr pid)
let close_process (inchan, outchan) =
let pid = find_proc_id "close_process" (Process(inchan, outchan)) in
close_in inchan;
begin try close_out outchan with Sys_error _ -> () end;
snd(waitpid_non_intr pid)
let close_process_full (inchan, outchan, errchan) =
let pid =
find_proc_id "close_process_full"
(Process_full(inchan, outchan, errchan)) in
close_in inchan;
begin try close_out outchan with Sys_error _ -> () end;
close_in errchan;
snd(waitpid_non_intr pid)
let open_connection sockaddr =
let sock =
socket (domain_of_sockaddr sockaddr) SOCK_STREAM 0 in
try
connect sock sockaddr;
ignore(try_set_close_on_exec sock);
(in_channel_of_descr sock, out_channel_of_descr sock)
with exn ->
close sock; raise exn
let shutdown_connection inchan =
shutdown (descr_of_in_channel inchan) SHUTDOWN_SEND
let rec accept_non_intr s =
try accept s
with Unix_error (EINTR, _, _) -> accept_non_intr s
let establish_server server_fun sockaddr =
let sock =
socket (domain_of_sockaddr sockaddr) SOCK_STREAM 0 in
setsockopt sock SO_REUSEADDR true;
bind sock sockaddr;
listen sock 5;
while true do
let (s, caller) = accept_non_intr sock in
The " double fork " trick , the process which calls server_fun will not
leave a zombie process
leave a zombie process *)
match fork() with
close sock;
ignore(try_set_close_on_exec s);
let inchan = in_channel_of_descr s in
let outchan = out_channel_of_descr s in
server_fun inchan outchan;
Do not close inchan nor outchan , as the server_fun could
have done it already , and we are about to exit anyway
( PR#3794 )
have done it already, and we are about to exit anyway
(PR#3794) *)
exit 0
done
|
b446148a3d4cf5a1f9d8f46ba23e271c790138794b5f0ee562063687ce72372a | fare/xcvb | package.lisp | #+xcvb (module (:description "Unit test package for XCVB"
:depends-on ("driver-test")))
(uiop/package:define-package #:xcvb-test
(:mix :hu.dwim.stefil :xcvb :fare-utils :uiop
:inferior-shell :lisp-invocation :alexandria :xcvb-driver)
(:use :closer-common-lisp)
(:import-from :xcvb-driver
#:lisp-present-p
#:+xcvb-lisps+)
(:import-from :xcvb
#:module-form-p #:read-module-declaration #:cmdize*
#:repl-command #:eval-command #:errexit
#:grain-pathname #:handle-global-options
#:define-command #:define-option-spec #:*program*)
(:export
#:test-xcvb
#:run-program*
#:run-program-backend*))
(in-package #:xcvb-test)
(defsuite* (xcvb-test
:in root-suite
:documentation "All XCVB unit tests"))
| null | https://raw.githubusercontent.com/fare/xcvb/460e27bd4cbd4db5e7ddf5b22c2ee455df445258/t/package.lisp | lisp | #+xcvb (module (:description "Unit test package for XCVB"
:depends-on ("driver-test")))
(uiop/package:define-package #:xcvb-test
(:mix :hu.dwim.stefil :xcvb :fare-utils :uiop
:inferior-shell :lisp-invocation :alexandria :xcvb-driver)
(:use :closer-common-lisp)
(:import-from :xcvb-driver
#:lisp-present-p
#:+xcvb-lisps+)
(:import-from :xcvb
#:module-form-p #:read-module-declaration #:cmdize*
#:repl-command #:eval-command #:errexit
#:grain-pathname #:handle-global-options
#:define-command #:define-option-spec #:*program*)
(:export
#:test-xcvb
#:run-program*
#:run-program-backend*))
(in-package #:xcvb-test)
(defsuite* (xcvb-test
:in root-suite
:documentation "All XCVB unit tests"))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.