code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
wordpress is_tag( int|string|int[]|string[] $tag = '' ): bool is\_tag( int|string|int[]|string[] $tag = '' ): bool
====================================================
Determines whether the query is for an existing tag archive page.
If the $tag parameter is specified, this function will additionally check if the query is for one of the tags specified.
For more information on this and similar theme functions, check out the [Conditional Tags](https://developer.wordpress.org/themes/basics/conditional-tags/) article in the Theme Developer Handbook.
`$tag` int|string|int[]|string[] Optional Tag ID, name, slug, or array of such to check against. Default: `''`
bool Whether the query is for an existing tag archive page.
File: `wp-includes/query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/query.php/)
```
function is_tag( $tag = '' ) {
global $wp_query;
if ( ! isset( $wp_query ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
return false;
}
return $wp_query->is_tag( $tag );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Query::is\_tag()](../classes/wp_query/is_tag) wp-includes/class-wp-query.php | Is the query for an existing tag archive page? |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_doing\_it\_wrong()](_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Used By | Description |
| --- | --- |
| [rest\_get\_queried\_resource\_route()](rest_get_queried_resource_route) wp-includes/rest-api.php | Gets the REST route for the currently queried object. |
| [wp\_get\_document\_title()](wp_get_document_title) wp-includes/general-template.php | Returns document title for the current page. |
| [get\_the\_archive\_title()](get_the_archive_title) wp-includes/general-template.php | Retrieves the archive title based on the queried object. |
| [term\_description()](term_description) wp-includes/category-template.php | Retrieves term description. |
| [wp\_list\_categories()](wp_list_categories) wp-includes/category-template.php | Displays or retrieves the HTML list of categories. |
| [feed\_links\_extra()](feed_links_extra) wp-includes/general-template.php | Displays the links to the extra feeds such as category feeds. |
| [wp\_title()](wp_title) wp-includes/general-template.php | Displays or retrieves page title for all areas of blog. |
| [single\_term\_title()](single_term_title) wp-includes/general-template.php | Displays or retrieves page title for taxonomy term archive. |
| [WP::handle\_404()](../classes/wp/handle_404) wp-includes/class-wp.php | Set the Headers for 404, if nothing is found for requested URL. |
| [get\_body\_class()](get_body_class) wp-includes/post-template.php | Retrieves an array of the class names for the body element. |
| [redirect\_canonical()](redirect_canonical) wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| Version | Description |
| --- | --- |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
wordpress get_edit_comment_link( int|WP_Comment $comment_id ): string|void get\_edit\_comment\_link( int|WP\_Comment $comment\_id ): string|void
=====================================================================
Retrieves the edit comment link.
`$comment_id` int|[WP\_Comment](../classes/wp_comment) Optional Comment ID or [WP\_Comment](../classes/wp_comment) object. string|void The edit comment link URL for the given comment.
File: `wp-includes/link-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/link-template.php/)
```
function get_edit_comment_link( $comment_id = 0 ) {
$comment = get_comment( $comment_id );
if ( ! current_user_can( 'edit_comment', $comment->comment_ID ) ) {
return;
}
$location = admin_url( 'comment.php?action=editcomment&c=' ) . $comment->comment_ID;
/**
* Filters the comment edit link.
*
* @since 2.3.0
*
* @param string $location The edit link.
*/
return apply_filters( 'get_edit_comment_link', $location );
}
```
[apply\_filters( 'get\_edit\_comment\_link', string $location )](../hooks/get_edit_comment_link)
Filters the comment edit link.
| Uses | Description |
| --- | --- |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [admin\_url()](admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_comment()](get_comment) wp-includes/comment.php | Retrieves comment data given a comment ID or comment object. |
| Used By | Description |
| --- | --- |
| [edit\_comment\_link()](edit_comment_link) wp-includes/link-template.php | Displays the edit comment link with formatting. |
| Version | Description |
| --- | --- |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
wordpress category_description( int $category ): string category\_description( int $category ): string
==============================================
Retrieves category description.
`$category` int Optional Category ID. Defaults to the current category ID. string Category description, if available.
If used in the archive.php template, place this function within the [is\_category()](is_category) conditional statement.
Otherwise, this function will stop the processing of the page for monthly and other archive pages.
File: `wp-includes/category-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/category-template.php/)
```
function category_description( $category = 0 ) {
return term_description( $category );
}
```
| Uses | Description |
| --- | --- |
| [term\_description()](term_description) wp-includes/category-template.php | Retrieves term description. |
| Version | Description |
| --- | --- |
| [1.0.0](https://developer.wordpress.org/reference/since/1.0.0/) | Introduced. |
wordpress user_can_delete_post( int $user_id, int $post_id, int $blog_id = 1 ): bool user\_can\_delete\_post( int $user\_id, int $post\_id, int $blog\_id = 1 ): bool
================================================================================
This function has been deprecated. Use [current\_user\_can()](current_user_can) instead.
Whether user can delete a post.
* [current\_user\_can()](current_user_can)
`$user_id` int Required `$post_id` int Required `$blog_id` int Optional Not Used Default: `1`
bool
File: `wp-includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/deprecated.php/)
```
function user_can_delete_post($user_id, $post_id, $blog_id = 1) {
_deprecated_function( __FUNCTION__, '2.0.0', 'current_user_can()' );
// Right now if one can edit, one can delete.
return user_can_edit_post($user_id, $post_id, $blog_id);
}
```
| Uses | Description |
| --- | --- |
| [user\_can\_edit\_post()](user_can_edit_post) wp-includes/deprecated.php | Whether user can edit a post. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Use [current\_user\_can()](current_user_can) |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_get_latest_revision_id_and_total_count( int|WP_Post $post ): array|WP_Error wp\_get\_latest\_revision\_id\_and\_total\_count( int|WP\_Post $post ): array|WP\_Error
=======================================================================================
Returns the latest revision ID and count of revisions for a post.
`$post` int|[WP\_Post](../classes/wp_post) Optional Post ID or [WP\_Post](../classes/wp_post) object. Default is global $post. array|[WP\_Error](../classes/wp_error) Returns associative array with latest revision ID and total count, or a [WP\_Error](../classes/wp_error) if the post does not exist or revisions are not enabled.
* `latest_id`intThe latest revision post ID or 0 if no revisions exist.
* `count`intThe total count of revisions for the given post.
File: `wp-includes/revision.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/revision.php/)
```
function wp_get_latest_revision_id_and_total_count( $post = 0 ) {
$post = get_post( $post );
if ( ! $post ) {
return new WP_Error( 'invalid_post', __( 'Invalid post.' ) );
}
if ( ! wp_revisions_enabled( $post ) ) {
return new WP_Error( 'revisions_not_enabled', __( 'Revisions not enabled.' ) );
}
$args = array(
'post_parent' => $post->ID,
'fields' => 'ids',
'post_type' => 'revision',
'post_status' => 'inherit',
'order' => 'DESC',
'orderby' => 'date ID',
'posts_per_page' => 1,
'ignore_sticky_posts' => true,
);
$revision_query = new WP_Query();
$revisions = $revision_query->query( $args );
if ( ! $revisions ) {
return array(
'latest_id' => 0,
'count' => 0,
);
}
return array(
'latest_id' => $revisions[0],
'count' => $revision_query->found_posts,
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_Query::\_\_construct()](../classes/wp_query/__construct) wp-includes/class-wp-query.php | Constructor. |
| [wp\_revisions\_enabled()](wp_revisions_enabled) wp-includes/revision.php | Determines whether revisions are enabled for a given post. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [WP\_Error::\_\_construct()](../classes/wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [wp\_get\_post\_revisions\_url()](wp_get_post_revisions_url) wp-includes/revision.php | Returns the url for viewing and potentially restoring revisions of a given post. |
| [register\_and\_do\_post\_meta\_boxes()](register_and_do_post_meta_boxes) wp-admin/includes/meta-boxes.php | Registers the default post meta boxes, and runs the `do_meta_boxes` actions. |
| [wp\_update\_custom\_css\_post()](wp_update_custom_css_post) wp-includes/theme.php | Updates the `custom_css` post for a given theme. |
| [WP\_REST\_Posts\_Controller::prepare\_links()](../classes/wp_rest_posts_controller/prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares links for the request. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress wp_comments_personal_data_eraser( string $email_address, int $page = 1 ): array wp\_comments\_personal\_data\_eraser( string $email\_address, int $page = 1 ): array
====================================================================================
Erases personal data associated with an email address from the comments table.
`$email_address` string Required The comment author email address. `$page` int Optional Comment page. Default: `1`
array
File: `wp-includes/comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/comment.php/)
```
function wp_comments_personal_data_eraser( $email_address, $page = 1 ) {
global $wpdb;
if ( empty( $email_address ) ) {
return array(
'items_removed' => false,
'items_retained' => false,
'messages' => array(),
'done' => true,
);
}
// Limit us to 500 comments at a time to avoid timing out.
$number = 500;
$page = (int) $page;
$items_removed = false;
$items_retained = false;
$comments = get_comments(
array(
'author_email' => $email_address,
'number' => $number,
'paged' => $page,
'order_by' => 'comment_ID',
'order' => 'ASC',
'include_unapproved' => true,
)
);
/* translators: Name of a comment's author after being anonymized. */
$anon_author = __( 'Anonymous' );
$messages = array();
foreach ( (array) $comments as $comment ) {
$anonymized_comment = array();
$anonymized_comment['comment_agent'] = '';
$anonymized_comment['comment_author'] = $anon_author;
$anonymized_comment['comment_author_email'] = '';
$anonymized_comment['comment_author_IP'] = wp_privacy_anonymize_data( 'ip', $comment->comment_author_IP );
$anonymized_comment['comment_author_url'] = '';
$anonymized_comment['user_id'] = 0;
$comment_id = (int) $comment->comment_ID;
/**
* Filters whether to anonymize the comment.
*
* @since 4.9.6
*
* @param bool|string $anon_message Whether to apply the comment anonymization (bool) or a custom
* message (string). Default true.
* @param WP_Comment $comment WP_Comment object.
* @param array $anonymized_comment Anonymized comment data.
*/
$anon_message = apply_filters( 'wp_anonymize_comment', true, $comment, $anonymized_comment );
if ( true !== $anon_message ) {
if ( $anon_message && is_string( $anon_message ) ) {
$messages[] = esc_html( $anon_message );
} else {
/* translators: %d: Comment ID. */
$messages[] = sprintf( __( 'Comment %d contains personal data but could not be anonymized.' ), $comment_id );
}
$items_retained = true;
continue;
}
$args = array(
'comment_ID' => $comment_id,
);
$updated = $wpdb->update( $wpdb->comments, $anonymized_comment, $args );
if ( $updated ) {
$items_removed = true;
clean_comment_cache( $comment_id );
} else {
$items_retained = true;
}
}
$done = count( $comments ) < $number;
return array(
'items_removed' => $items_removed,
'items_retained' => $items_retained,
'messages' => $messages,
'done' => $done,
);
}
```
[apply\_filters( 'wp\_anonymize\_comment', bool|string $anon\_message, WP\_Comment $comment, array $anonymized\_comment )](../hooks/wp_anonymize_comment)
Filters whether to anonymize the comment.
| Uses | Description |
| --- | --- |
| [wp\_privacy\_anonymize\_data()](wp_privacy_anonymize_data) wp-includes/functions.php | Returns uniform “anonymous” data by type. |
| [wpdb::update()](../classes/wpdb/update) wp-includes/class-wpdb.php | Updates a row in the table. |
| [clean\_comment\_cache()](clean_comment_cache) wp-includes/comment.php | Removes a comment from the object cache. |
| [get\_comments()](get_comments) wp-includes/comment.php | Retrieves a list of comments. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress image_attachment_fields_to_save( array $post, array $attachment ): array image\_attachment\_fields\_to\_save( array $post, array $attachment ): array
============================================================================
This function has been deprecated.
Was used to filter input from [media\_upload\_form\_handler()](media_upload_form_handler) and to assign a default post\_title from the file name if none supplied.
`$post` array Required The [WP\_Post](../classes/wp_post) attachment object converted to an array. `$attachment` array Required An array of attachment metadata. array Attachment post object converted to an array.
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
function image_attachment_fields_to_save( $post, $attachment ) {
_deprecated_function( __FUNCTION__, '6.0.0' );
return $post;
}
```
| Uses | Description |
| --- | --- |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | This function has been deprecated. |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress update_site_option( string $option, mixed $value ): bool update\_site\_option( string $option, mixed $value ): bool
==========================================================
Updates the value of an option that was already added for the current network.
* [update\_network\_option()](update_network_option)
`$option` string Required Name of the option. Expected to not be SQL-escaped. `$value` mixed Required Option value. Expected to not be SQL-escaped. bool True if the value was updated, false otherwise.
File: `wp-includes/option.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/option.php/)
```
function update_site_option( $option, $value ) {
return update_network_option( null, $option, $value );
}
```
| Uses | Description |
| --- | --- |
| [update\_network\_option()](update_network_option) wp-includes/option.php | Updates the value of a network option that was already added. |
| Used By | Description |
| --- | --- |
| [deactivated\_plugins\_notice()](deactivated_plugins_notice) wp-admin/includes/plugin.php | Renders an admin notice when a plugin was deactivated during an update. |
| [wp\_ajax\_toggle\_auto\_updates()](wp_ajax_toggle_auto_updates) wp-admin/includes/ajax-actions.php | Ajax handler to enable or disable plugin and theme auto-updates. |
| [WP\_Recovery\_Mode\_Cookie\_Service::recovery\_mode\_hash()](../classes/wp_recovery_mode_cookie_service/recovery_mode_hash) wp-includes/class-wp-recovery-mode-cookie-service.php | Gets a form of `wp_hash()` specific to Recovery Mode. |
| [update\_network\_option\_new\_admin\_email()](update_network_option_new_admin_email) wp-includes/ms-functions.php | Sends a confirmation request email when a change of network admin email address is attempted. |
| [WP\_Theme::network\_enable\_theme()](../classes/wp_theme/network_enable_theme) wp-includes/class-wp-theme.php | Enables a theme for all sites on the current network. |
| [WP\_Theme::network\_disable\_theme()](../classes/wp_theme/network_disable_theme) wp-includes/class-wp-theme.php | Disables a theme for all sites on the current network. |
| [WP\_Automatic\_Updater::after\_core\_update()](../classes/wp_automatic_updater/after_core_update) wp-admin/includes/class-wp-automatic-updater.php | If we tried to perform a core update, check if we should send an email, and if we need to avoid processing future updates. |
| [WP\_Automatic\_Updater::send\_email()](../classes/wp_automatic_updater/send_email) wp-admin/includes/class-wp-automatic-updater.php | Sends an email upon the completion or failure of a background core update. |
| [WP\_Plugins\_List\_Table::prepare\_items()](../classes/wp_plugins_list_table/prepare_items) wp-admin/includes/class-wp-plugins-list-table.php | |
| [grant\_super\_admin()](grant_super_admin) wp-includes/capabilities.php | Grants Super Admin privileges. |
| [revoke\_super\_admin()](revoke_super_admin) wp-includes/capabilities.php | Revokes Super Admin privileges. |
| [dismiss\_core\_update()](dismiss_core_update) wp-admin/includes/update.php | Dismisses core update. |
| [undismiss\_core\_update()](undismiss_core_update) wp-admin/includes/update.php | Undismisses core update. |
| [upgrade\_network()](upgrade_network) wp-admin/includes/upgrade.php | Executes network-level upgrade routines. |
| [activate\_plugin()](activate_plugin) wp-admin/includes/plugin.php | Attempts activation of plugin in a “sandbox” and redirects on success. |
| [deactivate\_plugins()](deactivate_plugins) wp-admin/includes/plugin.php | Deactivates a single plugin or multiple plugins. |
| [wp\_ajax\_wp\_compression\_test()](wp_ajax_wp_compression_test) wp-admin/includes/ajax-actions.php | Ajax handler for compression testing. |
| [wp\_salt()](wp_salt) wp-includes/pluggable.php | Returns a salt to add to hashes. |
| [set\_site\_transient()](set_site_transient) wp-includes/option.php | Sets/updates the value of a site transient. |
| [welcome\_user\_msg\_filter()](welcome_user_msg_filter) wp-includes/ms-functions.php | Ensures that the welcome message is not empty. Currently unused. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Modified into wrapper for [update\_network\_option()](update_network_option) |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
| programming_docs |
wordpress print_column_headers( string|WP_Screen $screen, bool $with_id = true ) print\_column\_headers( string|WP\_Screen $screen, bool $with\_id = true )
==========================================================================
Prints column headers for a particular screen.
`$screen` string|[WP\_Screen](../classes/wp_screen) Required The screen hook name or screen object. `$with_id` bool Optional Whether to set the ID attribute or not. Default: `true`
File: `wp-admin/includes/list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/list-table.php/)
```
function print_column_headers( $screen, $with_id = true ) {
$wp_list_table = new _WP_List_Table_Compat( $screen );
$wp_list_table->print_column_headers( $with_id );
}
```
| Uses | Description |
| --- | --- |
| [\_WP\_List\_Table\_Compat::\_\_construct()](../classes/_wp_list_table_compat/__construct) wp-admin/includes/class-wp-list-table-compat.php | Constructor. |
| [WP\_List\_Table::print\_column\_headers()](../classes/wp_list_table/print_column_headers) wp-admin/includes/class-wp-list-table.php | Prints column headers, accounting for hidden and sortable columns. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress wp_allowed_protocols(): string[] wp\_allowed\_protocols(): string[]
==================================
Retrieves a list of protocols to allow in HTML attributes.
* [wp\_kses()](wp_kses)
* [esc\_url()](esc_url)
string[] Array of allowed protocols. Defaults to an array containing `'http'`, `'https'`, `'ftp'`, `'ftps'`, `'mailto'`, `'news'`, `'irc'`, `'irc6'`, `'ircs'`, `'gopher'`, `'nntp'`, `'feed'`, `'telnet'`, `'mms'`, `'rtsp'`, `'sms'`, `'svn'`, `'tel'`, `'fax'`, `'xmpp'`, `'webcal'`, and `'urn'`.
This covers all common link protocols, except for `'javascript'` which should not be allowed for untrusted users.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function wp_allowed_protocols() {
static $protocols = array();
if ( empty( $protocols ) ) {
$protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'irc6', 'ircs', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'sms', 'svn', 'tel', 'fax', 'xmpp', 'webcal', 'urn' );
}
if ( ! did_action( 'wp_loaded' ) ) {
/**
* Filters the list of protocols allowed in HTML attributes.
*
* @since 3.0.0
*
* @param string[] $protocols Array of allowed protocols e.g. 'http', 'ftp', 'tel', and more.
*/
$protocols = array_unique( (array) apply_filters( 'kses_allowed_protocols', $protocols ) );
}
return $protocols;
}
```
[apply\_filters( 'kses\_allowed\_protocols', string[] $protocols )](../hooks/kses_allowed_protocols)
Filters the list of protocols allowed in HTML attributes.
| Uses | Description |
| --- | --- |
| [did\_action()](did_action) wp-includes/plugin.php | Retrieves the number of times an action has been fired during the current request. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_rel\_callback()](wp_rel_callback) wp-includes/formatting.php | Callback to add a rel attribute to HTML A element. |
| [wp\_filter\_oembed\_iframe\_title\_attribute()](wp_filter_oembed_iframe_title_attribute) wp-includes/embed.php | Filters the given oEmbed HTML to make sure iframes have a title attribute. |
| [wp\_targeted\_link\_rel\_callback()](wp_targeted_link_rel_callback) wp-includes/formatting.php | Callback to add `rel="noopener"` string to HTML A element. |
| [wp\_kses\_one\_attr()](wp_kses_one_attr) wp-includes/kses.php | Filters one HTML attribute and ensures its value is allowed. |
| [edit\_user()](edit_user) wp-admin/includes/user.php | Edit user settings based on contents of $\_POST |
| [\_links\_add\_base()](_links_add_base) wp-includes/formatting.php | Callback to add a base URL to relative links in passed content. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [safecss\_filter\_attr()](safecss_filter_attr) wp-includes/kses.php | Filters an inline style attribute and removes disallowed rules. |
| [wp\_kses()](wp_kses) wp-includes/kses.php | Filters text content and strips out disallowed HTML. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Added `'irc6'` and `'ircs'` to the protocols array. |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Added `'sms'` to the protocols array. |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Added `'urn'` to the protocols array. |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Added `'webcal'` to the protocols array. |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress wp_dashboard_recent_posts( array $args ): bool wp\_dashboard\_recent\_posts( array $args ): bool
=================================================
Generates Publishing Soon and Recently Published sections.
`$args` array Required An array of query and display arguments.
* `max`intNumber of posts to display.
* `status`stringPost status.
* `order`stringDesignates ascending (`'ASC'`) or descending (`'DESC'`) order.
* `title`stringSection title.
* `id`stringThe container id.
bool False if no posts were found. True otherwise.
File: `wp-admin/includes/dashboard.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/dashboard.php/)
```
function wp_dashboard_recent_posts( $args ) {
$query_args = array(
'post_type' => 'post',
'post_status' => $args['status'],
'orderby' => 'date',
'order' => $args['order'],
'posts_per_page' => (int) $args['max'],
'no_found_rows' => true,
'cache_results' => false,
'perm' => ( 'future' === $args['status'] ) ? 'editable' : 'readable',
);
/**
* Filters the query arguments used for the Recent Posts widget.
*
* @since 4.2.0
*
* @param array $query_args The arguments passed to WP_Query to produce the list of posts.
*/
$query_args = apply_filters( 'dashboard_recent_posts_query_args', $query_args );
$posts = new WP_Query( $query_args );
if ( $posts->have_posts() ) {
echo '<div id="' . $args['id'] . '" class="activity-block">';
echo '<h3>' . $args['title'] . '</h3>';
echo '<ul>';
$today = current_time( 'Y-m-d' );
$tomorrow = current_datetime()->modify( '+1 day' )->format( 'Y-m-d' );
$year = current_time( 'Y' );
while ( $posts->have_posts() ) {
$posts->the_post();
$time = get_the_time( 'U' );
if ( gmdate( 'Y-m-d', $time ) === $today ) {
$relative = __( 'Today' );
} elseif ( gmdate( 'Y-m-d', $time ) === $tomorrow ) {
$relative = __( 'Tomorrow' );
} elseif ( gmdate( 'Y', $time ) !== $year ) {
/* translators: Date and time format for recent posts on the dashboard, from a different calendar year, see https://www.php.net/manual/datetime.format.php */
$relative = date_i18n( __( 'M jS Y' ), $time );
} else {
/* translators: Date and time format for recent posts on the dashboard, see https://www.php.net/manual/datetime.format.php */
$relative = date_i18n( __( 'M jS' ), $time );
}
// Use the post edit link for those who can edit, the permalink otherwise.
$recent_post_link = current_user_can( 'edit_post', get_the_ID() ) ? get_edit_post_link() : get_permalink();
$draft_or_post_title = _draft_or_post_title();
printf(
'<li><span>%1$s</span> <a href="%2$s" aria-label="%3$s">%4$s</a></li>',
/* translators: 1: Relative date, 2: Time. */
sprintf( _x( '%1$s, %2$s', 'dashboard' ), $relative, get_the_time() ),
$recent_post_link,
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'Edit “%s”' ), $draft_or_post_title ) ),
$draft_or_post_title
);
}
echo '</ul>';
echo '</div>';
} else {
return false;
}
wp_reset_postdata();
return true;
}
```
[apply\_filters( 'dashboard\_recent\_posts\_query\_args', array $query\_args )](../hooks/dashboard_recent_posts_query_args)
Filters the query arguments used for the Recent Posts widget.
| Uses | Description |
| --- | --- |
| [current\_datetime()](current_datetime) wp-includes/functions.php | Retrieves the current time as an object using the site’s timezone. |
| [\_draft\_or\_post\_title()](_draft_or_post_title) wp-admin/includes/template.php | Gets the post title. |
| [get\_the\_time()](get_the_time) wp-includes/general-template.php | Retrieves the time at which the post was written. |
| [WP\_Query::\_\_construct()](../classes/wp_query/__construct) wp-includes/class-wp-query.php | Constructor. |
| [wp\_reset\_postdata()](wp_reset_postdata) wp-includes/query.php | After looping through a separate query, this function restores the $post global to the current post in the main query. |
| [date\_i18n()](date_i18n) wp-includes/functions.php | Retrieves the date in localized format, based on a sum of Unix timestamp and timezone offset in seconds. |
| [current\_time()](current_time) wp-includes/functions.php | Retrieves the current time based on specified type. |
| [get\_edit\_post\_link()](get_edit_post_link) wp-includes/link-template.php | Retrieves the edit post link for post. |
| [get\_the\_ID()](get_the_id) wp-includes/post-template.php | Retrieves the ID of the current item in the WordPress Loop. |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [get\_permalink()](get_permalink) wp-includes/link-template.php | Retrieves the full permalink for the current post or post ID. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_dashboard\_site\_activity()](wp_dashboard_site_activity) wp-admin/includes/dashboard.php | Callback function for Activity widget. |
| Version | Description |
| --- | --- |
| [3.8.0](https://developer.wordpress.org/reference/since/3.8.0/) | Introduced. |
wordpress get_term_to_edit( int|object $id, string $taxonomy ): string|int|null|WP_Error get\_term\_to\_edit( int|object $id, string $taxonomy ): string|int|null|WP\_Error
==================================================================================
Sanitizes term for editing.
Return value is [sanitize\_term()](sanitize_term) and usage is for sanitizing the term for editing. Function is for contextual and simplicity.
`$id` int|object Required Term ID or object. `$taxonomy` string Required Taxonomy name. string|int|null|[WP\_Error](../classes/wp_error) Will return empty string if $term is not an object.
File: `wp-includes/taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/taxonomy.php/)
```
function get_term_to_edit( $id, $taxonomy ) {
$term = get_term( $id, $taxonomy );
if ( is_wp_error( $term ) ) {
return $term;
}
if ( ! is_object( $term ) ) {
return '';
}
return sanitize_term( $term, $taxonomy, 'edit' );
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_term()](sanitize_term) wp-includes/taxonomy.php | Sanitizes all term fields. |
| [get\_term()](get_term) wp-includes/taxonomy.php | Gets all term data from database by term ID. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
wordpress populate_roles_250() populate\_roles\_250()
======================
Create and modify WordPress roles for WordPress 2.5.
File: `wp-admin/includes/schema.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/schema.php/)
```
function populate_roles_250() {
$role = get_role( 'administrator' );
if ( ! empty( $role ) ) {
$role->add_cap( 'edit_dashboard' );
}
}
```
| Uses | Description |
| --- | --- |
| [get\_role()](get_role) wp-includes/capabilities.php | Retrieves role object. |
| Used By | Description |
| --- | --- |
| [populate\_roles()](populate_roles) wp-admin/includes/schema.php | Execute WordPress role creation for the various WordPress versions. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress get_plugins( string $plugin_folder = '' ): array[] get\_plugins( string $plugin\_folder = '' ): array[]
====================================================
Checks the plugins directory and retrieve all plugin files with plugin data.
WordPress only supports plugin files in the base plugins directory (wp-content/plugins) and in one directory above the plugins directory (wp-content/plugins/my-plugin). The file it looks for has the plugin data and must be found in those two locations. It is recommended to keep your plugin files in their own directories.
The file with the plugin data is the file that will be included and therefore needs to have the main execution for the plugin. This does not mean everything must be contained in the file and it is recommended that the file be split for maintainability. Keep everything in one file for extreme optimization purposes.
`$plugin_folder` string Optional Relative path to single plugin folder. Default: `''`
array[] Array of arrays of plugin data, keyed by plugin file name. See [get\_plugin\_data()](get_plugin_data) .
If you have ``PHP Fatal error: Call to undefined function get_plugins()`` then you must include the file ‘`wp-admin/includes/plugin.php`‘ like in example.
Results are cached on the first run of the function, therefore it is recommended to call the function at least after the ‘`after_setup_theme`‘ action so that plugins and themes have the ability to filter the results.
File: `wp-admin/includes/plugin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/plugin.php/)
```
function get_plugins( $plugin_folder = '' ) {
$cache_plugins = wp_cache_get( 'plugins', 'plugins' );
if ( ! $cache_plugins ) {
$cache_plugins = array();
}
if ( isset( $cache_plugins[ $plugin_folder ] ) ) {
return $cache_plugins[ $plugin_folder ];
}
$wp_plugins = array();
$plugin_root = WP_PLUGIN_DIR;
if ( ! empty( $plugin_folder ) ) {
$plugin_root .= $plugin_folder;
}
// Files in wp-content/plugins directory.
$plugins_dir = @opendir( $plugin_root );
$plugin_files = array();
if ( $plugins_dir ) {
while ( ( $file = readdir( $plugins_dir ) ) !== false ) {
if ( '.' === substr( $file, 0, 1 ) ) {
continue;
}
if ( is_dir( $plugin_root . '/' . $file ) ) {
$plugins_subdir = @opendir( $plugin_root . '/' . $file );
if ( $plugins_subdir ) {
while ( ( $subfile = readdir( $plugins_subdir ) ) !== false ) {
if ( '.' === substr( $subfile, 0, 1 ) ) {
continue;
}
if ( '.php' === substr( $subfile, -4 ) ) {
$plugin_files[] = "$file/$subfile";
}
}
closedir( $plugins_subdir );
}
} else {
if ( '.php' === substr( $file, -4 ) ) {
$plugin_files[] = $file;
}
}
}
closedir( $plugins_dir );
}
if ( empty( $plugin_files ) ) {
return $wp_plugins;
}
foreach ( $plugin_files as $plugin_file ) {
if ( ! is_readable( "$plugin_root/$plugin_file" ) ) {
continue;
}
// Do not apply markup/translate as it will be cached.
$plugin_data = get_plugin_data( "$plugin_root/$plugin_file", false, false );
if ( empty( $plugin_data['Name'] ) ) {
continue;
}
$wp_plugins[ plugin_basename( $plugin_file ) ] = $plugin_data;
}
uasort( $wp_plugins, '_sort_uname_callback' );
$cache_plugins[ $plugin_folder ] = $wp_plugins;
wp_cache_set( 'plugins', $cache_plugins, 'plugins' );
return $wp_plugins;
}
```
| Uses | Description |
| --- | --- |
| [get\_plugin\_data()](get_plugin_data) wp-admin/includes/plugin.php | Parses the plugin contents to retrieve plugin’s metadata. |
| [wp\_cache\_set()](wp_cache_set) wp-includes/cache.php | Saves the data to the cache. |
| [plugin\_basename()](plugin_basename) wp-includes/plugin.php | Gets the basename of a plugin. |
| [wp\_cache\_get()](wp_cache_get) wp-includes/cache.php | Retrieves the cache contents from the cache by key and group. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Block\_Directory\_Controller::find\_plugin\_for\_slug()](../classes/wp_rest_block_directory_controller/find_plugin_for_slug) wp-includes/rest-api/endpoints/class-wp-rest-block-directory-controller.php | Finds an installed plugin for the given slug. |
| [WP\_REST\_Plugins\_Controller::get\_plugin\_data()](../classes/wp_rest_plugins_controller/get_plugin_data) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Gets the plugin header data for a plugin. |
| [WP\_REST\_Plugins\_Controller::get\_items()](../classes/wp_rest_plugins_controller/get_items) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Retrieves a collection of plugins. |
| [Plugin\_Installer\_Skin::do\_overwrite()](../classes/plugin_installer_skin/do_overwrite) wp-admin/includes/class-plugin-installer-skin.php | Check if the plugin can be overwritten and output the HTML for overwriting a plugin on upload. |
| [wp\_ajax\_toggle\_auto\_updates()](wp_ajax_toggle_auto_updates) wp-admin/includes/ajax-actions.php | Ajax handler to enable or disable plugin and theme auto-updates. |
| [WP\_Recovery\_Mode\_Email\_Service::get\_plugin()](../classes/wp_recovery_mode_email_service/get_plugin) wp-includes/class-wp-recovery-mode-email-service.php | Return the details for a single plugin based on the extension data from an error. |
| [WP\_Debug\_Data::debug\_data()](../classes/wp_debug_data/debug_data) wp-admin/includes/class-wp-debug-data.php | Static function for generating site debug data when required. |
| [WP\_Site\_Health::get\_test\_plugin\_version()](../classes/wp_site_health/get_test_plugin_version) wp-admin/includes/class-wp-site-health.php | Tests if plugins are outdated, or unnecessary. |
| [do\_block\_editor\_incompatible\_meta\_box()](do_block_editor_incompatible_meta_box) wp-admin/includes/template.php | Renders a “fake” meta box with an information message, shown on the block editor, when an incompatible meta box is found. |
| [\_get\_plugin\_from\_callback()](_get_plugin_from_callback) wp-admin/includes/template.php | Internal helper function to find the plugin from a meta box callback. |
| [wp\_edit\_theme\_plugin\_file()](wp_edit_theme_plugin_file) wp-admin/includes/file.php | Attempts to edit a file for a theme or plugin. |
| [wp\_ajax\_update\_plugin()](wp_ajax_update_plugin) wp-admin/includes/ajax-actions.php | Ajax handler for updating a plugin. |
| [Language\_Pack\_Upgrader::get\_name\_for\_update()](../classes/language_pack_upgrader/get_name_for_update) wp-admin/includes/class-language-pack-upgrader.php | Get the name of an item being updated. |
| [Plugin\_Upgrader::plugin\_info()](../classes/plugin_upgrader/plugin_info) wp-admin/includes/class-plugin-upgrader.php | Retrieve the path to the file that contains the plugin info. |
| [WP\_Plugins\_List\_Table::prepare\_items()](../classes/wp_plugins_list_table/prepare_items) wp-admin/includes/class-wp-plugins-list-table.php | |
| [get\_plugin\_updates()](get_plugin_updates) wp-admin/includes/update.php | Retrieves plugins with updates available. |
| [install\_plugin\_install\_status()](install_plugin_install_status) wp-admin/includes/plugin-install.php | Determines the status we can perform on a plugin. |
| [wp\_dashboard\_plugins\_output()](wp_dashboard_plugins_output) wp-admin/includes/deprecated.php | Display plugins text for the WordPress news widget. |
| [validate\_plugin()](validate_plugin) wp-admin/includes/plugin.php | Validates the plugin path. |
| [wp\_link\_manager\_disabled\_message()](wp_link_manager_disabled_message) wp-admin/includes/bookmark.php | Outputs the ‘disabled’ message for the WordPress Link Manager. |
| [wp\_update\_plugins()](wp_update_plugins) wp-includes/update.php | Checks for available updates to plugins based on the latest versions hosted on WordPress.org. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
| programming_docs |
wordpress wp_opcache_invalidate( string $filepath, bool $force = false ): bool wp\_opcache\_invalidate( string $filepath, bool $force = false ): bool
======================================================================
Attempts to clear the opcode cache for an individual PHP file.
This function can be called safely without having to check the file extension or availability of the OPcache extension.
Whether or not invalidation is possible is cached to improve performance.
`$filepath` string Required Path to the file, including extension, for which the opcode cache is to be cleared. `$force` bool Optional Invalidate even if the modification time is not newer than the file in cache.
Default: `false`
bool True if opcache was invalidated for `$filepath`, or there was nothing to invalidate.
False if opcache invalidation is not available, or is disabled via filter.
File: `wp-admin/includes/file.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/file.php/)
```
function wp_opcache_invalidate( $filepath, $force = false ) {
static $can_invalidate = null;
/*
* Check to see if WordPress is able to run `opcache_invalidate()` or not, and cache the value.
*
* First, check to see if the function is available to call, then if the host has restricted
* the ability to run the function to avoid a PHP warning.
*
* `opcache.restrict_api` can specify the path for files allowed to call `opcache_invalidate()`.
*
* If the host has this set, check whether the path in `opcache.restrict_api` matches
* the beginning of the path of the origin file.
*
* `$_SERVER['SCRIPT_FILENAME']` approximates the origin file's path, but `realpath()`
* is necessary because `SCRIPT_FILENAME` can be a relative path when run from CLI.
*
* For more details, see:
* - https://www.php.net/manual/en/opcache.configuration.php
* - https://www.php.net/manual/en/reserved.variables.server.php
* - https://core.trac.wordpress.org/ticket/36455
*/
if ( null === $can_invalidate
&& function_exists( 'opcache_invalidate' )
&& ( ! ini_get( 'opcache.restrict_api' )
|| stripos( realpath( $_SERVER['SCRIPT_FILENAME'] ), ini_get( 'opcache.restrict_api' ) ) === 0 )
) {
$can_invalidate = true;
}
// If invalidation is not available, return early.
if ( ! $can_invalidate ) {
return false;
}
// Verify that file to be invalidated has a PHP extension.
if ( '.php' !== strtolower( substr( $filepath, -4 ) ) ) {
return false;
}
/**
* Filters whether to invalidate a file from the opcode cache.
*
* @since 5.5.0
*
* @param bool $will_invalidate Whether WordPress will invalidate `$filepath`. Default true.
* @param string $filepath The path to the PHP file to invalidate.
*/
if ( apply_filters( 'wp_opcache_invalidate_file', true, $filepath ) ) {
return opcache_invalidate( $filepath, $force );
}
return false;
}
```
[apply\_filters( 'wp\_opcache\_invalidate\_file', bool $will\_invalidate, string $filepath )](../hooks/wp_opcache_invalidate_file)
Filters whether to invalidate a file from the opcode cache.
| Uses | Description |
| --- | --- |
| [stripos()](stripos) wp-includes/class-pop3.php | |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_edit\_theme\_plugin\_file()](wp_edit_theme_plugin_file) wp-admin/includes/file.php | Attempts to edit a file for a theme or plugin. |
| [Core\_Upgrader::upgrade()](../classes/core_upgrader/upgrade) wp-admin/includes/class-core-upgrader.php | Upgrade WordPress core. |
| [update\_core()](update_core) wp-admin/includes/update-core.php | Upgrades the core of WordPress. |
| [copy\_dir()](copy_dir) wp-admin/includes/file.php | Copies a directory from one location to another via the WordPress Filesystem Abstraction. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress _wp_make_subsizes( array $new_sizes, string $file, array $image_meta, int $attachment_id ): array \_wp\_make\_subsizes( array $new\_sizes, string $file, array $image\_meta, int $attachment\_id ): array
=======================================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Low-level function to create image sub-sizes.
Updates the image meta after each sub-size is created.
Errors are stored in the returned image metadata array.
`$new_sizes` array Required Array defining what sizes to create. `$file` string Required Full path to the image file. `$image_meta` array Required The attachment meta data array. `$attachment_id` int Required Attachment ID to process. array The attachment meta data with updated `sizes` array. Includes an array of errors encountered while resizing.
File: `wp-admin/includes/image.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/image.php/)
```
function _wp_make_subsizes( $new_sizes, $file, $image_meta, $attachment_id ) {
if ( empty( $image_meta ) || ! is_array( $image_meta ) ) {
// Not an image attachment.
return array();
}
// Check if any of the new sizes already exist.
if ( isset( $image_meta['sizes'] ) && is_array( $image_meta['sizes'] ) ) {
foreach ( $image_meta['sizes'] as $size_name => $size_meta ) {
/*
* Only checks "size name" so we don't override existing images even if the dimensions
* don't match the currently defined size with the same name.
* To change the behavior, unset changed/mismatched sizes in the `sizes` array in image meta.
*/
if ( array_key_exists( $size_name, $new_sizes ) ) {
unset( $new_sizes[ $size_name ] );
}
}
} else {
$image_meta['sizes'] = array();
}
if ( empty( $new_sizes ) ) {
// Nothing to do...
return $image_meta;
}
/*
* Sort the image sub-sizes in order of priority when creating them.
* This ensures there is an appropriate sub-size the user can access immediately
* even when there was an error and not all sub-sizes were created.
*/
$priority = array(
'medium' => null,
'large' => null,
'thumbnail' => null,
'medium_large' => null,
);
$new_sizes = array_filter( array_merge( $priority, $new_sizes ) );
$editor = wp_get_image_editor( $file );
if ( is_wp_error( $editor ) ) {
// The image cannot be edited.
return $image_meta;
}
// If stored EXIF data exists, rotate the source image before creating sub-sizes.
if ( ! empty( $image_meta['image_meta'] ) ) {
$rotated = $editor->maybe_exif_rotate();
if ( is_wp_error( $rotated ) ) {
// TODO: Log errors.
}
}
if ( method_exists( $editor, 'make_subsize' ) ) {
foreach ( $new_sizes as $new_size_name => $new_size_data ) {
$new_size_meta = $editor->make_subsize( $new_size_data );
if ( is_wp_error( $new_size_meta ) ) {
// TODO: Log errors.
} else {
// Save the size meta value.
$image_meta['sizes'][ $new_size_name ] = $new_size_meta;
wp_update_attachment_metadata( $attachment_id, $image_meta );
}
}
} else {
// Fall back to `$editor->multi_resize()`.
$created_sizes = $editor->multi_resize( $new_sizes );
if ( ! empty( $created_sizes ) ) {
$image_meta['sizes'] = array_merge( $image_meta['sizes'], $created_sizes );
wp_update_attachment_metadata( $attachment_id, $image_meta );
}
}
return $image_meta;
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_image\_editor()](wp_get_image_editor) wp-includes/media.php | Returns a [WP\_Image\_Editor](../classes/wp_image_editor) instance and loads file into it. |
| [wp\_update\_attachment\_metadata()](wp_update_attachment_metadata) wp-includes/post.php | Updates metadata for an attachment. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [wp\_update\_image\_subsizes()](wp_update_image_subsizes) wp-admin/includes/image.php | If any of the currently registered image sub-sizes are missing, create them and update the image meta data. |
| [wp\_create\_image\_subsizes()](wp_create_image_subsizes) wp-admin/includes/image.php | Creates image sub-sizes, adds the new data to the image meta `sizes` array, and updates the image metadata. |
| [wp\_generate\_attachment\_metadata()](wp_generate_attachment_metadata) wp-admin/includes/image.php | Generates attachment meta data and create image sub-sizes for images. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress get_nonauthor_user_ids() get\_nonauthor\_user\_ids()
===========================
This function has been deprecated. Use [get\_users()](get_users) instead.
Gets all users who are not authors.
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
function get_nonauthor_user_ids() {
_deprecated_function( __FUNCTION__, '3.1.0', 'get_users()' );
global $wpdb;
if ( !is_multisite() )
$level_key = $wpdb->get_blog_prefix() . 'user_level';
else
$level_key = $wpdb->get_blog_prefix() . 'capabilities'; // WPMU site admins don't have user_levels.
return $wpdb->get_col( $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s AND meta_value = '0'", $level_key) );
}
```
| Uses | Description |
| --- | --- |
| [wpdb::get\_col()](../classes/wpdb/get_col) wp-includes/class-wpdb.php | Retrieves one column from the database. |
| [wpdb::get\_blog\_prefix()](../classes/wpdb/get_blog_prefix) wp-includes/class-wpdb.php | Gets blog prefix. |
| [is\_multisite()](is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| [wpdb::prepare()](../classes/wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress the_media_upload_tabs() the\_media\_upload\_tabs()
==========================
Outputs the legacy media upload tabs UI.
File: `wp-admin/includes/media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/media.php/)
```
function the_media_upload_tabs() {
global $redir_tab;
$tabs = media_upload_tabs();
$default = 'type';
if ( ! empty( $tabs ) ) {
echo "<ul id='sidemenu'>\n";
if ( isset( $redir_tab ) && array_key_exists( $redir_tab, $tabs ) ) {
$current = $redir_tab;
} elseif ( isset( $_GET['tab'] ) && array_key_exists( $_GET['tab'], $tabs ) ) {
$current = $_GET['tab'];
} else {
/** This filter is documented in wp-admin/media-upload.php */
$current = apply_filters( 'media_upload_default_tab', $default );
}
foreach ( $tabs as $callback => $text ) {
$class = '';
if ( $current == $callback ) {
$class = " class='current'";
}
$href = add_query_arg(
array(
'tab' => $callback,
's' => false,
'paged' => false,
'post_mime_type' => false,
'm' => false,
)
);
$link = "<a href='" . esc_url( $href ) . "'$class>$text</a>";
echo "\t<li id='" . esc_attr( "tab-$callback" ) . "'>$link</li>\n";
}
echo "</ul>\n";
}
}
```
[apply\_filters( 'media\_upload\_default\_tab', string $tab )](../hooks/media_upload_default_tab)
Filters the default tab in the legacy (pre-3.5.0) media popup.
| Uses | Description |
| --- | --- |
| [media\_upload\_tabs()](media_upload_tabs) wp-admin/includes/media.php | Defines the default media upload tabs. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [add\_query\_arg()](add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [media\_upload\_header()](media_upload_header) wp-admin/includes/media.php | Outputs the legacy media upload header. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress _links_add_base( string $m ): string \_links\_add\_base( string $m ): string
=======================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Callback to add a base URL to relative links in passed content.
`$m` string Required The matched link. string The processed link.
File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function _links_add_base( $m ) {
global $_links_add_base;
// 1 = attribute name 2 = quotation mark 3 = URL.
return $m[1] . '=' . $m[2] .
( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols(), true ) ?
$m[3] :
WP_Http::make_absolute_url( $m[3], $_links_add_base )
)
. $m[2];
}
```
| Uses | Description |
| --- | --- |
| [WP\_Http::make\_absolute\_url()](../classes/wp_http/make_absolute_url) wp-includes/class-wp-http.php | Converts a relative URL to an absolute URL relative to a given URL. |
| [wp\_allowed\_protocols()](wp_allowed_protocols) wp-includes/functions.php | Retrieves a list of protocols to allow in HTML attributes. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress wp_spaces_regexp(): string wp\_spaces\_regexp(): string
============================
Returns the regexp for common whitespace characters.
By default, spaces include new lines, tabs, nbsp entities, and the UTF-8 nbsp.
This is designed to replace the PCRE \s sequence. In ticket #22692, that sequence was found to be unreliable due to random inclusion of the A0 byte.
string The spaces regexp.
File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function wp_spaces_regexp() {
static $spaces = '';
if ( empty( $spaces ) ) {
/**
* Filters the regexp for common whitespace characters.
*
* This string is substituted for the \s sequence as needed in regular
* expressions. For websites not written in English, different characters
* may represent whitespace. For websites not encoded in UTF-8, the 0xC2 0xA0
* sequence may not be in use.
*
* @since 4.0.0
*
* @param string $spaces Regexp pattern for matching common whitespace characters.
*/
$spaces = apply_filters( 'wp_spaces_regexp', '[\r\n\t ]|\xC2\xA0| ' );
}
return $spaces;
}
```
[apply\_filters( 'wp\_spaces\_regexp', string $spaces )](../hooks/wp_spaces_regexp)
Filters the regexp for common whitespace characters.
| Uses | Description |
| --- | --- |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [wptexturize\_primes()](wptexturize_primes) wp-includes/formatting.php | Implements a logic tree to determine whether or not “7′.” represents seven feet, then converts the special char into either a prime char or a closing quote char. |
| [wptexturize()](wptexturize) wp-includes/formatting.php | Replaces common plain text characters with formatted entities. |
| [shortcode\_unautop()](shortcode_unautop) wp-includes/formatting.php | Don’t auto-p wrap shortcodes that stand alone. |
| [smilies\_init()](smilies_init) wp-includes/functions.php | Converts smiley code to the icon graphic file equivalent. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress wp_ajax_install_plugin() wp\_ajax\_install\_plugin()
===========================
Ajax handler for installing a plugin.
* [Plugin\_Upgrader](../classes/plugin_upgrader)
File: `wp-admin/includes/ajax-actions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/ajax-actions.php/)
```
function wp_ajax_install_plugin() {
check_ajax_referer( 'updates' );
if ( empty( $_POST['slug'] ) ) {
wp_send_json_error(
array(
'slug' => '',
'errorCode' => 'no_plugin_specified',
'errorMessage' => __( 'No plugin specified.' ),
)
);
}
$status = array(
'install' => 'plugin',
'slug' => sanitize_key( wp_unslash( $_POST['slug'] ) ),
);
if ( ! current_user_can( 'install_plugins' ) ) {
$status['errorMessage'] = __( 'Sorry, you are not allowed to install plugins on this site.' );
wp_send_json_error( $status );
}
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
include_once ABSPATH . 'wp-admin/includes/plugin-install.php';
$api = plugins_api(
'plugin_information',
array(
'slug' => sanitize_key( wp_unslash( $_POST['slug'] ) ),
'fields' => array(
'sections' => false,
),
)
);
if ( is_wp_error( $api ) ) {
$status['errorMessage'] = $api->get_error_message();
wp_send_json_error( $status );
}
$status['pluginName'] = $api->name;
$skin = new WP_Ajax_Upgrader_Skin();
$upgrader = new Plugin_Upgrader( $skin );
$result = $upgrader->install( $api->download_link );
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
$status['debug'] = $skin->get_upgrade_messages();
}
if ( is_wp_error( $result ) ) {
$status['errorCode'] = $result->get_error_code();
$status['errorMessage'] = $result->get_error_message();
wp_send_json_error( $status );
} elseif ( is_wp_error( $skin->result ) ) {
$status['errorCode'] = $skin->result->get_error_code();
$status['errorMessage'] = $skin->result->get_error_message();
wp_send_json_error( $status );
} elseif ( $skin->get_errors()->has_errors() ) {
$status['errorMessage'] = $skin->get_error_messages();
wp_send_json_error( $status );
} elseif ( is_null( $result ) ) {
global $wp_filesystem;
$status['errorCode'] = 'unable_to_connect_to_filesystem';
$status['errorMessage'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' );
// Pass through the error from WP_Filesystem if one was raised.
if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
$status['errorMessage'] = esc_html( $wp_filesystem->errors->get_error_message() );
}
wp_send_json_error( $status );
}
$install_status = install_plugin_install_status( $api );
$pagenow = isset( $_POST['pagenow'] ) ? sanitize_key( $_POST['pagenow'] ) : '';
// If installation request is coming from import page, do not return network activation link.
$plugins_url = ( 'import' === $pagenow ) ? admin_url( 'plugins.php' ) : network_admin_url( 'plugins.php' );
if ( current_user_can( 'activate_plugin', $install_status['file'] ) && is_plugin_inactive( $install_status['file'] ) ) {
$status['activateUrl'] = add_query_arg(
array(
'_wpnonce' => wp_create_nonce( 'activate-plugin_' . $install_status['file'] ),
'action' => 'activate',
'plugin' => $install_status['file'],
),
$plugins_url
);
}
if ( is_multisite() && current_user_can( 'manage_network_plugins' ) && 'import' !== $pagenow ) {
$status['activateUrl'] = add_query_arg( array( 'networkwide' => 1 ), $status['activateUrl'] );
}
wp_send_json_success( $status );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Ajax\_Upgrader\_Skin::\_\_construct()](../classes/wp_ajax_upgrader_skin/__construct) wp-admin/includes/class-wp-ajax-upgrader-skin.php | Constructor. |
| [install\_plugin\_install\_status()](install_plugin_install_status) wp-admin/includes/plugin-install.php | Determines the status we can perform on a plugin. |
| [network\_admin\_url()](network_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the network. |
| [wp\_create\_nonce()](wp_create_nonce) wp-includes/pluggable.php | Creates a cryptographic token tied to a specific action, user, user session, and window of time. |
| [plugins\_api()](plugins_api) wp-admin/includes/plugin-install.php | Retrieves plugin installer pages from the WordPress.org Plugins API. |
| [is\_plugin\_inactive()](is_plugin_inactive) wp-admin/includes/plugin.php | Determines whether the plugin is inactive. |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_unslash()](wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [sanitize\_key()](sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [check\_ajax\_referer()](check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [is\_multisite()](is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [wp\_send\_json\_error()](wp_send_json_error) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating failure. |
| [wp\_send\_json\_success()](wp_send_json_success) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating success. |
| [add\_query\_arg()](add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [admin\_url()](admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
| programming_docs |
wordpress wp_nav_menu_item_post_type_meta_box( string $data_object, array $box ) wp\_nav\_menu\_item\_post\_type\_meta\_box( string $data\_object, array $box )
==============================================================================
Displays a meta box for a post type menu item.
`$data_object` string Required Not used. `$box` array Required Post type menu item meta box arguments.
* `id`stringMeta box `'id'` attribute.
* `title`stringMeta box title.
* `callback`callableMeta box display callback.
* `args`[WP\_Post\_Type](../classes/wp_post_type)Extra meta box arguments (the post type object for this meta box).
File: `wp-admin/includes/nav-menu.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/nav-menu.php/)
```
function wp_nav_menu_item_post_type_meta_box( $data_object, $box ) {
global $_nav_menu_placeholder, $nav_menu_selected_id;
$post_type_name = $box['args']->name;
$post_type = get_post_type_object( $post_type_name );
$tab_name = $post_type_name . '-tab';
// Paginate browsing for large numbers of post objects.
$per_page = 50;
$pagenum = isset( $_REQUEST[ $tab_name ] ) && isset( $_REQUEST['paged'] ) ? absint( $_REQUEST['paged'] ) : 1;
$offset = 0 < $pagenum ? $per_page * ( $pagenum - 1 ) : 0;
$args = array(
'offset' => $offset,
'order' => 'ASC',
'orderby' => 'title',
'posts_per_page' => $per_page,
'post_type' => $post_type_name,
'suppress_filters' => true,
'update_post_term_cache' => false,
'update_post_meta_cache' => false,
);
if ( isset( $box['args']->_default_query ) ) {
$args = array_merge( $args, (array) $box['args']->_default_query );
}
/*
* If we're dealing with pages, let's prioritize the Front Page,
* Posts Page and Privacy Policy Page at the top of the list.
*/
$important_pages = array();
if ( 'page' === $post_type_name ) {
$suppress_page_ids = array();
// Insert Front Page or custom Home link.
$front_page = 'page' === get_option( 'show_on_front' ) ? (int) get_option( 'page_on_front' ) : 0;
$front_page_obj = null;
if ( ! empty( $front_page ) ) {
$front_page_obj = get_post( $front_page );
$front_page_obj->front_or_home = true;
$important_pages[] = $front_page_obj;
$suppress_page_ids[] = $front_page_obj->ID;
} else {
$_nav_menu_placeholder = ( 0 > $_nav_menu_placeholder ) ? (int) $_nav_menu_placeholder - 1 : -1;
$front_page_obj = (object) array(
'front_or_home' => true,
'ID' => 0,
'object_id' => $_nav_menu_placeholder,
'post_content' => '',
'post_excerpt' => '',
'post_parent' => '',
'post_title' => _x( 'Home', 'nav menu home label' ),
'post_type' => 'nav_menu_item',
'type' => 'custom',
'url' => home_url( '/' ),
);
$important_pages[] = $front_page_obj;
}
// Insert Posts Page.
$posts_page = 'page' === get_option( 'show_on_front' ) ? (int) get_option( 'page_for_posts' ) : 0;
if ( ! empty( $posts_page ) ) {
$posts_page_obj = get_post( $posts_page );
$posts_page_obj->posts_page = true;
$important_pages[] = $posts_page_obj;
$suppress_page_ids[] = $posts_page_obj->ID;
}
// Insert Privacy Policy Page.
$privacy_policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' );
if ( ! empty( $privacy_policy_page_id ) ) {
$privacy_policy_page = get_post( $privacy_policy_page_id );
if ( $privacy_policy_page instanceof WP_Post && 'publish' === $privacy_policy_page->post_status ) {
$privacy_policy_page->privacy_policy_page = true;
$important_pages[] = $privacy_policy_page;
$suppress_page_ids[] = $privacy_policy_page->ID;
}
}
// Add suppression array to arguments for WP_Query.
if ( ! empty( $suppress_page_ids ) ) {
$args['post__not_in'] = $suppress_page_ids;
}
}
// @todo Transient caching of these results with proper invalidation on updating of a post of this type.
$get_posts = new WP_Query;
$posts = $get_posts->query( $args );
// Only suppress and insert when more than just suppression pages available.
if ( ! $get_posts->post_count ) {
if ( ! empty( $suppress_page_ids ) ) {
unset( $args['post__not_in'] );
$get_posts = new WP_Query;
$posts = $get_posts->query( $args );
} else {
echo '<p>' . __( 'No items.' ) . '</p>';
return;
}
} elseif ( ! empty( $important_pages ) ) {
$posts = array_merge( $important_pages, $posts );
}
$num_pages = $get_posts->max_num_pages;
$page_links = paginate_links(
array(
'base' => add_query_arg(
array(
$tab_name => 'all',
'paged' => '%#%',
'item-type' => 'post_type',
'item-object' => $post_type_name,
)
),
'format' => '',
'prev_text' => '<span aria-label="' . esc_attr__( 'Previous page' ) . '">' . __( '«' ) . '</span>',
'next_text' => '<span aria-label="' . esc_attr__( 'Next page' ) . '">' . __( '»' ) . '</span>',
'before_page_number' => '<span class="screen-reader-text">' . __( 'Page' ) . '</span> ',
'total' => $num_pages,
'current' => $pagenum,
)
);
$db_fields = false;
if ( is_post_type_hierarchical( $post_type_name ) ) {
$db_fields = array(
'parent' => 'post_parent',
'id' => 'ID',
);
}
$walker = new Walker_Nav_Menu_Checklist( $db_fields );
$current_tab = 'most-recent';
if ( isset( $_REQUEST[ $tab_name ] ) && in_array( $_REQUEST[ $tab_name ], array( 'all', 'search' ), true ) ) {
$current_tab = $_REQUEST[ $tab_name ];
}
if ( ! empty( $_REQUEST[ 'quick-search-posttype-' . $post_type_name ] ) ) {
$current_tab = 'search';
}
$removed_args = array(
'action',
'customlink-tab',
'edit-menu-item',
'menu-item',
'page-tab',
'_wpnonce',
);
$most_recent_url = '';
$view_all_url = '';
$search_url = '';
if ( $nav_menu_selected_id ) {
$most_recent_url = esc_url( add_query_arg( $tab_name, 'most-recent', remove_query_arg( $removed_args ) ) );
$view_all_url = esc_url( add_query_arg( $tab_name, 'all', remove_query_arg( $removed_args ) ) );
$search_url = esc_url( add_query_arg( $tab_name, 'search', remove_query_arg( $removed_args ) ) );
}
?>
<div id="posttype-<?php echo $post_type_name; ?>" class="posttypediv">
<ul id="posttype-<?php echo $post_type_name; ?>-tabs" class="posttype-tabs add-menu-item-tabs">
<li <?php echo ( 'most-recent' === $current_tab ? ' class="tabs"' : '' ); ?>>
<a class="nav-tab-link" data-type="tabs-panel-posttype-<?php echo esc_attr( $post_type_name ); ?>-most-recent" href="<?php echo $most_recent_url; ?>#tabs-panel-posttype-<?php echo $post_type_name; ?>-most-recent">
<?php _e( 'Most Recent' ); ?>
</a>
</li>
<li <?php echo ( 'all' === $current_tab ? ' class="tabs"' : '' ); ?>>
<a class="nav-tab-link" data-type="<?php echo esc_attr( $post_type_name ); ?>-all" href="<?php echo $view_all_url; ?>#<?php echo $post_type_name; ?>-all">
<?php _e( 'View All' ); ?>
</a>
</li>
<li <?php echo ( 'search' === $current_tab ? ' class="tabs"' : '' ); ?>>
<a class="nav-tab-link" data-type="tabs-panel-posttype-<?php echo esc_attr( $post_type_name ); ?>-search" href="<?php echo $search_url; ?>#tabs-panel-posttype-<?php echo $post_type_name; ?>-search">
<?php _e( 'Search' ); ?>
</a>
</li>
</ul><!-- .posttype-tabs -->
<div id="tabs-panel-posttype-<?php echo $post_type_name; ?>-most-recent" class="tabs-panel <?php echo ( 'most-recent' === $current_tab ? 'tabs-panel-active' : 'tabs-panel-inactive' ); ?>" role="region" aria-label="<?php _e( 'Most Recent' ); ?>" tabindex="0">
<ul id="<?php echo $post_type_name; ?>checklist-most-recent" class="categorychecklist form-no-clear">
<?php
$recent_args = array_merge(
$args,
array(
'orderby' => 'post_date',
'order' => 'DESC',
'posts_per_page' => 15,
)
);
$most_recent = $get_posts->query( $recent_args );
$args['walker'] = $walker;
/**
* Filters the posts displayed in the 'Most Recent' tab of the current
* post type's menu items meta box.
*
* The dynamic portion of the hook name, `$post_type_name`, refers to the post type name.
*
* Possible hook names include:
*
* - `nav_menu_items_post_recent`
* - `nav_menu_items_page_recent`
*
* @since 4.3.0
* @since 4.9.0 Added the `$recent_args` parameter.
*
* @param WP_Post[] $most_recent An array of post objects being listed.
* @param array $args An array of `WP_Query` arguments for the meta box.
* @param array $box Arguments passed to `wp_nav_menu_item_post_type_meta_box()`.
* @param array $recent_args An array of `WP_Query` arguments for 'Most Recent' tab.
*/
$most_recent = apply_filters( "nav_menu_items_{$post_type_name}_recent", $most_recent, $args, $box, $recent_args );
echo walk_nav_menu_tree( array_map( 'wp_setup_nav_menu_item', $most_recent ), 0, (object) $args );
?>
</ul>
</div><!-- /.tabs-panel -->
<div class="tabs-panel <?php echo ( 'search' === $current_tab ? 'tabs-panel-active' : 'tabs-panel-inactive' ); ?>" id="tabs-panel-posttype-<?php echo $post_type_name; ?>-search" role="region" aria-label="<?php echo $post_type->labels->search_items; ?>" tabindex="0">
<?php
if ( isset( $_REQUEST[ 'quick-search-posttype-' . $post_type_name ] ) ) {
$searched = esc_attr( $_REQUEST[ 'quick-search-posttype-' . $post_type_name ] );
$search_results = get_posts(
array(
's' => $searched,
'post_type' => $post_type_name,
'fields' => 'all',
'order' => 'DESC',
)
);
} else {
$searched = '';
$search_results = array();
}
?>
<p class="quick-search-wrap">
<label for="quick-search-posttype-<?php echo $post_type_name; ?>" class="screen-reader-text"><?php _e( 'Search' ); ?></label>
<input type="search"<?php wp_nav_menu_disabled_check( $nav_menu_selected_id ); ?> class="quick-search" value="<?php echo $searched; ?>" name="quick-search-posttype-<?php echo $post_type_name; ?>" id="quick-search-posttype-<?php echo $post_type_name; ?>" />
<span class="spinner"></span>
<?php submit_button( __( 'Search' ), 'small quick-search-submit hide-if-js', 'submit', false, array( 'id' => 'submit-quick-search-posttype-' . $post_type_name ) ); ?>
</p>
<ul id="<?php echo $post_type_name; ?>-search-checklist" data-wp-lists="list:<?php echo $post_type_name; ?>" class="categorychecklist form-no-clear">
<?php if ( ! empty( $search_results ) && ! is_wp_error( $search_results ) ) : ?>
<?php
$args['walker'] = $walker;
echo walk_nav_menu_tree( array_map( 'wp_setup_nav_menu_item', $search_results ), 0, (object) $args );
?>
<?php elseif ( is_wp_error( $search_results ) ) : ?>
<li><?php echo $search_results->get_error_message(); ?></li>
<?php elseif ( ! empty( $searched ) ) : ?>
<li><?php _e( 'No results found.' ); ?></li>
<?php endif; ?>
</ul>
</div><!-- /.tabs-panel -->
<div id="<?php echo $post_type_name; ?>-all" class="tabs-panel tabs-panel-view-all <?php echo ( 'all' === $current_tab ? 'tabs-panel-active' : 'tabs-panel-inactive' ); ?>" role="region" aria-label="<?php echo $post_type->labels->all_items; ?>" tabindex="0">
<?php if ( ! empty( $page_links ) ) : ?>
<div class="add-menu-item-pagelinks">
<?php echo $page_links; ?>
</div>
<?php endif; ?>
<ul id="<?php echo $post_type_name; ?>checklist" data-wp-lists="list:<?php echo $post_type_name; ?>" class="categorychecklist form-no-clear">
<?php
$args['walker'] = $walker;
if ( $post_type->has_archive ) {
$_nav_menu_placeholder = ( 0 > $_nav_menu_placeholder ) ? (int) $_nav_menu_placeholder - 1 : -1;
array_unshift(
$posts,
(object) array(
'ID' => 0,
'object_id' => $_nav_menu_placeholder,
'object' => $post_type_name,
'post_content' => '',
'post_excerpt' => '',
'post_title' => $post_type->labels->archives,
'post_type' => 'nav_menu_item',
'type' => 'post_type_archive',
'url' => get_post_type_archive_link( $post_type_name ),
)
);
}
/**
* Filters the posts displayed in the 'View All' tab of the current
* post type's menu items meta box.
*
* The dynamic portion of the hook name, `$post_type_name`, refers
* to the slug of the current post type.
*
* Possible hook names include:
*
* - `nav_menu_items_post`
* - `nav_menu_items_page`
*
* @since 3.2.0
* @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object.
*
* @see WP_Query::query()
*
* @param object[] $posts The posts for the current post type. Mostly `WP_Post` objects, but
* can also contain "fake" post objects to represent other menu items.
* @param array $args An array of `WP_Query` arguments.
* @param WP_Post_Type $post_type The current post type object for this menu item meta box.
*/
$posts = apply_filters( "nav_menu_items_{$post_type_name}", $posts, $args, $post_type );
$checkbox_items = walk_nav_menu_tree( array_map( 'wp_setup_nav_menu_item', $posts ), 0, (object) $args );
echo $checkbox_items;
?>
</ul>
<?php if ( ! empty( $page_links ) ) : ?>
<div class="add-menu-item-pagelinks">
<?php echo $page_links; ?>
</div>
<?php endif; ?>
</div><!-- /.tabs-panel -->
<p class="button-controls wp-clearfix" data-items-type="posttype-<?php echo esc_attr( $post_type_name ); ?>">
<span class="list-controls hide-if-no-js">
<input type="checkbox"<?php wp_nav_menu_disabled_check( $nav_menu_selected_id ); ?> id="<?php echo esc_attr( $tab_name ); ?>" class="select-all" />
<label for="<?php echo esc_attr( $tab_name ); ?>"><?php _e( 'Select All' ); ?></label>
</span>
<span class="add-to-menu">
<input type="submit"<?php wp_nav_menu_disabled_check( $nav_menu_selected_id ); ?> class="button submit-add-to-menu right" value="<?php esc_attr_e( 'Add to Menu' ); ?>" name="add-post-type-menu-item" id="<?php echo esc_attr( 'submit-posttype-' . $post_type_name ); ?>" />
<span class="spinner"></span>
</span>
</p>
</div><!-- /.posttypediv -->
<?php
}
```
[apply\_filters( "nav\_menu\_items\_{$post\_type\_name}", object[] $posts, array $args, WP\_Post\_Type $post\_type )](../hooks/nav_menu_items_post_type_name)
Filters the posts displayed in the ‘View All’ tab of the current post type’s menu items meta box.
[apply\_filters( "nav\_menu\_items\_{$post\_type\_name}\_recent", WP\_Post[] $most\_recent, array $args, array $box, array $recent\_args )](../hooks/nav_menu_items_post_type_name_recent)
Filters the posts displayed in the ‘Most Recent’ tab of the current post type’s menu items meta box.
| Uses | Description |
| --- | --- |
| [submit\_button()](submit_button) wp-admin/includes/template.php | Echoes a submit button, with provided text and appropriate class(es). |
| [get\_post\_type\_archive\_link()](get_post_type_archive_link) wp-includes/link-template.php | Retrieves the permalink for a post type archive. |
| [wp\_nav\_menu\_disabled\_check()](wp_nav_menu_disabled_check) wp-admin/includes/nav-menu.php | Check whether to disable the Menu Locations meta box submit button and inputs. |
| [is\_post\_type\_hierarchical()](is_post_type_hierarchical) wp-includes/post.php | Determines whether the post type is hierarchical. |
| [esc\_attr\_\_()](esc_attr__) wp-includes/l10n.php | Retrieves the translation of $text and escapes it for safe use in an attribute. |
| [esc\_attr\_e()](esc_attr_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in an attribute. |
| [get\_posts()](get_posts) wp-includes/post.php | Retrieves an array of the latest posts, or posts matching the given criteria. |
| [walk\_nav\_menu\_tree()](walk_nav_menu_tree) wp-includes/nav-menu-template.php | Retrieves the HTML list content for nav menu items. |
| [paginate\_links()](paginate_links) wp-includes/general-template.php | Retrieves paginated links for archive post pages. |
| [WP\_Query::\_\_construct()](../classes/wp_query/__construct) wp-includes/class-wp-query.php | Constructor. |
| [Walker\_Nav\_Menu\_Checklist::\_\_construct()](../classes/walker_nav_menu_checklist/__construct) wp-admin/includes/class-walker-nav-menu-checklist.php | |
| [remove\_query\_arg()](remove_query_arg) wp-includes/functions.php | Removes an item or items from a query string. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [get\_post\_type\_object()](get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [absint()](absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [home\_url()](home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [add\_query\_arg()](add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [\_e()](_e) wp-includes/l10n.php | Displays translated text. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress wp_download_language_pack( string $download ): string|false wp\_download\_language\_pack( string $download ): string|false
==============================================================
Download a language pack.
* [wp\_get\_available\_translations()](wp_get_available_translations)
`$download` string Required Language code to download. string|false Returns the language code if successfully downloaded (or already installed), or false on failure.
File: `wp-admin/includes/translation-install.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/translation-install.php/)
```
function wp_download_language_pack( $download ) {
// Check if the translation is already installed.
if ( in_array( $download, get_available_languages(), true ) ) {
return $download;
}
if ( ! wp_is_file_mod_allowed( 'download_language_pack' ) ) {
return false;
}
// Confirm the translation is one we can download.
$translations = wp_get_available_translations();
if ( ! $translations ) {
return false;
}
foreach ( $translations as $translation ) {
if ( $translation['language'] === $download ) {
$translation_to_load = true;
break;
}
}
if ( empty( $translation_to_load ) ) {
return false;
}
$translation = (object) $translation;
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
$skin = new Automatic_Upgrader_Skin;
$upgrader = new Language_Pack_Upgrader( $skin );
$translation->type = 'core';
$result = $upgrader->upgrade( $translation, array( 'clear_update_cache' => false ) );
if ( ! $result || is_wp_error( $result ) ) {
return false;
}
return $translation->language;
}
```
| Uses | Description |
| --- | --- |
| [wp\_is\_file\_mod\_allowed()](wp_is_file_mod_allowed) wp-includes/load.php | Determines whether file modifications are allowed. |
| [wp\_get\_available\_translations()](wp_get_available_translations) wp-admin/includes/translation-install.php | Get available translations from the WordPress.org API. |
| [get\_available\_languages()](get_available_languages) wp-includes/l10n.php | Gets all available languages based on the presence of \*.mo files in a given directory. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
| programming_docs |
wordpress get_the_archive_title(): string get\_the\_archive\_title(): string
==================================
Retrieves the archive title based on the queried object.
string Archive title.
File: `wp-includes/general-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/general-template.php/)
```
function get_the_archive_title() {
$title = __( 'Archives' );
$prefix = '';
if ( is_category() ) {
$title = single_cat_title( '', false );
$prefix = _x( 'Category:', 'category archive title prefix' );
} elseif ( is_tag() ) {
$title = single_tag_title( '', false );
$prefix = _x( 'Tag:', 'tag archive title prefix' );
} elseif ( is_author() ) {
$title = get_the_author();
$prefix = _x( 'Author:', 'author archive title prefix' );
} elseif ( is_year() ) {
$title = get_the_date( _x( 'Y', 'yearly archives date format' ) );
$prefix = _x( 'Year:', 'date archive title prefix' );
} elseif ( is_month() ) {
$title = get_the_date( _x( 'F Y', 'monthly archives date format' ) );
$prefix = _x( 'Month:', 'date archive title prefix' );
} elseif ( is_day() ) {
$title = get_the_date( _x( 'F j, Y', 'daily archives date format' ) );
$prefix = _x( 'Day:', 'date archive title prefix' );
} elseif ( is_tax( 'post_format' ) ) {
if ( is_tax( 'post_format', 'post-format-aside' ) ) {
$title = _x( 'Asides', 'post format archive title' );
} elseif ( is_tax( 'post_format', 'post-format-gallery' ) ) {
$title = _x( 'Galleries', 'post format archive title' );
} elseif ( is_tax( 'post_format', 'post-format-image' ) ) {
$title = _x( 'Images', 'post format archive title' );
} elseif ( is_tax( 'post_format', 'post-format-video' ) ) {
$title = _x( 'Videos', 'post format archive title' );
} elseif ( is_tax( 'post_format', 'post-format-quote' ) ) {
$title = _x( 'Quotes', 'post format archive title' );
} elseif ( is_tax( 'post_format', 'post-format-link' ) ) {
$title = _x( 'Links', 'post format archive title' );
} elseif ( is_tax( 'post_format', 'post-format-status' ) ) {
$title = _x( 'Statuses', 'post format archive title' );
} elseif ( is_tax( 'post_format', 'post-format-audio' ) ) {
$title = _x( 'Audio', 'post format archive title' );
} elseif ( is_tax( 'post_format', 'post-format-chat' ) ) {
$title = _x( 'Chats', 'post format archive title' );
}
} elseif ( is_post_type_archive() ) {
$title = post_type_archive_title( '', false );
$prefix = _x( 'Archives:', 'post type archive title prefix' );
} elseif ( is_tax() ) {
$queried_object = get_queried_object();
if ( $queried_object ) {
$tax = get_taxonomy( $queried_object->taxonomy );
$title = single_term_title( '', false );
$prefix = sprintf(
/* translators: %s: Taxonomy singular name. */
_x( '%s:', 'taxonomy term archive title prefix' ),
$tax->labels->singular_name
);
}
}
$original_title = $title;
/**
* Filters the archive title prefix.
*
* @since 5.5.0
*
* @param string $prefix Archive title prefix.
*/
$prefix = apply_filters( 'get_the_archive_title_prefix', $prefix );
if ( $prefix ) {
$title = sprintf(
/* translators: 1: Title prefix. 2: Title. */
_x( '%1$s %2$s', 'archive title' ),
$prefix,
'<span>' . $title . '</span>'
);
}
/**
* Filters the archive title.
*
* @since 4.1.0
* @since 5.5.0 Added the `$prefix` and `$original_title` parameters.
*
* @param string $title Archive title to be displayed.
* @param string $original_title Archive title without prefix.
* @param string $prefix Archive title prefix.
*/
return apply_filters( 'get_the_archive_title', $title, $original_title, $prefix );
}
```
[apply\_filters( 'get\_the\_archive\_title', string $title, string $original\_title, string $prefix )](../hooks/get_the_archive_title)
Filters the archive title.
[apply\_filters( 'get\_the\_archive\_title\_prefix', string $prefix )](../hooks/get_the_archive_title_prefix)
Filters the archive title prefix.
| Uses | Description |
| --- | --- |
| [get\_the\_author()](get_the_author) wp-includes/author-template.php | Retrieves the author of the current post. |
| [is\_author()](is_author) wp-includes/query.php | Determines whether the query is for an existing author archive page. |
| [get\_queried\_object()](get_queried_object) wp-includes/query.php | Retrieves the currently queried object. |
| [is\_post\_type\_archive()](is_post_type_archive) wp-includes/query.php | Determines whether the query is for an existing post type archive page. |
| [is\_tax()](is_tax) wp-includes/query.php | Determines whether the query is for an existing custom taxonomy archive page. |
| [is\_day()](is_day) wp-includes/query.php | Determines whether the query is for an existing day archive. |
| [is\_month()](is_month) wp-includes/query.php | Determines whether the query is for an existing month archive. |
| [is\_tag()](is_tag) wp-includes/query.php | Determines whether the query is for an existing tag archive page. |
| [is\_category()](is_category) wp-includes/query.php | Determines whether the query is for an existing category archive page. |
| [is\_year()](is_year) wp-includes/query.php | Determines whether the query is for an existing year archive. |
| [single\_term\_title()](single_term_title) wp-includes/general-template.php | Displays or retrieves page title for taxonomy term archive. |
| [post\_type\_archive\_title()](post_type_archive_title) wp-includes/general-template.php | Displays or retrieves title for a post type archive. |
| [single\_tag\_title()](single_tag_title) wp-includes/general-template.php | Displays or retrieves page title for tag post archive. |
| [single\_cat\_title()](single_cat_title) wp-includes/general-template.php | Displays or retrieves page title for category archive. |
| [get\_the\_date()](get_the_date) wp-includes/general-template.php | Retrieves the date on which the post was written. |
| [\_x()](_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [get\_taxonomy()](get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [the\_archive\_title()](the_archive_title) wp-includes/general-template.php | Displays the archive title based on the queried object. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | The title part is wrapped in a `<span>` element. |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress get_broken_themes(): array get\_broken\_themes(): array
============================
This function has been deprecated. Use [wp\_get\_themes()](wp_get_themes) instead.
Retrieves a list of broken themes.
* [wp\_get\_themes()](wp_get_themes)
array
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
function get_broken_themes() {
_deprecated_function( __FUNCTION__, '3.4.0', "wp_get_themes( array( 'errors' => true )" );
$themes = wp_get_themes( array( 'errors' => true ) );
$broken = array();
foreach ( $themes as $theme ) {
$name = $theme->get('Name');
$broken[ $name ] = array(
'Name' => $name,
'Title' => $name,
'Description' => $theme->errors()->get_error_message(),
);
}
return $broken;
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_themes()](wp_get_themes) wp-includes/theme.php | Returns an array of [WP\_Theme](../classes/wp_theme) objects based on the arguments. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Use [wp\_get\_themes()](wp_get_themes) |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress _unzip_file_ziparchive( string $file, string $to, string[] $needed_dirs = array() ): true|WP_Error \_unzip\_file\_ziparchive( string $file, string $to, string[] $needed\_dirs = array() ): true|WP\_Error
=======================================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness. Use [unzip\_file()](unzip_file) instead.
Attempts to unzip an archive using the ZipArchive class.
This function should not be called directly, use `unzip_file()` instead.
Assumes that [WP\_Filesystem()](wp_filesystem) has already been called and set up.
* [unzip\_file()](unzip_file)
`$file` string Required Full path and filename of ZIP archive. `$to` string Required Full path on the filesystem to extract archive to. `$needed_dirs` string[] Optional A partial list of required folders needed to be created. Default: `array()`
true|[WP\_Error](../classes/wp_error) True on success, [WP\_Error](../classes/wp_error) on failure.
File: `wp-admin/includes/file.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/file.php/)
```
function _unzip_file_ziparchive( $file, $to, $needed_dirs = array() ) {
global $wp_filesystem;
$z = new ZipArchive();
$zopen = $z->open( $file, ZIPARCHIVE::CHECKCONS );
if ( true !== $zopen ) {
return new WP_Error( 'incompatible_archive', __( 'Incompatible Archive.' ), array( 'ziparchive_error' => $zopen ) );
}
$uncompressed_size = 0;
for ( $i = 0; $i < $z->numFiles; $i++ ) {
$info = $z->statIndex( $i );
if ( ! $info ) {
return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) );
}
if ( '__MACOSX/' === substr( $info['name'], 0, 9 ) ) { // Skip the OS X-created __MACOSX directory.
continue;
}
// Don't extract invalid files:
if ( 0 !== validate_file( $info['name'] ) ) {
continue;
}
$uncompressed_size += $info['size'];
$dirname = dirname( $info['name'] );
if ( '/' === substr( $info['name'], -1 ) ) {
// Directory.
$needed_dirs[] = $to . untrailingslashit( $info['name'] );
} elseif ( '.' !== $dirname ) {
// Path to a file.
$needed_dirs[] = $to . untrailingslashit( $dirname );
}
}
/*
* disk_free_space() could return false. Assume that any falsey value is an error.
* A disk that has zero free bytes has bigger problems.
* Require we have enough space to unzip the file and copy its contents, with a 10% buffer.
*/
if ( wp_doing_cron() ) {
$available_space = function_exists( 'disk_free_space' ) ? @disk_free_space( WP_CONTENT_DIR ) : false;
if ( $available_space && ( $uncompressed_size * 2.1 ) > $available_space ) {
return new WP_Error(
'disk_full_unzip_file',
__( 'Could not copy files. You may have run out of disk space.' ),
compact( 'uncompressed_size', 'available_space' )
);
}
}
$needed_dirs = array_unique( $needed_dirs );
foreach ( $needed_dirs as $dir ) {
// Check the parent folders of the folders all exist within the creation array.
if ( untrailingslashit( $to ) === $dir ) { // Skip over the working directory, we know this exists (or will exist).
continue;
}
if ( strpos( $dir, $to ) === false ) { // If the directory is not within the working directory, skip it.
continue;
}
$parent_folder = dirname( $dir );
while ( ! empty( $parent_folder )
&& untrailingslashit( $to ) !== $parent_folder
&& ! in_array( $parent_folder, $needed_dirs, true )
) {
$needed_dirs[] = $parent_folder;
$parent_folder = dirname( $parent_folder );
}
}
asort( $needed_dirs );
// Create those directories if need be:
foreach ( $needed_dirs as $_dir ) {
// Only check to see if the Dir exists upon creation failure. Less I/O this way.
if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) ) {
return new WP_Error( 'mkdir_failed_ziparchive', __( 'Could not create directory.' ), $_dir );
}
}
unset( $needed_dirs );
for ( $i = 0; $i < $z->numFiles; $i++ ) {
$info = $z->statIndex( $i );
if ( ! $info ) {
return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) );
}
if ( '/' === substr( $info['name'], -1 ) ) { // Directory.
continue;
}
if ( '__MACOSX/' === substr( $info['name'], 0, 9 ) ) { // Don't extract the OS X-created __MACOSX directory files.
continue;
}
// Don't extract invalid files:
if ( 0 !== validate_file( $info['name'] ) ) {
continue;
}
$contents = $z->getFromIndex( $i );
if ( false === $contents ) {
return new WP_Error( 'extract_failed_ziparchive', __( 'Could not extract file from archive.' ), $info['name'] );
}
if ( ! $wp_filesystem->put_contents( $to . $info['name'], $contents, FS_CHMOD_FILE ) ) {
return new WP_Error( 'copy_failed_ziparchive', __( 'Could not copy file.' ), $info['name'] );
}
}
$z->close();
return true;
}
```
| Uses | Description |
| --- | --- |
| [wp\_doing\_cron()](wp_doing_cron) wp-includes/load.php | Determines whether the current request is a WordPress cron request. |
| [untrailingslashit()](untrailingslashit) wp-includes/formatting.php | Removes trailing forward slashes and backslashes if they exist. |
| [validate\_file()](validate_file) wp-includes/functions.php | Validates a file name and path against an allowed set of rules. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../classes/wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [unzip\_file()](unzip_file) wp-admin/includes/file.php | Unzips a specified ZIP file to a location on the filesystem via the WordPress Filesystem Abstraction. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress delete_site_transient( string $transient ): bool delete\_site\_transient( string $transient ): bool
==================================================
Deletes a site transient.
`$transient` string Required Transient name. Expected to not be SQL-escaped. bool True if the transient was deleted, false otherwise.
File: `wp-includes/option.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/option.php/)
```
function delete_site_transient( $transient ) {
/**
* Fires immediately before a specific site transient is deleted.
*
* The dynamic portion of the hook name, `$transient`, refers to the transient name.
*
* @since 3.0.0
*
* @param string $transient Transient name.
*/
do_action( "delete_site_transient_{$transient}", $transient );
if ( wp_using_ext_object_cache() || wp_installing() ) {
$result = wp_cache_delete( $transient, 'site-transient' );
} else {
$option_timeout = '_site_transient_timeout_' . $transient;
$option = '_site_transient_' . $transient;
$result = delete_site_option( $option );
if ( $result ) {
delete_site_option( $option_timeout );
}
}
if ( $result ) {
/**
* Fires after a transient is deleted.
*
* @since 3.0.0
*
* @param string $transient Deleted transient name.
*/
do_action( 'deleted_site_transient', $transient );
}
return $result;
}
```
[do\_action( 'deleted\_site\_transient', string $transient )](../hooks/deleted_site_transient)
Fires after a transient is deleted.
[do\_action( "delete\_site\_transient\_{$transient}", string $transient )](../hooks/delete_site_transient_transient)
Fires immediately before a specific site transient is deleted.
| Uses | Description |
| --- | --- |
| [wp\_installing()](wp_installing) wp-includes/load.php | Check or set whether WordPress is in “installation” mode. |
| [wp\_cache\_delete()](wp_cache_delete) wp-includes/cache.php | Removes the cache contents matching key and group. |
| [wp\_using\_ext\_object\_cache()](wp_using_ext_object_cache) wp-includes/load.php | Toggle `$_wp_using_ext_object_cache` on and off without directly touching global. |
| [delete\_site\_option()](delete_site_option) wp-includes/option.php | Removes a option by name for the current network. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [wp\_clean\_update\_cache()](wp_clean_update_cache) wp-includes/update.php | Clears existing update caches for plugins, themes, and core. |
| [Core\_Upgrader::upgrade()](../classes/core_upgrader/upgrade) wp-admin/includes/class-core-upgrader.php | Upgrade WordPress core. |
| [delete\_theme()](delete_theme) wp-admin/includes/theme.php | Removes a theme. |
| [install\_plugin\_install\_status()](install_plugin_install_status) wp-admin/includes/plugin-install.php | Determines the status we can perform on a plugin. |
| [wp\_clean\_plugins\_cache()](wp_clean_plugins_cache) wp-admin/includes/plugin.php | Clears the plugins cache used by [get\_plugins()](get_plugins) and by default, the plugin updates cache. |
| [update\_core()](update_core) wp-admin/includes/update-core.php | Upgrades the core of WordPress. |
| [wp\_clean\_themes\_cache()](wp_clean_themes_cache) wp-includes/theme.php | Clears the cache held by [get\_theme\_roots()](get_theme_roots) and [WP\_Theme](../classes/wp_theme). |
| Version | Description |
| --- | --- |
| [2.9.0](https://developer.wordpress.org/reference/since/2.9.0/) | Introduced. |
wordpress link_advanced_meta_box( object $link ) link\_advanced\_meta\_box( object $link )
=========================================
Displays advanced link options form fields.
`$link` object Required Current link object. File: `wp-admin/includes/meta-boxes.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/meta-boxes.php/)
```
function link_advanced_meta_box( $link ) {
?>
<table class="links-table" cellpadding="0">
<tr>
<th scope="row"><label for="link_image"><?php _e( 'Image Address' ); ?></label></th>
<td><input type="text" name="link_image" class="code" id="link_image" maxlength="255" value="<?php echo ( isset( $link->link_image ) ? esc_attr( $link->link_image ) : '' ); ?>" /></td>
</tr>
<tr>
<th scope="row"><label for="rss_uri"><?php _e( 'RSS Address' ); ?></label></th>
<td><input name="link_rss" class="code" type="text" id="rss_uri" maxlength="255" value="<?php echo ( isset( $link->link_rss ) ? esc_attr( $link->link_rss ) : '' ); ?>" /></td>
</tr>
<tr>
<th scope="row"><label for="link_notes"><?php _e( 'Notes' ); ?></label></th>
<td><textarea name="link_notes" id="link_notes" rows="10"><?php echo ( isset( $link->link_notes ) ? $link->link_notes : '' ); // textarea_escaped ?></textarea></td>
</tr>
<tr>
<th scope="row"><label for="link_rating"><?php _e( 'Rating' ); ?></label></th>
<td><select name="link_rating" id="link_rating" size="1">
<?php
for ( $rating = 0; $rating <= 10; $rating++ ) {
echo '<option value="' . $rating . '"';
if ( isset( $link->link_rating ) && $link->link_rating == $rating ) {
echo ' selected="selected"';
}
echo '>' . $rating . '</option>';
}
?>
</select> <?php _e( '(Leave at 0 for no rating.)' ); ?>
</td>
</tr>
</table>
<?php
}
```
| Uses | Description |
| --- | --- |
| [\_e()](_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
| programming_docs |
wordpress sanitize_comment_cookies() sanitize\_comment\_cookies()
============================
Sanitizes the cookies sent to the user already.
Will only do anything if the cookies have already been created for the user.
Mostly used after cookies had been sent to use elsewhere.
File: `wp-includes/comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/comment.php/)
```
function sanitize_comment_cookies() {
if ( isset( $_COOKIE[ 'comment_author_' . COOKIEHASH ] ) ) {
/**
* Filters the comment author's name cookie before it is set.
*
* When this filter hook is evaluated in wp_filter_comment(),
* the comment author's name string is passed.
*
* @since 1.5.0
*
* @param string $author_cookie The comment author name cookie.
*/
$comment_author = apply_filters( 'pre_comment_author_name', $_COOKIE[ 'comment_author_' . COOKIEHASH ] );
$comment_author = wp_unslash( $comment_author );
$comment_author = esc_attr( $comment_author );
$_COOKIE[ 'comment_author_' . COOKIEHASH ] = $comment_author;
}
if ( isset( $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] ) ) {
/**
* Filters the comment author's email cookie before it is set.
*
* When this filter hook is evaluated in wp_filter_comment(),
* the comment author's email string is passed.
*
* @since 1.5.0
*
* @param string $author_email_cookie The comment author email cookie.
*/
$comment_author_email = apply_filters( 'pre_comment_author_email', $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] );
$comment_author_email = wp_unslash( $comment_author_email );
$comment_author_email = esc_attr( $comment_author_email );
$_COOKIE[ 'comment_author_email_' . COOKIEHASH ] = $comment_author_email;
}
if ( isset( $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] ) ) {
/**
* Filters the comment author's URL cookie before it is set.
*
* When this filter hook is evaluated in wp_filter_comment(),
* the comment author's URL string is passed.
*
* @since 1.5.0
*
* @param string $author_url_cookie The comment author URL cookie.
*/
$comment_author_url = apply_filters( 'pre_comment_author_url', $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] );
$comment_author_url = wp_unslash( $comment_author_url );
$_COOKIE[ 'comment_author_url_' . COOKIEHASH ] = $comment_author_url;
}
}
```
[apply\_filters( 'pre\_comment\_author\_email', string $author\_email\_cookie )](../hooks/pre_comment_author_email)
Filters the comment author’s email cookie before it is set.
[apply\_filters( 'pre\_comment\_author\_name', string $author\_cookie )](../hooks/pre_comment_author_name)
Filters the comment author’s name cookie before it is set.
[apply\_filters( 'pre\_comment\_author\_url', string $author\_url\_cookie )](../hooks/pre_comment_author_url)
Filters the comment author’s URL cookie before it is set.
| Uses | Description |
| --- | --- |
| [wp\_unslash()](wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [2.0.4](https://developer.wordpress.org/reference/since/2.0.4/) | Introduced. |
wordpress wp_parse_url( string $url, int $component = -1 ): mixed wp\_parse\_url( string $url, int $component = -1 ): mixed
=========================================================
A wrapper for PHP’s parse\_url() function that handles consistency in the return values across PHP versions.
PHP 5.4.7 expanded parse\_url()’s ability to handle non-absolute URLs, including schemeless and relative URLs with "://" in the path. This function works around those limitations providing a standard output on PHP 5.2~5.4+.
Secondly, across various PHP versions, schemeless URLs containing a ":" in the query are being handled inconsistently. This function works around those differences as well.
`$url` string Required The URL to parse. `$component` int Optional The specific component to retrieve. Use one of the PHP predefined constants to specify which one.
Defaults to -1 (= return all parts as an array). Default: `-1`
mixed False on parse failure; Array of URL components on success; When a specific component has been requested: null if the component doesn't exist in the given URL; a string or - in the case of PHP\_URL\_PORT - integer when it does. See parse\_url()'s return values.
File: `wp-includes/http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/http.php/)
```
function wp_parse_url( $url, $component = -1 ) {
$to_unset = array();
$url = (string) $url;
if ( '//' === substr( $url, 0, 2 ) ) {
$to_unset[] = 'scheme';
$url = 'placeholder:' . $url;
} elseif ( '/' === substr( $url, 0, 1 ) ) {
$to_unset[] = 'scheme';
$to_unset[] = 'host';
$url = 'placeholder://placeholder' . $url;
}
$parts = parse_url( $url );
if ( false === $parts ) {
// Parsing failure.
return $parts;
}
// Remove the placeholder values.
foreach ( $to_unset as $key ) {
unset( $parts[ $key ] );
}
return _get_component_from_parsed_url_array( $parts, $component );
}
```
| Uses | Description |
| --- | --- |
| [\_get\_component\_from\_parsed\_url\_array()](_get_component_from_parsed_url_array) wp-includes/http.php | Retrieve a specific component from a parsed URL array. |
| Used By | Description |
| --- | --- |
| [wp\_cron\_conditionally\_prevent\_sslverify()](wp_cron_conditionally_prevent_sslverify) wp-includes/https-detection.php | Disables SSL verification if the ‘cron\_request’ arguments include an HTTPS URL. |
| [wp\_is\_home\_url\_using\_https()](wp_is_home_url_using_https) wp-includes/https-detection.php | Checks whether the current site URL is using HTTPS. |
| [wp\_is\_site\_url\_using\_https()](wp_is_site_url_using_https) wp-includes/https-detection.php | Checks whether the current site’s URL where WordPress is stored is using HTTPS. |
| [wp\_should\_replace\_insecure\_home\_url()](wp_should_replace_insecure_home_url) wp-includes/https-migration.php | Checks whether WordPress should replace old HTTP URLs to the site with their HTTPS counterpart. |
| [WP\_REST\_Server::serve\_batch\_request\_v1()](../classes/wp_rest_server/serve_batch_request_v1) wp-includes/rest-api/class-wp-rest-server.php | Serves the batch/v1 request. |
| [wp\_is\_authorize\_application\_password\_request\_valid()](wp_is_authorize_application_password_request_valid) wp-admin/includes/user.php | Checks if the Authorize Application Password request is valid. |
| [wp\_rel\_callback()](wp_rel_callback) wp-includes/formatting.php | Callback to add a rel attribute to HTML A element. |
| [load\_script\_textdomain()](load_script_textdomain) wp-includes/l10n.php | Loads the script translated strings. |
| [get\_oembed\_response\_data\_for\_url()](get_oembed_response_data_for_url) wp-includes/embed.php | Retrieves the oEmbed response data for a given URL. |
| [WP\_Customize\_Manager::is\_cross\_domain()](../classes/wp_customize_manager/is_cross_domain) wp-includes/class-wp-customize-manager.php | Determines whether the admin and the frontend are on different domains. |
| [WP\_Customize\_Manager::add\_state\_query\_params()](../classes/wp_customize_manager/add_state_query_params) wp-includes/class-wp-customize-manager.php | Adds customize state query params to a given URL if preview is allowed. |
| [wp\_resource\_hints()](wp_resource_hints) wp-includes/general-template.php | Prints resource hints to browsers for pre-fetching, pre-rendering and pre-connecting to web sites. |
| [wp\_dependencies\_unique\_hosts()](wp_dependencies_unique_hosts) wp-includes/general-template.php | Retrieves a list of unique hosts of all enqueued scripts and styles. |
| [strip\_fragment\_from\_url()](strip_fragment_from_url) wp-includes/canonical.php | Strips the #fragment from a URL, if one is present. |
| [WP\_Http::parse\_url()](../classes/wp_http/parse_url) wp-includes/class-wp-http.php | Used as a wrapper for PHP’s parse\_url() function that handles edgecases in < PHP 5.4.7. |
| [WP\_Customize\_Manager::customize\_preview\_settings()](../classes/wp_customize_manager/customize_preview_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for preview frame. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [wp\_notify\_postauthor()](wp_notify_postauthor) wp-includes/pluggable.php | Notifies an author (and/or others) of a comment/trackback/pingback on a post. |
| [wp\_mail()](wp_mail) wp-includes/pluggable.php | Sends an email, similar to PHP’s mail function. |
| [WP\_Http::make\_absolute\_url()](../classes/wp_http/make_absolute_url) wp-includes/class-wp-http.php | Converts a relative URL to an absolute URL relative to a given URL. |
| [wp\_update\_plugins()](wp_update_plugins) wp-includes/update.php | Checks for available updates to plugins based on the latest versions hosted on WordPress.org. |
| [wp\_update\_themes()](wp_update_themes) wp-includes/update.php | Checks for available updates to themes based on the latest versions hosted on WordPress.org. |
| [wp\_video\_shortcode()](wp_video_shortcode) wp-includes/media.php | Builds the Video shortcode output. |
| [wpmu\_welcome\_user\_notification()](wpmu_welcome_user_notification) wp-includes/ms-functions.php | Notifies a user that their account activation has been successful. |
| [wpmu\_welcome\_notification()](wpmu_welcome_notification) wp-includes/ms-functions.php | Notifies the site administrator that their site activation was successful. |
| [wpmu\_signup\_blog\_notification()](wpmu_signup_blog_notification) wp-includes/ms-functions.php | Sends a confirmation request email to a user when they sign up for a new site. The new site will not become active until the confirmation link is clicked. |
| [wpmu\_signup\_user\_notification()](wpmu_signup_user_notification) wp-includes/ms-functions.php | Sends a confirmation request email to a user when they sign up for a new user account (without signing up for a site at the same time). The user account will not become active until the confirmation link is clicked. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | The `$component` parameter was added for parity with PHP's `parse_url()`. |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress get_image_tag( int $id, string $alt, string $title, string $align, string|int[] $size = 'medium' ): string get\_image\_tag( int $id, string $alt, string $title, string $align, string|int[] $size = 'medium' ): string
============================================================================================================
Gets an img tag for an image attachment, scaling it down if requested.
The [‘get\_image\_tag\_class’](../hooks/get_image_tag_class) filter allows for changing the class name for the image without having to use regular expressions on the HTML content. The parameters are: what WordPress will use for the class, the Attachment ID, image align value, and the size the image should be.
The second filter, [‘get\_image\_tag’](../hooks/get_image_tag), has the HTML content, which can then be further manipulated by a plugin to change all attribute values and even HTML content.
`$id` int Required Attachment ID. `$alt` string Required Image description for the alt attribute. `$title` string Required Image description for the title attribute. `$align` string Required Part of the class name for aligning the image. `$size` string|int[] Optional Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order). Default `'medium'`. Default: `'medium'`
string HTML IMG element for given image attachment?
File: `wp-includes/media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/media.php/)
```
function get_image_tag( $id, $alt, $title, $align, $size = 'medium' ) {
list( $img_src, $width, $height ) = image_downsize( $id, $size );
$hwstring = image_hwstring( $width, $height );
$title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
$size_class = is_array( $size ) ? implode( 'x', $size ) : $size;
$class = 'align' . esc_attr( $align ) . ' size-' . esc_attr( $size_class ) . ' wp-image-' . $id;
/**
* Filters the value of the attachment's image tag class attribute.
*
* @since 2.6.0
*
* @param string $class CSS class name or space-separated list of classes.
* @param int $id Attachment ID.
* @param string $align Part of the class name for aligning the image.
* @param string|int[] $size Requested image size. Can be any registered image size name, or
* an array of width and height values in pixels (in that order).
*/
$class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
$html = '<img src="' . esc_url( $img_src ) . '" alt="' . esc_attr( $alt ) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
/**
* Filters the HTML content for the image tag.
*
* @since 2.6.0
*
* @param string $html HTML content for the image.
* @param int $id Attachment ID.
* @param string $alt Image description for the alt attribute.
* @param string $title Image description for the title attribute.
* @param string $align Part of the class name for aligning the image.
* @param string|int[] $size Requested image size. Can be any registered image size name, or
* an array of width and height values in pixels (in that order).
*/
return apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
}
```
[apply\_filters( 'get\_image\_tag', string $html, int $id, string $alt, string $title, string $align, string|int[] $size )](../hooks/get_image_tag)
Filters the HTML content for the image tag.
[apply\_filters( 'get\_image\_tag\_class', string $class, int $id, string $align, string|int[] $size )](../hooks/get_image_tag_class)
Filters the value of the attachment’s image tag class attribute.
| Uses | Description |
| --- | --- |
| [image\_downsize()](image_downsize) wp-includes/media.php | Scales an image to fit a particular size (such as ‘thumb’ or ‘medium’). |
| [image\_hwstring()](image_hwstring) wp-includes/media.php | Retrieves width and height attributes using given width and height values. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [get\_image\_send\_to\_editor()](get_image_send_to_editor) wp-admin/includes/media.php | Retrieves the image HTML to send to the editor. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress wp_is_xml_request(): bool wp\_is\_xml\_request(): bool
============================
Checks whether current request is an XML request, or is expecting an XML response.
bool True if `Accepts` or `Content-Type` headers contain `text/xml` or one of the related MIME types. False otherwise.
File: `wp-includes/load.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/load.php/)
```
function wp_is_xml_request() {
$accepted = array(
'text/xml',
'application/rss+xml',
'application/atom+xml',
'application/rdf+xml',
'text/xml+oembed',
'application/xml+oembed',
);
if ( isset( $_SERVER['HTTP_ACCEPT'] ) ) {
foreach ( $accepted as $type ) {
if ( false !== strpos( $_SERVER['HTTP_ACCEPT'], $type ) ) {
return true;
}
}
}
if ( isset( $_SERVER['CONTENT_TYPE'] ) && in_array( $_SERVER['CONTENT_TYPE'], $accepted, true ) ) {
return true;
}
return false;
}
```
| Used By | Description |
| --- | --- |
| [wp\_die()](wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress wp_sanitize_redirect( string $location ): string wp\_sanitize\_redirect( string $location ): string
==================================================
Sanitizes a URL for use in a redirect.
`$location` string Required The path to redirect to. string Redirect-sanitized URL.
File: `wp-includes/pluggable.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pluggable.php/)
```
function wp_sanitize_redirect( $location ) {
// Encode spaces.
$location = str_replace( ' ', '%20', $location );
$regex = '/
(
(?: [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
| \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2
| [\xE1-\xEC][\x80-\xBF]{2}
| \xED[\x80-\x9F][\x80-\xBF]
| [\xEE-\xEF][\x80-\xBF]{2}
| \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3
| [\xF1-\xF3][\x80-\xBF]{3}
| \xF4[\x80-\x8F][\x80-\xBF]{2}
){1,40} # ...one or more times
)/x';
$location = preg_replace_callback( $regex, '_wp_sanitize_utf8_in_redirect', $location );
$location = preg_replace( '|[^a-z0-9-~+_.?#=&;,/:%!*\[\]()@]|i', '', $location );
$location = wp_kses_no_null( $location );
// Remove %0D and %0A from location.
$strip = array( '%0d', '%0a', '%0D', '%0A' );
return _deep_replace( $strip, $location );
}
```
| Uses | Description |
| --- | --- |
| [\_deep\_replace()](_deep_replace) wp-includes/formatting.php | Performs a deep string replace operation to ensure the values in $search are no longer present. |
| [wp\_kses\_no\_null()](wp_kses_no_null) wp-includes/kses.php | Removes any invalid control characters in a text string. |
| Used By | Description |
| --- | --- |
| [wp\_redirect()](wp_redirect) wp-includes/pluggable.php | Redirects to another page. |
| [wp\_safe\_redirect()](wp_safe_redirect) wp-includes/pluggable.php | Performs a safe (local) redirect, using [wp\_redirect()](wp_redirect) . |
| [wp\_validate\_redirect()](wp_validate_redirect) wp-includes/pluggable.php | Validates a URL for use in a redirect. |
| Version | Description |
| --- | --- |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
wordpress default_password_nag_edit_user( int $user_ID, WP_User $old_data ) default\_password\_nag\_edit\_user( int $user\_ID, WP\_User $old\_data )
========================================================================
`$user_ID` int Required `$old_data` [WP\_User](../classes/wp_user) Required File: `wp-admin/includes/user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/user.php/)
```
function default_password_nag_edit_user( $user_ID, $old_data ) {
// Short-circuit it.
if ( ! get_user_option( 'default_password_nag', $user_ID ) ) {
return;
}
$new_data = get_userdata( $user_ID );
// Remove the nag if the password has been changed.
if ( $new_data->user_pass != $old_data->user_pass ) {
delete_user_setting( 'default_password_nag' );
update_user_meta( $user_ID, 'default_password_nag', false );
}
}
```
| Uses | Description |
| --- | --- |
| [update\_user\_meta()](update_user_meta) wp-includes/user.php | Updates user meta field based on user ID. |
| [delete\_user\_setting()](delete_user_setting) wp-includes/option.php | Deletes user interface settings. |
| [get\_user\_option()](get_user_option) wp-includes/user.php | Retrieves user option that can be either per Site or per Network. |
| [get\_userdata()](get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
| programming_docs |
wordpress maybe_create_table( string $table_name, string $create_ddl ): bool maybe\_create\_table( string $table\_name, string $create\_ddl ): bool
======================================================================
Creates a table in the database, if it doesn’t already exist.
This method checks for an existing database and creates a new one if it’s not already present. It doesn’t rely on MySQL’s "IF NOT EXISTS" statement, but chooses to query all tables first and then run the SQL statement creating the table.
`$table_name` string Required Database table name. `$create_ddl` string Required SQL statement to create table. bool True on success or if the table already exists. False on failure.
File: `wp-admin/includes/upgrade.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/upgrade.php/)
```
function maybe_create_table( $table_name, $create_ddl ) {
global $wpdb;
$query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table_name ) );
if ( $wpdb->get_var( $query ) === $table_name ) {
return true;
}
// Didn't find it, so try to create it.
$wpdb->query( $create_ddl );
// We cannot directly tell that whether this succeeded!
if ( $wpdb->get_var( $query ) === $table_name ) {
return true;
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::esc\_like()](../classes/wpdb/esc_like) wp-includes/class-wpdb.php | First half of escaping for `LIKE` special characters `%` and `_` before preparing for SQL. |
| [wpdb::get\_col()](../classes/wpdb/get_col) wp-includes/class-wpdb.php | Retrieves one column from the database. |
| [wpdb::query()](../classes/wpdb/query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| [wpdb::get\_var()](../classes/wpdb/get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| [wpdb::prepare()](../classes/wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Version | Description |
| --- | --- |
| [1.0.0](https://developer.wordpress.org/reference/since/1.0.0/) | Introduced. |
wordpress wp_ajax_delete_link() wp\_ajax\_delete\_link()
========================
Ajax handler for deleting a link.
File: `wp-admin/includes/ajax-actions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/ajax-actions.php/)
```
function wp_ajax_delete_link() {
$id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0;
check_ajax_referer( "delete-bookmark_$id" );
if ( ! current_user_can( 'manage_links' ) ) {
wp_die( -1 );
}
$link = get_bookmark( $id );
if ( ! $link || is_wp_error( $link ) ) {
wp_die( 1 );
}
if ( wp_delete_link( $id ) ) {
wp_die( 1 );
} else {
wp_die( 0 );
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_delete\_link()](wp_delete_link) wp-admin/includes/bookmark.php | Deletes a specified link from the database. |
| [get\_bookmark()](get_bookmark) wp-includes/bookmark.php | Retrieves bookmark data. |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [check\_ajax\_referer()](check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [wp\_die()](wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress wp_delete_attachment_files( int $post_id, array $meta, array $backup_sizes, string $file ): bool wp\_delete\_attachment\_files( int $post\_id, array $meta, array $backup\_sizes, string $file ): bool
=====================================================================================================
Deletes all files that belong to the given attachment.
`$post_id` int Required Attachment ID. `$meta` array Required The attachment's meta data. `$backup_sizes` array Required The meta data for the attachment's backup images. `$file` string Required Absolute path to the attachment's file. bool True on success, false on failure.
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function wp_delete_attachment_files( $post_id, $meta, $backup_sizes, $file ) {
global $wpdb;
$uploadpath = wp_get_upload_dir();
$deleted = true;
if ( ! empty( $meta['thumb'] ) ) {
// Don't delete the thumb if another attachment uses it.
if ( ! $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%' . $wpdb->esc_like( $meta['thumb'] ) . '%', $post_id ) ) ) {
$thumbfile = str_replace( wp_basename( $file ), $meta['thumb'], $file );
if ( ! empty( $thumbfile ) ) {
$thumbfile = path_join( $uploadpath['basedir'], $thumbfile );
$thumbdir = path_join( $uploadpath['basedir'], dirname( $file ) );
if ( ! wp_delete_file_from_directory( $thumbfile, $thumbdir ) ) {
$deleted = false;
}
}
}
}
// Remove intermediate and backup images if there are any.
if ( isset( $meta['sizes'] ) && is_array( $meta['sizes'] ) ) {
$intermediate_dir = path_join( $uploadpath['basedir'], dirname( $file ) );
foreach ( $meta['sizes'] as $size => $sizeinfo ) {
$intermediate_file = str_replace( wp_basename( $file ), $sizeinfo['file'], $file );
if ( ! empty( $intermediate_file ) ) {
$intermediate_file = path_join( $uploadpath['basedir'], $intermediate_file );
if ( ! wp_delete_file_from_directory( $intermediate_file, $intermediate_dir ) ) {
$deleted = false;
}
}
}
}
if ( ! empty( $meta['original_image'] ) ) {
if ( empty( $intermediate_dir ) ) {
$intermediate_dir = path_join( $uploadpath['basedir'], dirname( $file ) );
}
$original_image = str_replace( wp_basename( $file ), $meta['original_image'], $file );
if ( ! empty( $original_image ) ) {
$original_image = path_join( $uploadpath['basedir'], $original_image );
if ( ! wp_delete_file_from_directory( $original_image, $intermediate_dir ) ) {
$deleted = false;
}
}
}
if ( is_array( $backup_sizes ) ) {
$del_dir = path_join( $uploadpath['basedir'], dirname( $meta['file'] ) );
foreach ( $backup_sizes as $size ) {
$del_file = path_join( dirname( $meta['file'] ), $size['file'] );
if ( ! empty( $del_file ) ) {
$del_file = path_join( $uploadpath['basedir'], $del_file );
if ( ! wp_delete_file_from_directory( $del_file, $del_dir ) ) {
$deleted = false;
}
}
}
}
if ( ! wp_delete_file_from_directory( $file, $uploadpath['basedir'] ) ) {
$deleted = false;
}
return $deleted;
}
```
| Uses | Description |
| --- | --- |
| [wp\_delete\_file\_from\_directory()](wp_delete_file_from_directory) wp-includes/functions.php | Deletes a file if its path is within the given directory. |
| [wp\_get\_upload\_dir()](wp_get_upload_dir) wp-includes/functions.php | Retrieves uploads directory information. |
| [wpdb::esc\_like()](../classes/wpdb/esc_like) wp-includes/class-wpdb.php | First half of escaping for `LIKE` special characters `%` and `_` before preparing for SQL. |
| [path\_join()](path_join) wp-includes/functions.php | Joins two filesystem paths together. |
| [wpdb::get\_row()](../classes/wpdb/get_row) wp-includes/class-wpdb.php | Retrieves one row from the database. |
| [wp\_basename()](wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| [wpdb::prepare()](../classes/wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [wp\_delete\_attachment()](wp_delete_attachment) wp-includes/post.php | Trashes or deletes an attachment. |
| Version | Description |
| --- | --- |
| [4.9.7](https://developer.wordpress.org/reference/since/4.9.7/) | Introduced. |
wordpress wp_check_jsonp_callback( string $callback ): bool wp\_check\_jsonp\_callback( string $callback ): bool
====================================================
Checks that a JSONP callback is a valid JavaScript callback name.
Only allows alphanumeric characters and the dot character in callback function names. This helps to mitigate XSS attacks caused by directly outputting user input.
`$callback` string Required Supplied JSONP callback function name. bool Whether the callback function name is valid.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function wp_check_jsonp_callback( $callback ) {
if ( ! is_string( $callback ) ) {
return false;
}
preg_replace( '/[^\w\.]/', '', $callback, -1, $illegal_char_count );
return 0 === $illegal_char_count;
}
```
| Used By | Description |
| --- | --- |
| [wp\_is\_jsonp\_request()](wp_is_jsonp_request) wp-includes/load.php | Checks whether current request is a JSONP request, or is expecting a JSONP response. |
| [WP\_REST\_Server::serve\_request()](../classes/wp_rest_server/serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress _custom_logo_header_styles() \_custom\_logo\_header\_styles()
================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Adds CSS to hide header text for custom logo, based on Customizer setting.
File: `wp-includes/theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/theme.php/)
```
function _custom_logo_header_styles() {
if ( ! current_theme_supports( 'custom-header', 'header-text' )
&& get_theme_support( 'custom-logo', 'header-text' )
&& ! get_theme_mod( 'header_text', true )
) {
$classes = (array) get_theme_support( 'custom-logo', 'header-text' );
$classes = array_map( 'sanitize_html_class', $classes );
$classes = '.' . implode( ', .', $classes );
$type_attr = current_theme_supports( 'html5', 'style' ) ? '' : ' type="text/css"';
?>
<!-- Custom Logo: hide header text -->
<style id="custom-logo-css"<?php echo $type_attr; ?>>
<?php echo $classes; ?> {
position: absolute;
clip: rect(1px, 1px, 1px, 1px);
}
</style>
<?php
}
}
```
| Uses | Description |
| --- | --- |
| [get\_theme\_mod()](get_theme_mod) wp-includes/theme.php | Retrieves theme modification value for the active theme. |
| [get\_theme\_support()](get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| [current\_theme\_supports()](current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress wp_redirect( string $location, int $status = 302, string $x_redirect_by = 'WordPress' ): bool wp\_redirect( string $location, int $status = 302, string $x\_redirect\_by = 'WordPress' ): bool
================================================================================================
Redirects to another page.
Note: [wp\_redirect()](wp_redirect) does not exit automatically, and should almost always be followed by a call to `exit;`:
```
wp_redirect( $url );
exit;
```
Exiting can also be selectively manipulated by using [wp\_redirect()](wp_redirect) as a conditional
in conjunction with the [‘wp\_redirect’](../hooks/wp_redirect) and [‘wp\_redirect\_location’](../hooks/wp_redirect_location) filters:
```
if ( wp_redirect( $url ) ) {
exit;
}
```
`$location` string Required The path or URL to redirect to. `$status` int Optional HTTP response status code to use. Default `'302'` (Moved Temporarily). Default: `302`
`$x_redirect_by` string Optional The application doing the redirect. Default `'WordPress'`. Default: `'WordPress'`
bool False if the redirect was cancelled, true otherwise.
File: `wp-includes/pluggable.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pluggable.php/)
```
function wp_redirect( $location, $status = 302, $x_redirect_by = 'WordPress' ) {
global $is_IIS;
/**
* Filters the redirect location.
*
* @since 2.1.0
*
* @param string $location The path or URL to redirect to.
* @param int $status The HTTP response status code to use.
*/
$location = apply_filters( 'wp_redirect', $location, $status );
/**
* Filters the redirect HTTP response status code to use.
*
* @since 2.3.0
*
* @param int $status The HTTP response status code to use.
* @param string $location The path or URL to redirect to.
*/
$status = apply_filters( 'wp_redirect_status', $status, $location );
if ( ! $location ) {
return false;
}
if ( $status < 300 || 399 < $status ) {
wp_die( __( 'HTTP redirect status code must be a redirection code, 3xx.' ) );
}
$location = wp_sanitize_redirect( $location );
if ( ! $is_IIS && 'cgi-fcgi' !== PHP_SAPI ) {
status_header( $status ); // This causes problems on IIS and some FastCGI setups.
}
/**
* Filters the X-Redirect-By header.
*
* Allows applications to identify themselves when they're doing a redirect.
*
* @since 5.1.0
*
* @param string $x_redirect_by The application doing the redirect.
* @param int $status Status code to use.
* @param string $location The path to redirect to.
*/
$x_redirect_by = apply_filters( 'x_redirect_by', $x_redirect_by, $status, $location );
if ( is_string( $x_redirect_by ) ) {
header( "X-Redirect-By: $x_redirect_by" );
}
header( "Location: $location", true, $status );
return true;
}
```
[apply\_filters( 'wp\_redirect', string $location, int $status )](../hooks/wp_redirect)
Filters the redirect location.
[apply\_filters( 'wp\_redirect\_status', int $status, string $location )](../hooks/wp_redirect_status)
Filters the redirect HTTP response status code to use.
[apply\_filters( 'x\_redirect\_by', string $x\_redirect\_by, int $status, string $location )](../hooks/x_redirect_by)
Filters the X-Redirect-By header.
| Uses | Description |
| --- | --- |
| [wp\_sanitize\_redirect()](wp_sanitize_redirect) wp-includes/pluggable.php | Sanitizes a URL for use in a redirect. |
| [status\_header()](status_header) wp-includes/functions.php | Sets HTTP status header. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_die()](wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [do\_favicon()](do_favicon) wp-includes/functions.php | Displays the favicon.ico file content. |
| [WP\_Recovery\_Mode\_Link\_Service::handle\_begin\_link()](../classes/wp_recovery_mode_link_service/handle_begin_link) wp-includes/class-wp-recovery-mode-link-service.php | Enters recovery mode when the user hits wp-login.php with a valid recovery mode link. |
| [resume\_theme()](resume_theme) wp-admin/includes/theme.php | Tries to resume a single theme. |
| [resume\_plugin()](resume_plugin) wp-admin/includes/plugin.php | Tries to resume a single plugin. |
| [wp\_media\_attach\_action()](wp_media_attach_action) wp-admin/includes/media.php | Encapsulates the logic for Attach/Detach actions. |
| [WP\_List\_Table::set\_pagination\_args()](../classes/wp_list_table/set_pagination_args) wp-admin/includes/class-wp-list-table.php | An internal method that sets all the necessary pagination arguments |
| [wp\_dashboard\_setup()](wp_dashboard_setup) wp-admin/includes/dashboard.php | Registers dashboard widgets. |
| [activate\_plugin()](activate_plugin) wp-admin/includes/plugin.php | Attempts activation of plugin in a “sandbox” and redirects on success. |
| [redirect\_post()](redirect_post) wp-admin/includes/post.php | Redirects to previous page. |
| [do\_dismiss\_core\_update()](do_dismiss_core_update) wp-admin/update-core.php | Dismiss a core update. |
| [do\_undismiss\_core\_update()](do_undismiss_core_update) wp-admin/update-core.php | Undismiss a core update. |
| [WP\_Customize\_Manager::after\_setup\_theme()](../classes/wp_customize_manager/after_setup_theme) wp-includes/class-wp-customize-manager.php | Callback to validate a theme once it is loaded |
| [spawn\_cron()](spawn_cron) wp-includes/cron.php | Sends a request to run cron through HTTP request that doesn’t halt page loading. |
| [wp\_safe\_redirect()](wp_safe_redirect) wp-includes/pluggable.php | Performs a safe (local) redirect, using [wp\_redirect()](wp_redirect) . |
| [auth\_redirect()](auth_redirect) wp-includes/pluggable.php | Checks if a user is logged in, if not it redirects them to the login page. |
| [wp\_old\_slug\_redirect()](wp_old_slug_redirect) wp-includes/query.php | Redirect old slugs to the correct permalink. |
| [wp\_not\_installed()](wp_not_installed) wp-includes/load.php | Redirect to the installer if WordPress is not installed. |
| [wp\_redirect\_admin\_locations()](wp_redirect_admin_locations) wp-includes/canonical.php | Redirects a variety of shorthand URLs to the admin. |
| [redirect\_canonical()](redirect_canonical) wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| [maybe\_redirect\_404()](maybe_redirect_404) wp-includes/ms-functions.php | Corrects 404 redirects when NOBLOGREDIRECT is defined. |
| [wpmu\_admin\_do\_redirect()](wpmu_admin_do_redirect) wp-includes/ms-deprecated.php | Redirect a user based on $\_GET or $\_POST arguments. |
| Version | Description |
| --- | --- |
| [5.4.0](https://developer.wordpress.org/reference/since/5.4.0/) | On invalid status codes, [wp\_die()](wp_die) is called. |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | The `$x_redirect_by` parameter was added. |
| [1.5.1](https://developer.wordpress.org/reference/since/1.5.1/) | Introduced. |
wordpress wp_ajax_hidden_columns() wp\_ajax\_hidden\_columns()
===========================
Ajax handler for hidden columns.
File: `wp-admin/includes/ajax-actions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/ajax-actions.php/)
```
function wp_ajax_hidden_columns() {
check_ajax_referer( 'screen-options-nonce', 'screenoptionnonce' );
$page = isset( $_POST['page'] ) ? $_POST['page'] : '';
if ( sanitize_key( $page ) != $page ) {
wp_die( 0 );
}
$user = wp_get_current_user();
if ( ! $user ) {
wp_die( -1 );
}
$hidden = ! empty( $_POST['hidden'] ) ? explode( ',', $_POST['hidden'] ) : array();
update_user_meta( $user->ID, "manage{$page}columnshidden", $hidden );
wp_die( 1 );
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_current\_user()](wp_get_current_user) wp-includes/pluggable.php | Retrieves the current user object. |
| [update\_user\_meta()](update_user_meta) wp-includes/user.php | Updates user meta field based on user ID. |
| [sanitize\_key()](sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [check\_ajax\_referer()](check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [wp\_die()](wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
| programming_docs |
wordpress get_search_template(): string get\_search\_template(): string
===============================
Retrieves path of search template in current or parent template.
The template hierarchy and template path are filterable via the [‘$type\_template\_hierarchy’](../hooks/type_template_hierarchy) and [‘$type\_template’](../hooks/type_template) dynamic hooks, where `$type` is ‘search’.
* [get\_query\_template()](get_query_template)
string Full path to search template file.
File: `wp-includes/template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/template.php/)
```
function get_search_template() {
return get_query_template( 'search' );
}
```
| Uses | Description |
| --- | --- |
| [get\_query\_template()](get_query_template) wp-includes/template.php | Retrieves path to a template. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_get_installed_translations( string $type ): array wp\_get\_installed\_translations( string $type ): array
=======================================================
Gets installed translations.
Looks in the wp-content/languages directory for translations of plugins or themes.
`$type` string Required What to search for. Accepts `'plugins'`, `'themes'`, `'core'`. array Array of language data.
File: `wp-includes/l10n.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/l10n.php/)
```
function wp_get_installed_translations( $type ) {
if ( 'themes' !== $type && 'plugins' !== $type && 'core' !== $type ) {
return array();
}
$dir = 'core' === $type ? '' : "/$type";
if ( ! is_dir( WP_LANG_DIR ) ) {
return array();
}
if ( $dir && ! is_dir( WP_LANG_DIR . $dir ) ) {
return array();
}
$files = scandir( WP_LANG_DIR . $dir );
if ( ! $files ) {
return array();
}
$language_data = array();
foreach ( $files as $file ) {
if ( '.' === $file[0] || is_dir( WP_LANG_DIR . "$dir/$file" ) ) {
continue;
}
if ( substr( $file, -3 ) !== '.po' ) {
continue;
}
if ( ! preg_match( '/(?:(.+)-)?([a-z]{2,3}(?:_[A-Z]{2})?(?:_[a-z0-9]+)?).po/', $file, $match ) ) {
continue;
}
if ( ! in_array( substr( $file, 0, -3 ) . '.mo', $files, true ) ) {
continue;
}
list( , $textdomain, $language ) = $match;
if ( '' === $textdomain ) {
$textdomain = 'default';
}
$language_data[ $textdomain ][ $language ] = wp_get_pomo_file_data( WP_LANG_DIR . "$dir/$file" );
}
return $language_data;
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_pomo\_file\_data()](wp_get_pomo_file_data) wp-includes/l10n.php | Extracts headers from a PO file. |
| Used By | Description |
| --- | --- |
| [delete\_theme()](delete_theme) wp-admin/includes/theme.php | Removes a theme. |
| [delete\_plugins()](delete_plugins) wp-admin/includes/plugin.php | Removes directory and files of a plugin for a list of plugins. |
| [wp\_version\_check()](wp_version_check) wp-includes/update.php | Checks WordPress version against the newest version. |
| [wp\_update\_plugins()](wp_update_plugins) wp-includes/update.php | Checks for available updates to plugins based on the latest versions hosted on WordPress.org. |
| [wp\_update\_themes()](wp_update_themes) wp-includes/update.php | Checks for available updates to themes based on the latest versions hosted on WordPress.org. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress is_active_widget( callable|false $callback = false, string|false $widget_id = false, string|false $id_base = false, bool $skip_inactive = true ): string|false is\_active\_widget( callable|false $callback = false, string|false $widget\_id = false, string|false $id\_base = false, bool $skip\_inactive = true ): string|false
===================================================================================================================================================================
Determines whether a given widget is displayed on the front end.
Either $callback or $id\_base can be used $id\_base is the first argument when extending [WP\_Widget](../classes/wp_widget) class Without the optional $widget\_id parameter, returns the ID of the first sidebar in which the first instance of the widget with the given callback or $id\_base is found.
With the $widget\_id parameter, returns the ID of the sidebar where the widget with that callback/$id\_base AND that ID is found.
NOTE: $widget\_id and $id\_base are the same for single widgets. To be effective this function has to run after widgets have initialized, at action [‘init’](../hooks/init) or later.
For more information on this and similar theme functions, check out the [Conditional Tags](https://developer.wordpress.org/themes/basics/conditional-tags/) article in the Theme Developer Handbook.
`$callback` callable|false Optional Widget callback to check. Default: `false`
`$widget_id` string|false Optional Widget ID. Optional, but needed for checking.
Default: `false`
`$id_base` string|false Optional The base ID of a widget created by extending [WP\_Widget](../classes/wp_widget).
Default: `false`
`$skip_inactive` bool Optional Whether to check in `'wp_inactive_widgets'`.
Default: `true`
string|false ID of the sidebar in which the widget is active, false if the widget is not active.
File: `wp-includes/widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets.php/)
```
function is_active_widget( $callback = false, $widget_id = false, $id_base = false, $skip_inactive = true ) {
global $wp_registered_widgets;
$sidebars_widgets = wp_get_sidebars_widgets();
if ( is_array( $sidebars_widgets ) ) {
foreach ( $sidebars_widgets as $sidebar => $widgets ) {
if ( $skip_inactive && ( 'wp_inactive_widgets' === $sidebar || 'orphaned_widgets' === substr( $sidebar, 0, 16 ) ) ) {
continue;
}
if ( is_array( $widgets ) ) {
foreach ( $widgets as $widget ) {
if ( ( $callback && isset( $wp_registered_widgets[ $widget ]['callback'] ) && $wp_registered_widgets[ $widget ]['callback'] === $callback ) || ( $id_base && _get_widget_id_base( $widget ) === $id_base ) ) {
if ( ! $widget_id || $widget_id === $wp_registered_widgets[ $widget ]['id'] ) {
return $sidebar;
}
}
}
}
}
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_sidebars\_widgets()](wp_get_sidebars_widgets) wp-includes/widgets.php | Retrieve full list of sidebars and their widget instance IDs. |
| [\_get\_widget\_id\_base()](_get_widget_id_base) wp-includes/widgets.php | Retrieves the widget ID base value. |
| Used By | Description |
| --- | --- |
| [wp\_list\_widgets()](wp_list_widgets) wp-admin/includes/widgets.php | Display list of the available widgets. |
| [WP\_Widget\_Recent\_Comments::\_\_construct()](../classes/wp_widget_recent_comments/__construct) wp-includes/widgets/class-wp-widget-recent-comments.php | Sets up a new Recent Comments widget instance. |
| [WP\_Customize\_Widgets::get\_available\_widgets()](../classes/wp_customize_widgets/get_available_widgets) wp-includes/class-wp-customize-widgets.php | Builds up an index of all available widgets for use in Backbone models. |
| Version | Description |
| --- | --- |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Introduced. |
wordpress rest_sanitize_array( mixed $maybe_array ): array rest\_sanitize\_array( mixed $maybe\_array ): array
===================================================
Converts an array-like value to an array.
`$maybe_array` mixed Required The value being evaluated. array Returns the array extracted from the value.
File: `wp-includes/rest-api.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api.php/)
```
function rest_sanitize_array( $maybe_array ) {
if ( is_scalar( $maybe_array ) ) {
return wp_parse_list( $maybe_array );
}
if ( ! is_array( $maybe_array ) ) {
return array();
}
// Normalize to numeric array so nothing unexpected is in the keys.
return array_values( $maybe_array );
}
```
| Uses | Description |
| --- | --- |
| [wp\_parse\_list()](wp_parse_list) wp-includes/functions.php | Converts a comma- or space-separated list of scalar values to an array. |
| Used By | Description |
| --- | --- |
| [rest\_validate\_array\_value\_from\_schema()](rest_validate_array_value_from_schema) wp-includes/rest-api.php | Validates an array value based on a schema. |
| [rest\_sanitize\_value\_from\_schema()](rest_sanitize_value_from_schema) wp-includes/rest-api.php | Sanitize a value based on a schema. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress wp_kses_uri_attributes(): string[] wp\_kses\_uri\_attributes(): string[]
=====================================
Returns an array of HTML attribute names whose value contains a URL.
This function returns a list of all HTML attributes that must contain a URL according to the HTML specification.
This list includes URI attributes both allowed and disallowed by KSES.
string[] HTML attribute names whose value contains a URL.
File: `wp-includes/kses.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/kses.php/)
```
function wp_kses_uri_attributes() {
$uri_attributes = array(
'action',
'archive',
'background',
'cite',
'classid',
'codebase',
'data',
'formaction',
'href',
'icon',
'longdesc',
'manifest',
'poster',
'profile',
'src',
'usemap',
'xmlns',
);
/**
* Filters the list of attributes that are required to contain a URL.
*
* Use this filter to add any `data-` attributes that are required to be
* validated as a URL.
*
* @since 5.0.1
*
* @param string[] $uri_attributes HTML attribute names whose value contains a URL.
*/
$uri_attributes = apply_filters( 'wp_kses_uri_attributes', $uri_attributes );
return $uri_attributes;
}
```
[apply\_filters( 'wp\_kses\_uri\_attributes', string[] $uri\_attributes )](../hooks/wp_kses_uri_attributes)
Filters the list of attributes that are required to contain a URL.
| Uses | Description |
| --- | --- |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_kses\_one\_attr()](wp_kses_one_attr) wp-includes/kses.php | Filters one HTML attribute and ensures its value is allowed. |
| [wp\_kses\_hair()](wp_kses_hair) wp-includes/kses.php | Builds an attribute list from string containing attributes. |
| Version | Description |
| --- | --- |
| [5.0.1](https://developer.wordpress.org/reference/since/5.0.1/) | Introduced. |
wordpress wp_sitemaps_get_max_urls( string $object_type ): int wp\_sitemaps\_get\_max\_urls( string $object\_type ): int
=========================================================
Gets the maximum number of URLs for a sitemap.
`$object_type` string Required Object type for sitemap to be filtered (e.g. `'post'`, `'term'`, `'user'`). int The maximum number of URLs.
File: `wp-includes/sitemaps.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps.php/)
```
function wp_sitemaps_get_max_urls( $object_type ) {
/**
* Filters the maximum number of URLs displayed on a sitemap.
*
* @since 5.5.0
*
* @param int $max_urls The maximum number of URLs included in a sitemap. Default 2000.
* @param string $object_type Object type for sitemap to be filtered (e.g. 'post', 'term', 'user').
*/
return apply_filters( 'wp_sitemaps_max_urls', 2000, $object_type );
}
```
[apply\_filters( 'wp\_sitemaps\_max\_urls', int $max\_urls, string $object\_type )](../hooks/wp_sitemaps_max_urls)
Filters the maximum number of URLs displayed on a sitemap.
| Uses | Description |
| --- | --- |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Sitemaps\_Users::get\_max\_num\_pages()](../classes/wp_sitemaps_users/get_max_num_pages) wp-includes/sitemaps/providers/class-wp-sitemaps-users.php | Gets the max number of pages available for the object type. |
| [WP\_Sitemaps\_Users::get\_users\_query\_args()](../classes/wp_sitemaps_users/get_users_query_args) wp-includes/sitemaps/providers/class-wp-sitemaps-users.php | Returns the query args for retrieving users to list in the sitemap. |
| [WP\_Sitemaps\_Taxonomies::get\_url\_list()](../classes/wp_sitemaps_taxonomies/get_url_list) wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php | Gets a URL list for a taxonomy sitemap. |
| [WP\_Sitemaps\_Taxonomies::get\_max\_num\_pages()](../classes/wp_sitemaps_taxonomies/get_max_num_pages) wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php | Gets the max number of pages available for the object type. |
| [WP\_Sitemaps\_Taxonomies::get\_taxonomies\_query\_args()](../classes/wp_sitemaps_taxonomies/get_taxonomies_query_args) wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php | Returns the query args for retrieving taxonomy terms to list in the sitemap. |
| [WP\_Sitemaps\_Posts::get\_posts\_query\_args()](../classes/wp_sitemaps_posts/get_posts_query_args) wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php | Returns the query args for retrieving posts to list in the sitemap. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress get_the_author_firstname(): string get\_the\_author\_firstname(): string
=====================================
This function has been deprecated. Use [get\_the\_author\_meta()](get_the_author_meta) instead.
Retrieve the first name of the author of the current post.
* [get\_the\_author\_meta()](get_the_author_meta)
string The author's first name.
File: `wp-includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/deprecated.php/)
```
function get_the_author_firstname() {
_deprecated_function( __FUNCTION__, '2.8.0', 'get_the_author_meta(\'first_name\')' );
return get_the_author_meta('first_name');
}
```
| Uses | Description |
| --- | --- |
| [get\_the\_author\_meta()](get_the_author_meta) wp-includes/author-template.php | Retrieves the requested data of the author of the current post. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Use [get\_the\_author\_meta()](get_the_author_meta) |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_image_editor( int $post_id, false|object $msg = false ) wp\_image\_editor( int $post\_id, false|object $msg = false )
=============================================================
Loads the WP image-editing interface.
`$post_id` int Required Attachment post ID. `$msg` false|object Optional Message to display for image editor updates or errors.
Default: `false`
File: `wp-admin/includes/image-edit.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/image-edit.php/)
```
function wp_image_editor( $post_id, $msg = false ) {
$nonce = wp_create_nonce( "image_editor-$post_id" );
$meta = wp_get_attachment_metadata( $post_id );
$thumb = image_get_intermediate_size( $post_id, 'thumbnail' );
$sub_sizes = isset( $meta['sizes'] ) && is_array( $meta['sizes'] );
$note = '';
if ( isset( $meta['width'], $meta['height'] ) ) {
$big = max( $meta['width'], $meta['height'] );
} else {
die( __( 'Image data does not exist. Please re-upload the image.' ) );
}
$sizer = $big > 400 ? 400 / $big : 1;
$backup_sizes = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true );
$can_restore = false;
if ( ! empty( $backup_sizes ) && isset( $backup_sizes['full-orig'], $meta['file'] ) ) {
$can_restore = wp_basename( $meta['file'] ) !== $backup_sizes['full-orig']['file'];
}
if ( $msg ) {
if ( isset( $msg->error ) ) {
$note = "<div class='notice notice-error' tabindex='-1' role='alert'><p>$msg->error</p></div>";
} elseif ( isset( $msg->msg ) ) {
$note = "<div class='notice notice-success' tabindex='-1' role='alert'><p>$msg->msg</p></div>";
}
}
$edit_custom_sizes = false;
/**
* Filters whether custom sizes are available options for image editing.
*
* @since 6.0.0
*
* @param bool|string[] $edit_custom_sizes True if custom sizes can be edited or array of custom size names.
*/
$edit_custom_sizes = apply_filters( 'edit_custom_thumbnail_sizes', $edit_custom_sizes );
?>
<div class="imgedit-wrap wp-clearfix">
<div id="imgedit-panel-<?php echo $post_id; ?>">
<div class="imgedit-panel-content wp-clearfix">
<?php echo $note; ?>
<div class="imgedit-menu wp-clearfix">
<button type="button" onclick="imageEdit.handleCropToolClick( <?php echo "$post_id, '$nonce'"; ?>, this )" class="imgedit-crop button disabled" disabled><?php esc_html_e( 'Crop' ); ?></button>
<?php
// On some setups GD library does not provide imagerotate() - Ticket #11536.
if ( wp_image_editor_supports(
array(
'mime_type' => get_post_mime_type( $post_id ),
'methods' => array( 'rotate' ),
)
) ) {
$note_no_rotate = '';
?>
<button type="button" class="imgedit-rleft button" onclick="imageEdit.rotate( 90, <?php echo "$post_id, '$nonce'"; ?>, this)"><?php esc_html_e( 'Rotate left' ); ?></button>
<button type="button" class="imgedit-rright button" onclick="imageEdit.rotate(-90, <?php echo "$post_id, '$nonce'"; ?>, this)"><?php esc_html_e( 'Rotate right' ); ?></button>
<?php
} else {
$note_no_rotate = '<p class="note-no-rotate"><em>' . __( 'Image rotation is not supported by your web host.' ) . '</em></p>';
?>
<button type="button" class="imgedit-rleft button disabled" disabled></button>
<button type="button" class="imgedit-rright button disabled" disabled></button>
<?php } ?>
<button type="button" onclick="imageEdit.flip(1, <?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-flipv button"><?php esc_html_e( 'Flip vertical' ); ?></button>
<button type="button" onclick="imageEdit.flip(2, <?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-fliph button"><?php esc_html_e( 'Flip horizontal' ); ?></button>
<br class="imgedit-undo-redo-separator" />
<button type="button" id="image-undo-<?php echo $post_id; ?>" onclick="imageEdit.undo(<?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-undo button disabled" disabled><?php esc_html_e( 'Undo' ); ?></button>
<button type="button" id="image-redo-<?php echo $post_id; ?>" onclick="imageEdit.redo(<?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-redo button disabled" disabled><?php esc_html_e( 'Redo' ); ?></button>
<?php echo $note_no_rotate; ?>
</div>
<input type="hidden" id="imgedit-sizer-<?php echo $post_id; ?>" value="<?php echo $sizer; ?>" />
<input type="hidden" id="imgedit-history-<?php echo $post_id; ?>" value="" />
<input type="hidden" id="imgedit-undone-<?php echo $post_id; ?>" value="0" />
<input type="hidden" id="imgedit-selection-<?php echo $post_id; ?>" value="" />
<input type="hidden" id="imgedit-x-<?php echo $post_id; ?>" value="<?php echo isset( $meta['width'] ) ? $meta['width'] : 0; ?>" />
<input type="hidden" id="imgedit-y-<?php echo $post_id; ?>" value="<?php echo isset( $meta['height'] ) ? $meta['height'] : 0; ?>" />
<div id="imgedit-crop-<?php echo $post_id; ?>" class="imgedit-crop-wrap">
<img id="image-preview-<?php echo $post_id; ?>" onload="imageEdit.imgLoaded('<?php echo $post_id; ?>')"
src="<?php echo esc_url( admin_url( 'admin-ajax.php', 'relative' ) ) . '?action=imgedit-preview&_ajax_nonce=' . $nonce . '&postid=' . $post_id . '&rand=' . rand( 1, 99999 ); ?>" alt="" />
</div>
<div class="imgedit-submit">
<input type="button" onclick="imageEdit.close(<?php echo $post_id; ?>, 1)" class="button imgedit-cancel-btn" value="<?php esc_attr_e( 'Cancel' ); ?>" />
<input type="button" onclick="imageEdit.save(<?php echo "$post_id, '$nonce'"; ?>)" disabled="disabled" class="button button-primary imgedit-submit-btn" value="<?php esc_attr_e( 'Save' ); ?>" />
</div>
</div>
<div class="imgedit-settings">
<div class="imgedit-group">
<div class="imgedit-group-top">
<h2><?php _e( 'Scale Image' ); ?></h2>
<button type="button" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);" aria-expanded="false"><span class="screen-reader-text"><?php esc_html_e( 'Scale Image Help' ); ?></span></button>
<div class="imgedit-help">
<p><?php _e( 'You can proportionally scale the original image. For best results, scaling should be done before you crop, flip, or rotate. Images can only be scaled down, not up.' ); ?></p>
</div>
<?php if ( isset( $meta['width'], $meta['height'] ) ) : ?>
<p>
<?php
printf(
/* translators: %s: Image width and height in pixels. */
__( 'Original dimensions %s' ),
'<span class="imgedit-original-dimensions">' . $meta['width'] . ' × ' . $meta['height'] . '</span>'
);
?>
</p>
<?php endif; ?>
<div class="imgedit-submit">
<fieldset class="imgedit-scale">
<legend><?php _e( 'New dimensions:' ); ?></legend>
<div class="nowrap">
<label for="imgedit-scale-width-<?php echo $post_id; ?>" class="screen-reader-text"><?php _e( 'scale width' ); ?></label>
<input type="text" id="imgedit-scale-width-<?php echo $post_id; ?>" onkeyup="imageEdit.scaleChanged(<?php echo $post_id; ?>, 1, this)" onblur="imageEdit.scaleChanged(<?php echo $post_id; ?>, 1, this)" value="<?php echo isset( $meta['width'] ) ? $meta['width'] : 0; ?>" />
<span class="imgedit-separator" aria-hidden="true">×</span>
<label for="imgedit-scale-height-<?php echo $post_id; ?>" class="screen-reader-text"><?php _e( 'scale height' ); ?></label>
<input type="text" id="imgedit-scale-height-<?php echo $post_id; ?>" onkeyup="imageEdit.scaleChanged(<?php echo $post_id; ?>, 0, this)" onblur="imageEdit.scaleChanged(<?php echo $post_id; ?>, 0, this)" value="<?php echo isset( $meta['height'] ) ? $meta['height'] : 0; ?>" />
<span class="imgedit-scale-warn" id="imgedit-scale-warn-<?php echo $post_id; ?>">!</span>
<div class="imgedit-scale-button-wrapper"><input id="imgedit-scale-button" type="button" onclick="imageEdit.action(<?php echo "$post_id, '$nonce'"; ?>, 'scale')" class="button button-primary" value="<?php esc_attr_e( 'Scale' ); ?>" /></div>
</div>
</fieldset>
</div>
</div>
</div>
<?php if ( $can_restore ) { ?>
<div class="imgedit-group">
<div class="imgedit-group-top">
<h2><button type="button" onclick="imageEdit.toggleHelp(this);" class="button-link" aria-expanded="false"><?php _e( 'Restore original image' ); ?> <span class="dashicons dashicons-arrow-down imgedit-help-toggle"></span></button></h2>
<div class="imgedit-help imgedit-restore">
<p>
<?php
_e( 'Discard any changes and restore the original image.' );
if ( ! defined( 'IMAGE_EDIT_OVERWRITE' ) || ! IMAGE_EDIT_OVERWRITE ) {
echo ' ' . __( 'Previously edited copies of the image will not be deleted.' );
}
?>
</p>
<div class="imgedit-submit">
<input type="button" onclick="imageEdit.action(<?php echo "$post_id, '$nonce'"; ?>, 'restore')" class="button button-primary" value="<?php esc_attr_e( 'Restore image' ); ?>" <?php echo $can_restore; ?> />
</div>
</div>
</div>
</div>
<?php } ?>
<div class="imgedit-group">
<div class="imgedit-group-top">
<h2><?php _e( 'Image Crop' ); ?></h2>
<button type="button" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);" aria-expanded="false"><span class="screen-reader-text"><?php esc_html_e( 'Image Crop Help' ); ?></span></button>
<div class="imgedit-help">
<p><?php _e( 'To crop the image, click on it and drag to make your selection.' ); ?></p>
<p><strong><?php _e( 'Crop Aspect Ratio' ); ?></strong><br />
<?php _e( 'The aspect ratio is the relationship between the width and height. You can preserve the aspect ratio by holding down the shift key while resizing your selection. Use the input box to specify the aspect ratio, e.g. 1:1 (square), 4:3, 16:9, etc.' ); ?></p>
<p><strong><?php _e( 'Crop Selection' ); ?></strong><br />
<?php _e( 'Once you have made your selection, you can adjust it by entering the size in pixels. The minimum selection size is the thumbnail size as set in the Media settings.' ); ?></p>
</div>
</div>
<fieldset class="imgedit-crop-ratio">
<legend><?php _e( 'Aspect ratio:' ); ?></legend>
<div class="nowrap">
<label for="imgedit-crop-width-<?php echo $post_id; ?>" class="screen-reader-text"><?php _e( 'crop ratio width' ); ?></label>
<input type="text" id="imgedit-crop-width-<?php echo $post_id; ?>" onkeyup="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 0, this)" onblur="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 0, this)" />
<span class="imgedit-separator" aria-hidden="true">:</span>
<label for="imgedit-crop-height-<?php echo $post_id; ?>" class="screen-reader-text"><?php _e( 'crop ratio height' ); ?></label>
<input type="text" id="imgedit-crop-height-<?php echo $post_id; ?>" onkeyup="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 1, this)" onblur="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 1, this)" />
</div>
</fieldset>
<fieldset id="imgedit-crop-sel-<?php echo $post_id; ?>" class="imgedit-crop-sel">
<legend><?php _e( 'Selection:' ); ?></legend>
<div class="nowrap">
<label for="imgedit-sel-width-<?php echo $post_id; ?>" class="screen-reader-text"><?php _e( 'selection width' ); ?></label>
<input type="text" id="imgedit-sel-width-<?php echo $post_id; ?>" onkeyup="imageEdit.setNumSelection(<?php echo $post_id; ?>, this)" onblur="imageEdit.setNumSelection(<?php echo $post_id; ?>, this)" />
<span class="imgedit-separator" aria-hidden="true">×</span>
<label for="imgedit-sel-height-<?php echo $post_id; ?>" class="screen-reader-text"><?php _e( 'selection height' ); ?></label>
<input type="text" id="imgedit-sel-height-<?php echo $post_id; ?>" onkeyup="imageEdit.setNumSelection(<?php echo $post_id; ?>, this)" onblur="imageEdit.setNumSelection(<?php echo $post_id; ?>, this)" />
</div>
</fieldset>
</div>
<?php
if ( $thumb && $sub_sizes ) {
$thumb_img = wp_constrain_dimensions( $thumb['width'], $thumb['height'], 160, 120 );
?>
<div class="imgedit-group imgedit-applyto">
<div class="imgedit-group-top">
<h2><?php _e( 'Thumbnail Settings' ); ?></h2>
<button type="button" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);" aria-expanded="false"><span class="screen-reader-text"><?php esc_html_e( 'Thumbnail Settings Help' ); ?></span></button>
<div class="imgedit-help">
<p><?php _e( 'You can edit the image while preserving the thumbnail. For example, you may wish to have a square thumbnail that displays just a section of the image.' ); ?></p>
</div>
</div>
<figure class="imgedit-thumbnail-preview">
<img src="<?php echo $thumb['url']; ?>" width="<?php echo $thumb_img[0]; ?>" height="<?php echo $thumb_img[1]; ?>" class="imgedit-size-preview" alt="" draggable="false" />
<figcaption class="imgedit-thumbnail-preview-caption"><?php _e( 'Current thumbnail' ); ?></figcaption>
</figure>
<div id="imgedit-save-target-<?php echo $post_id; ?>" class="imgedit-save-target">
<fieldset>
<legend><?php _e( 'Apply changes to:' ); ?></legend>
<span class="imgedit-label">
<input type="radio" id="imgedit-target-all" name="imgedit-target-<?php echo $post_id; ?>" value="all" checked="checked" />
<label for="imgedit-target-all"><?php _e( 'All image sizes' ); ?></label>
</span>
<span class="imgedit-label">
<input type="radio" id="imgedit-target-thumbnail" name="imgedit-target-<?php echo $post_id; ?>" value="thumbnail" />
<label for="imgedit-target-thumbnail"><?php _e( 'Thumbnail' ); ?></label>
</span>
<span class="imgedit-label">
<input type="radio" id="imgedit-target-nothumb" name="imgedit-target-<?php echo $post_id; ?>" value="nothumb" />
<label for="imgedit-target-nothumb"><?php _e( 'All sizes except thumbnail' ); ?></label>
</span>
<?php
if ( $edit_custom_sizes ) {
if ( ! is_array( $edit_custom_sizes ) ) {
$edit_custom_sizes = get_intermediate_image_sizes();
}
foreach ( array_unique( $edit_custom_sizes ) as $key => $size ) {
if ( array_key_exists( $size, $meta['sizes'] ) ) {
if ( 'thumbnail' === $size ) {
continue;
}
?>
<span class="imgedit-label">
<input type="radio" id="imgedit-target-custom<?php echo esc_attr( $key ); ?>" name="imgedit-target-<?php echo $post_id; ?>" value="<?php echo esc_attr( $size ); ?>" />
<label for="imgedit-target-custom<?php echo esc_attr( $key ); ?>"><?php echo esc_html( $size ); ?></label>
</span>
<?php
}
}
}
?>
</fieldset>
</div>
</div>
<?php } ?>
</div>
</div>
<div class="imgedit-wait" id="imgedit-wait-<?php echo $post_id; ?>"></div>
<div class="hidden" id="imgedit-leaving-<?php echo $post_id; ?>"><?php _e( "There are unsaved changes that will be lost. 'OK' to continue, 'Cancel' to return to the Image Editor." ); ?></div>
</div>
<?php
}
```
[apply\_filters( 'edit\_custom\_thumbnail\_sizes', bool|string[] $edit\_custom\_sizes )](../hooks/edit_custom_thumbnail_sizes)
Filters whether custom sizes are available options for image editing.
| Uses | Description |
| --- | --- |
| [get\_post\_mime\_type()](get_post_mime_type) wp-includes/post.php | Retrieves the mime type of an attachment based on the ID. |
| [wp\_image\_editor\_supports()](wp_image_editor_supports) wp-includes/media.php | Tests whether there is an editor that supports a given mime type or methods. |
| [esc\_attr\_e()](esc_attr_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in an attribute. |
| [wp\_get\_attachment\_metadata()](wp_get_attachment_metadata) wp-includes/post.php | Retrieves attachment metadata for attachment ID. |
| [get\_intermediate\_image\_sizes()](get_intermediate_image_sizes) wp-includes/media.php | Gets the available intermediate image size names. |
| [wp\_constrain\_dimensions()](wp_constrain_dimensions) wp-includes/media.php | Calculates the new dimensions for a down-sampled image. |
| [image\_get\_intermediate\_size()](image_get_intermediate_size) wp-includes/media.php | Retrieves the image’s intermediate size (resized) path, width, and height. |
| [wp\_create\_nonce()](wp_create_nonce) wp-includes/pluggable.php | Creates a cryptographic token tied to a specific action, user, user session, and window of time. |
| [esc\_html\_e()](esc_html_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in HTML output. |
| [get\_post\_meta()](get_post_meta) wp-includes/post.php | Retrieves a post meta field for the given post ID. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [wp\_basename()](wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| [\_e()](_e) wp-includes/l10n.php | Displays translated text. |
| [admin\_url()](admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| Used By | Description |
| --- | --- |
| [edit\_form\_image\_editor()](edit_form_image_editor) wp-admin/includes/media.php | Displays the image and editor in the post editor |
| [wp\_ajax\_image\_editor()](wp_ajax_image_editor) wp-admin/includes/ajax-actions.php | Ajax handler for image editing. |
| Version | Description |
| --- | --- |
| [2.9.0](https://developer.wordpress.org/reference/since/2.9.0/) | Introduced. |
| programming_docs |
wordpress remove_option_whitelist( array $del_options, string|array $options = '' ): array remove\_option\_whitelist( array $del\_options, string|array $options = '' ): array
===================================================================================
This function has been deprecated. Use [remove\_allowed\_options()](remove_allowed_options) instead. Please consider writing more inclusive code.
Removes a list of options from the allowed options list.
`$del_options` array Required `$options` string|array Optional Default: `''`
array
File: `wp-includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/deprecated.php/)
```
function remove_option_whitelist( $del_options, $options = '' ) {
_deprecated_function( __FUNCTION__, '5.5.0', 'remove_allowed_options()' );
return remove_allowed_options( $del_options, $options );
}
```
| Uses | Description |
| --- | --- |
| [remove\_allowed\_options()](remove_allowed_options) wp-admin/includes/plugin.php | Removes a list of options from the allowed options list. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Use [remove\_allowed\_options()](remove_allowed_options) instead. Please consider writing more inclusive code. |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress delete_expired_transients( bool $force_db = false ) delete\_expired\_transients( bool $force\_db = false )
======================================================
Deletes all expired transients.
Note that this function won’t do anything if an external object cache is in use.
The multi-table delete syntax is used to delete the transient record from table a, and the corresponding transient\_timeout record from table b.
`$force_db` bool Optional Force cleanup to run against the database even when an external object cache is used. Default: `false`
File: `wp-includes/option.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/option.php/)
```
function delete_expired_transients( $force_db = false ) {
global $wpdb;
if ( ! $force_db && wp_using_ext_object_cache() ) {
return;
}
$wpdb->query(
$wpdb->prepare(
"DELETE a, b FROM {$wpdb->options} a, {$wpdb->options} b
WHERE a.option_name LIKE %s
AND a.option_name NOT LIKE %s
AND b.option_name = CONCAT( '_transient_timeout_', SUBSTRING( a.option_name, 12 ) )
AND b.option_value < %d",
$wpdb->esc_like( '_transient_' ) . '%',
$wpdb->esc_like( '_transient_timeout_' ) . '%',
time()
)
);
if ( ! is_multisite() ) {
// Single site stores site transients in the options table.
$wpdb->query(
$wpdb->prepare(
"DELETE a, b FROM {$wpdb->options} a, {$wpdb->options} b
WHERE a.option_name LIKE %s
AND a.option_name NOT LIKE %s
AND b.option_name = CONCAT( '_site_transient_timeout_', SUBSTRING( a.option_name, 17 ) )
AND b.option_value < %d",
$wpdb->esc_like( '_site_transient_' ) . '%',
$wpdb->esc_like( '_site_transient_timeout_' ) . '%',
time()
)
);
} elseif ( is_multisite() && is_main_site() && is_main_network() ) {
// Multisite stores site transients in the sitemeta table.
$wpdb->query(
$wpdb->prepare(
"DELETE a, b FROM {$wpdb->sitemeta} a, {$wpdb->sitemeta} b
WHERE a.meta_key LIKE %s
AND a.meta_key NOT LIKE %s
AND b.meta_key = CONCAT( '_site_transient_timeout_', SUBSTRING( a.meta_key, 17 ) )
AND b.meta_value < %d",
$wpdb->esc_like( '_site_transient_' ) . '%',
$wpdb->esc_like( '_site_transient_timeout_' ) . '%',
time()
)
);
}
}
```
| Uses | Description |
| --- | --- |
| [wpdb::esc\_like()](../classes/wpdb/esc_like) wp-includes/class-wpdb.php | First half of escaping for `LIKE` special characters `%` and `_` before preparing for SQL. |
| [wp\_using\_ext\_object\_cache()](wp_using_ext_object_cache) wp-includes/load.php | Toggle `$_wp_using_ext_object_cache` on and off without directly touching global. |
| [is\_main\_site()](is_main_site) wp-includes/functions.php | Determines whether a site is the main site of the current network. |
| [is\_main\_network()](is_main_network) wp-includes/functions.php | Determines whether a network is the main network of the Multisite installation. |
| [wpdb::query()](../classes/wpdb/query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| [is\_multisite()](is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [wpdb::prepare()](../classes/wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [populate\_options()](populate_options) wp-admin/includes/schema.php | Create WordPress options and set the default values. |
| [upgrade\_network()](upgrade_network) wp-admin/includes/upgrade.php | Executes network-level upgrade routines. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress the_comments_navigation( array $args = array() ) the\_comments\_navigation( array $args = array() )
==================================================
Displays navigation to next/previous set of comments, when applicable.
`$args` array Optional See [get\_the\_comments\_navigation()](get_the_comments_navigation) for available arguments. More Arguments from get\_the\_comments\_navigation( ... $args ) Default comments navigation arguments.
* `prev_text`stringAnchor text to display in the previous comments link.
Default 'Older comments'.
* `next_text`stringAnchor text to display in the next comments link.
Default 'Newer comments'.
* `screen_reader_text`stringScreen reader text for the nav element. Default 'Comments navigation'.
* `aria_label`stringARIA label text for the nav element. Default `'Comments'`.
* `class`stringCustom class for the nav element. Default `'comment-navigation'`.
Default: `array()`
File: `wp-includes/link-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/link-template.php/)
```
function the_comments_navigation( $args = array() ) {
echo get_the_comments_navigation( $args );
}
```
| Uses | Description |
| --- | --- |
| [get\_the\_comments\_navigation()](get_the_comments_navigation) wp-includes/link-template.php | Retrieves navigation to next/previous set of comments, when applicable. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress the_privacy_policy_link( string $before = '', string $after = '' ) the\_privacy\_policy\_link( string $before = '', string $after = '' )
=====================================================================
Displays the privacy policy link with formatting, when applicable.
`$before` string Optional Display before privacy policy link. Default: `''`
`$after` string Optional Display after privacy policy link. Default: `''`
File: `wp-includes/link-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/link-template.php/)
```
function the_privacy_policy_link( $before = '', $after = '' ) {
echo get_the_privacy_policy_link( $before, $after );
}
```
| Uses | Description |
| --- | --- |
| [get\_the\_privacy\_policy\_link()](get_the_privacy_policy_link) wp-includes/link-template.php | Returns the privacy policy link with formatting, when applicable. |
| Used By | Description |
| --- | --- |
| [login\_footer()](login_footer) wp-login.php | Outputs the footer for the login page. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress update_page_cache( array $pages ) update\_page\_cache( array $pages )
===================================
This function has been deprecated. Use [update\_post\_cache()](update_post_cache) instead.
Alias of [update\_post\_cache()](update_post_cache) .
* [update\_post\_cache()](update_post_cache) : Posts and pages are the same, alias is intentional
* [update\_post\_cache()](update_post_cache)
`$pages` array Required list of page objects File: `wp-includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/deprecated.php/)
```
function update_page_cache( &$pages ) {
_deprecated_function( __FUNCTION__, '3.4.0', 'update_post_cache()' );
update_post_cache( $pages );
}
```
| Uses | Description |
| --- | --- |
| [update\_post\_cache()](update_post_cache) wp-includes/post.php | Updates posts in cache. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Use [update\_post\_cache()](update_post_cache) |
| [1.5.1](https://developer.wordpress.org/reference/since/1.5.1/) | Introduced. |
wordpress get_editable_authors( int $user_id ): array|false get\_editable\_authors( int $user\_id ): array|false
====================================================
This function has been deprecated. Use [get\_users()](get_users) instead.
Gets author users who can edit posts.
`$user_id` int Required User ID. array|false List of editable authors. False if no editable users.
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
function get_editable_authors( $user_id ) {
_deprecated_function( __FUNCTION__, '3.1.0', 'get_users()' );
global $wpdb;
$editable = get_editable_user_ids( $user_id );
if ( !$editable ) {
return false;
} else {
$editable = join(',', $editable);
$authors = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($editable) ORDER BY display_name" );
}
return apply_filters('get_editable_authors', $authors);
}
```
| Uses | Description |
| --- | --- |
| [get\_editable\_user\_ids()](get_editable_user_ids) wp-admin/includes/deprecated.php | Gets the IDs of any users who can edit posts. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [wpdb::get\_results()](../classes/wpdb/get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress get_adjacent_post_link( string $format, string $link, bool $in_same_term = false, int[]|string $excluded_terms = '', bool $previous = true, string $taxonomy = 'category' ): string get\_adjacent\_post\_link( string $format, string $link, bool $in\_same\_term = false, int[]|string $excluded\_terms = '', bool $previous = true, string $taxonomy = 'category' ): string
=========================================================================================================================================================================================
Retrieves the adjacent post link.
Can be either next post link or previous.
`$format` string Required Link anchor format. `$link` string Required Link permalink format. `$in_same_term` bool Optional Whether link should be in a same taxonomy term. Default: `false`
`$excluded_terms` int[]|string Optional Array or comma-separated list of excluded terms IDs. Default: `''`
`$previous` bool Optional Whether to display link to previous or next post. Default: `true`
`$taxonomy` string Optional Taxonomy, if $in\_same\_term is true. Default `'category'`. Default: `'category'`
string The link URL of the previous or next post in relation to the current post.
File: `wp-includes/link-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/link-template.php/)
```
function get_adjacent_post_link( $format, $link, $in_same_term = false, $excluded_terms = '', $previous = true, $taxonomy = 'category' ) {
if ( $previous && is_attachment() ) {
$post = get_post( get_post()->post_parent );
} else {
$post = get_adjacent_post( $in_same_term, $excluded_terms, $previous, $taxonomy );
}
if ( ! $post ) {
$output = '';
} else {
$title = $post->post_title;
if ( empty( $post->post_title ) ) {
$title = $previous ? __( 'Previous Post' ) : __( 'Next Post' );
}
/** This filter is documented in wp-includes/post-template.php */
$title = apply_filters( 'the_title', $title, $post->ID );
$date = mysql2date( get_option( 'date_format' ), $post->post_date );
$rel = $previous ? 'prev' : 'next';
$string = '<a href="' . get_permalink( $post ) . '" rel="' . $rel . '">';
$inlink = str_replace( '%title', $title, $link );
$inlink = str_replace( '%date', $date, $inlink );
$inlink = $string . $inlink . '</a>';
$output = str_replace( '%link', $inlink, $format );
}
$adjacent = $previous ? 'previous' : 'next';
/**
* Filters the adjacent post link.
*
* The dynamic portion of the hook name, `$adjacent`, refers to the type
* of adjacency, 'next' or 'previous'.
*
* Possible hook names include:
*
* - `next_post_link`
* - `previous_post_link`
*
* @since 2.6.0
* @since 4.2.0 Added the `$adjacent` parameter.
*
* @param string $output The adjacent post link.
* @param string $format Link anchor format.
* @param string $link Link permalink format.
* @param WP_Post $post The adjacent post.
* @param string $adjacent Whether the post is previous or next.
*/
return apply_filters( "{$adjacent}_post_link", $output, $format, $link, $post, $adjacent );
}
```
[apply\_filters( 'the\_title', string $post\_title, int $post\_id )](../hooks/the_title)
Filters the post title.
[apply\_filters( "{$adjacent}\_post\_link", string $output, string $format, string $link, WP\_Post $post, string $adjacent )](../hooks/adjacent_post_link)
Filters the adjacent post link.
| Uses | Description |
| --- | --- |
| [is\_attachment()](is_attachment) wp-includes/query.php | Determines whether the query is for an existing attachment page. |
| [mysql2date()](mysql2date) wp-includes/functions.php | Converts given MySQL date string into a different format. |
| [get\_adjacent\_post()](get_adjacent_post) wp-includes/link-template.php | Retrieves the adjacent post. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_permalink()](get_permalink) wp-includes/link-template.php | Retrieves the full permalink for the current post or post ID. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [adjacent\_post\_link()](adjacent_post_link) wp-includes/link-template.php | Displays the adjacent post link. |
| [get\_previous\_post\_link()](get_previous_post_link) wp-includes/link-template.php | Retrieves the previous post link that is adjacent to the current post. |
| [get\_next\_post\_link()](get_next_post_link) wp-includes/link-template.php | Retrieves the next post link that is adjacent to the current post. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress tag_description( int $tag ): string tag\_description( int $tag ): string
====================================
Retrieves tag description.
`$tag` int Optional Tag ID. Defaults to the current tag ID. string Tag description, if available.
##### Usage:
```
$description = tag_description();
```
##### Notes:
Output is wrapped in <p> tags.
File: `wp-includes/category-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/category-template.php/)
```
function tag_description( $tag = 0 ) {
return term_description( $tag );
}
```
| Uses | Description |
| --- | --- |
| [term\_description()](term_description) wp-includes/category-template.php | Retrieves term description. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress list_core_update( object $update ) list\_core\_update( object $update )
====================================
Lists available core updates.
`$update` object Required File: `wp-admin/update-core.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/update-core.php/)
```
function list_core_update( $update ) {
global $wp_local_package, $wpdb;
static $first_pass = true;
$wp_version = get_bloginfo( 'version' );
$version_string = sprintf( '%s–%s', $update->current, get_locale() );
if ( 'en_US' === $update->locale && 'en_US' === get_locale() ) {
$version_string = $update->current;
} elseif ( 'en_US' === $update->locale && $update->packages->partial && $wp_version == $update->partial_version ) {
$updates = get_core_updates();
if ( $updates && 1 === count( $updates ) ) {
// If the only available update is a partial builds, it doesn't need a language-specific version string.
$version_string = $update->current;
}
} elseif ( 'en_US' === $update->locale && 'en_US' !== get_locale() ) {
$version_string = sprintf( '%s–%s', $update->current, $update->locale );
}
$current = false;
if ( ! isset( $update->response ) || 'latest' === $update->response ) {
$current = true;
}
$message = '';
$form_action = 'update-core.php?action=do-core-upgrade';
$php_version = PHP_VERSION;
$mysql_version = $wpdb->db_version();
$show_buttons = true;
// Nightly build versions have two hyphens and a commit number.
if ( preg_match( '/-\w+-\d+/', $update->current ) ) {
// Retrieve the major version number.
preg_match( '/^\d+.\d+/', $update->current, $update_major );
/* translators: %s: WordPress version. */
$submit = sprintf( __( 'Update to latest %s nightly' ), $update_major[0] );
} else {
/* translators: %s: WordPress version. */
$submit = sprintf( __( 'Update to version %s' ), $version_string );
}
if ( 'development' === $update->response ) {
$message = __( 'You can update to the latest nightly build manually:' );
} else {
if ( $current ) {
/* translators: %s: WordPress version. */
$submit = sprintf( __( 'Re-install version %s' ), $version_string );
$form_action = 'update-core.php?action=do-core-reinstall';
} else {
$php_compat = version_compare( $php_version, $update->php_version, '>=' );
if ( file_exists( WP_CONTENT_DIR . '/db.php' ) && empty( $wpdb->is_mysql ) ) {
$mysql_compat = true;
} else {
$mysql_compat = version_compare( $mysql_version, $update->mysql_version, '>=' );
}
$version_url = sprintf(
/* translators: %s: WordPress version. */
esc_url( __( 'https://wordpress.org/support/wordpress-version/version-%s/' ) ),
sanitize_title( $update->current )
);
$php_update_message = '</p><p>' . sprintf(
/* translators: %s: URL to Update PHP page. */
__( '<a href="%s">Learn more about updating PHP</a>.' ),
esc_url( wp_get_update_php_url() )
);
$annotation = wp_get_update_php_annotation();
if ( $annotation ) {
$php_update_message .= '</p><p><em>' . $annotation . '</em>';
}
if ( ! $mysql_compat && ! $php_compat ) {
$message = sprintf(
/* translators: 1: URL to WordPress release notes, 2: WordPress version number, 3: Minimum required PHP version number, 4: Minimum required MySQL version number, 5: Current PHP version number, 6: Current MySQL version number. */
__( 'You cannot update because <a href="%1$s">WordPress %2$s</a> requires PHP version %3$s or higher and MySQL version %4$s or higher. You are running PHP version %5$s and MySQL version %6$s.' ),
$version_url,
$update->current,
$update->php_version,
$update->mysql_version,
$php_version,
$mysql_version
) . $php_update_message;
} elseif ( ! $php_compat ) {
$message = sprintf(
/* translators: 1: URL to WordPress release notes, 2: WordPress version number, 3: Minimum required PHP version number, 4: Current PHP version number. */
__( 'You cannot update because <a href="%1$s">WordPress %2$s</a> requires PHP version %3$s or higher. You are running version %4$s.' ),
$version_url,
$update->current,
$update->php_version,
$php_version
) . $php_update_message;
} elseif ( ! $mysql_compat ) {
$message = sprintf(
/* translators: 1: URL to WordPress release notes, 2: WordPress version number, 3: Minimum required MySQL version number, 4: Current MySQL version number. */
__( 'You cannot update because <a href="%1$s">WordPress %2$s</a> requires MySQL version %3$s or higher. You are running version %4$s.' ),
$version_url,
$update->current,
$update->mysql_version,
$mysql_version
);
} else {
$message = sprintf(
/* translators: 1: Installed WordPress version number, 2: URL to WordPress release notes, 3: New WordPress version number, including locale if necessary. */
__( 'You can update from WordPress %1$s to <a href="%2$s">WordPress %3$s</a> manually:' ),
$wp_version,
$version_url,
$version_string
);
}
if ( ! $mysql_compat || ! $php_compat ) {
$show_buttons = false;
}
}
}
echo '<p>';
echo $message;
echo '</p>';
echo '<form method="post" action="' . esc_url( $form_action ) . '" name="upgrade" class="upgrade">';
wp_nonce_field( 'upgrade-core' );
echo '<p>';
echo '<input name="version" value="' . esc_attr( $update->current ) . '" type="hidden" />';
echo '<input name="locale" value="' . esc_attr( $update->locale ) . '" type="hidden" />';
if ( $show_buttons ) {
if ( $first_pass ) {
submit_button( $submit, $current ? '' : 'primary regular', 'upgrade', false );
$first_pass = false;
} else {
submit_button( $submit, '', 'upgrade', false );
}
}
if ( 'en_US' !== $update->locale ) {
if ( ! isset( $update->dismissed ) || ! $update->dismissed ) {
submit_button( __( 'Hide this update' ), '', 'dismiss', false );
} else {
submit_button( __( 'Bring back this update' ), '', 'undismiss', false );
}
}
echo '</p>';
if ( 'en_US' !== $update->locale && ( ! isset( $wp_local_package ) || $wp_local_package != $update->locale ) ) {
echo '<p class="hint">' . __( 'This localized version contains both the translation and various other localization fixes.' ) . '</p>';
} elseif ( 'en_US' === $update->locale && 'en_US' !== get_locale() && ( ! $update->packages->partial && $wp_version == $update->partial_version ) ) {
// Partial builds don't need language-specific warnings.
echo '<p class="hint">' . sprintf(
/* translators: %s: WordPress version. */
__( 'You are about to install WordPress %s <strong>in English (US)</strong>. There is a chance this update will break your translation. You may prefer to wait for the localized version to be released.' ),
'development' !== $update->response ? $update->current : ''
) . '</p>';
}
echo '</form>';
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_update\_php\_annotation()](wp_get_update_php_annotation) wp-includes/functions.php | Returns the default annotation for the web hosting altering the “Update PHP” page URL. |
| [wp\_get\_update\_php\_url()](wp_get_update_php_url) wp-includes/functions.php | Gets the URL to learn more about updating the PHP version the site is running on. |
| [get\_core\_updates()](get_core_updates) wp-admin/includes/update.php | Gets available core updates. |
| [submit\_button()](submit_button) wp-admin/includes/template.php | Echoes a submit button, with provided text and appropriate class(es). |
| [get\_locale()](get_locale) wp-includes/l10n.php | Retrieves the current locale. |
| [sanitize\_title()](sanitize_title) wp-includes/formatting.php | Sanitizes a string into a slug, which can be used in URLs or HTML attributes. |
| [wp\_nonce\_field()](wp_nonce_field) wp-includes/functions.php | Retrieves or display nonce hidden field for forms. |
| [wpdb::db\_version()](../classes/wpdb/db_version) wp-includes/class-wpdb.php | Retrieves the database server version. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [get\_bloginfo()](get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| Used By | Description |
| --- | --- |
| [dismissed\_updates()](dismissed_updates) wp-admin/update-core.php | Display dismissed updates. |
| [core\_upgrade\_preamble()](core_upgrade_preamble) wp-admin/update-core.php | Display upgrade WordPress for downloading latest or upgrading automatically form. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
| programming_docs |
wordpress get_default_feed(): string get\_default\_feed(): string
============================
Retrieves the default feed.
The default feed is ‘rss2’, unless a plugin changes it through the [‘default\_feed’](../hooks/default_feed) filter.
string Default feed, or for example `'rss2'`, `'atom'`, etc.
File: `wp-includes/feed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/feed.php/)
```
function get_default_feed() {
/**
* Filters the default feed type.
*
* @since 2.5.0
*
* @param string $feed_type Type of default feed. Possible values include 'rss2', 'atom'.
* Default 'rss2'.
*/
$default_feed = apply_filters( 'default_feed', 'rss2' );
return ( 'rss' === $default_feed ) ? 'rss2' : $default_feed;
}
```
[apply\_filters( 'default\_feed', string $feed\_type )](../hooks/default_feed)
Filters the default feed type.
| Uses | Description |
| --- | --- |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [feed\_links()](feed_links) wp-includes/general-template.php | Displays the links to the general feeds. |
| [WP::send\_headers()](../classes/wp/send_headers) wp-includes/class-wp.php | Sends additional HTTP headers for caching, content type, etc. |
| [WP\_Query::is\_feed()](../classes/wp_query/is_feed) wp-includes/class-wp-query.php | Is the query for a feed? |
| [do\_feed()](do_feed) wp-includes/functions.php | Loads the feed template from the use of an action hook. |
| [get\_search\_comments\_feed\_link()](get_search_comments_feed_link) wp-includes/link-template.php | Retrieves the permalink for the search results comments feed. |
| [get\_post\_type\_archive\_feed\_link()](get_post_type_archive_feed_link) wp-includes/link-template.php | Retrieves the permalink for a post type archive feed. |
| [get\_term\_feed\_link()](get_term_feed_link) wp-includes/link-template.php | Retrieves the feed link for a term. |
| [get\_search\_feed\_link()](get_search_feed_link) wp-includes/link-template.php | Retrieves the permalink for the search results feed. |
| [get\_feed\_link()](get_feed_link) wp-includes/link-template.php | Retrieves the permalink for the feed type. |
| [get\_post\_comments\_feed\_link()](get_post_comments_feed_link) wp-includes/link-template.php | Retrieves the permalink for the post comments feed. |
| [get\_author\_feed\_link()](get_author_feed_link) wp-includes/link-template.php | Retrieves the feed link for a given author. |
| [get\_the\_category\_rss()](get_the_category_rss) wp-includes/feed.php | Retrieves all of the post categories, formatted for use in feeds. |
| [feed\_content\_type()](feed_content_type) wp-includes/feed.php | Returns the content type for specified feed type. |
| [get\_the\_content\_feed()](get_the_content_feed) wp-includes/feed.php | Retrieves the post content for feeds. |
| [redirect\_canonical()](redirect_canonical) wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress get_bookmark_field( string $field, int $bookmark, string $context = 'display' ): string|WP_Error get\_bookmark\_field( string $field, int $bookmark, string $context = 'display' ): string|WP\_Error
===================================================================================================
Retrieves single bookmark data item or field.
`$field` string Required The name of the data field to return. `$bookmark` int Required The bookmark ID to get field. `$context` string Optional The context of how the field will be used. Default: `'display'`
string|[WP\_Error](../classes/wp_error)
File: `wp-includes/bookmark.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/bookmark.php/)
```
function get_bookmark_field( $field, $bookmark, $context = 'display' ) {
$bookmark = (int) $bookmark;
$bookmark = get_bookmark( $bookmark );
if ( is_wp_error( $bookmark ) ) {
return $bookmark;
}
if ( ! is_object( $bookmark ) ) {
return '';
}
if ( ! isset( $bookmark->$field ) ) {
return '';
}
return sanitize_bookmark_field( $field, $bookmark->$field, $bookmark->link_id, $context );
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_bookmark\_field()](sanitize_bookmark_field) wp-includes/bookmark.php | Sanitizes a bookmark field. |
| [get\_bookmark()](get_bookmark) wp-includes/bookmark.php | Retrieves bookmark data. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
wordpress get_metadata_default( string $meta_type, int $object_id, string $meta_key, bool $single = false ): mixed get\_metadata\_default( string $meta\_type, int $object\_id, string $meta\_key, bool $single = false ): mixed
=============================================================================================================
Retrieves default metadata value for the specified meta key and object.
By default, an empty string is returned if `$single` is true, or an empty array if it’s false.
`$meta_type` string Required Type of object metadata is for. Accepts `'post'`, `'comment'`, `'term'`, `'user'`, or any other object type with an associated meta table. `$object_id` int Required ID of the object metadata is for. `$meta_key` string Required Metadata key. `$single` bool Optional If true, return only the first value of the specified `$meta_key`.
This parameter has no effect if `$meta_key` is not specified. Default: `false`
mixed An array of default values if `$single` is false.
The default value of the meta field if `$single` is true.
File: `wp-includes/meta.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/meta.php/)
```
function get_metadata_default( $meta_type, $object_id, $meta_key, $single = false ) {
if ( $single ) {
$value = '';
} else {
$value = array();
}
/**
* Filters the default metadata value for a specified meta key and object.
*
* The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
* (post, comment, term, user, or any other type with an associated meta table).
*
* Possible filter names include:
*
* - `default_post_metadata`
* - `default_comment_metadata`
* - `default_term_metadata`
* - `default_user_metadata`
*
* @since 5.5.0
*
* @param mixed $value The value to return, either a single metadata value or an array
* of values depending on the value of `$single`.
* @param int $object_id ID of the object metadata is for.
* @param string $meta_key Metadata key.
* @param bool $single Whether to return only the first value of the specified `$meta_key`.
* @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
* or any other object type with an associated meta table.
*/
$value = apply_filters( "default_{$meta_type}_metadata", $value, $object_id, $meta_key, $single, $meta_type );
if ( ! $single && ! wp_is_numeric_array( $value ) ) {
$value = array( $value );
}
return $value;
}
```
[apply\_filters( "default\_{$meta\_type}\_metadata", mixed $value, int $object\_id, string $meta\_key, bool $single, string $meta\_type )](../hooks/default_meta_type_metadata)
Filters the default metadata value for a specified meta key and object.
| Uses | Description |
| --- | --- |
| [wp\_is\_numeric\_array()](wp_is_numeric_array) wp-includes/functions.php | Determines if the variable is a numeric-indexed array. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [get\_metadata()](get_metadata) wp-includes/meta.php | Retrieves the value of a metadata field for the specified object type and ID. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress wp_parse_str( string $string, array $array ) wp\_parse\_str( string $string, array $array )
==============================================
Parses a string into variables to be stored in an array.
`$string` string Required The string to be parsed. `$array` array Required Variables will be stored in this array. File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function wp_parse_str( $string, &$array ) {
parse_str( (string) $string, $array );
/**
* Filters the array of variables derived from a parsed string.
*
* @since 2.2.1
*
* @param array $array The array populated with variables.
*/
$array = apply_filters( 'wp_parse_str', $array );
}
```
[apply\_filters( 'wp\_parse\_str', array $array )](../hooks/wp_parse_str)
Filters the array of variables derived from a parsed string.
| Uses | Description |
| --- | --- |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Widgets\_Controller::get\_item\_schema()](../classes/wp_rest_widgets_controller/get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php | Retrieves the widget’s schema, conforming to JSON Schema. |
| [WP\_REST\_Widget\_Types\_Controller::register\_routes()](../classes/wp_rest_widget_types_controller/register_routes) wp-includes/rest-api/endpoints/class-wp-rest-widget-types-controller.php | Registers the widget type routes. |
| [WP\_REST\_Server::serve\_batch\_request\_v1()](../classes/wp_rest_server/serve_batch_request_v1) wp-includes/rest-api/class-wp-rest-server.php | Serves the batch/v1 request. |
| [WP\_REST\_Request::from\_url()](../classes/wp_rest_request/from_url) wp-includes/rest-api/class-wp-rest-request.php | Retrieves a [WP\_REST\_Request](../classes/wp_rest_request) object from a full URL. |
| [paginate\_links()](paginate_links) wp-includes/general-template.php | Retrieves paginated links for archive post pages. |
| [wp\_parse\_args()](wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [add\_query\_arg()](add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [wp\_style\_loader\_src()](wp_style_loader_src) wp-includes/script-loader.php | Administration Screen CSS for changing the styles. |
| Version | Description |
| --- | --- |
| [2.2.1](https://developer.wordpress.org/reference/since/2.2.1/) | Introduced. |
wordpress wp_ajax_ajax_tag_search() wp\_ajax\_ajax\_tag\_search()
=============================
Ajax handler for tag search.
File: `wp-admin/includes/ajax-actions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/ajax-actions.php/)
```
function wp_ajax_ajax_tag_search() {
if ( ! isset( $_GET['tax'] ) ) {
wp_die( 0 );
}
$taxonomy = sanitize_key( $_GET['tax'] );
$taxonomy_object = get_taxonomy( $taxonomy );
if ( ! $taxonomy_object ) {
wp_die( 0 );
}
if ( ! current_user_can( $taxonomy_object->cap->assign_terms ) ) {
wp_die( -1 );
}
$search = wp_unslash( $_GET['q'] );
$comma = _x( ',', 'tag delimiter' );
if ( ',' !== $comma ) {
$search = str_replace( $comma, ',', $search );
}
if ( false !== strpos( $search, ',' ) ) {
$search = explode( ',', $search );
$search = $search[ count( $search ) - 1 ];
}
$search = trim( $search );
/**
* Filters the minimum number of characters required to fire a tag search via Ajax.
*
* @since 4.0.0
*
* @param int $characters The minimum number of characters required. Default 2.
* @param WP_Taxonomy $taxonomy_object The taxonomy object.
* @param string $search The search term.
*/
$term_search_min_chars = (int) apply_filters( 'term_search_min_chars', 2, $taxonomy_object, $search );
/*
* Require $term_search_min_chars chars for matching (default: 2)
* ensure it's a non-negative, non-zero integer.
*/
if ( ( 0 == $term_search_min_chars ) || ( strlen( $search ) < $term_search_min_chars ) ) {
wp_die();
}
$results = get_terms(
array(
'taxonomy' => $taxonomy,
'name__like' => $search,
'fields' => 'names',
'hide_empty' => false,
'number' => isset( $_GET['number'] ) ? (int) $_GET['number'] : 0,
)
);
/**
* Filters the Ajax term search results.
*
* @since 6.1.0
*
* @param string[] $results Array of term names.
* @param WP_Taxonomy $taxonomy_object The taxonomy object.
* @param string $search The search term.
*/
$results = apply_filters( 'ajax_term_search_results', $results, $taxonomy_object, $search );
echo implode( "\n", $results );
wp_die();
}
```
[apply\_filters( 'ajax\_term\_search\_results', string[] $results, WP\_Taxonomy $taxonomy\_object, string $search )](../hooks/ajax_term_search_results)
Filters the Ajax term search results.
[apply\_filters( 'term\_search\_min\_chars', int $characters, WP\_Taxonomy $taxonomy\_object, string $search )](../hooks/term_search_min_chars)
Filters the minimum number of characters required to fire a tag search via Ajax.
| Uses | Description |
| --- | --- |
| [get\_terms()](get_terms) wp-includes/taxonomy.php | Retrieves the terms in a given taxonomy or list of taxonomies. |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_x()](_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [wp\_unslash()](wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [sanitize\_key()](sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [wp\_die()](wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [get\_taxonomy()](get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress user_can( int|WP_User $user, string $capability, mixed $args ): bool user\_can( int|WP\_User $user, string $capability, mixed $args ): bool
======================================================================
Returns whether a particular user has the specified capability.
This function also accepts an ID of an object to check against if the capability is a meta capability. Meta capabilities such as `edit_post` and `edit_user` are capabilities used by the `map_meta_cap()` function to map to primitive capabilities that a user or role has, such as `edit_posts` and `edit_others_posts`.
Example usage:
```
user_can( $user->ID, 'edit_posts' );
user_can( $user->ID, 'edit_post', $post->ID );
user_can( $user->ID, 'edit_post_meta', $post->ID, $meta_key );
```
`$user` int|[WP\_User](../classes/wp_user) Required User ID or object. `$capability` string Required Capability name. `$args` mixed Optional further parameters, typically starting with an object ID. bool Whether the user has the given capability.
File: `wp-includes/capabilities.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/capabilities.php/)
```
function user_can( $user, $capability, ...$args ) {
if ( ! is_object( $user ) ) {
$user = get_userdata( $user );
}
if ( empty( $user ) ) {
// User is logged out, create anonymous user object.
$user = new WP_User( 0 );
$user->init( new stdClass );
}
return $user->has_cap( $capability, ...$args );
}
```
| Uses | Description |
| --- | --- |
| [WP\_User::\_\_construct()](../classes/wp_user/__construct) wp-includes/class-wp-user.php | Constructor. |
| [get\_userdata()](get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](../classes/wp_rest_application_passwords_controller/get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [wp\_initialize\_site()](wp_initialize_site) wp-includes/ms-site.php | Runs the initialization routine for a given site. |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [map\_meta\_cap()](map_meta_cap) wp-includes/capabilities.php | Maps a capability to the primitive capabilities required of the given user to satisfy the capability being checked. |
| [wp\_notify\_postauthor()](wp_notify_postauthor) wp-includes/pluggable.php | Notifies an author (and/or others) of a comment/trackback/pingback on a post. |
| [wp\_notify\_moderator()](wp_notify_moderator) wp-includes/pluggable.php | Notifies the moderator of the site about a new comment that is awaiting approval. |
| [get\_allowed\_mime\_types()](get_allowed_mime_types) wp-includes/functions.php | Retrieves the list of allowed mime types and file extensions. |
| [get\_dashboard\_url()](get_dashboard_url) wp-includes/link-template.php | Retrieves the URL to the user’s dashboard. |
| [wp\_update\_comment()](wp_update_comment) wp-includes/comment.php | Updates an existing comment in the database. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Formalized the existing and already documented `...$args` parameter by adding it to the function signature. |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress wp_get_attachment_caption( int $post_id ): string|false wp\_get\_attachment\_caption( int $post\_id ): string|false
===========================================================
Retrieves the caption for an attachment.
`$post_id` int Optional Attachment ID. Default is the ID of the global `$post`. string|false Attachment caption on success, false on failure.
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function wp_get_attachment_caption( $post_id = 0 ) {
$post_id = (int) $post_id;
$post = get_post( $post_id );
if ( ! $post ) {
return false;
}
if ( 'attachment' !== $post->post_type ) {
return false;
}
$caption = $post->post_excerpt;
/**
* Filters the attachment caption.
*
* @since 4.6.0
*
* @param string $caption Caption for the given attachment.
* @param int $post_id Attachment ID.
*/
return apply_filters( 'wp_get_attachment_caption', $caption, $post->ID );
}
```
[apply\_filters( 'wp\_get\_attachment\_caption', string $caption, int $post\_id )](../hooks/wp_get_attachment_caption)
Filters the attachment caption.
| Uses | Description |
| --- | --- |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [get\_the\_post\_thumbnail\_caption()](get_the_post_thumbnail_caption) wp-includes/post-thumbnail-template.php | Returns the post thumbnail caption. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
| programming_docs |
wordpress update_network_option_new_admin_email( string $old_value, string $value ) update\_network\_option\_new\_admin\_email( string $old\_value, string $value )
===============================================================================
Sends a confirmation request email when a change of network admin email address is attempted.
The new network admin address will not become active until confirmed.
`$old_value` string Required The old network admin email address. `$value` string Required The proposed new network admin email address. File: `wp-includes/ms-functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-functions.php/)
```
function update_network_option_new_admin_email( $old_value, $value ) {
if ( get_site_option( 'admin_email' ) === $value || ! is_email( $value ) ) {
return;
}
$hash = md5( $value . time() . mt_rand() );
$new_admin_email = array(
'hash' => $hash,
'newemail' => $value,
);
update_site_option( 'network_admin_hash', $new_admin_email );
$switched_locale = switch_to_locale( get_user_locale() );
/* translators: Do not translate USERNAME, ADMIN_URL, EMAIL, SITENAME, SITEURL: those are placeholders. */
$email_text = __(
'Howdy ###USERNAME###,
You recently requested to have the network admin email address on
your network changed.
If this is correct, please click on the following link to change it:
###ADMIN_URL###
You can safely ignore and delete this email if you do not want to
take this action.
This email has been sent to ###EMAIL###
Regards,
All at ###SITENAME###
###SITEURL###'
);
/**
* Filters the text of the email sent when a change of network admin email address is attempted.
*
* The following strings have a special meaning and will get replaced dynamically:
* ###USERNAME### The current user's username.
* ###ADMIN_URL### The link to click on to confirm the email change.
* ###EMAIL### The proposed new network admin email address.
* ###SITENAME### The name of the network.
* ###SITEURL### The URL to the network.
*
* @since 4.9.0
*
* @param string $email_text Text in the email.
* @param array $new_admin_email {
* Data relating to the new network admin email address.
*
* @type string $hash The secure hash used in the confirmation link URL.
* @type string $newemail The proposed new network admin email address.
* }
*/
$content = apply_filters( 'new_network_admin_email_content', $email_text, $new_admin_email );
$current_user = wp_get_current_user();
$content = str_replace( '###USERNAME###', $current_user->user_login, $content );
$content = str_replace( '###ADMIN_URL###', esc_url( network_admin_url( 'settings.php?network_admin_hash=' . $hash ) ), $content );
$content = str_replace( '###EMAIL###', $value, $content );
$content = str_replace( '###SITENAME###', wp_specialchars_decode( get_site_option( 'site_name' ), ENT_QUOTES ), $content );
$content = str_replace( '###SITEURL###', network_home_url(), $content );
wp_mail(
$value,
sprintf(
/* translators: Email change notification email subject. %s: Network title. */
__( '[%s] Network Admin Email Change Request' ),
wp_specialchars_decode( get_site_option( 'site_name' ), ENT_QUOTES )
),
$content
);
if ( $switched_locale ) {
restore_previous_locale();
}
}
```
[apply\_filters( 'new\_network\_admin\_email\_content', string $email\_text, array $new\_admin\_email )](../hooks/new_network_admin_email_content)
Filters the text of the email sent when a change of network admin email address is attempted.
| Uses | Description |
| --- | --- |
| [restore\_previous\_locale()](restore_previous_locale) wp-includes/l10n.php | Restores the translations according to the previous locale. |
| [switch\_to\_locale()](switch_to_locale) wp-includes/l10n.php | Switches the translations according to the given locale. |
| [get\_user\_locale()](get_user_locale) wp-includes/l10n.php | Retrieves the locale of a user. |
| [is\_email()](is_email) wp-includes/formatting.php | Verifies that an email is valid. |
| [wp\_specialchars\_decode()](wp_specialchars_decode) wp-includes/formatting.php | Converts a number of HTML entities into their special characters. |
| [wp\_get\_current\_user()](wp_get_current_user) wp-includes/pluggable.php | Retrieves the current user object. |
| [wp\_mail()](wp_mail) wp-includes/pluggable.php | Sends an email, similar to PHP’s mail function. |
| [network\_admin\_url()](network_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the network. |
| [network\_home\_url()](network_home_url) wp-includes/link-template.php | Retrieves the home URL for the current network. |
| [update\_site\_option()](update_site_option) wp-includes/option.php | Updates the value of an option that was already added for the current network. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_site\_option()](get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress sanitize_term( array|object $term, string $taxonomy, string $context = 'display' ): array|object sanitize\_term( array|object $term, string $taxonomy, string $context = 'display' ): array|object
=================================================================================================
Sanitizes all term fields.
Relies on [sanitize\_term\_field()](sanitize_term_field) to sanitize the term. The difference is that this function will sanitize **all** fields. The context is based on [sanitize\_term\_field()](sanitize_term_field) .
The `$term` is expected to be either an array or an object.
`$term` array|object Required The term to check. `$taxonomy` string Required The taxonomy name to use. `$context` string Optional Context in which to sanitize the term.
Accepts `'raw'`, `'edit'`, `'db'`, `'display'`, `'rss'`, `'attribute'`, or `'js'`. Default `'display'`. Default: `'display'`
array|object Term with all fields sanitized.
File: `wp-includes/taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/taxonomy.php/)
```
function sanitize_term( $term, $taxonomy, $context = 'display' ) {
$fields = array( 'term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group', 'term_taxonomy_id', 'object_id' );
$do_object = is_object( $term );
$term_id = $do_object ? $term->term_id : ( isset( $term['term_id'] ) ? $term['term_id'] : 0 );
foreach ( (array) $fields as $field ) {
if ( $do_object ) {
if ( isset( $term->$field ) ) {
$term->$field = sanitize_term_field( $field, $term->$field, $term_id, $taxonomy, $context );
}
} else {
if ( isset( $term[ $field ] ) ) {
$term[ $field ] = sanitize_term_field( $field, $term[ $field ], $term_id, $taxonomy, $context );
}
}
}
if ( $do_object ) {
$term->filter = $context;
} else {
$term['filter'] = $context;
}
return $term;
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_term\_field()](sanitize_term_field) wp-includes/taxonomy.php | Sanitizes the field value in the term based on the context. |
| Used By | Description |
| --- | --- |
| [WP\_Term::filter()](../classes/wp_term/filter) wp-includes/class-wp-term.php | Sanitizes term fields, according to the filter type provided. |
| [WP\_Term::\_\_get()](../classes/wp_term/__get) wp-includes/class-wp-term.php | Getter. |
| [WP\_Term::get\_instance()](../classes/wp_term/get_instance) wp-includes/class-wp-term.php | Retrieve [WP\_Term](../classes/wp_term) instance. |
| [WP\_Terms\_List\_Table::single\_row()](../classes/wp_terms_list_table/single_row) wp-admin/includes/class-wp-terms-list-table.php | |
| [sanitize\_category()](sanitize_category) wp-includes/category.php | Sanitizes category data based on context. |
| [wp\_update\_term()](wp_update_term) wp-includes/taxonomy.php | Updates term based on arguments provided. |
| [wp\_insert\_term()](wp_insert_term) wp-includes/taxonomy.php | Adds a new term to the database. |
| [get\_term\_to\_edit()](get_term_to_edit) wp-includes/taxonomy.php | Sanitizes term for editing. |
| [get\_term()](get_term) wp-includes/taxonomy.php | Gets all term data from database by term ID. |
| Version | Description |
| --- | --- |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
wordpress wp_edit_posts_query( array|false $q = false ): array wp\_edit\_posts\_query( array|false $q = false ): array
=======================================================
Runs the query to fetch the posts for listing on the edit posts page.
`$q` array|false Optional Array of query variables to use to build the query.
Defaults to the `$_GET` superglobal. Default: `false`
array
File: `wp-admin/includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/post.php/)
```
function wp_edit_posts_query( $q = false ) {
if ( false === $q ) {
$q = $_GET;
}
$q['m'] = isset( $q['m'] ) ? (int) $q['m'] : 0;
$q['cat'] = isset( $q['cat'] ) ? (int) $q['cat'] : 0;
$post_stati = get_post_stati();
if ( isset( $q['post_type'] ) && in_array( $q['post_type'], get_post_types(), true ) ) {
$post_type = $q['post_type'];
} else {
$post_type = 'post';
}
$avail_post_stati = get_available_post_statuses( $post_type );
$post_status = '';
$perm = '';
if ( isset( $q['post_status'] ) && in_array( $q['post_status'], $post_stati, true ) ) {
$post_status = $q['post_status'];
$perm = 'readable';
}
$orderby = '';
if ( isset( $q['orderby'] ) ) {
$orderby = $q['orderby'];
} elseif ( isset( $q['post_status'] ) && in_array( $q['post_status'], array( 'pending', 'draft' ), true ) ) {
$orderby = 'modified';
}
$order = '';
if ( isset( $q['order'] ) ) {
$order = $q['order'];
} elseif ( isset( $q['post_status'] ) && 'pending' === $q['post_status'] ) {
$order = 'ASC';
}
$per_page = "edit_{$post_type}_per_page";
$posts_per_page = (int) get_user_option( $per_page );
if ( empty( $posts_per_page ) || $posts_per_page < 1 ) {
$posts_per_page = 20;
}
/**
* Filters the number of items per page to show for a specific 'per_page' type.
*
* The dynamic portion of the hook name, `$post_type`, refers to the post type.
*
* Possible hook names include:
*
* - `edit_post_per_page`
* - `edit_page_per_page`
* - `edit_attachment_per_page`
*
* @since 3.0.0
*
* @param int $posts_per_page Number of posts to display per page for the given post
* type. Default 20.
*/
$posts_per_page = apply_filters( "edit_{$post_type}_per_page", $posts_per_page );
/**
* Filters the number of posts displayed per page when specifically listing "posts".
*
* @since 2.8.0
*
* @param int $posts_per_page Number of posts to be displayed. Default 20.
* @param string $post_type The post type.
*/
$posts_per_page = apply_filters( 'edit_posts_per_page', $posts_per_page, $post_type );
$query = compact( 'post_type', 'post_status', 'perm', 'order', 'orderby', 'posts_per_page' );
// Hierarchical types require special args.
if ( is_post_type_hierarchical( $post_type ) && empty( $orderby ) ) {
$query['orderby'] = 'menu_order title';
$query['order'] = 'asc';
$query['posts_per_page'] = -1;
$query['posts_per_archive_page'] = -1;
$query['fields'] = 'id=>parent';
}
if ( ! empty( $q['show_sticky'] ) ) {
$query['post__in'] = (array) get_option( 'sticky_posts' );
}
wp( $query );
return $avail_post_stati;
}
```
[apply\_filters( 'edit\_posts\_per\_page', int $posts\_per\_page, string $post\_type )](../hooks/edit_posts_per_page)
Filters the number of posts displayed per page when specifically listing “posts”.
[apply\_filters( "edit\_{$post\_type}\_per\_page", int $posts\_per\_page )](../hooks/edit_post_type_per_page)
Filters the number of items per page to show for a specific ‘per\_page’ type.
| Uses | Description |
| --- | --- |
| [get\_available\_post\_statuses()](get_available_post_statuses) wp-admin/includes/post.php | Returns all the possible statuses for a post type. |
| [wp()](wp) wp-includes/functions.php | Sets up the WordPress query. |
| [get\_user\_option()](get_user_option) wp-includes/user.php | Retrieves user option that can be either per Site or per Network. |
| [get\_post\_stati()](get_post_stati) wp-includes/post.php | Gets a list of post statuses. |
| [is\_post\_type\_hierarchical()](is_post_type_hierarchical) wp-includes/post.php | Determines whether the post type is hierarchical. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [get\_post\_types()](get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| Used By | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::prepare\_items()](../classes/wp_posts_list_table/prepare_items) wp-admin/includes/class-wp-posts-list-table.php | |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress grant_super_admin( int $user_id ): bool grant\_super\_admin( int $user\_id ): bool
==========================================
Grants Super Admin privileges.
`$user_id` int Required ID of the user to be granted Super Admin privileges. bool True on success, false on failure. This can fail when the user is already a super admin or when the `$super_admins` global is defined.
Grants super admin privileges:
`grant_super_admin( $user_id );`
File: `wp-includes/capabilities.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/capabilities.php/)
```
function grant_super_admin( $user_id ) {
// If global super_admins override is defined, there is nothing to do here.
if ( isset( $GLOBALS['super_admins'] ) || ! is_multisite() ) {
return false;
}
/**
* Fires before the user is granted Super Admin privileges.
*
* @since 3.0.0
*
* @param int $user_id ID of the user that is about to be granted Super Admin privileges.
*/
do_action( 'grant_super_admin', $user_id );
// Directly fetch site_admins instead of using get_super_admins().
$super_admins = get_site_option( 'site_admins', array( 'admin' ) );
$user = get_userdata( $user_id );
if ( $user && ! in_array( $user->user_login, $super_admins, true ) ) {
$super_admins[] = $user->user_login;
update_site_option( 'site_admins', $super_admins );
/**
* Fires after the user is granted Super Admin privileges.
*
* @since 3.0.0
*
* @param int $user_id ID of the user that was granted Super Admin privileges.
*/
do_action( 'granted_super_admin', $user_id );
return true;
}
return false;
}
```
[do\_action( 'granted\_super\_admin', int $user\_id )](../hooks/granted_super_admin)
Fires after the user is granted Super Admin privileges.
[do\_action( 'grant\_super\_admin', int $user\_id )](../hooks/grant_super_admin)
Fires before the user is granted Super Admin privileges.
| Uses | Description |
| --- | --- |
| [update\_site\_option()](update_site_option) wp-includes/option.php | Updates the value of an option that was already added for the current network. |
| [get\_userdata()](get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [is\_multisite()](is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_site\_option()](get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress get_the_author_posts(): int get\_the\_author\_posts(): int
==============================
Retrieves the number of posts by the author of the current post.
int The number of posts by the author.
File: `wp-includes/author-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/author-template.php/)
```
function get_the_author_posts() {
$post = get_post();
if ( ! $post ) {
return 0;
}
return count_user_posts( $post->post_author, $post->post_type );
}
```
| Uses | Description |
| --- | --- |
| [count\_user\_posts()](count_user_posts) wp-includes/user.php | Gets the number of posts a user has written. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [the\_author\_posts()](the_author_posts) wp-includes/author-template.php | Displays the number of posts by the author of the current post. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_json_file_decode( string $filename, array $options = array() ): mixed wp\_json\_file\_decode( string $filename, array $options = array() ): mixed
===========================================================================
Reads and decodes a JSON file.
`$filename` string Required Path to the JSON file. `$options` array Optional Options to be used with `json_decode()`.
* `associative`boolOptional. When `true`, JSON objects will be returned as associative arrays.
When `false`, JSON objects will be returned as objects.
Default: `array()`
mixed Returns the value encoded in JSON in appropriate PHP type.
`null` is returned if the file is not found, or its content can't be decoded.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function wp_json_file_decode( $filename, $options = array() ) {
$result = null;
$filename = wp_normalize_path( realpath( $filename ) );
if ( ! $filename ) {
trigger_error(
sprintf(
/* translators: %s: Path to the JSON file. */
__( "File %s doesn't exist!" ),
$filename
)
);
return $result;
}
$options = wp_parse_args( $options, array( 'associative' => false ) );
$decoded_file = json_decode( file_get_contents( $filename ), $options['associative'] );
if ( JSON_ERROR_NONE !== json_last_error() ) {
trigger_error(
sprintf(
/* translators: 1: Path to the JSON file, 2: Error message. */
__( 'Error when decoding a JSON file at path %1$s: %2$s' ),
$filename,
json_last_error_msg()
)
);
return $result;
}
return $decoded_file;
}
```
| Uses | Description |
| --- | --- |
| [wp\_normalize\_path()](wp_normalize_path) wp-includes/functions.php | Normalizes a filesystem path. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_parse\_args()](wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Used By | Description |
| --- | --- |
| [WP\_Theme\_JSON\_Resolver::get\_style\_variations()](../classes/wp_theme_json_resolver/get_style_variations) wp-includes/class-wp-theme-json-resolver.php | Returns the style variations defined by the theme. |
| [get\_block\_metadata\_i18n\_schema()](get_block_metadata_i18n_schema) wp-includes/blocks.php | Gets i18n schema for block’s metadata read from `block.json` file. |
| [WP\_Theme\_JSON\_Resolver::read\_json\_file()](../classes/wp_theme_json_resolver/read_json_file) wp-includes/class-wp-theme-json-resolver.php | Processes a file that adheres to the theme.json schema and returns an array with its contents, or a void array if none found. |
| [WP\_Theme\_JSON\_Resolver::translate()](../classes/wp_theme_json_resolver/translate) wp-includes/class-wp-theme-json-resolver.php | Given a theme.json structure modifies it in place to update certain values by its translated strings according to the language set by the user. |
| [register\_block\_type\_from\_metadata()](register_block_type_from_metadata) wp-includes/blocks.php | Registers a block type from the metadata stored in the `block.json` file. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
| programming_docs |
wordpress wp_meta() wp\_meta()
==========
Theme container function for the ‘wp\_meta’ action.
The [‘wp\_meta’](../hooks/wp_meta) action can have several purposes, depending on how you use it, but one purpose might have been to allow for theme switching.
* By default, `wp meta()` is called immediately after [`wp_loginout()`](wp_loginout) by `sidebar.php` and the Meta widget, allowing functions to add new list items to the widget.
* As the `get_sidebar( $name );` function has the `do_action( 'get_sidebar', $name );` on top before it loads the sidebar file, this hook should be used to load stuff *before* the sidebar and `wp_meta();` should be called at the end of the sidebar template to allow adding callbacks after the sidebar.
File: `wp-includes/general-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/general-template.php/)
```
function wp_meta() {
/**
* Fires before displaying echoed content in the sidebar.
*
* @since 1.5.0
*/
do_action( 'wp_meta' );
}
```
[do\_action( 'wp\_meta' )](../hooks/wp_meta)
Fires before displaying echoed content in the sidebar.
| Uses | Description |
| --- | --- |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [WP\_Widget\_Meta::widget()](../classes/wp_widget_meta/widget) wp-includes/widgets/class-wp-widget-meta.php | Outputs the content for the current Meta widget instance. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress _build_block_template_result_from_post( WP_Post $post ): WP_Block_Template|WP_Error \_build\_block\_template\_result\_from\_post( WP\_Post $post ): WP\_Block\_Template|WP\_Error
=============================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Builds a unified template object based a post Object.
`$post` [WP\_Post](../classes/wp_post) Required Template post. [WP\_Block\_Template](../classes/wp_block_template)|[WP\_Error](../classes/wp_error) Template.
File: `wp-includes/block-template-utils.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/block-template-utils.php/)
```
function _build_block_template_result_from_post( $post ) {
$default_template_types = get_default_block_template_types();
$terms = get_the_terms( $post, 'wp_theme' );
if ( is_wp_error( $terms ) ) {
return $terms;
}
if ( ! $terms ) {
return new WP_Error( 'template_missing_theme', __( 'No theme is defined for this template.' ) );
}
$theme = $terms[0]->name;
$template_file = _get_block_template_file( $post->post_type, $post->post_name );
$has_theme_file = wp_get_theme()->get_stylesheet() === $theme && null !== $template_file;
$origin = get_post_meta( $post->ID, 'origin', true );
$is_wp_suggestion = get_post_meta( $post->ID, 'is_wp_suggestion', true );
$template = new WP_Block_Template();
$template->wp_id = $post->ID;
$template->id = $theme . '//' . $post->post_name;
$template->theme = $theme;
$template->content = $post->post_content;
$template->slug = $post->post_name;
$template->source = 'custom';
$template->origin = ! empty( $origin ) ? $origin : null;
$template->type = $post->post_type;
$template->description = $post->post_excerpt;
$template->title = $post->post_title;
$template->status = $post->post_status;
$template->has_theme_file = $has_theme_file;
$template->is_custom = empty( $is_wp_suggestion );
$template->author = $post->post_author;
if ( 'wp_template' === $post->post_type && $has_theme_file && isset( $template_file['postTypes'] ) ) {
$template->post_types = $template_file['postTypes'];
}
if ( 'wp_template' === $post->post_type && isset( $default_template_types[ $template->slug ] ) ) {
$template->is_custom = false;
}
if ( 'wp_template_part' === $post->post_type ) {
$type_terms = get_the_terms( $post, 'wp_template_part_area' );
if ( ! is_wp_error( $type_terms ) && false !== $type_terms ) {
$template->area = $type_terms[0]->name;
}
}
// Check for a block template without a description and title or with a title equal to the slug.
if ( 'wp_template' === $post->post_type && empty( $template->description ) && ( empty( $template->title ) || $template->title === $template->slug ) ) {
$matches = array();
// Check for a block template for a single author, page, post, tag, category, custom post type, or custom taxonomy.
if ( preg_match( '/(author|page|single|tag|category|taxonomy)-(.+)/', $template->slug, $matches ) ) {
$type = $matches[1];
$slug_remaining = $matches[2];
switch ( $type ) {
case 'author':
$nice_name = $slug_remaining;
$users = get_users(
array(
'capability' => 'edit_posts',
'search' => $nice_name,
'search_columns' => array( 'user_nicename' ),
'fields' => 'display_name',
)
);
if ( empty( $users ) ) {
$template->title = sprintf(
/* translators: Custom template title in the Site Editor, referencing a deleted author. %s: Author nicename. */
__( 'Deleted author: %s' ),
$nice_name
);
} else {
$author_name = $users[0];
$template->title = sprintf(
/* translators: Custom template title in the Site Editor. %s: Author name. */
__( 'Author: %s' ),
$author_name
);
$template->description = sprintf(
/* translators: Custom template description in the Site Editor. %s: Author name. */
__( 'Template for %s' ),
$author_name
);
$users_with_same_name = get_users(
array(
'capability' => 'edit_posts',
'search' => $author_name,
'search_columns' => array( 'display_name' ),
'fields' => 'display_name',
)
);
if ( count( $users_with_same_name ) > 1 ) {
$template->title = sprintf(
/* translators: Custom template title in the Site Editor. 1: Template title of an author template, 2: Author nicename. */
__( '%1$s (%2$s)' ),
$template->title,
$nice_name
);
}
}
break;
case 'page':
_wp_build_title_and_description_for_single_post_type_block_template( 'page', $slug_remaining, $template );
break;
case 'single':
$post_types = get_post_types();
foreach ( $post_types as $post_type ) {
$post_type_length = strlen( $post_type ) + 1;
// If $slug_remaining starts with $post_type followed by a hyphen.
if ( 0 === strncmp( $slug_remaining, $post_type . '-', $post_type_length ) ) {
$slug = substr( $slug_remaining, $post_type_length, strlen( $slug_remaining ) );
$found = _wp_build_title_and_description_for_single_post_type_block_template( $post_type, $slug, $template );
if ( $found ) {
break;
}
}
}
break;
case 'tag':
_wp_build_title_and_description_for_taxonomy_block_template( 'post_tag', $slug_remaining, $template );
break;
case 'category':
_wp_build_title_and_description_for_taxonomy_block_template( 'category', $slug_remaining, $template );
break;
case 'taxonomy':
$taxonomies = get_taxonomies();
foreach ( $taxonomies as $taxonomy ) {
$taxonomy_length = strlen( $taxonomy ) + 1;
// If $slug_remaining starts with $taxonomy followed by a hyphen.
if ( 0 === strncmp( $slug_remaining, $taxonomy . '-', $taxonomy_length ) ) {
$slug = substr( $slug_remaining, $taxonomy_length, strlen( $slug_remaining ) );
$found = _wp_build_title_and_description_for_taxonomy_block_template( $taxonomy, $slug, $template );
if ( $found ) {
break;
}
}
}
break;
}
}
}
return $template;
}
```
| Uses | Description |
| --- | --- |
| [\_wp\_build\_title\_and\_description\_for\_single\_post\_type\_block\_template()](_wp_build_title_and_description_for_single_post_type_block_template) wp-includes/block-template-utils.php | Builds the title and description of a post-specific template based on the underlying referenced post. |
| [\_wp\_build\_title\_and\_description\_for\_taxonomy\_block\_template()](_wp_build_title_and_description_for_taxonomy_block_template) wp-includes/block-template-utils.php | Builds the title and description of a taxonomy-specific template based on the underlying entity referenced. |
| [get\_default\_block\_template\_types()](get_default_block_template_types) wp-includes/block-template-utils.php | Returns a filtered list of default template types, containing their localized titles and descriptions. |
| [\_get\_block\_template\_file()](_get_block_template_file) wp-includes/block-template-utils.php | Retrieves the template file from the theme for a given slug. |
| [get\_the\_terms()](get_the_terms) wp-includes/category-template.php | Retrieves the terms of the taxonomy that are attached to the post. |
| [WP\_Theme::get\_stylesheet()](../classes/wp_theme/get_stylesheet) wp-includes/class-wp-theme.php | Returns the directory name of the theme’s “stylesheet” files, inside the theme root. |
| [get\_taxonomies()](get_taxonomies) wp-includes/taxonomy.php | Retrieves a list of registered taxonomy names or objects. |
| [get\_users()](get_users) wp-includes/user.php | Retrieves list of users matching criteria. |
| [wp\_get\_theme()](wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../classes/wp_theme) object for a theme. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_post\_meta()](get_post_meta) wp-includes/post.php | Retrieves a post meta field for the given post ID. |
| [get\_post\_types()](get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../classes/wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [get\_block\_templates()](get_block_templates) wp-includes/block-template-utils.php | Retrieves a list of unified template objects based on a query. |
| [get\_block\_template()](get_block_template) wp-includes/block-template-utils.php | Retrieves a single unified template object using its id. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress wp_edit_attachments_query_vars( array|false $q = false ): array wp\_edit\_attachments\_query\_vars( array|false $q = false ): array
===================================================================
Returns the query variables for the current attachments request.
`$q` array|false Optional Array of query variables to use to build the query.
Defaults to the `$_GET` superglobal. Default: `false`
array The parsed query vars.
File: `wp-admin/includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/post.php/)
```
function wp_edit_attachments_query_vars( $q = false ) {
if ( false === $q ) {
$q = $_GET;
}
$q['m'] = isset( $q['m'] ) ? (int) $q['m'] : 0;
$q['cat'] = isset( $q['cat'] ) ? (int) $q['cat'] : 0;
$q['post_type'] = 'attachment';
$post_type = get_post_type_object( 'attachment' );
$states = 'inherit';
if ( current_user_can( $post_type->cap->read_private_posts ) ) {
$states .= ',private';
}
$q['post_status'] = isset( $q['status'] ) && 'trash' === $q['status'] ? 'trash' : $states;
$q['post_status'] = isset( $q['attachment-filter'] ) && 'trash' === $q['attachment-filter'] ? 'trash' : $states;
$media_per_page = (int) get_user_option( 'upload_per_page' );
if ( empty( $media_per_page ) || $media_per_page < 1 ) {
$media_per_page = 20;
}
/**
* Filters the number of items to list per page when listing media items.
*
* @since 2.9.0
*
* @param int $media_per_page Number of media to list. Default 20.
*/
$q['posts_per_page'] = apply_filters( 'upload_per_page', $media_per_page );
$post_mime_types = get_post_mime_types();
if ( isset( $q['post_mime_type'] ) && ! array_intersect( (array) $q['post_mime_type'], array_keys( $post_mime_types ) ) ) {
unset( $q['post_mime_type'] );
}
foreach ( array_keys( $post_mime_types ) as $type ) {
if ( isset( $q['attachment-filter'] ) && "post_mime_type:$type" === $q['attachment-filter'] ) {
$q['post_mime_type'] = $type;
break;
}
}
if ( isset( $q['detached'] ) || ( isset( $q['attachment-filter'] ) && 'detached' === $q['attachment-filter'] ) ) {
$q['post_parent'] = 0;
}
if ( isset( $q['mine'] ) || ( isset( $q['attachment-filter'] ) && 'mine' === $q['attachment-filter'] ) ) {
$q['author'] = get_current_user_id();
}
// Filter query clauses to include filenames.
if ( isset( $q['s'] ) ) {
add_filter( 'wp_allow_query_attachment_by_filename', '__return_true' );
}
return $q;
}
```
[apply\_filters( 'upload\_per\_page', int $media\_per\_page )](../hooks/upload_per_page)
Filters the number of items to list per page when listing media items.
| Uses | Description |
| --- | --- |
| [get\_user\_option()](get_user_option) wp-includes/user.php | Retrieves user option that can be either per Site or per Network. |
| [get\_post\_mime\_types()](get_post_mime_types) wp-includes/post.php | Gets default post mime types. |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [add\_filter()](add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [get\_current\_user\_id()](get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [get\_post\_type\_object()](get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Used By | Description |
| --- | --- |
| [wp\_edit\_attachments\_query()](wp_edit_attachments_query) wp-admin/includes/post.php | Executes a query for attachments. An array of [WP\_Query](../classes/wp_query) arguments can be passed in, which will override the arguments set by this function. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress get_page( int|WP_Post $page, string $output = OBJECT, string $filter = 'raw' ): WP_Post|array|null get\_page( int|WP\_Post $page, string $output = OBJECT, string $filter = 'raw' ): WP\_Post|array|null
=====================================================================================================
This function has been deprecated. Use [get\_post()](get_post) instead.
Retrieves page data given a page ID or page object.
Use [get\_post()](get_post) instead of [get\_page()](get_page) .
`$page` int|[WP\_Post](../classes/wp_post) Required Page object or page ID. Passed by reference. `$output` string Optional The required return type. One of OBJECT, ARRAY\_A, or ARRAY\_N, which correspond to a [WP\_Post](../classes/wp_post) object, an associative array, or a numeric array, respectively. Default: `OBJECT`
`$filter` string Optional How the return value should be filtered. Accepts `'raw'`, `'edit'`, `'db'`, `'display'`. Default `'raw'`. Default: `'raw'`
[WP\_Post](../classes/wp_post)|array|null [WP\_Post](../classes/wp_post) or array on success, null on failure.
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function get_page( $page, $output = OBJECT, $filter = 'raw' ) {
return get_post( $page, $output, $filter );
}
```
| Uses | Description |
| --- | --- |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Use [get\_post()](get_post) |
| [1.5.1](https://developer.wordpress.org/reference/since/1.5.1/) | Introduced. |
wordpress get_comment_count( int $post_id ): int[] get\_comment\_count( int $post\_id ): int[]
===========================================
Retrieves the total comment counts for the whole site or a single post.
`$post_id` int Optional Restrict the comment counts to the given post. Default 0, which indicates that comment counts for the whole site will be retrieved. int[] The number of comments keyed by their status.
* `approved`intThe number of approved comments.
* `awaiting_moderation`intThe number of comments awaiting moderation (a.k.a. pending).
* `spam`intThe number of spam comments.
* `trash`intThe number of trashed comments.
* `post-trashed`intThe number of comments for posts that are in the trash.
* `total_comments`intThe total number of non-trashed comments, including spam.
* `all`intThe total number of pending or approved comments.
File: `wp-includes/comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/comment.php/)
```
function get_comment_count( $post_id = 0 ) {
$post_id = (int) $post_id;
$comment_count = array(
'approved' => 0,
'awaiting_moderation' => 0,
'spam' => 0,
'trash' => 0,
'post-trashed' => 0,
'total_comments' => 0,
'all' => 0,
);
$args = array(
'count' => true,
'update_comment_meta_cache' => false,
);
if ( $post_id > 0 ) {
$args['post_id'] = $post_id;
}
$mapping = array(
'approved' => 'approve',
'awaiting_moderation' => 'hold',
'spam' => 'spam',
'trash' => 'trash',
'post-trashed' => 'post-trashed',
);
$comment_count = array();
foreach ( $mapping as $key => $value ) {
$comment_count[ $key ] = get_comments( array_merge( $args, array( 'status' => $value ) ) );
}
$comment_count['all'] = $comment_count['approved'] + $comment_count['awaiting_moderation'];
$comment_count['total_comments'] = $comment_count['all'] + $comment_count['spam'];
return array_map( 'intval', $comment_count );
}
```
| Uses | Description |
| --- | --- |
| [get\_comments()](get_comments) wp-includes/comment.php | Retrieves a list of comments. |
| Used By | Description |
| --- | --- |
| [wp\_count\_comments()](wp_count_comments) wp-includes/comment.php | Retrieves the total comment counts for the whole site or a single post. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress get_posts( array $args = null ): WP_Post[]|int[] get\_posts( array $args = null ): WP\_Post[]|int[]
==================================================
Retrieves an array of the latest posts, or posts matching the given criteria.
For more information on the accepted arguments, see the [WP\_Query](../classes/wp_query) documentation in the Developer Handbook.
The `$ignore_sticky_posts` and `$no_found_rows` arguments are ignored by this function and both are set to `true`.
The defaults are as follows:
* [WP\_Query](../classes/wp_query)
* [WP\_Query::parse\_query()](../classes/wp_query/parse_query)
`$args` array Optional Arguments to retrieve posts. See [WP\_Query::parse\_query()](../classes/wp_query/parse_query) for all available arguments.
* `numberposts`intTotal number of posts to retrieve. Is an alias of `$posts_per_page` in [WP\_Query](../classes/wp_query). Accepts -1 for all. Default 5.
* `category`int|stringCategory ID or comma-separated list of IDs (this or any children).
Is an alias of `$cat` in [WP\_Query](../classes/wp_query). Default 0.
* `include`int[]An array of post IDs to retrieve, sticky posts will be included.
Is an alias of `$post__in` in [WP\_Query](../classes/wp_query). Default empty array.
* `exclude`int[]An array of post IDs not to retrieve. Default empty array.
* `suppress_filters`boolWhether to suppress filters. Default true.
More Arguments from WP\_Query::parse\_query( ... $query ) Array or string of Query parameters.
* `attachment_id`intAttachment post ID. Used for `'attachment'` post\_type.
* `author`int|stringAuthor ID, or comma-separated list of IDs.
* `author_name`stringUser `'user_nicename'`.
* `author__in`int[]An array of author IDs to query from.
* `author__not_in`int[]An array of author IDs not to query from.
* `cache_results`boolWhether to cache post information. Default true.
* `cat`int|stringCategory ID or comma-separated list of IDs (this or any children).
* `category__and`int[]An array of category IDs (AND in).
* `category__in`int[]An array of category IDs (OR in, no children).
* `category__not_in`int[]An array of category IDs (NOT in).
* `category_name`stringUse category slug (not name, this or any children).
* `comment_count`array|intFilter results by comment count. Provide an integer to match comment count exactly. Provide an array with integer `'value'` and `'compare'` operator (`'='`, `'!='`, `'>'`, `'>='`, `'<'`, `'<='` ) to compare against comment\_count in a specific way.
* `comment_status`stringComment status.
* `comments_per_page`intThe number of comments to return per page.
Default `'comments_per_page'` option.
* `date_query`arrayAn associative array of [WP\_Date\_Query](../classes/wp_date_query) arguments.
See [WP\_Date\_Query::\_\_construct()](../classes/wp_date_query/__construct).
* `day`intDay of the month. Accepts numbers 1-31.
* `exact`boolWhether to search by exact keyword. Default false.
* `fields`stringPost fields to query for. Accepts:
+ `''` Returns an array of complete post objects (`WP_Post[]`).
+ `'ids'` Returns an array of post IDs (`int[]`).
+ `'id=>parent'` Returns an associative array of parent post IDs, keyed by post ID (`int[]`). Default `''`.
* `hour`intHour of the day. Accepts numbers 0-23.
* `ignore_sticky_posts`int|boolWhether to ignore sticky posts or not. Setting this to false excludes stickies from `'post__in'`. Accepts `1|true`, `0|false`.
Default false.
* `m`intCombination YearMonth. Accepts any four-digit year and month numbers 01-12.
* `meta_key`string|string[]Meta key or keys to filter by.
* `meta_value`string|string[]Meta value or values to filter by.
* `meta_compare`stringMySQL operator used for comparing the meta value.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values and default value.
* `meta_compare_key`stringMySQL operator used for comparing the meta key.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values and default value.
* `meta_type`stringMySQL data type that the meta\_value column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values and default value.
* `meta_type_key`stringMySQL data type that the meta\_key column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values and default value.
* `meta_query`arrayAn associative array of [WP\_Meta\_Query](../classes/wp_meta_query) arguments.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values.
* `menu_order`intThe menu order of the posts.
* `minute`intMinute of the hour. Accepts numbers 0-59.
* `monthnum`intThe two-digit month. Accepts numbers 1-12.
* `name`stringPost slug.
* `nopaging`boolShow all posts (true) or paginate (false). Default false.
* `no_found_rows`boolWhether to skip counting the total rows found. Enabling can improve performance. Default false.
* `offset`intThe number of posts to offset before retrieval.
* `order`stringDesignates ascending or descending order of posts. Default `'DESC'`.
Accepts `'ASC'`, `'DESC'`.
* `orderby`string|arraySort retrieved posts by parameter. One or more options may be passed.
To use `'meta_value'`, or `'meta_value_num'`, `'meta_key=keyname'` must be also be defined. To sort by a specific `$meta_query` clause, use that clause's array key. Accepts:
+ `'none'`
+ `'name'`
+ `'author'`
+ `'date'`
+ `'title'`
+ `'modified'`
+ `'menu_order'`
+ `'parent'`
+ `'ID'`
+ `'rand'`
+ `'relevance'`
+ `'RAND(x)'` (where `'x'` is an integer seed value)
+ `'comment_count'`
+ `'meta_value'`
+ `'meta_value_num'`
+ `'post__in'`
+ `'post_name__in'`
+ `'post_parent__in'`
+ The array keys of `$meta_query`. Default is `'date'`, except when a search is being performed, when the default is `'relevance'`.
* `p`intPost ID.
* `page`intShow the number of posts that would show up on page X of a static front page.
* `paged`intThe number of the current page.
* `page_id`intPage ID.
* `pagename`stringPage slug.
* `perm`stringShow posts if user has the appropriate capability.
* `ping_status`stringPing status.
* `post__in`int[]An array of post IDs to retrieve, sticky posts will be included.
* `post__not_in`int[]An array of post IDs not to retrieve. Note: a string of comma- separated IDs will NOT work.
* `post_mime_type`stringThe mime type of the post. Used for `'attachment'` post\_type.
* `post_name__in`string[]An array of post slugs that results must match.
* `post_parent`intPage ID to retrieve child pages for. Use 0 to only retrieve top-level pages.
* `post_parent__in`int[]An array containing parent page IDs to query child pages from.
* `post_parent__not_in`int[]An array containing parent page IDs not to query child pages from.
* `post_type`string|string[]A post type slug (string) or array of post type slugs.
Default `'any'` if using `'tax_query'`.
* `post_status`string|string[]A post status (string) or array of post statuses.
* `posts_per_page`intThe number of posts to query for. Use -1 to request all posts.
* `posts_per_archive_page`intThe number of posts to query for by archive page. Overrides `'posts_per_page'` when [is\_archive()](is_archive) , or [is\_search()](is_search) are true.
* `s`stringSearch keyword(s). Prepending a term with a hyphen will exclude posts matching that term. Eg, 'pillow -sofa' will return posts containing `'pillow'` but not `'sofa'`. The character used for exclusion can be modified using the the `'wp_query_search_exclusion_prefix'` filter.
* `second`intSecond of the minute. Accepts numbers 0-59.
* `sentence`boolWhether to search by phrase. Default false.
* `suppress_filters`boolWhether to suppress filters. Default false.
* `tag`stringTag slug. Comma-separated (either), Plus-separated (all).
* `tag__and`int[]An array of tag IDs (AND in).
* `tag__in`int[]An array of tag IDs (OR in).
* `tag__not_in`int[]An array of tag IDs (NOT in).
* `tag_id`intTag id or comma-separated list of IDs.
* `tag_slug__and`string[]An array of tag slugs (AND in).
* `tag_slug__in`string[]An array of tag slugs (OR in). unless `'ignore_sticky_posts'` is true. Note: a string of comma-separated IDs will NOT work.
* `tax_query`arrayAn associative array of [WP\_Tax\_Query](../classes/wp_tax_query) arguments.
See [WP\_Tax\_Query::\_\_construct()](../classes/wp_tax_query/__construct).
* `title`stringPost title.
* `update_post_meta_cache`boolWhether to update the post meta cache. Default true.
* `update_post_term_cache`boolWhether to update the post term cache. Default true.
* `update_menu_item_cache`boolWhether to update the menu item cache. Default false.
* `lazy_load_term_meta`boolWhether to lazy-load term meta. Setting to false will disable cache priming for term meta, so that each [get\_term\_meta()](get_term_meta) call will hit the database.
Defaults to the value of `$update_post_term_cache`.
* `w`intThe week number of the year. Accepts numbers 0-53.
* `year`intThe four-digit year. Accepts any four-digit year.
Default: `null`
[WP\_Post](../classes/wp_post)[]|int[] Array of post objects or post IDs.
The most appropriate use for get\_posts is to create an array of posts based on a set of parameters. It retrieves a list of recent posts or posts matching this criteria. get\_posts can also be used to create Multiple Loops, though a more direct reference to [WP\_Query](../classes/wp_query) using new [WP\_Query](../classes/wp_query) is preferred in this case.
The parameters of get\_posts are similar to those of get\_pages but are implemented quite differently, and should be used in appropriate scenarios. get\_posts uses [WP\_Query](../classes/wp_query), whereas get\_pages queries the database more directly. Each have parameters that reflect this difference in implementation.
query\_posts also uses [WP\_Query](../classes/wp_query), but is not recommended because it directly alters the main loop by changing the variables of the global variable $wp\_query. get\_posts, on the other hand, simply references a new [WP\_Query](../classes/wp_query) object, and therefore does not affect or alter the main loop.
If you would like to alter the main query before it is executed, you can hook into it using pre\_get\_posts. If you would just like to call an array of posts based on a small and simple set of parameters within a page, then get\_posts is your best option.
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function get_posts( $args = null ) {
$defaults = array(
'numberposts' => 5,
'category' => 0,
'orderby' => 'date',
'order' => 'DESC',
'include' => array(),
'exclude' => array(),
'meta_key' => '',
'meta_value' => '',
'post_type' => 'post',
'suppress_filters' => true,
);
$parsed_args = wp_parse_args( $args, $defaults );
if ( empty( $parsed_args['post_status'] ) ) {
$parsed_args['post_status'] = ( 'attachment' === $parsed_args['post_type'] ) ? 'inherit' : 'publish';
}
if ( ! empty( $parsed_args['numberposts'] ) && empty( $parsed_args['posts_per_page'] ) ) {
$parsed_args['posts_per_page'] = $parsed_args['numberposts'];
}
if ( ! empty( $parsed_args['category'] ) ) {
$parsed_args['cat'] = $parsed_args['category'];
}
if ( ! empty( $parsed_args['include'] ) ) {
$incposts = wp_parse_id_list( $parsed_args['include'] );
$parsed_args['posts_per_page'] = count( $incposts ); // Only the number of posts included.
$parsed_args['post__in'] = $incposts;
} elseif ( ! empty( $parsed_args['exclude'] ) ) {
$parsed_args['post__not_in'] = wp_parse_id_list( $parsed_args['exclude'] );
}
$parsed_args['ignore_sticky_posts'] = true;
$parsed_args['no_found_rows'] = true;
$get_posts = new WP_Query;
return $get_posts->query( $parsed_args );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Query::\_\_construct()](../classes/wp_query/__construct) wp-includes/class-wp-query.php | Constructor. |
| [wp\_parse\_id\_list()](wp_parse_id_list) wp-includes/functions.php | Cleans up an array, comma- or space-separated list of IDs. |
| [wp\_parse\_args()](wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Used By | Description |
| --- | --- |
| [do\_all\_trackbacks()](do_all_trackbacks) wp-includes/comment.php | Performs all trackbacks. |
| [do\_all\_enclosures()](do_all_enclosures) wp-includes/comment.php | Performs all enclosures. |
| [do\_all\_pingbacks()](do_all_pingbacks) wp-includes/comment.php | Performs all pingbacks. |
| [WP\_Customize\_Manager::get\_changeset\_posts()](../classes/wp_customize_manager/get_changeset_posts) wp-includes/class-wp-customize-manager.php | Gets changeset posts. |
| [wp\_add\_trashed\_suffix\_to\_post\_name\_for\_trashed\_posts()](wp_add_trashed_suffix_to_post_name_for_trashed_posts) wp-includes/post.php | Adds a suffix if any trashed posts have a given slug. |
| [WP\_Customize\_Nav\_Menus::load\_available\_items\_query()](../classes/wp_customize_nav_menus/load_available_items_query) wp-includes/class-wp-customize-nav-menus.php | Performs the post\_type and taxonomy queries for loading available menu items. |
| [get\_children()](get_children) wp-includes/post.php | Retrieves all children of the post parent ID. |
| [wp\_generate\_attachment\_metadata()](wp_generate_attachment_metadata) wp-admin/includes/image.php | Generates attachment meta data and create image sub-sizes for images. |
| [wp\_dashboard\_recent\_drafts()](wp_dashboard_recent_drafts) wp-admin/includes/dashboard.php | Show recent drafts of the user on the dashboard. |
| [wp\_ajax\_find\_posts()](wp_ajax_find_posts) wp-admin/includes/ajax-actions.php | Ajax handler for querying posts for the Find Posts modal. |
| [wp\_nav\_menu\_item\_post\_type\_meta\_box()](wp_nav_menu_item_post_type_meta_box) wp-admin/includes/nav-menu.php | Displays a meta box for a post type menu item. |
| [get\_uploaded\_header\_images()](get_uploaded_header_images) wp-includes/theme.php | Gets the header images uploaded for the active theme. |
| [WP\_Query::get\_posts()](../classes/wp_query/get_posts) wp-includes/class-wp-query.php | Retrieves an array of posts based on query variables. |
| [get\_boundary\_post()](get_boundary_post) wp-includes/link-template.php | Retrieves the boundary post. |
| [gallery\_shortcode()](gallery_shortcode) wp-includes/media.php | Builds the Gallery shortcode output. |
| [wp\_playlist\_shortcode()](wp_playlist_shortcode) wp-includes/media.php | Builds the Playlist shortcode output. |
| [wp\_get\_recent\_posts()](wp_get_recent_posts) wp-includes/post.php | Retrieves a number of recent posts. |
| [wp\_get\_nav\_menu\_items()](wp_get_nav_menu_items) wp-includes/nav-menu.php | Retrieves all menu items of a navigation menu. |
| [wp\_xmlrpc\_server::wp\_getMediaLibrary()](../classes/wp_xmlrpc_server/wp_getmedialibrary) wp-includes/class-wp-xmlrpc-server.php | Retrieves a collection of media library items (or attachments) |
| [wp\_xmlrpc\_server::wp\_getPages()](../classes/wp_xmlrpc_server/wp_getpages) wp-includes/class-wp-xmlrpc-server.php | Retrieve Pages. |
| Version | Description |
| --- | --- |
| [1.2.0](https://developer.wordpress.org/reference/since/1.2.0/) | Introduced. |
| programming_docs |
wordpress do_trackbacks( int|WP_Post $post ) do\_trackbacks( int|WP\_Post $post )
====================================
Performs trackbacks.
`$post` int|[WP\_Post](../classes/wp_post) Required Post ID or object to do trackbacks on. File: `wp-includes/comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/comment.php/)
```
function do_trackbacks( $post ) {
global $wpdb;
$post = get_post( $post );
if ( ! $post ) {
return false;
}
$to_ping = get_to_ping( $post );
$pinged = get_pung( $post );
if ( empty( $to_ping ) ) {
$wpdb->update( $wpdb->posts, array( 'to_ping' => '' ), array( 'ID' => $post->ID ) );
return;
}
if ( empty( $post->post_excerpt ) ) {
/** This filter is documented in wp-includes/post-template.php */
$excerpt = apply_filters( 'the_content', $post->post_content, $post->ID );
} else {
/** This filter is documented in wp-includes/post-template.php */
$excerpt = apply_filters( 'the_excerpt', $post->post_excerpt );
}
$excerpt = str_replace( ']]>', ']]>', $excerpt );
$excerpt = wp_html_excerpt( $excerpt, 252, '…' );
/** This filter is documented in wp-includes/post-template.php */
$post_title = apply_filters( 'the_title', $post->post_title, $post->ID );
$post_title = strip_tags( $post_title );
if ( $to_ping ) {
foreach ( (array) $to_ping as $tb_ping ) {
$tb_ping = trim( $tb_ping );
if ( ! in_array( $tb_ping, $pinged, true ) ) {
trackback( $tb_ping, $post_title, $excerpt, $post->ID );
$pinged[] = $tb_ping;
} else {
$wpdb->query(
$wpdb->prepare(
"UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s,
'')) WHERE ID = %d",
$tb_ping,
$post->ID
)
);
}
}
}
}
```
[apply\_filters( 'the\_content', string $content )](../hooks/the_content)
Filters the post content.
[apply\_filters( 'the\_excerpt', string $post\_excerpt )](../hooks/the_excerpt)
Filters the displayed post excerpt.
[apply\_filters( 'the\_title', string $post\_title, int $post\_id )](../hooks/the_title)
Filters the post title.
| Uses | Description |
| --- | --- |
| [wp\_html\_excerpt()](wp_html_excerpt) wp-includes/formatting.php | Safely extracts not more than the first $count characters from HTML string. |
| [get\_to\_ping()](get_to_ping) wp-includes/post.php | Retrieves URLs that need to be pinged. |
| [get\_pung()](get_pung) wp-includes/post.php | Retrieves URLs already pinged for a post. |
| [wpdb::update()](../classes/wpdb/update) wp-includes/class-wpdb.php | Updates a row in the table. |
| [wpdb::query()](../classes/wpdb/query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| [trackback()](trackback) wp-includes/comment.php | Sends a Trackback. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wpdb::prepare()](../classes/wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [do\_all\_trackbacks()](do_all_trackbacks) wp-includes/comment.php | Performs all trackbacks. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | `$post` can be a [WP\_Post](../classes/wp_post) object. |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_maybe_inline_styles() wp\_maybe\_inline\_styles()
===========================
Allows small styles to be inlined.
This improves performance and sustainability, and is opt-in. Stylesheets can opt in by adding `path` data using `wp_style_add_data`, and defining the file’s absolute path:
```
wp_style_add_data( $style_handle, 'path', $file_path );
```
File: `wp-includes/script-loader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/script-loader.php/)
```
function wp_maybe_inline_styles() {
global $wp_styles;
$total_inline_limit = 20000;
/**
* The maximum size of inlined styles in bytes.
*
* @since 5.8.0
*
* @param int $total_inline_limit The file-size threshold, in bytes. Default 20000.
*/
$total_inline_limit = apply_filters( 'styles_inline_size_limit', $total_inline_limit );
$styles = array();
// Build an array of styles that have a path defined.
foreach ( $wp_styles->queue as $handle ) {
if ( wp_styles()->get_data( $handle, 'path' ) && file_exists( $wp_styles->registered[ $handle ]->extra['path'] ) ) {
$styles[] = array(
'handle' => $handle,
'src' => $wp_styles->registered[ $handle ]->src,
'path' => $wp_styles->registered[ $handle ]->extra['path'],
'size' => filesize( $wp_styles->registered[ $handle ]->extra['path'] ),
);
}
}
if ( ! empty( $styles ) ) {
// Reorder styles array based on size.
usort(
$styles,
static function( $a, $b ) {
return ( $a['size'] <= $b['size'] ) ? -1 : 1;
}
);
/*
* The total inlined size.
*
* On each iteration of the loop, if a style gets added inline the value of this var increases
* to reflect the total size of inlined styles.
*/
$total_inline_size = 0;
// Loop styles.
foreach ( $styles as $style ) {
// Size check. Since styles are ordered by size, we can break the loop.
if ( $total_inline_size + $style['size'] > $total_inline_limit ) {
break;
}
// Get the styles if we don't already have them.
$style['css'] = file_get_contents( $style['path'] );
// Check if the style contains relative URLs that need to be modified.
// URLs relative to the stylesheet's path should be converted to relative to the site's root.
$style['css'] = _wp_normalize_relative_css_links( $style['css'], $style['src'] );
// Set `src` to `false` and add styles inline.
$wp_styles->registered[ $style['handle'] ]->src = false;
if ( empty( $wp_styles->registered[ $style['handle'] ]->extra['after'] ) ) {
$wp_styles->registered[ $style['handle'] ]->extra['after'] = array();
}
array_unshift( $wp_styles->registered[ $style['handle'] ]->extra['after'], $style['css'] );
// Add the styles size to the $total_inline_size var.
$total_inline_size += (int) $style['size'];
}
}
}
```
[apply\_filters( 'styles\_inline\_size\_limit', int $total\_inline\_limit )](../hooks/styles_inline_size_limit)
The maximum size of inlined styles in bytes.
| Uses | Description |
| --- | --- |
| [\_wp\_normalize\_relative\_css\_links()](_wp_normalize_relative_css_links) wp-includes/script-loader.php | Makes URLs relative to the WordPress installation. |
| [wp\_styles()](wp_styles) wp-includes/functions.wp-styles.php | Initialize $wp\_styles if it has not been set. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress wp_get_attachment_image( int $attachment_id, string|int[] $size = 'thumbnail', bool $icon = false, string|array $attr = '' ): string wp\_get\_attachment\_image( int $attachment\_id, string|int[] $size = 'thumbnail', bool $icon = false, string|array $attr = '' ): string
========================================================================================================================================
Gets an HTML img element representing an image attachment.
While `$size` will accept an array, it is better to register a size with [add\_image\_size()](add_image_size) so that a cropped version is generated. It’s much more efficient than having to find the closest-sized image and then having the browser scale down the image.
`$attachment_id` int Required Image attachment ID. `$size` string|int[] Optional Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order). Default `'thumbnail'`. Default: `'thumbnail'`
`$icon` bool Optional Whether the image should be treated as an icon. Default: `false`
`$attr` string|array Optional Attributes for the image markup.
* `src`stringImage attachment URL.
* `class`stringCSS class name or space-separated list of classes.
Default `attachment-$size_class size-$size_class`, where `$size_class` is the image size being requested.
* `alt`stringImage description for the alt attribute.
* `srcset`stringThe `'srcset'` attribute value.
* `sizes`stringThe `'sizes'` attribute value.
* `loading`string|falseThe `'loading'` attribute value. Passing a value of false will result in the attribute being omitted for the image.
Defaults to `'lazy'`, depending on [wp\_lazy\_loading\_enabled()](wp_lazy_loading_enabled) .
* `decoding`stringThe `'decoding'` attribute value. Possible values are `'async'` (default), `'sync'`, or `'auto'`.
Default: `''`
string HTML img element or empty string on failure.
```
wp_get_attachment_image( $attachment_id, $size, $icon, $attr );
```
If the attachment is an image, the function returns an image at the specified size. For other attachments, the function returns a media icon if the $icon parameter is set to true.
To get attachment IDs dynamically in a template, you can use `get_posts( array( 'post_type' => 'attachment' ) )`, etc.
File: `wp-includes/media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/media.php/)
```
function wp_get_attachment_image( $attachment_id, $size = 'thumbnail', $icon = false, $attr = '' ) {
$html = '';
$image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
if ( $image ) {
list( $src, $width, $height ) = $image;
$attachment = get_post( $attachment_id );
$hwstring = image_hwstring( $width, $height );
$size_class = $size;
if ( is_array( $size_class ) ) {
$size_class = implode( 'x', $size_class );
}
$default_attr = array(
'src' => $src,
'class' => "attachment-$size_class size-$size_class",
'alt' => trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ),
'decoding' => 'async',
);
// Add `loading` attribute.
if ( wp_lazy_loading_enabled( 'img', 'wp_get_attachment_image' ) ) {
$default_attr['loading'] = wp_get_loading_attr_default( 'wp_get_attachment_image' );
}
$attr = wp_parse_args( $attr, $default_attr );
// If the default value of `lazy` for the `loading` attribute is overridden
// to omit the attribute for this image, ensure it is not included.
if ( array_key_exists( 'loading', $attr ) && ! $attr['loading'] ) {
unset( $attr['loading'] );
}
// Generate 'srcset' and 'sizes' if not already present.
if ( empty( $attr['srcset'] ) ) {
$image_meta = wp_get_attachment_metadata( $attachment_id );
if ( is_array( $image_meta ) ) {
$size_array = array( absint( $width ), absint( $height ) );
$srcset = wp_calculate_image_srcset( $size_array, $src, $image_meta, $attachment_id );
$sizes = wp_calculate_image_sizes( $size_array, $src, $image_meta, $attachment_id );
if ( $srcset && ( $sizes || ! empty( $attr['sizes'] ) ) ) {
$attr['srcset'] = $srcset;
if ( empty( $attr['sizes'] ) ) {
$attr['sizes'] = $sizes;
}
}
}
}
/**
* Filters the list of attachment image attributes.
*
* @since 2.8.0
*
* @param string[] $attr Array of attribute values for the image markup, keyed by attribute name.
* See wp_get_attachment_image().
* @param WP_Post $attachment Image attachment post.
* @param string|int[] $size Requested image size. Can be any registered image size name, or
* an array of width and height values in pixels (in that order).
*/
$attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
$attr = array_map( 'esc_attr', $attr );
$html = rtrim( "<img $hwstring" );
foreach ( $attr as $name => $value ) {
$html .= " $name=" . '"' . $value . '"';
}
$html .= ' />';
}
/**
* Filters the HTML img element representing an image attachment.
*
* @since 5.6.0
*
* @param string $html HTML img element or empty string on failure.
* @param int $attachment_id Image attachment ID.
* @param string|int[] $size Requested image size. Can be any registered image size name, or
* an array of width and height values in pixels (in that order).
* @param bool $icon Whether the image should be treated as an icon.
* @param string[] $attr Array of attribute values for the image markup, keyed by attribute name.
* See wp_get_attachment_image().
*/
return apply_filters( 'wp_get_attachment_image', $html, $attachment_id, $size, $icon, $attr );
}
```
[apply\_filters( 'wp\_get\_attachment\_image', string $html, int $attachment\_id, string|int[] $size, bool $icon, string[] $attr )](../hooks/wp_get_attachment_image)
Filters the HTML img element representing an image attachment.
[apply\_filters( 'wp\_get\_attachment\_image\_attributes', string[] $attr, WP\_Post $attachment, string|int[] $size )](../hooks/wp_get_attachment_image_attributes)
Filters the list of attachment image attributes.
| Uses | Description |
| --- | --- |
| [wp\_get\_loading\_attr\_default()](wp_get_loading_attr_default) wp-includes/media.php | Gets the default value to use for a `loading` attribute on an element. |
| [wp\_lazy\_loading\_enabled()](wp_lazy_loading_enabled) wp-includes/media.php | Determines whether to add the `loading` attribute to the specified tag in the specified context. |
| [wp\_calculate\_image\_srcset()](wp_calculate_image_srcset) wp-includes/media.php | A helper function to calculate the image sources to include in a ‘srcset’ attribute. |
| [wp\_calculate\_image\_sizes()](wp_calculate_image_sizes) wp-includes/media.php | Creates a ‘sizes’ attribute value for an image. |
| [wp\_get\_attachment\_image\_src()](wp_get_attachment_image_src) wp-includes/media.php | Retrieves an image to represent an attachment. |
| [image\_hwstring()](image_hwstring) wp-includes/media.php | Retrieves width and height attributes using given width and height values. |
| [wp\_get\_attachment\_metadata()](wp_get_attachment_metadata) wp-includes/post.php | Retrieves attachment metadata for attachment ID. |
| [wp\_parse\_args()](wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [absint()](absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post\_meta()](get_post_meta) wp-includes/post.php | Retrieves a post meta field for the given post ID. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [WP\_Widget\_Media\_Image::render\_media()](../classes/wp_widget_media_image/render_media) wp-includes/widgets/class-wp-widget-media-image.php | Render the media on the frontend. |
| [get\_custom\_logo()](get_custom_logo) wp-includes/general-template.php | Returns a custom logo, linked to home unless the theme supports removing the link on the home page. |
| [WP\_Media\_List\_Table::column\_title()](../classes/wp_media_list_table/column_title) wp-admin/includes/class-wp-media-list-table.php | Handles the title column output. |
| [\_wp\_post\_thumbnail\_html()](_wp_post_thumbnail_html) wp-admin/includes/post.php | Returns HTML for the post thumbnail meta box. |
| [WP\_Comments\_List\_Table::column\_response()](../classes/wp_comments_list_table/column_response) wp-admin/includes/class-wp-comments-list-table.php | |
| [get\_the\_post\_thumbnail()](get_the_post_thumbnail) wp-includes/post-thumbnail-template.php | Retrieves the post thumbnail. |
| [wp\_get\_attachment\_link()](wp_get_attachment_link) wp-includes/post-template.php | Retrieves an attachment page link using an image or icon, if possible. |
| [gallery\_shortcode()](gallery_shortcode) wp-includes/media.php | Builds the Gallery shortcode output. |
| [set\_post\_thumbnail()](set_post_thumbnail) wp-includes/post.php | Sets the post thumbnail (featured image) for the given post. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | The `$decoding` attribute was added. |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | The `$loading` attribute was added. |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | The `$srcset` and `$sizes` attributes were added. |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress doing_action( string|null $hook_name = null ): bool doing\_action( string|null $hook\_name = null ): bool
=====================================================
Returns whether or not an action hook is currently being processed.
The function [current\_action()](current_action) only returns the most recent action being executed.
[did\_action()](did_action) returns the number of times an action has been fired during the current request.
This function allows detection for any action currently being executed (regardless of whether it’s the most recent action to fire, in the case of hooks called from hook callbacks) to be verified.
* [current\_action()](current_action)
* [did\_action()](did_action)
`$hook_name` string|null Optional Action hook to check. Defaults to null, which checks if any action is currently being run. Default: `null`
bool Whether the action is currently in the stack.
File: `wp-includes/plugin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/plugin.php/)
```
function doing_action( $hook_name = null ) {
return doing_filter( $hook_name );
}
```
| Uses | Description |
| --- | --- |
| [doing\_filter()](doing_filter) wp-includes/plugin.php | Returns whether or not a filter hook is currently being processed. |
| Used By | Description |
| --- | --- |
| [wp\_enqueue\_stored\_styles()](wp_enqueue_stored_styles) wp-includes/script-loader.php | Fetches, processes and compiles stored core styles, then combines and renders them to the page. |
| [wp\_enqueue\_global\_styles()](wp_enqueue_global_styles) wp-includes/script-loader.php | Enqueues the global styles defined via theme.json. |
| [wp\_add\_privacy\_policy\_content()](wp_add_privacy_policy_content) wp-admin/includes/plugin.php | Declares a helper function for adding content to the Privacy Policy Guide. |
| [wp\_version\_check()](wp_version_check) wp-includes/update.php | Checks WordPress version against the newest version. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress force_ssl_content( bool $force = '' ): bool force\_ssl\_content( bool $force = '' ): bool
=============================================
Determines whether to force SSL on content.
`$force` bool Optional Default: `''`
bool True if forced, false if not forced.
File: `wp-includes/ms-functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-functions.php/)
```
function force_ssl_content( $force = '' ) {
static $forced_content = false;
if ( ! $force ) {
$old_forced = $forced_content;
$forced_content = $force;
return $old_forced;
}
return $forced_content;
}
```
| Used By | Description |
| --- | --- |
| [filter\_SSL()](filter_ssl) wp-includes/ms-functions.php | Formats a URL to use https. |
| Version | Description |
| --- | --- |
| [2.8.5](https://developer.wordpress.org/reference/since/2.8.5/) | Introduced. |
| programming_docs |
wordpress do_feed_rss() do\_feed\_rss()
===============
Loads the RSS 1.0 Feed Template.
* [load\_template()](load_template)
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function do_feed_rss() {
load_template( ABSPATH . WPINC . '/feed-rss.php' );
}
```
| Uses | Description |
| --- | --- |
| [load\_template()](load_template) wp-includes/template.php | Requires the template file with WordPress environment. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress add_theme_page( string $page_title, string $menu_title, string $capability, string $menu_slug, callable $callback = '', int $position = null ): string|false add\_theme\_page( string $page\_title, string $menu\_title, string $capability, string $menu\_slug, callable $callback = '', int $position = null ): string|false
=================================================================================================================================================================
Adds a submenu page to the Appearance main menu.
This function takes a capability which will be used to determine whether or not a page is included in the menu.
The function which is hooked in to handle the output of the page must check that the user has the required capability as well.
`$page_title` string Required The text to be displayed in the title tags of the page when the menu is selected. `$menu_title` string Required The text to be used for the menu. `$capability` string Required The capability required for this menu to be displayed to the user. `$menu_slug` string Required The slug name to refer to this menu by (should be unique for this menu). `$callback` callable Optional The function to be called to output the content for this page. Default: `''`
`$position` int Optional The position in the menu order this item should appear. Default: `null`
string|false The resulting page's hook\_suffix, or false if the user does not have the capability required.
* This function is a simple wrapper for a call to [add\_submenu\_page()](add_submenu_page) , passing the received arguments and specifying 'themes.php'as the $parent\_slug argument. This means the new page will be added as a sub menu to the *Appearance* menu.
* The $capability parameter is used to determine whether or not the page is included in the menu based on the [Roles and Capabilities](https://wordpress.org/support/article/roles-and-capabilities/ "Roles and Capabilities")) of the current user.
* The function handling the output of the options page should also verify the user’s capabilities.
File: `wp-admin/includes/plugin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/plugin.php/)
```
function add_theme_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $position = null ) {
return add_submenu_page( 'themes.php', $page_title, $menu_title, $capability, $menu_slug, $callback, $position );
}
```
| Uses | Description |
| --- | --- |
| [add\_submenu\_page()](add_submenu_page) wp-admin/includes/plugin.php | Adds a submenu page. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::init()](../classes/custom_image_header/init) wp-admin/includes/class-custom-image-header.php | Set up the hooks for the Custom Header admin page. |
| [Custom\_Background::init()](../classes/custom_background/init) wp-admin/includes/class-custom-background.php | Sets up the hooks for the Custom Background admin page. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Added the `$position` parameter. |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress wp_theme_auto_update_setting_template(): string wp\_theme\_auto\_update\_setting\_template(): string
====================================================
Returns the JavaScript template used to display the auto-update setting for a theme.
string The template for displaying the auto-update setting link.
File: `wp-admin/themes.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/themes.php/)
```
function wp_theme_auto_update_setting_template() {
$template = '
<div class="theme-autoupdate">
<# if ( data.autoupdate.supported ) { #>
<# if ( data.autoupdate.forced === false ) { #>
' . __( 'Auto-updates disabled' ) . '
<# } else if ( data.autoupdate.forced ) { #>
' . __( 'Auto-updates enabled' ) . '
<# } else if ( data.autoupdate.enabled ) { #>
<button type="button" class="toggle-auto-update button-link" data-slug="{{ data.id }}" data-wp-action="disable">
<span class="dashicons dashicons-update spin hidden" aria-hidden="true"></span><span class="label">' . __( 'Disable auto-updates' ) . '</span>
</button>
<# } else { #>
<button type="button" class="toggle-auto-update button-link" data-slug="{{ data.id }}" data-wp-action="enable">
<span class="dashicons dashicons-update spin hidden" aria-hidden="true"></span><span class="label">' . __( 'Enable auto-updates' ) . '</span>
</button>
<# } #>
<# } #>
<# if ( data.hasUpdate ) { #>
<# if ( data.autoupdate.supported && data.autoupdate.enabled ) { #>
<span class="auto-update-time">
<# } else { #>
<span class="auto-update-time hidden">
<# } #>
<br />' . wp_get_auto_update_message() . '</span>
<# } #>
<div class="notice notice-error notice-alt inline hidden"><p></p></div>
</div>
';
/**
* Filters the JavaScript template used to display the auto-update setting for a theme (in the overlay).
*
* See {@see wp_prepare_themes_for_js()} for the properties of the `data` object.
*
* @since 5.5.0
*
* @param string $template The template for displaying the auto-update setting link.
*/
return apply_filters( 'theme_auto_update_setting_template', $template );
}
```
[apply\_filters( 'theme\_auto\_update\_setting\_template', string $template )](../hooks/theme_auto_update_setting_template)
Filters the JavaScript template used to display the auto-update setting for a theme (in the overlay).
| Uses | Description |
| --- | --- |
| [wp\_get\_auto\_update\_message()](wp_get_auto_update_message) wp-admin/includes/update.php | Determines the appropriate auto-update message to be displayed. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress shortcode_unautop( string $text ): string shortcode\_unautop( string $text ): string
==========================================
Don’t auto-p wrap shortcodes that stand alone.
Ensures that shortcodes are not wrapped in `<p>...</p>`.
`$text` string Required The content. string The filtered content.
File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function shortcode_unautop( $text ) {
global $shortcode_tags;
if ( empty( $shortcode_tags ) || ! is_array( $shortcode_tags ) ) {
return $text;
}
$tagregexp = implode( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
$spaces = wp_spaces_regexp();
// phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound,WordPress.WhiteSpace.PrecisionAlignment.Found -- don't remove regex indentation
$pattern =
'/'
. '<p>' // Opening paragraph.
. '(?:' . $spaces . ')*+' // Optional leading whitespace.
. '(' // 1: The shortcode.
. '\\[' // Opening bracket.
. "($tagregexp)" // 2: Shortcode name.
. '(?![\\w-])' // Not followed by word character or hyphen.
// Unroll the loop: Inside the opening shortcode tag.
. '[^\\]\\/]*' // Not a closing bracket or forward slash.
. '(?:'
. '\\/(?!\\])' // A forward slash not followed by a closing bracket.
. '[^\\]\\/]*' // Not a closing bracket or forward slash.
. ')*?'
. '(?:'
. '\\/\\]' // Self closing tag and closing bracket.
. '|'
. '\\]' // Closing bracket.
. '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags.
. '[^\\[]*+' // Not an opening bracket.
. '(?:'
. '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag.
. '[^\\[]*+' // Not an opening bracket.
. ')*+'
. '\\[\\/\\2\\]' // Closing shortcode tag.
. ')?'
. ')'
. ')'
. '(?:' . $spaces . ')*+' // Optional trailing whitespace.
. '<\\/p>' // Closing paragraph.
. '/';
// phpcs:enable
return preg_replace( $pattern, '$1', $text );
}
```
| Uses | Description |
| --- | --- |
| [wp\_spaces\_regexp()](wp_spaces_regexp) wp-includes/formatting.php | Returns the regexp for common whitespace characters. |
| Used By | Description |
| --- | --- |
| [get\_the\_block\_template\_html()](get_the_block_template_html) wp-includes/block-template.php | Returns the markup for the current template. |
| [WP\_Widget\_Text::widget()](../classes/wp_widget_text/widget) wp-includes/widgets/class-wp-widget-text.php | Outputs the content for the current Text widget instance. |
| Version | Description |
| --- | --- |
| [2.9.0](https://developer.wordpress.org/reference/since/2.9.0/) | Introduced. |
wordpress _wp_admin_html_begin() \_wp\_admin\_html\_begin()
==========================
Prints out the beginning of the admin HTML header.
File: `wp-admin/includes/template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/template.php/)
```
function _wp_admin_html_begin() {
global $is_IE;
$admin_html_class = ( is_admin_bar_showing() ) ? 'wp-toolbar' : '';
if ( $is_IE ) {
header( 'X-UA-Compatible: IE=edge' );
}
?>
<!DOCTYPE html>
<html class="<?php echo $admin_html_class; ?>"
<?php
/**
* Fires inside the HTML tag in the admin header.
*
* @since 2.2.0
*/
do_action( 'admin_xml_ns' );
language_attributes();
?>
>
<head>
<meta http-equiv="Content-Type" content="<?php bloginfo( 'html_type' ); ?>; charset=<?php echo get_option( 'blog_charset' ); ?>" />
<?php
}
```
[do\_action( 'admin\_xml\_ns' )](../hooks/admin_xml_ns)
Fires inside the HTML tag in the admin header.
| Uses | Description |
| --- | --- |
| [language\_attributes()](language_attributes) wp-includes/general-template.php | Displays the language attributes for the ‘html’ tag. |
| [bloginfo()](bloginfo) wp-includes/general-template.php | Displays information about the current site. |
| [is\_admin\_bar\_showing()](is_admin_bar_showing) wp-includes/admin-bar.php | Determines whether the admin bar should be showing. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [iframe\_header()](iframe_header) wp-admin/includes/template.php | Generic Iframe header for use with Thickbox. |
| [wp\_iframe()](wp_iframe) wp-admin/includes/media.php | Outputs the iframe to display the media upload page. |
wordpress capital_P_dangit( string $text ): string capital\_P\_dangit( string $text ): string
==========================================
Forever eliminate “Wordpress” from the planet (or at least the little bit we can influence).
Violating our coding standards for a good function name.
`$text` string Required The text to be modified. string The modified text.
File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function capital_P_dangit( $text ) {
// Simple replacement for titles.
$current_filter = current_filter();
if ( 'the_title' === $current_filter || 'wp_title' === $current_filter ) {
return str_replace( 'Wordpress', 'WordPress', $text );
}
// Still here? Use the more judicious replacement.
static $dblq = false;
if ( false === $dblq ) {
$dblq = _x( '“', 'opening curly double quote' );
}
return str_replace(
array( ' Wordpress', '‘Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
array( ' WordPress', '‘WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
$text
);
}
```
| Uses | Description |
| --- | --- |
| [current\_filter()](current_filter) wp-includes/plugin.php | Retrieves the name of the current filter hook. |
| [\_x()](_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress wp_create_image_subsizes( string $file, int $attachment_id ): array wp\_create\_image\_subsizes( string $file, int $attachment\_id ): array
=======================================================================
Creates image sub-sizes, adds the new data to the image meta `sizes` array, and updates the image metadata.
Intended for use after an image is uploaded. Saves/updates the image metadata after each sub-size is created. If there was an error, it is added to the returned image metadata array.
`$file` string Required Full path to the image file. `$attachment_id` int Required Attachment ID to process. array The image attachment meta data.
File: `wp-admin/includes/image.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/image.php/)
```
function wp_create_image_subsizes( $file, $attachment_id ) {
$imagesize = wp_getimagesize( $file );
if ( empty( $imagesize ) ) {
// File is not an image.
return array();
}
// Default image meta.
$image_meta = array(
'width' => $imagesize[0],
'height' => $imagesize[1],
'file' => _wp_relative_upload_path( $file ),
'filesize' => wp_filesize( $file ),
'sizes' => array(),
);
// Fetch additional metadata from EXIF/IPTC.
$exif_meta = wp_read_image_metadata( $file );
if ( $exif_meta ) {
$image_meta['image_meta'] = $exif_meta;
}
// Do not scale (large) PNG images. May result in sub-sizes that have greater file size than the original. See #48736.
if ( 'image/png' !== $imagesize['mime'] ) {
/**
* Filters the "BIG image" threshold value.
*
* If the original image width or height is above the threshold, it will be scaled down. The threshold is
* used as max width and max height. The scaled down image will be used as the largest available size, including
* the `_wp_attached_file` post meta value.
*
* Returning `false` from the filter callback will disable the scaling.
*
* @since 5.3.0
*
* @param int $threshold The threshold value in pixels. Default 2560.
* @param array $imagesize {
* Indexed array of the image width and height in pixels.
*
* @type int $0 The image width.
* @type int $1 The image height.
* }
* @param string $file Full path to the uploaded image file.
* @param int $attachment_id Attachment post ID.
*/
$threshold = (int) apply_filters( 'big_image_size_threshold', 2560, $imagesize, $file, $attachment_id );
// If the original image's dimensions are over the threshold,
// scale the image and use it as the "full" size.
if ( $threshold && ( $image_meta['width'] > $threshold || $image_meta['height'] > $threshold ) ) {
$editor = wp_get_image_editor( $file );
if ( is_wp_error( $editor ) ) {
// This image cannot be edited.
return $image_meta;
}
// Resize the image.
$resized = $editor->resize( $threshold, $threshold );
$rotated = null;
// If there is EXIF data, rotate according to EXIF Orientation.
if ( ! is_wp_error( $resized ) && is_array( $exif_meta ) ) {
$resized = $editor->maybe_exif_rotate();
$rotated = $resized;
}
if ( ! is_wp_error( $resized ) ) {
// Append "-scaled" to the image file name. It will look like "my_image-scaled.jpg".
// This doesn't affect the sub-sizes names as they are generated from the original image (for best quality).
$saved = $editor->save( $editor->generate_filename( 'scaled' ) );
if ( ! is_wp_error( $saved ) ) {
$image_meta = _wp_image_meta_replace_original( $saved, $file, $image_meta, $attachment_id );
// If the image was rotated update the stored EXIF data.
if ( true === $rotated && ! empty( $image_meta['image_meta']['orientation'] ) ) {
$image_meta['image_meta']['orientation'] = 1;
}
} else {
// TODO: Log errors.
}
} else {
// TODO: Log errors.
}
} elseif ( ! empty( $exif_meta['orientation'] ) && 1 !== (int) $exif_meta['orientation'] ) {
// Rotate the whole original image if there is EXIF data and "orientation" is not 1.
$editor = wp_get_image_editor( $file );
if ( is_wp_error( $editor ) ) {
// This image cannot be edited.
return $image_meta;
}
// Rotate the image.
$rotated = $editor->maybe_exif_rotate();
if ( true === $rotated ) {
// Append `-rotated` to the image file name.
$saved = $editor->save( $editor->generate_filename( 'rotated' ) );
if ( ! is_wp_error( $saved ) ) {
$image_meta = _wp_image_meta_replace_original( $saved, $file, $image_meta, $attachment_id );
// Update the stored EXIF data.
if ( ! empty( $image_meta['image_meta']['orientation'] ) ) {
$image_meta['image_meta']['orientation'] = 1;
}
} else {
// TODO: Log errors.
}
}
}
}
/*
* Initial save of the new metadata.
* At this point the file was uploaded and moved to the uploads directory
* but the image sub-sizes haven't been created yet and the `sizes` array is empty.
*/
wp_update_attachment_metadata( $attachment_id, $image_meta );
$new_sizes = wp_get_registered_image_subsizes();
/**
* Filters the image sizes automatically generated when uploading an image.
*
* @since 2.9.0
* @since 4.4.0 Added the `$image_meta` argument.
* @since 5.3.0 Added the `$attachment_id` argument.
*
* @param array $new_sizes Associative array of image sizes to be created.
* @param array $image_meta The image meta data: width, height, file, sizes, etc.
* @param int $attachment_id The attachment post ID for the image.
*/
$new_sizes = apply_filters( 'intermediate_image_sizes_advanced', $new_sizes, $image_meta, $attachment_id );
return _wp_make_subsizes( $new_sizes, $file, $image_meta, $attachment_id );
}
```
[apply\_filters( 'big\_image\_size\_threshold', int $threshold, array $imagesize, string $file, int $attachment\_id )](../hooks/big_image_size_threshold)
Filters the “BIG image” threshold value.
[apply\_filters( 'intermediate\_image\_sizes\_advanced', array $new\_sizes, array $image\_meta, int $attachment\_id )](../hooks/intermediate_image_sizes_advanced)
Filters the image sizes automatically generated when uploading an image.
| Uses | Description |
| --- | --- |
| [wp\_filesize()](wp_filesize) wp-includes/functions.php | Wrapper for PHP filesize with filters and casting the result as an integer. |
| [wp\_getimagesize()](wp_getimagesize) wp-includes/media.php | Allows PHP’s getimagesize() to be debuggable when necessary. |
| [wp\_get\_registered\_image\_subsizes()](wp_get_registered_image_subsizes) wp-includes/media.php | Returns a normalized list of all currently registered image sub-sizes. |
| [\_wp\_image\_meta\_replace\_original()](_wp_image_meta_replace_original) wp-admin/includes/image.php | Updates the attached file and image meta data when the original image was edited. |
| [\_wp\_make\_subsizes()](_wp_make_subsizes) wp-admin/includes/image.php | Low-level function to create image sub-sizes. |
| [wp\_read\_image\_metadata()](wp_read_image_metadata) wp-admin/includes/image.php | Gets extended image metadata, exif or iptc as available. |
| [wp\_get\_image\_editor()](wp_get_image_editor) wp-includes/media.php | Returns a [WP\_Image\_Editor](../classes/wp_image_editor) instance and loads file into it. |
| [wp\_update\_attachment\_metadata()](wp_update_attachment_metadata) wp-includes/post.php | Updates metadata for an attachment. |
| [\_wp\_relative\_upload\_path()](_wp_relative_upload_path) wp-includes/post.php | Returns relative path to an uploaded file. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [wp\_update\_image\_subsizes()](wp_update_image_subsizes) wp-admin/includes/image.php | If any of the currently registered image sub-sizes are missing, create them and update the image meta data. |
| [wp\_generate\_attachment\_metadata()](wp_generate_attachment_metadata) wp-admin/includes/image.php | Generates attachment meta data and create image sub-sizes for images. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
| programming_docs |
wordpress wp_is_post_revision( int|WP_Post $post ): int|false wp\_is\_post\_revision( int|WP\_Post $post ): int|false
=======================================================
Determines if the specified post is a revision.
`$post` int|[WP\_Post](../classes/wp_post) Required Post ID or post object. int|false ID of revision's parent on success, false if not a revision.
File: `wp-includes/revision.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/revision.php/)
```
function wp_is_post_revision( $post ) {
$post = wp_get_post_revision( $post );
if ( ! $post ) {
return false;
}
return (int) $post->post_parent;
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_post\_revision()](wp_get_post_revision) wp-includes/revision.php | Gets a post revision. |
| Used By | Description |
| --- | --- |
| [wp\_post\_revision\_title()](wp_post_revision_title) wp-includes/post-template.php | Retrieves formatted date timestamp of a revision (linked to that revisions’s page). |
| [wp\_post\_revision\_title\_expanded()](wp_post_revision_title_expanded) wp-includes/post-template.php | Retrieves formatted date timestamp of a revision (linked to that revisions’s page). |
| [add\_post\_meta()](add_post_meta) wp-includes/post.php | Adds a meta field to the given post. |
| [delete\_post\_meta()](delete_post_meta) wp-includes/post.php | Deletes a post meta field for the given post ID. |
| [update\_post\_meta()](update_post_meta) wp-includes/post.php | Updates a post meta field based on the given post ID. |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress wp_robots_sensitive_page( array $robots ): array wp\_robots\_sensitive\_page( array $robots ): array
===================================================
Adds `noindex` and `noarchive` to the robots meta tag.
This directive tells web robots not to index or archive the page content and is recommended to be used for sensitive pages.
Typical usage is as a [‘wp\_robots’](../hooks/wp_robots) callback:
```
add_filter( 'wp_robots', 'wp_robots_sensitive_page' );
```
`$robots` array Required Associative array of robots directives. array Filtered robots directives.
File: `wp-includes/robots-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/robots-template.php/)
```
function wp_robots_sensitive_page( array $robots ) {
$robots['noindex'] = true;
$robots['noarchive'] = true;
return $robots;
}
```
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Introduced. |
wordpress ent2ncr( string $text ): string ent2ncr( string $text ): string
===============================
Converts named entities into numbered entities.
`$text` string Required The text within which entities will be converted. string Text with converted entities.
File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function ent2ncr( $text ) {
/**
* Filters text before named entities are converted into numbered entities.
*
* A non-null string must be returned for the filter to be evaluated.
*
* @since 3.3.0
*
* @param string|null $converted_text The text to be converted. Default null.
* @param string $text The text prior to entity conversion.
*/
$filtered = apply_filters( 'pre_ent2ncr', null, $text );
if ( null !== $filtered ) {
return $filtered;
}
$to_ncr = array(
'"' => '"',
'&' => '&',
'<' => '<',
'>' => '>',
'|' => '|',
' ' => ' ',
'¡' => '¡',
'¢' => '¢',
'£' => '£',
'¤' => '¤',
'¥' => '¥',
'¦' => '¦',
'&brkbar;' => '¦',
'§' => '§',
'¨' => '¨',
'¨' => '¨',
'©' => '©',
'ª' => 'ª',
'«' => '«',
'¬' => '¬',
'­' => '­',
'®' => '®',
'¯' => '¯',
'&hibar;' => '¯',
'°' => '°',
'±' => '±',
'²' => '²',
'³' => '³',
'´' => '´',
'µ' => 'µ',
'¶' => '¶',
'·' => '·',
'¸' => '¸',
'¹' => '¹',
'º' => 'º',
'»' => '»',
'¼' => '¼',
'½' => '½',
'¾' => '¾',
'¿' => '¿',
'À' => 'À',
'Á' => 'Á',
'Â' => 'Â',
'Ã' => 'Ã',
'Ä' => 'Ä',
'Å' => 'Å',
'Æ' => 'Æ',
'Ç' => 'Ç',
'È' => 'È',
'É' => 'É',
'Ê' => 'Ê',
'Ë' => 'Ë',
'Ì' => 'Ì',
'Í' => 'Í',
'Î' => 'Î',
'Ï' => 'Ï',
'Ð' => 'Ð',
'Ñ' => 'Ñ',
'Ò' => 'Ò',
'Ó' => 'Ó',
'Ô' => 'Ô',
'Õ' => 'Õ',
'Ö' => 'Ö',
'×' => '×',
'Ø' => 'Ø',
'Ù' => 'Ù',
'Ú' => 'Ú',
'Û' => 'Û',
'Ü' => 'Ü',
'Ý' => 'Ý',
'Þ' => 'Þ',
'ß' => 'ß',
'à' => 'à',
'á' => 'á',
'â' => 'â',
'ã' => 'ã',
'ä' => 'ä',
'å' => 'å',
'æ' => 'æ',
'ç' => 'ç',
'è' => 'è',
'é' => 'é',
'ê' => 'ê',
'ë' => 'ë',
'ì' => 'ì',
'í' => 'í',
'î' => 'î',
'ï' => 'ï',
'ð' => 'ð',
'ñ' => 'ñ',
'ò' => 'ò',
'ó' => 'ó',
'ô' => 'ô',
'õ' => 'õ',
'ö' => 'ö',
'÷' => '÷',
'ø' => 'ø',
'ù' => 'ù',
'ú' => 'ú',
'û' => 'û',
'ü' => 'ü',
'ý' => 'ý',
'þ' => 'þ',
'ÿ' => 'ÿ',
'Œ' => 'Œ',
'œ' => 'œ',
'Š' => 'Š',
'š' => 'š',
'Ÿ' => 'Ÿ',
'ƒ' => 'ƒ',
'ˆ' => 'ˆ',
'˜' => '˜',
'Α' => 'Α',
'Β' => 'Β',
'Γ' => 'Γ',
'Δ' => 'Δ',
'Ε' => 'Ε',
'Ζ' => 'Ζ',
'Η' => 'Η',
'Θ' => 'Θ',
'Ι' => 'Ι',
'Κ' => 'Κ',
'Λ' => 'Λ',
'Μ' => 'Μ',
'Ν' => 'Ν',
'Ξ' => 'Ξ',
'Ο' => 'Ο',
'Π' => 'Π',
'Ρ' => 'Ρ',
'Σ' => 'Σ',
'Τ' => 'Τ',
'Υ' => 'Υ',
'Φ' => 'Φ',
'Χ' => 'Χ',
'Ψ' => 'Ψ',
'Ω' => 'Ω',
'α' => 'α',
'β' => 'β',
'γ' => 'γ',
'δ' => 'δ',
'ε' => 'ε',
'ζ' => 'ζ',
'η' => 'η',
'θ' => 'θ',
'ι' => 'ι',
'κ' => 'κ',
'λ' => 'λ',
'μ' => 'μ',
'ν' => 'ν',
'ξ' => 'ξ',
'ο' => 'ο',
'π' => 'π',
'ρ' => 'ρ',
'ς' => 'ς',
'σ' => 'σ',
'τ' => 'τ',
'υ' => 'υ',
'φ' => 'φ',
'χ' => 'χ',
'ψ' => 'ψ',
'ω' => 'ω',
'ϑ' => 'ϑ',
'ϒ' => 'ϒ',
'ϖ' => 'ϖ',
' ' => ' ',
' ' => ' ',
' ' => ' ',
'‌' => '‌',
'‍' => '‍',
'‎' => '‎',
'‏' => '‏',
'–' => '–',
'—' => '—',
'‘' => '‘',
'’' => '’',
'‚' => '‚',
'“' => '“',
'”' => '”',
'„' => '„',
'†' => '†',
'‡' => '‡',
'•' => '•',
'…' => '…',
'‰' => '‰',
'′' => '′',
'″' => '″',
'‹' => '‹',
'›' => '›',
'‾' => '‾',
'⁄' => '⁄',
'€' => '€',
'ℑ' => 'ℑ',
'℘' => '℘',
'ℜ' => 'ℜ',
'™' => '™',
'ℵ' => 'ℵ',
'↵' => '↵',
'⇐' => '⇐',
'⇑' => '⇑',
'⇒' => '⇒',
'⇓' => '⇓',
'⇔' => '⇔',
'∀' => '∀',
'∂' => '∂',
'∃' => '∃',
'∅' => '∅',
'∇' => '∇',
'∈' => '∈',
'∉' => '∉',
'∋' => '∋',
'∏' => '∏',
'∑' => '∑',
'−' => '−',
'∗' => '∗',
'√' => '√',
'∝' => '∝',
'∞' => '∞',
'∠' => '∠',
'∧' => '∧',
'∨' => '∨',
'∩' => '∩',
'∪' => '∪',
'∫' => '∫',
'∴' => '∴',
'∼' => '∼',
'≅' => '≅',
'≈' => '≈',
'≠' => '≠',
'≡' => '≡',
'≤' => '≤',
'≥' => '≥',
'⊂' => '⊂',
'⊃' => '⊃',
'⊄' => '⊄',
'⊆' => '⊆',
'⊇' => '⊇',
'⊕' => '⊕',
'⊗' => '⊗',
'⊥' => '⊥',
'⋅' => '⋅',
'⌈' => '⌈',
'⌉' => '⌉',
'⌊' => '⌊',
'⌋' => '⌋',
'⟨' => '〈',
'⟩' => '〉',
'←' => '←',
'↑' => '↑',
'→' => '→',
'↓' => '↓',
'↔' => '↔',
'◊' => '◊',
'♠' => '♠',
'♣' => '♣',
'♥' => '♥',
'♦' => '♦',
);
return str_replace( array_keys( $to_ncr ), array_values( $to_ncr ), $text );
}
```
[apply\_filters( 'pre\_ent2ncr', string|null $converted\_text, string $text )](../hooks/pre_ent2ncr)
Filters text before named entities are converted into numbered entities.
| Uses | Description |
| --- | --- |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [get\_comment\_text()](get_comment_text) wp-includes/comment-template.php | Retrieves the text of the current comment. |
| Version | Description |
| --- | --- |
| [1.5.1](https://developer.wordpress.org/reference/since/1.5.1/) | Introduced. |
wordpress background_image() background\_image()
===================
Displays background image path.
File: `wp-includes/theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/theme.php/)
```
function background_image() {
echo get_background_image();
}
```
| Uses | Description |
| --- | --- |
| [get\_background\_image()](get_background_image) wp-includes/theme.php | Retrieves background image for custom background. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress _wp_privacy_statuses(): array \_wp\_privacy\_statuses(): array
================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Returns statuses for privacy requests.
array
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function _wp_privacy_statuses() {
return array(
'request-pending' => _x( 'Pending', 'request status' ), // Pending confirmation from user.
'request-confirmed' => _x( 'Confirmed', 'request status' ), // User has confirmed the action.
'request-failed' => _x( 'Failed', 'request status' ), // User failed to confirm the action.
'request-completed' => _x( 'Completed', 'request status' ), // Admin has handled the request.
);
}
```
| Uses | Description |
| --- | --- |
| [\_x()](_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| Used By | Description |
| --- | --- |
| [WP\_Privacy\_Requests\_Table::get\_views()](../classes/wp_privacy_requests_table/get_views) wp-admin/includes/class-wp-privacy-requests-table.php | Get an associative array ( id => link ) with the list of views available on this table. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress wp_get_schedule( string $hook, array $args = array() ): string|false wp\_get\_schedule( string $hook, array $args = array() ): string|false
======================================================================
Retrieve the recurrence schedule for an event.
* [wp\_get\_schedules()](wp_get_schedules) : for available schedules.
`$hook` string Required Action hook to identify the event. `$args` array Optional Arguments passed to the event's callback function.
Default: `array()`
string|false Schedule name on success, false if no schedule.
File: `wp-includes/cron.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/cron.php/)
```
function wp_get_schedule( $hook, $args = array() ) {
$schedule = false;
$event = wp_get_scheduled_event( $hook, $args );
if ( $event ) {
$schedule = $event->schedule;
}
/**
* Filters the schedule for a hook.
*
* @since 5.1.0
*
* @param string|false $schedule Schedule for the hook. False if not found.
* @param string $hook Action hook to execute when cron is run.
* @param array $args Arguments to pass to the hook's callback function.
*/
return apply_filters( 'get_schedule', $schedule, $hook, $args );
}
```
[apply\_filters( 'get\_schedule', string|false $schedule, string $hook, array $args )](../hooks/get_schedule)
Filters the schedule for a hook.
| Uses | Description |
| --- | --- |
| [wp\_get\_scheduled\_event()](wp_get_scheduled_event) wp-includes/cron.php | Retrieve a scheduled event. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | ['get\_schedule'](../hooks/get_schedule) filter added. |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress absint( mixed $maybeint ): int absint( mixed $maybeint ): int
==============================
Converts a value to non-negative integer.
`$maybeint` mixed Required Data you wish to have converted to a non-negative integer. int A non-negative integer.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function absint( $maybeint ) {
return abs( (int) $maybeint );
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menu\_Items\_Controller::prepare\_item\_for\_response()](../classes/wp_rest_menu_items_controller/prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Prepares a single post output for response. |
| [WP\_REST\_Menu\_Items\_Controller::prepare\_item\_for\_database()](../classes/wp_rest_menu_items_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Prepares a single post for create or update. |
| [WP\_REST\_Pattern\_Directory\_Controller::prepare\_item\_for\_response()](../classes/wp_rest_pattern_directory_controller/prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php | Prepare a raw block pattern before it gets output in a REST API response. |
| [build\_query\_vars\_from\_query\_block()](build_query_vars_from_query_block) wp-includes/blocks.php | Helper function that constructs a [WP\_Query](../classes/wp_query) args array from a `Query` block properties. |
| [get\_sitemap\_url()](get_sitemap_url) wp-includes/sitemaps.php | Retrieves the full URL for a sitemap. |
| [get\_metadata\_raw()](get_metadata_raw) wp-includes/meta.php | Retrieves raw metadata value for the specified object. |
| [wp\_filter\_content\_tags()](wp_filter_content_tags) wp-includes/media.php | Filters specific tags in post content and modifies their markup. |
| [WP\_Sitemaps::render\_sitemaps()](../classes/wp_sitemaps/render_sitemaps) wp-includes/sitemaps/class-wp-sitemaps.php | Renders sitemap templates based on rewrite rules. |
| [wp\_get\_user\_request()](wp_get_user_request) wp-includes/user.php | Returns the user request object for the specified request ID. |
| [wp\_validate\_user\_request\_key()](wp_validate_user_request_key) wp-includes/user.php | Validates a user request by comparing the key with the request’s key. |
| [wp\_send\_user\_request()](wp_send_user_request) wp-includes/user.php | Send a confirmation request email to confirm an action. |
| [WP\_Privacy\_Requests\_Table::get\_views()](../classes/wp_privacy_requests_table/get_views) wp-admin/includes/class-wp-privacy-requests-table.php | Get an associative array ( id => link ) with the list of views available on this table. |
| [WP\_Privacy\_Requests\_Table::prepare\_items()](../classes/wp_privacy_requests_table/prepare_items) wp-admin/includes/class-wp-privacy-requests-table.php | Prepare items to output. |
| [\_wp\_privacy\_resend\_request()](_wp_privacy_resend_request) wp-admin/includes/privacy-tools.php | Resend an existing request and return the result. |
| [\_wp\_privacy\_completed\_request()](_wp_privacy_completed_request) wp-admin/includes/privacy-tools.php | Marks a request as completed by the admin and logs the current timestamp. |
| [\_wp\_personal\_data\_handle\_actions()](_wp_personal_data_handle_actions) wp-admin/includes/privacy-tools.php | Handle list table actions. |
| [WP\_User::for\_site()](../classes/wp_user/for_site) wp-includes/class-wp-user.php | Sets the site to operate on. Defaults to the current site. |
| [WP\_Customize\_Manager::handle\_load\_themes\_request()](../classes/wp_customize_manager/handle_load_themes_request) wp-includes/class-wp-customize-manager.php | Loads themes into the theme browsing/installation UI. |
| [WP\_Roles::for\_site()](../classes/wp_roles/for_site) wp-includes/class-wp-roles.php | Sets the site to operate on. Defaults to the current site. |
| [wpdb::parse\_db\_host()](../classes/wpdb/parse_db_host) wp-includes/class-wpdb.php | Parses the DB\_HOST setting to interpret it for mysqli\_real\_connect(). |
| [WP\_Community\_Events::\_\_construct()](../classes/wp_community_events/__construct) wp-admin/includes/class-wp-community-events.php | Constructor for [WP\_Community\_Events](../classes/wp_community_events). |
| [WP\_Community\_Events::cache\_events()](../classes/wp_community_events/cache_events) wp-admin/includes/class-wp-community-events.php | Caches an array of events data from the Events API. |
| [WP\_Customize\_Manager::\_validate\_header\_video()](../classes/wp_customize_manager/_validate_header_video) wp-includes/class-wp-customize-manager.php | Callback for validating the header\_video value. |
| [get\_header\_video\_url()](get_header_video_url) wp-includes/theme.php | Retrieves header video URL for custom header. |
| [get\_header\_video\_settings()](get_header_video_settings) wp-includes/theme.php | Retrieves header video settings. |
| [WP\_REST\_Users\_Controller::prepare\_item\_for\_database()](../classes/wp_rest_users_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Prepares a single user for creation or update. |
| [WP\_REST\_Users\_Controller::delete\_item()](../classes/wp_rest_users_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Deletes a single user. |
| [WP\_REST\_Comments\_Controller::get\_items()](../classes/wp_rest_comments_controller/get_items) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Retrieves a list of comment items. |
| [WP\_Term\_Query::parse\_query()](../classes/wp_term_query/parse_query) wp-includes/class-wp-term-query.php | Parse arguments passed to the term query with default query parameters. |
| [get\_current\_network\_id()](get_current_network_id) wp-includes/load.php | Retrieves the current network ID. |
| [WP\_Network\_Query::get\_network\_ids()](../classes/wp_network_query/get_network_ids) wp-includes/class-wp-network-query.php | Used internally to get a list of network IDs matching the query vars. |
| [wp\_localize\_jquery\_ui\_datepicker()](wp_localize_jquery_ui_datepicker) wp-includes/script-loader.php | Localizes the jQuery UI datepicker. |
| [WP\_HTTP\_Requests\_Response::set\_status()](../classes/wp_http_requests_response/set_status) wp-includes/class-wp-http-requests-response.php | Sets the 3-digit HTTP status code. |
| [WP\_Site\_Query::get\_site\_ids()](../classes/wp_site_query/get_site_ids) wp-includes/class-wp-site-query.php | Used internally to get a list of site IDs matching the query vars. |
| [get\_oembed\_response\_data\_rich()](get_oembed_response_data_rich) wp-includes/embed.php | Filters the oEmbed response data to return an iframe embed code. |
| [get\_post\_embed\_html()](get_post_embed_html) wp-includes/embed.php | Retrieves the embed code for a specific post. |
| [get\_oembed\_response\_data()](get_oembed_response_data) wp-includes/embed.php | Retrieves the oEmbed response data for a given post. |
| [get\_header\_image\_tag()](get_header_image_tag) wp-includes/theme.php | Creates image tag markup for a custom header image. |
| [wp\_get\_attachment\_image\_srcset()](wp_get_attachment_image_srcset) wp-includes/media.php | Retrieves the value for an image attachment’s ‘srcset’ attribute. |
| [wp\_get\_attachment\_image\_sizes()](wp_get_attachment_image_sizes) wp-includes/media.php | Retrieves the value for an image attachment’s ‘sizes’ attribute. |
| [wp\_calculate\_image\_sizes()](wp_calculate_image_sizes) wp-includes/media.php | Creates a ‘sizes’ attribute value for an image. |
| [\_wp\_get\_image\_size\_from\_meta()](_wp_get_image_size_from_meta) wp-includes/media.php | Gets the image size as array from its meta data. |
| [WP\_HTTP\_Response::set\_status()](../classes/wp_http_response/set_status) wp-includes/class-wp-http-response.php | Sets the 3-digit HTTP status code. |
| [WP\_Comment\_Query::get\_comment\_ids()](../classes/wp_comment_query/get_comment_ids) wp-includes/class-wp-comment-query.php | Used internally to get a list of comment IDs matching the query vars. |
| [wp\_handle\_comment\_submission()](wp_handle_comment_submission) wp-includes/comment.php | Handles the submission of a comment, usually posted to wp-comments-post.php via a comment form. |
| [WP\_Customize\_Cropped\_Image\_Control::to\_json()](../classes/wp_customize_cropped_image_control/to_json) wp-includes/customize/class-wp-customize-cropped-image-control.php | Refresh the parameters passed to the JavaScript via JSON. |
| [WP\_Customize\_Nav\_Menus::search\_available\_items\_query()](../classes/wp_customize_nav_menus/search_available_items_query) wp-includes/class-wp-customize-nav-menus.php | Performs post queries for available-item searching. |
| [WP\_Customize\_Nav\_Menus::ajax\_load\_available\_items()](../classes/wp_customize_nav_menus/ajax_load_available_items) wp-includes/class-wp-customize-nav-menus.php | Ajax handler for loading available menu items. |
| [WP\_Customize\_Nav\_Menus::ajax\_search\_available\_items()](../classes/wp_customize_nav_menus/ajax_search_available_items) wp-includes/class-wp-customize-nav-menus.php | Ajax handler for searching available menu items. |
| [wp\_ajax\_crop\_image()](wp_ajax_crop_image) wp-admin/includes/ajax-actions.php | Ajax handler for cropping an image. |
| [get\_avatar\_data()](get_avatar_data) wp-includes/link-template.php | Retrieves default data about the avatar. |
| [Custom\_Background::ajax\_background\_add()](../classes/custom_background/ajax_background_add) wp-admin/includes/class-custom-background.php | Handles Ajax request for adding custom background context to an attachment. |
| [WP\_List\_Table::get\_pagenum()](../classes/wp_list_table/get_pagenum) wp-admin/includes/class-wp-list-table.php | Gets the current page number. |
| [wp\_check\_locked\_posts()](wp_check_locked_posts) wp-admin/includes/misc.php | Checks lock status for posts displayed on the Posts screen. |
| [wp\_refresh\_post\_lock()](wp_refresh_post_lock) wp-admin/includes/misc.php | Checks lock status on the New/Edit Post screen and refresh the lock. |
| [wp\_refresh\_post\_nonces()](wp_refresh_post_nonces) wp-admin/includes/misc.php | Checks nonce expiration on the New/Edit Post screen and refresh if needed. |
| [wp\_dashboard()](wp_dashboard) wp-admin/includes/dashboard.php | Displays the dashboard. |
| [add\_submenu\_page()](add_submenu_page) wp-admin/includes/plugin.php | Adds a submenu page. |
| [get\_media\_item()](get_media_item) wp-admin/includes/media.php | Retrieves HTML form for modifying the image attachment. |
| [media\_upload\_form()](media_upload_form) wp-admin/includes/media.php | Outputs the legacy media upload form. |
| [wp\_ajax\_save\_attachment\_order()](wp_ajax_save_attachment_order) wp-admin/includes/ajax-actions.php | Ajax handler for saving the attachment order. |
| [wp\_ajax\_get\_attachment()](wp_ajax_get_attachment) wp-admin/includes/ajax-actions.php | Ajax handler for getting an attachment. |
| [wp\_ajax\_save\_attachment()](wp_ajax_save_attachment) wp-admin/includes/ajax-actions.php | Ajax handler for updating attachment attributes. |
| [wp\_ajax\_save\_attachment\_compat()](wp_ajax_save_attachment_compat) wp-admin/includes/ajax-actions.php | Ajax handler for saving backward compatible attachment attributes. |
| [wp\_ajax\_wp\_link\_ajax()](wp_ajax_wp_link_ajax) wp-admin/includes/ajax-actions.php | Ajax handler for internal linking. |
| [wp\_ajax\_get\_comments()](wp_ajax_get_comments) wp-admin/includes/ajax-actions.php | Ajax handler for getting comments. |
| [wp\_ajax\_replyto\_comment()](wp_ajax_replyto_comment) wp-admin/includes/ajax-actions.php | Ajax handler for replying to a comment. |
| [wp\_prepare\_revisions\_for\_js()](wp_prepare_revisions_for_js) wp-admin/includes/revision.php | Prepare revisions for JavaScript. |
| [wp\_ajax\_autocomplete\_user()](wp_ajax_autocomplete_user) wp-admin/includes/ajax-actions.php | Ajax handler for user autocomplete. |
| [WP\_Comments\_List\_Table::get\_views()](../classes/wp_comments_list_table/get_views) wp-admin/includes/class-wp-comments-list-table.php | |
| [WP\_Comments\_List\_Table::\_\_construct()](../classes/wp_comments_list_table/__construct) wp-admin/includes/class-wp-comments-list-table.php | Constructor. |
| [wp\_nav\_menu\_item\_post\_type\_meta\_box()](wp_nav_menu_item_post_type_meta_box) wp-admin/includes/nav-menu.php | Displays a meta box for a post type menu item. |
| [wp\_nav\_menu\_item\_taxonomy\_meta\_box()](wp_nav_menu_item_taxonomy_meta_box) wp-admin/includes/nav-menu.php | Displays a meta box for a taxonomy menu item. |
| [get\_pending\_comments\_num()](get_pending_comments_num) wp-admin/includes/comment.php | Gets the number of pending comments on a post or posts. |
| [Custom\_Image\_Header::get\_header\_dimensions()](../classes/custom_image_header/get_header_dimensions) wp-admin/includes/class-custom-image-header.php | Calculate width and height based on what the currently selected theme supports. |
| [Custom\_Image\_Header::ajax\_header\_crop()](../classes/custom_image_header/ajax_header_crop) wp-admin/includes/class-custom-image-header.php | Gets attachment uploaded by Media Manager, crops it, then saves it as a new object. Returns JSON-encoded object details. |
| [Custom\_Image\_Header::ajax\_header\_add()](../classes/custom_image_header/ajax_header_add) wp-admin/includes/class-custom-image-header.php | Given an attachment ID for a header image, updates its “last used” timestamp to now. |
| [Custom\_Image\_Header::ajax\_header\_remove()](../classes/custom_image_header/ajax_header_remove) wp-admin/includes/class-custom-image-header.php | Given an attachment ID for a header image, unsets it as a user-uploaded header image for the active theme. |
| [Custom\_Image\_Header::step\_2()](../classes/custom_image_header/step_2) wp-admin/includes/class-custom-image-header.php | Display second step of custom header image page. |
| [Custom\_Image\_Header::step\_3()](../classes/custom_image_header/step_3) wp-admin/includes/class-custom-image-header.php | Display third step of custom header image page. |
| [Custom\_Image\_Header::js\_2()](../classes/custom_image_header/js_2) wp-admin/includes/class-custom-image-header.php | Display JavaScript based on Step 2. |
| [Custom\_Background::wp\_set\_background\_image()](../classes/custom_background/wp_set_background_image) wp-admin/includes/class-custom-background.php | |
| [WP\_Customize\_Manager::register\_controls()](../classes/wp_customize_manager/register_controls) wp-includes/class-wp-customize-manager.php | Registers some default controls. |
| [sanitize\_option()](sanitize_option) wp-includes/formatting.php | Sanitizes various option values based on the nature of the option. |
| [wp\_rand()](wp_rand) wp-includes/pluggable.php | Generates a random non-negative number. |
| [wp\_get\_archives()](wp_get_archives) wp-includes/general-template.php | Displays archive links based on type and format. |
| [WP\_Query::get\_posts()](../classes/wp_query/get_posts) wp-includes/class-wp-query.php | Retrieves an array of posts based on query variables. |
| [WP\_Query::parse\_query()](../classes/wp_query/parse_query) wp-includes/class-wp-query.php | Parse a query string and set query type booleans. |
| [WP\_Query::parse\_tax\_query()](../classes/wp_query/parse_tax_query) wp-includes/class-wp-query.php | Parses various taxonomy related query vars. |
| [get\_current\_blog\_id()](get_current_blog_id) wp-includes/load.php | Retrieve the current site ID. |
| [get\_status\_header\_desc()](get_status_header_desc) wp-includes/functions.php | Retrieves the description for the HTTP status. |
| [number\_format\_i18n()](number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| [WP\_Widget\_Recent\_Comments::update()](../classes/wp_widget_recent_comments/update) wp-includes/widgets/class-wp-widget-recent-comments.php | Handles updating settings for the current Recent Comments widget instance. |
| [WP\_Widget\_Recent\_Comments::form()](../classes/wp_widget_recent_comments/form) wp-includes/widgets/class-wp-widget-recent-comments.php | Outputs the settings form for the Recent Comments widget. |
| [WP\_Widget\_Recent\_Comments::widget()](../classes/wp_widget_recent_comments/widget) wp-includes/widgets/class-wp-widget-recent-comments.php | Outputs the content for the current Recent Comments widget instance. |
| [WP\_Widget\_Recent\_Posts::widget()](../classes/wp_widget_recent_posts/widget) wp-includes/widgets/class-wp-widget-recent-posts.php | Outputs the content for the current Recent Posts widget instance. |
| [WP\_Widget\_Recent\_Posts::form()](../classes/wp_widget_recent_posts/form) wp-includes/widgets/class-wp-widget-recent-posts.php | Outputs the settings form for the Recent Posts widget. |
| [get\_post\_comments\_feed\_link()](get_post_comments_feed_link) wp-includes/link-template.php | Retrieves the permalink for the post comments feed. |
| [rss\_enclosure()](rss_enclosure) wp-includes/feed.php | Displays the rss enclosure for the current post. |
| [WP\_User\_Query::prepare\_query()](../classes/wp_user_query/prepare_query) wp-includes/class-wp-user-query.php | Prepares the query variables. |
| [wp\_video\_shortcode()](wp_video_shortcode) wp-includes/media.php | Builds the Video shortcode output. |
| [wp\_get\_attachment\_image()](wp_get_attachment_image) wp-includes/media.php | Gets an HTML img element representing an image attachment. |
| [add\_image\_size()](add_image_size) wp-includes/media.php | Registers a new image size. |
| [set\_post\_thumbnail()](set_post_thumbnail) wp-includes/post.php | Sets the post thumbnail (featured image) for the given post. |
| [wp\_get\_recent\_posts()](wp_get_recent_posts) wp-includes/post.php | Retrieves a number of recent posts. |
| [is\_sticky()](is_sticky) wp-includes/post.php | Determines whether a post is sticky. |
| [get\_post\_custom()](get_post_custom) wp-includes/post.php | Retrieves post meta fields, based on post ID. |
| [url\_to\_postid()](url_to_postid) wp-includes/rewrite.php | Examines a URL and try to determine the post ID it represents. |
| [get\_bookmarks()](get_bookmarks) wp-includes/bookmark.php | Retrieves the list of bookmarks. |
| [wp\_xmlrpc\_server::mw\_getRecentPosts()](../classes/wp_xmlrpc_server/mw_getrecentposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve list of recent posts. |
| [wp\_xmlrpc\_server::mt\_getRecentPostTitles()](../classes/wp_xmlrpc_server/mt_getrecentposttitles) wp-includes/class-wp-xmlrpc-server.php | Retrieve the post titles of recent posts. |
| [wp\_xmlrpc\_server::blogger\_getRecentPosts()](../classes/wp_xmlrpc_server/blogger_getrecentposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve list of recent posts. |
| [wp\_xmlrpc\_server::wp\_getMediaLibrary()](../classes/wp_xmlrpc_server/wp_getmedialibrary) wp-includes/class-wp-xmlrpc-server.php | Retrieves a collection of media library items (or attachments) |
| [wp\_xmlrpc\_server::wp\_getComments()](../classes/wp_xmlrpc_server/wp_getcomments) wp-includes/class-wp-xmlrpc-server.php | Retrieve comments. |
| [wp\_xmlrpc\_server::wp\_newComment()](../classes/wp_xmlrpc_server/wp_newcomment) wp-includes/class-wp-xmlrpc-server.php | Create new comment. |
| [wp\_xmlrpc\_server::wp\_getPosts()](../classes/wp_xmlrpc_server/wp_getposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve posts. |
| [wp\_xmlrpc\_server::wp\_getTerms()](../classes/wp_xmlrpc_server/wp_getterms) wp-includes/class-wp-xmlrpc-server.php | Retrieve all terms for a taxonomy. |
| [wp\_xmlrpc\_server::wp\_getUsers()](../classes/wp_xmlrpc_server/wp_getusers) wp-includes/class-wp-xmlrpc-server.php | Retrieve users. |
| [wp\_xmlrpc\_server::\_insert\_post()](../classes/wp_xmlrpc_server/_insert_post) wp-includes/class-wp-xmlrpc-server.php | Helper method for wp\_newPost() and wp\_editPost(), containing shared logic. |
| [WP\_Customize\_Header\_Image\_Control::enqueue()](../classes/wp_customize_header_image_control/enqueue) wp-includes/customize/class-wp-customize-header-image-control.php | |
| [WP\_Customize\_Header\_Image\_Control::render\_content()](../classes/wp_customize_header_image_control/render_content) wp-includes/customize/class-wp-customize-header-image-control.php | |
| [wp\_new\_comment()](wp_new_comment) wp-includes/comment.php | Adds a new comment to the database. |
| [delete\_metadata()](delete_metadata) wp-includes/meta.php | Deletes metadata for the specified object. |
| [metadata\_exists()](metadata_exists) wp-includes/meta.php | Determines if a meta field with the given key exists for the given object ID. |
| [\_WP\_Editors::wp\_link\_query()](../classes/_wp_editors/wp_link_query) wp-includes/class-wp-editor.php | Performs post queries for internal linking. |
| [add\_metadata()](add_metadata) wp-includes/meta.php | Adds metadata for the specified object. |
| [update\_metadata()](update_metadata) wp-includes/meta.php | Updates metadata for the specified object. If no value already exists for the specified object ID and metadata key, the metadata will be added. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
| programming_docs |
wordpress add_custom_background( callable $wp_head_callback = '', callable $admin_head_callback = '', callable $admin_preview_callback = '' ) add\_custom\_background( callable $wp\_head\_callback = '', callable $admin\_head\_callback = '', callable $admin\_preview\_callback = '' )
===========================================================================================================================================
This function has been deprecated. Use [add\_theme\_support()](add_theme_support) instead.
Add callbacks for background image display.
* [add\_theme\_support()](add_theme_support)
`$wp_head_callback` callable Optional Call on the ['wp\_head'](../hooks/wp_head) action. Default: `''`
`$admin_head_callback` callable Optional Call on custom background administration screen. Default: `''`
`$admin_preview_callback` callable Optional Output a custom background image div on the custom background administration screen. Optional. Default: `''`
File: `wp-includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/deprecated.php/)
```
function add_custom_background( $wp_head_callback = '', $admin_head_callback = '', $admin_preview_callback = '' ) {
_deprecated_function( __FUNCTION__, '3.4.0', 'add_theme_support( \'custom-background\', $args )' );
$args = array();
if ( $wp_head_callback )
$args['wp-head-callback'] = $wp_head_callback;
if ( $admin_head_callback )
$args['admin-head-callback'] = $admin_head_callback;
if ( $admin_preview_callback )
$args['admin-preview-callback'] = $admin_preview_callback;
return add_theme_support( 'custom-background', $args );
}
```
| Uses | Description |
| --- | --- |
| [add\_theme\_support()](add_theme_support) wp-includes/theme.php | Registers theme support for a given feature. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Use [add\_theme\_support()](add_theme_support) |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress _wp_translate_php_url_constant_to_key( int $constant ): string|false \_wp\_translate\_php\_url\_constant\_to\_key( int $constant ): string|false
===========================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Translate a PHP\_URL\_\* constant to the named array keys PHP uses.
`$constant` int Required PHP\*URL\*\* constant. string|false The named key or false.
File: `wp-includes/http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/http.php/)
```
function _wp_translate_php_url_constant_to_key( $constant ) {
$translation = array(
PHP_URL_SCHEME => 'scheme',
PHP_URL_HOST => 'host',
PHP_URL_PORT => 'port',
PHP_URL_USER => 'user',
PHP_URL_PASS => 'pass',
PHP_URL_PATH => 'path',
PHP_URL_QUERY => 'query',
PHP_URL_FRAGMENT => 'fragment',
);
if ( isset( $translation[ $constant ] ) ) {
return $translation[ $constant ];
} else {
return false;
}
}
```
| Used By | Description |
| --- | --- |
| [\_get\_component\_from\_parsed\_url\_array()](_get_component_from_parsed_url_array) wp-includes/http.php | Retrieve a specific component from a parsed URL array. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress next_post_rel_link( string $title = '%title', bool $in_same_term = false, int[]|string $excluded_terms = '', string $taxonomy = 'category' ) next\_post\_rel\_link( string $title = '%title', bool $in\_same\_term = false, int[]|string $excluded\_terms = '', string $taxonomy = 'category' )
==================================================================================================================================================
Displays the relational link for the next post adjacent to the current post.
* [get\_adjacent\_post\_rel\_link()](get_adjacent_post_rel_link)
`$title` string Optional Link title format. Default `'%title'`. Default: `'%title'`
`$in_same_term` bool Optional Whether link should be in a same taxonomy term. Default: `false`
`$excluded_terms` int[]|string Optional Array or comma-separated list of excluded term IDs. Default: `''`
`$taxonomy` string Optional Taxonomy, if $in\_same\_term is true. Default `'category'`. Default: `'category'`
File: `wp-includes/link-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/link-template.php/)
```
function next_post_rel_link( $title = '%title', $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {
echo get_adjacent_post_rel_link( $title, $in_same_term, $excluded_terms, false, $taxonomy );
}
```
| Uses | Description |
| --- | --- |
| [get\_adjacent\_post\_rel\_link()](get_adjacent_post_rel_link) wp-includes/link-template.php | Retrieves the adjacent post relational link. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress get_sites( string|array $args = array() ): array|int get\_sites( string|array $args = array() ): array|int
=====================================================
Retrieves a list of sites matching requested arguments.
* [WP\_Site\_Query::parse\_query()](../classes/wp_site_query/parse_query)
`$args` string|array Optional Array or string of arguments. See [WP\_Site\_Query::\_\_construct()](../classes/wp_site_query/__construct) for information on accepted arguments. More Arguments from WP\_Site\_Query::\_\_construct( ... $query ) Array or query string of site query parameters.
* `site__in`int[]Array of site IDs to include.
* `site__not_in`int[]Array of site IDs to exclude.
* `count`boolWhether to return a site count (true) or array of site objects.
Default false.
* `date_query`arrayDate query clauses to limit sites by. See [WP\_Date\_Query](../classes/wp_date_query).
Default null.
* `fields`stringSite fields to return. Accepts `'ids'` (returns an array of site IDs) or empty (returns an array of complete site objects).
* `ID`intA site ID to only return that site.
* `number`intMaximum number of sites to retrieve. Default 100.
* `offset`intNumber of sites to offset the query. Used to build LIMIT clause.
Default 0.
* `no_found_rows`boolWhether to disable the `SQL_CALC_FOUND_ROWS` query. Default true.
* `orderby`string|arraySite status or array of statuses. Accepts:
+ `'id'`
+ `'domain'`
+ `'path'`
+ `'network_id'`
+ `'last_updated'`
+ `'registered'`
+ `'domain_length'`
+ `'path_length'`
+ `'site__in'`
+ `'network__in'`
+ `'deleted'`
+ `'mature'`
+ `'spam'`
+ `'archived'`
+ `'public'`
+ false, an empty array, or `'none'` to disable `ORDER BY` clause. Default `'id'`.
* `order`stringHow to order retrieved sites. Accepts `'ASC'`, `'DESC'`. Default `'ASC'`.
* `network_id`intLimit results to those affiliated with a given network ID. If 0, include all networks. Default 0.
* `network__in`int[]Array of network IDs to include affiliated sites for.
* `network__not_in`int[]Array of network IDs to exclude affiliated sites for.
* `domain`stringLimit results to those affiliated with a given domain.
* `domain__in`string[]Array of domains to include affiliated sites for.
* `domain__not_in`string[]Array of domains to exclude affiliated sites for.
* `path`stringLimit results to those affiliated with a given path.
* `path__in`string[]Array of paths to include affiliated sites for.
* `path__not_in`string[]Array of paths to exclude affiliated sites for.
* `public`intLimit results to public sites. Accepts `'1'` or `'0'`.
* `archived`intLimit results to archived sites. Accepts `'1'` or `'0'`.
* `mature`intLimit results to mature sites. Accepts `'1'` or `'0'`.
* `spam`intLimit results to spam sites. Accepts `'1'` or `'0'`.
* `deleted`intLimit results to deleted sites. Accepts `'1'` or `'0'`.
* `lang_id`intLimit results to a language ID.
* `lang__in`string[]Array of language IDs to include affiliated sites for.
* `lang__not_in`string[]Array of language IDs to exclude affiliated sites for.
* `search`stringSearch term(s) to retrieve matching sites for.
* `search_columns`string[]Array of column names to be searched. Accepts `'domain'` and `'path'`.
Default empty array.
* `update_site_cache`boolWhether to prime the cache for found sites. Default true.
* `update_site_meta_cache`boolWhether to prime the metadata cache for found sites. Default true.
* `meta_key`string|string[]Meta key or keys to filter by.
* `meta_value`string|string[]Meta value or values to filter by.
* `meta_compare`stringMySQL operator used for comparing the meta value.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values and default value.
* `meta_compare_key`stringMySQL operator used for comparing the meta key.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values and default value.
* `meta_type`stringMySQL data type that the meta\_value column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values and default value.
* `meta_type_key`stringMySQL data type that the meta\_key column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values and default value.
* `meta_query`arrayAn associative array of [WP\_Meta\_Query](../classes/wp_meta_query) arguments.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values.
Default: `array()`
array|int List of [WP\_Site](../classes/wp_site) objects, a list of site IDs when `'fields'` is set to `'ids'`, or the number of sites when `'count'` is passed as a query var.
File: `wp-includes/ms-site.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-site.php/)
```
function get_sites( $args = array() ) {
$query = new WP_Site_Query();
return $query->query( $args );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Query::\_\_construct()](../classes/wp_site_query/__construct) wp-includes/class-wp-site-query.php | Sets up the site query, based on the query vars passed. |
| Used By | Description |
| --- | --- |
| [get\_oembed\_response\_data\_for\_url()](get_oembed_response_data_for_url) wp-includes/embed.php | Retrieves the oEmbed response data for a given URL. |
| [WP\_Network::get\_main\_site\_id()](../classes/wp_network/get_main_site_id) wp-includes/class-wp-network.php | Returns the main site ID for the network. |
| [WP\_MS\_Sites\_List\_Table::prepare\_items()](../classes/wp_ms_sites_list_table/prepare_items) wp-admin/includes/class-wp-ms-sites-list-table.php | Prepares the list of sites for display. |
| [WP\_Importer::set\_blog()](../classes/wp_importer/set_blog) wp-admin/includes/class-wp-importer.php | |
| [get\_blogs\_of\_user()](get_blogs_of_user) wp-includes/user.php | Gets the sites a user belongs to. |
| [wp\_get\_sites()](wp_get_sites) wp-includes/ms-deprecated.php | Return an array of sites for a network or networks. |
| [wp\_update\_network\_site\_counts()](wp_update_network_site_counts) wp-includes/ms-functions.php | Updates the network-wide site count. |
| [domain\_exists()](domain_exists) wp-includes/ms-functions.php | Checks whether a site name is already taken. |
| [get\_blog\_id\_from\_url()](get_blog_id_from_url) wp-includes/ms-functions.php | Gets a blog’s numeric ID from its URL. |
| [get\_site\_by\_path()](get_site_by_path) wp-includes/ms-load.php | Retrieves the closest matching site object by its domain and path. |
| [get\_id\_from\_blogname()](get_id_from_blogname) wp-includes/ms-blogs.php | Retrieves a site’s ID given its (subdomain or directory) slug. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced the `'lang_id'`, `'lang__in'`, and `'lang__not_in'` parameters. |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress _get_path_to_translation_from_lang_dir( string $domain ): string|false \_get\_path\_to\_translation\_from\_lang\_dir( string $domain ): string|false
=============================================================================
This function has been deprecated. Use [\_get\_path\_to\_translation()](_get_path_to_translation) instead.
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness. Use [\_get\_path\_to\_translation()](_get_path_to_translation) instead.
Gets the path to a translation file in the languages directory for the current locale.
Holds a cached list of available .mo files to improve performance.
* [\_get\_path\_to\_translation()](_get_path_to_translation)
`$domain` string Required Text domain. Unique identifier for retrieving translated strings. string|false The path to the translation file or false if no translation file was found.
File: `wp-includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/deprecated.php/)
```
function _get_path_to_translation_from_lang_dir( $domain ) {
_deprecated_function( __FUNCTION__, '6.1.0', 'WP_Textdomain_Registry' );
static $cached_mofiles = null;
if ( null === $cached_mofiles ) {
$cached_mofiles = array();
$locations = array(
WP_LANG_DIR . '/plugins',
WP_LANG_DIR . '/themes',
);
foreach ( $locations as $location ) {
$mofiles = glob( $location . '/*.mo' );
if ( $mofiles ) {
$cached_mofiles = array_merge( $cached_mofiles, $mofiles );
}
}
}
$locale = determine_locale();
$mofile = "{$domain}-{$locale}.mo";
$path = WP_LANG_DIR . '/plugins/' . $mofile;
if ( in_array( $path, $cached_mofiles, true ) ) {
return $path;
}
$path = WP_LANG_DIR . '/themes/' . $mofile;
if ( in_array( $path, $cached_mofiles, true ) ) {
return $path;
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [determine\_locale()](determine_locale) wp-includes/l10n.php | Determines the current locale desired for the request. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Used By | Description |
| --- | --- |
| [\_get\_path\_to\_translation()](_get_path_to_translation) wp-includes/deprecated.php | Gets the path to a translation file for loading a textdomain just in time. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | This function has been deprecated. Use [\_get\_path\_to\_translation()](_get_path_to_translation) instead. |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress get_current_user_id(): int get\_current\_user\_id(): int
=============================
Gets the current user’s ID.
int The current user's ID, or 0 if no user is logged in.
File: `wp-includes/user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/user.php/)
```
function get_current_user_id() {
if ( ! function_exists( 'wp_get_current_user' ) ) {
return 0;
}
$user = wp_get_current_user();
return ( isset( $user->ID ) ? (int) $user->ID : 0 );
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_current\_user()](wp_get_current_user) wp-includes/pluggable.php | Retrieves the current user object. |
| Used By | Description |
| --- | --- |
| [build\_comment\_query\_vars\_from\_block()](build_comment_query_vars_from_block) wp-includes/blocks.php | Helper function that constructs a comment query vars array from the passed block properties. |
| [WP\_REST\_Templates\_Controller::prepare\_item\_for\_database()](../classes/wp_rest_templates_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Prepares a single template for create or update. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_current\_item\_permissions\_check()](../classes/wp_rest_application_passwords_controller/get_current_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Checks if a given request has access to get the currently used application password for a user. |
| [WP\_REST\_Autosaves\_Controller::create\_item()](../classes/wp_rest_autosaves_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Creates, updates or deletes an autosave revision. |
| [WP\_REST\_Autosaves\_Controller::create\_post\_autosave()](../classes/wp_rest_autosaves_controller/create_post_autosave) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Creates autosave for the specified post. |
| [wp\_default\_packages\_inline\_scripts()](wp_default_packages_inline_scripts) wp-includes/script-loader.php | Adds inline scripts required for the WordPress JavaScript packages. |
| [do\_block\_editor\_incompatible\_meta\_box()](do_block_editor_incompatible_meta_box) wp-admin/includes/template.php | Renders a “fake” meta box with an information message, shown on the block editor, when an incompatible meta box is found. |
| [the\_block\_editor\_meta\_boxes()](the_block_editor_meta_boxes) wp-admin/includes/post.php | Renders the meta boxes forms. |
| [register\_and\_do\_post\_meta\_boxes()](register_and_do_post_meta_boxes) wp-admin/includes/meta-boxes.php | Registers the default post meta boxes, and runs the `do_meta_boxes` actions. |
| [WP\_Customize\_Manager::handle\_dismiss\_autosave\_or\_lock\_request()](../classes/wp_customize_manager/handle_dismiss_autosave_or_lock_request) wp-includes/class-wp-customize-manager.php | Deletes a given auto-draft changeset or the autosave revision for a given changeset or delete changeset lock. |
| [WP\_Customize\_Manager::handle\_changeset\_trash\_request()](../classes/wp_customize_manager/handle_changeset_trash_request) wp-includes/class-wp-customize-manager.php | Handles request to trash a changeset. |
| [WP\_Customize\_Manager::set\_changeset\_lock()](../classes/wp_customize_manager/set_changeset_lock) wp-includes/class-wp-customize-manager.php | Marks the changeset post as being currently edited by the current user. |
| [WP\_Customize\_Manager::refresh\_changeset\_lock()](../classes/wp_customize_manager/refresh_changeset_lock) wp-includes/class-wp-customize-manager.php | Refreshes changeset lock with the current time if current user edited the changeset before. |
| [WP\_Customize\_Manager::get\_changeset\_posts()](../classes/wp_customize_manager/get_changeset_posts) wp-includes/class-wp-customize-manager.php | Gets changeset posts. |
| [wp\_localize\_community\_events()](wp_localize_community_events) wp-includes/script-loader.php | Localizes community events data that needs to be passed to dashboard.js. |
| [WP\_Widget\_Text::render\_control\_template\_scripts()](../classes/wp_widget_text/render_control_template_scripts) wp-includes/widgets/class-wp-widget-text.php | Render form template scripts. |
| [wp\_ajax\_get\_community\_events()](wp_ajax_get_community_events) wp-admin/includes/ajax-actions.php | Handles Ajax requests for community events |
| [WP\_Customize\_Manager::\_publish\_changeset\_values()](../classes/wp_customize_manager/_publish_changeset_values) wp-includes/class-wp-customize-manager.php | Publishes the values of a changeset. |
| [WP\_Customize\_Manager::save\_changeset\_post()](../classes/wp_customize_manager/save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [WP\_Customize\_Manager::changeset\_data()](../classes/wp_customize_manager/changeset_data) wp-includes/class-wp-customize-manager.php | Gets changeset data. |
| [WP\_REST\_Users\_Controller::delete\_current\_item()](../classes/wp_rest_users_controller/delete_current_item) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Deletes the current user. |
| [WP\_REST\_Users\_Controller::check\_role\_update()](../classes/wp_rest_users_controller/check_role_update) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Determines if the current user is allowed to make the desired roles change. |
| [WP\_REST\_Users\_Controller::update\_current\_item\_permissions\_check()](../classes/wp_rest_users_controller/update_current_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Checks if a given request has access to update the current user. |
| [WP\_REST\_Users\_Controller::update\_current\_item()](../classes/wp_rest_users_controller/update_current_item) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Updates the current user. |
| [WP\_REST\_Users\_Controller::delete\_current\_item\_permissions\_check()](../classes/wp_rest_users_controller/delete_current_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Checks if a given request has access to delete the current user. |
| [WP\_REST\_Users\_Controller::get\_current\_item()](../classes/wp_rest_users_controller/get_current_item) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Retrieves the current user. |
| [WP\_REST\_Users\_Controller::get\_item\_permissions\_check()](../classes/wp_rest_users_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Checks if a given request has access to read a user. |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_database()](../classes/wp_rest_posts_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post for create or update. |
| [WP\_REST\_Posts\_Controller::update\_item\_permissions\_check()](../classes/wp_rest_posts_controller/update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to update a post. |
| [WP\_REST\_Posts\_Controller::create\_item\_permissions\_check()](../classes/wp_rest_posts_controller/create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to create a post. |
| [WP\_REST\_Comments\_Controller::check\_edit\_permission()](../classes/wp_rest_comments_controller/check_edit_permission) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Checks if a comment can be edited or deleted. |
| [WP\_REST\_Comments\_Controller::check\_read\_permission()](../classes/wp_rest_comments_controller/check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Checks if the comment can be read. |
| [WP\_REST\_Comments\_Controller::create\_item\_permissions\_check()](../classes/wp_rest_comments_controller/create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Checks if a given request has access to create a comment. |
| [wp\_check\_comment\_flood()](wp_check_comment_flood) wp-includes/comment.php | Checks whether comment flooding is occurring. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](../classes/wp_customize_manager/customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [WP\_Screen::render\_meta\_boxes\_preferences()](../classes/wp_screen/render_meta_boxes_preferences) wp-admin/includes/class-wp-screen.php | Renders the meta boxes preferences. |
| [wp\_ajax\_save\_wporg\_username()](wp_ajax_save_wporg_username) wp-admin/includes/ajax-actions.php | Ajax handler for saving the user’s WordPress.org username. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::value\_as\_wp\_post\_nav\_menu\_item()](../classes/wp_customize_nav_menu_item_setting/value_as_wp_post_nav_menu_item) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get the value emulated into a [WP\_Post](../classes/wp_post) and set up as a nav\_menu\_item. |
| [wp\_edit\_attachments\_query\_vars()](wp_edit_attachments_query_vars) wp-admin/includes/post.php | Returns the query variables for the current attachments request. |
| [wp\_ajax\_destroy\_sessions()](wp_ajax_destroy_sessions) wp-admin/includes/ajax-actions.php | Ajax handler for destroying multiple open sessions for a user. |
| [wp\_destroy\_all\_sessions()](wp_destroy_all_sessions) wp-includes/user.php | Removes all session tokens for the current user from the database. |
| [wp\_get\_all\_sessions()](wp_get_all_sessions) wp-includes/user.php | Retrieves a list of sessions for the current user. |
| [wp\_destroy\_current\_session()](wp_destroy_current_session) wp-includes/user.php | Removes the current session token from the database. |
| [wp\_destroy\_other\_sessions()](wp_destroy_other_sessions) wp-includes/user.php | Removes all but the current session token for the current user for the database. |
| [\_access\_denied\_splash()](_access_denied_splash) wp-admin/includes/ms.php | Displays an access denied message when a user tries to view a site’s dashboard they do not have access to. |
| [choose\_primary\_blog()](choose_primary_blog) wp-admin/includes/ms.php | Handles the display of choosing a user’s primary site. |
| [new\_user\_email\_admin\_notice()](new_user_email_admin_notice) wp-includes/user.php | Adds an admin notice alerting the user to check for confirmation request email after email address change. |
| [install\_plugins\_favorites\_form()](install_plugins_favorites_form) wp-admin/includes/plugin-install.php | Shows a username form for the favorites page. |
| [wp\_dashboard\_quick\_press()](wp_dashboard_quick_press) wp-admin/includes/dashboard.php | The Quick Draft widget display and creation of drafts. |
| [wp\_dashboard\_recent\_drafts()](wp_dashboard_recent_drafts) wp-admin/includes/dashboard.php | Show recent drafts of the user on the dashboard. |
| [edit\_user()](edit_user) wp-admin/includes/user.php | Edit user settings based on contents of $\_POST |
| [WP\_Plugin\_Install\_List\_Table::prepare\_items()](../classes/wp_plugin_install_list_table/prepare_items) wp-admin/includes/class-wp-plugin-install-list-table.php | |
| [WP\_Internal\_Pointers::enqueue\_scripts()](../classes/wp_internal_pointers/enqueue_scripts) wp-admin/includes/class-wp-internal-pointers.php | Initializes the new feature pointers. |
| [WP\_Users\_List\_Table::single\_row()](../classes/wp_users_list_table/single_row) wp-admin/includes/class-wp-users-list-table.php | Generate HTML for a single row on the users.php admin panel. |
| [wp\_check\_post\_lock()](wp_check_post_lock) wp-admin/includes/post.php | Determines whether the post is currently being edited by another user. |
| [wp\_set\_post\_lock()](wp_set_post_lock) wp-admin/includes/post.php | Marks the post as currently being edited by the current user. |
| [wp\_create\_post\_autosave()](wp_create_post_autosave) wp-admin/includes/post.php | Creates autosave data for the specified post from `$_POST` data. |
| [post\_preview()](post_preview) wp-admin/includes/post.php | Saves a draft or manually autosaves for the purpose of showing a post preview. |
| [wp\_autosave()](wp_autosave) wp-admin/includes/post.php | Saves a post submitted with XHR. |
| [\_wp\_translate\_postdata()](_wp_translate_postdata) wp-admin/includes/post.php | Renames `$_POST` data from form names to DB post columns. |
| [edit\_post()](edit_post) wp-admin/includes/post.php | Updates an existing post with values provided in `$_POST`. |
| [bulk\_edit\_posts()](bulk_edit_posts) wp-admin/includes/post.php | Processes the post data for the bulk editing of posts. |
| [wp\_ajax\_save\_user\_color\_scheme()](wp_ajax_save_user_color_scheme) wp-admin/includes/ajax-actions.php | Ajax handler for auto-saving the selected color scheme for a user’s own profile. |
| [wp\_ajax\_wp\_remove\_post\_lock()](wp_ajax_wp_remove_post_lock) wp-admin/includes/ajax-actions.php | Ajax handler for removing a post lock. |
| [wp\_ajax\_dismiss\_wp\_pointer()](wp_ajax_dismiss_wp_pointer) wp-admin/includes/ajax-actions.php | Ajax handler for dismissing a WordPress pointer. |
| [wp\_ajax\_update\_welcome\_panel()](wp_ajax_update_welcome_panel) wp-admin/includes/ajax-actions.php | Ajax handler for updating whether to display the welcome panel. |
| [wp\_ajax\_inline\_save()](wp_ajax_inline_save) wp-admin/includes/ajax-actions.php | Ajax handler for Quick Edit saving a post from a list table. |
| [wp\_insert\_link()](wp_insert_link) wp-admin/includes/bookmark.php | Inserts a link into the database, or updates an existing link. |
| [WP\_Media\_List\_Table::display\_rows()](../classes/wp_media_list_table/display_rows) wp-admin/includes/class-wp-media-list-table.php | |
| [WP\_Comments\_List\_Table::get\_views()](../classes/wp_comments_list_table/get_views) wp-admin/includes/class-wp-comments-list-table.php | |
| [WP\_Posts\_List\_Table::single\_row()](../classes/wp_posts_list_table/single_row) wp-admin/includes/class-wp-posts-list-table.php | |
| [WP\_Posts\_List\_Table::get\_views()](../classes/wp_posts_list_table/get_views) wp-admin/includes/class-wp-posts-list-table.php | |
| [WP\_Posts\_List\_Table::\_\_construct()](../classes/wp_posts_list_table/__construct) wp-admin/includes/class-wp-posts-list-table.php | Constructor. |
| [WP\_Posts\_List\_Table::prepare\_items()](../classes/wp_posts_list_table/prepare_items) wp-admin/includes/class-wp-posts-list-table.php | |
| [wp\_notify\_postauthor()](wp_notify_postauthor) wp-includes/pluggable.php | Notifies an author (and/or others) of a comment/trackback/pingback on a post. |
| [wp\_clear\_auth\_cookie()](wp_clear_auth_cookie) wp-includes/pluggable.php | Removes all of the cookies associated with authentication. |
| [wp\_logout()](wp_logout) wp-includes/pluggable.php | Logs the current user out. |
| [wp\_admin\_bar\_dashboard\_view\_site\_menu()](wp_admin_bar_dashboard_view_site_menu) wp-includes/deprecated.php | Add the “Dashboard”/”Visit Site” menu. |
| [is\_blog\_user()](is_blog_user) wp-includes/deprecated.php | Checks if the current user belong to a given site. |
| [WP\_Query::get\_posts()](../classes/wp_query/get_posts) wp-includes/class-wp-query.php | Retrieves an array of posts based on query variables. |
| [get\_dashboard\_url()](get_dashboard_url) wp-includes/link-template.php | Retrieves the URL to the user’s dashboard. |
| [get\_edit\_profile\_url()](get_edit_profile_url) wp-includes/link-template.php | Retrieves the URL to the user’s profile editor. |
| [get\_edit\_user\_link()](get_edit_user_link) wp-includes/link-template.php | Retrieves the edit user link. |
| [get\_adjacent\_post()](get_adjacent_post) wp-includes/link-template.php | Retrieves the adjacent post. |
| [WP\_Admin\_Bar::initialize()](../classes/wp_admin_bar/initialize) wp-includes/class-wp-admin-bar.php | Initializes the admin bar. |
| [wp\_admin\_bar\_wp\_menu()](wp_admin_bar_wp_menu) wp-includes/admin-bar.php | Adds the WordPress logo menu. |
| [wp\_admin\_bar\_my\_account\_item()](wp_admin_bar_my_account_item) wp-includes/admin-bar.php | Adds the “My Account” item. |
| [wp\_admin\_bar\_my\_account\_menu()](wp_admin_bar_my_account_menu) wp-includes/admin-bar.php | Adds the “My Account” submenu items. |
| [wp\_user\_settings()](wp_user_settings) wp-includes/option.php | Saves and restores user interface settings stored in a cookie. |
| [get\_all\_user\_settings()](get_all_user_settings) wp-includes/option.php | Retrieves all user interface settings. |
| [wp\_set\_all\_user\_settings()](wp_set_all_user_settings) wp-includes/option.php | Private. Sets all user interface settings. |
| [delete\_all\_user\_settings()](delete_all_user_settings) wp-includes/option.php | Deletes the user settings of the current user. |
| [is\_user\_member\_of\_blog()](is_user_member_of_blog) wp-includes/user.php | Finds out whether a user is a member of a given blog. |
| [setup\_userdata()](setup_userdata) wp-includes/user.php | Sets up global user vars. |
| [get\_user\_option()](get_user_option) wp-includes/user.php | Retrieves user option that can be either per Site or per Network. |
| [get\_posts\_by\_author\_sql()](get_posts_by_author_sql) wp-includes/post.php | Retrieves the post SQL based on capability, author, and type. |
| [wp\_insert\_post()](wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [\_count\_posts\_cache\_key()](_count_posts_cache_key) wp-includes/post.php | Returns the cache key for [wp\_count\_posts()](wp_count_posts) based on the passed arguments. |
| [wp\_count\_posts()](wp_count_posts) wp-includes/post.php | Counts number of posts of a post type and if user has permissions to view. |
| [wp\_restore\_post\_revision()](wp_restore_post_revision) wp-includes/revision.php | Restores a post to the specified revision. |
| [is\_site\_admin()](is_site_admin) wp-includes/ms-deprecated.php | Determine if user is a site admin. |
| [wp\_list\_comments()](wp_list_comments) wp-includes/comment-template.php | Displays a list of comments. |
| [comments\_template()](comments_template) wp-includes/comment-template.php | Loads the comment template specified in $file. |
| [wp\_default\_scripts()](wp_default_scripts) wp-includes/script-loader.php | Registers all WordPress scripts. |
| [get\_page\_of\_comment()](get_page_of_comment) wp-includes/comment.php | Calculates what page number a comment will appear on for comment paging. |
| Version | Description |
| --- | --- |
| [MU (3.0.0)](https://developer.wordpress.org/reference/since/mu.3.0.0/) | Introduced. |
| programming_docs |
wordpress separate_comments( WP_Comment[] $comments ): WP_Comment[] separate\_comments( WP\_Comment[] $comments ): WP\_Comment[]
============================================================
Separates an array of comments into an array keyed by comment\_type.
`$comments` [WP\_Comment](../classes/wp_comment)[] Required Array of comments [WP\_Comment](../classes/wp_comment)[] Array of comments keyed by comment\_type.
File: `wp-includes/comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/comment.php/)
```
function separate_comments( &$comments ) {
$comments_by_type = array(
'comment' => array(),
'trackback' => array(),
'pingback' => array(),
'pings' => array(),
);
$count = count( $comments );
for ( $i = 0; $i < $count; $i++ ) {
$type = $comments[ $i ]->comment_type;
if ( empty( $type ) ) {
$type = 'comment';
}
$comments_by_type[ $type ][] = &$comments[ $i ];
if ( 'trackback' === $type || 'pingback' === $type ) {
$comments_by_type['pings'][] = &$comments[ $i ];
}
}
return $comments_by_type;
}
```
| Used By | Description |
| --- | --- |
| [wp\_list\_comments()](wp_list_comments) wp-includes/comment-template.php | Displays a list of comments. |
| [comments\_template()](comments_template) wp-includes/comment-template.php | Loads the comment template specified in $file. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress wp_new_blog_notification( string $blog_title, string $blog_url, int $user_id, string $password ) wp\_new\_blog\_notification( string $blog\_title, string $blog\_url, int $user\_id, string $password )
======================================================================================================
Notifies the site admin that the installation of WordPress is complete.
Sends an email to the new administrator that the installation is complete and provides them with a record of their login credentials.
`$blog_title` string Required Site title. `$blog_url` string Required Site URL. `$user_id` int Required Administrator's user ID. `$password` string Required Administrator's password. Note that a placeholder message is usually passed instead of the actual password. File: `wp-admin/includes/upgrade.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/upgrade.php/)
```
function wp_new_blog_notification( $blog_title, $blog_url, $user_id, $password ) {
$user = new WP_User( $user_id );
$email = $user->user_email;
$name = $user->user_login;
$login_url = wp_login_url();
$message = sprintf(
/* translators: New site notification email. 1: New site URL, 2: User login, 3: User password or password reset link, 4: Login URL. */
__(
'Your new WordPress site has been successfully set up at:
%1$s
You can log in to the administrator account with the following information:
Username: %2$s
Password: %3$s
Log in here: %4$s
We hope you enjoy your new site. Thanks!
--The WordPress Team
https://wordpress.org/
'
),
$blog_url,
$name,
$password,
$login_url
);
$installed_email = array(
'to' => $email,
'subject' => __( 'New WordPress Site' ),
'message' => $message,
'headers' => '',
);
/**
* Filters the contents of the email sent to the site administrator when WordPress is installed.
*
* @since 5.6.0
*
* @param array $installed_email {
* Used to build wp_mail().
*
* @type string $to The email address of the recipient.
* @type string $subject The subject of the email.
* @type string $message The content of the email.
* @type string $headers Headers.
* }
* @param WP_User $user The site administrator user object.
* @param string $blog_title The site title.
* @param string $blog_url The site URL.
* @param string $password The site administrator's password. Note that a placeholder message
* is usually passed instead of the user's actual password.
*/
$installed_email = apply_filters( 'wp_installed_email', $installed_email, $user, $blog_title, $blog_url, $password );
wp_mail(
$installed_email['to'],
$installed_email['subject'],
$installed_email['message'],
$installed_email['headers']
);
}
```
[apply\_filters( 'wp\_installed\_email', array $installed\_email, WP\_User $user, string $blog\_title, string $blog\_url, string $password )](../hooks/wp_installed_email)
Filters the contents of the email sent to the site administrator when WordPress is installed.
| Uses | Description |
| --- | --- |
| [WP\_User::\_\_construct()](../classes/wp_user/__construct) wp-includes/class-wp-user.php | Constructor. |
| [wp\_mail()](wp_mail) wp-includes/pluggable.php | Sends an email, similar to PHP’s mail function. |
| [wp\_login\_url()](wp_login_url) wp-includes/general-template.php | Retrieves the login URL. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_install()](wp_install) wp-admin/includes/upgrade.php | Installs the site. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress _update_generic_term_count( int[] $terms, WP_Taxonomy $taxonomy ) \_update\_generic\_term\_count( int[] $terms, WP\_Taxonomy $taxonomy )
======================================================================
Updates term count based on number of objects.
Default callback for the ‘link\_category’ taxonomy.
`$terms` int[] Required List of term taxonomy IDs. `$taxonomy` [WP\_Taxonomy](../classes/wp_taxonomy) Required Current taxonomy object of terms. File: `wp-includes/taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/taxonomy.php/)
```
function _update_generic_term_count( $terms, $taxonomy ) {
global $wpdb;
foreach ( (array) $terms as $term ) {
$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
/** This action is documented in wp-includes/taxonomy.php */
do_action( 'edit_term_taxonomy', $term, $taxonomy->name );
$wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
/** This action is documented in wp-includes/taxonomy.php */
do_action( 'edited_term_taxonomy', $term, $taxonomy->name );
}
}
```
[do\_action( 'edited\_term\_taxonomy', int $tt\_id, string $taxonomy, array $args )](../hooks/edited_term_taxonomy)
Fires immediately after a term-taxonomy relationship is updated.
[do\_action( 'edit\_term\_taxonomy', int $tt\_id, string $taxonomy, array $args )](../hooks/edit_term_taxonomy)
Fires immediate before a term-taxonomy relationship is updated.
| Uses | Description |
| --- | --- |
| [wpdb::update()](../classes/wpdb/update) wp-includes/class-wpdb.php | Updates a row in the table. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wpdb::get\_var()](../classes/wpdb/get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| [wpdb::prepare()](../classes/wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [wp\_update\_term\_count\_now()](wp_update_term_count_now) wp-includes/taxonomy.php | Performs term count update immediately. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress wp_register_tinymce_scripts( WP_Scripts $scripts, bool $force_uncompressed = false ) wp\_register\_tinymce\_scripts( WP\_Scripts $scripts, bool $force\_uncompressed = false )
=========================================================================================
Registers TinyMCE scripts.
`$scripts` [WP\_Scripts](../classes/wp_scripts) Required [WP\_Scripts](../classes/wp_scripts) object. `$force_uncompressed` bool Optional Whether to forcibly prevent gzip compression. Default: `false`
File: `wp-includes/script-loader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/script-loader.php/)
```
function wp_register_tinymce_scripts( $scripts, $force_uncompressed = false ) {
global $tinymce_version, $concatenate_scripts, $compress_scripts;
$suffix = wp_scripts_get_suffix();
$dev_suffix = wp_scripts_get_suffix( 'dev' );
script_concat_settings();
$compressed = $compress_scripts && $concatenate_scripts && isset( $_SERVER['HTTP_ACCEPT_ENCODING'] )
&& false !== stripos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip' ) && ! $force_uncompressed;
// Load tinymce.js when running from /src, otherwise load wp-tinymce.js.gz (in production)
// or tinymce.min.js (when SCRIPT_DEBUG is true).
if ( $compressed ) {
$scripts->add( 'wp-tinymce', includes_url( 'js/tinymce/' ) . 'wp-tinymce.js', array(), $tinymce_version );
} else {
$scripts->add( 'wp-tinymce-root', includes_url( 'js/tinymce/' ) . "tinymce$dev_suffix.js", array(), $tinymce_version );
$scripts->add( 'wp-tinymce', includes_url( 'js/tinymce/' ) . "plugins/compat3x/plugin$dev_suffix.js", array( 'wp-tinymce-root' ), $tinymce_version );
}
$scripts->add( 'wp-tinymce-lists', includes_url( "js/tinymce/plugins/lists/plugin$suffix.js" ), array( 'wp-tinymce' ), $tinymce_version );
}
```
| Uses | Description |
| --- | --- |
| [stripos()](stripos) wp-includes/class-pop3.php | |
| [wp\_scripts\_get\_suffix()](wp_scripts_get_suffix) wp-includes/script-loader.php | Returns the suffix that can be used for the scripts. |
| [includes\_url()](includes_url) wp-includes/link-template.php | Retrieves the URL to the includes directory. |
| [script\_concat\_settings()](script_concat_settings) wp-includes/script-loader.php | Determines the concatenation and compression settings for scripts and styles. |
| Used By | Description |
| --- | --- |
| [\_WP\_Editors::force\_uncompressed\_tinymce()](../classes/_wp_editors/force_uncompressed_tinymce) wp-includes/class-wp-editor.php | Force uncompressed TinyMCE when a custom theme has been defined. |
| [wp\_default\_packages()](wp_default_packages) wp-includes/script-loader.php | Registers all the WordPress packages scripts. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress is_child_theme(): bool is\_child\_theme(): bool
========================
Whether a child theme is in use.
bool True if a child theme is in use, false otherwise.
File: `wp-includes/theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/theme.php/)
```
function is_child_theme() {
return ( TEMPLATEPATH !== STYLESHEETPATH );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::get\_test\_theme\_version()](../classes/wp_site_health/get_test_theme_version) wp-admin/includes/class-wp-site-health.php | Tests if themes are outdated, or unnecessary. |
| [WP\_Customize\_Manager::prepare\_starter\_content\_attachments()](../classes/wp_customize_manager/prepare_starter_content_attachments) wp-includes/class-wp-customize-manager.php | Prepares starter content attachments. |
| [get\_editor\_stylesheets()](get_editor_stylesheets) wp-includes/theme.php | Retrieves any registered editor stylesheet URLs. |
| [validate\_current\_theme()](validate_current_theme) wp-includes/theme.php | Checks that the active theme has the required files. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress wp_print_plugin_file_tree( array|string $tree, string $label = '', int $level = 2, int $size = 1, int $index = 1 ) wp\_print\_plugin\_file\_tree( array|string $tree, string $label = '', int $level = 2, int $size = 1, int $index = 1 )
======================================================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Outputs the formatted file list for the plugin file editor.
`$tree` array|string Required List of file/folder paths, or filename. `$label` string Optional Name of file or folder to print. Default: `''`
`$level` int Optional The aria-level for the current iteration. Default: `2`
`$size` int Optional The aria-setsize for the current iteration. Default: `1`
`$index` int Optional The aria-posinset for the current iteration. Default: `1`
File: `wp-admin/includes/misc.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/misc.php/)
```
function wp_print_plugin_file_tree( $tree, $label = '', $level = 2, $size = 1, $index = 1 ) {
global $file, $plugin;
if ( is_array( $tree ) ) {
$index = 0;
$size = count( $tree );
foreach ( $tree as $label => $plugin_file ) :
$index++;
if ( ! is_array( $plugin_file ) ) {
wp_print_plugin_file_tree( $plugin_file, $label, $level, $index, $size );
continue;
}
?>
<li role="treeitem" aria-expanded="true" tabindex="-1"
aria-level="<?php echo esc_attr( $level ); ?>"
aria-setsize="<?php echo esc_attr( $size ); ?>"
aria-posinset="<?php echo esc_attr( $index ); ?>">
<span class="folder-label"><?php echo esc_html( $label ); ?> <span class="screen-reader-text"><?php _e( 'folder' ); ?></span><span aria-hidden="true" class="icon"></span></span>
<ul role="group" class="tree-folder"><?php wp_print_plugin_file_tree( $plugin_file, '', $level + 1, $index, $size ); ?></ul>
</li>
<?php
endforeach;
} else {
$url = add_query_arg(
array(
'file' => rawurlencode( $tree ),
'plugin' => rawurlencode( $plugin ),
),
self_admin_url( 'plugin-editor.php' )
);
?>
<li role="none" class="<?php echo esc_attr( $file === $tree ? 'current-file' : '' ); ?>">
<a role="treeitem" tabindex="<?php echo esc_attr( $file === $tree ? '0' : '-1' ); ?>"
href="<?php echo esc_url( $url ); ?>"
aria-level="<?php echo esc_attr( $level ); ?>"
aria-setsize="<?php echo esc_attr( $size ); ?>"
aria-posinset="<?php echo esc_attr( $index ); ?>">
<?php
if ( $file === $tree ) {
echo '<span class="notice notice-info">' . esc_html( $label ) . '</span>';
} else {
echo esc_html( $label );
}
?>
</a>
</li>
<?php
}
}
```
| Uses | Description |
| --- | --- |
| [self\_admin\_url()](self_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for either the current site or the network depending on context. |
| [wp\_print\_plugin\_file\_tree()](wp_print_plugin_file_tree) wp-admin/includes/misc.php | Outputs the formatted file list for the plugin file editor. |
| [\_e()](_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [add\_query\_arg()](add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| Used By | Description |
| --- | --- |
| [wp\_print\_plugin\_file\_tree()](wp_print_plugin_file_tree) wp-admin/includes/misc.php | Outputs the formatted file list for the plugin file editor. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress clean_blog_cache( WP_Site|int $blog ) clean\_blog\_cache( WP\_Site|int $blog )
========================================
Clean the blog cache
`$blog` [WP\_Site](../classes/wp_site)|int Required The site object or ID to be cleared from cache. File: `wp-includes/ms-site.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-site.php/)
```
function clean_blog_cache( $blog ) {
global $_wp_suspend_cache_invalidation;
if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
return;
}
if ( empty( $blog ) ) {
return;
}
$blog_id = $blog;
$blog = get_site( $blog_id );
if ( ! $blog ) {
if ( ! is_numeric( $blog_id ) ) {
return;
}
// Make sure a WP_Site object exists even when the site has been deleted.
$blog = new WP_Site(
(object) array(
'blog_id' => $blog_id,
'domain' => null,
'path' => null,
)
);
}
$blog_id = $blog->blog_id;
$domain_path_key = md5( $blog->domain . $blog->path );
wp_cache_delete( $blog_id, 'sites' );
wp_cache_delete( $blog_id, 'site-details' );
wp_cache_delete( $blog_id, 'blog-details' );
wp_cache_delete( $blog_id . 'short', 'blog-details' );
wp_cache_delete( $domain_path_key, 'blog-lookup' );
wp_cache_delete( $domain_path_key, 'blog-id-cache' );
wp_cache_delete( $blog_id, 'blog_meta' );
/**
* Fires immediately after a site has been removed from the object cache.
*
* @since 4.6.0
*
* @param string $id Site ID as a numeric string.
* @param WP_Site $blog Site object.
* @param string $domain_path_key md5 hash of domain and path.
*/
do_action( 'clean_site_cache', $blog_id, $blog, $domain_path_key );
wp_cache_set( 'last_changed', microtime(), 'sites' );
/**
* Fires after the blog details cache is cleared.
*
* @since 3.4.0
* @deprecated 4.9.0 Use {@see 'clean_site_cache'} instead.
*
* @param int $blog_id Blog ID.
*/
do_action_deprecated( 'refresh_blog_details', array( $blog_id ), '4.9.0', 'clean_site_cache' );
}
```
[do\_action( 'clean\_site\_cache', string $id, WP\_Site $blog, string $domain\_path\_key )](../hooks/clean_site_cache)
Fires immediately after a site has been removed from the object cache.
[do\_action\_deprecated( 'refresh\_blog\_details', int $blog\_id )](../hooks/refresh_blog_details)
Fires after the blog details cache is cleared.
| Uses | Description |
| --- | --- |
| [get\_site()](get_site) wp-includes/ms-site.php | Retrieves site data given a site ID or site object. |
| [do\_action\_deprecated()](do_action_deprecated) wp-includes/plugin.php | Fires functions attached to a deprecated action hook. |
| [WP\_Site::\_\_construct()](../classes/wp_site/__construct) wp-includes/class-wp-site.php | Creates a new [WP\_Site](../classes/wp_site) object. |
| [wp\_cache\_delete()](wp_cache_delete) wp-includes/cache.php | Removes the cache contents matching key and group. |
| [wp\_cache\_set()](wp_cache_set) wp-includes/cache.php | Saves the data to the cache. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [wp\_maybe\_clean\_new\_site\_cache\_on\_update()](wp_maybe_clean_new_site_cache_on_update) wp-includes/ms-site.php | Cleans the necessary caches after specific site data has been updated. |
| [wp\_initialize\_site()](wp_initialize_site) wp-includes/ms-site.php | Runs the initialization routine for a given site. |
| [wp\_insert\_site()](wp_insert_site) wp-includes/ms-site.php | Inserts a new site into the database. |
| [wp\_update\_site()](wp_update_site) wp-includes/ms-site.php | Updates a site in the database. |
| [wp\_delete\_site()](wp_delete_site) wp-includes/ms-site.php | Deletes a site from the database. |
| [insert\_blog()](insert_blog) wp-includes/ms-deprecated.php | Store basic site info in the blogs table. |
| [refresh\_blog\_details()](refresh_blog_details) wp-includes/ms-blogs.php | Clear the blog details cache. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
| programming_docs |
wordpress show_blog_form( string $blogname = '', string $blog_title = '', WP_Error|string $errors = '' ) show\_blog\_form( string $blogname = '', string $blog\_title = '', WP\_Error|string $errors = '' )
==================================================================================================
Generates and displays the Sign-up and Create Site forms.
`$blogname` string Optional The new site name. Default: `''`
`$blog_title` string Optional The new site title. Default: `''`
`$errors` [WP\_Error](../classes/wp_error)|string Optional A [WP\_Error](../classes/wp_error) object containing existing errors. Defaults to empty string. Default: `''`
File: `wp-signup.php`. [View all references](https://developer.wordpress.org/reference/files/wp-signup.php/)
```
function show_blog_form( $blogname = '', $blog_title = '', $errors = '' ) {
if ( ! is_wp_error( $errors ) ) {
$errors = new WP_Error();
}
$current_network = get_network();
// Blog name.
if ( ! is_subdomain_install() ) {
echo '<label for="blogname">' . __( 'Site Name (subdirectory only):' ) . '</label>';
} else {
echo '<label for="blogname">' . __( 'Site Domain (subdomain only):' ) . '</label>';
}
$errmsg_blogname = $errors->get_error_message( 'blogname' );
$errmsg_blogname_aria = '';
if ( $errmsg_blogname ) {
$errmsg_blogname_aria = 'wp-signup-blogname-error ';
echo '<p class="error" id="wp-signup-blogname-error">' . $errmsg_blogname . '</p>';
}
if ( ! is_subdomain_install() ) {
echo '<div class="wp-signup-blogname"><span class="prefix_address" id="prefix-address">' . $current_network->domain . $current_network->path . '</span><input name="blogname" type="text" id="blogname" value="' . esc_attr( $blogname ) . '" maxlength="60" autocomplete="off" required="required" aria-describedby="' . $errmsg_blogname_aria . 'prefix-address" /></div>';
} else {
$site_domain = preg_replace( '|^www\.|', '', $current_network->domain );
echo '<div class="wp-signup-blogname"><input name="blogname" type="text" id="blogname" value="' . esc_attr( $blogname ) . '" maxlength="60" autocomplete="off" required="required" aria-describedby="' . $errmsg_blogname_aria . 'suffix-address" /><span class="suffix_address" id="suffix-address">.' . esc_html( $site_domain ) . '</span></div>';
}
if ( ! is_user_logged_in() ) {
if ( ! is_subdomain_install() ) {
$site = $current_network->domain . $current_network->path . __( 'sitename' );
} else {
$site = __( 'domain' ) . '.' . $site_domain . $current_network->path;
}
printf(
'<p>(<strong>%s</strong>) %s</p>',
/* translators: %s: Site address. */
sprintf( __( 'Your address will be %s.' ), $site ),
__( 'Must be at least 4 characters, letters and numbers only. It cannot be changed, so choose carefully!' )
);
}
// Site Title.
?>
<label for="blog_title"><?php _e( 'Site Title:' ); ?></label>
<?php
$errmsg_blog_title = $errors->get_error_message( 'blog_title' );
$errmsg_blog_title_aria = '';
if ( $errmsg_blog_title ) {
$errmsg_blog_title_aria = ' aria-describedby="wp-signup-blog-title-error"';
echo '<p class="error" id="wp-signup-blog-title-error">' . $errmsg_blog_title . '</p>';
}
echo '<input name="blog_title" type="text" id="blog_title" value="' . esc_attr( $blog_title ) . '" required="required" autocomplete="off"' . $errmsg_blog_title_aria . ' />';
?>
<?php
// Site Language.
$languages = signup_get_available_languages();
if ( ! empty( $languages ) ) :
?>
<p>
<label for="site-language"><?php _e( 'Site Language:' ); ?></label>
<?php
// Network default.
$lang = get_site_option( 'WPLANG' );
if ( isset( $_POST['WPLANG'] ) ) {
$lang = $_POST['WPLANG'];
}
// Use US English if the default isn't available.
if ( ! in_array( $lang, $languages, true ) ) {
$lang = '';
}
wp_dropdown_languages(
array(
'name' => 'WPLANG',
'id' => 'site-language',
'selected' => $lang,
'languages' => $languages,
'show_available_translations' => false,
)
);
?>
</p>
<?php
endif; // Languages.
$blog_public_on_checked = '';
$blog_public_off_checked = '';
if ( isset( $_POST['blog_public'] ) && '0' === $_POST['blog_public'] ) {
$blog_public_off_checked = 'checked="checked"';
} else {
$blog_public_on_checked = 'checked="checked"';
}
?>
<div id="privacy">
<fieldset class="privacy-intro">
<legend>
<span class="label-heading"><?php _e( 'Privacy:' ); ?></span>
<?php _e( 'Allow search engines to index this site.' ); ?>
</legend>
<p class="wp-signup-radio-buttons">
<span class="wp-signup-radio-button">
<input type="radio" id="blog_public_on" name="blog_public" value="1" <?php echo $blog_public_on_checked; ?> />
<label class="checkbox" for="blog_public_on"><?php _e( 'Yes' ); ?></label>
</span>
<span class="wp-signup-radio-button">
<input type="radio" id="blog_public_off" name="blog_public" value="0" <?php echo $blog_public_off_checked; ?> />
<label class="checkbox" for="blog_public_off"><?php _e( 'No' ); ?></label>
</span>
</p>
</fieldset>
</div>
<?php
/**
* Fires after the site sign-up form.
*
* @since 3.0.0
*
* @param WP_Error $errors A WP_Error object possibly containing 'blogname' or 'blog_title' errors.
*/
do_action( 'signup_blogform', $errors );
}
```
[do\_action( 'signup\_blogform', WP\_Error $errors )](../hooks/signup_blogform)
Fires after the site sign-up form.
| Uses | Description |
| --- | --- |
| [get\_network()](get_network) wp-includes/ms-network.php | Retrieves network data given a network ID or network object. |
| [signup\_get\_available\_languages()](signup_get_available_languages) wp-signup.php | Retrieves languages available during the site/user sign-up process. |
| [wp\_dropdown\_languages()](wp_dropdown_languages) wp-includes/l10n.php | Displays or returns a Language selector. |
| [is\_subdomain\_install()](is_subdomain_install) wp-includes/ms-load.php | Whether a subdomain configuration is enabled. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_e()](_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [is\_user\_logged\_in()](is_user_logged_in) wp-includes/pluggable.php | Determines whether the current visitor is a logged in user. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_site\_option()](get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../classes/wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [signup\_another\_blog()](signup_another_blog) wp-signup.php | Shows a form for returning users to sign up for another site. |
| [signup\_blog()](signup_blog) wp-signup.php | Shows a form for a user or visitor to sign up for a new site. |
| Version | Description |
| --- | --- |
| [MU (3.0.0)](https://developer.wordpress.org/reference/since/mu.3.0.0/) | Introduced. |
wordpress wp_embed_register_handler( string $id, string $regex, callable $callback, int $priority = 10 ) wp\_embed\_register\_handler( string $id, string $regex, callable $callback, int $priority = 10 )
=================================================================================================
Registers an embed handler.
Should probably only be used for sites that do not support oEmbed.
`$id` string Required An internal ID/name for the handler. Needs to be unique. `$regex` string Required The regex that will be used to see if this handler should be used for a URL. `$callback` callable Required The callback function that will be called if the regex is matched. `$priority` int Optional Used to specify the order in which the registered handlers will be tested. Default: `10`
File: `wp-includes/embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/embed.php/)
```
function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
global $wp_embed;
$wp_embed->register_handler( $id, $regex, $callback, $priority );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Embed::register\_handler()](../classes/wp_embed/register_handler) wp-includes/class-wp-embed.php | Registers an embed handler. |
| Used By | Description |
| --- | --- |
| [wp\_maybe\_load\_embeds()](wp_maybe_load_embeds) wp-includes/embed.php | Determines if default embed handlers should be loaded. |
| Version | Description |
| --- | --- |
| [2.9.0](https://developer.wordpress.org/reference/since/2.9.0/) | Introduced. |
wordpress get_profile( string $field, false|int $user = false ): string get\_profile( string $field, false|int $user = false ): string
==============================================================
This function has been deprecated. Use [get\_the\_author\_meta()](get_the_author_meta) instead.
Retrieve user data based on field.
* [get\_the\_author\_meta()](get_the_author_meta)
`$field` string Required User meta field. `$user` false|int Optional User ID to retrieve the field for. Default false (current user). Default: `false`
string The author's field from the current author's DB object.
File: `wp-includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/deprecated.php/)
```
function get_profile( $field, $user = false ) {
_deprecated_function( __FUNCTION__, '3.0.0', 'get_the_author_meta()' );
if ( $user ) {
$user = get_user_by( 'login', $user );
$user = $user->ID;
}
return get_the_author_meta( $field, $user );
}
```
| Uses | Description |
| --- | --- |
| [get\_user\_by()](get_user_by) wp-includes/pluggable.php | Retrieves user info by a given field. |
| [get\_the\_author\_meta()](get_the_author_meta) wp-includes/author-template.php | Retrieves the requested data of the author of the current post. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Use [get\_the\_author\_meta()](get_the_author_meta) |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress rest_api_loaded() rest\_api\_loaded()
===================
Loads the REST API.
File: `wp-includes/rest-api.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api.php/)
```
function rest_api_loaded() {
if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
return;
}
/**
* Whether this is a REST Request.
*
* @since 4.4.0
* @var bool
*/
define( 'REST_REQUEST', true );
// Initialize the server.
$server = rest_get_server();
// Fire off the request.
$route = untrailingslashit( $GLOBALS['wp']->query_vars['rest_route'] );
if ( empty( $route ) ) {
$route = '/';
}
$server->serve_request( $route );
// We're done.
die();
}
```
| Uses | Description |
| --- | --- |
| [rest\_get\_server()](rest_get_server) wp-includes/rest-api.php | Retrieves the current REST server instance. |
| [untrailingslashit()](untrailingslashit) wp-includes/formatting.php | Removes trailing forward slashes and backslashes if they exist. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress get_post_reply_link( array $args = array(), int|WP_Post $post = null ): string|false|null get\_post\_reply\_link( array $args = array(), int|WP\_Post $post = null ): string|false|null
=============================================================================================
Retrieves HTML content for reply to post link.
`$args` array Optional Override default arguments.
* `add_below`stringThe first part of the selector used to identify the comment to respond below.
The resulting value is passed as the first parameter to addComment.moveForm(), concatenated as $add\_below-$comment->comment\_ID. Default is `'post'`.
* `respond_id`stringThe selector identifying the responding comment. Passed as the third parameter to addComment.moveForm(), and appended to the link URL as a hash value.
Default `'respond'`.
* `reply_text`stringText of the Reply link. Default is 'Leave a Comment'.
* `login_text`stringText of the link to reply if logged out. Default is 'Log in to leave a Comment'.
* `before`stringText or HTML to add before the reply link.
* `after`stringText or HTML to add after the reply link.
Default: `array()`
`$post` int|[WP\_Post](../classes/wp_post) Optional Post ID or [WP\_Post](../classes/wp_post) object the comment is going to be displayed on.
Default current post. Default: `null`
string|false|null Link to show comment form, if successful. False, if comments are closed.
File: `wp-includes/comment-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/comment-template.php/)
```
function get_post_reply_link( $args = array(), $post = null ) {
$defaults = array(
'add_below' => 'post',
'respond_id' => 'respond',
'reply_text' => __( 'Leave a Comment' ),
'login_text' => __( 'Log in to leave a Comment' ),
'before' => '',
'after' => '',
);
$args = wp_parse_args( $args, $defaults );
$post = get_post( $post );
if ( ! comments_open( $post->ID ) ) {
return false;
}
if ( get_option( 'comment_registration' ) && ! is_user_logged_in() ) {
$link = sprintf(
'<a rel="nofollow" class="comment-reply-login" href="%s">%s</a>',
wp_login_url( get_permalink() ),
$args['login_text']
);
} else {
$onclick = sprintf(
'return addComment.moveForm( "%1$s-%2$s", "0", "%3$s", "%2$s" )',
$args['add_below'],
$post->ID,
$args['respond_id']
);
$link = sprintf(
"<a rel='nofollow' class='comment-reply-link' href='%s' onclick='%s'>%s</a>",
get_permalink( $post->ID ) . '#' . $args['respond_id'],
$onclick,
$args['reply_text']
);
}
$formatted_link = $args['before'] . $link . $args['after'];
/**
* Filters the formatted post comments link HTML.
*
* @since 2.7.0
*
* @param string $formatted The HTML-formatted post comments link.
* @param int|WP_Post $post The post ID or WP_Post object.
*/
return apply_filters( 'post_comments_link', $formatted_link, $post );
}
```
[apply\_filters( 'post\_comments\_link', string $formatted, int|WP\_Post $post )](../hooks/post_comments_link)
Filters the formatted post comments link HTML.
| Uses | Description |
| --- | --- |
| [comments\_open()](comments_open) wp-includes/comment-template.php | Determines whether the current post is open for comments. |
| [wp\_login\_url()](wp_login_url) wp-includes/general-template.php | Retrieves the login URL. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_user\_logged\_in()](is_user_logged_in) wp-includes/pluggable.php | Determines whether the current visitor is a logged in user. |
| [wp\_parse\_args()](wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [get\_permalink()](get_permalink) wp-includes/link-template.php | Retrieves the full permalink for the current post or post ID. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [post\_reply\_link()](post_reply_link) wp-includes/comment-template.php | Displays the HTML content for reply to post link. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress ms_cookie_constants() ms\_cookie\_constants()
=======================
Defines Multisite cookie constants.
File: `wp-includes/ms-default-constants.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-default-constants.php/)
```
function ms_cookie_constants() {
$current_network = get_network();
/**
* @since 1.2.0
*/
if ( ! defined( 'COOKIEPATH' ) ) {
define( 'COOKIEPATH', $current_network->path );
}
/**
* @since 1.5.0
*/
if ( ! defined( 'SITECOOKIEPATH' ) ) {
define( 'SITECOOKIEPATH', $current_network->path );
}
/**
* @since 2.6.0
*/
if ( ! defined( 'ADMIN_COOKIE_PATH' ) ) {
$site_path = parse_url( get_option( 'siteurl' ), PHP_URL_PATH );
if ( ! is_subdomain_install() || is_string( $site_path ) && trim( $site_path, '/' ) ) {
define( 'ADMIN_COOKIE_PATH', SITECOOKIEPATH );
} else {
define( 'ADMIN_COOKIE_PATH', SITECOOKIEPATH . 'wp-admin' );
}
}
/**
* @since 2.0.0
*/
if ( ! defined( 'COOKIE_DOMAIN' ) && is_subdomain_install() ) {
if ( ! empty( $current_network->cookie_domain ) ) {
define( 'COOKIE_DOMAIN', '.' . $current_network->cookie_domain );
} else {
define( 'COOKIE_DOMAIN', '.' . $current_network->domain );
}
}
}
```
| Uses | Description |
| --- | --- |
| [get\_network()](get_network) wp-includes/ms-network.php | Retrieves network data given a network ID or network object. |
| [is\_subdomain\_install()](is_subdomain_install) wp-includes/ms-load.php | Whether a subdomain configuration is enabled. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress wp_get_default_update_php_url(): string wp\_get\_default\_update\_php\_url(): string
============================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Gets the default URL to learn more about updating the PHP version the site is running on.
Do not use this function to retrieve this URL. Instead, use [wp\_get\_update\_php\_url()](wp_get_update_php_url) when relying on the URL.
This function does not allow modifying the returned URL, and is only used to compare the actually used URL with the default one.
string Default URL to learn more about updating PHP.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function wp_get_default_update_php_url() {
return _x( 'https://wordpress.org/support/update-php/', 'localized PHP upgrade information page' );
}
```
| Uses | Description |
| --- | --- |
| [\_x()](_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| Used By | Description |
| --- | --- |
| [wp\_get\_update\_php\_annotation()](wp_get_update_php_annotation) wp-includes/functions.php | Returns the default annotation for the web hosting altering the “Update PHP” page URL. |
| [wp\_get\_update\_php\_url()](wp_get_update_php_url) wp-includes/functions.php | Gets the URL to learn more about updating the PHP version the site is running on. |
| Version | Description |
| --- | --- |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | Introduced. |
| programming_docs |
wordpress sanitize_category_field( string $field, mixed $value, int $cat_id, string $context ): mixed sanitize\_category\_field( string $field, mixed $value, int $cat\_id, string $context ): mixed
==============================================================================================
Sanitizes data in single category key field.
`$field` string Required Category key to sanitize. `$value` mixed Required Category value to sanitize. `$cat_id` int Required Category ID. `$context` string Required What filter to use, `'raw'`, `'display'`, etc. mixed Value after $value has been sanitized.
File: `wp-includes/category.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/category.php/)
```
function sanitize_category_field( $field, $value, $cat_id, $context ) {
return sanitize_term_field( $field, $value, $cat_id, 'category', $context );
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_term\_field()](sanitize_term_field) wp-includes/taxonomy.php | Sanitizes the field value in the term based on the context. |
| Version | Description |
| --- | --- |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
wordpress send_origin_headers(): string|false send\_origin\_headers(): string|false
=====================================
Send Access-Control-Allow-Origin and related headers if the current request is from an allowed origin.
If the request is an OPTIONS request, the script exits with either access control headers sent, or a 403 response if the origin is not allowed. For other request methods, you will receive a return value.
string|false Returns the origin URL if headers are sent. Returns false if headers are not sent.
File: `wp-includes/http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/http.php/)
```
function send_origin_headers() {
$origin = get_http_origin();
if ( is_allowed_http_origin( $origin ) ) {
header( 'Access-Control-Allow-Origin: ' . $origin );
header( 'Access-Control-Allow-Credentials: true' );
if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {
exit;
}
return $origin;
}
if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {
status_header( 403 );
exit;
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [status\_header()](status_header) wp-includes/functions.php | Sets HTTP status header. |
| [is\_allowed\_http\_origin()](is_allowed_http_origin) wp-includes/http.php | Determines if the HTTP origin is an authorized one. |
| [get\_http\_origin()](get_http_origin) wp-includes/http.php | Get the HTTP Origin of the current request. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::setup\_theme()](../classes/wp_customize_manager/setup_theme) wp-includes/class-wp-customize-manager.php | Starts preview and customize theme. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress _inject_theme_attribute_in_block_template_content( string $template_content ): string \_inject\_theme\_attribute\_in\_block\_template\_content( string $template\_content ): string
=============================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Parses wp\_template content and injects the active theme’s stylesheet as a theme attribute into each wp\_template\_part
`$template_content` string Required serialized wp\_template content. string Updated `'wp_template'` content.
File: `wp-includes/block-template-utils.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/block-template-utils.php/)
```
function _inject_theme_attribute_in_block_template_content( $template_content ) {
$has_updated_content = false;
$new_content = '';
$template_blocks = parse_blocks( $template_content );
$blocks = _flatten_blocks( $template_blocks );
foreach ( $blocks as &$block ) {
if (
'core/template-part' === $block['blockName'] &&
! isset( $block['attrs']['theme'] )
) {
$block['attrs']['theme'] = wp_get_theme()->get_stylesheet();
$has_updated_content = true;
}
}
if ( $has_updated_content ) {
foreach ( $template_blocks as &$block ) {
$new_content .= serialize_block( $block );
}
return $new_content;
}
return $template_content;
}
```
| Uses | Description |
| --- | --- |
| [\_flatten\_blocks()](_flatten_blocks) wp-includes/block-template-utils.php | Returns an array containing the references of the passed blocks and their inner blocks. |
| [serialize\_block()](serialize_block) wp-includes/blocks.php | Returns the content of a block, including comment delimiters, serializing all attributes from the given parsed block. |
| [parse\_blocks()](parse_blocks) wp-includes/blocks.php | Parses blocks out of a content string. |
| [WP\_Theme::get\_stylesheet()](../classes/wp_theme/get_stylesheet) wp-includes/class-wp-theme.php | Returns the directory name of the theme’s “stylesheet” files, inside the theme root. |
| [wp\_get\_theme()](wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../classes/wp_theme) object for a theme. |
| Used By | Description |
| --- | --- |
| [\_build\_block\_template\_result\_from\_file()](_build_block_template_result_from_file) wp-includes/block-template-utils.php | Builds a unified template object based on a theme file. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress kses_init() kses\_init()
============
Sets up most of the KSES filters for input form content.
First removes all of the KSES filters in case the current user does not need to have KSES filter the content. If the user does not have `unfiltered_html` capability, then KSES filters are added.
File: `wp-includes/kses.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/kses.php/)
```
function kses_init() {
kses_remove_filters();
if ( ! current_user_can( 'unfiltered_html' ) ) {
kses_init_filters();
}
}
```
| Uses | Description |
| --- | --- |
| [kses\_init\_filters()](kses_init_filters) wp-includes/kses.php | Adds all KSES input form content filters. |
| [kses\_remove\_filters()](kses_remove_filters) wp-includes/kses.php | Removes all KSES input form content filters. |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress sanitize_file_name( string $filename ): string sanitize\_file\_name( string $filename ): string
================================================
Sanitizes a filename, replacing whitespace with dashes.
Removes special characters that are illegal in filenames on certain operating systems and special characters requiring special escaping to manipulate at the command line. Replaces spaces and consecutive dashes with a single dash. Trims period, dash and underscore from beginning and end of filename. It is not guaranteed that this function will return a filename that is allowed to be uploaded.
`$filename` string Required The filename to be sanitized. string The sanitized filename.
The special characters are passed through the [sanitize\_file\_name\_chars](../hooks/sanitize_file_name_chars) filter before removing them from the file name, allowing plugins to change which characters are considered invalid. After `sanitize_file_name()` has done its work, it passes the sanitized file name through the [sanitize\_file\_name](../hooks/sanitize_file_name) filter.
File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function sanitize_file_name( $filename ) {
$filename_raw = $filename;
$filename = remove_accents( $filename );
$special_chars = array( '?', '[', ']', '/', '\\', '=', '<', '>', ':', ';', ',', "'", '"', '&', '$', '#', '*', '(', ')', '|', '~', '`', '!', '{', '}', '%', '+', '’', '«', '»', '”', '“', chr( 0 ) );
// Check for support for utf8 in the installed PCRE library once and store the result in a static.
static $utf8_pcre = null;
if ( ! isset( $utf8_pcre ) ) {
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
$utf8_pcre = @preg_match( '/^./u', 'a' );
}
if ( ! seems_utf8( $filename ) ) {
$_ext = pathinfo( $filename, PATHINFO_EXTENSION );
$_name = pathinfo( $filename, PATHINFO_FILENAME );
$filename = sanitize_title_with_dashes( $_name ) . '.' . $_ext;
}
if ( $utf8_pcre ) {
$filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
}
/**
* Filters the list of characters to remove from a filename.
*
* @since 2.8.0
*
* @param string[] $special_chars Array of characters to remove.
* @param string $filename_raw The original filename to be sanitized.
*/
$special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
$filename = str_replace( $special_chars, '', $filename );
$filename = str_replace( array( '%20', '+' ), '-', $filename );
$filename = preg_replace( '/[\r\n\t -]+/', '-', $filename );
$filename = trim( $filename, '.-_' );
if ( false === strpos( $filename, '.' ) ) {
$mime_types = wp_get_mime_types();
$filetype = wp_check_filetype( 'test.' . $filename, $mime_types );
if ( $filetype['ext'] === $filename ) {
$filename = 'unnamed-file.' . $filetype['ext'];
}
}
// Split the filename into a base and extension[s].
$parts = explode( '.', $filename );
// Return if only one extension.
if ( count( $parts ) <= 2 ) {
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
}
// Process multiple extensions.
$filename = array_shift( $parts );
$extension = array_pop( $parts );
$mimes = get_allowed_mime_types();
/*
* Loop over any intermediate extensions. Postfix them with a trailing underscore
* if they are a 2 - 5 character long alpha string not in the allowed extension list.
*/
foreach ( (array) $parts as $part ) {
$filename .= '.' . $part;
if ( preg_match( '/^[a-zA-Z]{2,5}\d?$/', $part ) ) {
$allowed = false;
foreach ( $mimes as $ext_preg => $mime_match ) {
$ext_preg = '!^(' . $ext_preg . ')$!i';
if ( preg_match( $ext_preg, $part ) ) {
$allowed = true;
break;
}
}
if ( ! $allowed ) {
$filename .= '_';
}
}
}
$filename .= '.' . $extension;
/**
* Filters a sanitized filename string.
*
* @since 2.8.0
*
* @param string $filename Sanitized filename.
* @param string $filename_raw The filename prior to sanitization.
*/
return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
}
```
[apply\_filters( 'sanitize\_file\_name', string $filename, string $filename\_raw )](../hooks/sanitize_file_name)
Filters a sanitized filename string.
[apply\_filters( 'sanitize\_file\_name\_chars', string[] $special\_chars, string $filename\_raw )](../hooks/sanitize_file_name_chars)
Filters the list of characters to remove from a filename.
| Uses | Description |
| --- | --- |
| [sanitize\_title\_with\_dashes()](sanitize_title_with_dashes) wp-includes/formatting.php | Sanitizes a title, replacing whitespace and a few other characters with dashes. |
| [remove\_accents()](remove_accents) wp-includes/formatting.php | Converts all accent characters to ASCII characters. |
| [seems\_utf8()](seems_utf8) wp-includes/formatting.php | Checks to see if a string is utf8 encoded. |
| [wp\_get\_mime\_types()](wp_get_mime_types) wp-includes/functions.php | Retrieves the list of mime types and file extensions. |
| [wp\_check\_filetype()](wp_check_filetype) wp-includes/functions.php | Retrieves the file type from the file name. |
| [get\_allowed\_mime\_types()](get_allowed_mime_types) wp-includes/functions.php | Retrieves the list of allowed mime types and file extensions. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_ajax\_crop\_image()](wp_ajax_crop_image) wp-admin/includes/ajax-actions.php | Ajax handler for cropping an image. |
| [File\_Upload\_Upgrader::\_\_construct()](../classes/file_upload_upgrader/__construct) wp-admin/includes/class-file-upload-upgrader.php | Construct the upgrader for a form. |
| [download\_url()](download_url) wp-admin/includes/file.php | Downloads a URL to a local temporary file using the WordPress HTTP API. |
| [wp\_unique\_filename()](wp_unique_filename) wp-includes/functions.php | Gets a filename that is sanitized and unique for the given directory. |
| [wp\_xmlrpc\_server::mw\_newMediaObject()](../classes/wp_xmlrpc_server/mw_newmediaobject) wp-includes/class-wp-xmlrpc-server.php | Uploads a file, following your settings. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress get_private_posts_cap_sql( string|array $post_type ): string get\_private\_posts\_cap\_sql( string|array $post\_type ): string
=================================================================
Retrieves the private post SQL based on capability.
This function provides a standardized way to appropriately select on the post\_status of a post type. The function will return a piece of SQL code that can be added to a WHERE clause; this SQL is constructed to allow all published posts, and all private posts to which the user has access.
`$post_type` string|array Required Single post type or an array of post types. Currently only supports `'post'` or `'page'`. string SQL code that can be added to a where clause.
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function get_private_posts_cap_sql( $post_type ) {
return get_posts_by_author_sql( $post_type, false );
}
```
| Uses | Description |
| --- | --- |
| [get\_posts\_by\_author\_sql()](get_posts_by_author_sql) wp-includes/post.php | Retrieves the post SQL based on capability, author, and type. |
| Used By | Description |
| --- | --- |
| [wp\_list\_authors()](wp_list_authors) wp-includes/author-template.php | Lists all the authors of the site, with several options available. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Added the ability to pass an array to `$post_type`. |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Introduced. |
wordpress generate_postdata( WP_Post|object|int $post ): array|false generate\_postdata( WP\_Post|object|int $post ): array|false
============================================================
Generates post data.
`$post` [WP\_Post](../classes/wp_post)|object|int Required [WP\_Post](../classes/wp_post) instance or Post ID/object. array|false Elements of post, or false on failure.
File: `wp-includes/query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/query.php/)
```
function generate_postdata( $post ) {
global $wp_query;
if ( ! empty( $wp_query ) && $wp_query instanceof WP_Query ) {
return $wp_query->generate_postdata( $post );
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Query::generate\_postdata()](../classes/wp_query/generate_postdata) wp-includes/class-wp-query.php | Generate post data. |
| Used By | Description |
| --- | --- |
| [get\_the\_content()](get_the_content) wp-includes/post-template.php | Retrieves the post content. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress the_content_feed( string $feed_type = null ) the\_content\_feed( string $feed\_type = null )
===============================================
Displays the post content for feeds.
`$feed_type` string Optional The type of feed. rss2 | atom | rss | rdf Default: `null`
File: `wp-includes/feed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/feed.php/)
```
function the_content_feed( $feed_type = null ) {
echo get_the_content_feed( $feed_type );
}
```
| Uses | Description |
| --- | --- |
| [get\_the\_content\_feed()](get_the_content_feed) wp-includes/feed.php | Retrieves the post content for feeds. |
| Version | Description |
| --- | --- |
| [2.9.0](https://developer.wordpress.org/reference/since/2.9.0/) | Introduced. |
wordpress wp_is_json_request(): bool wp\_is\_json\_request(): bool
=============================
Checks whether current request is a JSON request, or is expecting a JSON response.
bool True if `Accepts` or `Content-Type` headers contain `application/json`.
False otherwise.
File: `wp-includes/load.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/load.php/)
```
function wp_is_json_request() {
if ( isset( $_SERVER['HTTP_ACCEPT'] ) && wp_is_json_media_type( $_SERVER['HTTP_ACCEPT'] ) ) {
return true;
}
if ( isset( $_SERVER['CONTENT_TYPE'] ) && wp_is_json_media_type( $_SERVER['CONTENT_TYPE'] ) ) {
return true;
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [wp\_is\_json\_media\_type()](wp_is_json_media_type) wp-includes/load.php | Checks whether a string is a valid JSON Media Type. |
| Used By | Description |
| --- | --- |
| [determine\_locale()](determine_locale) wp-includes/l10n.php | Determines the current locale desired for the request. |
| [plugins\_api()](plugins_api) wp-admin/includes/plugin-install.php | Retrieves plugin installer pages from the WordPress.org Plugins API. |
| [wp\_debug\_mode()](wp_debug_mode) wp-includes/load.php | Set PHP error reporting based on WordPress debug settings. |
| [wp\_die()](wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [is\_admin\_bar\_showing()](is_admin_bar_showing) wp-includes/admin-bar.php | Determines whether the admin bar should be showing. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress wp_max_upload_size(): int wp\_max\_upload\_size(): int
============================
Determines the maximum upload size allowed in php.ini.
int Allowed upload size.
File: `wp-includes/media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/media.php/)
```
function wp_max_upload_size() {
$u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
$p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
/**
* Filters the maximum upload size allowed in php.ini.
*
* @since 2.5.0
*
* @param int $size Max upload size limit in bytes.
* @param int $u_bytes Maximum upload filesize in bytes.
* @param int $p_bytes Maximum size of POST data in bytes.
*/
return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
}
```
[apply\_filters( 'upload\_size\_limit', int $size, int $u\_bytes, int $p\_bytes )](../hooks/upload_size_limit)
Filters the maximum upload size allowed in php.ini.
| Uses | Description |
| --- | --- |
| [wp\_convert\_hr\_to\_bytes()](wp_convert_hr_to_bytes) wp-includes/load.php | Converts a shorthand byte value to an integer byte value. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [get\_default\_block\_editor\_settings()](get_default_block_editor_settings) wp-includes/block-editor.php | Returns the default block editor settings. |
| [wp\_import\_upload\_form()](wp_import_upload_form) wp-admin/includes/template.php | Outputs the form used by the importers to accept the data to be imported. |
| [media\_upload\_form()](media_upload_form) wp-admin/includes/media.php | Outputs the legacy media upload form. |
| [wp\_plupload\_default\_settings()](wp_plupload_default_settings) wp-includes/media.php | Prints default Plupload arguments. |
| [wp\_print\_media\_templates()](wp_print_media_templates) wp-includes/media-template.php | Prints the templates used in the media manager. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
| programming_docs |
wordpress get_hidden_columns( string|WP_Screen $screen ): string[] get\_hidden\_columns( string|WP\_Screen $screen ): string[]
===========================================================
Get a list of hidden columns.
`$screen` string|[WP\_Screen](../classes/wp_screen) Required The screen you want the hidden columns for string[] Array of IDs of hidden columns.
File: `wp-admin/includes/screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/screen.php/)
```
function get_hidden_columns( $screen ) {
if ( is_string( $screen ) ) {
$screen = convert_to_screen( $screen );
}
$hidden = get_user_option( 'manage' . $screen->id . 'columnshidden' );
$use_defaults = ! is_array( $hidden );
if ( $use_defaults ) {
$hidden = array();
/**
* Filters the default list of hidden columns.
*
* @since 4.4.0
*
* @param string[] $hidden Array of IDs of columns hidden by default.
* @param WP_Screen $screen WP_Screen object of the current screen.
*/
$hidden = apply_filters( 'default_hidden_columns', $hidden, $screen );
}
/**
* Filters the list of hidden columns.
*
* @since 4.4.0
* @since 4.4.1 Added the `use_defaults` parameter.
*
* @param string[] $hidden Array of IDs of hidden columns.
* @param WP_Screen $screen WP_Screen object of the current screen.
* @param bool $use_defaults Whether to show the default columns.
*/
return apply_filters( 'hidden_columns', $hidden, $screen, $use_defaults );
}
```
[apply\_filters( 'default\_hidden\_columns', string[] $hidden, WP\_Screen $screen )](../hooks/default_hidden_columns)
Filters the default list of hidden columns.
[apply\_filters( 'hidden\_columns', string[] $hidden, WP\_Screen $screen, bool $use\_defaults )](../hooks/hidden_columns)
Filters the list of hidden columns.
| Uses | Description |
| --- | --- |
| [convert\_to\_screen()](convert_to_screen) wp-admin/includes/template.php | Converts a screen string to a screen object. |
| [get\_user\_option()](get_user_option) wp-includes/user.php | Retrieves user option that can be either per Site or per Network. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Screen::render\_list\_table\_columns\_preferences()](../classes/wp_screen/render_list_table_columns_preferences) wp-admin/includes/class-wp-screen.php | Renders the list table columns preferences. |
| [WP\_List\_Table::get\_column\_info()](../classes/wp_list_table/get_column_info) wp-admin/includes/class-wp-list-table.php | Gets a list of all, hidden, and sortable columns, with filter applied. |
| [\_WP\_List\_Table\_Compat::get\_column\_info()](../classes/_wp_list_table_compat/get_column_info) wp-admin/includes/class-wp-list-table-compat.php | Gets a list of all, hidden, and sortable columns. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress wp_create_category( int|string $cat_name, int $category_parent ): int|WP_Error wp\_create\_category( int|string $cat\_name, int $category\_parent ): int|WP\_Error
===================================================================================
Adds a new category to the database if it does not already exist.
`$cat_name` int|string Required Category name. `$category_parent` int Optional ID of parent category. int|[WP\_Error](../classes/wp_error)
Parameters:
* `$cat_name`: Name for the new category.
* `$parent`: Category ID of the parent category.
Returns:
* 0 on failure, category id on success.
[wp\_create\_category()](wp_create_category) is a thin wrapper around [wp\_insert\_category()](wp_insert_category) .
Because this is a wrapper, it is not suitable for entering a complex custom taxonomy element.
If the category already exists, it is not duplicated. The ID of the original existing category is returned without error.
File: `wp-admin/includes/taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/taxonomy.php/)
```
function wp_create_category( $cat_name, $category_parent = 0 ) {
$id = category_exists( $cat_name, $category_parent );
if ( $id ) {
return $id;
}
return wp_insert_category(
array(
'cat_name' => $cat_name,
'category_parent' => $category_parent,
)
);
}
```
| Uses | Description |
| --- | --- |
| [category\_exists()](category_exists) wp-admin/includes/taxonomy.php | Checks whether a category exists. |
| [wp\_insert\_category()](wp_insert_category) wp-admin/includes/taxonomy.php | Updates an existing Category or creates a new Category. |
| Used By | Description |
| --- | --- |
| [wp\_create\_categories()](wp_create_categories) wp-admin/includes/taxonomy.php | Creates categories for the given post. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress get_all_page_ids(): string[] get\_all\_page\_ids(): string[]
===============================
Gets a list of page IDs.
string[] List of page IDs as strings.
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function get_all_page_ids() {
global $wpdb;
$page_ids = wp_cache_get( 'all_page_ids', 'posts' );
if ( ! is_array( $page_ids ) ) {
$page_ids = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_type = 'page'" );
wp_cache_add( 'all_page_ids', $page_ids, 'posts' );
}
return $page_ids;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::get\_col()](../classes/wpdb/get_col) wp-includes/class-wpdb.php | Retrieves one column from the database. |
| [wp\_cache\_add()](wp_cache_add) wp-includes/cache.php | Adds data to the cache, if the cache key doesn’t already exist. |
| [wp\_cache\_get()](wp_cache_get) wp-includes/cache.php | Retrieves the cache contents from the cache by key and group. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress get_taxonomy( string $taxonomy ): WP_Taxonomy|false get\_taxonomy( string $taxonomy ): WP\_Taxonomy|false
=====================================================
Retrieves the taxonomy object of $taxonomy.
The get\_taxonomy function will first check that the parameter string given is a taxonomy object and if it is, it will return it.
`$taxonomy` string Required Name of taxonomy object to return. [WP\_Taxonomy](../classes/wp_taxonomy)|false The taxonomy object or false if $taxonomy doesn't exist.
Note that it does NOT return the list of terms associated with the taxonomy. To do this, you should use [get\_term()](get_term) to return an object or [wp\_list\_categories()](wp_list_categories) to return an HTML list of terms
File: `wp-includes/taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/taxonomy.php/)
```
function get_taxonomy( $taxonomy ) {
global $wp_taxonomies;
if ( ! taxonomy_exists( $taxonomy ) ) {
return false;
}
return $wp_taxonomies[ $taxonomy ];
}
```
| Uses | Description |
| --- | --- |
| [taxonomy\_exists()](taxonomy_exists) wp-includes/taxonomy.php | Determines whether the taxonomy name exists. |
| Used By | Description |
| --- | --- |
| [\_wp\_build\_title\_and\_description\_for\_taxonomy\_block\_template()](_wp_build_title_and_description_for_taxonomy_block_template) wp-includes/block-template-utils.php | Builds the title and description of a taxonomy-specific template based on the underlying entity referenced. |
| [WP\_REST\_Menu\_Items\_Controller::prepare\_item\_for\_database()](../classes/wp_rest_menu_items_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Prepares a single post for create or update. |
| [rest\_get\_route\_for\_taxonomy\_items()](rest_get_route_for_taxonomy_items) wp-includes/rest-api.php | Gets the REST API route for a taxonomy. |
| [is\_taxonomy\_viewable()](is_taxonomy_viewable) wp-includes/taxonomy.php | Determines whether a taxonomy is considered “viewable”. |
| [register\_and\_do\_post\_meta\_boxes()](register_and_do_post_meta_boxes) wp-admin/includes/meta-boxes.php | Registers the default post meta boxes, and runs the `do_meta_boxes` actions. |
| [WP\_REST\_Terms\_Controller::check\_is\_taxonomy\_allowed()](../classes/wp_rest_terms_controller/check_is_taxonomy_allowed) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks that the taxonomy is valid. |
| [WP\_REST\_Terms\_Controller::prepare\_links()](../classes/wp_rest_terms_controller/prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Prepares links for the request. |
| [WP\_REST\_Terms\_Controller::get\_item\_schema()](../classes/wp_rest_terms_controller/get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Retrieves the term’s schema, conforming to JSON Schema. |
| [WP\_REST\_Terms\_Controller::get\_collection\_params()](../classes/wp_rest_terms_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Retrieves the query params for collections. |
| [WP\_REST\_Terms\_Controller::create\_item\_permissions\_check()](../classes/wp_rest_terms_controller/create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks if a request has access to create a term. |
| [WP\_REST\_Terms\_Controller::\_\_construct()](../classes/wp_rest_terms_controller/__construct) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Constructor. |
| [WP\_REST\_Terms\_Controller::get\_items\_permissions\_check()](../classes/wp_rest_terms_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks if a request has access to read terms in the specified taxonomy. |
| [WP\_REST\_Terms\_Controller::get\_items()](../classes/wp_rest_terms_controller/get_items) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Retrieves terms associated with a taxonomy. |
| [WP\_REST\_Taxonomies\_Controller::get\_item\_permissions\_check()](../classes/wp_rest_taxonomies_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php | Checks if a given request has access to a taxonomy. |
| [WP\_REST\_Taxonomies\_Controller::get\_item()](../classes/wp_rest_taxonomies_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php | Retrieves a specific taxonomy. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::get\_type\_label()](../classes/wp_customize_nav_menu_item_setting/get_type_label) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get type label. |
| [WP\_Posts\_List\_Table::categories\_dropdown()](../classes/wp_posts_list_table/categories_dropdown) wp-admin/includes/class-wp-posts-list-table.php | Displays a categories drop-down for filtering on the Posts list table. |
| [unregister\_taxonomy()](unregister_taxonomy) wp-includes/taxonomy.php | Unregisters a taxonomy. |
| [WP\_Customize\_Nav\_Menus::search\_available\_items\_query()](../classes/wp_customize_nav_menus/search_available_items_query) wp-includes/class-wp-customize-nav-menus.php | Performs post queries for available-item searching. |
| [WP\_Customize\_Nav\_Menus::load\_available\_items\_query()](../classes/wp_customize_nav_menus/load_available_items_query) wp-includes/class-wp-customize-nav-menus.php | Performs the post\_type and taxonomy queries for loading available menu items. |
| [WP\_Posts\_List\_Table::column\_default()](../classes/wp_posts_list_table/column_default) wp-admin/includes/class-wp-posts-list-table.php | Handles the default column output. |
| [WP\_Media\_List\_Table::column\_default()](../classes/wp_media_list_table/column_default) wp-admin/includes/class-wp-media-list-table.php | Handles output for the default column. |
| [WP\_Terms\_List\_Table::no\_items()](../classes/wp_terms_list_table/no_items) wp-admin/includes/class-wp-terms-list-table.php | |
| [get\_the\_archive\_title()](get_the_archive_title) wp-includes/general-template.php | Retrieves the archive title based on the queried object. |
| [WP\_Links\_List\_Table::extra\_tablenav()](../classes/wp_links_list_table/extra_tablenav) wp-admin/includes/class-wp-links-list-table.php | |
| [get\_inline\_data()](get_inline_data) wp-admin/includes/template.php | Adds hidden fields with the data for use in the inline editor for posts and pages. |
| [wp\_terms\_checklist()](wp_terms_checklist) wp-admin/includes/template.php | Outputs an unordered list of checkbox input elements labelled with term names. |
| [wp\_popular\_terms\_checklist()](wp_popular_terms_checklist) wp-admin/includes/template.php | Retrieves a list of the most popular terms from the specified taxonomy. |
| [get\_attachment\_fields\_to\_edit()](get_attachment_fields_to_edit) wp-admin/includes/media.php | Retrieves the attachment fields to edit form fields. |
| [get\_compat\_media\_markup()](get_compat_media_markup) wp-admin/includes/media.php | |
| [\_wp\_translate\_postdata()](_wp_translate_postdata) wp-admin/includes/post.php | Renames `$_POST` data from form names to DB post columns. |
| [edit\_post()](edit_post) wp-admin/includes/post.php | Updates an existing post with values provided in `$_POST`. |
| [bulk\_edit\_posts()](bulk_edit_posts) wp-admin/includes/post.php | Processes the post data for the bulk editing of posts. |
| [wp\_ajax\_inline\_save()](wp_ajax_inline_save) wp-admin/includes/ajax-actions.php | Ajax handler for Quick Edit saving a post from a list table. |
| [wp\_ajax\_inline\_save\_tax()](wp_ajax_inline_save_tax) wp-admin/includes/ajax-actions.php | Ajax handler for quick edit saving for a term. |
| [\_wp\_ajax\_add\_hierarchical\_term()](_wp_ajax_add_hierarchical_term) wp-admin/includes/ajax-actions.php | Ajax handler for adding a hierarchical term. |
| [wp\_ajax\_add\_link\_category()](wp_ajax_add_link_category) wp-admin/includes/ajax-actions.php | Ajax handler for adding a link category. |
| [wp\_ajax\_add\_tag()](wp_ajax_add_tag) wp-admin/includes/ajax-actions.php | Ajax handler to add a tag. |
| [wp\_ajax\_get\_tagcloud()](wp_ajax_get_tagcloud) wp-admin/includes/ajax-actions.php | Ajax handler for getting a tagcloud. |
| [wp\_ajax\_ajax\_tag\_search()](wp_ajax_ajax_tag_search) wp-admin/includes/ajax-actions.php | Ajax handler for tag search. |
| [post\_tags\_meta\_box()](post_tags_meta_box) wp-admin/includes/meta-boxes.php | Displays post tags form fields. |
| [post\_categories\_meta\_box()](post_categories_meta_box) wp-admin/includes/meta-boxes.php | Displays post categories form fields. |
| [WP\_Media\_List\_Table::get\_columns()](../classes/wp_media_list_table/get_columns) wp-admin/includes/class-wp-media-list-table.php | |
| [WP\_Terms\_List\_Table::column\_posts()](../classes/wp_terms_list_table/column_posts) wp-admin/includes/class-wp-terms-list-table.php | |
| [WP\_Terms\_List\_Table::inline\_edit()](../classes/wp_terms_list_table/inline_edit) wp-admin/includes/class-wp-terms-list-table.php | Outputs the hidden row displayed when inline editing |
| [WP\_Terms\_List\_Table::\_\_construct()](../classes/wp_terms_list_table/__construct) wp-admin/includes/class-wp-terms-list-table.php | Constructor. |
| [WP\_Terms\_List\_Table::ajax\_user\_can()](../classes/wp_terms_list_table/ajax_user_can) wp-admin/includes/class-wp-terms-list-table.php | |
| [WP\_Terms\_List\_Table::get\_bulk\_actions()](../classes/wp_terms_list_table/get_bulk_actions) wp-admin/includes/class-wp-terms-list-table.php | |
| [wp\_nav\_menu\_item\_taxonomy\_meta\_box()](wp_nav_menu_item_taxonomy_meta_box) wp-admin/includes/nav-menu.php | Displays a meta box for a taxonomy menu item. |
| [WP\_Posts\_List\_Table::inline\_edit()](../classes/wp_posts_list_table/inline_edit) wp-admin/includes/class-wp-posts-list-table.php | Outputs the hidden row displayed when inline editing |
| [WP\_Posts\_List\_Table::get\_columns()](../classes/wp_posts_list_table/get_columns) wp-admin/includes/class-wp-posts-list-table.php | |
| [map\_meta\_cap()](map_meta_cap) wp-includes/capabilities.php | Maps a capability to the primitive capabilities required of the given user to satisfy the capability being checked. |
| [wp\_list\_categories()](wp_list_categories) wp-includes/category-template.php | Displays or retrieves the HTML list of categories. |
| [feed\_links\_extra()](feed_links_extra) wp-includes/general-template.php | Displays the links to the extra feeds such as category feeds. |
| [wp\_title()](wp_title) wp-includes/general-template.php | Displays or retrieves page title for all areas of blog. |
| [WP\_Widget\_Tag\_Cloud::widget()](../classes/wp_widget_tag_cloud/widget) wp-includes/widgets/class-wp-widget-tag-cloud.php | Outputs the content for the current Tag Cloud widget instance. |
| [\_pad\_term\_counts()](_pad_term_counts) wp-includes/taxonomy.php | Adds count of children to parent count. |
| [get\_term\_link()](get_term_link) wp-includes/taxonomy.php | Generates a permalink for a taxonomy term archive. |
| [get\_the\_taxonomies()](get_the_taxonomies) wp-includes/taxonomy.php | Retrieves all taxonomies associated with a post. |
| [wp\_update\_term\_count\_now()](wp_update_term_count_now) wp-includes/taxonomy.php | Performs term count update immediately. |
| [wp\_get\_object\_terms()](wp_get_object_terms) wp-includes/taxonomy.php | Retrieves the terms associated with the given object(s), in the supplied taxonomies. |
| [wp\_set\_object\_terms()](wp_set_object_terms) wp-includes/taxonomy.php | Creates term and taxonomy relationships. |
| [wp\_delete\_term()](wp_delete_term) wp-includes/taxonomy.php | Removes a term from the database. |
| [is\_taxonomy\_hierarchical()](is_taxonomy_hierarchical) wp-includes/taxonomy.php | Determines whether the taxonomy object is hierarchical. |
| [get\_term\_feed\_link()](get_term_feed_link) wp-includes/link-template.php | Retrieves the feed link for a term. |
| [get\_edit\_term\_link()](get_edit_term_link) wp-includes/link-template.php | Retrieves the URL for editing a given term. |
| [edit\_term\_link()](edit_term_link) wp-includes/link-template.php | Displays or retrieves the edit term link with formatting. |
| [wp\_admin\_bar\_edit\_menu()](wp_admin_bar_edit_menu) wp-includes/admin-bar.php | Provides an edit link for posts and terms. |
| [wp\_insert\_post()](wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [redirect\_canonical()](redirect_canonical) wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| [\_post\_format\_request()](_post_format_request) wp-includes/post-formats.php | Filters the request to allow for the format prefix. |
| [wp\_setup\_nav\_menu\_item()](wp_setup_nav_menu_item) wp-includes/nav-menu.php | Decorates a menu item object with the shared navigation menu item properties. |
| [wp\_xmlrpc\_server::wp\_newTerm()](../classes/wp_xmlrpc_server/wp_newterm) wp-includes/class-wp-xmlrpc-server.php | Create a new term. |
| [wp\_xmlrpc\_server::wp\_editTerm()](../classes/wp_xmlrpc_server/wp_editterm) wp-includes/class-wp-xmlrpc-server.php | Edit a term. |
| [wp\_xmlrpc\_server::wp\_deleteTerm()](../classes/wp_xmlrpc_server/wp_deleteterm) wp-includes/class-wp-xmlrpc-server.php | Delete a term. |
| [wp\_xmlrpc\_server::wp\_getTerm()](../classes/wp_xmlrpc_server/wp_getterm) wp-includes/class-wp-xmlrpc-server.php | Retrieve a term. |
| [wp\_xmlrpc\_server::wp\_getTerms()](../classes/wp_xmlrpc_server/wp_getterms) wp-includes/class-wp-xmlrpc-server.php | Retrieve all terms for a taxonomy. |
| [wp\_xmlrpc\_server::wp\_getTaxonomy()](../classes/wp_xmlrpc_server/wp_gettaxonomy) wp-includes/class-wp-xmlrpc-server.php | Retrieve a taxonomy. |
| Version | Description |
| --- | --- |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
| programming_docs |
wordpress get_post_galleries_images( int|WP_Post $post ): array get\_post\_galleries\_images( int|WP\_Post $post ): array
=========================================================
Retrieves the image srcs from galleries from a post’s content, if present.
* [get\_post\_galleries()](get_post_galleries)
`$post` int|[WP\_Post](../classes/wp_post) Optional Post ID or [WP\_Post](../classes/wp_post) object. Default is global `$post`. array A list of lists, each containing image srcs parsed.
from an expanded shortcode
File: `wp-includes/media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/media.php/)
```
function get_post_galleries_images( $post = 0 ) {
$galleries = get_post_galleries( $post, false );
return wp_list_pluck( $galleries, 'src' );
}
```
| Uses | Description |
| --- | --- |
| [wp\_list\_pluck()](wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [get\_post\_galleries()](get_post_galleries) wp-includes/media.php | Retrieves galleries from the passed post’s content. |
| Version | Description |
| --- | --- |
| [3.6.0](https://developer.wordpress.org/reference/since/3.6.0/) | Introduced. |
wordpress rest_sanitize_value_from_schema( mixed $value, array $args, string $param = '' ): mixed|WP_Error rest\_sanitize\_value\_from\_schema( mixed $value, array $args, string $param = '' ): mixed|WP\_Error
=====================================================================================================
Sanitize a value based on a schema.
`$value` mixed Required The value to sanitize. `$args` array Required Schema array to use for sanitization. `$param` string Optional The parameter name, used in error messages. Default: `''`
mixed|[WP\_Error](../classes/wp_error) The sanitized value or a [WP\_Error](../classes/wp_error) instance if the value cannot be safely sanitized.
File: `wp-includes/rest-api.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api.php/)
```
function rest_sanitize_value_from_schema( $value, $args, $param = '' ) {
if ( isset( $args['anyOf'] ) ) {
$matching_schema = rest_find_any_matching_schema( $value, $args, $param );
if ( is_wp_error( $matching_schema ) ) {
return $matching_schema;
}
if ( ! isset( $args['type'] ) ) {
$args['type'] = $matching_schema['type'];
}
$value = rest_sanitize_value_from_schema( $value, $matching_schema, $param );
}
if ( isset( $args['oneOf'] ) ) {
$matching_schema = rest_find_one_matching_schema( $value, $args, $param );
if ( is_wp_error( $matching_schema ) ) {
return $matching_schema;
}
if ( ! isset( $args['type'] ) ) {
$args['type'] = $matching_schema['type'];
}
$value = rest_sanitize_value_from_schema( $value, $matching_schema, $param );
}
$allowed_types = array( 'array', 'object', 'string', 'number', 'integer', 'boolean', 'null' );
if ( ! isset( $args['type'] ) ) {
/* translators: %s: Parameter. */
_doing_it_wrong( __FUNCTION__, sprintf( __( 'The "type" schema keyword for %s is required.' ), $param ), '5.5.0' );
}
if ( is_array( $args['type'] ) ) {
$best_type = rest_handle_multi_type_schema( $value, $args, $param );
if ( ! $best_type ) {
return null;
}
$args['type'] = $best_type;
}
if ( ! in_array( $args['type'], $allowed_types, true ) ) {
_doing_it_wrong(
__FUNCTION__,
/* translators: 1: Parameter, 2: The list of allowed types. */
wp_sprintf( __( 'The "type" schema keyword for %1$s can only be one of the built-in types: %2$l.' ), $param, $allowed_types ),
'5.5.0'
);
}
if ( 'array' === $args['type'] ) {
$value = rest_sanitize_array( $value );
if ( ! empty( $args['items'] ) ) {
foreach ( $value as $index => $v ) {
$value[ $index ] = rest_sanitize_value_from_schema( $v, $args['items'], $param . '[' . $index . ']' );
}
}
if ( ! empty( $args['uniqueItems'] ) && ! rest_validate_array_contains_unique_items( $value ) ) {
/* translators: %s: Parameter. */
return new WP_Error( 'rest_duplicate_items', sprintf( __( '%s has duplicate items.' ), $param ) );
}
return $value;
}
if ( 'object' === $args['type'] ) {
$value = rest_sanitize_object( $value );
foreach ( $value as $property => $v ) {
if ( isset( $args['properties'][ $property ] ) ) {
$value[ $property ] = rest_sanitize_value_from_schema( $v, $args['properties'][ $property ], $param . '[' . $property . ']' );
continue;
}
$pattern_property_schema = rest_find_matching_pattern_property_schema( $property, $args );
if ( null !== $pattern_property_schema ) {
$value[ $property ] = rest_sanitize_value_from_schema( $v, $pattern_property_schema, $param . '[' . $property . ']' );
continue;
}
if ( isset( $args['additionalProperties'] ) ) {
if ( false === $args['additionalProperties'] ) {
unset( $value[ $property ] );
} elseif ( is_array( $args['additionalProperties'] ) ) {
$value[ $property ] = rest_sanitize_value_from_schema( $v, $args['additionalProperties'], $param . '[' . $property . ']' );
}
}
}
return $value;
}
if ( 'null' === $args['type'] ) {
return null;
}
if ( 'integer' === $args['type'] ) {
return (int) $value;
}
if ( 'number' === $args['type'] ) {
return (float) $value;
}
if ( 'boolean' === $args['type'] ) {
return rest_sanitize_boolean( $value );
}
// This behavior matches rest_validate_value_from_schema().
if ( isset( $args['format'] )
&& ( ! isset( $args['type'] ) || 'string' === $args['type'] || ! in_array( $args['type'], $allowed_types, true ) )
) {
switch ( $args['format'] ) {
case 'hex-color':
return (string) sanitize_hex_color( $value );
case 'date-time':
return sanitize_text_field( $value );
case 'email':
// sanitize_email() validates, which would be unexpected.
return sanitize_text_field( $value );
case 'uri':
return sanitize_url( $value );
case 'ip':
return sanitize_text_field( $value );
case 'uuid':
return sanitize_text_field( $value );
case 'text-field':
return sanitize_text_field( $value );
case 'textarea-field':
return sanitize_textarea_field( $value );
}
}
if ( 'string' === $args['type'] ) {
return (string) $value;
}
return $value;
}
```
| Uses | Description |
| --- | --- |
| [rest\_find\_any\_matching\_schema()](rest_find_any_matching_schema) wp-includes/rest-api.php | Finds the matching schema among the “anyOf” schemas. |
| [rest\_sanitize\_boolean()](rest_sanitize_boolean) wp-includes/rest-api.php | Changes a boolean-like value into the proper boolean value. |
| [sanitize\_url()](sanitize_url) wp-includes/formatting.php | Sanitizes a URL for database or redirect usage. |
| [wp\_sprintf()](wp_sprintf) wp-includes/formatting.php | WordPress implementation of PHP sprintf() with filters. |
| [sanitize\_text\_field()](sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [sanitize\_hex\_color()](sanitize_hex_color) wp-includes/formatting.php | Sanitizes a hex color. |
| [rest\_find\_one\_matching\_schema()](rest_find_one_matching_schema) wp-includes/rest-api.php | Finds the matching schema among the “oneOf” schemas. |
| [sanitize\_textarea\_field()](sanitize_textarea_field) wp-includes/formatting.php | Sanitizes a multiline string from user input or from the database. |
| [rest\_sanitize\_value\_from\_schema()](rest_sanitize_value_from_schema) wp-includes/rest-api.php | Sanitize a value based on a schema. |
| [rest\_sanitize\_object()](rest_sanitize_object) wp-includes/rest-api.php | Converts an object-like value to an object. |
| [rest\_validate\_array\_contains\_unique\_items()](rest_validate_array_contains_unique_items) wp-includes/rest-api.php | Checks if an array is made up of unique items. |
| [rest\_sanitize\_array()](rest_sanitize_array) wp-includes/rest-api.php | Converts an array-like value to an array. |
| [rest\_handle\_multi\_type\_schema()](rest_handle_multi_type_schema) wp-includes/rest-api.php | Handles getting the best type for a multi-type schema. |
| [rest\_find\_matching\_pattern\_property\_schema()](rest_find_matching_pattern_property_schema) wp-includes/rest-api.php | Finds the schema for a property using the patternProperties keyword. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_doing\_it\_wrong()](_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../classes/wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Widget\_Types\_Controller::prepare\_item\_for\_response()](../classes/wp_rest_widget_types_controller/prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-widget-types-controller.php | Prepares a widget type object for serialization. |
| [rest\_validate\_enum()](rest_validate_enum) wp-includes/rest-api.php | Validates that the given value is a member of the JSON Schema “enum”. |
| [WP\_REST\_Themes\_Controller::prepare\_theme\_support()](../classes/wp_rest_themes_controller/prepare_theme_support) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Prepares the theme support value for inclusion in the REST API response. |
| [WP\_REST\_Block\_Types\_Controller::prepare\_item\_for\_response()](../classes/wp_rest_block_types_controller/prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-block-types-controller.php | Prepares a block type object for serialization. |
| [WP\_REST\_Block\_Renderer\_Controller::register\_routes()](../classes/wp_rest_block_renderer_controller/register_routes) wp-includes/rest-api/endpoints/class-wp-rest-block-renderer-controller.php | Registers the necessary REST API routes, one for each dynamic block. |
| [WP\_Widget\_Media::update()](../classes/wp_widget_media/update) wp-includes/widgets/class-wp-widget-media.php | Sanitizes the widget form values as they are saved. |
| [rest\_sanitize\_value\_from\_schema()](rest_sanitize_value_from_schema) wp-includes/rest-api.php | Sanitize a value based on a schema. |
| [rest\_sanitize\_request\_arg()](rest_sanitize_request_arg) wp-includes/rest-api.php | Sanitize a request argument based on details registered to the route. |
| [WP\_REST\_Meta\_Fields::prepare\_value()](../classes/wp_rest_meta_fields/prepare_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Prepares a meta value for output. |
| [WP\_REST\_Meta\_Fields::update\_value()](../classes/wp_rest_meta_fields/update_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Updates meta values. |
| [WP\_REST\_Settings\_Controller::prepare\_value()](../classes/wp_rest_settings_controller/prepare_value) wp-includes/rest-api/endpoints/class-wp-rest-settings-controller.php | Prepares a value for output based off a schema array. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Added `text-field` and `textarea-field` formats. |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Support the "anyOf" and "oneOf" keywords. |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Added the `$param` parameter. |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress wp_star_rating( array $args = array() ): string wp\_star\_rating( array $args = array() ): string
=================================================
Outputs a HTML element with a star rating for a given rating.
Outputs a HTML element with the star rating exposed on a 0..5 scale in half star increments (ie. 1, 1.5, 2 stars). Optionally, if specified, the number of ratings may also be displayed by passing the $number parameter.
`$args` array Optional Array of star ratings arguments.
* `rating`int|floatThe rating to display, expressed in either a 0.5 rating increment, or percentage. Default 0.
* `type`stringFormat that the $rating is in. Valid values are `'rating'` (default), or, `'percent'`. Default `'rating'`.
* `number`intThe number of ratings that makes up this rating. Default 0.
* `echo`boolWhether to echo the generated markup. False to return the markup instead of echoing it. Default true.
Default: `array()`
string Star rating HTML.
In order to use this function on the front end, your template must include the *wp-admin/includes/template.php* file and enqueue the appropriate dashicons CSS font information.
Example CSS:
`@font-face {
font-family: "dashicons";
src: url("../fonts/dashicons.eot");
}`
@font-face {
font-family: "dashicons";
src: url(data:application/x-font-woff;charset=utf-8;base64,/\* !! Large amount of data removed, see wp-includes/css/dashicons.css for complete data !! \*/) format("woff"),
url("../fonts/dashicons.ttf") format("truetype"),
url("../fonts/dashicons.svg#dashicons") format("svg");
font-weight: normal;
font-style: normal;
}
.star-rating .star-full:before {
content: "\f155";
}
.star-rating .star-half:before {
content: "\f459";
}
.star-rating .star-empty:before {
content: "\f154";
}
.star-rating .star {
color: #0074A2;
display: inline-block;
font-family: dashicons;
font-size: 20px;
font-style: normal;
font-weight: 400;
height: 20px;
line-height: 1;
text-align: center;
text-decoration: inherit;
vertical-align: top;
width: 20px;
}
Note the font data in the above CSS has been omitted for clarity. This data must be included in working code. Refer to *wp-admin/css/dashicons.css*
File: `wp-admin/includes/template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/template.php/)
```
function wp_star_rating( $args = array() ) {
$defaults = array(
'rating' => 0,
'type' => 'rating',
'number' => 0,
'echo' => true,
);
$parsed_args = wp_parse_args( $args, $defaults );
// Non-English decimal places when the $rating is coming from a string.
$rating = (float) str_replace( ',', '.', $parsed_args['rating'] );
// Convert percentage to star rating, 0..5 in .5 increments.
if ( 'percent' === $parsed_args['type'] ) {
$rating = round( $rating / 10, 0 ) / 2;
}
// Calculate the number of each type of star needed.
$full_stars = floor( $rating );
$half_stars = ceil( $rating - $full_stars );
$empty_stars = 5 - $full_stars - $half_stars;
if ( $parsed_args['number'] ) {
/* translators: 1: The rating, 2: The number of ratings. */
$format = _n( '%1$s rating based on %2$s rating', '%1$s rating based on %2$s ratings', $parsed_args['number'] );
$title = sprintf( $format, number_format_i18n( $rating, 1 ), number_format_i18n( $parsed_args['number'] ) );
} else {
/* translators: %s: The rating. */
$title = sprintf( __( '%s rating' ), number_format_i18n( $rating, 1 ) );
}
$output = '<div class="star-rating">';
$output .= '<span class="screen-reader-text">' . $title . '</span>';
$output .= str_repeat( '<div class="star star-full" aria-hidden="true"></div>', $full_stars );
$output .= str_repeat( '<div class="star star-half" aria-hidden="true"></div>', $half_stars );
$output .= str_repeat( '<div class="star star-empty" aria-hidden="true"></div>', $empty_stars );
$output .= '</div>';
if ( $parsed_args['echo'] ) {
echo $output;
}
return $output;
}
```
| Uses | Description |
| --- | --- |
| [\_n()](_n) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_parse\_args()](wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [number\_format\_i18n()](number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::handle\_load\_themes\_request()](../classes/wp_customize_manager/handle_load_themes_request) wp-includes/class-wp-customize-manager.php | Loads themes into the theme browsing/installation UI. |
| [WP\_Theme\_Install\_List\_Table::install\_theme\_info()](../classes/wp_theme_install_list_table/install_theme_info) wp-admin/includes/class-wp-theme-install-list-table.php | Prints the info for a theme (to be used in the theme installer modal). |
| [install\_plugin\_information()](install_plugin_information) wp-admin/includes/plugin-install.php | Displays plugin information in dialog box form. |
| [WP\_Plugin\_Install\_List\_Table::display\_rows()](../classes/wp_plugin_install_list_table/display_rows) wp-admin/includes/class-wp-plugin-install-list-table.php | |
| [wp\_ajax\_query\_themes()](wp_ajax_query_themes) wp-admin/includes/ajax-actions.php | Ajax handler for getting themes from [themes\_api()](themes_api) . |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced the `echo` parameter. |
| [3.8.0](https://developer.wordpress.org/reference/since/3.8.0/) | Introduced. |
wordpress shortcode_parse_atts( string $text ): array|string shortcode\_parse\_atts( string $text ): array|string
====================================================
Retrieves all attributes from the shortcodes tag.
The attributes list has the attribute name as the key and the value of the attribute as the value in the key/value pair. This allows for easier retrieval of the attributes, since all attributes have to be known.
`$text` string Required array|string List of attribute values.
Returns empty array if `'""'` === trim( $text ).
Returns empty string if `''` === trim( $text ).
All other matches are checked for not empty().
File: `wp-includes/shortcodes.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/shortcodes.php/)
```
function shortcode_parse_atts( $text ) {
$atts = array();
$pattern = get_shortcode_atts_regex();
$text = preg_replace( "/[\x{00a0}\x{200b}]+/u", ' ', $text );
if ( preg_match_all( $pattern, $text, $match, PREG_SET_ORDER ) ) {
foreach ( $match as $m ) {
if ( ! empty( $m[1] ) ) {
$atts[ strtolower( $m[1] ) ] = stripcslashes( $m[2] );
} elseif ( ! empty( $m[3] ) ) {
$atts[ strtolower( $m[3] ) ] = stripcslashes( $m[4] );
} elseif ( ! empty( $m[5] ) ) {
$atts[ strtolower( $m[5] ) ] = stripcslashes( $m[6] );
} elseif ( isset( $m[7] ) && strlen( $m[7] ) ) {
$atts[] = stripcslashes( $m[7] );
} elseif ( isset( $m[8] ) && strlen( $m[8] ) ) {
$atts[] = stripcslashes( $m[8] );
} elseif ( isset( $m[9] ) ) {
$atts[] = stripcslashes( $m[9] );
}
}
// Reject any unclosed HTML elements.
foreach ( $atts as &$value ) {
if ( false !== strpos( $value, '<' ) ) {
if ( 1 !== preg_match( '/^[^<]*+(?:<[^>]*+>[^<]*+)*+$/', $value ) ) {
$value = '';
}
}
}
} else {
$atts = ltrim( $text );
}
return $atts;
}
```
| Uses | Description |
| --- | --- |
| [get\_shortcode\_atts\_regex()](get_shortcode_atts_regex) wp-includes/shortcodes.php | Retrieves the shortcode attributes regex. |
| Used By | Description |
| --- | --- |
| [wp\_ajax\_parse\_embed()](wp_ajax_parse_embed) wp-admin/includes/ajax-actions.php | Apply [embed] Ajax handlers to a string. |
| [do\_shortcode\_tag()](do_shortcode_tag) wp-includes/shortcodes.php | Regular Expression callable for [do\_shortcode()](do_shortcode) for calling shortcode hook. |
| [WP\_oEmbed::discover()](../classes/wp_oembed/discover) wp-includes/class-wp-oembed.php | Attempts to discover link tags at the given URL for an oEmbed provider. |
| [get\_post\_galleries()](get_post_galleries) wp-includes/media.php | Retrieves galleries from the passed post’s content. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
| programming_docs |
wordpress wp_remote_retrieve_headers( array|WP_Error $response ): Requests_Utility_CaseInsensitiveDictionary|array wp\_remote\_retrieve\_headers( array|WP\_Error $response ): Requests\_Utility\_CaseInsensitiveDictionary|array
==============================================================================================================
Retrieve only the headers from the raw response.
* [Requests\_Utility\_CaseInsensitiveDictionary](../classes/requests_utility_caseinsensitivedictionary)
`$response` array|[WP\_Error](../classes/wp_error) Required HTTP response. [Requests\_Utility\_CaseInsensitiveDictionary](../classes/requests_utility_caseinsensitivedictionary)|array The headers of the response, or empty array if incorrect parameter given.
File: `wp-includes/http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/http.php/)
```
function wp_remote_retrieve_headers( $response ) {
if ( is_wp_error( $response ) || ! isset( $response['headers'] ) ) {
return array();
}
return $response['headers'];
}
```
| Uses | Description |
| --- | --- |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [wp\_get\_http()](wp_get_http) wp-includes/deprecated.php | Perform a HTTP HEAD or GET request. |
| [wp\_get\_http\_headers()](wp_get_http_headers) wp-includes/functions.php | Retrieves HTTP Headers from URL. |
| [WP\_SimplePie\_File::\_\_construct()](../classes/wp_simplepie_file/__construct) wp-includes/class-wp-simplepie-file.php | Constructor. |
| [\_fetch\_remote\_file()](_fetch_remote_file) wp-includes/rss.php | Retrieve URL headers and content using WP HTTP Request API. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Return value changed from an array to an [Requests\_Utility\_CaseInsensitiveDictionary](../classes/requests_utility_caseinsensitivedictionary) instance. |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress rest_filter_response_by_context( array|object $data, array $schema, string $context ): array|object rest\_filter\_response\_by\_context( array|object $data, array $schema, string $context ): array|object
=======================================================================================================
Filters the response to remove any fields not available in the given context.
`$data` array|object Required The response data to modify. `$schema` array Required The schema for the endpoint used to filter the response. `$context` string Required The requested context. array|object The filtered response data.
File: `wp-includes/rest-api.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api.php/)
```
function rest_filter_response_by_context( $data, $schema, $context ) {
if ( isset( $schema['anyOf'] ) ) {
$matching_schema = rest_find_any_matching_schema( $data, $schema, '' );
if ( ! is_wp_error( $matching_schema ) ) {
if ( ! isset( $schema['type'] ) ) {
$schema['type'] = $matching_schema['type'];
}
$data = rest_filter_response_by_context( $data, $matching_schema, $context );
}
}
if ( isset( $schema['oneOf'] ) ) {
$matching_schema = rest_find_one_matching_schema( $data, $schema, '', true );
if ( ! is_wp_error( $matching_schema ) ) {
if ( ! isset( $schema['type'] ) ) {
$schema['type'] = $matching_schema['type'];
}
$data = rest_filter_response_by_context( $data, $matching_schema, $context );
}
}
if ( ! is_array( $data ) && ! is_object( $data ) ) {
return $data;
}
if ( isset( $schema['type'] ) ) {
$type = $schema['type'];
} elseif ( isset( $schema['properties'] ) ) {
$type = 'object'; // Back compat if a developer accidentally omitted the type.
} else {
return $data;
}
$is_array_type = 'array' === $type || ( is_array( $type ) && in_array( 'array', $type, true ) );
$is_object_type = 'object' === $type || ( is_array( $type ) && in_array( 'object', $type, true ) );
if ( $is_array_type && $is_object_type ) {
if ( rest_is_array( $data ) ) {
$is_object_type = false;
} else {
$is_array_type = false;
}
}
$has_additional_properties = $is_object_type && isset( $schema['additionalProperties'] ) && is_array( $schema['additionalProperties'] );
foreach ( $data as $key => $value ) {
$check = array();
if ( $is_array_type ) {
$check = isset( $schema['items'] ) ? $schema['items'] : array();
} elseif ( $is_object_type ) {
if ( isset( $schema['properties'][ $key ] ) ) {
$check = $schema['properties'][ $key ];
} else {
$pattern_property_schema = rest_find_matching_pattern_property_schema( $key, $schema );
if ( null !== $pattern_property_schema ) {
$check = $pattern_property_schema;
} elseif ( $has_additional_properties ) {
$check = $schema['additionalProperties'];
}
}
}
if ( ! isset( $check['context'] ) ) {
continue;
}
if ( ! in_array( $context, $check['context'], true ) ) {
if ( $is_array_type ) {
// All array items share schema, so there's no need to check each one.
$data = array();
break;
}
if ( is_object( $data ) ) {
unset( $data->$key );
} else {
unset( $data[ $key ] );
}
} elseif ( is_array( $value ) || is_object( $value ) ) {
$new_value = rest_filter_response_by_context( $value, $check, $context );
if ( is_object( $data ) ) {
$data->$key = $new_value;
} else {
$data[ $key ] = $new_value;
}
}
}
return $data;
}
```
| Uses | Description |
| --- | --- |
| [rest\_find\_any\_matching\_schema()](rest_find_any_matching_schema) wp-includes/rest-api.php | Finds the matching schema among the “anyOf” schemas. |
| [rest\_find\_one\_matching\_schema()](rest_find_one_matching_schema) wp-includes/rest-api.php | Finds the matching schema among the “oneOf” schemas. |
| [rest\_find\_matching\_pattern\_property\_schema()](rest_find_matching_pattern_property_schema) wp-includes/rest-api.php | Finds the schema for a property using the patternProperties keyword. |
| [rest\_filter\_response\_by\_context()](rest_filter_response_by_context) wp-includes/rest-api.php | Filters the response to remove any fields not available in the given context. |
| [rest\_is\_array()](rest_is_array) wp-includes/rest-api.php | Determines if a given value is array-like. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [rest\_filter\_response\_by\_context()](rest_filter_response_by_context) wp-includes/rest-api.php | Filters the response to remove any fields not available in the given context. |
| [WP\_REST\_Controller::filter\_response\_by\_context()](../classes/wp_rest_controller/filter_response_by_context) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Filters a response based on the context defined in the schema. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Support the "patternProperties" keyword for objects. Support the "anyOf" and "oneOf" keywords. |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress single_cat_title( string $prefix = '', bool $display = true ): string|void single\_cat\_title( string $prefix = '', bool $display = true ): string|void
============================================================================
Displays or retrieves page title for category archive.
Useful for category template files for displaying the category page title.
The prefix does not automatically place a space between the prefix, so if there should be a space, the parameter value will need to have it at the end.
`$prefix` string Optional What to display before the title. Default: `''`
`$display` bool Optional Whether to display or retrieve title. Default: `true`
string|void Title when retrieving.
File: `wp-includes/general-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/general-template.php/)
```
function single_cat_title( $prefix = '', $display = true ) {
return single_term_title( $prefix, $display );
}
```
| Uses | Description |
| --- | --- |
| [single\_term\_title()](single_term_title) wp-includes/general-template.php | Displays or retrieves page title for taxonomy term archive. |
| Used By | Description |
| --- | --- |
| [get\_the\_archive\_title()](get_the_archive_title) wp-includes/general-template.php | Retrieves the archive title based on the queried object. |
| Version | Description |
| --- | --- |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress wp_update_user( array|object|WP_User $userdata ): int|WP_Error wp\_update\_user( array|object|WP\_User $userdata ): int|WP\_Error
==================================================================
Updates a user in the database.
It is possible to update a user’s password by specifying the ‘user\_pass’ value in the $userdata parameter array.
If current user’s password is being updated, then the cookies will be cleared.
* [wp\_insert\_user()](wp_insert_user) : For what fields can be set in $userdata.
`$userdata` array|object|[WP\_User](../classes/wp_user) Required An array of user data or a user object of type stdClass or [WP\_User](../classes/wp_user). int|[WP\_Error](../classes/wp_error) The updated user's ID or a [WP\_Error](../classes/wp_error) object if the user could not be updated.
File: `wp-includes/user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/user.php/)
```
function wp_update_user( $userdata ) {
if ( $userdata instanceof stdClass ) {
$userdata = get_object_vars( $userdata );
} elseif ( $userdata instanceof WP_User ) {
$userdata = $userdata->to_array();
}
$user_id = isset( $userdata['ID'] ) ? (int) $userdata['ID'] : 0;
if ( ! $user_id ) {
return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
}
// First, get all of the original fields.
$user_obj = get_userdata( $user_id );
if ( ! $user_obj ) {
return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
}
$user = $user_obj->to_array();
// Add additional custom fields.
foreach ( _get_additional_user_keys( $user_obj ) as $key ) {
$user[ $key ] = get_user_meta( $user_id, $key, true );
}
// Escape data pulled from DB.
$user = add_magic_quotes( $user );
if ( ! empty( $userdata['user_pass'] ) && $userdata['user_pass'] !== $user_obj->user_pass ) {
// If password is changing, hash it now.
$plaintext_pass = $userdata['user_pass'];
$userdata['user_pass'] = wp_hash_password( $userdata['user_pass'] );
/**
* Filters whether to send the password change email.
*
* @since 4.3.0
*
* @see wp_insert_user() For `$user` and `$userdata` fields.
*
* @param bool $send Whether to send the email.
* @param array $user The original user array.
* @param array $userdata The updated user array.
*/
$send_password_change_email = apply_filters( 'send_password_change_email', true, $user, $userdata );
}
if ( isset( $userdata['user_email'] ) && $user['user_email'] !== $userdata['user_email'] ) {
/**
* Filters whether to send the email change email.
*
* @since 4.3.0
*
* @see wp_insert_user() For `$user` and `$userdata` fields.
*
* @param bool $send Whether to send the email.
* @param array $user The original user array.
* @param array $userdata The updated user array.
*/
$send_email_change_email = apply_filters( 'send_email_change_email', true, $user, $userdata );
}
clean_user_cache( $user_obj );
// Merge old and new fields with new fields overwriting old ones.
$userdata = array_merge( $user, $userdata );
$user_id = wp_insert_user( $userdata );
if ( is_wp_error( $user_id ) ) {
return $user_id;
}
$blog_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
$switched_locale = false;
if ( ! empty( $send_password_change_email ) || ! empty( $send_email_change_email ) ) {
$switched_locale = switch_to_locale( get_user_locale( $user_id ) );
}
if ( ! empty( $send_password_change_email ) ) {
/* translators: Do not translate USERNAME, ADMIN_EMAIL, EMAIL, SITENAME, SITEURL: those are placeholders. */
$pass_change_text = __(
'Hi ###USERNAME###,
This notice confirms that your password was changed on ###SITENAME###.
If you did not change your password, please contact the Site Administrator at
###ADMIN_EMAIL###
This email has been sent to ###EMAIL###
Regards,
All at ###SITENAME###
###SITEURL###'
);
$pass_change_email = array(
'to' => $user['user_email'],
/* translators: Password change notification email subject. %s: Site title. */
'subject' => __( '[%s] Password Changed' ),
'message' => $pass_change_text,
'headers' => '',
);
/**
* Filters the contents of the email sent when the user's password is changed.
*
* @since 4.3.0
*
* @param array $pass_change_email {
* Used to build wp_mail().
*
* @type string $to The intended recipients. Add emails in a comma separated string.
* @type string $subject The subject of the email.
* @type string $message The content of the email.
* The following strings have a special meaning and will get replaced dynamically:
* - ###USERNAME### The current user's username.
* - ###ADMIN_EMAIL### The admin email in case this was unexpected.
* - ###EMAIL### The user's email address.
* - ###SITENAME### The name of the site.
* - ###SITEURL### The URL to the site.
* @type string $headers Headers. Add headers in a newline (\r\n) separated string.
* }
* @param array $user The original user array.
* @param array $userdata The updated user array.
*/
$pass_change_email = apply_filters( 'password_change_email', $pass_change_email, $user, $userdata );
$pass_change_email['message'] = str_replace( '###USERNAME###', $user['user_login'], $pass_change_email['message'] );
$pass_change_email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $pass_change_email['message'] );
$pass_change_email['message'] = str_replace( '###EMAIL###', $user['user_email'], $pass_change_email['message'] );
$pass_change_email['message'] = str_replace( '###SITENAME###', $blog_name, $pass_change_email['message'] );
$pass_change_email['message'] = str_replace( '###SITEURL###', home_url(), $pass_change_email['message'] );
wp_mail( $pass_change_email['to'], sprintf( $pass_change_email['subject'], $blog_name ), $pass_change_email['message'], $pass_change_email['headers'] );
}
if ( ! empty( $send_email_change_email ) ) {
/* translators: Do not translate USERNAME, ADMIN_EMAIL, NEW_EMAIL, EMAIL, SITENAME, SITEURL: those are placeholders. */
$email_change_text = __(
'Hi ###USERNAME###,
This notice confirms that your email address on ###SITENAME### was changed to ###NEW_EMAIL###.
If you did not change your email, please contact the Site Administrator at
###ADMIN_EMAIL###
This email has been sent to ###EMAIL###
Regards,
All at ###SITENAME###
###SITEURL###'
);
$email_change_email = array(
'to' => $user['user_email'],
/* translators: Email change notification email subject. %s: Site title. */
'subject' => __( '[%s] Email Changed' ),
'message' => $email_change_text,
'headers' => '',
);
/**
* Filters the contents of the email sent when the user's email is changed.
*
* @since 4.3.0
*
* @param array $email_change_email {
* Used to build wp_mail().
*
* @type string $to The intended recipients.
* @type string $subject The subject of the email.
* @type string $message The content of the email.
* The following strings have a special meaning and will get replaced dynamically:
* - ###USERNAME### The current user's username.
* - ###ADMIN_EMAIL### The admin email in case this was unexpected.
* - ###NEW_EMAIL### The new email address.
* - ###EMAIL### The old email address.
* - ###SITENAME### The name of the site.
* - ###SITEURL### The URL to the site.
* @type string $headers Headers.
* }
* @param array $user The original user array.
* @param array $userdata The updated user array.
*/
$email_change_email = apply_filters( 'email_change_email', $email_change_email, $user, $userdata );
$email_change_email['message'] = str_replace( '###USERNAME###', $user['user_login'], $email_change_email['message'] );
$email_change_email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $email_change_email['message'] );
$email_change_email['message'] = str_replace( '###NEW_EMAIL###', $userdata['user_email'], $email_change_email['message'] );
$email_change_email['message'] = str_replace( '###EMAIL###', $user['user_email'], $email_change_email['message'] );
$email_change_email['message'] = str_replace( '###SITENAME###', $blog_name, $email_change_email['message'] );
$email_change_email['message'] = str_replace( '###SITEURL###', home_url(), $email_change_email['message'] );
wp_mail( $email_change_email['to'], sprintf( $email_change_email['subject'], $blog_name ), $email_change_email['message'], $email_change_email['headers'] );
}
if ( $switched_locale ) {
restore_previous_locale();
}
// Update the cookies if the password changed.
$current_user = wp_get_current_user();
if ( $current_user->ID == $user_id ) {
if ( isset( $plaintext_pass ) ) {
wp_clear_auth_cookie();
// Here we calculate the expiration length of the current auth cookie and compare it to the default expiration.
// If it's greater than this, then we know the user checked 'Remember Me' when they logged in.
$logged_in_cookie = wp_parse_auth_cookie( '', 'logged_in' );
/** This filter is documented in wp-includes/pluggable.php */
$default_cookie_life = apply_filters( 'auth_cookie_expiration', ( 2 * DAY_IN_SECONDS ), $user_id, false );
$remember = false;
if ( false !== $logged_in_cookie && ( $logged_in_cookie['expiration'] - time() ) > $default_cookie_life ) {
$remember = true;
}
wp_set_auth_cookie( $user_id, $remember );
}
}
return $user_id;
}
```
[apply\_filters( 'auth\_cookie\_expiration', int $length, int $user\_id, bool $remember )](../hooks/auth_cookie_expiration)
Filters the duration of the authentication cookie expiration period.
[apply\_filters( 'email\_change\_email', array $email\_change\_email, array $user, array $userdata )](../hooks/email_change_email)
Filters the contents of the email sent when the user’s email is changed.
[apply\_filters( 'password\_change\_email', array $pass\_change\_email, array $user, array $userdata )](../hooks/password_change_email)
Filters the contents of the email sent when the user’s password is changed.
[apply\_filters( 'send\_email\_change\_email', bool $send, array $user, array $userdata )](../hooks/send_email_change_email)
Filters whether to send the email change email.
[apply\_filters( 'send\_password\_change\_email', bool $send, array $user, array $userdata )](../hooks/send_password_change_email)
Filters whether to send the password change email.
| Uses | Description |
| --- | --- |
| [restore\_previous\_locale()](restore_previous_locale) wp-includes/l10n.php | Restores the translations according to the previous locale. |
| [wp\_mail()](wp_mail) wp-includes/pluggable.php | Sends an email, similar to PHP’s mail function. |
| [get\_user\_meta()](get_user_meta) wp-includes/user.php | Retrieves user meta field for a user. |
| [wp\_insert\_user()](wp_insert_user) wp-includes/user.php | Inserts a user into the database. |
| [clean\_user\_cache()](clean_user_cache) wp-includes/user.php | Cleans all user caches. |
| [\_get\_additional\_user\_keys()](_get_additional_user_keys) wp-includes/user.php | Returns a list of meta keys to be (maybe) populated in [wp\_update\_user()](wp_update_user) . |
| [add\_magic\_quotes()](add_magic_quotes) wp-includes/functions.php | Walks the array while sanitizing the contents. |
| [switch\_to\_locale()](switch_to_locale) wp-includes/l10n.php | Switches the translations according to the given locale. |
| [wp\_get\_current\_user()](wp_get_current_user) wp-includes/pluggable.php | Retrieves the current user object. |
| [wp\_set\_auth\_cookie()](wp_set_auth_cookie) wp-includes/pluggable.php | Sets the authentication cookies based on user ID. |
| [wp\_parse\_auth\_cookie()](wp_parse_auth_cookie) wp-includes/pluggable.php | Parses a cookie into its components. |
| [wp\_clear\_auth\_cookie()](wp_clear_auth_cookie) wp-includes/pluggable.php | Removes all of the cookies associated with authentication. |
| [wp\_hash\_password()](wp_hash_password) wp-includes/pluggable.php | Creates a hash (encrypt) of a plain text password. |
| [wp\_specialchars\_decode()](wp_specialchars_decode) wp-includes/formatting.php | Converts a number of HTML entities into their special characters. |
| [get\_user\_locale()](get_user_locale) wp-includes/l10n.php | Retrieves the locale of a user. |
| [get\_userdata()](get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [home\_url()](home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../classes/wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Users\_Controller::create\_item()](../classes/wp_rest_users_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Creates a single user. |
| [WP\_REST\_Users\_Controller::update\_item()](../classes/wp_rest_users_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Updates a single user. |
| [get\_password\_reset\_key()](get_password_reset_key) wp-includes/user.php | Creates, stores, then returns a password reset key for user. |
| [wp\_install()](wp_install) wp-admin/includes/upgrade.php | Installs the site. |
| [edit\_user()](edit_user) wp-admin/includes/user.php | Edit user settings based on contents of $\_POST |
| [wp\_xmlrpc\_server::wp\_editProfile()](../classes/wp_xmlrpc_server/wp_editprofile) wp-includes/class-wp-xmlrpc-server.php | Edit user’s profile. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
| programming_docs |
wordpress wp_get_linksbyname( string $category, string $args = '' ): string|null wp\_get\_linksbyname( string $category, string $args = '' ): string|null
========================================================================
This function has been deprecated. Use [wp\_list\_bookmarks()](wp_list_bookmarks) instead.
Gets the links associated with the named category.
* [wp\_list\_bookmarks()](wp_list_bookmarks)
`$category` string Required The category to use. `$args` string Optional Default: `''`
string|null
File: `wp-includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/deprecated.php/)
```
function wp_get_linksbyname($category, $args = '') {
_deprecated_function(__FUNCTION__, '2.1.0', 'wp_list_bookmarks()');
$defaults = array(
'after' => '<br />',
'before' => '',
'categorize' => 0,
'category_after' => '',
'category_before' => '',
'category_name' => $category,
'show_description' => 1,
'title_li' => '',
);
$parsed_args = wp_parse_args( $args, $defaults );
return wp_list_bookmarks($parsed_args);
}
```
| Uses | Description |
| --- | --- |
| [wp\_list\_bookmarks()](wp_list_bookmarks) wp-includes/bookmark-template.php | Retrieves or echoes all of the bookmarks. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| [wp\_parse\_args()](wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Use [wp\_list\_bookmarks()](wp_list_bookmarks) |
| [1.0.1](https://developer.wordpress.org/reference/since/1.0.1/) | Introduced. |
wordpress wp_embed_handler_youtube( array $matches, array $attr, string $url, array $rawattr ): string wp\_embed\_handler\_youtube( array $matches, array $attr, string $url, array $rawattr ): string
===============================================================================================
YouTube iframe embed handler callback.
Catches YouTube iframe embed URLs that are not parsable by oEmbed but can be translated into a URL that is.
`$matches` array Required The RegEx matches from the provided regex when calling [wp\_embed\_register\_handler()](wp_embed_register_handler) . `$attr` array Required Embed attributes. `$url` string Required The original URL that was matched by the regex. `$rawattr` array Required The original unmodified attributes. string The embed HTML.
File: `wp-includes/embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/embed.php/)
```
function wp_embed_handler_youtube( $matches, $attr, $url, $rawattr ) {
global $wp_embed;
$embed = $wp_embed->autoembed( sprintf( 'https://youtube.com/watch?v=%s', urlencode( $matches[2] ) ) );
/**
* Filters the YoutTube embed output.
*
* @since 4.0.0
*
* @see wp_embed_handler_youtube()
*
* @param string $embed YouTube embed output.
* @param array $attr An array of embed attributes.
* @param string $url The original URL that was matched by the regex.
* @param array $rawattr The original unmodified attributes.
*/
return apply_filters( 'wp_embed_handler_youtube', $embed, $attr, $url, $rawattr );
}
```
[apply\_filters( 'wp\_embed\_handler\_youtube', string $embed, array $attr, string $url, array $rawattr )](../hooks/wp_embed_handler_youtube)
Filters the YoutTube embed output.
| Uses | Description |
| --- | --- |
| [WP\_Embed::autoembed()](../classes/wp_embed/autoembed) wp-includes/class-wp-embed.php | Passes any unlinked URLs that are on their own line to [WP\_Embed::shortcode()](../classes/wp_embed/shortcode) for potential embedding. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress wp_is_application_passwords_available(): bool wp\_is\_application\_passwords\_available(): bool
=================================================
Checks if Application Passwords is globally available.
By default, Application Passwords is available to all sites using SSL or to local environments.
Use the [‘wp\_is\_application\_passwords\_available’](../hooks/wp_is_application_passwords_available) filter to adjust its availability.
bool
File: `wp-includes/user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/user.php/)
```
function wp_is_application_passwords_available() {
/**
* Filters whether Application Passwords is available.
*
* @since 5.6.0
*
* @param bool $available True if available, false otherwise.
*/
return apply_filters( 'wp_is_application_passwords_available', wp_is_application_passwords_supported() );
}
```
[apply\_filters( 'wp\_is\_application\_passwords\_available', bool $available )](../hooks/wp_is_application_passwords_available)
Filters whether Application Passwords is available.
| Uses | Description |
| --- | --- |
| [wp\_is\_application\_passwords\_supported()](wp_is_application_passwords_supported) wp-includes/user.php | Checks if Application Passwords is supported. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](../classes/wp_rest_application_passwords_controller/get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [wp\_is\_application\_passwords\_available\_for\_user()](wp_is_application_passwords_available_for_user) wp-includes/user.php | Checks if Application Passwords is available for a specific user. |
| [wp\_authenticate\_application\_password()](wp_authenticate_application_password) wp-includes/user.php | Authenticates the user using an application password. |
| [wp\_validate\_application\_password()](wp_validate_application_password) wp-includes/user.php | Validates the application password credentials passed via Basic Authentication. |
| [rest\_add\_application\_passwords\_to\_index()](rest_add_application_passwords_to_index) wp-includes/rest-api.php | Adds Application Passwords info to the REST API index. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress wp_check_term_hierarchy_for_loops( int $parent, int $term_id, string $taxonomy ): int wp\_check\_term\_hierarchy\_for\_loops( int $parent, int $term\_id, string $taxonomy ): int
===========================================================================================
Checks the given subset of the term hierarchy for hierarchy loops.
Prevents loops from forming and breaks those that it finds.
Attached to the [‘wp\_update\_term\_parent’](../hooks/wp_update_term_parent) filter.
`$parent` int Required `term_id` of the parent for the term we're checking. `$term_id` int Required The term we're checking. `$taxonomy` string Required The taxonomy of the term we're checking. int The new parent for the term.
File: `wp-includes/taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/taxonomy.php/)
```
function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
// Nothing fancy here - bail.
if ( ! $parent ) {
return 0;
}
// Can't be its own parent.
if ( $parent === $term_id ) {
return 0;
}
// Now look for larger loops.
$loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) );
if ( ! $loop ) {
return $parent; // No loop.
}
// Setting $parent to the given value causes a loop.
if ( isset( $loop[ $term_id ] ) ) {
return 0;
}
// There's a loop, but it doesn't contain $term_id. Break the loop.
foreach ( array_keys( $loop ) as $loop_member ) {
wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );
}
return $parent;
}
```
| Uses | Description |
| --- | --- |
| [wp\_find\_hierarchy\_loop()](wp_find_hierarchy_loop) wp-includes/functions.php | Finds hierarchy loops using a callback function that maps object IDs to parent IDs. |
| [wp\_update\_term()](wp_update_term) wp-includes/taxonomy.php | Updates term based on arguments provided. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress is_day(): bool is\_day(): bool
===============
Determines whether the query is for an existing day archive.
A conditional check to test whether the page is a date-based archive page displaying posts for the current day.
For more information on this and similar theme functions, check out the [Conditional Tags](https://developer.wordpress.org/themes/basics/conditional-tags/) article in the Theme Developer Handbook.
bool Whether the query is for an existing day archive.
File: `wp-includes/query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/query.php/)
```
function is_day() {
global $wp_query;
if ( ! isset( $wp_query ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
return false;
}
return $wp_query->is_day();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Query::is\_day()](../classes/wp_query/is_day) wp-includes/class-wp-query.php | Is the query for an existing day archive? |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_doing\_it\_wrong()](_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Used By | Description |
| --- | --- |
| [wp\_get\_document\_title()](wp_get_document_title) wp-includes/general-template.php | Returns document title for the current page. |
| [get\_the\_archive\_title()](get_the_archive_title) wp-includes/general-template.php | Retrieves the archive title based on the queried object. |
| [redirect\_canonical()](redirect_canonical) wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_privacy_generate_personal_data_export_group_html( array $group_data, string $group_id = '', int $groups_count = 1 ): string wp\_privacy\_generate\_personal\_data\_export\_group\_html( array $group\_data, string $group\_id = '', int $groups\_count = 1 ): string
========================================================================================================================================
Generate a single group for the personal data export report.
`$group_data` array Required The group data to render.
* `group_label`stringThe user-facing heading for the group, e.g. `'Comments'`.
* `items`array An array of group items.
+ `group_item_data`array An array of name-value pairs for the item.
- `name`stringThe user-facing name of an item name-value pair, e.g. 'IP Address'.
- `value`stringThe user-facing value of an item data pair, e.g. `'50.60.70.0'`.
} `$group_id` string Optional The group identifier. Default: `''`
`$groups_count` int Optional The number of all groups Default: `1`
string The HTML for this group and its items.
File: `wp-admin/includes/privacy-tools.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/privacy-tools.php/)
```
function wp_privacy_generate_personal_data_export_group_html( $group_data, $group_id = '', $groups_count = 1 ) {
$group_id_attr = sanitize_title_with_dashes( $group_data['group_label'] . '-' . $group_id );
$group_html = '<h2 id="' . esc_attr( $group_id_attr ) . '">';
$group_html .= esc_html( $group_data['group_label'] );
$items_count = count( (array) $group_data['items'] );
if ( $items_count > 1 ) {
$group_html .= sprintf( ' <span class="count">(%d)</span>', $items_count );
}
$group_html .= '</h2>';
if ( ! empty( $group_data['group_description'] ) ) {
$group_html .= '<p>' . esc_html( $group_data['group_description'] ) . '</p>';
}
$group_html .= '<div>';
foreach ( (array) $group_data['items'] as $group_item_id => $group_item_data ) {
$group_html .= '<table>';
$group_html .= '<tbody>';
foreach ( (array) $group_item_data as $group_item_datum ) {
$value = $group_item_datum['value'];
// If it looks like a link, make it a link.
if ( false === strpos( $value, ' ' ) && ( 0 === strpos( $value, 'http://' ) || 0 === strpos( $value, 'https://' ) ) ) {
$value = '<a href="' . esc_url( $value ) . '">' . esc_html( $value ) . '</a>';
}
$group_html .= '<tr>';
$group_html .= '<th>' . esc_html( $group_item_datum['name'] ) . '</th>';
$group_html .= '<td>' . wp_kses( $value, 'personal_data_export' ) . '</td>';
$group_html .= '</tr>';
}
$group_html .= '</tbody>';
$group_html .= '</table>';
}
if ( $groups_count > 1 ) {
$group_html .= '<div class="return-to-top">';
$group_html .= '<a href="#top"><span aria-hidden="true">↑ </span> ' . esc_html__( 'Go to top' ) . '</a>';
$group_html .= '</div>';
}
$group_html .= '</div>';
return $group_html;
}
```
| Uses | Description |
| --- | --- |
| [esc\_html\_\_()](esc_html__) wp-includes/l10n.php | Retrieves the translation of $text and escapes it for safe use in HTML output. |
| [sanitize\_title\_with\_dashes()](sanitize_title_with_dashes) wp-includes/formatting.php | Sanitizes a title, replacing whitespace and a few other characters with dashes. |
| [wp\_kses()](wp_kses) wp-includes/kses.php | Filters text content and strips out disallowed HTML. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| Used By | Description |
| --- | --- |
| [wp\_privacy\_generate\_personal\_data\_export\_file()](wp_privacy_generate_personal_data_export_file) wp-admin/includes/privacy-tools.php | Generate the personal data export file. |
| Version | Description |
| --- | --- |
| [5.4.0](https://developer.wordpress.org/reference/since/5.4.0/) | Added the `$group_id` and `$groups_count` parameters. |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress is_post_type_hierarchical( string $post_type ): bool is\_post\_type\_hierarchical( string $post\_type ): bool
========================================================
Determines whether the post type is hierarchical.
A false return value might also mean that the post type does not exist.
* [get\_post\_type\_object()](get_post_type_object)
`$post_type` string Required Post type name bool Whether post type is hierarchical.
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function is_post_type_hierarchical( $post_type ) {
if ( ! post_type_exists( $post_type ) ) {
return false;
}
$post_type = get_post_type_object( $post_type );
return $post_type->hierarchical;
}
```
| Uses | Description |
| --- | --- |
| [post\_type\_exists()](post_type_exists) wp-includes/post.php | Determines whether a post type is registered. |
| [get\_post\_type\_object()](get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Used By | Description |
| --- | --- |
| [build\_query\_vars\_from\_query\_block()](build_query_vars_from_query_block) wp-includes/blocks.php | Helper function that constructs a [WP\_Query](../classes/wp_query) args array from a `Query` block properties. |
| [wp\_check\_for\_changed\_dates()](wp_check_for_changed_dates) wp-includes/post.php | Checks for changed dates for published post objects and save the old date. |
| [WP\_Posts\_List\_Table::handle\_row\_actions()](../classes/wp_posts_list_table/handle_row_actions) wp-admin/includes/class-wp-posts-list-table.php | Generates and displays row action links. |
| [WP\_Posts\_List\_Table::column\_title()](../classes/wp_posts_list_table/column_title) wp-admin/includes/class-wp-posts-list-table.php | Handles the title column output. |
| [WP\_Posts\_List\_Table::column\_default()](../classes/wp_posts_list_table/column_default) wp-admin/includes/class-wp-posts-list-table.php | Handles the default column output. |
| [wp\_edit\_posts\_query()](wp_edit_posts_query) wp-admin/includes/post.php | Runs the query to fetch the posts for listing on the edit posts page. |
| [wp\_ajax\_inline\_save()](wp_ajax_inline_save) wp-admin/includes/ajax-actions.php | Ajax handler for Quick Edit saving a post from a list table. |
| [page\_attributes\_meta\_box()](page_attributes_meta_box) wp-admin/includes/meta-boxes.php | Displays page attributes form fields. |
| [wp\_nav\_menu\_item\_post\_type\_meta\_box()](wp_nav_menu_item_post_type_meta_box) wp-admin/includes/nav-menu.php | Displays a meta box for a post type menu item. |
| [WP\_Posts\_List\_Table::get\_table\_classes()](../classes/wp_posts_list_table/get_table_classes) wp-admin/includes/class-wp-posts-list-table.php | |
| [WP\_Posts\_List\_Table::prepare\_items()](../classes/wp_posts_list_table/prepare_items) wp-admin/includes/class-wp-posts-list-table.php | |
| [wp\_old\_slug\_redirect()](wp_old_slug_redirect) wp-includes/query.php | Redirect old slugs to the correct permalink. |
| [\_wp\_menu\_item\_classes\_by\_context()](_wp_menu_item_classes_by_context) wp-includes/nav-menu-template.php | Adds the class property classes for the current context, if applicable. |
| [wp\_list\_pages()](wp_list_pages) wp-includes/post-template.php | Retrieves or displays a list of pages (or hierarchical post type items) in list (li) format. |
| [wp\_check\_for\_changed\_slugs()](wp_check_for_changed_slugs) wp-includes/post.php | Checks for changed slugs for published post objects and save the old slug. |
| [wp\_unique\_post\_slug()](wp_unique_post_slug) wp-includes/post.php | Computes a unique slug for the post, when given the desired slug and some post details. |
| [wp\_delete\_post()](wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [WP\_Rewrite::generate\_rewrite\_rules()](../classes/wp_rewrite/generate_rewrite_rules) wp-includes/class-wp-rewrite.php | Generates rewrite rules from a permalink structure. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress get_user_metavalues( array $ids ): array get\_user\_metavalues( array $ids ): array
==========================================
This function has been deprecated.
Perform the query to get the $metavalues array(s) needed by \_fill\_user and \_fill\_many\_users
`$ids` array Required User ID numbers list. array of arrays. The array is indexed by user\_id, containing $metavalues object arrays.
File: `wp-includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/deprecated.php/)
```
function get_user_metavalues($ids) {
_deprecated_function( __FUNCTION__, '3.3.0' );
$objects = array();
$ids = array_map('intval', $ids);
foreach ( $ids as $id )
$objects[$id] = array();
$metas = update_meta_cache('user', $ids);
foreach ( $metas as $id => $meta ) {
foreach ( $meta as $key => $metavalues ) {
foreach ( $metavalues as $value ) {
$objects[$id][] = (object)array( 'user_id' => $id, 'meta_key' => $key, 'meta_value' => $value);
}
}
}
return $objects;
}
```
| Uses | Description |
| --- | --- |
| [update\_meta\_cache()](update_meta_cache) wp-includes/meta.php | Updates the metadata cache for the specified objects. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | This function has been deprecated. |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
| programming_docs |
wordpress wpmu_welcome_user_notification( int $user_id, string $password, array $meta = array() ): bool wpmu\_welcome\_user\_notification( int $user\_id, string $password, array $meta = array() ): bool
=================================================================================================
Notifies a user that their account activation has been successful.
Filter [‘wpmu\_welcome\_user\_notification’](../hooks/wpmu_welcome_user_notification) to disable or bypass.
Filter [‘update\_welcome\_user\_email’](../hooks/update_welcome_user_email) and [‘update\_welcome\_user\_subject’](../hooks/update_welcome_user_subject) to modify the content and subject line of the notification email.
`$user_id` int Required User ID. `$password` string Required User password. `$meta` array Optional Signup meta data. Default: `array()`
bool
File: `wp-includes/ms-functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-functions.php/)
```
function wpmu_welcome_user_notification( $user_id, $password, $meta = array() ) {
$current_network = get_network();
/**
* Filters whether to bypass the welcome email after user activation.
*
* Returning false disables the welcome email.
*
* @since MU (3.0.0)
*
* @param int $user_id User ID.
* @param string $password User password.
* @param array $meta Signup meta data. Default empty array.
*/
if ( ! apply_filters( 'wpmu_welcome_user_notification', $user_id, $password, $meta ) ) {
return false;
}
$welcome_email = get_site_option( 'welcome_user_email' );
$user = get_userdata( $user_id );
$switched_locale = switch_to_locale( get_user_locale( $user ) );
/**
* Filters the content of the welcome email after user activation.
*
* Content should be formatted for transmission via wp_mail().
*
* @since MU (3.0.0)
*
* @param string $welcome_email The message body of the account activation success email.
* @param int $user_id User ID.
* @param string $password User password.
* @param array $meta Signup meta data. Default empty array.
*/
$welcome_email = apply_filters( 'update_welcome_user_email', $welcome_email, $user_id, $password, $meta );
$welcome_email = str_replace( 'SITE_NAME', $current_network->site_name, $welcome_email );
$welcome_email = str_replace( 'USERNAME', $user->user_login, $welcome_email );
$welcome_email = str_replace( 'PASSWORD', $password, $welcome_email );
$welcome_email = str_replace( 'LOGINLINK', wp_login_url(), $welcome_email );
$admin_email = get_site_option( 'admin_email' );
if ( '' === $admin_email ) {
$admin_email = 'support@' . wp_parse_url( network_home_url(), PHP_URL_HOST );
}
$from_name = ( '' !== get_site_option( 'site_name' ) ) ? esc_html( get_site_option( 'site_name' ) ) : 'WordPress';
$message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . 'Content-Type: text/plain; charset="' . get_option( 'blog_charset' ) . "\"\n";
$message = $welcome_email;
if ( empty( $current_network->site_name ) ) {
$current_network->site_name = 'WordPress';
}
/* translators: New user notification email subject. 1: Network title, 2: New user login. */
$subject = __( 'New %1$s User: %2$s' );
/**
* Filters the subject of the welcome email after user activation.
*
* @since MU (3.0.0)
*
* @param string $subject Subject of the email.
*/
$subject = apply_filters( 'update_welcome_user_subject', sprintf( $subject, $current_network->site_name, $user->user_login ) );
wp_mail( $user->user_email, wp_specialchars_decode( $subject ), $message, $message_headers );
if ( $switched_locale ) {
restore_previous_locale();
}
return true;
}
```
[apply\_filters( 'update\_welcome\_user\_email', string $welcome\_email, int $user\_id, string $password, array $meta )](../hooks/update_welcome_user_email)
Filters the content of the welcome email after user activation.
[apply\_filters( 'update\_welcome\_user\_subject', string $subject )](../hooks/update_welcome_user_subject)
Filters the subject of the welcome email after user activation.
[apply\_filters( 'wpmu\_welcome\_user\_notification', int $user\_id, string $password, array $meta )](../hooks/wpmu_welcome_user_notification)
Filters whether to bypass the welcome email after user activation.
| Uses | Description |
| --- | --- |
| [restore\_previous\_locale()](restore_previous_locale) wp-includes/l10n.php | Restores the translations according to the previous locale. |
| [switch\_to\_locale()](switch_to_locale) wp-includes/l10n.php | Switches the translations according to the given locale. |
| [get\_user\_locale()](get_user_locale) wp-includes/l10n.php | Retrieves the locale of a user. |
| [get\_network()](get_network) wp-includes/ms-network.php | Retrieves network data given a network ID or network object. |
| [wp\_parse\_url()](wp_parse_url) wp-includes/http.php | A wrapper for PHP’s parse\_url() function that handles consistency in the return values across PHP versions. |
| [wp\_specialchars\_decode()](wp_specialchars_decode) wp-includes/formatting.php | Converts a number of HTML entities into their special characters. |
| [wp\_mail()](wp_mail) wp-includes/pluggable.php | Sends an email, similar to PHP’s mail function. |
| [wp\_login\_url()](wp_login_url) wp-includes/general-template.php | Retrieves the login URL. |
| [network\_home\_url()](network_home_url) wp-includes/link-template.php | Retrieves the home URL for the current network. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [get\_userdata()](get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_site\_option()](get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [MU (3.0.0)](https://developer.wordpress.org/reference/since/mu.3.0.0/) | Introduced. |
wordpress wp_is_recovery_mode(): bool wp\_is\_recovery\_mode(): bool
==============================
Is WordPress in Recovery Mode.
In this mode, plugins or themes that cause WSODs will be paused.
bool
File: `wp-includes/load.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/load.php/)
```
function wp_is_recovery_mode() {
return wp_recovery_mode()->is_active();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Recovery\_Mode::is\_active()](../classes/wp_recovery_mode/is_active) wp-includes/class-wp-recovery-mode.php | Checks whether recovery mode is active. |
| [wp\_recovery\_mode()](wp_recovery_mode) wp-includes/error-protection.php | Access the WordPress Recovery Mode instance. |
| Used By | Description |
| --- | --- |
| [WP\_Fatal\_Error\_Handler::display\_default\_error\_template()](../classes/wp_fatal_error_handler/display_default_error_template) wp-includes/class-wp-fatal-error-handler.php | Displays the default PHP error template. |
| [wp\_admin\_bar\_recovery\_mode\_menu()](wp_admin_bar_recovery_mode_menu) wp-includes/admin-bar.php | Adds a link to exit recovery mode when Recovery Mode is active. |
| [wp\_recovery\_mode\_nag()](wp_recovery_mode_nag) wp-admin/includes/update.php | Displays a notice when the user is in recovery mode. |
| [wp\_get\_active\_and\_valid\_themes()](wp_get_active_and_valid_themes) wp-includes/load.php | Retrieves an array of active and valid themes. |
| [login\_header()](login_header) wp-login.php | Output the login page header. |
| [deactivate\_plugins()](deactivate_plugins) wp-admin/includes/plugin.php | Deactivates a single plugin or multiple plugins. |
| [switch\_theme()](switch_theme) wp-includes/theme.php | Switches the theme. |
| [wp\_get\_active\_and\_valid\_plugins()](wp_get_active_and_valid_plugins) wp-includes/load.php | Retrieve an array of active and valid plugin files. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress wp_start_scraping_edited_file_errors() wp\_start\_scraping\_edited\_file\_errors()
===========================================
Start scraping edited file errors.
File: `wp-includes/load.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/load.php/)
```
function wp_start_scraping_edited_file_errors() {
if ( ! isset( $_REQUEST['wp_scrape_key'] ) || ! isset( $_REQUEST['wp_scrape_nonce'] ) ) {
return;
}
$key = substr( sanitize_key( wp_unslash( $_REQUEST['wp_scrape_key'] ) ), 0, 32 );
$nonce = wp_unslash( $_REQUEST['wp_scrape_nonce'] );
if ( get_transient( 'scrape_key_' . $key ) !== $nonce ) {
echo "###### wp_scraping_result_start:$key ######";
echo wp_json_encode(
array(
'code' => 'scrape_nonce_failure',
'message' => __( 'Scrape key check failed. Please try again.' ),
)
);
echo "###### wp_scraping_result_end:$key ######";
die();
}
if ( ! defined( 'WP_SANDBOX_SCRAPING' ) ) {
define( 'WP_SANDBOX_SCRAPING', true );
}
register_shutdown_function( 'wp_finalize_scraping_edited_file_errors', $key );
}
```
| Uses | Description |
| --- | --- |
| [get\_transient()](get_transient) wp-includes/option.php | Retrieves the value of a transient. |
| [wp\_json\_encode()](wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_unslash()](wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [sanitize\_key()](sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress remove_block_asset_path_prefix( string $asset_handle_or_path ): string remove\_block\_asset\_path\_prefix( string $asset\_handle\_or\_path ): string
=============================================================================
Removes the block asset’s path prefix if provided.
`$asset_handle_or_path` string Required Asset handle or prefixed path. string Path without the prefix or the original value.
File: `wp-includes/blocks.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/blocks.php/)
```
function remove_block_asset_path_prefix( $asset_handle_or_path ) {
$path_prefix = 'file:';
if ( 0 !== strpos( $asset_handle_or_path, $path_prefix ) ) {
return $asset_handle_or_path;
}
$path = substr(
$asset_handle_or_path,
strlen( $path_prefix )
);
if ( strpos( $path, './' ) === 0 ) {
$path = substr( $path, 2 );
}
return $path;
}
```
| Used By | Description |
| --- | --- |
| [register\_block\_script\_handle()](register_block_script_handle) wp-includes/blocks.php | Finds a script handle for the selected block metadata field. It detects when a path to file was provided and finds a corresponding asset file with details necessary to register the script under automatically generated handle name. It returns unprocessed script handle otherwise. |
| [register\_block\_style\_handle()](register_block_style_handle) wp-includes/blocks.php | Finds a style handle for the block metadata field. It detects when a path to file was provided and registers the style under automatically generated handle name. It returns unprocessed style handle otherwise. |
| [register\_block\_type\_from\_metadata()](register_block_type_from_metadata) wp-includes/blocks.php | Registers a block type from the metadata stored in the `block.json` file. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress install_plugin_install_status( array|object $api, bool $loop = false ): array install\_plugin\_install\_status( array|object $api, bool $loop = false ): array
================================================================================
Determines the status we can perform on a plugin.
`$api` array|object Required Data about the plugin retrieved from the API. `$loop` bool Optional Disable further loops. Default: `false`
array Plugin installation status data.
* `status`stringStatus of a plugin. Could be one of `'install'`, `'update_available'`, `'latest_installed'` or `'newer_installed'`.
* `url`stringPlugin installation URL.
* `version`stringThe most recent version of the plugin.
* `file`stringPlugin filename relative to the plugins directory.
File: `wp-admin/includes/plugin-install.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/plugin-install.php/)
```
function install_plugin_install_status( $api, $loop = false ) {
// This function is called recursively, $loop prevents further loops.
if ( is_array( $api ) ) {
$api = (object) $api;
}
// Default to a "new" plugin.
$status = 'install';
$url = false;
$update_file = false;
$version = '';
/*
* Check to see if this plugin is known to be installed,
* and has an update awaiting it.
*/
$update_plugins = get_site_transient( 'update_plugins' );
if ( isset( $update_plugins->response ) ) {
foreach ( (array) $update_plugins->response as $file => $plugin ) {
if ( $plugin->slug === $api->slug ) {
$status = 'update_available';
$update_file = $file;
$version = $plugin->new_version;
if ( current_user_can( 'update_plugins' ) ) {
$url = wp_nonce_url( self_admin_url( 'update.php?action=upgrade-plugin&plugin=' . $update_file ), 'upgrade-plugin_' . $update_file );
}
break;
}
}
}
if ( 'install' === $status ) {
if ( is_dir( WP_PLUGIN_DIR . '/' . $api->slug ) ) {
$installed_plugin = get_plugins( '/' . $api->slug );
if ( empty( $installed_plugin ) ) {
if ( current_user_can( 'install_plugins' ) ) {
$url = wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=' . $api->slug ), 'install-plugin_' . $api->slug );
}
} else {
$key = array_keys( $installed_plugin );
// Use the first plugin regardless of the name.
// Could have issues for multiple plugins in one directory if they share different version numbers.
$key = reset( $key );
$update_file = $api->slug . '/' . $key;
if ( version_compare( $api->version, $installed_plugin[ $key ]['Version'], '=' ) ) {
$status = 'latest_installed';
} elseif ( version_compare( $api->version, $installed_plugin[ $key ]['Version'], '<' ) ) {
$status = 'newer_installed';
$version = $installed_plugin[ $key ]['Version'];
} else {
// If the above update check failed, then that probably means that the update checker has out-of-date information, force a refresh.
if ( ! $loop ) {
delete_site_transient( 'update_plugins' );
wp_update_plugins();
return install_plugin_install_status( $api, true );
}
}
}
} else {
// "install" & no directory with that slug.
if ( current_user_can( 'install_plugins' ) ) {
$url = wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=' . $api->slug ), 'install-plugin_' . $api->slug );
}
}
}
if ( isset( $_GET['from'] ) ) {
$url .= '&from=' . urlencode( wp_unslash( $_GET['from'] ) );
}
$file = $update_file;
return compact( 'status', 'url', 'version', 'file' );
}
```
| Uses | Description |
| --- | --- |
| [install\_plugin\_install\_status()](install_plugin_install_status) wp-admin/includes/plugin-install.php | Determines the status we can perform on a plugin. |
| [get\_plugins()](get_plugins) wp-admin/includes/plugin.php | Checks the plugins directory and retrieve all plugin files with plugin data. |
| [self\_admin\_url()](self_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for either the current site or the network depending on context. |
| [wp\_update\_plugins()](wp_update_plugins) wp-includes/update.php | Checks for available updates to plugins based on the latest versions hosted on WordPress.org. |
| [get\_site\_transient()](get_site_transient) wp-includes/option.php | Retrieves the value of a site transient. |
| [delete\_site\_transient()](delete_site_transient) wp-includes/option.php | Deletes a site transient. |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [wp\_unslash()](wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [wp\_nonce\_url()](wp_nonce_url) wp-includes/functions.php | Retrieves URL with nonce added to URL query. |
| Used By | Description |
| --- | --- |
| [wp\_ajax\_install\_plugin()](wp_ajax_install_plugin) wp-admin/includes/ajax-actions.php | Ajax handler for installing a plugin. |
| [install\_plugin\_install\_status()](install_plugin_install_status) wp-admin/includes/plugin-install.php | Determines the status we can perform on a plugin. |
| [install\_plugin\_information()](install_plugin_information) wp-admin/includes/plugin-install.php | Displays plugin information in dialog box form. |
| [WP\_Plugin\_Install\_List\_Table::display\_rows()](../classes/wp_plugin_install_list_table/display_rows) wp-admin/includes/class-wp-plugin-install-list-table.php | |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress delete_term_meta( int $term_id, string $meta_key, mixed $meta_value = '' ): bool delete\_term\_meta( int $term\_id, string $meta\_key, mixed $meta\_value = '' ): bool
=====================================================================================
Removes metadata matching criteria from a term.
`$term_id` int Required Term ID. `$meta_key` string Required Metadata name. `$meta_value` mixed Optional Metadata value. If provided, rows will only be removed that match the value.
Must be serializable if non-scalar. Default: `''`
bool True on success, false on failure.
File: `wp-includes/taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/taxonomy.php/)
```
function delete_term_meta( $term_id, $meta_key, $meta_value = '' ) {
return delete_metadata( 'term', $term_id, $meta_key, $meta_value );
}
```
| Uses | Description |
| --- | --- |
| [delete\_metadata()](delete_metadata) wp-includes/meta.php | Deletes metadata for the specified object. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress format_for_editor( string $text, string $default_editor = null ): string format\_for\_editor( string $text, string $default\_editor = null ): string
===========================================================================
Formats text for the editor.
Generally the browsers treat everything inside a textarea as text, but it is still a good idea to HTML entity encode `<`, `>` and `&` in the content.
The filter [‘format\_for\_editor’](../hooks/format_for_editor) is applied here. If `$text` is empty the filter will be applied to an empty string.
* [\_WP\_Editors::editor()](../classes/_wp_editors/editor)
`$text` string Required The text to be formatted. `$default_editor` string Optional The default editor for the current user.
It is usually either `'html'` or `'tinymce'`. Default: `null`
string The formatted text after filter is applied.
File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function format_for_editor( $text, $default_editor = null ) {
if ( $text ) {
$text = htmlspecialchars( $text, ENT_NOQUOTES, get_option( 'blog_charset' ) );
}
/**
* Filters the text after it is formatted for the editor.
*
* @since 4.3.0
*
* @param string $text The formatted text.
* @param string $default_editor The default editor for the current user.
* It is usually either 'html' or 'tinymce'.
*/
return apply_filters( 'format_for_editor', $text, $default_editor );
}
```
[apply\_filters( 'format\_for\_editor', string $text, string $default\_editor )](../hooks/format_for_editor)
Filters the text after it is formatted for the editor.
| Uses | Description |
| --- | --- |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
| programming_docs |
wordpress _config_wp_siteurl( string $url = '' ): string \_config\_wp\_siteurl( string $url = '' ): string
=================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness. Use [WP\_SITEURL](../classes/wp_siteurl) instead.
Retrieves the WordPress site URL.
If the constant named ‘WP\_SITEURL’ is defined, then the value in that constant will always be returned. This can be used for debugging a site on your localhost while not having to change the database to your URL.
* [WP\_SITEURL](../classes/wp_siteurl)
`$url` string Optional URL to set the WordPress site location. Default: `''`
string The WordPress site URL.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function _config_wp_siteurl( $url = '' ) {
if ( defined( 'WP_SITEURL' ) ) {
return untrailingslashit( WP_SITEURL );
}
return $url;
}
```
| Uses | Description |
| --- | --- |
| [untrailingslashit()](untrailingslashit) wp-includes/formatting.php | Removes trailing forward slashes and backslashes if they exist. |
| Version | Description |
| --- | --- |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Introduced. |
wordpress get_dynamic_block_names(): string[] get\_dynamic\_block\_names(): string[]
======================================
Returns an array of the names of all registered dynamic block types.
string[] Array of dynamic block names.
File: `wp-includes/blocks.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/blocks.php/)
```
function get_dynamic_block_names() {
$dynamic_block_names = array();
$block_types = WP_Block_Type_Registry::get_instance()->get_all_registered();
foreach ( $block_types as $block_type ) {
if ( $block_type->is_dynamic() ) {
$dynamic_block_names[] = $block_type->name;
}
}
return $dynamic_block_names;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Block\_Type\_Registry::get\_instance()](../classes/wp_block_type_registry/get_instance) wp-includes/class-wp-block-type-registry.php | Utility method to retrieve the main instance of the class. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress get_page_template(): string get\_page\_template(): string
=============================
Retrieves path of page template in current or parent template.
Note: For block themes, use locate\_block\_template function instead.
The hierarchy for this template looks like:
1. {Page Template}.php
2. page-{page\_name}.php
3. page-{id}.php
4. page.php
An example of this is:
1. page-templates/full-width.php
2. page-about.php
3. page-4.php
4. page.php
The template hierarchy and template path are filterable via the [‘$type\_template\_hierarchy’](../hooks/type_template_hierarchy) and [‘$type\_template’](../hooks/type_template) dynamic hooks, where `$type` is ‘page’.
* [get\_query\_template()](get_query_template)
string Full path to page template file.
File: `wp-includes/template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/template.php/)
```
function get_page_template() {
$id = get_queried_object_id();
$template = get_page_template_slug();
$pagename = get_query_var( 'pagename' );
if ( ! $pagename && $id ) {
// If a static page is set as the front page, $pagename will not be set.
// Retrieve it from the queried object.
$post = get_queried_object();
if ( $post ) {
$pagename = $post->post_name;
}
}
$templates = array();
if ( $template && 0 === validate_file( $template ) ) {
$templates[] = $template;
}
if ( $pagename ) {
$pagename_decoded = urldecode( $pagename );
if ( $pagename_decoded !== $pagename ) {
$templates[] = "page-{$pagename_decoded}.php";
}
$templates[] = "page-{$pagename}.php";
}
if ( $id ) {
$templates[] = "page-{$id}.php";
}
$templates[] = 'page.php';
return get_query_template( 'page', $templates );
}
```
| Uses | Description |
| --- | --- |
| [get\_queried\_object\_id()](get_queried_object_id) wp-includes/query.php | Retrieves the ID of the currently queried object. |
| [get\_query\_var()](get_query_var) wp-includes/query.php | Retrieves the value of a query variable in the [WP\_Query](../classes/wp_query) class. |
| [get\_queried\_object()](get_queried_object) wp-includes/query.php | Retrieves the currently queried object. |
| [validate\_file()](validate_file) wp-includes/functions.php | Validates a file name and path against an allowed set of rules. |
| [get\_query\_template()](get_query_template) wp-includes/template.php | Retrieves path to a template. |
| [get\_page\_template\_slug()](get_page_template_slug) wp-includes/post-template.php | Gets the specific template filename for a given post. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | The decoded form of `page-{page_name}.php` was added to the top of the template hierarchy when the page name contains multibyte characters. |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress unregister_widget( string|WP_Widget $widget ) unregister\_widget( string|WP\_Widget $widget )
===============================================
Unregisters a widget.
Unregisters a [WP\_Widget](../classes/wp_widget) widget. Useful for un-registering default widgets.
Run within a function hooked to the [‘widgets\_init’](../hooks/widgets_init) action.
* [WP\_Widget](../classes/wp_widget)
`$widget` string|[WP\_Widget](../classes/wp_widget) Required Either the name of a `WP_Widget` subclass or an instance of a `WP_Widget` subclass. List of [WP\_Widget](../classes/wp_widget) subclass names:
`WP_Widget_Pages = Pages Widget
WP_Widget_Calendar = Calendar Widget
WP_Widget_Archives = Archives Widget
WP_Widget_Links = Links Widget
WP_Widget_Media_Audio = Audio Player Media Widget
WP_Widget_Media_Image = Image Media Widget
WP_Widget_Media_Video = Video Media Widget
WP_Widget_Media_Gallery = Gallery Media Widget
WP_Widget_Meta = Meta Widget
WP_Widget_Search = Search Widget
WP_Widget_Text = Text Widget
WP_Widget_Categories = Categories Widget
WP_Widget_Recent_Posts = Recent Posts Widget
WP_Widget_Recent_Comments = Recent Comments Widget
WP_Widget_RSS = RSS Widget
WP_Widget_Tag_Cloud = Tag Cloud Widget
WP_Nav_Menu_Widget = Menus Widget
WP_Widget_Custom_HTML = Custom HTML Widget`
File: `wp-includes/widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets.php/)
```
function unregister_widget( $widget ) {
global $wp_widget_factory;
$wp_widget_factory->unregister( $widget );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Factory::unregister()](../classes/wp_widget_factory/unregister) wp-includes/class-wp-widget-factory.php | Un-registers a widget subclass. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Updated the `$widget` parameter to also accept a [WP\_Widget](../classes/wp_widget) instance object instead of simply a `WP_Widget` subclass name. |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress get_oembed_response_data_rich( array $data, WP_Post $post, int $width, int $height ): array get\_oembed\_response\_data\_rich( array $data, WP\_Post $post, int $width, int $height ): array
================================================================================================
Filters the oEmbed response data to return an iframe embed code.
`$data` array Required The response data. `$post` [WP\_Post](../classes/wp_post) Required The post object. `$width` int Required The requested width. `$height` int Required The calculated height. array The modified response data.
File: `wp-includes/embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/embed.php/)
```
function get_oembed_response_data_rich( $data, $post, $width, $height ) {
$data['width'] = absint( $width );
$data['height'] = absint( $height );
$data['type'] = 'rich';
$data['html'] = get_post_embed_html( $width, $height, $post );
// Add post thumbnail to response if available.
$thumbnail_id = false;
if ( has_post_thumbnail( $post->ID ) ) {
$thumbnail_id = get_post_thumbnail_id( $post->ID );
}
if ( 'attachment' === get_post_type( $post ) ) {
if ( wp_attachment_is_image( $post ) ) {
$thumbnail_id = $post->ID;
} elseif ( wp_attachment_is( 'video', $post ) ) {
$thumbnail_id = get_post_thumbnail_id( $post );
$data['type'] = 'video';
}
}
if ( $thumbnail_id ) {
list( $thumbnail_url, $thumbnail_width, $thumbnail_height ) = wp_get_attachment_image_src( $thumbnail_id, array( $width, 99999 ) );
$data['thumbnail_url'] = $thumbnail_url;
$data['thumbnail_width'] = $thumbnail_width;
$data['thumbnail_height'] = $thumbnail_height;
}
return $data;
}
```
| Uses | Description |
| --- | --- |
| [get\_post\_embed\_html()](get_post_embed_html) wp-includes/embed.php | Retrieves the embed code for a specific post. |
| [wp\_attachment\_is()](wp_attachment_is) wp-includes/post.php | Verifies an attachment is of a given type. |
| [has\_post\_thumbnail()](has_post_thumbnail) wp-includes/post-thumbnail-template.php | Determines whether a post has an image attached. |
| [get\_post\_thumbnail\_id()](get_post_thumbnail_id) wp-includes/post-thumbnail-template.php | Retrieves the post thumbnail ID. |
| [wp\_get\_attachment\_image\_src()](wp_get_attachment_image_src) wp-includes/media.php | Retrieves an image to represent an attachment. |
| [wp\_attachment\_is\_image()](wp_attachment_is_image) wp-includes/post.php | Determines whether an attachment is an image. |
| [get\_post\_type()](get_post_type) wp-includes/post.php | Retrieves the post type of the current post or of a given post. |
| [absint()](absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress update_recently_edited( string $file ) update\_recently\_edited( string $file )
========================================
Updates the “recently-edited” file for the plugin or theme file editor.
`$file` string Required File: `wp-admin/includes/misc.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/misc.php/)
```
function update_recently_edited( $file ) {
$oldfiles = (array) get_option( 'recently_edited' );
if ( $oldfiles ) {
$oldfiles = array_reverse( $oldfiles );
$oldfiles[] = $file;
$oldfiles = array_reverse( $oldfiles );
$oldfiles = array_unique( $oldfiles );
if ( 5 < count( $oldfiles ) ) {
array_pop( $oldfiles );
}
} else {
$oldfiles[] = $file;
}
update_option( 'recently_edited', $oldfiles );
}
```
| Uses | Description |
| --- | --- |
| [update\_option()](update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress esc_xml( string $text ): string esc\_xml( string $text ): string
================================
Escaping for XML blocks.
`$text` string Required Text to escape. string Escaped text.
File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function esc_xml( $text ) {
$safe_text = wp_check_invalid_utf8( $text );
$cdata_regex = '\<\!\[CDATA\[.*?\]\]\>';
$regex = <<<EOF
/
(?=.*?{$cdata_regex}) # lookahead that will match anything followed by a CDATA Section
(?<non_cdata_followed_by_cdata>(.*?)) # the "anything" matched by the lookahead
(?<cdata>({$cdata_regex})) # the CDATA Section matched by the lookahead
| # alternative
(?<non_cdata>(.*)) # non-CDATA Section
/sx
EOF;
$safe_text = (string) preg_replace_callback(
$regex,
static function( $matches ) {
if ( ! isset( $matches[0] ) ) {
return '';
}
if ( isset( $matches['non_cdata'] ) ) {
// escape HTML entities in the non-CDATA Section.
return _wp_specialchars( $matches['non_cdata'], ENT_XML1 );
}
// Return the CDATA Section unchanged, escape HTML entities in the rest.
return _wp_specialchars( $matches['non_cdata_followed_by_cdata'], ENT_XML1 ) . $matches['cdata'];
},
$safe_text
);
/**
* Filters a string cleaned and escaped for output in XML.
*
* Text passed to esc_xml() is stripped of invalid or special characters
* before output. HTML named character references are converted to their
* equivalent code points.
*
* @since 5.5.0
*
* @param string $safe_text The text after it has been escaped.
* @param string $text The text prior to being escaped.
*/
return apply_filters( 'esc_xml', $safe_text, $text );
}
```
[apply\_filters( 'esc\_xml', string $safe\_text, string $text )](../hooks/esc_xml)
Filters a string cleaned and escaped for output in XML.
| Uses | Description |
| --- | --- |
| [wp\_check\_invalid\_utf8()](wp_check_invalid_utf8) wp-includes/formatting.php | Checks for invalid UTF8 in a string. |
| [\_wp\_specialchars()](_wp_specialchars) wp-includes/formatting.php | Converts a number of special characters into their HTML entities. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Sitemaps\_Renderer::get\_sitemap\_index\_xml()](../classes/wp_sitemaps_renderer/get_sitemap_index_xml) wp-includes/sitemaps/class-wp-sitemaps-renderer.php | Gets XML for a sitemap index. |
| [WP\_Sitemaps\_Renderer::get\_sitemap\_xml()](../classes/wp_sitemaps_renderer/get_sitemap_xml) wp-includes/sitemaps/class-wp-sitemaps-renderer.php | Gets XML for a sitemap. |
| [WP\_Sitemaps\_Renderer::check\_for\_simple\_xml\_availability()](../classes/wp_sitemaps_renderer/check_for_simple_xml_availability) wp-includes/sitemaps/class-wp-sitemaps-renderer.php | Checks for the availability of the SimpleXML extension and errors if missing. |
| [WP\_Sitemaps\_Stylesheet::get\_sitemap\_stylesheet()](../classes/wp_sitemaps_stylesheet/get_sitemap_stylesheet) wp-includes/sitemaps/class-wp-sitemaps-stylesheet.php | Returns the escaped XSL for all sitemaps, except index. |
| [WP\_Sitemaps\_Stylesheet::get\_sitemap\_index\_stylesheet()](../classes/wp_sitemaps_stylesheet/get_sitemap_index_stylesheet) wp-includes/sitemaps/class-wp-sitemaps-stylesheet.php | Returns the escaped XSL for the index sitemaps. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress wp_ajax_inline_save_tax() wp\_ajax\_inline\_save\_tax()
=============================
Ajax handler for quick edit saving for a term.
File: `wp-admin/includes/ajax-actions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/ajax-actions.php/)
```
function wp_ajax_inline_save_tax() {
check_ajax_referer( 'taxinlineeditnonce', '_inline_edit' );
$taxonomy = sanitize_key( $_POST['taxonomy'] );
$taxonomy_object = get_taxonomy( $taxonomy );
if ( ! $taxonomy_object ) {
wp_die( 0 );
}
if ( ! isset( $_POST['tax_ID'] ) || ! (int) $_POST['tax_ID'] ) {
wp_die( -1 );
}
$id = (int) $_POST['tax_ID'];
if ( ! current_user_can( 'edit_term', $id ) ) {
wp_die( -1 );
}
$wp_list_table = _get_list_table( 'WP_Terms_List_Table', array( 'screen' => 'edit-' . $taxonomy ) );
$tag = get_term( $id, $taxonomy );
$_POST['description'] = $tag->description;
$updated = wp_update_term( $id, $taxonomy, $_POST );
if ( $updated && ! is_wp_error( $updated ) ) {
$tag = get_term( $updated['term_id'], $taxonomy );
if ( ! $tag || is_wp_error( $tag ) ) {
if ( is_wp_error( $tag ) && $tag->get_error_message() ) {
wp_die( $tag->get_error_message() );
}
wp_die( __( 'Item not updated.' ) );
}
} else {
if ( is_wp_error( $updated ) && $updated->get_error_message() ) {
wp_die( $updated->get_error_message() );
}
wp_die( __( 'Item not updated.' ) );
}
$level = 0;
$parent = $tag->parent;
while ( $parent > 0 ) {
$parent_tag = get_term( $parent, $taxonomy );
$parent = $parent_tag->parent;
$level++;
}
$wp_list_table->single_row( $tag, $level );
wp_die();
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::single\_row()](../classes/wp_list_table/single_row) wp-admin/includes/class-wp-list-table.php | Generates content for a single row of the table. |
| [\_get\_list\_table()](_get_list_table) wp-admin/includes/list-table.php | Fetches an instance of a [WP\_List\_Table](../classes/wp_list_table) class. |
| [wp\_update\_term()](wp_update_term) wp-includes/taxonomy.php | Updates term based on arguments provided. |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [sanitize\_key()](sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [check\_ajax\_referer()](check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [wp\_die()](wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [get\_taxonomy()](get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| [get\_term()](get_term) wp-includes/taxonomy.php | Gets all term data from database by term ID. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress current_datetime(): DateTimeImmutable current\_datetime(): DateTimeImmutable
======================================
Retrieves the current time as an object using the site’s timezone.
DateTimeImmutable Date and time object.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function current_datetime() {
return new DateTimeImmutable( 'now', wp_timezone() );
}
```
| Uses | Description |
| --- | --- |
| [wp\_timezone()](wp_timezone) wp-includes/functions.php | Retrieves the timezone of the site as a `DateTimeZone` object. |
| Used By | Description |
| --- | --- |
| [wp\_dashboard\_recent\_posts()](wp_dashboard_recent_posts) wp-admin/includes/dashboard.php | Generates Publishing Soon and Recently Published sections. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress wp_list_sort( array $list, string|array $orderby = array(), string $order = 'ASC', bool $preserve_keys = false ): array wp\_list\_sort( array $list, string|array $orderby = array(), string $order = 'ASC', bool $preserve\_keys = false ): array
==========================================================================================================================
Sorts an array of objects or arrays based on one or more orderby arguments.
`$list` array Required An array of objects or arrays to sort. `$orderby` string|array Optional Either the field name to order by or an array of multiple orderby fields as $orderby => $order. Default: `array()`
`$order` string Optional Either `'ASC'` or `'DESC'`. Only used if $orderby is a string. Default: `'ASC'`
`$preserve_keys` bool Optional Whether to preserve keys. Default: `false`
array The sorted array.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function wp_list_sort( $list, $orderby = array(), $order = 'ASC', $preserve_keys = false ) {
if ( ! is_array( $list ) ) {
return array();
}
$util = new WP_List_Util( $list );
return $util->sort( $orderby, $order, $preserve_keys );
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Util::\_\_construct()](../classes/wp_list_util/__construct) wp-includes/class-wp-list-util.php | Constructor. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Setting::filter\_wp\_get\_nav\_menus()](../classes/wp_customize_nav_menu_setting/filter_wp_get_nav_menus) wp-includes/customize/class-wp-customize-nav-menu-setting.php | Filters the [wp\_get\_nav\_menus()](wp_get_nav_menus) result to ensure the inserted menu object is included, and the deleted one is removed. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::sort\_wp\_get\_nav\_menu\_items()](../classes/wp_customize_nav_menu_item_setting/sort_wp_get_nav_menu_items) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Re-apply the tail logic also applied on $items by [wp\_get\_nav\_menu\_items()](wp_get_nav_menu_items) . |
| [WP\_Customize\_Manager::prepare\_controls()](../classes/wp_customize_manager/prepare_controls) wp-includes/class-wp-customize-manager.php | Prepares panels, sections, and controls. |
| [get\_permalink()](get_permalink) wp-includes/link-template.php | Retrieves the full permalink for the current post or post ID. |
| [wp\_get\_nav\_menu\_items()](wp_get_nav_menu_items) wp-includes/nav-menu.php | Retrieves all menu items of a navigation menu. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress wp_img_tag_add_loading_attr( string $image, string $context ): string wp\_img\_tag\_add\_loading\_attr( string $image, string $context ): string
==========================================================================
Adds `loading` attribute to an `img` HTML tag.
`$image` string Required The HTML `img` tag where the attribute should be added. `$context` string Required Additional context to pass to the filters. string Converted `img` tag with `loading` attribute added.
File: `wp-includes/media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/media.php/)
```
function wp_img_tag_add_loading_attr( $image, $context ) {
// Get loading attribute value to use. This must occur before the conditional check below so that even images that
// are ineligible for being lazy-loaded are considered.
$value = wp_get_loading_attr_default( $context );
// Images should have source and dimension attributes for the `loading` attribute to be added.
if ( false === strpos( $image, ' src="' ) || false === strpos( $image, ' width="' ) || false === strpos( $image, ' height="' ) ) {
return $image;
}
/**
* Filters the `loading` attribute value to add to an image. Default `lazy`.
*
* Returning `false` or an empty string will not add the attribute.
* Returning `true` will add the default value.
*
* @since 5.5.0
*
* @param string|bool $value The `loading` attribute value. Returning a falsey value will result in
* the attribute being omitted for the image.
* @param string $image The HTML `img` tag to be filtered.
* @param string $context Additional context about how the function was called or where the img tag is.
*/
$value = apply_filters( 'wp_img_tag_add_loading_attr', $value, $image, $context );
if ( $value ) {
if ( ! in_array( $value, array( 'lazy', 'eager' ), true ) ) {
$value = 'lazy';
}
return str_replace( '<img', '<img loading="' . esc_attr( $value ) . '"', $image );
}
return $image;
}
```
[apply\_filters( 'wp\_img\_tag\_add\_loading\_attr', string|bool $value, string $image, string $context )](../hooks/wp_img_tag_add_loading_attr)
Filters the `loading` attribute value to add to an image. Default `lazy`.
| Uses | Description |
| --- | --- |
| [wp\_get\_loading\_attr\_default()](wp_get_loading_attr_default) wp-includes/media.php | Gets the default value to use for a `loading` attribute on an element. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_filter\_content\_tags()](wp_filter_content_tags) wp-includes/media.php | Filters specific tags in post content and modifies their markup. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress wp_get_attachment_image_srcset( int $attachment_id, string|int[] $size = 'medium', array $image_meta = null ): string|false wp\_get\_attachment\_image\_srcset( int $attachment\_id, string|int[] $size = 'medium', array $image\_meta = null ): string|false
=================================================================================================================================
Retrieves the value for an image attachment’s ‘srcset’ attribute.
* [wp\_calculate\_image\_srcset()](wp_calculate_image_srcset)
`$attachment_id` int Required Image attachment ID. `$size` string|int[] Optional Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order). Default `'medium'`. Default: `'medium'`
`$image_meta` array Optional The image meta data as returned by '[wp\_get\_attachment\_metadata()](wp_get_attachment_metadata) '.
Default: `null`
string|false A `'srcset'` value string or false.
File: `wp-includes/media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/media.php/)
```
function wp_get_attachment_image_srcset( $attachment_id, $size = 'medium', $image_meta = null ) {
$image = wp_get_attachment_image_src( $attachment_id, $size );
if ( ! $image ) {
return false;
}
if ( ! is_array( $image_meta ) ) {
$image_meta = wp_get_attachment_metadata( $attachment_id );
}
$image_src = $image[0];
$size_array = array(
absint( $image[1] ),
absint( $image[2] ),
);
return wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
}
```
| Uses | Description |
| --- | --- |
| [wp\_calculate\_image\_srcset()](wp_calculate_image_srcset) wp-includes/media.php | A helper function to calculate the image sources to include in a ‘srcset’ attribute. |
| [wp\_get\_attachment\_image\_src()](wp_get_attachment_image_src) wp-includes/media.php | Retrieves an image to represent an attachment. |
| [wp\_get\_attachment\_metadata()](wp_get_attachment_metadata) wp-includes/post.php | Retrieves attachment metadata for attachment ID. |
| [absint()](absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress wp_trash_comment( int|WP_Comment $comment_id ): bool wp\_trash\_comment( int|WP\_Comment $comment\_id ): bool
========================================================
Moves a comment to the Trash
If Trash is disabled, comment is permanently deleted.
`$comment_id` int|[WP\_Comment](../classes/wp_comment) Required Comment ID or [WP\_Comment](../classes/wp_comment) object. bool True on success, false on failure.
File: `wp-includes/comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/comment.php/)
```
function wp_trash_comment( $comment_id ) {
if ( ! EMPTY_TRASH_DAYS ) {
return wp_delete_comment( $comment_id, true );
}
$comment = get_comment( $comment_id );
if ( ! $comment ) {
return false;
}
/**
* Fires immediately before a comment is sent to the Trash.
*
* @since 2.9.0
* @since 4.9.0 Added the `$comment` parameter.
*
* @param string $comment_id The comment ID as a numeric string.
* @param WP_Comment $comment The comment to be trashed.
*/
do_action( 'trash_comment', $comment->comment_ID, $comment );
if ( wp_set_comment_status( $comment, 'trash' ) ) {
delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
add_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', $comment->comment_approved );
add_comment_meta( $comment->comment_ID, '_wp_trash_meta_time', time() );
/**
* Fires immediately after a comment is sent to Trash.
*
* @since 2.9.0
* @since 4.9.0 Added the `$comment` parameter.
*
* @param string $comment_id The comment ID as a numeric string.
* @param WP_Comment $comment The trashed comment.
*/
do_action( 'trashed_comment', $comment->comment_ID, $comment );
return true;
}
return false;
}
```
[do\_action( 'trashed\_comment', string $comment\_id, WP\_Comment $comment )](../hooks/trashed_comment)
Fires immediately after a comment is sent to Trash.
[do\_action( 'trash\_comment', string $comment\_id, WP\_Comment $comment )](../hooks/trash_comment)
Fires immediately before a comment is sent to the Trash.
| Uses | Description |
| --- | --- |
| [wp\_set\_comment\_status()](wp_set_comment_status) wp-includes/comment.php | Sets the status of a comment. |
| [wp\_delete\_comment()](wp_delete_comment) wp-includes/comment.php | Trashes or deletes a comment. |
| [delete\_comment\_meta()](delete_comment_meta) wp-includes/comment.php | Removes metadata matching criteria from a comment. |
| [add\_comment\_meta()](add_comment_meta) wp-includes/comment.php | Adds meta data field to a comment. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_comment()](get_comment) wp-includes/comment.php | Retrieves comment data given a comment ID or comment object. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Comments\_Controller::handle\_status\_param()](../classes/wp_rest_comments_controller/handle_status_param) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Sets the comment\_status of a given comment object when creating or updating a comment. |
| [WP\_REST\_Comments\_Controller::delete\_item()](../classes/wp_rest_comments_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Deletes a comment. |
| [wp\_ajax\_delete\_comment()](wp_ajax_delete_comment) wp-admin/includes/ajax-actions.php | Ajax handler for deleting a comment. |
| [wp\_delete\_comment()](wp_delete_comment) wp-includes/comment.php | Trashes or deletes a comment. |
| Version | Description |
| --- | --- |
| [2.9.0](https://developer.wordpress.org/reference/since/2.9.0/) | Introduced. |
wordpress rest_handle_multi_type_schema( mixed $value, array $args, string $param = '' ): string rest\_handle\_multi\_type\_schema( mixed $value, array $args, string $param = '' ): string
==========================================================================================
Handles getting the best type for a multi-type schema.
This is a wrapper for [rest\_get\_best\_type\_for\_value()](rest_get_best_type_for_value) that handles backward compatibility for schemas that use invalid types.
`$value` mixed Required The value to check. `$args` array Required The schema array to use. `$param` string Optional The parameter name, used in error messages. Default: `''`
string
File: `wp-includes/rest-api.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api.php/)
```
function rest_handle_multi_type_schema( $value, $args, $param = '' ) {
$allowed_types = array( 'array', 'object', 'string', 'number', 'integer', 'boolean', 'null' );
$invalid_types = array_diff( $args['type'], $allowed_types );
if ( $invalid_types ) {
_doing_it_wrong(
__FUNCTION__,
/* translators: 1: Parameter, 2: List of allowed types. */
wp_sprintf( __( 'The "type" schema keyword for %1$s can only contain the built-in types: %2$l.' ), $param, $allowed_types ),
'5.5.0'
);
}
$best_type = rest_get_best_type_for_value( $value, $args['type'] );
if ( ! $best_type ) {
if ( ! $invalid_types ) {
return '';
}
// Backward compatibility for previous behavior which allowed the value if there was an invalid type used.
$best_type = reset( $invalid_types );
}
return $best_type;
}
```
| Uses | Description |
| --- | --- |
| [rest\_get\_best\_type\_for\_value()](rest_get_best_type_for_value) wp-includes/rest-api.php | Gets the best type for a value. |
| [wp\_sprintf()](wp_sprintf) wp-includes/formatting.php | WordPress implementation of PHP sprintf() with filters. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_doing\_it\_wrong()](_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Used By | Description |
| --- | --- |
| [rest\_sanitize\_value\_from\_schema()](rest_sanitize_value_from_schema) wp-includes/rest-api.php | Sanitize a value based on a schema. |
| [rest\_validate\_value\_from\_schema()](rest_validate_value_from_schema) wp-includes/rest-api.php | Validate a value based on a schema. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress wp_get_shortlink( int $id, string $context = 'post', bool $allow_slugs = true ): string wp\_get\_shortlink( int $id, string $context = 'post', bool $allow\_slugs = true ): string
==========================================================================================
Returns a shortlink for a post, page, attachment, or site.
This function exists to provide a shortlink tag that all themes and plugins can target.
A plugin must hook in to provide the actual shortlinks. Default shortlink support is limited to providing ?p= style links for posts. Plugins can short-circuit this function via the [‘pre\_get\_shortlink’](../hooks/pre_get_shortlink) filter or filter the output via the [‘get\_shortlink’](../hooks/get_shortlink) filter.
`$id` int Optional A post or site ID. Default is 0, which means the current post or site. `$context` string Optional Whether the ID is a `'site'` ID, `'post'` ID, or `'media'` ID. If `'post'`, the post\_type of the post is consulted. If `'query'`, the current query is consulted to determine the ID and context. Default `'post'`. Default: `'post'`
`$allow_slugs` bool Optional Whether to allow post slugs in the shortlink. It is up to the plugin how and whether to honor this. Default: `true`
string A shortlink or an empty string if no shortlink exists for the requested resource or if shortlinks are not enabled.
File: `wp-includes/link-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/link-template.php/)
```
function wp_get_shortlink( $id = 0, $context = 'post', $allow_slugs = true ) {
/**
* Filters whether to preempt generating a shortlink for the given post.
*
* Returning a value other than false from the filter will short-circuit
* the shortlink generation process, returning that value instead.
*
* @since 3.0.0
*
* @param false|string $return Short-circuit return value. Either false or a URL string.
* @param int $id Post ID, or 0 for the current post.
* @param string $context The context for the link. One of 'post' or 'query',
* @param bool $allow_slugs Whether to allow post slugs in the shortlink.
*/
$shortlink = apply_filters( 'pre_get_shortlink', false, $id, $context, $allow_slugs );
if ( false !== $shortlink ) {
return $shortlink;
}
$post_id = 0;
if ( 'query' === $context && is_singular() ) {
$post_id = get_queried_object_id();
$post = get_post( $post_id );
} elseif ( 'post' === $context ) {
$post = get_post( $id );
if ( ! empty( $post->ID ) ) {
$post_id = $post->ID;
}
}
$shortlink = '';
// Return `?p=` link for all public post types.
if ( ! empty( $post_id ) ) {
$post_type = get_post_type_object( $post->post_type );
if ( 'page' === $post->post_type && get_option( 'page_on_front' ) == $post->ID && 'page' === get_option( 'show_on_front' ) ) {
$shortlink = home_url( '/' );
} elseif ( $post_type && $post_type->public ) {
$shortlink = home_url( '?p=' . $post_id );
}
}
/**
* Filters the shortlink for a post.
*
* @since 3.0.0
*
* @param string $shortlink Shortlink URL.
* @param int $id Post ID, or 0 for the current post.
* @param string $context The context for the link. One of 'post' or 'query',
* @param bool $allow_slugs Whether to allow post slugs in the shortlink. Not used by default.
*/
return apply_filters( 'get_shortlink', $shortlink, $id, $context, $allow_slugs );
}
```
[apply\_filters( 'get\_shortlink', string $shortlink, int $id, string $context, bool $allow\_slugs )](../hooks/get_shortlink)
Filters the shortlink for a post.
[apply\_filters( 'pre\_get\_shortlink', false|string $return, int $id, string $context, bool $allow\_slugs )](../hooks/pre_get_shortlink)
Filters whether to preempt generating a shortlink for the given post.
| Uses | Description |
| --- | --- |
| [is\_singular()](is_singular) wp-includes/query.php | Determines whether the query is for an existing single post of any post type (post, attachment, page, custom post types). |
| [get\_queried\_object\_id()](get_queried_object_id) wp-includes/query.php | Retrieves the ID of the currently queried object. |
| [home\_url()](home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [get\_post\_type\_object()](get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Used By | Description |
| --- | --- |
| [wp\_shortlink\_wp\_head()](wp_shortlink_wp_head) wp-includes/link-template.php | Injects rel=shortlink into the head if a shortlink is defined for the current page. |
| [wp\_shortlink\_header()](wp_shortlink_header) wp-includes/link-template.php | Sends a Link: rel=shortlink header if a shortlink is defined for the current page. |
| [the\_shortlink()](the_shortlink) wp-includes/link-template.php | Displays the shortlink for a post. |
| [wp\_admin\_bar\_shortlink\_menu()](wp_admin_bar_shortlink_menu) wp-includes/admin-bar.php | Provides a shortlink. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress unregister_post_meta( string $post_type, string $meta_key ): bool unregister\_post\_meta( string $post\_type, string $meta\_key ): bool
=====================================================================
Unregisters a meta key for posts.
`$post_type` string Required Post type the meta key is currently registered for. Pass an empty string if the meta key is registered across all existing post types. `$meta_key` string Required The meta key to unregister. bool True on success, false if the meta key was not previously registered.
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function unregister_post_meta( $post_type, $meta_key ) {
return unregister_meta_key( 'post', $meta_key, $post_type );
}
```
| Uses | Description |
| --- | --- |
| [unregister\_meta\_key()](unregister_meta_key) wp-includes/meta.php | Unregisters a meta key from the list of registered keys. |
| Version | Description |
| --- | --- |
| [4.9.8](https://developer.wordpress.org/reference/since/4.9.8/) | Introduced. |
wordpress the_search_query() the\_search\_query()
====================
Displays the contents of the search query variable.
The search query string is passed through [esc\_attr()](esc_attr) to ensure that it is safe for placing in an HTML attribute.
File: `wp-includes/general-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/general-template.php/)
```
function the_search_query() {
/**
* Filters the contents of the search query variable for display.
*
* @since 2.3.0
*
* @param mixed $search Contents of the search query variable.
*/
echo esc_attr( apply_filters( 'the_search_query', get_search_query( false ) ) );
}
```
[apply\_filters( 'the\_search\_query', mixed $search )](../hooks/the_search_query)
Filters the contents of the search query variable for display.
| Uses | Description |
| --- | --- |
| [get\_search\_query()](get_search_query) wp-includes/general-template.php | Retrieves the contents of the search WordPress query variable. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [media\_upload\_library\_form()](media_upload_library_form) wp-admin/includes/media.php | Outputs the legacy media upload form for the media library. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
| programming_docs |
wordpress get_the_content( string $more_link_text = null, bool $strip_teaser = false, WP_Post|object|int $post = null ): string get\_the\_content( string $more\_link\_text = null, bool $strip\_teaser = false, WP\_Post|object|int $post = null ): string
===========================================================================================================================
Retrieves the post content.
`$more_link_text` string Optional Content for when there is more text. Default: `null`
`$strip_teaser` bool Optional Strip teaser content before the more text. Default: `false`
`$post` [WP\_Post](../classes/wp_post)|object|int Optional [WP\_Post](../classes/wp_post) instance or Post ID/object. Default: `null`
string
When used inside [The Loop](https://developer.wordpress.org/themes/basics/the-loop/), this function will get the content of the current post.
If used outside [The Loop](https://developer.wordpress.org/themes/basics/the-loop/), you must inform the post you want to get the content from using the optional `$post` parameter.
An important difference from `[the\_content()](the_content)` is that `get_the_content()` does not pass the content through the `[the\_content](../hooks/the_content)` filter. This means that `get_the_content()` will not auto-embed videos or expand shortcodes, among other things.
File: `wp-includes/post-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post-template.php/)
```
function get_the_content( $more_link_text = null, $strip_teaser = false, $post = null ) {
global $page, $more, $preview, $pages, $multipage;
$_post = get_post( $post );
if ( ! ( $_post instanceof WP_Post ) ) {
return '';
}
// Use the globals if the $post parameter was not specified,
// but only after they have been set up in setup_postdata().
if ( null === $post && did_action( 'the_post' ) ) {
$elements = compact( 'page', 'more', 'preview', 'pages', 'multipage' );
} else {
$elements = generate_postdata( $_post );
}
if ( null === $more_link_text ) {
$more_link_text = sprintf(
'<span aria-label="%1$s">%2$s</span>',
sprintf(
/* translators: %s: Post title. */
__( 'Continue reading %s' ),
the_title_attribute(
array(
'echo' => false,
'post' => $_post,
)
)
),
__( '(more…)' )
);
}
$output = '';
$has_teaser = false;
// If post password required and it doesn't match the cookie.
if ( post_password_required( $_post ) ) {
return get_the_password_form( $_post );
}
// If the requested page doesn't exist.
if ( $elements['page'] > count( $elements['pages'] ) ) {
// Give them the highest numbered page that DOES exist.
$elements['page'] = count( $elements['pages'] );
}
$page_no = $elements['page'];
$content = $elements['pages'][ $page_no - 1 ];
if ( preg_match( '/<!--more(.*?)?-->/', $content, $matches ) ) {
if ( has_block( 'more', $content ) ) {
// Remove the core/more block delimiters. They will be left over after $content is split up.
$content = preg_replace( '/<!-- \/?wp:more(.*?) -->/', '', $content );
}
$content = explode( $matches[0], $content, 2 );
if ( ! empty( $matches[1] ) && ! empty( $more_link_text ) ) {
$more_link_text = strip_tags( wp_kses_no_null( trim( $matches[1] ) ) );
}
$has_teaser = true;
} else {
$content = array( $content );
}
if ( false !== strpos( $_post->post_content, '<!--noteaser-->' ) && ( ! $elements['multipage'] || 1 == $elements['page'] ) ) {
$strip_teaser = true;
}
$teaser = $content[0];
if ( $elements['more'] && $strip_teaser && $has_teaser ) {
$teaser = '';
}
$output .= $teaser;
if ( count( $content ) > 1 ) {
if ( $elements['more'] ) {
$output .= '<span id="more-' . $_post->ID . '"></span>' . $content[1];
} else {
if ( ! empty( $more_link_text ) ) {
/**
* Filters the Read More link text.
*
* @since 2.8.0
*
* @param string $more_link_element Read More link element.
* @param string $more_link_text Read More text.
*/
$output .= apply_filters( 'the_content_more_link', ' <a href="' . get_permalink( $_post ) . "#more-{$_post->ID}\" class=\"more-link\">$more_link_text</a>", $more_link_text );
}
$output = force_balance_tags( $output );
}
}
return $output;
}
```
[apply\_filters( 'the\_content\_more\_link', string $more\_link\_element, string $more\_link\_text )](../hooks/the_content_more_link)
Filters the Read More link text.
| Uses | Description |
| --- | --- |
| [generate\_postdata()](generate_postdata) wp-includes/query.php | Generates post data. |
| [has\_block()](has_block) wp-includes/blocks.php | Determines whether a $post or a string contains a specific block type. |
| [force\_balance\_tags()](force_balance_tags) wp-includes/formatting.php | Balances tags of string using a modified stack. |
| [wp\_kses\_no\_null()](wp_kses_no_null) wp-includes/kses.php | Removes any invalid control characters in a text string. |
| [did\_action()](did_action) wp-includes/plugin.php | Retrieves the number of times an action has been fired during the current request. |
| [get\_the\_password\_form()](get_the_password_form) wp-includes/post-template.php | Retrieves protected post password form content. |
| [post\_password\_required()](post_password_required) wp-includes/post-template.php | Determines whether the post requires password and whether a correct password has been provided. |
| [the\_title\_attribute()](the_title_attribute) wp-includes/post-template.php | Sanitizes the current title when retrieving or displaying. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_permalink()](get_permalink) wp-includes/link-template.php | Retrieves the full permalink for the current post or post ID. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [wp\_trim\_excerpt()](wp_trim_excerpt) wp-includes/formatting.php | Generates an excerpt from the content, if needed. |
| [the\_content\_rss()](the_content_rss) wp-includes/deprecated.php | Display the post content for the feed. |
| [get\_the\_content\_feed()](get_the_content_feed) wp-includes/feed.php | Retrieves the post content for feeds. |
| [the\_content()](the_content) wp-includes/post-template.php | Displays the post content. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Added the `$post` parameter. |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress get_the_date( string $format = '', int|WP_Post $post = null ): string|int|false get\_the\_date( string $format = '', int|WP\_Post $post = null ): string|int|false
==================================================================================
Retrieves the date on which the post was written.
Unlike [the\_date()](the_date) this function will always return the date.
Modify output with the [‘get\_the\_date’](../hooks/get_the_date) filter.
`$format` string Optional PHP date format. Defaults to the `'date_format'` option. Default: `''`
`$post` int|[WP\_Post](../classes/wp_post) Optional Post ID or [WP\_Post](../classes/wp_post) object. Default current post. Default: `null`
string|int|false Date the current post was written. False on failure.
File: `wp-includes/general-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/general-template.php/)
```
function get_the_date( $format = '', $post = null ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
$_format = ! empty( $format ) ? $format : get_option( 'date_format' );
$the_date = get_post_time( $_format, false, $post, true );
/**
* Filters the date a post was published.
*
* @since 3.0.0
*
* @param string|int $the_date Formatted date string or Unix timestamp if `$format` is 'U' or 'G'.
* @param string $format PHP date format.
* @param WP_Post $post The post object.
*/
return apply_filters( 'get_the_date', $the_date, $format, $post );
}
```
[apply\_filters( 'get\_the\_date', string|int $the\_date, string $format, WP\_Post $post )](../hooks/get_the_date)
Filters the date a post was published.
| Uses | Description |
| --- | --- |
| [get\_post\_time()](get_post_time) wp-includes/general-template.php | Retrieves the time at which the post was written. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [wp\_get\_document\_title()](wp_get_document_title) wp-includes/general-template.php | Returns document title for the current page. |
| [get\_the\_archive\_title()](get_the_archive_title) wp-includes/general-template.php | Retrieves the archive title based on the queried object. |
| [the\_date()](the_date) wp-includes/general-template.php | Displays or retrieves the date the current post was written (once per date) |
| [WP\_Widget\_Recent\_Posts::widget()](../classes/wp_widget_recent_posts/widget) wp-includes/widgets/class-wp-widget-recent-posts.php | Outputs the content for the current Recent Posts widget instance. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress validate_user_form(): array validate\_user\_form(): array
=============================
Validates user sign-up name and email.
array Contains username, email, and error messages.
See [wpmu\_validate\_user\_signup()](wpmu_validate_user_signup) for details.
File: `wp-signup.php`. [View all references](https://developer.wordpress.org/reference/files/wp-signup.php/)
```
function validate_user_form() {
return wpmu_validate_user_signup( $_POST['user_name'], $_POST['user_email'] );
}
```
| Uses | Description |
| --- | --- |
| [wpmu\_validate\_user\_signup()](wpmu_validate_user_signup) wp-includes/ms-functions.php | Sanitizes and validates data required for a user sign-up. |
| Used By | Description |
| --- | --- |
| [validate\_user\_signup()](validate_user_signup) wp-signup.php | Validates the new user sign-up. |
| Version | Description |
| --- | --- |
| [MU (3.0.0)](https://developer.wordpress.org/reference/since/mu.3.0.0/) | Introduced. |
wordpress _post_format_get_terms( array $terms, string|array $taxonomies, array $args ): array \_post\_format\_get\_terms( array $terms, string|array $taxonomies, array $args ): array
========================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Remove the post format prefix from the name property of the term objects created by [get\_terms()](get_terms) .
`$terms` array Required `$taxonomies` string|array Required `$args` array Required array
File: `wp-includes/post-formats.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post-formats.php/)
```
function _post_format_get_terms( $terms, $taxonomies, $args ) {
if ( in_array( 'post_format', (array) $taxonomies, true ) ) {
if ( isset( $args['fields'] ) && 'names' === $args['fields'] ) {
foreach ( $terms as $order => $name ) {
$terms[ $order ] = get_post_format_string( str_replace( 'post-format-', '', $name ) );
}
} else {
foreach ( (array) $terms as $order => $term ) {
if ( isset( $term->taxonomy ) && 'post_format' === $term->taxonomy ) {
$terms[ $order ]->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) );
}
}
}
}
return $terms;
}
```
| Uses | Description |
| --- | --- |
| [get\_post\_format\_string()](get_post_format_string) wp-includes/post-formats.php | Returns a pretty, translated version of a post format slug |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress wp_authenticate_email_password( WP_User|WP_Error|null $user, string $email, string $password ): WP_User|WP_Error wp\_authenticate\_email\_password( WP\_User|WP\_Error|null $user, string $email, string $password ): WP\_User|WP\_Error
=======================================================================================================================
Authenticates a user using the email and password.
`$user` [WP\_User](../classes/wp_user)|[WP\_Error](../classes/wp_error)|null Required [WP\_User](../classes/wp_user) or [WP\_Error](../classes/wp_error) object if a previous callback failed authentication. `$email` string Required Email address for authentication. `$password` string Required Password for authentication. [WP\_User](../classes/wp_user)|[WP\_Error](../classes/wp_error) [WP\_User](../classes/wp_user) on success, [WP\_Error](../classes/wp_error) on failure.
File: `wp-includes/user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/user.php/)
```
function wp_authenticate_email_password( $user, $email, $password ) {
if ( $user instanceof WP_User ) {
return $user;
}
if ( empty( $email ) || empty( $password ) ) {
if ( is_wp_error( $user ) ) {
return $user;
}
$error = new WP_Error();
if ( empty( $email ) ) {
// Uses 'empty_username' for back-compat with wp_signon().
$error->add( 'empty_username', __( '<strong>Error:</strong> The email field is empty.' ) );
}
if ( empty( $password ) ) {
$error->add( 'empty_password', __( '<strong>Error:</strong> The password field is empty.' ) );
}
return $error;
}
if ( ! is_email( $email ) ) {
return $user;
}
$user = get_user_by( 'email', $email );
if ( ! $user ) {
return new WP_Error(
'invalid_email',
__( 'Unknown email address. Check again or try your username.' )
);
}
/** This filter is documented in wp-includes/user.php */
$user = apply_filters( 'wp_authenticate_user', $user, $password );
if ( is_wp_error( $user ) ) {
return $user;
}
if ( ! wp_check_password( $password, $user->user_pass, $user->ID ) ) {
return new WP_Error(
'incorrect_password',
sprintf(
/* translators: %s: Email address. */
__( '<strong>Error:</strong> The password you entered for the email address %s is incorrect.' ),
'<strong>' . $email . '</strong>'
) .
' <a href="' . wp_lostpassword_url() . '">' .
__( 'Lost your password?' ) .
'</a>'
);
}
return $user;
}
```
[apply\_filters( 'wp\_authenticate\_user', WP\_User|WP\_Error $user, string $password )](../hooks/wp_authenticate_user)
Filters whether the given user can be authenticated with the provided password.
| Uses | Description |
| --- | --- |
| [is\_email()](is_email) wp-includes/formatting.php | Verifies that an email is valid. |
| [wp\_check\_password()](wp_check_password) wp-includes/pluggable.php | Checks the plaintext password against the encrypted Password. |
| [get\_user\_by()](get_user_by) wp-includes/pluggable.php | Retrieves user info by a given field. |
| [wp\_lostpassword\_url()](wp_lostpassword_url) wp-includes/general-template.php | Returns the URL that allows the user to reset the lost password. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../classes/wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress wp_ajax_date_format() wp\_ajax\_date\_format()
========================
Ajax handler for date formatting.
File: `wp-admin/includes/ajax-actions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/ajax-actions.php/)
```
function wp_ajax_date_format() {
wp_die( date_i18n( sanitize_option( 'date_format', wp_unslash( $_POST['date'] ) ) ) );
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_option()](sanitize_option) wp-includes/formatting.php | Sanitizes various option values based on the nature of the option. |
| [date\_i18n()](date_i18n) wp-includes/functions.php | Retrieves the date in localized format, based on a sum of Unix timestamp and timezone offset in seconds. |
| [wp\_unslash()](wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [wp\_die()](wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress get_post_meta_by_id( int $mid ): object|bool get\_post\_meta\_by\_id( int $mid ): object|bool
================================================
Returns post meta data by meta ID.
`$mid` int Required object|bool
File: `wp-admin/includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/post.php/)
```
function get_post_meta_by_id( $mid ) {
return get_metadata_by_mid( 'post', $mid );
}
```
| Uses | Description |
| --- | --- |
| [get\_metadata\_by\_mid()](get_metadata_by_mid) wp-includes/meta.php | Retrieves metadata by meta ID. |
| Used By | Description |
| --- | --- |
| [edit\_post()](edit_post) wp-admin/includes/post.php | Updates an existing post with values provided in `$_POST`. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress _deprecated_hook( string $hook, string $version, string $replacement = '', string $message = '' ) \_deprecated\_hook( string $hook, string $version, string $replacement = '', string $message = '' )
===================================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Marks a deprecated action or filter hook as deprecated and throws a notice.
Use the [‘deprecated\_hook\_run’](../hooks/deprecated_hook_run) action to get the backtrace describing where the deprecated hook was called.
Default behavior is to trigger a user error if `WP_DEBUG` is true.
This function is called by the [do\_action\_deprecated()](do_action_deprecated) and [apply\_filters\_deprecated()](apply_filters_deprecated) functions, and so generally does not need to be called directly.
`$hook` string Required The hook that was used. `$version` string Required The version of WordPress that deprecated the hook. `$replacement` string Optional The hook that should have been used. Default: `''`
`$message` string Optional A message regarding the change. Default: `''`
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function _deprecated_hook( $hook, $version, $replacement = '', $message = '' ) {
/**
* Fires when a deprecated hook is called.
*
* @since 4.6.0
*
* @param string $hook The hook that was called.
* @param string $replacement The hook that should be used as a replacement.
* @param string $version The version of WordPress that deprecated the argument used.
* @param string $message A message regarding the change.
*/
do_action( 'deprecated_hook_run', $hook, $replacement, $version, $message );
/**
* Filters whether to trigger deprecated hook errors.
*
* @since 4.6.0
*
* @param bool $trigger Whether to trigger deprecated hook errors. Requires
* `WP_DEBUG` to be defined true.
*/
if ( WP_DEBUG && apply_filters( 'deprecated_hook_trigger_error', true ) ) {
$message = empty( $message ) ? '' : ' ' . $message;
if ( $replacement ) {
trigger_error(
sprintf(
/* translators: 1: WordPress hook name, 2: Version number, 3: Alternative hook name. */
__( 'Hook %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
$hook,
$version,
$replacement
) . $message,
E_USER_DEPRECATED
);
} else {
trigger_error(
sprintf(
/* translators: 1: WordPress hook name, 2: Version number. */
__( 'Hook %1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ),
$hook,
$version
) . $message,
E_USER_DEPRECATED
);
}
}
}
```
[do\_action( 'deprecated\_hook\_run', string $hook, string $replacement, string $version, string $message )](../hooks/deprecated_hook_run)
Fires when a deprecated hook is called.
[apply\_filters( 'deprecated\_hook\_trigger\_error', bool $trigger )](../hooks/deprecated_hook_trigger_error)
Filters whether to trigger deprecated hook errors.
| Uses | Description |
| --- | --- |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [apply\_filters\_deprecated()](apply_filters_deprecated) wp-includes/plugin.php | Fires functions attached to a deprecated filter hook. |
| [do\_action\_deprecated()](do_action_deprecated) wp-includes/plugin.php | Fires functions attached to a deprecated action hook. |
| Version | Description |
| --- | --- |
| [5.4.0](https://developer.wordpress.org/reference/since/5.4.0/) | The error type is now classified as E\_USER\_DEPRECATED (used to default to E\_USER\_NOTICE). |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
| programming_docs |
wordpress wp_is_block_theme(): boolean wp\_is\_block\_theme(): boolean
===============================
Returns whether the active theme is a block-based theme or not.
boolean Whether the active theme is a block-based theme or not.
File: `wp-includes/theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/theme.php/)
```
function wp_is_block_theme() {
return wp_get_theme()->is_block_theme();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::is\_block\_theme()](../classes/wp_theme/is_block_theme) wp-includes/class-wp-theme.php | Returns whether this theme is a block-based theme or not. |
| [wp\_get\_theme()](wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../classes/wp_theme) object for a theme. |
| Used By | Description |
| --- | --- |
| [wp\_enqueue\_stored\_styles()](wp_enqueue_stored_styles) wp-includes/script-loader.php | Fetches, processes and compiles stored core styles, then combines and renders them to the page. |
| [wp\_enqueue\_block\_support\_styles()](wp_enqueue_block_support_styles) wp-includes/script-loader.php | Hooks inline styles in the proper place, depending on the active theme. |
| [\_add\_default\_theme\_supports()](_add_default_theme_supports) wp-includes/theme.php | Adds default theme supports for block themes when the ‘setup\_theme’ action fires. |
| [wp\_admin\_bar\_edit\_site\_menu()](wp_admin_bar_edit_site_menu) wp-includes/admin-bar.php | Adds the “Edit site” link to the Toolbar. |
| [\_add\_plugin\_file\_editor\_to\_tools()](_add_plugin_file_editor_to_tools) wp-admin/menu.php | Adds the ‘Plugin File Editor’ menu item after the ‘Themes File Editor’ in Tools for block themes. |
| [wp\_enable\_block\_templates()](wp_enable_block_templates) wp-includes/theme-templates.php | Enables the block templates (editor mode) for themes with theme.json by default. |
| [wp\_enqueue\_global\_styles()](wp_enqueue_global_styles) wp-includes/script-loader.php | Enqueues the global styles defined via theme.json. |
| [wp\_admin\_bar\_customize\_menu()](wp_admin_bar_customize_menu) wp-includes/admin-bar.php | Adds the “Customize” link to the Toolbar. |
| [wp\_welcome\_panel()](wp_welcome_panel) wp-admin/includes/dashboard.php | Displays a welcome panel to introduce users to WordPress. |
| [\_add\_themes\_utility\_last()](_add_themes_utility_last) wp-admin/menu.php | Adds the ‘Theme File Editor’ menu item to the bottom of the Appearance (non-block themes) or Tools (block themes) menu. |
| [wp\_widgets\_add\_menu()](wp_widgets_add_menu) wp-includes/functions.php | Appends the Widgets menu to the themes main menu. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress url_to_postid( string $url ): int url\_to\_postid( string $url ): int
===================================
Examines a URL and try to determine the post ID it represents.
Checks are supposedly from the hosted site blog.
`$url` string Required Permalink to check. int Post ID, or 0 on failure.
File: `wp-includes/rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rewrite.php/)
```
function url_to_postid( $url ) {
global $wp_rewrite;
/**
* Filters the URL to derive the post ID from.
*
* @since 2.2.0
*
* @param string $url The URL to derive the post ID from.
*/
$url = apply_filters( 'url_to_postid', $url );
$url_host = parse_url( $url, PHP_URL_HOST );
if ( is_string( $url_host ) ) {
$url_host = str_replace( 'www.', '', $url_host );
} else {
$url_host = '';
}
$home_url_host = parse_url( home_url(), PHP_URL_HOST );
if ( is_string( $home_url_host ) ) {
$home_url_host = str_replace( 'www.', '', $home_url_host );
} else {
$home_url_host = '';
}
// Bail early if the URL does not belong to this site.
if ( $url_host && $url_host !== $home_url_host ) {
return 0;
}
// First, check to see if there is a 'p=N' or 'page_id=N' to match against.
if ( preg_match( '#[?&](p|page_id|attachment_id)=(\d+)#', $url, $values ) ) {
$id = absint( $values[2] );
if ( $id ) {
return $id;
}
}
// Get rid of the #anchor.
$url_split = explode( '#', $url );
$url = $url_split[0];
// Get rid of URL ?query=string.
$url_split = explode( '?', $url );
$url = $url_split[0];
// Set the correct URL scheme.
$scheme = parse_url( home_url(), PHP_URL_SCHEME );
$url = set_url_scheme( $url, $scheme );
// Add 'www.' if it is absent and should be there.
if ( false !== strpos( home_url(), '://www.' ) && false === strpos( $url, '://www.' ) ) {
$url = str_replace( '://', '://www.', $url );
}
// Strip 'www.' if it is present and shouldn't be.
if ( false === strpos( home_url(), '://www.' ) ) {
$url = str_replace( '://www.', '://', $url );
}
if ( trim( $url, '/' ) === home_url() && 'page' === get_option( 'show_on_front' ) ) {
$page_on_front = get_option( 'page_on_front' );
if ( $page_on_front && get_post( $page_on_front ) instanceof WP_Post ) {
return (int) $page_on_front;
}
}
// Check to see if we are using rewrite rules.
$rewrite = $wp_rewrite->wp_rewrite_rules();
// Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options.
if ( empty( $rewrite ) ) {
return 0;
}
// Strip 'index.php/' if we're not using path info permalinks.
if ( ! $wp_rewrite->using_index_permalinks() ) {
$url = str_replace( $wp_rewrite->index . '/', '', $url );
}
if ( false !== strpos( trailingslashit( $url ), home_url( '/' ) ) ) {
// Chop off http://domain.com/[path].
$url = str_replace( home_url(), '', $url );
} else {
// Chop off /path/to/blog.
$home_path = parse_url( home_url( '/' ) );
$home_path = isset( $home_path['path'] ) ? $home_path['path'] : '';
$url = preg_replace( sprintf( '#^%s#', preg_quote( $home_path ) ), '', trailingslashit( $url ) );
}
// Trim leading and lagging slashes.
$url = trim( $url, '/' );
$request = $url;
$post_type_query_vars = array();
foreach ( get_post_types( array(), 'objects' ) as $post_type => $t ) {
if ( ! empty( $t->query_var ) ) {
$post_type_query_vars[ $t->query_var ] = $post_type;
}
}
// Look for matches.
$request_match = $request;
foreach ( (array) $rewrite as $match => $query ) {
// If the requesting file is the anchor of the match,
// prepend it to the path info.
if ( ! empty( $url ) && ( $url != $request ) && ( strpos( $match, $url ) === 0 ) ) {
$request_match = $url . '/' . $request;
}
if ( preg_match( "#^$match#", $request_match, $matches ) ) {
if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
// This is a verbose page match, let's check to be sure about it.
$page = get_page_by_path( $matches[ $varmatch[1] ] );
if ( ! $page ) {
continue;
}
$post_status_obj = get_post_status_object( $page->post_status );
if ( ! $post_status_obj->public && ! $post_status_obj->protected
&& ! $post_status_obj->private && $post_status_obj->exclude_from_search ) {
continue;
}
}
// Got a match.
// Trim the query of everything up to the '?'.
$query = preg_replace( '!^.+\?!', '', $query );
// Substitute the substring matches into the query.
$query = addslashes( WP_MatchesMapRegex::apply( $query, $matches ) );
// Filter out non-public query vars.
global $wp;
parse_str( $query, $query_vars );
$query = array();
foreach ( (array) $query_vars as $key => $value ) {
if ( in_array( (string) $key, $wp->public_query_vars, true ) ) {
$query[ $key ] = $value;
if ( isset( $post_type_query_vars[ $key ] ) ) {
$query['post_type'] = $post_type_query_vars[ $key ];
$query['name'] = $value;
}
}
}
// Resolve conflicts between posts with numeric slugs and date archive queries.
$query = wp_resolve_numeric_slug_conflicts( $query );
// Do the query.
$query = new WP_Query( $query );
if ( ! empty( $query->posts ) && $query->is_singular ) {
return $query->post->ID;
} else {
return 0;
}
}
}
return 0;
}
```
[apply\_filters( 'url\_to\_postid', string $url )](../hooks/url_to_postid)
Filters the URL to derive the post ID from.
| Uses | Description |
| --- | --- |
| [wp\_resolve\_numeric\_slug\_conflicts()](wp_resolve_numeric_slug_conflicts) wp-includes/rewrite.php | Resolves numeric slugs that collide with date permalinks. |
| [WP\_MatchesMapRegex::apply()](../classes/wp_matchesmapregex/apply) wp-includes/class-wp-matchesmapregex.php | Substitute substring matches in subject. |
| [WP\_Query::\_\_construct()](../classes/wp_query/__construct) wp-includes/class-wp-query.php | Constructor. |
| [set\_url\_scheme()](set_url_scheme) wp-includes/link-template.php | Sets the scheme for a URL. |
| [get\_page\_by\_path()](get_page_by_path) wp-includes/post.php | Retrieves a page given its path. |
| [get\_post\_status\_object()](get_post_status_object) wp-includes/post.php | Retrieves a post status object by name. |
| [WP\_Rewrite::wp\_rewrite\_rules()](../classes/wp_rewrite/wp_rewrite_rules) wp-includes/class-wp-rewrite.php | Retrieves the rewrite rules. |
| [WP\_Rewrite::using\_index\_permalinks()](../classes/wp_rewrite/using_index_permalinks) wp-includes/class-wp-rewrite.php | Determines whether permalinks are being used and rewrite module is not enabled. |
| [trailingslashit()](trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| [absint()](absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [home\_url()](home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [get\_post\_types()](get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| Used By | Description |
| --- | --- |
| [get\_oembed\_response\_data\_for\_url()](get_oembed_response_data_for_url) wp-includes/embed.php | Retrieves the oEmbed response data for a given URL. |
| [WP\_oEmbed\_Controller::get\_item()](../classes/wp_oembed_controller/get_item) wp-includes/class-wp-oembed-controller.php | Callback for the embed API endpoint. |
| [is\_local\_attachment()](is_local_attachment) wp-includes/post.php | Determines whether an attachment URI is local and really an attachment. |
| [wp\_xmlrpc\_server::pingback\_ping()](../classes/wp_xmlrpc_server/pingback_ping) wp-includes/class-wp-xmlrpc-server.php | Retrieves a pingback and registers it. |
| [wp\_xmlrpc\_server::pingback\_extensions\_getPingbacks()](../classes/wp_xmlrpc_server/pingback_extensions_getpingbacks) wp-includes/class-wp-xmlrpc-server.php | Retrieve array of URLs that pingbacked the given URL. |
| [wp\_xmlrpc\_server::wp\_newComment()](../classes/wp_xmlrpc_server/wp_newcomment) wp-includes/class-wp-xmlrpc-server.php | Create new comment. |
| [pingback()](pingback) wp-includes/comment.php | Pings back the links found in a post. |
| Version | Description |
| --- | --- |
| [1.0.0](https://developer.wordpress.org/reference/since/1.0.0/) | Introduced. |
wordpress remove_theme_support( string $feature ): bool|void remove\_theme\_support( string $feature ): bool|void
====================================================
Allows a theme to de-register its support of a certain feature
Should be called in the theme’s functions.php file. Generally would be used for child themes to override support from the parent theme.
* [add\_theme\_support()](add_theme_support)
`$feature` string Required The feature being removed. See [add\_theme\_support()](add_theme_support) for the list of possible values. More Arguments from add\_theme\_support( ... $feature ) The feature being added. Likely core values include:
* `'admin-bar'`
* `'align-wide'`
* `'automatic-feed-links'`
* `'core-block-patterns'`
* `'custom-background'`
* `'custom-header'`
* `'custom-line-height'`
* `'custom-logo'`
* `'customize-selective-refresh-widgets'`
* `'custom-spacing'`
* `'custom-units'`
* `'dark-editor-style'`
* `'disable-custom-colors'`
* `'disable-custom-font-sizes'`
* `'editor-color-palette'`
* `'editor-gradient-presets'`
* `'editor-font-sizes'`
* `'editor-styles'`
* `'featured-content'`
* `'html5'`
* `'menus'`
* `'post-formats'`
* `'post-thumbnails'`
* `'responsive-embeds'`
* `'starter-content'`
* `'title-tag'`
* `'wp-block-styles'`
* `'widgets'`
* `'widgets-block-editor'`
bool|void Whether feature was removed.
File: `wp-includes/theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/theme.php/)
```
function remove_theme_support( $feature ) {
// Do not remove internal registrations that are not used directly by themes.
if ( in_array( $feature, array( 'editor-style', 'widgets', 'menus' ), true ) ) {
return false;
}
return _remove_theme_support( $feature );
}
```
| Uses | Description |
| --- | --- |
| [\_remove\_theme\_support()](_remove_theme_support) wp-includes/theme.php | Do not use. Removes theme support internally without knowledge of those not used by themes directly. |
| Used By | Description |
| --- | --- |
| [remove\_custom\_image\_header()](remove_custom_image_header) wp-includes/deprecated.php | Remove image header support. |
| [remove\_custom\_background()](remove_custom_background) wp-includes/deprecated.php | Remove custom background support. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress wp_hash_password( string $password ): string wp\_hash\_password( string $password ): string
==============================================
Creates a hash (encrypt) of a plain text password.
For integration with other applications, this function can be overwritten to instead use the other package password checking algorithm.
`$password` string Required Plain text user password to hash. string The hash string of the password.
This function can be replaced via [plugins](https://wordpress.org/support/article/glossary/ "Glossary"). If plugins do not redefine these functions, then this will be used instead.
Creates a hash of a plain text password. Unless the global $wp\_hasher is set, the default implementation uses `PasswordHash`, which adds salt to the password and hashes it with `2**8 = 256` passes of MD5. MD5 is used by default because it’s supported on all platforms. You can configure `PasswordHash` to use Blowfish or extended DES (if available) instead of MD5 with the $portable\_hashes constructor argument or property (see examples).
File: `wp-includes/pluggable.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pluggable.php/)
```
function wp_hash_password( $password ) {
global $wp_hasher;
if ( empty( $wp_hasher ) ) {
require_once ABSPATH . WPINC . '/class-phpass.php';
// By default, use the portable hash from phpass.
$wp_hasher = new PasswordHash( 8, true );
}
return $wp_hasher->HashPassword( trim( $password ) );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Application\_Passwords::create\_new\_application\_password()](../classes/wp_application_passwords/create_new_application_password) wp-includes/class-wp-application-passwords.php | Creates a new application password. |
| [wp\_set\_password()](wp_set_password) wp-includes/pluggable.php | Updates the user’s password with a new encrypted one. |
| [wp\_check\_password()](wp_check_password) wp-includes/pluggable.php | Checks the plaintext password against the encrypted Password. |
| [wp\_update\_user()](wp_update_user) wp-includes/user.php | Updates a user in the database. |
| [wp\_insert\_user()](wp_insert_user) wp-includes/user.php | Inserts a user into the database. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress wp_trash_post( int $post_id ): WP_Post|false|null wp\_trash\_post( int $post\_id ): WP\_Post|false|null
=====================================================
Moves a post or page to the Trash
If Trash is disabled, the post or page is permanently deleted.
* [wp\_delete\_post()](wp_delete_post)
`$post_id` int Optional Post ID. Default is the ID of the global `$post` if `EMPTY_TRASH_DAYS` equals true. [WP\_Post](../classes/wp_post)|false|null Post data on success, false or null on failure.
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function wp_trash_post( $post_id = 0 ) {
if ( ! EMPTY_TRASH_DAYS ) {
return wp_delete_post( $post_id, true );
}
$post = get_post( $post_id );
if ( ! $post ) {
return $post;
}
if ( 'trash' === $post->post_status ) {
return false;
}
/**
* Filters whether a post trashing should take place.
*
* @since 4.9.0
*
* @param bool|null $trash Whether to go forward with trashing.
* @param WP_Post $post Post object.
*/
$check = apply_filters( 'pre_trash_post', null, $post );
if ( null !== $check ) {
return $check;
}
/**
* Fires before a post is sent to the Trash.
*
* @since 3.3.0
*
* @param int $post_id Post ID.
*/
do_action( 'wp_trash_post', $post_id );
add_post_meta( $post_id, '_wp_trash_meta_status', $post->post_status );
add_post_meta( $post_id, '_wp_trash_meta_time', time() );
$post_updated = wp_update_post(
array(
'ID' => $post_id,
'post_status' => 'trash',
)
);
if ( ! $post_updated ) {
return false;
}
wp_trash_post_comments( $post_id );
/**
* Fires after a post is sent to the Trash.
*
* @since 2.9.0
*
* @param int $post_id Post ID.
*/
do_action( 'trashed_post', $post_id );
return $post;
}
```
[apply\_filters( 'pre\_trash\_post', bool|null $trash, WP\_Post $post )](../hooks/pre_trash_post)
Filters whether a post trashing should take place.
[do\_action( 'trashed\_post', int $post\_id )](../hooks/trashed_post)
Fires after a post is sent to the Trash.
[do\_action( 'wp\_trash\_post', int $post\_id )](../hooks/wp_trash_post)
Fires before a post is sent to the Trash.
| Uses | Description |
| --- | --- |
| [wp\_update\_post()](wp_update_post) wp-includes/post.php | Updates a post with new post data. |
| [wp\_delete\_post()](wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [wp\_trash\_post\_comments()](wp_trash_post_comments) wp-includes/post.php | Moves comments for a post to the Trash. |
| [add\_post\_meta()](add_post_meta) wp-includes/post.php | Adds a meta field to the given post. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::delete\_item()](../classes/wp_rest_templates_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Deletes a single template. |
| [\_wp\_keep\_alive\_customize\_changeset\_dependent\_auto\_drafts()](_wp_keep_alive_customize_changeset_dependent_auto_drafts) wp-includes/theme.php | Makes sure that auto-draft posts get their post\_date bumped or status changed to draft to prevent premature garbage-collection. |
| [\_wp\_delete\_customize\_changeset\_dependent\_auto\_drafts()](_wp_delete_customize_changeset_dependent_auto_drafts) wp-includes/nav-menu.php | Deletes auto-draft posts associated with the supplied changeset. |
| [WP\_REST\_Posts\_Controller::delete\_item()](../classes/wp_rest_posts_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Deletes a single post. |
| [wp\_ajax\_trash\_post()](wp_ajax_trash_post) wp-admin/includes/ajax-actions.php | Ajax handler for sending a post to the Trash. |
| [wp\_delete\_attachment()](wp_delete_attachment) wp-includes/post.php | Trashes or deletes an attachment. |
| [wp\_delete\_post()](wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| Version | Description |
| --- | --- |
| [2.9.0](https://developer.wordpress.org/reference/since/2.9.0/) | Introduced. |
| programming_docs |
wordpress is_archive(): bool is\_archive(): bool
===================
Determines whether the query is for an existing archive page.
Archive pages include category, tag, author, date, custom post type, and custom taxonomy based archives.
For more information on this and similar theme functions, check out the [Conditional Tags](https://developer.wordpress.org/themes/basics/conditional-tags/) article in the Theme Developer Handbook.
* [is\_category()](is_category)
* [is\_tag()](is_tag)
* [is\_author()](is_author)
* [is\_date()](is_date)
* [is\_post\_type\_archive()](is_post_type_archive)
* [is\_tax()](is_tax)
bool Whether the query is for an existing archive page.
[is\_archive()](is_archive) does not accept any parameters. If you want to check if this is the archive of a custom post type, use is\_post\_type\_archive( $post\_type )
File: `wp-includes/query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/query.php/)
```
function is_archive() {
global $wp_query;
if ( ! isset( $wp_query ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
return false;
}
return $wp_query->is_archive();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Query::is\_archive()](../classes/wp_query/is_archive) wp-includes/class-wp-query.php | Is the query for an existing archive page? |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_doing\_it\_wrong()](_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Used By | Description |
| --- | --- |
| [wp\_get\_archives()](wp_get_archives) wp-includes/general-template.php | Displays archive links based on type and format. |
| [wp\_title()](wp_title) wp-includes/general-template.php | Displays or retrieves page title for all areas of blog. |
| [get\_body\_class()](get_body_class) wp-includes/post-template.php | Retrieves an array of the class names for the body element. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress get_blogaddress_by_domain( string $domain, string $path ): string get\_blogaddress\_by\_domain( string $domain, string $path ): string
====================================================================
This function has been deprecated.
Get a full blog URL, given a domain and a path.
`$domain` string Required `$path` string Required string
File: `wp-includes/ms-deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-deprecated.php/)
```
function get_blogaddress_by_domain( $domain, $path ) {
_deprecated_function( __FUNCTION__, '3.7.0' );
if ( is_subdomain_install() ) {
$url = "http://" . $domain.$path;
} else {
if ( $domain != $_SERVER['HTTP_HOST'] ) {
$blogname = substr( $domain, 0, strpos( $domain, '.' ) );
$url = 'http://' . substr( $domain, strpos( $domain, '.' ) + 1 ) . $path;
// We're not installing the main blog.
if ( 'www.' !== $blogname )
$url .= $blogname . '/';
} else { // Main blog.
$url = 'http://' . $domain . $path;
}
}
return sanitize_url( $url );
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_url()](sanitize_url) wp-includes/formatting.php | Sanitizes a URL for database or redirect usage. |
| [is\_subdomain\_install()](is_subdomain_install) wp-includes/ms-load.php | Whether a subdomain configuration is enabled. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | This function has been deprecated. |
| [MU (3.0.0)](https://developer.wordpress.org/reference/since/mu.3.0.0/) | Introduced. |
wordpress wp_get_user_request( int $request_id ): WP_User_Request|false wp\_get\_user\_request( int $request\_id ): WP\_User\_Request|false
===================================================================
Returns the user request object for the specified request ID.
`$request_id` int Required The ID of the user request. [WP\_User\_Request](../classes/wp_user_request)|false
File: `wp-includes/user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/user.php/)
```
function wp_get_user_request( $request_id ) {
$request_id = absint( $request_id );
$post = get_post( $request_id );
if ( ! $post || 'user_request' !== $post->post_type ) {
return false;
}
return new WP_User_Request( $post );
}
```
| Uses | Description |
| --- | --- |
| [WP\_User\_Request::\_\_construct()](../classes/wp_user_request/__construct) wp-includes/class-wp-user-request.php | Constructor. |
| [absint()](absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [wp\_get\_user\_request\_data()](wp_get_user_request_data) wp-includes/deprecated.php | Return the user request object for the specified request ID. |
| [wp\_validate\_user\_request\_key()](wp_validate_user_request_key) wp-includes/user.php | Validates a user request by comparing the key with the request’s key. |
| [\_wp\_privacy\_account\_request\_confirmed()](_wp_privacy_account_request_confirmed) wp-includes/user.php | Updates log when privacy request is confirmed. |
| [\_wp\_privacy\_send\_request\_confirmation\_notification()](_wp_privacy_send_request_confirmation_notification) wp-includes/user.php | Notifies the site administrator via email when a request is confirmed. |
| [\_wp\_privacy\_send\_erasure\_fulfillment\_notification()](_wp_privacy_send_erasure_fulfillment_notification) wp-includes/user.php | Notifies the user when their erasure request is fulfilled. |
| [\_wp\_privacy\_account\_request\_confirmed\_message()](_wp_privacy_account_request_confirmed_message) wp-includes/user.php | Returns request confirmation message HTML. |
| [wp\_send\_user\_request()](wp_send_user_request) wp-includes/user.php | Send a confirmation request email to confirm an action. |
| [wp\_privacy\_process\_personal\_data\_export\_page()](wp_privacy_process_personal_data_export_page) wp-admin/includes/privacy-tools.php | Intercept personal data exporter page Ajax responses in order to assemble the personal data export file. |
| [wp\_privacy\_generate\_personal\_data\_export\_file()](wp_privacy_generate_personal_data_export_file) wp-admin/includes/privacy-tools.php | Generate the personal data export file. |
| [wp\_privacy\_send\_personal\_data\_export\_email()](wp_privacy_send_personal_data_export_email) wp-admin/includes/privacy-tools.php | Send an email to the user with a link to the personal data export file |
| [WP\_Privacy\_Requests\_Table::prepare\_items()](../classes/wp_privacy_requests_table/prepare_items) wp-admin/includes/class-wp-privacy-requests-table.php | Prepare items to output. |
| [wp\_privacy\_process\_personal\_data\_erasure\_page()](wp_privacy_process_personal_data_erasure_page) wp-admin/includes/privacy-tools.php | Mark erasure requests as completed after processing is finished. |
| [\_wp\_privacy\_completed\_request()](_wp_privacy_completed_request) wp-admin/includes/privacy-tools.php | Marks a request as completed by the admin and logs the current timestamp. |
| [wp\_ajax\_wp\_privacy\_export\_personal\_data()](wp_ajax_wp_privacy_export_personal_data) wp-admin/includes/ajax-actions.php | Ajax handler for exporting a user’s personal data. |
| [wp\_ajax\_wp\_privacy\_erase\_personal\_data()](wp_ajax_wp_privacy_erase_personal_data) wp-admin/includes/ajax-actions.php | Ajax handler for erasing personal data. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress get_the_comments_navigation( array $args = array() ): string get\_the\_comments\_navigation( array $args = array() ): string
===============================================================
Retrieves navigation to next/previous set of comments, when applicable.
`$args` array Optional Default comments navigation arguments.
* `prev_text`stringAnchor text to display in the previous comments link.
Default 'Older comments'.
* `next_text`stringAnchor text to display in the next comments link.
Default 'Newer comments'.
* `screen_reader_text`stringScreen reader text for the nav element. Default 'Comments navigation'.
* `aria_label`stringARIA label text for the nav element. Default `'Comments'`.
* `class`stringCustom class for the nav element. Default `'comment-navigation'`.
Default: `array()`
string Markup for comments links.
File: `wp-includes/link-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/link-template.php/)
```
function get_the_comments_navigation( $args = array() ) {
$navigation = '';
// Are there comments to navigate through?
if ( get_comment_pages_count() > 1 ) {
// Make sure the nav element has an aria-label attribute: fallback to the screen reader text.
if ( ! empty( $args['screen_reader_text'] ) && empty( $args['aria_label'] ) ) {
$args['aria_label'] = $args['screen_reader_text'];
}
$args = wp_parse_args(
$args,
array(
'prev_text' => __( 'Older comments' ),
'next_text' => __( 'Newer comments' ),
'screen_reader_text' => __( 'Comments navigation' ),
'aria_label' => __( 'Comments' ),
'class' => 'comment-navigation',
)
);
$prev_link = get_previous_comments_link( $args['prev_text'] );
$next_link = get_next_comments_link( $args['next_text'] );
if ( $prev_link ) {
$navigation .= '<div class="nav-previous">' . $prev_link . '</div>';
}
if ( $next_link ) {
$navigation .= '<div class="nav-next">' . $next_link . '</div>';
}
$navigation = _navigation_markup( $navigation, $args['class'], $args['screen_reader_text'], $args['aria_label'] );
}
return $navigation;
}
```
| Uses | Description |
| --- | --- |
| [\_navigation\_markup()](_navigation_markup) wp-includes/link-template.php | Wraps passed links in navigational markup. |
| [get\_previous\_comments\_link()](get_previous_comments_link) wp-includes/link-template.php | Retrieves the link to the previous comments page. |
| [get\_next\_comments\_link()](get_next_comments_link) wp-includes/link-template.php | Retrieves the link to the next comments page. |
| [get\_comment\_pages\_count()](get_comment_pages_count) wp-includes/comment.php | Calculates the total number of comment pages. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_parse\_args()](wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Used By | Description |
| --- | --- |
| [the\_comments\_navigation()](the_comments_navigation) wp-includes/link-template.php | Displays navigation to next/previous set of comments, when applicable. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Added the `class` parameter. |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Added the `aria_label` parameter. |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress get_the_privacy_policy_link( string $before = '', string $after = '' ): string get\_the\_privacy\_policy\_link( string $before = '', string $after = '' ): string
==================================================================================
Returns the privacy policy link with formatting, when applicable.
`$before` string Optional Display before privacy policy link. Default: `''`
`$after` string Optional Display after privacy policy link. Default: `''`
string Markup for the link and surrounding elements. Empty string if it doesn't exist.
File: `wp-includes/link-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/link-template.php/)
```
function get_the_privacy_policy_link( $before = '', $after = '' ) {
$link = '';
$privacy_policy_url = get_privacy_policy_url();
$policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' );
$page_title = ( $policy_page_id ) ? get_the_title( $policy_page_id ) : '';
if ( $privacy_policy_url && $page_title ) {
$link = sprintf(
'<a class="privacy-policy-link" href="%s">%s</a>',
esc_url( $privacy_policy_url ),
esc_html( $page_title )
);
}
/**
* Filters the privacy policy link.
*
* @since 4.9.6
*
* @param string $link The privacy policy link. Empty string if it
* doesn't exist.
* @param string $privacy_policy_url The URL of the privacy policy. Empty string
* if it doesn't exist.
*/
$link = apply_filters( 'the_privacy_policy_link', $link, $privacy_policy_url );
if ( $link ) {
return $before . $link . $after;
}
return '';
}
```
[apply\_filters( 'the\_privacy\_policy\_link', string $link, string $privacy\_policy\_url )](../hooks/the_privacy_policy_link)
Filters the privacy policy link.
| Uses | Description |
| --- | --- |
| [get\_privacy\_policy\_url()](get_privacy_policy_url) wp-includes/link-template.php | Retrieves the URL to the privacy policy page. |
| [get\_the\_title()](get_the_title) wp-includes/post-template.php | Retrieves the post title. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [the\_privacy\_policy\_link()](the_privacy_policy_link) wp-includes/link-template.php | Displays the privacy policy link with formatting, when applicable. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress wp_ajax_closed_postboxes() wp\_ajax\_closed\_postboxes()
=============================
Ajax handler for closed post boxes.
File: `wp-admin/includes/ajax-actions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/ajax-actions.php/)
```
function wp_ajax_closed_postboxes() {
check_ajax_referer( 'closedpostboxes', 'closedpostboxesnonce' );
$closed = isset( $_POST['closed'] ) ? explode( ',', $_POST['closed'] ) : array();
$closed = array_filter( $closed );
$hidden = isset( $_POST['hidden'] ) ? explode( ',', $_POST['hidden'] ) : array();
$hidden = array_filter( $hidden );
$page = isset( $_POST['page'] ) ? $_POST['page'] : '';
if ( sanitize_key( $page ) != $page ) {
wp_die( 0 );
}
$user = wp_get_current_user();
if ( ! $user ) {
wp_die( -1 );
}
if ( is_array( $closed ) ) {
update_user_meta( $user->ID, "closedpostboxes_$page", $closed );
}
if ( is_array( $hidden ) ) {
// Postboxes that are always shown.
$hidden = array_diff( $hidden, array( 'submitdiv', 'linksubmitdiv', 'manage-menu', 'create-menu' ) );
update_user_meta( $user->ID, "metaboxhidden_$page", $hidden );
}
wp_die( 1 );
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_current\_user()](wp_get_current_user) wp-includes/pluggable.php | Retrieves the current user object. |
| [update\_user\_meta()](update_user_meta) wp-includes/user.php | Updates user meta field based on user ID. |
| [sanitize\_key()](sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [check\_ajax\_referer()](check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [wp\_die()](wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress previous_post_link( string $format = '« %link', string $link = '%title', bool $in_same_term = false, int[]|string $excluded_terms = '', string $taxonomy = 'category' ) previous\_post\_link( string $format = '« %link', string $link = '%title', bool $in\_same\_term = false, int[]|string $excluded\_terms = '', string $taxonomy = 'category' )
==================================================================================================================================================================================
Displays the previous post link that is adjacent to the current post.
* [get\_previous\_post\_link()](get_previous_post_link)
`$format` string Optional Link anchor format. Default '« %link'. Default: `'« %link'`
`$link` string Optional Link permalink format. Default `'%title'`. Default: `'%title'`
`$in_same_term` bool Optional Whether link should be in a same taxonomy term. Default: `false`
`$excluded_terms` int[]|string Optional Array or comma-separated list of excluded term IDs. Default: `''`
`$taxonomy` string Optional Taxonomy, if $in\_same\_term is true. Default `'category'`. Default: `'category'`
Used on single post permalink pages, this template tag displays a link to the previous post which exists in chronological order from the current post. This tag must be used in The Loop.
$format is the format string for the link. This is where to control what comes before and after the link. '%link' in string will be replaced with whatever is declared as 'link' (see next parameter). 'Go to %link' will generate “Go to <a href=…” Put HTML tags here to style the final results.
$in\_same\_term indicates whether previous post must be within the same taxonomy term as the current post. If set to 'true', only posts from the current taxonomy term will be displayed. If the post is in both the parent and subcategory, or more than one term, the previous post link will lead to the previous post in any of those terms.
$excluded\_terms is an array or a comma-separated list of numeric terms IDs from which the next post should not be listed. For example array(1, 5) or '1,5'. This argument used to accept a list of IDs separated by 'and', this was deprecated in WordPress 3.3. File: `wp-includes/link-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/link-template.php/)
```
function previous_post_link( $format = '« %link', $link = '%title', $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {
echo get_previous_post_link( $format, $link, $in_same_term, $excluded_terms, $taxonomy );
}
```
| Uses | Description |
| --- | --- |
| [get\_previous\_post\_link()](get_previous_post_link) wp-includes/link-template.php | Retrieves the previous post link that is adjacent to the current post. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress get_main_network_id(): int get\_main\_network\_id(): int
=============================
Gets the main network ID.
int The ID of the main network.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function get_main_network_id() {
if ( ! is_multisite() ) {
return 1;
}
$current_network = get_network();
if ( defined( 'PRIMARY_NETWORK_ID' ) ) {
$main_network_id = PRIMARY_NETWORK_ID;
} elseif ( isset( $current_network->id ) && 1 === (int) $current_network->id ) {
// If the current network has an ID of 1, assume it is the main network.
$main_network_id = 1;
} else {
$_networks = get_networks(
array(
'fields' => 'ids',
'number' => 1,
)
);
$main_network_id = array_shift( $_networks );
}
/**
* Filters the main network ID.
*
* @since 4.3.0
*
* @param int $main_network_id The ID of the main network.
*/
return (int) apply_filters( 'get_main_network_id', $main_network_id );
}
```
[apply\_filters( 'get\_main\_network\_id', int $main\_network\_id )](../hooks/get_main_network_id)
Filters the main network ID.
| Uses | Description |
| --- | --- |
| [get\_network()](get_network) wp-includes/ms-network.php | Retrieves network data given a network ID or network object. |
| [get\_networks()](get_networks) wp-includes/ms-network.php | Retrieves a list of networks. |
| [is\_multisite()](is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Application\_Passwords::is\_in\_use()](../classes/wp_application_passwords/is_in_use) wp-includes/class-wp-application-passwords.php | Checks if application passwords are being used by the site. |
| [WP\_Application\_Passwords::create\_new\_application\_password()](../classes/wp_application_passwords/create_new_application_password) wp-includes/class-wp-application-passwords.php | Creates a new application password. |
| [is\_site\_meta\_supported()](is_site_meta_supported) wp-includes/functions.php | Determines whether site meta is enabled. |
| [get\_current\_network\_id()](get_current_network_id) wp-includes/load.php | Retrieves the current network ID. |
| [upgrade\_network()](upgrade_network) wp-admin/includes/upgrade.php | Executes network-level upgrade routines. |
| [is\_main\_network()](is_main_network) wp-includes/functions.php | Determines whether a network is the main network of the Multisite installation. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
| programming_docs |
wordpress xmlrpc_pingback_error( IXR_Error $ixr_error ): IXR_Error xmlrpc\_pingback\_error( IXR\_Error $ixr\_error ): IXR\_Error
=============================================================
Default filter attached to xmlrpc\_pingback\_error.
Returns a generic pingback error code unless the error code is 48, which reports that the pingback is already registered.
`$ixr_error` [IXR\_Error](../classes/ixr_error) Required [IXR\_Error](../classes/ixr_error)
File: `wp-includes/comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/comment.php/)
```
function xmlrpc_pingback_error( $ixr_error ) {
if ( 48 === $ixr_error->code ) {
return $ixr_error;
}
return new IXR_Error( 0, '' );
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Error::\_\_construct()](../classes/ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| Version | Description |
| --- | --- |
| [3.5.1](https://developer.wordpress.org/reference/since/3.5.1/) | Introduced. |
wordpress wp_ajax_search_plugins() wp\_ajax\_search\_plugins()
===========================
Ajax handler for searching plugins.
File: `wp-admin/includes/ajax-actions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/ajax-actions.php/)
```
function wp_ajax_search_plugins() {
check_ajax_referer( 'updates' );
// Ensure after_plugin_row_{$plugin_file} gets hooked.
wp_plugin_update_rows();
$pagenow = isset( $_POST['pagenow'] ) ? sanitize_key( $_POST['pagenow'] ) : '';
if ( 'plugins-network' === $pagenow || 'plugins' === $pagenow ) {
set_current_screen( $pagenow );
}
/** @var WP_Plugins_List_Table $wp_list_table */
$wp_list_table = _get_list_table(
'WP_Plugins_List_Table',
array(
'screen' => get_current_screen(),
)
);
$status = array();
if ( ! $wp_list_table->ajax_user_can() ) {
$status['errorMessage'] = __( 'Sorry, you are not allowed to manage plugins for this site.' );
wp_send_json_error( $status );
}
// Set the correct requester, so pagination works.
$_SERVER['REQUEST_URI'] = add_query_arg(
array_diff_key(
$_POST,
array(
'_ajax_nonce' => null,
'action' => null,
)
),
network_admin_url( 'plugins.php', 'relative' )
);
$GLOBALS['s'] = wp_unslash( $_POST['s'] );
$wp_list_table->prepare_items();
ob_start();
$wp_list_table->display();
$status['count'] = count( $wp_list_table->items );
$status['items'] = ob_get_clean();
wp_send_json_success( $status );
}
```
| Uses | Description |
| --- | --- |
| [set\_current\_screen()](set_current_screen) wp-admin/includes/screen.php | Set the current screen object |
| [get\_current\_screen()](get_current_screen) wp-admin/includes/screen.php | Get the current screen object |
| [WP\_List\_Table::display()](../classes/wp_list_table/display) wp-admin/includes/class-wp-list-table.php | Displays the table. |
| [WP\_List\_Table::ajax\_user\_can()](../classes/wp_list_table/ajax_user_can) wp-admin/includes/class-wp-list-table.php | Checks the current user’s permissions |
| [WP\_List\_Table::prepare\_items()](../classes/wp_list_table/prepare_items) wp-admin/includes/class-wp-list-table.php | Prepares the list of items for displaying. |
| [wp\_plugin\_update\_rows()](wp_plugin_update_rows) wp-admin/includes/update.php | Adds a callback to display update information for plugins with updates available. |
| [\_get\_list\_table()](_get_list_table) wp-admin/includes/list-table.php | Fetches an instance of a [WP\_List\_Table](../classes/wp_list_table) class. |
| [network\_admin\_url()](network_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the network. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_unslash()](wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [sanitize\_key()](sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [check\_ajax\_referer()](check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [wp\_send\_json\_error()](wp_send_json_error) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating failure. |
| [wp\_send\_json\_success()](wp_send_json_success) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating success. |
| [add\_query\_arg()](add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress comments_rss(): string comments\_rss(): string
=======================
This function has been deprecated. Use [get\_post\_comments\_feed\_link()](get_post_comments_feed_link) instead.
Return link to the post RSS feed.
* [get\_post\_comments\_feed\_link()](get_post_comments_feed_link)
string
File: `wp-includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/deprecated.php/)
```
function comments_rss() {
_deprecated_function( __FUNCTION__, '2.2.0', 'get_post_comments_feed_link()' );
return esc_url( get_post_comments_feed_link() );
}
```
| Uses | Description |
| --- | --- |
| [get\_post\_comments\_feed\_link()](get_post_comments_feed_link) wp-includes/link-template.php | Retrieves the permalink for the post comments feed. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Use [get\_post\_comments\_feed\_link()](get_post_comments_feed_link) |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress register_sidebars( int $number = 1, array|string $args = array() ) register\_sidebars( int $number = 1, array|string $args = array() )
===================================================================
Creates multiple sidebars.
If you wanted to quickly create multiple sidebars for a theme or internally.
This function will allow you to do so. If you don’t pass the ‘name’ and/or ‘id’ in `$args`, then they will be built for you.
* [register\_sidebar()](register_sidebar) : The second parameter is documented by [register\_sidebar()](register_sidebar) and is the same here.
`$number` int Optional Number of sidebars to create. Default: `1`
`$args` array|string Optional Array or string of arguments for building a sidebar.
* `id`stringThe base string of the unique identifier for each sidebar. If provided, and multiple sidebars are being defined, the ID will have "-2" appended, and so on.
Default `'sidebar-'` followed by the number the sidebar creation is currently at.
* `name`stringThe name or title for the sidebars displayed in the admin dashboard. If registering more than one sidebar, include `'%d'` in the string as a placeholder for the uniquely assigned number for each sidebar.
Default `'Sidebar'` for the first sidebar, otherwise 'Sidebar %d'.
Default: `array()`
File: `wp-includes/widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets.php/)
```
function register_sidebars( $number = 1, $args = array() ) {
global $wp_registered_sidebars;
$number = (int) $number;
if ( is_string( $args ) ) {
parse_str( $args, $args );
}
for ( $i = 1; $i <= $number; $i++ ) {
$_args = $args;
if ( $number > 1 ) {
if ( isset( $args['name'] ) ) {
$_args['name'] = sprintf( $args['name'], $i );
} else {
/* translators: %d: Sidebar number. */
$_args['name'] = sprintf( __( 'Sidebar %d' ), $i );
}
} else {
$_args['name'] = isset( $args['name'] ) ? $args['name'] : __( 'Sidebar' );
}
// Custom specified ID's are suffixed if they exist already.
// Automatically generated sidebar names need to be suffixed regardless starting at -0.
if ( isset( $args['id'] ) ) {
$_args['id'] = $args['id'];
$n = 2; // Start at -2 for conflicting custom IDs.
while ( is_registered_sidebar( $_args['id'] ) ) {
$_args['id'] = $args['id'] . '-' . $n++;
}
} else {
$n = count( $wp_registered_sidebars );
do {
$_args['id'] = 'sidebar-' . ++$n;
} while ( is_registered_sidebar( $_args['id'] ) );
}
register_sidebar( $_args );
}
}
```
| Uses | Description |
| --- | --- |
| [is\_registered\_sidebar()](is_registered_sidebar) wp-includes/widgets.php | Checks if a sidebar is registered. |
| [register\_sidebar()](register_sidebar) wp-includes/widgets.php | Builds the definition for a single sidebar and returns the ID. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Introduced. |
wordpress install_themes_dashboard() install\_themes\_dashboard()
============================
Displays tags filter for themes.
File: `wp-admin/includes/theme-install.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/theme-install.php/)
```
function install_themes_dashboard() {
install_theme_search_form( false );
?>
<h4><?php _e( 'Feature Filter' ); ?></h4>
<p class="install-help"><?php _e( 'Find a theme based on specific features.' ); ?></p>
<form method="get">
<input type="hidden" name="tab" value="search" />
<?php
$feature_list = get_theme_feature_list();
echo '<div class="feature-filter">';
foreach ( (array) $feature_list as $feature_name => $features ) {
$feature_name = esc_html( $feature_name );
echo '<div class="feature-name">' . $feature_name . '</div>';
echo '<ol class="feature-group">';
foreach ( $features as $feature => $feature_name ) {
$feature_name = esc_html( $feature_name );
$feature = esc_attr( $feature );
?>
<li>
<input type="checkbox" name="features[]" id="feature-id-<?php echo $feature; ?>" value="<?php echo $feature; ?>" />
<label for="feature-id-<?php echo $feature; ?>"><?php echo $feature_name; ?></label>
</li>
<?php } ?>
</ol>
<br class="clear" />
<?php
}
?>
</div>
<br class="clear" />
<?php submit_button( __( 'Find Themes' ), '', 'search' ); ?>
</form>
<?php
}
```
| Uses | Description |
| --- | --- |
| [get\_theme\_feature\_list()](get_theme_feature_list) wp-admin/includes/theme.php | Retrieves list of WordPress theme features (aka theme tags). |
| [install\_theme\_search\_form()](install_theme_search_form) wp-admin/includes/theme-install.php | Displays search form for searching themes. |
| [submit\_button()](submit_button) wp-admin/includes/template.php | Echoes a submit button, with provided text and appropriate class(es). |
| [\_e()](_e) wp-includes/l10n.php | Displays translated text. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress wpmu_validate_blog_signup( string $blogname, string $blog_title, WP_User|string $user = '' ): array wpmu\_validate\_blog\_signup( string $blogname, string $blog\_title, WP\_User|string $user = '' ): array
========================================================================================================
Processes new site registrations.
Checks the data provided by the user during blog signup. Verifies the validity and uniqueness of blog paths and domains.
This function prevents the current user from registering a new site with a blogname equivalent to another user’s login name. Passing the $user parameter to the function, where $user is the other user, is effectively an override of this limitation.
Filter [‘wpmu\_validate\_blog\_signup’](../hooks/wpmu_validate_blog_signup) if you want to modify the way that WordPress validates new site signups.
`$blogname` string Required The blog name provided by the user. Must be unique. `$blog_title` string Required The blog title provided by the user. `$user` [WP\_User](../classes/wp_user)|string Optional The user object to check against the new site name. Default: `''`
array Array of domain, path, blog name, blog title, user and error messages.
* `domain`stringDomain for the site.
* `path`stringPath for the site. Used in subdirectory installations.
* `blogname`stringThe unique site name (slug).
* `blog_title`stringBlog title.
* `user`string|[WP\_User](../classes/wp_user)By default, an empty string. A user object if provided.
* `errors`[WP\_Error](../classes/wp_error)
[WP\_Error](../classes/wp_error) containing any errors found.
File: `wp-includes/ms-functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-functions.php/)
```
function wpmu_validate_blog_signup( $blogname, $blog_title, $user = '' ) {
global $wpdb, $domain;
$current_network = get_network();
$base = $current_network->path;
$blog_title = strip_tags( $blog_title );
$errors = new WP_Error();
$illegal_names = get_site_option( 'illegal_names' );
if ( false == $illegal_names ) {
$illegal_names = array( 'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator' );
add_site_option( 'illegal_names', $illegal_names );
}
/*
* On sub dir installations, some names are so illegal, only a filter can
* spring them from jail.
*/
if ( ! is_subdomain_install() ) {
$illegal_names = array_merge( $illegal_names, get_subdirectory_reserved_names() );
}
if ( empty( $blogname ) ) {
$errors->add( 'blogname', __( 'Please enter a site name.' ) );
}
if ( preg_match( '/[^a-z0-9]+/', $blogname ) ) {
$errors->add( 'blogname', __( 'Site names can only contain lowercase letters (a-z) and numbers.' ) );
}
if ( in_array( $blogname, $illegal_names, true ) ) {
$errors->add( 'blogname', __( 'That name is not allowed.' ) );
}
/**
* Filters the minimum site name length required when validating a site signup.
*
* @since 4.8.0
*
* @param int $length The minimum site name length. Default 4.
*/
$minimum_site_name_length = apply_filters( 'minimum_site_name_length', 4 );
if ( strlen( $blogname ) < $minimum_site_name_length ) {
/* translators: %s: Minimum site name length. */
$errors->add( 'blogname', sprintf( _n( 'Site name must be at least %s character.', 'Site name must be at least %s characters.', $minimum_site_name_length ), number_format_i18n( $minimum_site_name_length ) ) );
}
// Do not allow users to create a site that conflicts with a page on the main blog.
if ( ! is_subdomain_install() && $wpdb->get_var( $wpdb->prepare( 'SELECT post_name FROM ' . $wpdb->get_blog_prefix( $current_network->site_id ) . "posts WHERE post_type = 'page' AND post_name = %s", $blogname ) ) ) {
$errors->add( 'blogname', __( 'Sorry, you may not use that site name.' ) );
}
// All numeric?
if ( preg_match( '/^[0-9]*$/', $blogname ) ) {
$errors->add( 'blogname', __( 'Sorry, site names must have letters too!' ) );
}
/**
* Filters the new site name during registration.
*
* The name is the site's subdomain or the site's subdirectory
* path depending on the network settings.
*
* @since MU (3.0.0)
*
* @param string $blogname Site name.
*/
$blogname = apply_filters( 'newblogname', $blogname );
$blog_title = wp_unslash( $blog_title );
if ( empty( $blog_title ) ) {
$errors->add( 'blog_title', __( 'Please enter a site title.' ) );
}
// Check if the domain/path has been used already.
if ( is_subdomain_install() ) {
$mydomain = $blogname . '.' . preg_replace( '|^www\.|', '', $domain );
$path = $base;
} else {
$mydomain = $domain;
$path = $base . $blogname . '/';
}
if ( domain_exists( $mydomain, $path, $current_network->id ) ) {
$errors->add( 'blogname', __( 'Sorry, that site already exists!' ) );
}
/*
* Do not allow users to create a site that matches an existing user's login name,
* unless it's the user's own username.
*/
if ( username_exists( $blogname ) ) {
if ( ! is_object( $user ) || ( is_object( $user ) && ( $user->user_login != $blogname ) ) ) {
$errors->add( 'blogname', __( 'Sorry, that site is reserved!' ) );
}
}
// Has someone already signed up for this domain?
// TODO: Check email too?
$signup = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->signups WHERE domain = %s AND path = %s", $mydomain, $path ) );
if ( $signup instanceof stdClass ) {
$diff = time() - mysql2date( 'U', $signup->registered );
// If registered more than two days ago, cancel registration and let this signup go through.
if ( $diff > 2 * DAY_IN_SECONDS ) {
$wpdb->delete(
$wpdb->signups,
array(
'domain' => $mydomain,
'path' => $path,
)
);
} else {
$errors->add( 'blogname', __( 'That site is currently reserved but may be available in a couple days.' ) );
}
}
$result = array(
'domain' => $mydomain,
'path' => $path,
'blogname' => $blogname,
'blog_title' => $blog_title,
'user' => $user,
'errors' => $errors,
);
/**
* Filters site details and error messages following registration.
*
* @since MU (3.0.0)
*
* @param array $result {
* Array of domain, path, blog name, blog title, user and error messages.
*
* @type string $domain Domain for the site.
* @type string $path Path for the site. Used in subdirectory installations.
* @type string $blogname The unique site name (slug).
* @type string $blog_title Blog title.
* @type string|WP_User $user By default, an empty string. A user object if provided.
* @type WP_Error $errors WP_Error containing any errors found.
* }
*/
return apply_filters( 'wpmu_validate_blog_signup', $result );
}
```
[apply\_filters( 'minimum\_site\_name\_length', int $length )](../hooks/minimum_site_name_length)
Filters the minimum site name length required when validating a site signup.
[apply\_filters( 'newblogname', string $blogname )](../hooks/newblogname)
Filters the new site name during registration.
[apply\_filters( 'wpmu\_validate\_blog\_signup', array $result )](../hooks/wpmu_validate_blog_signup)
Filters site details and error messages following registration.
| Uses | Description |
| --- | --- |
| [get\_network()](get_network) wp-includes/ms-network.php | Retrieves network data given a network ID or network object. |
| [is\_subdomain\_install()](is_subdomain_install) wp-includes/ms-load.php | Whether a subdomain configuration is enabled. |
| [wpdb::get\_blog\_prefix()](../classes/wpdb/get_blog_prefix) wp-includes/class-wpdb.php | Gets blog prefix. |
| [\_n()](_n) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number. |
| [wpdb::delete()](../classes/wpdb/delete) wp-includes/class-wpdb.php | Deletes a row in the table. |
| [mysql2date()](mysql2date) wp-includes/functions.php | Converts given MySQL date string into a different format. |
| [wpdb::get\_row()](../classes/wpdb/get_row) wp-includes/class-wpdb.php | Retrieves one row from the database. |
| [add\_site\_option()](add_site_option) wp-includes/option.php | Adds a new option for the current network. |
| [get\_subdirectory\_reserved\_names()](get_subdirectory_reserved_names) wp-includes/ms-functions.php | Retrieves a list of reserved site on a sub-directory Multisite installation. |
| [username\_exists()](username_exists) wp-includes/user.php | Determines whether the given username exists. |
| [domain\_exists()](domain_exists) wp-includes/ms-functions.php | Checks whether a site name is already taken. |
| [wpdb::prepare()](../classes/wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| [get\_site\_option()](get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| [wpdb::get\_var()](../classes/wpdb/get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [number\_format\_i18n()](number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| [wp\_unslash()](wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../classes/wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [validate\_blog\_signup()](validate_blog_signup) wp-signup.php | Validates new site signup. |
| [validate\_blog\_form()](validate_blog_form) wp-signup.php | Validates the new site sign-up. |
| Version | Description |
| --- | --- |
| [MU (3.0.0)](https://developer.wordpress.org/reference/since/mu.3.0.0/) | Introduced. |
| programming_docs |
wordpress wp_transition_comment_status( string $new_status, string $old_status, WP_Comment $comment ) wp\_transition\_comment\_status( string $new\_status, string $old\_status, WP\_Comment $comment )
=================================================================================================
Calls hooks for when a comment status transition occurs.
Calls hooks for comment status transitions. If the new comment status is not the same as the previous comment status, then two hooks will be ran, the first is [‘transition\_comment\_status’](../hooks/transition_comment_status) with new status, old status, and comment data.
The next action called is [‘comment\_$old\_status\_to\_$new\_status’](../hooks/comment_old_status_to_new_status). It has the comment data.
The final action will run whether or not the comment statuses are the same.
The action is named [‘comment\_$new\_status\_$comment->comment\_type’](../hooks/comment_new_status_comment-comment_type).
`$new_status` string Required New comment status. `$old_status` string Required Previous comment status. `$comment` [WP\_Comment](../classes/wp_comment) Required Comment object. File: `wp-includes/comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/comment.php/)
```
function wp_transition_comment_status( $new_status, $old_status, $comment ) {
/*
* Translate raw statuses to human-readable formats for the hooks.
* This is not a complete list of comment status, it's only the ones
* that need to be renamed.
*/
$comment_statuses = array(
0 => 'unapproved',
'hold' => 'unapproved', // wp_set_comment_status() uses "hold".
1 => 'approved',
'approve' => 'approved', // wp_set_comment_status() uses "approve".
);
if ( isset( $comment_statuses[ $new_status ] ) ) {
$new_status = $comment_statuses[ $new_status ];
}
if ( isset( $comment_statuses[ $old_status ] ) ) {
$old_status = $comment_statuses[ $old_status ];
}
// Call the hooks.
if ( $new_status != $old_status ) {
/**
* Fires when the comment status is in transition.
*
* @since 2.7.0
*
* @param int|string $new_status The new comment status.
* @param int|string $old_status The old comment status.
* @param WP_Comment $comment Comment object.
*/
do_action( 'transition_comment_status', $new_status, $old_status, $comment );
/**
* Fires when the comment status is in transition from one specific status to another.
*
* The dynamic portions of the hook name, `$old_status`, and `$new_status`,
* refer to the old and new comment statuses, respectively.
*
* Possible hook names include:
*
* - `comment_unapproved_to_approved`
* - `comment_spam_to_approved`
* - `comment_approved_to_unapproved`
* - `comment_spam_to_unapproved`
* - `comment_unapproved_to_spam`
* - `comment_approved_to_spam`
*
* @since 2.7.0
*
* @param WP_Comment $comment Comment object.
*/
do_action( "comment_{$old_status}_to_{$new_status}", $comment );
}
/**
* Fires when the status of a specific comment type is in transition.
*
* The dynamic portions of the hook name, `$new_status`, and `$comment->comment_type`,
* refer to the new comment status, and the type of comment, respectively.
*
* Typical comment types include 'comment', 'pingback', or 'trackback'.
*
* Possible hook names include:
*
* - `comment_approved_comment`
* - `comment_approved_pingback`
* - `comment_approved_trackback`
* - `comment_unapproved_comment`
* - `comment_unapproved_pingback`
* - `comment_unapproved_trackback`
* - `comment_spam_comment`
* - `comment_spam_pingback`
* - `comment_spam_trackback`
*
* @since 2.7.0
*
* @param string $comment_ID The comment ID as a numeric string.
* @param WP_Comment $comment Comment object.
*/
do_action( "comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment );
}
```
[do\_action( "comment\_{$new\_status}\_{$comment->comment\_type}", string $comment\_ID, WP\_Comment $comment )](../hooks/comment_new_status_comment-comment_type)
Fires when the status of a specific comment type is in transition.
[do\_action( "comment\_{$old\_status}\_to\_{$new\_status}", WP\_Comment $comment )](../hooks/comment_old_status_to_new_status)
Fires when the comment status is in transition from one specific status to another.
[do\_action( 'transition\_comment\_status', int|string $new\_status, int|string $old\_status, WP\_Comment $comment )](../hooks/transition_comment_status)
Fires when the comment status is in transition.
| Uses | Description |
| --- | --- |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [wp\_set\_comment\_status()](wp_set_comment_status) wp-includes/comment.php | Sets the status of a comment. |
| [wp\_update\_comment()](wp_update_comment) wp-includes/comment.php | Updates an existing comment in the database. |
| [wp\_delete\_comment()](wp_delete_comment) wp-includes/comment.php | Trashes or deletes a comment. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress translate( string $text, string $domain = 'default' ): string translate( string $text, string $domain = 'default' ): string
=============================================================
Retrieves the translation of $text.
If there is no translation, or the text domain isn’t loaded, the original text is returned.
\_Note:\_ Don’t use [translate()](translate) directly, use [\_\_()](__) or related functions.
`$text` string Required Text to translate. `$domain` string Optional Text domain. Unique identifier for retrieving translated strings.
Default `'default'`. Default: `'default'`
string Translated text.
File: `wp-includes/l10n.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/l10n.php/)
```
function translate( $text, $domain = 'default' ) {
$translations = get_translations_for_domain( $domain );
$translation = $translations->translate( $text );
/**
* Filters text with its translation.
*
* @since 2.0.11
*
* @param string $translation Translated text.
* @param string $text Text to translate.
* @param string $domain Text domain. Unique identifier for retrieving translated strings.
*/
$translation = apply_filters( 'gettext', $translation, $text, $domain );
/**
* Filters text with its translation for a domain.
*
* The dynamic portion of the hook name, `$domain`, refers to the text domain.
*
* @since 5.5.0
*
* @param string $translation Translated text.
* @param string $text Text to translate.
* @param string $domain Text domain. Unique identifier for retrieving translated strings.
*/
$translation = apply_filters( "gettext_{$domain}", $translation, $text, $domain );
return $translation;
}
```
[apply\_filters( 'gettext', string $translation, string $text, string $domain )](../hooks/gettext)
Filters text with its translation.
[apply\_filters( "gettext\_{$domain}", string $translation, string $text, string $domain )](../hooks/gettext_domain)
Filters text with its translation for a domain.
| Uses | Description |
| --- | --- |
| [get\_translations\_for\_domain()](get_translations_for_domain) wp-includes/l10n.php | Returns the Translations instance for a text domain. |
| [Translations::translate()](../classes/translations/translate) wp-includes/pomo/translations.php | |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_credits\_section\_title()](wp_credits_section_title) wp-admin/includes/credits.php | Displays the title for a given group of contributors. |
| [wp\_credits\_section\_list()](wp_credits_section_list) wp-admin/includes/credits.php | Displays a list of contributors for a given group. |
| [\_get\_plugin\_data\_markup\_translate()](_get_plugin_data_markup_translate) wp-admin/includes/plugin.php | Sanitizes plugin data, optionally adds markup, optionally translates. |
| [wp\_get\_popular\_importers()](wp_get_popular_importers) wp-admin/includes/import.php | Returns a list from WordPress.org of popular importer plugins. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_attr\_\_()](esc_attr__) wp-includes/l10n.php | Retrieves the translation of $text and escapes it for safe use in an attribute. |
| [esc\_html\_\_()](esc_html__) wp-includes/l10n.php | Retrieves the translation of $text and escapes it for safe use in HTML output. |
| [\_e()](_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr\_e()](esc_attr_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in an attribute. |
| [esc\_html\_e()](esc_html_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in HTML output. |
| [\_c()](_c) wp-includes/deprecated.php | Retrieve translated string with vertical bar context |
| [translate\_with\_context()](translate_with_context) wp-includes/deprecated.php | Translates $text like [translate()](translate) , but assumes that the text contains a context after its last vertical bar. |
| [WP\_Theme::translate\_header()](../classes/wp_theme/translate_header) wp-includes/class-wp-theme.php | Translates a theme header. |
| [wp\_timezone\_choice()](wp_timezone_choice) wp-includes/functions.php | Gives a nicely-formatted list of timezone strings. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced gettext-{$domain} filter. |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Introduced. |
wordpress add_feed( string $feedname, callable $function ): string add\_feed( string $feedname, callable $function ): string
=========================================================
Adds a new feed type like /atom1/.
`$feedname` string Required Feed name. `$function` callable Required Callback to run on feed display. string Feed action name.
Requires one-time use of [flush\_rules()](../classes/wp_rewrite/flush_rules "Rewrite API/flush rules") to take effect.
File: `wp-includes/rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rewrite.php/)
```
function add_feed( $feedname, $function ) {
global $wp_rewrite;
if ( ! in_array( $feedname, $wp_rewrite->feeds, true ) ) {
$wp_rewrite->feeds[] = $feedname;
}
$hook = 'do_feed_' . $feedname;
// Remove default function hook.
remove_action( $hook, $hook );
add_action( $hook, $function, 10, 2 );
return $hook;
}
```
| Uses | Description |
| --- | --- |
| [remove\_action()](remove_action) wp-includes/plugin.php | Removes a callback function from an action hook. |
| [add\_action()](add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress wp_insert_user( array|object|WP_User $userdata ): int|WP_Error wp\_insert\_user( array|object|WP\_User $userdata ): int|WP\_Error
==================================================================
Inserts a user into the database.
Most of the `$userdata` array fields have filters associated with the values. Exceptions are ‘ID’, ‘rich\_editing’, ‘syntax\_highlighting’, ‘comment\_shortcuts’, ‘admin\_color’, ‘use\_ssl’, ‘user\_registered’, ‘user\_activation\_key’, ‘spam’, and ‘role’. The filters have the prefix ‘pre\_user\_’ followed by the field name. An example using ‘description’ would have the filter called ‘pre\_user\_description’ that can be hooked into.
`$userdata` array|object|[WP\_User](../classes/wp_user) Required An array, object, or [WP\_User](../classes/wp_user) object of user data arguments.
* `ID`intUser ID. If supplied, the user will be updated.
* `user_pass`stringThe plain-text user password.
* `user_login`stringThe user's login username.
* `user_nicename`stringThe URL-friendly user name.
* `user_url`stringThe user URL.
* `user_email`stringThe user email address.
* `display_name`stringThe user's display name.
Default is the user's username.
* `nickname`stringThe user's nickname.
Default is the user's username.
* `first_name`stringThe user's first name. For new users, will be used to build the first part of the user's display name if `$display_name` is not specified.
* `last_name`stringThe user's last name. For new users, will be used to build the second part of the user's display name if `$display_name` is not specified.
* `description`stringThe user's biographical description.
* `rich_editing`stringWhether to enable the rich-editor for the user.
Accepts `'true'` or `'false'` as a string literal, not boolean. Default `'true'`.
* `syntax_highlighting`stringWhether to enable the rich code editor for the user.
Accepts `'true'` or `'false'` as a string literal, not boolean. Default `'true'`.
* `comment_shortcuts`stringWhether to enable comment moderation keyboard shortcuts for the user. Accepts `'true'` or `'false'` as a string literal, not boolean. Default `'false'`.
* `admin_color`stringAdmin color scheme for the user. Default `'fresh'`.
* `use_ssl`boolWhether the user should always access the admin over https. Default false.
* `user_registered`stringDate the user registered in UTC. Format is 'Y-m-d H:i:s'.
* `user_activation_key`stringPassword reset key. Default empty.
* `spam`boolMultisite only. Whether the user is marked as spam.
Default false.
* `show_admin_bar_front`stringWhether to display the Admin Bar for the user on the site's front end. Accepts `'true'` or `'false'` as a string literal, not boolean. Default `'true'`.
* `role`stringUser's role.
* `locale`stringUser's locale. Default empty.
* `meta_input`arrayArray of custom user meta values keyed by meta key.
Default empty.
int|[WP\_Error](../classes/wp_error) The newly created user's ID or a [WP\_Error](../classes/wp_error) object if the user could not be created.
File: `wp-includes/user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/user.php/)
```
function wp_insert_user( $userdata ) {
global $wpdb;
if ( $userdata instanceof stdClass ) {
$userdata = get_object_vars( $userdata );
} elseif ( $userdata instanceof WP_User ) {
$userdata = $userdata->to_array();
}
// Are we updating or creating?
if ( ! empty( $userdata['ID'] ) ) {
$user_id = (int) $userdata['ID'];
$update = true;
$old_user_data = get_userdata( $user_id );
if ( ! $old_user_data ) {
return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
}
// Hashed in wp_update_user(), plaintext if called directly.
$user_pass = ! empty( $userdata['user_pass'] ) ? $userdata['user_pass'] : $old_user_data->user_pass;
} else {
$update = false;
// Hash the password.
$user_pass = wp_hash_password( $userdata['user_pass'] );
}
$sanitized_user_login = sanitize_user( $userdata['user_login'], true );
/**
* Filters a username after it has been sanitized.
*
* This filter is called before the user is created or updated.
*
* @since 2.0.3
*
* @param string $sanitized_user_login Username after it has been sanitized.
*/
$pre_user_login = apply_filters( 'pre_user_login', $sanitized_user_login );
// Remove any non-printable chars from the login string to see if we have ended up with an empty username.
$user_login = trim( $pre_user_login );
// user_login must be between 0 and 60 characters.
if ( empty( $user_login ) ) {
return new WP_Error( 'empty_user_login', __( 'Cannot create a user with an empty login name.' ) );
} elseif ( mb_strlen( $user_login ) > 60 ) {
return new WP_Error( 'user_login_too_long', __( 'Username may not be longer than 60 characters.' ) );
}
if ( ! $update && username_exists( $user_login ) ) {
return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
}
/**
* Filters the list of disallowed usernames.
*
* @since 4.4.0
*
* @param array $usernames Array of disallowed usernames.
*/
$illegal_logins = (array) apply_filters( 'illegal_user_logins', array() );
if ( in_array( strtolower( $user_login ), array_map( 'strtolower', $illegal_logins ), true ) ) {
return new WP_Error( 'invalid_username', __( 'Sorry, that username is not allowed.' ) );
}
/*
* If a nicename is provided, remove unsafe user characters before using it.
* Otherwise build a nicename from the user_login.
*/
if ( ! empty( $userdata['user_nicename'] ) ) {
$user_nicename = sanitize_user( $userdata['user_nicename'], true );
} else {
$user_nicename = mb_substr( $user_login, 0, 50 );
}
$user_nicename = sanitize_title( $user_nicename );
/**
* Filters a user's nicename before the user is created or updated.
*
* @since 2.0.3
*
* @param string $user_nicename The user's nicename.
*/
$user_nicename = apply_filters( 'pre_user_nicename', $user_nicename );
if ( mb_strlen( $user_nicename ) > 50 ) {
return new WP_Error( 'user_nicename_too_long', __( 'Nicename may not be longer than 50 characters.' ) );
}
$user_nicename_check = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1", $user_nicename, $user_login ) );
if ( $user_nicename_check ) {
$suffix = 2;
while ( $user_nicename_check ) {
// user_nicename allows 50 chars. Subtract one for a hyphen, plus the length of the suffix.
$base_length = 49 - mb_strlen( $suffix );
$alt_user_nicename = mb_substr( $user_nicename, 0, $base_length ) . "-$suffix";
$user_nicename_check = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1", $alt_user_nicename, $user_login ) );
$suffix++;
}
$user_nicename = $alt_user_nicename;
}
$raw_user_email = empty( $userdata['user_email'] ) ? '' : $userdata['user_email'];
/**
* Filters a user's email before the user is created or updated.
*
* @since 2.0.3
*
* @param string $raw_user_email The user's email.
*/
$user_email = apply_filters( 'pre_user_email', $raw_user_email );
/*
* If there is no update, just check for `email_exists`. If there is an update,
* check if current email and new email are the same, and check `email_exists`
* accordingly.
*/
if ( ( ! $update || ( ! empty( $old_user_data ) && 0 !== strcasecmp( $user_email, $old_user_data->user_email ) ) )
&& ! defined( 'WP_IMPORTING' )
&& email_exists( $user_email )
) {
return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
}
$raw_user_url = empty( $userdata['user_url'] ) ? '' : $userdata['user_url'];
/**
* Filters a user's URL before the user is created or updated.
*
* @since 2.0.3
*
* @param string $raw_user_url The user's URL.
*/
$user_url = apply_filters( 'pre_user_url', $raw_user_url );
if ( mb_strlen( $user_url ) > 100 ) {
return new WP_Error( 'user_url_too_long', __( 'User URL may not be longer than 100 characters.' ) );
}
$user_registered = empty( $userdata['user_registered'] ) ? gmdate( 'Y-m-d H:i:s' ) : $userdata['user_registered'];
$user_activation_key = empty( $userdata['user_activation_key'] ) ? '' : $userdata['user_activation_key'];
if ( ! empty( $userdata['spam'] ) && ! is_multisite() ) {
return new WP_Error( 'no_spam', __( 'Sorry, marking a user as spam is only supported on Multisite.' ) );
}
$spam = empty( $userdata['spam'] ) ? 0 : (bool) $userdata['spam'];
// Store values to save in user meta.
$meta = array();
$nickname = empty( $userdata['nickname'] ) ? $user_login : $userdata['nickname'];
/**
* Filters a user's nickname before the user is created or updated.
*
* @since 2.0.3
*
* @param string $nickname The user's nickname.
*/
$meta['nickname'] = apply_filters( 'pre_user_nickname', $nickname );
$first_name = empty( $userdata['first_name'] ) ? '' : $userdata['first_name'];
/**
* Filters a user's first name before the user is created or updated.
*
* @since 2.0.3
*
* @param string $first_name The user's first name.
*/
$meta['first_name'] = apply_filters( 'pre_user_first_name', $first_name );
$last_name = empty( $userdata['last_name'] ) ? '' : $userdata['last_name'];
/**
* Filters a user's last name before the user is created or updated.
*
* @since 2.0.3
*
* @param string $last_name The user's last name.
*/
$meta['last_name'] = apply_filters( 'pre_user_last_name', $last_name );
if ( empty( $userdata['display_name'] ) ) {
if ( $update ) {
$display_name = $user_login;
} elseif ( $meta['first_name'] && $meta['last_name'] ) {
$display_name = sprintf(
/* translators: 1: User's first name, 2: Last name. */
_x( '%1$s %2$s', 'Display name based on first name and last name' ),
$meta['first_name'],
$meta['last_name']
);
} elseif ( $meta['first_name'] ) {
$display_name = $meta['first_name'];
} elseif ( $meta['last_name'] ) {
$display_name = $meta['last_name'];
} else {
$display_name = $user_login;
}
} else {
$display_name = $userdata['display_name'];
}
/**
* Filters a user's display name before the user is created or updated.
*
* @since 2.0.3
*
* @param string $display_name The user's display name.
*/
$display_name = apply_filters( 'pre_user_display_name', $display_name );
$description = empty( $userdata['description'] ) ? '' : $userdata['description'];
/**
* Filters a user's description before the user is created or updated.
*
* @since 2.0.3
*
* @param string $description The user's description.
*/
$meta['description'] = apply_filters( 'pre_user_description', $description );
$meta['rich_editing'] = empty( $userdata['rich_editing'] ) ? 'true' : $userdata['rich_editing'];
$meta['syntax_highlighting'] = empty( $userdata['syntax_highlighting'] ) ? 'true' : $userdata['syntax_highlighting'];
$meta['comment_shortcuts'] = empty( $userdata['comment_shortcuts'] ) || 'false' === $userdata['comment_shortcuts'] ? 'false' : 'true';
$admin_color = empty( $userdata['admin_color'] ) ? 'fresh' : $userdata['admin_color'];
$meta['admin_color'] = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $admin_color );
$meta['use_ssl'] = empty( $userdata['use_ssl'] ) ? 0 : (bool) $userdata['use_ssl'];
$meta['show_admin_bar_front'] = empty( $userdata['show_admin_bar_front'] ) ? 'true' : $userdata['show_admin_bar_front'];
$meta['locale'] = isset( $userdata['locale'] ) ? $userdata['locale'] : '';
$compacted = compact( 'user_pass', 'user_nicename', 'user_email', 'user_url', 'user_registered', 'user_activation_key', 'display_name' );
$data = wp_unslash( $compacted );
if ( ! $update ) {
$data = $data + compact( 'user_login' );
}
if ( is_multisite() ) {
$data = $data + compact( 'spam' );
}
/**
* Filters user data before the record is created or updated.
*
* It only includes data in the users table, not any user metadata.
*
* @since 4.9.0
* @since 5.8.0 The `$userdata` parameter was added.
*
* @param array $data {
* Values and keys for the user.
*
* @type string $user_login The user's login. Only included if $update == false
* @type string $user_pass The user's password.
* @type string $user_email The user's email.
* @type string $user_url The user's url.
* @type string $user_nicename The user's nice name. Defaults to a URL-safe version of user's login
* @type string $display_name The user's display name.
* @type string $user_registered MySQL timestamp describing the moment when the user registered. Defaults to
* the current UTC timestamp.
* }
* @param bool $update Whether the user is being updated rather than created.
* @param int|null $user_id ID of the user to be updated, or NULL if the user is being created.
* @param array $userdata The raw array of data passed to wp_insert_user().
*/
$data = apply_filters( 'wp_pre_insert_user_data', $data, $update, ( $update ? $user_id : null ), $userdata );
if ( empty( $data ) || ! is_array( $data ) ) {
return new WP_Error( 'empty_data', __( 'Not enough data to create this user.' ) );
}
if ( $update ) {
if ( $user_email !== $old_user_data->user_email || $user_pass !== $old_user_data->user_pass ) {
$data['user_activation_key'] = '';
}
$wpdb->update( $wpdb->users, $data, array( 'ID' => $user_id ) );
} else {
$wpdb->insert( $wpdb->users, $data );
$user_id = (int) $wpdb->insert_id;
}
$user = new WP_User( $user_id );
/**
* Filters a user's meta values and keys immediately after the user is created or updated
* and before any user meta is inserted or updated.
*
* Does not include contact methods. These are added using `wp_get_user_contact_methods( $user )`.
*
* For custom meta fields, see the {@see 'insert_custom_user_meta'} filter.
*
* @since 4.4.0
* @since 5.8.0 The `$userdata` parameter was added.
*
* @param array $meta {
* Default meta values and keys for the user.
*
* @type string $nickname The user's nickname. Default is the user's username.
* @type string $first_name The user's first name.
* @type string $last_name The user's last name.
* @type string $description The user's description.
* @type string $rich_editing Whether to enable the rich-editor for the user. Default 'true'.
* @type string $syntax_highlighting Whether to enable the rich code editor for the user. Default 'true'.
* @type string $comment_shortcuts Whether to enable keyboard shortcuts for the user. Default 'false'.
* @type string $admin_color The color scheme for a user's admin screen. Default 'fresh'.
* @type int|bool $use_ssl Whether to force SSL on the user's admin area. 0|false if SSL
* is not forced.
* @type string $show_admin_bar_front Whether to show the admin bar on the front end for the user.
* Default 'true'.
* @type string $locale User's locale. Default empty.
* }
* @param WP_User $user User object.
* @param bool $update Whether the user is being updated rather than created.
* @param array $userdata The raw array of data passed to wp_insert_user().
*/
$meta = apply_filters( 'insert_user_meta', $meta, $user, $update, $userdata );
$custom_meta = array();
if ( array_key_exists( 'meta_input', $userdata ) && is_array( $userdata['meta_input'] ) && ! empty( $userdata['meta_input'] ) ) {
$custom_meta = $userdata['meta_input'];
}
/**
* Filters a user's custom meta values and keys immediately after the user is created or updated
* and before any user meta is inserted or updated.
*
* For non-custom meta fields, see the {@see 'insert_user_meta'} filter.
*
* @since 5.9.0
*
* @param array $custom_meta Array of custom user meta values keyed by meta key.
* @param WP_User $user User object.
* @param bool $update Whether the user is being updated rather than created.
* @param array $userdata The raw array of data passed to wp_insert_user().
*/
$custom_meta = apply_filters( 'insert_custom_user_meta', $custom_meta, $user, $update, $userdata );
$meta = array_merge( $meta, $custom_meta );
// Update user meta.
foreach ( $meta as $key => $value ) {
update_user_meta( $user_id, $key, $value );
}
foreach ( wp_get_user_contact_methods( $user ) as $key => $value ) {
if ( isset( $userdata[ $key ] ) ) {
update_user_meta( $user_id, $key, $userdata[ $key ] );
}
}
if ( isset( $userdata['role'] ) ) {
$user->set_role( $userdata['role'] );
} elseif ( ! $update ) {
$user->set_role( get_option( 'default_role' ) );
}
clean_user_cache( $user_id );
if ( $update ) {
/**
* Fires immediately after an existing user is updated.
*
* @since 2.0.0
* @since 5.8.0 The `$userdata` parameter was added.
*
* @param int $user_id User ID.
* @param WP_User $old_user_data Object containing user's data prior to update.
* @param array $userdata The raw array of data passed to wp_insert_user().
*/
do_action( 'profile_update', $user_id, $old_user_data, $userdata );
if ( isset( $userdata['spam'] ) && $userdata['spam'] != $old_user_data->spam ) {
if ( 1 == $userdata['spam'] ) {
/**
* Fires after the user is marked as a SPAM user.
*
* @since 3.0.0
*
* @param int $user_id ID of the user marked as SPAM.
*/
do_action( 'make_spam_user', $user_id );
} else {
/**
* Fires after the user is marked as a HAM user. Opposite of SPAM.
*
* @since 3.0.0
*
* @param int $user_id ID of the user marked as HAM.
*/
do_action( 'make_ham_user', $user_id );
}
}
} else {
/**
* Fires immediately after a new user is registered.
*
* @since 1.5.0
* @since 5.8.0 The `$userdata` parameter was added.
*
* @param int $user_id User ID.
* @param array $userdata The raw array of data passed to wp_insert_user().
*/
do_action( 'user_register', $user_id, $userdata );
}
return $user_id;
}
```
[apply\_filters( 'illegal\_user\_logins', array $usernames )](../hooks/illegal_user_logins)
Filters the list of disallowed usernames.
[apply\_filters( 'insert\_custom\_user\_meta', array $custom\_meta, WP\_User $user, bool $update, array $userdata )](../hooks/insert_custom_user_meta)
Filters a user’s custom meta values and keys immediately after the user is created or updated and before any user meta is inserted or updated.
[apply\_filters( 'insert\_user\_meta', array $meta, WP\_User $user, bool $update, array $userdata )](../hooks/insert_user_meta)
Filters a user’s meta values and keys immediately after the user is created or updated and before any user meta is inserted or updated.
[do\_action( 'make\_ham\_user', int $user\_id )](../hooks/make_ham_user)
Fires after the user is marked as a HAM user. Opposite of SPAM.
[do\_action( 'make\_spam\_user', int $user\_id )](../hooks/make_spam_user)
Fires after the user is marked as a SPAM user.
[apply\_filters( 'pre\_user\_description', string $description )](../hooks/pre_user_description)
Filters a user’s description before the user is created or updated.
[apply\_filters( 'pre\_user\_display\_name', string $display\_name )](../hooks/pre_user_display_name)
Filters a user’s display name before the user is created or updated.
[apply\_filters( 'pre\_user\_email', string $raw\_user\_email )](../hooks/pre_user_email)
Filters a user’s email before the user is created or updated.
[apply\_filters( 'pre\_user\_first\_name', string $first\_name )](../hooks/pre_user_first_name)
Filters a user’s first name before the user is created or updated.
[apply\_filters( 'pre\_user\_last\_name', string $last\_name )](../hooks/pre_user_last_name)
Filters a user’s last name before the user is created or updated.
[apply\_filters( 'pre\_user\_login', string $sanitized\_user\_login )](../hooks/pre_user_login)
Filters a username after it has been sanitized.
[apply\_filters( 'pre\_user\_nicename', string $user\_nicename )](../hooks/pre_user_nicename)
Filters a user’s nicename before the user is created or updated.
[apply\_filters( 'pre\_user\_nickname', string $nickname )](../hooks/pre_user_nickname)
Filters a user’s nickname before the user is created or updated.
[apply\_filters( 'pre\_user\_url', string $raw\_user\_url )](../hooks/pre_user_url)
Filters a user’s URL before the user is created or updated.
[do\_action( 'profile\_update', int $user\_id, WP\_User $old\_user\_data, array $userdata )](../hooks/profile_update)
Fires immediately after an existing user is updated.
[do\_action( 'user\_register', int $user\_id, array $userdata )](../hooks/user_register)
Fires immediately after a new user is registered.
[apply\_filters( 'wp\_pre\_insert\_user\_data', array $data, bool $update, int|null $user\_id, array $userdata )](../hooks/wp_pre_insert_user_data)
Filters user data before the record is created or updated.
| Uses | Description |
| --- | --- |
| [WP\_User::\_\_construct()](../classes/wp_user/__construct) wp-includes/class-wp-user.php | Constructor. |
| [username\_exists()](username_exists) wp-includes/user.php | Determines whether the given username exists. |
| [wpdb::insert()](../classes/wpdb/insert) wp-includes/class-wpdb.php | Inserts a row into the table. |
| [sanitize\_user()](sanitize_user) wp-includes/formatting.php | Sanitizes a username, stripping out unsafe characters. |
| [sanitize\_title()](sanitize_title) wp-includes/formatting.php | Sanitizes a string into a slug, which can be used in URLs or HTML attributes. |
| [wp\_hash\_password()](wp_hash_password) wp-includes/pluggable.php | Creates a hash (encrypt) of a plain text password. |
| [wpdb::update()](../classes/wpdb/update) wp-includes/class-wpdb.php | Updates a row in the table. |
| [update\_user\_meta()](update_user_meta) wp-includes/user.php | Updates user meta field based on user ID. |
| [clean\_user\_cache()](clean_user_cache) wp-includes/user.php | Cleans all user caches. |
| [email\_exists()](email_exists) wp-includes/user.php | Determines whether the given email exists. |
| [wp\_get\_user\_contact\_methods()](wp_get_user_contact_methods) wp-includes/user.php | Sets up the user contact methods. |
| [wpdb::prepare()](../classes/wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| [wpdb::get\_var()](../classes/wpdb/get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_multisite()](is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [get\_userdata()](get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [wp\_unslash()](wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [\_x()](_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [WP\_Error::\_\_construct()](../classes/wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Users\_Controller::create\_item()](../classes/wp_rest_users_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Creates a single user. |
| [edit\_user()](edit_user) wp-admin/includes/user.php | Edit user settings based on contents of $\_POST |
| [wp\_update\_user()](wp_update_user) wp-includes/user.php | Updates a user in the database. |
| [wp\_create\_user()](wp_create_user) wp-includes/user.php | Provides a simpler way of inserting a user into the database. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | The `meta_input` field can be passed to `$userdata` to allow addition of user meta data. |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | The `spam` field can be passed to `$userdata` (Multisite only). |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | The `locale` field can be passed to `$userdata`. |
| [3.6.0](https://developer.wordpress.org/reference/since/3.6.0/) | The `aim`, `jabber`, and `yim` fields were removed as default user contact methods for new installations. See [wp\_get\_user\_contact\_methods()](wp_get_user_contact_methods) . |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
| programming_docs |
wordpress wp_ajax_rest_nonce() wp\_ajax\_rest\_nonce()
=======================
Ajax handler to renew the REST API nonce.
File: `wp-admin/includes/ajax-actions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/ajax-actions.php/)
```
function wp_ajax_rest_nonce() {
exit( wp_create_nonce( 'wp_rest' ) );
}
```
| Uses | Description |
| --- | --- |
| [wp\_create\_nonce()](wp_create_nonce) wp-includes/pluggable.php | Creates a cryptographic token tied to a specific action, user, user session, and window of time. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress wp_html_excerpt( string $str, int $count, string $more = null ): string wp\_html\_excerpt( string $str, int $count, string $more = null ): string
=========================================================================
Safely extracts not more than the first $count characters from HTML string.
UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT* be counted as one character. For example & will be counted as 4, < as 3, etc.
`$str` string Required String to get the excerpt from. `$count` int Required Maximum number of characters to take. `$more` string Optional What to append if $str needs to be trimmed. Defaults to empty string. Default: `null`
string The excerpt.
File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function wp_html_excerpt( $str, $count, $more = null ) {
if ( null === $more ) {
$more = '';
}
$str = wp_strip_all_tags( $str, true );
$excerpt = mb_substr( $str, 0, $count );
// Remove part of an entity at the end.
$excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
if ( $str != $excerpt ) {
$excerpt = trim( $excerpt ) . $more;
}
return $excerpt;
}
```
| Uses | Description |
| --- | --- |
| [wp\_strip\_all\_tags()](wp_strip_all_tags) wp-includes/formatting.php | Properly strips all HTML tags including script and style |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menus::customize\_register()](../classes/wp_customize_nav_menus/customize_register) wp-includes/class-wp-customize-nav-menus.php | Adds the customizer settings and controls. |
| [get\_media\_item()](get_media_item) wp-admin/includes/media.php | Retrieves HTML form for modifying the image attachment. |
| [WP\_Comments\_List\_Table::column\_author()](../classes/wp_comments_list_table/column_author) wp-admin/includes/class-wp-comments-list-table.php | |
| [wp\_admin\_bar\_site\_menu()](wp_admin_bar_site_menu) wp-includes/admin-bar.php | Adds the “Site Name” menu. |
| [do\_trackbacks()](do_trackbacks) wp-includes/comment.php | Performs trackbacks. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress clean_attachment_cache( int $id, bool $clean_terms = false ) clean\_attachment\_cache( int $id, bool $clean\_terms = false )
===============================================================
Will clean the attachment in the cache.
Cleaning means delete from the cache. Optionally will clean the term object cache associated with the attachment ID.
This function will not run if $\_wp\_suspend\_cache\_invalidation is not empty.
`$id` int Required The attachment ID in the cache to clean. `$clean_terms` bool Optional Whether to clean terms cache. Default: `false`
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function clean_attachment_cache( $id, $clean_terms = false ) {
global $_wp_suspend_cache_invalidation;
if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
return;
}
$id = (int) $id;
wp_cache_delete( $id, 'posts' );
wp_cache_delete( $id, 'post_meta' );
if ( $clean_terms ) {
clean_object_term_cache( $id, 'attachment' );
}
/**
* Fires after the given attachment's cache is cleaned.
*
* @since 3.0.0
*
* @param int $id Attachment ID.
*/
do_action( 'clean_attachment_cache', $id );
}
```
[do\_action( 'clean\_attachment\_cache', int $id )](../hooks/clean_attachment_cache)
Fires after the given attachment’s cache is cleaned.
| Uses | Description |
| --- | --- |
| [wp\_cache\_delete()](wp_cache_delete) wp-includes/cache.php | Removes the cache contents matching key and group. |
| [clean\_object\_term\_cache()](clean_object_term_cache) wp-includes/taxonomy.php | Removes the taxonomy relationship to terms from the cache. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [wp\_media\_attach\_action()](wp_media_attach_action) wp-admin/includes/media.php | Encapsulates the logic for Attach/Detach actions. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress human_readable_duration( string $duration = '' ): string|false human\_readable\_duration( string $duration = '' ): string|false
================================================================
Converts a duration to human readable format.
`$duration` string Optional Duration will be in string format (HH:ii:ss) OR (ii:ss), with a possible prepended negative sign (-). Default: `''`
string|false A human readable duration string, false on failure.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function human_readable_duration( $duration = '' ) {
if ( ( empty( $duration ) || ! is_string( $duration ) ) ) {
return false;
}
$duration = trim( $duration );
// Remove prepended negative sign.
if ( '-' === substr( $duration, 0, 1 ) ) {
$duration = substr( $duration, 1 );
}
// Extract duration parts.
$duration_parts = array_reverse( explode( ':', $duration ) );
$duration_count = count( $duration_parts );
$hour = null;
$minute = null;
$second = null;
if ( 3 === $duration_count ) {
// Validate HH:ii:ss duration format.
if ( ! ( (bool) preg_match( '/^([0-9]+):([0-5]?[0-9]):([0-5]?[0-9])$/', $duration ) ) ) {
return false;
}
// Three parts: hours, minutes & seconds.
list( $second, $minute, $hour ) = $duration_parts;
} elseif ( 2 === $duration_count ) {
// Validate ii:ss duration format.
if ( ! ( (bool) preg_match( '/^([0-5]?[0-9]):([0-5]?[0-9])$/', $duration ) ) ) {
return false;
}
// Two parts: minutes & seconds.
list( $second, $minute ) = $duration_parts;
} else {
return false;
}
$human_readable_duration = array();
// Add the hour part to the string.
if ( is_numeric( $hour ) ) {
/* translators: %s: Time duration in hour or hours. */
$human_readable_duration[] = sprintf( _n( '%s hour', '%s hours', $hour ), (int) $hour );
}
// Add the minute part to the string.
if ( is_numeric( $minute ) ) {
/* translators: %s: Time duration in minute or minutes. */
$human_readable_duration[] = sprintf( _n( '%s minute', '%s minutes', $minute ), (int) $minute );
}
// Add the second part to the string.
if ( is_numeric( $second ) ) {
/* translators: %s: Time duration in second or seconds. */
$human_readable_duration[] = sprintf( _n( '%s second', '%s seconds', $second ), (int) $second );
}
return implode( ', ', $human_readable_duration );
}
```
| Uses | Description |
| --- | --- |
| [\_n()](_n) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number. |
| Used By | Description |
| --- | --- |
| [wp\_prepare\_attachment\_for\_js()](wp_prepare_attachment_for_js) wp-includes/media.php | Prepares an attachment post object for JS, where it is expected to be JSON-encoded and fit into an Attachment model. |
| Version | Description |
| --- | --- |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | Introduced. |
wordpress wp_remote_retrieve_response_message( array|WP_Error $response ): string wp\_remote\_retrieve\_response\_message( array|WP\_Error $response ): string
============================================================================
Retrieve only the response message from the raw response.
Will return an empty string if incorrect parameter value is given.
`$response` array|[WP\_Error](../classes/wp_error) Required HTTP response. string The response message. Empty string if incorrect parameter given.
File: `wp-includes/http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/http.php/)
```
function wp_remote_retrieve_response_message( $response ) {
if ( is_wp_error( $response ) || ! isset( $response['response'] ) || ! is_array( $response['response'] ) ) {
return '';
}
return $response['response']['message'];
}
```
| Uses | Description |
| --- | --- |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::check\_for\_page\_caching()](../classes/wp_site_health/check_for_page_caching) wp-admin/includes/class-wp-site-health.php | Checks if site has page cache enabled or not. |
| [wp\_update\_https\_detection\_errors()](wp_update_https_detection_errors) wp-includes/https-detection.php | Runs a remote HTTPS request to detect whether HTTPS supported, and stores potential errors. |
| [WP\_Site\_Health::get\_test\_rest\_availability()](../classes/wp_site_health/get_test_rest_availability) wp-admin/includes/class-wp-site-health.php | Tests if the REST API is accessible. |
| [download\_url()](download_url) wp-admin/includes/file.php | Downloads a URL to a local temporary file using the WordPress HTTP API. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress new_user_email_admin_notice() new\_user\_email\_admin\_notice()
=================================
Adds an admin notice alerting the user to check for confirmation request email after email address change.
File: `wp-includes/user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/user.php/)
```
function new_user_email_admin_notice() {
global $pagenow;
if ( 'profile.php' === $pagenow && isset( $_GET['updated'] ) ) {
$email = get_user_meta( get_current_user_id(), '_new_email', true );
if ( $email ) {
/* translators: %s: New email address. */
echo '<div class="notice notice-info"><p>' . sprintf( __( 'Your email address has not been updated yet. Please check your inbox at %s for a confirmation email.' ), '<code>' . esc_html( $email['newemail'] ) . '</code>' ) . '</p></div>';
}
}
}
```
| Uses | Description |
| --- | --- |
| [get\_user\_meta()](get_user_meta) wp-includes/user.php | Retrieves user meta field for a user. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [get\_current\_user\_id()](get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | This function was moved from wp-admin/includes/ms.php so it's no longer Multisite specific. |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress wp_is_json_media_type( string $media_type ): bool wp\_is\_json\_media\_type( string $media\_type ): bool
======================================================
Checks whether a string is a valid JSON Media Type.
`$media_type` string Required A Media Type string to check. bool True if string is a valid JSON Media Type.
File: `wp-includes/load.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/load.php/)
```
function wp_is_json_media_type( $media_type ) {
static $cache = array();
if ( ! isset( $cache[ $media_type ] ) ) {
$cache[ $media_type ] = (bool) preg_match( '/(^|\s|,)application\/([\w!#\$&-\^\.\+]+\+)?json(\+oembed)?($|\s|;|,)/i', $media_type );
}
return $cache[ $media_type ];
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Request::is\_json\_content\_type()](../classes/wp_rest_request/is_json_content_type) wp-includes/rest-api/class-wp-rest-request.php | Checks if the request has specified a JSON content-type. |
| [wp\_is\_json\_request()](wp_is_json_request) wp-includes/load.php | Checks whether current request is a JSON request, or is expecting a JSON response. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress wp_not_installed() wp\_not\_installed()
====================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Redirect to the installer if WordPress is not installed.
Dies with an error message when Multisite is enabled.
File: `wp-includes/load.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/load.php/)
```
function wp_not_installed() {
if ( is_blog_installed() || wp_installing() ) {
return;
}
nocache_headers();
if ( is_multisite() ) {
wp_die( __( 'The site you have requested is not installed properly. Please contact the system administrator.' ) );
}
require ABSPATH . WPINC . '/kses.php';
require ABSPATH . WPINC . '/pluggable.php';
$link = wp_guess_url() . '/wp-admin/install.php';
wp_redirect( $link );
die();
}
```
| Uses | Description |
| --- | --- |
| [wp\_installing()](wp_installing) wp-includes/load.php | Check or set whether WordPress is in “installation” mode. |
| [wp\_redirect()](wp_redirect) wp-includes/pluggable.php | Redirects to another page. |
| [wp\_guess\_url()](wp_guess_url) wp-includes/functions.php | Guesses the URL for the site. |
| [is\_blog\_installed()](is_blog_installed) wp-includes/functions.php | Determines whether WordPress is already installed. |
| [nocache\_headers()](nocache_headers) wp-includes/functions.php | Sets the headers to prevent caching for the different browsers. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_multisite()](is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [wp\_die()](wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress get_comment_delimited_block_content( string|null $block_name, array $block_attributes, string $block_content ): string get\_comment\_delimited\_block\_content( string|null $block\_name, array $block\_attributes, string $block\_content ): string
=============================================================================================================================
Returns the content of a block, including comment delimiters.
`$block_name` string|null Required Block name. Null if the block name is unknown, e.g. Classic blocks have their name set to null. `$block_attributes` array Required Block attributes. `$block_content` string Required Block save content. string Comment-delimited block content.
File: `wp-includes/blocks.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/blocks.php/)
```
function get_comment_delimited_block_content( $block_name, $block_attributes, $block_content ) {
if ( is_null( $block_name ) ) {
return $block_content;
}
$serialized_block_name = strip_core_block_namespace( $block_name );
$serialized_attributes = empty( $block_attributes ) ? '' : serialize_block_attributes( $block_attributes ) . ' ';
if ( empty( $block_content ) ) {
return sprintf( '<!-- wp:%s %s/-->', $serialized_block_name, $serialized_attributes );
}
return sprintf(
'<!-- wp:%s %s-->%s<!-- /wp:%s -->',
$serialized_block_name,
$serialized_attributes,
$block_content,
$serialized_block_name
);
}
```
| Uses | Description |
| --- | --- |
| [strip\_core\_block\_namespace()](strip_core_block_namespace) wp-includes/blocks.php | Returns the block name to use for serialization. This will remove the default “core/” namespace from a block name. |
| [serialize\_block\_attributes()](serialize_block_attributes) wp-includes/blocks.php | Given an array of attributes, returns a string in the serialized attributes format prepared for post content. |
| Used By | Description |
| --- | --- |
| [serialize\_block()](serialize_block) wp-includes/blocks.php | Returns the content of a block, including comment delimiters, serializing all attributes from the given parsed block. |
| Version | Description |
| --- | --- |
| [5.3.1](https://developer.wordpress.org/reference/since/5.3.1/) | Introduced. |
wordpress is_multisite(): bool is\_multisite(): bool
=====================
If Multisite is enabled.
bool True if Multisite is enabled, false otherwise.
##### Usage
```
if ( is_multisite() ) { echo 'Multisite is enabled'; }
```
File: `wp-includes/load.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/load.php/)
```
function is_multisite() {
if ( defined( 'MULTISITE' ) ) {
return MULTISITE;
}
if ( defined( 'SUBDOMAIN_INSTALL' ) || defined( 'VHOST' ) || defined( 'SUNRISE' ) ) {
return true;
}
return false;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::should\_suggest\_persistent\_object\_cache()](../classes/wp_site_health/should_suggest_persistent_object_cache) wp-admin/includes/class-wp-site-health.php | Determines whether to suggest using a persistent object cache. |
| [wp\_maybe\_update\_user\_counts()](wp_maybe_update_user_counts) wp-includes/user.php | Updates the total count of users on the site if live user counting is enabled. |
| [wp\_update\_user\_counts()](wp_update_user_counts) wp-includes/user.php | Updates the total count of users on the site. |
| [wp\_is\_large\_user\_count()](wp_is_large_user_count) wp-includes/user.php | Determines whether the site has a large number of users. |
| [deactivated\_plugins\_notice()](deactivated_plugins_notice) wp-admin/includes/plugin.php | Renders an admin notice when a plugin was deactivated during an update. |
| [WP\_REST\_Site\_Health\_Controller::register\_routes()](../classes/wp_rest_site_health_controller/register_routes) wp-includes/rest-api/endpoints/class-wp-rest-site-health-controller.php | Registers API routes. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](../classes/wp_rest_application_passwords_controller/get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [WP\_REST\_Plugins\_Controller::plugin\_status\_permission\_check()](../classes/wp_rest_plugins_controller/plugin_status_permission_check) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Handle updating a plugin’s status. |
| [WP\_REST\_Plugins\_Controller::handle\_plugin\_status()](../classes/wp_rest_plugins_controller/handle_plugin_status) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Handle updating a plugin’s status. |
| [WP\_REST\_Plugins\_Controller::get\_item\_schema()](../classes/wp_rest_plugins_controller/get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Retrieves the plugin’s schema, conforming to JSON Schema. |
| [WP\_REST\_Plugins\_Controller::get\_collection\_params()](../classes/wp_rest_plugins_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Retrieves the query params for the collections. |
| [WP\_REST\_Plugins\_Controller::check\_read\_permission()](../classes/wp_rest_plugins_controller/check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if the given plugin can be viewed by the current user. |
| [WP\_REST\_Plugins\_Controller::register\_routes()](../classes/wp_rest_plugins_controller/register_routes) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Registers the routes for the plugins controller. |
| [wp\_maybe\_grant\_site\_health\_caps()](wp_maybe_grant_site_health_caps) wp-includes/capabilities.php | Filters the user capabilities to grant the ‘view\_site\_health\_checks’ capabilities as necessary. |
| [WP\_Recovery\_Mode::is\_network\_plugin()](../classes/wp_recovery_mode/is_network_plugin) wp-includes/class-wp-recovery-mode.php | Checks whether the given extension a network activated plugin. |
| [WP\_Fatal\_Error\_Handler::display\_default\_error\_template()](../classes/wp_fatal_error_handler/display_default_error_template) wp-includes/class-wp-fatal-error-handler.php | Displays the default PHP error template. |
| [WP\_Fatal\_Error\_Handler::handle()](../classes/wp_fatal_error_handler/handle) wp-includes/class-wp-fatal-error-handler.php | Runs the shutdown handler. |
| [WP\_Debug\_Data::debug\_data()](../classes/wp_debug_data/debug_data) wp-admin/includes/class-wp-debug-data.php | Static function for generating site debug data when required. |
| [WP\_Site\_Health::get\_test\_plugin\_version()](../classes/wp_site_health/get_test_plugin_version) wp-admin/includes/class-wp-site-health.php | Tests if plugins are outdated, or unnecessary. |
| [WP\_Site\_Health::get\_test\_theme\_version()](../classes/wp_site_health/get_test_theme_version) wp-admin/includes/class-wp-site-health.php | Tests if themes are outdated, or unnecessary. |
| [WP\_Site\_Health\_Auto\_Updates::test\_wp\_version\_check\_attached()](../classes/wp_site_health_auto_updates/test_wp_version_check_attached) wp-admin/includes/class-wp-site-health-auto-updates.php | Checks if updates are intercepted by a filter. |
| [wp\_ajax\_health\_check\_get\_sizes()](wp_ajax_health_check_get_sizes) wp-admin/includes/ajax-actions.php | Ajax handler for site health check to get directories and database sizes. |
| [is\_site\_meta\_supported()](is_site_meta_supported) wp-includes/functions.php | Determines whether site meta is enabled. |
| [populate\_network\_meta()](populate_network_meta) wp-admin/includes/schema.php | Creates WordPress network meta and sets the default values. |
| [get\_oembed\_response\_data\_for\_url()](get_oembed_response_data_for_url) wp-includes/embed.php | Retrieves the oEmbed response data for a given URL. |
| [WP\_REST\_Attachments\_Controller::check\_upload\_size()](../classes/wp_rest_attachments_controller/check_upload_size) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Determine if uploaded file exceeds space quota on multisite. |
| [WP\_Roles::get\_roles\_data()](../classes/wp_roles/get_roles_data) wp-includes/class-wp-roles.php | Gets the available roles data. |
| [get\_main\_site\_id()](get_main_site_id) wp-includes/functions.php | Gets the main site ID. |
| [WP\_Customize\_Themes\_Panel::content\_template()](../classes/wp_customize_themes_panel/content_template) wp-includes/customize/class-wp-customize-themes-panel.php | An Underscore (JS) template for this panel’s content (but not its container). |
| [WP\_Customize\_Themes\_Section::render\_template()](../classes/wp_customize_themes_section/render_template) wp-includes/customize/class-wp-customize-themes-section.php | Render a themes section as a JS template. |
| [delete\_expired\_transients()](delete_expired_transients) wp-includes/option.php | Deletes all expired transients. |
| [WP\_REST\_Users\_Controller::get\_user()](../classes/wp_rest_users_controller/get_user) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Get the user, if the ID is valid. |
| [WP\_REST\_Users\_Controller::check\_role\_update()](../classes/wp_rest_users_controller/check_role_update) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Determines if the current user is allowed to make the desired roles change. |
| [WP\_REST\_Users\_Controller::delete\_item()](../classes/wp_rest_users_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Deletes a single user. |
| [WP\_REST\_Users\_Controller::create\_item()](../classes/wp_rest_users_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Creates a single user. |
| [register\_initial\_settings()](register_initial_settings) wp-includes/option.php | Registers default settings available in WordPress. |
| [WP\_Theme::network\_enable\_theme()](../classes/wp_theme/network_enable_theme) wp-includes/class-wp-theme.php | Enables a theme for all sites on the current network. |
| [WP\_Theme::network\_disable\_theme()](../classes/wp_theme/network_disable_theme) wp-includes/class-wp-theme.php | Disables a theme for all sites on the current network. |
| [get\_current\_network\_id()](get_current_network_id) wp-includes/load.php | Retrieves the current network ID. |
| [wp\_ajax\_install\_theme()](wp_ajax_install_theme) wp-admin/includes/ajax-actions.php | Ajax handler for installing a theme. |
| [wp\_ajax\_install\_plugin()](wp_ajax_install_plugin) wp-admin/includes/ajax-actions.php | Ajax handler for installing a plugin. |
| [has\_custom\_logo()](has_custom_logo) wp-includes/general-template.php | Determines whether the site has a custom logo. |
| [get\_custom\_logo()](get_custom_logo) wp-includes/general-template.php | Returns a custom logo, linked to home unless the theme supports removing the link on the home page. |
| [\_wp\_upload\_dir()](_wp_upload_dir) wp-includes/functions.php | A non-filtered, non-cached version of [wp\_upload\_dir()](wp_upload_dir) that doesn’t check the path. |
| [get\_rest\_url()](get_rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint on a site. |
| [wp\_get\_users\_with\_no\_role()](wp_get_users_with_no_role) wp-includes/user.php | Gets the user IDs of all users with no role on this site. |
| [get\_password\_reset\_key()](get_password_reset_key) wp-includes/user.php | Creates, stores, then returns a password reset key for user. |
| [update\_network\_option()](update_network_option) wp-includes/option.php | Updates the value of a network option that was already added. |
| [add\_network\_option()](add_network_option) wp-includes/option.php | Adds a new network option. |
| [delete\_network\_option()](delete_network_option) wp-includes/option.php | Removes a network option by name. |
| [get\_network\_option()](get_network_option) wp-includes/option.php | Retrieves a network’s option value based on the option name. |
| [get\_site\_icon\_url()](get_site_icon_url) wp-includes/general-template.php | Returns the Site Icon URL. |
| [get\_main\_network\_id()](get_main_network_id) wp-includes/functions.php | Gets the main network ID. |
| [WP\_Customize\_Theme\_Control::content\_template()](../classes/wp_customize_theme_control/content_template) wp-includes/customize/class-wp-customize-theme-control.php | Render a JS template for theme display. |
| [\_wp\_handle\_upload()](_wp_handle_upload) wp-admin/includes/file.php | Handles PHP uploads in WordPress. |
| [retrieve\_password()](retrieve_password) wp-includes/user.php | Handles sending a password retrieval email to a user. |
| [network\_step2()](network_step2) wp-admin/includes/network.php | Prints step 2 for Network installation process. |
| [Plugin\_Upgrader::bulk\_upgrade()](../classes/plugin_upgrader/bulk_upgrade) wp-admin/includes/class-plugin-upgrader.php | Bulk upgrade several plugins at once. |
| [Theme\_Upgrader::bulk\_upgrade()](../classes/theme_upgrader/bulk_upgrade) wp-admin/includes/class-theme-upgrader.php | Upgrade several themes at once. |
| [wp\_prepare\_themes\_for\_js()](wp_prepare_themes_for_js) wp-admin/includes/theme.php | Prepares themes for JavaScript. |
| [delete\_theme()](delete_theme) wp-admin/includes/theme.php | Removes a theme. |
| [get\_theme\_update\_available()](get_theme_update_available) wp-admin/includes/theme.php | Retrieves the update link if there is a theme update available. |
| [WP\_Plugins\_List\_Table::get\_bulk\_actions()](../classes/wp_plugins_list_table/get_bulk_actions) wp-admin/includes/class-wp-plugins-list-table.php | |
| [WP\_Plugins\_List\_Table::display\_rows()](../classes/wp_plugins_list_table/display_rows) wp-admin/includes/class-wp-plugins-list-table.php | |
| [WP\_Plugins\_List\_Table::single\_row()](../classes/wp_plugins_list_table/single_row) wp-admin/includes/class-wp-plugins-list-table.php | |
| [WP\_Plugins\_List\_Table::\_\_construct()](../classes/wp_plugins_list_table/__construct) wp-admin/includes/class-wp-plugins-list-table.php | Constructor. |
| [WP\_Plugins\_List\_Table::prepare\_items()](../classes/wp_plugins_list_table/prepare_items) wp-admin/includes/class-wp-plugins-list-table.php | |
| [WP\_Plugins\_List\_Table::no\_items()](../classes/wp_plugins_list_table/no_items) wp-admin/includes/class-wp-plugins-list-table.php | |
| [wxr\_site\_url()](wxr_site_url) wp-admin/includes/export.php | Returns the URL of the site. |
| [WP\_User\_Search::prepare\_query()](../classes/wp_user_search/prepare_query) wp-admin/includes/deprecated.php | Prepares the user search query (legacy). |
| [get\_author\_user\_ids()](get_author_user_ids) wp-admin/includes/deprecated.php | Get all user IDs. |
| [get\_editable\_user\_ids()](get_editable_user_ids) wp-admin/includes/deprecated.php | Gets the IDs of any users who can edit posts. |
| [get\_nonauthor\_user\_ids()](get_nonauthor_user_ids) wp-admin/includes/deprecated.php | Gets all users who are not authors. |
| [Plugin\_Installer\_Skin::after()](../classes/plugin_installer_skin/after) wp-admin/includes/class-plugin-installer-skin.php | Action to perform following a plugin install. |
| [grant\_super\_admin()](grant_super_admin) wp-includes/capabilities.php | Grants Super Admin privileges. |
| [revoke\_super\_admin()](revoke_super_admin) wp-includes/capabilities.php | Revokes Super Admin privileges. |
| [save\_mod\_rewrite\_rules()](save_mod_rewrite_rules) wp-admin/includes/misc.php | Updates the htaccess file with the current rules if it is writable. |
| [iis7\_save\_url\_rewrite\_rules()](iis7_save_url_rewrite_rules) wp-admin/includes/misc.php | Updates the IIS web.config file with the current rules if it is writable. |
| [update\_home\_siteurl()](update_home_siteurl) wp-admin/includes/misc.php | Flushes rewrite rules if siteurl, home or page\_on\_front changed. |
| [populate\_network()](populate_network) wp-admin/includes/schema.php | Populate network settings. |
| [wp\_get\_db\_schema()](wp_get_db_schema) wp-admin/includes/schema.php | Retrieve the SQL for creating database tables. |
| [populate\_options()](populate_options) wp-admin/includes/schema.php | Create WordPress options and set the default values. |
| [update\_nag()](update_nag) wp-admin/includes/update.php | Returns core update notification message. |
| [wp\_plugin\_update\_row()](wp_plugin_update_row) wp-admin/includes/update.php | Displays update information for a plugin. |
| [wp\_dashboard\_quota()](wp_dashboard_quota) wp-admin/includes/dashboard.php | Displays file upload quota on dashboard. |
| [pre\_schema\_upgrade()](pre_schema_upgrade) wp-admin/includes/upgrade.php | Runs before the schema is upgraded. |
| [wp\_upgrade()](wp_upgrade) wp-admin/includes/upgrade.php | Runs WordPress Upgrade functions. |
| [wp\_install\_defaults()](wp_install_defaults) wp-admin/includes/upgrade.php | Creates the initial content for a newly-installed site. |
| [\_get\_dropins()](_get_dropins) wp-admin/includes/plugin.php | Returns drop-ins that WordPress uses. |
| [is\_plugin\_active\_for\_network()](is_plugin_active_for_network) wp-admin/includes/plugin.php | Determines whether the plugin is active for the entire network. |
| [activate\_plugin()](activate_plugin) wp-admin/includes/plugin.php | Attempts activation of plugin in a “sandbox” and redirects on success. |
| [deactivate\_plugins()](deactivate_plugins) wp-admin/includes/plugin.php | Deactivates a single plugin or multiple plugins. |
| [validate\_active\_plugins()](validate_active_plugins) wp-admin/includes/plugin.php | Validates active plugins. |
| [edit\_user()](edit_user) wp-admin/includes/user.php | Edit user settings based on contents of $\_POST |
| [wp\_delete\_user()](wp_delete_user) wp-admin/includes/user.php | Remove user and optionally reassign posts and links to another user. |
| [WP\_Themes\_List\_Table::no\_items()](../classes/wp_themes_list_table/no_items) wp-admin/includes/class-wp-themes-list-table.php | |
| [WP\_Themes\_List\_Table::display\_rows()](../classes/wp_themes_list_table/display_rows) wp-admin/includes/class-wp-themes-list-table.php | |
| [WP\_Users\_List\_Table::single\_row()](../classes/wp_users_list_table/single_row) wp-admin/includes/class-wp-users-list-table.php | Generate HTML for a single row on the users.php admin panel. |
| [WP\_Users\_List\_Table::get\_bulk\_actions()](../classes/wp_users_list_table/get_bulk_actions) wp-admin/includes/class-wp-users-list-table.php | Retrieve an associative array of bulk actions available on this table. |
| [media\_upload\_form()](media_upload_form) wp-admin/includes/media.php | Outputs the legacy media upload form. |
| [wp\_ajax\_query\_themes()](wp_ajax_query_themes) wp-admin/includes/ajax-actions.php | Ajax handler for getting themes from [themes\_api()](themes_api) . |
| [wp\_ajax\_autocomplete\_user()](wp_ajax_autocomplete_user) wp-admin/includes/ajax-actions.php | Ajax handler for user autocomplete. |
| [WP\_Importer::set\_blog()](../classes/wp_importer/set_blog) wp-admin/includes/class-wp-importer.php | |
| [WP\_User::has\_cap()](../classes/wp_user/has_cap) wp-includes/class-wp-user.php | Returns whether the user has the specified capability. |
| [WP\_User::get\_role\_caps()](../classes/wp_user/get_role_caps) wp-includes/class-wp-user.php | Retrieves all of the capabilities of the user’s roles, and merges them with individual user capabilities. |
| [is\_super\_admin()](is_super_admin) wp-includes/capabilities.php | Determines whether user is a site admin. |
| [current\_user\_can\_for\_blog()](current_user_can_for_blog) wp-includes/capabilities.php | Returns whether the current user has the specified capability for a given site. |
| [WP\_Customize\_Manager::enqueue\_control\_scripts()](../classes/wp_customize_manager/enqueue_control_scripts) wp-includes/class-wp-customize-manager.php | Enqueues scripts for customize controls. |
| [WP\_Customize\_Manager::register\_controls()](../classes/wp_customize_manager/register_controls) wp-includes/class-wp-customize-manager.php | Registers some default controls. |
| [map\_meta\_cap()](map_meta_cap) wp-includes/capabilities.php | Maps a capability to the primitive capabilities required of the given user to satisfy the capability being checked. |
| [WP\_Object\_Cache::\_\_construct()](../classes/wp_object_cache/__construct) wp-includes/class-wp-object-cache.php | Sets up object properties; PHP 5 style constructor. |
| [wp\_get\_themes()](wp_get_themes) wp-includes/theme.php | Returns an array of [WP\_Theme](../classes/wp_theme) objects based on the arguments. |
| [load\_default\_textdomain()](load_default_textdomain) wp-includes/l10n.php | Loads default translated strings based on locale. |
| [get\_locale()](get_locale) wp-includes/l10n.php | Retrieves the current locale. |
| [sanitize\_option()](sanitize_option) wp-includes/formatting.php | Sanitizes various option values based on the nature of the option. |
| [wp\_lostpassword\_url()](wp_lostpassword_url) wp-includes/general-template.php | Returns the URL that allows the user to reset the lost password. |
| [wp\_admin\_bar\_dashboard\_view\_site\_menu()](wp_admin_bar_dashboard_view_site_menu) wp-includes/deprecated.php | Add the “Dashboard”/”Visit Site” menu. |
| [WP\_Theme::get\_allowed\_on\_site()](../classes/wp_theme/get_allowed_on_site) wp-includes/class-wp-theme.php | Returns array of stylesheet names of themes allowed on the site. |
| [WP\_Theme::is\_allowed()](../classes/wp_theme/is_allowed) wp-includes/class-wp-theme.php | Determines whether the theme is allowed (multisite only). |
| [wp\_not\_installed()](wp_not_installed) wp-includes/load.php | Redirect to the installer if WordPress is not installed. |
| [wp\_get\_active\_and\_valid\_plugins()](wp_get_active_and_valid_plugins) wp-includes/load.php | Retrieve an array of active and valid plugin files. |
| [is\_main\_site()](is_main_site) wp-includes/functions.php | Determines whether a site is the main site of the current network. |
| [is\_main\_network()](is_main_network) wp-includes/functions.php | Determines whether a network is the main network of the Multisite installation. |
| [wp\_upload\_bits()](wp_upload_bits) wp-includes/functions.php | Creates a file in the upload folder with given content. |
| [wp\_initial\_constants()](wp_initial_constants) wp-includes/default-constants.php | Defines initial WordPress constants. |
| [get\_dashboard\_url()](get_dashboard_url) wp-includes/link-template.php | Retrieves the URL to the user’s dashboard. |
| [network\_site\_url()](network_site_url) wp-includes/link-template.php | Retrieves the site URL for the current network. |
| [network\_home\_url()](network_home_url) wp-includes/link-template.php | Retrieves the home URL for the current network. |
| [network\_admin\_url()](network_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the network. |
| [get\_home\_url()](get_home_url) wp-includes/link-template.php | Retrieves the URL for a given site where the front end is accessible. |
| [get\_site\_url()](get_site_url) wp-includes/link-template.php | Retrieves the URL for a given site where WordPress application files (e.g. wp-blog-header.php or the wp-admin/ folder) are accessible. |
| [WP\_Admin\_Bar::initialize()](../classes/wp_admin_bar/initialize) wp-includes/class-wp-admin-bar.php | Initializes the admin bar. |
| [wp\_version\_check()](wp_version_check) wp-includes/update.php | Checks WordPress version against the newest version. |
| [wp\_admin\_bar\_wp\_menu()](wp_admin_bar_wp_menu) wp-includes/admin-bar.php | Adds the WordPress logo menu. |
| [wp\_admin\_bar\_my\_account\_item()](wp_admin_bar_my_account_item) wp-includes/admin-bar.php | Adds the “My Account” item. |
| [wp\_admin\_bar\_my\_account\_menu()](wp_admin_bar_my_account_menu) wp-includes/admin-bar.php | Adds the “My Account” submenu items. |
| [wp\_admin\_bar\_site\_menu()](wp_admin_bar_site_menu) wp-includes/admin-bar.php | Adds the “Site Name” menu. |
| [wp\_admin\_bar\_my\_sites\_menu()](wp_admin_bar_my_sites_menu) wp-includes/admin-bar.php | Adds the “My Sites/[Site Name]” menu and all submenus. |
| [wp\_admin\_bar\_new\_content\_menu()](wp_admin_bar_new_content_menu) wp-includes/admin-bar.php | Adds “Add New” menu. |
| [wp\_load\_alloptions()](wp_load_alloptions) wp-includes/option.php | Loads and caches all autoloaded options, if available or all options. |
| [wp\_load\_core\_site\_options()](wp_load_core_site_options) wp-includes/option.php | Loads and caches certain often requested site options if [is\_multisite()](is_multisite) and a persistent cache is not being used. |
| [WP\_User\_Query::prepare\_query()](../classes/wp_user_query/prepare_query) wp-includes/class-wp-user-query.php | Prepares the query variables. |
| [wp\_insert\_user()](wp_insert_user) wp-includes/user.php | Inserts a user into the database. |
| [get\_blogs\_of\_user()](get_blogs_of_user) wp-includes/user.php | Gets the sites a user belongs to. |
| [is\_user\_member\_of\_blog()](is_user_member_of_blog) wp-includes/user.php | Finds out whether a user is a member of a given blog. |
| [count\_users()](count_users) wp-includes/user.php | Counts number of users who have each of the user roles. |
| [wp\_authenticate\_spam\_check()](wp_authenticate_spam_check) wp-includes/user.php | For Multisite blogs, checks if the authenticated user has been marked as a spammer, or if the user’s primary blog has been marked as spam. |
| [wp\_plupload\_default\_settings()](wp_plupload_default_settings) wp-includes/media.php | Prints default Plupload arguments. |
| [wp\_delete\_attachment()](wp_delete_attachment) wp-includes/post.php | Trashes or deletes an attachment. |
| [WP\_Rewrite::rewrite\_rules()](../classes/wp_rewrite/rewrite_rules) wp-includes/class-wp-rewrite.php | Constructs rewrite matches and queries from permalink structure. |
| [redirect\_canonical()](redirect_canonical) wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| [get\_dirsize()](get_dirsize) wp-includes/functions.php | Gets the size of a directory. |
| [get\_active\_blog\_for\_user()](get_active_blog_for_user) wp-includes/ms-functions.php | Gets one of a user’s active blogs. |
| [get\_user\_count()](get_user_count) wp-includes/user.php | Returns the number of active users in your installation. |
| [wp\_xmlrpc\_server::mw\_newMediaObject()](../classes/wp_xmlrpc_server/mw_newmediaobject) wp-includes/class-wp-xmlrpc-server.php | Uploads a file, following your settings. |
| [wp\_xmlrpc\_server::blogger\_getUsersBlogs()](../classes/wp_xmlrpc_server/blogger_getusersblogs) wp-includes/class-wp-xmlrpc-server.php | Retrieve blogs that user owns. |
| [wp\_xmlrpc\_server::wp\_getUsersBlogs()](../classes/wp_xmlrpc_server/wp_getusersblogs) wp-includes/class-wp-xmlrpc-server.php | Retrieve the blogs of the user. |
| [wpdb::tables()](../classes/wpdb/tables) wp-includes/class-wpdb.php | Returns an array of WordPress tables. |
| [wpdb::print\_error()](../classes/wpdb/print_error) wp-includes/class-wpdb.php | Prints SQL/DB error. |
| [wpdb::init\_charset()](../classes/wpdb/init_charset) wp-includes/class-wpdb.php | Sets $this->charset and $this->collate. |
| [wpdb::set\_prefix()](../classes/wpdb/set_prefix) wp-includes/class-wpdb.php | Sets the table prefix for the WordPress tables. |
| [wpdb::get\_blog\_prefix()](../classes/wpdb/get_blog_prefix) wp-includes/class-wpdb.php | Gets blog prefix. |
| [wp\_print\_media\_templates()](wp_print_media_templates) wp-includes/media-template.php | Prints the templates used in the media manager. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
| programming_docs |
wordpress rest_get_url_prefix(): string rest\_get\_url\_prefix(): string
================================
Retrieves the URL prefix for any API resource.
string Prefix.
File: `wp-includes/rest-api.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api.php/)
```
function rest_get_url_prefix() {
/**
* Filters the REST URL prefix.
*
* @since 4.4.0
*
* @param string $prefix URL prefix. Default 'wp-json'.
*/
return apply_filters( 'rest_url_prefix', 'wp-json' );
}
```
[apply\_filters( 'rest\_url\_prefix', string $prefix )](../hooks/rest_url_prefix)
Filters the REST URL prefix.
| Uses | Description |
| --- | --- |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [get\_rest\_url()](get_rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint on a site. |
| [rest\_api\_register\_rewrites()](rest_api_register_rewrites) wp-includes/rest-api.php | Adds REST rewrite rules. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress check_comment_flood_db() check\_comment\_flood\_db()
===========================
Hooks WP’s native database-based comment-flood check.
This wrapper maintains backward compatibility with plugins that expect to be able to unhook the legacy [check\_comment\_flood\_db()](check_comment_flood_db) function from ‘check\_comment\_flood’ using [remove\_action()](remove_action) .
File: `wp-includes/comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/comment.php/)
```
function check_comment_flood_db() {
add_filter( 'wp_is_comment_flood', 'wp_check_comment_flood', 10, 5 );
}
```
| Uses | Description |
| --- | --- |
| [add\_filter()](add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Converted to be an [add\_filter()](add_filter) wrapper. |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
wordpress wpmu_delete_user( int $id ): bool wpmu\_delete\_user( int $id ): bool
===================================
Delete a user from the network and remove from all sites.
`$id` int Required The user ID. bool True if the user was deleted, otherwise false.
File: `wp-admin/includes/ms.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/ms.php/)
```
function wpmu_delete_user( $id ) {
global $wpdb;
if ( ! is_numeric( $id ) ) {
return false;
}
$id = (int) $id;
$user = new WP_User( $id );
if ( ! $user->exists() ) {
return false;
}
// Global super-administrators are protected, and cannot be deleted.
$_super_admins = get_super_admins();
if ( in_array( $user->user_login, $_super_admins, true ) ) {
return false;
}
/**
* Fires before a user is deleted from the network.
*
* @since MU (3.0.0)
* @since 5.5.0 Added the `$user` parameter.
*
* @param int $id ID of the user about to be deleted from the network.
* @param WP_User $user WP_User object of the user about to be deleted from the network.
*/
do_action( 'wpmu_delete_user', $id, $user );
$blogs = get_blogs_of_user( $id );
if ( ! empty( $blogs ) ) {
foreach ( $blogs as $blog ) {
switch_to_blog( $blog->userblog_id );
remove_user_from_blog( $id, $blog->userblog_id );
$post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_author = %d", $id ) );
foreach ( (array) $post_ids as $post_id ) {
wp_delete_post( $post_id );
}
// Clean links.
$link_ids = $wpdb->get_col( $wpdb->prepare( "SELECT link_id FROM $wpdb->links WHERE link_owner = %d", $id ) );
if ( $link_ids ) {
foreach ( $link_ids as $link_id ) {
wp_delete_link( $link_id );
}
}
restore_current_blog();
}
}
$meta = $wpdb->get_col( $wpdb->prepare( "SELECT umeta_id FROM $wpdb->usermeta WHERE user_id = %d", $id ) );
foreach ( $meta as $mid ) {
delete_metadata_by_mid( 'user', $mid );
}
$wpdb->delete( $wpdb->users, array( 'ID' => $id ) );
clean_user_cache( $user );
/** This action is documented in wp-admin/includes/user.php */
do_action( 'deleted_user', $id, null, $user );
return true;
}
```
[do\_action( 'deleted\_user', int $id, int|null $reassign, WP\_User $user )](../hooks/deleted_user)
Fires immediately after a user is deleted from the database.
[do\_action( 'wpmu\_delete\_user', int $id, WP\_User $user )](../hooks/wpmu_delete_user)
Fires before a user is deleted from the network.
| Uses | Description |
| --- | --- |
| [wp\_delete\_link()](wp_delete_link) wp-admin/includes/bookmark.php | Deletes a specified link from the database. |
| [WP\_User::\_\_construct()](../classes/wp_user/__construct) wp-includes/class-wp-user.php | Constructor. |
| [get\_super\_admins()](get_super_admins) wp-includes/capabilities.php | Retrieves a list of super admins. |
| [clean\_user\_cache()](clean_user_cache) wp-includes/user.php | Cleans all user caches. |
| [get\_blogs\_of\_user()](get_blogs_of_user) wp-includes/user.php | Gets the sites a user belongs to. |
| [wp\_delete\_post()](wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [remove\_user\_from\_blog()](remove_user_from_blog) wp-includes/ms-functions.php | Removes a user from a blog. |
| [switch\_to\_blog()](switch_to_blog) wp-includes/ms-blogs.php | Switch the current blog. |
| [restore\_current\_blog()](restore_current_blog) wp-includes/ms-blogs.php | Restore the current blog, after calling [switch\_to\_blog()](switch_to_blog) . |
| [wpdb::get\_col()](../classes/wpdb/get_col) wp-includes/class-wpdb.php | Retrieves one column from the database. |
| [wpdb::delete()](../classes/wpdb/delete) wp-includes/class-wpdb.php | Deletes a row in the table. |
| [delete\_metadata\_by\_mid()](delete_metadata_by_mid) wp-includes/meta.php | Deletes metadata by meta ID. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wpdb::prepare()](../classes/wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress checked( mixed $checked, mixed $current = true, bool $echo = true ): string checked( mixed $checked, mixed $current = true, bool $echo = true ): string
===========================================================================
Outputs the HTML checked attribute.
Compares the first two arguments and if identical marks as checked.
`$checked` mixed Required One of the values to compare. `$current` mixed Optional The other value to compare if not just true.
Default: `true`
`$echo` bool Optional Whether to echo or just return the string.
Default: `true`
string HTML attribute or empty string.
File: `wp-includes/general-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/general-template.php/)
```
function checked( $checked, $current = true, $echo = true ) {
return __checked_selected_helper( $checked, $current, $echo, 'checked' );
}
```
| Uses | Description |
| --- | --- |
| [\_\_checked\_selected\_helper()](__checked_selected_helper) wp-includes/general-template.php | Private helper function for checked, selected, disabled and readonly. |
| Used By | Description |
| --- | --- |
| [WP\_Screen::render\_meta\_boxes\_preferences()](../classes/wp_screen/render_meta_boxes_preferences) wp-admin/includes/class-wp-screen.php | Renders the meta boxes preferences. |
| [WP\_Screen::render\_list\_table\_columns\_preferences()](../classes/wp_screen/render_list_table_columns_preferences) wp-admin/includes/class-wp-screen.php | Renders the list table columns preferences. |
| [WP\_Screen::render\_view\_mode()](../classes/wp_screen/render_view_mode) wp-admin/includes/class-wp-screen.php | Renders the list table view mode preferences. |
| [signup\_user()](signup_user) wp-signup.php | Shows a form for a visitor to sign up for a new user account. |
| [network\_step1()](network_step1) wp-admin/includes/network.php | Prints step 1 for Network installation process. |
| [display\_setup\_form()](display_setup_form) wp-admin/install.php | Displays installer setup form. |
| [use\_ssl\_preference()](use_ssl_preference) wp-admin/includes/user.php | Optional SSL preference that can be turned on by hooking to the ‘personal\_options’ action. |
| [WP\_Screen::show\_screen\_options()](../classes/wp_screen/show_screen_options) wp-admin/includes/class-wp-screen.php | |
| [WP\_Screen::render\_screen\_layout()](../classes/wp_screen/render_screen_layout) wp-admin/includes/class-wp-screen.php | Renders the option for number of columns on the page. |
| [meta\_box\_prefs()](meta_box_prefs) wp-admin/includes/screen.php | Prints the meta box preferences for screen meta. |
| [admin\_color\_scheme\_picker()](admin_color_scheme_picker) wp-admin/includes/misc.php | Displays the default admin color scheme picker (Used in user-edit.php). |
| [Walker\_Category\_Checklist::start\_el()](../classes/walker_category_checklist/start_el) wp-admin/includes/class-walker-category-checklist.php | Start the element output. |
| [wp\_media\_insert\_url\_form()](wp_media_insert_url_form) wp-admin/includes/media.php | Creates the form for external url. |
| [post\_comment\_status\_meta\_box()](post_comment_status_meta_box) wp-admin/includes/meta-boxes.php | Displays comments status form fields. |
| [link\_submit\_meta\_box()](link_submit_meta_box) wp-admin/includes/meta-boxes.php | Displays link create form fields. |
| [post\_submit\_meta\_box()](post_submit_meta_box) wp-admin/includes/meta-boxes.php | Displays post submit form fields. |
| [post\_format\_meta\_box()](post_format_meta_box) wp-admin/includes/meta-boxes.php | Displays post format form elements. |
| [Walker\_Nav\_Menu\_Edit::start\_el()](../classes/walker_nav_menu_edit/start_el) wp-admin/includes/class-walker-nav-menu-edit.php | Start the element output. |
| [request\_filesystem\_credentials()](request_filesystem_credentials) wp-admin/includes/file.php | Displays a form to the user to request for their FTP/SSH details in order to connect to the filesystem. |
| [Custom\_Image\_Header::step\_1()](../classes/custom_image_header/step_1) wp-admin/includes/class-custom-image-header.php | Display first step of custom header image page. |
| [Custom\_Image\_Header::show\_header\_selector()](../classes/custom_image_header/show_header_selector) wp-admin/includes/class-custom-image-header.php | Display UI for selecting one of several default headers. |
| [Custom\_Background::admin\_page()](../classes/custom_background/admin_page) wp-admin/includes/class-custom-background.php | Displays the custom background page. |
| [WP\_Widget\_Tag\_Cloud::form()](../classes/wp_widget_tag_cloud/form) wp-includes/widgets/class-wp-widget-tag-cloud.php | Outputs the Tag Cloud widget settings form. |
| [WP\_Widget\_Recent\_Posts::form()](../classes/wp_widget_recent_posts/form) wp-includes/widgets/class-wp-widget-recent-posts.php | Outputs the settings form for the Recent Posts widget. |
| [WP\_Widget\_Categories::form()](../classes/wp_widget_categories/form) wp-includes/widgets/class-wp-widget-categories.php | Outputs the settings form for the Categories widget. |
| [WP\_Widget\_Text::form()](../classes/wp_widget_text/form) wp-includes/widgets/class-wp-widget-text.php | Outputs the Text widget settings form. |
| [WP\_Widget\_Archives::form()](../classes/wp_widget_archives/form) wp-includes/widgets/class-wp-widget-archives.php | Outputs the settings form for the Archives widget. |
| [WP\_Widget\_Links::form()](../classes/wp_widget_links/form) wp-includes/widgets/class-wp-widget-links.php | Outputs the settings form for the Links widget. |
| [wp\_widget\_rss\_form()](wp_widget_rss_form) wp-includes/widgets.php | Display RSS widget options form. |
| [WP\_Customize\_Control::render\_content()](../classes/wp_customize_control/render_content) wp-includes/class-wp-customize-control.php | Render the control’s content. |
| Version | Description |
| --- | --- |
| [1.0.0](https://developer.wordpress.org/reference/since/1.0.0/) | Introduced. |
wordpress wp_kses_data( string $data ): string wp\_kses\_data( string $data ): string
======================================
Sanitize content with allowed HTML KSES rules.
This function expects unslashed data.
`$data` string Required Content to filter, expected to not be escaped. string Filtered content.
File: `wp-includes/kses.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/kses.php/)
```
function wp_kses_data( $data ) {
return wp_kses( $data, current_filter() );
}
```
| Uses | Description |
| --- | --- |
| [wp\_kses()](wp_kses) wp-includes/kses.php | Filters text content and strips out disallowed HTML. |
| [current\_filter()](current_filter) wp-includes/plugin.php | Retrieves the name of the current filter hook. |
| Used By | Description |
| --- | --- |
| [sanitize\_option()](sanitize_option) wp-includes/formatting.php | Sanitizes various option values based on the nature of the option. |
| Version | Description |
| --- | --- |
| [2.9.0](https://developer.wordpress.org/reference/since/2.9.0/) | Introduced. |
wordpress next_post_link( string $format = '%link »', string $link = '%title', bool $in_same_term = false, int[]|string $excluded_terms = '', string $taxonomy = 'category' ) next\_post\_link( string $format = '%link »', string $link = '%title', bool $in\_same\_term = false, int[]|string $excluded\_terms = '', string $taxonomy = 'category' )
==============================================================================================================================================================================
Displays the next post link that is adjacent to the current post.
* [get\_next\_post\_link()](get_next_post_link)
`$format` string Optional Link anchor format. Default '« %link'. Default: `'%link »'`
`$link` string Optional Link permalink format. Default `'%title'` Default: `'%title'`
`$in_same_term` bool Optional Whether link should be in a same taxonomy term. Default: `false`
`$excluded_terms` int[]|string Optional Array or comma-separated list of excluded term IDs. Default: `''`
`$taxonomy` string Optional Taxonomy, if $in\_same\_term is true. Default `'category'`. Default: `'category'`
File: `wp-includes/link-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/link-template.php/)
```
function next_post_link( $format = '%link »', $link = '%title', $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {
echo get_next_post_link( $format, $link, $in_same_term, $excluded_terms, $taxonomy );
}
```
| Uses | Description |
| --- | --- |
| [get\_next\_post\_link()](get_next_post_link) wp-includes/link-template.php | Retrieves the next post link that is adjacent to the current post. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress get_user_setting( string $name, string|false $default = false ): mixed get\_user\_setting( string $name, string|false $default = false ): mixed
========================================================================
Retrieves user interface setting value based on setting name.
`$name` string Required The name of the setting. `$default` string|false Optional Default value to return when $name is not set. Default: `false`
mixed The last saved user setting or the default value/false if it doesn't exist.
File: `wp-includes/option.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/option.php/)
```
function get_user_setting( $name, $default = false ) {
$all_user_settings = get_all_user_settings();
return isset( $all_user_settings[ $name ] ) ? $all_user_settings[ $name ] : $default;
}
```
| Uses | Description |
| --- | --- |
| [get\_all\_user\_settings()](get_all_user_settings) wp-includes/option.php | Retrieves all user interface settings. |
| Used By | Description |
| --- | --- |
| [WP\_Screen::render\_view\_mode()](../classes/wp_screen/render_view_mode) wp-admin/includes/class-wp-screen.php | Renders the list table view mode preferences. |
| [WP\_Comments\_List\_Table::handle\_row\_actions()](../classes/wp_comments_list_table/handle_row_actions) wp-admin/includes/class-wp-comments-list-table.php | Generates and displays row actions links. |
| [WP\_MS\_Users\_List\_Table::prepare\_items()](../classes/wp_ms_users_list_table/prepare_items) wp-admin/includes/class-wp-ms-users-list-table.php | |
| [WP\_Screen::show\_screen\_options()](../classes/wp_screen/show_screen_options) wp-admin/includes/class-wp-screen.php | |
| [WP\_List\_Table::get\_table\_classes()](../classes/wp_list_table/get_table_classes) wp-admin/includes/class-wp-list-table.php | Gets a list of CSS classes for the [WP\_List\_Table](../classes/wp_list_table) table tag. |
| [WP\_List\_Table::row\_actions()](../classes/wp_list_table/row_actions) wp-admin/includes/class-wp-list-table.php | Generates the required HTML for a list of row action links. |
| [default\_password\_nag\_handler()](default_password_nag_handler) wp-admin/includes/user.php | |
| [WP\_MS\_Sites\_List\_Table::prepare\_items()](../classes/wp_ms_sites_list_table/prepare_items) wp-admin/includes/class-wp-ms-sites-list-table.php | Prepares the list of sites for display. |
| [media\_upload\_type\_form()](media_upload_type_form) wp-admin/includes/media.php | Outputs the legacy media upload form for a given media type. |
| [media\_upload\_type\_url\_form()](media_upload_type_url_form) wp-admin/includes/media.php | Outputs the legacy media upload form for external media. |
| [media\_upload\_gallery\_form()](media_upload_gallery_form) wp-admin/includes/media.php | Adds gallery form to upload iframe. |
| [media\_upload\_library\_form()](media_upload_library_form) wp-admin/includes/media.php | Outputs the legacy media upload form for the media library. |
| [media\_upload\_max\_image\_resize()](media_upload_max_image_resize) wp-admin/includes/media.php | Displays the checkbox to scale images. |
| [image\_align\_input\_fields()](image_align_input_fields) wp-admin/includes/media.php | Retrieves HTML for the image alignment radio buttons with the specified one checked. |
| [image\_size\_input\_fields()](image_size_input_fields) wp-admin/includes/media.php | Retrieves HTML for the size radio buttons with the specified one checked. |
| [image\_link\_input\_fields()](image_link_input_fields) wp-admin/includes/media.php | Retrieves HTML for the Link URL buttons with the default link type as specified. |
| [WP\_Comments\_List\_Table::prepare\_items()](../classes/wp_comments_list_table/prepare_items) wp-admin/includes/class-wp-comments-list-table.php | |
| [WP\_Posts\_List\_Table::prepare\_items()](../classes/wp_posts_list_table/prepare_items) wp-admin/includes/class-wp-posts-list-table.php | |
| [wp\_default\_editor()](wp_default_editor) wp-includes/general-template.php | Finds out which editor should be displayed by default. |
| [\_WP\_Editors::parse\_settings()](../classes/_wp_editors/parse_settings) wp-includes/class-wp-editor.php | Parse default arguments for the editor instance. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
| programming_docs |
wordpress wp_get_attachment_link( int|WP_Post $post, string|int[] $size = 'thumbnail', bool $permalink = false, bool $icon = false, string|false $text = false, array|string $attr = '' ): string wp\_get\_attachment\_link( int|WP\_Post $post, string|int[] $size = 'thumbnail', bool $permalink = false, bool $icon = false, string|false $text = false, array|string $attr = '' ): string
===========================================================================================================================================================================================
Retrieves an attachment page link using an image or icon, if possible.
`$post` int|[WP\_Post](../classes/wp_post) Optional Post ID or post object. `$size` string|int[] Optional Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order). Default `'thumbnail'`. Default: `'thumbnail'`
`$permalink` bool Optional Whether to add permalink to image. Default: `false`
`$icon` bool Optional Whether the attachment is an icon. Default: `false`
`$text` string|false Optional Link text to use. Activated by passing a string, false otherwise.
Default: `false`
`$attr` array|string Optional Array or string of attributes. Default: `''`
string HTML content.
File: `wp-includes/post-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post-template.php/)
```
function wp_get_attachment_link( $post = 0, $size = 'thumbnail', $permalink = false, $icon = false, $text = false, $attr = '' ) {
$_post = get_post( $post );
if ( empty( $_post ) || ( 'attachment' !== $_post->post_type ) || ! wp_get_attachment_url( $_post->ID ) ) {
return __( 'Missing Attachment' );
}
$url = wp_get_attachment_url( $_post->ID );
if ( $permalink ) {
$url = get_attachment_link( $_post->ID );
}
if ( $text ) {
$link_text = $text;
} elseif ( $size && 'none' !== $size ) {
$link_text = wp_get_attachment_image( $_post->ID, $size, $icon, $attr );
} else {
$link_text = '';
}
if ( '' === trim( $link_text ) ) {
$link_text = $_post->post_title;
}
if ( '' === trim( $link_text ) ) {
$link_text = esc_html( pathinfo( get_attached_file( $_post->ID ), PATHINFO_FILENAME ) );
}
$link_html = "<a href='" . esc_url( $url ) . "'>$link_text</a>";
/**
* Filters a retrieved attachment page link.
*
* @since 2.7.0
* @since 5.1.0 Added the `$attr` parameter.
*
* @param string $link_html The page link HTML output.
* @param int|WP_Post $post Post ID or object. Can be 0 for the current global post.
* @param string|int[] $size Requested image size. Can be any registered image size name, or
* an array of width and height values in pixels (in that order).
* @param bool $permalink Whether to add permalink to image. Default false.
* @param bool $icon Whether to include an icon.
* @param string|false $text If string, will be link text.
* @param array|string $attr Array or string of attributes.
*/
return apply_filters( 'wp_get_attachment_link', $link_html, $post, $size, $permalink, $icon, $text, $attr );
}
```
[apply\_filters( 'wp\_get\_attachment\_link', string $link\_html, int|WP\_Post $post, string|int[] $size, bool $permalink, bool $icon, string|false $text, array|string $attr )](../hooks/wp_get_attachment_link)
Filters a retrieved attachment page link.
| Uses | Description |
| --- | --- |
| [get\_attachment\_link()](get_attachment_link) wp-includes/link-template.php | Retrieves the permalink for an attachment. |
| [wp\_get\_attachment\_image()](wp_get_attachment_image) wp-includes/media.php | Gets an HTML img element representing an image attachment. |
| [wp\_get\_attachment\_url()](wp_get_attachment_url) wp-includes/post.php | Retrieves the URL for an attachment. |
| [get\_attached\_file()](get_attached_file) wp-includes/post.php | Retrieves attached file path based on attachment ID. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [get\_adjacent\_image\_link()](get_adjacent_image_link) wp-includes/media.php | Gets the next or previous image link that has the same post parent. |
| [prepend\_attachment()](prepend_attachment) wp-includes/post-template.php | Wraps attachment in paragraph tag before content. |
| [the\_attachment\_link()](the_attachment_link) wp-includes/post-template.php | Displays an attachment page link using an image or icon. |
| [gallery\_shortcode()](gallery_shortcode) wp-includes/media.php | Builds the Gallery shortcode output. |
| [wp\_playlist\_shortcode()](wp_playlist_shortcode) wp-includes/media.php | Builds the Playlist shortcode output. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | The `$post` parameter can now accept either a post ID or `WP_Post` object. |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress get_trackback_url(): string get\_trackback\_url(): string
=============================
Retrieves the current post’s trackback URL.
There is a check to see if permalink’s have been enabled and if so, will retrieve the pretty path. If permalinks weren’t enabled, the ID of the current post is used and appended to the correct page to go to.
string The trackback URL after being filtered.
File: `wp-includes/comment-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/comment-template.php/)
```
function get_trackback_url() {
if ( get_option( 'permalink_structure' ) ) {
$trackback_url = trailingslashit( get_permalink() ) . user_trailingslashit( 'trackback', 'single_trackback' );
} else {
$trackback_url = get_option( 'siteurl' ) . '/wp-trackback.php?p=' . get_the_ID();
}
/**
* Filters the returned trackback URL.
*
* @since 2.2.0
*
* @param string $trackback_url The trackback URL.
*/
return apply_filters( 'trackback_url', $trackback_url );
}
```
[apply\_filters( 'trackback\_url', string $trackback\_url )](../hooks/trackback_url)
Filters the returned trackback URL.
| Uses | Description |
| --- | --- |
| [user\_trailingslashit()](user_trailingslashit) wp-includes/link-template.php | Retrieves a trailing-slashed string if the site is set for adding trailing slashes. |
| [get\_the\_ID()](get_the_id) wp-includes/post-template.php | Retrieves the ID of the current item in the WordPress Loop. |
| [trailingslashit()](trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| [get\_permalink()](get_permalink) wp-includes/link-template.php | Retrieves the full permalink for the current post or post ID. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [trackback\_url()](trackback_url) wp-includes/comment-template.php | Displays the current post’s trackback URL. |
| [trackback\_rdf()](trackback_rdf) wp-includes/comment-template.php | Generates and displays the RDF for the trackback information of current post. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_debug_mode() wp\_debug\_mode()
=================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Set PHP error reporting based on WordPress debug settings.
Uses three constants: `WP_DEBUG`, `WP_DEBUG_DISPLAY`, and `WP_DEBUG_LOG`.
All three can be defined in wp-config.php. By default, `WP_DEBUG` and `WP_DEBUG_LOG` are set to false, and `WP_DEBUG_DISPLAY` is set to true.
When `WP_DEBUG` is true, all PHP notices are reported. WordPress will also display internal notices: when a deprecated WordPress function, function argument, or file is used. Deprecated code may be removed from a later version.
It is strongly recommended that plugin and theme developers use `WP_DEBUG` in their development environments.
`WP_DEBUG_DISPLAY` and `WP_DEBUG_LOG` perform no function unless `WP_DEBUG` is true.
When `WP_DEBUG_DISPLAY` is true, WordPress will force errors to be displayed.
`WP_DEBUG_DISPLAY` defaults to true. Defining it as null prevents WordPress from changing the global configuration setting. Defining `WP_DEBUG_DISPLAY` as false will force errors to be hidden.
When `WP_DEBUG_LOG` is true, errors will be logged to `wp-content/debug.log`.
When `WP_DEBUG_LOG` is a valid path, errors will be logged to the specified file.
Errors are never displayed for XML-RPC, REST, `ms-files.php`, and Ajax requests.
File: `wp-includes/load.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/load.php/)
```
function wp_debug_mode() {
/**
* Filters whether to allow the debug mode check to occur.
*
* This filter runs before it can be used by plugins. It is designed for
* non-web runtimes. Returning false causes the `WP_DEBUG` and related
* constants to not be checked and the default PHP values for errors
* will be used unless you take care to update them yourself.
*
* To use this filter you must define a `$wp_filter` global before
* WordPress loads, usually in `wp-config.php`.
*
* Example:
*
* $GLOBALS['wp_filter'] = array(
* 'enable_wp_debug_mode_checks' => array(
* 10 => array(
* array(
* 'accepted_args' => 0,
* 'function' => function() {
* return false;
* },
* ),
* ),
* ),
* );
*
* @since 4.6.0
*
* @param bool $enable_debug_mode Whether to enable debug mode checks to occur. Default true.
*/
if ( ! apply_filters( 'enable_wp_debug_mode_checks', true ) ) {
return;
}
if ( WP_DEBUG ) {
error_reporting( E_ALL );
if ( WP_DEBUG_DISPLAY ) {
ini_set( 'display_errors', 1 );
} elseif ( null !== WP_DEBUG_DISPLAY ) {
ini_set( 'display_errors', 0 );
}
if ( in_array( strtolower( (string) WP_DEBUG_LOG ), array( 'true', '1' ), true ) ) {
$log_path = WP_CONTENT_DIR . '/debug.log';
} elseif ( is_string( WP_DEBUG_LOG ) ) {
$log_path = WP_DEBUG_LOG;
} else {
$log_path = false;
}
if ( $log_path ) {
ini_set( 'log_errors', 1 );
ini_set( 'error_log', $log_path );
}
} else {
error_reporting( E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR );
}
if (
defined( 'XMLRPC_REQUEST' ) || defined( 'REST_REQUEST' ) || defined( 'MS_FILES_REQUEST' ) ||
( defined( 'WP_INSTALLING' ) && WP_INSTALLING ) ||
wp_doing_ajax() || wp_is_json_request() ) {
ini_set( 'display_errors', 0 );
}
}
```
[apply\_filters( 'enable\_wp\_debug\_mode\_checks', bool $enable\_debug\_mode )](../hooks/enable_wp_debug_mode_checks)
Filters whether to allow the debug mode check to occur.
| Uses | Description |
| --- | --- |
| [wp\_is\_json\_request()](wp_is_json_request) wp-includes/load.php | Checks whether current request is a JSON request, or is expecting a JSON response. |
| [wp\_doing\_ajax()](wp_doing_ajax) wp-includes/load.php | Determines whether the current request is a WordPress Ajax request. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | `WP_DEBUG_LOG` can be a file path. |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress wp_maybe_transition_site_statuses_on_update( WP_Site $new_site, WP_Site|null $old_site = null ) wp\_maybe\_transition\_site\_statuses\_on\_update( WP\_Site $new\_site, WP\_Site|null $old\_site = null )
=========================================================================================================
Triggers actions on site status updates.
`$new_site` [WP\_Site](../classes/wp_site) Required The site object after the update. `$old_site` [WP\_Site](../classes/wp_site)|null Optional If $new\_site has been updated, this must be the previous state of that site. Default: `null`
File: `wp-includes/ms-site.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-site.php/)
```
function wp_maybe_transition_site_statuses_on_update( $new_site, $old_site = null ) {
$site_id = $new_site->id;
// Use the default values for a site if no previous state is given.
if ( ! $old_site ) {
$old_site = new WP_Site( new stdClass() );
}
if ( $new_site->spam != $old_site->spam ) {
if ( 1 == $new_site->spam ) {
/**
* Fires when the 'spam' status is added to a site.
*
* @since MU (3.0.0)
*
* @param int $site_id Site ID.
*/
do_action( 'make_spam_blog', $site_id );
} else {
/**
* Fires when the 'spam' status is removed from a site.
*
* @since MU (3.0.0)
*
* @param int $site_id Site ID.
*/
do_action( 'make_ham_blog', $site_id );
}
}
if ( $new_site->mature != $old_site->mature ) {
if ( 1 == $new_site->mature ) {
/**
* Fires when the 'mature' status is added to a site.
*
* @since 3.1.0
*
* @param int $site_id Site ID.
*/
do_action( 'mature_blog', $site_id );
} else {
/**
* Fires when the 'mature' status is removed from a site.
*
* @since 3.1.0
*
* @param int $site_id Site ID.
*/
do_action( 'unmature_blog', $site_id );
}
}
if ( $new_site->archived != $old_site->archived ) {
if ( 1 == $new_site->archived ) {
/**
* Fires when the 'archived' status is added to a site.
*
* @since MU (3.0.0)
*
* @param int $site_id Site ID.
*/
do_action( 'archive_blog', $site_id );
} else {
/**
* Fires when the 'archived' status is removed from a site.
*
* @since MU (3.0.0)
*
* @param int $site_id Site ID.
*/
do_action( 'unarchive_blog', $site_id );
}
}
if ( $new_site->deleted != $old_site->deleted ) {
if ( 1 == $new_site->deleted ) {
/**
* Fires when the 'deleted' status is added to a site.
*
* @since 3.5.0
*
* @param int $site_id Site ID.
*/
do_action( 'make_delete_blog', $site_id );
} else {
/**
* Fires when the 'deleted' status is removed from a site.
*
* @since 3.5.0
*
* @param int $site_id Site ID.
*/
do_action( 'make_undelete_blog', $site_id );
}
}
if ( $new_site->public != $old_site->public ) {
/**
* Fires after the current blog's 'public' setting is updated.
*
* @since MU (3.0.0)
*
* @param int $site_id Site ID.
* @param string $value The value of the site status.
*/
do_action( 'update_blog_public', $site_id, $new_site->public );
}
}
```
[do\_action( 'archive\_blog', int $site\_id )](../hooks/archive_blog)
Fires when the ‘archived’ status is added to a site.
[do\_action( 'make\_delete\_blog', int $site\_id )](../hooks/make_delete_blog)
Fires when the ‘deleted’ status is added to a site.
[do\_action( 'make\_ham\_blog', int $site\_id )](../hooks/make_ham_blog)
Fires when the ‘spam’ status is removed from a site.
[do\_action( 'make\_spam\_blog', int $site\_id )](../hooks/make_spam_blog)
Fires when the ‘spam’ status is added to a site.
[do\_action( 'make\_undelete\_blog', int $site\_id )](../hooks/make_undelete_blog)
Fires when the ‘deleted’ status is removed from a site.
[do\_action( 'mature\_blog', int $site\_id )](../hooks/mature_blog)
Fires when the ‘mature’ status is added to a site.
[do\_action( 'unarchive\_blog', int $site\_id )](../hooks/unarchive_blog)
Fires when the ‘archived’ status is removed from a site.
[do\_action( 'unmature\_blog', int $site\_id )](../hooks/unmature_blog)
Fires when the ‘mature’ status is removed from a site.
[do\_action( 'update\_blog\_public', int $site\_id, string $value )](../hooks/update_blog_public)
Fires after the current blog’s ‘public’ setting is updated.
| Uses | Description |
| --- | --- |
| [WP\_Site::\_\_construct()](../classes/wp_site/__construct) wp-includes/class-wp-site.php | Creates a new [WP\_Site](../classes/wp_site) object. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | Introduced. |
wordpress _wp_get_user_contactmethods( WP_User|null $user = null ): string[] \_wp\_get\_user\_contactmethods( WP\_User|null $user = null ): string[]
=======================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
The old private function for setting up user contact methods.
Use [wp\_get\_user\_contact\_methods()](wp_get_user_contact_methods) instead.
`$user` [WP\_User](../classes/wp_user)|null Optional [WP\_User](../classes/wp_user) object. Default: `null`
string[] Array of contact method labels keyed by contact method.
File: `wp-includes/user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/user.php/)
```
function _wp_get_user_contactmethods( $user = null ) {
return wp_get_user_contact_methods( $user );
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_user\_contact\_methods()](wp_get_user_contact_methods) wp-includes/user.php | Sets up the user contact methods. |
| Version | Description |
| --- | --- |
| [2.9.0](https://developer.wordpress.org/reference/since/2.9.0/) | Introduced. |
wordpress wp_remove_object_terms( int $object_id, string|int|array $terms, string $taxonomy ): bool|WP_Error wp\_remove\_object\_terms( int $object\_id, string|int|array $terms, string $taxonomy ): bool|WP\_Error
=======================================================================================================
Removes term(s) associated with a given object.
`$object_id` int Required The ID of the object from which the terms will be removed. `$terms` string|int|array Required The slug(s) or ID(s) of the term(s) to remove. `$taxonomy` string Required Taxonomy name. bool|[WP\_Error](../classes/wp_error) True on success, false or [WP\_Error](../classes/wp_error) on failure.
File: `wp-includes/taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/taxonomy.php/)
```
function wp_remove_object_terms( $object_id, $terms, $taxonomy ) {
global $wpdb;
$object_id = (int) $object_id;
if ( ! taxonomy_exists( $taxonomy ) ) {
return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
}
if ( ! is_array( $terms ) ) {
$terms = array( $terms );
}
$tt_ids = array();
foreach ( (array) $terms as $term ) {
if ( '' === trim( $term ) ) {
continue;
}
$term_info = term_exists( $term, $taxonomy );
if ( ! $term_info ) {
// Skip if a non-existent term ID is passed.
if ( is_int( $term ) ) {
continue;
}
}
if ( is_wp_error( $term_info ) ) {
return $term_info;
}
$tt_ids[] = $term_info['term_taxonomy_id'];
}
if ( $tt_ids ) {
$in_tt_ids = "'" . implode( "', '", $tt_ids ) . "'";
/**
* Fires immediately before an object-term relationship is deleted.
*
* @since 2.9.0
* @since 4.7.0 Added the `$taxonomy` parameter.
*
* @param int $object_id Object ID.
* @param array $tt_ids An array of term taxonomy IDs.
* @param string $taxonomy Taxonomy slug.
*/
do_action( 'delete_term_relationships', $object_id, $tt_ids, $taxonomy );
$deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) );
wp_cache_delete( $object_id, $taxonomy . '_relationships' );
wp_cache_delete( 'last_changed', 'terms' );
/**
* Fires immediately after an object-term relationship is deleted.
*
* @since 2.9.0
* @since 4.7.0 Added the `$taxonomy` parameter.
*
* @param int $object_id Object ID.
* @param array $tt_ids An array of term taxonomy IDs.
* @param string $taxonomy Taxonomy slug.
*/
do_action( 'deleted_term_relationships', $object_id, $tt_ids, $taxonomy );
wp_update_term_count( $tt_ids, $taxonomy );
return (bool) $deleted;
}
return false;
}
```
[do\_action( 'deleted\_term\_relationships', int $object\_id, array $tt\_ids, string $taxonomy )](../hooks/deleted_term_relationships)
Fires immediately after an object-term relationship is deleted.
[do\_action( 'delete\_term\_relationships', int $object\_id, array $tt\_ids, string $taxonomy )](../hooks/delete_term_relationships)
Fires immediately before an object-term relationship is deleted.
| Uses | Description |
| --- | --- |
| [wp\_cache\_delete()](wp_cache_delete) wp-includes/cache.php | Removes the cache contents matching key and group. |
| [wp\_update\_term\_count()](wp_update_term_count) wp-includes/taxonomy.php | Updates the amount of terms in taxonomy. |
| [term\_exists()](term_exists) wp-includes/taxonomy.php | Determines whether a taxonomy term exists. |
| [taxonomy\_exists()](taxonomy_exists) wp-includes/taxonomy.php | Determines whether the taxonomy name exists. |
| [wpdb::query()](../classes/wpdb/query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wpdb::prepare()](../classes/wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../classes/wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [wp\_set\_object\_terms()](wp_set_object_terms) wp-includes/taxonomy.php | Creates term and taxonomy relationships. |
| [wp\_delete\_object\_term\_relationships()](wp_delete_object_term_relationships) wp-includes/taxonomy.php | Unlinks the object from the taxonomy or taxonomies. |
| [wp\_delete\_term()](wp_delete_term) wp-includes/taxonomy.php | Removes a term from the database. |
| Version | Description |
| --- | --- |
| [3.6.0](https://developer.wordpress.org/reference/since/3.6.0/) | Introduced. |
| programming_docs |
wordpress add_settings_field( string $id, string $title, callable $callback, string $page, string $section = 'default', array $args = array() ) add\_settings\_field( string $id, string $title, callable $callback, string $page, string $section = 'default', array $args = array() )
=======================================================================================================================================
Adds a new field to a section of a settings page.
Part of the Settings API. Use this to define a settings field that will show as part of a settings section inside a settings page. The fields are shown using [do\_settings\_fields()](do_settings_fields) in [do\_settings\_sections()](do_settings_sections) .
The $callback argument should be the name of a function that echoes out the HTML input tags for this setting field. Use [get\_option()](get_option) to retrieve existing values to show.
`$id` string Required Slug-name to identify the field. Used in the `'id'` attribute of tags. `$title` string Required Formatted title of the field. Shown as the label for the field during output. `$callback` callable Required Function that fills the field with the desired form inputs. The function should echo its output. `$page` string Required The slug-name of the settings page on which to show the section (general, reading, writing, ...). `$section` string Optional The slug-name of the section of the settings page in which to show the box. Default `'default'`. Default: `'default'`
`$args` array Optional Extra arguments that get passed to the callback function.
* `label_for`stringWhen supplied, the setting title will be wrapped in a `<label>` element, its `for` attribute populated with this value.
* `class`stringCSS Class to be added to the `<tr>` element when the field is output.
Default: `array()`
**You MUST register any options** used by this function with [register\_setting()](register_setting) or they won’t be saved and updated automatically.
**The callback function** needs to output the appropriate html input and fill it with the old value, the saving will be done behind the scenes.
The html input field’s **name** attribute must match $option\_name in [register\_setting()](register_setting) , and **value** can be filled using [get\_option()](get_option) .
This function can also be used to add extra settings fields to the default WP settings pages like media or general. You can add them to an existing section, or use [add\_settings\_section()](add_settings_section) to create a new section to add the fields to.
See [Settings API](https://developer.wordpress.org/apis/handbook/settings/ "Settings API") for details.
File: `wp-admin/includes/template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/template.php/)
```
function add_settings_field( $id, $title, $callback, $page, $section = 'default', $args = array() ) {
global $wp_settings_fields;
if ( 'misc' === $page ) {
_deprecated_argument(
__FUNCTION__,
'3.0.0',
sprintf(
/* translators: %s: misc */
__( 'The "%s" options group has been removed. Use another settings group.' ),
'misc'
)
);
$page = 'general';
}
if ( 'privacy' === $page ) {
_deprecated_argument(
__FUNCTION__,
'3.5.0',
sprintf(
/* translators: %s: privacy */
__( 'The "%s" options group has been removed. Use another settings group.' ),
'privacy'
)
);
$page = 'reading';
}
$wp_settings_fields[ $page ][ $section ][ $id ] = array(
'id' => $id,
'title' => $title,
'callback' => $callback,
'args' => $args,
);
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_deprecated\_argument()](_deprecated_argument) wp-includes/functions.php | Marks a function argument as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | The `$class` argument was added. |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress is_blog_installed(): bool is\_blog\_installed(): bool
===========================
Determines whether WordPress is already installed.
The cache will be checked first. If you have a cache plugin, which saves the cache values, then this will work. If you use the default WordPress cache, and the database goes away, then you might have problems.
Checks for the ‘siteurl’ option for whether WordPress is installed.
For more information on this and similar theme functions, check out the [Conditional Tags](https://developer.wordpress.org/themes/basics/conditional-tags/) article in the Theme Developer Handbook.
bool Whether the site is already installed.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function is_blog_installed() {
global $wpdb;
/*
* Check cache first. If options table goes away and we have true
* cached, oh well.
*/
if ( wp_cache_get( 'is_blog_installed' ) ) {
return true;
}
$suppress = $wpdb->suppress_errors();
if ( ! wp_installing() ) {
$alloptions = wp_load_alloptions();
}
// If siteurl is not set to autoload, check it specifically.
if ( ! isset( $alloptions['siteurl'] ) ) {
$installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
} else {
$installed = $alloptions['siteurl'];
}
$wpdb->suppress_errors( $suppress );
$installed = ! empty( $installed );
wp_cache_set( 'is_blog_installed', $installed );
if ( $installed ) {
return true;
}
// If visiting repair.php, return true and let it take over.
if ( defined( 'WP_REPAIRING' ) ) {
return true;
}
$suppress = $wpdb->suppress_errors();
/*
* Loop over the WP tables. If none exist, then scratch installation is allowed.
* If one or more exist, suggest table repair since we got here because the
* options table could not be accessed.
*/
$wp_tables = $wpdb->tables();
foreach ( $wp_tables as $table ) {
// The existence of custom user tables shouldn't suggest an unwise state or prevent a clean installation.
if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table ) {
continue;
}
if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table ) {
continue;
}
$described_table = $wpdb->get_results( "DESCRIBE $table;" );
if (
( ! $described_table && empty( $wpdb->last_error ) ) ||
( is_array( $described_table ) && 0 === count( $described_table ) )
) {
continue;
}
// One or more tables exist. This is not good.
wp_load_translations_early();
// Die with a DB error.
$wpdb->error = sprintf(
/* translators: %s: Database repair URL. */
__( 'One or more database tables are unavailable. The database may need to be <a href="%s">repaired</a>.' ),
'maint/repair.php?referrer=is_blog_installed'
);
dead_db();
}
$wpdb->suppress_errors( $suppress );
wp_cache_set( 'is_blog_installed', false );
return false;
}
```
| Uses | Description |
| --- | --- |
| [wp\_installing()](wp_installing) wp-includes/load.php | Check or set whether WordPress is in “installation” mode. |
| [wp\_cache\_set()](wp_cache_set) wp-includes/cache.php | Saves the data to the cache. |
| [wp\_load\_translations\_early()](wp_load_translations_early) wp-includes/load.php | Attempt an early load of translations. |
| [dead\_db()](dead_db) wp-includes/functions.php | Loads custom DB error or display WordPress DB error. |
| [wp\_load\_alloptions()](wp_load_alloptions) wp-includes/option.php | Loads and caches all autoloaded options, if available or all options. |
| [wpdb::suppress\_errors()](../classes/wpdb/suppress_errors) wp-includes/class-wpdb.php | Enables or disables suppressing of database errors. |
| [wpdb::tables()](../classes/wpdb/tables) wp-includes/class-wpdb.php | Returns an array of WordPress tables. |
| [wp\_cache\_get()](wp_cache_get) wp-includes/cache.php | Retrieves the cache contents from the cache by key and group. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wpdb::get\_var()](../classes/wpdb/get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| [wpdb::get\_results()](../classes/wpdb/get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| Used By | Description |
| --- | --- |
| [wp\_upgrade()](wp_upgrade) wp-admin/includes/upgrade.php | Runs WordPress Upgrade functions. |
| [wp\_not\_installed()](wp_not_installed) wp-includes/load.php | Redirect to the installer if WordPress is not installed. |
| [wp\_widgets\_init()](wp_widgets_init) wp-includes/widgets.php | Registers all of the default WordPress widgets on startup. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress wp_setup_widgets_block_editor() wp\_setup\_widgets\_block\_editor()
===================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Enables the widgets block editor. This is hooked into ‘after\_setup\_theme’ so that the block editor is enabled by default but can be disabled by themes.
File: `wp-includes/widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets.php/)
```
function wp_setup_widgets_block_editor() {
add_theme_support( 'widgets-block-editor' );
}
```
| Uses | Description |
| --- | --- |
| [add\_theme\_support()](add_theme_support) wp-includes/theme.php | Registers theme support for a given feature. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress current_theme_info(): WP_Theme current\_theme\_info(): WP\_Theme
=================================
This function has been deprecated. Use [wp\_get\_theme()](wp_get_theme) instead.
Retrieves information on the current active theme.
* [wp\_get\_theme()](wp_get_theme)
[WP\_Theme](../classes/wp_theme)
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
function current_theme_info() {
_deprecated_function( __FUNCTION__, '3.4.0', 'wp_get_theme()' );
return wp_get_theme();
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_theme()](wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../classes/wp_theme) object for a theme. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Use [wp\_get\_theme()](wp_get_theme) |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress wp_safe_remote_get( string $url, array $args = array() ): array|WP_Error wp\_safe\_remote\_get( string $url, array $args = array() ): array|WP\_Error
============================================================================
Retrieve the raw response from a safe HTTP request using the GET method.
This function is ideal when the HTTP request is being made to an arbitrary URL. The URL is validated to avoid redirection and request forgery attacks.
* [wp\_remote\_request()](wp_remote_request) : For more information on the response array format.
* [WP\_Http::request()](../classes/wp_http/request): For default arguments information.
`$url` string Required URL to retrieve. `$args` array Optional Request arguments. Default: `array()`
array|[WP\_Error](../classes/wp_error) The response or [WP\_Error](../classes/wp_error) on failure.
File: `wp-includes/http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/http.php/)
```
function wp_safe_remote_get( $url, $args = array() ) {
$args['reject_unsafe_urls'] = true;
$http = _wp_http_get_object();
return $http->get( $url, $args );
}
```
| Uses | Description |
| --- | --- |
| [\_wp\_http\_get\_object()](_wp_http_get_object) wp-includes/http.php | Returns the initialized [WP\_Http](../classes/wp_http) Object |
| Used By | Description |
| --- | --- |
| [WP\_REST\_URL\_Details\_Controller::get\_remote\_url()](../classes/wp_rest_url_details_controller/get_remote_url) wp-includes/rest-api/endpoints/class-wp-rest-url-details-controller.php | Retrieves the document title from a remote URL. |
| [download\_url()](download_url) wp-admin/includes/file.php | Downloads a URL to a local temporary file using the WordPress HTTP API. |
| [wp\_remote\_fopen()](wp_remote_fopen) wp-includes/functions.php | HTTP request for URI to retrieve content. |
| [WP\_oEmbed::discover()](../classes/wp_oembed/discover) wp-includes/class-wp-oembed.php | Attempts to discover link tags at the given URL for an oEmbed provider. |
| [WP\_oEmbed::\_fetch\_with\_format()](../classes/wp_oembed/_fetch_with_format) wp-includes/class-wp-oembed.php | Fetches result from an oEmbed provider for a specific format and complete provider URL |
| [wp\_xmlrpc\_server::pingback\_ping()](../classes/wp_xmlrpc_server/pingback_ping) wp-includes/class-wp-xmlrpc-server.php | Retrieves a pingback and registers it. |
| [discover\_pingback\_server\_uri()](discover_pingback_server_uri) wp-includes/comment.php | Finds a pingback server URI based on the given URL. |
| Version | Description |
| --- | --- |
| [3.6.0](https://developer.wordpress.org/reference/since/3.6.0/) | Introduced. |
wordpress wp_edit_attachments_query( array|false $q = false ): array wp\_edit\_attachments\_query( array|false $q = false ): array
=============================================================
Executes a query for attachments. An array of [WP\_Query](../classes/wp_query) arguments can be passed in, which will override the arguments set by this function.
`$q` array|false Optional Array of query variables to use to build the query.
Defaults to the `$_GET` superglobal. Default: `false`
array
File: `wp-admin/includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/post.php/)
```
function wp_edit_attachments_query( $q = false ) {
wp( wp_edit_attachments_query_vars( $q ) );
$post_mime_types = get_post_mime_types();
$avail_post_mime_types = get_available_post_mime_types( 'attachment' );
return array( $post_mime_types, $avail_post_mime_types );
}
```
| Uses | Description |
| --- | --- |
| [wp\_edit\_attachments\_query\_vars()](wp_edit_attachments_query_vars) wp-admin/includes/post.php | Returns the query variables for the current attachments request. |
| [get\_available\_post\_mime\_types()](get_available_post_mime_types) wp-includes/post.php | Gets all available post MIME types for a given post type. |
| [wp()](wp) wp-includes/functions.php | Sets up the WordPress query. |
| [get\_post\_mime\_types()](get_post_mime_types) wp-includes/post.php | Gets default post mime types. |
| Used By | Description |
| --- | --- |
| [media\_upload\_library\_form()](media_upload_library_form) wp-admin/includes/media.php | Outputs the legacy media upload form for the media library. |
| [WP\_Media\_List\_Table::prepare\_items()](../classes/wp_media_list_table/prepare_items) wp-admin/includes/class-wp-media-list-table.php | |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress wp_ajax_get_comments( string $action ) wp\_ajax\_get\_comments( string $action )
=========================================
Ajax handler for getting comments.
`$action` string Required Action to perform. File: `wp-admin/includes/ajax-actions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/ajax-actions.php/)
```
function wp_ajax_get_comments( $action ) {
global $post_id;
if ( empty( $action ) ) {
$action = 'get-comments';
}
check_ajax_referer( $action );
if ( empty( $post_id ) && ! empty( $_REQUEST['p'] ) ) {
$id = absint( $_REQUEST['p'] );
if ( ! empty( $id ) ) {
$post_id = $id;
}
}
if ( empty( $post_id ) ) {
wp_die( -1 );
}
$wp_list_table = _get_list_table( 'WP_Post_Comments_List_Table', array( 'screen' => 'edit-comments' ) );
if ( ! current_user_can( 'edit_post', $post_id ) ) {
wp_die( -1 );
}
$wp_list_table->prepare_items();
if ( ! $wp_list_table->has_items() ) {
wp_die( 1 );
}
$x = new WP_Ajax_Response();
ob_start();
foreach ( $wp_list_table->items as $comment ) {
if ( ! current_user_can( 'edit_comment', $comment->comment_ID ) && 0 === $comment->comment_approved ) {
continue;
}
get_comment( $comment );
$wp_list_table->single_row( $comment );
}
$comment_list_item = ob_get_clean();
$x->add(
array(
'what' => 'comments',
'data' => $comment_list_item,
)
);
$x->send();
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::single\_row()](../classes/wp_list_table/single_row) wp-admin/includes/class-wp-list-table.php | Generates content for a single row of the table. |
| [WP\_List\_Table::prepare\_items()](../classes/wp_list_table/prepare_items) wp-admin/includes/class-wp-list-table.php | Prepares the list of items for displaying. |
| [WP\_List\_Table::has\_items()](../classes/wp_list_table/has_items) wp-admin/includes/class-wp-list-table.php | Whether the table has items to display or not |
| [\_get\_list\_table()](_get_list_table) wp-admin/includes/list-table.php | Fetches an instance of a [WP\_List\_Table](../classes/wp_list_table) class. |
| [WP\_Ajax\_Response::\_\_construct()](../classes/wp_ajax_response/__construct) wp-includes/class-wp-ajax-response.php | Constructor – Passes args to [WP\_Ajax\_Response::add()](../classes/wp_ajax_response/add). |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [check\_ajax\_referer()](check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [absint()](absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [wp\_die()](wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [get\_comment()](get_comment) wp-includes/comment.php | Retrieves comment data given a comment ID or comment object. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress get_boundary_post( bool $in_same_term = false, int[]|string $excluded_terms = '', bool $start = true, string $taxonomy = 'category' ): null|array get\_boundary\_post( bool $in\_same\_term = false, int[]|string $excluded\_terms = '', bool $start = true, string $taxonomy = 'category' ): null|array
======================================================================================================================================================
Retrieves the boundary post.
Boundary being either the first or last post by publish date within the constraints specified by $in\_same\_term or $excluded\_terms.
`$in_same_term` bool Optional Whether returned post should be in a same taxonomy term.
Default: `false`
`$excluded_terms` int[]|string Optional Array or comma-separated list of excluded term IDs.
Default: `''`
`$start` bool Optional Whether to retrieve first or last post. Default true Default: `true`
`$taxonomy` string Optional Taxonomy, if $in\_same\_term is true. Default `'category'`. Default: `'category'`
null|array Array containing the boundary post object if successful, null otherwise.
[get\_boundary\_post()](get_boundary_post) will set the post pointer to the first post.
File: `wp-includes/link-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/link-template.php/)
```
function get_boundary_post( $in_same_term = false, $excluded_terms = '', $start = true, $taxonomy = 'category' ) {
$post = get_post();
if ( ! $post || ! is_single() || is_attachment() || ! taxonomy_exists( $taxonomy ) ) {
return null;
}
$query_args = array(
'posts_per_page' => 1,
'order' => $start ? 'ASC' : 'DESC',
'update_post_term_cache' => false,
'update_post_meta_cache' => false,
);
$term_array = array();
if ( ! is_array( $excluded_terms ) ) {
if ( ! empty( $excluded_terms ) ) {
$excluded_terms = explode( ',', $excluded_terms );
} else {
$excluded_terms = array();
}
}
if ( $in_same_term || ! empty( $excluded_terms ) ) {
if ( $in_same_term ) {
$term_array = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
}
if ( ! empty( $excluded_terms ) ) {
$excluded_terms = array_map( 'intval', $excluded_terms );
$excluded_terms = array_diff( $excluded_terms, $term_array );
$inverse_terms = array();
foreach ( $excluded_terms as $excluded_term ) {
$inverse_terms[] = $excluded_term * -1;
}
$excluded_terms = $inverse_terms;
}
$query_args['tax_query'] = array(
array(
'taxonomy' => $taxonomy,
'terms' => array_merge( $term_array, $excluded_terms ),
),
);
}
return get_posts( $query_args );
}
```
| Uses | Description |
| --- | --- |
| [is\_single()](is_single) wp-includes/query.php | Determines whether the query is for an existing single post. |
| [is\_attachment()](is_attachment) wp-includes/query.php | Determines whether the query is for an existing attachment page. |
| [wp\_get\_object\_terms()](wp_get_object_terms) wp-includes/taxonomy.php | Retrieves the terms associated with the given object(s), in the supplied taxonomies. |
| [taxonomy\_exists()](taxonomy_exists) wp-includes/taxonomy.php | Determines whether the taxonomy name exists. |
| [get\_posts()](get_posts) wp-includes/post.php | Retrieves an array of the latest posts, or posts matching the given criteria. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [get\_boundary\_post\_rel\_link()](get_boundary_post_rel_link) wp-includes/deprecated.php | Get boundary post relational link. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
| programming_docs |
wordpress make_clickable( string $text ): string make\_clickable( string $text ): string
=======================================
Converts plaintext URI to HTML links.
Converts URI, www and ftp, and email addresses. Finishes by fixing links within links.
`$text` string Required Content to convert URIs. string Content with converted URIs.
This function can be fed long strings with URIs and email links and will convert them into clickable links. You are not limited to feeding it just the link text itself (see the long string in the example above).
File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function make_clickable( $text ) {
$r = '';
$textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // Split out HTML tags.
$nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>.
foreach ( $textarr as $piece ) {
if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) || preg_match( '|^<script[\s>]|i', $piece ) || preg_match( '|^<style[\s>]|i', $piece ) ) {
$nested_code_pre++;
} elseif ( $nested_code_pre && ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) || '</script>' === strtolower( $piece ) || '</style>' === strtolower( $piece ) ) ) {
$nested_code_pre--;
}
if ( $nested_code_pre || empty( $piece ) || ( '<' === $piece[0] && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
$r .= $piece;
continue;
}
// Long strings might contain expensive edge cases...
if ( 10000 < strlen( $piece ) ) {
// ...break it up.
foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses.
if ( 2101 < strlen( $chunk ) ) {
$r .= $chunk; // Too big, no whitespace: bail.
} else {
$r .= make_clickable( $chunk );
}
}
} else {
$ret = " $piece "; // Pad with whitespace to simplify the regexes.
$url_clickable = '~
([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation.
( # 2: URL.
[\\w]{1,20}+:// # Scheme and hier-part prefix.
(?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long.
[\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character.
(?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character.
[\'.,;:!?)] # Punctuation URL character.
[\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character.
)*
)
(\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing).
~xS';
// The regex is a non-anchored pattern and does not have a single fixed starting character.
// Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
$ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
$ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
$ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
$ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
$r .= $ret;
}
}
// Cleanup of accidental links within links.
return preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', '$1$3</a>', $r );
}
```
| Uses | Description |
| --- | --- |
| [\_split\_str\_by\_whitespace()](_split_str_by_whitespace) wp-includes/formatting.php | Breaks a string into chunks by splitting at whitespace characters. |
| [make\_clickable()](make_clickable) wp-includes/formatting.php | Converts plaintext URI to HTML links. |
| Used By | Description |
| --- | --- |
| [make\_clickable()](make_clickable) wp-includes/formatting.php | Converts plaintext URI to HTML links. |
| Version | Description |
| --- | --- |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress page_attributes_meta_box( WP_Post $post ) page\_attributes\_meta\_box( WP\_Post $post )
=============================================
Displays page attributes form fields.
`$post` [WP\_Post](../classes/wp_post) Required Current post object. File: `wp-admin/includes/meta-boxes.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/meta-boxes.php/)
```
function page_attributes_meta_box( $post ) {
if ( is_post_type_hierarchical( $post->post_type ) ) :
$dropdown_args = array(
'post_type' => $post->post_type,
'exclude_tree' => $post->ID,
'selected' => $post->post_parent,
'name' => 'parent_id',
'show_option_none' => __( '(no parent)' ),
'sort_column' => 'menu_order, post_title',
'echo' => 0,
);
/**
* Filters the arguments used to generate a Pages drop-down element.
*
* @since 3.3.0
*
* @see wp_dropdown_pages()
*
* @param array $dropdown_args Array of arguments used to generate the pages drop-down.
* @param WP_Post $post The current post.
*/
$dropdown_args = apply_filters( 'page_attributes_dropdown_pages_args', $dropdown_args, $post );
$pages = wp_dropdown_pages( $dropdown_args );
if ( ! empty( $pages ) ) :
?>
<p class="post-attributes-label-wrapper parent-id-label-wrapper"><label class="post-attributes-label" for="parent_id"><?php _e( 'Parent' ); ?></label></p>
<?php echo $pages; ?>
<?php
endif; // End empty pages check.
endif; // End hierarchical check.
if ( count( get_page_templates( $post ) ) > 0 && get_option( 'page_for_posts' ) != $post->ID ) :
$template = ! empty( $post->page_template ) ? $post->page_template : false;
?>
<p class="post-attributes-label-wrapper page-template-label-wrapper"><label class="post-attributes-label" for="page_template"><?php _e( 'Template' ); ?></label>
<?php
/**
* Fires immediately after the label inside the 'Template' section
* of the 'Page Attributes' meta box.
*
* @since 4.4.0
*
* @param string|false $template The template used for the current post.
* @param WP_Post $post The current post.
*/
do_action( 'page_attributes_meta_box_template', $template, $post );
?>
</p>
<select name="page_template" id="page_template">
<?php
/**
* Filters the title of the default page template displayed in the drop-down.
*
* @since 4.1.0
*
* @param string $label The display value for the default page template title.
* @param string $context Where the option label is displayed. Possible values
* include 'meta-box' or 'quick-edit'.
*/
$default_title = apply_filters( 'default_page_template_title', __( 'Default template' ), 'meta-box' );
?>
<option value="default"><?php echo esc_html( $default_title ); ?></option>
<?php page_template_dropdown( $template, $post->post_type ); ?>
</select>
<?php endif; ?>
<?php if ( post_type_supports( $post->post_type, 'page-attributes' ) ) : ?>
<p class="post-attributes-label-wrapper menu-order-label-wrapper"><label class="post-attributes-label" for="menu_order"><?php _e( 'Order' ); ?></label></p>
<input name="menu_order" type="text" size="4" id="menu_order" value="<?php echo esc_attr( $post->menu_order ); ?>" />
<?php
/**
* Fires before the help hint text in the 'Page Attributes' meta box.
*
* @since 4.9.0
*
* @param WP_Post $post The current post.
*/
do_action( 'page_attributes_misc_attributes', $post );
?>
<?php if ( 'page' === $post->post_type && get_current_screen()->get_help_tabs() ) : ?>
<p class="post-attributes-help-text"><?php _e( 'Need help? Use the Help tab above the screen title.' ); ?></p>
<?php
endif;
endif;
}
```
[apply\_filters( 'default\_page\_template\_title', string $label, string $context )](../hooks/default_page_template_title)
Filters the title of the default page template displayed in the drop-down.
[apply\_filters( 'page\_attributes\_dropdown\_pages\_args', array $dropdown\_args, WP\_Post $post )](../hooks/page_attributes_dropdown_pages_args)
Filters the arguments used to generate a Pages drop-down element.
[do\_action( 'page\_attributes\_meta\_box\_template', string|false $template, WP\_Post $post )](../hooks/page_attributes_meta_box_template)
Fires immediately after the label inside the ‘Template’ section of the ‘Page Attributes’ meta box.
[do\_action( 'page\_attributes\_misc\_attributes', WP\_Post $post )](../hooks/page_attributes_misc_attributes)
Fires before the help hint text in the ‘Page Attributes’ meta box.
| Uses | Description |
| --- | --- |
| [get\_page\_templates()](get_page_templates) wp-admin/includes/theme.php | Gets the page templates available in this theme. |
| [WP\_Screen::get\_help\_tabs()](../classes/wp_screen/get_help_tabs) wp-admin/includes/class-wp-screen.php | Gets the help tabs registered for the screen. |
| [get\_current\_screen()](get_current_screen) wp-admin/includes/screen.php | Get the current screen object |
| [page\_template\_dropdown()](page_template_dropdown) wp-admin/includes/template.php | Prints out option HTML elements for the page templates drop-down. |
| [wp\_dropdown\_pages()](wp_dropdown_pages) wp-includes/post-template.php | Retrieves or displays a list of pages as a dropdown (select list). |
| [post\_type\_supports()](post_type_supports) wp-includes/post.php | Checks a post type’s support for a given feature. |
| [is\_post\_type\_hierarchical()](is_post_type_hierarchical) wp-includes/post.php | Determines whether the post type is hierarchical. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_e()](_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress is_term( int|string $term, string $taxonomy = '', int $parent ): mixed is\_term( int|string $term, string $taxonomy = '', int $parent ): mixed
=======================================================================
This function has been deprecated. Use [term\_exists()](term_exists) instead.
Check if Term exists.
* [term\_exists()](term_exists)
`$term` int|string Required The term to check `$taxonomy` string Optional The taxonomy name to use Default: `''`
`$parent` int Required ID of parent term under which to confine the exists search. mixed Get the term ID or term object, if exists.
File: `wp-includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/deprecated.php/)
```
function is_term( $term, $taxonomy = '', $parent = 0 ) {
_deprecated_function( __FUNCTION__, '3.0.0', 'term_exists()' );
return term_exists( $term, $taxonomy, $parent );
}
```
| Uses | Description |
| --- | --- |
| [term\_exists()](term_exists) wp-includes/taxonomy.php | Determines whether a taxonomy term exists. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Use [term\_exists()](term_exists) |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
wordpress add_user_meta( int $user_id, string $meta_key, mixed $meta_value, bool $unique = false ): int|false add\_user\_meta( int $user\_id, string $meta\_key, mixed $meta\_value, bool $unique = false ): int|false
========================================================================================================
Adds meta data to a user.
`$user_id` int Required User ID. `$meta_key` string Required Metadata name. `$meta_value` mixed Required Metadata value. Must be serializable if non-scalar. `$unique` bool Optional Whether the same key should not be added.
Default: `false`
int|false Meta ID on success, false on failure.
File: `wp-includes/user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/user.php/)
```
function add_user_meta( $user_id, $meta_key, $meta_value, $unique = false ) {
return add_metadata( 'user', $user_id, $meta_key, $meta_value, $unique );
}
```
| Uses | Description |
| --- | --- |
| [add\_metadata()](add_metadata) wp-includes/meta.php | Adds metadata for the specified object. |
| Used By | Description |
| --- | --- |
| [WP\_Internal\_Pointers::dismiss\_pointers\_for\_new\_users()](../classes/wp_internal_pointers/dismiss_pointers_for_new_users) wp-admin/includes/class-wp-internal-pointers.php | Prevents new users from seeing existing ‘new feature’ pointers. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress got_mod_rewrite(): bool got\_mod\_rewrite(): bool
=========================
Returns whether the server is running Apache with the mod\_rewrite module loaded.
bool Whether the server is running Apache with the mod\_rewrite module loaded.
File: `wp-admin/includes/misc.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/misc.php/)
```
function got_mod_rewrite() {
$got_rewrite = apache_mod_loaded( 'mod_rewrite', true );
/**
* Filters whether Apache and mod_rewrite are present.
*
* This filter was previously used to force URL rewriting for other servers,
* like nginx. Use the {@see 'got_url_rewrite'} filter in got_url_rewrite() instead.
*
* @since 2.5.0
*
* @see got_url_rewrite()
*
* @param bool $got_rewrite Whether Apache and mod_rewrite are present.
*/
return apply_filters( 'got_rewrite', $got_rewrite );
}
```
[apply\_filters( 'got\_rewrite', bool $got\_rewrite )](../hooks/got_rewrite)
Filters whether Apache and mod\_rewrite are present.
| Uses | Description |
| --- | --- |
| [apache\_mod\_loaded()](apache_mod_loaded) wp-includes/functions.php | Determines whether the specified module exist in the Apache config. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::get\_test\_authorization\_header()](../classes/wp_site_health/get_test_authorization_header) wp-admin/includes/class-wp-site-health.php | Tests if the Authorization header has the expected values. |
| [network\_step1()](network_step1) wp-admin/includes/network.php | Prints step 1 for Network installation process. |
| [save\_mod\_rewrite\_rules()](save_mod_rewrite_rules) wp-admin/includes/misc.php | Updates the htaccess file with the current rules if it is writable. |
| [got\_url\_rewrite()](got_url_rewrite) wp-admin/includes/misc.php | Returns whether the server supports URL rewriting. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress do_accordion_sections( string|object $screen, string $context, mixed $data_object ): int do\_accordion\_sections( string|object $screen, string $context, mixed $data\_object ): int
===========================================================================================
Meta Box Accordion Template Function.
Largely made up of abstracted code from [do\_meta\_boxes()](do_meta_boxes) , this function serves to build meta boxes as list items for display as a collapsible accordion.
`$screen` string|object Required The screen identifier. `$context` string Required The screen context for which to display accordion sections. `$data_object` mixed Required Gets passed to the section callback function as the first parameter. int Number of meta boxes as accordion sections.
File: `wp-admin/includes/template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/template.php/)
```
function do_accordion_sections( $screen, $context, $data_object ) {
global $wp_meta_boxes;
wp_enqueue_script( 'accordion' );
if ( empty( $screen ) ) {
$screen = get_current_screen();
} elseif ( is_string( $screen ) ) {
$screen = convert_to_screen( $screen );
}
$page = $screen->id;
$hidden = get_hidden_meta_boxes( $screen );
?>
<div id="side-sortables" class="accordion-container">
<ul class="outer-border">
<?php
$i = 0;
$first_open = false;
if ( isset( $wp_meta_boxes[ $page ][ $context ] ) ) {
foreach ( array( 'high', 'core', 'default', 'low' ) as $priority ) {
if ( isset( $wp_meta_boxes[ $page ][ $context ][ $priority ] ) ) {
foreach ( $wp_meta_boxes[ $page ][ $context ][ $priority ] as $box ) {
if ( false === $box || ! $box['title'] ) {
continue;
}
$i++;
$hidden_class = in_array( $box['id'], $hidden, true ) ? 'hide-if-js' : '';
$open_class = '';
if ( ! $first_open && empty( $hidden_class ) ) {
$first_open = true;
$open_class = 'open';
}
?>
<li class="control-section accordion-section <?php echo $hidden_class; ?> <?php echo $open_class; ?> <?php echo esc_attr( $box['id'] ); ?>" id="<?php echo esc_attr( $box['id'] ); ?>">
<h3 class="accordion-section-title hndle" tabindex="0">
<?php echo esc_html( $box['title'] ); ?>
<span class="screen-reader-text"><?php _e( 'Press return or enter to open this section' ); ?></span>
</h3>
<div class="accordion-section-content <?php postbox_classes( $box['id'], $page ); ?>">
<div class="inside">
<?php call_user_func( $box['callback'], $data_object, $box ); ?>
</div><!-- .inside -->
</div><!-- .accordion-section-content -->
</li><!-- .accordion-section -->
<?php
}
}
}
}
?>
</ul><!-- .outer-border -->
</div><!-- .accordion-container -->
<?php
return $i;
}
```
| Uses | Description |
| --- | --- |
| [get\_current\_screen()](get_current_screen) wp-admin/includes/screen.php | Get the current screen object |
| [get\_hidden\_meta\_boxes()](get_hidden_meta_boxes) wp-admin/includes/screen.php | Gets an array of IDs of hidden meta boxes. |
| [convert\_to\_screen()](convert_to_screen) wp-admin/includes/template.php | Converts a screen string to a screen object. |
| [postbox\_classes()](postbox_classes) wp-admin/includes/post.php | Returns the list of classes to be used by a meta box. |
| [wp\_enqueue\_script()](wp_enqueue_script) wp-includes/functions.wp-scripts.php | Enqueue a script. |
| [\_e()](_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| Version | Description |
| --- | --- |
| [3.6.0](https://developer.wordpress.org/reference/since/3.6.0/) | Introduced. |
wordpress has_action( string $hook_name, callable|string|array|false $callback = false ): bool|int has\_action( string $hook\_name, callable|string|array|false $callback = false ): bool|int
==========================================================================================
Checks if any action has been registered for a hook.
When using the `$callback` argument, this function may return a non-boolean value that evaluates to false (e.g. 0), so use the `===` operator for testing the return value.
* [has\_filter()](has_filter) : [has\_action()](has_action) is an alias of [has\_filter()](has_filter) .
`$hook_name` string Required The name of the action hook. `$callback` callable|string|array|false Optional The callback to check for.
This function can be called unconditionally to speculatively check a callback that may or may not exist. Default: `false`
bool|int If `$callback` is omitted, returns boolean for whether the hook has anything registered. When checking a specific function, the priority of that hook is returned, or false if the function is not attached.
Since this action is an alias of [has\_filter()](has_filter) , it also uses the global array $wp\_filter that stores all of the filters / actions.
File: `wp-includes/plugin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/plugin.php/)
```
function has_action( $hook_name, $callback = false ) {
return has_filter( $hook_name, $callback );
}
```
| Uses | Description |
| --- | --- |
| [has\_filter()](has_filter) wp-includes/plugin.php | Checks if any filter has been registered for a hook. |
| Used By | Description |
| --- | --- |
| [wp\_maybe\_enqueue\_oembed\_host\_js()](wp_maybe_enqueue_oembed_host_js) wp-includes/embed.php | Enqueue the wp-embed script if the provided oEmbed HTML contains a post embed. |
| [wp\_is\_local\_html\_output()](wp_is_local_html_output) wp-includes/https-detection.php | Checks whether a given HTML string is likely an output from this WordPress site. |
| [wp\_insert\_site()](wp_insert_site) wp-includes/ms-site.php | Inserts a new site into the database. |
| [WP\_Customize\_Manager::save\_changeset\_post()](../classes/wp_customize_manager/save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [do\_action\_deprecated()](do_action_deprecated) wp-includes/plugin.php | Fires functions attached to a deprecated action hook. |
| [WP\_Screen::render\_meta\_boxes\_preferences()](../classes/wp_screen/render_meta_boxes_preferences) wp-admin/includes/class-wp-screen.php | Renders the meta boxes preferences. |
| [wp\_admin\_bar\_customize\_menu()](wp_admin_bar_customize_menu) wp-includes/admin-bar.php | Adds the “Customize” link to the Toolbar. |
| [display\_setup\_form()](display_setup_form) wp-admin/install.php | Displays installer setup form. |
| [get\_plugin\_page\_hook()](get_plugin_page_hook) wp-admin/includes/plugin.php | Gets the hook attached to the administrative page of a plugin. |
| [do\_feed()](do_feed) wp-includes/functions.php | Loads the feed template from the use of an action hook. |
| [WP\_Customize\_Setting::preview()](../classes/wp_customize_setting/preview) wp-includes/class-wp-customize-setting.php | Add filters to supply the setting’s value when accessed. |
| [WP\_Customize\_Setting::update()](../classes/wp_customize_setting/update) wp-includes/class-wp-customize-setting.php | Save the value of the setting, using the related API. |
| [comment\_form()](comment_form) wp-includes/comment-template.php | Outputs a complete commenting form for use within a template. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
| programming_docs |
wordpress wp_title_rss( string $deprecated = '–' ) wp\_title\_rss( string $deprecated = '–' )
==========================================
Displays the blog title for display of the feed title.
`$deprecated` string Optional Unused. Default: `'–'`
File: `wp-includes/feed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/feed.php/)
```
function wp_title_rss( $deprecated = '–' ) {
if ( '–' !== $deprecated ) {
/* translators: %s: 'document_title_separator' filter name. */
_deprecated_argument( __FUNCTION__, '4.4.0', sprintf( __( 'Use the %s filter instead.' ), '<code>document_title_separator</code>' ) );
}
/**
* Filters the blog title for display of the feed title.
*
* @since 2.2.0
* @since 4.4.0 The `$sep` parameter was deprecated and renamed to `$deprecated`.
*
* @see get_wp_title_rss()
*
* @param string $wp_title_rss The current blog title.
* @param string $deprecated Unused.
*/
echo apply_filters( 'wp_title_rss', get_wp_title_rss(), $deprecated );
}
```
[apply\_filters( 'wp\_title\_rss', string $wp\_title\_rss, string $deprecated )](../hooks/wp_title_rss)
Filters the blog title for display of the feed title.
| Uses | Description |
| --- | --- |
| [get\_wp\_title\_rss()](get_wp_title_rss) wp-includes/feed.php | Retrieves the blog title for the feed title. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_deprecated\_argument()](_deprecated_argument) wp-includes/functions.php | Marks a function argument as deprecated and inform when it has been used. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | The optional `$sep` parameter was deprecated and renamed to `$deprecated`. |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Introduced. |
wordpress _c( string $text, string $domain = 'default' ): string \_c( string $text, string $domain = 'default' ): string
=======================================================
This function has been deprecated. Use [\_x()](_x) instead.
Retrieve translated string with vertical bar context
Quite a few times, there will be collisions with similar translatable text found in more than two places but with different translated context.
In order to use the separate contexts, the [\_c()](_c) function is used and the translatable string uses a pipe (‘|’) which has the context the string is in.
When the translated string is returned, it is everything before the pipe, not including the pipe character. If there is no pipe in the translated text then everything is returned.
* [\_x()](_x)
`$text` string Required Text to translate. `$domain` string Optional Domain to retrieve the translated text. Default: `'default'`
string Translated context string without pipe.
File: `wp-includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/deprecated.php/)
```
function _c( $text, $domain = 'default' ) {
_deprecated_function( __FUNCTION__, '2.9.0', '_x()' );
return before_last_bar( translate( $text, $domain ) );
}
```
| Uses | Description |
| --- | --- |
| [before\_last\_bar()](before_last_bar) wp-includes/l10n.php | Removes last item on a pipe-delimited string. |
| [translate()](translate) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [2.9.0](https://developer.wordpress.org/reference/since/2.9.0/) | Use [\_x()](_x) |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Introduced. |
wordpress find_core_update( string $version, string $locale ): object|false find\_core\_update( string $version, string $locale ): object|false
===================================================================
Finds the available update for WordPress core.
`$version` string Required Version string to find the update for. `$locale` string Required Locale to find the update for. object|false The core update offering on success, false on failure.
File: `wp-admin/includes/update.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/update.php/)
```
function find_core_update( $version, $locale ) {
$from_api = get_site_transient( 'update_core' );
if ( ! isset( $from_api->updates ) || ! is_array( $from_api->updates ) ) {
return false;
}
$updates = $from_api->updates;
foreach ( $updates as $update ) {
if ( $update->current == $version && $update->locale == $locale ) {
return $update;
}
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [get\_site\_transient()](get_site_transient) wp-includes/option.php | Retrieves the value of a site transient. |
| Used By | Description |
| --- | --- |
| [do\_core\_upgrade()](do_core_upgrade) wp-admin/update-core.php | Upgrade WordPress core display. |
| [do\_dismiss\_core\_update()](do_dismiss_core_update) wp-admin/update-core.php | Dismiss a core update. |
| [do\_undismiss\_core\_update()](do_undismiss_core_update) wp-admin/update-core.php | Undismiss a core update. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress get_term_feed_link( int|WP_Term|object $term, string $taxonomy = '', string $feed = '' ): string|false get\_term\_feed\_link( int|WP\_Term|object $term, string $taxonomy = '', string $feed = '' ): string|false
==========================================================================================================
Retrieves the feed link for a term.
Returns a link to the feed for all posts in a given term. A specific feed can be requested or left blank to get the default feed.
`$term` int|[WP\_Term](../classes/wp_term)|object Required The ID or term object whose feed link will be retrieved. `$taxonomy` string Optional Taxonomy of `$term_id`. Default: `''`
`$feed` string Optional Feed type. Possible values include `'rss2'`, `'atom'`.
Default is the value of [get\_default\_feed()](get_default_feed) . Default: `''`
string|false Link to the feed for the term specified by `$term` and `$taxonomy`.
File: `wp-includes/link-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/link-template.php/)
```
function get_term_feed_link( $term, $taxonomy = '', $feed = '' ) {
if ( ! is_object( $term ) ) {
$term = (int) $term;
}
$term = get_term( $term, $taxonomy );
if ( empty( $term ) || is_wp_error( $term ) ) {
return false;
}
$taxonomy = $term->taxonomy;
if ( empty( $feed ) ) {
$feed = get_default_feed();
}
$permalink_structure = get_option( 'permalink_structure' );
if ( ! $permalink_structure ) {
if ( 'category' === $taxonomy ) {
$link = home_url( "?feed=$feed&cat=$term->term_id" );
} elseif ( 'post_tag' === $taxonomy ) {
$link = home_url( "?feed=$feed&tag=$term->slug" );
} else {
$t = get_taxonomy( $taxonomy );
$link = home_url( "?feed=$feed&$t->query_var=$term->slug" );
}
} else {
$link = get_term_link( $term, $term->taxonomy );
if ( get_default_feed() == $feed ) {
$feed_link = 'feed';
} else {
$feed_link = "feed/$feed";
}
$link = trailingslashit( $link ) . user_trailingslashit( $feed_link, 'feed' );
}
if ( 'category' === $taxonomy ) {
/**
* Filters the category feed link.
*
* @since 1.5.1
*
* @param string $link The category feed link.
* @param string $feed Feed type. Possible values include 'rss2', 'atom'.
*/
$link = apply_filters( 'category_feed_link', $link, $feed );
} elseif ( 'post_tag' === $taxonomy ) {
/**
* Filters the post tag feed link.
*
* @since 2.3.0
*
* @param string $link The tag feed link.
* @param string $feed Feed type. Possible values include 'rss2', 'atom'.
*/
$link = apply_filters( 'tag_feed_link', $link, $feed );
} else {
/**
* Filters the feed link for a taxonomy other than 'category' or 'post_tag'.
*
* @since 3.0.0
*
* @param string $link The taxonomy feed link.
* @param string $feed Feed type. Possible values include 'rss2', 'atom'.
* @param string $taxonomy The taxonomy name.
*/
$link = apply_filters( 'taxonomy_feed_link', $link, $feed, $taxonomy );
}
return $link;
}
```
[apply\_filters( 'category\_feed\_link', string $link, string $feed )](../hooks/category_feed_link)
Filters the category feed link.
[apply\_filters( 'tag\_feed\_link', string $link, string $feed )](../hooks/tag_feed_link)
Filters the post tag feed link.
[apply\_filters( 'taxonomy\_feed\_link', string $link, string $feed, string $taxonomy )](../hooks/taxonomy_feed_link)
Filters the feed link for a taxonomy other than ‘category’ or ‘post\_tag’.
| Uses | Description |
| --- | --- |
| [get\_term\_link()](get_term_link) wp-includes/taxonomy.php | Generates a permalink for a taxonomy term archive. |
| [user\_trailingslashit()](user_trailingslashit) wp-includes/link-template.php | Retrieves a trailing-slashed string if the site is set for adding trailing slashes. |
| [get\_default\_feed()](get_default_feed) wp-includes/feed.php | Retrieves the default feed. |
| [trailingslashit()](trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| [get\_term()](get_term) wp-includes/taxonomy.php | Gets all term data from database by term ID. |
| [get\_taxonomy()](get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| [home\_url()](home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [Walker\_Category::start\_el()](../classes/walker_category/start_el) wp-includes/class-walker-category.php | Starts the element output. |
| [feed\_links\_extra()](feed_links_extra) wp-includes/general-template.php | Displays the links to the extra feeds such as category feeds. |
| [get\_tag\_feed\_link()](get_tag_feed_link) wp-includes/link-template.php | Retrieves the permalink for a tag feed. |
| [get\_category\_feed\_link()](get_category_feed_link) wp-includes/link-template.php | Retrieves the feed link for a category. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress get_edit_tag_link( int|WP_Term|object $tag, string $taxonomy = 'post_tag' ): string get\_edit\_tag\_link( int|WP\_Term|object $tag, string $taxonomy = 'post\_tag' ): string
========================================================================================
Retrieves the edit link for a tag.
`$tag` int|[WP\_Term](../classes/wp_term)|object Required The ID or term object whose edit link will be retrieved. `$taxonomy` string Optional Taxonomy slug. Default `'post_tag'`. Default: `'post_tag'`
string The edit tag link URL for the given tag.
File: `wp-includes/link-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/link-template.php/)
```
function get_edit_tag_link( $tag, $taxonomy = 'post_tag' ) {
/**
* Filters the edit link for a tag (or term in another taxonomy).
*
* @since 2.7.0
*
* @param string $link The term edit link.
*/
return apply_filters( 'get_edit_tag_link', get_edit_term_link( $tag, $taxonomy ) );
}
```
[apply\_filters( 'get\_edit\_tag\_link', string $link )](../hooks/get_edit_tag_link)
Filters the edit link for a tag (or term in another taxonomy).
| Uses | Description |
| --- | --- |
| [get\_edit\_term\_link()](get_edit_term_link) wp-includes/link-template.php | Retrieves the URL for editing a given term. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress is_privacy_policy(): bool is\_privacy\_policy(): bool
===========================
Determines whether the query is for the Privacy Policy page.
The Privacy Policy page is the page that shows the Privacy Policy content of the site.
[is\_privacy\_policy()](is_privacy_policy) is dependent on the site’s "Change your Privacy Policy page" Privacy Settings ‘wp\_page\_for\_privacy\_policy’.
This function will return true only on the page you set as the "Privacy Policy page".
For more information on this and similar theme functions, check out the [Conditional Tags](https://developer.wordpress.org/themes/basics/conditional-tags/) article in the Theme Developer Handbook.
bool Whether the query is for the Privacy Policy page.
File: `wp-includes/query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/query.php/)
```
function is_privacy_policy() {
global $wp_query;
if ( ! isset( $wp_query ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
return false;
}
return $wp_query->is_privacy_policy();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Query::is\_privacy\_policy()](../classes/wp_query/is_privacy_policy) wp-includes/class-wp-query.php | Is the query for the Privacy Policy page? |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_doing\_it\_wrong()](_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Used By | Description |
| --- | --- |
| [get\_body\_class()](get_body_class) wp-includes/post-template.php | Retrieves an array of the class names for the body element. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress register_new_user( string $user_login, string $user_email ): int|WP_Error register\_new\_user( string $user\_login, string $user\_email ): int|WP\_Error
==============================================================================
Handles registering a new user.
`$user_login` string Required User's username for logging in `$user_email` string Required User's email address to send password and add int|[WP\_Error](../classes/wp_error) Either user's ID or error on failure.
The **[register\_new\_user()](register_new_user)** function inserts a new user into the WordPress database. This function is used when a new user registers through WordPress’ Login Page. It differs from [wp\_create\_user()](wp_create_user) in that it requires a valid username and email address but doesn’t allow to choose a password, generating a random one using [wp\_generate\_password()](wp_generate_password) . If you want to create a new user with a specific password or with additional parameters, use [wp\_create\_user()](wp_create_user) or [wp\_insert\_user()](wp_insert_user) instead.
**[register\_new\_user()](register_new_user)** doesn’t handle the user creation itself, it simply checks the submitted username and email validity and generates a random password, relying on [wp\_create\_user()](wp_create_user) to create the new User. If registration worked it sends a notification email to the user with his password using [wp\_new\_user\_notification()](wp_new_user_notification) . In case of registration failure it returns a [WP\_Error](../classes/wp_error)().
[register\_new\_user()](register_new_user) also provides two useful hooks to customize validation rules or user registration process, [register\_post](https://codex.wordpress.org/Plugin_API/Action_Reference/register_post "Plugin API/Action Reference/register post") and [registration\_errors](https://codex.wordpress.org/Plugin_API/Filter_Reference/registration_errors "Plugin API/Filter Reference/registration errors").
File: `wp-includes/user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/user.php/)
```
function register_new_user( $user_login, $user_email ) {
$errors = new WP_Error();
$sanitized_user_login = sanitize_user( $user_login );
/**
* Filters the email address of a user being registered.
*
* @since 2.1.0
*
* @param string $user_email The email address of the new user.
*/
$user_email = apply_filters( 'user_registration_email', $user_email );
// Check the username.
if ( '' === $sanitized_user_login ) {
$errors->add( 'empty_username', __( '<strong>Error:</strong> Please enter a username.' ) );
} elseif ( ! validate_username( $user_login ) ) {
$errors->add( 'invalid_username', __( '<strong>Error:</strong> This username is invalid because it uses illegal characters. Please enter a valid username.' ) );
$sanitized_user_login = '';
} elseif ( username_exists( $sanitized_user_login ) ) {
$errors->add( 'username_exists', __( '<strong>Error:</strong> This username is already registered. Please choose another one.' ) );
} else {
/** This filter is documented in wp-includes/user.php */
$illegal_user_logins = (array) apply_filters( 'illegal_user_logins', array() );
if ( in_array( strtolower( $sanitized_user_login ), array_map( 'strtolower', $illegal_user_logins ), true ) ) {
$errors->add( 'invalid_username', __( '<strong>Error:</strong> Sorry, that username is not allowed.' ) );
}
}
// Check the email address.
if ( '' === $user_email ) {
$errors->add( 'empty_email', __( '<strong>Error:</strong> Please type your email address.' ) );
} elseif ( ! is_email( $user_email ) ) {
$errors->add( 'invalid_email', __( '<strong>Error:</strong> The email address is not correct.' ) );
$user_email = '';
} elseif ( email_exists( $user_email ) ) {
$errors->add(
'email_exists',
sprintf(
/* translators: %s: Link to the login page. */
__( '<strong>Error:</strong> This email address is already registered. <a href="%s">Log in</a> with this address or choose another one.' ),
wp_login_url()
)
);
}
/**
* Fires when submitting registration form data, before the user is created.
*
* @since 2.1.0
*
* @param string $sanitized_user_login The submitted username after being sanitized.
* @param string $user_email The submitted email.
* @param WP_Error $errors Contains any errors with submitted username and email,
* e.g., an empty field, an invalid username or email,
* or an existing username or email.
*/
do_action( 'register_post', $sanitized_user_login, $user_email, $errors );
/**
* Filters the errors encountered when a new user is being registered.
*
* The filtered WP_Error object may, for example, contain errors for an invalid
* or existing username or email address. A WP_Error object should always be returned,
* but may or may not contain errors.
*
* If any errors are present in $errors, this will abort the user's registration.
*
* @since 2.1.0
*
* @param WP_Error $errors A WP_Error object containing any errors encountered
* during registration.
* @param string $sanitized_user_login User's username after it has been sanitized.
* @param string $user_email User's email.
*/
$errors = apply_filters( 'registration_errors', $errors, $sanitized_user_login, $user_email );
if ( $errors->has_errors() ) {
return $errors;
}
$user_pass = wp_generate_password( 12, false );
$user_id = wp_create_user( $sanitized_user_login, $user_pass, $user_email );
if ( ! $user_id || is_wp_error( $user_id ) ) {
$errors->add(
'registerfail',
sprintf(
/* translators: %s: Admin email address. */
__( '<strong>Error:</strong> Could not register you… please contact the <a href="mailto:%s">site admin</a>!' ),
get_option( 'admin_email' )
)
);
return $errors;
}
update_user_meta( $user_id, 'default_password_nag', true ); // Set up the password change nag.
if ( ! empty( $_COOKIE['wp_lang'] ) ) {
$wp_lang = sanitize_text_field( $_COOKIE['wp_lang'] );
if ( in_array( $wp_lang, get_available_languages(), true ) ) {
update_user_meta( $user_id, 'locale', $wp_lang ); // Set user locale if defined on registration.
}
}
/**
* Fires after a new user registration has been recorded.
*
* @since 4.4.0
*
* @param int $user_id ID of the newly registered user.
*/
do_action( 'register_new_user', $user_id );
return $user_id;
}
```
[apply\_filters( 'illegal\_user\_logins', array $usernames )](../hooks/illegal_user_logins)
Filters the list of disallowed usernames.
[do\_action( 'register\_new\_user', int $user\_id )](../hooks/register_new_user)
Fires after a new user registration has been recorded.
[do\_action( 'register\_post', string $sanitized\_user\_login, string $user\_email, WP\_Error $errors )](../hooks/register_post)
Fires when submitting registration form data, before the user is created.
[apply\_filters( 'registration\_errors', WP\_Error $errors, string $sanitized\_user\_login, string $user\_email )](../hooks/registration_errors)
Filters the errors encountered when a new user is being registered.
[apply\_filters( 'user\_registration\_email', string $user\_email )](../hooks/user_registration_email)
Filters the email address of a user being registered.
| Uses | Description |
| --- | --- |
| [get\_available\_languages()](get_available_languages) wp-includes/l10n.php | Gets all available languages based on the presence of \*.mo files in a given directory. |
| [username\_exists()](username_exists) wp-includes/user.php | Determines whether the given username exists. |
| [sanitize\_text\_field()](sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [is\_email()](is_email) wp-includes/formatting.php | Verifies that an email is valid. |
| [sanitize\_user()](sanitize_user) wp-includes/formatting.php | Sanitizes a username, stripping out unsafe characters. |
| [wp\_generate\_password()](wp_generate_password) wp-includes/pluggable.php | Generates a random password drawn from the defined set of characters. |
| [wp\_login\_url()](wp_login_url) wp-includes/general-template.php | Retrieves the login URL. |
| [update\_user\_meta()](update_user_meta) wp-includes/user.php | Updates user meta field based on user ID. |
| [email\_exists()](email_exists) wp-includes/user.php | Determines whether the given email exists. |
| [wp\_create\_user()](wp_create_user) wp-includes/user.php | Provides a simpler way of inserting a user into the database. |
| [validate\_username()](validate_username) wp-includes/user.php | Checks whether a username is valid. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [WP\_Error::\_\_construct()](../classes/wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
| programming_docs |
wordpress clean_site_details_cache( int $site_id ) clean\_site\_details\_cache( int $site\_id )
============================================
Cleans the site details cache for a site.
`$site_id` int Optional Site ID. Default is the current site ID. File: `wp-includes/ms-blogs.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-blogs.php/)
```
function clean_site_details_cache( $site_id = 0 ) {
$site_id = (int) $site_id;
if ( ! $site_id ) {
$site_id = get_current_blog_id();
}
wp_cache_delete( $site_id, 'site-details' );
wp_cache_delete( $site_id, 'blog-details' );
}
```
| Uses | Description |
| --- | --- |
| [wp\_cache\_delete()](wp_cache_delete) wp-includes/cache.php | Removes the cache contents matching key and group. |
| [get\_current\_blog\_id()](get_current_blog_id) wp-includes/load.php | Retrieve the current site ID. |
| Version | Description |
| --- | --- |
| [4.7.4](https://developer.wordpress.org/reference/since/4.7.4/) | Introduced. |
wordpress wp_register_fatal_error_handler() wp\_register\_fatal\_error\_handler()
=====================================
Registers the shutdown handler for fatal errors.
The handler will only be registered if [wp\_is\_fatal\_error\_handler\_enabled()](wp_is_fatal_error_handler_enabled) returns true.
File: `wp-includes/error-protection.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/error-protection.php/)
```
function wp_register_fatal_error_handler() {
if ( ! wp_is_fatal_error_handler_enabled() ) {
return;
}
$handler = null;
if ( defined( 'WP_CONTENT_DIR' ) && is_readable( WP_CONTENT_DIR . '/fatal-error-handler.php' ) ) {
$handler = include WP_CONTENT_DIR . '/fatal-error-handler.php';
}
if ( ! is_object( $handler ) || ! is_callable( array( $handler, 'handle' ) ) ) {
$handler = new WP_Fatal_Error_Handler();
}
register_shutdown_function( array( $handler, 'handle' ) );
}
```
| Uses | Description |
| --- | --- |
| [wp\_is\_fatal\_error\_handler\_enabled()](wp_is_fatal_error_handler_enabled) wp-includes/error-protection.php | Checks whether the fatal error handler is enabled. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress _fetch_remote_file( string $url, array $headers = "" ): Snoopy \_fetch\_remote\_file( string $url, array $headers = "" ): Snoopy
=================================================================
Retrieve URL headers and content using WP HTTP Request API.
`$url` string Required URL to retrieve `$headers` array Optional Headers to send to the URL. Default: `""`
Snoopy style response
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
function _fetch_remote_file($url, $headers = "" ) {
$resp = wp_safe_remote_request( $url, array( 'headers' => $headers, 'timeout' => MAGPIE_FETCH_TIME_OUT ) );
if ( is_wp_error($resp) ) {
$error = array_shift($resp->errors);
$resp = new stdClass;
$resp->status = 500;
$resp->response_code = 500;
$resp->error = $error[0] . "\n"; //\n = Snoopy compatibility
return $resp;
}
// Snoopy returns headers unprocessed.
// Also note, WP_HTTP lowercases all keys, Snoopy did not.
$return_headers = array();
foreach ( wp_remote_retrieve_headers( $resp ) as $key => $value ) {
if ( !is_array($value) ) {
$return_headers[] = "$key: $value";
} else {
foreach ( $value as $v )
$return_headers[] = "$key: $v";
}
}
$response = new stdClass;
$response->status = wp_remote_retrieve_response_code( $resp );
$response->response_code = wp_remote_retrieve_response_code( $resp );
$response->headers = $return_headers;
$response->results = wp_remote_retrieve_body( $resp );
return $response;
}
```
| Uses | Description |
| --- | --- |
| [wp\_safe\_remote\_request()](wp_safe_remote_request) wp-includes/http.php | Retrieve the raw response from a safe HTTP request. |
| [wp\_remote\_retrieve\_headers()](wp_remote_retrieve_headers) wp-includes/http.php | Retrieve only the headers from the raw response. |
| [wp\_remote\_retrieve\_response\_code()](wp_remote_retrieve_response_code) wp-includes/http.php | Retrieve only the response code from the raw response. |
| [wp\_remote\_retrieve\_body()](wp_remote_retrieve_body) wp-includes/http.php | Retrieve only the body from the raw response. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [fetch\_rss()](fetch_rss) wp-includes/rss.php | Build Magpie object based on RSS from URL. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress get_post_type_archive_template(): string get\_post\_type\_archive\_template(): string
============================================
Retrieves path of post type archive template in current or parent template.
The template hierarchy and template path are filterable via the [‘$type\_template\_hierarchy’](../hooks/type_template_hierarchy) and [‘$type\_template’](../hooks/type_template) dynamic hooks, where `$type` is ‘archive’.
* [get\_archive\_template()](get_archive_template)
string Full path to archive template file.
File: `wp-includes/template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/template.php/)
```
function get_post_type_archive_template() {
$post_type = get_query_var( 'post_type' );
if ( is_array( $post_type ) ) {
$post_type = reset( $post_type );
}
$obj = get_post_type_object( $post_type );
if ( ! ( $obj instanceof WP_Post_Type ) || ! $obj->has_archive ) {
return '';
}
return get_archive_template();
}
```
| Uses | Description |
| --- | --- |
| [get\_query\_var()](get_query_var) wp-includes/query.php | Retrieves the value of a query variable in the [WP\_Query](../classes/wp_query) class. |
| [get\_archive\_template()](get_archive_template) wp-includes/template.php | Retrieves path of archive template in current or parent template. |
| [get\_post\_type\_object()](get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress delete_site_meta( int $site_id, string $meta_key, mixed $meta_value = '' ): bool delete\_site\_meta( int $site\_id, string $meta\_key, mixed $meta\_value = '' ): bool
=====================================================================================
Removes metadata matching criteria from a site.
You can match based on the key, or key and value. Removing based on key and value, will keep from removing duplicate metadata with the same key. It also allows removing all metadata matching key, if needed.
`$site_id` int Required Site ID. `$meta_key` string Required Metadata name. `$meta_value` mixed Optional Metadata value. If provided, rows will only be removed that match the value.
Must be serializable if non-scalar. Default: `''`
bool True on success, false on failure.
File: `wp-includes/ms-site.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-site.php/)
```
function delete_site_meta( $site_id, $meta_key, $meta_value = '' ) {
return delete_metadata( 'blog', $site_id, $meta_key, $meta_value );
}
```
| Uses | Description |
| --- | --- |
| [delete\_metadata()](delete_metadata) wp-includes/meta.php | Deletes metadata for the specified object. |
| Version | Description |
| --- | --- |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | Introduced. |
wordpress populate_roles_270() populate\_roles\_270()
======================
Create and modify WordPress roles for WordPress 2.7.
File: `wp-admin/includes/schema.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/schema.php/)
```
function populate_roles_270() {
$role = get_role( 'administrator' );
if ( ! empty( $role ) ) {
$role->add_cap( 'install_plugins' );
$role->add_cap( 'update_themes' );
}
}
```
| Uses | Description |
| --- | --- |
| [get\_role()](get_role) wp-includes/capabilities.php | Retrieves role object. |
| Used By | Description |
| --- | --- |
| [populate\_roles()](populate_roles) wp-admin/includes/schema.php | Execute WordPress role creation for the various WordPress versions. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress the_block_editor_meta_box_post_form_hidden_fields( WP_Post $post ) the\_block\_editor\_meta\_box\_post\_form\_hidden\_fields( WP\_Post $post )
===========================================================================
Renders the hidden form required for the meta boxes form.
`$post` [WP\_Post](../classes/wp_post) Required Current post object. File: `wp-admin/includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/post.php/)
```
function the_block_editor_meta_box_post_form_hidden_fields( $post ) {
$form_extra = '';
if ( 'auto-draft' === $post->post_status ) {
$form_extra .= "<input type='hidden' id='auto_draft' name='auto_draft' value='1' />";
}
$form_action = 'editpost';
$nonce_action = 'update-post_' . $post->ID;
$form_extra .= "<input type='hidden' id='post_ID' name='post_ID' value='" . esc_attr( $post->ID ) . "' />";
$referer = wp_get_referer();
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
wp_nonce_field( $nonce_action );
/*
* Some meta boxes hook into these actions to add hidden input fields in the classic post form.
* For backward compatibility, we can capture the output from these actions,
* and extract the hidden input fields.
*/
ob_start();
/** This filter is documented in wp-admin/edit-form-advanced.php */
do_action( 'edit_form_after_title', $post );
/** This filter is documented in wp-admin/edit-form-advanced.php */
do_action( 'edit_form_advanced', $post );
$classic_output = ob_get_clean();
$classic_elements = wp_html_split( $classic_output );
$hidden_inputs = '';
foreach ( $classic_elements as $element ) {
if ( 0 !== strpos( $element, '<input ' ) ) {
continue;
}
if ( preg_match( '/\stype=[\'"]hidden[\'"]\s/', $element ) ) {
echo $element;
}
}
?>
<input type="hidden" id="user-id" name="user_ID" value="<?php echo (int) $user_id; ?>" />
<input type="hidden" id="hiddenaction" name="action" value="<?php echo esc_attr( $form_action ); ?>" />
<input type="hidden" id="originalaction" name="originalaction" value="<?php echo esc_attr( $form_action ); ?>" />
<input type="hidden" id="post_type" name="post_type" value="<?php echo esc_attr( $post->post_type ); ?>" />
<input type="hidden" id="original_post_status" name="original_post_status" value="<?php echo esc_attr( $post->post_status ); ?>" />
<input type="hidden" id="referredby" name="referredby" value="<?php echo $referer ? esc_url( $referer ) : ''; ?>" />
<?php
if ( 'draft' !== get_post_status( $post ) ) {
wp_original_referer_field( true, 'previous' );
}
echo $form_extra;
wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false );
wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false );
// Permalink title nonce.
wp_nonce_field( 'samplepermalink', 'samplepermalinknonce', false );
/**
* Adds hidden input fields to the meta box save form.
*
* Hook into this action to print `<input type="hidden" ... />` fields, which will be POSTed back to
* the server when meta boxes are saved.
*
* @since 5.0.0
*
* @param WP_Post $post The post that is being edited.
*/
do_action( 'block_editor_meta_box_hidden_fields', $post );
}
```
[do\_action( 'block\_editor\_meta\_box\_hidden\_fields', WP\_Post $post )](../hooks/block_editor_meta_box_hidden_fields)
Adds hidden input fields to the meta box save form.
[do\_action( 'edit\_form\_advanced', WP\_Post $post )](../hooks/edit_form_advanced)
Fires after ‘normal’ context meta boxes have been output for all post types other than ‘page’.
[do\_action( 'edit\_form\_after\_title', WP\_Post $post )](../hooks/edit_form_after_title)
Fires after the title field.
| Uses | Description |
| --- | --- |
| [wp\_html\_split()](wp_html_split) wp-includes/formatting.php | Separates HTML elements and comments from the text. |
| [wp\_get\_current\_user()](wp_get_current_user) wp-includes/pluggable.php | Retrieves the current user object. |
| [wp\_get\_referer()](wp_get_referer) wp-includes/functions.php | Retrieves referer from ‘\_wp\_http\_referer’ or HTTP referer. |
| [wp\_nonce\_field()](wp_nonce_field) wp-includes/functions.php | Retrieves or display nonce hidden field for forms. |
| [wp\_original\_referer\_field()](wp_original_referer_field) wp-includes/functions.php | Retrieves or displays original referer hidden field for forms. |
| [get\_post\_status()](get_post_status) wp-includes/post.php | Retrieves the post status based on the post ID. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [the\_block\_editor\_meta\_boxes()](the_block_editor_meta_boxes) wp-admin/includes/post.php | Renders the meta boxes forms. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress get_the_block_template_html(): string get\_the\_block\_template\_html(): string
=========================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Returns the markup for the current template.
string Block template markup.
File: `wp-includes/block-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/block-template.php/)
```
function get_the_block_template_html() {
global $_wp_current_template_content;
global $wp_embed;
if ( ! $_wp_current_template_content ) {
if ( is_user_logged_in() ) {
return '<h1>' . esc_html__( 'No matching template found' ) . '</h1>';
}
return;
}
$content = $wp_embed->run_shortcode( $_wp_current_template_content );
$content = $wp_embed->autoembed( $content );
$content = do_blocks( $content );
$content = wptexturize( $content );
$content = convert_smilies( $content );
$content = shortcode_unautop( $content );
$content = wp_filter_content_tags( $content );
$content = do_shortcode( $content );
$content = str_replace( ']]>', ']]>', $content );
// Wrap block template in .wp-site-blocks to allow for specific descendant styles
// (e.g. `.wp-site-blocks > *`).
return '<div class="wp-site-blocks">' . $content . '</div>';
}
```
| Uses | Description |
| --- | --- |
| [wp\_filter\_content\_tags()](wp_filter_content_tags) wp-includes/media.php | Filters specific tags in post content and modifies their markup. |
| [do\_blocks()](do_blocks) wp-includes/blocks.php | Parses dynamic blocks out of `post_content` and re-renders them. |
| [esc\_html\_\_()](esc_html__) wp-includes/l10n.php | Retrieves the translation of $text and escapes it for safe use in HTML output. |
| [convert\_smilies()](convert_smilies) wp-includes/formatting.php | Converts text equivalent of smilies to images. |
| [wptexturize()](wptexturize) wp-includes/formatting.php | Replaces common plain text characters with formatted entities. |
| [shortcode\_unautop()](shortcode_unautop) wp-includes/formatting.php | Don’t auto-p wrap shortcodes that stand alone. |
| [WP\_Embed::autoembed()](../classes/wp_embed/autoembed) wp-includes/class-wp-embed.php | Passes any unlinked URLs that are on their own line to [WP\_Embed::shortcode()](../classes/wp_embed/shortcode) for potential embedding. |
| [WP\_Embed::run\_shortcode()](../classes/wp_embed/run_shortcode) wp-includes/class-wp-embed.php | Processes the [embed] shortcode. |
| [do\_shortcode()](do_shortcode) wp-includes/shortcodes.php | Searches content for shortcodes and filter shortcodes through their hooks. |
| [is\_user\_logged\_in()](is_user_logged_in) wp-includes/pluggable.php | Determines whether the current visitor is a logged in user. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress wp_filter_oembed_result( string $result, object $data, string $url ): string wp\_filter\_oembed\_result( string $result, object $data, string $url ): string
===============================================================================
Filters the given oEmbed HTML.
If the `$url` isn’t on the trusted providers list, we need to filter the HTML heavily for security.
Only filters ‘rich’ and ‘video’ response types.
`$result` string Required The oEmbed HTML result. `$data` object Required A data object result from an oEmbed provider. `$url` string Required The URL of the content to be embedded. string The filtered and sanitized oEmbed result.
File: `wp-includes/embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/embed.php/)
```
function wp_filter_oembed_result( $result, $data, $url ) {
if ( false === $result || ! in_array( $data->type, array( 'rich', 'video' ), true ) ) {
return $result;
}
$wp_oembed = _wp_oembed_get_object();
// Don't modify the HTML for trusted providers.
if ( false !== $wp_oembed->get_provider( $url, array( 'discover' => false ) ) ) {
return $result;
}
$allowed_html = array(
'a' => array(
'href' => true,
),
'blockquote' => array(),
'iframe' => array(
'src' => true,
'width' => true,
'height' => true,
'frameborder' => true,
'marginwidth' => true,
'marginheight' => true,
'scrolling' => true,
'title' => true,
),
);
$html = wp_kses( $result, $allowed_html );
preg_match( '|(<blockquote>.*?</blockquote>)?.*(<iframe.*?></iframe>)|ms', $html, $content );
// We require at least the iframe to exist.
if ( empty( $content[2] ) ) {
return false;
}
$html = $content[1] . $content[2];
preg_match( '/ src=([\'"])(.*?)\1/', $html, $results );
if ( ! empty( $results ) ) {
$secret = wp_generate_password( 10, false );
$url = esc_url( "{$results[2]}#?secret=$secret" );
$q = $results[1];
$html = str_replace( $results[0], ' src=' . $q . $url . $q . ' data-secret=' . $q . $secret . $q, $html );
$html = str_replace( '<blockquote', "<blockquote data-secret=\"$secret\"", $html );
}
$allowed_html['blockquote']['data-secret'] = true;
$allowed_html['iframe']['data-secret'] = true;
$html = wp_kses( $html, $allowed_html );
if ( ! empty( $content[1] ) ) {
// We have a blockquote to fall back on. Hide the iframe by default.
$html = str_replace( '<iframe', '<iframe style="position: absolute; clip: rect(1px, 1px, 1px, 1px);"', $html );
$html = str_replace( '<blockquote', '<blockquote class="wp-embedded-content"', $html );
}
$html = str_ireplace( '<iframe', '<iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted"', $html );
return $html;
}
```
| Uses | Description |
| --- | --- |
| [WP\_oEmbed::get\_provider()](../classes/wp_oembed/get_provider) wp-includes/class-wp-oembed.php | Takes a URL and returns the corresponding oEmbed provider’s URL, if there is one. |
| [wp\_generate\_password()](wp_generate_password) wp-includes/pluggable.php | Generates a random password drawn from the defined set of characters. |
| [wp\_kses()](wp_kses) wp-includes/kses.php | Filters text content and strips out disallowed HTML. |
| [\_wp\_oembed\_get\_object()](_wp_oembed_get_object) wp-includes/embed.php | Returns the initialized [WP\_oEmbed](../classes/wp_oembed) object. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
| programming_docs |
wordpress get_column_headers( string|WP_Screen $screen ): string[] get\_column\_headers( string|WP\_Screen $screen ): string[]
===========================================================
Get the column headers for a screen
`$screen` string|[WP\_Screen](../classes/wp_screen) Required The screen you want the headers for string[] The column header labels keyed by column ID.
File: `wp-admin/includes/screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/screen.php/)
```
function get_column_headers( $screen ) {
static $column_headers = array();
if ( is_string( $screen ) ) {
$screen = convert_to_screen( $screen );
}
if ( ! isset( $column_headers[ $screen->id ] ) ) {
/**
* Filters the column headers for a list table on a specific screen.
*
* The dynamic portion of the hook name, `$screen->id`, refers to the
* ID of a specific screen. For example, the screen ID for the Posts
* list table is edit-post, so the filter for that screen would be
* manage_edit-post_columns.
*
* @since 3.0.0
*
* @param string[] $columns The column header labels keyed by column ID.
*/
$column_headers[ $screen->id ] = apply_filters( "manage_{$screen->id}_columns", array() );
}
return $column_headers[ $screen->id ];
}
```
[apply\_filters( "manage\_{$screen->id}\_columns", string[] $columns )](../hooks/manage_screen-id_columns)
Filters the column headers for a list table on a specific screen.
| Uses | Description |
| --- | --- |
| [convert\_to\_screen()](convert_to_screen) wp-admin/includes/template.php | Converts a screen string to a screen object. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Screen::render\_list\_table\_columns\_preferences()](../classes/wp_screen/render_list_table_columns_preferences) wp-admin/includes/class-wp-screen.php | Renders the list table columns preferences. |
| [WP\_List\_Table::get\_primary\_column\_name()](../classes/wp_list_table/get_primary_column_name) wp-admin/includes/class-wp-list-table.php | Gets the name of the primary column. |
| [WP\_Screen::show\_screen\_options()](../classes/wp_screen/show_screen_options) wp-admin/includes/class-wp-screen.php | |
| [WP\_List\_Table::get\_column\_info()](../classes/wp_list_table/get_column_info) wp-admin/includes/class-wp-list-table.php | Gets a list of all, hidden, and sortable columns, with filter applied. |
| [\_WP\_List\_Table\_Compat::get\_column\_info()](../classes/_wp_list_table_compat/get_column_info) wp-admin/includes/class-wp-list-table-compat.php | Gets a list of all, hidden, and sortable columns. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress _deep_replace( string|array $search, string $subject ): string \_deep\_replace( string|array $search, string $subject ): string
================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Performs a deep string replace operation to ensure the values in $search are no longer present.
Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values e.g. $subject = ‘%0%0%0DDD’, $search =’%0D’, $result =” rather than the ‘%0%0DD’ that str\_replace would return
`$search` string|array Required The value being searched for, otherwise known as the needle.
An array may be used to designate multiple needles. `$subject` string Required The string being searched and replaced on, otherwise known as the haystack. string The string with the replaced values.
File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function _deep_replace( $search, $subject ) {
$subject = (string) $subject;
$count = 1;
while ( $count ) {
$subject = str_replace( $search, '', $subject, $count );
}
return $subject;
}
```
| Used By | Description |
| --- | --- |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [wp\_sanitize\_redirect()](wp_sanitize_redirect) wp-includes/pluggable.php | Sanitizes a URL for use in a redirect. |
| Version | Description |
| --- | --- |
| [2.8.1](https://developer.wordpress.org/reference/since/2.8.1/) | Introduced. |
wordpress addslashes_strings_only( mixed $value ): mixed addslashes\_strings\_only( mixed $value ): mixed
================================================
This function has been deprecated. Use [wp\_slash()](wp_slash) instead.
Adds slashes only if the provided value is a string.
* [wp\_slash()](wp_slash)
`$value` mixed Required mixed
File: `wp-includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/deprecated.php/)
```
function addslashes_strings_only( $value ) {
return is_string( $value ) ? addslashes( $value ) : $value;
}
```
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | This function has been deprecated. Use [wp\_slash()](wp_slash) instead. |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress cat_is_ancestor_of( int|object $cat1, int|object $cat2 ): bool cat\_is\_ancestor\_of( int|object $cat1, int|object $cat2 ): bool
=================================================================
Checks if a category is an ancestor of another category.
You can use either an ID or the category object for both parameters.
If you use an integer, the category will be retrieved.
`$cat1` int|object Required ID or object to check if this is the parent category. `$cat2` int|object Required The child category. bool Whether $cat2 is child of $cat1.
* The function evaluates if the second category is a child of the first category.
* Any level of ancestry will return True.
* Arguments should be either integer or objects; if arguments are string representations of integers and not true integers, **cat\_is\_ancestor\_of** will return False.
File: `wp-includes/category.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/category.php/)
```
function cat_is_ancestor_of( $cat1, $cat2 ) {
return term_is_ancestor_of( $cat1, $cat2, 'category' );
}
```
| Uses | Description |
| --- | --- |
| [term\_is\_ancestor\_of()](term_is_ancestor_of) wp-includes/taxonomy.php | Checks if a term is an ancestor of another term. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress is_site_meta_supported(): bool is\_site\_meta\_supported(): bool
=================================
Determines whether site meta is enabled.
This function checks whether the ‘blogmeta’ database table exists. The result is saved as a setting for the main network, making it essentially a global setting. Subsequent requests will refer to this setting instead of running the query.
bool True if site meta is supported, false otherwise.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function is_site_meta_supported() {
global $wpdb;
if ( ! is_multisite() ) {
return false;
}
$network_id = get_main_network_id();
$supported = get_network_option( $network_id, 'site_meta_supported', false );
if ( false === $supported ) {
$supported = $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->blogmeta}'" ) ? 1 : 0;
update_network_option( $network_id, 'site_meta_supported', $supported );
}
return (bool) $supported;
}
```
| Uses | Description |
| --- | --- |
| [update\_network\_option()](update_network_option) wp-includes/option.php | Updates the value of a network option that was already added. |
| [get\_network\_option()](get_network_option) wp-includes/option.php | Retrieves a network’s option value based on the option name. |
| [get\_main\_network\_id()](get_main_network_id) wp-includes/functions.php | Gets the main network ID. |
| [is\_multisite()](is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [wpdb::get\_var()](../classes/wpdb/get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| Used By | Description |
| --- | --- |
| [wp\_check\_site\_meta\_support\_prefilter()](wp_check_site_meta_support_prefilter) wp-includes/ms-site.php | Aborts calls to site meta if it is not supported. |
| [wp\_delete\_site()](wp_delete_site) wp-includes/ms-site.php | Deletes a site from the database. |
| [populate\_site\_meta()](populate_site_meta) wp-admin/includes/schema.php | Creates WordPress site meta and sets the default values. |
| [upgrade\_network()](upgrade_network) wp-admin/includes/upgrade.php | Executes network-level upgrade routines. |
| Version | Description |
| --- | --- |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | Introduced. |
wordpress get_filesystem_method( array $args = array(), string $context = '', bool $allow_relaxed_file_ownership = false ): string get\_filesystem\_method( array $args = array(), string $context = '', bool $allow\_relaxed\_file\_ownership = false ): string
=============================================================================================================================
Determines which method to use for reading, writing, modifying, or deleting files on the filesystem.
The priority of the transports are: Direct, SSH2, FTP PHP Extension, FTP Sockets (Via Sockets class, or `fsockopen()`). Valid values for these are: ‘direct’, ‘ssh2’, ‘ftpext’ or ‘ftpsockets’.
The return value can be overridden by defining the `FS_METHOD` constant in `wp-config.php`, or filtering via [‘filesystem\_method’](../hooks/filesystem_method).
`$args` array Optional Connection details. Default: `array()`
`$context` string Optional Full path to the directory that is tested for being writable. Default: `''`
`$allow_relaxed_file_ownership` bool Optional Whether to allow Group/World writable.
Default: `false`
string The transport to use, see description for valid return values.
File: `wp-admin/includes/file.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/file.php/)
```
function get_filesystem_method( $args = array(), $context = '', $allow_relaxed_file_ownership = false ) {
// Please ensure that this is either 'direct', 'ssh2', 'ftpext', or 'ftpsockets'.
$method = defined( 'FS_METHOD' ) ? FS_METHOD : false;
if ( ! $context ) {
$context = WP_CONTENT_DIR;
}
// If the directory doesn't exist (wp-content/languages) then use the parent directory as we'll create it.
if ( WP_LANG_DIR === $context && ! is_dir( $context ) ) {
$context = dirname( $context );
}
$context = trailingslashit( $context );
if ( ! $method ) {
$temp_file_name = $context . 'temp-write-test-' . str_replace( '.', '-', uniqid( '', true ) );
$temp_handle = @fopen( $temp_file_name, 'w' );
if ( $temp_handle ) {
// Attempt to determine the file owner of the WordPress files, and that of newly created files.
$wp_file_owner = false;
$temp_file_owner = false;
if ( function_exists( 'fileowner' ) ) {
$wp_file_owner = @fileowner( __FILE__ );
$temp_file_owner = @fileowner( $temp_file_name );
}
if ( false !== $wp_file_owner && $wp_file_owner === $temp_file_owner ) {
/*
* WordPress is creating files as the same owner as the WordPress files,
* this means it's safe to modify & create new files via PHP.
*/
$method = 'direct';
$GLOBALS['_wp_filesystem_direct_method'] = 'file_owner';
} elseif ( $allow_relaxed_file_ownership ) {
/*
* The $context directory is writable, and $allow_relaxed_file_ownership is set,
* this means we can modify files safely in this directory.
* This mode doesn't create new files, only alter existing ones.
*/
$method = 'direct';
$GLOBALS['_wp_filesystem_direct_method'] = 'relaxed_ownership';
}
fclose( $temp_handle );
@unlink( $temp_file_name );
}
}
if ( ! $method && isset( $args['connection_type'] ) && 'ssh' === $args['connection_type'] && extension_loaded( 'ssh2' ) ) {
$method = 'ssh2';
}
if ( ! $method && extension_loaded( 'ftp' ) ) {
$method = 'ftpext';
}
if ( ! $method && ( extension_loaded( 'sockets' ) || function_exists( 'fsockopen' ) ) ) {
$method = 'ftpsockets'; // Sockets: Socket extension; PHP Mode: FSockopen / fwrite / fread.
}
/**
* Filters the filesystem method to use.
*
* @since 2.6.0
*
* @param string $method Filesystem method to return.
* @param array $args An array of connection details for the method.
* @param string $context Full path to the directory that is tested for being writable.
* @param bool $allow_relaxed_file_ownership Whether to allow Group/World writable.
*/
return apply_filters( 'filesystem_method', $method, $args, $context, $allow_relaxed_file_ownership );
}
```
[apply\_filters( 'filesystem\_method', string $method, array $args, string $context, bool $allow\_relaxed\_file\_ownership )](../hooks/filesystem_method)
Filters the filesystem method to use.
| Uses | Description |
| --- | --- |
| [trailingslashit()](trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::is\_filesystem\_available()](../classes/wp_rest_plugins_controller/is_filesystem_available) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Determine if the endpoints are available. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](../classes/wp_customize_manager/customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [wp\_print\_request\_filesystem\_credentials\_modal()](wp_print_request_filesystem_credentials_modal) wp-admin/includes/file.php | Prints the filesystem credentials modal when needed. |
| [request\_filesystem\_credentials()](request_filesystem_credentials) wp-admin/includes/file.php | Displays a form to the user to request for their FTP/SSH details in order to connect to the filesystem. |
| [WP\_Filesystem()](wp_filesystem) wp-admin/includes/file.php | Initializes and connects the WordPress Filesystem Abstraction classes. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress wp_refresh_heartbeat_nonces( array $response ): array wp\_refresh\_heartbeat\_nonces( array $response ): array
========================================================
Adds the latest Heartbeat and REST-API nonce to the Heartbeat response.
`$response` array Required The Heartbeat response. array The Heartbeat response.
File: `wp-admin/includes/misc.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/misc.php/)
```
function wp_refresh_heartbeat_nonces( $response ) {
// Refresh the Rest API nonce.
$response['rest_nonce'] = wp_create_nonce( 'wp_rest' );
// Refresh the Heartbeat nonce.
$response['heartbeat_nonce'] = wp_create_nonce( 'heartbeat-nonce' );
return $response;
}
```
| Uses | Description |
| --- | --- |
| [wp\_create\_nonce()](wp_create_nonce) wp-includes/pluggable.php | Creates a cryptographic token tied to a specific action, user, user session, and window of time. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress has_tag( string|int|array $tag = '', int|WP_Post $post = null ): bool has\_tag( string|int|array $tag = '', int|WP\_Post $post = null ): bool
=======================================================================
Checks if the current post has any of given tags.
The given tags are checked against the post’s tags’ term\_ids, names and slugs.
Tags given as integers will only be checked against the post’s tags’ term\_ids.
If no tags are given, determines if post has any tags.
For more information on this and similar theme functions, check out the [Conditional Tags](https://developer.wordpress.org/themes/basics/conditional-tags/) article in the Theme Developer Handbook.
`$tag` string|int|array Optional The tag name/term\_id/slug, or an array of them to check for. Default: `''`
`$post` int|[WP\_Post](../classes/wp_post) Optional Post to check. Defaults to the current post. Default: `null`
bool True if the current post has any of the given tags (or any tag, if no tag specified). False otherwise.
File: `wp-includes/category-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/category-template.php/)
```
function has_tag( $tag = '', $post = null ) {
return has_term( $tag, 'post_tag', $post );
}
```
| Uses | Description |
| --- | --- |
| [has\_term()](has_term) wp-includes/category-template.php | Checks if the current post has any of given terms. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Can be used outside of the WordPress Loop if `$post` is provided. |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress comment_date( string $format = '', int|WP_Comment $comment_ID ) comment\_date( string $format = '', int|WP\_Comment $comment\_ID )
==================================================================
Displays the comment date of the current comment.
`$format` string Optional PHP date format. Defaults to the `'date_format'` option. Default: `''`
`$comment_ID` int|[WP\_Comment](../classes/wp_comment) Optional [WP\_Comment](../classes/wp_comment) or ID of the comment for which to print the date.
Default current comment. For the format of the date, see [Formatting Date and Time](https://wordpress.org/support/article/formatting-date-and-time/).
File: `wp-includes/comment-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/comment-template.php/)
```
function comment_date( $format = '', $comment_ID = 0 ) {
echo get_comment_date( $format, $comment_ID );
}
```
| Uses | Description |
| --- | --- |
| [get\_comment\_date()](get_comment_date) wp-includes/comment-template.php | Retrieves the comment date of the current comment. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Added the ability for `$comment_ID` to also accept a [WP\_Comment](../classes/wp_comment) object. |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress get_temp_dir(): string get\_temp\_dir(): string
========================
Determines a writable directory for temporary files.
Function’s preference is the return value of sys\_get\_temp\_dir(), followed by your PHP temporary upload directory, followed by WP\_CONTENT\_DIR, before finally defaulting to /tmp/
In the event that this function does not find a writable location, It may be overridden by the WP\_TEMP\_DIR constant in your wp-config.php file.
string Writable temporary directory.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function get_temp_dir() {
static $temp = '';
if ( defined( 'WP_TEMP_DIR' ) ) {
return trailingslashit( WP_TEMP_DIR );
}
if ( $temp ) {
return trailingslashit( $temp );
}
if ( function_exists( 'sys_get_temp_dir' ) ) {
$temp = sys_get_temp_dir();
if ( @is_dir( $temp ) && wp_is_writable( $temp ) ) {
return trailingslashit( $temp );
}
}
$temp = ini_get( 'upload_tmp_dir' );
if ( @is_dir( $temp ) && wp_is_writable( $temp ) ) {
return trailingslashit( $temp );
}
$temp = WP_CONTENT_DIR . '/';
if ( is_dir( $temp ) && wp_is_writable( $temp ) ) {
return $temp;
}
return '/tmp/';
}
```
| Uses | Description |
| --- | --- |
| [wp\_is\_writable()](wp_is_writable) wp-includes/functions.php | Determines if a directory is writable. |
| [trailingslashit()](trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| Used By | Description |
| --- | --- |
| [wp\_generate\_block\_templates\_export\_file()](wp_generate_block_templates_export_file) wp-includes/block-template-utils.php | Creates an export of the current templates and template parts from the site editor at the specified path in a ZIP file. |
| [wp\_read\_video\_metadata()](wp_read_video_metadata) wp-admin/includes/media.php | Retrieves metadata from a video file’s ID3 tags. |
| [wp\_read\_audio\_metadata()](wp_read_audio_metadata) wp-admin/includes/media.php | Retrieves metadata from an audio file’s ID3 tags. |
| [wp\_tempnam()](wp_tempnam) wp-admin/includes/file.php | Returns a filename of a temporary unique file. |
| [WP\_Http::request()](../classes/wp_http/request) wp-includes/class-wp-http.php | Send an HTTP request to a URI. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
| programming_docs |
wordpress get_post_type_object( string $post_type ): WP_Post_Type|null get\_post\_type\_object( string $post\_type ): WP\_Post\_Type|null
==================================================================
Retrieves a post type object by name.
* [register\_post\_type()](register_post_type)
`$post_type` string Required The name of a registered post type. [WP\_Post\_Type](../classes/wp_post_type)|null [WP\_Post\_Type](../classes/wp_post_type) object if it exists, null otherwise.
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function get_post_type_object( $post_type ) {
global $wp_post_types;
if ( ! is_scalar( $post_type ) || empty( $wp_post_types[ $post_type ] ) ) {
return null;
}
return $wp_post_types[ $post_type ];
}
```
| Used By | Description |
| --- | --- |
| [\_wp\_build\_title\_and\_description\_for\_single\_post\_type\_block\_template()](_wp_build_title_and_description_for_single_post_type_block_template) wp-includes/block-template-utils.php | Builds the title and description of a post-specific template based on the underlying referenced post. |
| [WP\_REST\_Menu\_Items\_Controller::prepare\_item\_for\_database()](../classes/wp_rest_menu_items_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Prepares a single post for create or update. |
| [WP\_REST\_Global\_Styles\_Controller::get\_available\_actions()](../classes/wp_rest_global_styles_controller/get_available_actions) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Get the link relations available for the post and current user. |
| [rest\_get\_route\_for\_post\_type\_items()](rest_get_route_for_post_type_items) wp-includes/rest-api.php | Gets the REST API route for a post type. |
| [WP\_REST\_Templates\_Controller::get\_available\_actions()](../classes/wp_rest_templates_controller/get_available_actions) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Get the link relations available for the post and current user. |
| [WP\_REST\_Templates\_Controller::\_\_construct()](../classes/wp_rest_templates_controller/__construct) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Constructor. |
| [wp\_force\_plain\_post\_permalink()](wp_force_plain_post_permalink) wp-includes/link-template.php | Determine whether post should always use a plain permalink structure. |
| [WP\_REST\_Autosaves\_Controller::\_\_construct()](../classes/wp_rest_autosaves_controller/__construct) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Constructor. |
| [use\_block\_editor\_for\_post\_type()](use_block_editor_for_post_type) wp-includes/post.php | Returns whether a post type is compatible with the block editor. |
| [register\_and\_do\_post\_meta\_boxes()](register_and_do_post_meta_boxes) wp-admin/includes/meta-boxes.php | Registers the default post meta boxes, and runs the `do_meta_boxes` actions. |
| [WP\_REST\_Posts\_Controller::get\_available\_actions()](../classes/wp_rest_posts_controller/get_available_actions) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Gets the link relations available for the post and current user. |
| [WP\_Customize\_Manager::check\_changeset\_lock\_with\_heartbeat()](../classes/wp_customize_manager/check_changeset_lock_with_heartbeat) wp-includes/class-wp-customize-manager.php | Checks locked changeset with heartbeat API. |
| [WP\_Customize\_Manager::handle\_override\_changeset\_lock\_request()](../classes/wp_customize_manager/handle_override_changeset_lock_request) wp-includes/class-wp-customize-manager.php | Removes changeset lock when take over request is sent via Ajax. |
| [WP\_Customize\_Manager::handle\_dismiss\_autosave\_or\_lock\_request()](../classes/wp_customize_manager/handle_dismiss_autosave_or_lock_request) wp-includes/class-wp-customize-manager.php | Deletes a given auto-draft changeset or the autosave revision for a given changeset or delete changeset lock. |
| [WP\_Customize\_Manager::handle\_changeset\_trash\_request()](../classes/wp_customize_manager/handle_changeset_trash_request) wp-includes/class-wp-customize-manager.php | Handles request to trash a changeset. |
| [WP\_Customize\_Manager::grant\_edit\_post\_capability\_for\_changeset()](../classes/wp_customize_manager/grant_edit_post_capability_for_changeset) wp-includes/class-wp-customize-manager.php | Re-maps ‘edit\_post’ meta cap for a customize\_changeset post to be the same as ‘customize’ maps. |
| [get\_the\_post\_type\_description()](get_the_post_type_description) wp-includes/general-template.php | Retrieves the description for a post type archive. |
| [wp\_load\_press\_this()](wp_load_press_this) wp-admin/press-this.php | |
| [WP\_REST\_Revisions\_Controller::delete\_item\_permissions\_check()](../classes/wp_rest_revisions_controller/delete_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php | Checks if a given request has access to delete a revision. |
| [WP\_REST\_Revisions\_Controller::\_\_construct()](../classes/wp_rest_revisions_controller/__construct) wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php | Constructor. |
| [WP\_REST\_Posts\_Controller::prepare\_links()](../classes/wp_rest_posts_controller/prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares links for the request. |
| [WP\_REST\_Posts\_Controller::get\_item\_schema()](../classes/wp_rest_posts_controller/get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves the post’s schema, conforming to JSON Schema. |
| [WP\_REST\_Posts\_Controller::get\_collection\_params()](../classes/wp_rest_posts_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves the query params for the posts collection. |
| [WP\_REST\_Posts\_Controller::sanitize\_post\_statuses()](../classes/wp_rest_posts_controller/sanitize_post_statuses) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Sanitizes and validates the list of post statuses, including whether the user can query private statuses. |
| [WP\_REST\_Posts\_Controller::check\_is\_post\_type\_allowed()](../classes/wp_rest_posts_controller/check_is_post_type_allowed) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given post type can be viewed or managed. |
| [WP\_REST\_Posts\_Controller::check\_read\_permission()](../classes/wp_rest_posts_controller/check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be read. |
| [WP\_REST\_Posts\_Controller::check\_update\_permission()](../classes/wp_rest_posts_controller/check_update_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be edited. |
| [WP\_REST\_Posts\_Controller::check\_create\_permission()](../classes/wp_rest_posts_controller/check_create_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be created. |
| [WP\_REST\_Posts\_Controller::check\_delete\_permission()](../classes/wp_rest_posts_controller/check_delete_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be deleted. |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_response()](../classes/wp_rest_posts_controller/prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post output for response. |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_database()](../classes/wp_rest_posts_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post for create or update. |
| [WP\_REST\_Posts\_Controller::update\_item\_permissions\_check()](../classes/wp_rest_posts_controller/update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to update a post. |
| [WP\_REST\_Posts\_Controller::get\_item()](../classes/wp_rest_posts_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves a single post. |
| [WP\_REST\_Posts\_Controller::create\_item\_permissions\_check()](../classes/wp_rest_posts_controller/create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to create a post. |
| [WP\_REST\_Posts\_Controller::\_\_construct()](../classes/wp_rest_posts_controller/__construct) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Constructor. |
| [WP\_REST\_Posts\_Controller::get\_items\_permissions\_check()](../classes/wp_rest_posts_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to read posts. |
| [WP\_REST\_Post\_Types\_Controller::get\_item()](../classes/wp_rest_post_types_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php | Retrieves a specific post type. |
| [WP\_REST\_Comments\_Controller::check\_read\_post\_permission()](../classes/wp_rest_comments_controller/check_read_post_permission) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Checks if the post can be read. |
| [WP\_Customize\_Nav\_Menus::print\_post\_type\_container()](../classes/wp_customize_nav_menus/print_post_type_container) wp-includes/class-wp-customize-nav-menus.php | Prints the markup for new menu items. |
| [WP\_Customize\_Nav\_Menus::sanitize\_nav\_menus\_created\_posts()](../classes/wp_customize_nav_menus/sanitize_nav_menus_created_posts) wp-includes/class-wp-customize-nav-menus.php | Sanitizes post IDs for posts created for nav menu items to be published. |
| [WP\_Customize\_Nav\_Menus::ajax\_insert\_auto\_draft\_post()](../classes/wp_customize_nav_menus/ajax_insert_auto_draft_post) wp-includes/class-wp-customize-nav-menus.php | Ajax handler for adding a new auto-draft post. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::get\_original\_title()](../classes/wp_customize_nav_menu_item_setting/get_original_title) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get original title. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::get\_type\_label()](../classes/wp_customize_nav_menu_item_setting/get_type_label) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get type label. |
| [unregister\_post\_type()](unregister_post_type) wp-includes/post.php | Unregisters a post type. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](../classes/wp_customize_manager/customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [get\_preview\_post\_link()](get_preview_post_link) wp-includes/link-template.php | Retrieves the URL used for the post preview. |
| [is\_post\_type\_viewable()](is_post_type_viewable) wp-includes/post.php | Determines whether a post type is considered “viewable”. |
| [wp\_admin\_bar\_customize\_menu()](wp_admin_bar_customize_menu) wp-includes/admin-bar.php | Adds the “Customize” link to the Toolbar. |
| [wp\_xmlrpc\_server::\_toggle\_sticky()](../classes/wp_xmlrpc_server/_toggle_sticky) wp-includes/class-wp-xmlrpc-server.php | Encapsulate the logic for sticking a post and determining if the user has permission to do so |
| [WP\_Customize\_Nav\_Menus::enqueue\_scripts()](../classes/wp_customize_nav_menus/enqueue_scripts) wp-includes/class-wp-customize-nav-menus.php | Enqueues scripts and styles for Customizer pane. |
| [WP\_Customize\_Nav\_Menus::load\_available\_items\_query()](../classes/wp_customize_nav_menus/load_available_items_query) wp-includes/class-wp-customize-nav-menus.php | Performs the post\_type and taxonomy queries for loading available menu items. |
| [WP\_Posts\_List\_Table::handle\_row\_actions()](../classes/wp_posts_list_table/handle_row_actions) wp-admin/includes/class-wp-posts-list-table.php | Generates and displays row action links. |
| [WP\_Posts\_List\_Table::column\_title()](../classes/wp_posts_list_table/column_title) wp-admin/includes/class-wp-posts-list-table.php | Handles the title column output. |
| [WP\_Media\_List\_Table::column\_parent()](../classes/wp_media_list_table/column_parent) wp-admin/includes/class-wp-media-list-table.php | Handles the parent column output. |
| [wp\_edit\_attachments\_query\_vars()](wp_edit_attachments_query_vars) wp-admin/includes/post.php | Returns the query variables for the current attachments request. |
| [export\_wp()](export_wp) wp-admin/includes/export.php | Generates the WXR export file for download. |
| [get\_editable\_user\_ids()](get_editable_user_ids) wp-admin/includes/deprecated.php | Gets the IDs of any users who can edit posts. |
| [WP\_List\_Table::months\_dropdown()](../classes/wp_list_table/months_dropdown) wp-admin/includes/class-wp-list-table.php | Displays a dropdown for filtering items in the list table by month. |
| [wp\_dashboard\_right\_now()](wp_dashboard_right_now) wp-admin/includes/dashboard.php | Dashboard widget that displays some basic stats about the site. |
| [wp\_dashboard\_setup()](wp_dashboard_setup) wp-admin/includes/dashboard.php | Registers dashboard widgets. |
| [get\_inline\_data()](get_inline_data) wp-admin/includes/template.php | Adds hidden fields with the data for use in the inline editor for posts and pages. |
| [get\_media\_item()](get_media_item) wp-admin/includes/media.php | Retrieves HTML form for modifying the image attachment. |
| [\_wp\_post\_thumbnail\_html()](_wp_post_thumbnail_html) wp-admin/includes/post.php | Returns HTML for the post thumbnail meta box. |
| [\_admin\_notice\_post\_locked()](_admin_notice_post_locked) wp-admin/includes/post.php | Outputs the HTML for the notice to say that someone else is editing or has taken over editing of this post. |
| [wp\_write\_post()](wp_write_post) wp-admin/includes/post.php | Creates a new post from the “Write Post” form using `$_POST` information. |
| [get\_sample\_permalink()](get_sample_permalink) wp-admin/includes/post.php | Returns a sample permalink based on the post name. |
| [\_wp\_translate\_postdata()](_wp_translate_postdata) wp-admin/includes/post.php | Renames `$_POST` data from form names to DB post columns. |
| [edit\_post()](edit_post) wp-admin/includes/post.php | Updates an existing post with values provided in `$_POST`. |
| [bulk\_edit\_posts()](bulk_edit_posts) wp-admin/includes/post.php | Processes the post data for the bulk editing of posts. |
| [wp\_ajax\_query\_attachments()](wp_ajax_query_attachments) wp-admin/includes/ajax-actions.php | Ajax handler for querying attachments. |
| [wp\_ajax\_add\_menu\_item()](wp_ajax_add_menu_item) wp-admin/includes/ajax-actions.php | Ajax handler for adding a menu item. |
| [post\_author\_meta\_box()](post_author_meta_box) wp-admin/includes/meta-boxes.php | Displays form field with list of authors. |
| [post\_submit\_meta\_box()](post_submit_meta_box) wp-admin/includes/meta-boxes.php | Displays post submit form fields. |
| [WP\_Comments\_List\_Table::column\_response()](../classes/wp_comments_list_table/column_response) wp-admin/includes/class-wp-comments-list-table.php | |
| [WP\_Terms\_List\_Table::column\_posts()](../classes/wp_terms_list_table/column_posts) wp-admin/includes/class-wp-terms-list-table.php | |
| [Walker\_Nav\_Menu\_Edit::start\_el()](../classes/walker_nav_menu_edit/start_el) wp-admin/includes/class-walker-nav-menu-edit.php | Start the element output. |
| [\_wp\_ajax\_menu\_quick\_search()](_wp_ajax_menu_quick_search) wp-admin/includes/nav-menu.php | Prints the appropriate response to a menu quick search. |
| [wp\_nav\_menu\_item\_post\_type\_meta\_box()](wp_nav_menu_item_post_type_meta_box) wp-admin/includes/nav-menu.php | Displays a meta box for a post type menu item. |
| [WP\_Posts\_List\_Table::inline\_edit()](../classes/wp_posts_list_table/inline_edit) wp-admin/includes/class-wp-posts-list-table.php | Outputs the hidden row displayed when inline editing |
| [WP\_Posts\_List\_Table::no\_items()](../classes/wp_posts_list_table/no_items) wp-admin/includes/class-wp-posts-list-table.php | |
| [WP\_Posts\_List\_Table::get\_bulk\_actions()](../classes/wp_posts_list_table/get_bulk_actions) wp-admin/includes/class-wp-posts-list-table.php | |
| [WP\_Posts\_List\_Table::extra\_tablenav()](../classes/wp_posts_list_table/extra_tablenav) wp-admin/includes/class-wp-posts-list-table.php | |
| [WP\_Posts\_List\_Table::\_\_construct()](../classes/wp_posts_list_table/__construct) wp-admin/includes/class-wp-posts-list-table.php | Constructor. |
| [WP\_Posts\_List\_Table::ajax\_user\_can()](../classes/wp_posts_list_table/ajax_user_can) wp-admin/includes/class-wp-posts-list-table.php | |
| [map\_meta\_cap()](map_meta_cap) wp-includes/capabilities.php | Maps a capability to the primitive capabilities required of the given user to satisfy the capability being checked. |
| [WP\_Customize\_Manager::save()](../classes/wp_customize_manager/save) wp-includes/class-wp-customize-manager.php | Handles customize\_save WP Ajax request to save/update a changeset. |
| [wp\_list\_categories()](wp_list_categories) wp-includes/category-template.php | Displays or retrieves the HTML list of categories. |
| [feed\_links\_extra()](feed_links_extra) wp-includes/general-template.php | Displays the links to the extra feeds such as category feeds. |
| [wp\_get\_archives()](wp_get_archives) wp-includes/general-template.php | Displays archive links based on type and format. |
| [wp\_title()](wp_title) wp-includes/general-template.php | Displays or retrieves page title for all areas of blog. |
| [post\_type\_archive\_title()](post_type_archive_title) wp-includes/general-template.php | Displays or retrieves title for a post type archive. |
| [WP\_Query::get\_queried\_object()](../classes/wp_query/get_queried_object) wp-includes/class-wp-query.php | Retrieves the currently queried object. |
| [WP\_Query::is\_post\_type\_archive()](../classes/wp_query/is_post_type_archive) wp-includes/class-wp-query.php | Is the query for an existing post type archive page? |
| [WP\_Query::get\_posts()](../classes/wp_query/get_posts) wp-includes/class-wp-query.php | Retrieves an array of posts based on query variables. |
| [WP\_Query::parse\_query()](../classes/wp_query/parse_query) wp-includes/class-wp-query.php | Parse a query string and set query type booleans. |
| [register\_taxonomy\_for\_object\_type()](register_taxonomy_for_object_type) wp-includes/taxonomy.php | Adds an already registered taxonomy to an object type. |
| [unregister\_taxonomy\_for\_object\_type()](unregister_taxonomy_for_object_type) wp-includes/taxonomy.php | Removes an already registered taxonomy from an object type. |
| [wp\_get\_shortlink()](wp_get_shortlink) wp-includes/link-template.php | Returns a shortlink for a post, page, attachment, or site. |
| [get\_adjacent\_post()](get_adjacent_post) wp-includes/link-template.php | Retrieves the adjacent post. |
| [get\_post\_type\_archive\_link()](get_post_type_archive_link) wp-includes/link-template.php | Retrieves the permalink for a post type archive. |
| [get\_post\_type\_archive\_feed\_link()](get_post_type_archive_feed_link) wp-includes/link-template.php | Retrieves the permalink for a post type archive feed. |
| [get\_edit\_post\_link()](get_edit_post_link) wp-includes/link-template.php | Retrieves the edit post link for post. |
| [get\_delete\_post\_link()](get_delete_post_link) wp-includes/link-template.php | Retrieves the delete posts link for post. |
| [get\_post\_permalink()](get_post_permalink) wp-includes/link-template.php | Retrieves the permalink for a post of a custom post type. |
| [wp\_admin\_bar\_my\_sites\_menu()](wp_admin_bar_my_sites_menu) wp-includes/admin-bar.php | Adds the “My Sites/[Site Name]” menu and all submenus. |
| [wp\_admin\_bar\_edit\_menu()](wp_admin_bar_edit_menu) wp-includes/admin-bar.php | Provides an edit link for posts and terms. |
| [get\_post\_type\_archive\_template()](get_post_type_archive_template) wp-includes/template.php | Retrieves path of post type archive template in current or parent template. |
| [wp\_enqueue\_media()](wp_enqueue_media) wp-includes/media.php | Enqueues all scripts, styles, settings, and templates necessary to use all media JS APIs. |
| [get\_posts\_by\_author\_sql()](get_posts_by_author_sql) wp-includes/post.php | Retrieves the post SQL based on capability, author, and type. |
| [wp\_insert\_post()](wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [\_count\_posts\_cache\_key()](_count_posts_cache_key) wp-includes/post.php | Returns the cache key for [wp\_count\_posts()](wp_count_posts) based on the passed arguments. |
| [wp\_count\_posts()](wp_count_posts) wp-includes/post.php | Counts number of posts of a post type and if user has permissions to view. |
| [\_add\_post\_type\_submenus()](_add_post_type_submenus) wp-includes/post.php | Adds submenus for post types. |
| [is\_post\_type\_hierarchical()](is_post_type_hierarchical) wp-includes/post.php | Determines whether the post type is hierarchical. |
| [post\_type\_exists()](post_type_exists) wp-includes/post.php | Determines whether a post type is registered. |
| [redirect\_canonical()](redirect_canonical) wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| [\_update\_blog\_date\_on\_post\_publish()](_update_blog_date_on_post_publish) wp-includes/ms-blogs.php | Handler for updating the site’s last updated date when a post is published or an already published post is changed. |
| [\_update\_blog\_date\_on\_post\_delete()](_update_blog_date_on_post_delete) wp-includes/ms-blogs.php | Handler for updating the current site’s last updated date when a published post is deleted. |
| [wp\_setup\_nav\_menu\_item()](wp_setup_nav_menu_item) wp-includes/nav-menu.php | Decorates a menu item object with the shared navigation menu item properties. |
| [wp\_update\_nav\_menu\_item()](wp_update_nav_menu_item) wp-includes/nav-menu.php | Saves the properties of a menu item or create a new one. |
| [wp\_xmlrpc\_server::blogger\_newPost()](../classes/wp_xmlrpc_server/blogger_newpost) wp-includes/class-wp-xmlrpc-server.php | Creates new post. |
| [wp\_xmlrpc\_server::mw\_newPost()](../classes/wp_xmlrpc_server/mw_newpost) wp-includes/class-wp-xmlrpc-server.php | Create a new post. |
| [wp\_xmlrpc\_server::wp\_getPostType()](../classes/wp_xmlrpc_server/wp_getposttype) wp-includes/class-wp-xmlrpc-server.php | Retrieves a post type |
| [wp\_xmlrpc\_server::wp\_getComments()](../classes/wp_xmlrpc_server/wp_getcomments) wp-includes/class-wp-xmlrpc-server.php | Retrieve comments. |
| [wp\_xmlrpc\_server::wp\_getPosts()](../classes/wp_xmlrpc_server/wp_getposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve posts. |
| [wp\_xmlrpc\_server::\_insert\_post()](../classes/wp_xmlrpc_server/_insert_post) wp-includes/class-wp-xmlrpc-server.php | Helper method for wp\_newPost() and wp\_editPost(), containing shared logic. |
| [WP\_Customize\_Control::render\_content()](../classes/wp_customize_control/render_content) wp-includes/class-wp-customize-control.php | Render the control’s content. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Object returned is now an instance of `WP_Post_Type`. |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
| programming_docs |
wordpress wp_site_admin_email_change_notification( string $old_email, string $new_email, string $option_name ) wp\_site\_admin\_email\_change\_notification( string $old\_email, string $new\_email, string $option\_name )
============================================================================================================
Sends an email to the old site admin email address when the site admin email address changes.
`$old_email` string Required The old site admin email address. `$new_email` string Required The new site admin email address. `$option_name` string Required The relevant database option name. File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function wp_site_admin_email_change_notification( $old_email, $new_email, $option_name ) {
$send = true;
// Don't send the notification to the default 'admin_email' value.
if ( '[email protected]' === $old_email ) {
$send = false;
}
/**
* Filters whether to send the site admin email change notification email.
*
* @since 4.9.0
*
* @param bool $send Whether to send the email notification.
* @param string $old_email The old site admin email address.
* @param string $new_email The new site admin email address.
*/
$send = apply_filters( 'send_site_admin_email_change_email', $send, $old_email, $new_email );
if ( ! $send ) {
return;
}
/* translators: Do not translate OLD_EMAIL, NEW_EMAIL, SITENAME, SITEURL: those are placeholders. */
$email_change_text = __(
'Hi,
This notice confirms that the admin email address was changed on ###SITENAME###.
The new admin email address is ###NEW_EMAIL###.
This email has been sent to ###OLD_EMAIL###
Regards,
All at ###SITENAME###
###SITEURL###'
);
$email_change_email = array(
'to' => $old_email,
/* translators: Site admin email change notification email subject. %s: Site title. */
'subject' => __( '[%s] Admin Email Changed' ),
'message' => $email_change_text,
'headers' => '',
);
// Get site name.
$site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
/**
* Filters the contents of the email notification sent when the site admin email address is changed.
*
* @since 4.9.0
*
* @param array $email_change_email {
* Used to build wp_mail().
*
* @type string $to The intended recipient.
* @type string $subject The subject of the email.
* @type string $message The content of the email.
* The following strings have a special meaning and will get replaced dynamically:
* - ###OLD_EMAIL### The old site admin email address.
* - ###NEW_EMAIL### The new site admin email address.
* - ###SITENAME### The name of the site.
* - ###SITEURL### The URL to the site.
* @type string $headers Headers.
* }
* @param string $old_email The old site admin email address.
* @param string $new_email The new site admin email address.
*/
$email_change_email = apply_filters( 'site_admin_email_change_email', $email_change_email, $old_email, $new_email );
$email_change_email['message'] = str_replace( '###OLD_EMAIL###', $old_email, $email_change_email['message'] );
$email_change_email['message'] = str_replace( '###NEW_EMAIL###', $new_email, $email_change_email['message'] );
$email_change_email['message'] = str_replace( '###SITENAME###', $site_name, $email_change_email['message'] );
$email_change_email['message'] = str_replace( '###SITEURL###', home_url(), $email_change_email['message'] );
wp_mail(
$email_change_email['to'],
sprintf(
$email_change_email['subject'],
$site_name
),
$email_change_email['message'],
$email_change_email['headers']
);
}
```
[apply\_filters( 'send\_site\_admin\_email\_change\_email', bool $send, string $old\_email, string $new\_email )](../hooks/send_site_admin_email_change_email)
Filters whether to send the site admin email change notification email.
[apply\_filters( 'site\_admin\_email\_change\_email', array $email\_change\_email, string $old\_email, string $new\_email )](../hooks/site_admin_email_change_email)
Filters the contents of the email notification sent when the site admin email address is changed.
| Uses | Description |
| --- | --- |
| [wp\_specialchars\_decode()](wp_specialchars_decode) wp-includes/formatting.php | Converts a number of HTML entities into their special characters. |
| [wp\_mail()](wp_mail) wp-includes/pluggable.php | Sends an email, similar to PHP’s mail function. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [home\_url()](home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress wp_set_post_tags( int $post_id, string|array $tags = '', bool $append = false ): array|false|WP_Error wp\_set\_post\_tags( int $post\_id, string|array $tags = '', bool $append = false ): array|false|WP\_Error
==========================================================================================================
Sets the tags for a post.
* [wp\_set\_object\_terms()](wp_set_object_terms)
`$post_id` int Optional The Post ID. Does not default to the ID of the global $post. `$tags` string|array Optional An array of tags to set for the post, or a string of tags separated by commas. Default: `''`
`$append` bool Optional If true, don't delete existing tags, just add on. If false, replace the tags with the new tags. Default: `false`
array|false|[WP\_Error](../classes/wp_error) Array of term taxonomy IDs of affected terms. [WP\_Error](../classes/wp_error) or false on failure.
If you set IDs of an existing tag in the array, WordPress assigns the existing tag.
If you pass text in the array, WP will create a tag if it doesn’t exist and assigns it to the post
You can mix text and IDs. The text will create a term, if it not exists, the ID will be used for an existing tag – both get assigned to the post.
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
return wp_set_post_terms( $post_id, $tags, 'post_tag', $append );
}
```
| Uses | Description |
| --- | --- |
| [wp\_set\_post\_terms()](wp_set_post_terms) wp-includes/post.php | Sets the terms for a post. |
| Used By | Description |
| --- | --- |
| [wp\_add\_post\_tags()](wp_add_post_tags) wp-includes/post.php | Adds tags to a post. |
| [wp\_insert\_post()](wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| Version | Description |
| --- | --- |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
wordpress unregister_taxonomy_for_object_type( string $taxonomy, string $object_type ): bool unregister\_taxonomy\_for\_object\_type( string $taxonomy, string $object\_type ): bool
=======================================================================================
Removes an already registered taxonomy from an object type.
`$taxonomy` string Required Name of taxonomy object. `$object_type` string Required Name of the object type. bool True if successful, false if not.
File: `wp-includes/taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/taxonomy.php/)
```
function unregister_taxonomy_for_object_type( $taxonomy, $object_type ) {
global $wp_taxonomies;
if ( ! isset( $wp_taxonomies[ $taxonomy ] ) ) {
return false;
}
if ( ! get_post_type_object( $object_type ) ) {
return false;
}
$key = array_search( $object_type, $wp_taxonomies[ $taxonomy ]->object_type, true );
if ( false === $key ) {
return false;
}
unset( $wp_taxonomies[ $taxonomy ]->object_type[ $key ] );
/**
* Fires after a taxonomy is unregistered for an object type.
*
* @since 5.1.0
*
* @param string $taxonomy Taxonomy name.
* @param string $object_type Name of the object type.
*/
do_action( 'unregistered_taxonomy_for_object_type', $taxonomy, $object_type );
return true;
}
```
[do\_action( 'unregistered\_taxonomy\_for\_object\_type', string $taxonomy, string $object\_type )](../hooks/unregistered_taxonomy_for_object_type)
Fires after a taxonomy is unregistered for an object type.
| Uses | Description |
| --- | --- |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_post\_type\_object()](get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Used By | Description |
| --- | --- |
| [WP\_Post\_Type::unregister\_taxonomies()](../classes/wp_post_type/unregister_taxonomies) wp-includes/class-wp-post-type.php | Removes the post type from all taxonomies. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress nocache_headers() nocache\_headers()
==================
Sets the headers to prevent caching for the different browsers.
Different browsers support different nocache headers, so several headers must be sent so that all of them get the point that no caching should occur.
* [wp\_get\_nocache\_headers()](wp_get_nocache_headers)
##### Usage:
```
nocache_headers();
```
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function nocache_headers() {
if ( headers_sent() ) {
return;
}
$headers = wp_get_nocache_headers();
unset( $headers['Last-Modified'] );
header_remove( 'Last-Modified' );
foreach ( $headers as $name => $field_value ) {
header( "{$name}: {$field_value}" );
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_nocache\_headers()](wp_get_nocache_headers) wp-includes/functions.php | Gets the header information to prevent caching. |
| Used By | Description |
| --- | --- |
| [\_jsonp\_wp\_die\_handler()](_jsonp_wp_die_handler) wp-includes/functions.php | Kills WordPress execution and displays JSONP response with an error message. |
| [\_xml\_wp\_die\_handler()](_xml_wp_die_handler) wp-includes/functions.php | Kills WordPress execution and displays XML response with an error message. |
| [\_json\_wp\_die\_handler()](_json_wp_die_handler) wp-includes/functions.php | Kills WordPress execution and displays JSON response with an error message. |
| [WP\_Customize\_Manager::customize\_preview\_init()](../classes/wp_customize_manager/customize_preview_init) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings. |
| [auth\_redirect()](auth_redirect) wp-includes/pluggable.php | Checks if a user is logged in, if not it redirects them to the login page. |
| [WP::handle\_404()](../classes/wp/handle_404) wp-includes/class-wp.php | Set the Headers for 404, if nothing is found for requested URL. |
| [wp\_not\_installed()](wp_not_installed) wp-includes/load.php | Redirect to the installer if WordPress is not installed. |
| [\_default\_wp\_die\_handler()](_default_wp_die_handler) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [\_ajax\_wp\_die\_handler()](_ajax_wp_die_handler) wp-includes/functions.php | Kills WordPress execution and displays Ajax response with an error message. |
| [\_xmlrpc\_wp\_die\_handler()](_xmlrpc_wp_die_handler) wp-includes/functions.php | Kills WordPress execution and displays XML response with an error message. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress wp_json_encode( mixed $data, int $options, int $depth = 512 ): string|false wp\_json\_encode( mixed $data, int $options, int $depth = 512 ): string|false
=============================================================================
Encodes a variable into JSON, with some sanity checks.
`$data` mixed Required Variable (usually an array or object) to encode as JSON. `$options` int Optional Options to be passed to json\_encode(). Default 0. `$depth` int Optional Maximum depth to walk through $data. Must be greater than 0. Default: `512`
string|false The JSON encoded string, or false if it cannot be encoded.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function wp_json_encode( $data, $options = 0, $depth = 512 ) {
$json = json_encode( $data, $options, $depth );
// If json_encode() was successful, no need to do more sanity checking.
if ( false !== $json ) {
return $json;
}
try {
$data = _wp_json_sanity_check( $data, $depth );
} catch ( Exception $e ) {
return false;
}
return json_encode( $data, $options, $depth );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Style\_Engine\_Processor::combine\_rules\_selectors()](../classes/wp_style_engine_processor/combine_rules_selectors) wp-includes/style-engine/class-wp-style-engine-processor.php | Combines selectors from the rules store when they have the same styles. |
| [WP\_REST\_Global\_Styles\_Controller::prepare\_item\_for\_database()](../classes/wp_rest_global_styles_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Prepares a single global styles config for update. |
| [wp\_generate\_block\_templates\_export\_file()](wp_generate_block_templates_export_file) wp-includes/block-template-utils.php | Creates an export of the current templates and template parts from the site editor at the specified path in a ZIP file. |
| [wp\_filter\_global\_styles\_post()](wp_filter_global_styles_post) wp-includes/kses.php | Sanitizes global styles user content removing unsafe rules. |
| [block\_editor\_rest\_api\_preload()](block_editor_rest_api_preload) wp-includes/block-editor.php | Preloads common data used with the block editor by specifying an array of REST API paths that will be preloaded for a given block editor context. |
| [rest\_validate\_enum()](rest_validate_enum) wp-includes/rest-api.php | Validates that the given value is a member of the JSON Schema “enum”. |
| [WP\_Application\_Passwords\_List\_Table::print\_js\_template\_row()](../classes/wp_application_passwords_list_table/print_js_template_row) wp-admin/includes/class-wp-application-passwords-list-table.php | Prints the JavaScript template for the new row item. |
| [serialize\_block\_attributes()](serialize_block_attributes) wp-includes/blocks.php | Given an array of attributes, returns a string in the serialized attributes format prepared for post content. |
| [WP\_Site\_Health::wp\_cron\_scheduled\_check()](../classes/wp_site_health/wp_cron_scheduled_check) wp-admin/includes/class-wp-site-health.php | Runs the scheduled event to check and update the latest site health status for the website. |
| [enqueue\_editor\_block\_styles\_assets()](enqueue_editor_block_styles_assets) wp-includes/script-loader.php | Function responsible for enqueuing the assets required for block styles functionality on the editor. |
| [\_jsonp\_wp\_die\_handler()](_jsonp_wp_die_handler) wp-includes/functions.php | Kills WordPress execution and displays JSONP response with an error message. |
| [wp\_ajax\_health\_check\_site\_status\_result()](wp_ajax_health_check_site_status_result) wp-admin/includes/ajax-actions.php | Ajax handler for site health check to update the result status. |
| [\_json\_wp\_die\_handler()](_json_wp_die_handler) wp-includes/functions.php | Kills WordPress execution and displays JSON response with an error message. |
| [wp\_default\_packages\_vendor()](wp_default_packages_vendor) wp-includes/script-loader.php | Registers all the WordPress vendor scripts that are in the standardized `js/dist/vendor/` location. |
| [wp\_default\_packages\_inline\_scripts()](wp_default_packages_inline_scripts) wp-includes/script-loader.php | Adds inline scripts required for the WordPress JavaScript packages. |
| [wp\_tinymce\_inline\_scripts()](wp_tinymce_inline_scripts) wp-includes/script-loader.php | Adds inline scripts required for the TinyMCE in the block editor. |
| [the\_block\_editor\_meta\_boxes()](the_block_editor_meta_boxes) wp-admin/includes/post.php | Renders the meta boxes forms. |
| [wp\_create\_user\_request()](wp_create_user_request) wp-includes/user.php | Creates and logs a user request to perform a specific action. |
| [WP\_Privacy\_Policy\_Content::notice()](../classes/wp_privacy_policy_content/notice) wp-admin/includes/class-wp-privacy-policy-content.php | Add a notice with a link to the guide when editing the privacy policy page. |
| [wp\_privacy\_generate\_personal\_data\_export\_file()](wp_privacy_generate_personal_data_export_file) wp-admin/includes/privacy-tools.php | Generate the personal data export file. |
| [wp\_start\_scraping\_edited\_file\_errors()](wp_start_scraping_edited_file_errors) wp-includes/load.php | Start scraping edited file errors. |
| [wp\_finalize\_scraping\_edited\_file\_errors()](wp_finalize_scraping_edited_file_errors) wp-includes/load.php | Finalize scraping for edited file errors. |
| [wp\_enqueue\_code\_editor()](wp_enqueue_code_editor) wp-includes/general-template.php | Enqueues assets needed by the code editor for the given settings. |
| [WP\_Widget\_Text::\_register\_one()](../classes/wp_widget_text/_register_one) wp-includes/widgets/class-wp-widget-text.php | Add hooks for enqueueing assets when registering all widget instances of this widget class. |
| [WP\_Widget\_Media\_Gallery::enqueue\_admin\_scripts()](../classes/wp_widget_media_gallery/enqueue_admin_scripts) wp-includes/widgets/class-wp-widget-media-gallery.php | Loads the required media files for the media manager and scripts for media widgets. |
| [WP\_Widget\_Custom\_HTML::\_register\_one()](../classes/wp_widget_custom_html/_register_one) wp-includes/widgets/class-wp-widget-custom-html.php | Add hooks for enqueueing assets when registering all widget instances of this widget class. |
| [WP\_Widget\_Custom\_HTML::enqueue\_admin\_scripts()](../classes/wp_widget_custom_html/enqueue_admin_scripts) wp-includes/widgets/class-wp-widget-custom-html.php | Loads the required scripts and styles for the widget control. |
| [WP\_Customize\_Date\_Time\_Control::content\_template()](../classes/wp_customize_date_time_control/content_template) wp-includes/customize/class-wp-customize-date-time-control.php | Renders a JS template for the content of date time control. |
| [\_WP\_Editors::default\_settings()](../classes/_wp_editors/default_settings) wp-includes/class-wp-editor.php | Returns the default TinyMCE settings. |
| [WP\_Widget\_Media\_Audio::enqueue\_admin\_scripts()](../classes/wp_widget_media_audio/enqueue_admin_scripts) wp-includes/widgets/class-wp-widget-media-audio.php | Loads the required media files for the media manager and scripts for media widgets. |
| [WP\_Widget\_Media\_Video::enqueue\_admin\_scripts()](../classes/wp_widget_media_video/enqueue_admin_scripts) wp-includes/widgets/class-wp-widget-media-video.php | Loads the required scripts and styles for the widget control. |
| [WP\_Widget\_Media\_Image::enqueue\_admin\_scripts()](../classes/wp_widget_media_image/enqueue_admin_scripts) wp-includes/widgets/class-wp-widget-media-image.php | Loads the required media files for the media manager and scripts for media widgets. |
| [WP\_Community\_Events::maybe\_log\_events\_response()](../classes/wp_community_events/maybe_log_events_response) wp-admin/includes/class-wp-community-events.php | Logs responses to Events API requests. |
| [WP\_Customize\_Manager::save\_changeset\_post()](../classes/wp_customize_manager/save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [wp\_localize\_jquery\_ui\_datepicker()](wp_localize_jquery_ui_datepicker) wp-includes/script-loader.php | Localizes the jQuery UI datepicker. |
| [WP\_Customize\_Widgets::filter\_dynamic\_sidebar\_params()](../classes/wp_customize_widgets/filter_dynamic_sidebar_params) wp-includes/class-wp-customize-widgets.php | Inject selective refresh data attributes into widget container elements. |
| [WP\_Customize\_Selective\_Refresh::export\_preview\_data()](../classes/wp_customize_selective_refresh/export_preview_data) wp-includes/customize/class-wp-customize-selective-refresh.php | Exports data in preview after it has finished rendering so that partials can be added at runtime. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](../classes/wp_customize_manager/customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [WP\_REST\_Server::serve\_request()](../classes/wp_rest_server/serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| [WP\_REST\_Server::json\_error()](../classes/wp_rest_server/json_error) wp-includes/rest-api/class-wp-rest-server.php | Retrieves an appropriate error representation in JSON. |
| [WP\_Customize\_Nav\_Menus::export\_preview\_data()](../classes/wp_customize_nav_menus/export_preview_data) wp-includes/class-wp-customize-nav-menus.php | Exports data from PHP to JS. |
| [WP\_Customize\_Nav\_Menus::filter\_wp\_nav\_menu()](../classes/wp_customize_nav_menus/filter_wp_nav_menu) wp-includes/class-wp-customize-nav-menus.php | Prepares [wp\_nav\_menu()](wp_nav_menu) calls for partial refresh. |
| [WP\_Customize\_Nav\_Menus::enqueue\_scripts()](../classes/wp_customize_nav_menus/enqueue_scripts) wp-includes/class-wp-customize-nav-menus.php | Enqueues scripts and styles for Customizer pane. |
| [WP\_List\_Table::ajax\_response()](../classes/wp_list_table/ajax_response) wp-admin/includes/class-wp-list-table.php | Handles an incoming ajax request (called from admin-ajax.php) |
| [WP\_List\_Table::\_js\_vars()](../classes/wp_list_table/_js_vars) wp-admin/includes/class-wp-list-table.php | Sends required variables to JavaScript land. |
| [admin\_color\_scheme\_picker()](admin_color_scheme_picker) wp-admin/includes/misc.php | Displays the default admin color scheme picker (Used in user-edit.php). |
| [wp\_color\_scheme\_settings()](wp_color_scheme_settings) wp-admin/includes/misc.php | |
| [WP\_Internal\_Pointers::print\_js()](../classes/wp_internal_pointers/print_js) wp-admin/includes/class-wp-internal-pointers.php | Print the pointer JavaScript data. |
| [compression\_test()](compression_test) wp-admin/includes/template.php | Tests support for compressing JavaScript from PHP. |
| [WP\_Themes\_List\_Table::\_js\_vars()](../classes/wp_themes_list_table/_js_vars) wp-admin/includes/class-wp-themes-list-table.php | Send required variables to JavaScript land |
| [media\_upload\_form()](media_upload_form) wp-admin/includes/media.php | Outputs the legacy media upload form. |
| [media\_send\_to\_editor()](media_send_to_editor) wp-admin/includes/media.php | Adds image HTML to editor. |
| [wp\_ajax\_upload\_attachment()](wp_ajax_upload_attachment) wp-admin/includes/ajax-actions.php | Ajax handler for uploading attachments |
| [wp\_ajax\_menu\_get\_metabox()](wp_ajax_menu_get_metabox) wp-admin/includes/ajax-actions.php | Ajax handler for retrieving menu meta boxes. |
| [wp\_ajax\_wp\_link\_ajax()](wp_ajax_wp_link_ajax) wp-admin/includes/ajax-actions.php | Ajax handler for internal linking. |
| [wp\_ajax\_autocomplete\_user()](wp_ajax_autocomplete_user) wp-admin/includes/ajax-actions.php | Ajax handler for user autocomplete. |
| [\_wp\_ajax\_menu\_quick\_search()](_wp_ajax_menu_quick_search) wp-admin/includes/nav-menu.php | Prints the appropriate response to a menu quick search. |
| [options\_general\_add\_js()](options_general_add_js) wp-admin/includes/options.php | Display JavaScript on the page. |
| [WP\_Customize\_Manager::customize\_preview\_settings()](../classes/wp_customize_manager/customize_preview_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for preview frame. |
| [WP\_Customize\_Manager::wp\_die()](../classes/wp_customize_manager/wp_die) wp-includes/class-wp-customize-manager.php | Custom wp\_die wrapper. Returns either the standard message for UI or the Ajax message. |
| [\_wp\_customize\_loader\_settings()](_wp_customize_loader_settings) wp-includes/theme.php | Adds settings for the customize-loader script. |
| [wp\_send\_json()](wp_send_json) wp-includes/functions.php | Sends a JSON response back to an Ajax request. |
| [wp\_version\_check()](wp_version_check) wp-includes/update.php | Checks WordPress version against the newest version. |
| [wp\_update\_plugins()](wp_update_plugins) wp-includes/update.php | Checks for available updates to plugins based on the latest versions hosted on WordPress.org. |
| [wp\_update\_themes()](wp_update_themes) wp-includes/update.php | Checks for available updates to themes based on the latest versions hosted on WordPress.org. |
| [wp\_plupload\_default\_settings()](wp_plupload_default_settings) wp-includes/media.php | Prints default Plupload arguments. |
| [wp\_playlist\_shortcode()](wp_playlist_shortcode) wp-includes/media.php | Builds the Playlist shortcode output. |
| [WP\_Scripts::localize()](../classes/wp_scripts/localize) wp-includes/class-wp-scripts.php | Localizes a script, only if the script has already been added. |
| [WP\_Customize\_Widgets::export\_preview\_data()](../classes/wp_customize_widgets/export_preview_data) wp-includes/class-wp-customize-widgets.php | Communicates the sidebars that appeared on the page at the very end of the page, and at the very end of the wp\_footer, |
| [WP\_Customize\_Widgets::enqueue\_scripts()](../classes/wp_customize_widgets/enqueue_scripts) wp-includes/class-wp-customize-widgets.php | Enqueues scripts and styles for Customizer panel and export data to JavaScript. |
| [wp\_default\_scripts()](wp_default_scripts) wp-includes/script-loader.php | Registers all WordPress scripts. |
| [\_WP\_Editors::editor\_settings()](../classes/_wp_editors/editor_settings) wp-includes/class-wp-editor.php | |
| [\_WP\_Editors::wp\_mce\_translation()](../classes/_wp_editors/wp_mce_translation) wp-includes/class-wp-editor.php | Translates the default TinyMCE strings and returns them as JSON encoded object ready to be loaded with tinymce.addI18n(), or as JS snippet that should run after tinymce.js is loaded. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | No longer handles support for PHP < 5.6. |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
| programming_docs |
wordpress delete_network_option( int $network_id, string $option ): bool delete\_network\_option( int $network\_id, string $option ): bool
=================================================================
Removes a network option by name.
* [delete\_option()](delete_option)
`$network_id` int Required ID of the network. Can be null to default to the current network ID. `$option` string Required Name of the option to delete. Expected to not be SQL-escaped. bool True if the option was deleted, false otherwise.
File: `wp-includes/option.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/option.php/)
```
function delete_network_option( $network_id, $option ) {
global $wpdb;
if ( $network_id && ! is_numeric( $network_id ) ) {
return false;
}
$network_id = (int) $network_id;
// Fallback to the current network if a network ID is not specified.
if ( ! $network_id ) {
$network_id = get_current_network_id();
}
/**
* Fires immediately before a specific network option is deleted.
*
* The dynamic portion of the hook name, `$option`, refers to the option name.
*
* @since 3.0.0
* @since 4.4.0 The `$option` parameter was added.
* @since 4.7.0 The `$network_id` parameter was added.
*
* @param string $option Option name.
* @param int $network_id ID of the network.
*/
do_action( "pre_delete_site_option_{$option}", $option, $network_id );
if ( ! is_multisite() ) {
$result = delete_option( $option );
} else {
$row = $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM {$wpdb->sitemeta} WHERE meta_key = %s AND site_id = %d", $option, $network_id ) );
if ( is_null( $row ) || ! $row->meta_id ) {
return false;
}
$cache_key = "$network_id:$option";
wp_cache_delete( $cache_key, 'site-options' );
$result = $wpdb->delete(
$wpdb->sitemeta,
array(
'meta_key' => $option,
'site_id' => $network_id,
)
);
}
if ( $result ) {
/**
* Fires after a specific network option has been deleted.
*
* The dynamic portion of the hook name, `$option`, refers to the option name.
*
* @since 2.9.0 As "delete_site_option_{$key}"
* @since 3.0.0
* @since 4.7.0 The `$network_id` parameter was added.
*
* @param string $option Name of the network option.
* @param int $network_id ID of the network.
*/
do_action( "delete_site_option_{$option}", $option, $network_id );
/**
* Fires after a network option has been deleted.
*
* @since 3.0.0
* @since 4.7.0 The `$network_id` parameter was added.
*
* @param string $option Name of the network option.
* @param int $network_id ID of the network.
*/
do_action( 'delete_site_option', $option, $network_id );
return true;
}
return false;
}
```
[do\_action( 'delete\_site\_option', string $option, int $network\_id )](../hooks/delete_site_option)
Fires after a network option has been deleted.
[do\_action( "delete\_site\_option\_{$option}", string $option, int $network\_id )](../hooks/delete_site_option_option)
Fires after a specific network option has been deleted.
[do\_action( "pre\_delete\_site\_option\_{$option}", string $option, int $network\_id )](../hooks/pre_delete_site_option_option)
Fires immediately before a specific network option is deleted.
| Uses | Description |
| --- | --- |
| [get\_current\_network\_id()](get_current_network_id) wp-includes/load.php | Retrieves the current network ID. |
| [wp\_cache\_delete()](wp_cache_delete) wp-includes/cache.php | Removes the cache contents matching key and group. |
| [delete\_option()](delete_option) wp-includes/option.php | Removes option by name. Prevents removal of protected WordPress options. |
| [wpdb::get\_row()](../classes/wpdb/get_row) wp-includes/class-wpdb.php | Retrieves one row from the database. |
| [wpdb::delete()](../classes/wpdb/delete) wp-includes/class-wpdb.php | Deletes a row in the table. |
| [is\_multisite()](is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wpdb::prepare()](../classes/wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [upgrade\_network()](upgrade_network) wp-admin/includes/upgrade.php | Executes network-level upgrade routines. |
| [delete\_site\_option()](delete_site_option) wp-includes/option.php | Removes a option by name for the current network. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress wp_logout_url( string $redirect = '' ): string wp\_logout\_url( string $redirect = '' ): string
================================================
Retrieves the logout URL.
Returns the URL that allows the user to log out of the site.
`$redirect` string Optional Path to redirect to on logout. Default: `''`
string The logout URL. Note: HTML-encoded via [esc\_html()](esc_html) in [wp\_nonce\_url()](wp_nonce_url) .
File: `wp-includes/general-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/general-template.php/)
```
function wp_logout_url( $redirect = '' ) {
$args = array();
if ( ! empty( $redirect ) ) {
$args['redirect_to'] = urlencode( $redirect );
}
$logout_url = add_query_arg( $args, site_url( 'wp-login.php?action=logout', 'login' ) );
$logout_url = wp_nonce_url( $logout_url, 'log-out' );
/**
* Filters the logout URL.
*
* @since 2.8.0
*
* @param string $logout_url The HTML-encoded logout URL.
* @param string $redirect Path to redirect to on logout.
*/
return apply_filters( 'logout_url', $logout_url, $redirect );
}
```
[apply\_filters( 'logout\_url', string $logout\_url, string $redirect )](../hooks/logout_url)
Filters the logout URL.
| Uses | Description |
| --- | --- |
| [site\_url()](site_url) wp-includes/link-template.php | Retrieves the URL for the current site where WordPress application files (e.g. wp-blog-header.php or the wp-admin/ folder) are accessible. |
| [wp\_nonce\_url()](wp_nonce_url) wp-includes/functions.php | Retrieves URL with nonce added to URL query. |
| [add\_query\_arg()](add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_loginout()](wp_loginout) wp-includes/general-template.php | Displays the Log In/Out link. |
| [wp\_nonce\_ays()](wp_nonce_ays) wp-includes/functions.php | Displays “Are You Sure” message to confirm the action being taken. |
| [WP\_Admin\_Bar::\_render()](../classes/wp_admin_bar/_render) wp-includes/class-wp-admin-bar.php | |
| [wp\_admin\_bar\_my\_account\_menu()](wp_admin_bar_my_account_menu) wp-includes/admin-bar.php | Adds the “My Account” submenu items. |
| [comment\_form()](comment_form) wp-includes/comment-template.php | Outputs a complete commenting form for use within a template. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress get_others_drafts( int $user_id ): array get\_others\_drafts( int $user\_id ): array
===========================================
This function has been deprecated. Use [get\_posts()](get_posts) instead.
Retrieve drafts from other users.
* [get\_posts()](get_posts)
`$user_id` int Required User ID. array List of drafts from other users.
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
function get_others_drafts($user_id) {
_deprecated_function( __FUNCTION__, '3.1.0' );
return get_others_unpublished_posts($user_id, 'draft');
}
```
| Uses | Description |
| --- | --- |
| [get\_others\_unpublished\_posts()](get_others_unpublished_posts) wp-admin/includes/deprecated.php | Retrieves editable posts from other users. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress has_term_meta( int $term_id ): array|false has\_term\_meta( int $term\_id ): array|false
=============================================
Gets all meta data, including meta IDs, for the given term ID.
`$term_id` int Required Term ID. array|false Array with meta data, or false when the meta table is not installed.
File: `wp-includes/taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/taxonomy.php/)
```
function has_term_meta( $term_id ) {
$check = wp_check_term_meta_support_prefilter( null );
if ( null !== $check ) {
return $check;
}
global $wpdb;
return $wpdb->get_results( $wpdb->prepare( "SELECT meta_key, meta_value, meta_id, term_id FROM $wpdb->termmeta WHERE term_id = %d ORDER BY meta_key,meta_id", $term_id ), ARRAY_A );
}
```
| Uses | Description |
| --- | --- |
| [wp\_check\_term\_meta\_support\_prefilter()](wp_check_term_meta_support_prefilter) wp-includes/taxonomy.php | Aborts calls to term meta if it is not supported. |
| [wpdb::get\_results()](../classes/wpdb/get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| [wpdb::prepare()](../classes/wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::get\_term\_custom\_fields()](../classes/wp_xmlrpc_server/get_term_custom_fields) wp-includes/class-wp-xmlrpc-server.php | Retrieve custom fields for a term. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress get_category_parents( int $category_id, bool $link = false, string $separator = '/', bool $nicename = false, array $deprecated = array() ): string|WP_Error get\_category\_parents( int $category\_id, bool $link = false, string $separator = '/', bool $nicename = false, array $deprecated = array() ): string|WP\_Error
===============================================================================================================================================================
Retrieves category parents with separator.
`$category_id` int Required Category ID. `$link` bool Optional Whether to format with link. Default: `false`
`$separator` string Optional How to separate categories. Default `'/'`. Default: `'/'`
`$nicename` bool Optional Whether to use nice name for display. Default: `false`
`$deprecated` array Optional Not used. Default: `array()`
string|[WP\_Error](../classes/wp_error) A list of category parents on success, [WP\_Error](../classes/wp_error) on failure.
File: `wp-includes/category-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/category-template.php/)
```
function get_category_parents( $category_id, $link = false, $separator = '/', $nicename = false, $deprecated = array() ) {
if ( ! empty( $deprecated ) ) {
_deprecated_argument( __FUNCTION__, '4.8.0' );
}
$format = $nicename ? 'slug' : 'name';
$args = array(
'separator' => $separator,
'link' => $link,
'format' => $format,
);
return get_term_parents_list( $category_id, 'category', $args );
}
```
| Uses | Description |
| --- | --- |
| [get\_term\_parents\_list()](get_term_parents_list) wp-includes/category-template.php | Retrieves term parents with separator. |
| [\_deprecated\_argument()](_deprecated_argument) wp-includes/functions.php | Marks a function argument as deprecated and inform when it has been used. |
| Used By | Description |
| --- | --- |
| [get\_the\_category\_list()](get_the_category_list) wp-includes/category-template.php | Retrieves category list for a post in either HTML list or custom format. |
| [get\_permalink()](get_permalink) wp-includes/link-template.php | Retrieves the full permalink for the current post or post ID. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | The `$visited` parameter was deprecated and renamed to `$deprecated`. |
| [1.2.0](https://developer.wordpress.org/reference/since/1.2.0/) | Introduced. |
wordpress wp_dequeue_script( string $handle ) wp\_dequeue\_script( string $handle )
=====================================
Remove a previously enqueued script.
* [WP\_Dependencies::dequeue()](../classes/wp_dependencies/dequeue)
`$handle` string Required Name of the script to be removed. File: `wp-includes/functions.wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions-wp-scripts.php/)
```
function wp_dequeue_script( $handle ) {
_wp_scripts_maybe_doing_it_wrong( __FUNCTION__, $handle );
wp_scripts()->dequeue( $handle );
}
```
| Uses | Description |
| --- | --- |
| [wp\_scripts()](wp_scripts) wp-includes/functions.wp-scripts.php | Initialize $wp\_scripts if it has not been set. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress get_feed_build_date( string $format ): string|false get\_feed\_build\_date( string $format ): string|false
======================================================
Gets the UTC time of the most recently modified post from [WP\_Query](../classes/wp_query).
If viewing a comment feed, the time of the most recently modified comment will be returned.
`$format` string Required Date format string to return the time in. string|false The time in requested format, or false on failure.
File: `wp-includes/feed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/feed.php/)
```
function get_feed_build_date( $format ) {
global $wp_query;
$datetime = false;
$max_modified_time = false;
$utc = new DateTimeZone( 'UTC' );
if ( ! empty( $wp_query ) && $wp_query->have_posts() ) {
// Extract the post modified times from the posts.
$modified_times = wp_list_pluck( $wp_query->posts, 'post_modified_gmt' );
// If this is a comment feed, check those objects too.
if ( $wp_query->is_comment_feed() && $wp_query->comment_count ) {
// Extract the comment modified times from the comments.
$comment_times = wp_list_pluck( $wp_query->comments, 'comment_date_gmt' );
// Add the comment times to the post times for comparison.
$modified_times = array_merge( $modified_times, $comment_times );
}
// Determine the maximum modified time.
$datetime = date_create_immutable_from_format( 'Y-m-d H:i:s', max( $modified_times ), $utc );
}
if ( false === $datetime ) {
// Fall back to last time any post was modified or published.
$datetime = date_create_immutable_from_format( 'Y-m-d H:i:s', get_lastpostmodified( 'GMT' ), $utc );
}
if ( false !== $datetime ) {
$max_modified_time = $datetime->format( $format );
}
/**
* Filters the date the last post or comment in the query was modified.
*
* @since 5.2.0
*
* @param string|false $max_modified_time Date the last post or comment was modified in the query, in UTC.
* False on failure.
* @param string $format The date format requested in get_feed_build_date().
*/
return apply_filters( 'get_feed_build_date', $max_modified_time, $format );
}
```
[apply\_filters( 'get\_feed\_build\_date', string|false $max\_modified\_time, string $format )](../hooks/get_feed_build_date)
Filters the date the last post or comment in the query was modified.
| Uses | Description |
| --- | --- |
| [WP\_Query::is\_comment\_feed()](../classes/wp_query/is_comment_feed) wp-includes/class-wp-query.php | Is the query for a comments feed? |
| [WP\_Query::have\_posts()](../classes/wp_query/have_posts) wp-includes/class-wp-query.php | Determines whether there are more posts available in the loop. |
| [wp\_list\_pluck()](wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [get\_lastpostmodified()](get_lastpostmodified) wp-includes/post.php | Gets the most recent time that a post on the site was modified. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress readonly( mixed $readonly, mixed $current = true, bool $echo = true ): string readonly( mixed $readonly, mixed $current = true, bool $echo = true ): string
=============================================================================
This function has been deprecated. Use [wp\_readonly()](wp_readonly) instead.
Outputs the HTML readonly attribute.
Compares the first two arguments and if identical marks as readonly.
This function is deprecated, and cannot be used on PHP >= 8.1.
* [wp\_readonly()](wp_readonly)
`$readonly` mixed Required One of the values to compare. `$current` mixed Optional The other value to compare if not just true.
Default: `true`
`$echo` bool Optional Whether to echo or just return the string.
Default: `true`
string HTML attribute or empty string.
File: `wp-includes/php-compat/readonly.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/php-compat/readonly.php/)
```
function readonly( $readonly, $current = true, $echo = true ) {
_deprecated_function( __FUNCTION__, '5.9.0', 'wp_readonly()' );
return wp_readonly( $readonly, $current, $echo );
}
```
| Uses | Description |
| --- | --- |
| [wp\_readonly()](wp_readonly) wp-includes/general-template.php | Outputs the HTML readonly attribute. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Use [wp\_readonly()](wp_readonly) introduced in 5.9.0. |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress wp_magic_quotes() wp\_magic\_quotes()
===================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Add magic quotes to `$_GET`, `$_POST`, `$_COOKIE`, and `$_SERVER`.
Also forces `$_REQUEST` to be `$_GET + $_POST`. If `$_SERVER`, `$_COOKIE`, or `$_ENV` are needed, use those superglobals directly.
File: `wp-includes/load.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/load.php/)
```
function wp_magic_quotes() {
// Escape with wpdb.
$_GET = add_magic_quotes( $_GET );
$_POST = add_magic_quotes( $_POST );
$_COOKIE = add_magic_quotes( $_COOKIE );
$_SERVER = add_magic_quotes( $_SERVER );
// Force REQUEST to be GET + POST.
$_REQUEST = array_merge( $_GET, $_POST );
}
```
| Uses | Description |
| --- | --- |
| [add\_magic\_quotes()](add_magic_quotes) wp-includes/functions.php | Walks the array while sanitizing the contents. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
| programming_docs |
wordpress wp_installing( bool $is_installing = null ): bool wp\_installing( bool $is\_installing = null ): bool
===================================================
Check or set whether WordPress is in “installation” mode.
If the `WP_INSTALLING` constant is defined during the bootstrap, `wp_installing()` will default to `true`.
`$is_installing` bool Optional True to set WP into Installing mode, false to turn Installing mode off.
Omit this parameter if you only want to fetch the current status. Default: `null`
bool True if WP is installing, otherwise false. When a `$is_installing` is passed, the function will report whether WP was in installing mode prior to the change to `$is_installing`.
File: `wp-includes/load.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/load.php/)
```
function wp_installing( $is_installing = null ) {
static $installing = null;
// Support for the `WP_INSTALLING` constant, defined before WP is loaded.
if ( is_null( $installing ) ) {
$installing = defined( 'WP_INSTALLING' ) && WP_INSTALLING;
}
if ( ! is_null( $is_installing ) ) {
$old_installing = $installing;
$installing = $is_installing;
return (bool) $old_installing;
}
return (bool) $installing;
}
```
| Used By | Description |
| --- | --- |
| [\_wp\_theme\_json\_webfonts\_handler()](_wp_theme_json_webfonts_handler) wp-includes/script-loader.php | Runs the theme.json webfonts handler. |
| [wp\_schedule\_update\_user\_counts()](wp_schedule_update_user_counts) wp-includes/user.php | Schedules a recurring recalculation of the total count of users. |
| [wp\_schedule\_https\_detection()](wp_schedule_https_detection) wp-includes/https-detection.php | Schedules the Cron hook for detecting HTTPS support. |
| [wp\_update\_https\_migration\_required()](wp_update_https_migration_required) wp-includes/https-migration.php | Updates the ‘https\_migration\_required’ option if needed when the given URL has been updated from HTTP to HTTPS. |
| [filter\_default\_metadata()](filter_default_metadata) wp-includes/meta.php | Filters into default\_{$object\_type}\_metadata and adds in default value. |
| [wp\_is\_maintenance\_mode()](wp_is_maintenance_mode) wp-includes/load.php | Check if maintenance mode is enabled. |
| [WP\_Site\_Health::maybe\_create\_scheduled\_event()](../classes/wp_site_health/maybe_create_scheduled_event) wp-admin/includes/class-wp-site-health.php | Creates a weekly cron event, if one does not already exist. |
| [WP\_Recovery\_Mode::initialize()](../classes/wp_recovery_mode/initialize) wp-includes/class-wp-recovery-mode.php | Initialize recovery mode for the current request. |
| [wp\_get\_active\_and\_valid\_themes()](wp_get_active_and_valid_themes) wp-includes/load.php | Retrieves an array of active and valid themes. |
| [wp\_initialize\_site()](wp_initialize_site) wp-includes/ms-site.php | Runs the initialization routine for a given site. |
| [wp\_default\_packages\_inline\_scripts()](wp_default_packages_inline_scripts) wp-includes/script-loader.php | Adds inline scripts required for the WordPress JavaScript packages. |
| [wp\_schedule\_delete\_old\_privacy\_export\_files()](wp_schedule_delete_old_privacy_export_files) wp-includes/functions.php | Schedules a `WP_Cron` job to delete expired export files. |
| [ms\_load\_current\_site\_and\_network()](ms_load_current_site_and_network) wp-includes/ms-load.php | Identifies the network and site of a requested domain and path and populates the corresponding network and site global objects as part of the multisite bootstrap process. |
| [wp\_get\_available\_translations()](wp_get_available_translations) wp-admin/includes/translation-install.php | Get available translations from the WordPress.org API. |
| [WP\_Automatic\_Updater::is\_disabled()](../classes/wp_automatic_updater/is_disabled) wp-admin/includes/class-wp-automatic-updater.php | Determines whether the entire automatic updater is disabled. |
| [update\_home\_siteurl()](update_home_siteurl) wp-admin/includes/misc.php | Flushes rewrite rules if siteurl, home or page\_on\_front changed. |
| [request\_filesystem\_credentials()](request_filesystem_credentials) wp-admin/includes/file.php | Displays a form to the user to request for their FTP/SSH details in order to connect to the filesystem. |
| [validate\_current\_theme()](validate_current_theme) wp-includes/theme.php | Checks that the active theme has the required files. |
| [load\_default\_textdomain()](load_default_textdomain) wp-includes/l10n.php | Loads default translated strings based on locale. |
| [get\_locale()](get_locale) wp-includes/l10n.php | Retrieves the current locale. |
| [wp\_not\_installed()](wp_not_installed) wp-includes/load.php | Redirect to the installer if WordPress is not installed. |
| [wp\_get\_active\_and\_valid\_plugins()](wp_get_active_and_valid_plugins) wp-includes/load.php | Retrieve an array of active and valid plugin files. |
| [dead\_db()](dead_db) wp-includes/functions.php | Loads custom DB error or display WordPress DB error. |
| [is\_blog\_installed()](is_blog_installed) wp-includes/functions.php | Determines whether WordPress is already installed. |
| [wp\_schedule\_update\_checks()](wp_schedule_update_checks) wp-includes/update.php | Schedules core, theme, and plugin update checks. |
| [wp\_version\_check()](wp_version_check) wp-includes/update.php | Checks WordPress version against the newest version. |
| [wp\_update\_plugins()](wp_update_plugins) wp-includes/update.php | Checks for available updates to plugins based on the latest versions hosted on WordPress.org. |
| [wp\_update\_themes()](wp_update_themes) wp-includes/update.php | Checks for available updates to themes based on the latest versions hosted on WordPress.org. |
| [set\_site\_transient()](set_site_transient) wp-includes/option.php | Sets/updates the value of a site transient. |
| [delete\_site\_transient()](delete_site_transient) wp-includes/option.php | Deletes a site transient. |
| [get\_site\_transient()](get_site_transient) wp-includes/option.php | Retrieves the value of a site transient. |
| [get\_transient()](get_transient) wp-includes/option.php | Retrieves the value of a transient. |
| [set\_transient()](set_transient) wp-includes/option.php | Sets/updates the value of a transient. |
| [wp\_load\_alloptions()](wp_load_alloptions) wp-includes/option.php | Loads and caches all autoloaded options, if available or all options. |
| [wp\_load\_core\_site\_options()](wp_load_core_site_options) wp-includes/option.php | Loads and caches certain often requested site options if [is\_multisite()](is_multisite) and a persistent cache is not being used. |
| [update\_option()](update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [add\_option()](add_option) wp-includes/option.php | Adds a new option. |
| [delete\_option()](delete_option) wp-includes/option.php | Removes option by name. Prevents removal of protected WordPress options. |
| [delete\_transient()](delete_transient) wp-includes/option.php | Deletes a transient. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [wp\_schedule\_update\_network\_counts()](wp_schedule_update_network_counts) wp-includes/ms-functions.php | Schedules update of the network-wide counts for the current network. |
| [wpmu\_create\_blog()](wpmu_create_blog) wp-includes/ms-functions.php | Creates a site. |
| [wp\_style\_loader\_src()](wp_style_loader_src) wp-includes/script-loader.php | Administration Screen CSS for changing the styles. |
| [script\_concat\_settings()](script_concat_settings) wp-includes/script-loader.php | Determines the concatenation and compression settings for scripts and styles. |
| [wp\_default\_scripts()](wp_default_scripts) wp-includes/script-loader.php | Registers all WordPress scripts. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress wp_checkdate( int $month, int $day, int $year, string $source_date ): bool wp\_checkdate( int $month, int $day, int $year, string $source\_date ): bool
============================================================================
Tests if the supplied date is valid for the Gregorian calendar.
`$month` int Required Month number. `$day` int Required Day number. `$year` int Required Year number. `$source_date` string Required The date to filter. bool True if valid date, false if not valid date.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function wp_checkdate( $month, $day, $year, $source_date ) {
/**
* Filters whether the given date is valid for the Gregorian calendar.
*
* @since 3.5.0
*
* @param bool $checkdate Whether the given date is valid.
* @param string $source_date Date to check.
*/
return apply_filters( 'wp_checkdate', checkdate( $month, $day, $year ), $source_date );
}
```
[apply\_filters( 'wp\_checkdate', bool $checkdate, string $source\_date )](../hooks/wp_checkdate)
Filters whether the given date is valid for the Gregorian calendar.
| Uses | Description |
| --- | --- |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_resolve\_post\_date()](wp_resolve_post_date) wp-includes/post.php | Uses wp\_checkdate to return a valid Gregorian-calendar value for post\_date. |
| [wp\_validate\_site\_data()](wp_validate_site_data) wp-includes/ms-site.php | Validates data for a site prior to inserting or updating in the database. |
| [WP\_Date\_Query::validate\_date\_values()](../classes/wp_date_query/validate_date_values) wp-includes/class-wp-date-query.php | Validates the given date\_query values and triggers errors if something is not valid. |
| [\_wp\_translate\_postdata()](_wp_translate_postdata) wp-admin/includes/post.php | Renames `$_POST` data from form names to DB post columns. |
| [WP\_Customize\_Manager::save()](../classes/wp_customize_manager/save) wp-includes/class-wp-customize-manager.php | Handles customize\_save WP Ajax request to save/update a changeset. |
| [WP\_Query::parse\_query()](../classes/wp_query/parse_query) wp-includes/class-wp-query.php | Parse a query string and set query type booleans. |
| [redirect\_canonical()](redirect_canonical) wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress get_html_split_regex(): string get\_html\_split\_regex(): string
=================================
Retrieves the regular expression for an HTML element.
string The regular expression
File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function get_html_split_regex() {
static $regex;
if ( ! isset( $regex ) ) {
// phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation
$comments =
'!' // Start of comment, after the <.
. '(?:' // Unroll the loop: Consume everything until --> is found.
. '-(?!->)' // Dash not followed by end of comment.
. '[^\-]*+' // Consume non-dashes.
. ')*+' // Loop possessively.
. '(?:-->)?'; // End of comment. If not found, match all input.
$cdata =
'!\[CDATA\[' // Start of comment, after the <.
. '[^\]]*+' // Consume non-].
. '(?:' // Unroll the loop: Consume everything until ]]> is found.
. '](?!]>)' // One ] not followed by end of comment.
. '[^\]]*+' // Consume non-].
. ')*+' // Loop possessively.
. '(?:]]>)?'; // End of comment. If not found, match all input.
$escaped =
'(?=' // Is the element escaped?
. '!--'
. '|'
. '!\[CDATA\['
. ')'
. '(?(?=!-)' // If yes, which type?
. $comments
. '|'
. $cdata
. ')';
$regex =
'/(' // Capture the entire match.
. '<' // Find start of element.
. '(?' // Conditional expression follows.
. $escaped // Find end of escaped element.
. '|' // ...else...
. '[^>]*>?' // Find end of normal element.
. ')'
. ')/';
// phpcs:enable
}
return $regex;
}
```
| Used By | Description |
| --- | --- |
| [wp\_html\_split()](wp_html_split) wp-includes/formatting.php | Separates HTML elements and comments from the text. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress sanitize_title_with_dashes( string $title, string $raw_title = '', string $context = 'display' ): string sanitize\_title\_with\_dashes( string $title, string $raw\_title = '', string $context = 'display' ): string
============================================================================================================
Sanitizes a title, replacing whitespace and a few other characters with dashes.
Limits the output to alphanumeric characters, underscore (\_) and dash (-).
Whitespace becomes a dash.
`$title` string Required The title to be sanitized. `$raw_title` string Optional Not used. Default: `''`
`$context` string Optional The operation for which the string is sanitized.
When set to `'save'`, additional entities are converted to hyphens or stripped entirely. Default `'display'`. Default: `'display'`
string The sanitized title.
* This function does not replace special accented characters.
* This function does not apply the [sanitize\_title](../hooks/sanitize_title) filter to the title.
File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
$title = strip_tags( $title );
// Preserve escaped octets.
$title = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title );
// Remove percent signs that are not part of an octet.
$title = str_replace( '%', '', $title );
// Restore octets.
$title = preg_replace( '|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title );
if ( seems_utf8( $title ) ) {
if ( function_exists( 'mb_strtolower' ) ) {
$title = mb_strtolower( $title, 'UTF-8' );
}
$title = utf8_uri_encode( $title, 200 );
}
$title = strtolower( $title );
if ( 'save' === $context ) {
// Convert  , &ndash, and &mdash to hyphens.
$title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
// Convert  , &ndash, and &mdash HTML entities to hyphens.
$title = str_replace( array( ' ', ' ', '–', '–', '—', '—' ), '-', $title );
// Convert forward slash to hyphen.
$title = str_replace( '/', '-', $title );
// Strip these characters entirely.
$title = str_replace(
array(
// Soft hyphens.
'%c2%ad',
// ¡ and ¿.
'%c2%a1',
'%c2%bf',
// Angle quotes.
'%c2%ab',
'%c2%bb',
'%e2%80%b9',
'%e2%80%ba',
// Curly quotes.
'%e2%80%98',
'%e2%80%99',
'%e2%80%9c',
'%e2%80%9d',
'%e2%80%9a',
'%e2%80%9b',
'%e2%80%9e',
'%e2%80%9f',
// Bullet.
'%e2%80%a2',
// ©, ®, °, &hellip, and &trade.
'%c2%a9',
'%c2%ae',
'%c2%b0',
'%e2%80%a6',
'%e2%84%a2',
// Acute accents.
'%c2%b4',
'%cb%8a',
'%cc%81',
'%cd%81',
// Grave accent, macron, caron.
'%cc%80',
'%cc%84',
'%cc%8c',
// Non-visible characters that display without a width.
'%e2%80%8b', // Zero width space.
'%e2%80%8c', // Zero width non-joiner.
'%e2%80%8d', // Zero width joiner.
'%e2%80%8e', // Left-to-right mark.
'%e2%80%8f', // Right-to-left mark.
'%e2%80%aa', // Left-to-right embedding.
'%e2%80%ab', // Right-to-left embedding.
'%e2%80%ac', // Pop directional formatting.
'%e2%80%ad', // Left-to-right override.
'%e2%80%ae', // Right-to-left override.
'%ef%bb%bf', // Byte order mark.
'%ef%bf%bc', // Object replacement character.
),
'',
$title
);
// Convert non-visible characters that display with a width to hyphen.
$title = str_replace(
array(
'%e2%80%80', // En quad.
'%e2%80%81', // Em quad.
'%e2%80%82', // En space.
'%e2%80%83', // Em space.
'%e2%80%84', // Three-per-em space.
'%e2%80%85', // Four-per-em space.
'%e2%80%86', // Six-per-em space.
'%e2%80%87', // Figure space.
'%e2%80%88', // Punctuation space.
'%e2%80%89', // Thin space.
'%e2%80%8a', // Hair space.
'%e2%80%a8', // Line separator.
'%e2%80%a9', // Paragraph separator.
'%e2%80%af', // Narrow no-break space.
),
'-',
$title
);
// Convert × to 'x'.
$title = str_replace( '%c3%97', 'x', $title );
}
// Kill entities.
$title = preg_replace( '/&.+?;/', '', $title );
$title = str_replace( '.', '-', $title );
$title = preg_replace( '/[^%a-z0-9 _-]/', '', $title );
$title = preg_replace( '/\s+/', '-', $title );
$title = preg_replace( '|-+|', '-', $title );
$title = trim( $title, '-' );
return $title;
}
```
| Uses | Description |
| --- | --- |
| [seems\_utf8()](seems_utf8) wp-includes/formatting.php | Checks to see if a string is utf8 encoded. |
| [utf8\_uri\_encode()](utf8_uri_encode) wp-includes/formatting.php | Encodes the Unicode values to be used in the URI. |
| Used By | Description |
| --- | --- |
| [WP\_Privacy\_Policy\_Content::privacy\_policy\_guide()](../classes/wp_privacy_policy_content/privacy_policy_guide) wp-admin/includes/class-wp-privacy-policy-content.php | Output the privacy policy guide together with content from the theme and plugins. |
| [wp\_privacy\_generate\_personal\_data\_export\_group\_html()](wp_privacy_generate_personal_data_export_group_html) wp-admin/includes/privacy-tools.php | Generate a single group for the personal data export report. |
| [wp\_privacy\_generate\_personal\_data\_export\_file()](wp_privacy_generate_personal_data_export_file) wp-admin/includes/privacy-tools.php | Generate the personal data export file. |
| [WP\_Taxonomy::set\_props()](../classes/wp_taxonomy/set_props) wp-includes/class-wp-taxonomy.php | Sets taxonomy properties. |
| [WP\_Post\_Type::set\_props()](../classes/wp_post_type/set_props) wp-includes/class-wp-post-type.php | Sets post type properties. |
| [install\_dashboard()](install_dashboard) wp-admin/includes/plugin-install.php | Displays the Featured tab of Add Plugins screen. |
| [WP\_Plugin\_Install\_List\_Table::prepare\_items()](../classes/wp_plugin_install_list_table/prepare_items) wp-admin/includes/class-wp-plugin-install-list-table.php | |
| [sanitize\_file\_name()](sanitize_file_name) wp-includes/formatting.php | Sanitizes a filename, replacing whitespace with dashes. |
| Version | Description |
| --- | --- |
| [1.2.0](https://developer.wordpress.org/reference/since/1.2.0/) | Introduced. |
wordpress weblog_ping( string $server = '', string $path = '' ) weblog\_ping( string $server = '', string $path = '' )
======================================================
Sends a pingback.
`$server` string Optional Host of blog to connect to. Default: `''`
`$path` string Optional Path to send the ping. Default: `''`
File: `wp-includes/comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/comment.php/)
```
function weblog_ping( $server = '', $path = '' ) {
include_once ABSPATH . WPINC . '/class-IXR.php';
include_once ABSPATH . WPINC . '/class-wp-http-ixr-client.php';
// Using a timeout of 3 seconds should be enough to cover slow servers.
$client = new WP_HTTP_IXR_Client( $server, ( ( ! strlen( trim( $path ) ) || ( '/' === $path ) ) ? false : $path ) );
$client->timeout = 3;
$client->useragent .= ' -- WordPress/' . get_bloginfo( 'version' );
// When set to true, this outputs debug messages by itself.
$client->debug = false;
$home = trailingslashit( home_url() );
if ( ! $client->query( 'weblogUpdates.extendedPing', get_option( 'blogname' ), $home, get_bloginfo( 'rss2_url' ) ) ) { // Then try a normal ping.
$client->query( 'weblogUpdates.ping', get_option( 'blogname' ), $home );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_HTTP\_IXR\_Client::\_\_construct()](../classes/wp_http_ixr_client/__construct) wp-includes/class-wp-http-ixr-client.php | |
| [trailingslashit()](trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| [get\_bloginfo()](get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| [home\_url()](home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [generic\_ping()](generic_ping) wp-includes/comment.php | Sends pings to all of the ping site services. |
| Version | Description |
| --- | --- |
| [1.2.0](https://developer.wordpress.org/reference/since/1.2.0/) | Introduced. |
| programming_docs |
wordpress wp_underscore_video_template() wp\_underscore\_video\_template()
=================================
Outputs the markup for a video tag to be used in an Underscore template when data.model is passed.
File: `wp-includes/media-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/media-template.php/)
```
function wp_underscore_video_template() {
$video_types = wp_get_video_extensions();
?>
<# var w_rule = '', classes = [],
w, h, settings = wp.media.view.settings,
isYouTube = isVimeo = false;
if ( ! _.isEmpty( data.model.src ) ) {
isYouTube = data.model.src.match(/youtube|youtu\.be/);
isVimeo = -1 !== data.model.src.indexOf('vimeo');
}
if ( settings.contentWidth && data.model.width >= settings.contentWidth ) {
w = settings.contentWidth;
} else {
w = data.model.width;
}
if ( w !== data.model.width ) {
h = Math.ceil( ( data.model.height * w ) / data.model.width );
} else {
h = data.model.height;
}
if ( w ) {
w_rule = 'width: ' + w + 'px; ';
}
if ( isYouTube ) {
classes.push( 'youtube-video' );
}
if ( isVimeo ) {
classes.push( 'vimeo-video' );
}
#>
<div style="{{ w_rule }}" class="wp-video">
<video controls
class="wp-video-shortcode {{ classes.join( ' ' ) }}"
<# if ( w ) { #>width="{{ w }}"<# } #>
<# if ( h ) { #>height="{{ h }}"<# } #>
<?php
$props = array(
'poster' => '',
'preload' => 'metadata',
);
foreach ( $props as $key => $value ) :
if ( empty( $value ) ) {
?>
<#
if ( ! _.isUndefined( data.model.<?php echo $key; ?> ) && data.model.<?php echo $key; ?> ) {
#> <?php echo $key; ?>="{{ data.model.<?php echo $key; ?> }}"<#
} #>
<?php
} else {
echo $key
?>
="{{ _.isUndefined( data.model.<?php echo $key; ?> ) ? '<?php echo $value; ?>' : data.model.<?php echo $key; ?> }}"
<?php
}
endforeach;
?>
<#
<?php
foreach ( array( 'autoplay', 'loop' ) as $attr ) :
?>
if ( ! _.isUndefined( data.model.<?php echo $attr; ?> ) && data.model.<?php echo $attr; ?> ) {
#> <?php echo $attr; ?><#
}
<?php endforeach; ?>#>
>
<# if ( ! _.isEmpty( data.model.src ) ) {
if ( isYouTube ) { #>
<source src="{{ data.model.src }}" type="video/youtube" />
<# } else if ( isVimeo ) { #>
<source src="{{ data.model.src }}" type="video/vimeo" />
<# } else { #>
<source src="{{ data.model.src }}" type="{{ settings.embedMimes[ data.model.src.split('.').pop() ] }}" />
<# }
} #>
<?php
foreach ( $video_types as $type ) :
?>
<# if ( data.model.<?php echo $type; ?> ) { #>
<source src="{{ data.model.<?php echo $type; ?> }}" type="{{ settings.embedMimes[ '<?php echo $type; ?>' ] }}" />
<# } #>
<?php endforeach; ?>
{{{ data.model.content }}}
</video>
</div>
<?php
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_video\_extensions()](wp_get_video_extensions) wp-includes/media.php | Returns a filtered list of supported video formats. |
| Used By | Description |
| --- | --- |
| [WP\_Widget\_Media\_Video::render\_control\_template\_scripts()](../classes/wp_widget_media_video/render_control_template_scripts) wp-includes/widgets/class-wp-widget-media-video.php | Render form template scripts. |
| [wp\_print\_media\_templates()](wp_print_media_templates) wp-includes/media-template.php | Prints the templates used in the media manager. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress get_default_page_to_edit(): WP_Post get\_default\_page\_to\_edit(): WP\_Post
========================================
This function has been deprecated. Use [get\_default\_post\_to\_edit()](get_default_post_to_edit) instead.
Gets the default page information to use.
* [get\_default\_post\_to\_edit()](get_default_post_to_edit)
[WP\_Post](../classes/wp_post) Post object containing all the default post data as attributes
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
function get_default_page_to_edit() {
_deprecated_function( __FUNCTION__, '3.5.0', "get_default_post_to_edit( 'page' )" );
$page = get_default_post_to_edit();
$page->post_type = 'page';
return $page;
}
```
| Uses | Description |
| --- | --- |
| [get\_default\_post\_to\_edit()](get_default_post_to_edit) wp-admin/includes/post.php | Returns default post information to use when populating the “Write Post” form. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Use [get\_default\_post\_to\_edit()](get_default_post_to_edit) |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress _filter_block_template_part_area( string $type ): string \_filter\_block\_template\_part\_area( string $type ): string
=============================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Checks whether the input ‘area’ is a supported value.
Returns the input if supported, otherwise returns the ‘uncategorized’ value.
`$type` string Required Template part area name. string Input if supported, else the uncategorized value.
File: `wp-includes/block-template-utils.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/block-template-utils.php/)
```
function _filter_block_template_part_area( $type ) {
$allowed_areas = array_map(
static function ( $item ) {
return $item['area'];
},
get_allowed_block_template_part_areas()
);
if ( in_array( $type, $allowed_areas, true ) ) {
return $type;
}
$warning_message = sprintf(
/* translators: %1$s: Template area type, %2$s: the uncategorized template area value. */
__( '"%1$s" is not a supported wp_template_part area value and has been added as "%2$s".' ),
$type,
WP_TEMPLATE_PART_AREA_UNCATEGORIZED
);
trigger_error( $warning_message, E_USER_NOTICE );
return WP_TEMPLATE_PART_AREA_UNCATEGORIZED;
}
```
| Uses | Description |
| --- | --- |
| [get\_allowed\_block\_template\_part\_areas()](get_allowed_block_template_part_areas) wp-includes/block-template-utils.php | Returns a filtered list of allowed area values for template parts. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [\_add\_block\_template\_part\_area\_info()](_add_block_template_part_area_info) wp-includes/block-template-utils.php | Attempts to add the template part’s area information to the input template. |
| [WP\_REST\_Templates\_Controller::prepare\_item\_for\_database()](../classes/wp_rest_templates_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Prepares a single template for create or update. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress get_inline_data( WP_Post $post ) get\_inline\_data( WP\_Post $post )
===================================
Adds hidden fields with the data for use in the inline editor for posts and pages.
`$post` [WP\_Post](../classes/wp_post) Required Post object. File: `wp-admin/includes/template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/template.php/)
```
function get_inline_data( $post ) {
$post_type_object = get_post_type_object( $post->post_type );
if ( ! current_user_can( 'edit_post', $post->ID ) ) {
return;
}
$title = esc_textarea( trim( $post->post_title ) );
echo '
<div class="hidden" id="inline_' . $post->ID . '">
<div class="post_title">' . $title . '</div>' .
/** This filter is documented in wp-admin/edit-tag-form.php */
'<div class="post_name">' . apply_filters( 'editable_slug', $post->post_name, $post ) . '</div>
<div class="post_author">' . $post->post_author . '</div>
<div class="comment_status">' . esc_html( $post->comment_status ) . '</div>
<div class="ping_status">' . esc_html( $post->ping_status ) . '</div>
<div class="_status">' . esc_html( $post->post_status ) . '</div>
<div class="jj">' . mysql2date( 'd', $post->post_date, false ) . '</div>
<div class="mm">' . mysql2date( 'm', $post->post_date, false ) . '</div>
<div class="aa">' . mysql2date( 'Y', $post->post_date, false ) . '</div>
<div class="hh">' . mysql2date( 'H', $post->post_date, false ) . '</div>
<div class="mn">' . mysql2date( 'i', $post->post_date, false ) . '</div>
<div class="ss">' . mysql2date( 's', $post->post_date, false ) . '</div>
<div class="post_password">' . esc_html( $post->post_password ) . '</div>';
if ( $post_type_object->hierarchical ) {
echo '<div class="post_parent">' . $post->post_parent . '</div>';
}
echo '<div class="page_template">' . ( $post->page_template ? esc_html( $post->page_template ) : 'default' ) . '</div>';
if ( post_type_supports( $post->post_type, 'page-attributes' ) ) {
echo '<div class="menu_order">' . $post->menu_order . '</div>';
}
$taxonomy_names = get_object_taxonomies( $post->post_type );
foreach ( $taxonomy_names as $taxonomy_name ) {
$taxonomy = get_taxonomy( $taxonomy_name );
if ( ! $taxonomy->show_in_quick_edit ) {
continue;
}
if ( $taxonomy->hierarchical ) {
$terms = get_object_term_cache( $post->ID, $taxonomy_name );
if ( false === $terms ) {
$terms = wp_get_object_terms( $post->ID, $taxonomy_name );
wp_cache_add( $post->ID, wp_list_pluck( $terms, 'term_id' ), $taxonomy_name . '_relationships' );
}
$term_ids = empty( $terms ) ? array() : wp_list_pluck( $terms, 'term_id' );
echo '<div class="post_category" id="' . $taxonomy_name . '_' . $post->ID . '">' . implode( ',', $term_ids ) . '</div>';
} else {
$terms_to_edit = get_terms_to_edit( $post->ID, $taxonomy_name );
if ( ! is_string( $terms_to_edit ) ) {
$terms_to_edit = '';
}
echo '<div class="tags_input" id="' . $taxonomy_name . '_' . $post->ID . '">'
. esc_html( str_replace( ',', ', ', $terms_to_edit ) ) . '</div>';
}
}
if ( ! $post_type_object->hierarchical ) {
echo '<div class="sticky">' . ( is_sticky( $post->ID ) ? 'sticky' : '' ) . '</div>';
}
if ( post_type_supports( $post->post_type, 'post-formats' ) ) {
echo '<div class="post_format">' . esc_html( get_post_format( $post->ID ) ) . '</div>';
}
/**
* Fires after outputting the fields for the inline editor for posts and pages.
*
* @since 4.9.8
*
* @param WP_Post $post The current post object.
* @param WP_Post_Type $post_type_object The current post's post type object.
*/
do_action( 'add_inline_data', $post, $post_type_object );
echo '</div>';
}
```
[do\_action( 'add\_inline\_data', WP\_Post $post, WP\_Post\_Type $post\_type\_object )](../hooks/add_inline_data)
Fires after outputting the fields for the inline editor for posts and pages.
[apply\_filters( 'editable\_slug', string $slug, WP\_Term|WP\_Post $tag )](../hooks/editable_slug)
Filters the editable slug for a post or term.
| Uses | Description |
| --- | --- |
| [get\_terms\_to\_edit()](get_terms_to_edit) wp-admin/includes/taxonomy.php | Gets comma-separated list of terms available to edit for the given post ID. |
| [get\_object\_term\_cache()](get_object_term_cache) wp-includes/taxonomy.php | Retrieves the cached term objects for the given object ID. |
| [post\_type\_supports()](post_type_supports) wp-includes/post.php | Checks a post type’s support for a given feature. |
| [is\_sticky()](is_sticky) wp-includes/post.php | Determines whether a post is sticky. |
| [get\_object\_taxonomies()](get_object_taxonomies) wp-includes/taxonomy.php | Returns the names or objects of the taxonomies which are registered for the requested object or object type, such as a post object or post type name. |
| [wp\_get\_object\_terms()](wp_get_object_terms) wp-includes/taxonomy.php | Retrieves the terms associated with the given object(s), in the supplied taxonomies. |
| [mysql2date()](mysql2date) wp-includes/functions.php | Converts given MySQL date string into a different format. |
| [wp\_list\_pluck()](wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [esc\_textarea()](esc_textarea) wp-includes/formatting.php | Escaping for textarea values. |
| [wp\_cache\_add()](wp_cache_add) wp-includes/cache.php | Adds data to the cache, if the cache key doesn’t already exist. |
| [get\_post\_format()](get_post_format) wp-includes/post-formats.php | Retrieve the format slug for a post |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [get\_taxonomy()](get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_post\_type\_object()](get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Used By | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::column\_title()](../classes/wp_posts_list_table/column_title) wp-admin/includes/class-wp-posts-list-table.php | Handles the title column output. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress wp_get_extension_error_description( array $error ): string wp\_get\_extension\_error\_description( array $error ): string
==============================================================
Get a human readable description of an extension’s error.
`$error` array Required Error details from `error_get_last()`. string Formatted error description.
File: `wp-includes/error-protection.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/error-protection.php/)
```
function wp_get_extension_error_description( $error ) {
$constants = get_defined_constants( true );
$constants = isset( $constants['Core'] ) ? $constants['Core'] : $constants['internal'];
$core_errors = array();
foreach ( $constants as $constant => $value ) {
if ( 0 === strpos( $constant, 'E_' ) ) {
$core_errors[ $value ] = $constant;
}
}
if ( isset( $core_errors[ $error['type'] ] ) ) {
$error['type'] = $core_errors[ $error['type'] ];
}
/* translators: 1: Error type, 2: Error line number, 3: Error file name, 4: Error message. */
$error_message = __( 'An error of type %1$s was caused in line %2$s of the file %3$s. Error message: %4$s' );
return sprintf(
$error_message,
"<code>{$error['type']}</code>",
"<code>{$error['line']}</code>",
"<code>{$error['file']}</code>",
"<code>{$error['message']}</code>"
);
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Email\_Service::send\_recovery\_mode\_email()](../classes/wp_recovery_mode_email_service/send_recovery_mode_email) wp-includes/class-wp-recovery-mode-email-service.php | Sends the Recovery Mode email to the site admin email address. |
| [WP\_Plugins\_List\_Table::single\_row()](../classes/wp_plugins_list_table/single_row) wp-admin/includes/class-wp-plugins-list-table.php | |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress wp_enqueue_editor_block_directory_assets() wp\_enqueue\_editor\_block\_directory\_assets()
===============================================
Enqueues the assets required for the block directory within the block editor.
File: `wp-includes/script-loader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/script-loader.php/)
```
function wp_enqueue_editor_block_directory_assets() {
wp_enqueue_script( 'wp-block-directory' );
wp_enqueue_style( 'wp-block-directory' );
}
```
| Uses | Description |
| --- | --- |
| [wp\_enqueue\_script()](wp_enqueue_script) wp-includes/functions.wp-scripts.php | Enqueue a script. |
| [wp\_enqueue\_style()](wp_enqueue_style) wp-includes/functions.wp-styles.php | Enqueue a CSS stylesheet. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress add_action( string $hook_name, callable $callback, int $priority = 10, int $accepted_args = 1 ): true add\_action( string $hook\_name, callable $callback, int $priority = 10, int $accepted\_args = 1 ): true
========================================================================================================
Adds a callback function to an action hook.
Actions are the hooks that the WordPress core launches at specific points during execution, or when specific events occur. Plugins can specify that one or more of its PHP functions are executed at these points, using the Action API.
`$hook_name` string Required The name of the action to add the callback to. `$callback` callable Required The callback to be run when the action is called. `$priority` int Optional Used to specify the order in which the functions associated with a particular action are executed.
Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action. Default: `10`
`$accepted_args` int Optional The number of arguments the function accepts. Default: `1`
true Always returns true.
```
add_action( $hook, $function_to_add, $priority, $accepted_args );
```
To find out the number and name of arguments for an action, simply search the code base for the matching [do\_action()](do_action) call. For example, if you are hooking into ‘save\_post’, you would find it in post.php:
```
do_action( 'save_post', $post_ID, $post, $update );
```
Your add\_action call would look like:
```
add_action( 'save_post', 'wpdocs_my_save_post', 10, 3 );
```
And your function would be:
```
function wpdocs_my_save_post( $post_ID, $post, $update ) {
// do stuff here
}
```
File: `wp-includes/plugin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/plugin.php/)
```
function add_action( $hook_name, $callback, $priority = 10, $accepted_args = 1 ) {
return add_filter( $hook_name, $callback, $priority, $accepted_args );
}
```
| Uses | Description |
| --- | --- |
| [add\_filter()](add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_enqueue\_block\_support\_styles()](wp_enqueue_block_support_styles) wp-includes/script-loader.php | Hooks inline styles in the proper place, depending on the active theme. |
| [\_wp\_theme\_json\_webfonts\_handler()](_wp_theme_json_webfonts_handler) wp-includes/script-loader.php | Runs the theme.json webfonts handler. |
| [wp\_enqueue\_block\_style()](wp_enqueue_block_style) wp-includes/script-loader.php | Enqueues a stylesheet for a specific block. |
| [locate\_block\_template()](locate_block_template) wp-includes/block-template.php | Finds a block template with equal or higher specificity than a given PHP template file. |
| [WP\_Sitemaps::init()](../classes/wp_sitemaps/init) wp-includes/sitemaps/class-wp-sitemaps.php | Initiates all sitemap functionality. |
| [WP\_Recovery\_Mode::initialize()](../classes/wp_recovery_mode/initialize) wp-includes/class-wp-recovery-mode.php | Initialize recovery mode for the current request. |
| [WP\_Site\_Health::\_\_construct()](../classes/wp_site_health/__construct) wp-admin/includes/class-wp-site-health.php | [WP\_Site\_Health](../classes/wp_site_health) constructor. |
| [wp\_is\_site\_initialized()](wp_is_site_initialized) wp-includes/ms-site.php | Checks whether a site is initialized. |
| [register\_and\_do\_post\_meta\_boxes()](register_and_do_post_meta_boxes) wp-admin/includes/meta-boxes.php | Registers the default post meta boxes, and runs the `do_meta_boxes` actions. |
| [WP\_Privacy\_Policy\_Content::text\_change\_check()](../classes/wp_privacy_policy_content/text_change_check) wp-admin/includes/class-wp-privacy-policy-content.php | Quick check if any privacy info has changed. |
| [WP\_Roles::get\_roles\_data()](../classes/wp_roles/get_roles_data) wp-includes/class-wp-roles.php | Gets the available roles data. |
| [WP\_Widget\_Text::\_register\_one()](../classes/wp_widget_text/_register_one) wp-includes/widgets/class-wp-widget-text.php | Add hooks for enqueueing assets when registering all widget instances of this widget class. |
| [WP\_Widget\_Custom\_HTML::\_register\_one()](../classes/wp_widget_custom_html/_register_one) wp-includes/widgets/class-wp-widget-custom-html.php | Add hooks for enqueueing assets when registering all widget instances of this widget class. |
| [WP\_Widget\_Media::\_register\_one()](../classes/wp_widget_media/_register_one) wp-includes/widgets/class-wp-widget-media.php | Add hooks while registering all widget instances of this widget class. |
| [\_WP\_Editors::enqueue\_default\_editor()](../classes/_wp_editors/enqueue_default_editor) wp-includes/class-wp-editor.php | Enqueue all editor scripts. |
| [\_wp\_delete\_customize\_changeset\_dependent\_auto\_drafts()](_wp_delete_customize_changeset_dependent_auto_drafts) wp-includes/nav-menu.php | Deletes auto-draft posts associated with the supplied changeset. |
| [WP\_Customize\_Manager::import\_theme\_starter\_content()](../classes/wp_customize_manager/import_theme_starter_content) wp-includes/class-wp-customize-manager.php | Imports theme starter content into the customized state. |
| [WP\_Post\_Type::register\_meta\_boxes()](../classes/wp_post_type/register_meta_boxes) wp-includes/class-wp-post-type.php | Registers the post type meta box if a custom callback was specified. |
| [WP\_Post\_Type::add\_hooks()](../classes/wp_post_type/add_hooks) wp-includes/class-wp-post-type.php | Adds the future post hook action for the post type. |
| [WP\_Customize\_Widgets::selective\_refresh\_init()](../classes/wp_customize_widgets/selective_refresh_init) wp-includes/class-wp-customize-widgets.php | Adds hooks for selective refresh. |
| [WP\_Customize\_Selective\_Refresh::init\_preview()](../classes/wp_customize_selective_refresh/init_preview) wp-includes/customize/class-wp-customize-selective-refresh.php | Initializes the Customizer preview. |
| [WP\_Customize\_Selective\_Refresh::enqueue\_preview\_scripts()](../classes/wp_customize_selective_refresh/enqueue_preview_scripts) wp-includes/customize/class-wp-customize-selective-refresh.php | Enqueues preview scripts. |
| [WP\_Customize\_Selective\_Refresh::\_\_construct()](../classes/wp_customize_selective_refresh/__construct) wp-includes/customize/class-wp-customize-selective-refresh.php | Plugin bootstrap for Partial Refresh functionality. |
| [rest\_api\_default\_filters()](rest_api_default_filters) wp-includes/rest-api.php | Registers the default REST API filters. |
| [WP\_Customize\_Setting::aggregate\_multidimensional()](../classes/wp_customize_setting/aggregate_multidimensional) wp-includes/class-wp-customize-setting.php | Set up the setting for aggregated multidimensional values. |
| [wp\_admin\_bar\_customize\_menu()](wp_admin_bar_customize_menu) wp-includes/admin-bar.php | Adds the “Customize” link to the Toolbar. |
| [WP\_Widget\_Factory::\_\_construct()](../classes/wp_widget_factory/__construct) wp-includes/class-wp-widget-factory.php | PHP5 constructor. |
| [WP\_Customize\_Site\_Icon\_Control::\_\_construct()](../classes/wp_customize_site_icon_control/__construct) wp-includes/customize/class-wp-customize-site-icon-control.php | Constructor. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::\_\_construct()](../classes/wp_customize_nav_menu_item_setting/__construct) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Constructor. |
| [WP\_Customize\_Nav\_Menus::customize\_preview\_init()](../classes/wp_customize_nav_menus/customize_preview_init) wp-includes/class-wp-customize-nav-menus.php | Adds hooks for the Customizer preview. |
| [WP\_Customize\_Nav\_Menus::\_\_construct()](../classes/wp_customize_nav_menus/__construct) wp-includes/class-wp-customize-nav-menus.php | Constructor. |
| [WP\_Site\_Icon::\_\_construct()](../classes/wp_site_icon/__construct) wp-admin/includes/class-wp-site-icon.php | Registers actions and filters. |
| [login\_header()](login_header) wp-login.php | Output the login page header. |
| [Language\_Pack\_Upgrader::bulk\_upgrade()](../classes/language_pack_upgrader/bulk_upgrade) wp-admin/includes/class-language-pack-upgrader.php | Bulk upgrade language packs. |
| [Theme\_Upgrader::install()](../classes/theme_upgrader/install) wp-admin/includes/class-theme-upgrader.php | Install a theme package. |
| [Theme\_Upgrader::upgrade()](../classes/theme_upgrader/upgrade) wp-admin/includes/class-theme-upgrader.php | Upgrade a theme. |
| [Plugin\_Upgrader::install()](../classes/plugin_upgrader/install) wp-admin/includes/class-plugin-upgrader.php | Install a plugin package. |
| [Plugin\_Upgrader::upgrade()](../classes/plugin_upgrader/upgrade) wp-admin/includes/class-plugin-upgrader.php | Upgrade a plugin. |
| [WP\_List\_Table::\_\_construct()](../classes/wp_list_table/__construct) wp-admin/includes/class-wp-list-table.php | Constructor. |
| [WP\_Theme\_Install\_List\_Table::prepare\_items()](../classes/wp_theme_install_list_table/prepare_items) wp-admin/includes/class-wp-theme-install-list-table.php | |
| [wp\_plugin\_update\_rows()](wp_plugin_update_rows) wp-admin/includes/update.php | Adds a callback to display update information for plugins with updates available. |
| [wp\_theme\_update\_rows()](wp_theme_update_rows) wp-admin/includes/update.php | Adds a callback to display update information for themes with updates available. |
| [uninstall\_plugin()](uninstall_plugin) wp-admin/includes/plugin.php | Uninstalls a single plugin. |
| [add\_menu\_page()](add_menu_page) wp-admin/includes/plugin.php | Adds a top-level menu page. |
| [add\_submenu\_page()](add_submenu_page) wp-admin/includes/plugin.php | Adds a submenu page. |
| [WP\_Plugin\_Install\_List\_Table::prepare\_items()](../classes/wp_plugin_install_list_table/prepare_items) wp-admin/includes/class-wp-plugin-install-list-table.php | |
| [WP\_Internal\_Pointers::enqueue\_scripts()](../classes/wp_internal_pointers/enqueue_scripts) wp-admin/includes/class-wp-internal-pointers.php | Initializes the new feature pointers. |
| [Custom\_Image\_Header::\_\_construct()](../classes/custom_image_header/__construct) wp-admin/includes/class-custom-image-header.php | Constructor – Register administration header callback. |
| [Custom\_Image\_Header::init()](../classes/custom_image_header/init) wp-admin/includes/class-custom-image-header.php | Set up the hooks for the Custom Header admin page. |
| [Custom\_Background::\_\_construct()](../classes/custom_background/__construct) wp-admin/includes/class-custom-background.php | Constructor – Registers administration header callback. |
| [Custom\_Background::init()](../classes/custom_background/init) wp-admin/includes/class-custom-background.php | Sets up the hooks for the Custom Background admin page. |
| [WP\_Customize\_Manager::customize\_preview\_init()](../classes/wp_customize_manager/customize_preview_init) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings. |
| [WP\_Customize\_Manager::setup\_theme()](../classes/wp_customize_manager/setup_theme) wp-includes/class-wp-customize-manager.php | Starts preview and customize theme. |
| [WP\_Customize\_Manager::\_\_construct()](../classes/wp_customize_manager/__construct) wp-includes/class-wp-customize-manager.php | Constructor. |
| [wp\_cron()](wp_cron) wp-includes/cron.php | Register [\_wp\_cron()](_wp_cron) to run on the {@see ‘wp\_loaded’} action. |
| [\_custom\_header\_background\_just\_in\_time()](_custom_header_background_just_in_time) wp-includes/theme.php | Registers the internal custom header and background routines. |
| [add\_thickbox()](add_thickbox) wp-includes/general-template.php | Enqueues the default ThickBox js and css. |
| [wp\_auth\_check\_load()](wp_auth_check_load) wp-includes/functions.php | Loads the auth check for monitoring whether the user is still logged in. |
| [wp\_maybe\_load\_widgets()](wp_maybe_load_widgets) wp-includes/functions.php | Determines if Widgets library should be loaded. |
| [WP\_Widget\_Recent\_Comments::\_\_construct()](../classes/wp_widget_recent_comments/__construct) wp-includes/widgets/class-wp-widget-recent-comments.php | Sets up a new Recent Comments widget instance. |
| [WP\_Embed::\_\_construct()](../classes/wp_embed/__construct) wp-includes/class-wp-embed.php | Constructor |
| [WP\_Admin\_Bar::add\_menus()](../classes/wp_admin_bar/add_menus) wp-includes/class-wp-admin-bar.php | Adds menus to the admin bar. |
| [WP\_Admin\_Bar::initialize()](../classes/wp_admin_bar/initialize) wp-includes/class-wp-admin-bar.php | Initializes the admin bar. |
| [register\_activation\_hook()](register_activation_hook) wp-includes/plugin.php | Set the activation hook for a plugin. |
| [register\_deactivation\_hook()](register_deactivation_hook) wp-includes/plugin.php | Sets the deactivation hook for a plugin. |
| [WP\_Customize\_Setting::preview()](../classes/wp_customize_setting/preview) wp-includes/class-wp-customize-setting.php | Add filters to supply the setting’s value when accessed. |
| [wp\_enqueue\_media()](wp_enqueue_media) wp-includes/media.php | Enqueues all scripts, styles, settings, and templates necessary to use all media JS APIs. |
| [wp\_playlist\_scripts()](wp_playlist_scripts) wp-includes/media.php | Outputs and enqueues default scripts and styles for playlists. |
| [WP\_Rewrite::wp\_rewrite\_rules()](../classes/wp_rewrite/wp_rewrite_rules) wp-includes/class-wp-rewrite.php | Retrieves the rewrite rules. |
| [WP\_Rewrite::flush\_rules()](../classes/wp_rewrite/flush_rules) wp-includes/class-wp-rewrite.php | Removes rewrite rules and then recreate rewrite rules. |
| [add\_feed()](add_feed) wp-includes/rewrite.php | Adds a new feed type like /atom1/. |
| [WP\_Scripts::\_\_construct()](../classes/wp_scripts/__construct) wp-includes/class-wp-scripts.php | Constructor. |
| [WP\_Customize\_Header\_Image\_Control::prepare\_control()](../classes/wp_customize_header_image_control/prepare_control) wp-includes/customize/class-wp-customize-header-image-control.php | |
| [WP\_Customize\_Widgets::customize\_preview\_init()](../classes/wp_customize_widgets/customize_preview_init) wp-includes/class-wp-customize-widgets.php | Adds hooks for the Customizer preview. |
| [WP\_Customize\_Widgets::\_\_construct()](../classes/wp_customize_widgets/__construct) wp-includes/class-wp-customize-widgets.php | Initial loader. |
| [WP\_Customize\_Widgets::schedule\_customize\_register()](../classes/wp_customize_widgets/schedule_customize_register) wp-includes/class-wp-customize-widgets.php | Ensures widgets are available for all types of previews. |
| [wp\_set\_comment\_status()](wp_set_comment_status) wp-includes/comment.php | Sets the status of a comment. |
| [\_WP\_Editors::editor\_settings()](../classes/_wp_editors/editor_settings) wp-includes/class-wp-editor.php | |
| [wp\_print\_media\_templates()](wp_print_media_templates) wp-includes/media-template.php | Prints the templates used in the media manager. |
| Version | Description |
| --- | --- |
| [1.2.0](https://developer.wordpress.org/reference/since/1.2.0/) | Introduced. |
| programming_docs |
wordpress rest_format_combining_operation_error( string $param, array $error ): WP_Error rest\_format\_combining\_operation\_error( string $param, array $error ): WP\_Error
===================================================================================
Formats a combining operation error into a [WP\_Error](../classes/wp_error) object.
`$param` string Required The parameter name. `$error` array Required The error details. [WP\_Error](../classes/wp_error)
File: `wp-includes/rest-api.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api.php/)
```
function rest_format_combining_operation_error( $param, $error ) {
$position = $error['index'];
$reason = $error['error_object']->get_error_message();
if ( isset( $error['schema']['title'] ) ) {
$title = $error['schema']['title'];
return new WP_Error(
'rest_no_matching_schema',
/* translators: 1: Parameter, 2: Schema title, 3: Reason. */
sprintf( __( '%1$s is not a valid %2$s. Reason: %3$s' ), $param, $title, $reason ),
array( 'position' => $position )
);
}
return new WP_Error(
'rest_no_matching_schema',
/* translators: 1: Parameter, 2: Reason. */
sprintf( __( '%1$s does not match the expected format. Reason: %2$s' ), $param, $reason ),
array( 'position' => $position )
);
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../classes/wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [rest\_get\_combining\_operation\_error()](rest_get_combining_operation_error) wp-includes/rest-api.php | Gets the error of combining operation. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress wp_dashboard_primary() wp\_dashboard\_primary()
========================
‘WordPress Events and News’ dashboard widget.
File: `wp-admin/includes/dashboard.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/dashboard.php/)
```
function wp_dashboard_primary() {
$feeds = array(
'news' => array(
/**
* Filters the primary link URL for the 'WordPress Events and News' dashboard widget.
*
* @since 2.5.0
*
* @param string $link The widget's primary link URL.
*/
'link' => apply_filters( 'dashboard_primary_link', __( 'https://wordpress.org/news/' ) ),
/**
* Filters the primary feed URL for the 'WordPress Events and News' dashboard widget.
*
* @since 2.3.0
*
* @param string $url The widget's primary feed URL.
*/
'url' => apply_filters( 'dashboard_primary_feed', __( 'https://wordpress.org/news/feed/' ) ),
/**
* Filters the primary link title for the 'WordPress Events and News' dashboard widget.
*
* @since 2.3.0
*
* @param string $title Title attribute for the widget's primary link.
*/
'title' => apply_filters( 'dashboard_primary_title', __( 'WordPress Blog' ) ),
'items' => 2,
'show_summary' => 0,
'show_author' => 0,
'show_date' => 0,
),
'planet' => array(
/**
* Filters the secondary link URL for the 'WordPress Events and News' dashboard widget.
*
* @since 2.3.0
*
* @param string $link The widget's secondary link URL.
*/
'link' => apply_filters( 'dashboard_secondary_link', __( 'https://planet.wordpress.org/' ) ),
/**
* Filters the secondary feed URL for the 'WordPress Events and News' dashboard widget.
*
* @since 2.3.0
*
* @param string $url The widget's secondary feed URL.
*/
'url' => apply_filters( 'dashboard_secondary_feed', __( 'https://planet.wordpress.org/feed/' ) ),
/**
* Filters the secondary link title for the 'WordPress Events and News' dashboard widget.
*
* @since 2.3.0
*
* @param string $title Title attribute for the widget's secondary link.
*/
'title' => apply_filters( 'dashboard_secondary_title', __( 'Other WordPress News' ) ),
/**
* Filters the number of secondary link items for the 'WordPress Events and News' dashboard widget.
*
* @since 4.4.0
*
* @param string $items How many items to show in the secondary feed.
*/
'items' => apply_filters( 'dashboard_secondary_items', 3 ),
'show_summary' => 0,
'show_author' => 0,
'show_date' => 0,
),
);
wp_dashboard_cached_rss_widget( 'dashboard_primary', 'wp_dashboard_primary_output', $feeds );
}
```
[apply\_filters( 'dashboard\_primary\_feed', string $url )](../hooks/dashboard_primary_feed)
Filters the primary feed URL for the ‘WordPress Events and News’ dashboard widget.
[apply\_filters( 'dashboard\_primary\_link', string $link )](../hooks/dashboard_primary_link)
Filters the primary link URL for the ‘WordPress Events and News’ dashboard widget.
[apply\_filters( 'dashboard\_primary\_title', string $title )](../hooks/dashboard_primary_title)
Filters the primary link title for the ‘WordPress Events and News’ dashboard widget.
[apply\_filters( 'dashboard\_secondary\_feed', string $url )](../hooks/dashboard_secondary_feed)
Filters the secondary feed URL for the ‘WordPress Events and News’ dashboard widget.
[apply\_filters( 'dashboard\_secondary\_items', string $items )](../hooks/dashboard_secondary_items)
Filters the number of secondary link items for the ‘WordPress Events and News’ dashboard widget.
[apply\_filters( 'dashboard\_secondary\_link', string $link )](../hooks/dashboard_secondary_link)
Filters the secondary link URL for the ‘WordPress Events and News’ dashboard widget.
[apply\_filters( 'dashboard\_secondary\_title', string $title )](../hooks/dashboard_secondary_title)
Filters the secondary link title for the ‘WordPress Events and News’ dashboard widget.
| Uses | Description |
| --- | --- |
| [wp\_dashboard\_cached\_rss\_widget()](wp_dashboard_cached_rss_widget) wp-admin/includes/dashboard.php | Checks to see if all of the feed url in $check\_urls are cached. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_dashboard\_events\_news()](wp_dashboard_events_news) wp-admin/includes/dashboard.php | Renders the Events and News dashboard widget. |
| [wp\_ajax\_dashboard\_widgets()](wp_ajax_dashboard_widgets) wp-admin/includes/ajax-actions.php | Ajax handler for dashboard widgets. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Removed popular plugins feed. |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress rest_get_server(): WP_REST_Server rest\_get\_server(): WP\_REST\_Server
=====================================
Retrieves the current REST server instance.
Instantiates a new instance if none exists already.
[WP\_REST\_Server](../classes/wp_rest_server) REST server instance.
File: `wp-includes/rest-api.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api.php/)
```
function rest_get_server() {
/* @var WP_REST_Server $wp_rest_server */
global $wp_rest_server;
if ( empty( $wp_rest_server ) ) {
/**
* Filters the REST Server Class.
*
* This filter allows you to adjust the server class used by the REST API, using a
* different class to handle requests.
*
* @since 4.4.0
*
* @param string $class_name The name of the server class. Default 'WP_REST_Server'.
*/
$wp_rest_server_class = apply_filters( 'wp_rest_server_class', 'WP_REST_Server' );
$wp_rest_server = new $wp_rest_server_class;
/**
* Fires when preparing to serve a REST API request.
*
* Endpoint objects should be created and register their hooks on this action rather
* than another action to ensure they're only loaded when needed.
*
* @since 4.4.0
*
* @param WP_REST_Server $wp_rest_server Server object.
*/
do_action( 'rest_api_init', $wp_rest_server );
}
return $wp_rest_server;
}
```
[do\_action( 'rest\_api\_init', WP\_REST\_Server $wp\_rest\_server )](../hooks/rest_api_init)
Fires when preparing to serve a REST API request.
[apply\_filters( 'wp\_rest\_server\_class', string $class\_name )](../hooks/wp_rest_server_class)
Filters the REST Server Class.
| Uses | Description |
| --- | --- |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [rest\_preload\_api\_request()](rest_preload_api_request) wp-includes/rest-api.php | Append result of internal request to REST API for purpose of preloading data to be attached to a page. |
| [WP\_REST\_Controller::prepare\_response\_for\_collection()](../classes/wp_rest_controller/prepare_response_for_collection) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Prepares a response for insertion into a collection. |
| [rest\_cookie\_check\_errors()](rest_cookie_check_errors) wp-includes/rest-api.php | Checks for errors when using cookie-based authentication. |
| [rest\_do\_request()](rest_do_request) wp-includes/rest-api.php | Do a REST request. |
| [rest\_api\_loaded()](rest_api_loaded) wp-includes/rest-api.php | Loads the REST API. |
| [register\_rest\_route()](register_rest_route) wp-includes/rest-api.php | Registers a REST API route. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress wp_maintenance() wp\_maintenance()
=================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Die with a maintenance message when conditions are met.
The default message can be replaced by using a drop-in (maintenance.php in the wp-content directory).
File: `wp-includes/load.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/load.php/)
```
function wp_maintenance() {
// Return if maintenance mode is disabled.
if ( ! wp_is_maintenance_mode() ) {
return;
}
if ( file_exists( WP_CONTENT_DIR . '/maintenance.php' ) ) {
require_once WP_CONTENT_DIR . '/maintenance.php';
die();
}
require_once ABSPATH . WPINC . '/functions.php';
wp_load_translations_early();
header( 'Retry-After: 600' );
wp_die(
__( 'Briefly unavailable for scheduled maintenance. Check back in a minute.' ),
__( 'Maintenance' ),
503
);
}
```
| Uses | Description |
| --- | --- |
| [wp\_is\_maintenance\_mode()](wp_is_maintenance_mode) wp-includes/load.php | Check if maintenance mode is enabled. |
| [wp\_load\_translations\_early()](wp_load_translations_early) wp-includes/load.php | Attempt an early load of translations. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_die()](wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress _get_widget_id_base( string $id ): string \_get\_widget\_id\_base( string $id ): string
=============================================
Retrieves the widget ID base value.
`$id` string Required Widget ID. string Widget ID base.
File: `wp-includes/widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets.php/)
```
function _get_widget_id_base( $id ) {
return preg_replace( '/-[0-9]+$/', '', $id );
}
```
| Used By | Description |
| --- | --- |
| [is\_active\_widget()](is_active_widget) wp-includes/widgets.php | Determines whether a given widget is displayed on the front end. |
| [wp\_register\_sidebar\_widget()](wp_register_sidebar_widget) wp-includes/widgets.php | Register an instance of a widget. |
| [wp\_register\_widget\_control()](wp_register_widget_control) wp-includes/widgets.php | Registers widget control callback for customizing options. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress get_lastpostmodified( string $timezone = 'server', string $post_type = 'any' ): string get\_lastpostmodified( string $timezone = 'server', string $post\_type = 'any' ): string
========================================================================================
Gets the most recent time that a post on the site was modified.
The server timezone is the default and is the difference between GMT and server time. The ‘blog’ value is just when the last post was modified.
The ‘gmt’ is when the last post was modified in GMT time.
`$timezone` string Optional The timezone for the timestamp. See [get\_lastpostdate()](get_lastpostdate) for information on accepted values.
Default `'server'`. More Arguments from get\_lastpostdate( ... $timezone ) The timezone for the timestamp. Accepts `'server'`, `'blog'`, or `'gmt'`.
`'server'` uses the server's internal timezone.
`'blog'` uses the `post_date` field, which proxies to the timezone set for the site.
`'gmt'` uses the `post_date_gmt` field.
Default `'server'`. Default: `'server'`
`$post_type` string Optional The post type to check. Default `'any'`. Default: `'any'`
string The timestamp in 'Y-m-d H:i:s' format, or false on failure.
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function get_lastpostmodified( $timezone = 'server', $post_type = 'any' ) {
/**
* Pre-filter the return value of get_lastpostmodified() before the query is run.
*
* @since 4.4.0
*
* @param string|false $lastpostmodified The most recent time that a post was modified,
* in 'Y-m-d H:i:s' format, or false. Returning anything
* other than false will short-circuit the function.
* @param string $timezone Location to use for getting the post modified date.
* See get_lastpostdate() for accepted `$timezone` values.
* @param string $post_type The post type to check.
*/
$lastpostmodified = apply_filters( 'pre_get_lastpostmodified', false, $timezone, $post_type );
if ( false !== $lastpostmodified ) {
return $lastpostmodified;
}
$lastpostmodified = _get_last_post_time( $timezone, 'modified', $post_type );
$lastpostdate = get_lastpostdate( $timezone, $post_type );
if ( $lastpostdate > $lastpostmodified ) {
$lastpostmodified = $lastpostdate;
}
/**
* Filters the most recent time that a post on the site was modified.
*
* @since 2.3.0
* @since 5.5.0 Added the `$post_type` parameter.
*
* @param string|false $lastpostmodified The most recent time that a post was modified,
* in 'Y-m-d H:i:s' format. False on failure.
* @param string $timezone Location to use for getting the post modified date.
* See get_lastpostdate() for accepted `$timezone` values.
* @param string $post_type The post type to check.
*/
return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone, $post_type );
}
```
[apply\_filters( 'get\_lastpostmodified', string|false $lastpostmodified, string $timezone, string $post\_type )](../hooks/get_lastpostmodified)
Filters the most recent time that a post on the site was modified.
[apply\_filters( 'pre\_get\_lastpostmodified', string|false $lastpostmodified, string $timezone, string $post\_type )](../hooks/pre_get_lastpostmodified)
Pre-filter the return value of [get\_lastpostmodified()](get_lastpostmodified) before the query is run.
| Uses | Description |
| --- | --- |
| [get\_lastpostdate()](get_lastpostdate) wp-includes/post.php | Retrieves the most recent time that a post on the site was published. |
| [\_get\_last\_post\_time()](_get_last_post_time) wp-includes/post.php | Gets the timestamp of the last time any post was modified or published. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [get\_feed\_build\_date()](get_feed_build_date) wp-includes/feed.php | Gets the UTC time of the most recently modified post from [WP\_Query](../classes/wp_query). |
| [WP::send\_headers()](../classes/wp/send_headers) wp-includes/class-wp.php | Sends additional HTTP headers for caching, content type, etc. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | The `$post_type` argument was added. |
| [1.2.0](https://developer.wordpress.org/reference/since/1.2.0/) | Introduced. |
wordpress update_sitemeta_cache( array $site_ids ): array|false update\_sitemeta\_cache( array $site\_ids ): array|false
========================================================
Updates metadata cache for list of site IDs.
Performs SQL query to retrieve all metadata for the sites matching `$site_ids` and stores them in the cache.
Subsequent calls to `get_site_meta()` will not need to query the database.
`$site_ids` array Required List of site IDs. array|false An array of metadata on success, false if there is nothing to update.
File: `wp-includes/ms-site.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-site.php/)
```
function update_sitemeta_cache( $site_ids ) {
// Ensure this filter is hooked in even if the function is called early.
if ( ! has_filter( 'update_blog_metadata_cache', 'wp_check_site_meta_support_prefilter' ) ) {
add_filter( 'update_blog_metadata_cache', 'wp_check_site_meta_support_prefilter' );
}
return update_meta_cache( 'blog', $site_ids );
}
```
| Uses | Description |
| --- | --- |
| [has\_filter()](has_filter) wp-includes/plugin.php | Checks if any filter has been registered for a hook. |
| [update\_meta\_cache()](update_meta_cache) wp-includes/meta.php | Updates the metadata cache for the specified objects. |
| [add\_filter()](add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Used By | Description |
| --- | --- |
| [update\_site\_cache()](update_site_cache) wp-includes/ms-site.php | Updates sites in cache. |
| Version | Description |
| --- | --- |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | Introduced. |
wordpress get_comment_class( string|string[] $css_class = '', int|WP_Comment $comment_id = null, int|WP_Post $post = null ): string[] get\_comment\_class( string|string[] $css\_class = '', int|WP\_Comment $comment\_id = null, int|WP\_Post $post = null ): string[]
=================================================================================================================================
Returns the classes for the comment div as an array.
`$css_class` string|string[] Optional One or more classes to add to the class list. Default: `''`
`$comment_id` int|[WP\_Comment](../classes/wp_comment) Optional Comment ID or [WP\_Comment](../classes/wp_comment) object. Default current comment. Default: `null`
`$post` int|[WP\_Post](../classes/wp_post) Optional Post ID or [WP\_Post](../classes/wp_post) object. Default current post. Default: `null`
string[] An array of classes.
File: `wp-includes/comment-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/comment-template.php/)
```
function get_comment_class( $css_class = '', $comment_id = null, $post = null ) {
global $comment_alt, $comment_depth, $comment_thread_alt;
$classes = array();
$comment = get_comment( $comment_id );
if ( ! $comment ) {
return $classes;
}
// Get the comment type (comment, trackback).
$classes[] = ( empty( $comment->comment_type ) ) ? 'comment' : $comment->comment_type;
// Add classes for comment authors that are registered users.
$user = $comment->user_id ? get_userdata( $comment->user_id ) : false;
if ( $user ) {
$classes[] = 'byuser';
$classes[] = 'comment-author-' . sanitize_html_class( $user->user_nicename, $comment->user_id );
// For comment authors who are the author of the post.
$_post = get_post( $post );
if ( $_post ) {
if ( $comment->user_id === $_post->post_author ) {
$classes[] = 'bypostauthor';
}
}
}
if ( empty( $comment_alt ) ) {
$comment_alt = 0;
}
if ( empty( $comment_depth ) ) {
$comment_depth = 1;
}
if ( empty( $comment_thread_alt ) ) {
$comment_thread_alt = 0;
}
if ( $comment_alt % 2 ) {
$classes[] = 'odd';
$classes[] = 'alt';
} else {
$classes[] = 'even';
}
$comment_alt++;
// Alt for top-level comments.
if ( 1 == $comment_depth ) {
if ( $comment_thread_alt % 2 ) {
$classes[] = 'thread-odd';
$classes[] = 'thread-alt';
} else {
$classes[] = 'thread-even';
}
$comment_thread_alt++;
}
$classes[] = "depth-$comment_depth";
if ( ! empty( $css_class ) ) {
if ( ! is_array( $css_class ) ) {
$css_class = preg_split( '#\s+#', $css_class );
}
$classes = array_merge( $classes, $css_class );
}
$classes = array_map( 'esc_attr', $classes );
/**
* Filters the returned CSS classes for the current comment.
*
* @since 2.7.0
*
* @param string[] $classes An array of comment classes.
* @param string[] $css_class An array of additional classes added to the list.
* @param string $comment_id The comment ID as a numeric string.
* @param WP_Comment $comment The comment object.
* @param int|WP_Post $post The post ID or WP_Post object.
*/
return apply_filters( 'comment_class', $classes, $css_class, $comment->comment_ID, $comment, $post );
}
```
[apply\_filters( 'comment\_class', string[] $classes, string[] $css\_class, string $comment\_id, WP\_Comment $comment, int|WP\_Post $post )](../hooks/comment_class)
Filters the returned CSS classes for the current comment.
| Uses | Description |
| --- | --- |
| [sanitize\_html\_class()](sanitize_html_class) wp-includes/formatting.php | Sanitizes an HTML classname to ensure it only contains valid characters. |
| [get\_userdata()](get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [get\_comment()](get_comment) wp-includes/comment.php | Retrieves comment data given a comment ID or comment object. |
| Used By | Description |
| --- | --- |
| [WP\_Comments\_List\_Table::single\_row()](../classes/wp_comments_list_table/single_row) wp-admin/includes/class-wp-comments-list-table.php | |
| [comment\_class()](comment_class) wp-includes/comment-template.php | Generates semantic classes for each comment element. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Added the ability for `$comment_id` to also accept a [WP\_Comment](../classes/wp_comment) object. |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
| programming_docs |
wordpress wp_cache_reset() wp\_cache\_reset()
==================
This function has been deprecated. Use [WP\_Object\_Cache::reset()](../classes/wp_object_cache/reset) instead.
Resets internal cache keys and structures.
If the cache back end uses global blog or site IDs as part of its cache keys, this function instructs the back end to reset those keys and perform any cleanup since blog or site IDs have changed since cache init.
This function is deprecated. Use [wp\_cache\_switch\_to\_blog()](wp_cache_switch_to_blog) instead of this function when preparing the cache for a blog switch. For clearing the cache during unit tests, consider using [wp\_cache\_init()](wp_cache_init) . [wp\_cache\_init()](wp_cache_init) is not recommended outside of unit tests as the performance penalty for using it is high.
* [WP\_Object\_Cache::reset()](../classes/wp_object_cache/reset)
File: `wp-includes/cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/cache.php/)
```
function wp_cache_reset() {
_deprecated_function( __FUNCTION__, '3.5.0', 'wp_cache_switch_to_blog()' );
global $wp_object_cache;
$wp_object_cache->reset();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Object\_Cache::reset()](../classes/wp_object_cache/reset) wp-includes/class-wp-object-cache.php | Resets cache keys. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Use [wp\_cache\_switch\_to\_blog()](wp_cache_switch_to_blog) |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress single_term_title( string $prefix = '', bool $display = true ): string|void single\_term\_title( string $prefix = '', bool $display = true ): string|void
=============================================================================
Displays or retrieves page title for taxonomy term archive.
Useful for taxonomy term template files for displaying the taxonomy term page title.
The prefix does not automatically place a space between the prefix, so if there should be a space, the parameter value will need to have it at the end.
`$prefix` string Optional What to display before the title. Default: `''`
`$display` bool Optional Whether to display or retrieve title. Default: `true`
string|void Title when retrieving.
File: `wp-includes/general-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/general-template.php/)
```
function single_term_title( $prefix = '', $display = true ) {
$term = get_queried_object();
if ( ! $term ) {
return;
}
if ( is_category() ) {
/**
* Filters the category archive page title.
*
* @since 2.0.10
*
* @param string $term_name Category name for archive being displayed.
*/
$term_name = apply_filters( 'single_cat_title', $term->name );
} elseif ( is_tag() ) {
/**
* Filters the tag archive page title.
*
* @since 2.3.0
*
* @param string $term_name Tag name for archive being displayed.
*/
$term_name = apply_filters( 'single_tag_title', $term->name );
} elseif ( is_tax() ) {
/**
* Filters the custom taxonomy archive page title.
*
* @since 3.1.0
*
* @param string $term_name Term name for archive being displayed.
*/
$term_name = apply_filters( 'single_term_title', $term->name );
} else {
return;
}
if ( empty( $term_name ) ) {
return;
}
if ( $display ) {
echo $prefix . $term_name;
} else {
return $prefix . $term_name;
}
}
```
[apply\_filters( 'single\_cat\_title', string $term\_name )](../hooks/single_cat_title)
Filters the category archive page title.
[apply\_filters( 'single\_tag\_title', string $term\_name )](../hooks/single_tag_title)
Filters the tag archive page title.
[apply\_filters( 'single\_term\_title', string $term\_name )](../hooks/single_term_title)
Filters the custom taxonomy archive page title.
| Uses | Description |
| --- | --- |
| [is\_category()](is_category) wp-includes/query.php | Determines whether the query is for an existing category archive page. |
| [is\_tag()](is_tag) wp-includes/query.php | Determines whether the query is for an existing tag archive page. |
| [is\_tax()](is_tax) wp-includes/query.php | Determines whether the query is for an existing custom taxonomy archive page. |
| [get\_queried\_object()](get_queried_object) wp-includes/query.php | Retrieves the currently queried object. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_get\_document\_title()](wp_get_document_title) wp-includes/general-template.php | Returns document title for the current page. |
| [get\_the\_archive\_title()](get_the_archive_title) wp-includes/general-template.php | Retrieves the archive title based on the queried object. |
| [wp\_title()](wp_title) wp-includes/general-template.php | Displays or retrieves page title for all areas of blog. |
| [single\_cat\_title()](single_cat_title) wp-includes/general-template.php | Displays or retrieves page title for category archive. |
| [single\_tag\_title()](single_tag_title) wp-includes/general-template.php | Displays or retrieves page title for tag post archive. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress do_undismiss_core_update() do\_undismiss\_core\_update()
=============================
Undismiss a core update.
File: `wp-admin/update-core.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/update-core.php/)
```
function do_undismiss_core_update() {
$version = isset( $_POST['version'] ) ? $_POST['version'] : false;
$locale = isset( $_POST['locale'] ) ? $_POST['locale'] : 'en_US';
$update = find_core_update( $version, $locale );
if ( ! $update ) {
return;
}
undismiss_core_update( $version, $locale );
wp_redirect( wp_nonce_url( 'update-core.php?action=upgrade-core', 'upgrade-core' ) );
exit;
}
```
| Uses | Description |
| --- | --- |
| [find\_core\_update()](find_core_update) wp-admin/includes/update.php | Finds the available update for WordPress core. |
| [undismiss\_core\_update()](undismiss_core_update) wp-admin/includes/update.php | Undismisses core update. |
| [wp\_redirect()](wp_redirect) wp-includes/pluggable.php | Redirects to another page. |
| [wp\_nonce\_url()](wp_nonce_url) wp-includes/functions.php | Retrieves URL with nonce added to URL query. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress add_custom_image_header( callable $wp_head_callback, callable $admin_head_callback, callable $admin_preview_callback = '' ) add\_custom\_image\_header( callable $wp\_head\_callback, callable $admin\_head\_callback, callable $admin\_preview\_callback = '' )
====================================================================================================================================
This function has been deprecated. Use [add\_theme\_support()](add_theme_support) instead.
Add callbacks for image header display.
* [add\_theme\_support()](add_theme_support)
`$wp_head_callback` callable Required Call on the ['wp\_head'](../hooks/wp_head) action. `$admin_head_callback` callable Required Call on custom header administration screen. `$admin_preview_callback` callable Optional Output a custom header image div on the custom header administration screen. Optional. Default: `''`
File: `wp-includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/deprecated.php/)
```
function add_custom_image_header( $wp_head_callback, $admin_head_callback, $admin_preview_callback = '' ) {
_deprecated_function( __FUNCTION__, '3.4.0', 'add_theme_support( \'custom-header\', $args )' );
$args = array(
'wp-head-callback' => $wp_head_callback,
'admin-head-callback' => $admin_head_callback,
);
if ( $admin_preview_callback )
$args['admin-preview-callback'] = $admin_preview_callback;
return add_theme_support( 'custom-header', $args );
}
```
| Uses | Description |
| --- | --- |
| [add\_theme\_support()](add_theme_support) wp-includes/theme.php | Registers theme support for a given feature. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Use [add\_theme\_support()](add_theme_support) |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress wp_get_attachment_url( int $attachment_id ): string|false wp\_get\_attachment\_url( int $attachment\_id ): string|false
=============================================================
Retrieves the URL for an attachment.
`$attachment_id` int Optional Attachment post ID. Defaults to global $post. string|false Attachment URL, otherwise false.
You can change the output of this function through the [wp get attachment url](../hooks/wp_get_attachment_url "Plugin API/Filter Reference") filter.
This function will not URL encode the URL. If you have attachments with invalid characters in their name, you should raw URL encode the output of this function in order to have a valid URL.
Sample code that gives you a root-relative URL to your attachment:
```
<pre>$parsed = parse_url( wp_get_attachment_url( $attachment->ID ) );
$url = dirname( $parsed [ 'path' ] ) . '/' . rawurlencode( basename( $parsed[ 'path' ] ) );</pre>
<pre>
```
If you want a URI for the [attachment page](https://codex.wordpress.org/Templates_Hierarchy#Attachment_display "Templates Hierarchy"), not the attachment file itself, you can use [get\_attachment\_link](get_attachment_link "Function Reference/get attachment link").
Also refer: [wp\_insert\_attachment](wp_insert_attachment "Function Reference/wp insert attachment"), [wp\_upload\_dir](wp_upload_dir "Function Reference/wp upload dir"), [wp\_get\_attachment\_image\_src](wp_get_attachment_image_src "Function Reference/wp get attachment image src")
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function wp_get_attachment_url( $attachment_id = 0 ) {
global $pagenow;
$attachment_id = (int) $attachment_id;
$post = get_post( $attachment_id );
if ( ! $post ) {
return false;
}
if ( 'attachment' !== $post->post_type ) {
return false;
}
$url = '';
// Get attached file.
$file = get_post_meta( $post->ID, '_wp_attached_file', true );
if ( $file ) {
// Get upload directory.
$uploads = wp_get_upload_dir();
if ( $uploads && false === $uploads['error'] ) {
// Check that the upload base exists in the file location.
if ( 0 === strpos( $file, $uploads['basedir'] ) ) {
// Replace file location with url location.
$url = str_replace( $uploads['basedir'], $uploads['baseurl'], $file );
} elseif ( false !== strpos( $file, 'wp-content/uploads' ) ) {
// Get the directory name relative to the basedir (back compat for pre-2.7 uploads).
$url = trailingslashit( $uploads['baseurl'] . '/' . _wp_get_attachment_relative_path( $file ) ) . wp_basename( $file );
} else {
// It's a newly-uploaded file, therefore $file is relative to the basedir.
$url = $uploads['baseurl'] . "/$file";
}
}
}
/*
* If any of the above options failed, Fallback on the GUID as used pre-2.7,
* not recommended to rely upon this.
*/
if ( ! $url ) {
$url = get_the_guid( $post->ID );
}
// On SSL front end, URLs should be HTTPS.
if ( is_ssl() && ! is_admin() && 'wp-login.php' !== $pagenow ) {
$url = set_url_scheme( $url );
}
/**
* Filters the attachment URL.
*
* @since 2.1.0
*
* @param string $url URL for the given attachment.
* @param int $attachment_id Attachment post ID.
*/
$url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
if ( ! $url ) {
return false;
}
return $url;
}
```
[apply\_filters( 'wp\_get\_attachment\_url', string $url, int $attachment\_id )](../hooks/wp_get_attachment_url)
Filters the attachment URL.
| Uses | Description |
| --- | --- |
| [wp\_get\_upload\_dir()](wp_get_upload_dir) wp-includes/functions.php | Retrieves uploads directory information. |
| [\_wp\_get\_attachment\_relative\_path()](_wp_get_attachment_relative_path) wp-includes/media.php | Gets the attachment path relative to the upload directory. |
| [is\_ssl()](is_ssl) wp-includes/load.php | Determines if SSL is used. |
| [set\_url\_scheme()](set_url_scheme) wp-includes/link-template.php | Sets the scheme for a URL. |
| [get\_the\_guid()](get_the_guid) wp-includes/post-template.php | Retrieves the Post Global Unique Identifier (guid). |
| [wp\_basename()](wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| [trailingslashit()](trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| [is\_admin()](is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post\_meta()](get_post_meta) wp-includes/post.php | Retrieves a post meta field for the given post ID. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [get\_media\_states()](get_media_states) wp-admin/includes/template.php | Retrieves an array of media states from an attachment. |
| [wp\_get\_original\_image\_url()](wp_get_original_image_url) wp-includes/post.php | Retrieves the URL to an original attachment image. |
| [wp\_media\_personal\_data\_exporter()](wp_media_personal_data_exporter) wp-includes/media.php | Finds and exports attachments associated with an email address. |
| [WP\_Widget\_Media\_Audio::render\_media()](../classes/wp_widget_media_audio/render_media) wp-includes/widgets/class-wp-widget-media-audio.php | Render the media on the frontend. |
| [WP\_Widget\_Media\_Video::render\_media()](../classes/wp_widget_media_video/render_media) wp-includes/widgets/class-wp-widget-media-video.php | Render the media on the frontend. |
| [WP\_Widget\_Media\_Image::render\_media()](../classes/wp_widget_media_image/render_media) wp-includes/widgets/class-wp-widget-media-image.php | Render the media on the frontend. |
| [WP\_Customize\_Manager::import\_theme\_starter\_content()](../classes/wp_customize_manager/import_theme_starter_content) wp-includes/class-wp-customize-manager.php | Imports theme starter content into the customized state. |
| [get\_header\_video\_url()](get_header_video_url) wp-includes/theme.php | Retrieves header video URL for custom header. |
| [WP\_REST\_Attachments\_Controller::prepare\_item\_for\_response()](../classes/wp_rest_attachments_controller/prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Prepares a single attachment output for response. |
| [WP\_Site\_Icon::create\_attachment\_object()](../classes/wp_site_icon/create_attachment_object) wp-admin/includes/class-wp-site-icon.php | Creates an attachment ‘object’. |
| [wp\_ajax\_crop\_image()](wp_ajax_crop_image) wp-admin/includes/ajax-actions.php | Ajax handler for cropping an image. |
| [export\_wp()](export_wp) wp-admin/includes/export.php | Generates the WXR export file for download. |
| [wp\_save\_image()](wp_save_image) wp-admin/includes/image-edit.php | Saves image to post, along with enqueued changes in `$_REQUEST['history']`. |
| [\_load\_image\_to\_edit\_path()](_load_image_to_edit_path) wp-admin/includes/image.php | Retrieves the path or URL of an attachment’s attached file. |
| [edit\_form\_image\_editor()](edit_form_image_editor) wp-admin/includes/media.php | Displays the image and editor in the post editor |
| [attachment\_submitbox\_metadata()](attachment_submitbox_metadata) wp-admin/includes/media.php | Displays non-editable attachment metadata in the publish meta box. |
| [get\_attachment\_fields\_to\_edit()](get_attachment_fields_to_edit) wp-admin/includes/media.php | Retrieves the attachment fields to edit form fields. |
| [media\_sideload\_image()](media_sideload_image) wp-admin/includes/media.php | Downloads an image from the specified URL, saves it as an attachment, and optionally attaches it to a post. |
| [image\_link\_input\_fields()](image_link_input_fields) wp-admin/includes/media.php | Retrieves HTML for the Link URL buttons with the default link type as specified. |
| [WP\_Media\_List\_Table::\_get\_row\_actions()](../classes/wp_media_list_table/_get_row_actions) wp-admin/includes/class-wp-media-list-table.php | |
| [Custom\_Image\_Header::create\_attachment\_object()](../classes/custom_image_header/create_attachment_object) wp-admin/includes/class-custom-image-header.php | Create an attachment ‘object’. |
| [Custom\_Image\_Header::ajax\_header\_crop()](../classes/custom_image_header/ajax_header_crop) wp-admin/includes/class-custom-image-header.php | Gets attachment uploaded by Media Manager, crops it, then saves it as a new object. Returns JSON-encoded object details. |
| [Custom\_Image\_Header::step\_3()](../classes/custom_image_header/step_3) wp-admin/includes/class-custom-image-header.php | Display third step of custom header image page. |
| [\_delete\_attachment\_theme\_mod()](_delete_attachment_theme_mod) wp-includes/theme.php | Checks an attachment being deleted to see if it’s a header or background image. |
| [get\_uploaded\_header\_images()](get_uploaded_header_images) wp-includes/theme.php | Gets the header images uploaded for the active theme. |
| [get\_the\_attachment\_link()](get_the_attachment_link) wp-includes/deprecated.php | Retrieve HTML content of attachment image with link. |
| [get\_attachment\_icon\_src()](get_attachment_icon_src) wp-includes/deprecated.php | Retrieve icon URL and Path. |
| [wp\_get\_attachment\_link()](wp_get_attachment_link) wp-includes/post-template.php | Retrieves an attachment page link using an image or icon, if possible. |
| [prepend\_attachment()](prepend_attachment) wp-includes/post-template.php | Wraps attachment in paragraph tag before content. |
| [get\_post\_galleries()](get_post_galleries) wp-includes/media.php | Retrieves galleries from the passed post’s content. |
| [wp\_prepare\_attachment\_for\_js()](wp_prepare_attachment_for_js) wp-includes/media.php | Prepares an attachment post object for JS, where it is expected to be JSON-encoded and fit into an Attachment model. |
| [wp\_video\_shortcode()](wp_video_shortcode) wp-includes/media.php | Builds the Video shortcode output. |
| [wp\_playlist\_shortcode()](wp_playlist_shortcode) wp-includes/media.php | Builds the Playlist shortcode output. |
| [wp\_audio\_shortcode()](wp_audio_shortcode) wp-includes/media.php | Builds the Audio shortcode output. |
| [image\_get\_intermediate\_size()](image_get_intermediate_size) wp-includes/media.php | Retrieves the image’s intermediate size (resized) path, width, and height. |
| [image\_downsize()](image_downsize) wp-includes/media.php | Scales an image to fit a particular size (such as ‘thumb’ or ‘medium’). |
| [wp\_xmlrpc\_server::\_prepare\_media\_item()](../classes/wp_xmlrpc_server/_prepare_media_item) wp-includes/class-wp-xmlrpc-server.php | Prepares media item data for return in an XML-RPC object. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
| programming_docs |
wordpress add_meta( int $post_ID ): int|bool add\_meta( int $post\_ID ): int|bool
====================================
Adds post meta data defined in the `$_POST` superglobal for a post with given ID.
`$post_ID` int Required int|bool
* The information used is POSTed from the “Custom Fields” form on the Edit Post Administration screen.
* Data used for the added metadata is taken from `$_POST['metakeyselect']`, `$_POST['metakeyinput']`, `$_POST['metavalue']`. Either the select or input fields are used for the meta key. If both are present, input field is used.
File: `wp-admin/includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/post.php/)
```
function add_meta( $post_ID ) {
$post_ID = (int) $post_ID;
$metakeyselect = isset( $_POST['metakeyselect'] ) ? wp_unslash( trim( $_POST['metakeyselect'] ) ) : '';
$metakeyinput = isset( $_POST['metakeyinput'] ) ? wp_unslash( trim( $_POST['metakeyinput'] ) ) : '';
$metavalue = isset( $_POST['metavalue'] ) ? $_POST['metavalue'] : '';
if ( is_string( $metavalue ) ) {
$metavalue = trim( $metavalue );
}
if ( ( ( '#NONE#' !== $metakeyselect ) && ! empty( $metakeyselect ) ) || ! empty( $metakeyinput ) ) {
/*
* We have a key/value pair. If both the select and the input
* for the key have data, the input takes precedence.
*/
if ( '#NONE#' !== $metakeyselect ) {
$metakey = $metakeyselect;
}
if ( $metakeyinput ) {
$metakey = $metakeyinput; // Default.
}
if ( is_protected_meta( $metakey, 'post' ) || ! current_user_can( 'add_post_meta', $post_ID, $metakey ) ) {
return false;
}
$metakey = wp_slash( $metakey );
return add_post_meta( $post_ID, $metakey, $metavalue );
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [add\_post\_meta()](add_post_meta) wp-includes/post.php | Adds a meta field to the given post. |
| [is\_protected\_meta()](is_protected_meta) wp-includes/meta.php | Determines whether a meta key is considered protected. |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [wp\_unslash()](wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [wp\_slash()](wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| Used By | Description |
| --- | --- |
| [wp\_write\_post()](wp_write_post) wp-admin/includes/post.php | Creates a new post from the “Write Post” form using `$_POST` information. |
| [edit\_post()](edit_post) wp-admin/includes/post.php | Updates an existing post with values provided in `$_POST`. |
| [wp\_ajax\_add\_meta()](wp_ajax_add_meta) wp-admin/includes/ajax-actions.php | Ajax handler for adding meta. |
| Version | Description |
| --- | --- |
| [1.2.0](https://developer.wordpress.org/reference/since/1.2.0/) | Introduced. |
wordpress parent_dropdown( int $default_page, int $parent_page, int $level, int|WP_Post $post = null ): void|false parent\_dropdown( int $default\_page, int $parent\_page, int $level, int|WP\_Post $post = null ): void|false
============================================================================================================
Prints out option HTML elements for the page parents drop-down.
`$default_page` int Optional The default page ID to be pre-selected. Default 0. `$parent_page` int Optional The parent page ID. Default 0. `$level` int Optional Page depth level. Default 0. `$post` int|[WP\_Post](../classes/wp_post) Optional Post ID or [WP\_Post](../classes/wp_post) object. Default: `null`
void|false Void on success, false if the page has no children.
File: `wp-admin/includes/template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/template.php/)
```
function parent_dropdown( $default_page = 0, $parent_page = 0, $level = 0, $post = null ) {
global $wpdb;
$post = get_post( $post );
$items = $wpdb->get_results(
$wpdb->prepare(
"SELECT ID, post_parent, post_title
FROM $wpdb->posts
WHERE post_parent = %d AND post_type = 'page'
ORDER BY menu_order",
$parent_page
)
);
if ( $items ) {
foreach ( $items as $item ) {
// A page cannot be its own parent.
if ( $post && $post->ID && (int) $item->ID === $post->ID ) {
continue;
}
$pad = str_repeat( ' ', $level * 3 );
$selected = selected( $default_page, $item->ID, false );
echo "\n\t<option class='level-$level' value='$item->ID' $selected>$pad " . esc_html( $item->post_title ) . '</option>';
parent_dropdown( $default_page, $item->ID, $level + 1 );
}
} else {
return false;
}
}
```
| Uses | Description |
| --- | --- |
| [parent\_dropdown()](parent_dropdown) wp-admin/includes/template.php | Prints out option HTML elements for the page parents drop-down. |
| [selected()](selected) wp-includes/general-template.php | Outputs the HTML selected attribute. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [get\_post()](get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wpdb::get\_results()](../classes/wpdb/get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| [wpdb::prepare()](../classes/wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [parent\_dropdown()](parent_dropdown) wp-admin/includes/template.php | Prints out option HTML elements for the page parents drop-down. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | `$post` argument was added. |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress map_deep( mixed $value, callable $callback ): mixed map\_deep( mixed $value, callable $callback ): mixed
====================================================
Maps a function to all non-iterable elements of an array or an object.
This is similar to `array_walk_recursive()` but acts upon objects too.
`$value` mixed Required The array, object, or scalar. `$callback` callable Required The function to map onto $value. mixed The value with the callback applied to all non-arrays and non-objects inside it.
File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function map_deep( $value, $callback ) {
if ( is_array( $value ) ) {
foreach ( $value as $index => $item ) {
$value[ $index ] = map_deep( $item, $callback );
}
} elseif ( is_object( $value ) ) {
$object_vars = get_object_vars( $value );
foreach ( $object_vars as $property_name => $property_value ) {
$value->$property_name = map_deep( $property_value, $callback );
}
} else {
$value = call_user_func( $callback, $value );
}
return $value;
}
```
| Uses | Description |
| --- | --- |
| [map\_deep()](map_deep) wp-includes/formatting.php | Maps a function to all non-iterable elements of an array or an object. |
| Used By | Description |
| --- | --- |
| [wp\_slash\_strings\_only()](wp_slash_strings_only) wp-includes/deprecated.php | Adds slashes to only string values in an array of values. |
| [wp\_kses\_post\_deep()](wp_kses_post_deep) wp-includes/kses.php | Navigates through an array, object, or scalar, and sanitizes content for allowed HTML tags for post content. |
| [map\_deep()](map_deep) wp-includes/formatting.php | Maps a function to all non-iterable elements of an array or an object. |
| [urldecode\_deep()](urldecode_deep) wp-includes/formatting.php | Navigates through an array, object, or scalar, and decodes URL-encoded values |
| [stripslashes\_deep()](stripslashes_deep) wp-includes/formatting.php | Navigates through an array, object, or scalar, and removes slashes from the values. |
| [urlencode\_deep()](urlencode_deep) wp-includes/formatting.php | Navigates through an array, object, or scalar, and encodes the values to be used in a URL. |
| [rawurlencode\_deep()](rawurlencode_deep) wp-includes/formatting.php | Navigates through an array, object, or scalar, and raw-encodes the values to be used in a URL. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress wp_ajax_health_check_dotorg_communication() wp\_ajax\_health\_check\_dotorg\_communication()
================================================
This function has been deprecated. Use [WP\_REST\_Site\_Health\_Controller::test\_dotorg\_communication()](../classes/wp_rest_site_health_controller/test_dotorg_communication) instead.
Ajax handler for site health checks on server communication.
* [WP\_REST\_Site\_Health\_Controller::test\_dotorg\_communication()](../classes/wp_rest_site_health_controller/test_dotorg_communication)
File: `wp-admin/includes/ajax-actions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/ajax-actions.php/)
```
function wp_ajax_health_check_dotorg_communication() {
_doing_it_wrong(
'wp_ajax_health_check_dotorg_communication',
sprintf(
// translators: 1: The Site Health action that is no longer used by core. 2: The new function that replaces it.
__( 'The Site Health check for %1$s has been replaced with %2$s.' ),
'wp_ajax_health_check_dotorg_communication',
'WP_REST_Site_Health_Controller::test_dotorg_communication'
),
'5.6.0'
);
check_ajax_referer( 'health-check-site-status' );
if ( ! current_user_can( 'view_site_health_checks' ) ) {
wp_send_json_error();
}
if ( ! class_exists( 'WP_Site_Health' ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php';
}
$site_health = WP_Site_Health::get_instance();
wp_send_json_success( $site_health->get_test_dotorg_communication() );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::get\_instance()](../classes/wp_site_health/get_instance) wp-admin/includes/class-wp-site-health.php | Returns an instance of the [WP\_Site\_Health](../classes/wp_site_health) class, or create one if none exist yet. |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [check\_ajax\_referer()](check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [\_doing\_it\_wrong()](_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| [wp\_send\_json\_error()](wp_send_json_error) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating failure. |
| [wp\_send\_json\_success()](wp_send_json_success) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating success. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Use [WP\_REST\_Site\_Health\_Controller::test\_dotorg\_communication()](../classes/wp_rest_site_health_controller/test_dotorg_communication) |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress admin_color_scheme_picker( int $user_id ) admin\_color\_scheme\_picker( int $user\_id )
=============================================
Displays the default admin color scheme picker (Used in user-edit.php).
`$user_id` int Required User ID. File: `wp-admin/includes/misc.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/misc.php/)
```
function admin_color_scheme_picker( $user_id ) {
global $_wp_admin_css_colors;
ksort( $_wp_admin_css_colors );
if ( isset( $_wp_admin_css_colors['fresh'] ) ) {
// Set Default ('fresh') and Light should go first.
$_wp_admin_css_colors = array_filter(
array_merge(
array(
'fresh' => '',
'light' => '',
'modern' => '',
),
$_wp_admin_css_colors
)
);
}
$current_color = get_user_option( 'admin_color', $user_id );
if ( empty( $current_color ) || ! isset( $_wp_admin_css_colors[ $current_color ] ) ) {
$current_color = 'fresh';
}
?>
<fieldset id="color-picker" class="scheme-list">
<legend class="screen-reader-text"><span><?php _e( 'Admin Color Scheme' ); ?></span></legend>
<?php
wp_nonce_field( 'save-color-scheme', 'color-nonce', false );
foreach ( $_wp_admin_css_colors as $color => $color_info ) :
?>
<div class="color-option <?php echo ( $color === $current_color ) ? 'selected' : ''; ?>">
<input name="admin_color" id="admin_color_<?php echo esc_attr( $color ); ?>" type="radio" value="<?php echo esc_attr( $color ); ?>" class="tog" <?php checked( $color, $current_color ); ?> />
<input type="hidden" class="css_url" value="<?php echo esc_url( $color_info->url ); ?>" />
<input type="hidden" class="icon_colors" value="<?php echo esc_attr( wp_json_encode( array( 'icons' => $color_info->icon_colors ) ) ); ?>" />
<label for="admin_color_<?php echo esc_attr( $color ); ?>"><?php echo esc_html( $color_info->name ); ?></label>
<table class="color-palette">
<tr>
<?php
foreach ( $color_info->colors as $html_color ) {
?>
<td style="background-color: <?php echo esc_attr( $html_color ); ?>"> </td>
<?php
}
?>
</tr>
</table>
</div>
<?php
endforeach;
?>
</fieldset>
<?php
}
```
| Uses | Description |
| --- | --- |
| [wp\_nonce\_field()](wp_nonce_field) wp-includes/functions.php | Retrieves or display nonce hidden field for forms. |
| [checked()](checked) wp-includes/general-template.php | Outputs the HTML checked attribute. |
| [get\_user\_option()](get_user_option) wp-includes/user.php | Retrieves user option that can be either per Site or per Network. |
| [wp\_json\_encode()](wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [\_e()](_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress wp_default_packages_vendor( WP_Scripts $scripts ) wp\_default\_packages\_vendor( WP\_Scripts $scripts )
=====================================================
Registers all the WordPress vendor scripts that are in the standardized `js/dist/vendor/` location.
For the order of `$scripts->add` see `wp_default_scripts`.
`$scripts` [WP\_Scripts](../classes/wp_scripts) Required [WP\_Scripts](../classes/wp_scripts) object. File: `wp-includes/script-loader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/script-loader.php/)
```
function wp_default_packages_vendor( $scripts ) {
global $wp_locale;
$suffix = wp_scripts_get_suffix();
$vendor_scripts = array(
'react' => array( 'wp-polyfill' ),
'react-dom' => array( 'react' ),
'regenerator-runtime',
'moment',
'lodash',
'wp-polyfill-fetch',
'wp-polyfill-formdata',
'wp-polyfill-node-contains',
'wp-polyfill-url',
'wp-polyfill-dom-rect',
'wp-polyfill-element-closest',
'wp-polyfill-object-fit',
'wp-polyfill' => array( 'regenerator-runtime' ),
);
$vendor_scripts_versions = array(
'react' => '17.0.1',
'react-dom' => '17.0.1',
'regenerator-runtime' => '0.13.9',
'moment' => '2.29.4',
'lodash' => '4.17.19',
'wp-polyfill-fetch' => '3.6.2',
'wp-polyfill-formdata' => '4.0.10',
'wp-polyfill-node-contains' => '4.4.0',
'wp-polyfill-url' => '3.6.4',
'wp-polyfill-dom-rect' => '4.4.0',
'wp-polyfill-element-closest' => '2.0.2',
'wp-polyfill-object-fit' => '2.3.5',
'wp-polyfill' => '3.15.0',
);
foreach ( $vendor_scripts as $handle => $dependencies ) {
if ( is_string( $dependencies ) ) {
$handle = $dependencies;
$dependencies = array();
}
$path = "/wp-includes/js/dist/vendor/$handle$suffix.js";
$version = $vendor_scripts_versions[ $handle ];
$scripts->add( $handle, $path, $dependencies, $version, 1 );
}
did_action( 'init' ) && $scripts->add_inline_script( 'lodash', 'window.lodash = _.noConflict();' );
did_action( 'init' ) && $scripts->add_inline_script(
'moment',
sprintf(
"moment.updateLocale( '%s', %s );",
get_user_locale(),
wp_json_encode(
array(
'months' => array_values( $wp_locale->month ),
'monthsShort' => array_values( $wp_locale->month_abbrev ),
'weekdays' => array_values( $wp_locale->weekday ),
'weekdaysShort' => array_values( $wp_locale->weekday_abbrev ),
'week' => array(
'dow' => (int) get_option( 'start_of_week', 0 ),
),
'longDateFormat' => array(
'LT' => get_option( 'time_format', __( 'g:i a' ) ),
'LTS' => null,
'L' => null,
'LL' => get_option( 'date_format', __( 'F j, Y' ) ),
'LLL' => __( 'F j, Y g:i a' ),
'LLLL' => null,
),
)
)
),
'after'
);
}
```
| Uses | Description |
| --- | --- |
| [wp\_scripts\_get\_suffix()](wp_scripts_get_suffix) wp-includes/script-loader.php | Returns the suffix that can be used for the scripts. |
| [get\_user\_locale()](get_user_locale) wp-includes/l10n.php | Retrieves the locale of a user. |
| [did\_action()](did_action) wp-includes/plugin.php | Retrieves the number of times an action has been fired during the current request. |
| [wp\_json\_encode()](wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [wp\_default\_packages()](wp_default_packages) wp-includes/script-loader.php | Registers all the WordPress packages scripts. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress get_most_recent_post_of_user( int $user_id ): array get\_most\_recent\_post\_of\_user( int $user\_id ): array
=========================================================
Gets a user’s most recent post.
Walks through each of a user’s blogs to find the post with the most recent post\_date\_gmt.
`$user_id` int Required array Contains the blog\_id, post\_id, post\_date\_gmt, and post\_gmt\_ts
File: `wp-includes/ms-functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-functions.php/)
```
function get_most_recent_post_of_user( $user_id ) {
global $wpdb;
$user_blogs = get_blogs_of_user( (int) $user_id );
$most_recent_post = array();
// Walk through each blog and get the most recent post
// published by $user_id.
foreach ( (array) $user_blogs as $blog ) {
$prefix = $wpdb->get_blog_prefix( $blog->userblog_id );
$recent_post = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_date_gmt FROM {$prefix}posts WHERE post_author = %d AND post_type = 'post' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1", $user_id ), ARRAY_A );
// Make sure we found a post.
if ( isset( $recent_post['ID'] ) ) {
$post_gmt_ts = strtotime( $recent_post['post_date_gmt'] );
/*
* If this is the first post checked
* or if this post is newer than the current recent post,
* make it the new most recent post.
*/
if ( ! isset( $most_recent_post['post_gmt_ts'] ) || ( $post_gmt_ts > $most_recent_post['post_gmt_ts'] ) ) {
$most_recent_post = array(
'blog_id' => $blog->userblog_id,
'post_id' => $recent_post['ID'],
'post_date_gmt' => $recent_post['post_date_gmt'],
'post_gmt_ts' => $post_gmt_ts,
);
}
}
}
return $most_recent_post;
}
```
| Uses | Description |
| --- | --- |
| [get\_blogs\_of\_user()](get_blogs_of_user) wp-includes/user.php | Gets the sites a user belongs to. |
| [wpdb::get\_row()](../classes/wpdb/get_row) wp-includes/class-wpdb.php | Retrieves one row from the database. |
| [wpdb::get\_blog\_prefix()](../classes/wpdb/get_blog_prefix) wp-includes/class-wpdb.php | Gets blog prefix. |
| [wpdb::prepare()](../classes/wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Version | Description |
| --- | --- |
| [MU (3.0.0)](https://developer.wordpress.org/reference/since/mu.3.0.0/) | Introduced. |
| programming_docs |
wordpress reset_mbstring_encoding() reset\_mbstring\_encoding()
===========================
Resets the mbstring internal encoding to a users previously set encoding.
* [mbstring\_binary\_safe\_encoding()](mbstring_binary_safe_encoding)
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function reset_mbstring_encoding() {
mbstring_binary_safe_encoding( true );
}
```
| Uses | Description |
| --- | --- |
| [mbstring\_binary\_safe\_encoding()](mbstring_binary_safe_encoding) wp-includes/functions.php | Sets the mbstring internal encoding to a binary safe encoding when func\_overload is enabled. |
| Used By | Description |
| --- | --- |
| [verify\_file\_signature()](verify_file_signature) wp-admin/includes/file.php | Verifies the contents of a file against its ED25519 signature. |
| [wpdb::strip\_invalid\_text()](../classes/wpdb/strip_invalid_text) wp-includes/class-wpdb.php | Strips any invalid characters based on value/charset pairs. |
| [WP\_Filesystem\_FTPext::put\_contents()](../classes/wp_filesystem_ftpext/put_contents) wp-admin/includes/class-wp-filesystem-ftpext.php | Writes a string to a file. |
| [WP\_Filesystem\_Direct::put\_contents()](../classes/wp_filesystem_direct/put_contents) wp-admin/includes/class-wp-filesystem-direct.php | Writes a string to a file. |
| [wp\_read\_image\_metadata()](wp_read_image_metadata) wp-admin/includes/image.php | Gets extended image metadata, exif or iptc as available. |
| [WP\_Filesystem\_ftpsockets::dirlist()](../classes/wp_filesystem_ftpsockets/dirlist) wp-admin/includes/class-wp-filesystem-ftpsockets.php | Gets details for files in a directory or a specific file. |
| [WP\_Filesystem\_ftpsockets::get\_contents()](../classes/wp_filesystem_ftpsockets/get_contents) wp-admin/includes/class-wp-filesystem-ftpsockets.php | Reads entire file into a string. |
| [WP\_Filesystem\_ftpsockets::put\_contents()](../classes/wp_filesystem_ftpsockets/put_contents) wp-admin/includes/class-wp-filesystem-ftpsockets.php | Writes a string to a file. |
| [\_unzip\_file\_pclzip()](_unzip_file_pclzip) wp-admin/includes/file.php | Attempts to unzip an archive using the PclZip library. |
| [seems\_utf8()](seems_utf8) wp-includes/formatting.php | Checks to see if a string is utf8 encoded. |
| [utf8\_uri\_encode()](utf8_uri_encode) wp-includes/formatting.php | Encodes the Unicode values to be used in the URI. |
| [WP\_Http::request()](../classes/wp_http/request) wp-includes/class-wp-http.php | Send an HTTP request to a URI. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress wp_get_global_styles_svg_filters(): string wp\_get\_global\_styles\_svg\_filters(): string
===============================================
Returns a string containing the SVGs to be referenced as filters (duotone).
string
File: `wp-includes/global-styles-and-settings.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/global-styles-and-settings.php/)
```
function wp_get_global_styles_svg_filters() {
// Return cached value if it can be used and exists.
// It's cached by theme to make sure that theme switching clears the cache.
$can_use_cached = (
( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) &&
( ! defined( 'SCRIPT_DEBUG' ) || ! SCRIPT_DEBUG ) &&
( ! defined( 'REST_REQUEST' ) || ! REST_REQUEST ) &&
! is_admin()
);
$transient_name = 'global_styles_svg_filters_' . get_stylesheet();
if ( $can_use_cached ) {
$cached = get_transient( $transient_name );
if ( $cached ) {
return $cached;
}
}
$supports_theme_json = WP_Theme_JSON_Resolver::theme_has_support();
$origins = array( 'default', 'theme', 'custom' );
if ( ! $supports_theme_json ) {
$origins = array( 'default' );
}
$tree = WP_Theme_JSON_Resolver::get_merged_data();
$svgs = $tree->get_svg_filters( $origins );
if ( $can_use_cached ) {
// Cache for a minute, same as wp_get_global_stylesheet.
set_transient( $transient_name, $svgs, MINUTE_IN_SECONDS );
}
return $svgs;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme\_JSON\_Resolver::theme\_has\_support()](../classes/wp_theme_json_resolver/theme_has_support) wp-includes/class-wp-theme-json-resolver.php | Determines whether the active theme has a theme.json file. |
| [WP\_Theme\_JSON\_Resolver::get\_merged\_data()](../classes/wp_theme_json_resolver/get_merged_data) wp-includes/class-wp-theme-json-resolver.php | Returns the data merged from multiple origins. |
| [get\_stylesheet()](get_stylesheet) wp-includes/theme.php | Retrieves name of the current stylesheet. |
| [get\_transient()](get_transient) wp-includes/option.php | Retrieves the value of a transient. |
| [set\_transient()](set_transient) wp-includes/option.php | Sets/updates the value of a transient. |
| [is\_admin()](is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| Used By | Description |
| --- | --- |
| [wp\_global\_styles\_render\_svg\_filters()](wp_global_styles_render_svg_filters) wp-includes/script-loader.php | Renders the SVG filters supplied by theme.json. |
| Version | Description |
| --- | --- |
| [5.9.1](https://developer.wordpress.org/reference/since/5.9.1/) | Introduced. |
wordpress post_comment_status_meta_box( WP_Post $post ) post\_comment\_status\_meta\_box( WP\_Post $post )
==================================================
Displays comments status form fields.
`$post` [WP\_Post](../classes/wp_post) Required Current post object. File: `wp-admin/includes/meta-boxes.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/meta-boxes.php/)
```
function post_comment_status_meta_box( $post ) {
?>
<input name="advanced_view" type="hidden" value="1" />
<p class="meta-options">
<label for="comment_status" class="selectit"><input name="comment_status" type="checkbox" id="comment_status" value="open" <?php checked( $post->comment_status, 'open' ); ?> /> <?php _e( 'Allow comments' ); ?></label><br />
<label for="ping_status" class="selectit"><input name="ping_status" type="checkbox" id="ping_status" value="open" <?php checked( $post->ping_status, 'open' ); ?> />
<?php
printf(
/* translators: %s: Documentation URL. */
__( 'Allow <a href="%s">trackbacks and pingbacks</a> on this page' ),
__( 'https://wordpress.org/support/article/introduction-to-blogging/#managing-comments' )
);
?>
</label>
<?php
/**
* Fires at the end of the Discussion meta box on the post editing screen.
*
* @since 3.1.0
*
* @param WP_Post $post WP_Post object for the current post.
*/
do_action( 'post_comment_status_meta_box-options', $post ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
?>
</p>
<?php
}
```
[do\_action( 'post\_comment\_status\_meta\_box-options', WP\_Post $post )](../hooks/post_comment_status_meta_box-options)
Fires at the end of the Discussion meta box on the post editing screen.
| Uses | Description |
| --- | --- |
| [checked()](checked) wp-includes/general-template.php | Outputs the HTML checked attribute. |
| [\_e()](_e) wp-includes/l10n.php | Displays translated text. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress previous_posts( bool $echo = true ): string|void previous\_posts( bool $echo = true ): string|void
=================================================
Displays or retrieves the previous posts page link.
`$echo` bool Optional Whether to echo the link. Default: `true`
string|void The previous posts page link if `$echo = false`.
File: `wp-includes/link-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/link-template.php/)
```
function previous_posts( $echo = true ) {
$output = esc_url( get_previous_posts_page_link() );
if ( $echo ) {
echo $output;
} else {
return $output;
}
}
```
| Uses | Description |
| --- | --- |
| [get\_previous\_posts\_page\_link()](get_previous_posts_page_link) wp-includes/link-template.php | Retrieves the previous posts page link. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| Used By | Description |
| --- | --- |
| [get\_previous\_posts\_link()](get_previous_posts_link) wp-includes/link-template.php | Retrieves the previous posts page link. |
| Version | Description |
| --- | --- |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress network_admin_url( string $path = '', string $scheme = 'admin' ): string network\_admin\_url( string $path = '', string $scheme = 'admin' ): string
==========================================================================
Retrieves the URL to the admin area for the network.
`$path` string Optional path relative to the admin URL. Default: `''`
`$scheme` string Optional The scheme to use. Default is `'admin'`, which obeys [force\_ssl\_admin()](force_ssl_admin) and [is\_ssl()](is_ssl) . `'http'` or `'https'` can be passed to force those schemes. Default: `'admin'`
string Admin URL link with optional path appended.
* The network\_admin\_url template tag retrieves the URL to the [Network Admin](https://wordpress.org/support/article/network-admin/) area for the current site with the appropriate protocol, “https” if [is\_ssl()](is_ssl) and “http” otherwise. If `$scheme` is “http” or “https”, [is\_ssl()](is_ssl) is overridden.
* If the site is not setup as [multisite](https://wordpress.org/support/article/create-a-network/), [admin\_url()](admin_url) will be used instead.
File: `wp-includes/link-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/link-template.php/)
```
function network_admin_url( $path = '', $scheme = 'admin' ) {
if ( ! is_multisite() ) {
return admin_url( $path, $scheme );
}
$url = network_site_url( 'wp-admin/network/', $scheme );
if ( $path && is_string( $path ) ) {
$url .= ltrim( $path, '/' );
}
/**
* Filters the network admin URL.
*
* @since 3.0.0
* @since 5.8.0 The `$scheme` parameter was added.
*
* @param string $url The complete network admin URL including scheme and path.
* @param string $path Path relative to the network admin URL. Blank string if
* no path is specified.
* @param string|null $scheme The scheme to use. Accepts 'http', 'https',
* 'admin', or null. Default is 'admin', which obeys force_ssl_admin() and is_ssl().
*/
return apply_filters( 'network_admin_url', $url, $path, $scheme );
}
```
[apply\_filters( 'network\_admin\_url', string $url, string $path, string|null $scheme )](../hooks/network_admin_url)
Filters the network admin URL.
| Uses | Description |
| --- | --- |
| [network\_site\_url()](network_site_url) wp-includes/link-template.php | Retrieves the site URL for the current network. |
| [is\_multisite()](is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [admin\_url()](admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::get\_test\_plugin\_version()](../classes/wp_site_health/get_test_plugin_version) wp-admin/includes/class-wp-site-health.php | Tests if plugins are outdated, or unnecessary. |
| [WP\_Customize\_Manager::handle\_load\_themes\_request()](../classes/wp_customize_manager/handle_load_themes_request) wp-includes/class-wp-customize-manager.php | Loads themes into the theme browsing/installation UI. |
| [update\_network\_option\_new\_admin\_email()](update_network_option_new_admin_email) wp-includes/ms-functions.php | Sends a confirmation request email when a change of network admin email address is attempted. |
| [get\_site\_screen\_help\_tab\_args()](get_site_screen_help_tab_args) wp-admin/includes/ms.php | Returns the arguments for the help tab on the Edit Site screens. |
| [network\_edit\_site\_nav()](network_edit_site_nav) wp-admin/includes/ms.php | Outputs the HTML for a network’s “Edit Site” tabular interface. |
| [wp\_ajax\_search\_install\_plugins()](wp_ajax_search_install_plugins) wp-admin/includes/ajax-actions.php | Ajax handler for searching plugins to install. |
| [wp\_ajax\_search\_plugins()](wp_ajax_search_plugins) wp-admin/includes/ajax-actions.php | Ajax handler for searching plugins. |
| [wp\_ajax\_install\_theme()](wp_ajax_install_theme) wp-admin/includes/ajax-actions.php | Ajax handler for installing a theme. |
| [wp\_ajax\_install\_plugin()](wp_ajax_install_plugin) wp-admin/includes/ajax-actions.php | Ajax handler for installing a plugin. |
| [WP\_MS\_Sites\_List\_Table::handle\_row\_actions()](../classes/wp_ms_sites_list_table/handle_row_actions) wp-admin/includes/class-wp-ms-sites-list-table.php | Generates and displays row action links. |
| [WP\_MS\_Sites\_List\_Table::column\_blogname()](../classes/wp_ms_sites_list_table/column_blogname) wp-admin/includes/class-wp-ms-sites-list-table.php | Handles the site name column output. |
| [WP\_MS\_Sites\_List\_Table::column\_users()](../classes/wp_ms_sites_list_table/column_users) wp-admin/includes/class-wp-ms-sites-list-table.php | Handles the users column output. |
| [WP\_MS\_Users\_List\_Table::handle\_row\_actions()](../classes/wp_ms_users_list_table/handle_row_actions) wp-admin/includes/class-wp-ms-users-list-table.php | Generates and displays row action links. |
| [WP\_MS\_Users\_List\_Table::column\_blogs()](../classes/wp_ms_users_list_table/column_blogs) wp-admin/includes/class-wp-ms-users-list-table.php | Handles the sites column output. |
| [WP\_Automatic\_Updater::send\_email()](../classes/wp_automatic_updater/send_email) wp-admin/includes/class-wp-automatic-updater.php | Sends an email upon the completion or failure of a background core update. |
| [WP\_MS\_Users\_List\_Table::get\_views()](../classes/wp_ms_users_list_table/get_views) wp-admin/includes/class-wp-ms-users-list-table.php | |
| [WP\_Plugins\_List\_Table::single\_row()](../classes/wp_plugins_list_table/single_row) wp-admin/includes/class-wp-plugins-list-table.php | |
| [site\_admin\_notice()](site_admin_notice) wp-admin/includes/ms.php | Displays an admin notice to upgrade all sites after a core upgrade. |
| [core\_update\_footer()](core_update_footer) wp-admin/includes/update.php | Returns core update footer message. |
| [update\_nag()](update_nag) wp-admin/includes/update.php | Returns core update notification message. |
| [update\_right\_now\_message()](update_right_now_message) wp-admin/includes/update.php | Displays WordPress version and active theme in the ‘At a Glance’ dashboard widget. |
| [wp\_network\_dashboard\_right\_now()](wp_network_dashboard_right_now) wp-admin/includes/dashboard.php | |
| [WP\_Plugin\_Install\_List\_Table::display\_rows()](../classes/wp_plugin_install_list_table/display_rows) wp-admin/includes/class-wp-plugin-install-list-table.php | |
| [WP\_Themes\_List\_Table::no\_items()](../classes/wp_themes_list_table/no_items) wp-admin/includes/class-wp-themes-list-table.php | |
| [wp\_ajax\_query\_themes()](wp_ajax_query_themes) wp-admin/includes/ajax-actions.php | Ajax handler for getting themes from [themes\_api()](themes_api) . |
| [self\_admin\_url()](self_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for either the current site or the network depending on context. |
| [get\_edit\_profile\_url()](get_edit_profile_url) wp-includes/link-template.php | Retrieves the URL to the user’s profile editor. |
| [wp\_admin\_bar\_site\_menu()](wp_admin_bar_site_menu) wp-includes/admin-bar.php | Adds the “Site Name” menu. |
| [wp\_admin\_bar\_my\_sites\_menu()](wp_admin_bar_my_sites_menu) wp-includes/admin-bar.php | Adds the “My Sites/[Site Name]” menu and all submenus. |
| [wp\_admin\_bar\_updates\_menu()](wp_admin_bar_updates_menu) wp-includes/admin-bar.php | Provides an update link if theme/plugin/core updates are available. |
| [newblog\_notify\_siteadmin()](newblog_notify_siteadmin) wp-includes/ms-functions.php | Notifies the network admin that a new site has been activated. |
| [newuser\_notify\_siteadmin()](newuser_notify_siteadmin) wp-includes/ms-functions.php | Notifies the network admin that a new user has been activated. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress user_can_access_admin_page(): bool user\_can\_access\_admin\_page(): bool
======================================
Determines whether the current user can access the current admin page.
bool True if the current user can access the admin page, false otherwise.
File: `wp-admin/includes/plugin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/plugin.php/)
```
function user_can_access_admin_page() {
global $pagenow, $menu, $submenu, $_wp_menu_nopriv, $_wp_submenu_nopriv,
$plugin_page, $_registered_pages;
$parent = get_admin_page_parent();
if ( ! isset( $plugin_page ) && isset( $_wp_submenu_nopriv[ $parent ][ $pagenow ] ) ) {
return false;
}
if ( isset( $plugin_page ) ) {
if ( isset( $_wp_submenu_nopriv[ $parent ][ $plugin_page ] ) ) {
return false;
}
$hookname = get_plugin_page_hookname( $plugin_page, $parent );
if ( ! isset( $_registered_pages[ $hookname ] ) ) {
return false;
}
}
if ( empty( $parent ) ) {
if ( isset( $_wp_menu_nopriv[ $pagenow ] ) ) {
return false;
}
if ( isset( $_wp_submenu_nopriv[ $pagenow ][ $pagenow ] ) ) {
return false;
}
if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[ $pagenow ][ $plugin_page ] ) ) {
return false;
}
if ( isset( $plugin_page ) && isset( $_wp_menu_nopriv[ $plugin_page ] ) ) {
return false;
}
foreach ( array_keys( $_wp_submenu_nopriv ) as $key ) {
if ( isset( $_wp_submenu_nopriv[ $key ][ $pagenow ] ) ) {
return false;
}
if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[ $key ][ $plugin_page ] ) ) {
return false;
}
}
return true;
}
if ( isset( $plugin_page ) && $plugin_page === $parent && isset( $_wp_menu_nopriv[ $plugin_page ] ) ) {
return false;
}
if ( isset( $submenu[ $parent ] ) ) {
foreach ( $submenu[ $parent ] as $submenu_array ) {
if ( isset( $plugin_page ) && $submenu_array[2] === $plugin_page ) {
return current_user_can( $submenu_array[1] );
} elseif ( $submenu_array[2] === $pagenow ) {
return current_user_can( $submenu_array[1] );
}
}
}
foreach ( $menu as $menu_array ) {
if ( $menu_array[2] === $parent ) {
return current_user_can( $menu_array[1] );
}
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [get\_admin\_page\_parent()](get_admin_page_parent) wp-admin/includes/plugin.php | Gets the parent file of the current admin page. |
| [get\_plugin\_page\_hookname()](get_plugin_page_hookname) wp-admin/includes/plugin.php | Gets the hook name for the administrative page of a plugin. |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress register_term_meta( string $taxonomy, string $meta_key, array $args ): bool register\_term\_meta( string $taxonomy, string $meta\_key, array $args ): bool
==============================================================================
Registers a meta key for terms.
`$taxonomy` string Required Taxonomy to register a meta key for. Pass an empty string to register the meta key across all existing taxonomies. `$meta_key` string Required The meta key to register. `$args` array Required Data used to describe the meta key when registered. See [register\_meta()](register_meta) for a list of supported arguments. More Arguments from register\_meta( ... $args ) Data used to describe the meta key when registered.
* `object_subtype`stringA subtype; e.g. if the object type is "post", the post type. If left empty, the meta key will be registered on the entire object type. Default empty.
* `type`stringThe type of data associated with this meta key.
Valid values are `'string'`, `'boolean'`, `'integer'`, `'number'`, `'array'`, and `'object'`.
* `description`stringA description of the data attached to this meta key.
* `single`boolWhether the meta key has one value per object, or an array of values per object.
* `default`mixedThe default value returned from [get\_metadata()](get_metadata) if no value has been set yet.
When using a non-single meta key, the default value is for the first entry.
In other words, when calling [get\_metadata()](get_metadata) with `$single` set to `false`, the default value given here will be wrapped in an array.
* `sanitize_callback`callableA function or method to call when sanitizing `$meta_key` data.
* `auth_callback`callableOptional. A function or method to call when performing edit\_post\_meta, add\_post\_meta, and delete\_post\_meta capability checks.
* `show_in_rest`bool|arrayWhether data associated with this meta key can be considered public and should be accessible via the REST API. A custom post type must also declare support for custom fields for registered meta to be accessible via REST.
When registering complex meta values this argument may optionally be an array with `'schema'` or `'prepare_callback'` keys instead of a boolean.
bool True if the meta key was successfully registered, false if not.
File: `wp-includes/taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/taxonomy.php/)
```
function register_term_meta( $taxonomy, $meta_key, array $args ) {
$args['object_subtype'] = $taxonomy;
return register_meta( 'term', $meta_key, $args );
}
```
| Uses | Description |
| --- | --- |
| [register\_meta()](register_meta) wp-includes/meta.php | Registers a meta key. |
| Version | Description |
| --- | --- |
| [4.9.8](https://developer.wordpress.org/reference/since/4.9.8/) | Introduced. |
| programming_docs |
wordpress rawurlencode_deep( mixed $value ): mixed rawurlencode\_deep( mixed $value ): mixed
=========================================
Navigates through an array, object, or scalar, and raw-encodes the values to be used in a URL.
`$value` mixed Required The array or string to be encoded. mixed The encoded value.
File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function rawurlencode_deep( $value ) {
return map_deep( $value, 'rawurlencode' );
}
```
| Uses | Description |
| --- | --- |
| [map\_deep()](map_deep) wp-includes/formatting.php | Maps a function to all non-iterable elements of an array or an object. |
| Used By | Description |
| --- | --- |
| [get\_avatar\_data()](get_avatar_data) wp-includes/link-template.php | Retrieves default data about the avatar. |
| [redirect\_canonical()](redirect_canonical) wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress the_author_posts_link( string $deprecated = '' ) the\_author\_posts\_link( string $deprecated = '' )
===================================================
Displays an HTML link to the author page of the current post’s author.
`$deprecated` string Optional Unused. Default: `''`
File: `wp-includes/author-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/author-template.php/)
```
function the_author_posts_link( $deprecated = '' ) {
if ( ! empty( $deprecated ) ) {
_deprecated_argument( __FUNCTION__, '2.1.0' );
}
echo get_the_author_posts_link();
}
```
| Uses | Description |
| --- | --- |
| [get\_the\_author\_posts\_link()](get_the_author_posts_link) wp-includes/author-template.php | Retrieves an HTML link to the author page of the current post’s author. |
| [\_deprecated\_argument()](_deprecated_argument) wp-includes/functions.php | Marks a function argument as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Converted into a wrapper for [get\_the\_author\_posts\_link()](get_the_author_posts_link) |
| [1.2.0](https://developer.wordpress.org/reference/since/1.2.0/) | Introduced. |
wordpress get_post( int|WP_Post|null $post = null, string $output = OBJECT, string $filter = 'raw' ): WP_Post|array|null get\_post( int|WP\_Post|null $post = null, string $output = OBJECT, string $filter = 'raw' ): WP\_Post|array|null
=================================================================================================================
Retrieves post data given a post ID or post object.
See [sanitize\_post()](sanitize_post) for optional $filter values. Also, the parameter `$post`, must be given as a variable, since it is passed by reference.
`$post` int|[WP\_Post](../classes/wp_post)|null Optional Post ID or post object. `null`, `false`, `0` and other PHP falsey values return the current global post inside the loop. A numerically valid post ID that points to a non-existent post returns `null`. Defaults to global $post. Default: `null`
`$output` string Optional The required return type. One of OBJECT, ARRAY\_A, or ARRAY\_N, which correspond to a [WP\_Post](../classes/wp_post) object, an associative array, or a numeric array, respectively. Default: `OBJECT`
`$filter` string Optional Type of filter to apply. Accepts `'raw'`, `'edit'`, `'db'`, or `'display'`. Default `'raw'`. Default: `'raw'`
[WP\_Post](../classes/wp_post)|array|null Type corresponding to $output on success or null on failure.
When $output is OBJECT, a `WP_Post` instance is returned.
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) {
if ( empty( $post ) && isset( $GLOBALS['post'] ) ) {
$post = $GLOBALS['post'];
}
if ( $post instanceof WP_Post ) {
$_post = $post;
} elseif ( is_object( $post ) ) {
if ( empty( $post->filter ) ) {
$_post = sanitize_post( $post, 'raw' );
$_post = new WP_Post( $_post );
} elseif ( 'raw' === $post->filter ) {
$_post = new WP_Post( $post );
} else {
$_post = WP_Post::get_instance( $post->ID );
}
} else {
$_post = WP_Post::get_instance( $post );
}
if ( ! $_post ) {
return null;
}
$_post = $_post->filter( $filter );
if ( ARRAY_A === $output ) {
return $_post->to_array();
} elseif ( ARRAY_N === $output ) {
return array_values( $_post->to_array() );
}
return $_post;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Post::\_\_construct()](../classes/wp_post/__construct) wp-includes/class-wp-post.php | Constructor. |
| [WP\_Post::get\_instance()](../classes/wp_post/get_instance) wp-includes/class-wp-post.php | Retrieve [WP\_Post](../classes/wp_post) instance. |
| [sanitize\_post()](sanitize_post) wp-includes/post.php | Sanitizes every post field. |
| Used By | Description |
| --- | --- |
| [wp\_get\_latest\_revision\_id\_and\_total\_count()](wp_get_latest_revision_id_and_total_count) wp-includes/revision.php | Returns the latest revision ID and count of revisions for a post. |
| [wp\_get\_post\_revisions\_url()](wp_get_post_revisions_url) wp-includes/revision.php | Returns the url for viewing and potentially restoring revisions of a given post. |
| [WP\_Theme\_JSON\_Resolver::get\_user\_data\_from\_wp\_global\_styles()](../classes/wp_theme_json_resolver/get_user_data_from_wp_global_styles) wp-includes/class-wp-theme-json-resolver.php | Returns the custom post type that contains the user’s origin config for the active theme or a void array if none are found. |
| [WP\_REST\_Menu\_Items\_Controller::create\_item()](../classes/wp_rest_menu_items_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Creates a single post. |
| [WP\_REST\_Menu\_Items\_Controller::update\_item()](../classes/wp_rest_menu_items_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Updates a single nav menu item. |
| [WP\_REST\_Menu\_Items\_Controller::delete\_item()](../classes/wp_rest_menu_items_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Deletes a single menu item. |
| [WP\_REST\_Menu\_Items\_Controller::prepare\_item\_for\_database()](../classes/wp_rest_menu_items_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Prepares a single post for create or update. |
| [WP\_REST\_Global\_Styles\_Controller::get\_post()](../classes/wp_rest_global_styles_controller/get_post) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Get the post, if the ID is valid. |
| [WP\_REST\_Global\_Styles\_Controller::update\_item()](../classes/wp_rest_global_styles_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Updates a single global style config. |
| [WP\_REST\_Global\_Styles\_Controller::prepare\_item\_for\_database()](../classes/wp_rest_global_styles_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Prepares a single global styles config for update. |
| [wp\_set\_unique\_slug\_on\_create\_template\_part()](wp_set_unique_slug_on_create_template_part) wp-includes/theme-templates.php | Sets a custom slug when creating auto-draft template parts. |
| [\_resolve\_template\_for\_new\_post()](_resolve_template_for_new_post) wp-includes/block-template.php | Sets the current [WP\_Query](../classes/wp_query) to return auto-draft posts. |
| [WP\_REST\_Templates\_Controller::update\_item()](../classes/wp_rest_templates_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Updates a single template. |
| [WP\_REST\_Templates\_Controller::create\_item()](../classes/wp_rest_templates_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Creates a single template. |
| [get\_adjacent\_image\_link()](get_adjacent_image_link) wp-includes/media.php | Gets the next or previous image link that has the same post parent. |
| [WP\_REST\_Posts\_Controller::check\_password\_required()](../classes/wp_rest_posts_controller/check_password_required) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Overrides the result of the post password check for REST requested posts. |
| [wp\_force\_plain\_post\_permalink()](wp_force_plain_post_permalink) wp-includes/link-template.php | Determine whether post should always use a plain permalink structure. |
| [is\_post\_publicly\_viewable()](is_post_publicly_viewable) wp-includes/post.php | Determines whether a post is publicly viewable. |
| [get\_post\_parent()](get_post_parent) wp-includes/post-template.php | Retrieves the parent post object for the given post. |
| [wp\_after\_insert\_post()](wp_after_insert_post) wp-includes/post.php | Fires actions after a post, its terms and meta data has been saved. |
| [WP\_REST\_Attachments\_Controller::edit\_media\_item()](../classes/wp_rest_attachments_controller/edit_media_item) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Applies edits to a media item and creates a new attachment record. |
| [rest\_get\_route\_for\_post()](rest_get_route_for_post) wp-includes/rest-api.php | Gets the REST API route for a post. |
| [wp\_get\_user\_request()](wp_get_user_request) wp-includes/user.php | Returns the user request object for the specified request ID. |
| [WP\_REST\_Attachments\_Controller::insert\_attachment()](../classes/wp_rest_attachments_controller/insert_attachment) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Inserts the attachment post in the database. Does not update the attachment meta. |
| [WP\_REST\_Attachments\_Controller::post\_process\_item()](../classes/wp_rest_attachments_controller/post_process_item) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Performs post processing on an attachment. |
| [get\_post\_datetime()](get_post_datetime) wp-includes/general-template.php | Retrieves post published or modified time as a `DateTimeImmutable` object instance. |
| [wp\_ajax\_media\_create\_image\_subsizes()](wp_ajax_media_create_image_subsizes) wp-admin/includes/ajax-actions.php | Ajax handler for creating missing image sub-sizes for just uploaded images. |
| [WP\_Query::generate\_postdata()](../classes/wp_query/generate_postdata) wp-includes/class-wp-query.php | Generate post data. |
| [WP\_REST\_Autosaves\_Controller::create\_item()](../classes/wp_rest_autosaves_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Creates, updates or deletes an autosave revision. |
| [WP\_REST\_Autosaves\_Controller::create\_post\_autosave()](../classes/wp_rest_autosaves_controller/create_post_autosave) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Creates autosave for the specified post. |
| [WP\_REST\_Block\_Renderer\_Controller::get\_item\_permissions\_check()](../classes/wp_rest_block_renderer_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-block-renderer-controller.php | Checks if a given request has access to read blocks. |
| [WP\_REST\_Block\_Renderer\_Controller::get\_item()](../classes/wp_rest_block_renderer_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-block-renderer-controller.php | Returns block output from block’s registered render\_callback. |
| [WP\_REST\_Post\_Search\_Handler::prepare\_item()](../classes/wp_rest_post_search_handler/prepare_item) wp-includes/rest-api/search/class-wp-rest-post-search-handler.php | Prepares the search result for a given ID. |
| [WP\_REST\_Post\_Search\_Handler::prepare\_item\_links()](../classes/wp_rest_post_search_handler/prepare_item_links) wp-includes/rest-api/search/class-wp-rest-post-search-handler.php | Prepares links for the search result of a given ID. |
| [has\_blocks()](has_blocks) wp-includes/blocks.php | Determines whether a post or content string has blocks. |
| [has\_block()](has_block) wp-includes/blocks.php | Determines whether a $post or a string contains a specific block type. |
| [use\_block\_editor\_for\_post()](use_block_editor_for_post) wp-includes/post.php | Returns whether the post can be edited in the block editor. |
| [WP\_Privacy\_Policy\_Content::notice()](../classes/wp_privacy_policy_content/notice) wp-admin/includes/class-wp-privacy-policy-content.php | Add a notice with a link to the guide when editing the privacy policy page. |
| [\_wp\_privacy\_resend\_request()](_wp_privacy_resend_request) wp-admin/includes/privacy-tools.php | Resend an existing request and return the result. |
| [WP\_Customize\_Manager::trash\_changeset\_post()](../classes/wp_customize_manager/trash_changeset_post) wp-includes/class-wp-customize-manager.php | Trashes or deletes a changeset post. |
| [WP\_REST\_Posts\_Controller::check\_template()](../classes/wp_rest_posts_controller/check_template) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks whether the template is valid for the given post. |
| [WP\_REST\_Revisions\_Controller::get\_revision()](../classes/wp_rest_revisions_controller/get_revision) wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php | Get the revision, if the ID is valid. |
| [WP\_REST\_Revisions\_Controller::get\_parent()](../classes/wp_rest_revisions_controller/get_parent) wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php | Get the parent post, if the ID is valid. |
| [WP\_REST\_Posts\_Controller::get\_post()](../classes/wp_rest_posts_controller/get_post) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Gets the post, if the ID is valid. |
| [WP\_REST\_Comments\_Controller::get\_comment()](../classes/wp_rest_comments_controller/get_comment) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Get the comment, if the ID is valid. |
| [\_wp\_delete\_customize\_changeset\_dependent\_auto\_drafts()](_wp_delete_customize_changeset_dependent_auto_drafts) wp-includes/nav-menu.php | Deletes auto-draft posts associated with the supplied changeset. |
| [WP\_Widget\_Media\_Audio::render\_media()](../classes/wp_widget_media_audio/render_media) wp-includes/widgets/class-wp-widget-media-audio.php | Render the media on the frontend. |
| [WP\_Widget\_Media\_Video::render\_media()](../classes/wp_widget_media_video/render_media) wp-includes/widgets/class-wp-widget-media-video.php | Render the media on the frontend. |
| [WP\_Widget\_Media::display\_media\_state()](../classes/wp_widget_media/display_media_state) wp-includes/widgets/class-wp-widget-media.php | Filters the default media display states for items in the Media list table. |
| [WP\_Widget\_Media::is\_attachment\_with\_mime\_type()](../classes/wp_widget_media/is_attachment_with_mime_type) wp-includes/widgets/class-wp-widget-media.php | Determine if the supplied attachment is for a valid attachment post with the specified MIME type. |
| [WP\_Widget\_Media\_Image::render\_media()](../classes/wp_widget_media_image/render_media) wp-includes/widgets/class-wp-widget-media-image.php | Render the media on the frontend. |
| [WP\_Customize\_Manager::\_publish\_changeset\_values()](../classes/wp_customize_manager/_publish_changeset_values) wp-includes/class-wp-customize-manager.php | Publishes the values of a changeset. |
| [WP\_Customize\_Manager::save\_changeset\_post()](../classes/wp_customize_manager/save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [WP\_Customize\_Manager::import\_theme\_starter\_content()](../classes/wp_customize_manager/import_theme_starter_content) wp-includes/class-wp-customize-manager.php | Imports theme starter content into the customized state. |
| [WP\_Customize\_Manager::get\_changeset\_post\_data()](../classes/wp_customize_manager/get_changeset_post_data) wp-includes/class-wp-customize-manager.php | Gets the data stored in a changeset post. |
| [wp\_update\_custom\_css\_post()](wp_update_custom_css_post) wp-includes/theme.php | Updates the `custom_css` post for a given theme. |
| [wp\_get\_custom\_css\_post()](wp_get_custom_css_post) wp-includes/theme.php | Fetches the `custom_css` post for a given theme. |
| [WP\_REST\_Attachments\_Controller::create\_item()](../classes/wp_rest_attachments_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Creates a single attachment. |
| [WP\_REST\_Attachments\_Controller::update\_item()](../classes/wp_rest_attachments_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Updates a single attachment. |
| [WP\_REST\_Terms\_Controller::get\_items\_permissions\_check()](../classes/wp_rest_terms_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks if a request has access to read terms in the specified taxonomy. |
| [WP\_REST\_Posts\_Controller::check\_read\_permission()](../classes/wp_rest_posts_controller/check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be read. |
| [WP\_REST\_Posts\_Controller::handle\_template()](../classes/wp_rest_posts_controller/handle_template) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Sets the template for a post. |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_database()](../classes/wp_rest_posts_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post for create or update. |
| [WP\_REST\_Posts\_Controller::create\_item()](../classes/wp_rest_posts_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Creates a single post. |
| [WP\_REST\_Posts\_Controller::update\_item()](../classes/wp_rest_posts_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Updates a single post. |
| [WP\_REST\_Posts\_Controller::delete\_item()](../classes/wp_rest_posts_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Deletes a single post. |
| [WP\_REST\_Comments\_Controller::check\_read\_permission()](../classes/wp_rest_comments_controller/check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Checks if the comment can be read. |
| [WP\_REST\_Comments\_Controller::prepare\_links()](../classes/wp_rest_comments_controller/prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Prepares links for the request. |
| [WP\_REST\_Comments\_Controller::update\_item()](../classes/wp_rest_comments_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Updates a comment. |
| [WP\_REST\_Comments\_Controller::get\_item\_permissions\_check()](../classes/wp_rest_comments_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Checks if a given request has access to read the comment. |
| [WP\_REST\_Comments\_Controller::create\_item\_permissions\_check()](../classes/wp_rest_comments_controller/create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Checks if a given request has access to create a comment. |
| [WP\_REST\_Comments\_Controller::get\_items\_permissions\_check()](../classes/wp_rest_comments_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Checks if a given request has access to read comments. |
| [WP\_Customize\_Nav\_Menus::sanitize\_nav\_menus\_created\_posts()](../classes/wp_customize_nav_menus/sanitize_nav_menus_created_posts) wp-includes/class-wp-customize-nav-menus.php | Sanitizes post IDs for posts created for nav menu items to be published. |
| [WP\_Customize\_Nav\_Menus::insert\_auto\_draft\_post()](../classes/wp_customize_nav_menus/insert_auto_draft_post) wp-includes/class-wp-customize-nav-menus.php | Adds a new `auto-draft` post. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::get\_original\_title()](../classes/wp_customize_nav_menu_item_setting/get_original_title) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get original title. |
| [\_wp\_preview\_post\_thumbnail\_filter()](_wp_preview_post_thumbnail_filter) wp-includes/revision.php | Filters post thumbnail lookup to set the post thumbnail. |
| [wp\_get\_canonical\_url()](wp_get_canonical_url) wp-includes/link-template.php | Returns the canonical URL for a post. |
| [wp\_get\_attachment\_caption()](wp_get_attachment_caption) wp-includes/post.php | Retrieves the caption for an attachment. |
| [\_wp\_post\_revision\_data()](_wp_post_revision_data) wp-includes/revision.php | Returns a post array ready to be inserted into the posts table as a post revision. |
| [wp\_add\_trashed\_suffix\_to\_post\_name\_for\_post()](wp_add_trashed_suffix_to_post_name_for_post) wp-includes/post.php | Adds a trashed suffix for a given post. |
| [get\_post\_embed\_url()](get_post_embed_url) wp-includes/embed.php | Retrieves the URL to embed a specific post in an iframe. |
| [get\_post\_embed\_html()](get_post_embed_html) wp-includes/embed.php | Retrieves the embed code for a specific post. |
| [get\_oembed\_response\_data()](get_oembed_response_data) wp-includes/embed.php | Retrieves the oEmbed response data for a given post. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](../classes/wp_customize_manager/customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [WP\_Comment::\_\_isset()](../classes/wp_comment/__isset) wp-includes/class-wp-comment.php | Check whether a non-public property is set. |
| [WP\_Comment::\_\_get()](../classes/wp_comment/__get) wp-includes/class-wp-comment.php | Magic getter. |
| [wp\_handle\_comment\_submission()](wp_handle_comment_submission) wp-includes/comment.php | Handles the submission of a comment, usually posted to wp-comments-post.php via a comment form. |
| [get\_preview\_post\_link()](get_preview_post_link) wp-includes/link-template.php | Retrieves the URL used for the post preview. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::value()](../classes/wp_customize_nav_menu_item_setting/value) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get the instance data for a given nav\_menu\_item setting. |
| [WP\_Customize\_Nav\_Menus::load\_available\_items\_query()](../classes/wp_customize_nav_menus/load_available_items_query) wp-includes/class-wp-customize-nav-menus.php | Performs the post\_type and taxonomy queries for loading available menu items. |
| [WP\_Posts\_List\_Table::column\_title()](../classes/wp_posts_list_table/column_title) wp-admin/includes/class-wp-posts-list-table.php | Handles the title column output. |
| [WP\_Site\_Icon::create\_attachment\_object()](../classes/wp_site_icon/create_attachment_object) wp-admin/includes/class-wp-site-icon.php | Creates an attachment ‘object’. |
| [wp\_ajax\_crop\_image()](wp_ajax_crop_image) wp-admin/includes/ajax-actions.php | Ajax handler for cropping an image. |
| [WP\_Media\_List\_Table::column\_parent()](../classes/wp_media_list_table/column_parent) wp-admin/includes/class-wp-media-list-table.php | Handles the parent column output. |
| [wp\_attachment\_is()](wp_attachment_is) wp-includes/post.php | Verifies an attachment is of a given type. |
| [WP\_Query::setup\_postdata()](../classes/wp_query/setup_postdata) wp-includes/class-wp-query.php | Set up global post data. |
| [\_update\_posts\_count\_on\_delete()](_update_posts_count_on_delete) wp-includes/ms-blogs.php | Handler for updating the current site’s posts count when a post is deleted. |
| [wp\_ajax\_parse\_embed()](wp_ajax_parse_embed) wp-admin/includes/ajax-actions.php | Apply [embed] Ajax handlers to a string. |
| [wp\_ajax\_parse\_media\_shortcode()](wp_ajax_parse_media_shortcode) wp-admin/includes/ajax-actions.php | |
| [File\_Upload\_Upgrader::\_\_construct()](../classes/file_upload_upgrader/__construct) wp-admin/includes/class-file-upload-upgrader.php | Construct the upgrader for a form. |
| [WP\_Screen::get()](../classes/wp_screen/get) wp-admin/includes/class-wp-screen.php | Fetches a screen object. |
| [wxr\_post\_taxonomy()](wxr_post_taxonomy) wp-admin/includes/export.php | Outputs list of taxonomy terms, in XML tag format, associated with a post. |
| [get\_post\_to\_edit()](get_post_to_edit) wp-admin/includes/deprecated.php | Gets an existing post and format it for editing. |
| [stream\_preview\_image()](stream_preview_image) wp-admin/includes/image-edit.php | Streams image in post to browser, along with enqueued changes in `$_REQUEST['history']`. |
| [wp\_save\_image()](wp_save_image) wp-admin/includes/image-edit.php | Saves image to post, along with enqueued changes in `$_REQUEST['history']`. |
| [wp\_generate\_attachment\_metadata()](wp_generate_attachment_metadata) wp-admin/includes/image.php | Generates attachment meta data and create image sub-sizes for images. |
| [wp\_dashboard\_quick\_press()](wp_dashboard_quick_press) wp-admin/includes/dashboard.php | The Quick Draft widget display and creation of drafts. |
| [the\_post\_password()](the_post_password) wp-admin/includes/template.php | Displays the post password. |
| [meta\_form()](meta_form) wp-admin/includes/template.php | Prints the form in the Custom Fields meta box. |
| [touch\_time()](touch_time) wp-admin/includes/template.php | Prints out HTML form date elements for editing post or comment publish date. |
| [parent\_dropdown()](parent_dropdown) wp-admin/includes/template.php | Prints out option HTML elements for the page parents drop-down. |
| [wp\_popular\_terms\_checklist()](wp_popular_terms_checklist) wp-admin/includes/template.php | Retrieves a list of the most popular terms from the specified taxonomy. |
| [media\_upload\_flash\_bypass()](media_upload_flash_bypass) wp-admin/includes/media.php | Displays the multi-file uploader message. |
| [attachment\_submitbox\_metadata()](attachment_submitbox_metadata) wp-admin/includes/media.php | Displays non-editable attachment metadata in the publish meta box. |
| [image\_media\_send\_to\_editor()](image_media_send_to_editor) wp-admin/includes/media.php | Retrieves the media element HTML to send to the editor. |
| [get\_attachment\_fields\_to\_edit()](get_attachment_fields_to_edit) wp-admin/includes/media.php | Retrieves the attachment fields to edit form fields. |
| [get\_media\_items()](get_media_items) wp-admin/includes/media.php | Retrieves HTML for media items of post gallery. |
| [get\_media\_item()](get_media_item) wp-admin/includes/media.php | Retrieves HTML form for modifying the image attachment. |
| [get\_compat\_media\_markup()](get_compat_media_markup) wp-admin/includes/media.php | |
| [media\_upload\_form\_handler()](media_upload_form_handler) wp-admin/includes/media.php | Handles form submissions for the legacy media uploader. |
| [media\_handle\_upload()](media_handle_upload) wp-admin/includes/media.php | Saves a file submitted from a POST request and create an attachment post for it. |
| [media\_handle\_sideload()](media_handle_sideload) wp-admin/includes/media.php | Handles a side-loaded file in the same way as an uploaded file is handled by [media\_handle\_upload()](media_handle_upload) . |
| [media\_buttons()](media_buttons) wp-admin/includes/media.php | Adds the media button to the editor. |
| [get\_sample\_permalink\_html()](get_sample_permalink_html) wp-admin/includes/post.php | Returns the HTML of the sample permalink slug editor. |
| [\_wp\_post\_thumbnail\_html()](_wp_post_thumbnail_html) wp-admin/includes/post.php | Returns HTML for the post thumbnail meta box. |
| [wp\_check\_post\_lock()](wp_check_post_lock) wp-admin/includes/post.php | Determines whether the post is currently being edited by another user. |
| [wp\_set\_post\_lock()](wp_set_post_lock) wp-admin/includes/post.php | Marks the post as currently being edited by the current user. |
| [\_admin\_notice\_post\_locked()](_admin_notice_post_locked) wp-admin/includes/post.php | Outputs the HTML for the notice to say that someone else is editing or has taken over editing of this post. |
| [wp\_create\_post\_autosave()](wp_create_post_autosave) wp-admin/includes/post.php | Creates autosave data for the specified post from `$_POST` data. |
| [post\_preview()](post_preview) wp-admin/includes/post.php | Saves a draft or manually autosaves for the purpose of showing a post preview. |
| [wp\_autosave()](wp_autosave) wp-admin/includes/post.php | Saves a post submitted with XHR. |
| [\_fix\_attachment\_links()](_fix_attachment_links) wp-admin/includes/post.php | Replaces hrefs of attachment anchors with up-to-date permalinks. |
| [get\_sample\_permalink()](get_sample_permalink) wp-admin/includes/post.php | Returns a sample permalink based on the post name. |
| [edit\_post()](edit_post) wp-admin/includes/post.php | Updates an existing post with values provided in `$_POST`. |
| [bulk\_edit\_posts()](bulk_edit_posts) wp-admin/includes/post.php | Processes the post data for the bulk editing of posts. |
| [get\_default\_post\_to\_edit()](get_default_post_to_edit) wp-admin/includes/post.php | Returns default post information to use when populating the “Write Post” form. |
| [wp\_ajax\_save\_attachment\_order()](wp_ajax_save_attachment_order) wp-admin/includes/ajax-actions.php | Ajax handler for saving the attachment order. |
| [wp\_ajax\_send\_attachment\_to\_editor()](wp_ajax_send_attachment_to_editor) wp-admin/includes/ajax-actions.php | Ajax handler for sending an attachment to the editor. |
| [wp\_ajax\_send\_link\_to\_editor()](wp_ajax_send_link_to_editor) wp-admin/includes/ajax-actions.php | Ajax handler for sending a link to the editor. |
| [wp\_ajax\_get\_revision\_diffs()](wp_ajax_get_revision_diffs) wp-admin/includes/ajax-actions.php | Ajax handler for getting revision diffs. |
| [wp\_ajax\_wp\_fullscreen\_save\_post()](wp_ajax_wp_fullscreen_save_post) wp-admin/includes/ajax-actions.php | Ajax handler for saving posts from the fullscreen editor. |
| [wp\_ajax\_wp\_remove\_post\_lock()](wp_ajax_wp_remove_post_lock) wp-admin/includes/ajax-actions.php | Ajax handler for removing a post lock. |
| [wp\_ajax\_get\_attachment()](wp_ajax_get_attachment) wp-admin/includes/ajax-actions.php | Ajax handler for getting an attachment. |
| [wp\_ajax\_save\_attachment()](wp_ajax_save_attachment) wp-admin/includes/ajax-actions.php | Ajax handler for updating attachment attributes. |
| [wp\_ajax\_save\_attachment\_compat()](wp_ajax_save_attachment_compat) wp-admin/includes/ajax-actions.php | Ajax handler for saving backward compatible attachment attributes. |
| [wp\_ajax\_add\_menu\_item()](wp_ajax_add_menu_item) wp-admin/includes/ajax-actions.php | Ajax handler for adding a menu item. |
| [wp\_ajax\_add\_meta()](wp_ajax_add_meta) wp-admin/includes/ajax-actions.php | Ajax handler for adding meta. |
| [wp\_ajax\_inline\_save()](wp_ajax_inline_save) wp-admin/includes/ajax-actions.php | Ajax handler for Quick Edit saving a post from a list table. |
| [wp\_ajax\_delete\_post()](wp_ajax_delete_post) wp-admin/includes/ajax-actions.php | Ajax handler for deleting a post. |
| [wp\_ajax\_trash\_post()](wp_ajax_trash_post) wp-admin/includes/ajax-actions.php | Ajax handler for sending a post to the Trash. |
| [wp\_ajax\_delete\_page()](wp_ajax_delete_page) wp-admin/includes/ajax-actions.php | Ajax handler to delete a page. |
| [wp\_ajax\_replyto\_comment()](wp_ajax_replyto_comment) wp-admin/includes/ajax-actions.php | Ajax handler for replying to a comment. |
| [wp\_get\_revision\_ui\_diff()](wp_get_revision_ui_diff) wp-admin/includes/revision.php | Get the revision UI diff. |
| [wp\_prepare\_revisions\_for\_js()](wp_prepare_revisions_for_js) wp-admin/includes/revision.php | Prepare revisions for JavaScript. |
| [WP\_Comments\_List\_Table::column\_response()](../classes/wp_comments_list_table/column_response) wp-admin/includes/class-wp-comments-list-table.php | |
| [WP\_Comments\_List\_Table::single\_row()](../classes/wp_comments_list_table/single_row) wp-admin/includes/class-wp-comments-list-table.php | |
| [Walker\_Nav\_Menu\_Edit::start\_el()](../classes/walker_nav_menu_edit/start_el) wp-admin/includes/class-walker-nav-menu-edit.php | Start the element output. |
| [\_wp\_ajax\_menu\_quick\_search()](_wp_ajax_menu_quick_search) wp-admin/includes/nav-menu.php | Prints the appropriate response to a menu quick search. |
| [wp\_nav\_menu\_item\_post\_type\_meta\_box()](wp_nav_menu_item_post_type_meta_box) wp-admin/includes/nav-menu.php | Displays a meta box for a post type menu item. |
| [WP\_Posts\_List\_Table::single\_row()](../classes/wp_posts_list_table/single_row) wp-admin/includes/class-wp-posts-list-table.php | |
| [WP\_Posts\_List\_Table::\_page\_rows()](../classes/wp_posts_list_table/_page_rows) wp-admin/includes/class-wp-posts-list-table.php | Given a top level page ID, display the nested hierarchy of sub-pages together with paging support |
| [Custom\_Image\_Header::create\_attachment\_object()](../classes/custom_image_header/create_attachment_object) wp-admin/includes/class-custom-image-header.php | Create an attachment ‘object’. |
| [author\_can()](author_can) wp-includes/capabilities.php | Returns whether the author of the supplied post has the specified capability. |
| [map\_meta\_cap()](map_meta_cap) wp-includes/capabilities.php | Maps a capability to the primitive capabilities required of the given user to satisfy the capability being checked. |
| [WP\_Customize\_Manager::save()](../classes/wp_customize_manager/save) wp-includes/class-wp-customize-manager.php | Handles customize\_save WP Ajax request to save/update a changeset. |
| [has\_term()](has_term) wp-includes/category-template.php | Checks if the current post has any of given terms. |
| [get\_the\_terms()](get_the_terms) wp-includes/category-template.php | Retrieves the terms of the taxonomy that are attached to the post. |
| [wp\_trim\_excerpt()](wp_trim_excerpt) wp-includes/formatting.php | Generates an excerpt from the content, if needed. |
| [wp\_notify\_postauthor()](wp_notify_postauthor) wp-includes/pluggable.php | Notifies an author (and/or others) of a comment/trackback/pingback on a post. |
| [wp\_notify\_moderator()](wp_notify_moderator) wp-includes/pluggable.php | Notifies the moderator of the site about a new comment that is awaiting approval. |
| [feed\_links\_extra()](feed_links_extra) wp-includes/general-template.php | Displays the links to the extra feeds such as category feeds. |
| [get\_the\_modified\_date()](get_the_modified_date) wp-includes/general-template.php | Retrieves the date on which the post was last modified. |
| [get\_the\_time()](get_the_time) wp-includes/general-template.php | Retrieves the time at which the post was written. |
| [get\_post\_time()](get_post_time) wp-includes/general-template.php | Retrieves the time at which the post was written. |
| [get\_the\_modified\_time()](get_the_modified_time) wp-includes/general-template.php | Retrieves the time at which the post was last modified. |
| [get\_post\_modified\_time()](get_post_modified_time) wp-includes/general-template.php | Retrieves the time at which the post was last modified. |
| [the\_weekday()](the_weekday) wp-includes/general-template.php | Displays the weekday on which the post was written. |
| [the\_weekday\_date()](the_weekday_date) wp-includes/general-template.php | Displays the weekday on which the post was written. |
| [the\_date\_xml()](the_date_xml) wp-includes/general-template.php | Outputs the date in iso8601 format for xml files. |
| [get\_the\_date()](get_the_date) wp-includes/general-template.php | Retrieves the date on which the post was written. |
| [wp\_get\_single\_post()](wp_get_single_post) wp-includes/deprecated.php | Retrieve a single post, based on post ID. |
| [get\_parent\_post\_rel\_link()](get_parent_post_rel_link) wp-includes/deprecated.php | Get parent post relational link. |
| [get\_the\_attachment\_link()](get_the_attachment_link) wp-includes/deprecated.php | Retrieve HTML content of attachment image with link. |
| [get\_attachment\_icon\_src()](get_attachment_icon_src) wp-includes/deprecated.php | Retrieve icon URL and Path. |
| [get\_attachment\_icon()](get_attachment_icon) wp-includes/deprecated.php | Retrieve HTML content of icon attachment image element. |
| [get\_attachment\_innerHTML()](get_attachment_innerhtml) wp-includes/deprecated.php | Retrieve HTML content of image element. |
| [user\_can\_edit\_post()](user_can_edit_post) wp-includes/deprecated.php | Whether user can edit a post. |
| [get\_postdata()](get_postdata) wp-includes/deprecated.php | Retrieves all post data for a given post. |
| [start\_wp()](start_wp) wp-includes/deprecated.php | Sets up the WordPress Loop. |
| [WP\_Query::get\_queried\_object()](../classes/wp_query/get_queried_object) wp-includes/class-wp-query.php | Retrieves the currently queried object. |
| [WP\_Query::get\_posts()](../classes/wp_query/get_posts) wp-includes/class-wp-query.php | Retrieves an array of posts based on query variables. |
| [wp\_scheduled\_delete()](wp_scheduled_delete) wp-includes/functions.php | Permanently deletes comments or posts of any type that have held a status of ‘trash’ for the number of days defined in EMPTY\_TRASH\_DAYS. |
| [do\_enclose()](do_enclose) wp-includes/functions.php | Checks content for video and audio links to add as enclosures. |
| [WP\_Embed::cache\_oembed()](../classes/wp_embed/cache_oembed) wp-includes/class-wp-embed.php | Triggers a caching of all oEmbed results. |
| [WP\_Embed::maybe\_run\_ajax\_cache()](../classes/wp_embed/maybe_run_ajax_cache) wp-includes/class-wp-embed.php | If a post/page was saved, then output JavaScript to make an Ajax request that will call [WP\_Embed::cache\_oembed()](../classes/wp_embed/cache_oembed). |
| [WP\_Embed::shortcode()](../classes/wp_embed/shortcode) wp-includes/class-wp-embed.php | The [do\_shortcode()](do_shortcode) callback function. |
| [get\_the\_taxonomies()](get_the_taxonomies) wp-includes/taxonomy.php | Retrieves all taxonomies associated with a post. |
| [get\_post\_taxonomies()](get_post_taxonomies) wp-includes/taxonomy.php | Retrieves all taxonomy names for the given post. |
| [wp\_get\_shortlink()](wp_get_shortlink) wp-includes/link-template.php | Returns a shortlink for a post, page, attachment, or site. |
| [the\_shortlink()](the_shortlink) wp-includes/link-template.php | Displays the shortlink for a post. |
| [get\_adjacent\_post\_link()](get_adjacent_post_link) wp-includes/link-template.php | Retrieves the adjacent post link. |
| [get\_adjacent\_post()](get_adjacent_post) wp-includes/link-template.php | Retrieves the adjacent post. |
| [get\_adjacent\_post\_rel\_link()](get_adjacent_post_rel_link) wp-includes/link-template.php | Retrieves the adjacent post relational link. |
| [get\_boundary\_post()](get_boundary_post) wp-includes/link-template.php | Retrieves the boundary post. |
| [get\_edit\_post\_link()](get_edit_post_link) wp-includes/link-template.php | Retrieves the edit post link for post. |
| [edit\_post\_link()](edit_post_link) wp-includes/link-template.php | Displays the edit post link for post. |
| [get\_delete\_post\_link()](get_delete_post_link) wp-includes/link-template.php | Retrieves the delete posts link for post. |
| [get\_post\_comments\_feed\_link()](get_post_comments_feed_link) wp-includes/link-template.php | Retrieves the permalink for the post comments feed. |
| [permalink\_anchor()](permalink_anchor) wp-includes/link-template.php | Displays the permalink anchor for the current post. |
| [get\_permalink()](get_permalink) wp-includes/link-template.php | Retrieves the full permalink for the current post or post ID. |
| [get\_post\_permalink()](get_post_permalink) wp-includes/link-template.php | Retrieves the permalink for a post of a custom post type. |
| [get\_page\_link()](get_page_link) wp-includes/link-template.php | Retrieves the permalink for the current page or page ID. |
| [\_get\_page\_link()](_get_page_link) wp-includes/link-template.php | Retrieves the page permalink. |
| [get\_attachment\_link()](get_attachment_link) wp-includes/link-template.php | Retrieves the permalink for an attachment. |
| [wp\_admin\_bar\_edit\_menu()](wp_admin_bar_edit_menu) wp-includes/admin-bar.php | Provides an edit link for posts and terms. |
| [get\_post\_thumbnail\_id()](get_post_thumbnail_id) wp-includes/post-thumbnail-template.php | Retrieves the post thumbnail ID. |
| [get\_the\_post\_thumbnail()](get_the_post_thumbnail) wp-includes/post-thumbnail-template.php | Retrieves the post thumbnail. |
| [Walker\_Page::start\_el()](../classes/walker_page/start_el) wp-includes/class-walker-page.php | Outputs the beginning of the current element in the tree. |
| [wp\_get\_attachment\_link()](wp_get_attachment_link) wp-includes/post-template.php | Retrieves an attachment page link using an image or icon, if possible. |
| [prepend\_attachment()](prepend_attachment) wp-includes/post-template.php | Wraps attachment in paragraph tag before content. |
| [get\_the\_password\_form()](get_the_password_form) wp-includes/post-template.php | Retrieves protected post password form content. |
| [get\_page\_template\_slug()](get_page_template_slug) wp-includes/post-template.php | Gets the specific template filename for a given post. |
| [wp\_post\_revision\_title()](wp_post_revision_title) wp-includes/post-template.php | Retrieves formatted date timestamp of a revision (linked to that revisions’s page). |
| [wp\_post\_revision\_title\_expanded()](wp_post_revision_title_expanded) wp-includes/post-template.php | Retrieves formatted date timestamp of a revision (linked to that revisions’s page). |
| [wp\_list\_post\_revisions()](wp_list_post_revisions) wp-includes/post-template.php | Displays a list of a post’s revisions. |
| [post\_password\_required()](post_password_required) wp-includes/post-template.php | Determines whether the post requires password and whether a correct password has been provided. |
| [\_wp\_link\_page()](_wp_link_page) wp-includes/post-template.php | Helper function for [wp\_link\_pages()](wp_link_pages) . |
| [get\_the\_guid()](get_the_guid) wp-includes/post-template.php | Retrieves the Post Global Unique Identifier (guid). |
| [get\_the\_content()](get_the_content) wp-includes/post-template.php | Retrieves the post content. |
| [get\_the\_excerpt()](get_the_excerpt) wp-includes/post-template.php | Retrieves the post excerpt. |
| [has\_excerpt()](has_excerpt) wp-includes/post-template.php | Determines whether the post has a custom excerpt. |
| [get\_post\_class()](get_post_class) wp-includes/post-template.php | Retrieves an array of the class names for the post container element. |
| [get\_body\_class()](get_body_class) wp-includes/post-template.php | Retrieves an array of the class names for the body element. |
| [get\_the\_ID()](get_the_id) wp-includes/post-template.php | Retrieves the ID of the current item in the WordPress Loop. |
| [the\_title\_attribute()](the_title_attribute) wp-includes/post-template.php | Sanitizes the current title when retrieving or displaying. |
| [get\_the\_title()](get_the_title) wp-includes/post-template.php | Retrieves the post title. |
| [the\_guid()](the_guid) wp-includes/post-template.php | Displays the Post Global Unique Identifier (guid). |
| [get\_post\_galleries()](get_post_galleries) wp-includes/media.php | Retrieves galleries from the passed post’s content. |
| [wp\_prepare\_attachment\_for\_js()](wp_prepare_attachment_for_js) wp-includes/media.php | Prepares an attachment post object for JS, where it is expected to be JSON-encoded and fit into an Attachment model. |
| [wp\_enqueue\_media()](wp_enqueue_media) wp-includes/media.php | Enqueues all scripts, styles, settings, and templates necessary to use all media JS APIs. |
| [get\_attached\_media()](get_attached_media) wp-includes/media.php | Retrieves media attached to the passed post. |
| [wp\_video\_shortcode()](wp_video_shortcode) wp-includes/media.php | Builds the Video shortcode output. |
| [get\_attachment\_taxonomies()](get_attachment_taxonomies) wp-includes/media.php | Retrieves taxonomies attached to given the attachment. |
| [gallery\_shortcode()](gallery_shortcode) wp-includes/media.php | Builds the Gallery shortcode output. |
| [wp\_playlist\_shortcode()](wp_playlist_shortcode) wp-includes/media.php | Builds the Playlist shortcode output. |
| [wp\_audio\_shortcode()](wp_audio_shortcode) wp-includes/media.php | Builds the Audio shortcode output. |
| [wp\_get\_attachment\_image()](wp_get_attachment_image) wp-includes/media.php | Gets an HTML img element representing an image attachment. |
| [clean\_post\_cache()](clean_post_cache) wp-includes/post.php | Will clean the post in the cache. |
| [wp\_get\_post\_parent\_id()](wp_get_post_parent_id) wp-includes/post.php | Returns the ID of the post’s parent. |
| [set\_post\_thumbnail()](set_post_thumbnail) wp-includes/post.php | Sets the post thumbnail (featured image) for the given post. |
| [delete\_post\_thumbnail()](delete_post_thumbnail) wp-includes/post.php | Removes the thumbnail (featured image) from the given post. |
| [wp\_mime\_type\_icon()](wp_mime_type_icon) wp-includes/post.php | Retrieves the icon for a MIME type or attachment. |
| [wp\_delete\_attachment()](wp_delete_attachment) wp-includes/post.php | Trashes or deletes an attachment. |
| [wp\_get\_attachment\_metadata()](wp_get_attachment_metadata) wp-includes/post.php | Retrieves attachment metadata for attachment ID. |
| [wp\_update\_attachment\_metadata()](wp_update_attachment_metadata) wp-includes/post.php | Updates metadata for an attachment. |
| [wp\_get\_attachment\_url()](wp_get_attachment_url) wp-includes/post.php | Retrieves the URL for an attachment. |
| [wp\_get\_attachment\_thumb\_file()](wp_get_attachment_thumb_file) wp-includes/deprecated.php | Retrieves thumbnail for an attachment. |
| [get\_pung()](get_pung) wp-includes/post.php | Retrieves URLs already pinged for a post. |
| [get\_to\_ping()](get_to_ping) wp-includes/post.php | Retrieves URLs that need to be pinged. |
| [trackback\_url\_list()](trackback_url_list) wp-includes/post.php | Does trackbacks for a list of URLs. |
| [get\_page()](get_page) wp-includes/post.php | Retrieves page data given a page ID or page object. |
| [get\_page\_by\_path()](get_page_by_path) wp-includes/post.php | Retrieves a page given its path. |
| [get\_page\_by\_title()](get_page_by_title) wp-includes/post.php | Retrieves a page given its title. |
| [get\_page\_uri()](get_page_uri) wp-includes/post.php | Builds the URI path for a page. |
| [is\_local\_attachment()](is_local_attachment) wp-includes/post.php | Determines whether an attachment URI is local and really an attachment. |
| [wp\_publish\_post()](wp_publish_post) wp-includes/post.php | Publishes a post by transitioning the post status. |
| [check\_and\_publish\_future\_post()](check_and_publish_future_post) wp-includes/post.php | Publishes future post and make sure post ID has future post status. |
| [wp\_unique\_post\_slug()](wp_unique_post_slug) wp-includes/post.php | Computes a unique slug for the post, when given the desired slug and some post details. |
| [add\_ping()](add_ping) wp-includes/post.php | Adds a URL to those already pinged. |
| [wp\_untrash\_post\_comments()](wp_untrash_post_comments) wp-includes/post.php | Restores comments for a post from the Trash. |
| [wp\_insert\_post()](wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [wp\_update\_post()](wp_update_post) wp-includes/post.php | Updates a post with new post data. |
| [wp\_delete\_post()](wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [\_reset\_front\_page\_settings\_for\_post()](_reset_front_page_settings_for_post) wp-includes/post.php | Resets the page\_on\_front, show\_on\_front, and page\_for\_post settings when a linked page is deleted or trashed. |
| [wp\_trash\_post()](wp_trash_post) wp-includes/post.php | Moves a post or page to the Trash |
| [wp\_untrash\_post()](wp_untrash_post) wp-includes/post.php | Restores a post from the Trash. |
| [wp\_trash\_post\_comments()](wp_trash_post_comments) wp-includes/post.php | Moves comments for a post to the Trash. |
| [get\_post\_ancestors()](get_post_ancestors) wp-includes/post.php | Retrieves the IDs of the ancestors of a post. |
| [get\_post\_field()](get_post_field) wp-includes/post.php | Retrieves data from a post field based on Post ID. |
| [get\_post\_mime\_type()](get_post_mime_type) wp-includes/post.php | Retrieves the mime type of an attachment based on the ID. |
| [get\_post\_status()](get_post_status) wp-includes/post.php | Retrieves the post status based on the post ID. |
| [get\_post\_type()](get_post_type) wp-includes/post.php | Retrieves the post type of the current post or of a given post. |
| [update\_attached\_file()](update_attached_file) wp-includes/post.php | Updates attachment file path based on attachment ID. |
| [url\_to\_postid()](url_to_postid) wp-includes/rewrite.php | Examines a URL and try to determine the post ID it represents. |
| [redirect\_canonical()](redirect_canonical) wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| [\_wp\_put\_post\_revision()](_wp_put_post_revision) wp-includes/revision.php | Inserts post data into the posts table as a post revision. |
| [wp\_get\_post\_revision()](wp_get_post_revision) wp-includes/revision.php | Gets a post revision. |
| [wp\_get\_post\_revisions()](wp_get_post_revisions) wp-includes/revision.php | Returns all revisions of specified post. |
| [\_wp\_preview\_terms\_filter()](_wp_preview_terms_filter) wp-includes/revision.php | Filters terms lookup to set the post format. |
| [\_wp\_post\_revision\_fields()](_wp_post_revision_fields) wp-includes/revision.php | Determines which fields of posts are to be saved in revisions. |
| [wp\_save\_post\_revision()](wp_save_post_revision) wp-includes/revision.php | Creates a revision for the current version of a post. |
| [wp\_get\_post\_autosave()](wp_get_post_autosave) wp-includes/revision.php | Retrieves the autosaved data of the specified post. |
| [get\_blog\_post()](get_blog_post) wp-includes/ms-functions.php | Gets a blog post from any site on the network. |
| [get\_post\_format()](get_post_format) wp-includes/post-formats.php | Retrieve the format slug for a post |
| [set\_post\_format()](set_post_format) wp-includes/post-formats.php | Assign a format to a post |
| [get\_the\_author\_posts()](get_the_author_posts) wp-includes/author-template.php | Retrieves the number of posts by the author of the current post. |
| [get\_the\_modified\_author()](get_the_modified_author) wp-includes/author-template.php | Retrieves the author who last edited the current post. |
| [\_update\_blog\_date\_on\_post\_delete()](_update_blog_date_on_post_delete) wp-includes/ms-blogs.php | Handler for updating the current site’s last updated date when a published post is deleted. |
| [wp\_setup\_nav\_menu\_item()](wp_setup_nav_menu_item) wp-includes/nav-menu.php | Decorates a menu item object with the shared navigation menu item properties. |
| [wp\_update\_nav\_menu\_item()](wp_update_nav_menu_item) wp-includes/nav-menu.php | Saves the properties of a menu item or create a new one. |
| [wp\_xmlrpc\_server::mt\_getPostCategories()](../classes/wp_xmlrpc_server/mt_getpostcategories) wp-includes/class-wp-xmlrpc-server.php | Retrieve post categories. |
| [wp\_xmlrpc\_server::mt\_setPostCategories()](../classes/wp_xmlrpc_server/mt_setpostcategories) wp-includes/class-wp-xmlrpc-server.php | Sets categories for a post. |
| [wp\_xmlrpc\_server::mt\_getTrackbackPings()](../classes/wp_xmlrpc_server/mt_gettrackbackpings) wp-includes/class-wp-xmlrpc-server.php | Retrieve trackbacks sent to a given post. |
| [wp\_xmlrpc\_server::mt\_publishPost()](../classes/wp_xmlrpc_server/mt_publishpost) wp-includes/class-wp-xmlrpc-server.php | Sets a post’s publish status to ‘publish’. |
| [wp\_xmlrpc\_server::pingback\_ping()](../classes/wp_xmlrpc_server/pingback_ping) wp-includes/class-wp-xmlrpc-server.php | Retrieves a pingback and registers it. |
| [wp\_xmlrpc\_server::pingback\_extensions\_getPingbacks()](../classes/wp_xmlrpc_server/pingback_extensions_getpingbacks) wp-includes/class-wp-xmlrpc-server.php | Retrieve array of URLs that pingbacked the given URL. |
| [wp\_xmlrpc\_server::mw\_editPost()](../classes/wp_xmlrpc_server/mw_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post. |
| [wp\_xmlrpc\_server::mw\_getPost()](../classes/wp_xmlrpc_server/mw_getpost) wp-includes/class-wp-xmlrpc-server.php | Retrieve post. |
| [wp\_xmlrpc\_server::mw\_newMediaObject()](../classes/wp_xmlrpc_server/mw_newmediaobject) wp-includes/class-wp-xmlrpc-server.php | Uploads a file, following your settings. |
| [wp\_xmlrpc\_server::blogger\_getPost()](../classes/wp_xmlrpc_server/blogger_getpost) wp-includes/class-wp-xmlrpc-server.php | Retrieve post. |
| [wp\_xmlrpc\_server::blogger\_editPost()](../classes/wp_xmlrpc_server/blogger_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post. |
| [wp\_xmlrpc\_server::blogger\_deletePost()](../classes/wp_xmlrpc_server/blogger_deletepost) wp-includes/class-wp-xmlrpc-server.php | Remove a post. |
| [wp\_xmlrpc\_server::wp\_getMediaItem()](../classes/wp_xmlrpc_server/wp_getmediaitem) wp-includes/class-wp-xmlrpc-server.php | Retrieve a media item by ID |
| [wp\_xmlrpc\_server::wp\_getRevisions()](../classes/wp_xmlrpc_server/wp_getrevisions) wp-includes/class-wp-xmlrpc-server.php | Retrieve revisions for a specific post. |
| [wp\_xmlrpc\_server::wp\_restoreRevision()](../classes/wp_xmlrpc_server/wp_restorerevision) wp-includes/class-wp-xmlrpc-server.php | Restore a post revision |
| [wp\_xmlrpc\_server::wp\_newComment()](../classes/wp_xmlrpc_server/wp_newcomment) wp-includes/class-wp-xmlrpc-server.php | Create new comment. |
| [wp\_xmlrpc\_server::wp\_getCommentCount()](../classes/wp_xmlrpc_server/wp_getcommentcount) wp-includes/class-wp-xmlrpc-server.php | Retrieve comment count. |
| [wp\_xmlrpc\_server::wp\_deletePage()](../classes/wp_xmlrpc_server/wp_deletepage) wp-includes/class-wp-xmlrpc-server.php | Delete page. |
| [wp\_xmlrpc\_server::wp\_editPage()](../classes/wp_xmlrpc_server/wp_editpage) wp-includes/class-wp-xmlrpc-server.php | Edit page. |
| [wp\_xmlrpc\_server::wp\_getPage()](../classes/wp_xmlrpc_server/wp_getpage) wp-includes/class-wp-xmlrpc-server.php | Retrieve page. |
| [wp\_xmlrpc\_server::\_prepare\_page()](../classes/wp_xmlrpc_server/_prepare_page) wp-includes/class-wp-xmlrpc-server.php | Prepares page data for return in an XML-RPC object. |
| [wp\_xmlrpc\_server::\_insert\_post()](../classes/wp_xmlrpc_server/_insert_post) wp-includes/class-wp-xmlrpc-server.php | Helper method for wp\_newPost() and wp\_editPost(), containing shared logic. |
| [wp\_xmlrpc\_server::wp\_editPost()](../classes/wp_xmlrpc_server/wp_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post for any registered post type. |
| [wp\_xmlrpc\_server::wp\_deletePost()](../classes/wp_xmlrpc_server/wp_deletepost) wp-includes/class-wp-xmlrpc-server.php | Delete a post for any registered post type. |
| [wp\_xmlrpc\_server::wp\_getPost()](../classes/wp_xmlrpc_server/wp_getpost) wp-includes/class-wp-xmlrpc-server.php | Retrieve a post. |
| [wp\_xmlrpc\_server::\_prepare\_post()](../classes/wp_xmlrpc_server/_prepare_post) wp-includes/class-wp-xmlrpc-server.php | Prepares post data for return in an XML-RPC object. |
| [WP\_Customize\_Control::render\_content()](../classes/wp_customize_control/render_content) wp-includes/class-wp-customize-control.php | Render the control’s content. |
| [get\_post\_reply\_link()](get_post_reply_link) wp-includes/comment-template.php | Retrieves HTML content for reply to post link. |
| [comment\_form()](comment_form) wp-includes/comment-template.php | Outputs a complete commenting form for use within a template. |
| [comments\_open()](comments_open) wp-includes/comment-template.php | Determines whether the current post is open for comments. |
| [pings\_open()](pings_open) wp-includes/comment-template.php | Determines whether the current post is open for pings. |
| [wp\_comment\_form\_unfiltered\_html\_nonce()](wp_comment_form_unfiltered_html_nonce) wp-includes/comment-template.php | Displays form token for unfiltered comments. |
| [get\_comment\_reply\_link()](get_comment_reply_link) wp-includes/comment-template.php | Retrieves HTML content for reply to comment link. |
| [get\_comments\_number()](get_comments_number) wp-includes/comment-template.php | Retrieves the amount of comments a post has. |
| [get\_comment\_class()](get_comment_class) wp-includes/comment-template.php | Returns the classes for the comment div as an array. |
| [\_close\_comments\_for\_old\_post()](_close_comments_for_old_post) wp-includes/comment.php | Closes comments on an old post. Hooked to comments\_open and pings\_open. |
| [wp\_update\_comment()](wp_update_comment) wp-includes/comment.php | Updates an existing comment in the database. |
| [wp\_update\_comment\_count\_now()](wp_update_comment_count_now) wp-includes/comment.php | Updates the comment count for the post. |
| [do\_trackbacks()](do_trackbacks) wp-includes/comment.php | Performs trackbacks. |
| [pingback()](pingback) wp-includes/comment.php | Pings back the links found in a post. |
| [\_WP\_Editors::editor\_settings()](../classes/_wp_editors/editor_settings) wp-includes/class-wp-editor.php | |
| Version | Description |
| --- | --- |
| [1.5.1](https://developer.wordpress.org/reference/since/1.5.1/) | Introduced. |
| programming_docs |
wordpress _copy_image_file( int $attachment_id ): string|false \_copy\_image\_file( int $attachment\_id ): string|false
========================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Copies an existing image file.
`$attachment_id` int Required Attachment ID. string|false New file path on success, false on failure.
File: `wp-admin/includes/image.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/image.php/)
```
function _copy_image_file( $attachment_id ) {
$dst_file = get_attached_file( $attachment_id );
$src_file = $dst_file;
if ( ! file_exists( $src_file ) ) {
$src_file = _load_image_to_edit_path( $attachment_id );
}
if ( $src_file ) {
$dst_file = str_replace( wp_basename( $dst_file ), 'copy-' . wp_basename( $dst_file ), $dst_file );
$dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), wp_basename( $dst_file ) );
/*
* The directory containing the original file may no longer
* exist when using a replication plugin.
*/
wp_mkdir_p( dirname( $dst_file ) );
if ( ! copy( $src_file, $dst_file ) ) {
$dst_file = false;
}
} else {
$dst_file = false;
}
return $dst_file;
}
```
| Uses | Description |
| --- | --- |
| [\_load\_image\_to\_edit\_path()](_load_image_to_edit_path) wp-admin/includes/image.php | Retrieves the path or URL of an attachment’s attached file. |
| [wp\_unique\_filename()](wp_unique_filename) wp-includes/functions.php | Gets a filename that is sanitized and unique for the given directory. |
| [wp\_mkdir\_p()](wp_mkdir_p) wp-includes/functions.php | Recursive directory creation based on full path. |
| [get\_attached\_file()](get_attached_file) wp-includes/post.php | Retrieves attached file path based on attachment ID. |
| [wp\_basename()](wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::step\_3()](../classes/custom_image_header/step_3) wp-admin/includes/class-custom-image-header.php | Display third step of custom header image page. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress get_allowed_block_types( WP_Block_Editor_Context $block_editor_context ): bool|string[] get\_allowed\_block\_types( WP\_Block\_Editor\_Context $block\_editor\_context ): bool|string[]
===============================================================================================
Gets the list of allowed block types to use in the block editor.
`$block_editor_context` [WP\_Block\_Editor\_Context](../classes/wp_block_editor_context) Required The current block editor context. bool|string[] Array of block type slugs, or boolean to enable/disable all.
File: `wp-includes/block-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/block-editor.php/)
```
function get_allowed_block_types( $block_editor_context ) {
$allowed_block_types = true;
/**
* Filters the allowed block types for all editor types.
*
* @since 5.8.0
*
* @param bool|string[] $allowed_block_types Array of block type slugs, or boolean to enable/disable all.
* Default true (all registered block types supported).
* @param WP_Block_Editor_Context $block_editor_context The current block editor context.
*/
$allowed_block_types = apply_filters( 'allowed_block_types_all', $allowed_block_types, $block_editor_context );
if ( ! empty( $block_editor_context->post ) ) {
$post = $block_editor_context->post;
/**
* Filters the allowed block types for the editor.
*
* @since 5.0.0
* @deprecated 5.8.0 Use the {@see 'allowed_block_types_all'} filter instead.
*
* @param bool|string[] $allowed_block_types Array of block type slugs, or boolean to enable/disable all.
* Default true (all registered block types supported)
* @param WP_Post $post The post resource data.
*/
$allowed_block_types = apply_filters_deprecated( 'allowed_block_types', array( $allowed_block_types, $post ), '5.8.0', 'allowed_block_types_all' );
}
return $allowed_block_types;
}
```
[apply\_filters\_deprecated( 'allowed\_block\_types', bool|string[] $allowed\_block\_types, WP\_Post $post )](../hooks/allowed_block_types)
Filters the allowed block types for the editor.
[apply\_filters( 'allowed\_block\_types\_all', bool|string[] $allowed\_block\_types, WP\_Block\_Editor\_Context $block\_editor\_context )](../hooks/allowed_block_types_all)
Filters the allowed block types for all editor types.
| Uses | Description |
| --- | --- |
| [apply\_filters\_deprecated()](apply_filters_deprecated) wp-includes/plugin.php | Fires functions attached to a deprecated filter hook. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [get\_block\_editor\_settings()](get_block_editor_settings) wp-includes/block-editor.php | Returns the contextualized block editor settings for a selected editor context. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress _get_component_from_parsed_url_array( array|false $url_parts, int $component = -1 ): mixed \_get\_component\_from\_parsed\_url\_array( array|false $url\_parts, int $component = -1 ): mixed
=================================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Retrieve a specific component from a parsed URL array.
`$url_parts` array|false Required The parsed URL. Can be false if the URL failed to parse. `$component` int Optional The specific component to retrieve. Use one of the PHP predefined constants to specify which one.
Defaults to -1 (= return all parts as an array). Default: `-1`
mixed False on parse failure; Array of URL components on success; When a specific component has been requested: null if the component doesn't exist in the given URL; a string or - in the case of PHP\_URL\_PORT - integer when it does. See parse\_url()'s return values.
File: `wp-includes/http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/http.php/)
```
function _get_component_from_parsed_url_array( $url_parts, $component = -1 ) {
if ( -1 === $component ) {
return $url_parts;
}
$key = _wp_translate_php_url_constant_to_key( $component );
if ( false !== $key && is_array( $url_parts ) && isset( $url_parts[ $key ] ) ) {
return $url_parts[ $key ];
} else {
return null;
}
}
```
| Uses | Description |
| --- | --- |
| [\_wp\_translate\_php\_url\_constant\_to\_key()](_wp_translate_php_url_constant_to_key) wp-includes/http.php | Translate a PHP\_URL\_\* constant to the named array keys PHP uses. |
| Used By | Description |
| --- | --- |
| [wp\_parse\_url()](wp_parse_url) wp-includes/http.php | A wrapper for PHP’s parse\_url() function that handles consistency in the return values across PHP versions. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress rest_is_array( mixed $maybe_array ): bool rest\_is\_array( mixed $maybe\_array ): bool
============================================
Determines if a given value is array-like.
`$maybe_array` mixed Required The value being evaluated. bool
File: `wp-includes/rest-api.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api.php/)
```
function rest_is_array( $maybe_array ) {
if ( is_scalar( $maybe_array ) ) {
$maybe_array = wp_parse_list( $maybe_array );
}
return wp_is_numeric_array( $maybe_array );
}
```
| Uses | Description |
| --- | --- |
| [wp\_parse\_list()](wp_parse_list) wp-includes/functions.php | Converts a comma- or space-separated list of scalar values to an array. |
| [wp\_is\_numeric\_array()](wp_is_numeric_array) wp-includes/functions.php | Determines if the variable is a numeric-indexed array. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::prepare\_tax\_query()](../classes/wp_rest_posts_controller/prepare_tax_query) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares the ‘tax\_query’ for a collection of posts. |
| [rest\_validate\_array\_value\_from\_schema()](rest_validate_array_value_from_schema) wp-includes/rest-api.php | Validates an array value based on a schema. |
| [rest\_filter\_response\_by\_context()](rest_filter_response_by_context) wp-includes/rest-api.php | Filters the response to remove any fields not available in the given context. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress _get_dropins(): array[] \_get\_dropins(): array[]
=========================
Returns drop-ins that WordPress uses.
Includes Multisite drop-ins only when [is\_multisite()](is_multisite)
array[] Key is file name. The value is an array, with the first value the purpose of the drop-in and the second value the name of the constant that must be true for the drop-in to be used, or true if no constant is required.
File: `wp-admin/includes/plugin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/plugin.php/)
```
function _get_dropins() {
$dropins = array(
'advanced-cache.php' => array( __( 'Advanced caching plugin.' ), 'WP_CACHE' ), // WP_CACHE
'db.php' => array( __( 'Custom database class.' ), true ), // Auto on load.
'db-error.php' => array( __( 'Custom database error message.' ), true ), // Auto on error.
'install.php' => array( __( 'Custom installation script.' ), true ), // Auto on installation.
'maintenance.php' => array( __( 'Custom maintenance message.' ), true ), // Auto on maintenance.
'object-cache.php' => array( __( 'External object cache.' ), true ), // Auto on load.
'php-error.php' => array( __( 'Custom PHP error message.' ), true ), // Auto on error.
'fatal-error-handler.php' => array( __( 'Custom PHP fatal error handler.' ), true ), // Auto on error.
);
if ( is_multisite() ) {
$dropins['sunrise.php'] = array( __( 'Executed before Multisite is loaded.' ), 'SUNRISE' ); // SUNRISE
$dropins['blog-deleted.php'] = array( __( 'Custom site deleted message.' ), true ); // Auto on deleted blog.
$dropins['blog-inactive.php'] = array( __( 'Custom site inactive message.' ), true ); // Auto on inactive blog.
$dropins['blog-suspended.php'] = array( __( 'Custom site suspended message.' ), true ); // Auto on archived or spammed blog.
}
return $dropins;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_multisite()](is_multisite) wp-includes/load.php | If Multisite is enabled. |
| Used By | Description |
| --- | --- |
| [WP\_Debug\_Data::debug\_data()](../classes/wp_debug_data/debug_data) wp-admin/includes/class-wp-debug-data.php | Static function for generating site debug data when required. |
| [WP\_Plugins\_List\_Table::single\_row()](../classes/wp_plugins_list_table/single_row) wp-admin/includes/class-wp-plugins-list-table.php | |
| [get\_dropins()](get_dropins) wp-admin/includes/plugin.php | Checks the wp-content directory and retrieve all drop-ins with any plugin data. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress install_search_form( bool $deprecated = true ) install\_search\_form( bool $deprecated = true )
================================================
Displays a search form for searching plugins.
`$deprecated` bool Optional Not used. Default: `true`
File: `wp-admin/includes/plugin-install.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/plugin-install.php/)
```
function install_search_form( $deprecated = true ) {
$type = isset( $_REQUEST['type'] ) ? wp_unslash( $_REQUEST['type'] ) : 'term';
$term = isset( $_REQUEST['s'] ) ? wp_unslash( $_REQUEST['s'] ) : '';
?>
<form class="search-form search-plugins" method="get">
<input type="hidden" name="tab" value="search" />
<label class="screen-reader-text" for="typeselector"><?php _e( 'Search plugins by:' ); ?></label>
<select name="type" id="typeselector">
<option value="term"<?php selected( 'term', $type ); ?>><?php _e( 'Keyword' ); ?></option>
<option value="author"<?php selected( 'author', $type ); ?>><?php _e( 'Author' ); ?></option>
<option value="tag"<?php selected( 'tag', $type ); ?>><?php _ex( 'Tag', 'Plugin Installer' ); ?></option>
</select>
<label class="screen-reader-text" for="search-plugins"><?php _e( 'Search Plugins' ); ?></label>
<input type="search" name="s" id="search-plugins" value="<?php echo esc_attr( $term ); ?>" class="wp-filter-search" placeholder="<?php esc_attr_e( 'Search plugins...' ); ?>" />
<?php submit_button( __( 'Search Plugins' ), 'hide-if-js', false, false, array( 'id' => 'search-submit' ) ); ?>
</form>
<?php
}
```
| Uses | Description |
| --- | --- |
| [submit\_button()](submit_button) wp-admin/includes/template.php | Echoes a submit button, with provided text and appropriate class(es). |
| [\_ex()](_ex) wp-includes/l10n.php | Displays translated string with gettext context. |
| [esc\_attr\_e()](esc_attr_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in an attribute. |
| [selected()](selected) wp-includes/general-template.php | Outputs the HTML selected attribute. |
| [\_e()](_e) wp-includes/l10n.php | Displays translated text. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_unslash()](wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Used By | Description |
| --- | --- |
| [WP\_Plugin\_Install\_List\_Table::views()](../classes/wp_plugin_install_list_table/views) wp-admin/includes/class-wp-plugin-install-list-table.php | Overrides parent views so we can use the filter bar display. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | The `$type_selector` parameter was deprecated. |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress install_themes_upload() install\_themes\_upload()
=========================
Displays a form to upload themes from zip files.
File: `wp-admin/includes/theme-install.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/theme-install.php/)
```
function install_themes_upload() {
?>
<p class="install-help"><?php _e( 'If you have a theme in a .zip format, you may install or update it by uploading it here.' ); ?></p>
<form method="post" enctype="multipart/form-data" class="wp-upload-form" action="<?php echo esc_url( self_admin_url( 'update.php?action=upload-theme' ) ); ?>">
<?php wp_nonce_field( 'theme-upload' ); ?>
<label class="screen-reader-text" for="themezip"><?php _e( 'Theme zip file' ); ?></label>
<input type="file" id="themezip" name="themezip" accept=".zip" />
<?php submit_button( __( 'Install Now' ), '', 'install-theme-submit', false ); ?>
</form>
<?php
}
```
| Uses | Description |
| --- | --- |
| [submit\_button()](submit_button) wp-admin/includes/template.php | Echoes a submit button, with provided text and appropriate class(es). |
| [wp\_nonce\_field()](wp_nonce_field) wp-includes/functions.php | Retrieves or display nonce hidden field for forms. |
| [self\_admin\_url()](self_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for either the current site or the network depending on context. |
| [\_e()](_e) wp-includes/l10n.php | Displays translated text. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress wpmu_welcome_notification( int $blog_id, int $user_id, string $password, string $title, array $meta = array() ): bool wpmu\_welcome\_notification( int $blog\_id, int $user\_id, string $password, string $title, array $meta = array() ): bool
=========================================================================================================================
Notifies the site administrator that their site activation was successful.
Filter [‘wpmu\_welcome\_notification’](../hooks/wpmu_welcome_notification) to disable or bypass.
Filter [‘update\_welcome\_email’](../hooks/update_welcome_email) and [‘update\_welcome\_subject’](../hooks/update_welcome_subject) to modify the content and subject line of the notification email.
`$blog_id` int Required Site ID. `$user_id` int Required User ID. `$password` string Required User password, or "N/A" if the user account is not new. `$title` string Required Site title. `$meta` array Optional Signup meta data. By default, contains the requested privacy setting and lang\_id. Default: `array()`
bool Whether the email notification was sent.
File: `wp-includes/ms-functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-functions.php/)
```
function wpmu_welcome_notification( $blog_id, $user_id, $password, $title, $meta = array() ) {
$current_network = get_network();
/**
* Filters whether to bypass the welcome email sent to the site administrator after site activation.
*
* Returning false disables the welcome email.
*
* @since MU (3.0.0)
*
* @param int|false $blog_id Site ID, or false to prevent the email from sending.
* @param int $user_id User ID of the site administrator.
* @param string $password User password, or "N/A" if the user account is not new.
* @param string $title Site title.
* @param array $meta Signup meta data. By default, contains the requested privacy setting and lang_id.
*/
if ( ! apply_filters( 'wpmu_welcome_notification', $blog_id, $user_id, $password, $title, $meta ) ) {
return false;
}
$user = get_userdata( $user_id );
$switched_locale = switch_to_locale( get_user_locale( $user ) );
$welcome_email = get_site_option( 'welcome_email' );
if ( false == $welcome_email ) {
/* translators: Do not translate USERNAME, SITE_NAME, BLOG_URL, PASSWORD: those are placeholders. */
$welcome_email = __(
'Howdy USERNAME,
Your new SITE_NAME site has been successfully set up at:
BLOG_URL
You can log in to the administrator account with the following information:
Username: USERNAME
Password: PASSWORD
Log in here: BLOG_URLwp-login.php
We hope you enjoy your new site. Thanks!
--The Team @ SITE_NAME'
);
}
$url = get_blogaddress_by_id( $blog_id );
$welcome_email = str_replace( 'SITE_NAME', $current_network->site_name, $welcome_email );
$welcome_email = str_replace( 'BLOG_TITLE', $title, $welcome_email );
$welcome_email = str_replace( 'BLOG_URL', $url, $welcome_email );
$welcome_email = str_replace( 'USERNAME', $user->user_login, $welcome_email );
$welcome_email = str_replace( 'PASSWORD', $password, $welcome_email );
/**
* Filters the content of the welcome email sent to the site administrator after site activation.
*
* Content should be formatted for transmission via wp_mail().
*
* @since MU (3.0.0)
*
* @param string $welcome_email Message body of the email.
* @param int $blog_id Site ID.
* @param int $user_id User ID of the site administrator.
* @param string $password User password, or "N/A" if the user account is not new.
* @param string $title Site title.
* @param array $meta Signup meta data. By default, contains the requested privacy setting and lang_id.
*/
$welcome_email = apply_filters( 'update_welcome_email', $welcome_email, $blog_id, $user_id, $password, $title, $meta );
$admin_email = get_site_option( 'admin_email' );
if ( '' === $admin_email ) {
$admin_email = 'support@' . wp_parse_url( network_home_url(), PHP_URL_HOST );
}
$from_name = ( '' !== get_site_option( 'site_name' ) ) ? esc_html( get_site_option( 'site_name' ) ) : 'WordPress';
$message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . 'Content-Type: text/plain; charset="' . get_option( 'blog_charset' ) . "\"\n";
$message = $welcome_email;
if ( empty( $current_network->site_name ) ) {
$current_network->site_name = 'WordPress';
}
/* translators: New site notification email subject. 1: Network title, 2: New site title. */
$subject = __( 'New %1$s Site: %2$s' );
/**
* Filters the subject of the welcome email sent to the site administrator after site activation.
*
* @since MU (3.0.0)
*
* @param string $subject Subject of the email.
*/
$subject = apply_filters( 'update_welcome_subject', sprintf( $subject, $current_network->site_name, wp_unslash( $title ) ) );
wp_mail( $user->user_email, wp_specialchars_decode( $subject ), $message, $message_headers );
if ( $switched_locale ) {
restore_previous_locale();
}
return true;
}
```
[apply\_filters( 'update\_welcome\_email', string $welcome\_email, int $blog\_id, int $user\_id, string $password, string $title, array $meta )](../hooks/update_welcome_email)
Filters the content of the welcome email sent to the site administrator after site activation.
[apply\_filters( 'update\_welcome\_subject', string $subject )](../hooks/update_welcome_subject)
Filters the subject of the welcome email sent to the site administrator after site activation.
[apply\_filters( 'wpmu\_welcome\_notification', int|false $blog\_id, int $user\_id, string $password, string $title, array $meta )](../hooks/wpmu_welcome_notification)
Filters whether to bypass the welcome email sent to the site administrator after site activation.
| Uses | Description |
| --- | --- |
| [restore\_previous\_locale()](restore_previous_locale) wp-includes/l10n.php | Restores the translations according to the previous locale. |
| [switch\_to\_locale()](switch_to_locale) wp-includes/l10n.php | Switches the translations according to the given locale. |
| [get\_user\_locale()](get_user_locale) wp-includes/l10n.php | Retrieves the locale of a user. |
| [get\_network()](get_network) wp-includes/ms-network.php | Retrieves network data given a network ID or network object. |
| [wp\_parse\_url()](wp_parse_url) wp-includes/http.php | A wrapper for PHP’s parse\_url() function that handles consistency in the return values across PHP versions. |
| [wp\_specialchars\_decode()](wp_specialchars_decode) wp-includes/formatting.php | Converts a number of HTML entities into their special characters. |
| [wp\_mail()](wp_mail) wp-includes/pluggable.php | Sends an email, similar to PHP’s mail function. |
| [network\_home\_url()](network_home_url) wp-includes/link-template.php | Retrieves the home URL for the current network. |
| [get\_blogaddress\_by\_id()](get_blogaddress_by_id) wp-includes/ms-blogs.php | Get a full blog URL, given a blog ID. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_unslash()](wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [get\_userdata()](get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_site\_option()](get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [MU (3.0.0)](https://developer.wordpress.org/reference/since/mu.3.0.0/) | Introduced. |
| programming_docs |
wordpress wp_parse_widget_id( string $id ): array wp\_parse\_widget\_id( string $id ): array
==========================================
Converts a widget ID into its id\_base and number components.
`$id` string Required Widget ID. array Array containing a widget's id\_base and number components.
File: `wp-includes/widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets.php/)
```
function wp_parse_widget_id( $id ) {
$parsed = array();
if ( preg_match( '/^(.+)-(\d+)$/', $id, $matches ) ) {
$parsed['id_base'] = $matches[1];
$parsed['number'] = (int) $matches[2];
} else {
// Likely an old single widget.
$parsed['id_base'] = $id;
}
return $parsed;
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Widgets\_Controller::prepare\_item\_for\_response()](../classes/wp_rest_widgets_controller/prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php | Prepares the widget for the REST response. |
| [WP\_REST\_Widgets\_Controller::update\_item()](../classes/wp_rest_widgets_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php | Updates an existing widget. |
| [WP\_REST\_Widgets\_Controller::delete\_item()](../classes/wp_rest_widgets_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php | Deletes a widget. |
| [WP\_REST\_Widgets\_Controller::save\_widget()](../classes/wp_rest_widgets_controller/save_widget) wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php | Saves the widget in the request object. |
| [WP\_REST\_Widget\_Types\_Controller::get\_widgets()](../classes/wp_rest_widget_types_controller/get_widgets) wp-includes/rest-api/endpoints/class-wp-rest-widget-types-controller.php | Normalize array of widgets. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress wp_can_install_language_pack(): bool wp\_can\_install\_language\_pack(): bool
========================================
Check if WordPress has access to the filesystem without asking for credentials.
bool Returns true on success, false on failure.
File: `wp-admin/includes/translation-install.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/translation-install.php/)
```
function wp_can_install_language_pack() {
if ( ! wp_is_file_mod_allowed( 'can_install_language_pack' ) ) {
return false;
}
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
$skin = new Automatic_Upgrader_Skin;
$upgrader = new Language_Pack_Upgrader( $skin );
$upgrader->init();
$check = $upgrader->fs_connect( array( WP_CONTENT_DIR, WP_LANG_DIR ) );
if ( ! $check || is_wp_error( $check ) ) {
return false;
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [wp\_is\_file\_mod\_allowed()](wp_is_file_mod_allowed) wp-includes/load.php | Determines whether file modifications are allowed. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress user_can_richedit(): bool user\_can\_richedit(): bool
===========================
Determines whether the user can access the visual editor.
Checks if the user can access the visual editor and that it’s supported by the user’s browser.
bool True if the user can access the visual editor, false otherwise.
File: `wp-includes/general-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/general-template.php/)
```
function user_can_richedit() {
global $wp_rich_edit, $is_gecko, $is_opera, $is_safari, $is_chrome, $is_IE, $is_edge;
if ( ! isset( $wp_rich_edit ) ) {
$wp_rich_edit = false;
if ( 'true' === get_user_option( 'rich_editing' ) || ! is_user_logged_in() ) { // Default to 'true' for logged out users.
if ( $is_safari ) {
$wp_rich_edit = ! wp_is_mobile() || ( preg_match( '!AppleWebKit/(\d+)!', $_SERVER['HTTP_USER_AGENT'], $match ) && (int) $match[1] >= 534 );
} elseif ( $is_IE ) {
$wp_rich_edit = ( strpos( $_SERVER['HTTP_USER_AGENT'], 'Trident/7.0;' ) !== false );
} elseif ( $is_gecko || $is_chrome || $is_edge || ( $is_opera && ! wp_is_mobile() ) ) {
$wp_rich_edit = true;
}
}
}
/**
* Filters whether the user can access the visual editor.
*
* @since 2.1.0
*
* @param bool $wp_rich_edit Whether the user can access the visual editor.
*/
return apply_filters( 'user_can_richedit', $wp_rich_edit );
}
```
[apply\_filters( 'user\_can\_richedit', bool $wp\_rich\_edit )](../hooks/user_can_richedit)
Filters whether the user can access the visual editor.
| Uses | Description |
| --- | --- |
| [wp\_is\_mobile()](wp_is_mobile) wp-includes/vars.php | Test if the current browser runs on a mobile device (smart phone, tablet, etc.) |
| [get\_user\_option()](get_user_option) wp-includes/user.php | Retrieves user option that can be either per Site or per Network. |
| [is\_user\_logged\_in()](is_user_logged_in) wp-includes/pluggable.php | Determines whether the current visitor is a logged in user. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [\_WP\_Editors::print\_default\_editor\_scripts()](../classes/_wp_editors/print_default_editor_scripts) wp-includes/class-wp-editor.php | Print (output) all editor scripts and default settings. |
| [get\_media\_item()](get_media_item) wp-admin/includes/media.php | Retrieves HTML form for modifying the image attachment. |
| [get\_compat\_media\_markup()](get_compat_media_markup) wp-admin/includes/media.php | |
| [wp\_default\_editor()](wp_default_editor) wp-includes/general-template.php | Finds out which editor should be displayed by default. |
| [WP\_Widget\_Text::form()](../classes/wp_widget_text/form) wp-includes/widgets/class-wp-widget-text.php | Outputs the Text widget settings form. |
| [sanitize\_post\_field()](sanitize_post_field) wp-includes/post.php | Sanitizes a post field based on context. |
| [\_WP\_Editors::parse\_settings()](../classes/_wp_editors/parse_settings) wp-includes/class-wp-editor.php | Parse default arguments for the editor instance. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress permalink_link() permalink\_link()
=================
This function has been deprecated. Use [the\_permalink()](the_permalink) instead.
Print the permalink of the current post in the loop.
* [the\_permalink()](the_permalink)
File: `wp-includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/deprecated.php/)
```
function permalink_link() {
_deprecated_function( __FUNCTION__, '1.2.0', 'the_permalink()' );
the_permalink();
}
```
| Uses | Description |
| --- | --- |
| [the\_permalink()](the_permalink) wp-includes/link-template.php | Displays the permalink for the current post. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [1.2.0](https://developer.wordpress.org/reference/since/1.2.0/) | Use [the\_permalink()](the_permalink) |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress wp_update_network_counts( int|null $network_id = null ) wp\_update\_network\_counts( int|null $network\_id = null )
===========================================================
Updates the network-wide counts for the current network.
`$network_id` int|null Optional ID of the network. Default is the current network. Default: `null`
File: `wp-includes/ms-functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-functions.php/)
```
function wp_update_network_counts( $network_id = null ) {
wp_update_network_user_counts( $network_id );
wp_update_network_site_counts( $network_id );
}
```
| Uses | Description |
| --- | --- |
| [wp\_update\_network\_user\_counts()](wp_update_network_user_counts) wp-includes/ms-functions.php | Updates the network-wide user count. |
| [wp\_update\_network\_site\_counts()](wp_update_network_site_counts) wp-includes/ms-functions.php | Updates the network-wide site count. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | The `$network_id` parameter has been added. |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress wp_send_new_user_notifications( int $user_id, string $notify = 'both' ) wp\_send\_new\_user\_notifications( int $user\_id, string $notify = 'both' )
============================================================================
Initiates email notifications related to the creation of new users.
Notifications are sent both to the site admin and to the newly created user.
`$user_id` int Required ID of the newly created user. `$notify` string Optional Type of notification that should happen. Accepts `'admin'` or an empty string (admin only), `'user'`, or `'both'` (admin and user).
Default `'both'`. Default: `'both'`
File: `wp-includes/user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/user.php/)
```
function wp_send_new_user_notifications( $user_id, $notify = 'both' ) {
wp_new_user_notification( $user_id, null, $notify );
}
```
| Uses | Description |
| --- | --- |
| [wp\_new\_user\_notification()](wp_new_user_notification) wp-includes/pluggable.php | Emails login credentials to a newly-registered user. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Converted the `$notify` parameter to accept `'user'` for sending notifications only to the user created. |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress is_author( int|string|int[]|string[] $author = '' ): bool is\_author( int|string|int[]|string[] $author = '' ): bool
==========================================================
Determines whether the query is for an existing author archive page.
If the $author parameter is specified, this function will additionally check if the query is for one of the authors specified.
For more information on this and similar theme functions, check out the [Conditional Tags](https://developer.wordpress.org/themes/basics/conditional-tags/) article in the Theme Developer Handbook.
`$author` int|string|int[]|string[] Optional User ID, nickname, nicename, or array of such to check against. Default: `''`
bool Whether the query is for an existing author archive page.
File: `wp-includes/query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/query.php/)
```
function is_author( $author = '' ) {
global $wp_query;
if ( ! isset( $wp_query ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
return false;
}
return $wp_query->is_author( $author );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Query::is\_author()](../classes/wp_query/is_author) wp-includes/class-wp-query.php | Is the query for an existing author archive page? |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_doing\_it\_wrong()](_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Used By | Description |
| --- | --- |
| [rest\_get\_queried\_resource\_route()](rest_get_queried_resource_route) wp-includes/rest-api.php | Gets the REST route for the currently queried object. |
| [wp\_get\_document\_title()](wp_get_document_title) wp-includes/general-template.php | Returns document title for the current page. |
| [get\_the\_archive\_description()](get_the_archive_description) wp-includes/general-template.php | Retrieves the description for an author, post type, or term archive. |
| [get\_the\_archive\_title()](get_the_archive_title) wp-includes/general-template.php | Retrieves the archive title based on the queried object. |
| [feed\_links\_extra()](feed_links_extra) wp-includes/general-template.php | Displays the links to the extra feeds such as category feeds. |
| [wp\_title()](wp_title) wp-includes/general-template.php | Displays or retrieves page title for all areas of blog. |
| [WP::handle\_404()](../classes/wp/handle_404) wp-includes/class-wp.php | Set the Headers for 404, if nothing is found for requested URL. |
| [wp\_dropdown\_users()](wp_dropdown_users) wp-includes/user.php | Creates dropdown HTML content of users. |
| [get\_body\_class()](get_body_class) wp-includes/post-template.php | Retrieves an array of the class names for the body element. |
| [redirect\_canonical()](redirect_canonical) wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_uninitialize_site( int|WP_Site $site_id ): true|WP_Error wp\_uninitialize\_site( int|WP\_Site $site\_id ): true|WP\_Error
================================================================
Runs the uninitialization routine for a given site.
This process includes dropping the site’s database tables and deleting its uploads directory.
`$site_id` int|[WP\_Site](../classes/wp_site) Required Site ID or object. true|[WP\_Error](../classes/wp_error) True on success, or error object on failure.
File: `wp-includes/ms-site.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-site.php/)
```
function wp_uninitialize_site( $site_id ) {
global $wpdb;
if ( empty( $site_id ) ) {
return new WP_Error( 'site_empty_id', __( 'Site ID must not be empty.' ) );
}
$site = get_site( $site_id );
if ( ! $site ) {
return new WP_Error( 'site_invalid_id', __( 'Site with the ID does not exist.' ) );
}
if ( ! wp_is_site_initialized( $site ) ) {
return new WP_Error( 'site_already_uninitialized', __( 'The site appears to be already uninitialized.' ) );
}
$users = get_users(
array(
'blog_id' => $site->id,
'fields' => 'ids',
)
);
// Remove users from the site.
if ( ! empty( $users ) ) {
foreach ( $users as $user_id ) {
remove_user_from_blog( $user_id, $site->id );
}
}
$switch = false;
if ( get_current_blog_id() !== $site->id ) {
$switch = true;
switch_to_blog( $site->id );
}
$uploads = wp_get_upload_dir();
$tables = $wpdb->tables( 'blog' );
/**
* Filters the tables to drop when the site is deleted.
*
* @since MU (3.0.0)
*
* @param string[] $tables Array of names of the site tables to be dropped.
* @param int $site_id The ID of the site to drop tables for.
*/
$drop_tables = apply_filters( 'wpmu_drop_tables', $tables, $site->id );
foreach ( (array) $drop_tables as $table ) {
$wpdb->query( "DROP TABLE IF EXISTS `$table`" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
}
/**
* Filters the upload base directory to delete when the site is deleted.
*
* @since MU (3.0.0)
*
* @param string $basedir Uploads path without subdirectory. @see wp_upload_dir()
* @param int $site_id The site ID.
*/
$dir = apply_filters( 'wpmu_delete_blog_upload_dir', $uploads['basedir'], $site->id );
$dir = rtrim( $dir, DIRECTORY_SEPARATOR );
$top_dir = $dir;
$stack = array( $dir );
$index = 0;
while ( $index < count( $stack ) ) {
// Get indexed directory from stack.
$dir = $stack[ $index ];
// phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged
$dh = @opendir( $dir );
if ( $dh ) {
$file = @readdir( $dh );
while ( false !== $file ) {
if ( '.' === $file || '..' === $file ) {
$file = @readdir( $dh );
continue;
}
if ( @is_dir( $dir . DIRECTORY_SEPARATOR . $file ) ) {
$stack[] = $dir . DIRECTORY_SEPARATOR . $file;
} elseif ( @is_file( $dir . DIRECTORY_SEPARATOR . $file ) ) {
@unlink( $dir . DIRECTORY_SEPARATOR . $file );
}
$file = @readdir( $dh );
}
@closedir( $dh );
}
$index++;
}
$stack = array_reverse( $stack ); // Last added directories are deepest.
foreach ( (array) $stack as $dir ) {
if ( $dir != $top_dir ) {
@rmdir( $dir );
}
}
// phpcs:enable WordPress.PHP.NoSilencedErrors.Discouraged
if ( $switch ) {
restore_current_blog();
}
return true;
}
```
[apply\_filters( 'wpmu\_delete\_blog\_upload\_dir', string $basedir, int $site\_id )](../hooks/wpmu_delete_blog_upload_dir)
Filters the upload base directory to delete when the site is deleted.
[apply\_filters( 'wpmu\_drop\_tables', string[] $tables, int $site\_id )](../hooks/wpmu_drop_tables)
Filters the tables to drop when the site is deleted.
| Uses | Description |
| --- | --- |
| [wp\_is\_site\_initialized()](wp_is_site_initialized) wp-includes/ms-site.php | Checks whether a site is initialized. |
| [get\_site()](get_site) wp-includes/ms-site.php | Retrieves site data given a site ID or site object. |
| [wp\_get\_upload\_dir()](wp_get_upload_dir) wp-includes/functions.php | Retrieves uploads directory information. |
| [get\_users()](get_users) wp-includes/user.php | Retrieves list of users matching criteria. |
| [remove\_user\_from\_blog()](remove_user_from_blog) wp-includes/ms-functions.php | Removes a user from a blog. |
| [switch\_to\_blog()](switch_to_blog) wp-includes/ms-blogs.php | Switch the current blog. |
| [restore\_current\_blog()](restore_current_blog) wp-includes/ms-blogs.php | Restore the current blog, after calling [switch\_to\_blog()](switch_to_blog) . |
| [wpdb::query()](../classes/wpdb/query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| [wpdb::tables()](../classes/wpdb/tables) wp-includes/class-wpdb.php | Returns an array of WordPress tables. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_current\_blog\_id()](get_current_blog_id) wp-includes/load.php | Retrieve the current site ID. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [WP\_Error::\_\_construct()](../classes/wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | Introduced. |
wordpress signup_nonce_check( array $result ): array signup\_nonce\_check( array $result ): array
============================================
Processes the signup nonce created in [signup\_nonce\_fields()](signup_nonce_fields) .
`$result` array Required array
File: `wp-includes/ms-functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-functions.php/)
```
function signup_nonce_check( $result ) {
if ( ! strpos( $_SERVER['PHP_SELF'], 'wp-signup.php' ) ) {
return $result;
}
if ( ! wp_verify_nonce( $_POST['_signup_form'], 'signup_form_' . $_POST['signup_form_id'] ) ) {
$result['errors']->add( 'invalid_nonce', __( 'Unable to submit this form, please try again.' ) );
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [wp\_verify\_nonce()](wp_verify_nonce) wp-includes/pluggable.php | Verifies that a correct security nonce was used with time limit. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [MU (3.0.0)](https://developer.wordpress.org/reference/since/mu.3.0.0/) | Introduced. |
| programming_docs |
wordpress wp_update_core( $current, $feedback = '' ) wp\_update\_core( $current, $feedback = '' )
============================================
This function has been deprecated. Use [Core\_Upgrader](../classes/core_upgrader)() instead.
This was once used to kick-off the Core Updater.
Deprecated in favor of instantating a [Core\_Upgrader](../classes/core_upgrader) instance directly, and calling the ‘upgrade’ method.
* [Core\_Upgrader](../classes/core_upgrader)
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
function wp_update_core($current, $feedback = '') {
_deprecated_function( __FUNCTION__, '3.7.0', 'new Core_Upgrader();' );
if ( !empty($feedback) )
add_filter('update_feedback', $feedback);
require ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
$upgrader = new Core_Upgrader();
return $upgrader->upgrade($current);
}
```
| Uses | Description |
| --- | --- |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| [add\_filter()](add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Use [Core\_Upgrader](../classes/core_upgrader) |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress wp_suspend_cache_invalidation( bool $suspend = true ): bool wp\_suspend\_cache\_invalidation( bool $suspend = true ): bool
==============================================================
Suspends cache invalidation.
Turns cache invalidation on and off. Useful during imports where you don’t want to do invalidations every time a post is inserted. Callers must be sure that what they are doing won’t lead to an inconsistent cache when invalidation is suspended.
`$suspend` bool Optional Whether to suspend or enable cache invalidation. Default: `true`
bool The current suspend setting.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function wp_suspend_cache_invalidation( $suspend = true ) {
global $_wp_suspend_cache_invalidation;
$current_suspend = $_wp_suspend_cache_invalidation;
$_wp_suspend_cache_invalidation = $suspend;
return $current_suspend;
}
```
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress get_space_used(): int get\_space\_used(): int
=======================
Returns the space used by the current site.
int Used space in megabytes.
File: `wp-includes/ms-functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ms-functions.php/)
```
function get_space_used() {
/**
* Filters the amount of storage space used by the current site, in megabytes.
*
* @since 3.5.0
*
* @param int|false $space_used The amount of used space, in megabytes. Default false.
*/
$space_used = apply_filters( 'pre_get_space_used', false );
if ( false === $space_used ) {
$upload_dir = wp_upload_dir();
$space_used = get_dirsize( $upload_dir['basedir'] ) / MB_IN_BYTES;
}
return $space_used;
}
```
[apply\_filters( 'pre\_get\_space\_used', int|false $space\_used )](../hooks/pre_get_space_used)
Filters the amount of storage space used by the current site, in megabytes.
| Uses | Description |
| --- | --- |
| [wp\_upload\_dir()](wp_upload_dir) wp-includes/functions.php | Returns an array containing the current upload directory’s path and URL. |
| [get\_dirsize()](get_dirsize) wp-includes/functions.php | Gets the size of a directory. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [upload\_is\_user\_over\_quota()](upload_is_user_over_quota) wp-admin/includes/ms.php | Check whether a site has used its allotted upload space. |
| [display\_space\_usage()](display_space_usage) wp-admin/includes/ms.php | Displays the amount of disk space used by the current site. Not used in core. |
| [wp\_dashboard\_quota()](wp_dashboard_quota) wp-admin/includes/dashboard.php | Displays file upload quota on dashboard. |
| [get\_upload\_space\_available()](get_upload_space_available) wp-includes/ms-functions.php | Determines if there is any upload space left in the current blog’s quota. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress maintenance_nag(): void|false maintenance\_nag(): void|false
==============================
Displays maintenance nag HTML message.
void|false
File: `wp-admin/includes/update.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/update.php/)
```
function maintenance_nag() {
// Include an unmodified $wp_version.
require ABSPATH . WPINC . '/version.php';
global $upgrading;
$nag = isset( $upgrading );
if ( ! $nag ) {
$failed = get_site_option( 'auto_core_update_failed' );
/*
* If an update failed critically, we may have copied over version.php but not other files.
* In that case, if the installation claims we're running the version we attempted, nag.
* This is serious enough to err on the side of nagging.
*
* If we simply failed to update before we tried to copy any files, then assume things are
* OK if they are now running the latest.
*
* This flag is cleared whenever a successful update occurs using Core_Upgrader.
*/
$comparison = ! empty( $failed['critical'] ) ? '>=' : '>';
if ( isset( $failed['attempted'] ) && version_compare( $failed['attempted'], $wp_version, $comparison ) ) {
$nag = true;
}
}
if ( ! $nag ) {
return false;
}
if ( current_user_can( 'update_core' ) ) {
$msg = sprintf(
/* translators: %s: URL to WordPress Updates screen. */
__( 'An automated WordPress update has failed to complete - <a href="%s">please attempt the update again now</a>.' ),
'update-core.php'
);
} else {
$msg = __( 'An automated WordPress update has failed to complete! Please notify the site administrator.' );
}
echo "<div class='update-nag notice notice-warning inline'>$msg</div>";
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_site\_option()](get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress _maybe_update_plugins() \_maybe\_update\_plugins()
==========================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Checks the last time plugins were run before checking plugin versions.
This might have been backported to WordPress 2.6.1 for performance reasons.
This is used for the wp-admin to check only so often instead of every page load.
File: `wp-includes/update.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/update.php/)
```
function _maybe_update_plugins() {
$current = get_site_transient( 'update_plugins' );
if ( isset( $current->last_checked )
&& 12 * HOUR_IN_SECONDS > ( time() - $current->last_checked )
) {
return;
}
wp_update_plugins();
}
```
| Uses | Description |
| --- | --- |
| [wp\_update\_plugins()](wp_update_plugins) wp-includes/update.php | Checks for available updates to plugins based on the latest versions hosted on WordPress.org. |
| [get\_site\_transient()](get_site_transient) wp-includes/option.php | Retrieves the value of a site transient. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress request_filesystem_credentials( string $form_post, string $type = '', bool|WP_Error $error = false, string $context = '', array $extra_fields = null, bool $allow_relaxed_file_ownership = false ): bool|array request\_filesystem\_credentials( string $form\_post, string $type = '', bool|WP\_Error $error = false, string $context = '', array $extra\_fields = null, bool $allow\_relaxed\_file\_ownership = false ): bool|array
======================================================================================================================================================================================================================
Displays a form to the user to request for their FTP/SSH details in order to connect to the filesystem.
All chosen/entered details are saved, excluding the password.
Hostnames may be in the form of hostname:portnumber (eg: wordpress.org:2467) to specify an alternate FTP/SSH port.
Plugins may override this form by returning true|false via the [‘request\_filesystem\_credentials’](../hooks/request_filesystem_credentials) filter.
`$form_post` string Required The URL to post the form to. `$type` string Optional Chosen type of filesystem. Default: `''`
`$error` bool|[WP\_Error](../classes/wp_error) Optional Whether the current request has failed to connect, or an error object. Default: `false`
`$context` string Optional Full path to the directory that is tested for being writable. Default: `''`
`$extra_fields` array Optional Extra `POST` fields to be checked for inclusion in the post. Default: `null`
`$allow_relaxed_file_ownership` bool Optional Whether to allow Group/World writable.
Default: `false`
bool|array True if no filesystem credentials are required, false if they are required but have not been provided, array of credentials if they are required and have been provided.
File: `wp-admin/includes/file.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/file.php/)
```
function request_filesystem_credentials( $form_post, $type = '', $error = false, $context = '', $extra_fields = null, $allow_relaxed_file_ownership = false ) {
global $pagenow;
/**
* Filters the filesystem credentials.
*
* Returning anything other than an empty string will effectively short-circuit
* output of the filesystem credentials form, returning that value instead.
*
* A filter should return true if no filesystem credentials are required, false if they are required but have not been
* provided, or an array of credentials if they are required and have been provided.
*
* @since 2.5.0
* @since 4.6.0 The `$context` parameter default changed from `false` to an empty string.
*
* @param mixed $credentials Credentials to return instead. Default empty string.
* @param string $form_post The URL to post the form to.
* @param string $type Chosen type of filesystem.
* @param bool|WP_Error $error Whether the current request has failed to connect,
* or an error object.
* @param string $context Full path to the directory that is tested for
* being writable.
* @param array $extra_fields Extra POST fields.
* @param bool $allow_relaxed_file_ownership Whether to allow Group/World writable.
*/
$req_cred = apply_filters( 'request_filesystem_credentials', '', $form_post, $type, $error, $context, $extra_fields, $allow_relaxed_file_ownership );
if ( '' !== $req_cred ) {
return $req_cred;
}
if ( empty( $type ) ) {
$type = get_filesystem_method( array(), $context, $allow_relaxed_file_ownership );
}
if ( 'direct' === $type ) {
return true;
}
if ( is_null( $extra_fields ) ) {
$extra_fields = array( 'version', 'locale' );
}
$credentials = get_option(
'ftp_credentials',
array(
'hostname' => '',
'username' => '',
)
);
$submitted_form = wp_unslash( $_POST );
// Verify nonce, or unset submitted form field values on failure.
if ( ! isset( $_POST['_fs_nonce'] ) || ! wp_verify_nonce( $_POST['_fs_nonce'], 'filesystem-credentials' ) ) {
unset(
$submitted_form['hostname'],
$submitted_form['username'],
$submitted_form['password'],
$submitted_form['public_key'],
$submitted_form['private_key'],
$submitted_form['connection_type']
);
}
$ftp_constants = array(
'hostname' => 'FTP_HOST',
'username' => 'FTP_USER',
'password' => 'FTP_PASS',
'public_key' => 'FTP_PUBKEY',
'private_key' => 'FTP_PRIKEY',
);
// If defined, set it to that. Else, if POST'd, set it to that. If not, set it to an empty string.
// Otherwise, keep it as it previously was (saved details in option).
foreach ( $ftp_constants as $key => $constant ) {
if ( defined( $constant ) ) {
$credentials[ $key ] = constant( $constant );
} elseif ( ! empty( $submitted_form[ $key ] ) ) {
$credentials[ $key ] = $submitted_form[ $key ];
} elseif ( ! isset( $credentials[ $key ] ) ) {
$credentials[ $key ] = '';
}
}
// Sanitize the hostname, some people might pass in odd data.
$credentials['hostname'] = preg_replace( '|\w+://|', '', $credentials['hostname'] ); // Strip any schemes off.
if ( strpos( $credentials['hostname'], ':' ) ) {
list( $credentials['hostname'], $credentials['port'] ) = explode( ':', $credentials['hostname'], 2 );
if ( ! is_numeric( $credentials['port'] ) ) {
unset( $credentials['port'] );
}
} else {
unset( $credentials['port'] );
}
if ( ( defined( 'FTP_SSH' ) && FTP_SSH ) || ( defined( 'FS_METHOD' ) && 'ssh2' === FS_METHOD ) ) {
$credentials['connection_type'] = 'ssh';
} elseif ( ( defined( 'FTP_SSL' ) && FTP_SSL ) && 'ftpext' === $type ) { // Only the FTP Extension understands SSL.
$credentials['connection_type'] = 'ftps';
} elseif ( ! empty( $submitted_form['connection_type'] ) ) {
$credentials['connection_type'] = $submitted_form['connection_type'];
} elseif ( ! isset( $credentials['connection_type'] ) ) { // All else fails (and it's not defaulted to something else saved), default to FTP.
$credentials['connection_type'] = 'ftp';
}
if ( ! $error
&& ( ! empty( $credentials['hostname'] ) && ! empty( $credentials['username'] ) && ! empty( $credentials['password'] )
|| 'ssh' === $credentials['connection_type'] && ! empty( $credentials['public_key'] ) && ! empty( $credentials['private_key'] )
)
) {
$stored_credentials = $credentials;
if ( ! empty( $stored_credentials['port'] ) ) { // Save port as part of hostname to simplify above code.
$stored_credentials['hostname'] .= ':' . $stored_credentials['port'];
}
unset(
$stored_credentials['password'],
$stored_credentials['port'],
$stored_credentials['private_key'],
$stored_credentials['public_key']
);
if ( ! wp_installing() ) {
update_option( 'ftp_credentials', $stored_credentials );
}
return $credentials;
}
$hostname = isset( $credentials['hostname'] ) ? $credentials['hostname'] : '';
$username = isset( $credentials['username'] ) ? $credentials['username'] : '';
$public_key = isset( $credentials['public_key'] ) ? $credentials['public_key'] : '';
$private_key = isset( $credentials['private_key'] ) ? $credentials['private_key'] : '';
$port = isset( $credentials['port'] ) ? $credentials['port'] : '';
$connection_type = isset( $credentials['connection_type'] ) ? $credentials['connection_type'] : '';
if ( $error ) {
$error_string = __( '<strong>Error:</strong> Could not connect to the server. Please verify the settings are correct.' );
if ( is_wp_error( $error ) ) {
$error_string = esc_html( $error->get_error_message() );
}
echo '<div id="message" class="error"><p>' . $error_string . '</p></div>';
}
$types = array();
if ( extension_loaded( 'ftp' ) || extension_loaded( 'sockets' ) || function_exists( 'fsockopen' ) ) {
$types['ftp'] = __( 'FTP' );
}
if ( extension_loaded( 'ftp' ) ) { // Only this supports FTPS.
$types['ftps'] = __( 'FTPS (SSL)' );
}
if ( extension_loaded( 'ssh2' ) ) {
$types['ssh'] = __( 'SSH2' );
}
/**
* Filters the connection types to output to the filesystem credentials form.
*
* @since 2.9.0
* @since 4.6.0 The `$context` parameter default changed from `false` to an empty string.
*
* @param string[] $types Types of connections.
* @param array $credentials Credentials to connect with.
* @param string $type Chosen filesystem method.
* @param bool|WP_Error $error Whether the current request has failed to connect,
* or an error object.
* @param string $context Full path to the directory that is tested for being writable.
*/
$types = apply_filters( 'fs_ftp_connection_types', $types, $credentials, $type, $error, $context );
?>
<form action="<?php echo esc_url( $form_post ); ?>" method="post">
<div id="request-filesystem-credentials-form" class="request-filesystem-credentials-form">
<?php
// Print a H1 heading in the FTP credentials modal dialog, default is a H2.
$heading_tag = 'h2';
if ( 'plugins.php' === $pagenow || 'plugin-install.php' === $pagenow ) {
$heading_tag = 'h1';
}
echo "<$heading_tag id='request-filesystem-credentials-title'>" . __( 'Connection Information' ) . "</$heading_tag>";
?>
<p id="request-filesystem-credentials-desc">
<?php
$label_user = __( 'Username' );
$label_pass = __( 'Password' );
_e( 'To perform the requested action, WordPress needs to access your web server.' );
echo ' ';
if ( ( isset( $types['ftp'] ) || isset( $types['ftps'] ) ) ) {
if ( isset( $types['ssh'] ) ) {
_e( 'Please enter your FTP or SSH credentials to proceed.' );
$label_user = __( 'FTP/SSH Username' );
$label_pass = __( 'FTP/SSH Password' );
} else {
_e( 'Please enter your FTP credentials to proceed.' );
$label_user = __( 'FTP Username' );
$label_pass = __( 'FTP Password' );
}
echo ' ';
}
_e( 'If you do not remember your credentials, you should contact your web host.' );
$hostname_value = esc_attr( $hostname );
if ( ! empty( $port ) ) {
$hostname_value .= ":$port";
}
$password_value = '';
if ( defined( 'FTP_PASS' ) ) {
$password_value = '*****';
}
?>
</p>
<label for="hostname">
<span class="field-title"><?php _e( 'Hostname' ); ?></span>
<input name="hostname" type="text" id="hostname" aria-describedby="request-filesystem-credentials-desc" class="code" placeholder="<?php esc_attr_e( 'example: www.wordpress.org' ); ?>" value="<?php echo $hostname_value; ?>"<?php disabled( defined( 'FTP_HOST' ) ); ?> />
</label>
<div class="ftp-username">
<label for="username">
<span class="field-title"><?php echo $label_user; ?></span>
<input name="username" type="text" id="username" value="<?php echo esc_attr( $username ); ?>"<?php disabled( defined( 'FTP_USER' ) ); ?> />
</label>
</div>
<div class="ftp-password">
<label for="password">
<span class="field-title"><?php echo $label_pass; ?></span>
<input name="password" type="password" id="password" value="<?php echo $password_value; ?>"<?php disabled( defined( 'FTP_PASS' ) ); ?> />
<?php
if ( ! defined( 'FTP_PASS' ) ) {
_e( 'This password will not be stored on the server.' );}
?>
</label>
</div>
<fieldset>
<legend><?php _e( 'Connection Type' ); ?></legend>
<?php
$disabled = disabled( ( defined( 'FTP_SSL' ) && FTP_SSL ) || ( defined( 'FTP_SSH' ) && FTP_SSH ), true, false );
foreach ( $types as $name => $text ) :
?>
<label for="<?php echo esc_attr( $name ); ?>">
<input type="radio" name="connection_type" id="<?php echo esc_attr( $name ); ?>" value="<?php echo esc_attr( $name ); ?>" <?php checked( $name, $connection_type ); ?> <?php echo $disabled; ?> />
<?php echo $text; ?>
</label>
<?php
endforeach;
?>
</fieldset>
<?php
if ( isset( $types['ssh'] ) ) {
$hidden_class = '';
if ( 'ssh' !== $connection_type || empty( $connection_type ) ) {
$hidden_class = ' class="hidden"';
}
?>
<fieldset id="ssh-keys"<?php echo $hidden_class; ?>>
<legend><?php _e( 'Authentication Keys' ); ?></legend>
<label for="public_key">
<span class="field-title"><?php _e( 'Public Key:' ); ?></span>
<input name="public_key" type="text" id="public_key" aria-describedby="auth-keys-desc" value="<?php echo esc_attr( $public_key ); ?>"<?php disabled( defined( 'FTP_PUBKEY' ) ); ?> />
</label>
<label for="private_key">
<span class="field-title"><?php _e( 'Private Key:' ); ?></span>
<input name="private_key" type="text" id="private_key" value="<?php echo esc_attr( $private_key ); ?>"<?php disabled( defined( 'FTP_PRIKEY' ) ); ?> />
</label>
<p id="auth-keys-desc"><?php _e( 'Enter the location on the server where the public and private keys are located. If a passphrase is needed, enter that in the password field above.' ); ?></p>
</fieldset>
<?php
}
foreach ( (array) $extra_fields as $field ) {
if ( isset( $submitted_form[ $field ] ) ) {
echo '<input type="hidden" name="' . esc_attr( $field ) . '" value="' . esc_attr( $submitted_form[ $field ] ) . '" />';
}
}
// Make sure the `submit_button()` function is available during the REST API call
// from WP_Site_Health_Auto_Updates::test_check_wp_filesystem_method().
if ( ! function_exists( 'submit_button' ) ) {
require_once ABSPATH . '/wp-admin/includes/template.php';
}
?>
<p class="request-filesystem-credentials-action-buttons">
<?php wp_nonce_field( 'filesystem-credentials', '_fs_nonce', false, true ); ?>
<button class="button cancel-button" data-js-action="close" type="button"><?php _e( 'Cancel' ); ?></button>
<?php submit_button( __( 'Proceed' ), '', 'upgrade', false ); ?>
</p>
</div>
</form>
<?php
return false;
}
```
[apply\_filters( 'fs\_ftp\_connection\_types', string[] $types, array $credentials, string $type, bool|WP\_Error $error, string $context )](../hooks/fs_ftp_connection_types)
Filters the connection types to output to the filesystem credentials form.
[apply\_filters( 'request\_filesystem\_credentials', mixed $credentials, string $form\_post, string $type, bool|WP\_Error $error, string $context, array $extra\_fields, bool $allow\_relaxed\_file\_ownership )](../hooks/request_filesystem_credentials)
Filters the filesystem credentials.
| Uses | Description |
| --- | --- |
| [wp\_installing()](wp_installing) wp-includes/load.php | Check or set whether WordPress is in “installation” mode. |
| [disabled()](disabled) wp-includes/general-template.php | Outputs the HTML disabled attribute. |
| [get\_filesystem\_method()](get_filesystem_method) wp-admin/includes/file.php | Determines which method to use for reading, writing, modifying, or deleting files on the filesystem. |
| [esc\_attr\_e()](esc_attr_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in an attribute. |
| [wp\_nonce\_field()](wp_nonce_field) wp-includes/functions.php | Retrieves or display nonce hidden field for forms. |
| [checked()](checked) wp-includes/general-template.php | Outputs the HTML checked attribute. |
| [submit\_button()](submit_button) wp-admin/includes/template.php | Echoes a submit button, with provided text and appropriate class(es). |
| [wp\_verify\_nonce()](wp_verify_nonce) wp-includes/pluggable.php | Verifies that a correct security nonce was used with time limit. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [update\_option()](update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [esc\_html()](esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [wp\_unslash()](wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [\_e()](_e) wp-includes/l10n.php | Displays translated text. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::is\_filesystem\_available()](../classes/wp_rest_plugins_controller/is_filesystem_available) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Determine if the endpoints are available. |
| [wp\_ajax\_delete\_plugin()](wp_ajax_delete_plugin) wp-admin/includes/ajax-actions.php | Ajax handler for deleting a plugin. |
| [wp\_ajax\_delete\_theme()](wp_ajax_delete_theme) wp-admin/includes/ajax-actions.php | Ajax handler for deleting a theme. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](../classes/wp_customize_manager/customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [wp\_print\_request\_filesystem\_credentials\_modal()](wp_print_request_filesystem_credentials_modal) wp-admin/includes/file.php | Prints the filesystem credentials modal when needed. |
| [delete\_theme()](delete_theme) wp-admin/includes/theme.php | Removes a theme. |
| [WP\_Upgrader\_Skin::request\_filesystem\_credentials()](../classes/wp_upgrader_skin/request_filesystem_credentials) wp-admin/includes/class-wp-upgrader-skin.php | Displays a form to the user to request for their FTP/SSH details in order to connect to the filesystem. |
| [delete\_plugins()](delete_plugins) wp-admin/includes/plugin.php | Removes directory and files of a plugin for a list of plugins. |
| [do\_core\_upgrade()](do_core_upgrade) wp-admin/update-core.php | Upgrade WordPress core display. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | The `$context` parameter default changed from `false` to an empty string. |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
| programming_docs |
wordpress date_i18n( string $format, int|bool $timestamp_with_offset = false, bool $gmt = false ): string date\_i18n( string $format, int|bool $timestamp\_with\_offset = false, bool $gmt = false ): string
==================================================================================================
Retrieves the date in localized format, based on a sum of Unix timestamp and timezone offset in seconds.
If the locale specifies the locale month and weekday, then the locale will take over the format for the date. If it isn’t, then the date format string will be used instead.
Note that due to the way WP typically generates a sum of timestamp and offset with `strtotime()`, it implies offset added at a *current* time, not at the time the timestamp represents. Storing such timestamps or calculating them differently will lead to invalid output.
`$format` string Required Format to display the date. `$timestamp_with_offset` int|bool Optional A sum of Unix timestamp and timezone offset in seconds. Default: `false`
`$gmt` bool Optional Whether to use GMT timezone. Only applies if timestamp is not provided. Default: `false`
string The date, translated if locale specifies it.
File: `wp-includes/functions.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/functions.php/)
```
function date_i18n( $format, $timestamp_with_offset = false, $gmt = false ) {
$timestamp = $timestamp_with_offset;
// If timestamp is omitted it should be current time (summed with offset, unless `$gmt` is true).
if ( ! is_numeric( $timestamp ) ) {
// phpcs:ignore WordPress.DateTime.CurrentTimeTimestamp.Requested
$timestamp = current_time( 'timestamp', $gmt );
}
/*
* This is a legacy implementation quirk that the returned timestamp is also with offset.
* Ideally this function should never be used to produce a timestamp.
*/
if ( 'U' === $format ) {
$date = $timestamp;
} elseif ( $gmt && false === $timestamp_with_offset ) { // Current time in UTC.
$date = wp_date( $format, null, new DateTimeZone( 'UTC' ) );
} elseif ( false === $timestamp_with_offset ) { // Current time in site's timezone.
$date = wp_date( $format );
} else {
/*
* Timestamp with offset is typically produced by a UTC `strtotime()` call on an input without timezone.
* This is the best attempt to reverse that operation into a local time to use.
*/
$local_time = gmdate( 'Y-m-d H:i:s', $timestamp );
$timezone = wp_timezone();
$datetime = date_create( $local_time, $timezone );
$date = wp_date( $format, $datetime->getTimestamp(), $timezone );
}
/**
* Filters the date formatted based on the locale.
*
* @since 2.8.0
*
* @param string $date Formatted date string.
* @param string $format Format to display the date.
* @param int $timestamp A sum of Unix timestamp and timezone offset in seconds.
* Might be without offset if input omitted timestamp but requested GMT.
* @param bool $gmt Whether to use GMT timezone. Only applies if timestamp was not provided.
* Default false.
*/
$date = apply_filters( 'date_i18n', $date, $format, $timestamp, $gmt );
return $date;
}
```
[apply\_filters( 'date\_i18n', string $date, string $format, int $timestamp, bool $gmt )](../hooks/date_i18n)
Filters the date formatted based on the locale.
| Uses | Description |
| --- | --- |
| [wp\_date()](wp_date) wp-includes/functions.php | Retrieves the date, in localized format. |
| [wp\_timezone()](wp_timezone) wp-includes/functions.php | Retrieves the timezone of the site as a `DateTimeZone` object. |
| [current\_time()](current_time) wp-includes/functions.php | Retrieves the current time based on specified type. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Application\_Passwords\_List\_Table::column\_created()](../classes/wp_application_passwords_list_table/column_created) wp-admin/includes/class-wp-application-passwords-list-table.php | Handles the created column output. |
| [WP\_Application\_Passwords\_List\_Table::column\_last\_used()](../classes/wp_application_passwords_list_table/column_last_used) wp-admin/includes/class-wp-application-passwords-list-table.php | Handles the last used column output. |
| [wp\_user\_personal\_data\_exporter()](wp_user_personal_data_exporter) wp-includes/user.php | Finds and exports personal data associated with an email address from the user and user\_meta table. |
| [WP\_Privacy\_Policy\_Content::privacy\_policy\_guide()](../classes/wp_privacy_policy_content/privacy_policy_guide) wp-admin/includes/class-wp-privacy-policy-content.php | Output the privacy policy guide together with content from the theme and plugins. |
| [wp\_privacy\_send\_personal\_data\_export\_email()](wp_privacy_send_personal_data_export_email) wp-admin/includes/privacy-tools.php | Send an email to the user with a link to the personal data export file |
| [WP\_Privacy\_Requests\_Table::get\_timestamp\_as\_date()](../classes/wp_privacy_requests_table/get_timestamp_as_date) wp-admin/includes/class-wp-privacy-requests-table.php | Convert timestamp for display. |
| [WP\_Community\_Events::format\_event\_data\_time()](../classes/wp_community_events/format_event_data_time) wp-admin/includes/class-wp-community-events.php | Adds formatted date and time items for each event in an API response. |
| [heartbeat\_autosave()](heartbeat_autosave) wp-admin/includes/misc.php | Performs autosave with heartbeat. |
| [wp\_dashboard\_recent\_posts()](wp_dashboard_recent_posts) wp-admin/includes/dashboard.php | Generates Publishing Soon and Recently Published sections. |
| [wp\_ajax\_date\_format()](wp_ajax_date_format) wp-admin/includes/ajax-actions.php | Ajax handler for date formatting. |
| [wp\_ajax\_time\_format()](wp_ajax_time_format) wp-admin/includes/ajax-actions.php | Ajax handler for time formatting. |
| [wp\_ajax\_wp\_fullscreen\_save\_post()](wp_ajax_wp_fullscreen_save_post) wp-admin/includes/ajax-actions.php | Ajax handler for saving posts from the fullscreen editor. |
| [wp\_prepare\_revisions\_for\_js()](wp_prepare_revisions_for_js) wp-admin/includes/revision.php | Prepare revisions for JavaScript. |
| [post\_submit\_meta\_box()](post_submit_meta_box) wp-admin/includes/meta-boxes.php | Displays post submit form fields. |
| [attachment\_submit\_meta\_box()](attachment_submit_meta_box) wp-admin/includes/meta-boxes.php | Displays attachment submit form fields. |
| [wp\_get\_archives()](wp_get_archives) wp-includes/general-template.php | Displays archive links based on type and format. |
| [wp\_widget\_rss\_output()](wp_widget_rss_output) wp-includes/widgets.php | Display the RSS entries in a list. |
| [wp\_post\_revision\_title()](wp_post_revision_title) wp-includes/post-template.php | Retrieves formatted date timestamp of a revision (linked to that revisions’s page). |
| [wp\_post\_revision\_title\_expanded()](wp_post_revision_title_expanded) wp-includes/post-template.php | Retrieves formatted date timestamp of a revision (linked to that revisions’s page). |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Converted into a wrapper for [wp\_date()](wp_date) . |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress wp_rel_nofollow_callback( array $matches ): string wp\_rel\_nofollow\_callback( array $matches ): string
=====================================================
This function has been deprecated. Use [wp\_rel\_callback()](wp_rel_callback) instead.
Callback to add `rel="nofollow"` string to HTML A element.
`$matches` array Required Single match. string HTML A Element with `rel="nofollow"`.
File: `wp-includes/formatting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/formatting.php/)
```
function wp_rel_nofollow_callback( $matches ) {
return wp_rel_callback( $matches, 'nofollow' );
}
```
| Uses | Description |
| --- | --- |
| [wp\_rel\_callback()](wp_rel_callback) wp-includes/formatting.php | Callback to add a rel attribute to HTML A element. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Use [wp\_rel\_callback()](wp_rel_callback) |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
wordpress get_terms( array|string $args = array(), array|string $deprecated = '' ): WP_Term[]|int[]|string[]|string|WP_Error get\_terms( array|string $args = array(), array|string $deprecated = '' ): WP\_Term[]|int[]|string[]|string|WP\_Error
=====================================================================================================================
Retrieves the terms in a given taxonomy or list of taxonomies.
You can fully inject any customizations to the query before it is sent, as well as control the output with a filter.
The return type varies depending on the value passed to `$args['fields']`. See [WP\_Term\_Query::get\_terms()](../classes/wp_term_query/get_terms) for details. In all cases, a `WP_Error` object will be returned if an invalid taxonomy is requested.
The [‘get\_terms’](../hooks/get_terms) filter will be called when the cache has the term and will pass the found term along with the array of $taxonomies and array of $args.
This filter is also called before the array of terms is passed and will pass the array of terms, along with the $taxonomies and $args.
The [‘list\_terms\_exclusions’](../hooks/list_terms_exclusions) filter passes the compiled exclusions along with the $args.
The [‘get\_terms\_orderby’](../hooks/get_terms_orderby) filter passes the `ORDER BY` clause for the query along with the $args array.
Prior to 4.5.0, the first parameter of `get_terms()` was a taxonomy or list of taxonomies:
```
$terms = get_terms( 'post_tag', array(
'hide_empty' => false,
) );
```
Since 4.5.0, taxonomies should be passed via the ‘taxonomy’ argument in the `$args` array:
```
$terms = get_terms( array(
'taxonomy' => 'post_tag',
'hide_empty' => false,
) );
```
`$args` array|string Optional Array or string of arguments. See [WP\_Term\_Query::\_\_construct()](../classes/wp_term_query/__construct) for information on accepted arguments. More Arguments from WP\_Term\_Query::\_\_construct( ... $query ) Array or query string of term query parameters.
* `taxonomy`string|string[]Taxonomy name, or array of taxonomy names, to which results should be limited.
* `object_ids`int|int[]Object ID, or array of object IDs. Results will be limited to terms associated with these objects.
* `orderby`stringField(s) to order terms by. Accepts:
+ Term fields (`'name'`, `'slug'`, `'term_group'`, `'term_id'`, `'id'`, `'description'`, `'parent'`, `'term_order'`). Unless `$object_ids` is not empty, `'term_order'` is treated the same as `'term_id'`.
+ `'count'` to use the number of objects associated with the term.
+ `'include'` to match the `'order'` of the `$include` param.
+ `'slug__in'` to match the `'order'` of the `$slug` param.
+ `'meta_value'`
+ `'meta_value_num'`.
+ The value of `$meta_key`.
+ The array keys of `$meta_query`.
+ `'none'` to omit the ORDER BY clause. Default `'name'`.
* `order`stringWhether to order terms in ascending or descending order.
Accepts `'ASC'` (ascending) or `'DESC'` (descending).
Default `'ASC'`.
* `hide_empty`bool|intWhether to hide terms not assigned to any posts. Accepts `1|true` or `0|false`. Default `1|true`.
* `include`int[]|stringArray or comma/space-separated string of term IDs to include.
Default empty array.
* `exclude`int[]|stringArray or comma/space-separated string of term IDs to exclude.
If `$include` is non-empty, `$exclude` is ignored.
Default empty array.
* `exclude_tree`int[]|stringArray or comma/space-separated string of term IDs to exclude along with all of their descendant terms. If `$include` is non-empty, `$exclude_tree` is ignored. Default empty array.
* `number`int|stringMaximum number of terms to return. Accepts ``''`|0` (all) or any positive number. Default ``''`|0` (all). Note that `$number` may not return accurate results when coupled with `$object_ids`.
See #41796 for details.
* `offset`intThe number by which to offset the terms query.
* `fields`stringTerm fields to query for. Accepts:
+ `'all'` Returns an array of complete term objects (`WP_Term[]`).
+ `'all_with_object_id'` Returns an array of term objects with the `'object_id'` param (`WP_Term[]`). Works only when the `$object_ids` parameter is populated.
+ `'ids'` Returns an array of term IDs (`int[]`).
+ `'tt_ids'` Returns an array of term taxonomy IDs (`int[]`).
+ `'names'` Returns an array of term names (`string[]`).
+ `'slugs'` Returns an array of term slugs (`string[]`).
+ `'count'` Returns the number of matching terms (`int`).
+ `'id=>parent'` Returns an associative array of parent term IDs, keyed by term ID (`int[]`).
+ `'id=>name'` Returns an associative array of term names, keyed by term ID (`string[]`).
+ `'id=>slug'` Returns an associative array of term slugs, keyed by term ID (`string[]`). Default `'all'`.
* `count`boolWhether to return a term count. If true, will take precedence over `$fields`. Default false.
* `name`string|string[]Name or array of names to return term(s) for.
* `slug`string|string[]Slug or array of slugs to return term(s) for.
* `term_taxonomy_id`int|int[]Term taxonomy ID, or array of term taxonomy IDs, to match when querying terms.
* `hierarchical`boolWhether to include terms that have non-empty descendants (even if `$hide_empty` is set to true). Default true.
* `search`stringSearch criteria to match terms. Will be SQL-formatted with wildcards before and after.
* `name__like`stringRetrieve terms with criteria by which a term is LIKE `$name__like`.
* `description__like`stringRetrieve terms where the description is LIKE `$description__like`.
* `pad_counts`boolWhether to pad the quantity of a term's children in the quantity of each term's "count" object variable. Default false.
* `get`stringWhether to return terms regardless of ancestry or whether the terms are empty. Accepts `'all'` or `''` (disabled). Default `''`.
* `child_of`intTerm ID to retrieve child terms of. If multiple taxonomies are passed, `$child_of` is ignored. Default 0.
* `parent`intParent term ID to retrieve direct-child terms of.
* `childless`boolTrue to limit results to terms that have no children.
This parameter has no effect on non-hierarchical taxonomies.
Default false.
* `cache_domain`stringUnique cache key to be produced when this query is stored in an object cache. Default `'core'`.
* `update_term_meta_cache`boolWhether to prime meta caches for matched terms. Default true.
* `meta_key`string|string[]Meta key or keys to filter by.
* `meta_value`string|string[]Meta value or values to filter by.
* `meta_compare`stringMySQL operator used for comparing the meta value.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values and default value.
* `meta_compare_key`stringMySQL operator used for comparing the meta key.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values and default value.
* `meta_type`stringMySQL data type that the meta\_value column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values and default value.
* `meta_type_key`stringMySQL data type that the meta\_key column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values and default value.
* `meta_query`arrayAn associative array of [WP\_Meta\_Query](../classes/wp_meta_query) arguments.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values.
Default: `array()`
`$deprecated` array|string Optional Argument array, when using the legacy function parameter format.
If present, this parameter will be interpreted as `$args`, and the first function parameter will be parsed as a taxonomy or array of taxonomies.
Default: `''`
[WP\_Term](../classes/wp_term)[]|int[]|string[]|string|[WP\_Error](../classes/wp_error) Array of terms, a count thereof as a numeric string, or [WP\_Error](../classes/wp_error) if any of the taxonomies do not exist.
See the function description for more information.
File: `wp-includes/taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/taxonomy.php/)
```
function get_terms( $args = array(), $deprecated = '' ) {
$term_query = new WP_Term_Query();
$defaults = array(
'suppress_filter' => false,
);
/*
* Legacy argument format ($taxonomy, $args) takes precedence.
*
* We detect legacy argument format by checking if
* (a) a second non-empty parameter is passed, or
* (b) the first parameter shares no keys with the default array (ie, it's a list of taxonomies)
*/
$_args = wp_parse_args( $args );
$key_intersect = array_intersect_key( $term_query->query_var_defaults, (array) $_args );
$do_legacy_args = $deprecated || empty( $key_intersect );
if ( $do_legacy_args ) {
$taxonomies = (array) $args;
$args = wp_parse_args( $deprecated, $defaults );
$args['taxonomy'] = $taxonomies;
} else {
$args = wp_parse_args( $args, $defaults );
if ( isset( $args['taxonomy'] ) && null !== $args['taxonomy'] ) {
$args['taxonomy'] = (array) $args['taxonomy'];
}
}
if ( ! empty( $args['taxonomy'] ) ) {
foreach ( $args['taxonomy'] as $taxonomy ) {
if ( ! taxonomy_exists( $taxonomy ) ) {
return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
}
}
}
// Don't pass suppress_filter to WP_Term_Query.
$suppress_filter = $args['suppress_filter'];
unset( $args['suppress_filter'] );
$terms = $term_query->query( $args );
// Count queries are not filtered, for legacy reasons.
if ( ! is_array( $terms ) ) {
return $terms;
}
if ( $suppress_filter ) {
return $terms;
}
/**
* Filters the found terms.
*
* @since 2.3.0
* @since 4.6.0 Added the `$term_query` parameter.
*
* @param array $terms Array of found terms.
* @param array|null $taxonomies An array of taxonomies if known.
* @param array $args An array of get_terms() arguments.
* @param WP_Term_Query $term_query The WP_Term_Query object.
*/
return apply_filters( 'get_terms', $terms, $term_query->query_vars['taxonomy'], $term_query->query_vars, $term_query );
}
```
[apply\_filters( 'get\_terms', array $terms, array|null $taxonomies, array $args, WP\_Term\_Query $term\_query )](../hooks/get_terms)
Filters the found terms.
| Uses | Description |
| --- | --- |
| [WP\_Term\_Query::\_\_construct()](../classes/wp_term_query/__construct) wp-includes/class-wp-term-query.php | Constructor. |
| [taxonomy\_exists()](taxonomy_exists) wp-includes/taxonomy.php | Determines whether the taxonomy name exists. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_parse\_args()](wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [WP\_Error::\_\_construct()](../classes/wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::formats\_dropdown()](../classes/wp_posts_list_table/formats_dropdown) wp-admin/includes/class-wp-posts-list-table.php | Displays a formats drop-down for filtering items. |
| [taxonomy\_meta\_box\_sanitize\_cb\_input()](taxonomy_meta_box_sanitize_cb_input) wp-admin/includes/post.php | Sanitizes POST values from an input taxonomy metabox. |
| [WP\_REST\_Terms\_Controller::get\_items()](../classes/wp_rest_terms_controller/get_items) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Retrieves terms associated with a taxonomy. |
| [WP\_Term\_Query::get\_terms()](../classes/wp_term_query/get_terms) wp-includes/class-wp-term-query.php | Retrieves the query results. |
| [WP\_Customize\_Nav\_Menus::search\_available\_items\_query()](../classes/wp_customize_nav_menus/search_available_items_query) wp-includes/class-wp-customize-nav-menus.php | Performs post queries for available-item searching. |
| [WP\_Customize\_Nav\_Menus::load\_available\_items\_query()](../classes/wp_customize_nav_menus/load_available_items_query) wp-includes/class-wp-customize-nav-menus.php | Performs the post\_type and taxonomy queries for loading available menu items. |
| [export\_wp()](export_wp) wp-admin/includes/export.php | Generates the WXR export file for download. |
| [wp\_terms\_checklist()](wp_terms_checklist) wp-admin/includes/template.php | Outputs an unordered list of checkbox input elements labelled with term names. |
| [wp\_popular\_terms\_checklist()](wp_popular_terms_checklist) wp-admin/includes/template.php | Retrieves a list of the most popular terms from the specified taxonomy. |
| [wp\_link\_category\_checklist()](wp_link_category_checklist) wp-admin/includes/template.php | Outputs a link category checklist element. |
| [wp\_ajax\_get\_tagcloud()](wp_ajax_get_tagcloud) wp-admin/includes/ajax-actions.php | Ajax handler for getting a tagcloud. |
| [wp\_ajax\_ajax\_tag\_search()](wp_ajax_ajax_tag_search) wp-admin/includes/ajax-actions.php | Ajax handler for tag search. |
| [WP\_Terms\_List\_Table::prepare\_items()](../classes/wp_terms_list_table/prepare_items) wp-admin/includes/class-wp-terms-list-table.php | |
| [\_wp\_ajax\_menu\_quick\_search()](_wp_ajax_menu_quick_search) wp-admin/includes/nav-menu.php | Prints the appropriate response to a menu quick search. |
| [wp\_nav\_menu\_item\_taxonomy\_meta\_box()](wp_nav_menu_item_taxonomy_meta_box) wp-admin/includes/nav-menu.php | Displays a meta box for a taxonomy menu item. |
| [Walker\_Category::start\_el()](../classes/walker_category/start_el) wp-includes/class-walker-category.php | Starts the element output. |
| [wp\_tag\_cloud()](wp_tag_cloud) wp-includes/category-template.php | Displays a tag cloud. |
| [wp\_dropdown\_categories()](wp_dropdown_categories) wp-includes/category-template.php | Displays or retrieves the HTML dropdown list of categories. |
| [get\_tags()](get_tags) wp-includes/category.php | Retrieves all post tags. |
| [get\_categories()](get_categories) wp-includes/category.php | Retrieves a list of category objects. |
| [get\_category\_by\_path()](get_category_by_path) wp-includes/category.php | Retrieves a category based on URL containing the category slug. |
| [get\_all\_category\_ids()](get_all_category_ids) wp-includes/deprecated.php | Retrieves all category IDs. |
| [WP\_Widget\_Links::form()](../classes/wp_widget_links/form) wp-includes/widgets/class-wp-widget-links.php | Outputs the settings form for the Links widget. |
| [\_get\_term\_hierarchy()](_get_term_hierarchy) wp-includes/taxonomy.php | Retrieves children of taxonomy as term IDs. |
| [wp\_get\_object\_terms()](wp_get_object_terms) wp-includes/taxonomy.php | Retrieves the terms associated with the given object(s), in the supplied taxonomies. |
| [wp\_insert\_term()](wp_insert_term) wp-includes/taxonomy.php | Adds a new term to the database. |
| [wp\_count\_terms()](wp_count_terms) wp-includes/taxonomy.php | Counts how many terms are in taxonomy. |
| [get\_term\_by()](get_term_by) wp-includes/taxonomy.php | Gets all term data from database by term field and data. |
| [term\_exists()](term_exists) wp-includes/taxonomy.php | Determines whether a taxonomy term exists. |
| [wp\_list\_bookmarks()](wp_list_bookmarks) wp-includes/bookmark-template.php | Retrieves or echoes all of the bookmarks. |
| [wp\_get\_nav\_menus()](wp_get_nav_menus) wp-includes/nav-menu.php | Returns all navigation menu objects. |
| [wp\_xmlrpc\_server::wp\_getTerms()](../classes/wp_xmlrpc_server/wp_getterms) wp-includes/class-wp-xmlrpc-server.php | Retrieve all terms for a taxonomy. |
| [wp\_xmlrpc\_server::\_insert\_post()](../classes/wp_xmlrpc_server/_insert_post) wp-includes/class-wp-xmlrpc-server.php | Helper method for wp\_newPost() and wp\_editPost(), containing shared logic. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced `'suppress_filter'` parameter. |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Changed the function signature so that the `$args` array can be provided as the first parameter. Introduced `'meta_key'` and `'meta_value'` parameters. Introduced the ability to order results by metadata. |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced the ability to pass `'term_id'` as an alias of `'id'` for the `orderby` parameter. Introduced the `'meta_query'` and `'update_term_meta_cache'` parameters. Converted to return a list of [WP\_Term](../classes/wp_term) objects. |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced `'name'` and `'childless'` parameters. |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
| programming_docs |
wordpress is_uninstallable_plugin( string $plugin ): bool is\_uninstallable\_plugin( string $plugin ): bool
=================================================
Determines whether the plugin can be uninstalled.
`$plugin` string Required Path to the plugin file relative to the plugins directory. bool Whether plugin can be uninstalled.
File: `wp-admin/includes/plugin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/plugin.php/)
```
function is_uninstallable_plugin( $plugin ) {
$file = plugin_basename( $plugin );
$uninstallable_plugins = (array) get_option( 'uninstall_plugins' );
if ( isset( $uninstallable_plugins[ $file ] ) || file_exists( WP_PLUGIN_DIR . '/' . dirname( $file ) . '/uninstall.php' ) ) {
return true;
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [plugin\_basename()](plugin_basename) wp-includes/plugin.php | Gets the basename of a plugin. |
| [get\_option()](get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_Plugins\_List\_Table::single\_row()](../classes/wp_plugins_list_table/single_row) wp-admin/includes/class-wp-plugins-list-table.php | |
| [delete\_plugins()](delete_plugins) wp-admin/includes/plugin.php | Removes directory and files of a plugin for a list of plugins. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress wp_plugin_update_row( string $file, array $plugin_data ): void|false wp\_plugin\_update\_row( string $file, array $plugin\_data ): void|false
========================================================================
Displays update information for a plugin.
`$file` string Required Plugin basename. `$plugin_data` array Required Plugin information. void|false
File: `wp-admin/includes/update.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/update.php/)
```
function wp_plugin_update_row( $file, $plugin_data ) {
$current = get_site_transient( 'update_plugins' );
if ( ! isset( $current->response[ $file ] ) ) {
return false;
}
$response = $current->response[ $file ];
$plugins_allowedtags = array(
'a' => array(
'href' => array(),
'title' => array(),
),
'abbr' => array( 'title' => array() ),
'acronym' => array( 'title' => array() ),
'code' => array(),
'em' => array(),
'strong' => array(),
);
$plugin_name = wp_kses( $plugin_data['Name'], $plugins_allowedtags );
$plugin_slug = isset( $response->slug ) ? $response->slug : $response->id;
if ( isset( $response->slug ) ) {
$details_url = self_admin_url( 'plugin-install.php?tab=plugin-information&plugin=' . $plugin_slug . '§ion=changelog' );
} elseif ( isset( $response->url ) ) {
$details_url = $response->url;
} else {
$details_url = $plugin_data['PluginURI'];
}
$details_url = add_query_arg(
array(
'TB_iframe' => 'true',
'width' => 600,
'height' => 800,
),
$details_url
);
/** @var WP_Plugins_List_Table $wp_list_table */
$wp_list_table = _get_list_table(
'WP_Plugins_List_Table',
array(
'screen' => get_current_screen(),
)
);
if ( is_network_admin() || ! is_multisite() ) {
if ( is_network_admin() ) {
$active_class = is_plugin_active_for_network( $file ) ? ' active' : '';
} else {
$active_class = is_plugin_active( $file ) ? ' active' : '';
}
$requires_php = isset( $response->requires_php ) ? $response->requires_php : null;
$compatible_php = is_php_version_compatible( $requires_php );
$notice_type = $compatible_php ? 'notice-warning' : 'notice-error';
printf(
'<tr class="plugin-update-tr%s" id="%s" data-slug="%s" data-plugin="%s">' .
'<td colspan="%s" class="plugin-update colspanchange">' .
'<div class="update-message notice inline %s notice-alt"><p>',
$active_class,
esc_attr( $plugin_slug . '-update' ),
esc_attr( $plugin_slug ),
esc_attr( $file ),
esc_attr( $wp_list_table->get_column_count() ),
$notice_type
);
if ( ! current_user_can( 'update_plugins' ) ) {
printf(
/* translators: 1: Plugin name, 2: Details URL, 3: Additional link attributes, 4: Version number. */
__( 'There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a>.' ),
$plugin_name,
esc_url( $details_url ),
sprintf(
'class="thickbox open-plugin-details-modal" aria-label="%s"',
/* translators: 1: Plugin name, 2: Version number. */
esc_attr( sprintf( __( 'View %1$s version %2$s details' ), $plugin_name, $response->new_version ) )
),
esc_attr( $response->new_version )
);
} elseif ( empty( $response->package ) ) {
printf(
/* translators: 1: Plugin name, 2: Details URL, 3: Additional link attributes, 4: Version number. */
__( 'There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a>. <em>Automatic update is unavailable for this plugin.</em>' ),
$plugin_name,
esc_url( $details_url ),
sprintf(
'class="thickbox open-plugin-details-modal" aria-label="%s"',
/* translators: 1: Plugin name, 2: Version number. */
esc_attr( sprintf( __( 'View %1$s version %2$s details' ), $plugin_name, $response->new_version ) )
),
esc_attr( $response->new_version )
);
} else {
if ( $compatible_php ) {
printf(
/* translators: 1: Plugin name, 2: Details URL, 3: Additional link attributes, 4: Version number, 5: Update URL, 6: Additional link attributes. */
__( 'There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a> or <a href="%5$s" %6$s>update now</a>.' ),
$plugin_name,
esc_url( $details_url ),
sprintf(
'class="thickbox open-plugin-details-modal" aria-label="%s"',
/* translators: 1: Plugin name, 2: Version number. */
esc_attr( sprintf( __( 'View %1$s version %2$s details' ), $plugin_name, $response->new_version ) )
),
esc_attr( $response->new_version ),
wp_nonce_url( self_admin_url( 'update.php?action=upgrade-plugin&plugin=' ) . $file, 'upgrade-plugin_' . $file ),
sprintf(
'class="update-link" aria-label="%s"',
/* translators: %s: Plugin name. */
esc_attr( sprintf( _x( 'Update %s now', 'plugin' ), $plugin_name ) )
)
);
} else {
printf(
/* translators: 1: Plugin name, 2: Details URL, 3: Additional link attributes, 4: Version number 5: URL to Update PHP page. */
__( 'There is a new version of %1$s available, but it does not work with your version of PHP. <a href="%2$s" %3$s>View version %4$s details</a> or <a href="%5$s">learn more about updating PHP</a>.' ),
$plugin_name,
esc_url( $details_url ),
sprintf(
'class="thickbox open-plugin-details-modal" aria-label="%s"',
/* translators: 1: Plugin name, 2: Version number. */
esc_attr( sprintf( __( 'View %1$s version %2$s details' ), $plugin_name, $response->new_version ) )
),
esc_attr( $response->new_version ),
esc_url( wp_get_update_php_url() )
);
wp_update_php_annotation( '<br><em>', '</em>' );
}
}
/**
* Fires at the end of the update message container in each
* row of the plugins list table.
*
* The dynamic portion of the hook name, `$file`, refers to the path
* of the plugin's primary file relative to the plugins directory.
*
* @since 2.8.0
*
* @param array $plugin_data An array of plugin metadata. See get_plugin_data()
* and the {@see 'plugin_row_meta'} filter for the list
* of possible values.
* @param object $response {
* An object of metadata about the available plugin update.
*
* @type string $id Plugin ID, e.g. `w.org/plugins/[plugin-name]`.
* @type string $slug Plugin slug.
* @type string $plugin Plugin basename.
* @type string $new_version New plugin version.
* @type string $url Plugin URL.
* @type string $package Plugin update package URL.
* @type string[] $icons An array of plugin icon URLs.
* @type string[] $banners An array of plugin banner URLs.
* @type string[] $banners_rtl An array of plugin RTL banner URLs.
* @type string $requires The version of WordPress which the plugin requires.
* @type string $tested The version of WordPress the plugin is tested against.
* @type string $requires_php The version of PHP which the plugin requires.
* }
*/
do_action( "in_plugin_update_message-{$file}", $plugin_data, $response ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
echo '</p></div></td></tr>';
}
}
```
[do\_action( "in\_plugin\_update\_message-{$file}", array $plugin\_data, object $response )](../hooks/in_plugin_update_message-file)
Fires at the end of the update message container in each row of the plugins list table.
| Uses | Description |
| --- | --- |
| [is\_php\_version\_compatible()](is_php_version_compatible) wp-includes/functions.php | Checks compatibility with the current PHP version. |
| [\_get\_list\_table()](_get_list_table) wp-admin/includes/list-table.php | Fetches an instance of a [WP\_List\_Table](../classes/wp_list_table) class. |
| [self\_admin\_url()](self_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for either the current site or the network depending on context. |
| [is\_network\_admin()](is_network_admin) wp-includes/load.php | Determines whether the current request is for the network administrative interface. |
| [wp\_kses()](wp_kses) wp-includes/kses.php | Filters text content and strips out disallowed HTML. |
| [wp\_get\_update\_php\_url()](wp_get_update_php_url) wp-includes/functions.php | Gets the URL to learn more about updating the PHP version the site is running on. |
| [get\_site\_transient()](get_site_transient) wp-includes/option.php | Retrieves the value of a site transient. |
| [is\_plugin\_active()](is_plugin_active) wp-admin/includes/plugin.php | Determines whether a plugin is active. |
| [is\_plugin\_active\_for\_network()](is_plugin_active_for_network) wp-admin/includes/plugin.php | Determines whether the plugin is active for the entire network. |
| [WP\_List\_Table::get\_column\_count()](../classes/wp_list_table/get_column_count) wp-admin/includes/class-wp-list-table.php | Returns the number of visible columns. |
| [get\_current\_screen()](get_current_screen) wp-admin/includes/screen.php | Get the current screen object |
| [wp\_update\_php\_annotation()](wp_update_php_annotation) wp-includes/functions.php | Prints the default annotation for the web host altering the “Update PHP” page URL. |
| [current\_user\_can()](current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_attr()](esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [is\_multisite()](is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [wp\_nonce\_url()](wp_nonce_url) wp-includes/functions.php | Retrieves URL with nonce added to URL query. |
| [add\_query\_arg()](add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [\_x()](_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| Version | Description |
| --- | --- |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
wordpress is_paged(): bool is\_paged(): bool
=================
Determines whether the query is for a paged result and not for the first page.
For more information on this and similar theme functions, check out the [Conditional Tags](https://developer.wordpress.org/themes/basics/conditional-tags/) article in the Theme Developer Handbook.
bool Whether the query is for a paged result.
File: `wp-includes/query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/query.php/)
```
function is_paged() {
global $wp_query;
if ( ! isset( $wp_query ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
return false;
}
return $wp_query->is_paged();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Query::is\_paged()](../classes/wp_query/is_paged) wp-includes/class-wp-query.php | Is the query for a paged result and not for the first page? |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_doing\_it\_wrong()](_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Used By | Description |
| --- | --- |
| [get\_custom\_logo()](get_custom_logo) wp-includes/general-template.php | Returns a custom logo, linked to home unless the theme supports removing the link on the home page. |
| [WP::handle\_404()](../classes/wp/handle_404) wp-includes/class-wp.php | Set the Headers for 404, if nothing is found for requested URL. |
| [wp\_page\_menu()](wp_page_menu) wp-includes/post-template.php | Displays or retrieves a list of pages with an optional home link. |
| [get\_post\_class()](get_post_class) wp-includes/post-template.php | Retrieves an array of the class names for the post container element. |
| [get\_body\_class()](get_body_class) wp-includes/post-template.php | Retrieves an array of the class names for the body element. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress confirm_blog_signup( string $domain, string $path, string $blog_title, string $user_name = '', string $user_email = '', array $meta = array() ) confirm\_blog\_signup( string $domain, string $path, string $blog\_title, string $user\_name = '', string $user\_email = '', array $meta = array() )
====================================================================================================================================================
Shows a message confirming that the new site has been registered and is awaiting activation.
`$domain` string Required The domain or subdomain of the site. `$path` string Required The path of the site. `$blog_title` string Required The title of the new site. `$user_name` string Optional The user's username. Default: `''`
`$user_email` string Optional The user's email address. Default: `''`
`$meta` array Optional Any additional meta from the ['add\_signup\_meta'](../hooks/add_signup_meta) filter in [validate\_blog\_signup()](validate_blog_signup) . Default: `array()`
File: `wp-signup.php`. [View all references](https://developer.wordpress.org/reference/files/wp-signup.php/)
```
function confirm_blog_signup( $domain, $path, $blog_title, $user_name = '', $user_email = '', $meta = array() ) {
?>
<h2>
<?php
/* translators: %s: Site address. */
printf( __( 'Congratulations! Your new site, %s, is almost ready.' ), "<a href='http://{$domain}{$path}'>{$blog_title}</a>" )
?>
</h2>
<p><?php _e( 'But, before you can start using your site, <strong>you must activate it</strong>.' ); ?></p>
<p>
<?php
/* translators: %s: Email address. */
printf( __( 'Check your inbox at %s and click the link given.' ), '<strong>' . $user_email . '</strong>' );
?>
</p>
<p><?php _e( 'If you do not activate your site within two days, you will have to sign up again.' ); ?></p>
<h2><?php _e( 'Still waiting for your email?' ); ?></h2>
<p><?php _e( 'If you have not received your email yet, there are a number of things you can do:' ); ?></p>
<ul id="noemail-tips">
<li><p><strong><?php _e( 'Wait a little longer. Sometimes delivery of email can be delayed by processes outside of our control.' ); ?></strong></p></li>
<li><p><?php _e( 'Check the junk or spam folder of your email client. Sometime emails wind up there by mistake.' ); ?></p></li>
<li>
<?php
/* translators: %s: Email address. */
printf( __( 'Have you entered your email correctly? You have entered %s, if it’s incorrect, you will not receive your email.' ), $user_email );
?>
</li>
</ul>
<?php
/** This action is documented in wp-signup.php */
do_action( 'signup_finished' );
}
```
[do\_action( 'signup\_finished' )](../hooks/signup_finished)
Fires when the site or user sign-up process is complete.
| Uses | Description |
| --- | --- |
| [\_\_()](__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_e()](_e) wp-includes/l10n.php | Displays translated text. |
| [do\_action()](do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [validate\_blog\_signup()](validate_blog_signup) wp-signup.php | Validates new site signup. |
| Version | Description |
| --- | --- |
| [MU (3.0.0)](https://developer.wordpress.org/reference/since/mu.3.0.0/) | Introduced. |
wordpress media_upload_type_url_form( string $type = null, object $errors = null, int $id = null ) media\_upload\_type\_url\_form( string $type = null, object $errors = null, int $id = null )
============================================================================================
Outputs the legacy media upload form for external media.
`$type` string Optional Default: `null`
`$errors` object Optional Default: `null`
`$id` int Optional Default: `null`
File: `wp-admin/includes/media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/media.php/)
```
function media_upload_type_url_form( $type = null, $errors = null, $id = null ) {
if ( null === $type ) {
$type = 'image';
}
media_upload_header();
$post_id = isset( $_REQUEST['post_id'] ) ? (int) $_REQUEST['post_id'] : 0;
$form_action_url = admin_url( "media-upload.php?type=$type&tab=type&post_id=$post_id" );
/** This filter is documented in wp-admin/includes/media.php */
$form_action_url = apply_filters( 'media_upload_form_url', $form_action_url, $type );
$form_class = 'media-upload-form type-form validate';
if ( get_user_setting( 'uploader' ) ) {
$form_class .= ' html-uploader';
}
?>
<form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="<?php echo $type; ?>-form">
<input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
<?php wp_nonce_field( 'media-form' ); ?>
<h3 class="media-title"><?php _e( 'Insert media from another website' ); ?></h3>
<script type="text/javascript">
var addExtImage = {
width : '',
height : '',
align : 'alignnone',
insert : function() {
var t = this, html, f = document.forms[0], cls, title = '', alt = '', caption = '';
if ( '' === f.src.value || '' === t.width )
return false;
if ( f.alt.value )
alt = f.alt.value.replace(/'/g, ''').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
<?php
/** This filter is documented in wp-admin/includes/media.php */
if ( ! apply_filters( 'disable_captions', '' ) ) {
?>
if ( f.caption.value ) {
caption = f.caption.value.replace(/\r\n|\r/g, '\n');
caption = caption.replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(a){
return a.replace(/[\r\n\t]+/, ' ');
});
caption = caption.replace(/\s*\n\s*/g, '<br />');
}
<?php
}
?>
cls = caption ? '' : ' class="'+t.align+'"';
html = '<img alt="'+alt+'" src="'+f.src.value+'"'+cls+' width="'+t.width+'" height="'+t.height+'" />';
if ( f.url.value ) {
url = f.url.value.replace(/'/g, ''').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
html = '<a href="'+url+'">'+html+'</a>';
}
if ( caption )
html = '[caption id="" align="'+t.align+'" width="'+t.width+'"]'+html+caption+'[/caption]';
var win = window.dialogArguments || opener || parent || top;
win.send_to_editor(html);
return false;
},
resetImageData : function() {
var t = addExtImage;
t.width = t.height = '';
document.getElementById('go_button').style.color = '#bbb';
if ( ! document.forms[0].src.value )
document.getElementById('status_img').innerHTML = '';
else document.getElementById('status_img').innerHTML = '<img src="<?php echo esc_url( admin_url( 'images/no.png' ) ); ?>" alt="" />';
},
updateImageData : function() {
var t = addExtImage;
t.width = t.preloadImg.width;
t.height = t.preloadImg.height;
document.getElementById('go_button').style.color = '#333';
document.getElementById('status_img').innerHTML = '<img src="<?php echo esc_url( admin_url( 'images/yes.png' ) ); ?>" alt="" />';
},
getImageData : function() {
if ( jQuery('table.describe').hasClass('not-image') )
return;
var t = addExtImage, src = document.forms[0].src.value;
if ( ! src ) {
t.resetImageData();
return false;
}
document.getElementById('status_img').innerHTML = '<img src="<?php echo esc_url( admin_url( 'images/spinner-2x.gif' ) ); ?>" alt="" width="16" height="16" />';
t.preloadImg = new Image();
t.preloadImg.onload = t.updateImageData;
t.preloadImg.onerror = t.resetImageData;
t.preloadImg.src = src;
}
};
jQuery( function($) {
$('.media-types input').click( function() {
$('table.describe').toggleClass('not-image', $('#not-image').prop('checked') );
});
} );
</script>
<div id="media-items">
<div class="media-item media-blank">
<?php
/**
* Filters the insert media from URL form HTML.
*
* @since 3.3.0
*
* @param string $form_html The insert from URL form HTML.
*/
echo apply_filters( 'type_url_form_media', wp_media_insert_url_form( $type ) );
?>
</div>
</div>
</form>
<?php
}
```
[apply\_filters( 'disable\_captions', bool $bool )](../hooks/disable_captions)
Filters whether to disable captions.
[apply\_filters( 'media\_upload\_form\_url', string $form\_action\_url, string $type )](../hooks/media_upload_form_url)
Filters the media upload form action URL.
[apply\_filters( 'type\_url\_form\_media', string $form\_html )](../hooks/type_url_form_media)
Filters the insert media from URL form HTML.
| Uses | Description |
| --- | --- |
| [wp\_media\_insert\_url\_form()](wp_media_insert_url_form) wp-admin/includes/media.php | Creates the form for external url. |
| [media\_upload\_header()](media_upload_header) wp-admin/includes/media.php | Outputs the legacy media upload header. |
| [wp\_nonce\_field()](wp_nonce_field) wp-includes/functions.php | Retrieves or display nonce hidden field for forms. |
| [get\_user\_setting()](get_user_setting) wp-includes/option.php | Retrieves user interface setting value based on setting name. |
| [\_e()](_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_url()](esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [admin\_url()](admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
| programming_docs |
wordpress get_taxonomy_labels( WP_Taxonomy $tax ): object get\_taxonomy\_labels( WP\_Taxonomy $tax ): object
==================================================
Builds an object with all taxonomy labels out of a taxonomy object.
`$tax` [WP\_Taxonomy](../classes/wp_taxonomy) Required Taxonomy object. object Taxonomy labels object. The first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories).
* `name`stringGeneral name for the taxonomy, usually plural. The same as and overridden by `$tax->label`. Default `'Tags'`/`'Categories'`.
* `singular_name`stringName for one object of this taxonomy. Default `'Tag'`/`'Category'`.
* `search_items`stringDefault 'Search Tags`'/'`Search Categories'.
* `popular_items`stringThis label is only used for non-hierarchical taxonomies.
Default 'Popular Tags'.
* `all_items`stringDefault 'All Tags`'/'`All Categories'.
* `parent_item`stringThis label is only used for hierarchical taxonomies. Default 'Parent Category'.
* `parent_item_colon`stringThe same as `parent_item`, but with colon `:` in the end.
* `name_field_description`stringDescription for the Name field on Edit Tags screen.
Default 'The name is how it appears on your site'.
* `slug_field_description`stringDescription for the Slug field on Edit Tags screen.
Default 'The “slug” is the URL-friendly version of the name. It is usually all lowercase and contains only letters, numbers, and hyphens'.
* `parent_field_description`stringDescription for the Parent field on Edit Tags screen.
Default 'Assign a parent term to create a hierarchy.
The term Jazz, for example, would be the parent of Bebop and Big Band'.
* `desc_field_description`stringDescription for the Description field on Edit Tags screen.
Default 'The description is not prominent by default; however, some themes may show it'.
* `edit_item`stringDefault 'Edit Tag`'/'`Edit Category'.
* `view_item`stringDefault 'View Tag`'/'`View Category'.
* `update_item`stringDefault 'Update Tag`'/'`Update Category'.
* `add_new_item`stringDefault 'Add New Tag`'/'`Add New Category'.
* `new_item_name`stringDefault 'New Tag Name`'/'`New Category Name'.
* `separate_items_with_commas`stringThis label is only used for non-hierarchical taxonomies. Default 'Separate tags with commas', used in the meta box.
* `add_or_remove_items`stringThis label is only used for non-hierarchical taxonomies. Default 'Add or remove tags', used in the meta box when JavaScript is disabled.
* `choose_from_most_used`stringThis label is only used on non-hierarchical taxonomies. Default 'Choose from the most used tags', used in the meta box.
* `not_found`stringDefault 'No tags found`'/'`No categories found', used in the meta box and taxonomy list table.
* `no_terms`stringDefault 'No tags`'/'`No categories', used in the posts and media list tables.
* `filter_by_item`stringThis label is only used for hierarchical taxonomies. Default 'Filter by category', used in the posts list table.
* `items_list_navigation`stringLabel for the table pagination hidden heading.
* `items_list`stringLabel for the table hidden heading.
* `most_used`stringTitle for the Most Used tab. Default 'Most Used'.
* `back_to_items`stringLabel displayed after a term has been updated.
* `item_link`stringUsed in the block editor. Title for a navigation link block variation.
Default 'Tag Link`'/'`Category Link'.
* `item_link_description`stringUsed in the block editor. Description for a navigation link block variation. Default 'A link to a tag`'/'`A link to a category'.
File: `wp-includes/taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/taxonomy.php/)
```
function get_taxonomy_labels( $tax ) {
$tax->labels = (array) $tax->labels;
if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) ) {
$tax->labels['separate_items_with_commas'] = $tax->helps;
}
if ( isset( $tax->no_tagcloud ) && empty( $tax->labels['not_found'] ) ) {
$tax->labels['not_found'] = $tax->no_tagcloud;
}
$nohier_vs_hier_defaults = WP_Taxonomy::get_default_labels();
$nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
$labels = _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
$taxonomy = $tax->name;
$default_labels = clone $labels;
/**
* Filters the labels of a specific taxonomy.
*
* The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
*
* Possible hook names include:
*
* - `taxonomy_labels_category`
* - `taxonomy_labels_post_tag`
*
* @since 4.4.0
*
* @see get_taxonomy_labels() for the full list of taxonomy labels.
*
* @param object $labels Object with labels for the taxonomy as member variables.
*/
$labels = apply_filters( "taxonomy_labels_{$taxonomy}", $labels );
// Ensure that the filtered labels contain all required default values.
$labels = (object) array_merge( (array) $default_labels, (array) $labels );
return $labels;
}
```
[apply\_filters( "taxonomy\_labels\_{$taxonomy}", object $labels )](../hooks/taxonomy_labels_taxonomy)
Filters the labels of a specific taxonomy.
| Uses | Description |
| --- | --- |
| [WP\_Taxonomy::get\_default\_labels()](../classes/wp_taxonomy/get_default_labels) wp-includes/class-wp-taxonomy.php | Returns the default labels for taxonomies. |
| [\_get\_custom\_object\_labels()](_get_custom_object_labels) wp-includes/post.php | Builds an object with custom-something object (post type, taxonomy) labels out of a custom-something object |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Taxonomy::set\_props()](../classes/wp_taxonomy/set_props) wp-includes/class-wp-taxonomy.php | Sets taxonomy properties. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Added the `name_field_description`, `slug_field_description`, `parent_field_description`, and `desc_field_description` labels. |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Added the `item_link` and `item_link_description` labels. |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Added the `filter_by_item` label. |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Added the `most_used` and `back_to_items` labels. |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Added the `items_list_navigation` and `items_list` labels. |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Added the `no_terms` label. |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress wp_generate_auth_cookie( int $user_id, int $expiration, string $scheme = 'auth', string $token = '' ): string wp\_generate\_auth\_cookie( int $user\_id, int $expiration, string $scheme = 'auth', string $token = '' ): string
=================================================================================================================
Generates authentication cookie contents.
`$user_id` int Required User ID. `$expiration` int Required The time the cookie expires as a UNIX timestamp. `$scheme` string Optional The cookie scheme to use: `'auth'`, `'secure_auth'`, or `'logged_in'`.
Default `'auth'`. Default: `'auth'`
`$token` string Optional User's session token to use for this cookie. Default: `''`
string Authentication cookie contents. Empty string if user does not exist.
File: `wp-includes/pluggable.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pluggable.php/)
```
function wp_generate_auth_cookie( $user_id, $expiration, $scheme = 'auth', $token = '' ) {
$user = get_userdata( $user_id );
if ( ! $user ) {
return '';
}
if ( ! $token ) {
$manager = WP_Session_Tokens::get_instance( $user_id );
$token = $manager->create( $expiration );
}
$pass_frag = substr( $user->user_pass, 8, 4 );
$key = wp_hash( $user->user_login . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme );
// If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
$algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
$hash = hash_hmac( $algo, $user->user_login . '|' . $expiration . '|' . $token, $key );
$cookie = $user->user_login . '|' . $expiration . '|' . $token . '|' . $hash;
/**
* Filters the authentication cookie.
*
* @since 2.5.0
* @since 4.0.0 The `$token` parameter was added.
*
* @param string $cookie Authentication cookie.
* @param int $user_id User ID.
* @param int $expiration The time the cookie expires as a UNIX timestamp.
* @param string $scheme Cookie scheme used. Accepts 'auth', 'secure_auth', or 'logged_in'.
* @param string $token User's session token used.
*/
return apply_filters( 'auth_cookie', $cookie, $user_id, $expiration, $scheme, $token );
}
```
[apply\_filters( 'auth\_cookie', string $cookie, int $user\_id, int $expiration, string $scheme, string $token )](../hooks/auth_cookie)
Filters the authentication cookie.
| Uses | Description |
| --- | --- |
| [WP\_Session\_Tokens::get\_instance()](../classes/wp_session_tokens/get_instance) wp-includes/class-wp-session-tokens.php | Retrieves a session manager instance for a user. |
| [wp\_hash()](wp_hash) wp-includes/pluggable.php | Gets hash of given string. |
| [get\_userdata()](get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [apply\_filters()](apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_set\_auth\_cookie()](wp_set_auth_cookie) wp-includes/pluggable.php | Sets the authentication cookies based on user ID. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | The `$token` parameter was added. |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress _post_type_meta_capabilities( string[] $capabilities = null ) \_post\_type\_meta\_capabilities( string[] $capabilities = null )
=================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Stores or returns a list of post type meta caps for [map\_meta\_cap()](map_meta_cap) .
`$capabilities` string[] Optional Post type meta capabilities. Default: `null`
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function _post_type_meta_capabilities( $capabilities = null ) {
global $post_type_meta_caps;
foreach ( $capabilities as $core => $custom ) {
if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ), true ) ) {
$post_type_meta_caps[ $custom ] = $core;
}
}
}
```
| Used By | Description |
| --- | --- |
| [get\_post\_type\_capabilities()](get_post_type_capabilities) wp-includes/post.php | Builds an object with all post type capabilities out of a post type object |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress wp_color_scheme_settings() wp\_color\_scheme\_settings()
=============================
File: `wp-admin/includes/misc.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/misc.php/)
```
function wp_color_scheme_settings() {
global $_wp_admin_css_colors;
$color_scheme = get_user_option( 'admin_color' );
// It's possible to have a color scheme set that is no longer registered.
if ( empty( $_wp_admin_css_colors[ $color_scheme ] ) ) {
$color_scheme = 'fresh';
}
if ( ! empty( $_wp_admin_css_colors[ $color_scheme ]->icon_colors ) ) {
$icon_colors = $_wp_admin_css_colors[ $color_scheme ]->icon_colors;
} elseif ( ! empty( $_wp_admin_css_colors['fresh']->icon_colors ) ) {
$icon_colors = $_wp_admin_css_colors['fresh']->icon_colors;
} else {
// Fall back to the default set of icon colors if the default scheme is missing.
$icon_colors = array(
'base' => '#a7aaad',
'focus' => '#72aee6',
'current' => '#fff',
);
}
echo '<script type="text/javascript">var _wpColorScheme = ' . wp_json_encode( array( 'icons' => $icon_colors ) ) . ";</script>\n";
}
```
| Uses | Description |
| --- | --- |
| [get\_user\_option()](get_user_option) wp-includes/user.php | Retrieves user option that can be either per Site or per Network. |
| [wp\_json\_encode()](wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
wordpress saveDomDocument( DOMDocument $doc, string $filename ) saveDomDocument( DOMDocument $doc, string $filename )
=====================================================
Saves the XML document into a file.
`$doc` DOMDocument Required `$filename` string Required File: `wp-admin/includes/misc.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/misc.php/)
```
function saveDomDocument( $doc, $filename ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
$config = $doc->saveXML();
$config = preg_replace( "/([^\r])\n/", "$1\r\n", $config );
$fp = fopen( $filename, 'w' );
fwrite( $fp, $config );
fclose( $fp );
}
```
| Used By | Description |
| --- | --- |
| [iis7\_delete\_rewrite\_rule()](iis7_delete_rewrite_rule) wp-admin/includes/misc.php | Deletes WordPress rewrite rule from web.config file if it exists there. |
| [iis7\_add\_rewrite\_rule()](iis7_add_rewrite_rule) wp-admin/includes/misc.php | Adds WordPress rewrite rule to the IIS 7+ configuration file. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress the_author_login() the\_author\_login()
====================
This function has been deprecated. Use [the\_author\_meta()](the_author_meta) instead.
Display the login name of the author of the current post.
* [the\_author\_meta()](the_author_meta)
File: `wp-includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/deprecated.php/)
```
function the_author_login() {
_deprecated_function( __FUNCTION__, '2.8.0', 'the_author_meta(\'login\')' );
the_author_meta('login');
}
```
| Uses | Description |
| --- | --- |
| [the\_author\_meta()](the_author_meta) wp-includes/author-template.php | Outputs the field from the user’s DB object. Defaults to current post’s author. |
| [\_deprecated\_function()](_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Use [the\_author\_meta()](the_author_meta) |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress wp_get_post_tags( int $post_id, array $args = array() ): array|WP_Error wp\_get\_post\_tags( int $post\_id, array $args = array() ): array|WP\_Error
============================================================================
Retrieves the tags for a post.
There is only one default for this function, called ‘fields’ and by default is set to ‘all’. There are other defaults that can be overridden in [wp\_get\_object\_terms()](wp_get_object_terms) .
`$post_id` int Optional The Post ID. Does not default to the ID of the global $post. Default 0. `$args` array Optional Tag query parameters.
See [WP\_Term\_Query::\_\_construct()](../classes/wp_term_query/__construct) for supported arguments. More Arguments from WP\_Term\_Query::\_\_construct( ... $query ) Array or query string of term query parameters.
* `taxonomy`string|string[]Taxonomy name, or array of taxonomy names, to which results should be limited.
* `object_ids`int|int[]Object ID, or array of object IDs. Results will be limited to terms associated with these objects.
* `orderby`stringField(s) to order terms by. Accepts:
+ Term fields (`'name'`, `'slug'`, `'term_group'`, `'term_id'`, `'id'`, `'description'`, `'parent'`, `'term_order'`). Unless `$object_ids` is not empty, `'term_order'` is treated the same as `'term_id'`.
+ `'count'` to use the number of objects associated with the term.
+ `'include'` to match the `'order'` of the `$include` param.
+ `'slug__in'` to match the `'order'` of the `$slug` param.
+ `'meta_value'`
+ `'meta_value_num'`.
+ The value of `$meta_key`.
+ The array keys of `$meta_query`.
+ `'none'` to omit the ORDER BY clause. Default `'name'`.
* `order`stringWhether to order terms in ascending or descending order.
Accepts `'ASC'` (ascending) or `'DESC'` (descending).
Default `'ASC'`.
* `hide_empty`bool|intWhether to hide terms not assigned to any posts. Accepts `1|true` or `0|false`. Default `1|true`.
* `include`int[]|stringArray or comma/space-separated string of term IDs to include.
Default empty array.
* `exclude`int[]|stringArray or comma/space-separated string of term IDs to exclude.
If `$include` is non-empty, `$exclude` is ignored.
Default empty array.
* `exclude_tree`int[]|stringArray or comma/space-separated string of term IDs to exclude along with all of their descendant terms. If `$include` is non-empty, `$exclude_tree` is ignored. Default empty array.
* `number`int|stringMaximum number of terms to return. Accepts ``''`|0` (all) or any positive number. Default ``''`|0` (all). Note that `$number` may not return accurate results when coupled with `$object_ids`.
See #41796 for details.
* `offset`intThe number by which to offset the terms query.
* `fields`stringTerm fields to query for. Accepts:
+ `'all'` Returns an array of complete term objects (`WP_Term[]`).
+ `'all_with_object_id'` Returns an array of term objects with the `'object_id'` param (`WP_Term[]`). Works only when the `$object_ids` parameter is populated.
+ `'ids'` Returns an array of term IDs (`int[]`).
+ `'tt_ids'` Returns an array of term taxonomy IDs (`int[]`).
+ `'names'` Returns an array of term names (`string[]`).
+ `'slugs'` Returns an array of term slugs (`string[]`).
+ `'count'` Returns the number of matching terms (`int`).
+ `'id=>parent'` Returns an associative array of parent term IDs, keyed by term ID (`int[]`).
+ `'id=>name'` Returns an associative array of term names, keyed by term ID (`string[]`).
+ `'id=>slug'` Returns an associative array of term slugs, keyed by term ID (`string[]`). Default `'all'`.
* `count`boolWhether to return a term count. If true, will take precedence over `$fields`. Default false.
* `name`string|string[]Name or array of names to return term(s) for.
* `slug`string|string[]Slug or array of slugs to return term(s) for.
* `term_taxonomy_id`int|int[]Term taxonomy ID, or array of term taxonomy IDs, to match when querying terms.
* `hierarchical`boolWhether to include terms that have non-empty descendants (even if `$hide_empty` is set to true). Default true.
* `search`stringSearch criteria to match terms. Will be SQL-formatted with wildcards before and after.
* `name__like`stringRetrieve terms with criteria by which a term is LIKE `$name__like`.
* `description__like`stringRetrieve terms where the description is LIKE `$description__like`.
* `pad_counts`boolWhether to pad the quantity of a term's children in the quantity of each term's "count" object variable. Default false.
* `get`stringWhether to return terms regardless of ancestry or whether the terms are empty. Accepts `'all'` or `''` (disabled). Default `''`.
* `child_of`intTerm ID to retrieve child terms of. If multiple taxonomies are passed, `$child_of` is ignored. Default 0.
* `parent`intParent term ID to retrieve direct-child terms of.
* `childless`boolTrue to limit results to terms that have no children.
This parameter has no effect on non-hierarchical taxonomies.
Default false.
* `cache_domain`stringUnique cache key to be produced when this query is stored in an object cache. Default `'core'`.
* `update_term_meta_cache`boolWhether to prime meta caches for matched terms. Default true.
* `meta_key`string|string[]Meta key or keys to filter by.
* `meta_value`string|string[]Meta value or values to filter by.
* `meta_compare`stringMySQL operator used for comparing the meta value.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values and default value.
* `meta_compare_key`stringMySQL operator used for comparing the meta key.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values and default value.
* `meta_type`stringMySQL data type that the meta\_value column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values and default value.
* `meta_type_key`stringMySQL data type that the meta\_key column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values and default value.
* `meta_query`arrayAn associative array of [WP\_Meta\_Query](../classes/wp_meta_query) arguments.
See [WP\_Meta\_Query::\_\_construct()](../classes/wp_meta_query/__construct) for accepted values.
Default: `array()`
array|[WP\_Error](../classes/wp_error) Array of [WP\_Term](../classes/wp_term) objects on success or empty array if no tags were found.
[WP\_Error](../classes/wp_error) object if `'post_tag'` taxonomy doesn't exist.
File: `wp-includes/post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/post.php/)
```
function wp_get_post_tags( $post_id = 0, $args = array() ) {
return wp_get_post_terms( $post_id, 'post_tag', $args );
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_post\_terms()](wp_get_post_terms) wp-includes/post.php | Retrieves the terms for a post. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::mw\_getPost()](../classes/wp_xmlrpc_server/mw_getpost) wp-includes/class-wp-xmlrpc-server.php | Retrieve post. |
| [wp\_xmlrpc\_server::mw\_getRecentPosts()](../classes/wp_xmlrpc_server/mw_getrecentposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve list of recent posts. |
| Version | Description |
| --- | --- |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
| programming_docs |
wordpress _prime_term_caches( array $term_ids, bool $update_meta_cache = true ) \_prime\_term\_caches( array $term\_ids, bool $update\_meta\_cache = true )
===========================================================================
Adds any terms from the given IDs to the cache that do not already exist in cache.
`$term_ids` array Required Array of term IDs. `$update_meta_cache` bool Optional Whether to update the meta cache. Default: `true`
File: `wp-includes/taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/taxonomy.php/)
```
function _prime_term_caches( $term_ids, $update_meta_cache = true ) {
global $wpdb;
$non_cached_ids = _get_non_cached_ids( $term_ids, 'terms' );
if ( ! empty( $non_cached_ids ) ) {
$fresh_terms = $wpdb->get_results( sprintf( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE t.term_id IN (%s)", implode( ',', array_map( 'intval', $non_cached_ids ) ) ) );
update_term_cache( $fresh_terms );
if ( $update_meta_cache ) {
update_termmeta_cache( $non_cached_ids );
}
}
}
```
| Uses | Description |
| --- | --- |
| [update\_termmeta\_cache()](update_termmeta_cache) wp-includes/taxonomy.php | Updates metadata cache for list of term IDs. |
| [\_get\_non\_cached\_ids()](_get_non_cached_ids) wp-includes/functions.php | Retrieves IDs that are not already present in the cache. |
| [update\_term\_cache()](update_term_cache) wp-includes/taxonomy.php | Updates terms in cache. |
| [wpdb::get\_results()](../classes/wpdb/get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| Used By | Description |
| --- | --- |
| [update\_menu\_item\_cache()](update_menu_item_cache) wp-includes/nav-menu.php | Updates post and term caches for all linked objects for a list of menu items. |
| [WP\_Term\_Query::get\_terms()](../classes/wp_term_query/get_terms) wp-includes/class-wp-term-query.php | Retrieves the query results. |
| [get\_object\_term\_cache()](get_object_term_cache) wp-includes/taxonomy.php | Retrieves the cached term objects for the given object ID. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | This function is no longer marked as "private". |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
nix None `builtins.abort s`
------------------
Abort Nix expression evaluation and print the error message *s*.
`builtins.add e1 e2`
--------------------
Return the sum of the numbers *e1* and *e2*.
`builtins.all pred list`
------------------------
Return `true` if the function *pred* returns `true` for all elements of *list*, and `false` otherwise.
`builtins.any pred list`
------------------------
Return `true` if the function *pred* returns `true` for at least one element of *list*, and `false` otherwise.
`builtins.attrNames set`
------------------------
Return the names of the attributes in the set *set* in an alphabetically sorted list. For instance, `builtins.attrNames { y = 1; x = "foo"; }` evaluates to `[ "x" "y" ]`.
`builtins.attrValues set`
-------------------------
Return the values of the attributes in the set *set* in the order corresponding to the sorted attribute names.
`builtins.baseNameOf s`
-----------------------
Return the *base name* of the string *s*, that is, everything following the final slash in the string. This is similar to the GNU `basename` command.
`builtins.bitAnd e1 e2`
-----------------------
Return the bitwise AND of the integers *e1* and *e2*.
`builtins.bitOr e1 e2`
----------------------
Return the bitwise OR of the integers *e1* and *e2*.
`builtins.bitXor e1 e2`
-----------------------
Return the bitwise XOR of the integers *e1* and *e2*.
`builtins.break v`
------------------
In debug mode (enabled using `--debugger`), pause Nix expression evaluation and enter the REPL. Otherwise, return the argument `v`.
`builtins.catAttrs attr list`
-----------------------------
Collect each attribute named *attr* from a list of attribute sets. Attrsets that don't contain the named attribute are ignored. For example,
```
builtins.catAttrs "a" [{a = 1;} {b = 0;} {a = 2;}]
```
evaluates to `[1 2]`.
`builtins.ceil double`
----------------------
Converts an IEEE-754 double-precision floating-point number (*double*) to the next higher integer.
If the datatype is neither an integer nor a "float", an evaluation error will be thrown.
`builtins.compareVersions s1 s2`
--------------------------------
Compare two strings representing versions and return `-1` if version *s1* is older than version *s2*, `0` if they are the same, and `1` if *s1* is newer than *s2*. The version comparison algorithm is the same as the one used by [`nix-env -u`](https://nixos.org/manual/nix/stable/command-ref/nix-env.html#operation---upgrade).
`builtins.concatLists lists`
----------------------------
Concatenate a list of lists into a single list.
`builtins.concatMap f list`
---------------------------
This function is equivalent to `builtins.concatLists (map f list)` but is more efficient.
`builtins.concatStringsSep separator list`
------------------------------------------
Concatenate a list of strings with a separator between each element, e.g. `concatStringsSep "/" ["usr" "local" "bin"] == "usr/local/bin"`.
`builtins.deepSeq e1 e2`
------------------------
This is like `seq e1 e2`, except that *e1* is evaluated *deeply*: if it’s a list or set, its elements or attributes are also evaluated recursively.
`builtins.dirOf s`
------------------
Return the directory part of the string *s*, that is, everything before the final slash in the string. This is similar to the GNU `dirname` command.
`builtins.div e1 e2`
--------------------
Return the quotient of the numbers *e1* and *e2*.
`builtins.elem x xs`
--------------------
Return `true` if a value equal to *x* occurs in the list *xs*, and `false` otherwise.
`builtins.elemAt xs n`
----------------------
Return element *n* from the list *xs*. Elements are counted starting from 0. A fatal error occurs if the index is out of bounds.
`builtins.fetchClosure args`
----------------------------
Fetch a Nix store closure from a binary cache, rewriting it into content-addressed form. For example,
```
builtins.fetchClosure {
fromStore = "https://cache.nixos.org";
fromPath = /nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1;
toPath = /nix/store/ldbhlwhh39wha58rm61bkiiwm6j7211j-git-2.33.1;
}
```
fetches `/nix/store/r2jd...` from the specified binary cache, and rewrites it into the content-addressed store path `/nix/store/ldbh...`.
If `fromPath` is already content-addressed, or if you are allowing impure evaluation (`--impure`), then `toPath` may be omitted.
To find out the correct value for `toPath` given a `fromPath`, you can use `nix store make-content-addressed`:
```
# nix store make-content-addressed --from https://cache.nixos.org /nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1
rewrote '/nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1' to '/nix/store/ldbhlwhh39wha58rm61bkiiwm6j7211j-git-2.33.1'
```
This function is similar to `builtins.storePath` in that it allows you to use a previously built store path in a Nix expression. However, it is more reproducible because it requires specifying a binary cache from which the path can be fetched. Also, requiring a content-addressed final store path avoids the need for users to configure binary cache public keys.
This function is only available if you enable the experimental feature `fetch-closure`.
`builtins.fetchGit args`
------------------------
Fetch a path from git. *args* can be a URL, in which case the HEAD of the repo at that URL is fetched. Otherwise, it can be an attribute with the following attributes (all except `url` optional):
* url
The URL of the repo.
* name
The name of the directory the repo should be exported to in the store. Defaults to the basename of the URL.
* rev
The git revision to fetch. Defaults to the tip of `ref`.
* ref
The git ref to look for the requested revision under. This is often a branch or tag name. Defaults to `HEAD`.
By default, the `ref` value is prefixed with `refs/heads/`. As of Nix 2.3.0 Nix will not prefix `refs/heads/` if `ref` starts with `refs/`.
* submodules
A Boolean parameter that specifies whether submodules should be checked out. Defaults to `false`.
* shallow
A Boolean parameter that specifies whether fetching a shallow clone is allowed. Defaults to `false`.
* allRefs
Whether to fetch all refs of the repository. With this argument being true, it's possible to load a `rev` from *any* `ref` (by default only `rev`s from the specified `ref` are supported).
Here are some examples of how to use `fetchGit`.
* To fetch a private repository over SSH:
```
builtins.fetchGit {
url = "[email protected]:my-secret/repository.git";
ref = "master";
rev = "adab8b916a45068c044658c4158d81878f9ed1c3";
}
```
* To fetch an arbitrary reference:
```
builtins.fetchGit {
url = "https://github.com/NixOS/nix.git";
ref = "refs/heads/0.5-release";
}
```
* If the revision you're looking for is in the default branch of the git repository you don't strictly need to specify the branch name in the `ref` attribute.
However, if the revision you're looking for is in a future branch for the non-default branch you will need to specify the the `ref` attribute as well.
```
builtins.fetchGit {
url = "https://github.com/nixos/nix.git";
rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452";
ref = "1.11-maintenance";
}
```
> **Note**
>
> It is nice to always specify the branch which a revision belongs to. Without the branch being specified, the fetcher might fail if the default branch changes. Additionally, it can be confusing to try a commit from a non-default branch and see the fetch fail. If the branch is specified the fault is much more obvious.
>
>
* If the revision you're looking for is in the default branch of the git repository you may omit the `ref` attribute.
```
builtins.fetchGit {
url = "https://github.com/nixos/nix.git";
rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452";
}
```
* To fetch a specific tag:
```
builtins.fetchGit {
url = "https://github.com/nixos/nix.git";
ref = "refs/tags/1.9";
}
```
* To fetch the latest version of a remote branch:
```
builtins.fetchGit {
url = "ssh://[email protected]/nixos/nix.git";
ref = "master";
}
```
> **Note**
>
> Nix will refetch the branch in accordance with the option `tarball-ttl`.
>
>
> **Note**
>
> This behavior is disabled in *Pure evaluation mode*.
>
>
`builtins.fetchTarball args`
----------------------------
Download the specified URL, unpack it and return the path of the unpacked tree. The file must be a tape archive (`.tar`) compressed with `gzip`, `bzip2` or `xz`. The top-level path component of the files in the tarball is removed, so it is best if the tarball contains a single directory at top level. The typical use of the function is to obtain external Nix expression dependencies, such as a particular version of Nixpkgs, e.g.
```
with import (fetchTarball https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz) {};
stdenv.mkDerivation { … }
```
The fetched tarball is cached for a certain amount of time (1 hour by default) in `~/.cache/nix/tarballs/`. You can change the cache timeout either on the command line with `--tarball-ttl` *number-of-seconds* or in the Nix configuration file by adding the line `tarball-ttl =` *number-of-seconds*.
Note that when obtaining the hash with `nix-prefetch-url` the option `--unpack` is required.
This function can also verify the contents against a hash. In that case, the function takes a set instead of a URL. The set requires the attribute `url` and the attribute `sha256`, e.g.
```
with import (fetchTarball {
url = "https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz";
sha256 = "1jppksrfvbk5ypiqdz4cddxdl8z6zyzdb2srq8fcffr327ld5jj2";
}) {};
stdenv.mkDerivation { … }
```
This function is not available if [restricted evaluation mode](https://nixos.org/manual/nix/stable/command-ref/conf-file.html) is enabled.
`builtins.fetchurl url`
-----------------------
Download the specified URL and return the path of the downloaded file. This function is not available if [restricted evaluation mode](https://nixos.org/manual/nix/stable/command-ref/conf-file.html) is enabled.
`builtins.filter f list`
------------------------
Return a list consisting of the elements of *list* for which the function *f* returns `true`.
`builtins.filterSource e1 e2`
-----------------------------
> **Warning**
>
> `filterSource` should not be used to filter store paths. Since `filterSource` uses the name of the input directory while naming the output directory, doing so will produce a directory name in the form of `<hash2>-<hash>-<name>`, where `<hash>-<name>` is the name of the input directory. Since `<hash>` depends on the unfiltered directory, the name of the output directory will indirectly depend on files that are filtered out by the function. This will trigger a rebuild even when a filtered out file is changed. Use `builtins.path` instead, which allows specifying the name of the output directory.
>
>
This function allows you to copy sources into the Nix store while filtering certain files. For instance, suppose that you want to use the directory `source-dir` as an input to a Nix expression, e.g.
```
stdenv.mkDerivation {
...
src = ./source-dir;
}
```
However, if `source-dir` is a Subversion working copy, then all those annoying `.svn` subdirectories will also be copied to the store. Worse, the contents of those directories may change a lot, causing lots of spurious rebuilds. With `filterSource` you can filter out the `.svn` directories:
```
src = builtins.filterSource
(path: type: type != "directory" || baseNameOf path != ".svn")
./source-dir;
```
Thus, the first argument *e1* must be a predicate function that is called for each regular file, directory or symlink in the source tree *e2*. If the function returns `true`, the file is copied to the Nix store, otherwise it is omitted. The function is called with two arguments. The first is the full path of the file. The second is a string that identifies the type of the file, which is either `"regular"`, `"directory"`, `"symlink"` or `"unknown"` (for other kinds of files such as device nodes or fifos — but note that those cannot be copied to the Nix store, so if the predicate returns `true` for them, the copy will fail). If you exclude a directory, the entire corresponding subtree of *e2* will be excluded.
`builtins.floor double`
-----------------------
Converts an IEEE-754 double-precision floating-point number (*double*) to the next lower integer.
If the datatype is neither an integer nor a "float", an evaluation error will be thrown.
`builtins.foldl' op nul list`
-----------------------------
Reduce a list by applying a binary operator, from left to right, e.g. `foldl' op nul [x0 x1 x2 ...] = op (op (op nul x0) x1) x2) ...`. The operator is applied strictly, i.e., its arguments are evaluated first. For example, `foldl' (x: y: x + y) 0 [1 2 3]` evaluates to 6.
`builtins.fromJSON e`
---------------------
Convert a JSON string to a Nix value. For example,
```
builtins.fromJSON ''{"x": [1, 2, 3], "y": null}''
```
returns the value `{ x = [ 1 2 3 ]; y = null; }`.
`builtins.functionArgs f`
-------------------------
Return a set containing the names of the formal arguments expected by the function *f*. The value of each attribute is a Boolean denoting whether the corresponding argument has a default value. For instance, `functionArgs ({ x, y ? 123}: ...) = { x = false; y = true; }`.
"Formal argument" here refers to the attributes pattern-matched by the function. Plain lambdas are not included, e.g. `functionArgs (x: ...) = { }`.
`builtins.genList generator length`
-----------------------------------
Generate list of size *length*, with each element *i* equal to the value returned by *generator* `i`. For example,
```
builtins.genList (x: x * x) 5
```
returns the list `[ 0 1 4 9 16 ]`.
`builtins.genericClosure attrset`
---------------------------------
Take an *attrset* with values named `startSet` and `operator` in order to return a *list of attrsets* by starting with the `startSet`, recursively applying the `operator` function to each element. The *attrsets* in the `startSet` and produced by the `operator` must each contain value named `key` which are comparable to each other. The result is produced by repeatedly calling the operator for each element encountered with a unique key, terminating when no new elements are produced. For example,
```
builtins.genericClosure {
startSet = [ {key = 5;} ];
operator = item: [{
key = if (item.key / 2 ) * 2 == item.key
then item.key / 2
else 3 * item.key + 1;
}];
}
```
evaluates to
```
[ { key = 5; } { key = 16; } { key = 8; } { key = 4; } { key = 2; } { key = 1; } ]
```
`builtins.getAttr s set`
------------------------
`getAttr` returns the attribute named *s* from *set*. Evaluation aborts if the attribute doesn’t exist. This is a dynamic version of the `.` operator, since *s* is an expression rather than an identifier.
`builtins.getEnv s`
-------------------
`getEnv` returns the value of the environment variable *s*, or an empty string if the variable doesn’t exist. This function should be used with care, as it can introduce all sorts of nasty environment dependencies in your Nix expression.
`getEnv` is used in Nix Packages to locate the file `~/.nixpkgs/config.nix`, which contains user-local settings for Nix Packages. (That is, it does a `getEnv "HOME"` to locate the user’s home directory.)
`builtins.getFlake args`
------------------------
Fetch a flake from a flake reference, and return its output attributes and some metadata. For example:
```
(builtins.getFlake "nix/55bc52401966fbffa525c574c14f67b00bc4fb3a").packages.x86_64-linux.nix
```
Unless impure evaluation is allowed (`--impure`), the flake reference must be "locked", e.g. contain a Git revision or content hash. An example of an unlocked usage is:
```
(builtins.getFlake "github:edolstra/dwarffs").rev
```
This function is only available if you enable the experimental feature `flakes`.
`builtins.groupBy f list`
-------------------------
Groups elements of *list* together by the string returned from the function *f* called on each element. It returns an attribute set where each attribute value contains the elements of *list* that are mapped to the same corresponding attribute name returned by *f*.
For example,
```
builtins.groupBy (builtins.substring 0 1) ["foo" "bar" "baz"]
```
evaluates to
```
{ b = [ "bar" "baz" ]; f = [ "foo" ]; }
```
`builtins.hasAttr s set`
------------------------
`hasAttr` returns `true` if *set* has an attribute named *s*, and `false` otherwise. This is a dynamic version of the `?` operator, since *s* is an expression rather than an identifier.
`builtins.hashFile type p`
--------------------------
Return a base-16 representation of the cryptographic hash of the file at path *p*. The hash algorithm specified by *type* must be one of `"md5"`, `"sha1"`, `"sha256"` or `"sha512"`.
`builtins.hashString type s`
----------------------------
Return a base-16 representation of the cryptographic hash of string *s*. The hash algorithm specified by *type* must be one of `"md5"`, `"sha1"`, `"sha256"` or `"sha512"`.
`builtins.head list`
--------------------
Return the first element of a list; abort evaluation if the argument isn’t a list or is an empty list. You can test whether a list is empty by comparing it with `[]`.
`builtins.import path`
----------------------
Load, parse and return the Nix expression in the file *path*. If *path* is a directory, the file `default.nix` in that directory is loaded. Evaluation aborts if the file doesn’t exist or contains an incorrect Nix expression. `import` implements Nix’s module system: you can put any Nix expression (such as a set or a function) in a separate file, and use it from Nix expressions in other files.
> **Note**
>
> Unlike some languages, `import` is a regular function in Nix. Paths using the angle bracket syntax (e.g., `import` *<foo>*) are [normal path values](https://nixos.org/manual/nix/stable/expressions/language-values.html).
>
>
A Nix expression loaded by `import` must not contain any *free variables* (identifiers that are not defined in the Nix expression itself and are not built-in). Therefore, it cannot refer to variables that are in scope at the call site. For instance, if you have a calling expression
```
rec {
x = 123;
y = import ./foo.nix;
}
```
then the following `foo.nix` will give an error:
```
x + 456
```
since `x` is not in scope in `foo.nix`. If you want `x` to be available in `foo.nix`, you should pass it as a function argument:
```
rec {
x = 123;
y = import ./foo.nix x;
}
```
and
```
x: x + 456
```
(The function argument doesn’t have to be called `x` in `foo.nix`; any name would work.)
`builtins.intersectAttrs e1 e2`
-------------------------------
Return a set consisting of the attributes in the set *e2* that also exist in the set *e1*.
`builtins.isAttrs e`
--------------------
Return `true` if *e* evaluates to a set, and `false` otherwise.
`builtins.isBool e`
-------------------
Return `true` if *e* evaluates to a bool, and `false` otherwise.
`builtins.isFloat e`
--------------------
Return `true` if *e* evaluates to a float, and `false` otherwise.
`builtins.isFunction e`
-----------------------
Return `true` if *e* evaluates to a function, and `false` otherwise.
`builtins.isInt e`
------------------
Return `true` if *e* evaluates to an integer, and `false` otherwise.
`builtins.isList e`
-------------------
Return `true` if *e* evaluates to a list, and `false` otherwise.
`builtins.isNull e`
-------------------
Return `true` if *e* evaluates to `null`, and `false` otherwise.
> **Warning**
>
> This function is *deprecated*; just write `e == null` instead.
>
>
`builtins.isPath e`
-------------------
Return `true` if *e* evaluates to a path, and `false` otherwise.
`builtins.isString e`
---------------------
Return `true` if *e* evaluates to a string, and `false` otherwise.
`builtins.length e`
-------------------
Return the length of the list *e*.
`builtins.lessThan e1 e2`
-------------------------
Return `true` if the number *e1* is less than the number *e2*, and `false` otherwise. Evaluation aborts if either *e1* or *e2* does not evaluate to a number.
`builtins.listToAttrs e`
------------------------
Construct a set from a list specifying the names and values of each attribute. Each element of the list should be a set consisting of a string-valued attribute `name` specifying the name of the attribute, and an attribute `value` specifying its value. Example:
```
builtins.listToAttrs
[ { name = "foo"; value = 123; }
{ name = "bar"; value = 456; }
]
```
evaluates to
```
{ foo = 123; bar = 456; }
```
`builtins.map f list`
---------------------
Apply the function *f* to each element in the list *list*. For example,
```
map (x: "foo" + x) [ "bar" "bla" "abc" ]
```
evaluates to `[ "foobar" "foobla" "fooabc" ]`.
`builtins.mapAttrs f attrset`
-----------------------------
Apply function *f* to every element of *attrset*. For example,
```
builtins.mapAttrs (name: value: value * 10) { a = 1; b = 2; }
```
evaluates to `{ a = 10; b = 20; }`.
`builtins.match regex str`
--------------------------
Returns a list if the [extended POSIX regular expression](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_04) *regex* matches *str* precisely, otherwise returns `null`. Each item in the list is a regex group.
```
builtins.match "ab" "abc"
```
Evaluates to `null`.
```
builtins.match "abc" "abc"
```
Evaluates to `[ ]`.
```
builtins.match "a(b)(c)" "abc"
```
Evaluates to `[ "b" "c" ]`.
```
builtins.match "[[:space:]]+([[:upper:]]+)[[:space:]]+" " FOO "
```
Evaluates to `[ "FOO" ]`.
`builtins.mul e1 e2`
--------------------
Return the product of the numbers *e1* and *e2*.
`builtins.parseDrvName s`
-------------------------
Split the string *s* into a package name and version. The package name is everything up to but not including the first dash followed by a digit, and the version is everything following that dash. The result is returned in a set `{ name, version }`. Thus, `builtins.parseDrvName "nix-0.12pre12876"` returns `{ name = "nix"; version = "0.12pre12876"; }`.
`builtins.partition pred list`
------------------------------
Given a predicate function *pred*, this function returns an attrset containing a list named `right`, containing the elements in *list* for which *pred* returned `true`, and a list named `wrong`, containing the elements for which it returned `false`. For example,
```
builtins.partition (x: x > 10) [1 23 9 3 42]
```
evaluates to
```
{ right = [ 23 42 ]; wrong = [ 1 9 3 ]; }
```
`builtins.path args`
--------------------
An enrichment of the built-in path type, based on the attributes present in *args*. All are optional except `path`:
* path
The underlying path.
* name
The name of the path when added to the store. This can used to reference paths that have nix-illegal characters in their names, like `@`.
* filter
A function of the type expected by `builtins.filterSource`, with the same semantics.
* recursive
When `false`, when `path` is added to the store it is with a flat hash, rather than a hash of the NAR serialization of the file. Thus, `path` must refer to a regular file, not a directory. This allows similar behavior to `fetchurl`. Defaults to `true`.
* sha256
When provided, this is the expected hash of the file at the path. Evaluation will fail if the hash is incorrect, and providing a hash allows `builtins.path` to be used even when the `pure-eval` nix config option is on.
`builtins.pathExists path`
--------------------------
Return `true` if the path *path* exists at evaluation time, and `false` otherwise.
`builtins.placeholder output`
-----------------------------
Return a placeholder string for the specified *output* that will be substituted by the corresponding output path at build time. Typical outputs would be `"out"`, `"bin"` or `"dev"`.
`builtins.readDir path`
-----------------------
Return the contents of the directory *path* as a set mapping directory entries to the corresponding file type. For instance, if directory `A` contains a regular file `B` and another directory `C`, then `builtins.readDir ./A` will return the set
```
{ B = "regular"; C = "directory"; }
```
The possible values for the file type are `"regular"`, `"directory"`, `"symlink"` and `"unknown"`.
`builtins.readFile path`
------------------------
Return the contents of the file *path* as a string.
`builtins.removeAttrs set list`
-------------------------------
Remove the attributes listed in *list* from *set*. The attributes don’t have to exist in *set*. For instance,
```
removeAttrs { x = 1; y = 2; z = 3; } [ "a" "x" "z" ]
```
evaluates to `{ y = 2; }`.
`builtins.replaceStrings from to s`
-----------------------------------
Given string *s*, replace every occurrence of the strings in *from* with the corresponding string in *to*. For example,
```
builtins.replaceStrings ["oo" "a"] ["a" "i"] "foobar"
```
evaluates to `"fabir"`.
`builtins.seq e1 e2`
--------------------
Evaluate *e1*, then evaluate and return *e2*. This ensures that a computation is strict in the value of *e1*.
`builtins.sort comparator list`
-------------------------------
Return *list* in sorted order. It repeatedly calls the function *comparator* with two elements. The comparator should return `true` if the first element is less than the second, and `false` otherwise. For example,
```
builtins.sort builtins.lessThan [ 483 249 526 147 42 77 ]
```
produces the list `[ 42 77 147 249 483 526 ]`.
This is a stable sort: it preserves the relative order of elements deemed equal by the comparator.
`builtins.split regex str`
--------------------------
Returns a list composed of non matched strings interleaved with the lists of the [extended POSIX regular expression](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_04) *regex* matches of *str*. Each item in the lists of matched sequences is a regex group.
```
builtins.split "(a)b" "abc"
```
Evaluates to `[ "" [ "a" ] "c" ]`.
```
builtins.split "([ac])" "abc"
```
Evaluates to `[ "" [ "a" ] "b" [ "c" ] "" ]`.
```
builtins.split "(a)|(c)" "abc"
```
Evaluates to `[ "" [ "a" null ] "b" [ null "c" ] "" ]`.
```
builtins.split "([[:upper:]]+)" " FOO "
```
Evaluates to `[ " " [ "FOO" ] " " ]`.
`builtins.splitVersion s`
-------------------------
Split a string representing a version into its components, by the same version splitting logic underlying the version comparison in [`nix-env -u`](https://nixos.org/manual/nix/stable/command-ref/nix-env.html#operation---upgrade).
`builtins.storePath path`
-------------------------
This function allows you to define a dependency on an already existing store path. For example, the derivation attribute `src = builtins.storePath /nix/store/f1d18v1y…-source` causes the derivation to depend on the specified path, which must exist or be substitutable. Note that this differs from a plain path (e.g. `src = /nix/store/f1d18v1y…-source`) in that the latter causes the path to be *copied* again to the Nix store, resulting in a new path (e.g. `/nix/store/ld01dnzc…-source-source`).
This function is not available in pure evaluation mode.
`builtins.stringLength e`
-------------------------
Return the length of the string *e*. If *e* is not a string, evaluation is aborted.
`builtins.sub e1 e2`
--------------------
Return the difference between the numbers *e1* and *e2*.
`builtins.substring start len s`
--------------------------------
Return the substring of *s* from character position *start* (zero-based) up to but not including *start + len*. If *start* is greater than the length of the string, an empty string is returned, and if *start + len* lies beyond the end of the string, only the substring up to the end of the string is returned. *start* must be non-negative. For example,
```
builtins.substring 0 3 "nixos"
```
evaluates to `"nix"`.
`builtins.tail list`
--------------------
Return the second to last elements of a list; abort evaluation if the argument isn’t a list or is an empty list.
> **Warning**
>
> This function should generally be avoided since it's inefficient: unlike Haskell's `tail`, it takes O(n) time, so recursing over a list by repeatedly calling `tail` takes O(n^2) time.
>
>
`builtins.throw s`
------------------
Throw an error message *s*. This usually aborts Nix expression evaluation, but in `nix-env -qa` and other commands that try to evaluate a set of derivations to get information about those derivations, a derivation that throws an error is silently skipped (which is not the case for `abort`).
`builtins.toFile name s`
------------------------
Store the string *s* in a file in the Nix store and return its path. The file has suffix *name*. This file can be used as an input to derivations. One application is to write builders “inline”. For instance, the following Nix expression combines the [Nix expression for GNU Hello](https://nixos.org/manual/nix/stable/expressions/expression-syntax.html) and its [build script](https://nixos.org/manual/nix/stable/expressions/build-script.html) into one file:
```
{ stdenv, fetchurl, perl }:
stdenv.mkDerivation {
name = "hello-2.1.1";
builder = builtins.toFile "builder.sh" "
source $stdenv/setup
PATH=$perl/bin:$PATH
tar xvfz $src
cd hello-*
./configure --prefix=$out
make
make install
";
src = fetchurl {
url = "http://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz";
sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465";
};
inherit perl;
}
```
It is even possible for one file to refer to another, e.g.,
```
builder = let
configFile = builtins.toFile "foo.conf" "
# This is some dummy configuration file.
...
";
in builtins.toFile "builder.sh" "
source $stdenv/setup
...
cp ${configFile} $out/etc/foo.conf
";
```
Note that `${configFile}` is an [antiquotation](https://nixos.org/manual/nix/stable/expressions/language-values.html), so the result of the expression `configFile` (i.e., a path like `/nix/store/m7p7jfny445k...-foo.conf`) will be spliced into the resulting string.
It is however *not* allowed to have files mutually referring to each other, like so:
```
let
foo = builtins.toFile "foo" "...${bar}...";
bar = builtins.toFile "bar" "...${foo}...";
in foo
```
This is not allowed because it would cause a cyclic dependency in the computation of the cryptographic hashes for `foo` and `bar`.
It is also not possible to reference the result of a derivation. If you are using Nixpkgs, the `writeTextFile` function is able to do that.
`builtins.toJSON e`
-------------------
Return a string containing a JSON representation of *e*. Strings, integers, floats, booleans, nulls and lists are mapped to their JSON equivalents. Sets (except derivations) are represented as objects. Derivations are translated to a JSON string containing the derivation’s output path. Paths are copied to the store and represented as a JSON string of the resulting store path.
`builtins.toPath s`
-------------------
**DEPRECATED.** Use `/. + "/path"` to convert a string into an absolute path. For relative paths, use `./. + "/path"`.
`builtins.toString e`
---------------------
Convert the expression *e* to a string. *e* can be:
* A string (in which case the string is returned unmodified).
* A path (e.g., `toString /foo/bar` yields `"/foo/bar"`.
* A set containing `{ __toString = self: ...; }` or `{ outPath = ...; }`.
* An integer.
* A list, in which case the string representations of its elements are joined with spaces.
* A Boolean (`false` yields `""`, `true` yields `"1"`).
* `null`, which yields the empty string.
`builtins.toXML e`
------------------
Return a string containing an XML representation of *e*. The main application for `toXML` is to communicate information with the builder in a more structured format than plain environment variables.
Here is an example where this is the case:
```
{ stdenv, fetchurl, libxslt, jira, uberwiki }:
stdenv.mkDerivation (rec {
name = "web-server";
buildInputs = [ libxslt ];
builder = builtins.toFile "builder.sh" "
source $stdenv/setup
mkdir $out
echo "$servlets" | xsltproc ${stylesheet} - > $out/server-conf.xml ①
";
stylesheet = builtins.toFile "stylesheet.xsl" ②
"<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>
<xsl:template match='/'>
<Configure>
<xsl:for-each select='/expr/list/attrs'>
<Call name='addWebApplication'>
<Arg><xsl:value-of select=\"attr[@name = 'path']/string/@value\" /></Arg>
<Arg><xsl:value-of select=\"attr[@name = 'war']/path/@value\" /></Arg>
</Call>
</xsl:for-each>
</Configure>
</xsl:template>
</xsl:stylesheet>
";
servlets = builtins.toXML [ ③
{ path = "/bugtracker"; war = jira + "/lib/atlassian-jira.war"; }
{ path = "/wiki"; war = uberwiki + "/uberwiki.war"; }
];
})
```
The builder is supposed to generate the configuration file for a [Jetty servlet container](http://jetty.mortbay.org/). A servlet container contains a number of servlets (`*.war` files) each exported under a specific URI prefix. So the servlet configuration is a list of sets containing the `path` and `war` of the servlet (①). This kind of information is difficult to communicate with the normal method of passing information through an environment variable, which just concatenates everything together into a string (which might just work in this case, but wouldn’t work if fields are optional or contain lists themselves). Instead the Nix expression is converted to an XML representation with `toXML`, which is unambiguous and can easily be processed with the appropriate tools. For instance, in the example an XSLT stylesheet (at point ②) is applied to it (at point ①) to generate the XML configuration file for the Jetty server. The XML representation produced at point ③ by `toXML` is as follows:
```
<?xml version='1.0' encoding='utf-8'?>
<expr>
<list>
<attrs>
<attr name="path">
<string value="/bugtracker" />
</attr>
<attr name="war">
<path value="/nix/store/d1jh9pasa7k2...-jira/lib/atlassian-jira.war" />
</attr>
</attrs>
<attrs>
<attr name="path">
<string value="/wiki" />
</attr>
<attr name="war">
<path value="/nix/store/y6423b1yi4sx...-uberwiki/uberwiki.war" />
</attr>
</attrs>
</list>
</expr>
```
Note that we used the `toFile` built-in to write the builder and the stylesheet “inline” in the Nix expression. The path of the stylesheet is spliced into the builder using the syntax `xsltproc ${stylesheet}`.
`builtins.trace e1 e2`
----------------------
Evaluate *e1* and print its abstract syntax representation on standard error. Then return *e2*. This function is useful for debugging.
`builtins.traceVerbose e1 e2`
-----------------------------
Evaluate *e1* and print its abstract syntax representation on standard error if `--trace-verbose` is enabled. Then return *e2*. This function is useful for debugging.
`builtins.tryEval e`
--------------------
Try to shallowly evaluate *e*. Return a set containing the attributes `success` (`true` if *e* evaluated successfully, `false` if an error was thrown) and `value`, equalling *e* if successful and `false` otherwise. `tryEval` will only prevent errors created by `throw` or `assert` from being thrown. Errors `tryEval` will not catch are for example those created by `abort` and type errors generated by builtins. Also note that this doesn't evaluate *e* deeply, so `let e = { x = throw ""; }; in (builtins.tryEval e).success` will be `true`. Using `builtins.deepSeq` one can get the expected result: `let e = { x = throw ""; }; in (builtins.tryEval (builtins.deepSeq e e)).success` will be `false`.
`builtins.typeOf e`
-------------------
Return a string representing the type of the value *e*, namely `"int"`, `"bool"`, `"string"`, `"path"`, `"null"`, `"set"`, `"list"`, `"lambda"` or `"float"`.
`builtins.zipAttrsWith f list`
------------------------------
Transpose a list of attribute sets into an attribute set of lists, then apply `mapAttrs`.
`f` receives two arguments: the attribute name and a non-empty list of all values encountered for that attribute name.
The result is an attribute set where the attribute names are the union of the attribute names in each element of `list`. The attribute values are the return values of `f`.
```
builtins.zipAttrsWith
(name: values: { inherit name values; })
[ { a = "x"; } { a = "y"; b = "z"; } ]
```
evaluates to
```
{
a = { name = "a"; values = [ "x" "y" ]; };
b = { name = "b"; values = [ "z" ]; };
}
```
| programming_docs |
nix None
`lib.asserts.assertMsg`
-----------------------
#####
`assertMsg :: Bool -> String -> Bool`
Located at [lib/asserts.nix:19](https://github.com/NixOS/nixpkgs/blob/master/lib/asserts.nix#L19) in `<nixpkgs>`.
Print a trace message if `pred` is false.
Intended to be used to augment asserts with helpful error messages.
`pred`
Condition under which the `msg` should *not* be printed.
`msg`
Message to print.
**Example: Printing when the predicate is false**
```
assert lib.asserts.assertMsg ("foo" == "bar") "foo is not bar, silly"
stderr> trace: foo is not bar, silly
stderr> assert failed
```
`lib.asserts.assertOneOf`
-------------------------
#####
`assertOneOf :: String -> String ->
StringList -> Bool`
Located at [lib/asserts.nix:36](https://github.com/NixOS/nixpkgs/blob/master/lib/asserts.nix#L36) in `<nixpkgs>`.
Specialized `asserts.assertMsg` for checking if `val` is one of the elements of `xs`. Useful for checking enums.
`name`
The name of the variable the user entered `val` into, for inclusion in the error message.
`val`
The value of what the user provided, to be compared against the values in `xs`.
`xs`
The list of valid values.
**Example: Ensuring a user provided a possible value**
```
let sslLibrary = "bearssl";
in lib.asserts.assertOneOf "sslLibrary" sslLibrary [ "openssl" "libressl" ];
=> false
stderr> trace: sslLibrary must be one of "openssl", "libressl", but is: "bearssl"
```
`lib.attrset.attrByPath`
------------------------
#####
`attrByPath :: [String] -> Any -> AttrSet -> Any`
Located at [lib/attrsets.nix:24](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L24) in `<nixpkgs>`.
Return an attribute from within nested attribute sets.
`attrPath`
A list of strings representing the path through the nested attribute set `set`.
`default`
Default value if `attrPath` does not resolve to an existing value.
`set`
The nested attributeset to select values from.
**Example: Extracting a value from a nested attribute set**
```
let set = { a = { b = 3; }; };
in lib.attrsets.attrByPath [ "a" "b" ] 0 set
=> 3
```
**Example: No value at the path, instead using the default**
```
lib.attrsets.attrByPath [ "a" "b" ] 0 {}
=> 0
```
`lib.attrsets.hasAttrByPath`
----------------------------
#####
`hasAttrByPath :: [String] -> AttrSet -> Bool`
Located at [lib/attrsets.nix:42](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L42) in `<nixpkgs>`.
Determine if an attribute exists within a nested attribute set.
`attrPath`
A list of strings representing the path through the nested attribute set `set`.
`set`
The nested attributeset to check.
**Example: A nested value does exist inside a set**
```
lib.attrsets.hasAttrByPath
[ "a" "b" "c" "d" ]
{ a = { b = { c = { d = 123; }; }; }; }
=> true
```
`lib.attrsets.setAttrByPath`
----------------------------
#####
`setAttrByPath :: [String] -> Any -> AttrSet`
Located at [lib/attrsets.nix:57](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L57) in `<nixpkgs>`.
Create a new attribute set with `value` set at the nested attribute location specified in `attrPath`.
`attrPath`
A list of strings representing the path through the nested attribute set.
`value`
The value to set at the location described by `attrPath`.
**Example: Creating a new nested attribute set**
```
lib.attrsets.setAttrByPath [ "a" "b" ] 3
=> { a = { b = 3; }; }
```
`lib.attrsets.getAttrFromPath`
------------------------------
#####
`getAttrFromPath :: [String] -> AttrSet -> Value`
Located at [lib/attrsets.nix:76](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L76) in `<nixpkgs>`.
Like [Section 5.1.2.1, “`lib.attrset.attrByPath`”](#function-library-lib.attrsets.attrByPath "5.1.2.1. lib.attrset.attrByPath") except without a default, and it will throw if the value doesn't exist.
`attrPath`
A list of strings representing the path through the nested attribute set `set`.
`set`
The nested attribute set to find the value in.
**Example: Succesfully getting a value from an attribute set**
```
lib.attrsets.getAttrFromPath [ "a" "b" ] { a = { b = 3; }; }
=> 3
```
**Example: Throwing after failing to get a value from an attribute set**
```
lib.attrsets.getAttrFromPath [ "x" "y" ] { }
=> error: cannot find attribute `x.y'
```
`lib.attrsets.attrVals`
-----------------------
#####
`attrVals :: [String] -> AttrSet -> [Any]`
Located at [lib/attrsets.nix:184](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L184) in `<nixpkgs>`.
Return the specified attributes from a set. All values must exist.
`nameList`
The list of attributes to fetch from `set`. Each attribute name must exist on the attrbitue set.
`set`
The set to get attribute values from.
**Example: Getting several values from an attribute set**
```
lib.attrsets.attrVals [ "a" "b" "c" ] { a = 1; b = 2; c = 3; }
=> [ 1 2 3 ]
```
**Example: Getting missing values from an attribute set**
```
lib.attrsets.attrVals [ "d" ] { }
error: attribute 'd' missing
```
`lib.attrsets.attrValues`
-------------------------
#####
`attrValues :: AttrSet -> [Any]`
Located at [lib/attrsets.nix:194](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L194) in `<nixpkgs>`.
Get all the attribute values from an attribute set.
Provides a backwards-compatible interface of `builtins.attrValues` for Nix version older than 1.8.
`attrs`
The attribute set.
**Example:**
```
lib.attrsets.attrValues { a = 1; b = 2; c = 3; }
=> [ 1 2 3 ]
```
`lib.attrsets.catAttrs`
-----------------------
#####
`catAttrs :: String -> [AttrSet] -> [Any]`
Located at [lib/attrsets.nix:213](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L213) in `<nixpkgs>`.
Collect each attribute named `attr' from the list of attribute sets, `sets`. Sets that don't contain the named attribute are ignored.
Provides a backwards-compatible interface of `builtins.catAttrs` for Nix version older than 1.9.
`attr`
Attribute name to select from each attribute set in `sets`.
`sets`
The list of attribute sets to select `attr` from.
**Example: Collect an attribute from a list of attribute sets.**
Attribute sets which don't have the attribute are ignored.
```
catAttrs "a" [{a = 1;} {b = 0;} {a = 2;}]
=> [ 1 2 ]
```
`lib.attrsets.filterAttrs`
--------------------------
#####
`filterAttrs :: (String -> Any -> Bool) -> AttrSet -> AttrSet`
Located at [lib/attrsets.nix:224](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L224) in `<nixpkgs>`.
Filter an attribute set by removing all attributes for which the given predicate return false.
`pred`
`String -> Any -> Bool`
Predicate which returns true to include an attribute, or returns false to exclude it.
`name`
The attribute's name
`value`
The attribute's value
Returns `true` to include the attribute, `false` to exclude the attribute.
`set`
The attribute set to filter
**Example: Filtering an attributeset**
```
filterAttrs (n: v: n == "foo") { foo = 1; bar = 2; }
=> { foo = 1; }
```
`lib.attrsets.filterAttrsRecursive`
-----------------------------------
#####
`filterAttrsRecursive :: (String -> Any -> Bool) -> AttrSet -> AttrSet`
Located at [lib/attrsets.nix:235](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L235) in `<nixpkgs>`.
Filter an attribute set recursively by removing all attributes for which the given predicate return false.
`pred`
`String -> Any -> Bool`
Predicate which returns true to include an attribute, or returns false to exclude it.
`name`
The attribute's name
`value`
The attribute's value
Returns `true` to include the attribute, `false` to exclude the attribute.
`set`
The attribute set to filter
**Example: Recursively filtering an attribute set**
```
lib.attrsets.filterAttrsRecursive
(n: v: v != null)
{
levelA = {
example = "hi";
levelB = {
hello = "there";
this-one-is-present = {
this-is-excluded = null;
};
};
this-one-is-also-excluded = null;
};
also-excluded = null;
}
=> {
levelA = {
example = "hi";
levelB = {
hello = "there";
this-one-is-present = { };
};
};
}
```
`lib.attrsets.foldAttrs`
------------------------
#####
`foldAttrs :: (Any -> Any -> Any) -> Any -> [AttrSets] -> Any`
Located at [lib/attrsets.nix:254](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L254) in `<nixpkgs>`.
Apply fold function to values grouped by key.
`op`
`Any -> Any -> Any`
Given a value `val` and a collector `col`, combine the two.
`val`
An attribute's value
`col`
The result of previous `op` calls with other values and `nul`.
`nul`
The null-value, the starting value.
`list_of_attrs`
A list of attribute sets to fold together by key.
**Example: Combining an attribute of lists in to one attribute set**
```
lib.attrsets.foldAttrs
(n: a: [n] ++ a) []
[
{ a = 2; b = 7; }
{ a = 3; }
{ b = 6; }
]
=> { a = [ 2 3 ]; b = [ 7 6 ]; }
```
`lib.attrsets.collect`
----------------------
#####
`collect :: (Any -> Bool) -> AttrSet -> [Any]`
Located at [lib/attrsets.nix:278](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L278) in `<nixpkgs>`.
Recursively collect sets that verify a given predicate named `pred` from the set `attrs`. The recursion stops when `pred` returns `true`.
`pred`
`Any -> Bool`
Given an attribute's value, determine if recursion should stop.
`value`
The attribute set value.
`attrs`
The attribute set to recursively collect.
**Example: Collecting all lists from an attribute set**
```
lib.attrsets.collect isList { a = { b = ["b"]; }; c = [1]; }
=> [["b"] [1]]
```
**Example: Collecting all attribute-sets which contain the outPath attribute name.**
```
collect (x: x ? outPath)
{ a = { outPath = "a/"; }; b = { outPath = "b/"; }; }
=> [{ outPath = "a/"; } { outPath = "b/"; }]
```
`lib.attrsets.nameValuePair`
----------------------------
#####
`nameValuePair :: String -> Any -> AttrSet`
Located at [lib/attrsets.nix:312](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L312) in `<nixpkgs>`.
Utility function that creates a `{name, value}` pair as expected by `builtins.listToAttrs`.
`name`
The attribute name.
`value`
The attribute value.
**Example: Creating a name value pair**
```
nameValuePair "some" 6
=> { name = "some"; value = 6; }
```
`lib.attrsets.mapAttrs`
-----------------------
Located at [lib/attrsets.nix:325](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L325) in `<nixpkgs>`.
Apply a function to each element in an attribute set, creating a new attribute set.
Provides a backwards-compatible interface of `builtins.mapAttrs` for Nix version older than 2.1.
`fn`
`String -> Any -> Any`
Given an attribute's name and value, return a new value.
`name`
The name of the attribute.
`value`
The attribute's value.
**Example: Modifying each value of an attribute set**
```
lib.attrsets.mapAttrs
(name: value: name + "-" + value)
{ x = "foo"; y = "bar"; }
=> { x = "x-foo"; y = "y-bar"; }
```
`lib.attrsets.mapAttrs'`
------------------------
#####
`mapAttrs' :: (String -> Any -> { name = String; value = Any }) -> AttrSet -> AttrSet`
Located at [lib/attrsets.nix:339](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L339) in `<nixpkgs>`.
Like `mapAttrs`, but allows the name of each attribute to be changed in addition to the value. The applied function should return both the new name and value as a `nameValuePair`.
`fn`
`String -> Any -> { name = String; value = Any }`
Given an attribute's name and value, return a new [name value pair](#function-library-lib.attrsets.nameValuePair "5.1.2.12. lib.attrsets.nameValuePair").
`name`
The name of the attribute.
`value`
The attribute's value.
`set`
The attribute set to map over.
**Example: Change the name and value of each attribute of an attribute set**
```
lib.attrsets.mapAttrs' (name: value: lib.attrsets.nameValuePair ("foo_" + name) ("bar-" + value))
{ x = "a"; y = "b"; }
=> { foo_x = "bar-a"; foo_y = "bar-b"; }
```
`lib.attrsets.mapAttrsToList`
-----------------------------
#####
`mapAttrsToList :: (String -> Any -> Any) ->
AttrSet -> [Any]`
Located at [lib/attrsets.nix:355](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L355) in `<nixpkgs>`.
Call `fn` for each attribute in the given `set` and return the result in a list.
`fn`
`String -> Any -> Any`
Given an attribute's name and value, return a new value.
`name`
The name of the attribute.
`value`
The attribute's value.
`set`
The attribute set to map over.
**Example: Combine attribute values and names in to a list**
```
lib.attrsets.mapAttrsToList (name: value: "${name}=${value}")
{ x = "a"; y = "b"; }
=> [ "x=a" "y=b" ]
```
`lib.attrsets.mapAttrsRecursive`
--------------------------------
#####
`mapAttrsRecursive :: ([String] > Any -> Any) -> AttrSet -> AttrSet`
Located at [lib/attrsets.nix:372](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L372) in `<nixpkgs>`.
Like `mapAttrs`, except that it recursively applies itself to attribute sets. Also, the first argument of the argument function is a *list* of the names of the containing attributes.
`f`
`[ String ] -> Any -> Any`
Given a list of attribute names and value, return a new value.
`name_path`
The list of attribute names to this value.
For example, the `name_path` for the `example` string in the attribute set `{ foo = { bar = "example"; }; }` is `[ "foo" "bar" ]`.
`value`
The attribute's value.
`set`
The attribute set to recursively map over.
**Example: A contrived example of using lib.attrsets.mapAttrsRecursive**
```
mapAttrsRecursive
(path: value: concatStringsSep "-" (path ++ [value]))
{
n = {
a = "A";
m = {
b = "B";
c = "C";
};
};
d = "D";
}
=> {
n = {
a = "n-a-A";
m = {
b = "n-m-b-B";
c = "n-m-c-C";
};
};
d = "d-D";
}
```
`lib.attrsets.mapAttrsRecursiveCond`
------------------------------------
#####
`mapAttrsRecursiveCond :: (AttrSet -> Bool) -> ([ String ] -> Any -> Any) -> AttrSet -> AttrSet`
Located at [lib/attrsets.nix:393](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L393) in `<nixpkgs>`.
Like `mapAttrsRecursive`, but it takes an additional predicate function that tells it whether to recursive into an attribute set. If it returns false, `mapAttrsRecursiveCond` does not recurse, but does apply the map function. It is returns true, it does recurse, and does not apply the map function.
`cond`
`(AttrSet -> Bool)`
Determine if `mapAttrsRecursive` should recurse deeper in to the attribute set.
`attributeset`
An attribute set.
`f`
`[ String ] -> Any -> Any`
Given a list of attribute names and value, return a new value.
`name_path`
The list of attribute names to this value.
For example, the `name_path` for the `example` string in the attribute set `{ foo = { bar = "example"; }; }` is `[ "foo" "bar" ]`.
`value`
The attribute's value.
`set`
The attribute set to recursively map over.
**Example: Only convert attribute values to JSON if the containing attribute set is marked for recursion**
```
lib.attrsets.mapAttrsRecursiveCond
({ recurse ? false, ... }: recurse)
(name: value: builtins.toJSON value)
{
dorecur = {
recurse = true;
hello = "there";
};
dontrecur = {
converted-to- = "json";
};
}
=> {
dorecur = {
hello = "\"there\"";
recurse = "true";
};
dontrecur = "{\"converted-to\":\"json\"}";
}
```
`lib.attrsets.genAttrs`
-----------------------
#####
`genAttrs :: [ String ] -> (String -> Any) -> AttrSet`
Located at [lib/attrsets.nix:413](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L413) in `<nixpkgs>`.
Generate an attribute set by mapping a function over a list of attribute names.
`names`
Names of values in the resulting attribute set.
`f`
`String -> Any`
Takes the name of the attribute and return the attribute's value.
`name`
The name of the attribute to generate a value for.
**Example: Generate an attrset based on names only**
```
lib.attrsets.genAttrs [ "foo" "bar" ] (name: "x_${name}")
=> { foo = "x_foo"; bar = "x_bar"; }
```
`lib.attrsets.isDerivation`
---------------------------
#####
`isDerivation :: Any -> Bool`
Located at [lib/attrsets.nix:427](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L427) in `<nixpkgs>`.
Check whether the argument is a derivation. Any set with `{ type = "derivation"; }` counts as a derivation.
`value`
The value which is possibly a derivation.
**Example: A package is a derivation**
```
lib.attrsets.isDerivation (import <nixpkgs> {}).ruby
=> true
```
**Example: Anything else is not a derivation**
```
lib.attrsets.isDerivation "foobar"
=> false
```
`lib.attrsets.toDerivation`
---------------------------
#####
`toDerivation :: Path -> Derivation`
Located at [lib/attrsets.nix:430](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L430) in `<nixpkgs>`.
Converts a store path to a fake derivation.
`path`
A store path to convert to a derivation.
`lib.attrsets.optionalAttrs`
----------------------------
#####
`optionalAttrs :: Bool -> AttrSet`
Located at [lib/attrsets.nix:453](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L453) in `<nixpkgs>`.
Conditionally return an attribute set or an empty attribute set.
`cond`
Condition under which the `as` attribute set is returned.
`as`
The attribute set to return if `cond` is true.
**Example: Return the provided attribute set when cond is true**
```
lib.attrsets.optionalAttrs true { my = "set"; }
=> { my = "set"; }
```
**Example: Return an empty attribute set when cond is false**
```
lib.attrsets.optionalAttrs false { my = "set"; }
=> { }
```
`lib.attrsets.zipAttrsWithNames`
--------------------------------
#####
`zipAttrsWithNames :: [ String ] -> (String -> [ Any ] -> Any) -> [ AttrSet ] -> AttrSet`
Located at [lib/attrsets.nix:463](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L463) in `<nixpkgs>`.
Merge sets of attributes and use the function `f` to merge attribute values where the attribute name is in `names`.
`names`
A list of attribute names to zip.
`f`
`(String -> [ Any ] -> Any`
Accepts an attribute name, all the values, and returns a combined value.
`name`
The name of the attribute each value came from.
`vs`
A list of values collected from the list of attribute sets.
`sets`
A list of attribute sets to zip together.
**Example: Summing a list of attribute sets of numbers**
```
lib.attrsets.zipAttrsWithNames
[ "a" "b" ]
(name: vals: "${name} ${toString (builtins.foldl' (a: b: a + b) 0 vals)}")
[
{ a = 1; b = 1; c = 1; }
{ a = 10; }
{ b = 100; }
{ c = 1000; }
]
=> { a = "a 11"; b = "b 101"; }
```
`lib.attrsets.zipAttrsWith`
---------------------------
#####
`zipAttrsWith :: (String -> [ Any ] -> Any) -> [ AttrSet ] -> AttrSet`
Located at [lib/attrsets.nix:478](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L478) in `<nixpkgs>`.
Merge sets of attributes and use the function `f` to merge attribute values. Similar to [Section 5.1.2.22, “`lib.attrsets.zipAttrsWithNames`”](#function-library-lib.attrsets.zipAttrsWithNames "5.1.2.22. lib.attrsets.zipAttrsWithNames") where all key names are passed for `names`.
`f`
`(String -> [ Any ] -> Any`
Accepts an attribute name, all the values, and returns a combined value.
`name`
The name of the attribute each value came from.
`vs`
A list of values collected from the list of attribute sets.
`sets`
A list of attribute sets to zip together.
**Example: Summing a list of attribute sets of numbers**
```
lib.attrsets.zipAttrsWith
(name: vals: "${name} ${toString (builtins.foldl' (a: b: a + b) 0 vals)}")
[
{ a = 1; b = 1; c = 1; }
{ a = 10; }
{ b = 100; }
{ c = 1000; }
]
=> { a = "a 11"; b = "b 101"; c = "c 1001"; }
```
`lib.attrsets.zipAttrs`
-----------------------
#####
`zipAttrs :: [ AttrSet ] -> AttrSet`
Located at [lib/attrsets.nix:486](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L486) in `<nixpkgs>`.
Merge sets of attributes and combine each attribute value in to a list. Similar to [Section 5.1.2.23, “`lib.attrsets.zipAttrsWith`”](#function-library-lib.attrsets.zipAttrsWith "5.1.2.23. lib.attrsets.zipAttrsWith") where the merge function returns a list of all values.
`sets`
A list of attribute sets to zip together.
**Example: Combining a list of attribute sets**
```
lib.attrsets.zipAttrs
[
{ a = 1; b = 1; c = 1; }
{ a = 10; }
{ b = 100; }
{ c = 1000; }
]
=> { a = [ 1 10 ]; b = [ 1 100 ]; c = [ 1 1000 ]; }
```
`lib.attrsets.recursiveUpdateUntil`
-----------------------------------
#####
`recursiveUpdateUntil :: ( [ String ] -> AttrSet -> AttrSet -> Bool ) -> AttrSet -> AttrSet -> AttrSet`
Located at [lib/attrsets.nix:516](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L516) in `<nixpkgs>`.
Does the same as the update operator `//` except that attributes are merged until the given predicate is verified. The predicate should accept 3 arguments which are the path to reach the attribute, a part of the first attribute set and a part of the second attribute set. When the predicate is verified, the value of the first attribute set is replaced by the value of the second attribute set.
`pred`
`[ String ] -> AttrSet -> AttrSet -> Bool`
`path`
The path to the values in the left and right hand sides.
`l`
The left hand side value.
`r`
The right hand side value.
`lhs`
The left hand attribute set of the merge.
`rhs`
The right hand attribute set of the merge.
**Example: Recursively merging two attribute sets**
```
lib.attrsets.recursiveUpdateUntil (path: l: r: path == ["foo"])
{
# first attribute set
foo.bar = 1;
foo.baz = 2;
bar = 3;
}
{
#second attribute set
foo.bar = 1;
foo.quz = 2;
baz = 4;
}
=> {
foo.bar = 1; # 'foo.*' from the second set
foo.quz = 2; #
bar = 3; # 'bar' from the first set
baz = 4; # 'baz' from the second set
}
```
`lib.attrsets.recursiveUpdate`
------------------------------
#####
`recursiveUpdate :: AttrSet -> AttrSet -> AttrSet`
Located at [lib/attrsets.nix:547](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L547) in `<nixpkgs>`.
A recursive variant of the update operator `//`. The recursion stops when one of the attribute values is not an attribute set, in which case the right hand side value takes precedence over the left hand side value.
`lhs`
The left hand attribute set of the merge.
`rhs`
The right hand attribute set of the merge.
**Example: Recursively merging two attribute sets**
```
recursiveUpdate
{
boot.loader.grub.enable = true;
boot.loader.grub.device = "/dev/hda";
}
{
boot.loader.grub.device = "";
}
=> {
boot.loader.grub.enable = true;
boot.loader.grub.device = "";
}
```
`lib.attrsets.recurseIntoAttrs`
-------------------------------
#####
`recurseIntoAttrs :: AttrSet -> AttrSet`
Located at [lib/attrsets.nix:617](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L617) in `<nixpkgs>`.
Make various Nix tools consider the contents of the resulting attribute set when looking for what to build, find, etc.
This function only affects a single attribute set; it does not apply itself recursively for nested attribute sets.
`attrs`
An attribute set to scan for derivations.
**Example: Making Nix look inside an attribute set**
```
{ pkgs ? import <nixpkgs> {} }:
{
myTools = pkgs.lib.recurseIntoAttrs {
inherit (pkgs) hello figlet;
};
}
```
`lib.attrsets.cartesianProductOfSets`
-------------------------------------
#####
`cartesianProductOfSets :: AttrSet -> [ AttrSet ]`
Located at [lib/attrsets.nix:297](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L297) in `<nixpkgs>`.
Return the cartesian product of attribute set value combinations.
`set`
An attribute set with attributes that carry lists of values.
**Example: Creating the cartesian product of a list of attribute values**
```
cartesianProductOfSets { a = [ 1 2 ]; b = [ 10 20 ]; }
=> [
{ a = 1; b = 10; }
{ a = 1; b = 20; }
{ a = 2; b = 10; }
{ a = 2; b = 20; }
]
```
`lib.strings.concatStrings`
---------------------------
#####
`concatStrings :: [string] -> string`
Concatenate a list of strings.
**Example: lib.strings.concatStrings usage example**
```
concatStrings ["foo" "bar"]
=> "foobar"
```
Located at [lib/strings.nix:44](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L44) in `<nixpkgs>`.
`lib.strings.concatMapStrings`
------------------------------
#####
`concatMapStrings :: (a -> string) -> [a] -> string`
Map a function over a list and concatenate the resulting strings.
`f`
Function argument
`list`
Function argument
**Example: lib.strings.concatMapStrings usage example**
```
concatMapStrings (x: "a" + x) ["foo" "bar"]
=> "afooabar"
```
Located at [lib/strings.nix:54](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L54) in `<nixpkgs>`.
`lib.strings.concatImapStrings`
-------------------------------
#####
`concatImapStrings :: (int -> a -> string) -> [a] -> string`
Like `concatMapStrings` except that the f functions also gets the position as a parameter.
`f`
Function argument
`list`
Function argument
**Example: lib.strings.concatImapStrings usage example**
```
concatImapStrings (pos: x: "${toString pos}-${x}") ["foo" "bar"]
=> "1-foo2-bar"
```
Located at [lib/strings.nix:65](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L65) in `<nixpkgs>`.
`lib.strings.intersperse`
-------------------------
#####
`intersperse :: a -> [a] -> [a]`
Place an element between each element of a list
`separator`
Separator to add between elements
`list`
Input list
**Example: lib.strings.intersperse usage example**
```
intersperse "/" ["usr" "local" "bin"]
=> ["usr" "/" "local" "/" "bin"].
```
Located at [lib/strings.nix:75](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L75) in `<nixpkgs>`.
`lib.strings.concatStringsSep`
------------------------------
#####
`concatStringsSep :: string -> [string] -> string`
Concatenate a list of strings with a separator between each element
**Example: lib.strings.concatStringsSep usage example**
```
concatStringsSep "/" ["usr" "local" "bin"]
=> "usr/local/bin"
```
Located at [lib/strings.nix:92](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L92) in `<nixpkgs>`.
`lib.strings.concatMapStringsSep`
---------------------------------
#####
`concatMapStringsSep :: string -> (a -> string) -> [a] -> string`
Maps a function over a list of strings and then concatenates the result with the specified separator interspersed between elements.
`sep`
Separator to add between elements
`f`
Function to map over the list
`list`
List of input strings
**Example: lib.strings.concatMapStringsSep usage example**
```
concatMapStringsSep "-" (x: toUpper x) ["foo" "bar" "baz"]
=> "FOO-BAR-BAZ"
```
Located at [lib/strings.nix:105](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L105) in `<nixpkgs>`.
`lib.strings.concatImapStringsSep`
----------------------------------
#####
`concatIMapStringsSep :: string -> (int -> a -> string) -> [a] -> string`
Same as `concatMapStringsSep`, but the mapping function additionally receives the position of its argument.
`sep`
Separator to add between elements
`f`
Function that receives elements and their positions
`list`
List of input strings
**Example: lib.strings.concatImapStringsSep usage example**
```
concatImapStringsSep "-" (pos: x: toString (x / pos)) [ 6 6 6 ]
=> "6-3-2"
```
Located at [lib/strings.nix:122](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L122) in `<nixpkgs>`.
`lib.strings.makeSearchPath`
----------------------------
#####
`makeSearchPath :: string -> [string] -> string`
Construct a Unix-style, colon-separated search path consisting of the given `subDir` appended to each of the given paths.
`subDir`
Directory name to append
`paths`
List of base paths
**Example: lib.strings.makeSearchPath usage example**
```
makeSearchPath "bin" ["/root" "/usr" "/usr/local"]
=> "/root/bin:/usr/bin:/usr/local/bin"
makeSearchPath "bin" [""]
=> "/bin"
```
Located at [lib/strings.nix:141](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L141) in `<nixpkgs>`.
`lib.strings.makeSearchPathOutput`
----------------------------------
#####
`string -> string -> [package] -> string`
Construct a Unix-style search path by appending the given `subDir` to the specified `output` of each of the packages. If no output by the given name is found, fallback to `.out` and then to the default.
`output`
Package output to use
`subDir`
Directory name to append
`pkgs`
List of packages
**Example: lib.strings.makeSearchPathOutput usage example**
```
makeSearchPathOutput "dev" "bin" [ pkgs.openssl pkgs.zlib ]
=> "/nix/store/9rz8gxhzf8sw4kf2j2f1grr49w8zx5vj-openssl-1.0.1r-dev/bin:/nix/store/wwh7mhwh269sfjkm6k5665b5kgp7jrk2-zlib-1.2.8/bin"
```
Located at [lib/strings.nix:159](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L159) in `<nixpkgs>`.
`lib.strings.makeLibraryPath`
-----------------------------
Construct a library search path (such as RPATH) containing the libraries for a set of packages
**Example: lib.strings.makeLibraryPath usage example**
```
makeLibraryPath [ "/usr" "/usr/local" ]
=> "/usr/lib:/usr/local/lib"
pkgs = import <nixpkgs> { }
makeLibraryPath [ pkgs.openssl pkgs.zlib ]
=> "/nix/store/9rz8gxhzf8sw4kf2j2f1grr49w8zx5vj-openssl-1.0.1r/lib:/nix/store/wwh7mhwh269sfjkm6k5665b5kgp7jrk2-zlib-1.2.8/lib"
```
Located at [lib/strings.nix:177](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L177) in `<nixpkgs>`.
`lib.strings.makeBinPath`
-------------------------
Construct a binary search path (such as $PATH) containing the binaries for a set of packages.
**Example: lib.strings.makeBinPath usage example**
```
makeBinPath ["/root" "/usr" "/usr/local"]
=> "/root/bin:/usr/bin:/usr/local/bin"
```
Located at [lib/strings.nix:186](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L186) in `<nixpkgs>`.
`lib.strings.optionalString`
----------------------------
#####
`optionalString :: bool -> string -> string`
Depending on the boolean `cond', return either the given string or the empty string. Useful to concatenate against a bigger string.
`cond`
Condition
`string`
String to return if condition is true
**Example: lib.strings.optionalString usage example**
```
optionalString true "some-string"
=> "some-string"
optionalString false "some-string"
=> ""
```
Located at [lib/strings.nix:199](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L199) in `<nixpkgs>`.
`lib.strings.hasPrefix`
-----------------------
#####
`hasPrefix :: string -> string -> bool`
Determine whether a string has given prefix.
`pref`
Prefix to check for
`str`
Input string
**Example: lib.strings.hasPrefix usage example**
```
hasPrefix "foo" "foobar"
=> true
hasPrefix "foo" "barfoo"
=> false
```
Located at [lib/strings.nix:215](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L215) in `<nixpkgs>`.
`lib.strings.hasSuffix`
-----------------------
#####
`hasSuffix :: string -> string -> bool`
Determine whether a string has given suffix.
`suffix`
Suffix to check for
`content`
Input string
**Example: lib.strings.hasSuffix usage example**
```
hasSuffix "foo" "foobar"
=> false
hasSuffix "foo" "barfoo"
=> true
```
Located at [lib/strings.nix:231](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L231) in `<nixpkgs>`.
`lib.strings.hasInfix`
----------------------
#####
`hasInfix :: string -> string -> bool`
Determine whether a string contains the given infix
`infix`
Function argument
`content`
Function argument
**Example: lib.strings.hasInfix usage example**
```
hasInfix "bc" "abcd"
=> true
hasInfix "ab" "abcd"
=> true
hasInfix "cd" "abcd"
=> true
hasInfix "foo" "abcd"
=> false
```
Located at [lib/strings.nix:256](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L256) in `<nixpkgs>`.
`lib.strings.stringToCharacters`
--------------------------------
#####
`stringToCharacters :: string -> [string]`
Convert a string to a list of characters (i.e. singleton strings). This allows you to, e.g., map a function over each character. However, note that this will likely be horribly inefficient; Nix is not a general purpose programming language. Complex string manipulations should, if appropriate, be done in a derivation. Also note that Nix treats strings as a list of bytes and thus doesn't handle unicode.
`s`
Function argument
**Example: lib.strings.stringToCharacters usage example**
```
stringToCharacters ""
=> [ ]
stringToCharacters "abc"
=> [ "a" "b" "c" ]
stringToCharacters "💩"
=> [ "�" "�" "�" "�" ]
```
Located at [lib/strings.nix:277](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L277) in `<nixpkgs>`.
`lib.strings.stringAsChars`
---------------------------
#####
`stringAsChars :: (string -> string) -> string -> string`
Manipulate a string character by character and replace them by strings before concatenating the results.
`f`
Function to map over each individual character
`s`
Input string
**Example: lib.strings.stringAsChars usage example**
```
stringAsChars (x: if x == "a" then "i" else x) "nax"
=> "nix"
```
Located at [lib/strings.nix:289](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L289) in `<nixpkgs>`.
`lib.strings.escape`
--------------------
#####
`escape :: [string] -> string -> string`
Escape occurrence of the elements of `list` in `string` by prefixing it with a backslash.
`list`
Function argument
**Example: lib.strings.escape usage example**
```
escape ["(" ")"] "(foo)"
=> "\\(foo\\)"
```
Located at [lib/strings.nix:306](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L306) in `<nixpkgs>`.
`lib.strings.escapeShellArg`
----------------------------
#####
`escapeShellArg :: string -> string`
Quote string to be used safely within the Bourne shell.
`arg`
Function argument
**Example: lib.strings.escapeShellArg usage example**
```
escapeShellArg "esc'ape\nme"
=> "'esc'\\''ape\nme'"
```
Located at [lib/strings.nix:316](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L316) in `<nixpkgs>`.
`lib.strings.escapeShellArgs`
-----------------------------
#####
`escapeShellArgs :: [string] -> string`
Quote all arguments to be safely passed to the Bourne shell.
**Example: lib.strings.escapeShellArgs usage example**
```
escapeShellArgs ["one" "two three" "four'five"]
=> "'one' 'two three' 'four'\\''five'"
```
Located at [lib/strings.nix:326](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L326) in `<nixpkgs>`.
`lib.strings.isValidPosixName`
------------------------------
#####
`string -> bool`
Test whether the given name is a valid POSIX shell variable name.
`name`
Function argument
**Example: lib.strings.isValidPosixName usage example**
```
isValidPosixName "foo_bar000"
=> true
isValidPosixName "0-bad.jpg"
=> false
```
Located at [lib/strings.nix:338](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L338) in `<nixpkgs>`.
`lib.strings.toShellVar`
------------------------
#####
`string -> (string | listOf string | attrsOf string) -> string`
Translate a Nix value into a shell variable declaration, with proper escaping.
The value can be a string (mapped to a regular variable), a list of strings (mapped to a Bash-style array) or an attribute set of strings (mapped to a Bash-style associative array). Note that "string" includes string-coercible values like paths or derivations.
Strings are translated into POSIX sh-compatible code; lists and attribute sets assume a shell that understands Bash syntax (e.g. Bash or ZSH).
`name`
Function argument
`value`
Function argument
**Example: lib.strings.toShellVar usage example**
```
''
${toShellVar "foo" "some string"}
[[ "$foo" == "some string" ]]
''
```
Located at [lib/strings.nix:358](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L358) in `<nixpkgs>`.
`lib.strings.toShellVars`
-------------------------
#####
`attrsOf (string | listOf string | attrsOf string) -> string`
Translate an attribute set into corresponding shell variable declarations using `toShellVar`.
`vars`
Function argument
**Example: lib.strings.toShellVars usage example**
```
let
foo = "value";
bar = foo;
in ''
${toShellVars { inherit foo bar; }}
[[ "$foo" == "$bar" ]]
''
```
Located at [lib/strings.nix:386](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L386) in `<nixpkgs>`.
`lib.strings.escapeNixString`
-----------------------------
#####
`string -> string`
Turn a string into a Nix expression representing that string
`s`
Function argument
**Example: lib.strings.escapeNixString usage example**
```
escapeNixString "hello\${}\n"
=> "\"hello\\\${}\\n\""
```
Located at [lib/strings.nix:396](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L396) in `<nixpkgs>`.
`lib.strings.escapeRegex`
-------------------------
#####
`string -> string`
Turn a string into an exact regular expression
**Example: lib.strings.escapeRegex usage example**
```
escapeRegex "[^a-z]*"
=> "\\[\\^a-z]\\*"
```
Located at [lib/strings.nix:406](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L406) in `<nixpkgs>`.
`lib.strings.escapeNixIdentifier`
---------------------------------
#####
`string -> string`
Quotes a string if it can't be used as an identifier directly.
`s`
Function argument
**Example: lib.strings.escapeNixIdentifier usage example**
```
escapeNixIdentifier "hello"
=> "hello"
escapeNixIdentifier "0abc"
=> "\"0abc\""
```
Located at [lib/strings.nix:418](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L418) in `<nixpkgs>`.
`lib.strings.escapeXML`
-----------------------
#####
`string -> string`
Escapes a string such that it is safe to include verbatim in an XML document.
**Example: lib.strings.escapeXML usage example**
```
escapeXML ''"test" 'test' < & >''
=> ""test" 'test' < & >"
```
Located at [lib/strings.nix:432](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L432) in `<nixpkgs>`.
`lib.strings.toLower`
---------------------
#####
`toLower :: string -> string`
Converts an ASCII string to lower-case.
**Example: lib.strings.toLower usage example**
```
toLower "HOME"
=> "home"
```
Located at [lib/strings.nix:462](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L462) in `<nixpkgs>`.
`lib.strings.toUpper`
---------------------
#####
`toUpper :: string -> string`
Converts an ASCII string to upper-case.
**Example: lib.strings.toUpper usage example**
```
toUpper "home"
=> "HOME"
```
Located at [lib/strings.nix:472](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L472) in `<nixpkgs>`.
`lib.strings.addContextFrom`
----------------------------
Appends string context from another string. This is an implementation detail of Nix.
Strings in Nix carry an invisible `context` which is a list of strings representing store paths. If the string is later used in a derivation attribute, the derivation will properly populate the inputDrvs and inputSrcs.
`a`
Function argument
`b`
Function argument
**Example: lib.strings.addContextFrom usage example**
```
pkgs = import <nixpkgs> { };
addContextFrom pkgs.coreutils "bar"
=> "bar"
```
Located at [lib/strings.nix:487](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L487) in `<nixpkgs>`.
`lib.strings.splitString`
-------------------------
Cut a string with a separator and produces a list of strings which were separated by this separator.
`_sep`
Function argument
`_s`
Function argument
**Example: lib.strings.splitString usage example**
```
splitString "." "foo.bar.baz"
=> [ "foo" "bar" "baz" ]
splitString "/" "/usr/local/bin"
=> [ "" "usr" "local" "bin" ]
```
Located at [lib/strings.nix:498](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L498) in `<nixpkgs>`.
`lib.strings.removePrefix`
--------------------------
#####
`string -> string -> string`
Return a string without the specified prefix, if the prefix matches.
`prefix`
Prefix to remove if it matches
`str`
Input string
**Example: lib.strings.removePrefix usage example**
```
removePrefix "foo." "foo.bar.baz"
=> "bar.baz"
removePrefix "xxx" "foo.bar.baz"
=> "foo.bar.baz"
```
Located at [lib/strings.nix:516](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L516) in `<nixpkgs>`.
`lib.strings.removeSuffix`
--------------------------
#####
`string -> string -> string`
Return a string without the specified suffix, if the suffix matches.
`suffix`
Suffix to remove if it matches
`str`
Input string
**Example: lib.strings.removeSuffix usage example**
```
removeSuffix "front" "homefront"
=> "home"
removeSuffix "xxx" "homefront"
=> "homefront"
```
Located at [lib/strings.nix:540](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L540) in `<nixpkgs>`.
`lib.strings.versionOlder`
--------------------------
Return true if string v1 denotes a version older than v2.
`v1`
Function argument
`v2`
Function argument
**Example: lib.strings.versionOlder usage example**
```
versionOlder "1.1" "1.2"
=> true
versionOlder "1.1" "1.1"
=> false
```
Located at [lib/strings.nix:562](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L562) in `<nixpkgs>`.
`lib.strings.versionAtLeast`
----------------------------
Return true if string v1 denotes a version equal to or newer than v2.
`v1`
Function argument
`v2`
Function argument
**Example: lib.strings.versionAtLeast usage example**
```
versionAtLeast "1.1" "1.0"
=> true
versionAtLeast "1.1" "1.1"
=> true
versionAtLeast "1.1" "1.2"
=> false
```
Located at [lib/strings.nix:574](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L574) in `<nixpkgs>`.
`lib.strings.getName`
---------------------
This function takes an argument that's either a derivation or a derivation's "name" attribute and extracts the name part from that argument.
`x`
Function argument
**Example: lib.strings.getName usage example**
```
getName "youtube-dl-2016.01.01"
=> "youtube-dl"
getName pkgs.youtube-dl
=> "youtube-dl"
```
Located at [lib/strings.nix:586](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L586) in `<nixpkgs>`.
`lib.strings.getVersion`
------------------------
This function takes an argument that's either a derivation or a derivation's "name" attribute and extracts the version part from that argument.
`x`
Function argument
**Example: lib.strings.getVersion usage example**
```
getVersion "youtube-dl-2016.01.01"
=> "2016.01.01"
getVersion pkgs.youtube-dl
=> "2016.01.01"
```
Located at [lib/strings.nix:603](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L603) in `<nixpkgs>`.
`lib.strings.nameFromURL`
-------------------------
Extract name with version from URL. Ask for separator which is supposed to start extension.
`url`
Function argument
`sep`
Function argument
**Example: lib.strings.nameFromURL usage example**
```
nameFromURL "https://nixos.org/releases/nix/nix-1.7/nix-1.7-x86_64-linux.tar.bz2" "-"
=> "nix"
nameFromURL "https://nixos.org/releases/nix/nix-1.7/nix-1.7-x86_64-linux.tar.bz2" "_"
=> "nix-1.7-x86"
```
Located at [lib/strings.nix:619](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L619) in `<nixpkgs>`.
`lib.strings.enableFeature`
---------------------------
Create an --{enable,disable}-<feat> string that can be passed to standard GNU Autoconf scripts.
`enable`
Function argument
`feat`
Function argument
**Example: lib.strings.enableFeature usage example**
```
enableFeature true "shared"
=> "--enable-shared"
enableFeature false "shared"
=> "--disable-shared"
```
Located at [lib/strings.nix:635](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L635) in `<nixpkgs>`.
`lib.strings.enableFeatureAs`
-----------------------------
Create an --{enable-<feat>=<value>,disable-<feat>} string that can be passed to standard GNU Autoconf scripts.
`enable`
Function argument
`feat`
Function argument
`value`
Function argument
**Example: lib.strings.enableFeatureAs usage example**
```
enableFeatureAs true "shared" "foo"
=> "--enable-shared=foo"
enableFeatureAs false "shared" (throw "ignored")
=> "--disable-shared"
```
Located at [lib/strings.nix:648](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L648) in `<nixpkgs>`.
`lib.strings.withFeature`
-------------------------
Create an --{with,without}-<feat> string that can be passed to standard GNU Autoconf scripts.
`with_`
Function argument
`feat`
Function argument
**Example: lib.strings.withFeature usage example**
```
withFeature true "shared"
=> "--with-shared"
withFeature false "shared"
=> "--without-shared"
```
Located at [lib/strings.nix:659](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L659) in `<nixpkgs>`.
`lib.strings.withFeatureAs`
---------------------------
Create an --{with-<feat>=<value>,without-<feat>} string that can be passed to standard GNU Autoconf scripts.
`with_`
Function argument
`feat`
Function argument
`value`
Function argument
**Example: lib.strings.withFeatureAs usage example**
```
withFeatureAs true "shared" "foo"
=> "--with-shared=foo"
withFeatureAs false "shared" (throw "ignored")
=> "--without-shared"
```
Located at [lib/strings.nix:672](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L672) in `<nixpkgs>`.
`lib.strings.fixedWidthString`
------------------------------
#####
`fixedWidthString :: int -> string -> string -> string`
Create a fixed width string with additional prefix to match required width.
This function will fail if the input string is longer than the requested length.
`width`
Function argument
`filler`
Function argument
`str`
Function argument
**Example: lib.strings.fixedWidthString usage example**
```
fixedWidthString 5 "0" (toString 15)
=> "00015"
```
Located at [lib/strings.nix:686](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L686) in `<nixpkgs>`.
`lib.strings.fixedWidthNumber`
------------------------------
Format a number adding leading zeroes up to fixed width.
`width`
Function argument
`n`
Function argument
**Example: lib.strings.fixedWidthNumber usage example**
```
fixedWidthNumber 5 15
=> "00015"
```
Located at [lib/strings.nix:703](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L703) in `<nixpkgs>`.
`lib.strings.floatToString`
---------------------------
Convert a float to a string, but emit a warning when precision is lost during the conversion
`float`
Function argument
**Example: lib.strings.floatToString usage example**
```
floatToString 0.000001
=> "0.000001"
floatToString 0.0000001
=> trace: warning: Imprecise conversion from float to string 0.000000
"0.000000"
```
Located at [lib/strings.nix:715](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L715) in `<nixpkgs>`.
`lib.strings.isCoercibleToString`
---------------------------------
Check whether a value can be coerced to a string
`x`
Function argument
Located at [lib/strings.nix:722](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L722) in `<nixpkgs>`.
`lib.strings.isStorePath`
-------------------------
Check whether a value is a store path.
`x`
Function argument
**Example: lib.strings.isStorePath usage example**
```
isStorePath "/nix/store/d945ibfx9x185xf04b890y4f9g3cbb63-python-2.7.11/bin/python"
=> false
isStorePath "/nix/store/d945ibfx9x185xf04b890y4f9g3cbb63-python-2.7.11"
=> true
isStorePath pkgs.python
=> true
isStorePath [] || isStorePath 42 || isStorePath {} || …
=> false
```
Located at [lib/strings.nix:740](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L740) in `<nixpkgs>`.
`lib.strings.toInt`
-------------------
#####
`string -> int`
Parse a string as an int.
`str`
Function argument
**Example: lib.strings.toInt usage example**
```
toInt "1337"
=> 1337
toInt "-4"
=> -4
toInt "3.14"
=> error: floating point JSON numbers are not supported
```
Located at [lib/strings.nix:761](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L761) in `<nixpkgs>`.
`lib.strings.readPathsFromFile`
-------------------------------
Read a list of paths from `file`, relative to the `rootPath`. Lines beginning with `#` are treated as comments and ignored. Whitespace is significant.
NOTE: This function is not performant and should be avoided.
**Example: lib.strings.readPathsFromFile usage example**
```
readPathsFromFile /prefix
./pkgs/development/libraries/qt-5/5.4/qtbase/series
=> [ "/prefix/dlopen-resolv.patch" "/prefix/tzdir.patch"
"/prefix/dlopen-libXcursor.patch" "/prefix/dlopen-openssl.patch"
"/prefix/dlopen-dbus.patch" "/prefix/xdg-config-dirs.patch"
"/prefix/nix-profiles-library-paths.patch"
"/prefix/compose-search-path.patch" ]
```
Located at [lib/strings.nix:782](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L782) in `<nixpkgs>`.
`lib.strings.fileContents`
--------------------------
#####
`fileContents :: path -> string`
Read the contents of a file removing the trailing \n
`file`
Function argument
**Example: lib.strings.fileContents usage example**
```
$ echo "1.0" > ./version
fileContents ./version
=> "1.0"
```
Located at [lib/strings.nix:802](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L802) in `<nixpkgs>`.
`lib.strings.sanitizeDerivationName`
------------------------------------
#####
`sanitizeDerivationName :: String -> String`
Creates a valid derivation name from a potentially invalid one.
**Example: lib.strings.sanitizeDerivationName usage example**
```
sanitizeDerivationName "../hello.bar # foo"
=> "-hello.bar-foo"
sanitizeDerivationName ""
=> "unknown"
sanitizeDerivationName pkgs.hello
=> "-nix-store-2g75chlbpxlrqn15zlby2dfh8hr9qwbk-hello-2.10"
```
Located at [lib/strings.nix:817](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L817) in `<nixpkgs>`.
`lib.strings.levenshtein`
-------------------------
#####
`levenshtein :: string -> string -> int`
Computes the Levenshtein distance between two strings. Complexity O(n\*m) where n and m are the lengths of the strings. Algorithm adjusted from https://stackoverflow.com/a/9750974/6605742
`a`
Function argument
`b`
Function argument
**Example: lib.strings.levenshtein usage example**
```
levenshtein "foo" "foo"
=> 0
levenshtein "book" "hook"
=> 1
levenshtein "hello" "Heyo"
=> 3
```
Located at [lib/strings.nix:856](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L856) in `<nixpkgs>`.
`lib.strings.commonPrefixLength`
--------------------------------
Returns the length of the prefix common to both strings.
`a`
Function argument
`b`
Function argument
Located at [lib/strings.nix:877](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L877) in `<nixpkgs>`.
`lib.strings.commonSuffixLength`
--------------------------------
Returns the length of the suffix common to both strings.
`a`
Function argument
`b`
Function argument
Located at [lib/strings.nix:885](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L885) in `<nixpkgs>`.
`lib.strings.levenshteinAtMost`
-------------------------------
#####
`levenshteinAtMost :: int -> string -> string -> bool`
Returns whether the levenshtein distance between two strings is at most some value Complexity is O(min(n,m)) for k <= 2 and O(n\*m) otherwise
**Example: lib.strings.levenshteinAtMost usage example**
```
levenshteinAtMost 0 "foo" "foo"
=> true
levenshteinAtMost 1 "foo" "boa"
=> false
levenshteinAtMost 2 "foo" "boa"
=> true
levenshteinAtMost 2 "This is a sentence" "this is a sentense."
=> false
levenshteinAtMost 3 "This is a sentence" "this is a sentense."
=> true
```
Located at [lib/strings.nix:909](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L909) in `<nixpkgs>`.
`lib.trivial.id`
----------------
#####
`id :: a -> a`
The identity function For when you need a function that does “nothing”.
`x`
The value to return
Located at [lib/trivial.nix:12](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L12) in `<nixpkgs>`.
`lib.trivial.const`
-------------------
#####
`const :: a -> b -> a`
The constant function
Ignores the second argument. If called with only one argument, constructs a function that always returns a static value.
`x`
Value to return
`y`
Value to ignore
**Example: lib.trivial.const usage example**
```
let f = const 5; in f 10
=> 5
```
Located at [lib/trivial.nix:26](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L26) in `<nixpkgs>`.
`lib.trivial.pipe`
------------------
#####
`pipe :: a -> [<functions>] -> <return type of last function>`
Pipes a value through a list of functions, left to right.
`val`
Function argument
`functions`
Function argument
**Example: lib.trivial.pipe usage example**
```
pipe 2 [
(x: x + 2) # 2 + 2 = 4
(x: x * 2) # 4 * 2 = 8
]
=> 8
# ideal to do text transformations
pipe [ "a/b" "a/c" ] [
# create the cp command
(map (file: ''cp "${src}/${file}" $out\n''))
# concatenate all commands into one string
lib.concatStrings
# make that string into a nix derivation
(pkgs.runCommand "copy-to-out" {})
]
=> <drv which copies all files to $out>
The output type of each function has to be the input type
of the next function, and the last function returns the
final value.
```
Located at [lib/trivial.nix:61](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L61) in `<nixpkgs>`.
`lib.trivial.concat`
--------------------
#####
`concat :: [a] -> [a] -> [a]`
Concatenate two lists
`x`
Function argument
`y`
Function argument
**Example: lib.trivial.concat usage example**
```
concat [ 1 2 ] [ 3 4 ]
=> [ 1 2 3 4 ]
```
Located at [lib/trivial.nix:80](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L80) in `<nixpkgs>`.
`lib.trivial.or`
----------------
boolean “or”
`x`
Function argument
`y`
Function argument
Located at [lib/trivial.nix:83](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L83) in `<nixpkgs>`.
`lib.trivial.and`
-----------------
boolean “and”
`x`
Function argument
`y`
Function argument
Located at [lib/trivial.nix:86](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L86) in `<nixpkgs>`.
`lib.trivial.bitAnd`
--------------------
bitwise “and”
Located at [lib/trivial.nix:89](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L89) in `<nixpkgs>`.
`lib.trivial.bitOr`
-------------------
bitwise “or”
Located at [lib/trivial.nix:94](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L94) in `<nixpkgs>`.
`lib.trivial.bitXor`
--------------------
bitwise “xor”
Located at [lib/trivial.nix:99](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L99) in `<nixpkgs>`.
`lib.trivial.bitNot`
--------------------
bitwise “not”
Located at [lib/trivial.nix:104](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L104) in `<nixpkgs>`.
`lib.trivial.boolToString`
--------------------------
#####
`boolToString :: bool -> string`
Convert a boolean to a string.
This function uses the strings "true" and "false" to represent boolean values. Calling `toString` on a bool instead returns "1" and "" (sic!).
`b`
Function argument
Located at [lib/trivial.nix:114](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L114) in `<nixpkgs>`.
`lib.trivial.mergeAttrs`
------------------------
Merge two attribute sets shallowly, right side trumps left
mergeAttrs :: attrs -> attrs -> attrs
`x`
Left attribute set
`y`
Right attribute set (higher precedence for equal keys)
**Example: lib.trivial.mergeAttrs usage example**
```
mergeAttrs { a = 1; b = 2; } { b = 3; c = 4; }
=> { a = 1; b = 3; c = 4; }
```
Located at [lib/trivial.nix:124](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L124) in `<nixpkgs>`.
`lib.trivial.flip`
------------------
#####
`flip :: (a -> b -> c) -> (b -> a -> c)`
Flip the order of the arguments of a binary function.
`f`
Function argument
`a`
Function argument
`b`
Function argument
**Example: lib.trivial.flip usage example**
```
flip concat [1] [2]
=> [ 2 1 ]
```
Located at [lib/trivial.nix:138](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L138) in `<nixpkgs>`.
`lib.trivial.mapNullable`
-------------------------
Apply function if the supplied argument is non-null.
`f`
Function to call
`a`
Argument to check for null before passing it to `f`
**Example: lib.trivial.mapNullable usage example**
```
mapNullable (x: x+1) null
=> null
mapNullable (x: x+1) 22
=> 23
```
Located at [lib/trivial.nix:148](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L148) in `<nixpkgs>`.
`lib.trivial.version`
---------------------
Returns the current full nixpkgs version number.
Located at [lib/trivial.nix:164](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L164) in `<nixpkgs>`.
`lib.trivial.release`
---------------------
Returns the current nixpkgs release number as string.
Located at [lib/trivial.nix:167](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L167) in `<nixpkgs>`.
`lib.trivial.oldestSupportedRelease`
------------------------------------
The latest release that is supported, at the time of release branch-off, if applicable.
Ideally, out-of-tree modules should be able to evaluate cleanly with all supported Nixpkgs versions (master, release and old release until EOL). So if possible, deprecation warnings should take effect only when all out-of-tree expressions/libs/modules can upgrade to the new way without losing support for supported Nixpkgs versions.
This release number allows deprecation warnings to be implemented such that they take effect as soon as the oldest release reaches end of life.
Located at [lib/trivial.nix:180](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L180) in `<nixpkgs>`.
`lib.trivial.isInOldestRelease`
-------------------------------
Whether a feature is supported in all supported releases (at the time of release branch-off, if applicable). See `oldestSupportedRelease`.
`release`
Release number of feature introduction as an integer, e.g. 2111 for 21.11. Set it to the upcoming release, matching the nixpkgs/.version file.
Located at [lib/trivial.nix:186](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L186) in `<nixpkgs>`.
`lib.trivial.codeName`
----------------------
Returns the current nixpkgs release code name.
On each release the first letter is bumped and a new animal is chosen starting with that new letter.
Located at [lib/trivial.nix:198](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L198) in `<nixpkgs>`.
`lib.trivial.versionSuffix`
---------------------------
Returns the current nixpkgs version suffix as string.
Located at [lib/trivial.nix:201](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L201) in `<nixpkgs>`.
`lib.trivial.revisionWithDefault`
---------------------------------
#####
`revisionWithDefault :: string -> string`
Attempts to return the the current revision of nixpkgs and returns the supplied default value otherwise.
`default`
Default value to return if revision can not be determined
Located at [lib/trivial.nix:212](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L212) in `<nixpkgs>`.
`lib.trivial.inNixShell`
------------------------
#####
`inNixShell :: bool`
Determine whether the function is being called from inside a Nix shell.
Located at [lib/trivial.nix:230](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L230) in `<nixpkgs>`.
`lib.trivial.min`
-----------------
Return minimum of two numbers.
`x`
Function argument
`y`
Function argument
Located at [lib/trivial.nix:236](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L236) in `<nixpkgs>`.
`lib.trivial.max`
-----------------
Return maximum of two numbers.
`x`
Function argument
`y`
Function argument
Located at [lib/trivial.nix:239](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L239) in `<nixpkgs>`.
`lib.trivial.mod`
-----------------
Integer modulus
`base`
Function argument
`int`
Function argument
**Example: lib.trivial.mod usage example**
```
mod 11 10
=> 1
mod 1 10
=> 1
```
Located at [lib/trivial.nix:249](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L249) in `<nixpkgs>`.
`lib.trivial.compare`
---------------------
C-style comparisons
a < b, compare a b => -1 a == b, compare a b => 0 a > b, compare a b => 1
`a`
Function argument
`b`
Function argument
Located at [lib/trivial.nix:260](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L260) in `<nixpkgs>`.
`lib.trivial.splitByAndCompare`
-------------------------------
#####
`(a -> bool) -> (a -> a -> int) -> (a -> a -> int) -> (a -> a -> int)`
Split type into two subtypes by predicate `p`, take all elements of the first subtype to be less than all the elements of the second subtype, compare elements of a single subtype with `yes` and `no` respectively.
`p`
Predicate
`yes`
Comparison function if predicate holds for both values
`no`
Comparison function if predicate holds for neither value
`a`
First value to compare
`b`
Second value to compare
**Example: lib.trivial.splitByAndCompare usage example**
```
let cmp = splitByAndCompare (hasPrefix "foo") compare compare; in
cmp "a" "z" => -1
cmp "fooa" "fooz" => -1
cmp "f" "a" => 1
cmp "fooa" "a" => -1
# while
compare "fooa" "a" => 1
```
Located at [lib/trivial.nix:285](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L285) in `<nixpkgs>`.
`lib.trivial.importJSON`
------------------------
Reads a JSON file.
Type :: path -> any
`path`
Function argument
Located at [lib/trivial.nix:305](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L305) in `<nixpkgs>`.
`lib.trivial.importTOML`
------------------------
Reads a TOML file.
Type :: path -> any
`path`
Function argument
Located at [lib/trivial.nix:312](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L312) in `<nixpkgs>`.
`lib.trivial.warn`
------------------
#####
`string -> a -> a`
Print a warning before returning the second argument. This function behaves like `builtins.trace`, but requires a string message and formats it as a warning, including the `warning: ` prefix.
To get a call stack trace and abort evaluation, set the environment variable `NIX\_ABORT\_ON\_WARN=true` and set the Nix options `--option pure-eval false --show-trace`
Located at [lib/trivial.nix:340](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L340) in `<nixpkgs>`.
`lib.trivial.warnIf`
--------------------
#####
`bool -> string -> a -> a`
Like warn, but only warn when the first argument is `true`.
`cond`
Function argument
`msg`
Function argument
Located at [lib/trivial.nix:350](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L350) in `<nixpkgs>`.
`lib.trivial.warnIfNot`
-----------------------
#####
`bool -> string -> a -> a`
Like warnIf, but negated (warn if the first argument is `false`).
`cond`
Function argument
`msg`
Function argument
Located at [lib/trivial.nix:357](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L357) in `<nixpkgs>`.
`lib.trivial.throwIfNot`
------------------------
#####
`bool -> string -> a -> a`
Like the `assert b; e` expression, but with a custom error message and without the semicolon.
If true, return the identity function, `r: r`.
If false, throw the error message.
Calls can be juxtaposed using function application, as `(r: r) a = a`, so `(r: r) (r: r) a = a`, and so forth.
`cond`
Function argument
`msg`
Function argument
**Example: lib.trivial.throwIfNot usage example**
```
throwIfNot (lib.isList overlays) "The overlays argument to nixpkgs must be a list."
lib.foldr (x: throwIfNot (lib.isFunction x) "All overlays passed to nixpkgs must be functions.") (r: r) overlays
pkgs
```
Located at [lib/trivial.nix:379](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L379) in `<nixpkgs>`.
`lib.trivial.throwIf`
---------------------
#####
`bool -> string -> a -> a`
Like throwIfNot, but negated (throw if the first argument is `true`).
`cond`
Function argument
`msg`
Function argument
Located at [lib/trivial.nix:386](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L386) in `<nixpkgs>`.
`lib.trivial.checkListOfEnum`
-----------------------------
#####
`String -> List ComparableVal -> List ComparableVal -> a -> a`
Check if the elements in a list are valid values from a enum, returning the identity function, or throwing an error message otherwise.
`msg`
Function argument
`valid`
Function argument
`given`
Function argument
**Example: lib.trivial.checkListOfEnum usage example**
```
let colorVariants = ["bright" "dark" "black"]
in checkListOfEnum "color variants" [ "standard" "light" "dark" ] colorVariants;
=>
error: color variants: bright, black unexpected; valid ones: standard, light, dark
```
Located at [lib/trivial.nix:398](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L398) in `<nixpkgs>`.
`lib.trivial.setFunctionArgs`
-----------------------------
Add metadata about expected function arguments to a function. The metadata should match the format given by builtins.functionArgs, i.e. a set from expected argument to a bool representing whether that argument has a default or not. setFunctionArgs : (a → b) → Map String Bool → (a → b)
This function is necessary because you can't dynamically create a function of the { a, b ? foo, ... }: format, but some facilities like callPackage expect to be able to query expected arguments.
`f`
Function argument
`args`
Function argument
Located at [lib/trivial.nix:421](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L421) in `<nixpkgs>`.
`lib.trivial.functionArgs`
--------------------------
Extract the expected function arguments from a function. This works both with nix-native { a, b ? foo, ... }: style functions and functions with args set with 'setFunctionArgs'. It has the same return type and semantics as builtins.functionArgs. setFunctionArgs : (a → b) → Map String Bool.
`f`
Function argument
Located at [lib/trivial.nix:433](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L433) in `<nixpkgs>`.
`lib.trivial.isFunction`
------------------------
Check whether something is a function or something annotated with function args.
`f`
Function argument
Located at [lib/trivial.nix:441](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L441) in `<nixpkgs>`.
`lib.trivial.toFunction`
------------------------
Turns any non-callable values into constant functions. Returns callable values as is.
`v`
Any value
**Example: lib.trivial.toFunction usage example**
```
nix-repl> lib.toFunction 1 2
1
nix-repl> lib.toFunction (x: x + 1) 2
3
```
Located at [lib/trivial.nix:456](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L456) in `<nixpkgs>`.
`lib.trivial.toHexString`
-------------------------
Convert the given positive integer to a string of its hexadecimal representation. For example:
toHexString 0 => "0"
toHexString 16 => "10"
toHexString 250 => "FA"
`i`
Function argument
Located at [lib/trivial.nix:472](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L472) in `<nixpkgs>`.
`lib.trivial.toBaseDigits`
--------------------------
`toBaseDigits base i` converts the positive integer i to a list of its digits in the given base. For example:
toBaseDigits 10 123 => [ 1 2 3 ]
toBaseDigits 2 6 => [ 1 1 0 ]
toBaseDigits 16 250 => [ 15 10 ]
`base`
Function argument
`i`
Function argument
Located at [lib/trivial.nix:498](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L498) in `<nixpkgs>`.
`lib.lists.singleton`
---------------------
#####
`singleton :: a -> [a]`
Create a list consisting of a single element. `singleton x` is sometimes more convenient with respect to indentation than `[x]` when x spans multiple lines.
`x`
Function argument
**Example: lib.lists.singleton usage example**
```
singleton "foo"
=> [ "foo" ]
```
Located at [lib/lists.nix:23](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L23) in `<nixpkgs>`.
`lib.lists.forEach`
-------------------
#####
`forEach :: [a] -> (a -> b) -> [b]`
Apply the function to each element in the list. Same as `map`, but arguments flipped.
`xs`
Function argument
`f`
Function argument
**Example: lib.lists.forEach usage example**
```
forEach [ 1 2 ] (x:
toString x
)
=> [ "1" "2" ]
```
Located at [lib/lists.nix:36](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L36) in `<nixpkgs>`.
`lib.lists.foldr`
-----------------
#####
`foldr :: (a -> b -> b) -> b -> [a] -> b`
“right fold” a binary function `op` between successive elements of `list` with `nul' as the starting value, i.e., `foldr op nul [x\_1 x\_2 ... x\_n] == op x\_1 (op x\_2 ... (op x\_n nul))`.
`op`
Function argument
`nul`
Function argument
`list`
Function argument
**Example: lib.lists.foldr usage example**
```
concat = foldr (a: b: a + b) "z"
concat [ "a" "b" "c" ]
=> "abcz"
# different types
strange = foldr (int: str: toString (int + 1) + str) "a"
strange [ 1 2 3 4 ]
=> "2345a"
```
Located at [lib/lists.nix:53](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L53) in `<nixpkgs>`.
`lib.lists.fold`
----------------
`fold` is an alias of `foldr` for historic reasons
Located at [lib/lists.nix:64](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L64) in `<nixpkgs>`.
`lib.lists.foldl`
-----------------
#####
`foldl :: (b -> a -> b) -> b -> [a] -> b`
“left fold”, like `foldr`, but from the left: `foldl op nul [x\_1 x\_2 ... x\_n] == op (... (op (op nul x\_1) x\_2) ... x\_n)`.
`op`
Function argument
`nul`
Function argument
`list`
Function argument
**Example: lib.lists.foldl usage example**
```
lconcat = foldl (a: b: a + b) "z"
lconcat [ "a" "b" "c" ]
=> "zabc"
# different types
lstrange = foldl (str: int: str + toString (int + 1)) "a"
lstrange [ 1 2 3 4 ]
=> "a2345"
```
Located at [lib/lists.nix:81](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L81) in `<nixpkgs>`.
`lib.lists.foldl'`
------------------
#####
`foldl' :: (b -> a -> b) -> b -> [a] -> b`
Strict version of `foldl`.
The difference is that evaluation is forced upon access. Usually used with small whole results (in contrast with lazily-generated list or large lists where only a part is consumed.)
Located at [lib/lists.nix:97](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L97) in `<nixpkgs>`.
`lib.lists.imap0`
-----------------
#####
`imap0 :: (int -> a -> b) -> [a] -> [b]`
Map with index starting from 0
`f`
Function argument
`list`
Function argument
**Example: lib.lists.imap0 usage example**
```
imap0 (i: v: "${v}-${toString i}") ["a" "b"]
=> [ "a-0" "b-1" ]
```
Located at [lib/lists.nix:107](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L107) in `<nixpkgs>`.
`lib.lists.imap1`
-----------------
#####
`imap1 :: (int -> a -> b) -> [a] -> [b]`
Map with index starting from 1
`f`
Function argument
`list`
Function argument
**Example: lib.lists.imap1 usage example**
```
imap1 (i: v: "${v}-${toString i}") ["a" "b"]
=> [ "a-1" "b-2" ]
```
Located at [lib/lists.nix:117](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L117) in `<nixpkgs>`.
`lib.lists.concatMap`
---------------------
#####
`concatMap :: (a -> [b]) -> [a] -> [b]`
Map and concatenate the result.
**Example: lib.lists.concatMap usage example**
```
concatMap (x: [x] ++ ["z"]) ["a" "b"]
=> [ "a" "z" "b" "z" ]
```
Located at [lib/lists.nix:127](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L127) in `<nixpkgs>`.
`lib.lists.flatten`
-------------------
Flatten the argument into a single list; that is, nested lists are spliced into the top-level lists.
`x`
Function argument
**Example: lib.lists.flatten usage example**
```
flatten [1 [2 [3] 4] 5]
=> [1 2 3 4 5]
flatten 1
=> [1]
```
Located at [lib/lists.nix:138](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L138) in `<nixpkgs>`.
`lib.lists.remove`
------------------
#####
`remove :: a -> [a] -> [a]`
Remove elements equal to 'e' from a list. Useful for buildInputs.
`e`
Element to remove from the list
**Example: lib.lists.remove usage example**
```
remove 3 [ 1 3 4 3 ]
=> [ 1 4 ]
```
Located at [lib/lists.nix:151](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L151) in `<nixpkgs>`.
`lib.lists.findSingle`
----------------------
#####
`findSingle :: (a -> bool) -> a -> a -> [a] -> a`
Find the sole element in the list matching the specified predicate, returns `default` if no such element exists, or `multiple` if there are multiple matching elements.
`pred`
Predicate
`default`
Default value to return if element was not found.
`multiple`
Default value to return if more than one element was found
`list`
Input list
**Example: lib.lists.findSingle usage example**
```
findSingle (x: x == 3) "none" "multiple" [ 1 3 3 ]
=> "multiple"
findSingle (x: x == 3) "none" "multiple" [ 1 3 ]
=> 3
findSingle (x: x == 3) "none" "multiple" [ 1 9 ]
=> "none"
```
Located at [lib/lists.nix:169](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L169) in `<nixpkgs>`.
`lib.lists.findFirst`
---------------------
#####
`findFirst :: (a -> bool) -> a -> [a] -> a`
Find the first element in the list matching the specified predicate or return `default` if no such element exists.
`pred`
Predicate
`default`
Default value to return
`list`
Input list
**Example: lib.lists.findFirst usage example**
```
findFirst (x: x > 3) 7 [ 1 6 4 ]
=> 6
findFirst (x: x > 9) 7 [ 1 6 4 ]
=> 7
```
Located at [lib/lists.nix:194](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L194) in `<nixpkgs>`.
`lib.lists.any`
---------------
#####
`any :: (a -> bool) -> [a] -> bool`
Return true if function `pred` returns true for at least one element of `list`.
**Example: lib.lists.any usage example**
```
any isString [ 1 "a" { } ]
=> true
any isString [ 1 { } ]
=> false
```
Located at [lib/lists.nix:215](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L215) in `<nixpkgs>`.
`lib.lists.all`
---------------
#####
`all :: (a -> bool) -> [a] -> bool`
Return true if function `pred` returns true for all elements of `list`.
**Example: lib.lists.all usage example**
```
all (x: x < 3) [ 1 2 ]
=> true
all (x: x < 3) [ 1 2 3 ]
=> false
```
Located at [lib/lists.nix:228](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L228) in `<nixpkgs>`.
`lib.lists.count`
-----------------
#####
`count :: (a -> bool) -> [a] -> int`
Count how many elements of `list` match the supplied predicate function.
`pred`
Predicate
**Example: lib.lists.count usage example**
```
count (x: x == 3) [ 3 2 3 4 6 ]
=> 2
```
Located at [lib/lists.nix:239](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L239) in `<nixpkgs>`.
`lib.lists.optional`
--------------------
#####
`optional :: bool -> a -> [a]`
Return a singleton list or an empty list, depending on a boolean value. Useful when building lists with optional elements (e.g. `++ optional (system == "i686-linux") firefox').
`cond`
Function argument
`elem`
Function argument
**Example: lib.lists.optional usage example**
```
optional true "foo"
=> [ "foo" ]
optional false "foo"
=> [ ]
```
Located at [lib/lists.nix:255](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L255) in `<nixpkgs>`.
`lib.lists.optionals`
---------------------
#####
`optionals :: bool -> [a] -> [a]`
Return a list or an empty list, depending on a boolean value.
`cond`
Condition
`elems`
List to return if condition is true
**Example: lib.lists.optionals usage example**
```
optionals true [ 2 3 ]
=> [ 2 3 ]
optionals false [ 2 3 ]
=> [ ]
```
Located at [lib/lists.nix:267](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L267) in `<nixpkgs>`.
`lib.lists.toList`
------------------
If argument is a list, return it; else, wrap it in a singleton list. If you're using this, you should almost certainly reconsider if there isn't a more "well-typed" approach.
`x`
Function argument
**Example: lib.lists.toList usage example**
```
toList [ 1 2 ]
=> [ 1 2 ]
toList "hi"
=> [ "hi "]
```
Located at [lib/lists.nix:284](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L284) in `<nixpkgs>`.
`lib.lists.range`
-----------------
#####
`range :: int -> int -> [int]`
Return a list of integers from `first' up to and including `last'.
`first`
First integer in the range
`last`
Last integer in the range
**Example: lib.lists.range usage example**
```
range 2 4
=> [ 2 3 4 ]
range 3 2
=> [ ]
```
Located at [lib/lists.nix:296](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L296) in `<nixpkgs>`.
`lib.lists.partition`
---------------------
#####
`(a -> bool) -> [a] -> { right :: [a], wrong :: [a] }`
Splits the elements of a list in two lists, `right` and `wrong`, depending on the evaluation of a predicate.
**Example: lib.lists.partition usage example**
```
partition (x: x > 2) [ 5 1 2 3 4 ]
=> { right = [ 5 3 4 ]; wrong = [ 1 2 ]; }
```
Located at [lib/lists.nix:315](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L315) in `<nixpkgs>`.
`lib.lists.groupBy'`
--------------------
Splits the elements of a list into many lists, using the return value of a predicate. Predicate should return a string which becomes keys of attrset `groupBy' returns.
`groupBy'` allows to customise the combining function and initial value
`op`
Function argument
`nul`
Function argument
`pred`
Function argument
`lst`
Function argument
**Example: lib.lists.groupBy' usage example**
```
groupBy (x: boolToString (x > 2)) [ 5 1 2 3 4 ]
=> { true = [ 5 3 4 ]; false = [ 1 2 ]; }
groupBy (x: x.name) [ {name = "icewm"; script = "icewm &";}
{name = "xfce"; script = "xfce4-session &";}
{name = "icewm"; script = "icewmbg &";}
{name = "mate"; script = "gnome-session &";}
]
=> { icewm = [ { name = "icewm"; script = "icewm &"; }
{ name = "icewm"; script = "icewmbg &"; } ];
mate = [ { name = "mate"; script = "gnome-session &"; } ];
xfce = [ { name = "xfce"; script = "xfce4-session &"; } ];
}
groupBy' builtins.add 0 (x: boolToString (x > 2)) [ 5 1 2 3 4 ]
=> { true = 12; false = 3; }
```
Located at [lib/lists.nix:344](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L344) in `<nixpkgs>`.
`lib.lists.zipListsWith`
------------------------
#####
`zipListsWith :: (a -> b -> c) -> [a] -> [b] -> [c]`
Merges two lists of the same size together. If the sizes aren't the same the merging stops at the shortest. How both lists are merged is defined by the first argument.
`f`
Function to zip elements of both lists
`fst`
First list
`snd`
Second list
**Example: lib.lists.zipListsWith usage example**
```
zipListsWith (a: b: a + b) ["h" "l"] ["e" "o"]
=> ["he" "lo"]
```
Located at [lib/lists.nix:364](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L364) in `<nixpkgs>`.
`lib.lists.zipLists`
--------------------
#####
`zipLists :: [a] -> [b] -> [{ fst :: a, snd :: b}]`
Merges two lists of the same size together. If the sizes aren't the same the merging stops at the shortest.
**Example: lib.lists.zipLists usage example**
```
zipLists [ 1 2 ] [ "a" "b" ]
=> [ { fst = 1; snd = "a"; } { fst = 2; snd = "b"; } ]
```
Located at [lib/lists.nix:383](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L383) in `<nixpkgs>`.
`lib.lists.reverseList`
-----------------------
#####
`reverseList :: [a] -> [a]`
Reverse the order of the elements of a list.
`xs`
Function argument
**Example: lib.lists.reverseList usage example**
```
reverseList [ "b" "o" "j" ]
=> [ "j" "o" "b" ]
```
Located at [lib/lists.nix:394](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L394) in `<nixpkgs>`.
`lib.lists.listDfs`
-------------------
Depth-First Search (DFS) for lists `list != []`.
`before a b == true` means that `b` depends on `a` (there's an edge from `b` to `a`).
`stopOnCycles`
Function argument
`before`
Function argument
`list`
Function argument
**Example: lib.lists.listDfs usage example**
```
listDfs true hasPrefix [ "/home/user" "other" "/" "/home" ]
== { minimal = "/"; # minimal element
visited = [ "/home/user" ]; # seen elements (in reverse order)
rest = [ "/home" "other" ]; # everything else
}
listDfs true hasPrefix [ "/home/user" "other" "/" "/home" "/" ]
== { cycle = "/"; # cycle encountered at this element
loops = [ "/" ]; # and continues to these elements
visited = [ "/" "/home/user" ]; # elements leading to the cycle (in reverse order)
rest = [ "/home" "other" ]; # everything else
```
Located at [lib/lists.nix:416](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L416) in `<nixpkgs>`.
`lib.lists.toposort`
--------------------
Sort a list based on a partial ordering using DFS. This implementation is O(N^2), if your ordering is linear, use `sort` instead.
`before a b == true` means that `b` should be after `a` in the result.
`before`
Function argument
`list`
Function argument
**Example: lib.lists.toposort usage example**
```
toposort hasPrefix [ "/home/user" "other" "/" "/home" ]
== { result = [ "/" "/home" "/home/user" "other" ]; }
toposort hasPrefix [ "/home/user" "other" "/" "/home" "/" ]
== { cycle = [ "/home/user" "/" "/" ]; # path leading to a cycle
loops = [ "/" ]; } # loops back to these elements
toposort hasPrefix [ "other" "/home/user" "/home" "/" ]
== { result = [ "other" "/" "/home" "/home/user" ]; }
toposort (a: b: a < b) [ 3 2 1 ] == { result = [ 1 2 3 ]; }
```
Located at [lib/lists.nix:455](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L455) in `<nixpkgs>`.
`lib.lists.sort`
----------------
Sort a list based on a comparator function which compares two elements and returns true if the first argument is strictly below the second argument. The returned list is sorted in an increasing order. The implementation does a quick-sort.
**Example: lib.lists.sort usage example**
```
sort (a: b: a < b) [ 5 3 7 ]
=> [ 3 5 7 ]
```
Located at [lib/lists.nix:483](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L483) in `<nixpkgs>`.
`lib.lists.compareLists`
------------------------
Compare two lists element-by-element.
`cmp`
Function argument
`a`
Function argument
`b`
Function argument
**Example: lib.lists.compareLists usage example**
```
compareLists compare [] []
=> 0
compareLists compare [] [ "a" ]
=> -1
compareLists compare [ "a" ] []
=> 1
compareLists compare [ "a" "b" ] [ "a" "c" ]
=> 1
```
Located at [lib/lists.nix:512](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L512) in `<nixpkgs>`.
`lib.lists.naturalSort`
-----------------------
Sort list using "Natural sorting". Numeric portions of strings are sorted in numeric order.
`lst`
Function argument
**Example: lib.lists.naturalSort usage example**
```
naturalSort ["disk11" "disk8" "disk100" "disk9"]
=> ["disk8" "disk9" "disk11" "disk100"]
naturalSort ["10.46.133.149" "10.5.16.62" "10.54.16.25"]
=> ["10.5.16.62" "10.46.133.149" "10.54.16.25"]
naturalSort ["v0.2" "v0.15" "v0.0.9"]
=> [ "v0.0.9" "v0.2" "v0.15" ]
```
Located at [lib/lists.nix:535](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L535) in `<nixpkgs>`.
`lib.lists.take`
----------------
#####
`take :: int -> [a] -> [a]`
Return the first (at most) N elements of a list.
`count`
Number of elements to take
**Example: lib.lists.take usage example**
```
take 2 [ "a" "b" "c" "d" ]
=> [ "a" "b" ]
take 2 [ ]
=> [ ]
```
Located at [lib/lists.nix:553](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L553) in `<nixpkgs>`.
`lib.lists.drop`
----------------
#####
`drop :: int -> [a] -> [a]`
Remove the first (at most) N elements of a list.
`count`
Number of elements to drop
`list`
Input list
**Example: lib.lists.drop usage example**
```
drop 2 [ "a" "b" "c" "d" ]
=> [ "c" "d" ]
drop 2 [ ]
=> [ ]
```
Located at [lib/lists.nix:567](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L567) in `<nixpkgs>`.
`lib.lists.sublist`
-------------------
#####
`sublist :: int -> int -> [a] -> [a]`
Return a list consisting of at most `count` elements of `list`, starting at index `start`.
`start`
Index at which to start the sublist
`count`
Number of elements to take
`list`
Input list
**Example: lib.lists.sublist usage example**
```
sublist 1 3 [ "a" "b" "c" "d" "e" ]
=> [ "b" "c" "d" ]
sublist 1 3 [ ]
=> [ ]
```
Located at [lib/lists.nix:584](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L584) in `<nixpkgs>`.
`lib.lists.last`
----------------
#####
`last :: [a] -> a`
Return the last element of a list.
This function throws an error if the list is empty.
`list`
Function argument
**Example: lib.lists.last usage example**
```
last [ 1 2 3 ]
=> 3
```
Located at [lib/lists.nix:608](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L608) in `<nixpkgs>`.
`lib.lists.init`
----------------
#####
`init :: [a] -> [a]`
Return all elements but the last.
This function throws an error if the list is empty.
`list`
Function argument
**Example: lib.lists.init usage example**
```
init [ 1 2 3 ]
=> [ 1 2 ]
```
Located at [lib/lists.nix:622](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L622) in `<nixpkgs>`.
`lib.lists.crossLists`
----------------------
Return the image of the cross product of some lists by a function.
**Example: lib.lists.crossLists usage example**
```
crossLists (x:y: "${toString x}${toString y}") [[1 2] [3 4]]
=> [ "13" "14" "23" "24" ]
```
Located at [lib/lists.nix:633](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L633) in `<nixpkgs>`.
`lib.lists.unique`
------------------
#####
`unique :: [a] -> [a]`
Remove duplicate elements from the list. O(n^2) complexity.
**Example: lib.lists.unique usage example**
```
unique [ 3 2 3 4 ]
=> [ 3 2 4 ]
```
Located at [lib/lists.nix:646](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L646) in `<nixpkgs>`.
`lib.lists.intersectLists`
--------------------------
Intersects list 'e' and another list. O(nm) complexity.
`e`
Function argument
**Example: lib.lists.intersectLists usage example**
```
intersectLists [ 1 2 3 ] [ 6 3 2 ]
=> [ 3 2 ]
```
Located at [lib/lists.nix:654](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L654) in `<nixpkgs>`.
`lib.lists.subtractLists`
-------------------------
Subtracts list 'e' from another list. O(nm) complexity.
`e`
Function argument
**Example: lib.lists.subtractLists usage example**
```
subtractLists [ 3 2 ] [ 1 2 3 4 5 3 ]
=> [ 1 4 5 ]
```
Located at [lib/lists.nix:662](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L662) in `<nixpkgs>`.
`lib.lists.mutuallyExclusive`
-----------------------------
Test if two lists have no common element. It should be slightly more efficient than (intersectLists a b == [])
`a`
Function argument
`b`
Function argument
Located at [lib/lists.nix:667](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L667) in `<nixpkgs>`.
`lib.debug.traceIf`
-------------------
#####
`traceIf :: bool -> string -> a -> a`
Conditionally trace the supplied message, based on a predicate.
`pred`
Predicate to check
`msg`
Message that should be traced
`x`
Value to return
**Example: lib.debug.traceIf usage example**
```
traceIf true "hello" 3
trace: hello
=> 3
```
Located at [lib/debug.nix:51](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L51) in `<nixpkgs>`.
`lib.debug.traceValFn`
----------------------
#####
`traceValFn :: (a -> b) -> a -> a`
Trace the supplied value after applying a function to it, and return the original value.
`f`
Function to apply
`x`
Value to trace and return
**Example: lib.debug.traceValFn usage example**
```
traceValFn (v: "mystring ${v}") "foo"
trace: mystring foo
=> "foo"
```
Located at [lib/debug.nix:69](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L69) in `<nixpkgs>`.
`lib.debug.traceVal`
--------------------
#####
`traceVal :: a -> a`
Trace the supplied value and return it.
**Example: lib.debug.traceVal usage example**
```
traceVal 42
# trace: 42
=> 42
```
Located at [lib/debug.nix:84](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L84) in `<nixpkgs>`.
`lib.debug.traceSeq`
--------------------
#####
`traceSeq :: a -> b -> b`
`builtins.trace`, but the value is `builtins.deepSeq`ed first.
`x`
The value to trace
`y`
The value to return
**Example: lib.debug.traceSeq usage example**
```
trace { a.b.c = 3; } null
trace: { a = <CODE>; }
=> null
traceSeq { a.b.c = 3; } null
trace: { a = { b = { c = 3; }; }; }
=> null
```
Located at [lib/debug.nix:98](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L98) in `<nixpkgs>`.
`lib.debug.traceSeqN`
---------------------
Like `traceSeq`, but only evaluate down to depth n. This is very useful because lots of `traceSeq` usages lead to an infinite recursion.
`depth`
Function argument
`x`
Function argument
`y`
Function argument
**Example: lib.debug.traceSeqN usage example**
```
traceSeqN 2 { a.b.c = 3; } null
trace: { a = { b = {…}; }; }
=> null
```
Located at [lib/debug.nix:113](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L113) in `<nixpkgs>`.
`lib.debug.traceValSeqFn`
-------------------------
A combination of `traceVal` and `traceSeq` that applies a provided function to the value to be traced after `deepSeq`ing it.
`f`
Function to apply
`v`
Value to trace
Located at [lib/debug.nix:130](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L130) in `<nixpkgs>`.
`lib.debug.traceValSeq`
-----------------------
A combination of `traceVal` and `traceSeq`.
Located at [lib/debug.nix:137](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L137) in `<nixpkgs>`.
`lib.debug.traceValSeqNFn`
--------------------------
A combination of `traceVal` and `traceSeqN` that applies a provided function to the value to be traced.
`f`
Function to apply
`depth`
Function argument
`v`
Value to trace
Located at [lib/debug.nix:141](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L141) in `<nixpkgs>`.
`lib.debug.traceValSeqN`
------------------------
A combination of `traceVal` and `traceSeqN`.
Located at [lib/debug.nix:149](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L149) in `<nixpkgs>`.
`lib.debug.traceFnSeqN`
-----------------------
Trace the input and output of a function `f` named `name`, both down to `depth`.
This is useful for adding around a function call, to see the before/after of values as they are transformed.
`depth`
Function argument
`name`
Function argument
`f`
Function argument
`v`
Function argument
**Example: lib.debug.traceFnSeqN usage example**
```
traceFnSeqN 2 "id" (x: x) { a.b.c = 3; }
trace: { fn = "id"; from = { a.b = {…}; }; to = { a.b = {…}; }; }
=> { a.b.c = 3; }
```
Located at [lib/debug.nix:162](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L162) in `<nixpkgs>`.
`lib.debug.runTests`
--------------------
Evaluate a set of tests. A test is an attribute set `{expr, expected}`, denoting an expression and its expected result. The result is a list of failed tests, each represented as `{name, expected, actual}`, denoting the attribute name of the failing test and its expected and actual results.
Used for regression testing of the functions in lib; see tests.nix for an example. Only tests having names starting with "test" are run.
Add attr { tests = ["testName"]; } to run these tests only.
`tests`
Tests to run
Located at [lib/debug.nix:188](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L188) in `<nixpkgs>`.
`lib.debug.testAllTrue`
-----------------------
Create a test assuming that list elements are `true`.
`expr`
Function argument
**Example: lib.debug.testAllTrue usage example**
```
{ testX = allTrue [ true ]; }
```
Located at [lib/debug.nix:204](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L204) in `<nixpkgs>`.
`lib.options.isOption`
----------------------
#####
`isOption :: a -> bool`
Returns true when the given argument is an option
**Example: lib.options.isOption usage example**
```
isOption 1 // => false
isOption (mkOption {}) // => true
```
Located at [lib/options.nix:50](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L50) in `<nixpkgs>`.
`lib.options.mkOption`
----------------------
Creates an Option attribute set. mkOption accepts an attribute set with the following keys:
All keys default to `null` when not given.
`pattern`
Structured function argument
`default`
Default value used when no definition is given in the configuration.
`defaultText`
Textual representation of the default, for the manual.
`example`
Example value used in the manual.
`description`
String describing the option.
`relatedPackages`
Related packages used in the manual (see `genRelatedPackages` in ../nixos/lib/make-options-doc/default.nix).
`type`
Option type, providing type-checking and value merging.
`apply`
Function that converts the option value to something else.
`internal`
Whether the option is for NixOS developers only.
`visible`
Whether the option shows up in the manual. Default: true. Use false to hide the option and any sub-options from submodules. Use "shallow" to hide only sub-options.
`readOnly`
Whether the option can be set only once
**Example: lib.options.mkOption usage example**
```
mkOption { } // => { _type = "option"; }
mkOption { default = "foo"; } // => { _type = "option"; default = "foo"; }
```
Located at [lib/options.nix:60](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L60) in `<nixpkgs>`.
`lib.options.mkEnableOption`
----------------------------
Creates an Option attribute set for a boolean value option i.e an option to be toggled on or off:
`name`
Name for the created option
**Example: lib.options.mkEnableOption usage example**
```
mkEnableOption "foo"
=> { _type = "option"; default = false; description = "Whether to enable foo."; example = true; type = { ... }; }
```
Located at [lib/options.nix:92](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L92) in `<nixpkgs>`.
`lib.options.mkPackageOption`
-----------------------------
#####
`mkPackageOption :: pkgs -> string -> { default :: [string], example :: null | string | [string] } -> optionThe package is specified as a list of strings representing its attribute path in nixpkgs.Because of this, you need to pass nixpkgs itself as the first argument.The second argument is the name of the option, used in the description "The <name> package to use.".You can also pass an example value, either a literal string or a package's attribute path.You can omit the default path if the name of the option is also attribute path in nixpkgs.`
Creates an Option attribute set for an option that specifies the package a module should use for some purpose.
`pkgs`
Package set (a specific version of nixpkgs)
`name`
Name for the package, shown in option description
`pattern`
Structured function argument
`default`
Function argument
`example`
Function argument
**Example: lib.options.mkPackageOption usage example**
```
mkPackageOption pkgs "hello" { }
=> { _type = "option"; default = «derivation /nix/store/3r2vg51hlxj3cx5vscp0vkv60bqxkaq0-hello-2.10.drv»; defaultText = { ... }; description = "The hello package to use."; type = { ... }; }
mkPackageOption pkgs "GHC" {
default = [ "ghc" ];
example = "pkgs.haskell.package.ghc922.ghc.withPackages (hkgs: [ hkgs.primes ])";
}
=> { _type = "option"; default = «derivation /nix/store/jxx55cxsjrf8kyh3fp2ya17q99w7541r-ghc-8.10.7.drv»; defaultText = { ... }; description = "The GHC package to use."; example = { ... }; type = { ... }; }
```
Located at [lib/options.nix:127](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L127) in `<nixpkgs>`.
`lib.options.mkSinkUndeclaredOptions`
-------------------------------------
This option accepts anything, but it does not produce any result.
This is useful for sharing a module across different module sets without having to implement similar features as long as the values of the options are not accessed.
`attrs`
Function argument
Located at [lib/options.nix:149](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L149) in `<nixpkgs>`.
`lib.options.mergeEqualOption`
------------------------------
"Merge" option definitions by checking that they all have the same value.
`loc`
Function argument
`defs`
Function argument
Located at [lib/options.nix:182](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L182) in `<nixpkgs>`.
`lib.options.getValues`
-----------------------
#####
`getValues :: [ { value :: a } ] -> [a]`
Extracts values of all "value" keys of the given list.
**Example: lib.options.getValues usage example**
```
getValues [ { value = 1; } { value = 2; } ] // => [ 1 2 ]
getValues [ ] // => [ ]
```
Located at [lib/options.nix:202](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L202) in `<nixpkgs>`.
`lib.options.getFiles`
----------------------
#####
`getFiles :: [ { file :: a } ] -> [a]`
Extracts values of all "file" keys of the given list
**Example: lib.options.getFiles usage example**
```
getFiles [ { file = "file1"; } { file = "file2"; } ] // => [ "file1" "file2" ]
getFiles [ ] // => [ ]
```
Located at [lib/options.nix:212](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L212) in `<nixpkgs>`.
`lib.options.scrubOptionValue`
------------------------------
This function recursively removes all derivation attributes from `x` except for the `name` attribute.
This is to make the generation of `options.xml` much more efficient: the XML representation of derivations is very large (on the order of megabytes) and is not actually used by the manual generator.
`x`
Function argument
Located at [lib/options.nix:255](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L255) in `<nixpkgs>`.
`lib.options.literalExpression`
-------------------------------
For use in the `defaultText` and `example` option attributes. Causes the given string to be rendered verbatim in the documentation as Nix code. This is necessary for complex values, e.g. functions, or values that depend on other values or packages.
`text`
Function argument
Located at [lib/options.nix:268](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L268) in `<nixpkgs>`.
`lib.options.literalDocBook`
----------------------------
For use in the `defaultText` and `example` option attributes. Causes the given DocBook text to be inserted verbatim in the documentation, for when a `literalExpression` would be too hard to read.
`text`
Function argument
Located at [lib/options.nix:279](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L279) in `<nixpkgs>`.
`lib.options.showOption`
------------------------
Convert an option, described as a list of the option parts in to a safe, human readable version.
`parts`
Function argument
**Example: lib.options.showOption usage example**
```
(showOption ["foo" "bar" "baz"]) == "foo.bar.baz"
(showOption ["foo" "bar.baz" "tux"]) == "foo.bar.baz.tux"
Placeholders will not be quoted as they are not actual values:
(showOption ["foo" "*" "bar"]) == "foo.*.bar"
(showOption ["foo" "<name>" "bar"]) == "foo.<name>.bar"
Unlike attributes, options can also start with numbers:
(showOption ["windowManager" "2bwm" "enable"]) == "windowManager.2bwm.enable"
```
Located at [lib/options.nix:299](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L299) in `<nixpkgs>`.
`lib.sources.pathType`
----------------------
Returns the type of a path: regular (for file), symlink, or directory.
`path`
Function argument
Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`.
`lib.sources.pathIsDirectory`
-----------------------------
Returns true if the path exists and is a directory, false otherwise.
`path`
Function argument
Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`.
`lib.sources.pathIsRegularFile`
-------------------------------
Returns true if the path exists and is a regular file, false otherwise.
`path`
Function argument
Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`.
`lib.sources.cleanSourceFilter`
-------------------------------
A basic filter for `cleanSourceWith` that removes directories of version control system, backup files (\*~) and some generated files.
`name`
Function argument
`type`
Function argument
Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`.
`lib.sources.cleanSource`
-------------------------
Filters a source tree removing version control files and directories using cleanSourceFilter.
`src`
Function argument
**Example: lib.sources.cleanSource usage example**
```
cleanSource ./.
```
Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`.
`lib.sources.cleanSourceWith`
-----------------------------
Like `builtins.filterSource`, except it will compose with itself, allowing you to chain multiple calls together without any intermediate copies being put in the nix store.
`pattern`
Structured function argument
`src`
A path or cleanSourceWith result to filter and/or rename.
`filter`
Optional with default value: constant true (include everything)
`name`
Optional name to use as part of the store path.
**Example: lib.sources.cleanSourceWith usage example**
```
lib.cleanSourceWith {
filter = f;
src = lib.cleanSourceWith {
filter = g;
src = ./.;
};
}
# Succeeds!
builtins.filterSource f (builtins.filterSource g ./.)
# Fails!
```
Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`.
`lib.sources.trace`
-------------------
#####
`sources.trace :: sourceLike -> Source`
Add logging to a source, for troubleshooting the filtering behavior.
`src`
Source to debug. The returned source will behave like this source, but also log its filter invocations.
Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`.
`lib.sources.sourceByRegex`
---------------------------
Filter sources by a list of regular expressions.
`src`
Function argument
`regexes`
Function argument
**Example: lib.sources.sourceByRegex usage example**
```
src = sourceByRegex ./my-subproject [".*\.py$" "^database.sql$"]
```
Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`.
`lib.sources.sourceFilesBySuffices`
-----------------------------------
#####
`sourceLike -> [String] -> Source`
Get all files ending with the specified suffices from the given source directory or its descendants, omitting files that do not match any suffix. The result of the example below will include files like `./dir/module.c` and `./dir/subdir/doc.xml` if present.
`src`
Path or source containing the files to be returned
`exts`
A list of file suffix strings
**Example: lib.sources.sourceFilesBySuffices usage example**
```
sourceFilesBySuffices ./. [ ".xml" ".c" ]
```
Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`.
`lib.sources.commitIdFromGitRepo`
---------------------------------
Get the commit id of a git repo.
**Example: lib.sources.commitIdFromGitRepo usage example**
```
commitIdFromGitRepo <nixpkgs/.git>
```
Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`.
`pkgs.fetchurl` and `pkgs.fetchzip`
------------------------------------
Two basic fetchers are `fetchurl` and `fetchzip`. Both of these have two required arguments, a URL and a hash. The hash is typically `sha256`, although many more hash algorithms are supported. Nixpkgs contributors are currently recommended to use `sha256`. This hash will be used by Nix to identify your source. A typical usage of `fetchurl` is provided below.
```
{ stdenv, fetchurl }:
stdenv.mkDerivation {
name = "hello";
src = fetchurl {
url = "http://www.example.org/hello.tar.gz";
sha256 = "1111111111111111111111111111111111111111111111111111";
};
}
```
The main difference between `fetchurl` and `fetchzip` is in how they store the contents. `fetchurl` will store the unaltered contents of the URL within the Nix store. `fetchzip` on the other hand, will decompress the archive for you, making files and directories directly accessible in the future. `fetchzip` can only be used with archives. Despite the name, `fetchzip` is not limited to .zip files and can also be used with any tarball.
`fetchpatch` works very similarly to `fetchurl` with the same arguments expected. It expects patch files as a source and performs normalization on them before computing the checksum. For example, it will remove comments or other unstable parts that are sometimes added by version control systems and can change over time.
Most other fetchers return a directory rather than a single file.
`pkgs.fetchsvn`
---------------
Used with Subversion. Expects `url` to a Subversion directory, `rev`, and `sha256`.
`pkgs.fetchgit`
---------------
Used with Git. Expects `url` to a Git repo, `rev`, and `sha256`. `rev` in this case can be full the git commit id (SHA1 hash) or a tag name like `refs/tags/v1.0`.
Additionally, the following optional arguments can be given: `fetchSubmodules = true` makes `fetchgit` also fetch the submodules of a repository. If `deepClone` is set to true, the entire repository is cloned as opposing to just creating a shallow clone. `deepClone = true` also implies `leaveDotGit = true` which means that the `.git` directory of the clone won’t be removed after checkout.
If only parts of the repository are needed, `sparseCheckout` can be used. This will prevent git from fetching unnecessary blobs from server, see [git sparse-checkout](https://git-scm.com/docs/git-sparse-checkout) and [git clone –filter](https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---filterltfilter-specgt) for more information:
```
{ stdenv, fetchgit }:
stdenv.mkDerivation {
name = "hello";
src = fetchgit {
url = "https://...";
sparseCheckout = ''
path/to/be/included
another/path
'';
sha256 = "0000000000000000000000000000000000000000000000000000";
};
}
```
`pkgs.fetchfossil`
------------------
Used with Fossil. Expects `url` to a Fossil archive, `rev`, and `sha256`.
`pkgs.fetchcvs`
---------------
Used with CVS. Expects `cvsRoot`, `tag`, and `sha256`.
`pkgs.fetchhg`
--------------
Used with Mercurial. Expects `url`, `rev`, and `sha256`.
A number of fetcher functions wrap part of `fetchurl` and `fetchzip`. They are mainly convenience functions intended for commonly used destinations of source code in Nixpkgs. These wrapper fetchers are listed below.
`pkgs.fetchFromGitea`
---------------------
`fetchFromGitea` expects five arguments. `domain` is the gitea server name. `owner` is a string corresponding to the Gitea user or organization that controls this repository. `repo` corresponds to the name of the software repository. These are located at the top of every Gitea HTML page as `owner`/`repo`. `rev` corresponds to the Git commit hash or tag (e.g `v1.0`) that will be downloaded from Git. Finally, `sha256` corresponds to the hash of the extracted directory. Again, other hash algorithms are also available but `sha256` is currently preferred.
`pkgs.fetchFromGitHub`
----------------------
`fetchFromGitHub` expects four arguments. `owner` is a string corresponding to the GitHub user or organization that controls this repository. `repo` corresponds to the name of the software repository. These are located at the top of every GitHub HTML page as `owner`/`repo`. `rev` corresponds to the Git commit hash or tag (e.g `v1.0`) that will be downloaded from Git. Finally, `sha256` corresponds to the hash of the extracted directory. Again, other hash algorithms are also available, but `sha256` is currently preferred.
`fetchFromGitHub` uses `fetchzip` to download the source archive generated by GitHub for the specified revision. If `leaveDotGit`, `deepClone` or `fetchSubmodules` are set to `true`, `fetchFromGitHub` will use `fetchgit` instead. Refer to its section for documentation of these options.
`pkgs.fetchFromGitLab`
----------------------
This is used with GitLab repositories. The arguments expected are very similar to `fetchFromGitHub` above.
`pkgs.fetchFromGitiles`
-----------------------
This is used with Gitiles repositories. The arguments expected are similar to `fetchgit`.
`pkgs.fetchFromBitbucket`
-------------------------
This is used with BitBucket repositories. The arguments expected are very similar to fetchFromGitHub above.
`pkgs.fetchFromSavannah`
------------------------
This is used with Savannah repositories. The arguments expected are very similar to `fetchFromGitHub` above.
`pkgs.fetchFromRepoOrCz`
------------------------
This is used with repo.or.cz repositories. The arguments expected are very similar to `fetchFromGitHub` above.
`pkgs.fetchFromSourcehut`
-------------------------
This is used with sourcehut repositories. Similar to `fetchFromGitHub` above, it expects `owner`, `repo`, `rev` and `sha256`, but don’t forget the tilde (~) in front of the username! Expected arguments also include `vc` (“git” (default) or “hg”), `domain` and `fetchSubmodules`.
If `fetchSubmodules` is `true`, `fetchFromSourcehut` uses `fetchgit` or `fetchhg` with `fetchSubmodules` or `fetchSubrepos` set to `true`, respectively. Otherwise, the fetcher uses `fetchzip`.
`pkgs.runCommand`
-----------------
This takes three arguments, `name`, `env`, and `buildCommand`. `name` is just the name that Nix will append to the store path in the same way that `stdenv.mkDerivation` uses its `name` attribute. `env` is an attribute set specifying environment variables that will be set for this derivation. These attributes are then passed to the wrapped `stdenv.mkDerivation`. `buildCommand` specifies the commands that will be run to create this derivation. Note that you will need to create `$out` for Nix to register the command as successful.
An example of using `runCommand` is provided below.
```
(import <nixpkgs> {}).runCommand "my-example" {} ''
echo My example command is running
mkdir $out
echo I can write data to the Nix store > $out/message
echo I can also run basic commands like:
echo ls
ls
echo whoami
whoami
echo date
date
''
```
`pkgs.runCommandCC`
-------------------
This works just like `runCommand`. The only difference is that it also provides a C compiler in `buildCommand`’s environment. To minimize your dependencies, you should only use this if you are sure you will need a C compiler as part of running your command.
`pkgs.runCommandLocal`
----------------------
Variant of `runCommand` that forces the derivation to be built locally, it is not substituted. This is intended for very cheap commands (<1s execution time). It saves on the network round-trip and can speed up a build.
`pkgs.writeTextFile`, `pkgs.writeText`, `pkgs.writeTextDir`, `pkgs.writeScript`, `pkgs.writeScriptBin`
-------------------------------------------------------------------------------------------------------
These functions write `text` to the Nix store. This is useful for creating scripts from Nix expressions. `writeTextFile` takes an attribute set and expects two arguments, `name` and `text`. `name` corresponds to the name used in the Nix store path. `text` will be the contents of the file. You can also set `executable` to true to make this file have the executable bit set.
Many more commands wrap `writeTextFile` including `writeText`, `writeTextDir`, `writeScript`, and `writeScriptBin`. These are convenience functions over `writeTextFile`.
Here are a few examples:
```
# Writes my-file to /nix/store/<store path>
writeTextFile {
name = "my-file";
text = ''
Contents of File
'';
}
# See also the `writeText` helper function below.
# Writes executable my-file to /nix/store/<store path>/bin/my-file
writeTextFile {
name = "my-file";
text = ''
Contents of File
'';
executable = true;
destination = "/bin/my-file";
}
# Writes contents of file to /nix/store/<store path>
writeText "my-file"
''
Contents of File
'';
# Writes contents of file to /nix/store/<store path>/share/my-file
writeTextDir "share/my-file"
''
Contents of File
'';
# Writes my-file to /nix/store/<store path> and makes executable
writeScript "my-file"
''
Contents of File
'';
# Writes my-file to /nix/store/<store path>/bin/my-file and makes executable.
writeScriptBin "my-file"
''
Contents of File
'';
# Writes my-file to /nix/store/<store path> and makes executable.
writeShellScript "my-file"
''
Contents of File
'';
# Writes my-file to /nix/store/<store path>/bin/my-file and makes executable.
writeShellScriptBin "my-file"
''
Contents of File
'';
```
`pkgs.concatTextFile`, `pkgs.concatText`, `pkgs.concatScript`
--------------------------------------------------------------
These functions concatenate `files` to the Nix store in a single file. This is useful for configuration files structured in lines of text. `concatTextFile` takes an attribute set and expects two arguments, `name` and `files`. `name` corresponds to the name used in the Nix store path. `files` will be the files to be concatenated. You can also set `executable` to true to make this file have the executable bit set. `concatText` and`concatScript` are simple wrappers over `concatTextFile`.
Here are a few examples:
```
# Writes my-file to /nix/store/<store path>
concatTextFile {
name = "my-file";
files = [ drv1 "${drv2}/path/to/file" ];
}
# See also the `concatText` helper function below.
# Writes executable my-file to /nix/store/<store path>/bin/my-file
concatTextFile {
name = "my-file";
files = [ drv1 "${drv2}/path/to/file" ];
executable = true;
destination = "/bin/my-file";
}
# Writes contents of files to /nix/store/<store path>
concatText "my-file" [ file1 file2 ]
# Writes contents of files to /nix/store/<store path>
concatScript "my-file" [ file1 file2 ]
```
`pkgs.writeShellApplication`
----------------------------
This can be used to easily produce a shell script that has some dependencies (`runtimeInputs`). It automatically sets the `PATH` of the script to contain all of the listed inputs, sets some sanity shellopts (`errexit`, `nounset`, `pipefail`), and checks the resulting script with [`shellcheck`](https://github.com/koalaman/shellcheck).
For example, look at the following code:
```
writeShellApplication {
name = "show-nixos-org";
runtimeInputs = [ curl w3m ];
text = ''
curl -s 'https://nixos.org' | w3m -dump -T text/html
'';
}
```
Unlike with normal `writeShellScriptBin`, there is no need to manually write out `${curl}/bin/curl`, setting the PATH was handled by `writeShellApplication`. Moreover, the script is being checked with `shellcheck` for more strict validation.
`pkgs.symlinkJoin`
------------------
This can be used to put many derivations into the same directory structure. It works by creating a new derivation and adding symlinks to each of the paths listed. It expects two arguments, `name`, and `paths`. `name` is the name used in the Nix store path for the created derivation. `paths` is a list of paths that will be symlinked. These paths can be to Nix store derivations or any other subdirectory contained within. Here is an example:
```
# adds symlinks of hello and stack to current build and prints "links added"
symlinkJoin { name = "myexample"; paths = [ pkgs.hello pkgs.stack ]; postBuild = "echo links added"; }
```
This creates a derivation with a directory structure like the following:
```
/nix/store/sglsr5g079a5235hy29da3mq3hv8sjmm-myexample
|-- bin
| |-- hello -> /nix/store/qy93dp4a3rqyn2mz63fbxjg228hffwyw-hello-2.10/bin/hello
| `-- stack -> /nix/store/6lzdpxshx78281vy056lbk553ijsdr44-stack-2.1.3.1/bin/stack
`-- share
|-- bash-completion
| `-- completions
| `-- stack -> /nix/store/6lzdpxshx78281vy056lbk553ijsdr44-stack-2.1.3.1/share/bash-completion/completions/stack
|-- fish
| `-- vendor_completions.d
| `-- stack.fish -> /nix/store/6lzdpxshx78281vy056lbk553ijsdr44-stack-2.1.3.1/share/fish/vendor_completions.d/stack.fish
...
```
`pkgs.writeReferencesToFile`
----------------------------
Writes the closure of transitive dependencies to a file.
This produces the equivalent of `nix-store -q --requisites`.
For example,
```
writeReferencesToFile (writeScriptBin "hi" ''${hello}/bin/hello'')
```
produces an output path `/nix/store/<hash>-runtime-deps` containing
```
/nix/store/<hash>-hello-2.10
/nix/store/<hash>-hi
/nix/store/<hash>-libidn2-2.3.0
/nix/store/<hash>-libunistring-0.9.10
/nix/store/<hash>-glibc-2.32-40
```
You can see that this includes `hi`, the original input path, `hello`, which is a direct reference, but also the other paths that are indirectly required to run `hello`.
`pkgs.writeDirectReferencesToFile`
----------------------------------
Writes the set of references to the output file, that is, their immediate dependencies.
This produces the equivalent of `nix-store -q --references`.
For example,
```
writeDirectReferencesToFile (writeScriptBin "hi" ''${hello}/bin/hello'')
```
produces an output path `/nix/store/<hash>-runtime-references` containing
```
/nix/store/<hash>-hello-2.10
```
but none of `hello`’s dependencies because those are not referenced directly by `hi`’s output.
`pkgs.buildFHSUserEnv`
----------------------
`buildFHSUserEnv` provides a way to build and run FHS-compatible lightweight sandboxes. It creates an isolated root with bound `/nix/store`, so its footprint in terms of disk space needed is quite small. This allows one to run software which is hard or unfeasible to patch for NixOS – 3rd-party source trees with FHS assumptions, games distributed as tarballs, software with integrity checking and/or external self-updated binaries. It uses Linux namespaces feature to create temporary lightweight environments which are destroyed after all child processes exit, without root user rights requirement. Accepted arguments are:
* `name` Environment name.
* `targetPkgs` Packages to be installed for the main host’s architecture (i.e. x86\_64 on x86\_64 installations). Along with libraries binaries are also installed.
* `multiPkgs` Packages to be installed for all architectures supported by a host (i.e. i686 and x86\_64 on x86\_64 installations). Only libraries are installed by default.
* `extraBuildCommands` Additional commands to be executed for finalizing the directory structure.
* `extraBuildCommandsMulti` Like `extraBuildCommands`, but executed only on multilib architectures.
* `extraOutputsToInstall` Additional derivation outputs to be linked for both target and multi-architecture packages.
* `extraInstallCommands` Additional commands to be executed for finalizing the derivation with runner script.
* `runScript` A command that would be executed inside the sandbox and passed all the command line arguments. It defaults to `bash`.
* `profile` Optional script for `/etc/profile` within the sandbox.
One can create a simple environment using a `shell.nix` like that:
```
{ pkgs ? import <nixpkgs> {} }:
(pkgs.buildFHSUserEnv {
name = "simple-x11-env";
targetPkgs = pkgs: (with pkgs;
[ udev
alsa-lib
]) ++ (with pkgs.xorg;
[ libX11
libXcursor
libXrandr
]);
multiPkgs = pkgs: (with pkgs;
[ udev
alsa-lib
]);
runScript = "bash";
}).env
```
Running `nix-shell` would then drop you into a shell with these libraries and binaries available. You can use this to run closed-source applications which expect FHS structure without hassles: simply change `runScript` to the application path, e.g. `./bin/start.sh` – relative paths are supported.
Additionally, the FHS builder links all relocated gsettings-schemas (the glib setup-hook moves them to `share/gsettings-schemas/${name}/glib-2.0/schemas`) to their standard FHS location. This means you don’t need to wrap binaries with `wrapGAppsHook`.
`pkgs.mkShell`
--------------
`pkgs.mkShell` is a specialized `stdenv.mkDerivation` that removes some repetition when using it with `nix-shell` (or `nix develop`).
### Usage
Here is a common usage example:
```
{ pkgs ? import <nixpkgs> {} }:
pkgs.mkShell {
packages = [ pkgs.gnumake ];
inputsFrom = [ pkgs.hello pkgs.gnutar ];
shellHook = ''
export DEBUG=1
'';
}
```
### Attributes
* `name` (default: `nix-shell`). Set the name of the derivation.
* `packages` (default: `[]`). Add executable packages to the `nix-shell` environment.
* `inputsFrom` (default: `[]`). Add build dependencies of the listed derivations to the `nix-shell` environment.
* `shellHook` (default: `""`). Bash statements that are executed by `nix-shell`.
… all the attributes of `stdenv.mkDerivation`.
### Building the shell
This derivation output will contain a text file that contains a reference to all the build inputs. This is useful in CI where we want to make sure that every derivation, and its dependencies, build properly. Or when creating a GC root so that the build dependencies don’t get garbage-collected.
`pkgs.appimageTools`
--------------------
`pkgs.appimageTools` is a set of functions for extracting and wrapping [AppImage](https://appimage.org/) files. They are meant to be used if traditional packaging from source is infeasible, or it would take too long. To quickly run an AppImage file, `pkgs.appimage-run` can be used as well.
### `AppImage formats`
There are different formats for AppImages, see [the specification](https://github.com/AppImage/AppImageSpec/blob/74ad9ca2f94bf864a4a0dac1f369dd4f00bd1c28/draft.md#image-format) for details.
* Type 1 images are ISO 9660 files that are also ELF executables.
* Type 2 images are ELF executables with an appended filesystem.
They can be told apart with `file -k`:
```
$ file -k type1.AppImage
type1.AppImage: ELF 64-bit LSB executable, x86-64, version 1 (SYSV) ISO 9660 CD-ROM filesystem data 'AppImage' (Lepton 3.x), scale 0-0,
spot sensor temperature 0.000000, unit celsius, color scheme 0, calibration: offset 0.000000, slope 0.000000, dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.18, BuildID[sha1]=d629f6099d2344ad82818172add1d38c5e11bc6d, stripped\012- data
$ file -k type2.AppImage
type2.AppImage: ELF 64-bit LSB executable, x86-64, version 1 (SYSV) (Lepton 3.x), scale 232-60668, spot sensor temperature -4.187500, color scheme 15, show scale bar, calibration: offset -0.000000, slope 0.000000 (Lepton 2.x), scale 4111-45000, spot sensor temperature 412442.250000, color scheme 3, minimum point enabled, calibration: offset -75402534979642766821519867692934234112.000000, slope 5815371847733706829839455140374904832.000000, dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.18, BuildID[sha1]=79dcc4e55a61c293c5e19edbd8d65b202842579f, stripped\012- data
```
Note how the type 1 AppImage is described as an `ISO 9660 CD-ROM filesystem`, and the type 2 AppImage is not.
### `Wrapping`
Depending on the type of AppImage you’re wrapping, you’ll have to use `wrapType1` or `wrapType2`.
```
appimageTools.wrapType2 { # or wrapType1
name = "patchwork";
src = fetchurl {
url = "https://github.com/ssbc/patchwork/releases/download/v3.11.4/Patchwork-3.11.4-linux-x86_64.AppImage";
sha256 = "1blsprpkvm0ws9b96gb36f0rbf8f5jgmw4x6dsb1kswr4ysf591s";
};
extraPkgs = pkgs: with pkgs; [ ];
}
```
* `name` specifies the name of the resulting image.
* `src` specifies the AppImage file to extract.
* `extraPkgs` allows you to pass a function to include additional packages inside the FHS environment your AppImage is going to run in. There are a few ways to learn which dependencies an application needs:
+ Looking through the extracted AppImage files, reading its scripts and running `patchelf` and `ldd` on its executables. This can also be done in `appimage-run`, by setting `APPIMAGE_DEBUG_EXEC=bash`.
+ Running `strace -vfefile` on the wrapped executable, looking for libraries that can’t be found.
`pkgs.dockerTools`
------------------
`pkgs.dockerTools` is a set of functions for creating and manipulating Docker images according to the [Docker Image Specification v1.2.0](https://github.com/moby/moby/blob/master/image/spec/v1.2.md#docker-image-specification-v120). Docker itself is not used to perform any of the operations done by these functions.
### `pkgs.dockerTools.buildImage`
This function is analogous to the `docker build` command, in that it can be used to build a Docker-compatible repository tarball containing a single image with one or multiple layers. As such, the result is suitable for being loaded in Docker with `docker load`.
The parameters of `buildImage` with relative example values are described below:
```
buildImage {
name = "redis";
tag = "latest";
fromImage = someBaseImage;
fromImageName = null;
fromImageTag = "latest";
contents = pkgs.redis;
runAsRoot = ''
#!${pkgs.runtimeShell}
mkdir -p /data
'';
config = {
Cmd = [ "/bin/redis-server" ];
WorkingDir = "/data";
Volumes = { "/data" = { }; };
};
}
```
The above example will build a Docker image `redis/latest` from the given base image. Loading and running this image in Docker results in `redis-server` being started automatically.
* `name` specifies the name of the resulting image. This is the only required argument for `buildImage`.
* `tag` specifies the tag of the resulting image. By default it’s `null`, which indicates that the nix output hash will be used as tag.
* `fromImage` is the repository tarball containing the base image. It must be a valid Docker image, such as exported by `docker save`. By default it’s `null`, which can be seen as equivalent to `FROM scratch` of a `Dockerfile`.
* `fromImageName` can be used to further specify the base image within the repository, in case it contains multiple images. By default it’s `null`, in which case `buildImage` will peek the first image available in the repository.
* `fromImageTag` can be used to further specify the tag of the base image within the repository, in case an image contains multiple tags. By default it’s `null`, in which case `buildImage` will peek the first tag available for the base image.
* `contents` is a derivation that will be copied in the new layer of the resulting image. This can be similarly seen as `ADD contents/ /` in a `Dockerfile`. By default it’s `null`.
* `runAsRoot` is a bash script that will run as root in an environment that overlays the existing layers of the base image with the new resulting layer, including the previously copied `contents` derivation. This can be similarly seen as `RUN ...` in a `Dockerfile`.
> ***NOTE:*** Using this parameter requires the `kvm` device to be available.
>
>
* `config` is used to specify the configuration of the containers that will be started off the built image in Docker. The available options are listed in the [Docker Image Specification v1.2.0](https://github.com/moby/moby/blob/master/image/spec/v1.2.md#image-json-field-descriptions).
After the new layer has been created, its closure (to which `contents`, `config` and `runAsRoot` contribute) will be copied in the layer itself. Only new dependencies that are not already in the existing layers will be copied.
At the end of the process, only one new single layer will be produced and added to the resulting image.
The resulting repository will only list the single image `image/tag`. In the case of [the `buildImage` example](#ex-dockerTools-buildImage), it would be `redis/latest`.
It is possible to inspect the arguments with which an image was built using its `buildArgs` attribute.
> ***NOTE:*** If you see errors similar to `getProtocolByName: does not exist (no such protocol name: tcp)` you may need to add `pkgs.iana-etc` to `contents`.
>
>
> ***NOTE:*** If you see errors similar to `Error_Protocol ("certificate has unknown CA",True,UnknownCa)` you may need to add `pkgs.cacert` to `contents`.
>
>
By default `buildImage` will use a static date of one second past the UNIX Epoch. This allows `buildImage` to produce binary reproducible images. When listing images with `docker images`, the newly created images will be listed like this:
```
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello latest 08c791c7846e 48 years ago 25.2MB
```
You can break binary reproducibility but have a sorted, meaningful `CREATED` column by setting `created` to `now`.
```
pkgs.dockerTools.buildImage {
name = "hello";
tag = "latest";
created = "now";
contents = pkgs.hello;
config.Cmd = [ "/bin/hello" ];
}
```
Now the Docker CLI will display a reasonable date and sort the images as expected:
```
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello latest de2bf4786de6 About a minute ago 25.2MB
```
However, the produced images will not be binary reproducible.
### `pkgs.dockerTools.buildLayeredImage`
Create a Docker image with many of the store paths being on their own layer to improve sharing between images. The image is realized into the Nix store as a gzipped tarball. Depending on the intended usage, many users might prefer to use `streamLayeredImage` instead, which this function uses internally.
`name`
The name of the resulting image.
`tag` *optional*
Tag of the generated image.
*Default:* the output path’s hash
`fromImage` *optional*
The repository tarball containing the base image. It must be a valid Docker image, such as one exported by `docker save`.
*Default:* `null`, which can be seen as equivalent to `FROM scratch` of a `Dockerfile`.
`contents` *optional*
Top-level paths in the container. Either a single derivation, or a list of derivations.
*Default:* `[]`
`config` *optional*
Run-time configuration of the container. A full list of the options are available at in the [Docker Image Specification v1.2.0](https://github.com/moby/moby/blob/master/image/spec/v1.2.md#image-json-field-descriptions).
*Default:* `{}`
`created` *optional*
Date and time the layers were created. Follows the same `now` exception supported by `buildImage`.
*Default:* `1970-01-01T00:00:01Z`
`maxLayers` *optional*
Maximum number of layers to create.
*Default:* `100`
*Maximum:* `125`
`extraCommands` *optional*
Shell commands to run while building the final layer, without access to most of the layer contents. Changes to this layer are “on top” of all the other layers, so can create additional directories and files.
`fakeRootCommands` *optional*
Shell commands to run while creating the archive for the final layer in a fakeroot environment. Unlike `extraCommands`, you can run `chown` to change the owners of the files in the archive, changing fakeroot’s state instead of the real filesystem. The latter would require privileges that the build user does not have. Static binaries do not interact with the fakeroot environment. By default all files in the archive will be owned by root.
`enableFakechroot` *optional*
Whether to run in `fakeRootCommands` in `fakechroot`, making programs behave as though `/` is the root of the image being created, while files in the Nix store are available as usual. This allows scripts that perform installation in `/` to work as expected. Considering that `fakechroot` is implemented via the same mechanism as `fakeroot`, the same caveats apply.
*Default:* `false`
####
`Behavior of` `contents` in the final image
Each path directly listed in `contents` will have a symlink in the root of the image.
For example:
```
pkgs.dockerTools.buildLayeredImage {
name = "hello";
contents = [ pkgs.hello ];
}
```
will create symlinks for all the paths in the `hello` package:
```
/bin/hello -> /nix/store/h1zb1padqbbb7jicsvkmrym3r6snphxg-hello-2.10/bin/hello
/share/info/hello.info -> /nix/store/h1zb1padqbbb7jicsvkmrym3r6snphxg-hello-2.10/share/info/hello.info
/share/locale/bg/LC_MESSAGES/hello.mo -> /nix/store/h1zb1padqbbb7jicsvkmrym3r6snphxg-hello-2.10/share/locale/bg/LC_MESSAGES/hello.mo
```
####
`Automatic inclusion of` `config` references
The closure of `config` is automatically included in the closure of the final image.
This allows you to make very simple Docker images with very little code. This container will start up and run `hello`:
```
pkgs.dockerTools.buildLayeredImage {
name = "hello";
config.Cmd = [ "${pkgs.hello}/bin/hello" ];
}
```
####
`Adjusting` `maxLayers`
Increasing the `maxLayers` increases the number of layers which have a chance to be shared between different images.
Modern Docker installations support up to 128 layers, but older versions support as few as 42.
If the produced image will not be extended by other Docker builds, it is safe to set `maxLayers` to `128`. However, it will be impossible to extend the image further.
The first (`maxLayers-2`) most “popular” paths will have their own individual layers, then layer #`maxLayers-1` will contain all the remaining “unpopular” paths, and finally layer #`maxLayers` will contain the Image configuration.
Docker’s Layers are not inherently ordered, they are content-addressable and are not explicitly layered until they are composed in to an Image.
### `pkgs.dockerTools.streamLayeredImage`
Builds a script which, when run, will stream an uncompressed tarball of a Docker image to stdout. The arguments to this function are as for `buildLayeredImage`. This method of constructing an image does not realize the image into the Nix store, so it saves on IO and disk/cache space, particularly with large images.
The image produced by running the output script can be piped directly into `docker load`, to load it into the local docker daemon:
```
$(nix-build) | docker load
```
Alternatively, the image be piped via `gzip` into `skopeo`, e.g., to copy it into a registry:
```
$(nix-build) | gzip --fast | skopeo copy docker-archive:/dev/stdin docker://some_docker_registry/myimage:tag
```
### `pkgs.dockerTools.pullImage`
This function is analogous to the `docker pull` command, in that it can be used to pull a Docker image from a Docker registry. By default [Docker Hub](https://hub.docker.com/) is used to pull images.
Its parameters are described in the example below:
```
pullImage {
imageName = "nixos/nix";
imageDigest =
"sha256:20d9485b25ecfd89204e843a962c1bd70e9cc6858d65d7f5fadc340246e2116b";
finalImageName = "nix";
finalImageTag = "1.11";
sha256 = "0mqjy3zq2v6rrhizgb9nvhczl87lcfphq9601wcprdika2jz7qh8";
os = "linux";
arch = "x86_64";
}
```
* `imageName` specifies the name of the image to be downloaded, which can also include the registry namespace (e.g. `nixos`). This argument is required.
* `imageDigest` specifies the digest of the image to be downloaded. This argument is required.
* `finalImageName`, if specified, this is the name of the image to be created. Note it is never used to fetch the image since we prefer to rely on the immutable digest ID. By default it’s equal to `imageName`.
* `finalImageTag`, if specified, this is the tag of the image to be created. Note it is never used to fetch the image since we prefer to rely on the immutable digest ID. By default it’s `latest`.
* `sha256` is the checksum of the whole fetched image. This argument is required.
* `os`, if specified, is the operating system of the fetched image. By default it’s `linux`.
* `arch`, if specified, is the cpu architecture of the fetched image. By default it’s `x86_64`.
`nix-prefetch-docker` command can be used to get required image parameters:
```
$ nix run nixpkgs.nix-prefetch-docker -c nix-prefetch-docker --image-name mysql --image-tag 5
```
Since a given `imageName` may transparently refer to a manifest list of images which support multiple architectures and/or operating systems, you can supply the `--os` and `--arch` arguments to specify exactly which image you want. By default it will match the OS and architecture of the host the command is run on.
```
$ nix-prefetch-docker --image-name mysql --image-tag 5 --arch x86_64 --os linux
```
Desired image name and tag can be set using `--final-image-name` and `--final-image-tag` arguments:
```
$ nix-prefetch-docker --image-name mysql --image-tag 5 --final-image-name eu.gcr.io/my-project/mysql --final-image-tag prod
```
### `pkgs.dockerTools.exportImage`
This function is analogous to the `docker export` command, in that it can be used to flatten a Docker image that contains multiple layers. It is in fact the result of the merge of all the layers of the image. As such, the result is suitable for being imported in Docker with `docker import`.
> ***NOTE:*** Using this function requires the `kvm` device to be available.
>
>
The parameters of `exportImage` are the following:
```
exportImage {
fromImage = someLayeredImage;
fromImageName = null;
fromImageTag = null;
name = someLayeredImage.name;
}
```
The parameters relative to the base image have the same synopsis as described in [buildImage](#ssec-pkgs-dockerTools-buildImage "15.2.1. buildImage"), except that `fromImage` is the only required argument in this case.
The `name` argument is the name of the derivation output, which defaults to `fromImage.name`.
### `pkgs.dockerTools.shadowSetup`
This constant string is a helper for setting up the base files for managing users and groups, only if such files don’t exist already. It is suitable for being used in a [`buildImage` `runAsRoot`](#ex-dockerTools-buildImage-runAsRoot) script for cases like in the example below:
```
buildImage {
name = "shadow-basic";
runAsRoot = ''
#!${pkgs.runtimeShell}
${pkgs.dockerTools.shadowSetup}
groupadd -r redis
useradd -r -g redis redis
mkdir /data
chown redis:redis /data
'';
}
```
Creating base files like `/etc/passwd` or `/etc/login.defs` is necessary for shadow-utils to manipulate users and groups.
`pkgs.ociTools`
---------------
`pkgs.ociTools` is a set of functions for creating containers according to the [OCI container specification v1.0.0](https://github.com/opencontainers/runtime-spec). Beyond that, it makes no assumptions about the container runner you choose to use to run the created container.
### `pkgs.ociTools.buildContainer`
This function creates a simple OCI container that runs a single command inside of it. An OCI container consists of a `config.json` and a rootfs directory. The nix store of the container will contain all referenced dependencies of the given command.
The parameters of `buildContainer` with an example value are described below:
```
buildContainer {
args = [
(with pkgs;
writeScript "run.sh" ''
#!${bash}/bin/bash
exec ${bash}/bin/bash
'').outPath
];
mounts = {
"/data" = {
type = "none";
source = "/var/lib/mydata";
options = [ "bind" ];
};
};
readonly = false;
}
```
* `args` specifies a set of arguments to run inside the container. This is the only required argument for `buildContainer`. All referenced packages inside the derivation will be made available inside the container.
* `mounts` specifies additional mount points chosen by the user. By default only a minimal set of necessary filesystems are mounted into the container (e.g procfs, cgroupfs)
* `readonly` makes the container's rootfs read-only if it is set to true. The default value is false `false`.
`pkgs.snapTools`
----------------
`pkgs.snapTools` is a set of functions for creating Snapcraft images. Snap and Snapcraft is not used to perform these operations.
### `The makeSnap Function`
`makeSnap` takes a single named argument, `meta`. This argument mirrors [the upstream `snap.yaml` format](https://docs.snapcraft.io/snap-format) exactly.
The `base` should not be specified, as `makeSnap` will force set it.
Currently, `makeSnap` does not support creating GUI stubs.
### `Build a Hello World Snap`
The following expression packages GNU Hello as a Snapcraft snap.
```
let
inherit (import <nixpkgs> { }) snapTools hello;
in snapTools.makeSnap {
meta = {
name = "hello";
summary = hello.meta.description;
description = hello.meta.longDescription;
architectures = [ "amd64" ];
confinement = "strict";
apps.hello.command = "${hello}/bin/hello";
};
}
```
`nix-build` this expression and install it with `snap install ./result --dangerous`. `hello` will now be the Snapcraft version of the package.
### `Build a Graphical Snap`
Graphical programs require many more integrations with the host. This example uses Firefox as an example because it is one of the most complicated programs we could package.
```
let
inherit (import <nixpkgs> { }) snapTools firefox;
in snapTools.makeSnap {
meta = {
name = "nix-example-firefox";
summary = firefox.meta.description;
architectures = [ "amd64" ];
apps.nix-example-firefox = {
command = "${firefox}/bin/firefox";
plugs = [
"pulseaudio"
"camera"
"browser-support"
"avahi-observe"
"cups-control"
"desktop"
"desktop-legacy"
"gsettings"
"home"
"network"
"mount-observe"
"removable-media"
"x11"
];
};
confinement = "strict";
};
}
```
`nix-build` this expression and install it with `snap install ./result --dangerous`. `nix-example-firefox` will now be the Snapcraft version of the Firefox package.
The specific meaning behind plugs can be looked up in the [Snapcraft interface documentation](https://docs.snapcraft.io/supported-interfaces).
| programming_docs |
ocaml Chapter 2 The module system Chapter 2 The module system
===========================
* [2.1 Structures](moduleexamples#s%3Amodule%3Astructures)
* [2.2 Signatures](moduleexamples#s%3Asignature)
* [2.3 Functors](moduleexamples#s%3Afunctors)
* [2.4 Functors and type abstraction](moduleexamples#s%3Afunctors-and-abstraction)
* [2.5 Modules and separate compilation](moduleexamples#s%3Aseparate-compilation)
This chapter introduces the module system of OCaml.
[](#s:module:structures)2.1 Structures
----------------------------------------
A primary motivation for modules is to package together related definitions (such as the definitions of a data type and associated operations over that type) and enforce a consistent naming scheme for these definitions. This avoids running out of names or accidentally confusing names. Such a package is called a *structure* and is introduced by the struct…end construct, which contains an arbitrary sequence of definitions. The structure is usually given a name with the module binding. For instance, here is a structure packaging together a type of priority queues and their operations:
```
# module PrioQueue =
struct
type priority = int
type 'a queue = Empty | Node of priority * 'a * 'a queue * 'a queue
let empty = Empty
let rec insert queue prio elt =
match queue with
Empty -> Node(prio, elt, Empty, Empty)
| Node(p, e, left, right) ->
if prio <= p
then Node(prio, elt, insert right p e, left)
else Node(p, e, insert right prio elt, left)
exception Queue_is_empty
let rec remove_top = function
Empty -> raise Queue_is_empty
| Node(prio, elt, left, Empty) -> left
| Node(prio, elt, Empty, right) -> right
| Node(prio, elt, (Node(lprio, lelt, _, _) as left),
(Node(rprio, relt, _, _) as right)) ->
if lprio <= rprio
then Node(lprio, lelt, remove_top left, right)
else Node(rprio, relt, left, remove_top right)
let extract = function
Empty -> raise Queue_is_empty
| Node(prio, elt, _, _) as queue -> (prio, elt, remove_top queue)
end;;
module PrioQueue :
sig
type priority = int
type 'a queue = Empty | Node of priority * 'a * 'a queue * 'a queue
val empty : 'a queue
val insert : 'a queue -> priority -> 'a -> 'a queue
exception Queue_is_empty
val remove_top : 'a queue -> 'a queue
val extract : 'a queue -> priority * 'a * 'a queue
end
```
Outside the structure, its components can be referred to using the “dot notation”, that is, identifiers qualified by a structure name. For instance, PrioQueue.insert is the function insert defined inside the structure PrioQueue and PrioQueue.queue is the type queue defined in PrioQueue.
```
# PrioQueue.insert PrioQueue.empty 1 "hello";;
- : string PrioQueue.queue =
PrioQueue.Node (1, "hello", PrioQueue.Empty, PrioQueue.Empty)
```
Another possibility is to open the module, which brings all identifiers defined inside the module in the scope of the current structure.
```
# open PrioQueue;;
```
```
# insert empty 1 "hello";;
- : string PrioQueue.queue = Node (1, "hello", Empty, Empty)
```
Opening a module enables lighter access to its components, at the cost of making it harder to identify in which module an identifier has been defined. In particular, opened modules can shadow identifiers present in the current scope, potentially leading to confusing errors:
```
# let empty = []
open PrioQueue;;
val empty : 'a list = []
```
```
# let x = 1 :: empty ;;
Error: This expression has type 'a PrioQueue.queue
but an expression was expected of type int list
```
A partial solution to this conundrum is to open modules locally, making the components of the module available only in the concerned expression. This can also make the code both easier to read (since the open statement is closer to where it is used) and easier to refactor (since the code fragment is more self-contained). Two constructions are available for this purpose:
```
# let open PrioQueue in
insert empty 1 "hello";;
- : string PrioQueue.queue = Node (1, "hello", Empty, Empty)
```
and
```
# PrioQueue.(insert empty 1 "hello");;
- : string PrioQueue.queue = Node (1, "hello", Empty, Empty)
```
In the second form, when the body of a local open is itself delimited by parentheses, braces or bracket, the parentheses of the local open can be omitted. For instance,
```
# PrioQueue.[empty] = PrioQueue.([empty]);;
- : bool = true
```
```
# PrioQueue.[|empty|] = PrioQueue.([|empty|]);;
- : bool = true
```
```
# PrioQueue.{ contents = empty } = PrioQueue.({ contents = empty });;
- : bool = true
```
becomes
```
# PrioQueue.[insert empty 1 "hello"];;
- : string PrioQueue.queue list = [Node (1, "hello", Empty, Empty)]
```
This second form also works for patterns:
```
# let at_most_one_element x = match x with
| PrioQueue.( Empty| Node (_,_, Empty,Empty) ) -> true
| _ -> false ;;
val at_most_one_element : 'a PrioQueue.queue -> bool =
```
It is also possible to copy the components of a module inside another module by using an include statement. This can be particularly useful to extend existing modules. As an illustration, we could add functions that return an optional value rather than an exception when the priority queue is empty.
```
# module PrioQueueOpt =
struct
include PrioQueue
let remove_top_opt x =
try Some(remove_top x) with Queue_is_empty -> None
let extract_opt x =
try Some(extract x) with Queue_is_empty -> None
end;;
module PrioQueueOpt :
sig
type priority = int
type 'a queue =
'a PrioQueue.queue =
Empty
| Node of priority * 'a * 'a queue * 'a queue
val empty : 'a queue
val insert : 'a queue -> priority -> 'a -> 'a queue
exception Queue_is_empty
val remove_top : 'a queue -> 'a queue
val extract : 'a queue -> priority * 'a * 'a queue
val remove_top_opt : 'a queue -> 'a queue option
val extract_opt : 'a queue -> (priority * 'a * 'a queue) option
end
```
[](#s:signature)2.2 Signatures
--------------------------------
Signatures are interfaces for structures. A signature specifies which components of a structure are accessible from the outside, and with which type. It can be used to hide some components of a structure (e.g. local function definitions) or export some components with a restricted type. For instance, the signature below specifies the three priority queue operations empty, insert and extract, but not the auxiliary function remove\_top. Similarly, it makes the queue type abstract (by not providing its actual representation as a concrete type).
```
# module type PRIOQUEUE =
sig
type priority = int (* still concrete *)
type 'a queue (* now abstract *)
val empty : 'a queue
val insert : 'a queue -> int -> 'a -> 'a queue
val extract : 'a queue -> int * 'a * 'a queue
exception Queue_is_empty
end;;
module type PRIOQUEUE =
sig
type priority = int
type 'a queue
val empty : 'a queue
val insert : 'a queue -> int -> 'a -> 'a queue
val extract : 'a queue -> int * 'a * 'a queue
exception Queue_is_empty
end
```
Restricting the PrioQueue structure by this signature results in another view of the PrioQueue structure where the remove\_top function is not accessible and the actual representation of priority queues is hidden:
```
# module AbstractPrioQueue = (PrioQueue : PRIOQUEUE);;
module AbstractPrioQueue : PRIOQUEUE
```
```
# AbstractPrioQueue.remove_top ;;
Error: Unbound value AbstractPrioQueue.remove_top
```
```
# AbstractPrioQueue.insert AbstractPrioQueue.empty 1 "hello";;
- : string AbstractPrioQueue.queue =
```
The restriction can also be performed during the definition of the structure, as in
```
module PrioQueue = (struct ... end : PRIOQUEUE);;
```
An alternate syntax is provided for the above:
```
module PrioQueue : PRIOQUEUE = struct ... end;;
```
Like for modules, it is possible to include a signature to copy its components inside the current signature. For instance, we can extend the PRIOQUEUE signature with the extract\_opt function:
```
# module type PRIOQUEUE_WITH_OPT =
sig
include PRIOQUEUE
val extract_opt : 'a queue -> (int * 'a * 'a queue) option
end;;
module type PRIOQUEUE_WITH_OPT =
sig
type priority = int
type 'a queue
val empty : 'a queue
val insert : 'a queue -> int -> 'a -> 'a queue
val extract : 'a queue -> int * 'a * 'a queue
exception Queue_is_empty
val extract_opt : 'a queue -> (int * 'a * 'a queue) option
end
```
[](#s:functors)2.3 Functors
-----------------------------
Functors are “functions” from modules to modules. Functors let you create parameterized modules and then provide other modules as parameter(s) to get a specific implementation. For instance, a Set module implementing sets as sorted lists could be parameterized to work with any module that provides an element type and a comparison function compare (such as OrderedString):
```
# type comparison = Less | Equal | Greater;;
type comparison = Less | Equal | Greater
```
```
# module type ORDERED_TYPE =
sig
type t
val compare: t -> t -> comparison
end;;
module type ORDERED_TYPE = sig type t val compare : t -> t -> comparison end
```
```
# module Set =
functor (Elt: ORDERED_TYPE) ->
struct
type element = Elt.t
type set = element list
let empty = []
let rec add x s =
match s with
[] -> [x]
| hd::tl ->
match Elt.compare x hd with
Equal -> s (* x is already in s *)
| Less -> x :: s (* x is smaller than all elements of s *)
| Greater -> hd :: add x tl
let rec member x s =
match s with
[] -> false
| hd::tl ->
match Elt.compare x hd with
Equal -> true (* x belongs to s *)
| Less -> false (* x is smaller than all elements of s *)
| Greater -> member x tl
end;;
module Set :
functor (Elt : ORDERED_TYPE) ->
sig
type element = Elt.t
type set = element list
val empty : 'a list
val add : Elt.t -> Elt.t list -> Elt.t list
val member : Elt.t -> Elt.t list -> bool
end
```
By applying the Set functor to a structure implementing an ordered type, we obtain set operations for this type:
```
# module OrderedString =
struct
type t = string
let compare x y = if x = y then Equal else if x < y then Less else Greater
end;;
module OrderedString :
sig type t = string val compare : 'a -> 'a -> comparison end
```
```
# module StringSet = Set(OrderedString);;
module StringSet :
sig
type element = OrderedString.t
type set = element list
val empty : 'a list
val add : OrderedString.t -> OrderedString.t list -> OrderedString.t list
val member : OrderedString.t -> OrderedString.t list -> bool
end
```
```
# StringSet.member "bar" (StringSet.add "foo" StringSet.empty);;
- : bool = false
```
[](#s:functors-and-abstraction)2.4 Functors and type abstraction
------------------------------------------------------------------
As in the PrioQueue example, it would be good style to hide the actual implementation of the type set, so that users of the structure will not rely on sets being lists, and we can switch later to another, more efficient representation of sets without breaking their code. This can be achieved by restricting Set by a suitable functor signature:
```
# module type SETFUNCTOR =
functor (Elt: ORDERED_TYPE) ->
sig
type element = Elt.t (* concrete *)
type set (* abstract *)
val empty : set
val add : element -> set -> set
val member : element -> set -> bool
end;;
module type SETFUNCTOR =
functor (Elt : ORDERED_TYPE) ->
sig
type element = Elt.t
type set
val empty : set
val add : element -> set -> set
val member : element -> set -> bool
end
```
```
# module AbstractSet = (Set : SETFUNCTOR);;
module AbstractSet : SETFUNCTOR
```
```
# module AbstractStringSet = AbstractSet(OrderedString);;
module AbstractStringSet :
sig
type element = OrderedString.t
type set = AbstractSet(OrderedString).set
val empty : set
val add : element -> set -> set
val member : element -> set -> bool
end
```
```
# AbstractStringSet.add "gee" AbstractStringSet.empty;;
- : AbstractStringSet.set =
```
In an attempt to write the type constraint above more elegantly, one may wish to name the signature of the structure returned by the functor, then use that signature in the constraint:
```
# module type SET =
sig
type element
type set
val empty : set
val add : element -> set -> set
val member : element -> set -> bool
end;;
module type SET =
sig
type element
type set
val empty : set
val add : element -> set -> set
val member : element -> set -> bool
end
```
```
# module WrongSet = (Set : functor(Elt: ORDERED_TYPE) -> SET);;
module WrongSet : functor (Elt : ORDERED_TYPE) -> SET
```
```
# module WrongStringSet = WrongSet(OrderedString);;
module WrongStringSet :
sig
type element = WrongSet(OrderedString).element
type set = WrongSet(OrderedString).set
val empty : set
val add : element -> set -> set
val member : element -> set -> bool
end
```
```
# WrongStringSet.add "gee" WrongStringSet.empty ;;
Error: This expression has type string but an expression was expected of type
WrongStringSet.element = WrongSet(OrderedString).element
```
The problem here is that SET specifies the type element abstractly, so that the type equality between element in the result of the functor and t in its argument is forgotten. Consequently, WrongStringSet.element is not the same type as string, and the operations of WrongStringSet cannot be applied to strings. As demonstrated above, it is important that the type element in the signature SET be declared equal to Elt.t; unfortunately, this is impossible above since SET is defined in a context where Elt does not exist. To overcome this difficulty, OCaml provides a with type construct over signatures that allows enriching a signature with extra type equalities:
```
# module AbstractSet2 =
(Set : functor(Elt: ORDERED_TYPE) -> (SET with type element = Elt.t));;
module AbstractSet2 :
functor (Elt : ORDERED_TYPE) ->
sig
type element = Elt.t
type set
val empty : set
val add : element -> set -> set
val member : element -> set -> bool
end
```
As in the case of simple structures, an alternate syntax is provided for defining functors and restricting their result:
```
module AbstractSet2(Elt: ORDERED_TYPE) : (SET with type element = Elt.t) =
struct ... end;;
```
Abstracting a type component in a functor result is a powerful technique that provides a high degree of type safety, as we now illustrate. Consider an ordering over character strings that is different from the standard ordering implemented in the OrderedString structure. For instance, we compare strings without distinguishing upper and lower case.
```
# module NoCaseString =
struct
type t = string
let compare s1 s2 =
OrderedString.compare (String.lowercase_ascii s1) (String.lowercase_ascii s2)
end;;
module NoCaseString :
sig type t = string val compare : string -> string -> comparison end
```
```
# module NoCaseStringSet = AbstractSet(NoCaseString);;
module NoCaseStringSet :
sig
type element = NoCaseString.t
type set = AbstractSet(NoCaseString).set
val empty : set
val add : element -> set -> set
val member : element -> set -> bool
end
```
```
# NoCaseStringSet.add "FOO" AbstractStringSet.empty ;;
Error: This expression has type
AbstractStringSet.set = AbstractSet(OrderedString).set
but an expression was expected of type
NoCaseStringSet.set = AbstractSet(NoCaseString).set
```
Note that the two types AbstractStringSet.set and NoCaseStringSet.set are not compatible, and values of these two types do not match. This is the correct behavior: even though both set types contain elements of the same type (strings), they are built upon different orderings of that type, and different invariants need to be maintained by the operations (being strictly increasing for the standard ordering and for the case-insensitive ordering). Applying operations from AbstractStringSet to values of type NoCaseStringSet.set could give incorrect results, or build lists that violate the invariants of NoCaseStringSet.
[](#s:separate-compilation)2.5 Modules and separate compilation
-----------------------------------------------------------------
All examples of modules so far have been given in the context of the interactive system. However, modules are most useful for large, batch-compiled programs. For these programs, it is a practical necessity to split the source into several files, called compilation units, that can be compiled separately, thus minimizing recompilation after changes.
In OCaml, compilation units are special cases of structures and signatures, and the relationship between the units can be explained easily in terms of the module system. A compilation unit A comprises two files:
* the implementation file A.ml, which contains a sequence of definitions, analogous to the inside of a struct…end construct;
* the interface file A.mli, which contains a sequence of specifications, analogous to the inside of a sig…end construct.
These two files together define a structure named A as if the following definition was entered at top-level:
```
module A: sig (* contents of file A.mli *) end
= struct (* contents of file A.ml *) end;;
```
The files that define the compilation units can be compiled separately using the ocamlc -c command (the -c option means “compile only, do not try to link”); this produces compiled interface files (with extension .cmi) and compiled object code files (with extension .cmo). When all units have been compiled, their .cmo files are linked together using the ocamlc command. For instance, the following commands compile and link a program composed of two compilation units Aux and Main:
```
$ ocamlc -c Aux.mli # produces aux.cmi
$ ocamlc -c Aux.ml # produces aux.cmo
$ ocamlc -c Main.mli # produces main.cmi
$ ocamlc -c Main.ml # produces main.cmo
$ ocamlc -o theprogram Aux.cmo Main.cmo
```
The program behaves exactly as if the following phrases were entered at top-level:
```
module Aux: sig (* contents of Aux.mli *) end
= struct (* contents of Aux.ml *) end;;
module Main: sig (* contents of Main.mli *) end
= struct (* contents of Main.ml *) end;;
```
In particular, Main can refer to Aux: the definitions and declarations contained in Main.ml and Main.mli can refer to definition in Aux.ml, using the Aux.ident notation, provided these definitions are exported in Aux.mli.
The order in which the .cmo files are given to ocamlc during the linking phase determines the order in which the module definitions occur. Hence, in the example above, Aux appears first and Main can refer to it, but Aux cannot refer to Main.
Note that only top-level structures can be mapped to separately-compiled files, but neither functors nor module types. However, all module-class objects can appear as components of a structure, so the solution is to put the functor or module type inside a structure, which can then be mapped to a file.
| programming_docs |
ocaml Chapter 14 The toplevel system or REPL (ocaml) Chapter 14 The toplevel system or REPL (ocaml)
==============================================
* [14.1 Options](toplevel#s%3Atoplevel-options)
* [14.2 Toplevel directives](toplevel#s%3Atoplevel-directives)
* [14.3 The toplevel and the module system](toplevel#s%3Atoplevel-modules)
* [14.4 Common errors](toplevel#s%3Atoplevel-common-errors)
* [14.5 Building custom toplevel systems: ocamlmktop](toplevel#s%3Acustom-toplevel)
* [14.6 The native toplevel: ocamlnat (experimental)](toplevel#s%3Aocamlnat)
This chapter describes the toplevel system for OCaml, that permits interactive use of the OCaml system through a read-eval-print loop (REPL). In this mode, the system repeatedly reads OCaml phrases from the input, then typechecks, compile and evaluate them, then prints the inferred type and result value, if any. The system prints a # (sharp) prompt before reading each phrase.
Input to the toplevel can span several lines. It is terminated by ;; (a double-semicolon). The toplevel input consists in one or several toplevel phrases, with the following syntax:
| | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| toplevel-input | ::= | { [definition](modules#definition) }+ ;; |
| | ∣ | [expr](expr#expr) ;; |
| | ∣ | # [ident](lex#ident) [ [directive-argument](#directive-argument) ] ;; |
| |
| directive-argument | ::= | [string-literal](lex#string-literal) |
| | ∣ | [integer-literal](lex#integer-literal) |
| | ∣ | [value-path](names#value-path) |
| | ∣ | true ∣ false |
|
A phrase can consist of a definition, like those found in implementations of compilation units or in struct … end module expressions. The definition can bind value names, type names, an exception, a module name, or a module type name. The toplevel system performs the bindings, then prints the types and values (if any) for the names thus defined.
A phrase may also consist in a value expression (section [11.7](expr#s%3Avalue-expr)). It is simply evaluated without performing any bindings, and its value is printed.
Finally, a phrase can also consist in a toplevel directive, starting with # (the sharp sign). These directives control the behavior of the toplevel; they are listed below in section [14.2](#s%3Atoplevel-directives).
>
> Unix: The toplevel system is started by the command ocaml, as follows:
> ```
>
> ocaml options objects # interactive mode
> ocaml options objects scriptfile # script mode
>
> ```
> options are described below. objects are filenames ending in .cmo or .cma; they are loaded into the interpreter immediately after options are set. scriptfile is any file name not ending in .cmo or .cma.If no scriptfile is given on the command line, the toplevel system enters interactive mode: phrases are read on standard input, results are printed on standard output, errors on standard error. End-of-file on standard input terminates ocaml (see also the #quit directive in section [14.2](#s%3Atoplevel-directives)).
>
>
> On start-up (before the first phrase is read), if the file .ocamlinit exists in the current directory, its contents are read as a sequence of OCaml phrases and executed as per the #use directive described in section [14.2](#s%3Atoplevel-directives). The evaluation outcode for each phrase are not displayed. If the current directory does not contain an .ocamlinit file, the file XDG\_CONFIG\_HOME/ocaml/init.ml is looked up according to the XDG base directory specification and used instead (on Windows this is skipped). If that file doesn’t exist then an [.ocamlinit] file in the users’ home directory (determined via environment variable HOME) is used if existing.
>
>
> The toplevel system does not perform line editing, but it can easily be used in conjunction with an external line editor such as ledit, or rlwrap. An improved toplevel, utop, is also available. Another option is to use ocaml under Gnu Emacs, which gives the full editing power of Emacs (command run-caml from library inf-caml).
>
>
> At any point, the parsing, compilation or evaluation of the current phrase can be interrupted by pressing ctrl-C (or, more precisely, by sending the INTR signal to the ocaml process). The toplevel then immediately returns to the # prompt.
>
>
> If scriptfile is given on the command-line to ocaml, the toplevel system enters script mode: the contents of the file are read as a sequence of OCaml phrases and executed, as per the #use directive (section [14.2](#s%3Atoplevel-directives)). The outcome of the evaluation is not printed. On reaching the end of file, the ocaml command exits immediately. No commands are read from standard input. Sys.argv is transformed, ignoring all OCaml parameters, and starting with the script file name in Sys.argv.(0).
>
>
> In script mode, the first line of the script is ignored if it starts with #!. Thus, it should be possible to make the script itself executable and put as first line #!/usr/local/bin/ocaml, thus calling the toplevel system automatically when the script is run. However, ocaml itself is a #! script on most installations of OCaml, and Unix kernels usually do not handle nested #! scripts. A better solution is to put the following as the first line of the script:
>
>
>
> ```
> #!/usr/local/bin/ocamlrun /usr/local/bin/ocaml
>
> ```
>
>
[](#s:toplevel-options)14.1 Options
-------------------------------------
The following command-line options are recognized by the ocaml command.
-absname
Force error messages to show absolute paths for file names.
-args filename
Read additional newline-terminated command line arguments from filename. It is not possible to pass a scriptfile via file to the toplevel.
-args0 filename
Read additional null character terminated command line arguments from filename. It is not possible to pass a scriptfile via file to the toplevel.
-I directory
Add the given directory to the list of directories searched for source and compiled files. By default, the current directory is searched first, then the standard library directory. Directories added with -I are searched after the current directory, in the order in which they were given on the command line, but before the standard library directory. See also option -nostdlib.If the given directory starts with +, it is taken relative to the standard library directory. For instance, -I +unix adds the subdirectory unix of the standard library to the search path.
Directories can also be added to the list once the toplevel is running with the #directory directive (section [14.2](#s%3Atoplevel-directives)).
-init file
Load the given file instead of the default initialization file. The default file is .ocamlinit in the current directory if it exists, otherwise XDG\_CONFIG\_HOME/ocaml/init.ml or .ocamlinit in the user’s home directory.
-labels
Labels are not ignored in types, labels may be used in applications, and labelled parameters can be given in any order. This is the default.
-no-app-funct
Deactivates the applicative behaviour of functors. With this option, each functor application generates new types in its result and applying the same functor twice to the same argument yields two incompatible structures.
-noassert
Do not compile assertion checks. Note that the special form assert false is always compiled because it is typed specially.
-nolabels
Ignore non-optional labels in types. Labels cannot be used in applications, and parameter order becomes strict.
-noprompt
Do not display any prompt when waiting for input.
-nopromptcont
Do not display the secondary prompt when waiting for continuation lines in multi-line inputs. This should be used e.g. when running ocaml in an emacs window.
-nostdlib
Do not include the standard library directory in the list of directories searched for source and compiled files.
-ppx command
After parsing, pipe the abstract syntax tree through the preprocessor command. The module Ast\_mapper, described in chapter [29](parsing#c%3Aparsinglib): [Ast\_mapper](https://v2.ocaml.org/releases/5.0/htmlman/compilerlibref/Ast_mapper.html) , implements the external interface of a preprocessor.
-principal
Check information path during type-checking, to make sure that all types are derived in a principal way. When using labelled arguments and/or polymorphic methods, this flag is required to ensure future versions of the compiler will be able to infer types correctly, even if internal algorithms change. All programs accepted in -principal mode are also accepted in the default mode with equivalent types, but different binary signatures, and this may slow down type checking; yet it is a good idea to use it once before publishing source code.
-rectypes
Allow arbitrary recursive types during type-checking. By default, only recursive types where the recursion goes through an object type are supported.
-safe-string
Enforce the separation between types string and bytes, thereby making strings read-only. This is the default, and enforced since OCaml 5.0.
-short-paths
When a type is visible under several module-paths, use the shortest one when printing the type’s name in inferred interfaces and error and warning messages. Identifier names starting with an underscore \_ or containing double underscores \_\_ incur a penalty of +10 when computing their length.
-stdin
Read the standard input as a script file rather than starting an interactive session.
-strict-sequence
Force the left-hand part of each sequence to have type unit.
-strict-formats
Reject invalid formats that were accepted in legacy format implementations. You should use this flag to detect and fix such invalid formats, as they will be rejected by future OCaml versions.
-unsafe
Turn bound checking off for array and string accesses (the v.(i) and s.[i] constructs). Programs compiled with -unsafe are therefore faster, but unsafe: anything can happen if the program accesses an array or string outside of its bounds.
-unsafe-string
Identify the types string and bytes, thereby making strings writable. This is intended for compatibility with old source code and should not be used with new software. This option raises an error unconditionally since OCaml 5.0.
-v
Print the version number of the compiler and the location of the standard library directory, then exit.
-verbose
Print all external commands before they are executed, Useful to debug C library problems.
-version
Print version string and exit.
-vnum
Print short version number and exit.
-no-version
Do not print the version banner at startup.
-w warning-list
Enable, disable, or mark as fatal the warnings specified by the argument warning-list. Each warning can be *enabled* or *disabled*, and each warning can be *fatal* or *non-fatal*. If a warning is disabled, it isn’t displayed and doesn’t affect compilation in any way (even if it is fatal). If a warning is enabled, it is displayed normally by the compiler whenever the source code triggers it. If it is enabled and fatal, the compiler will also stop with an error after displaying it.The warning-list argument is a sequence of warning specifiers, with no separators between them. A warning specifier is one of the following:
+num
Enable warning number num.
-num
Disable warning number num.
@num
Enable and mark as fatal warning number num.
+num1..num2
Enable warnings in the given range.
-num1..num2
Disable warnings in the given range.
@num1..num2
Enable and mark as fatal warnings in the given range.
+letter
Enable the set of warnings corresponding to letter. The letter may be uppercase or lowercase.
-letter
Disable the set of warnings corresponding to letter. The letter may be uppercase or lowercase.
@letter
Enable and mark as fatal the set of warnings corresponding to letter. The letter may be uppercase or lowercase.
uppercase-letter
Enable the set of warnings corresponding to uppercase-letter.
lowercase-letter
Disable the set of warnings corresponding to lowercase-letter.
Alternatively, warning-list can specify a single warning using its mnemonic name (see below), as follows:
+name
Enable warning name.
-name
Disable warning name.
@name
Enable and mark as fatal warning name.
Warning numbers, letters and names which are not currently defined are ignored. The warnings are as follows (the name following each number specifies the mnemonic for that warning).
1 comment-start
Suspicious-looking start-of-comment mark.
2 comment-not-end
Suspicious-looking end-of-comment mark.
3
Deprecated synonym for the ’deprecated’ alert.
4 fragile-match
Fragile pattern matching: matching that will remain complete even if additional constructors are added to one of the variant types matched.
5 ignored-partial-application
Partially applied function: expression whose result has function type and is ignored.
6 labels-omitted
Label omitted in function application.
7 method-override
Method overridden.
8 partial-match
Partial match: missing cases in pattern-matching.
9 missing-record-field-pattern
Missing fields in a record pattern.
10 non-unit-statement
Expression on the left-hand side of a sequence that doesn’t have type unit (and that is not a function, see warning number 5).
11 redundant-case
Redundant case in a pattern matching (unused match case).
12 redundant-subpat
Redundant sub-pattern in a pattern-matching.
13 instance-variable-override
Instance variable overridden.
14 illegal-backslash
Illegal backslash escape in a string constant.
15 implicit-public-methods
Private method made public implicitly.
16 unerasable-optional-argument
Unerasable optional argument.
17 undeclared-virtual-method
Undeclared virtual method.
18 not-principal
Non-principal type.
19 non-principal-labels
Type without principality.
20 ignored-extra-argument
Unused function argument.
21 nonreturning-statement
Non-returning statement.
22 preprocessor
Preprocessor warning.
23 useless-record-with
Useless record with clause.
24 bad-module-name
Bad module name: the source file name is not a valid OCaml module name.
25
Ignored: now part of warning 8.
26 unused-var
Suspicious unused variable: unused variable that is bound with let or as, and doesn’t start with an underscore (\_) character.
27 unused-var-strict
Innocuous unused variable: unused variable that is not bound with let nor as, and doesn’t start with an underscore (\_) character.
28 wildcard-arg-to-constant-constr
Wildcard pattern given as argument to a constant constructor.
29 eol-in-string
Unescaped end-of-line in a string constant (non-portable code).
30 duplicate-definitions
Two labels or constructors of the same name are defined in two mutually recursive types.
31 module-linked-twice
A module is linked twice in the same executable. (since 4.00)
32 unused-value-declaration
Unused value declaration. (since 4.00)
33 unused-open
Unused open statement. (since 4.00)
34 unused-type-declaration
Unused type declaration. (since 4.00)
35 unused-for-index
Unused for-loop index. (since 4.00)
36 unused-ancestor
Unused ancestor variable. (since 4.00)
37 unused-constructor
Unused constructor. (since 4.00)
38 unused-extension
Unused extension constructor. (since 4.00)
39 unused-rec-flag
Unused rec flag. (since 4.00)
40 name-out-of-scope
Constructor or label name used out of scope. (since 4.01)
41 ambiguous-name
Ambiguous constructor or label name. (since 4.01)
42 disambiguated-name
Disambiguated constructor or label name (compatibility warning). (since 4.01)
43 nonoptional-label
Nonoptional label applied as optional. (since 4.01)
44 open-shadow-identifier
Open statement shadows an already defined identifier. (since 4.01)
45 open-shadow-label-constructor
Open statement shadows an already defined label or constructor. (since 4.01)
46 bad-env-variable
Error in environment variable. (since 4.01)
47 attribute-payload
Illegal attribute payload. (since 4.02)
48 eliminated-optional-arguments
Implicit elimination of optional arguments. (since 4.02)
49 no-cmi-file
Absent cmi file when looking up module alias. (since 4.02)
50 unexpected-docstring
Unexpected documentation comment. (since 4.03)
51 wrong-tailcall-expectation
Function call annotated with an incorrect @tailcall attribute. (since 4.03)
52 fragile-literal-pattern (see [13.5.3](comp#ss%3Awarn52))
Fragile constant pattern. (since 4.03)
53 misplaced-attribute
Attribute cannot appear in this context. (since 4.03)
54 duplicated-attribute
Attribute used more than once on an expression. (since 4.03)
55 inlining-impossible
Inlining impossible. (since 4.03)
56 unreachable-case
Unreachable case in a pattern-matching (based on type information). (since 4.03)
57 ambiguous-var-in-pattern-guard (see [13.5.4](comp#ss%3Awarn57))
Ambiguous or-pattern variables under guard. (since 4.03)
58 no-cmx-file
Missing cmx file. (since 4.03)
59 flambda-assignment-to-non-mutable-value
Assignment to non-mutable value. (since 4.03)
60 unused-module
Unused module declaration. (since 4.04)
61 unboxable-type-in-prim-decl
Unboxable type in primitive declaration. (since 4.04)
62 constraint-on-gadt
Type constraint on GADT type declaration. (since 4.06)
63 erroneous-printed-signature
Erroneous printed signature. (since 4.08)
64 unsafe-array-syntax-without-parsing
-unsafe used with a preprocessor returning a syntax tree. (since 4.08)
65 redefining-unit
Type declaration defining a new ’()’ constructor. (since 4.08)
66 unused-open-bang
Unused open! statement. (since 4.08)
67 unused-functor-parameter
Unused functor parameter. (since 4.10)
68 match-on-mutable-state-prevent-uncurry
Pattern-matching depending on mutable state prevents the remaining arguments from being uncurried. (since 4.12)
69 unused-field
Unused record field. (since 4.13)
70 missing-mli
Missing interface file. (since 4.13)
71 unused-tmc-attribute
Unused @tail\_mod\_cons attribute. (since 4.14)
72 tmc-breaks-tailcall
A tail call is turned into a non-tail call by the @tail\_mod\_cons transformation. (since 4.14)
A
all warnings
C
warnings 1, 2.
D
Alias for warning 3.
E
Alias for warning 4.
F
Alias for warning 5.
K
warnings 32, 33, 34, 35, 36, 37, 38, 39.
L
Alias for warning 6.
M
Alias for warning 7.
P
Alias for warning 8.
R
Alias for warning 9.
S
Alias for warning 10.
U
warnings 11, 12.
V
Alias for warning 13.
X
warnings 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 30.
Y
Alias for warning 26.
Z
Alias for warning 27.
The default setting is -w +a-4-6-7-9-27-29-32..42-44-45-48-50-60. It is displayed by -help. Note that warnings 5 and 10 are not always triggered, depending on the internals of the type checker.
-warn-error warning-list
Mark as fatal the warnings specified in the argument warning-list. The compiler will stop with an error when one of these warnings is emitted. The warning-list has the same meaning as for the -w option: a + sign (or an uppercase letter) marks the corresponding warnings as fatal, a - sign (or a lowercase letter) turns them back into non-fatal warnings, and a @ sign both enables and marks as fatal the corresponding warnings.Note: it is not recommended to use warning sets (i.e. letters) as arguments to -warn-error in production code, because this can break your build when future versions of OCaml add some new warnings.
The default setting is -warn-error -a+31 (only warning 31 is fatal).
-warn-help
Show the description of all available warning numbers.
- file
Use file as a script file name, even when it starts with a hyphen (-).
-help or --help
Display a short usage summary and exit.
>
> Unix: The following environment variables are also consulted:
> OCAMLTOP\_INCLUDE\_PATH
> Additional directories to search for compiled object code files (.cmi, .cmo and .cma). The specified directories are considered from left to right, after the include directories specified on the command line via -I have been searched. Available since OCaml 4.08.
> OCAMLTOP\_UTF\_8
> When printing string values, non-ascii bytes ( > \0x7E ) are printed as decimal escape sequence if OCAMLTOP\_UTF\_8 is set to false. Otherwise, they are printed unescaped.
> TERM
> When printing error messages, the toplevel system attempts to underline visually the location of the error. It consults the TERM variable to determines the type of output terminal and look up its capabilities in the terminal database.
> XDG\_CONFIG\_HOME, HOME
> .ocamlinit lookup procedure (see above).
>
[](#s:toplevel-directives)14.2 Toplevel directives
----------------------------------------------------
The following directives control the toplevel behavior, load files in memory, and trace program execution.
Note: all directives start with a # (sharp) symbol. This # must be typed before the directive, and must not be confused with the # prompt displayed by the interactive loop. For instance, typing #quit;; will exit the toplevel loop, but typing quit;; will result in an “unbound value quit” error.
General
#help;;
Prints a list of all available directives, with corresponding argument type if appropriate.
#quit;;
Exit the toplevel loop and terminate the ocaml command.
Loading codes
#cd "dir-name";;
Change the current working directory.
#directory "dir-name";;
Add the given directory to the list of directories searched for source and compiled files.
#remove\_directory "dir-name";;
Remove the given directory from the list of directories searched for source and compiled files. Do nothing if the list does not contain the given directory.
#load "file-name";;
Load in memory a bytecode object file (.cmo file) or library file (.cma file) produced by the batch compiler ocamlc.
#load\_rec "file-name";;
Load in memory a bytecode object file (.cmo file) or library file (.cma file) produced by the batch compiler ocamlc. When loading an object file that depends on other modules which have not been loaded yet, the .cmo files for these modules are searched and loaded as well, recursively. The loading order is not specified.
#use "file-name";;
Read, compile and execute source phrases from the given file. This is textual inclusion: phrases are processed just as if they were typed on standard input. The reading of the file stops at the first error encountered.
#use\_output "command";;
Execute a command and evaluate its output as if it had been captured to a file and passed to #use.
#mod\_use "file-name";;
Similar to #use but also wrap the code into a top-level module of the same name as capitalized file name without extensions, following semantics of the compiler.
For directives that take file names as arguments, if the given file name specifies no directory, the file is searched in the following directories:
1. In script mode, the directory containing the script currently executing; in interactive mode, the current working directory.
2. Directories added with the #directory directive.
3. Directories given on the command line with -I options.
4. The standard library directory.
Environment queries
#show\_class class-path;;
#show\_class\_type class-path;;
#show\_exception ident;;
#show\_module module-path;;
#show\_module\_type modtype-path;;
#show\_type typeconstr;;
#show\_val value-path;;
Print the signature of the corresponding component.
#show ident;;
Print the signatures of components with name ident in all the above categories.
Pretty-printing
#install\_printer printer-name;;
This directive registers the function named printer-name (a value path) as a printer for values whose types match the argument type of the function. That is, the toplevel loop will call printer-name when it has such a value to print.The printing function printer-name should have type Format.formatter -> t -> unit, where t is the type for the values to be printed, and should output its textual representation for the value of type t on the given formatter, using the functions provided by the Format library. For backward compatibility, printer-name can also have type t -> unit and should then output on the standard formatter, but this usage is deprecated.
#print\_depth n;;
Limit the printing of values to a maximal depth of n. The parts of values whose depth exceeds n are printed as ... (ellipsis).
#print\_length n;;
Limit the number of value nodes printed to at most n. Remaining parts of values are printed as ... (ellipsis).
#remove\_printer printer-name;;
Remove the named function from the table of toplevel printers.
Tracing
#trace function-name;;
After executing this directive, all calls to the function named function-name will be “traced”. That is, the argument and the result are displayed for each call, as well as the exceptions escaping out of the function, raised either by the function itself or by another function it calls. If the function is curried, each argument is printed as it is passed to the function.
#untrace function-name;;
Stop tracing the given function.
#untrace\_all;;
Stop tracing all functions traced so far.
Compiler options
#labels bool;;
Ignore labels in function types if argument is false, or switch back to default behaviour (commuting style) if argument is true.
#ppx "file-name";;
After parsing, pipe the abstract syntax tree through the preprocessor command.
#principal bool;;
If the argument is true, check information paths during type-checking, to make sure that all types are derived in a principal way. If the argument is false, do not check information paths.
#rectypes;;
Allow arbitrary recursive types during type-checking. Note: once enabled, this option cannot be disabled because that would lead to unsoundness of the type system.
#warn\_error "warning-list";;
Treat as errors the warnings enabled by the argument and as normal warnings the warnings disabled by the argument.
#warnings "warning-list";;
Enable or disable warnings according to the argument.
[](#s:toplevel-modules)14.3 The toplevel and the module system
----------------------------------------------------------------
Toplevel phrases can refer to identifiers defined in compilation units with the same mechanisms as for separately compiled units: either by using qualified names (Modulename.localname), or by using the open construct and unqualified names (see section [11.3](names#s%3Anames)).
However, before referencing another compilation unit, an implementation of that unit must be present in memory. At start-up, the toplevel system contains implementations for all the modules in the the standard library. Implementations for user modules can be entered with the #load directive described above. Referencing a unit for which no implementation has been provided results in the error Reference to undefined global `...'.
Note that entering open Mod merely accesses the compiled interface (.cmi file) for Mod, but does not load the implementation of Mod, and does not cause any error if no implementation of Mod has been loaded. The error “reference to undefined global Mod” will occur only when executing a value or module definition that refers to Mod.
[](#s:toplevel-common-errors)14.4 Common errors
-------------------------------------------------
This section describes and explains the most frequently encountered error messages.
Cannot find file filename
The named file could not be found in the current directory, nor in the directories of the search path.If filename has the format mod.cmi, this means you have referenced the compilation unit mod, but its compiled interface could not be found. Fix: compile mod.mli or mod.ml first, to create the compiled interface mod.cmi.
If filename has the format mod.cmo, this means you are trying to load with #load a bytecode object file that does not exist yet. Fix: compile mod.ml first.
If your program spans several directories, this error can also appear because you haven’t specified the directories to look into. Fix: use the #directory directive to add the correct directories to the search path.
This expression has type t1, but is used with type t2
See section [13.4](comp#s%3Acomp-errors).
Reference to undefined global mod
You have neglected to load in memory an implementation for a module with #load. See section [14.3](#s%3Atoplevel-modules) above.
[](#s:custom-toplevel)14.5 Building custom toplevel systems: ocamlmktop
-------------------------------------------------------------------------
The ocamlmktop command builds OCaml toplevels that contain user code preloaded at start-up.
The ocamlmktop command takes as argument a set of .cmo and .cma files, and links them with the object files that implement the OCaml toplevel. The typical use is:
```
ocamlmktop -o mytoplevel foo.cmo bar.cmo gee.cmo
```
This creates the bytecode file mytoplevel, containing the OCaml toplevel system, plus the code from the three .cmo files. This toplevel is directly executable and is started by:
```
./mytoplevel
```
This enters a regular toplevel loop, except that the code from foo.cmo, bar.cmo and gee.cmo is already loaded in memory, just as if you had typed:
```
#load "foo.cmo";;
#load "bar.cmo";;
#load "gee.cmo";;
```
on entrance to the toplevel. The modules Foo, Bar and Gee are not opened, though; you still have to do
```
open Foo;;
```
yourself, if this is what you wish.
###
[](#ss:ocamlmktop-options)14.5.1 Options
The following command-line options are recognized by ocamlmktop.
-cclib libname
Pass the -llibname option to the C linker when linking in “custom runtime” mode. See the corresponding option for ocamlc, in chapter [13](comp#c%3Acamlc).
-ccopt option
Pass the given option to the C compiler and linker, when linking in “custom runtime” mode. See the corresponding option for ocamlc, in chapter [13](comp#c%3Acamlc).
-custom
Link in “custom runtime” mode. See the corresponding option for ocamlc, in chapter [13](comp#c%3Acamlc).
-I directory
Add the given directory to the list of directories searched for compiled object code files (.cmo and .cma).
-o exec-file
Specify the name of the toplevel file produced by the linker. The default is a.out.
[](#s:ocamlnat)14.6 The native toplevel: ocamlnat (experimental)
------------------------------------------------------------------
This section describes a tool that is not yet officially supported but may be found useful.
OCaml code executing in the traditional toplevel system uses the bytecode interpreter. When increased performance is required, or for testing programs that will only execute correctly when compiled to native code, the *native toplevel* may be used instead.
For the majority of installations the native toplevel will not have been installed along with the rest of the OCaml toolchain. In such circumstances it will be necessary to build the OCaml distribution from source. From the built source tree of the distribution you may use make natruntop to build and execute a native toplevel. (Alternatively make ocamlnat can be used, which just performs the build step.)
If the make install command is run after having built the native toplevel then the ocamlnat program (either from the source or the installation directory) may be invoked directly rather than using make natruntop.
| programming_docs |
ocaml None
[](#s:bigarray-access)12.11 Syntax for Bigarray access
--------------------------------------------------------
(Introduced in Objective Caml 3.00)
| | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [expr](expr#expr) | ::= | ... |
| | ∣ | [expr](expr#expr) .{ [expr](expr#expr) { , [expr](expr#expr) } } |
| | ∣ | [expr](expr#expr) .{ [expr](expr#expr) { , [expr](expr#expr) } } <- [expr](expr#expr) |
|
This extension provides syntactic sugar for getting and setting elements in the arrays provided by the [Bigarray](libref/bigarray) module.
The short expressions are translated into calls to functions of the Bigarray module as described in the following table.
| | |
| --- | --- |
| expression | translation |
| [expr](expr#expr)0.{[expr](expr#expr)1} | Bigarray.Array1.get [expr](expr#expr)0 [expr](expr#expr)1 |
| [expr](expr#expr)0.{[expr](expr#expr)1} <-[expr](expr#expr) | Bigarray.Array1.set [expr](expr#expr)0 [expr](expr#expr)1 [expr](expr#expr) |
| [expr](expr#expr)0.{[expr](expr#expr)1, [expr](expr#expr)2} | Bigarray.Array2.get [expr](expr#expr)0 [expr](expr#expr)1 [expr](expr#expr)2 |
| [expr](expr#expr)0.{[expr](expr#expr)1, [expr](expr#expr)2} <-[expr](expr#expr) | Bigarray.Array2.set [expr](expr#expr)0 [expr](expr#expr)1 [expr](expr#expr)2 [expr](expr#expr) |
| [expr](expr#expr)0.{[expr](expr#expr)1, [expr](expr#expr)2, [expr](expr#expr)3} | Bigarray.Array3.get [expr](expr#expr)0 [expr](expr#expr)1 [expr](expr#expr)2 [expr](expr#expr)3 |
| [expr](expr#expr)0.{[expr](expr#expr)1, [expr](expr#expr)2, [expr](expr#expr)3} <-[expr](expr#expr) | Bigarray.Array3.set [expr](expr#expr)0 [expr](expr#expr)1 [expr](expr#expr)2 [expr](expr#expr)3 [expr](expr#expr) |
| [expr](expr#expr)0.{[expr](expr#expr)1, …, [expr](expr#expr)n} | Bigarray.Genarray.get [expr](expr#expr)0 [| [expr](expr#expr)1, … , [expr](expr#expr)n |] |
| [expr](expr#expr)0.{[expr](expr#expr)1, …, [expr](expr#expr)n} <-[expr](expr#expr) | Bigarray.Genarray.set [expr](expr#expr)0 [| [expr](expr#expr)1, … , [expr](expr#expr)n |] [expr](expr#expr) |
The last two entries are valid for any n > 3.
ocaml Chapter 28 The standard library Chapter 28 The standard library
===============================
This chapter describes the functions provided by the OCaml standard library. The modules from the standard library are automatically linked with the user’s object code files by the ocamlc command. Hence, these modules can be used in standalone programs without having to add any .cmo file on the command line for the linking phase. Similarly, in interactive use, these globals can be used in toplevel phrases without having to load any .cmo file in memory.
Unlike the core Stdlib module, submodules are not automatically “opened” when compilation starts, or when the toplevel system is launched. Hence it is necessary to use qualified identifiers to refer to the functions provided by these modules, or to add open directives.
* [Module Arg](libref/arg): parsing of command line arguments
* [Module Array](libref/array): array operations
* [Module ArrayLabels](libref/arraylabels): array operations (with labels)
* [Module Atomic](libref/atomic): atomic references
* [Module Bigarray](libref/bigarray): large, multi-dimensional, numerical arrays
* [Module Bool](libref/bool): boolean values
* [Module Buffer](libref/buffer): extensible buffers
* [Module Bytes](libref/bytes): byte sequences
* [Module BytesLabels](libref/byteslabels): byte sequences (with labels)
* [Module Callback](libref/callback): registering OCaml values with the C runtime
* [Module Char](libref/char): character operations
* [Module Complex](libref/complex): complex numbers
* [Module Condition](libref/condition): condition variables to synchronize between threads
* [Module Domain](libref/domain): Domain spawn/join and domain local variables
* [Module Digest](libref/digest): MD5 message digest
* [Module Effect](libref/effect): deep and shallow effect handlers
* [Module Either](libref/either): either values
* [Module Ephemeron](libref/ephemeron): Ephemerons and weak hash table
* [Module Filename](libref/filename): operations on file names
* [Module Float](libref/float): floating-point numbers
* [Module Format](libref/format): pretty printing
* [Module Fun](libref/fun): function values
* [Module Gc](libref/gc): memory management control and statistics; finalized values
* [Module Hashtbl](libref/hashtbl): hash tables and hash functions
* [Module In\_channel](libref/in_channel): input channels
* [Module Int](libref/int): integers
* [Module Int32](libref/int32): 32-bit integers
* [Module Int64](libref/int64): 64-bit integers
* [Module Lazy](libref/lazy): deferred computations
* [Module Lexing](libref/lexing): the run-time library for lexers generated by ocamllex
* [Module List](libref/list): list operations
* [Module ListLabels](libref/listlabels): list operations (with labels)
* [Module Map](libref/map): association tables over ordered types
* [Module Marshal](libref/marshal): marshaling of data structures
* [Module MoreLabels](libref/morelabels): include modules Hashtbl, Map and Set with labels
* [Module Mutex](libref/mutex): locks for mutual exclusion
* [Module Nativeint](libref/nativeint): processor-native integers
* [Module Oo](libref/oo): object-oriented extension
* [Module Option](libref/option): option values
* [Module Out\_channel](libref/out_channel): output channels
* [Module Parsing](libref/parsing): the run-time library for parsers generated by ocamlyacc
* [Module Printexc](libref/printexc): facilities for printing exceptions
* [Module Printf](libref/printf): formatting printing functions
* [Module Queue](libref/queue): first-in first-out queues
* [Module Random](libref/random): pseudo-random number generator (PRNG)
* [Module Result](libref/result): result values
* [Module Runtime\_events](libref/runtime_events): Runtime event tracing
* [Module Scanf](libref/scanf): formatted input functions
* [Module Seq](libref/seq): functional iterators
* [Module Set](libref/set): sets over ordered types
* [Module Semaphore](libref/semaphore): semaphores, another thread synchronization mechanism
* [Module Stack](libref/stack): last-in first-out stacks
* [Module StdLabels](libref/stdlabels): include modules Array, List and String with labels
* [Module String](libref/string): string operations
* [Module StringLabels](libref/stringlabels): string operations (with labels)
* [Module Sys](libref/sys): system interface
* [Module Uchar](libref/uchar): Unicode characters
* [Module Unit](libref/unit): unit values
* [Module Weak](libref/weak): arrays of weak pointers
ocaml None
[](#s:attributes)12.12 Attributes
-----------------------------------
* [12.12.1 Built-in attributes](attributes#ss%3Abuiltin-attributes)
(Introduced in OCaml 4.02, infix notations for constructs other than expressions added in 4.03)
Attributes are “decorations” of the syntax tree which are mostly ignored by the type-checker but can be used by external tools. An attribute is made of an identifier and a payload, which can be a structure, a type expression (prefixed with :), a signature (prefixed with :) or a pattern (prefixed with ?) optionally followed by a when clause:
| | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| attr-id | ::= | [lowercase-ident](lex#lowercase-ident) |
| | ∣ | [capitalized-ident](lex#capitalized-ident) |
| | ∣ | [attr-id](#attr-id) . [attr-id](#attr-id) |
| |
| attr-payload | ::= | [ [module-items](modules#module-items) ] |
| | ∣ | : [typexpr](types#typexpr) |
| | ∣ | : [ [specification](modtypes#specification) ] |
| | ∣ | ? [pattern](patterns#pattern) [when [expr](expr#expr)] |
| |
|
The first form of attributes is attached with a postfix notation on “algebraic” categories:
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| attribute | ::= | [@ [attr-id](#attr-id) [attr-payload](#attr-payload) ] |
| |
| [expr](expr#expr) | ::= | ... |
| | ∣ | [expr](expr#expr) [attribute](#attribute) |
| |
| [typexpr](types#typexpr) | ::= | ... |
| | ∣ | [typexpr](types#typexpr) [attribute](#attribute) |
| |
| [pattern](patterns#pattern) | ::= | ... |
| | ∣ | [pattern](patterns#pattern) [attribute](#attribute) |
| |
| [module-expr](modules#module-expr) | ::= | ... |
| | ∣ | [module-expr](modules#module-expr) [attribute](#attribute) |
| |
| [module-type](modtypes#module-type) | ::= | ... |
| | ∣ | [module-type](modtypes#module-type) [attribute](#attribute) |
| |
| class-expr | ::= | ... |
| | ∣ | [class-expr](classes#class-expr) [attribute](#attribute) |
| |
| class-type | ::= | ... |
| | ∣ | [class-type](classes#class-type) [attribute](#attribute) |
| |
|
This form of attributes can also be inserted after the `[tag-name](names#tag-name) in polymorphic variant type expressions ([tag-spec-first](types#tag-spec-first), [tag-spec](types#tag-spec), [tag-spec-full](types#tag-spec-full)) or after the [method-name](names#method-name) in [method-type](types#method-type).
The same syntactic form is also used to attach attributes to labels and constructors in type declarations:
| | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| field-decl | ::= | [mutable] [field-name](names#field-name) : [poly-typexpr](types#poly-typexpr) { [attribute](#attribute) } |
| |
| [constr-decl](typedecl#constr-decl) | ::= | ([constr-name](names#constr-name) ∣ ()) [ of [constr-args](typedecl#constr-args) ] { [attribute](#attribute) } |
| |
|
Note: when a label declaration is followed by a semi-colon, attributes can also be put after the semi-colon (in which case they are merged to those specified before).
The second form of attributes are attached to “blocks” such as type declarations, class fields, etc:
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| item-attribute | ::= | [@@ [attr-id](#attr-id) [attr-payload](#attr-payload) ] |
| |
| typedef | ::= | ... |
| | ∣ | [typedef](typedecl#typedef) [item-attribute](#item-attribute) |
| |
| exception-definition | ::= | exception [constr-decl](typedecl#constr-decl) |
| | ∣ | exception [constr-name](names#constr-name) = [constr](names#constr) |
| |
| module-items | ::= | [;;] ( [definition](modules#definition) ∣ [expr](expr#expr) { [item-attribute](#item-attribute) } ) { [;;] [definition](modules#definition) ∣ ;; [expr](expr#expr) { [item-attribute](#item-attribute) } } [;;] |
| |
| class-binding | ::= | ... |
| | ∣ | [class-binding](classes#class-binding) [item-attribute](#item-attribute) |
| |
| class-spec | ::= | ... |
| | ∣ | [class-spec](classes#class-spec) [item-attribute](#item-attribute) |
| |
| classtype-def | ::= | ... |
| | ∣ | [classtype-def](classes#classtype-def) [item-attribute](#item-attribute) |
| |
| [definition](modules#definition) | ::= | let [rec] [let-binding](expr#let-binding) { and [let-binding](expr#let-binding) } |
| | ∣ | external [value-name](names#value-name) : [typexpr](types#typexpr) = [external-declaration](intfc#external-declaration) { [item-attribute](#item-attribute) } |
| | ∣ | [type-definition](typedecl#type-definition) |
| | ∣ | [exception-definition](typedecl#exception-definition) { [item-attribute](#item-attribute) } |
| | ∣ | [class-definition](classes#class-definition) |
| | ∣ | [classtype-definition](classes#classtype-definition) |
| | ∣ | module [module-name](names#module-name) { ( [module-name](names#module-name) : [module-type](modtypes#module-type) ) } [ : [module-type](modtypes#module-type) ] = [module-expr](modules#module-expr) { [item-attribute](#item-attribute) } |
| | ∣ | module type [modtype-name](names#modtype-name) = [module-type](modtypes#module-type) { [item-attribute](#item-attribute) } |
| | ∣ | open [module-path](names#module-path) { [item-attribute](#item-attribute) } |
| | ∣ | include [module-expr](modules#module-expr) { [item-attribute](#item-attribute) } |
| | ∣ | module rec [module-name](names#module-name) : [module-type](modtypes#module-type) = [module-expr](modules#module-expr) { [item-attribute](#item-attribute) } { and [module-name](names#module-name) : [module-type](modtypes#module-type) = [module-expr](modules#module-expr) { [item-attribute](#item-attribute) } } |
| |
| [specification](modtypes#specification) | ::= | val [value-name](names#value-name) : [typexpr](types#typexpr) { [item-attribute](#item-attribute) } |
| | ∣ | external [value-name](names#value-name) : [typexpr](types#typexpr) = [external-declaration](intfc#external-declaration) { [item-attribute](#item-attribute) } |
| | ∣ | [type-definition](typedecl#type-definition) |
| | ∣ | exception [constr-decl](typedecl#constr-decl) { [item-attribute](#item-attribute) } |
| | ∣ | [class-specification](classes#class-specification) |
| | ∣ | [classtype-definition](classes#classtype-definition) |
| | ∣ | module [module-name](names#module-name) : [module-type](modtypes#module-type) { [item-attribute](#item-attribute) } |
| | ∣ | module [module-name](names#module-name) { ( [module-name](names#module-name) : [module-type](modtypes#module-type) ) } : [module-type](modtypes#module-type) { [item-attribute](#item-attribute) } |
| | ∣ | module type [modtype-name](names#modtype-name) { [item-attribute](#item-attribute) } |
| | ∣ | module type [modtype-name](names#modtype-name) = [module-type](modtypes#module-type) { [item-attribute](#item-attribute) } |
| | ∣ | open [module-path](names#module-path) { [item-attribute](#item-attribute) } |
| | ∣ | include [module-type](modtypes#module-type) { [item-attribute](#item-attribute) } |
| |
| class-field-spec | ::= | ... |
| | ∣ | [class-field-spec](classes#class-field-spec) [item-attribute](#item-attribute) |
| |
| [class-field](classes#class-field) | ::= | ... |
| | ∣ | [class-field](classes#class-field) [item-attribute](#item-attribute) |
| |
|
A third form of attributes appears as stand-alone structure or signature items in the module or class sub-languages. They are not attached to any specific node in the syntax tree:
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| floating-attribute | ::= | [@@@ [attr-id](#attr-id) [attr-payload](#attr-payload) ] |
| |
| [definition](modules#definition) | ::= | ... |
| | ∣ | [floating-attribute](#floating-attribute) |
| |
| [specification](modtypes#specification) | ::= | ... |
| | ∣ | [floating-attribute](#floating-attribute) |
| |
| class-field-spec | ::= | ... |
| | ∣ | [floating-attribute](#floating-attribute) |
| |
| [class-field](classes#class-field) | ::= | ... |
| | ∣ | [floating-attribute](#floating-attribute) |
| |
|
(Note: contrary to what the grammar above describes, item-attributes cannot be attached to these floating attributes in [class-field-spec](classes#class-field-spec) and [class-field](classes#class-field).)
It is also possible to specify attributes using an infix syntax. For instance:
```
let[@foo] x = 2 in x + 1 === (let x = 2 [@@foo] in x + 1)
begin[@foo][@bar x] ... end === (begin ... end)[@foo][@bar x]
module[@foo] M = ... === module M = ... [@@foo]
type[@foo] t = T === type t = T [@@foo]
method[@foo] m = ... === method m = ... [@@foo]
```
For let, the attributes are applied to each bindings:
```
let[@foo] x = 2 and y = 3 in x + y === (let x = 2 [@@foo] and y = 3 in x + y)
let[@foo] x = 2
and[@bar] y = 3 in x + y === (let x = 2 [@@foo] and y = 3 [@@bar] in x + y)
```
###
[](#ss:builtin-attributes)12.12.1 Built-in attributes
Some attributes are understood by the type-checker:
* “ocaml.warning” or “warning”, with a string literal payload. This can be used as floating attributes in a signature/structure/object/object type. The string is parsed and has the same effect as the -w command-line option, in the scope between the attribute and the end of the current signature/structure/object/object type. The attribute can also be attached to any kind of syntactic item which support attributes (such as an expression, or a type expression) in which case its scope is limited to that item. Note that it is not well-defined which scope is used for a specific warning. This is implementation dependent and can change between versions. Some warnings are even completely outside the control of “ocaml.warning” (for instance, warnings 1, 2, 14, 29 and 50).
* “ocaml.warnerror” or “warnerror”, with a string literal payload. Same as “ocaml.warning”, for the -warn-error command-line option.
* “ocaml.alert” or “alert”: see section [12.21](alerts#s%3Aalerts).
* “ocaml.deprecated” or “deprecated”: alias for the “deprecated” alert, see section [12.21](alerts#s%3Aalerts).
* “ocaml.deprecated\_mutable” or “deprecated\_mutable”. Can be applied to a mutable record label. If the label is later used to modify the field (with “expr.l <- expr”), the “deprecated” alert will be triggered. If the payload of the attribute is a string literal, the alert message includes this text.
* “ocaml.ppwarning” or “ppwarning”, in any context, with a string literal payload. The text is reported as warning (22) by the compiler (currently, the warning location is the location of the string payload). This is mostly useful for preprocessors which need to communicate warnings to the user. This could also be used to mark explicitly some code location for further inspection.
* “ocaml.warn\_on\_literal\_pattern” or “warn\_on\_literal\_pattern” annotate constructors in type definition. A warning (52) is then emitted when this constructor is pattern matched with a constant literal as argument. This attribute denotes constructors whose argument is purely informative and may change in the future. Therefore, pattern matching on this argument with a constant literal is unreliable. For instance, all built-in exception constructors are marked as “warn\_on\_literal\_pattern”. Note that, due to an implementation limitation, this warning (52) is only triggered for single argument constructor.
* “ocaml.tailcall” or “tailcall” can be applied to function application in order to check that the call is tailcall optimized. If it it not the case, a warning (51) is emitted.
* “ocaml.inline” or “inline” take either “never”, “always” or nothing as payload on a function or functor definition. If no payload is provided, the default value is “always”. This payload controls when applications of the annotated functions should be inlined.
* “ocaml.inlined” or “inlined” can be applied to any function or functor application to check that the call is inlined by the compiler. If the call is not inlined, a warning (55) is emitted.
* “ocaml.noalloc”, “ocaml.unboxed”and “ocaml.untagged” or “noalloc”, “unboxed” and “untagged” can be used on external definitions to obtain finer control over the C-to-OCaml interface. See [22.11](intfc#s%3AC-cheaper-call) for more details.
* “ocaml.immediate” or “immediate” applied on an abstract type mark the type as having a non-pointer implementation (e.g. “int”, “bool”, “char” or enumerated types). Mutation of these immediate types does not activate the garbage collector’s write barrier, which can significantly boost performance in programs relying heavily on mutable state.
* “ocaml.immediate64” or “immediate64” applied on an abstract type mark the type as having a non-pointer implementation on 64 bit platforms. No assumption is made on other platforms. In order to produce a type with the “immediate64“ attribute, one must use “Sys.Immediate64.Make“ functor.
* ocaml.unboxed or unboxed can be used on a type definition if the type is a single-field record or a concrete type with a single constructor that has a single argument. It tells the compiler to optimize the representation of the type by removing the block that represents the record or the constructor (i.e. a value of this type is physically equal to its argument). In the case of GADTs, an additional restriction applies: the argument must not be an existential variable, represented by an existential type variable, or an abstract type constructor applied to an existential type variable.
* ocaml.boxed or boxed can be used on type definitions to mean the opposite of ocaml.unboxed: keep the unoptimized representation of the type. When there is no annotation, the default is currently boxed but it may change in the future.
* ocaml.local or local take either never, always, maybe or nothing as payload on a function definition. If no payload is provided, the default is always. The attribute controls an optimization which consists in compiling a function into a static continuation. Contrary to inlining, this optimization does not duplicate the function’s body. This is possible when all references to the function are full applications, all sharing the same continuation (for instance, the returned value of several branches of a pattern matching). never disables the optimization, always asserts that the optimization applies (otherwise a warning 55 is emitted) and maybe lets the optimization apply when possible (this is the default behavior when the attribute is not specified). The optimization is implicitly disabled when using the bytecode compiler in debug mode (-g), and for functions marked with an ocaml.inline always or ocaml.unrolled attribute which supersede ocaml.local.
```
module X = struct
[@@@warning "+9"] (* locally enable warning 9 in this structure *)
…
end
[@@deprecated "Please use module 'Y' instead."]
let x = begin[@warning "+9"] […] end
type t = A | B
[@@deprecated "Please use type 's' instead."]
```
```
let fires_warning_22 x =
assert (x >= 0) [@ppwarning "TODO: remove this later"]
Warning 22 [preprocessor]: TODO: remove this later
```
```
let rec is_a_tail_call = function
| [] -> ()
| _ :: q -> (is_a_tail_call[@tailcall]) q
let rec not_a_tail_call = function
| [] -> []
| x :: q -> x :: (not_a_tail_call[@tailcall]) q
Warning 51 [wrong-tailcall-expectation]: expected tailcall
```
```
let f x = x [@@inline]
let () = (f[@inlined]) ()
```
```
type fragile =
| Int of int [@warn_on_literal_pattern]
| String of string [@warn_on_literal_pattern]
```
```
let fragile_match_1 = function
| Int 0 -> ()
| _ -> ()
Warning 52 [fragile-literal-pattern]: Code should not depend on the actual values of
this constructor's arguments. They are only for information
and may change in future versions. (See manual section 13.5)
val fragile_match_1 : fragile -> unit =
```
```
let fragile_match_2 = function
| String "constant" -> ()
| _ -> ()
Warning 52 [fragile-literal-pattern]: Code should not depend on the actual values of
this constructor's arguments. They are only for information
and may change in future versions. (See manual section 13.5)
val fragile_match_2 : fragile -> unit =
```
```
module Immediate: sig
type t [@@immediate]
val x: t ref
end = struct
type t = A | B
let x = ref A
end
```
```
module Int_or_int64 : sig
type t [@@immediate64]
val zero : t
val one : t
val add : t -> t -> t
end = struct
include Sys.Immediate64.Make(Int)(Int64)
module type S = sig
val zero : t
val one : t
val add : t -> t -> t
end
let impl : (module S) =
match repr with
| Immediate ->
(module Int : S)
| Non_immediate ->
(module Int64 : S)
include (val impl : S)
end
```
| programming_docs |
ocaml Chapter 3 Objects in OCaml Chapter 3 Objects in OCaml
==========================
* [3.1 Classes and objects](objectexamples#s%3Aclasses-and-objects)
* [3.2 Immediate objects](objectexamples#s%3Aimmediate-objects)
* [3.3 Reference to self](objectexamples#s%3Areference-to-self)
* [3.4 Initializers](objectexamples#s%3Ainitializers)
* [3.5 Virtual methods](objectexamples#s%3Avirtual-methods)
* [3.6 Private methods](objectexamples#s%3Aprivate-methods)
* [3.7 Class interfaces](objectexamples#s%3Aclass-interfaces)
* [3.8 Inheritance](objectexamples#s%3Ainheritance)
* [3.9 Multiple inheritance](objectexamples#s%3Amultiple-inheritance)
* [3.10 Parameterized classes](objectexamples#s%3Aparameterized-classes)
* [3.11 Polymorphic methods](objectexamples#s%3Apolymorphic-methods)
* [3.12 Using coercions](objectexamples#s%3Ausing-coercions)
* [3.13 Functional objects](objectexamples#s%3Afunctional-objects)
* [3.14 Cloning objects](objectexamples#s%3Acloning-objects)
* [3.15 Recursive classes](objectexamples#s%3Arecursive-classes)
* [3.16 Binary methods](objectexamples#s%3Abinary-methods)
* [3.17 Friends](objectexamples#s%3Afriends)
(Chapter written by Jérôme Vouillon, Didier Rémy and Jacques Garrigue)
This chapter gives an overview of the object-oriented features of OCaml.
Note that the relationship between object, class and type in OCaml is different than in mainstream object-oriented languages such as Java and C++, so you shouldn’t assume that similar keywords mean the same thing. Object-oriented features are used much less frequently in OCaml than in those languages. OCaml has alternatives that are often more appropriate, such as modules and functors. Indeed, many OCaml programs do not use objects at all.
[](#s:classes-and-objects)3.1 Classes and objects
---------------------------------------------------
The class point below defines one instance variable x and two methods get\_x and move. The initial value of the instance variable is 0. The variable x is declared mutable, so the method move can change its value.
```
# class point =
object
val mutable x = 0
method get_x = x
method move d = x <- x + d
end;;
class point :
object val mutable x : int method get_x : int method move : int -> unit end
```
We now create a new point p, instance of the point class.
```
# let p = new point;;
val p : point =
```
Note that the type of p is point. This is an abbreviation automatically defined by the class definition above. It stands for the object type <get\_x : int; move : int -> unit>, listing the methods of class point along with their types.
We now invoke some methods of p:
```
# p#get_x;;
- : int = 0
```
```
# p#move 3;;
- : unit = ()
```
```
# p#get_x;;
- : int = 3
```
The evaluation of the body of a class only takes place at object creation time. Therefore, in the following example, the instance variable x is initialized to different values for two different objects.
```
# let x0 = ref 0;;
val x0 : int ref = {contents = 0}
```
```
# class point =
object
val mutable x = incr x0; !x0
method get_x = x
method move d = x <- x + d
end;;
class point :
object val mutable x : int method get_x : int method move : int -> unit end
```
```
# new point#get_x;;
- : int = 1
```
```
# new point#get_x;;
- : int = 2
```
The class point can also be abstracted over the initial values of the x coordinate.
```
# class point = fun x_init ->
object
val mutable x = x_init
method get_x = x
method move d = x <- x + d
end;;
class point :
int ->
object val mutable x : int method get_x : int method move : int -> unit end
```
Like in function definitions, the definition above can be abbreviated as:
```
# class point x_init =
object
val mutable x = x_init
method get_x = x
method move d = x <- x + d
end;;
class point :
int ->
object val mutable x : int method get_x : int method move : int -> unit end
```
An instance of the class point is now a function that expects an initial parameter to create a point object:
```
# new point;;
- : int -> point =
```
```
# let p = new point 7;;
val p : point =
```
The parameter x\_init is, of course, visible in the whole body of the definition, including methods. For instance, the method get\_offset in the class below returns the position of the object relative to its initial position.
```
# class point x_init =
object
val mutable x = x_init
method get_x = x
method get_offset = x - x_init
method move d = x <- x + d
end;;
class point :
int ->
object
val mutable x : int
method get_offset : int
method get_x : int
method move : int -> unit
end
```
Expressions can be evaluated and bound before defining the object body of the class. This is useful to enforce invariants. For instance, points can be automatically adjusted to the nearest point on a grid, as follows:
```
# class adjusted_point x_init =
let origin = (x_init / 10) * 10 in
object
val mutable x = origin
method get_x = x
method get_offset = x - origin
method move d = x <- x + d
end;;
class adjusted_point :
int ->
object
val mutable x : int
method get_offset : int
method get_x : int
method move : int -> unit
end
```
(One could also raise an exception if the x\_init coordinate is not on the grid.) In fact, the same effect could be obtained here by calling the definition of class point with the value of the origin.
```
# class adjusted_point x_init = point ((x_init / 10) * 10);;
class adjusted_point : int -> point
```
An alternate solution would have been to define the adjustment in a special allocation function:
```
# let new_adjusted_point x_init = new point ((x_init / 10) * 10);;
val new_adjusted_point : int -> point =
```
However, the former pattern is generally more appropriate, since the code for adjustment is part of the definition of the class and will be inherited.
This ability provides class constructors as can be found in other languages. Several constructors can be defined this way to build objects of the same class but with different initialization patterns; an alternative is to use initializers, as described below in section [3.4](#s%3Ainitializers).
[](#s:immediate-objects)3.2 Immediate objects
-----------------------------------------------
There is another, more direct way to create an object: create it without going through a class.
The syntax is exactly the same as for class expressions, but the result is a single object rather than a class. All the constructs described in the rest of this section also apply to immediate objects.
```
# let p =
object
val mutable x = 0
method get_x = x
method move d = x <- x + d
end;;
val p : < get_x : int; move : int -> unit > =
```
```
# p#get_x;;
- : int = 0
```
```
# p#move 3;;
- : unit = ()
```
```
# p#get_x;;
- : int = 3
```
Unlike classes, which cannot be defined inside an expression, immediate objects can appear anywhere, using variables from their environment.
```
# let minmax x y =
if x < y then object method min = x method max = y end
else object method min = y method max = x end;;
val minmax : 'a -> 'a -> < max : 'a; min : 'a > =
```
Immediate objects have two weaknesses compared to classes: their types are not abbreviated, and you cannot inherit from them. But these two weaknesses can be advantages in some situations, as we will see in sections [3.3](#s%3Areference-to-self) and [3.10](#s%3Aparameterized-classes).
[](#s:reference-to-self)3.3 Reference to self
-----------------------------------------------
A method or an initializer can invoke methods on self (that is, the current object). For that, self must be explicitly bound, here to the variable s (s could be any identifier, even though we will often choose the name self.)
```
# class printable_point x_init =
object (s)
val mutable x = x_init
method get_x = x
method move d = x <- x + d
method print = print_int s#get_x
end;;
class printable_point :
int ->
object
val mutable x : int
method get_x : int
method move : int -> unit
method print : unit
end
```
```
# let p = new printable_point 7;;
val p : printable_point =
```
```
# p#print;;
7- : unit = ()
```
Dynamically, the variable s is bound at the invocation of a method. In particular, when the class printable\_point is inherited, the variable s will be correctly bound to the object of the subclass.
A common problem with self is that, as its type may be extended in subclasses, you cannot fix it in advance. Here is a simple example.
```
# let ints = ref [];;
val ints : '_weak1 list ref = {contents = []}
```
```
# class my_int =
object (self)
method n = 1
method register = ints := self :: !ints
end ;;
Error: This expression has type < n : int; register : 'a; .. >
but an expression was expected of type 'weak1
Self type cannot escape its class
```
You can ignore the first two lines of the error message. What matters is the last one: putting self into an external reference would make it impossible to extend it through inheritance. We will see in section [3.12](#s%3Ausing-coercions) a workaround to this problem. Note however that, since immediate objects are not extensible, the problem does not occur with them.
```
# let my_int =
object (self)
method n = 1
method register = ints := self :: !ints
end;;
val my_int : < n : int; register : unit > =
```
[](#s:initializers)3.4 Initializers
-------------------------------------
Let-bindings within class definitions are evaluated before the object is constructed. It is also possible to evaluate an expression immediately after the object has been built. Such code is written as an anonymous hidden method called an initializer. Therefore, it can access self and the instance variables.
```
# class printable_point x_init =
let origin = (x_init / 10) * 10 in
object (self)
val mutable x = origin
method get_x = x
method move d = x <- x + d
method print = print_int self#get_x
initializer print_string "new point at "; self#print; print_newline ()
end;;
class printable_point :
int ->
object
val mutable x : int
method get_x : int
method move : int -> unit
method print : unit
end
```
```
# let p = new printable_point 17;;
new point at 10
val p : printable_point =
```
Initializers cannot be overridden. On the contrary, all initializers are evaluated sequentially. Initializers are particularly useful to enforce invariants. Another example can be seen in section [8.1](advexamples#s%3Aextended-bank-accounts).
[](#s:virtual-methods)3.5 Virtual methods
-------------------------------------------
It is possible to declare a method without actually defining it, using the keyword virtual. This method will be provided later in subclasses. A class containing virtual methods must be flagged virtual, and cannot be instantiated (that is, no object of this class can be created). It still defines type abbreviations (treating virtual methods as other methods.)
```
# class virtual abstract_point x_init =
object (self)
method virtual get_x : int
method get_offset = self#get_x - x_init
method virtual move : int -> unit
end;;
class virtual abstract_point :
int ->
object
method get_offset : int
method virtual get_x : int
method virtual move : int -> unit
end
```
```
# class point x_init =
object
inherit abstract_point x_init
val mutable x = x_init
method get_x = x
method move d = x <- x + d
end;;
class point :
int ->
object
val mutable x : int
method get_offset : int
method get_x : int
method move : int -> unit
end
```
Instance variables can also be declared as virtual, with the same effect as with methods.
```
# class virtual abstract_point2 =
object
val mutable virtual x : int
method move d = x <- x + d
end;;
class virtual abstract_point2 :
object val mutable virtual x : int method move : int -> unit end
```
```
# class point2 x_init =
object
inherit abstract_point2
val mutable x = x_init
method get_offset = x - x_init
end;;
class point2 :
int ->
object
val mutable x : int
method get_offset : int
method move : int -> unit
end
```
[](#s:private-methods)3.6 Private methods
-------------------------------------------
Private methods are methods that do not appear in object interfaces. They can only be invoked from other methods of the same object.
```
# class restricted_point x_init =
object (self)
val mutable x = x_init
method get_x = x
method private move d = x <- x + d
method bump = self#move 1
end;;
class restricted_point :
int ->
object
val mutable x : int
method bump : unit
method get_x : int
method private move : int -> unit
end
```
```
# let p = new restricted_point 0;;
val p : restricted_point =
```
```
# p#move 10 ;;
Error: This expression has type restricted_point
It has no method move
```
```
# p#bump;;
- : unit = ()
```
Note that this is not the same thing as private and protected methods in Java or C++, which can be called from other objects of the same class. This is a direct consequence of the independence between types and classes in OCaml: two unrelated classes may produce objects of the same type, and there is no way at the type level to ensure that an object comes from a specific class. However a possible encoding of friend methods is given in section [3.17](#s%3Afriends).
Private methods are inherited (they are by default visible in subclasses), unless they are hidden by signature matching, as described below.
Private methods can be made public in a subclass.
```
# class point_again x =
object (self)
inherit restricted_point x
method virtual move : _
end;;
class point_again :
int ->
object
val mutable x : int
method bump : unit
method get_x : int
method move : int -> unit
end
```
The annotation virtual here is only used to mention a method without providing its definition. Since we didn’t add the private annotation, this makes the method public, keeping the original definition.
An alternative definition is
```
# class point_again x =
object (self : < move : _; ..> )
inherit restricted_point x
end;;
class point_again :
int ->
object
val mutable x : int
method bump : unit
method get_x : int
method move : int -> unit
end
```
The constraint on self’s type is requiring a public move method, and this is sufficient to override private.
One could think that a private method should remain private in a subclass. However, since the method is visible in a subclass, it is always possible to pick its code and define a method of the same name that runs that code, so yet another (heavier) solution would be:
```
# class point_again x =
object
inherit restricted_point x as super
method move = super#move
end;;
class point_again :
int ->
object
val mutable x : int
method bump : unit
method get_x : int
method move : int -> unit
end
```
Of course, private methods can also be virtual. Then, the keywords must appear in this order: method private virtual.
[](#s:class-interfaces)3.7 Class interfaces
---------------------------------------------
Class interfaces are inferred from class definitions. They may also be defined directly and used to restrict the type of a class. Like class declarations, they also define a new type abbreviation.
```
# class type restricted_point_type =
object
method get_x : int
method bump : unit
end;;
class type restricted_point_type =
object method bump : unit method get_x : int end
```
```
# fun (x : restricted_point_type) -> x;;
- : restricted_point_type -> restricted_point_type =
```
In addition to program documentation, class interfaces can be used to constrain the type of a class. Both concrete instance variables and concrete private methods can be hidden by a class type constraint. Public methods and virtual members, however, cannot.
```
# class restricted_point' x = (restricted_point x : restricted_point_type);;
class restricted_point' : int -> restricted_point_type
```
Or, equivalently:
```
# class restricted_point' = (restricted_point : int -> restricted_point_type);;
class restricted_point' : int -> restricted_point_type
```
The interface of a class can also be specified in a module signature, and used to restrict the inferred signature of a module.
```
# module type POINT = sig
class restricted_point' : int ->
object
method get_x : int
method bump : unit
end
end;;
module type POINT =
sig
class restricted_point' :
int -> object method bump : unit method get_x : int end
end
```
```
# module Point : POINT = struct
class restricted_point' = restricted_point
end;;
module Point : POINT
```
[](#s:inheritance)3.8 Inheritance
-----------------------------------
We illustrate inheritance by defining a class of colored points that inherits from the class of points. This class has all instance variables and all methods of class point, plus a new instance variable c and a new method color.
```
# class colored_point x (c : string) =
object
inherit point x
val c = c
method color = c
end;;
class colored_point :
int ->
string ->
object
val c : string
val mutable x : int
method color : string
method get_offset : int
method get_x : int
method move : int -> unit
end
```
```
# let p' = new colored_point 5 "red";;
val p' : colored_point =
```
```
# p'#get_x, p'#color;;
- : int * string = (5, "red")
```
A point and a colored point have incompatible types, since a point has no method color. However, the function get\_x below is a generic function applying method get\_x to any object p that has this method (and possibly some others, which are represented by an ellipsis in the type). Thus, it applies to both points and colored points.
```
# let get_succ_x p = p#get_x + 1;;
val get_succ_x : < get_x : int; .. > -> int =
```
```
# get_succ_x p + get_succ_x p';;
- : int = 8
```
Methods need not be declared previously, as shown by the example:
```
# let set_x p = p#set_x;;
val set_x : < set_x : 'a; .. > -> 'a =
```
```
# let incr p = set_x p (get_succ_x p);;
val incr : < get_x : int; set_x : int -> 'a; .. > -> 'a =
```
[](#s:multiple-inheritance)3.9 Multiple inheritance
-----------------------------------------------------
Multiple inheritance is allowed. Only the last definition of a method is kept: the redefinition in a subclass of a method that was visible in the parent class overrides the definition in the parent class. Previous definitions of a method can be reused by binding the related ancestor. Below, super is bound to the ancestor printable\_point. The name super is a pseudo value identifier that can only be used to invoke a super-class method, as in super#print.
```
# class printable_colored_point y c =
object (self)
val c = c
method color = c
inherit printable_point y as super
method! print =
print_string "(";
super#print;
print_string ", ";
print_string (self#color);
print_string ")"
end;;
class printable_colored_point :
int ->
string ->
object
val c : string
val mutable x : int
method color : string
method get_x : int
method move : int -> unit
method print : unit
end
```
```
# let p' = new printable_colored_point 17 "red";;
new point at (10, red)
val p' : printable_colored_point =
```
```
# p'#print;;
(10, red)- : unit = ()
```
A private method that has been hidden in the parent class is no longer visible, and is thus not overridden. Since initializers are treated as private methods, all initializers along the class hierarchy are evaluated, in the order they are introduced.
Note that for clarity’s sake, the method print is explicitly marked as overriding another definition by annotating the method keyword with an exclamation mark !. If the method print were not overriding the print method of printable\_point, the compiler would raise an error:
```
# object
method! m = ()
end;;
Error: The method `m' has no previous definition
```
This explicit overriding annotation also works for val and inherit:
```
# class another_printable_colored_point y c c' =
object (self)
inherit printable_point y
inherit! printable_colored_point y c
val! c = c'
end;;
class another_printable_colored_point :
int ->
string ->
string ->
object
val c : string
val mutable x : int
method color : string
method get_x : int
method move : int -> unit
method print : unit
end
```
[](#s:parameterized-classes)3.10 Parameterized classes
--------------------------------------------------------
Reference cells can be implemented as objects. The naive definition fails to typecheck:
```
# class oref x_init =
object
val mutable x = x_init
method get = x
method set y = x <- y
end;;
Error: Some type variables are unbound in this type:
class oref :
'a ->
object
val mutable x : 'a
method get : 'a
method set : 'a -> unit
end
The method get has type 'a where 'a is unbound
```
The reason is that at least one of the methods has a polymorphic type (here, the type of the value stored in the reference cell), thus either the class should be parametric, or the method type should be constrained to a monomorphic type. A monomorphic instance of the class could be defined by:
```
# class oref (x_init:int) =
object
val mutable x = x_init
method get = x
method set y = x <- y
end;;
class oref :
int ->
object val mutable x : int method get : int method set : int -> unit end
```
Note that since immediate objects do not define a class type, they have no such restriction.
```
# let new_oref x_init =
object
val mutable x = x_init
method get = x
method set y = x <- y
end;;
val new_oref : 'a -> < get : 'a; set : 'a -> unit > =
```
On the other hand, a class for polymorphic references must explicitly list the type parameters in its declaration. Class type parameters are listed between [ and ]. The type parameters must also be bound somewhere in the class body by a type constraint.
```
# class ['a] oref x_init =
object
val mutable x = (x_init : 'a)
method get = x
method set y = x <- y
end;;
class ['a] oref :
'a -> object val mutable x : 'a method get : 'a method set : 'a -> unit end
```
```
# let r = new oref 1 in r#set 2; (r#get);;
- : int = 2
```
The type parameter in the declaration may actually be constrained in the body of the class definition. In the class type, the actual value of the type parameter is displayed in the constraint clause.
```
# class ['a] oref_succ (x_init:'a) =
object
val mutable x = x_init + 1
method get = x
method set y = x <- y
end;;
class ['a] oref_succ :
'a ->
object
constraint 'a = int
val mutable x : int
method get : int
method set : int -> unit
end
```
Let us consider a more complex example: define a circle, whose center may be any kind of point. We put an additional type constraint in method move, since no free variables must remain unaccounted for by the class type parameters.
```
# class ['a] circle (c : 'a) =
object
val mutable center = c
method center = center
method set_center c = center <- c
method move = (center#move : int -> unit)
end;;
class ['a] circle :
'a ->
object
constraint 'a = < move : int -> unit; .. >
val mutable center : 'a
method center : 'a
method move : int -> unit
method set_center : 'a -> unit
end
```
An alternate definition of circle, using a constraint clause in the class definition, is shown below. The type #point used below in the constraint clause is an abbreviation produced by the definition of class point. This abbreviation unifies with the type of any object belonging to a subclass of class point. It actually expands to < get\_x : int; move : int -> unit; .. >. This leads to the following alternate definition of circle, which has slightly stronger constraints on its argument, as we now expect center to have a method get\_x.
```
# class ['a] circle (c : 'a) =
object
constraint 'a = #point
val mutable center = c
method center = center
method set_center c = center <- c
method move = center#move
end;;
class ['a] circle :
'a ->
object
constraint 'a = #point
val mutable center : 'a
method center : 'a
method move : int -> unit
method set_center : 'a -> unit
end
```
The class colored\_circle is a specialized version of class circle that requires the type of the center to unify with #colored\_point, and adds a method color. Note that when specializing a parameterized class, the instance of type parameter must always be explicitly given. It is again written between [ and ].
```
# class ['a] colored_circle c =
object
constraint 'a = #colored_point
inherit ['a] circle c
method color = center#color
end;;
class ['a] colored_circle :
'a ->
object
constraint 'a = #colored_point
val mutable center : 'a
method center : 'a
method color : string
method move : int -> unit
method set_center : 'a -> unit
end
```
[](#s:polymorphic-methods)3.11 Polymorphic methods
----------------------------------------------------
While parameterized classes may be polymorphic in their contents, they are not enough to allow polymorphism of method use.
A classical example is defining an iterator.
```
# List.fold_left;;
- : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a =
```
```
# class ['a] intlist (l : int list) =
object
method empty = (l = [])
method fold f (accu : 'a) = List.fold_left f accu l
end;;
class ['a] intlist :
int list ->
object method empty : bool method fold : ('a -> int -> 'a) -> 'a -> 'a end
```
At first look, we seem to have a polymorphic iterator, however this does not work in practice.
```
# let l = new intlist [1; 2; 3];;
val l : '_weak2 intlist =
```
```
# l#fold (fun x y -> x+y) 0;;
- : int = 6
```
```
# l;;
- : int intlist =
```
```
# l#fold (fun s x -> s ^ Int.to_string x ^ " ") "" ;;
Error: This expression has type int but an expression was expected of type
string
```
Our iterator works, as shows its first use for summation. However, since objects themselves are not polymorphic (only their constructors are), using the fold method fixes its type for this individual object. Our next attempt to use it as a string iterator fails.
The problem here is that quantification was wrongly located: it is not the class we want to be polymorphic, but the fold method. This can be achieved by giving an explicitly polymorphic type in the method definition.
```
# class intlist (l : int list) =
object
method empty = (l = [])
method fold : 'a. ('a -> int -> 'a) -> 'a -> 'a =
fun f accu -> List.fold_left f accu l
end;;
class intlist :
int list ->
object method empty : bool method fold : ('a -> int -> 'a) -> 'a -> 'a end
```
```
# let l = new intlist [1; 2; 3];;
val l : intlist =
```
```
# l#fold (fun x y -> x+y) 0;;
- : int = 6
```
```
# l#fold (fun s x -> s ^ Int.to_string x ^ " ") "";;
- : string = "1 2 3 "
```
As you can see in the class type shown by the compiler, while polymorphic method types must be fully explicit in class definitions (appearing immediately after the method name), quantified type variables can be left implicit in class descriptions. Why require types to be explicit? The problem is that (int -> int -> int) -> int -> int would also be a valid type for fold, and it happens to be incompatible with the polymorphic type we gave (automatic instantiation only works for toplevel types variables, not for inner quantifiers, where it becomes an undecidable problem.) So the compiler cannot choose between those two types, and must be helped.
However, the type can be completely omitted in the class definition if it is already known, through inheritance or type constraints on self. Here is an example of method overriding.
```
# class intlist_rev l =
object
inherit intlist l
method! fold f accu = List.fold_left f accu (List.rev l)
end;;
```
The following idiom separates description and definition.
```
# class type ['a] iterator =
object method fold : ('b -> 'a -> 'b) -> 'b -> 'b end;;
```
```
# class intlist' l =
object (self : int #iterator)
method empty = (l = [])
method fold f accu = List.fold_left f accu l
end;;
```
Note here the (self : int #iterator) idiom, which ensures that this object implements the interface iterator.
Polymorphic methods are called in exactly the same way as normal methods, but you should be aware of some limitations of type inference. Namely, a polymorphic method can only be called if its type is known at the call site. Otherwise, the method will be assumed to be monomorphic, and given an incompatible type.
```
# let sum lst = lst#fold (fun x y -> x+y) 0;;
val sum : < fold : (int -> int -> int) -> int -> 'a; .. > -> 'a =
```
```
# sum l ;;
Error: This expression has type intlist
but an expression was expected of type
< fold : (int -> int -> int) -> int -> 'a; .. >
Types for method fold are incompatible
```
The workaround is easy: you should put a type constraint on the parameter.
```
# let sum (lst : _ #iterator) = lst#fold (fun x y -> x+y) 0;;
val sum : int #iterator -> int =
```
Of course the constraint may also be an explicit method type. Only occurrences of quantified variables are required.
```
# let sum lst =
(lst : < fold : 'a. ('a -> _ -> 'a) -> 'a -> 'a; .. >)#fold (+) 0;;
val sum : < fold : 'a. ('a -> int -> 'a) -> 'a -> 'a; .. > -> int =
```
Another use of polymorphic methods is to allow some form of implicit subtyping in method arguments. We have already seen in section [3.8](#s%3Ainheritance) how some functions may be polymorphic in the class of their argument. This can be extended to methods.
```
# class type point0 = object method get_x : int end;;
class type point0 = object method get_x : int end
```
```
# class distance_point x =
object
inherit point x
method distance : 'a. (#point0 as 'a) -> int =
fun other -> abs (other#get_x - x)
end;;
class distance_point :
int ->
object
val mutable x : int
method distance : #point0 -> int
method get_offset : int
method get_x : int
method move : int -> unit
end
```
```
# let p = new distance_point 3 in
(p#distance (new point 8), p#distance (new colored_point 1 "blue"));;
- : int * int = (5, 2)
```
Note here the special syntax (#point0 as 'a) we have to use to quantify the extensible part of #point0. As for the variable binder, it can be omitted in class specifications. If you want polymorphism inside object field it must be quantified independently.
```
# class multi_poly =
object
method m1 : 'a. (< n1 : 'b. 'b -> 'b; .. > as 'a) -> _ =
fun o -> o#n1 true, o#n1 "hello"
method m2 : 'a 'b. (< n2 : 'b -> bool; .. > as 'a) -> 'b -> _ =
fun o x -> o#n2 x
end;;
class multi_poly :
object
method m1 : < n1 : 'b. 'b -> 'b; .. > -> bool * string
method m2 : < n2 : 'b -> bool; .. > -> 'b -> bool
end
```
In method m1, o must be an object with at least a method n1, itself polymorphic. In method m2, the argument of n2 and x must have the same type, which is quantified at the same level as 'a.
[](#s:using-coercions)3.12 Using coercions
--------------------------------------------
Subtyping is never implicit. There are, however, two ways to perform subtyping. The most general construction is fully explicit: both the domain and the codomain of the type coercion must be given.
We have seen that points and colored points have incompatible types. For instance, they cannot be mixed in the same list. However, a colored point can be coerced to a point, hiding its color method:
```
# let colored_point_to_point cp = (cp : colored_point :> point);;
val colored_point_to_point : colored_point -> point =
```
```
# let p = new point 3 and q = new colored_point 4 "blue";;
val p : point =
val q : colored\_point =
```
```
# let l = [p; (colored_point_to_point q)];;
val l : point list = [; ]
```
An object of type t can be seen as an object of type t' only if t is a subtype of t'. For instance, a point cannot be seen as a colored point.
```
# (p : point :> colored_point);;
Error: Type point = < get_offset : int; get_x : int; move : int -> unit >
is not a subtype of
colored_point =
< color : string; get_offset : int; get_x : int;
move : int -> unit >
The first object type has no method color
```
Indeed, narrowing coercions without runtime checks would be unsafe. Runtime type checks might raise exceptions, and they would require the presence of type information at runtime, which is not the case in the OCaml system. For these reasons, there is no such operation available in the language.
Be aware that subtyping and inheritance are not related. Inheritance is a syntactic relation between classes while subtyping is a semantic relation between types. For instance, the class of colored points could have been defined directly, without inheriting from the class of points; the type of colored points would remain unchanged and thus still be a subtype of points.
The domain of a coercion can often be omitted. For instance, one can define:
```
# let to_point cp = (cp :> point);;
val to_point : #point -> point =
```
In this case, the function colored\_point\_to\_point is an instance of the function to\_point. This is not always true, however. The fully explicit coercion is more precise and is sometimes unavoidable. Consider, for example, the following class:
```
# class c0 = object method m = {< >} method n = 0 end;;
class c0 : object ('a) method m : 'a method n : int end
```
The object type c0 is an abbreviation for <m : 'a; n : int> as 'a. Consider now the type declaration:
```
# class type c1 = object method m : c1 end;;
class type c1 = object method m : c1 end
```
The object type c1 is an abbreviation for the type <m : 'a> as 'a. The coercion from an object of type c0 to an object of type c1 is correct:
```
# fun (x:c0) -> (x : c0 :> c1);;
- : c0 -> c1 =
```
However, the domain of the coercion cannot always be omitted. In that case, the solution is to use the explicit form. Sometimes, a change in the class-type definition can also solve the problem
```
# class type c2 = object ('a) method m : 'a end;;
class type c2 = object ('a) method m : 'a end
```
```
# fun (x:c0) -> (x :> c2);;
- : c0 -> c2 =
```
While class types c1 and c2 are different, both object types c1 and c2 expand to the same object type (same method names and types). Yet, when the domain of a coercion is left implicit and its co-domain is an abbreviation of a known class type, then the class type, rather than the object type, is used to derive the coercion function. This allows leaving the domain implicit in most cases when coercing from a subclass to its superclass. The type of a coercion can always be seen as below:
```
# let to_c1 x = (x :> c1);;
val to_c1 : < m : #c1; .. > -> c1 =
```
```
# let to_c2 x = (x :> c2);;
val to_c2 : #c2 -> c2 =
```
Note the difference between these two coercions: in the case of to\_c2, the type #c2 = < m : 'a; .. > as 'a is polymorphically recursive (according to the explicit recursion in the class type of c2); hence the success of applying this coercion to an object of class c0. On the other hand, in the first case, c1 was only expanded and unrolled twice to obtain < m : < m : c1; .. >; .. > (remember #c1 = < m : c1; .. >), without introducing recursion. You may also note that the type of to\_c2 is #c2 -> c2 while the type of to\_c1 is more general than #c1 -> c1. This is not always true, since there are class types for which some instances of #c are not subtypes of c, as explained in section [3.16](#s%3Abinary-methods). Yet, for parameterless classes the coercion (\_ :> c) is always more general than (\_ : #c :> c).
A common problem may occur when one tries to define a coercion to a class c while defining class c. The problem is due to the type abbreviation not being completely defined yet, and so its subtypes are not clearly known. Then, a coercion (\_ :> c) or (\_ : #c :> c) is taken to be the identity function, as in
```
# fun x -> (x :> 'a);;
- : 'a -> 'a =
```
As a consequence, if the coercion is applied to self, as in the following example, the type of self is unified with the closed type c (a closed object type is an object type without ellipsis). This would constrain the type of self be closed and is thus rejected. Indeed, the type of self cannot be closed: this would prevent any further extension of the class. Therefore, a type error is generated when the unification of this type with another type would result in a closed object type.
```
# class c = object method m = 1 end
and d = object (self)
inherit c
method n = 2
method as_c = (self :> c)
end;;
Error: This expression cannot be coerced to type c = < m : int >; it has type
< as_c : c; m : int; n : int; .. >
but is here used with type c
Self type cannot escape its class
```
However, the most common instance of this problem, coercing self to its current class, is detected as a special case by the type checker, and properly typed.
```
# class c = object (self) method m = (self :> c) end;;
class c : object method m : c end
```
This allows the following idiom, keeping a list of all objects belonging to a class or its subclasses:
```
# let all_c = ref [];;
val all_c : '_weak3 list ref = {contents = []}
```
```
# class c (m : int) =
object (self)
method m = m
initializer all_c := (self :> c) :: !all_c
end;;
class c : int -> object method m : int end
```
This idiom can in turn be used to retrieve an object whose type has been weakened:
```
# let rec lookup_obj obj = function [] -> raise Not_found
| obj' :: l ->
if (obj :> < >) = (obj' :> < >) then obj' else lookup_obj obj l ;;
val lookup_obj : < .. > -> (< .. > as 'a) list -> 'a =
```
```
# let lookup_c obj = lookup_obj obj !all_c;;
val lookup_c : < .. > -> < m : int > =
```
The type < m : int > we see here is just the expansion of c, due to the use of a reference; we have succeeded in getting back an object of type c.
The previous coercion problem can often be avoided by first defining the abbreviation, using a class type:
```
# class type c' = object method m : int end;;
class type c' = object method m : int end
```
```
# class c : c' = object method m = 1 end
and d = object (self)
inherit c
method n = 2
method as_c = (self :> c')
end;;
class c : c'
and d : object method as_c : c' method m : int method n : int end
```
It is also possible to use a virtual class. Inheriting from this class simultaneously forces all methods of c to have the same type as the methods of c'.
```
# class virtual c' = object method virtual m : int end;;
class virtual c' : object method virtual m : int end
```
```
# class c = object (self) inherit c' method m = 1 end;;
class c : object method m : int end
```
One could think of defining the type abbreviation directly:
```
# type c' = <m : int>;;
```
However, the abbreviation #c' cannot be defined directly in a similar way. It can only be defined by a class or a class-type definition. This is because a #-abbreviation carries an implicit anonymous variable .. that cannot be explicitly named. The closer you get to it is:
```
# type 'a c'_class = 'a constraint 'a = < m : int; .. >;;
```
with an extra type variable capturing the open object type.
[](#s:functional-objects)3.13 Functional objects
--------------------------------------------------
It is possible to write a version of class point without assignments on the instance variables. The override construct {< ... >} returns a copy of “self” (that is, the current object), possibly changing the value of some instance variables.
```
# class functional_point y =
object
val x = y
method get_x = x
method move d = {< x = x + d >}
method move_to x = {< x >}
end;;
class functional_point :
int ->
object ('a)
val x : int
method get_x : int
method move : int -> 'a
method move_to : int -> 'a
end
```
```
# let p = new functional_point 7;;
val p : functional_point =
```
```
# p#get_x;;
- : int = 7
```
```
# (p#move 3)#get_x;;
- : int = 10
```
```
# (p#move_to 15)#get_x;;
- : int = 15
```
```
# p#get_x;;
- : int = 7
```
As with records, the form {< x >} is an elided version of {< x = x >} which avoids the repetition of the instance variable name. Note that the type abbreviation functional\_point is recursive, which can be seen in the class type of functional\_point: the type of self is 'a and 'a appears inside the type of the method move.
The above definition of functional\_point is not equivalent to the following:
```
# class bad_functional_point y =
object
val x = y
method get_x = x
method move d = new bad_functional_point (x+d)
method move_to x = new bad_functional_point x
end;;
class bad_functional_point :
int ->
object
val x : int
method get_x : int
method move : int -> bad_functional_point
method move_to : int -> bad_functional_point
end
```
While objects of either class will behave the same, objects of their subclasses will be different. In a subclass of bad\_functional\_point, the method move will keep returning an object of the parent class. On the contrary, in a subclass of functional\_point, the method move will return an object of the subclass.
Functional update is often used in conjunction with binary methods as illustrated in section [8.2.1](advexamples#ss%3Astring-as-class).
[](#s:cloning-objects)3.14 Cloning objects
--------------------------------------------
Objects can also be cloned, whether they are functional or imperative. The library function Oo.copy makes a shallow copy of an object. That is, it returns a new object that has the same methods and instance variables as its argument. The instance variables are copied but their contents are shared. Assigning a new value to an instance variable of the copy (using a method call) will not affect instance variables of the original, and conversely. A deeper assignment (for example if the instance variable is a reference cell) will of course affect both the original and the copy.
The type of Oo.copy is the following:
```
# Oo.copy;;
- : (< .. > as 'a) -> 'a =
```
The keyword as in that type binds the type variable 'a to the object type < .. >. Therefore, Oo.copy takes an object with any methods (represented by the ellipsis), and returns an object of the same type. The type of Oo.copy is different from type < .. > -> < .. > as each ellipsis represents a different set of methods. Ellipsis actually behaves as a type variable.
```
# let p = new point 5;;
val p : point =
```
```
# let q = Oo.copy p;;
val q : point =
```
```
# q#move 7; (p#get_x, q#get_x);;
- : int * int = (5, 12)
```
In fact, Oo.copy p will behave as p#copy assuming that a public method copy with body {< >} has been defined in the class of p.
Objects can be compared using the generic comparison functions = and <>. Two objects are equal if and only if they are physically equal. In particular, an object and its copy are not equal.
```
# let q = Oo.copy p;;
val q : point =
```
```
# p = q, p = p;;
- : bool * bool = (false, true)
```
Other generic comparisons such as (<, <=, ...) can also be used on objects. The relation < defines an unspecified but strict ordering on objects. The ordering relationship between two objects is fixed permanently once the two objects have been created, and it is not affected by mutation of fields.
Cloning and override have a non empty intersection. They are interchangeable when used within an object and without overriding any field:
```
# class copy =
object
method copy = {< >}
end;;
class copy : object ('a) method copy : 'a end
```
```
# class copy =
object (self)
method copy = Oo.copy self
end;;
class copy : object ('a) method copy : 'a end
```
Only the override can be used to actually override fields, and only the Oo.copy primitive can be used externally.
Cloning can also be used to provide facilities for saving and restoring the state of objects.
```
# class backup =
object (self : 'mytype)
val mutable copy = None
method save = copy <- Some {< copy = None >}
method restore = match copy with Some x -> x | None -> self
end;;
class backup :
object ('a)
val mutable copy : 'a option
method restore : 'a
method save : unit
end
```
The above definition will only backup one level. The backup facility can be added to any class by using multiple inheritance.
```
# class ['a] backup_ref x = object inherit ['a] oref x inherit backup end;;
class ['a] backup_ref :
'a ->
object ('b)
val mutable copy : 'b option
val mutable x : 'a
method get : 'a
method restore : 'b
method save : unit
method set : 'a -> unit
end
```
```
# let rec get p n = if n = 0 then p # get else get (p # restore) (n-1);;
val get : (< get : 'b; restore : 'a; .. > as 'a) -> int -> 'b =
```
```
# let p = new backup_ref 0 in
p # save; p # set 1; p # save; p # set 2;
[get p 0; get p 1; get p 2; get p 3; get p 4];;
- : int list = [2; 1; 1; 1; 1]
```
We can define a variant of backup that retains all copies. (We also add a method clear to manually erase all copies.)
```
# class backup =
object (self : 'mytype)
val mutable copy = None
method save = copy <- Some {< >}
method restore = match copy with Some x -> x | None -> self
method clear = copy <- None
end;;
class backup :
object ('a)
val mutable copy : 'a option
method clear : unit
method restore : 'a
method save : unit
end
```
```
# class ['a] backup_ref x = object inherit ['a] oref x inherit backup end;;
class ['a] backup_ref :
'a ->
object ('b)
val mutable copy : 'b option
val mutable x : 'a
method clear : unit
method get : 'a
method restore : 'b
method save : unit
method set : 'a -> unit
end
```
```
# let p = new backup_ref 0 in
p # save; p # set 1; p # save; p # set 2;
[get p 0; get p 1; get p 2; get p 3; get p 4];;
- : int list = [2; 1; 0; 0; 0]
```
[](#s:recursive-classes)3.15 Recursive classes
------------------------------------------------
Recursive classes can be used to define objects whose types are mutually recursive.
```
# class window =
object
val mutable top_widget = (None : widget option)
method top_widget = top_widget
end
and widget (w : window) =
object
val window = w
method window = window
end;;
class window :
object
val mutable top_widget : widget option
method top_widget : widget option
end
and widget : window -> object val window : window method window : window end
```
Although their types are mutually recursive, the classes widget and window are themselves independent.
[](#s:binary-methods)3.16 Binary methods
------------------------------------------
A binary method is a method which takes an argument of the same type as self. The class comparable below is a template for classes with a binary method leq of type 'a -> bool where the type variable 'a is bound to the type of self. Therefore, #comparable expands to < leq : 'a -> bool; .. > as 'a. We see here that the binder as also allows writing recursive types.
```
# class virtual comparable =
object (_ : 'a)
method virtual leq : 'a -> bool
end;;
class virtual comparable : object ('a) method virtual leq : 'a -> bool end
```
We then define a subclass money of comparable. The class money simply wraps floats as comparable objects.[1](#note1) We will extend money below with more operations. We have to use a type constraint on the class parameter x because the primitive <= is a polymorphic function in OCaml. The inherit clause ensures that the type of objects of this class is an instance of #comparable.
```
# class money (x : float) =
object
inherit comparable
val repr = x
method value = repr
method leq p = repr <= p#value
end;;
class money :
float ->
object ('a)
val repr : float
method leq : 'a -> bool
method value : float
end
```
Note that the type money is not a subtype of type comparable, as the self type appears in contravariant position in the type of method leq. Indeed, an object m of class money has a method leq that expects an argument of type money since it accesses its value method. Considering m of type comparable would allow a call to method leq on m with an argument that does not have a method value, which would be an error.
Similarly, the type money2 below is not a subtype of type money.
```
# class money2 x =
object
inherit money x
method times k = {< repr = k *. repr >}
end;;
class money2 :
float ->
object ('a)
val repr : float
method leq : 'a -> bool
method times : float -> 'a
method value : float
end
```
It is however possible to define functions that manipulate objects of type either money or money2: the function min will return the minimum of any two objects whose type unifies with #comparable. The type of min is not the same as #comparable -> #comparable -> #comparable, as the abbreviation #comparable hides a type variable (an ellipsis). Each occurrence of this abbreviation generates a new variable.
```
# let min (x : #comparable) y =
if x#leq y then x else y;;
val min : (#comparable as 'a) -> 'a -> 'a =
```
This function can be applied to objects of type money or money2.
```
# (min (new money 1.3) (new money 3.1))#value;;
- : float = 1.3
```
```
# (min (new money2 5.0) (new money2 3.14))#value;;
- : float = 3.14
```
More examples of binary methods can be found in sections [8.2.1](advexamples#ss%3Astring-as-class) and [8.2.3](advexamples#ss%3Aset-as-class).
Note the use of override for method times. Writing new money2 (k \*. repr) instead of {< repr = k \*. repr >} would not behave well with inheritance: in a subclass money3 of money2 the times method would return an object of class money2 but not of class money3 as would be expected.
The class money could naturally carry another binary method. Here is a direct definition:
```
# class money x =
object (self : 'a)
val repr = x
method value = repr
method print = print_float repr
method times k = {< repr = k *. x >}
method leq (p : 'a) = repr <= p#value
method plus (p : 'a) = {< repr = x +. p#value >}
end;;
class money :
float ->
object ('a)
val repr : float
method leq : 'a -> bool
method plus : 'a -> 'a
method print : unit
method times : float -> 'a
method value : float
end
```
[](#s:friends)3.17 Friends
----------------------------
The above class money reveals a problem that often occurs with binary methods. In order to interact with other objects of the same class, the representation of money objects must be revealed, using a method such as value. If we remove all binary methods (here plus and leq), the representation can easily be hidden inside objects by removing the method value as well. However, this is not possible as soon as some binary method requires access to the representation of objects of the same class (other than self).
```
# class safe_money x =
object (self : 'a)
val repr = x
method print = print_float repr
method times k = {< repr = k *. x >}
end;;
class safe_money :
float ->
object ('a)
val repr : float
method print : unit
method times : float -> 'a
end
```
Here, the representation of the object is known only to a particular object. To make it available to other objects of the same class, we are forced to make it available to the whole world. However we can easily restrict the visibility of the representation using the module system.
```
# module type MONEY =
sig
type t
class c : float ->
object ('a)
val repr : t
method value : t
method print : unit
method times : float -> 'a
method leq : 'a -> bool
method plus : 'a -> 'a
end
end;;
```
```
# module Euro : MONEY =
struct
type t = float
class c x =
object (self : 'a)
val repr = x
method value = repr
method print = print_float repr
method times k = {< repr = k *. x >}
method leq (p : 'a) = repr <= p#value
method plus (p : 'a) = {< repr = x +. p#value >}
end
end;;
```
Another example of friend functions may be found in section [8.2.3](advexamples#ss%3Aset-as-class). These examples occur when a group of objects (here objects of the same class) and functions should see each others internal representation, while their representation should be hidden from the outside. The solution is always to define all friends in the same module, give access to the representation and use a signature constraint to make the representation abstract outside the module.
[1](#text1)
floats are an approximation of decimal numbers, they are unsuitable for use in most monetary calculations as they may introduce errors.
| programming_docs |
ocaml None
[](#s:values)11.2 Values
--------------------------
* [11.2.1 Base values](values#ss%3Avalues%3Abase)
* [11.2.2 Tuples](values#ss%3Avalues%3Atuple)
* [11.2.3 Records](values#ss%3Avalues%3Arecords)
* [11.2.4 Arrays](values#ss%3Avalues%3Aarray)
* [11.2.5 Variant values](values#ss%3Avalues%3Avariant)
* [11.2.6 Polymorphic variants](values#ss%3Avalues%3Apolyvars)
* [11.2.7 Functions](values#ss%3Avalues%3Afun)
* [11.2.8 Objects](values#ss%3Avalues%3Aobj)
This section describes the kinds of values that are manipulated by OCaml programs.
###
[](#ss:values:base)11.2.1 Base values
####
[](#sss:values:integer)Integer numbers
Integer values are integer numbers from −230 to 230−1, that is −1073741824 to 1073741823. The implementation may support a wider range of integer values: on 64-bit platforms, the current implementation supports integers ranging from −262 to 262−1.
####
[](#sss:values:float)Floating-point numbers
Floating-point values are numbers in floating-point representation. The current implementation uses double-precision floating-point numbers conforming to the IEEE 754 standard, with 53 bits of mantissa and an exponent ranging from −1022 to 1023.
####
[](#sss:values:char)Characters
Character values are represented as 8-bit integers between 0 and 255. Character codes between 0 and 127 are interpreted following the ASCII standard. The current implementation interprets character codes between 128 and 255 following the ISO 8859-1 standard.
####
[](#sss:values:string)Character strings
String values are finite sequences of characters. The current implementation supports strings containing up to 224 − 5 characters (16777211 characters); on 64-bit platforms, the limit is 257 − 9.
###
[](#ss:values:tuple)11.2.2 Tuples
Tuples of values are written (v1, …, vn), standing for the n-tuple of values v1 to vn. The current implementation supports tuple of up to 222 − 1 elements (4194303 elements).
###
[](#ss:values:records)11.2.3 Records
Record values are labeled tuples of values. The record value written { [field](names#field)1 = v1; …; [field](names#field)n = vn } associates the value vi to the record field [field](names#field)i, for i = 1 … n. The current implementation supports records with up to 222 − 1 fields (4194303 fields).
###
[](#ss:values:array)11.2.4 Arrays
Arrays are finite, variable-sized sequences of values of the same type. The current implementation supports arrays containing up to 222 − 1 elements (4194303 elements) unless the elements are floating-point numbers (2097151 elements in this case); on 64-bit platforms, the limit is 254 − 1 for all arrays.
###
[](#ss:values:variant)11.2.5 Variant values
Variant values are either a constant constructor, or a non-constant constructor applied to a number of values. The former case is written [constr](names#constr); the latter case is written [constr](names#constr) (v1, ... , vn ), where the vi are said to be the arguments of the non-constant constructor [constr](names#constr). The parentheses may be omitted if there is only one argument.
The following constants are treated like built-in constant constructors:
| | |
| --- | --- |
| Constant | Constructor |
| false | the boolean false |
| true | the boolean true |
| () | the “unit” value |
| [] | the empty list |
The current implementation limits each variant type to have at most 246 non-constant constructors and 230−1 constant constructors.
###
[](#ss:values:polyvars)11.2.6 Polymorphic variants
Polymorphic variants are an alternate form of variant values, not belonging explicitly to a predefined variant type, and following specific typing rules. They can be either constant, written `[tag-name](names#tag-name), or non-constant, written `[tag-name](names#tag-name)(v).
###
[](#ss:values:fun)11.2.7 Functions
Functional values are mappings from values to values.
###
[](#ss:values:obj)11.2.8 Objects
Objects are composed of a hidden internal state which is a record of instance variables, and a set of methods for accessing and modifying these variables. The structure of an object is described by the toplevel class that created it.
ocaml Chapter 31 The str library: regular expressions and string processing Chapter 31 The str library: regular expressions and string processing
=====================================================================
The str library provides high-level string processing functions, some based on regular expressions. It is intended to support the kind of file processing that is usually performed with scripting languages such as awk, perl or sed.
Programs that use the str library must be linked as follows:
```
ocamlc other options -I +str str.cma other files
ocamlopt other options -I +str str.cmxa other files
```
For interactive use of the str library, do:
```
ocamlmktop -o mytop str.cma
./mytop
```
or (if dynamic linking of C libraries is supported on your platform), start ocaml and type
```
# #directory "+str";;
```
```
# #load "str.cma";;
```
* [Module Str](libref/str): regular expressions and string processing
ocaml Part I An introduction to OCaml The OCaml system
release 5.0
Documentation and user’s manual
Xavier Leroy,
Damien Doligez, Alain Frisch, Jacques Garrigue,
Didier Rémy, KC Sivaramakrishnan and Jérôme Vouillon
20thDecember , 2022
Copyright © 2022 Institut National de Recherche en Informatique et en Automatique
This manual is also available in [PDF](https://ocaml.org/releases/5.0/ocaml-5.0-refman.pdf), [plain text](https://ocaml.org/releases/5.0/ocaml-5.0-refman.txt), as a [bundle of HTML files](https://ocaml.org/releases/5.0/ocaml-5.0-refman-html.tar.gz), and as a [bundle of Emacs Info files](https://ocaml.org/releases/5.0/ocaml-5.0-refman.info.tar.gz).
* [Contents](manual001)
* [Foreword](foreword)
Part I An introduction to OCaml
===============================
* [Chapter 1 The core language](coreexamples)
* [Chapter 2 The module system](moduleexamples)
* [Chapter 3 Objects in OCaml](objectexamples)
* [Chapter 4 Labeled arguments](lablexamples)
* [Chapter 5 Polymorphic variants](polyvariant)
* [Chapter 6 Polymorphism and its limitations](polymorphism)
* [Chapter 7 Generalized algebraic datatypes](gadts-tutorial)
* [Chapter 8 Advanced examples with classes and modules](advexamples)
* [Chapter 9 Parallel programming](parallelism)
* [Chapter 10 Memory model: The hard bits](memorymodel)
Part II The OCaml language
==========================
* [Chapter 11 The OCaml language](language)
* [Chapter 12 Language extensions](extn)
Part III The OCaml tools
========================
* [Chapter 13 Batch compilation (ocamlc)](comp)
* [Chapter 14 The toplevel system or REPL (ocaml)](toplevel)
* [Chapter 15 The runtime system (ocamlrun)](runtime)
* [Chapter 16 Native-code compilation (ocamlopt)](native)
* [Chapter 17 Lexer and parser generators (ocamllex, ocamlyacc)](lexyacc)
* [Chapter 18 Dependency generator (ocamldep)](depend)
* [Chapter 19 The documentation generator (ocamldoc)](ocamldoc)
* [Chapter 20 The debugger (ocamldebug)](debugger)
* [Chapter 21 Profiling (ocamlprof)](profil)
* [Chapter 22 Interfacing C with OCaml](intfc)
* [Chapter 23 Optimisation with Flambda](flambda)
* [Chapter 24 Fuzzing with afl-fuzz](afl-fuzz)
* [Chapter 25 Runtime tracing with runtime events](runtime-tracing)
* [Chapter 26 The “Tail Modulo Constructor” program transformation](tail_mod_cons)
Part IV The OCaml library
=========================
* [Chapter 27 The core library](core)
* [Chapter 28 The standard library](stdlib)
* [Chapter 29 The compiler front-end](parsing)
* [Chapter 30 The unix library: Unix system calls](libunix)
* [Chapter 31 The str library: regular expressions and string processing](libstr)
* [Chapter 32 The runtime\_events library](runtime_events)
* [Chapter 33 The threads library](libthreads)
* [Chapter 34 The dynlink library: dynamic loading and linking of object files](libdynlink)
* [Chapter 35 Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk)](old)
Part V Indexes
==============
* [Index of modules](libref/index_modules)
* [Index of module types](libref/index_module_types)
* [Index of types](libref/index_types)
* [Index of exceptions](libref/index_exceptions)
* [Index of values](libref/index_values)
* [Index of keywords](manual074)
>
> *This document was translated from LATEX by* [*HEVEA*](http://hevea.inria.fr/index.html)*.*
>
ocaml None
[](#s:patterns)11.6 Patterns
------------------------------
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| pattern | ::= | [value-name](names#value-name) |
| | ∣ | \_ |
| | ∣ | [constant](const#constant) |
| | ∣ | [pattern](#pattern) as [value-name](names#value-name) |
| | ∣ | ( [pattern](#pattern) ) |
| | ∣ | ( [pattern](#pattern) : [typexpr](types#typexpr) ) |
| | ∣ | [pattern](#pattern) | [pattern](#pattern) |
| | ∣ | [constr](names#constr) [pattern](#pattern) |
| | ∣ | `[tag-name](names#tag-name) [pattern](#pattern) |
| | ∣ | #[typeconstr](names#typeconstr) |
| | ∣ | [pattern](#pattern) { , [pattern](#pattern) }+ |
| | ∣ | { [field](names#field) [: [typexpr](types#typexpr)] [= [pattern](#pattern)]{ ; [field](names#field) [: [typexpr](types#typexpr)] [= [pattern](#pattern)] } [; \_ ] [ ; ] } |
| | ∣ | [ [pattern](#pattern) { ; [pattern](#pattern) } [ ; ] ] |
| | ∣ | [pattern](#pattern) :: [pattern](#pattern) |
| | ∣ | [| [pattern](#pattern) { ; [pattern](#pattern) } [ ; ] |] |
| | ∣ | [char-literal](lex#char-literal) .. [char-literal](lex#char-literal) |
| | ∣ | lazy [pattern](#pattern) |
| | ∣ | exception [pattern](#pattern) |
| | ∣ | [module-path](names#module-path) .( [pattern](#pattern) ) |
| | ∣ | [module-path](names#module-path) .[ [pattern](#pattern) ] |
| | ∣ | [module-path](names#module-path) .[| [pattern](#pattern) |] |
| | ∣ | [module-path](names#module-path) .{ [pattern](#pattern) } |
|
See also the following language extensions: [first-class modules](firstclassmodules#s%3Afirst-class-modules), [attributes](attributes#s%3Aattributes) and [extension nodes](extensionnodes#s%3Aextension-nodes).
The table below shows the relative precedences and associativity of operators and non-closed pattern constructions. The constructions with higher precedences come first.
| | |
| --- | --- |
| Operator | Associativity |
| .. | – |
| lazy (see section [11.6](#sss%3Apat-lazy)) | – |
| Constructor application, Tag application | right |
| :: | right |
| , | – |
| | | left |
| as | – |
Patterns are templates that allow selecting data structures of a given shape, and binding identifiers to components of the data structure. This selection operation is called pattern matching; its outcome is either “this value does not match this pattern”, or “this value matches this pattern, resulting in the following bindings of names to values”.
####
[](#sss:pat-variable)Variable patterns
A pattern that consists in a value name matches any value, binding the name to the value. The pattern \_ also matches any value, but does not bind any name.
```
# let is_empty = function
| [] -> true
| _ :: _ -> false;;
val is_empty : 'a list -> bool =
```
Patterns are *linear*: a variable cannot be bound several times by a given pattern. In particular, there is no way to test for equality between two parts of a data structure using only a pattern:
```
# let pair_equal = function
| x, x -> true
| x, y -> false;;
Error: Variable x is bound several times in this matching
```
However, we can use a when guard for this purpose:
```
# let pair_equal = function
| x, y when x = y -> true
| _ -> false;;
val pair_equal : 'a * 'a -> bool =
```
####
[](#sss:pat-const)Constant patterns
A pattern consisting in a constant matches the values that are equal to this constant.
```
# let bool_of_string = function
| "true" -> true
| "false" -> false
| _ -> raise (Invalid_argument "bool_of_string");;
val bool_of_string : string -> bool =
```
####
[](#sss:pat-alias)Alias patterns
The pattern [pattern](#pattern)1 as [value-name](names#value-name) matches the same values as [pattern](#pattern)1. If the matching against [pattern](#pattern)1 is successful, the name [value-name](names#value-name) is bound to the matched value, in addition to the bindings performed by the matching against [pattern](#pattern)1.
```
# let sort_pair ((x, y) as p) =
if x <= y then p else (y, x);;
val sort_pair : 'a * 'a -> 'a * 'a =
```
####
[](#sss:pat-parenthesized)Parenthesized patterns
The pattern ( [pattern](#pattern)1 ) matches the same values as [pattern](#pattern)1. A type constraint can appear in a parenthesized pattern, as in ( [pattern](#pattern)1 : [typexpr](types#typexpr) ). This constraint forces the type of [pattern](#pattern)1 to be compatible with [typexpr](types#typexpr).
```
# let int_triple_is_ordered ((a, b, c) : int * int * int) =
a <= b && b <= c;;
val int_triple_is_ordered : int * int * int -> bool =
```
####
[](#sss:pat-or)“Or” patterns
The pattern [pattern](#pattern)1 | [pattern](#pattern)2 represents the logical “or” of the two patterns [pattern](#pattern)1 and [pattern](#pattern)2. A value matches [pattern](#pattern)1 | [pattern](#pattern)2 if it matches [pattern](#pattern)1 or [pattern](#pattern)2. The two sub-patterns [pattern](#pattern)1 and [pattern](#pattern)2 must bind exactly the same identifiers to values having the same types. Matching is performed from left to right. More precisely, in case some value v matches [pattern](#pattern)1 | [pattern](#pattern)2, the bindings performed are those of [pattern](#pattern)1 when v matches [pattern](#pattern)1. Otherwise, value v matches [pattern](#pattern)2 whose bindings are performed.
```
# type shape = Square of float | Rect of (float * float) | Circle of float
let is_rectangular = function
| Square _ | Rect _ -> true
| Circle _ -> false;;
type shape = Square of float | Rect of (float * float) | Circle of float
val is_rectangular : shape -> bool =
```
####
[](#sss:pat-variant)Variant patterns
The pattern [constr](names#constr) ( [pattern](#pattern)1 , … , [pattern](#pattern)n ) matches all variants whose constructor is equal to [constr](names#constr), and whose arguments match [pattern](#pattern)1 … [pattern](#pattern)n. It is a type error if n is not the number of arguments expected by the constructor.
The pattern [constr](names#constr) \_ matches all variants whose constructor is [constr](names#constr).
```
# type 'a tree = Lf | Br of 'a tree * 'a * 'a tree
let rec total = function
| Br (l, x, r) -> total l + x + total r
| Lf -> 0;;
type 'a tree = Lf | Br of 'a tree * 'a * 'a tree
val total : int tree -> int =
```
The pattern [pattern](#pattern)1 :: [pattern](#pattern)2 matches non-empty lists whose heads match [pattern](#pattern)1, and whose tails match [pattern](#pattern)2.
The pattern [ [pattern](#pattern)1 ; … ; [pattern](#pattern)n ] matches lists of length n whose elements match [pattern](#pattern)1 …[pattern](#pattern)n, respectively. This pattern behaves like [pattern](#pattern)1 :: … :: [pattern](#pattern)n :: [].
```
# let rec destutter = function
| [] -> []
| [a] -> [a]
| a :: b :: t -> if a = b then destutter (b :: t) else a :: destutter (b :: t);;
val destutter : 'a list -> 'a list =
```
####
[](#sss:pat-polyvar)Polymorphic variant patterns
The pattern `[tag-name](names#tag-name) [pattern](#pattern)1 matches all polymorphic variants whose tag is equal to [tag-name](names#tag-name), and whose argument matches [pattern](#pattern)1.
```
# let rec split = function
| [] -> ([], [])
| h :: t ->
let ss, gs = split t in
match h with
| `Sheep _ as s -> (s :: ss, gs)
| `Goat _ as g -> (ss, g :: gs);;
val split :
[< `Goat of 'a | `Sheep of 'b ] list ->
[> `Sheep of 'b ] list * [> `Goat of 'a ] list =
```
####
[](#sss:pat-polyvar-abbrev)Polymorphic variant abbreviation patterns
If the type [('a,'b,…)] [typeconstr](names#typeconstr) = [ `[tag-name](names#tag-name)1 [typexpr](types#typexpr)1 | … | `[tag-name](names#tag-name)n [typexpr](types#typexpr)n] is defined, then the pattern #[typeconstr](names#typeconstr) is a shorthand for the following or-pattern: ( `[tag-name](names#tag-name)1(\_ : [typexpr](types#typexpr)1) | … | `[tag-name](names#tag-name)n(\_ : [typexpr](types#typexpr)n)). It matches all values of type [< [typeconstr](names#typeconstr) ].
```
# type 'a rectangle = [`Square of 'a | `Rectangle of 'a * 'a]
type 'a shape = [`Circle of 'a | 'a rectangle]
let try_rectangle = function
| #rectangle as r -> Some r
| `Circle _ -> None;;
type 'a rectangle = [ `Rectangle of 'a * 'a | `Square of 'a ]
type 'a shape = [ `Circle of 'a | `Rectangle of 'a * 'a | `Square of 'a ]
val try_rectangle :
[< `Circle of 'a | `Rectangle of 'b * 'b | `Square of 'b ] ->
[> `Rectangle of 'b * 'b | `Square of 'b ] option =
```
####
[](#sss:pat-tuple)Tuple patterns
The pattern [pattern](#pattern)1 , … , [pattern](#pattern)n matches n-tuples whose components match the patterns [pattern](#pattern)1 through [pattern](#pattern)n. That is, the pattern matches the tuple values (v1, …, vn) such that [pattern](#pattern)i matches vi for i = 1,… , n.
```
# let vector (x0, y0) (x1, y1) =
(x1 -. x0, y1 -. y0);;
val vector : float * float -> float * float -> float * float =
```
####
[](#sss:pat-record)Record patterns
The pattern { [field](names#field)1 [= [pattern](#pattern)1] ; … ; [field](names#field)n [= [pattern](#pattern)n] } matches records that define at least the fields [field](names#field)1 through [field](names#field)n, and such that the value associated to [field](names#field)i matches the pattern [pattern](#pattern)i, for i = 1,… , n. A single identifier [field](names#field)k stands for [field](names#field)k = [field](names#field)k , and a single qualified identifier [module-path](names#module-path) . [field](names#field)k stands for [module-path](names#module-path) . [field](names#field)k = [field](names#field)k . The record value can define more fields than [field](names#field)1 …[field](names#field)n; the values associated to these extra fields are not taken into account for matching. Optionally, a record pattern can be terminated by ; \_ to convey the fact that not all fields of the record type are listed in the record pattern and that it is intentional. Optional type constraints can be added field by field with { [field](names#field)1 : [typexpr](types#typexpr)1 = [pattern](#pattern)1 ;… ;[field](names#field)n : [typexpr](types#typexpr)n = [pattern](#pattern)n } to force the type of [field](names#field)k to be compatible with [typexpr](types#typexpr)k.
```
# let bytes_allocated
{Gc.minor_words = minor;
Gc.major_words = major;
Gc.promoted_words = prom;
_}
=
(Sys.word_size / 4) * int_of_float (minor +. major -. prom);;
val bytes_allocated : Gc.stat -> int =
```
####
[](#sss:pat-array)Array patterns
The pattern [| [pattern](#pattern)1 ; … ; [pattern](#pattern)n |] matches arrays of length n such that the i-th array element matches the pattern [pattern](#pattern)i, for i = 1,… , n.
```
# let matrix3_is_symmetric = function
| [|[|_; b; c|];
[|d; _; f|];
[|g; h; _|]|] -> b = d && c = g && f = h
| _ -> failwith "matrix3_is_symmetric: not a 3x3 matrix";;
val matrix3_is_symmetric : 'a array array -> bool =
```
####
[](#sss:pat-range)Range patterns
The pattern ' c ' .. ' d ' is a shorthand for the pattern
' c ' | ' c1 ' | ' c2 ' | … | ' cn ' | ' d '
where c1, c2, …, cn are the characters that occur between c and d in the ASCII character set. For instance, the pattern '0'..'9' matches all characters that are digits.
```
# type char_class = Uppercase | Lowercase | Digit | Other
let classify_char = function
| 'A'..'Z' -> Uppercase
| 'a'..'z' -> Lowercase
| '0'..'9' -> Digit
| _ -> Other;;
type char_class = Uppercase | Lowercase | Digit | Other
val classify_char : char -> char_class =
```
####
[](#sss:pat-lazy)Lazy patterns
(Introduced in Objective Caml 3.11)
| | | | |
| --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [pattern](#pattern) | ::= | ... |
|
The pattern lazy [pattern](#pattern) matches a value v of type Lazy.t, provided [pattern](#pattern) matches the result of forcing v with Lazy.force. A successful match of a pattern containing lazy sub-patterns forces the corresponding parts of the value being matched, even those that imply no test such as lazy [value-name](names#value-name) or lazy \_. Matching a value with a [pattern-matching](expr#pattern-matching) where some patterns contain lazy sub-patterns may imply forcing parts of the value, even when the pattern selected in the end has no lazy sub-pattern.
```
# let force_opt = function
| Some (lazy n) -> n
| None -> 0;;
val force_opt : int lazy_t option -> int =
```
For more information, see the description of module Lazy in the standard library (module [Lazy](libref/lazy)).
####
[](#sss:exception-match)Exception patterns
(Introduced in OCaml 4.02)
A new form of exception pattern, exception [pattern](#pattern) , is allowed only as a toplevel pattern or inside a toplevel or-pattern under a match...with pattern-matching (other occurrences are rejected by the type-checker).
Cases with such a toplevel pattern are called “exception cases”, as opposed to regular “value cases”. Exception cases are applied when the evaluation of the matched expression raises an exception. The exception value is then matched against all the exception cases and re-raised if none of them accept the exception (as with a try...with block). Since the bodies of all exception and value cases are outside the scope of the exception handler, they are all considered to be in tail-position: if the match...with block itself is in tail position in the current function, any function call in tail position in one of the case bodies results in an actual tail call.
A pattern match must contain at least one value case. It is an error if all cases are exceptions, because there would be no code to handle the return of a value.
```
# let find_opt p l =
match List.find p l with
| exception Not_found -> None
| x -> Some x;;
val find_opt : ('a -> bool) -> 'a list -> 'a option =
```
####
[](#sss:pat-open)Local opens for patterns
(Introduced in OCaml 4.04)
For patterns, local opens are limited to the [module-path](names#module-path).([pattern](#pattern)) construction. This construction locally opens the module referred to by the module path [module-path](names#module-path) in the scope of the pattern [pattern](#pattern).
When the body of a local open pattern is delimited by [ ], [| |], or { }, the parentheses can be omitted. For example, [module-path](names#module-path).[[pattern](#pattern)] is equivalent to [module-path](names#module-path).([[pattern](#pattern)]), and [module-path](names#module-path).[| [pattern](#pattern) |] is equivalent to [module-path](names#module-path).([| [pattern](#pattern) |]).
```
# let bytes_allocated Gc.{minor_words; major_words; promoted_words; _} =
(Sys.word_size / 4)
* int_of_float (minor_words +. major_words -. promoted_words);;
val bytes_allocated : Gc.stat -> int =
```
| programming_docs |
ocaml None
[](#s:inline-records)12.17 Inline records
-------------------------------------------
(Introduced in OCaml 4.03)
| | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| constr-args | ::= | ... |
| | ∣ | [record-decl](typedecl#record-decl) |
| |
|
The arguments of sum-type constructors can now be defined using the same syntax as records. Mutable and polymorphic fields are allowed. GADT syntax is supported. Attributes can be specified on individual fields.
Syntactically, building or matching constructors with such an inline record argument is similar to working with a unary constructor whose unique argument is a declared record type. A pattern can bind the inline record as a pseudo-value, but the record cannot escape the scope of the binding and can only be used with the dot-notation to extract or modify fields or to build new constructor values.
```
type t =
| Point of {width: int; mutable x: float; mutable y: float}
| Other
let v = Point {width = 10; x = 0.; y = 0.}
let scale l = function
| Point p -> Point {p with x = l *. p.x; y = l *. p.y}
| Other -> Other
let print = function
| Point {x; y; _} -> Printf.printf "%f/%f" x y
| Other -> ()
let reset = function
| Point p -> p.x <- 0.; p.y <- 0.
| Other -> ()
```
```
let invalid = function
| Point p -> p
Error: This form is not allowed as the type of the inlined record could escape.
```
ocaml Chapter 8 Advanced examples with classes and modules Chapter 8 Advanced examples with classes and modules
====================================================
* [8.1 Extended example: bank accounts](advexamples#s%3Aextended-bank-accounts)
* [8.2 Simple modules as classes](advexamples#s%3Amodules-as-classes)
* [8.3 The subject/observer pattern](advexamples#s%3Asubject-observer)
(Chapter written by Didier Rémy)
In this chapter, we show some larger examples using objects, classes and modules. We review many of the object features simultaneously on the example of a bank account. We show how modules taken from the standard library can be expressed as classes. Lastly, we describe a programming pattern known as *virtual types* through the example of window managers.
[](#s:extended-bank-accounts)8.1 Extended example: bank accounts
------------------------------------------------------------------
In this section, we illustrate most aspects of Object and inheritance by refining, debugging, and specializing the following initial naive definition of a simple bank account. (We reuse the module Euro defined at the end of chapter [3](objectexamples#c%3Aobjectexamples).)
```
# let euro = new Euro.c;;
val euro : float -> Euro.c =
```
```
# let zero = euro 0.;;
val zero : Euro.c =
```
```
# let neg x = x#times (-1.);;
val neg : < times : float -> 'a; .. > -> 'a =
```
```
# class account =
object
val mutable balance = zero
method balance = balance
method deposit x = balance <- balance # plus x
method withdraw x =
if x#leq balance then (balance <- balance # plus (neg x); x) else zero
end;;
class account :
object
val mutable balance : Euro.c
method balance : Euro.c
method deposit : Euro.c -> unit
method withdraw : Euro.c -> Euro.c
end
```
```
# let c = new account in c # deposit (euro 100.); c # withdraw (euro 50.);;
- : Euro.c =
```
We now refine this definition with a method to compute interest.
```
# class account_with_interests =
object (self)
inherit account
method private interest = self # deposit (self # balance # times 0.03)
end;;
class account_with_interests :
object
val mutable balance : Euro.c
method balance : Euro.c
method deposit : Euro.c -> unit
method private interest : unit
method withdraw : Euro.c -> Euro.c
end
```
We make the method interest private, since clearly it should not be called freely from the outside. Here, it is only made accessible to subclasses that will manage monthly or yearly updates of the account.
We should soon fix a bug in the current definition: the deposit method can be used for withdrawing money by depositing negative amounts. We can fix this directly:
```
# class safe_account =
object
inherit account
method deposit x = if zero#leq x then balance <- balance#plus x
end;;
class safe_account :
object
val mutable balance : Euro.c
method balance : Euro.c
method deposit : Euro.c -> unit
method withdraw : Euro.c -> Euro.c
end
```
However, the bug might be fixed more safely by the following definition:
```
# class safe_account =
object
inherit account as unsafe
method deposit x =
if zero#leq x then unsafe # deposit x
else raise (Invalid_argument "deposit")
end;;
class safe_account :
object
val mutable balance : Euro.c
method balance : Euro.c
method deposit : Euro.c -> unit
method withdraw : Euro.c -> Euro.c
end
```
In particular, this does not require the knowledge of the implementation of the method deposit.
To keep track of operations, we extend the class with a mutable field history and a private method trace to add an operation in the log. Then each method to be traced is redefined.
```
# type 'a operation = Deposit of 'a | Retrieval of 'a;;
type 'a operation = Deposit of 'a | Retrieval of 'a
```
```
# class account_with_history =
object (self)
inherit safe_account as super
val mutable history = []
method private trace x = history <- x :: history
method deposit x = self#trace (Deposit x); super#deposit x
method withdraw x = self#trace (Retrieval x); super#withdraw x
method history = List.rev history
end;;
class account_with_history :
object
val mutable balance : Euro.c
val mutable history : Euro.c operation list
method balance : Euro.c
method deposit : Euro.c -> unit
method history : Euro.c operation list
method private trace : Euro.c operation -> unit
method withdraw : Euro.c -> Euro.c
end
```
One may wish to open an account and simultaneously deposit some initial amount. Although the initial implementation did not address this requirement, it can be achieved by using an initializer.
```
# class account_with_deposit x =
object
inherit account_with_history
initializer balance <- x
end;;
class account_with_deposit :
Euro.c ->
object
val mutable balance : Euro.c
val mutable history : Euro.c operation list
method balance : Euro.c
method deposit : Euro.c -> unit
method history : Euro.c operation list
method private trace : Euro.c operation -> unit
method withdraw : Euro.c -> Euro.c
end
```
A better alternative is:
```
# class account_with_deposit x =
object (self)
inherit account_with_history
initializer self#deposit x
end;;
class account_with_deposit :
Euro.c ->
object
val mutable balance : Euro.c
val mutable history : Euro.c operation list
method balance : Euro.c
method deposit : Euro.c -> unit
method history : Euro.c operation list
method private trace : Euro.c operation -> unit
method withdraw : Euro.c -> Euro.c
end
```
Indeed, the latter is safer since the call to deposit will automatically benefit from safety checks and from the trace. Let’s test it:
```
# let ccp = new account_with_deposit (euro 100.) in
let _balance = ccp#withdraw (euro 50.) in
ccp#history;;
- : Euro.c operation list = [Deposit ; Retrieval ]
```
Closing an account can be done with the following polymorphic function:
```
# let close c = c#withdraw c#balance;;
val close : < balance : 'a; withdraw : 'a -> 'b; .. > -> 'b =
```
Of course, this applies to all sorts of accounts.
Finally, we gather several versions of the account into a module Account abstracted over some currency.
```
# let today () = (01,01,2000) (* an approximation *)
module Account (M:MONEY) =
struct
type m = M.c
let m = new M.c
let zero = m 0.
class bank =
object (self)
val mutable balance = zero
method balance = balance
val mutable history = []
method private trace x = history <- x::history
method deposit x =
self#trace (Deposit x);
if zero#leq x then balance <- balance # plus x
else raise (Invalid_argument "deposit")
method withdraw x =
if x#leq balance then
(balance <- balance # plus (neg x); self#trace (Retrieval x); x)
else zero
method history = List.rev history
end
class type client_view =
object
method deposit : m -> unit
method history : m operation list
method withdraw : m -> m
method balance : m
end
class virtual check_client x =
let y = if (m 100.)#leq x then x
else raise (Failure "Insufficient initial deposit") in
object (self)
initializer self#deposit y
method virtual deposit: m -> unit
end
module Client (B : sig class bank : client_view end) =
struct
class account x : client_view =
object
inherit B.bank
inherit check_client x
end
let discount x =
let c = new account x in
if today() < (1998,10,30) then c # deposit (m 100.); c
end
end;;
```
This shows the use of modules to group several class definitions that can in fact be thought of as a single unit. This unit would be provided by a bank for both internal and external uses. This is implemented as a functor that abstracts over the currency so that the same code can be used to provide accounts in different currencies.
The class bank is the *real* implementation of the bank account (it could have been inlined). This is the one that will be used for further extensions, refinements, etc. Conversely, the client will only be given the client view.
```
# module Euro_account = Account(Euro);;
```
```
# module Client = Euro_account.Client (Euro_account);;
```
```
# new Client.account (new Euro.c 100.);;
```
Hence, the clients do not have direct access to the balance, nor the history of their own accounts. Their only way to change their balance is to deposit or withdraw money. It is important to give the clients a class and not just the ability to create accounts (such as the promotional discount account), so that they can personalize their account. For instance, a client may refine the deposit and withdraw methods so as to do his own financial bookkeeping, automatically. On the other hand, the function discount is given as such, with no possibility for further personalization.
It is important to provide the client’s view as a functor Client so that client accounts can still be built after a possible specialization of the bank. The functor Client may remain unchanged and be passed the new definition to initialize a client’s view of the extended account.
```
# module Investment_account (M : MONEY) =
struct
type m = M.c
module A = Account(M)
class bank =
object
inherit A.bank as super
method deposit x =
if (new M.c 1000.)#leq x then
print_string "Would you like to invest?";
super#deposit x
end
module Client = A.Client
end;;
```
The functor Client may also be redefined when some new features of the account can be given to the client.
```
# module Internet_account (M : MONEY) =
struct
type m = M.c
module A = Account(M)
class bank =
object
inherit A.bank
method mail s = print_string s
end
class type client_view =
object
method deposit : m -> unit
method history : m operation list
method withdraw : m -> m
method balance : m
method mail : string -> unit
end
module Client (B : sig class bank : client_view end) =
struct
class account x : client_view =
object
inherit B.bank
inherit A.check_client x
end
end
end;;
```
[](#s:modules-as-classes)8.2 Simple modules as classes
--------------------------------------------------------
One may wonder whether it is possible to treat primitive types such as integers and strings as objects. Although this is usually uninteresting for integers or strings, there may be some situations where this is desirable. The class money above is such an example. We show here how to do it for strings.
###
[](#ss:string-as-class)8.2.1 Strings
A naive definition of strings as objects could be:
```
# class ostring s =
object
method get n = String.get s n
method print = print_string s
method escaped = new ostring (String.escaped s)
end;;
class ostring :
string ->
object
method escaped : ostring
method get : int -> char
method print : unit
end
```
However, the method escaped returns an object of the class ostring, and not an object of the current class. Hence, if the class is further extended, the method escaped will only return an object of the parent class.
```
# class sub_string s =
object
inherit ostring s
method sub start len = new sub_string (String.sub s start len)
end;;
class sub_string :
string ->
object
method escaped : ostring
method get : int -> char
method print : unit
method sub : int -> int -> sub_string
end
```
As seen in section [3.16](objectexamples#s%3Abinary-methods), the solution is to use functional update instead. We need to create an instance variable containing the representation s of the string.
```
# class better_string s =
object
val repr = s
method get n = String.get repr n
method print = print_string repr
method escaped = {< repr = String.escaped repr >}
method sub start len = {< repr = String.sub s start len >}
end;;
class better_string :
string ->
object ('a)
val repr : string
method escaped : 'a
method get : int -> char
method print : unit
method sub : int -> int -> 'a
end
```
As shown in the inferred type, the methods escaped and sub now return objects of the same type as the one of the class.
Another difficulty is the implementation of the method concat. In order to concatenate a string with another string of the same class, one must be able to access the instance variable externally. Thus, a method repr returning s must be defined. Here is the correct definition of strings:
```
# class ostring s =
object (self : 'mytype)
val repr = s
method repr = repr
method get n = String.get repr n
method print = print_string repr
method escaped = {< repr = String.escaped repr >}
method sub start len = {< repr = String.sub s start len >}
method concat (t : 'mytype) = {< repr = repr ^ t#repr >}
end;;
class ostring :
string ->
object ('a)
val repr : string
method concat : 'a -> 'a
method escaped : 'a
method get : int -> char
method print : unit
method repr : string
method sub : int -> int -> 'a
end
```
Another constructor of the class string can be defined to return a new string of a given length:
```
# class cstring n = ostring (String.make n ' ');;
class cstring : int -> ostring
```
Here, exposing the representation of strings is probably harmless. We do could also hide the representation of strings as we hid the currency in the class money of section [3.17](objectexamples#s%3Afriends).
####
[](#sss:stack-as-class)Stacks
There is sometimes an alternative between using modules or classes for parametric data types. Indeed, there are situations when the two approaches are quite similar. For instance, a stack can be straightforwardly implemented as a class:
```
# exception Empty;;
exception Empty
```
```
# class ['a] stack =
object
val mutable l = ([] : 'a list)
method push x = l <- x::l
method pop = match l with [] -> raise Empty | a::l' -> l <- l'; a
method clear = l <- []
method length = List.length l
end;;
class ['a] stack :
object
val mutable l : 'a list
method clear : unit
method length : int
method pop : 'a
method push : 'a -> unit
end
```
However, writing a method for iterating over a stack is more problematic. A method fold would have type ('b -> 'a -> 'b) -> 'b -> 'b. Here 'a is the parameter of the stack. The parameter 'b is not related to the class 'a stack but to the argument that will be passed to the method fold. A naive approach is to make 'b an extra parameter of class stack:
```
# class ['a, 'b] stack2 =
object
inherit ['a] stack
method fold f (x : 'b) = List.fold_left f x l
end;;
class ['a, 'b] stack2 :
object
val mutable l : 'a list
method clear : unit
method fold : ('b -> 'a -> 'b) -> 'b -> 'b
method length : int
method pop : 'a
method push : 'a -> unit
end
```
However, the method fold of a given object can only be applied to functions that all have the same type:
```
# let s = new stack2;;
val s : ('_weak1, '_weak2) stack2 =
```
```
# s#fold ( + ) 0;;
- : int = 0
```
```
# s;;
- : (int, int) stack2 =
```
A better solution is to use polymorphic methods, which were introduced in OCaml version 3.05. Polymorphic methods makes it possible to treat the type variable 'b in the type of fold as universally quantified, giving fold the polymorphic type Forall 'b. ('b -> 'a -> 'b) -> 'b -> 'b. An explicit type declaration on the method fold is required, since the type checker cannot infer the polymorphic type by itself.
```
# class ['a] stack3 =
object
inherit ['a] stack
method fold : 'b. ('b -> 'a -> 'b) -> 'b -> 'b
= fun f x -> List.fold_left f x l
end;;
class ['a] stack3 :
object
val mutable l : 'a list
method clear : unit
method fold : ('b -> 'a -> 'b) -> 'b -> 'b
method length : int
method pop : 'a
method push : 'a -> unit
end
```
###
[](#ss:hashtbl-as-class)8.2.2 Hashtbl
A simplified version of object-oriented hash tables should have the following class type.
```
# class type ['a, 'b] hash_table =
object
method find : 'a -> 'b
method add : 'a -> 'b -> unit
end;;
class type ['a, 'b] hash_table =
object method add : 'a -> 'b -> unit method find : 'a -> 'b end
```
A simple implementation, which is quite reasonable for small hash tables is to use an association list:
```
# class ['a, 'b] small_hashtbl : ['a, 'b] hash_table =
object
val mutable table = []
method find key = List.assoc key table
method add key value = table <- (key, value) :: table
end;;
class ['a, 'b] small_hashtbl : ['a, 'b] hash_table
```
A better implementation, and one that scales up better, is to use a true hash table… whose elements are small hash tables!
```
# class ['a, 'b] hashtbl size : ['a, 'b] hash_table =
object (self)
val table = Array.init size (fun i -> new small_hashtbl)
method private hash key =
(Hashtbl.hash key) mod (Array.length table)
method find key = table.(self#hash key) # find key
method add key = table.(self#hash key) # add key
end;;
class ['a, 'b] hashtbl : int -> ['a, 'b] hash_table
```
###
[](#ss:set-as-class)8.2.3 Sets
Implementing sets leads to another difficulty. Indeed, the method union needs to be able to access the internal representation of another object of the same class.
This is another instance of friend functions as seen in section [3.17](objectexamples#s%3Afriends). Indeed, this is the same mechanism used in the module Set in the absence of objects.
In the object-oriented version of sets, we only need to add an additional method tag to return the representation of a set. Since sets are parametric in the type of elements, the method tag has a parametric type 'a tag, concrete within the module definition but abstract in its signature. From outside, it will then be guaranteed that two objects with a method tag of the same type will share the same representation.
```
# module type SET =
sig
type 'a tag
class ['a] c :
object ('b)
method is_empty : bool
method mem : 'a -> bool
method add : 'a -> 'b
method union : 'b -> 'b
method iter : ('a -> unit) -> unit
method tag : 'a tag
end
end;;
```
```
# module Set : SET =
struct
let rec merge l1 l2 =
match l1 with
[] -> l2
| h1 :: t1 ->
match l2 with
[] -> l1
| h2 :: t2 ->
if h1 < h2 then h1 :: merge t1 l2
else if h1 > h2 then h2 :: merge l1 t2
else merge t1 l2
type 'a tag = 'a list
class ['a] c =
object (_ : 'b)
val repr = ([] : 'a list)
method is_empty = (repr = [])
method mem x = List.exists (( = ) x) repr
method add x = {< repr = merge [x] repr >}
method union (s : 'b) = {< repr = merge repr s#tag >}
method iter (f : 'a -> unit) = List.iter f repr
method tag = repr
end
end;;
```
[](#s:subject-observer)8.3 The subject/observer pattern
---------------------------------------------------------
The following example, known as the subject/observer pattern, is often presented in the literature as a difficult inheritance problem with inter-connected classes. The general pattern amounts to the definition a pair of two classes that recursively interact with one another.
The class observer has a distinguished method notify that requires two arguments, a subject and an event to execute an action.
```
# class virtual ['subject, 'event] observer =
object
method virtual notify : 'subject -> 'event -> unit
end;;
class virtual ['subject, 'event] observer :
object method virtual notify : 'subject -> 'event -> unit end
```
The class subject remembers a list of observers in an instance variable, and has a distinguished method notify\_observers to broadcast the message notify to all observers with a particular event e.
```
# class ['observer, 'event] subject =
object (self)
val mutable observers = ([]:'observer list)
method add_observer obs = observers <- (obs :: observers)
method notify_observers (e : 'event) =
List.iter (fun x -> x#notify self e) observers
end;;
class ['a, 'event] subject :
object ('b)
constraint 'a = < notify : 'b -> 'event -> unit; .. >
val mutable observers : 'a list
method add_observer : 'a -> unit
method notify_observers : 'event -> unit
end
```
The difficulty usually lies in defining instances of the pattern above by inheritance. This can be done in a natural and obvious manner in OCaml, as shown on the following example manipulating windows.
```
# type event = Raise | Resize | Move;;
type event = Raise | Resize | Move
```
```
# let string_of_event = function
Raise -> "Raise" | Resize -> "Resize" | Move -> "Move";;
val string_of_event : event -> string =
```
```
# let count = ref 0;;
val count : int ref = {contents = 0}
```
```
# class ['observer] window_subject =
let id = count := succ !count; !count in
object (self)
inherit ['observer, event] subject
val mutable position = 0
method identity = id
method move x = position <- position + x; self#notify_observers Move
method draw = Printf.printf "{Position = %d}\n" position;
end;;
class ['a] window_subject :
object ('b)
constraint 'a = < notify : 'b -> event -> unit; .. >
val mutable observers : 'a list
val mutable position : int
method add_observer : 'a -> unit
method draw : unit
method identity : int
method move : int -> unit
method notify_observers : event -> unit
end
```
```
# class ['subject] window_observer =
object
inherit ['subject, event] observer
method notify s e = s#draw
end;;
class ['a] window_observer :
object
constraint 'a = < draw : unit; .. >
method notify : 'a -> event -> unit
end
```
As can be expected, the type of window is recursive.
```
# let window = new window_subject;;
val window : < notify : 'a -> event -> unit; _.. > window_subject as 'a =
```
However, the two classes of window\_subject and window\_observer are not mutually recursive.
```
# let window_observer = new window_observer;;
val window_observer : < draw : unit; _.. > window_observer =
```
```
# window#add_observer window_observer;;
- : unit = ()
```
```
# window#move 1;;
{Position = 1}
- : unit = ()
```
Classes window\_observer and window\_subject can still be extended by inheritance. For instance, one may enrich the subject with new behaviors and refine the behavior of the observer.
```
# class ['observer] richer_window_subject =
object (self)
inherit ['observer] window_subject
val mutable size = 1
method resize x = size <- size + x; self#notify_observers Resize
val mutable top = false
method raise = top <- true; self#notify_observers Raise
method draw = Printf.printf "{Position = %d; Size = %d}\n" position size;
end;;
class ['a] richer_window_subject :
object ('b)
constraint 'a = < notify : 'b -> event -> unit; .. >
val mutable observers : 'a list
val mutable position : int
val mutable size : int
val mutable top : bool
method add_observer : 'a -> unit
method draw : unit
method identity : int
method move : int -> unit
method notify_observers : event -> unit
method raise : unit
method resize : int -> unit
end
```
```
# class ['subject] richer_window_observer =
object
inherit ['subject] window_observer as super
method notify s e = if e <> Raise then s#raise; super#notify s e
end;;
class ['a] richer_window_observer :
object
constraint 'a = < draw : unit; raise : unit; .. >
method notify : 'a -> event -> unit
end
```
We can also create a different kind of observer:
```
# class ['subject] trace_observer =
object
inherit ['subject, event] observer
method notify s e =
Printf.printf
"<Window %d <== %s>\n" s#identity (string_of_event e)
end;;
class ['a] trace_observer :
object
constraint 'a = < identity : int; .. >
method notify : 'a -> event -> unit
end
```
and attach several observers to the same object:
```
# let window = new richer_window_subject;;
val window :
< notify : 'a -> event -> unit; _.. > richer_window_subject as 'a =
```
```
# window#add_observer (new richer_window_observer);;
- : unit = ()
```
```
# window#add_observer (new trace_observer);;
- : unit = ()
```
```
# window#move 1; window#resize 2;;
{Position = 1; Size = 1}
{Position = 1; Size = 1}
{Position = 1; Size = 3}
{Position = 1; Size = 3}
- : unit = ()
```
| programming_docs |
ocaml None
[](#s:module-expr)11.11 Module expressions (module implementations)
---------------------------------------------------------------------
* [11.11.1 Simple module expressions](modules#ss%3Amexpr-simple)
* [11.11.2 Structures](modules#ss%3Amexpr-structures)
* [11.11.3 Functors](modules#ss%3Amexpr-functors)
Module expressions are the module-level equivalent of value expressions: they evaluate to modules, thus providing implementations for the specifications expressed in module types.
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| module-expr | ::= | [module-path](names#module-path) |
| | ∣ | struct [ [module-items](#module-items) ] end |
| | ∣ | functor ( [module-name](names#module-name) : [module-type](modtypes#module-type) ) -> [module-expr](#module-expr) |
| | ∣ | [module-expr](#module-expr) ( [module-expr](#module-expr) ) |
| | ∣ | ( [module-expr](#module-expr) ) |
| | ∣ | ( [module-expr](#module-expr) : [module-type](modtypes#module-type) ) |
| |
| module-items | ::= | { ;; } ( [definition](#definition) ∣ [expr](expr#expr) ) { { ;; } ( [definition](#definition) ∣ ;; [expr](expr#expr)) } { ;; } |
| |
| definition | ::= | let [rec] [let-binding](expr#let-binding) { and [let-binding](expr#let-binding) } |
| | ∣ | external [value-name](names#value-name) : [typexpr](types#typexpr) = [external-declaration](intfc#external-declaration) |
| | ∣ | [type-definition](typedecl#type-definition) |
| | ∣ | [exception-definition](typedecl#exception-definition) |
| | ∣ | [class-definition](classes#class-definition) |
| | ∣ | [classtype-definition](classes#classtype-definition) |
| | ∣ | module [module-name](names#module-name) { ( [module-name](names#module-name) : [module-type](modtypes#module-type) ) } [ : [module-type](modtypes#module-type) ] = [module-expr](#module-expr) |
| | ∣ | module type [modtype-name](names#modtype-name) = [module-type](modtypes#module-type) |
| | ∣ | open [module-path](names#module-path) |
| | ∣ | include [module-expr](#module-expr) |
|
See also the following language extensions: [recursive modules](recursivemodules#s%3Arecursive-modules), [first-class modules](firstclassmodules#s%3Afirst-class-modules), [overriding in open statements](overridingopen#s%3Aexplicit-overriding-open), [attributes](attributes#s%3Aattributes), [extension nodes](extensionnodes#s%3Aextension-nodes) and [generative functors](generativefunctors#s%3Agenerative-functors).
###
[](#ss:mexpr-simple)11.11.1 Simple module expressions
The expression [module-path](names#module-path) evaluates to the module bound to the name [module-path](names#module-path).
The expression ( [module-expr](#module-expr) ) evaluates to the same module as [module-expr](#module-expr).
The expression ( [module-expr](#module-expr) : [module-type](modtypes#module-type) ) checks that the type of [module-expr](#module-expr) is a subtype of [module-type](modtypes#module-type), that is, that all components specified in [module-type](modtypes#module-type) are implemented in [module-expr](#module-expr), and their implementation meets the requirements given in [module-type](modtypes#module-type). In other terms, it checks that the implementation [module-expr](#module-expr) meets the type specification [module-type](modtypes#module-type). The whole expression evaluates to the same module as [module-expr](#module-expr), except that all components not specified in [module-type](modtypes#module-type) are hidden and can no longer be accessed.
###
[](#ss:mexpr-structures)11.11.2 Structures
Structures struct … end are collections of definitions for value names, type names, exceptions, module names and module type names. The definitions are evaluated in the order in which they appear in the structure. The scopes of the bindings performed by the definitions extend to the end of the structure. As a consequence, a definition may refer to names bound by earlier definitions in the same structure.
For compatibility with toplevel phrases (chapter [14](toplevel#c%3Acamllight)), optional ;; are allowed after and before each definition in a structure. These ;; have no semantic meanings. Similarly, an [expr](expr#expr) preceded by ;; is allowed as a component of a structure. It is equivalent to let \_ = [expr](expr#expr), i.e. [expr](expr#expr) is evaluated for its side-effects but is not bound to any identifier. If [expr](expr#expr) is the first component of a structure, the preceding ;; can be omitted.
####
[](#sss:mexpr-value-defs)Value definitions
A value definition let [rec] [let-binding](expr#let-binding) { and [let-binding](expr#let-binding) } bind value names in the same way as a let … in … expression (see section [11.7.2](expr#sss%3Aexpr-localdef)). The value names appearing in the left-hand sides of the bindings are bound to the corresponding values in the right-hand sides.
A value definition external [value-name](names#value-name) : [typexpr](types#typexpr) = [external-declaration](intfc#external-declaration) implements [value-name](names#value-name) as the external function specified in [external-declaration](intfc#external-declaration) (see chapter [22](intfc#c%3Aintf-c)).
####
[](#sss:mexpr-type-defs)Type definitions
A definition of one or several type components is written type [typedef](typedecl#typedef) { and [typedef](typedecl#typedef) } and consists of a sequence of mutually recursive definitions of type names.
####
[](#sss:mexpr-exn-defs)Exception definitions
Exceptions are defined with the syntax exception [constr-decl](typedecl#constr-decl) or exception [constr-name](names#constr-name) = [constr](names#constr).
####
[](#sss:mexpr-class-defs)Class definitions
A definition of one or several classes is written class [class-binding](classes#class-binding) { and [class-binding](classes#class-binding) } and consists of a sequence of mutually recursive definitions of class names. Class definitions are described more precisely in section [11.9.3](classes#ss%3Aclass-def).
####
[](#sss:mexpr-classtype-defs)Class type definitions
A definition of one or several classes is written class type [classtype-def](classes#classtype-def) { and [classtype-def](classes#classtype-def) } and consists of a sequence of mutually recursive definitions of class type names. Class type definitions are described more precisely in section [11.9.5](classes#ss%3Aclasstype).
####
[](#sss:mexpr-module-defs)Module definitions
The basic form for defining a module component is module [module-name](names#module-name) = [module-expr](#module-expr), which evaluates [module-expr](#module-expr) and binds the result to the name [module-name](names#module-name).
One can write
module [module-name](names#module-name) : [module-type](modtypes#module-type) = [module-expr](#module-expr)
instead of
module [module-name](names#module-name) = ( [module-expr](#module-expr) : [module-type](modtypes#module-type) ).
Another derived form is
module [module-name](names#module-name) ( name1 : [module-type](modtypes#module-type)1 ) … ( namen : [module-type](modtypes#module-type)n ) = [module-expr](#module-expr)
which is equivalent to
module [module-name](names#module-name) = functor ( name1 : [module-type](modtypes#module-type)1 ) -> … -> [module-expr](#module-expr)
####
[](#sss:mexpr-modtype-defs)Module type definitions
A definition for a module type is written module type [modtype-name](names#modtype-name) = [module-type](modtypes#module-type). It binds the name [modtype-name](names#modtype-name) to the module type denoted by the expression [module-type](modtypes#module-type).
####
[](#sss:mexpr-open)Opening a module path
The expression open [module-path](names#module-path) in a structure does not define any components nor perform any bindings. It simply affects the parsing of the following items of the structure, allowing components of the module denoted by [module-path](names#module-path) to be referred to by their simple names name instead of path accesses [module-path](names#module-path) . name. The scope of the open stops at the end of the structure expression.
####
[](#sss:mexpr-include)Including the components of another structure
The expression include [module-expr](#module-expr) in a structure re-exports in the current structure all definitions of the structure denoted by [module-expr](#module-expr). For instance, if you define a module S as below
```
module S = struct type t = int let x = 2 end
```
defining the module B as
```
module B = struct include S let y = (x + 1 : t) end
```
is equivalent to defining it as
```
module B = struct type t = S.t let x = S.x let y = (x + 1 : t) end
```
The difference between open and include is that open simply provides short names for the components of the opened structure, without defining any components of the current structure, while include also adds definitions for the components of the included structure.
###
[](#ss:mexpr-functors)11.11.3 Functors
####
[](#sss:mexpr-functor-defs)Functor definition
The expression functor ( [module-name](names#module-name) : [module-type](modtypes#module-type) ) -> [module-expr](#module-expr) evaluates to a functor that takes as argument modules of the type [module-type](modtypes#module-type)1, binds [module-name](names#module-name) to these modules, evaluates [module-expr](#module-expr) in the extended environment, and returns the resulting modules as results. No restrictions are placed on the type of the functor argument; in particular, a functor may take another functor as argument (“higher-order” functor).
When the result module expression is itself a functor,
functor ( name1 : [module-type](modtypes#module-type)1 ) -> … -> functor ( namen : [module-type](modtypes#module-type)n ) -> [module-expr](#module-expr)
one may use the abbreviated form
functor ( name1 : [module-type](modtypes#module-type)1 ) … ( namen : [module-type](modtypes#module-type)n ) -> [module-expr](#module-expr)
####
[](#sss:mexpr-functor-app)Functor application
The expression [module-expr](#module-expr)1 ( [module-expr](#module-expr)2 ) evaluates [module-expr](#module-expr)1 to a functor and [module-expr](#module-expr)2 to a module, and applies the former to the latter. The type of [module-expr](#module-expr)2 must match the type expected for the arguments of the functor [module-expr](#module-expr)1.
ocaml Chapter 10 Memory model: The hard bits Chapter 10 Memory model: The hard bits
======================================
* [10.1 Why weakly consistent memory?](memorymodel#s%3Awhy_relaxed_memory)
* [10.2 Data race freedom implies sequential consistency](memorymodel#s%3Adrf_sc)
* [10.3 Reasoning with DRF-SC](memorymodel#s%3Adrf_reasoning)
* [10.4 Local data race freedom](memorymodel#s%3Alocal_drf)
* [10.5 An operational view of the memory model](memorymodel#s%3Amm_semantics)
* [10.6 Non-compliant operations](memorymodel#s%3Amm_tearing)
This chapter describes the details of OCaml relaxed memory model. The relaxed memory model describes what values an OCaml program is allowed to witness when reading a memory location. If you are interested in high-level parallel programming in OCaml, please have a look at the parallel programming chapter [9](parallelism#c%3Aparallelism).
This chapter is aimed at experts who would like to understand the details of the OCaml memory model from a practitioner’s perspective. For a formal definition of the OCaml memory model, its guarantees and the compilation to hardware memory models, please have a look at the PLDI 2018 paper on [Bounding Data Races in Space and Time](https://doi.org/10.1145/3192366.3192421). The memory model presented in this chapter is an extension of the one presented in the PLDI 2018 paper. This chapter also covers some pragmatic aspects of the memory model that are not covered in the paper.
[](#s:why_relaxed_memory)10.1 Why weakly consistent memory?
-------------------------------------------------------------
The simplest memory model that we could give to our programs is sequential consistency. Under sequential consistency, the values observed by the program can be explained through some interleaving of the operations from different domains in the program. For example, consider the following program with two domains d1 and d2 executing in parallel:
```
let d1 a b =
let r1 = !a * 2 in
let r2 = !b in
let r3 = !a * 2 in
(r1, r2, r3)
let d2 b = b := 0
let main () =
let a = ref 1 in
let b = ref 1 in
let h = Domain.spawn (fun _ ->
let r1, r2, r3 = d1 a b in
Printf.printf "r1 = %d, r2 = %d, r3 = %d\n" r1 r2 r3)
in
d2 b;
Domain.join h
```
The reference cells a and b are initially 1. The user may observe r1 = 2, r2 = 0, r3 = 2 if the write to b in d2 occurred before the read of b in d1. Here, the observed behaviour can be explained in terms of interleaving of the operations from different domains.
Let us now assume that a and b are aliases of each other.
```
let d1 a b =
let r1 = !a * 2 in
let r2 = !b in
let r3 = !a * 2 in
(r1, r2, r3)
let d2 b = b := 0
let main () =
let ab = ref 1 in
let h = Domain.spawn (fun _ ->
let r1, r2, r3 = d1 ab ab in
assert (not (r1 = 2 && r2 = 0 && r3 = 2)))
in
d2 ab;
Domain.join h
```
In the above program, the variables ab, a and b refer to the same reference cell. One would expect that the assertion in the main function will never fail. The reasoning is that if r2 is 0, then the write in d2 occurred before the read of b in d1. Given that a and b are aliases, the second read of a in d1 should also return 0.
###
[](#ss:mm_comp_opt)10.1.1 Compiler optimisations
Surprisingly, this assertion may fail in OCaml due to compiler optimisations. The OCaml compiler observes the common sub-expression !a \* 2 in d1 and optimises the program to:
```
let d1 a b =
let r1 = !a * 2 in
let r2 = !b in
let r3 = r1 in (* CSE: !a * 2 ==> r1 *)
(r1, r2, r3)
let d2 b = b := 0
let main () =
let ab = ref 1 in
let h = Domain.spawn (fun _ ->
let r1, r2, r3 = d1 ab ab in
assert (not (r1 = 2 && r2 = 0 && r3 = 2)))
in
d2 ab;
Domain.join h
```
This optimisation is known as the common sub-expression elimination (CSE). Such optimisations are valid and necessary for good performance, and do not change the sequential meaning of the program. However, CSE breaks sequential reasoning.
In the optimized program above, even if the write to b in d2 occurs between the first and the second reads in d1, the program will observe the value 2 for r3, causing the assertion to fail. The observed behaviour cannot be explained by interleaving of operations from different domains in the source program. Thus, CSE optimization is said to be invalid under sequential consistency.
One way to explain the observed behaviour is as if the operations performed on a domain were reordered. For example, if the second and the third reads from d2 were reordered,
```
let d1 a b =
let r1 = !a * 2 in
let r3 = !a * 2 in
let r2 = !b in
(r1, r2, r3)
```
then we can explain the observed behaviour (2,0,2) returned by d1.
###
[](#ss:mm_hw_opt)10.1.2 Hardware optimisations
The other source of reordering is by the hardware. Modern hardware architectures have complex cache hierarchies with multiple levels of cache. While cache coherence ensures that reads and writes to a single memory location respect sequential consistency, the guarantees on programs that operate on different memory locations are much weaker. Consider the following program:
```
let a = ref 0
and b = ref 0
let d1 () =
a := 1;
!b
let d2 () =
b := 1;
!a
let main () =
let h = Domain.spawn d2 in
let r1 = d1 () in
let r2 = Domain.join h in
assert (not (r1 = 0 && r2 = 0))
```
Under sequential consistency, we would never expect the assertion to fail. However, even on x86, which offers much stronger guarantees than ARM, the writes performed at a CPU core are not immediately published to all of the other cores. Since a and b are different memory locations, the reads of a and b may both witness the initial values, leading to the assertion failure.
This behaviour can be explained if a load is allowed to be reordered before a preceding store to a different memory location. This reordering can happen due to the presence of in-core store-buffers on modern processors. Each core effectively has a FIFO buffer of pending writes to avoid the need to block while a write completes. The writes to a and b may be in the store-buffers of cores c1 and c2 running the domains d1 and d2, respectively. The reads of b and a running on the cores c1 and c2, respectively, will not see the writes if the writes have not propagated from the buffers to the main memory.
[](#s:drf_sc)10.2 Data race freedom implies sequential consistency
--------------------------------------------------------------------
The aim of the OCaml relaxed memory model is to precisely describe which orders are preserved by the OCaml program. The compiler and the hardware are free to optimize the program as long as they respect the ordering guarantees of the memory model. While programming directly under the relaxed memory model is difficult, the memory model also describes the conditions under which a program will only exhibit sequentially consistent behaviours. This guarantee is known as *data race freedom implies sequential consistency* (DRF-SC). In this section, we shall describe this guarantee. In order to do this, we first need a number of definitions.
###
[](#s:atomics)10.2.1 Memory locations
OCaml classifies memory locations into *atomic* and *non-atomic* locations. Reference cells, array fields and mutable record fields are non-atomic memory locations. Immutable objects are non-atomic locations with an initialising write but no further updates. Atomic memory locations are those that are created using the [Atomic](libref/atomic) module.
###
[](#s:happens_before)10.2.2 Happens-before relation
Let us imagine that the OCaml programs are executed by an abstract machine that executes one action at a time, arbitrarily picking one of the available domains at each step. We classify actions into two: *inter-domain* and *intra-domain*. An inter-domain action is one which can be observed and be influenced by actions on other domains. There are several inter-domain actions:
* Reads and writes of atomic and non-atomic locations.
* Spawn and join of domains.
* Operations on mutexes.
On the other hand, intra-domain actions can neither be observed nor influence the execution of other domains. Examples include evaluating an arithmetic expression, calling a function, etc. The memory model specification ignores such intra-domain actions. In the sequel, we use the term action to indicate inter-domain actions.
A totally ordered list of actions executed by the abstract machine is called an *execution trace*. There might be several possible execution traces for a given program due to non-determinism.
For a given execution trace, we define an irreflexive, transitive *happens-before relation* that captures the causality between actions in the OCaml program. The happens-before relation is defined as the smallest transitive relation satisfying the following properties:
* We define the order in which a domain executes its actions as the *program order*. If an action x precedes another action y in program order, then x precedes y in happens-before order.
* If x is a write to an atomic location and y is a subsequent read or write to that memory location in the execution trace, then x precedes y in happens-before order. For atomic locations, compare\_and\_set, fetch\_and\_add, exchange, incr and decr are considered to perform both a read and a write.
* If x is Domain.spawn f and y is the first action in the newly spawned domain executing f, then x precedes y in happens-before order.
* If x is the last action in a domain d and y is Domain.join d, then x precedes y in happens-before order.
* If x is an unlock operation on a mutex, and y is any subsequent operation on the mutex in the execution trace, then x precedes y in happens-before order.
###
[](#s:datarace)10.2.3 Data race
In a given trace, two actions are said to be *conflicting* if they access the same non-atomic location, at least one is a write and neither is an initialising write to that location.
We say that a program has a *data race* if there exists some execution trace of the program with two conflicting actions and there does not exist a happens-before relationship between the conflicting accesses. A program without data races is said to be *correctly synchronised*.
###
[](#ss:drf_sc)10.2.4 DRF-SC
DRF-SC guarantee: A program without data races will only exhibit sequentially consistent behaviours.
DRF-SC is a strong guarantee for the programmers. Programmers can use *sequential reasoning* i.e., reasoning by executing one inter-domain action after the other, to identify whether their program has a data race. In particular, they do not need to reason about reorderings described in section [10.1](#s%3Awhy_relaxed_memory) in order to determine whether their program has a data race. Once the determination that a particular program is data race free is made, they do not need to worry about reorderings in their code.
[](#s:drf_reasoning)10.3 Reasoning with DRF-SC
------------------------------------------------
In this section, we will look at examples of using DRF-SC for program reasoning. In this section, we will use the functions with names dN to represent domains executing in parallel with other domains. That is, we assume that there is a main function that runs the dN functions in parallel as follows:
```
let main () =
let h1 = Domain.spawn d1 in
let h2 = Domain.spawn d2 in
...
ignore @@ Domain.join h1;
ignore @@ Domain.join h2
```
Here is a simple example with a data race:
```
(* Has data race *)
let r = ref 0
let d1 () = r := 1
let d2 () = !r
```
r is a non-atomic reference. The two domains race to access the reference, and d1 is a write. Since there is no happens-before relationship between the conflicting accesses, there is a data race.
Both of the programs that we had seen in the section [10.1](#s%3Awhy_relaxed_memory) have data races. It is no surprise that they exhibit non sequentially consistent behaviours.
Accessing disjoint array indices and fields of a record in parallel is not a data race. For example,
```
(* No data race *)
let a = [| 0; 1 |]
let d1 () = a.(0) <- 42
let d2 () = a.(1) <- 42
```
```
(* No data race *)
type t = {
mutable a : int;
mutable b : int
}
let r = {a = 0; b = 1}
let d1 () = r.a <- 42
let d2 () = r.b <- 42
```
do not have data races.
Races on atomic locations do not lead to a data race.
```
(* No data race *)
let r = Atomic.make 0
let d1 () = Atomic.set r 1
let d2 () = Atomic.get r
```
####
[](#s:mm_msg_passing)Message-passing
Atomic variables may be used for implementing non-blocking communication between domains.
```
(* No data race *)
let msg = ref 0
let flag = Atomic.make false
let d1 () =
msg := 42; (* a *)
Atomic.set flag true (* b *)
let d2 () =
if Atomic.get flag (* c *) then
!msg (* d *)
else 0
```
Observe that the actions a and d write and read from the same non-atomic location msg, respectively, and hence are conflicting. We need to establish that a and d have a happens-before relationship in order to show that this program does not have a data race.
The action a precedes b in program order, and hence, a happens-before b. Similarly, c happens-before d. If d2 observes the atomic variable flag to be true, then b precedes c in happens-before order. Since happens-before is transitive, the conflicting actions a and d are in happens-before order. If d2 observes the flag to be false, then the read of msg is not done. Hence, there is no conflicting access in this execution trace. Hence, the program does not have a data race.
The following modified version of the message passing program does have a data race.
```
(* Has data race *)
let msg = ref 0
let flag = Atomic.make false
let d1 () =
msg := 42; (* a *)
Atomic.set flag true (* b *)
let d2 () =
ignore (Atomic.get flag); (* c *)
!msg (* d *)
```
The domain d2 now unconditionally reads the non-atomic reference msg. Consider the execution trace:
```
Atomic.get flag; (* c *)
!msg; (* d *)
msg := 42; (* a *)
Atomic.set flag true (* b *)
```
In this trace, d and a are conflicting operations. But there is no happens-before relationship between them. Hence, this program has a data race.
[](#s:local_drf)10.4 Local data race freedom
----------------------------------------------
The OCaml memory model offers strong guarantees even for programs with data races. It offers what is known as *local data race freedom sequential consistency (LDRF-SC)* guarantee. A formal definition of this property is beyond the scope of this manual chapter. Interested readers are encouraged to read the PLDI 2018 paper on [Bounding Data Races in Space and Time](https://doi.org/10.1145/3192366.3192421).
Informally, LDRF-SC says that the data race free parts of the program remain sequentially consistent. That is, even if the program has data races, those parts of the program that are disjoint from the parts with data races are amenable to sequential reasoning.
Consider the following snippet:
```
let snippet () =
let c = ref 0 in
c := 42;
let a = !c in
(a, c)
```
Observe that c is a newly allocated reference. Can the read of c return a value which is not 42? That is, can a ever be not 42? Surprisingly, in the C++ and Java memory models, the answer is yes. With the C++ memory model, if the program has a data race, even in unrelated parts, then the semantics is undefined. If this snippet were linked with a library that had a data race, then, under the C++ memory model, the read may return any value. Since data races on unrelated locations can affect program behaviour, we say that C++ memory model is not bounded in space.
Unlike C++, Java memory model is bounded in space. But Java memory model is not bounded in time; data races in the future will affect the past behaviour. For example, consider the translation of this example to Java. We assume a prior definition of Class c {int x;} and a shared *non-volatile* variable C g. Now the snippet may be part of a larger program with parallel threads:
```
(* Thread 1 *)
C c = new C();
c.x = 42;
a = c.x;
g = c;
(* Thread 2 *)
g.x = 7;
```
The read of c.x and the write of g in the first thread are done on separate memory locations. Hence, the Java memory model allows them to be reordered. As a result, the write in the second thread may occur before the read of c.x, and hence, c.x returns 7.
The OCaml equivalent of the Java code above is:
```
let g = ref None
let snippet () =
let c = ref 0 in
c := 42;
let a = !c in
(a, c)
let d1 () =
let (a,c) = snippet () in
g := Some c;
a
let d2 () =
match !g with
| None -> ()
| Some c -> c := 7
```
Observe that there is a data race on both g and c. Consider only the first three instructions in snippet:
```
let c = ref 0 in
c := 42;
let a = !c in
...
```
The OCaml memory model is bounded both in space and time. The only memory location here is c. Reasoning only about this snippet, there is neither the data race in space (the race on g) nor in time (the future race on c). Hence, the snippet will have sequentially consistent behaviour, and the value returned by !c will be 42.
The OCaml memory model guarantees that even for programs with data races, memory safety is preserved. While programs with data races may observe non-sequentially consistent behaviours, they will not crash.
[](#s:mm_semantics)10.5 An operational view of the memory model
-----------------------------------------------------------------
In this section, we describe the semantics of the OCaml memory model. A formal definition of the operational view of the memory model is presented in section 3 of the PLDI 2018 paper on [Bounding Data Races in Space and Time](https://doi.org/10.1145/3192366.3192421). This section presents an informal description of the memory model with the help of an example.
Given an OCaml program, which may possibly contain data races, the operational semantics tells you the values that may be observed by the read of a memory location. For simplicity, we restrict the intra-thread actions to just the accesses to atomic and non-atomic locations, ignoring domain spawn and join operations, and the operations on mutexes.
We describe the semantics of the OCaml memory model in a straightforward small-step operational manner. That is, the semantics is described by an abstract machine that executes one action at a time, arbitrarily picking one of the available domains at each step. This is similar to the abstract machine that we had used to describe the happens-before relationship in section [10.2.2](#s%3Ahappens_before).
###
[](#ss:mm_non_atomic)10.5.1 Non-atomic locations
In the semantics, we model non-atomic locations as finite maps from timestamps t to values v. We take timestamps to be rational numbers. The timestamps are totally ordered but dense; there is a timestamp between any two others.
For example,
```
a: [t1 -> 1; t2 -> 2]
b: [t3 -> 3; t4 -> 4; t5 -> 5]
c: [t6 -> 5; t7 -> 6; t8 -> 7]
```
represents three non-atomic locations a, b and c and their histories. The location a has two writes at timestamps t1 and t2 with values 1 and 2, respectively. When we write a: [t1 -> 1; t2 -> 2], we assume that t1 < t2. We assume that the locations are initialised with a history that has a single entry at timestamp 0 that maps to the initial value.
###
[](#ss:mm_domains)10.5.2 Domains
Each domain is equipped with a *frontier*, which is a map from non-atomic locations to timestamps. Intuitively, each domain’s frontier records, for each non-atomic location, the latest write known to the thread. More recent writes may have occurred, but are not guaranteed to be visible.
For example,
```
d1: [a -> t1; b -> t3; c -> t7]
d2: [a -> t1; b -> t4; c -> t7]
```
represents two domains d1 and d2 and their frontiers.
###
[](#ss:mm_na_access)10.5.3 Non-atomic accesses
Let us now define the semantics of non-atomic reads and writes. Suppose domain d1 performs the read of b. For non-atomic reads, the domains may read an arbitrary element of the history for that location, as long as it is not older than the timestamp in the domains’s frontier. In this case, since d1 frontier at b is at t3, the read may return the value 3, 4 or 5. A non-atomic read does not change the frontier of the current domain.
Suppose domain d2 writes the value 10 to c (c := 10). We pick a new timestamp t9 for this write such that it is later than d2’s frontier at c. Note a subtlety here: this new timestamp might not be later than everything else in the history, but merely later than any other write known to the writing domain. Hence, t9 may be inserted in c’s history either (a) between t7 and t8 or (b) after t8. Let us pick the former option for our discussion. Since the new write appears after all the writes known by the domain d2 to the location c, d2’s frontier at c is also updated. The new state of the abstract machine is:
```
(* Non-atomic locations *)
a: [t1 -> 1; t2 -> 2]
b: [t3 -> 3; t4 -> 4; t5 -> 5]
c: [t6 -> 5; t7 -> 6; t9 -> 10; t8 -> 7] (* new write at t9 *)
(* Domains *)
d1: [a -> t1; b -> t3; c -> t7]
d2: [a -> t1; b -> t4; c -> t9] (* frontier updated at c *)
```
###
[](#ss:mm_at_access)10.5.4 Atomic accesses
Atomic locations carry not only values but also synchronization information. We model atomic locations as a pair of the value held by that location and a frontier. The frontier models the synchronization information, which is merged with the frontiers of threads that operate on the location. In this way, non-atomic writes made by one thread can become known to another by communicating via an atomic location.
For example,
```
(* Atomic locations *)
A: 10, [a -> t1; b -> t5; c -> t7]
B: 5, [a -> t2; b -> t4; c -> t6]
```
shows two atomic variables A and B with values 10 and 5, respectively, and frontiers of their own. We use upper-case variable names to indicate atomic locations.
During atomic reads, the frontier of the location is merged into that of the domain performing the read. For example, suppose d1 reads B. The read returns 5, and d1’s frontier updated by merging it with B’s frontier, choosing the later timestamp for each location. The abstract machine state before the atomic read is:
```
(* Non-atomic locations *)
a: [t1 -> 1; t2 -> 2]
b: [t3 -> 3; t4 -> 4; t5 -> 5]
c: [t6 -> 5; t7 -> 6; t9 -> 10; t8 -> 7]
(* Domains *)
d1: [a -> t1; b -> t3; c -> t7]
d2: [a -> t1; b -> t4; c -> t9]
(* Atomic locations *)
A: 10, [a -> t1; b -> t5; c -> t7]
B: 5, [a -> t2; b -> t4; c -> t6]
```
As a result of the atomic read, the abstract machine state is updated to:
```
(* Non-atomic locations *)
a: [t1 -> 1; t2 -> 2]
b: [t3 -> 3; t4 -> 4; t5 -> 5]
c: [t6 -> 5; t7 -> 6; t9 -> 10; t8 -> 7]
(* Domains *)
d1: [a -> t2; b -> t4; c -> t7] (* frontier updated at a and b *)
d2: [a -> t1; b -> t4; c -> t9]
(* Atomic locations *)
A: 10, [a -> t1; b -> t5; c -> t7]
B: 5, [a -> t2; b -> t4; c -> t6]
```
During atomic writes, the value held by the atomic location is updated. The frontiers of both the writing domain and that of the location being written to are updated to the merge of the two frontiers. For example, if d2 writes 20 to A in the current machine state, the machine state is updated to:
```
(* Non-atomic locations *)
a: [t1 -> 1; t2 -> 2]
b: [t3 -> 3; t4 -> 4; t5 -> 5]
c: [t6 -> 5; t7 -> 6; t9 -> 10; t8 -> 7]
(* Domains *)
d1: [a -> t2; b -> t4; c -> t7]
d2: [a -> t1; b -> t5; c -> t9] (* frontier updated at b *)
(* Atomic locations *)
A: 20, [a -> t1; b -> t5; c -> t9] (* value updated. frontier updated at c. *)
B: 5, [a -> t2; b -> t4; c -> t6]
```
###
[](#s:mm_semantics_reasoning)10.5.5 Reasoning with the semantics
Let us revisit an example from earlier (section [10.1](#s%3Awhy_relaxed_memory)).
```
let a = ref 0
and b = ref 0
let d1 () =
a := 1;
!b
let d2 () =
b := 1;
!a
let main () =
let h = Domain.spawn d2 in
let r1 = d1 () in
let r2 = Domain.join h in
assert (not (r1 = 0 && r2 = 0))
```
This program has a data race on a and b, and hence, the program may exhibit non sequentially consistent behaviour. Let us use the semantics to show that the program may exhibit r1 = 0 && r2 = 0.
The initial state of the abstract machine is:
```
(* Non-atomic locations *)
a: [t0 -> 0]
b: [t1 -> 0]
(* Domains *)
d1: [a -> t0; b -> t1]
d2: [a -> t0; b -> t1]
```
There are several possible schedules for executing this program. Let us consider the following schedule:
```
1: a := 1 @ d1
2: b := 1 @ d2
3: !b @ d1
4: !a @ d2
```
After the first action a:=1 by d1, the machine state is:
```
(* Non-atomic locations *)
a: [t0 -> 0; t2 -> 1] (* new write at t2 *)
b: [t1 -> 0]
(* Domains *)
d1: [a -> t2; b -> t1] (* frontier updated at a *)
d2: [a -> t0; b -> t1]
```
After the second action b:=1 by d2, the machine state is:
```
(* Non-atomic locations *)
a: [t0 -> 0; t2 -> 1]
b: [t1 -> 0; t3 -> 1] (* new write at t3 *)
(* Domains *)
d1: [a -> t2; b -> t1]
d2: [a -> t0; b -> t3] (* frontier updated at b *)
```
Now, for the third action !b by d1, observe that d1’s frontier at b is at t1. Hence, the read may return either 0 or 1. Let us assume that it returns 0. The machine state is not updated by the non-atomic read.
Similarly, for the fourth action !a by d2, d2’s frontier at a is at t0. Hence, this read may also return either 0 or 1. Let us assume that it returns 0. Hence, the assertion in the original program, assert (not (r1 = 0 && r2 = 0)), will fail for this particular execution.
[](#s:mm_tearing)10.6 Non-compliant operations
------------------------------------------------
There are certain operations which are not memory model compliant.
* Array.blit function on float arrays may cause *tearing*. When an unsynchronized blit operation runs concurrently with some overlapping write to the fields of the same float array, the field may end up with bits from either of the writes.
* With flat-float arrays or records with only float fields on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing.
* The Bytes module [Bytes](libref/bytes) permits mixed-mode accesses where reads and writes may be of different sizes. Unsynchronized mixed-mode accesses lead to tearing.
| programming_docs |
ocaml Chapter 26 The “Tail Modulo Constructor” program transformation Chapter 26 The “Tail Modulo Constructor” program transformation
===============================================================
* [26.1 Disambiguation](tail_mod_cons#sec%3Adisambiguation)
* [26.2 Danger: getting out of tail-mod-cons](tail_mod_cons#sec%3Aout-of-tmc)
* [26.3 Details on the transformation](tail_mod_cons#sec%3Adetails)
* [26.4 Current limitations](tail_mod_cons#sec%3Alimitations)
(Introduced in OCaml 4.14)
Note: this feature is considered experimental, and its interface may evolve, with user feedback, in the next few releases of the language.
Consider this natural implementation of the List.map function:
```
let rec map f l =
match l with
| [] -> []
| x :: xs ->
let y = f x in
y :: map f xs
```
A well-known limitation of this implementation is that the recursive call, map f xs, is not in *tail* position. The runtime needs to remember to continue with y :: r after the call returns a value r, therefore this function consumes some amount of call-stack space on each recursive call. The stack usage of map f li is proportional to the length of li. This is a correctness issue for large lists on operating systems with limited stack space – the dreaded Stack\_overflow exception.
```
# List.length (map Fun.id (List.init 1_000_000 Fun.id));;
- : int = 1000000
```
In this implementation of map, the recursive call happens in a position that is not a *tail* position in the program, but within a datatype constructor application that is itself in *tail* position. We say that those positions, that are composed of tail positions and constructor applications, are *tail modulo constructor* (TMC) positions – we sometimes write *tail modulo cons* for brevity.
It is possible to rewrite programs such that tail modulo cons positions become tail positions; after this transformation, the implementation of map above becomes *tail-recursive*, in the sense that it only consumes a constant amount of stack space. The OCaml compiler implements this transformation on demand, using the [@tail\_mod\_cons] or [@ocaml.tail\_mod\_cons] attribute on the function to transform.
```
let[@tail_mod_cons] rec map f l =
match l with
| [] -> []
| x :: xs ->
let y = f x in
y :: map f xs
```
```
# List.length (map Fun.id (List.init 1_000_000 Fun.id));;
- : int = 1000000
```
This transformation only improves calls in tail-modulo-cons position, it does not improve recursive calls that do not fit in this fragment:
```
(* does *not* work: addition is not a data constructor *)
let[@tail_mod_cons] rec length l =
match l with
| [] -> 0
| _ :: xs -> 1 + length xs
Warning 71 [unused-tmc-attribute]: This function is marked @tail_mod_cons
but is never applied in TMC position.
```
It is of course possible to use the [@tail\_mod\_cons] transformation on functions that contain some recursive calls in tail-modulo-cons position, and some calls in other, arbitrary positions. Only the tail calls and tail-modulo-cons calls will happen in constant stack space.
#####
[](#sec616)General design
This feature is provided as an explicit program transformation, not an implicit optimization. It is annotation-driven: the user is expected to express their intent by adding annotations in the program using attributes, and will be asked to do so in any ambiguous situation.
We expect it to be used mostly by advanced OCaml users needing to get some guarantees on the stack-consumption behavior of their programs. Our recommendation is to use the [@tailcall] annotation on all callsites that should not consume any stack space. [@tail\_mod\_cons] extends the set of functions on which calls can be annotated to be tail calls, helping establish stack-consumption guarantees in more cases.
#####
[](#sec617)Performance
A standard approach to get a tail-recursive version of List.map is to use an accumulator to collect output elements, and reverse it at the end of the traversal.
```
let rec map f l = map_aux f [] l
and map_aux f acc l =
match l with
| [] -> List.rev acc
| x :: xs ->
let y = f x in
map_aux f (y :: acc) xs
```
This version is tail-recursive, but it is measurably slower than the simple, non-tail-recursive version. In contrast, the tail-mod-cons transformation provides an implementation that has comparable performance to the original version, even on small inputs.
#####
[](#sec618)Evaluation order
Beware that the tail-modulo-cons transformation has an effect on evaluation order: the constructor argument that is transformed into tail-position will always be evaluated last. Consider the following example:
```
type 'a two_headed_list =
| Nil
| Consnoc of 'a * 'a two_headed_list * 'a
let[@tail_mod_cons] rec map f = function
| Nil -> Nil
| Consnoc (front, body, rear) ->
Consnoc (f front, map f body, f rear)
```
Due to the [@tail\_mod\_cons] transformation, the calls to f front and f rear will be evaluated before map f body. In particular, this is likely to be different from the evaluation order of the unannotated version. (The evaluation order of constructor arguments is unspecified in OCaml, but many implementations typically use left-to-right or right-to-left.)
This effect on evaluation order is one of the reasons why the tail-modulo-cons transformation has to be explicitly requested by the user, instead of being applied as an automatic optimization.
#####
[](#sec619)Why tail-modulo-cons?
Other program transformations, in particular a transformation to continuation-passing style (CPS), can make all functions tail-recursive, instead of targeting only a small fragment. Some reasons to provide builtin support for the less-general tail-mod-cons are as follows:
* The tail-mod-cons transformation preserves the performance of the original, non-tail-recursive version, while a continuation-passing-style transformation incurs a measurable constant-factor overhead.
* The tail-mod-cons transformation cannot be expressed as a source-to-source transformation of OCaml programs, as it relies on mutable state in type-unsafe ways. In contrast, continuation-passing-style versions can be written by hand, possibly using a convenient monadic notation.
[](#sec:disambiguation)26.1 Disambiguation
--------------------------------------------
It may happen that several arguments of a constructor are recursive calls to a tail-modulo-cons function. The transformation can only turn one of these calls into a tail call. The compiler will not make an implicit choice, but ask the user to provide an explicit disambiguation.
Consider this type of syntactic expressions (assuming some pre-existing type var of expression variables):
```
type var (* some pre-existing type of variables *)
type exp =
| Var of var
| Let of binding * exp
and binding = var * exp
```
Consider a map function on variables. The direct definition has two recursive calls inside arguments of the Let constructor, so it gets rejected as ambiguous.
```
let[@tail_mod_cons] rec map_vars f exp =
match exp with
| Var v -> Var (f v)
| Let ((v, def), body) ->
Let ((f v, map_vars f def), map_vars f body)
Error: [@tail_mod_cons]: this constructor application may be TMC-transformed
in several different ways. Please disambiguate by adding an explicit
[@tailcall] attribute to the call that should be made tail-recursive,
or a [@tailcall false] attribute on calls that should not be
transformed.
This call could be annotated.
This call could be annotated.
```
To disambiguate, the user should add a [@tailcall] attribute to the recursive call that should be transformed to tail position:
```
let[@tail_mod_cons] rec map_vars f exp =
match exp with
| Var v -> Var (f v)
| Let ((v, def), body) ->
Let ((f v, map_vars f def), (map_vars[@tailcall]) f body)
```
Be aware that the resulting function is *not* tail-recursive, the recursive call on def will consume stack space. However, expression trees tend to be right-leaning (lots of Let in sequence, rather than nested inside each other), so putting the call on body in tail position is an interesting improvement over the naive definition: it gives bounded stack space consumption if we assume a bound on the nesting depth of Let constructs.
One would also get an error when using conflicting annotations, asking for two of the constructor arguments to be put in tail position:
```
let[@tail_mod_cons] rec map_vars f exp =
match exp with
| Var v -> Var (f v)
| Let ((v, def), body) ->
Let ((f v, (map_vars[@tailcall]) f def), (map_vars[@tailcall]) f body)
Error: [@tail_mod_cons]: this constructor application may be TMC-transformed
in several different ways. Only one of the arguments may become a TMC
call, but several arguments contain calls that are explicitly marked
as tail-recursive. Please fix the conflict by reviewing and fixing the
conflicting annotations.
This call is explicitly annotated.
This call is explicitly annotated.
```
[](#sec:out-of-tmc)26.2 Danger: getting out of tail-mod-cons
--------------------------------------------------------------
Due to the nature of the tail-mod-cons transformation (see Section [26.3](#sec%3Adetails) for a presentation of transformation):
* Calls from a tail-mod-cons function to another tail-mod-cons function declared in the same recursive-binding group are transformed into tail calls, as soon as they occur in tail position or tail-modulo-cons position in the source function.
* Calls from a function *not* annotated tail-mod-cons to a tail-mod-cons function or, conversely, from a tail-mod-cons function to a non-tail-mod-cons function are transformed into *non*-tail calls, even if they syntactically appear in tail position in the source program.
The fact that calls in tail position in the source program may become non-tail calls if they go from a tail-mod-cons to a non-tail-mod-cons function is surprising, and the transformation will warn about them.
For example:
```
let[@tail_mod_cons] rec flatten = function
| [] -> []
| xs :: xss ->
let rec append_flatten xs xss =
match xs with
| [] -> flatten xss
| x :: xs -> x :: append_flatten xs xss
in append_flatten xs xss
Warning 71 [unused-tmc-attribute]: This function is marked @tail_mod_cons
but is never applied in TMC position.
Warning 72 [tmc-breaks-tailcall]: This call
is in tail-modulo-cons positionin a TMC function,
but the function called is not itself specialized for TMC,
so the call will not be transformed into a tail call.
Please either mark the called function with the [@tail_mod_cons]
attribute, or mark this call with the [@tailcall false] attribute
to make its non-tailness explicit.
```
Here the append\_flatten helper is not annotated with [@tail\_mod\_cons], so the calls append\_flatten xs xss and flatten xss will *not* be tail calls. The correct fix here is to annotate append\_flatten to be tail-mod-cons.
```
let[@tail_mod_cons] rec flatten = function
| [] -> []
| xs :: xss ->
let[@tail_mod_cons] rec append_flatten xs xss =
match xs with
| [] -> flatten xss
| x :: xs -> x :: append_flatten xs xss
in append_flatten xs xss
```
The same warning occurs when append\_flatten is a non-tail-mod-cons function of the same recursive group; using the tail-mod-cons transformation is a property of individual functions, not whole recursive groups.
```
let[@tail_mod_cons] rec flatten = function
| [] -> []
| xs :: xss -> append_flatten xs xss
and append_flatten xs xss =
match xs with
| [] -> flatten xss
| x :: xs -> x :: append_flatten xs xss
Warning 71 [unused-tmc-attribute]: This function is marked @tail_mod_cons
but is never applied in TMC position.
Warning 72 [tmc-breaks-tailcall]: This call
is in tail-modulo-cons positionin a TMC function,
but the function called is not itself specialized for TMC,
so the call will not be transformed into a tail call.
Please either mark the called function with the [@tail_mod_cons]
attribute, or mark this call with the [@tailcall false] attribute
to make its non-tailness explicit.
```
Again, the fix is to specialize append\_flatten as well:
```
let[@tail_mod_cons] rec flatten = function
| [] -> []
| xs :: xss -> append_flatten xs xss
and[@tail_mod_cons] append_flatten xs xss =
match xs with
| [] -> flatten xss
| x :: xs -> x :: append_flatten xs xss
```
Non-recursive functions can also be annotated [@tail\_mod\_cons]; this is typically useful for local bindings to recursive functions.
Incorrect version:
```
let[@tail_mod_cons] rec map_vars f exp =
let self exp = map_vars f exp in
match exp with
| Var v -> Var (f v)
| Let ((v, def), body) ->
Let ((f v, self def), (self[@tailcall]) body)
Warning 51 [wrong-tailcall-expectation]: expected tailcall
Warning 51 [wrong-tailcall-expectation]: expected tailcall
Warning 71 [unused-tmc-attribute]: This function is marked @tail_mod_cons
but is never applied in TMC position.
```
Recommended fix:
```
let[@tail_mod_cons] rec map_vars f exp =
let[@tail_mod_cons] self exp = map_vars f exp in
match exp with
| Var v -> Var (f v)
| Let ((v, def), body) ->
Let ((f v, self def), (self[@tailcall]) body)
```
In other cases, there is either no benefit in making the called function tail-mod-cons, or it is not possible: for example, it is a function parameter (the transformation only works with direct calls to known functions).
For example, consider a substitution function on binary trees:
```
type 'a tree = Leaf of 'a | Node of 'a tree * 'a tree
let[@tail_mod_cons] rec bind (f : 'a -> 'a tree) (t : 'a tree) : 'a tree =
match t with
| Leaf v -> f v
| Node (left, right) ->
Node (bind f left, (bind[@tailcall]) f right)
Warning 72 [tmc-breaks-tailcall]: This call
is in tail-modulo-cons positionin a TMC function,
but the function called is not itself specialized for TMC,
so the call will not be transformed into a tail call.
Please either mark the called function with the [@tail_mod_cons]
attribute, or mark this call with the [@tailcall false] attribute
to make its non-tailness explicit.
```
Here f is a function parameter, not a direct call, and the current implementation is strictly first-order, it does not support tail-mod-cons arguments. In this case, the user should indicate that they realize this call to f v is not, in fact, in tail position, by using (f[@tailcall false]) v.
```
type 'a tree = Leaf of 'a | Node of 'a tree * 'a tree
let[@tail_mod_cons] rec bind (f : 'a -> 'a tree) (t : 'a tree) : 'a tree =
match t with
| Leaf v -> (f[@tailcall false]) v
| Node (left, right) ->
Node (bind f left, (bind[@tailcall]) f right)
```
[](#sec:details)26.3 Details on the transformation
----------------------------------------------------
To use this advanced feature, it helps to be aware that the function transformation produces a specialized function in destination-passing-style.
Recall our map example:
```
let rec map f l =
match l with
| [] -> []
| x :: xs ->
let y = f x in
y :: map f xs
```
Below is a description of the transformed program in pseudo-OCaml notation: some operations are not expressible in OCaml source code. (The transformation in fact happens on the Lambda intermediate representation of the OCaml compiler.)
```
let rec map f l =
match l with
| [] -> []
| x :: xs ->
let y = f x in
let dst = y ::{mutable} Hole in
map_dps f xs dst 1;
dst
and map_dps f l dst idx =
match l with
| [] -> dst.idx <- []
| x :: xs ->
let y = f x in
let dst' = y ::{mutable} Hole in
dst.idx <- dst';
map_dps f xs dst' 1
```
The source version of map gets transformed into two functions, a *direct-style* version that is also called map, and a *destination-passing-style* version (DPS) called map\_dps. The destination-passing-style version does not return a result directly, instead it writes it into a memory location specified by two additional function parameters, dst (a memory block) and i (a position within the memory block).
The source call y :: map f xs gets transformed into the creation of a mutable block y ::{mutable} Hole, whose second parameter is an un-initialized *hole*. The block is then passed to map\_dps as a destination parameter (with offset 1).
Notice that map does not call itself recursively, it calls map\_dps. Then, map\_dps calls itself recursively, in a tail-recursive way.
The call from map to map\_dps is *not* a tail call (this is something that we could improve in the future); but this call happens only once when invoking map f l, with all list elements after the first one processed in constant stack by map\_dps.
This explains the “getting out of tail-mod-cons” subtleties. Consider our previous example involving mutual recursion between flatten and append\_flatten.
```
let[@tail_mod_cons] rec flatten l =
match l with
| [] -> []
| xs :: xss ->
append_flatten xs xss
```
The call to append\_flatten, which syntactically appears in tail position, gets transformed differently depending on whether the function has a destination-passing-style version available, that is, whether it is itself annotated [@tail\_mod\_cons]:
```
(* if append_flatten_dps exists *)
and flatten_dps l dst i =
match l with
| [] -> dst.i <- []
| xs :: xss ->
append_flatten_dps xs xss dst i
(* if append_flatten_dps does not exist *)
and rec flatten_dps l dst i =
match l with
| [] -> dst.i <- []
| xs :: xss ->
dst.i <- append_flatten xs xss
```
If append\_flatten does not have a destination-passing-style version, the call gets transformed to a non-tail call.
[](#sec:limitations)26.4 Current limitations
----------------------------------------------
#####
[](#sec624)Purely syntactic criterion
Just like tail calls in general, the notion of tail-modulo-constructor position is purely syntactic; some simple refactoring will move calls out of tail-modulo-constructor position.
```
(* works as expected *)
let[@tail_mod_cons] rec map f li =
match li with
| [] -> []
| x :: xs ->
let y = f x in
y ::
(* this call is in TMC position *)
map f xs
```
```
(* not optimizable anymore *)
let[@tail_mod_cons] rec map f li =
match li with
| [] -> []
| x :: xs ->
let y = f x in
let ys =
(* this call is not in TMC position anymore *)
map f xs in
y :: ys
Warning 71 [unused-tmc-attribute]: This function is marked @tail_mod_cons
but is never applied in TMC position.
```
#####
[](#sec625)Local, first-order transformation
When a function gets transformed with tail-mod-cons, two definitions are generated, one providing a direct-style interface and one providing the destination-passing-style version. However, not all calls to this function in tail-modulo-cons position will use the destination-passing-style version and become tail calls:
* The transformation is local: only tail-mod-cons calls to foo within the same compilation unit as foo become tail calls.
* The transformation is first-order: only direct calls to known tail-mod-cons functions become tail calls when in tail-mod-cons position, never calls to function parameters.
Consider the call Option.map foo x for example: even if foo is called in tail-mod-cons position within the definition of Option.map, that call will never become a tail call. (This would be the case even if the call to Option.map was inside the Option module.)
In general this limitation is not a problem for recursive functions: the first call from an outside module or a higher-order function will consume stack space, but further recursive calls in tail-mod-cons position will get optimized. For example, if List.map is defined as a tail-mod-cons function, calls from outside the List module will not become tail calls when in tail positions, but the recursive calls within the definition of List.map are in tail-modulo-cons positions and do become tail calls: processing the first element of the list will consume stack space, but all further elements are handled in constant space.
These limitations may be an issue in more complex situations where mutual recursion happens between functions, with some functions not annotated tail-mod-cons, or defined across different modules, or called indirectly, for example through function parameters.
#####
[](#sec626)Non-exact calls to tupled functions
OCaml performs an implicit optimization for “tupled” functions, which take a single parameter that is a tuple: let f (x, y, z) = .... Direct calls to these functions with a tuple literal argument (like f (a, b, c)) will call the “tupled” function by passing the parameters directly, instead of building a tuple of them. Other calls, either indirect calls or calls passing a more complex tuple value (like let t = (a, b, c) in f t) are compiled as “inexact” calls that go through a wrapper.
The [@tail\_mod\_cons] transformation supports tupled functions, but will only optimize “exact” calls in tail position; direct calls to something other than a tuple literal will not become tail calls. The user can manually unpack a tuple to force a call to be “exact”: let (x, y, z) = t in f (x, y, z). If there is any doubt as to whether a call can be tail-mod-cons-optimized or not, one can use the [@tailcall] attribute on the called function, which will warn if the transformation is not possible.
```
let rec map (f, l) =
match l with
| [] -> []
| x :: xs ->
let y = f x in
let args = (f, xs) in
(* this inexact call cannot be tail-optimized, so a warning will be raised *)
y :: (map[@tailcall]) args
Warning 51 [wrong-tailcall-expectation]: expected tailcall
```
| programming_docs |
ocaml None
[](#s:lexical-conventions)11.1 Lexical conventions
----------------------------------------------------
####
[](#sss:lex:blanks)Blanks
The following characters are considered as blanks: space, horizontal tabulation, carriage return, line feed and form feed. Blanks are ignored, but they separate adjacent identifiers, literals and keywords that would otherwise be confused as one single identifier, literal or keyword.
####
[](#sss:lex:comments)Comments
Comments are introduced by the two characters (\*, with no intervening blanks, and terminated by the characters \*), with no intervening blanks. Comments are treated as blank characters. Comments do not occur inside string or character literals. Nested comments are handled correctly.
```
(* single line comment *)
(* multiple line comment, commenting out part of a program, and containing a
nested comment:
let f = function
| 'A'..'Z' -> "Uppercase"
(* Add other cases later... *)
*)
```
####
[](#sss:lex:identifiers)Identifiers
| | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| ident | ::= | ([letter](#letter) ∣ \_) { [letter](#letter) ∣ 0…9 ∣ \_ ∣ ' } |
| |
| capitalized-ident | ::= | (A…Z) { [letter](#letter) ∣ 0…9 ∣ \_ ∣ ' } |
| |
| lowercase-ident | ::= | (a…z ∣ \_) { [letter](#letter) ∣ 0…9 ∣ \_ ∣ ' } |
| |
| letter | ::= | A…Z ∣ a…z |
|
Identifiers are sequences of letters, digits, \_ (the underscore character), and ' (the single quote), starting with a letter or an underscore. Letters contain at least the 52 lowercase and uppercase letters from the ASCII set. The current implementation also recognizes as letters some characters from the ISO 8859-1 set (characters 192–214 and 216–222 as uppercase letters; characters 223–246 and 248–255 as lowercase letters). This feature is deprecated and should be avoided for future compatibility.
All characters in an identifier are meaningful. The current implementation accepts identifiers up to 16000000 characters in length.
In many places, OCaml makes a distinction between capitalized identifiers and identifiers that begin with a lowercase letter. The underscore character is considered a lowercase letter for this purpose.
####
[](#sss:integer-literals)Integer literals
| | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| integer-literal | ::= | [-] (0…9) { 0…9 ∣ \_ } |
| | ∣ | [-] (0x ∣ 0X) (0…9 ∣ A…F ∣ a…f) { 0…9 ∣ A…F ∣ a…f ∣ \_ } |
| | ∣ | [-] (0o ∣ 0O) (0…7) { 0…7 ∣ \_ } |
| | ∣ | [-] (0b ∣ 0B) (0…1) { 0…1 ∣ \_ } |
| |
| int32-literal | ::= | [integer-literal](#integer-literal) l |
| |
| int64-literal | ::= | [integer-literal](#integer-literal) L |
| |
| nativeint-literal | ::= | [integer-literal](#integer-literal) n |
|
An integer literal is a sequence of one or more digits, optionally preceded by a minus sign. By default, integer literals are in decimal (radix 10). The following prefixes select a different radix:
| | |
| --- | --- |
| Prefix | Radix |
| 0x, 0X | hexadecimal (radix 16) |
| 0o, 0O | octal (radix 8) |
| 0b, 0B | binary (radix 2) |
(The initial 0 is the digit zero; the O for octal is the letter O.) An integer literal can be followed by one of the letters l, L or n to indicate that this integer has type int32, int64 or nativeint respectively, instead of the default type int for integer literals. The interpretation of integer literals that fall outside the range of representable integer values is undefined.
For convenience and readability, underscore characters (\_) are accepted (and ignored) within integer literals.
```
# let house_number = 37
let million = 1_000_000
let copyright = 0x00A9
let counter64bit = ref 0L;;
val house_number : int = 37
val million : int = 1000000
val copyright : int = 169
val counter64bit : int64 ref = {contents = 0L}
```
####
[](#sss:floating-point-literals)Floating-point literals
| | | | | | | |
| --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| float-literal | ::= | [-] (0…9) { 0…9 ∣ \_ } [. { 0…9 ∣ \_ }] [(e ∣ E) [+ ∣ -] (0…9) { 0…9 ∣ \_ }] |
| | ∣ | [-] (0x ∣ 0X) (0…9 ∣ A…F ∣ a…f) { 0…9 ∣ A…F ∣ a…f ∣ \_ } [. { 0…9 ∣ A…F ∣ a…f ∣ \_ }] [(p ∣ P) [+ ∣ -] (0…9) { 0…9 ∣ \_ }] |
|
Floating-point decimal literals consist in an integer part, a fractional part and an exponent part. The integer part is a sequence of one or more digits, optionally preceded by a minus sign. The fractional part is a decimal point followed by zero, one or more digits. The exponent part is the character e or E followed by an optional + or - sign, followed by one or more digits. It is interpreted as a power of 10. The fractional part or the exponent part can be omitted but not both, to avoid ambiguity with integer literals. The interpretation of floating-point literals that fall outside the range of representable floating-point values is undefined.
Floating-point hexadecimal literals are denoted with the 0x or 0X prefix. The syntax is similar to that of floating-point decimal literals, with the following differences. The integer part and the fractional part use hexadecimal digits. The exponent part starts with the character p or P. It is written in decimal and interpreted as a power of 2.
For convenience and readability, underscore characters (\_) are accepted (and ignored) within floating-point literals.
```
# let pi = 3.141_592_653_589_793_12
let small_negative = -1e-5
let machine_epsilon = 0x1p-52;;
val pi : float = 3.14159265358979312
val small_negative : float = -1e-05
val machine_epsilon : float = 2.22044604925031308e-16
```
####
[](#sss:character-literals)Character literals
| | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| char-literal | ::= | ' regular-char ' |
| | ∣ | ' [escape-sequence](#escape-sequence) ' |
| |
| escape-sequence | ::= | \ (\ ∣ " ∣ ' ∣ n ∣ t ∣ b ∣ r ∣ space) |
| | ∣ | \ (0…9) (0…9) (0…9) |
| | ∣ | \x (0…9 ∣ A…F ∣ a…f) (0…9 ∣ A…F ∣ a…f) |
| | ∣ | \o (0…3) (0…7) (0…7) |
|
Character literals are delimited by ' (single quote) characters. The two single quotes enclose either one character different from ' and \, or one of the escape sequences below:
| | |
| --- | --- |
| Sequence | Character denoted |
| \\ | backslash (\) |
| \" | double quote (") |
| \' | single quote (') |
| \n | linefeed (LF) |
| \r | carriage return (CR) |
| \t | horizontal tabulation (TAB) |
| \b | backspace (BS) |
| \space | space (SPC) |
| \ddd | the character with ASCII code ddd in decimal |
| \xhh | the character with ASCII code hh in hexadecimal |
| \oooo | the character with ASCII code ooo in octal |
```
# let a = 'a'
let single_quote = '\''
let copyright = '\xA9';;
val a : char = 'a'
val single_quote : char = '\''
val copyright : char = '\169'
```
####
[](#sss:stringliterals)String literals
| | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| string-literal | ::= | " { [string-character](#string-character) } " |
| | ∣ | { [quoted-string-id](#quoted-string-id) | { any-char } | [quoted-string-id](#quoted-string-id) } |
| |
| quoted-string-id | ::= | { a...z ∣ \_ } |
| |
| string-character | ::= | regular-string-char |
| | ∣ | [escape-sequence](#escape-sequence) |
| | ∣ | \u{ { 0…9 ∣ A…F ∣ a…f }+ } |
| | ∣ | \ newline { space ∣ tab } |
|
String literals are delimited by " (double quote) characters. The two double quotes enclose a sequence of either characters different from " and \, or escape sequences from the table given above for character literals, or a Unicode character escape sequence.
A Unicode character escape sequence is substituted by the UTF-8 encoding of the specified Unicode scalar value. The Unicode scalar value, an integer in the ranges 0x0000...0xD7FF or 0xE000...0x10FFFF, is defined using 1 to 6 hexadecimal digits; leading zeros are allowed.
```
# let greeting = "Hello, World!\n"
let superscript_plus = "\u{207A}";;
val greeting : string = "Hello, World!\n"
val superscript_plus : string = "⁺"
```
To allow splitting long string literals across lines, the sequence \newline spaces-or-tabs (a backslash at the end of a line followed by any number of spaces and horizontal tabulations at the beginning of the next line) is ignored inside string literals.
```
# let longstr =
"Call me Ishmael. Some years ago — never mind how long \
precisely — having little or no money in my purse, and \
nothing particular to interest me on shore, I thought I\
\ would sail about a little and see the watery part of t\
he world.";;
val longstr : string =
"Call me Ishmael. Some years ago — never mind how long precisely — having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world."
```
Quoted string literals provide an alternative lexical syntax for string literals. They are useful to represent strings of arbitrary content without escaping. Quoted strings are delimited by a matching pair of { [quoted-string-id](#quoted-string-id) | and | [quoted-string-id](#quoted-string-id) } with the same [quoted-string-id](#quoted-string-id) on both sides. Quoted strings do not interpret any character in a special way but requires that the sequence | [quoted-string-id](#quoted-string-id) } does not occur in the string itself. The identifier [quoted-string-id](#quoted-string-id) is a (possibly empty) sequence of lowercase letters and underscores that can be freely chosen to avoid such issue.
```
# let quoted_greeting = {|"Hello, World!"|}
let nested = {ext|hello {|world|}|ext};;
val quoted_greeting : string = "\"Hello, World!\""
val nested : string = "hello {|world|}"
```
The current implementation places practically no restrictions on the length of string literals.
####
[](#sss:labelname)Naming labels
To avoid ambiguities, naming labels in expressions cannot just be defined syntactically as the sequence of the three tokens ~, [ident](#ident) and :, and have to be defined at the lexical level.
| | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| label-name | ::= | [lowercase-ident](#lowercase-ident) |
| |
| label | ::= | ~ [label-name](#label-name) : |
| |
| optlabel | ::= | ? [label-name](#label-name) : |
|
Naming labels come in two flavours: [label](#label) for normal arguments and [optlabel](#optlabel) for optional ones. They are simply distinguished by their first character, either ~ or ?.
Despite [label](#label) and [optlabel](#optlabel) being lexical entities in expressions, their expansions ~ [label-name](#label-name) : and ? [label-name](#label-name) : will be used in grammars, for the sake of readability. Note also that inside type expressions, this expansion can be taken literally, *i.e.* there are really 3 tokens, with optional blanks between them.
####
[](#sss:lex-ops-symbols)Prefix and infix symbols
| | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| infix-symbol | ::= | ([core-operator-char](#core-operator-char) ∣ % ∣ <) { [operator-char](#operator-char) } |
| | ∣ | # { [operator-char](#operator-char) }+ |
| |
| prefix-symbol | ::= | ! { [operator-char](#operator-char) } |
| | ∣ | (? ∣ ~) { [operator-char](#operator-char) }+ |
| |
| operator-char | ::= | ~ ∣ ! ∣ ? ∣ [core-operator-char](#core-operator-char) ∣ % ∣ < ∣ : ∣ . |
| |
| core-operator-char | ::= | $ ∣ & ∣ \* ∣ + ∣ - ∣ / ∣ = ∣ > ∣ @ ∣ ^ ∣ | |
|
See also the following language extensions: [extension operators](extensionsyntax#s%3Aext-ops), [extended indexing operators](indexops#s%3Aindex-operators), and [binding operators](bindingops#s%3Abinding-operators).
Sequences of “operator characters”, such as <=> or !!, are read as a single token from the [infix-symbol](#infix-symbol) or [prefix-symbol](#prefix-symbol) class. These symbols are parsed as prefix and infix operators inside expressions, but otherwise behave like normal identifiers.
####
[](#sss:keywords)Keywords
The identifiers below are reserved as keywords, and cannot be employed otherwise:
```
and as assert asr begin class
constraint do done downto else end
exception external false for fun function
functor if in include inherit initializer
land lazy let lor lsl lsr
lxor match method mod module mutable
new nonrec object of open or
private rec sig struct then to
true try type val virtual when
while with
```
The following character sequences are also keywords:
```
!= # & && ' ( ) * + , -
-. -> . .. .~ : :: := :> ; ;;
< <- = > >] >} ? [ [< [> [|
] _ ` { {< | |] || } ~
```
Note that the following identifiers are keywords of the now unmaintained Camlp4 system and should be avoided for backwards compatibility reasons.
```
parser value $ $$ $: <: << >> ??
```
####
[](#sss:lex-ambiguities)Ambiguities
Lexical ambiguities are resolved according to the “longest match” rule: when a character sequence can be decomposed into two tokens in several different ways, the decomposition retained is the one with the longest first token.
####
[](#sss:lex-linedir)Line number directives
| | | | |
| --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| linenum-directive | ::= | # { 0…9 }+ " { [string-character](#string-character) } " |
|
Preprocessors that generate OCaml source code can insert line number directives in their output so that error messages produced by the compiler contain line numbers and file names referring to the source file before preprocessing, instead of after preprocessing. A line number directive starts at the beginning of a line, is composed of a # (sharp sign), followed by a positive integer (the source line number), followed by a character string (the source file name). Line number directives are treated as blanks during lexical analysis.
ocaml Chapter 12 Language extensions Chapter 12 Language extensions
==============================
This chapter describes language extensions and convenience features that are implemented in OCaml, but not described in chapter [11](language#c%3Arefman).
* [12.1 Recursive definitions of values](letrecvalues)
* [12.2 Recursive modules](recursivemodules)
* [12.3 Private types](privatetypes)
* [12.4 Locally abstract types](locallyabstract)
* [12.5 First-class modules](firstclassmodules)
* [12.6 Recovering the type of a module](moduletypeof)
* [12.7 Substituting inside a signature](signaturesubstitution)
* [12.8 Type-level module aliases](modulealias)
* [12.9 Overriding in open statements](overridingopen)
* [12.10 Generalized algebraic datatypes](gadts)
* [12.11 Syntax for Bigarray access](bigarray)
* [12.12 Attributes](attributes)
* [12.13 Extension nodes](extensionnodes)
* [12.14 Extensible variant types](extensiblevariants)
* [12.15 Generative functors](generativefunctors)
* [12.16 Extension-only syntax](extensionsyntax)
* [12.17 Inline records](inlinerecords)
* [12.18 Documentation comments](doccomments)
* [12.19 Extended indexing operators](indexops)
* [12.20 Empty variant types](emptyvariants)
* [12.21 Alerts](alerts)
* [12.22 Generalized open statements](generalizedopens)
* [12.23 Binding operators](bindingops)
* [12.24 Effect handlers](effects)
ocaml Chapter 23 Optimisation with Flambda Chapter 23 Optimisation with Flambda
====================================
* [23.1 Overview](flambda#s%3Aflambda-overview)
* [23.2 Command-line flags](flambda#s%3Aflambda-cli)
* [23.3 Inlining](flambda#s%3Aflambda-inlining)
* [23.4 Specialisation](flambda#s%3Aflambda-specialisation)
* [23.5 Default settings of parameters](flambda#s%3Aflambda-defaults)
* [23.6 Manual control of inlining and specialisation](flambda#s%3Aflambda-manual-control)
* [23.7 Simplification](flambda#s%3Aflambda-simplification)
* [23.8 Other code motion transformations](flambda#s%3Aflambda-other-transfs)
* [23.9 Unboxing transformations](flambda#s%3Aflambda-unboxing)
* [23.10 Removal of unused code and values](flambda#s%3Aflambda-remove-unused)
* [23.11 Other code transformations](flambda#s%3Aflambda-other)
* [23.12 Treatment of effects](flambda#s%3Aflambda-effects)
* [23.13 Compilation of statically-allocated modules](flambda#s%3Aflambda-static-modules)
* [23.14 Inhibition of optimisation](flambda#s%3Aflambda-inhibition)
* [23.15 Use of unsafe operations](flambda#s%3Aflambda-unsafe)
* [23.16 Glossary](flambda#s%3Aflambda-glossary)
[](#s:flambda-overview)23.1 Overview
--------------------------------------
*Flambda* is the term used to describe a series of optimisation passes provided by the native code compilers as of OCaml 4.03.
Flambda aims to make it easier to write idiomatic OCaml code without incurring performance penalties.
To use the Flambda optimisers it is necessary to pass the -flambda option to the OCaml configure script. (There is no support for a single compiler that can operate in both Flambda and non-Flambda modes.) Code compiled with Flambda cannot be linked into the same program as code compiled without Flambda. Attempting to do this will result in a compiler error.
Whether or not a particular ocamlopt uses Flambda may be determined by invoking it with the -config option and looking for any line starting with “flambda:”. If such a line is present and says “true”, then Flambda is supported, otherwise it is not.
Flambda provides full optimisation across different compilation units, so long as the .cmx files for the dependencies of the unit currently being compiled are available. (A compilation unit corresponds to a single .ml source file.) However it does not yet act entirely as a whole-program compiler: for example, elimination of dead code across a complete set of compilation units is not supported.
Optimisation with Flambda is not currently supported when generating bytecode.
Flambda should not in general affect the semantics of existing programs. Two exceptions to this rule are: possible elimination of pure code that is being benchmarked (see section [23.14](#s%3Aflambda-inhibition)) and changes in behaviour of code using unsafe operations (see section [23.15](#s%3Aflambda-unsafe)).
Flambda does not yet optimise array or string bounds checks. Neither does it take hints for optimisation from any assertions written by the user in the code.
Consult the *Glossary* at the end of this chapter for definitions of technical terms used below.
[](#s:flambda-cli)23.2 Command-line flags
-------------------------------------------
The Flambda optimisers provide a variety of command-line flags that may be used to control their behaviour. Detailed descriptions of each flag are given in the referenced sections. Those sections also describe any arguments which the particular flags take.
Commonly-used options:
-O2
Perform more optimisation than usual. Compilation times may be lengthened. (This flag is an abbreviation for a certain set of parameters described in section [23.5](#s%3Aflambda-defaults).)
-O3
Perform even more optimisation than usual, possibly including unrolling of recursive functions. Compilation times may be significantly lengthened.
-Oclassic
Make inlining decisions at the point of definition of a function rather than at the call site(s). This mirrors the behaviour of OCaml compilers not using Flambda. Compared to compilation using the new Flambda inlining heuristics (for example at -O2) it produces smaller .cmx files, shorter compilation times and code that probably runs rather slower. When using -Oclassic, only the following options described in this section are relevant: -inlining-report and -inline. If any other of the options described in this section are used, the behaviour is undefined and may cause an error in future versions of the compiler.
-inlining-report
Emit .inlining files (one per round of optimisation) showing all of the inliner’s decisions.
Less commonly-used options:
-remove-unused-arguments
Remove unused function arguments even when the argument is not specialised. This may have a small performance penalty. See section [23.10.3](#ss%3Aflambda-remove-unused-args).
-unbox-closures
Pass free variables via specialised arguments rather than closures (an optimisation for reducing allocation). See section [23.9.3](#ss%3Aflambda-unbox-closures). This may have a small performance penalty.
Advanced options, only needed for detailed tuning:
-inline
The behaviour depends on whether -Oclassic is used. * When not in -Oclassic mode, -inline limits the total size of functions considered for inlining during any speculative inlining search. (See section [23.3.6](#ss%3Aflambda-speculation).) Note that this parameter does not control the assessment as to whether any particular function may be inlined. Raising it to excessive amounts will not necessarily cause more functions to be inlined.
* When in -Oclassic mode, -inline behaves as in previous versions of the compiler: it is the maximum size of function to be considered for inlining. See section [23.3.1](#ss%3Aflambda-classic).
-inline-toplevel
The equivalent of -inline but used when speculative inlining starts at toplevel. See section [23.3.6](#ss%3Aflambda-speculation). Not used in -Oclassic mode.
-inline-branch-factor
Controls how the inliner assesses whether a code path is likely to be hot or cold. See section [23.3.5](#ss%3Aflambda-assessment-inlining).
-inline-alloc-cost, -inline-branch-cost, -inline-call-cost
Controls how the inliner assesses the runtime performance penalties associated with various operations. See section [23.3.5](#ss%3Aflambda-assessment-inlining).
-inline-indirect-cost, -inline-prim-cost
Likewise.
-inline-lifting-benefit
Controls inlining of functors at toplevel. See section [23.3.5](#ss%3Aflambda-assessment-inlining).
-inline-max-depth
The maximum depth of any speculative inlining search. See section [23.3.6](#ss%3Aflambda-speculation).
-inline-max-unroll
The maximum depth of any unrolling of recursive functions during any speculative inlining search. See section [23.3.6](#ss%3Aflambda-speculation).
-no-unbox-free-vars-of-closures
Do not unbox closure variables. See section [23.9.1](#ss%3Aflambda-unbox-fvs).
-no-unbox-specialised-args
Do not unbox arguments to which functions have been specialised. See section [23.9.2](#ss%3Aflambda-unbox-spec-args).
-rounds
How many rounds of optimisation to perform. See section [23.2.1](#ss%3Aflambda-rounds).
-unbox-closures-factor
Scaling factor for benefit calculation when using -unbox-closures. See section [23.9.3](#ss%3Aflambda-unbox-closures).
#####
[](#sec549)Notes
* The set of command line flags relating to optimisation should typically be specified to be the same across an entire project. Flambda does not currently record the requested flags in the .cmx files. As such, inlining of functions from previously-compiled units will subject their code to the optimisation parameters of the unit currently being compiled, rather than those specified when they were previously compiled. It is hoped to rectify this deficiency in the future.
* Flambda-specific flags do not affect linking with the exception of affecting the optimisation of code in the startup file (containing generated functions such as currying helpers). Typically such optimisation will not be significant, so eliding such flags at link time might be reasonable.
* Flambda-specific flags are silently accepted even when the -flambda option was not provided to the configure script. (There is no means provided to change this behaviour.) This is intended to make it more straightforward to run benchmarks with and without the Flambda optimisers in effect.
* Some of the Flambda flags may be subject to change in future releases.
###
[](#ss:flambda-rounds)23.2.1 Specification of optimisation parameters by round
Flambda operates in *rounds*: one round consists of a certain sequence of transformations that may then be repeated in order to achieve more satisfactory results. The number of rounds can be set manually using the -rounds parameter (although this is not necessary when using predefined optimisation levels such as with -O2 and -O3). For high optimisation the number of rounds might be set at 3 or 4.
Command-line flags that may apply per round, for example those with -cost in the name, accept arguments of the form:
*n* | *round*=*n*[,...]
* If the first form is used, with a single integer specified, the value will apply to all rounds.
* If the second form is used, zero-based *round* integers specify values which are to be used only for those rounds.
The flags -Oclassic, -O2 and -O3 are applied before all other flags, meaning that certain parameters may be overridden without having to specify every parameter usually invoked by the given optimisation level.
[](#s:flambda-inlining)23.3 Inlining
--------------------------------------
*Inlining* refers to the copying of the code of a function to a place where the function is called. The code of the function will be surrounded by bindings of its parameters to the corresponding arguments.
The aims of inlining are:
* to reduce the runtime overhead caused by function calls (including setting up for such calls and returning afterwards);
* to reduce instruction cache misses by expressing frequently-taken paths through the program using fewer machine instructions; and
* to reduce the amount of allocation (especially of closures).
These goals are often reached not just by inlining itself but also by other optimisations that the compiler is able to perform as a result of inlining.
When a recursive call to a function (within the definition of that function or another in the same mutually-recursive group) is inlined, the procedure is also known as *unrolling*. This is somewhat akin to loop peeling. For example, given the following code:
```
let rec fact x =
if x = 0 then
1
else
x * fact (x - 1)
let n = fact 4
```
unrolling once at the call site fact 4 produces (with the body of fact unchanged):
```
let n =
if 4 = 0 then
1
else
4 * fact (4 - 1)
```
This simplifies to:
```
let n = 4 * fact 3
```
Flambda provides significantly enhanced inlining capabilities relative to previous versions of the compiler.
####
[](#sss:flambda-inlining-aside)Aside: when inlining is performed
Inlining is performed together with all of the other Flambda optimisation passes, that is to say, after closure conversion. This has three particular advantages over a potentially more straightforward implementation prior to closure conversion:
* It permits higher-order inlining, for example when a non-inlinable function always returns the same function yet with different environments of definition. Not all such cases are supported yet, but it is intended that such support will be improved in future.
* It is easier to integrate with cross-module optimisation, since imported information about other modules is already in the correct intermediate language.
* It becomes more straightforward to optimise closure allocations since the layout of closures does not have to be estimated in any way: it is known. Similarly, it becomes more straightforward to control which variables end up in which closures, helping to avoid closure bloat.
###
[](#ss:flambda-classic)23.3.1 Classic inlining heuristic
In -Oclassic mode the behaviour of the Flambda inliner mimics previous versions of the compiler. (Code may still be subject to further optimisations not performed by previous versions of the compiler: functors may be inlined, constants are lifted and unused code is eliminated all as described elsewhere in this chapter. See sections [23.3.3](#sss%3Aflambda-functors), [23.8.1](#ss%3Aflambda-lift-const) and [23.10](#s%3Aflambda-remove-unused). At the definition site of a function, the body of the function is measured. It will then be marked as eligible for inlining (and hence inlined at every direct call site) if:
* the measured size (in unspecified units) is smaller than that of a function call plus the argument of the -inline command-line flag; and
* the function is not recursive.
Non-Flambda versions of the compiler cannot inline functions that contain a definition of another function. However -Oclassic does permit this. Further, non-Flambda versions also cannot inline functions that are only themselves exposed as a result of a previous pass of inlining, but again this is permitted by -Oclassic. For example:
```
module M : sig
val i : int
end = struct
let f x =
let g y = x + y in
g
let h = f 3
let i = h 4 (* h is correctly discovered to be g and inlined *)
end
```
All of this contrasts with the normal Flambda mode, that is to say without -Oclassic, where:
* the inlining decision is made at the call site; and
* recursive functions can be handled, by *specialisation* (see below).
The Flambda mode is described in the next section.
###
[](#ss:flambda-inlining-overview)23.3.2 Overview of “Flambda” inlining heuristics
The Flambda inlining heuristics, used whenever the compiler is configured for Flambda and -Oclassic was not specified, make inlining decisions at call sites. This helps in situations where the context is important. For example:
```
let f b x =
if b then
x
else
... big expression ...
let g x = f true x
```
In this case, we would like to inline f into g, because a conditional jump can be eliminated and the code size should reduce. If the inlining decision has been made after the declaration of f without seeing the use, its size would have probably made it ineligible for inlining; but at the call site, its final size can be known. Further, this function should probably not be inlined systematically: if b is unknown, or indeed false, there is little benefit to trade off against a large increase in code size. In the existing non-Flambda inliner this isn’t a great problem because chains of inlining were cut off fairly quickly. However it has led to excessive use of overly-large inlining parameters such as -inline 10000.
In more detail, at each call site the following procedure is followed:
* Determine whether it is clear that inlining would be beneficial without, for the moment, doing any inlining within the function itself. (The exact assessment of *benefit* is described below.) If so, the function is inlined.
* If inlining the function is not clearly beneficial, then inlining will be performed *speculatively* inside the function itself. The search for speculative inlining possibilities is controlled by two parameters: the *inlining threshold* and the *inlining depth*. (These are described in more detail below.)
+ If such speculation shows that performing some inlining inside the function would be beneficial, then such inlining is performed and the resulting function inlined at the original call site.
+ Otherwise, nothing happens.
Inlining within recursive functions of calls to other functions in the same mutually-recursive group is kept in check by an *unrolling depth*, described below. This ensures that functions are not unrolled to excess. (Unrolling is only enabled if -O3 optimisation level is selected and/or the -inline-max-unroll flag is passed with an argument greater than zero.)
###
[](#ss:flambda-by-constructs)23.3.3 Handling of specific language constructs
####
[](#sss:flambda-functors)Functors
There is nothing particular about functors that inhibits inlining compared to normal functions. To the inliner, these both look the same, except that functors are marked as such.
Applications of functors at toplevel are biased in favour of inlining. (This bias may be adjusted: see the documentation for -inline-lifting-benefit below.)
Applications of functors not at toplevel, for example in a local module inside some other expression, are treated by the inliner identically to normal function calls.
####
[](#sss:flambda-first-class-modules)First-class modules
The inliner will be able to consider inlining a call to a function in a first class module if it knows which particular function is going to be called. The presence of the first-class module record that wraps the set of functions in the module does not per se inhibit inlining.
####
[](#sss:flambda-objects)Objects
Method calls to objects are not at present inlined by Flambda.
###
[](#ss:flambda-inlining-reports)23.3.4 Inlining reports
If the -inlining-report option is provided to the compiler then a file will be emitted corresponding to each round of optimisation. For the OCaml source file *basename*.ml the files are named *basename*.*round*.inlining.org, with *round* a zero-based integer. Inside the files, which are formatted as “org mode”, will be found English prose describing the decisions that the inliner took.
###
[](#ss:flambda-assessment-inlining)23.3.5 Assessment of inlining benefit
Inlining typically results in an increase in code size, which if left unchecked, may not only lead to grossly large executables and excessive compilation times but also a decrease in performance due to worse locality. As such, the Flambda inliner trades off the change in code size against the expected runtime performance benefit, with the benefit being computed based on the number of operations that the compiler observes may be removed as a result of inlining.
For example given the following code:
```
let f b x =
if b then
x
else
... big expression ...
let g x = f true x
```
it would be observed that inlining of f would remove:
* one direct call;
* one conditional branch.
Formally, an estimate of runtime performance benefit is computed by first summing the cost of the operations that are known to be removed as a result of the inlining and subsequent simplification of the inlined body. The individual costs for the various kinds of operations may be adjusted using the various -inline-...-cost flags as follows. Costs are specified as integers. All of these flags accept a single argument describing such integers using the conventions detailed in section [23.2.1](#ss%3Aflambda-rounds).
-inline-alloc-cost
The cost of an allocation.
-inline-branch-cost
The cost of a branch.
-inline-call-cost
The cost of a direct function call.
-inline-indirect-cost
The cost of an indirect function call.
-inline-prim-cost
The cost of a *primitive*. Primitives encompass operations including arithmetic and memory access.
(Default values are described in section [23.5](#s%3Aflambda-defaults) below.)
The initial benefit value is then scaled by a factor that attempts to compensate for the fact that the current point in the code, if under some number of conditional branches, may be cold. (Flambda does not currently compute hot and cold paths.) The factor—the estimated probability that the inliner really is on a *hot* path—is calculated as 1/(1 + f)d, where f is set by -inline-branch-factor and d is the nesting depth of branches at the current point. As the inliner descends into more deeply-nested branches, the benefit of inlining thus lessens.
The resulting benefit value is known as the *estimated benefit*.
The change in code size is also estimated: morally speaking it should be the change in machine code size, but since that is not available to the inliner, an approximation is used.
If the estimated benefit exceeds the increase in code size then the inlined version of the function will be kept. Otherwise the function will not be inlined.
Applications of functors at toplevel will be given an additional benefit (which may be controlled by the -inline-lifting-benefit flag) to bias inlining in such situations towards keeping the inlined version.
###
[](#ss:flambda-speculation)23.3.6 Control of speculation
As described above, there are three parameters that restrict the search for inlining opportunities during speculation:
* the *inlining threshold*;
* the *inlining depth*;
* the *unrolling depth*.
These parameters are ultimately bounded by the arguments provided to the corresponding command-line flags (or their default values):
* -inline (or, if the call site that triggered speculation is at toplevel, -inline-toplevel);
* -inline-max-depth;
* -inline-max-unroll.
Note in particular that -inline does not have the meaning that it has in the previous compiler or in -Oclassic mode. In both of those situations -inline was effectively some kind of basic assessment of inlining benefit. However in Flambda inlining mode it corresponds to a constraint on the search; the assessment of benefit is independent, as described above.
When speculation starts the inlining threshold starts at the value set by -inline (or -inline-toplevel if appropriate, see above). Upon making a speculative inlining decision the threshold is reduced by the code size of the function being inlined. If the threshold becomes exhausted, at or below zero, no further speculation will be performed.
The inlining depth starts at zero and is increased by one every time the inliner descends into another function. It is then decreased by one every time the inliner leaves such function. If the depth exceeds the value set by -inline-max-depth then speculation stops. This parameter is intended as a general backstop for situations where the inlining threshold does not control the search sufficiently.
The unrolling depth applies to calls within the same mutually-recursive group of functions. Each time an inlining of such a call is performed the depth is incremented by one when examining the resulting body. If the depth reaches the limit set by -inline-max-unroll then speculation stops.
[](#s:flambda-specialisation)23.4 Specialisation
--------------------------------------------------
The inliner may discover a call site to a recursive function where something is known about the arguments: for example, they may be equal to some other variables currently in scope. In this situation it may be beneficial to *specialise* the function to those arguments. This is done by copying the declaration of the function (and any others involved in any same mutually-recursive declaration) and noting the extra information about the arguments. The arguments augmented by this information are known as *specialised arguments*. In order to try to ensure that specialisation is not performed uselessly, arguments are only specialised if it can be shown that they are *invariant*: in other words, during the execution of the recursive function(s) themselves, the arguments never change.
Unless overridden by an attribute (see below), specialisation of a function will not be attempted if:
* the compiler is in -Oclassic mode;
* the function is not obviously recursive;
* the function is not closed.
The compiler can prove invariance of function arguments across multiple functions within a recursive group (although this has some limitations, as shown by the example below).
It should be noted that the *unboxing of closures* pass (see below) can introduce specialised arguments on non-recursive functions. (No other place in the compiler currently does this.)
#####
[](#sec563)Example: the well-known List.iter function
This function might be written like so:
```
let rec iter f l =
match l with
| [] -> ()
| h :: t ->
f h;
iter f t
```
and used like this:
```
let print_int x =
print_endline (Int.to_string x)
let run xs =
iter print_int (List.rev xs)
```
The argument f to iter is invariant so the function may be specialised:
```
let run xs =
let rec iter' f l =
(* The compiler knows: f holds the same value as foo throughout iter'. *)
match l with
| [] -> ()
| h :: t ->
f h;
iter' f t
in
iter' print_int (List.rev xs)
```
The compiler notes down that for the function iter’, the argument f is specialised to the constant closure print\_int. This means that the body of iter’ may be simplified:
```
let run xs =
let rec iter' f l =
(* The compiler knows: f holds the same value as foo throughout iter'. *)
match l with
| [] -> ()
| h :: t ->
print_int h; (* this is now a direct call *)
iter' f t
in
iter' print_int (List.rev xs)
```
The call to print\_int can indeed be inlined:
```
let run xs =
let rec iter' f l =
(* The compiler knows: f holds the same value as foo throughout iter'. *)
match l with
| [] -> ()
| h :: t ->
print_endline (Int.to_string h);
iter' f t
in
iter' print_int (List.rev xs)
```
The unused specialised argument f may now be removed, leaving:
```
let run xs =
let rec iter' l =
match l with
| [] -> ()
| h :: t ->
print_endline (Int.to_string h);
iter' t
in
iter' (List.rev xs)
```
#####
[](#sec564)Aside on invariant parameters.
The compiler cannot currently detect invariance in cases such as the following.
```
let rec iter_swap f g l =
match l with
| [] -> ()
| 0 :: t ->
iter_swap g f l
| h :: t ->
f h;
iter_swap f g t
```
###
[](#ss:flambda-assessment-specialisation)23.4.1 Assessment of specialisation benefit
The benefit of specialisation is assessed in a similar way as for inlining. Specialised argument information may mean that the body of the function being specialised can be simplified: the removed operations are accumulated into a benefit. This, together with the size of the duplicated (specialised) function declaration, is then assessed against the size of the call to the original function.
[](#s:flambda-defaults)23.5 Default settings of parameters
------------------------------------------------------------
The default settings (when not using -Oclassic) are for one round of optimisation using the following parameters.
| | |
| --- | --- |
| Parameter | Setting |
| -inline | 10 |
| -inline-branch-factor | 0.1 |
| -inline-alloc-cost | 7 |
| -inline-branch-cost | 5 |
| -inline-call-cost | 5 |
| -inline-indirect-cost | 4 |
| -inline-prim-cost | 3 |
| -inline-lifting-benefit | 1300 |
| -inline-toplevel | 160 |
| -inline-max-depth | 1 |
| -inline-max-unroll | 0 |
| -unbox-closures-factor | 10 |
###
[](#ss:flambda-o2)23.5.1 Settings at -O2 optimisation level
When -O2 is specified two rounds of optimisation are performed. The first round uses the default parameters (see above). The second uses the following parameters.
| | |
| --- | --- |
| Parameter | Setting |
| -inline | 25 |
| -inline-branch-factor | Same as default |
| -inline-alloc-cost | Double the default |
| -inline-branch-cost | Double the default |
| -inline-call-cost | Double the default |
| -inline-indirect-cost | Double the default |
| -inline-prim-cost | Double the default |
| -inline-lifting-benefit | Same as default |
| -inline-toplevel | 400 |
| -inline-max-depth | 2 |
| -inline-max-unroll | Same as default |
| -unbox-closures-factor | Same as default |
###
[](#ss:flambda-o3)23.5.2 Settings at -O3 optimisation level
When -O3 is specified three rounds of optimisation are performed. The first two rounds are as for -O2. The third round uses the following parameters.
| | |
| --- | --- |
| Parameter | Setting |
| -inline | 50 |
| -inline-branch-factor | Same as default |
| -inline-alloc-cost | Triple the default |
| -inline-branch-cost | Triple the default |
| -inline-call-cost | Triple the default |
| -inline-indirect-cost | Triple the default |
| -inline-prim-cost | Triple the default |
| -inline-lifting-benefit | Same as default |
| -inline-toplevel | 800 |
| -inline-max-depth | 3 |
| -inline-max-unroll | 1 |
| -unbox-closures-factor | Same as default |
[](#s:flambda-manual-control)23.6 Manual control of inlining and specialisation
---------------------------------------------------------------------------------
Should the inliner prove recalcitrant and refuse to inline a particular function, or if the observed inlining decisions are not to the programmer’s satisfaction for some other reason, inlining behaviour can be dictated by the programmer directly in the source code. One example where this might be appropriate is when the programmer, but not the compiler, knows that a particular function call is on a cold code path. It might be desirable to prevent inlining of the function so that the code size along the hot path is kept smaller, so as to increase locality.
The inliner is directed using attributes. For non-recursive functions (and one-step unrolling of recursive functions, although @unroll is more clear for this purpose) the following are supported:
@@inline always or @@inline never
Attached to a *declaration* of a function or functor, these direct the inliner to either always or never inline, irrespective of the size/benefit calculation. (If the function is recursive then the body is substituted and no special action is taken for the recursive call site(s).) @@inline with no argument is equivalent to @@inline always.
@inlined always or @inlined never
Attached to a function *application*, these direct the inliner likewise. These attributes at call sites override any other attribute that may be present on the corresponding declaration. @inlined with no argument is equivalent to @inlined always. @@inlined hint is equivalent to @@inline always except that it will not trigger warning 55 if the function application cannot be inlined.
For recursive functions the relevant attributes are:
@@specialise always or @@specialise never
Attached to a declaration of a function or functor, this directs the inliner to either always or never specialise the function so long as it has appropriate contextual knowledge, irrespective of the size/benefit calculation. @@specialise with no argument is equivalent to @@specialise always.
@specialised always or @specialised never
Attached to a function application, this directs the inliner likewise. This attribute at a call site overrides any other attribute that may be present on the corresponding declaration. (Note that the function will still only be specialised if there exist one or more invariant parameters whose values are known.) @specialised with no argument is equivalent to @specialised always.
@unrolled n
This attribute is attached to a function application and always takes an integer argument. Each time the inliner sees the attribute it behaves as follows: * If n is zero or less, nothing happens.
* Otherwise the function being called is substituted at the call site with its body having been rewritten such that any recursive calls to that function *or any others in the same mutually-recursive group* are annotated with the attribute unrolled(n − 1). Inlining may continue on that body.
As such, n behaves as the “maximum depth of unrolling”.
A compiler warning will be emitted if it was found impossible to obey an annotation from an @inlined or @specialised attribute.
#####
[](#sec570)Example showing correct placement of attributes
```
module F (M : sig type t end) = struct
let[@inline never] bar x =
x * 3
let foo x =
(bar [@inlined]) (42 + x)
end [@@inline never]
module X = F [@inlined] (struct type t = int end)
```
[](#s:flambda-simplification)23.7 Simplification
--------------------------------------------------
Simplification, which is run in conjunction with inlining, propagates information (known as *approximations*) about which variables hold what values at runtime. Certain relationships between variables and symbols are also tracked: for example, some variable may be known to always hold the same value as some other variable; or perhaps some variable may be known to always hold the value pointed to by some symbol.
The propagation can help to eliminate allocations in cases such as:
```
let f x y =
...
let p = x, y in
...
... (fst p) ... (snd p) ...
```
The projections from p may be replaced by uses of the variables x and y, potentially meaning that p becomes unused.
The propagation performed by the simplification pass is also important for discovering which functions flow to indirect call sites. This can enable the transformation of such call sites into direct call sites, which makes them eligible for an inlining transformation.
Note that no information is propagated about the contents of strings, even in safe-string mode, because it cannot yet be guaranteed that they are immutable throughout a given program.
[](#s:flambda-other-transfs)23.8 Other code motion transformations
--------------------------------------------------------------------
###
[](#ss:flambda-lift-const)23.8.1 Lifting of constants
Expressions found to be constant will be lifted to symbol bindings—that is to say, they will be statically allocated in the object file—when they evaluate to boxed values. Such constants may be straightforward numeric constants, such as the floating-point number 42.0, or more complicated values such as constant closures.
Lifting of constants to toplevel reduces allocation at runtime.
The compiler aims to share constants lifted to toplevel such that there are no duplicate definitions. However if .cmx files are hidden from the compiler then maximal sharing may not be possible.
#####
[](#sec574)Notes about float arrays
The following language semantics apply specifically to constant float arrays. (By “constant float array” is meant an array consisting entirely of floating point numbers that are known at compile time. A common case is a literal such as [| 42.0; 43.0; |].
* Constant float arrays at the toplevel are mutable and never shared. (That is to say, for each such definition there is a distinct symbol in the data section of the object file pointing at the array.)
* Constant float arrays not at toplevel are mutable and are created each time the expression is evaluated. This can be thought of as an operation that takes an immutable array (which in the source code has no associated name; let us call it the *initialising array*) and duplicates it into a fresh mutable array.
+ If the array is of size four or less, the expression will create a fresh block and write the values into it one by one. There is no reference to the initialising array as a whole.
+ Otherwise, the initialising array is lifted out and subject to the normal constant sharing procedure; creation of the array consists of bulk copying the initialising array into a fresh value on the OCaml heap.
###
[](#ss:flambda-lift-toplevel-let)23.8.2 Lifting of toplevel let bindings
Toplevel let-expressions may be lifted to symbol bindings to ensure that the corresponding bound variables are not captured by closures. If the defining expression of a given binding is found to be constant, it is bound as such (the technical term is a *let-symbol* binding).
Otherwise, the symbol is bound to a (statically-allocated) *preallocated block* containing one field. At runtime, the defining expression will be evaluated and the first field of the block filled with the resulting value. This *initialise-symbol* binding causes one extra indirection but ensures, by virtue of the symbol’s address being known at compile time, that uses of the value are not captured by closures.
It should be noted that the blocks corresponding to initialise-symbol bindings are kept alive forever, by virtue of them occurring in a static table of GC roots within the object file. This extended lifetime of expressions may on occasion be surprising. If it is desired to create some non-constant value (for example when writing GC tests) that does not have this extended lifetime, then it may be created and used inside a function, with the application point of that function (perhaps at toplevel)—or indeed the function declaration itself—marked as to never be inlined. This technique prevents lifting of the definition of the value in question (assuming of course that it is not constant).
[](#s:flambda-unboxing)23.9 Unboxing transformations
------------------------------------------------------
The transformations in this section relate to the splitting apart of *boxed* (that is to say, non-immediate) values. They are largely intended to reduce allocation, which tends to result in a runtime performance profile with lower variance and smaller tails.
###
[](#ss:flambda-unbox-fvs)23.9.1 Unboxing of closure variables
This transformation is enabled unless -no-unbox-free-vars-of-closures is provided.
Variables that appear in closure environments may themselves be boxed values. As such, they may be split into further closure variables, each of which corresponds to some projection from the original closure variable(s). This transformation is called *unboxing of closure variables* or *unboxing of free variables of closures*. It is only applied when there is reasonable certainty that there are no uses of the boxed free variable itself within the corresponding function bodies.
#####
[](#sec578)Example:
In the following code, the compiler observes that the closure returned from the function f contains a variable pair (free in the body of f) that may be split into two separate variables.
```
let f x0 x1 =
let pair = x0, x1 in
Printf.printf "foo\n";
fun y ->
fst pair + snd pair + y
```
After some simplification one obtains:
```
let f x0 x1 =
let pair_0 = x0 in
let pair_1 = x1 in
Printf.printf "foo\n";
fun y ->
pair_0 + pair_1 + y
```
and then:
```
let f x0 x1 =
Printf.printf "foo\n";
fun y ->
x0 + x1 + y
```
The allocation of the pair has been eliminated.
This transformation does not operate if it would cause the closure to contain more than twice as many closure variables as it did beforehand.
###
[](#ss:flambda-unbox-spec-args)23.9.2 Unboxing of specialised arguments
This transformation is enabled unless -no-unbox-specialised-args is provided.
It may become the case during compilation that one or more invariant arguments to a function become specialised to a particular value. When such values are themselves boxed the corresponding specialised arguments may be split into more specialised arguments corresponding to the projections out of the boxed value that occur within the function body. This transformation is called *unboxing of specialised arguments*. It is only applied when there is reasonable certainty that the boxed argument itself is unused within the function.
If the function in question is involved in a recursive group then unboxing of specialised arguments may be immediately replicated across the group based on the dataflow between invariant arguments.
#####
[](#sec580)Example:
Having been given the following code, the compiler will inline loop into f, and then observe inv being invariant and always the pair formed by adding 42 and 43 to the argument x of the function f.
```
let rec loop inv xs =
match xs with
| [] -> fst inv + snd inv
| x::xs -> x + loop2 xs inv
and loop2 ys inv =
match ys with
| [] -> 4
| y::ys -> y - loop inv ys
let f x =
Printf.printf "%d\n" (loop (x + 42, x + 43) [1; 2; 3])
```
Since the functions have sufficiently few arguments, more specialised arguments will be added. After some simplification one obtains:
```
let f x =
let rec loop' xs inv_0 inv_1 =
match xs with
| [] -> inv_0 + inv_1
| x::xs -> x + loop2' xs inv_0 inv_1
and loop2' ys inv_0 inv_1 =
match ys with
| [] -> 4
| y::ys -> y - loop' ys inv_0 inv_1
in
Printf.printf "%d\n" (loop' [1; 2; 3] (x + 42) (x + 43))
```
The allocation of the pair within f has been removed. (Since the two closures for loop’ and loop2’ are constant they will also be lifted to toplevel with no runtime allocation penalty. This would also happen without having run the transformation to unbox specialise arguments.)
The transformation to unbox specialised arguments never introduces extra allocation.
The transformation will not unbox arguments if it would result in the original function having sufficiently many arguments so as to inhibit tail-call optimisation.
The transformation is implemented by creating a wrapper function that accepts the original arguments. Meanwhile, the original function is renamed and extra arguments are added corresponding to the unboxed specialised arguments; this new function is called from the wrapper. The wrapper will then be inlined at direct call sites. Indeed, all call sites will be direct unless -unbox-closures is being used, since they will have been generated by the compiler when originally specialising the function. (In the case of -unbox-closures other functions may appear with specialised arguments; in this case there may be indirect calls and these will incur a small penalty owing to having to bounce through the wrapper. The technique of *direct call surrogates* used for -unbox-closures is not used by the transformation to unbox specialised arguments.)
###
[](#ss:flambda-unbox-closures)23.9.3 Unboxing of closures
This transformation is *not* enabled by default. It may be enabled using the -unbox-closures flag.
The transformation replaces closure variables by specialised arguments. The aim is to cause more closures to become closed. It is particularly applicable, as a means of reducing allocation, where the function concerned cannot be inlined or specialised. For example, some non-recursive function might be too large to inline; or some recursive function might offer no opportunities for specialisation perhaps because its only argument is one of type unit.
At present there may be a small penalty in terms of actual runtime performance when this transformation is enabled, although more stable performance may be obtained due to reduced allocation. It is recommended that developers experiment to determine whether the option is beneficial for their code. (It is expected that in the future it will be possible for the performance degradation to be removed.)
#####
[](#sec582)Simple example:
In the following code (which might typically occur when g is too large to inline) the value of x would usually be communicated to the application of the + function via the closure of g.
```
let f x =
let g y =
x + y
in
(g [@inlined never]) 42
```
Unboxing of the closure causes the value for x inside g to be passed as an argument to g rather than through its closure. This means that the closure of g becomes constant and may be lifted to toplevel, eliminating the runtime allocation.
The transformation is implemented by adding a new wrapper function in the manner of that used when unboxing specialised arguments. The closure variables are still free in the wrapper, but the intention is that when the wrapper is inlined at direct call sites, the relevant values are passed directly to the main function via the new specialised arguments.
Adding such a wrapper will penalise indirect calls to the function (which might exist in arbitrary places; remember that this transformation is not for example applied only on functions the compiler has produced as a result of specialisation) since such calls will bounce through the wrapper. To mitigate this, if a function is small enough when weighed up against the number of free variables being removed, it will be duplicated by the transformation to obtain two versions: the original (used for indirect calls, since we can do no better) and the wrapper/rewritten function pair as described in the previous paragraph. The wrapper/rewritten function pair will only be used at direct call sites of the function. (The wrapper in this case is known as a *direct call surrogate*, since it takes the place of another function—the unchanged version used for indirect calls—at direct call sites.)
The -unbox-closures-factor command line flag, which takes an integer, may be used to adjust the point at which a function is deemed large enough to be ineligible for duplication. The benefit of duplication is scaled by the integer before being evaluated against the size.
#####
[](#sec583)Harder example:
In the following code, there are two closure variables that would typically cause closure allocations. One is called fv and occurs inside the function baz; the other is called z and occurs inside the function bar. In this toy (yet sophisticated) example we again use an attribute to simulate the typical situation where the first argument of baz is too large to inline.
```
let foo c =
let rec bar zs fv =
match zs with
| [] -> []
| z::zs ->
let rec baz f = function
| [] -> []
| a::l -> let r = fv + ((f [@inlined never]) a) in r :: baz f l
in
(map2 (fun y -> z + y) [z; 2; 3; 4]) @ bar zs fv
in
Printf.printf "%d" (List.length (bar [1; 2; 3; 4] c))
```
The code resulting from applying -O3 -unbox-closures to this code passes the free variables via function arguments in order to eliminate all closure allocation in this example (aside from any that might be performed inside printf).
[](#s:flambda-remove-unused)23.10 Removal of unused code and values
---------------------------------------------------------------------
###
[](#ss:flambda-redundant-let)23.10.1 Removal of redundant let expressions
The simplification pass removes unused let bindings so long as their corresponding defining expressions have “no effects”. See the section “Treatment of effects” below for the precise definition of this term.
###
[](#ss:flambda-redundant)23.10.2 Removal of redundant program constructs
This transformation is analogous to the removal of let-expressions whose defining expressions have no effects. It operates instead on symbol bindings, removing those that have no effects.
###
[](#ss:flambda-remove-unused-args)23.10.3 Removal of unused arguments
This transformation is only enabled by default for specialised arguments. It may be enabled for all arguments using the -remove-unused-arguments flag.
The pass analyses functions to determine which arguments are unused. Removal is effected by creating a wrapper function, which will be inlined at every direct call site, that accepts the original arguments and then discards the unused ones before calling the original function. As a consequence, this transformation may be detrimental if the original function is usually indirectly called, since such calls will now bounce through the wrapper. (The technique of *direct call surrogates* used to reduce this penalty during unboxing of closure variables (see above) does not yet apply to the pass that removes unused arguments.)
###
[](#ss:flambda-removal-closure-vars)23.10.4 Removal of unused closure variables
This transformation performs an analysis across the whole compilation unit to determine whether there exist closure variables that are never used. Such closure variables are then eliminated. (Note that this has to be a whole-unit analysis because a projection of a closure variable from some particular closure may have propagated to an arbitrary location within the code due to inlining.)
[](#s:flambda-other)23.11 Other code transformations
------------------------------------------------------
###
[](#ss:flambda-non-escaping-refs)23.11.1 Transformation of non-escaping references into mutable variables
Flambda performs a simple analysis analogous to that performed elsewhere in the compiler that can transform refs into mutable variables that may then be held in registers (or on the stack as appropriate) rather than being allocated on the OCaml heap. This only happens so long as the reference concerned can be shown to not escape from its defining scope.
###
[](#ss:flambda-subst-closure-vars)23.11.2 Substitution of closure variables for specialised arguments
This transformation discovers closure variables that are known to be equal to specialised arguments. Such closure variables are replaced by the specialised arguments; the closure variables may then be removed by the “removal of unused closure variables” pass (see below).
[](#s:flambda-effects)23.12 Treatment of effects
--------------------------------------------------
The Flambda optimisers classify expressions in order to determine whether an expression:
* does not need to be evaluated at all; and/or
* may be duplicated.
This is done by forming judgements on the *effects* and the *coeffects* that might be performed were the expression to be executed. Effects talk about how the expression might affect the world; coeffects talk about how the world might affect the expression.
Effects are classified as follows:
No effects:
The expression does not change the observable state of the world. For example, it must not write to any mutable storage, call arbitrary external functions or change control flow (e.g. by raising an exception). Note that allocation is *not* classed as having “no effects” (see below). * It is assumed in the compiler that expressions with no effects, whose results are not used, may be eliminated. (This typically happens where the expression in question is the defining expression of a let; in such cases the let-expression will be eliminated.) It is further assumed that such expressions with no effects may be duplicated (and thus possibly executed more than once).
* Exceptions arising from allocation points, for example “out of memory” or exceptions propagated from finalizers or signal handlers, are treated as “effects out of the ether” and thus ignored for our determination here of effectfulness. The same goes for floating point operations that may cause hardware traps on some platforms.
Only generative effects:
The expression does not change the observable state of the world save for possibly affecting the state of the garbage collector by performing an allocation. Expressions that only have generative effects and whose results are unused may be eliminated by the compiler. However, unlike expressions with “no effects”, such expressions will never be eligible for duplication.
Arbitrary effects:
All other expressions.
There is a single classification for coeffects:
No coeffects:
The expression does not observe the effects (in the sense described above) of other expressions. For example, it must not read from any mutable storage or call arbitrary external functions.
It is assumed in the compiler that, subject to data dependencies, expressions with neither effects nor coeffects may be reordered with respect to other expressions.
[](#s:flambda-static-modules)23.13 Compilation of statically-allocated modules
--------------------------------------------------------------------------------
Compilation of modules that are able to be statically allocated (for example, the module corresponding to an entire compilation unit, as opposed to a first class module dependent on values computed at runtime) initially follows the strategy used for bytecode. A sequence of let-bindings, which may be interspersed with arbitrary effects, surrounds a record creation that becomes the module block. The Flambda-specific transformation follows: these bindings are lifted to toplevel symbols, as described above.
[](#s:flambda-inhibition)23.14 Inhibition of optimisation
-----------------------------------------------------------
Especially when writing benchmarking suites that run non-side-effecting algorithms in loops, it may be found that the optimiser entirely elides the code being benchmarked. This behaviour can be prevented by using the Sys.opaque\_identity function (which indeed behaves as a normal OCaml function and does not possess any “magic” semantics). The documentation of the Sys module should be consulted for further details.
[](#s:flambda-unsafe)23.15 Use of unsafe operations
-----------------------------------------------------
The behaviour of the Flambda simplification pass means that certain unsafe operations, which may without Flambda or when using previous versions of the compiler be safe, must not be used. This specifically refers to functions found in the Obj module.
In particular, it is forbidden to change any value (for example using Obj.set\_field or Obj.set\_tag) that is not mutable. (Values returned from C stubs are always treated as mutable.) The compiler will emit warning 59 if it detects such a write—but it cannot warn in all cases. Here is an example of code that will trigger the warning:
```
let f x =
let a = 42, x in
(Obj.magic a : int ref) := 1;
fst a
```
The reason this is unsafe is because the simplification pass believes that fst a holds the value 42; and indeed it must, unless type soundness has been broken via unsafe operations.
If it must be the case that code has to be written that triggers warning 59, but the code is known to actually be correct (for some definition of correct), then Sys.opaque\_identity may be used to wrap the value before unsafe operations are performed upon it. Great care must be taken when doing this to ensure that the opacity is added at the correct place. It must be emphasised that this use of Sys.opaque\_identity is only for exceptional cases. It should not be used in normal code or to try to guide the optimiser.
As an example, this code will return the integer 1:
```
let f x =
let a = Sys.opaque_identity (42, x) in
(Obj.magic a : int ref) := 1;
fst a
```
However the following code will still return 42:
```
let f x =
let a = 42, x in
Sys.opaque_identity (Obj.magic a : int ref) := 1;
fst a
```
High levels of inlining performed by Flambda may expose bugs in code thought previously to be correct. Take care, for example, not to add type annotations that claim some mutable value is always immediate if it might be possible for an unsafe operation to update it to a boxed value.
[](#s:flambda-glossary)23.16 Glossary
---------------------------------------
The following terminology is used in this chapter of the manual.
Call site
See *direct call site* and *indirect call site* below.
Closed function
A function whose body has no free variables except its parameters and any to which are bound other functions within the same (possibly mutually-recursive) declaration.
Closure
The runtime representation of a function. This includes pointers to the code of the function together with the values of any variables that are used in the body of the function but actually defined outside of the function, in the enclosing scope. The values of such variables, collectively known as the *environment*, are required because the function may be invoked from a place where the original bindings of such variables are no longer in scope. A group of possibly mutually-recursive functions defined using *let rec* all share a single closure. (Note to developers: in the Flambda source code a *closure* always corresponds to a single function; a *set of closures* refers to a group of such.)
Closure variable
A member of the environment held within the closure of a given function.
Constant
Some entity (typically an expression) the value of which is known by the compiler at compile time. Constantness may be explicit from the source code or inferred by the Flambda optimisers.
Constant closure
A closure that is statically allocated in an object file. It is almost always the case that the environment portion of such a closure is empty.
Defining expression
The expression e in let x = e in e’.
Direct call site
A place in a program’s code where a function is called and it is known at compile time which function it will always be.
Indirect call site
A place in a program’s code where a function is called but is not known to be a *direct call site*.
Program
A collection of *symbol bindings* forming the definition of a single compilation unit (i.e. .cmx file).
Specialised argument
An argument to a function that is known to always hold a particular value at runtime. These are introduced by the inliner when specialising recursive functions; and the unbox-closures pass. (See section [23.4](#s%3Aflambda-specialisation).)
Symbol
A name referencing a particular place in an object file or executable image. At that particular place will be some constant value. Symbols may be examined using operating system-specific tools (for example objdump on Linux).
Symbol binding
Analogous to a let-expression but working at the level of symbols defined in the object file. The address of a symbol is fixed, but it may be bound to both constant and non-constant expressions.
Toplevel
An expression in the current program which is not enclosed within any function declaration.
Variable
A named entity to which some OCaml value is bound by a let expression, pattern-matching construction, or similar.
| programming_docs |
ocaml Chapter 24 Fuzzing with afl-fuzz Chapter 24 Fuzzing with afl-fuzz
================================
* [24.1 Overview](afl-fuzz#s%3Aafl-overview)
* [24.2 Generating instrumentation](afl-fuzz#s%3Aafl-generate)
* [24.3 Example](afl-fuzz#s%3Aafl-example)
[](#s:afl-overview)24.1 Overview
----------------------------------
American fuzzy lop (“afl-fuzz”) is a *fuzzer*, a tool for testing software by providing randomly-generated inputs, searching for those inputs which cause the program to crash.
Unlike most fuzzers, afl-fuzz observes the internal behaviour of the program being tested, and adjusts the test cases it generates to trigger unexplored execution paths. As a result, test cases generated by afl-fuzz cover more of the possible behaviours of the tested program than other fuzzers.
This requires that programs to be tested are instrumented to communicate with afl-fuzz. The native-code compiler “ocamlopt” can generate such instrumentation, allowing afl-fuzz to be used against programs written in OCaml.
For more information on afl-fuzz, see the website at <http://lcamtuf.coredump.cx/afl/>.
[](#s:afl-generate)24.2 Generating instrumentation
----------------------------------------------------
The instrumentation that afl-fuzz requires is not generated by default, and must be explicitly enabled, by passing the -afl-instrument option to ocamlopt.
To fuzz a large system without modifying build tools, OCaml’s configure script also accepts the afl-instrument option. If OCaml is configured with afl-instrument, then all programs compiled by ocamlopt will be instrumented.
###
[](#ss:afl-advanced)24.2.1 Advanced options
In rare cases, it is useful to control the amount of instrumentation generated. By passing the -afl-inst-ratio N argument to ocamlopt with N less than 100, instrumentation can be generated for only N% of branches. (See the afl-fuzz documentation on the parameter AFL\_INST\_RATIO for the precise effect of this).
[](#s:afl-example)24.3 Example
--------------------------------
As an example, we fuzz-test the following program, readline.ml:
```
let _ =
let s = read_line () in
match Array.to_list (Array.init (String.length s) (String.get s)) with
['s'; 'e'; 'c'; 'r'; 'e'; 't'; ' '; 'c'; 'o'; 'd'; 'e'] -> failwith "uh oh"
| _ -> ()
```
There is a single input (the string “secret code”) which causes this program to crash, but finding it by blind random search is infeasible.
Instead, we compile with afl-fuzz instrumentation enabled:
```
ocamlopt -afl-instrument readline.ml -o readline
```
Next, we run the program under afl-fuzz:
```
mkdir input
echo asdf > input/testcase
mkdir output
afl-fuzz -m none -i input -o output ./readline
```
By inspecting instrumentation output, the fuzzer finds the crashing input quickly.
Note: To fuzz-test an OCaml program with afl-fuzz, passing the option -m none is required to disable afl-fuzz’s default 50MB virtual memory limit.
ocaml Chapter 25 Runtime tracing with runtime events Chapter 25 Runtime tracing with runtime events
==============================================
* [25.1 Overview](runtime-tracing#s%3Aruntime-tracing-overview)
* [25.2 Architecture](runtime-tracing#s%3Aruntime-tracing-architecture)
* [25.3 Usage](runtime-tracing#s-runtime-tracing-usage)
This chapter describes the runtime events tracing system which enables continuous extraction of performance information from the OCaml runtime with very low overhead. The system and interfaces are low-level and tightly coupled to the runtime implementation, it is intended for end-users to rely on tooling to consume and visualise data of interest.
Data emitted includes:
* Event times of garbage collector and runtime phases
* Minor and major heap sizings and utilization
* Allocation and promotion rates between heaps
[](#s:runtime-tracing-overview)25.1 Overview
----------------------------------------------
There are three main classes of events emitted by the runtime events system:
Spans
Events spanning over a duration in time. For example, the runtime events tracing system emits a span event that starts when a minor collection begins in the OCaml garbage collector and ends when the collection is completed. Spans can contain other spans, e.g other span events may be emitted that begin after a minor collection has begun and end before it does.
Lifecycle events
Events that occur at a moment in time. For example, when a domain terminates, a corresponding lifecycle event is emitted.
Counters
Events that include a measurement of some quantity of interest. For example, the number of words promoted from the minor to the major heap during the last minor garbage collection is emitted as a counter event.
The runtime events tracing system is designed to be used in different contexts:
Self monitoring
OCaml programs and libraries can install their own callbacks to listen for runtime events and react to them programmatically, for example, to export events to disk or over the network.
External monitoring
An external process can consume the runtime events of an OCaml program whose runtime tracing system has been enabled by setting the corresponding environment variable.
The runtime events tracing system logs events to a *ring buffer*. Consequently, old events are being overwritten by new events. Consumers can either continuously consume events or choose to only do so in response to some circumstance, e.g if a particular query or operation takes longer than expected to complete.
[](#s:runtime-tracing-architecture)25.2 Architecture
------------------------------------------------------
The runtime tracing system conceptually consists of two parts: 1) the probes which emit events and 2) the events transport that ingests and transports these events.
###
[](#s:runtime-tracing-probes)25.2.1 Probes
Probes collect events from the runtime system. These are further split in to two sets: 1) probes that are always available and 2) probes that are only available in the instrumented runtime. Probes in the instrumented runtime are primarily of interest to developers of the OCaml runtime and garbage collector and, at present, only consist of major heap allocation size counter events.
The full set of events emitted by probes and their documentation can be found in [Module Runtime\_events](libref/runtime_events).
###
[](#s:runtime-tracing-ingestion)25.2.2 Events transport
The events transport part of the system ingests events emitted by the probes and makes them available to consumers.
####
[](#s:runtime-tracing-ringbuffers)Ring buffers
Events are transported using a data structure known as a *ring buffer*. This data structure consists of two pointers into a linear backing array, the tail pointer points to a location where new events can be written and the head pointer points to the oldest event in the buffer that can be read. When insufficient space is available in the backing array to write new events, the head pointer is advanced and the oldest events are overwritten by new ones.
The ring buffer implementation used in runtime events can be written by at most one producer at a time but can be read simultaneously by multiple consumers without coordination from the producer. There is a unique ring buffer for every running domain and, on domain termination, ring buffers may be re-used for newly spawned domains. The ring buffers themselves are stored in a memory-mapped file with the processes identifier as the name and the extension .events, this enables them to be read from outside the main OCaml process. See [Runtime\_events](libref/runtime_events) for more information.
####
[](#s:runtime-tracing-apis)Consumption APIs
The runtime event tracing system provides both OCaml and C APIs which are cursor-based and polling-driven. The high-level process for consuming events is as follows:
1. A cursor is created via Runtime\_events.create\_cursor for either the current process or an external process (specified by a path and PID).
2. Runtime\_events.Callbacks.create is called to register a callback function to receive the events.
3. The cursor is polled via Runtime\_events.read\_poll using the callbacks created in the previous step. For each matching event in the ring buffers, the provided callback functions are called.
[](#s-runtime-tracing-usage)25.3 Usage
----------------------------------------
###
[](#s-runtime-tracing-ocaml-apis)25.3.1 With OCaml APIs
We start with a simple example that prints the name, begin and end times of events emitted by the runtime event tracing system:
```
let runtime_begin _ ts phase =
Printf.printf "Begin\t%s\t%Ld\n"
(Runtime_events.runtime_phase_name phase)
(Runtime_events.Timestamp.to_int64 ts)
let runtime_end _ ts phase =
Printf.printf "End\t%s\t%Ld\n"
(Runtime_events.runtime_phase_name phase)
(Runtime_events.Timestamp.to_int64 ts)
let () =
Runtime_events.start ();
let cursor = Runtime_events.create_cursor None in
let callbacks = Runtime_events.Callbacks.create ~runtime_begin ~runtime_end ()
in
while true do
let list_ref = ref [] in (* for later fake GC work *)
for _ = 1 to 100 do
(* here we do some fake GC work *)
list_ref := [];
for _ = 1 to 10 do
list_ref := (Sys.opaque_identity(ref 42)) :: !list_ref
done;
Gc.full_major ();
done;
ignore(Runtime_events.read_poll cursor callbacks None);
Unix.sleep 1
done
```
The next step is to compile and link the program with the runtime\_events library. This can be done as follows:
```
ocamlopt -I +runtime_events -I +unix unix.cmxa runtime_events.cmxa
example.ml -o example
```
When using the *dune* build system, this example can be built as follows:
```
(executable
(name example)
(modules example)
(libraries unix runtime_events))
```
Running the compiled binary of the example gives an output similar to:
```
Begin explicit_gc_full_major 24086187297852
Begin stw_leader 24086187298594
Begin minor 24086187299404
Begin minor_global_roots 24086187299807
End minor_global_roots 24086187331461
Begin minor_remembered_set 24086187331631
Begin minor_finalizers_oldify 24086187544312
End minor_finalizers_oldify 24086187544704
Begin minor_remembered_set_promote 24086187544879
End minor_remembered_set_promote 24086187606414
End minor_remembered_set 24086187606584
Begin minor_finalizers_admin 24086187606854
End minor_finalizers_admin 24086187607152
Begin minor_local_roots 24086187607329
Begin minor_local_roots_promote 24086187609699
End minor_local_roots_promote 24086187610539
End minor_local_roots 24086187610709
End minor 24086187611746
Begin minor_clear 24086187612238
End minor_clear 24086187612580
End stw_leader 24086187613209
...
```
This is an example of self-monitoring, where a program explicitly starts listening to runtime events and monitors itself.
For external monitoring, a program does not need to be aware of the existence of runtime events. Runtime events can be controlled via the environment variable OCAML\_RUNTIME\_EVENTS\_START which, when set, will cause the runtime tracing system to be started at program initialization.
We could remove Runtime\_events.start (); from the previous example and, instead, call the program as below to produce the same result:
```
OCAML_RUNTIME_EVENTS_START=1 ./example
```
####
[](#s-runtime-tracing-environment-variables)Environment variables
Environment variables can be used to control different aspects of the runtime event tracing system. The following environment variables are available:
* OCAML\_RUNTIME\_EVENTS\_START if set will cause the runtime events system to be started as part of the OCaml runtime initialization.
* OCAML\_RUNTIME\_EVENTS\_DIR sets the directory where the .events files containing the runtime event tracing system’s ring buffers will be located. If not present the program’s working directory will be used.
* OCAML\_RUNTIME\_EVENTS\_PRESERVE if set will make the OCaml runtime preserve the runtime events ring buffer files past the termination of the OCaml program. This can be useful for monitoring very short running programs. If not set, the .events files of the OCaml program will be deleted at program termination.
The size of the runtime events ring buffers can be configured via OCAMLRUNPARAM, see section [15.2](runtime#s%3Aocamlrun-options) for more information.
####
[](#s-runtime-tracing-instrumented-runtime)Building with the instrumented runtime
To receive events that are only available in the instrumented runtime, the OCaml program needs to be compiled and linked against the instrumented runtime. For our example program from earlier, this is achieved as follows:
```
ocamlopt -runtime-variant i -I +runtime_events -I +unix unix.cmxa runtime_events.cmxa example.ml -o example
```
And for dune:
```
(executable
(name example)
(modules example)
(flags "-runtime-variant=i")
(libraries unix runtime_events))
```
###
[](#s-runtime-tracing-tooling)25.3.2 With tooling
Programmatic access to events is intended primarily for writers of observability libraries and tooling that end-users use. The flexible API enables use of the performance data from runtime events for logging and monitoring purposes.
In this section we cover several utilities in the runtime\_events\_tools package which provide simple ways of extracting and summarising data from runtime events. The trace utility in particular produces similar data to the previous ’eventlog’ instrumentation system available in OCaml 4.12 to 4.14.
First, install runtime\_events\_tools in an OCaml 5.0+ opam switch:
```
opam install runtime_events_tools
```
This should install the olly tool in your path. You can now generate runtime traces for programs compiled with OCaml 5.0+ using the trace subcommand:
```
olly trace trace.json 'your_program.exe .. args ..'
```
Runtime tracing data will be generated in the json Trace Event Format to trace.json. This can then be loaded into the Chrome tracing viewer or into [Perfetto](https://ui.perfetto.dev/) to visualize the collected trace.
####
[](#s-runtime-tracing-latency)Measuring GC latency
The olly utility also includes a latency subcommand which consumes runtime events data and on program completion emits a parseable histogram summary of pause durations. It can be run as follows:
```
olly latency 'your_program.exe .. args ..'
```
This should produce an output similar to the following:
```
GC latency profile:
#[Mean (ms): 2.46, Stddev (ms): 3.87]
#[Min (ms): 0.01, max (ms): 9.17]
Percentile Latency (ms)
25.0000 0.01
50.0000 0.23
60.0000 0.23
70.0000 0.45
75.0000 0.45
80.0000 0.45
85.0000 0.45
90.0000 9.17
95.0000 9.17
96.0000 9.17
97.0000 9.17
98.0000 9.17
99.0000 9.17
99.9000 9.17
99.9900 9.17
99.9990 9.17
99.9999 9.17
100.0000 9.17
```
ocaml None
[](#s:tydef)11.8 Type and exception definitions
-------------------------------------------------
* [11.8.1 Type definitions](typedecl#ss%3Atypedefs)
* [11.8.2 Exception definitions](typedecl#ss%3Aexndef)
###
[](#ss:typedefs)11.8.1 Type definitions
Type definitions bind type constructors to data types: either variant types, record types, type abbreviations, or abstract data types. They also bind the value constructors and record fields associated with the definition.
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| type-definition | ::= | type [nonrec] [typedef](#typedef) { and [typedef](#typedef) } |
| |
| typedef | ::= | [[type-params](#type-params)] [typeconstr-name](names#typeconstr-name) [type-information](#type-information) |
| |
| type-information | ::= | [[type-equation](#type-equation)] [[type-representation](#type-representation)] { [type-constraint](#type-constraint) } |
| |
| type-equation | ::= | = [typexpr](types#typexpr) |
| |
| type-representation | ::= | = [|] [constr-decl](#constr-decl) { | [constr-decl](#constr-decl) } |
| | ∣ | = [record-decl](#record-decl) |
| | ∣ | = | |
| |
| type-params | ::= | [type-param](#type-param) |
| | ∣ | ( [type-param](#type-param) { , [type-param](#type-param) } ) |
| |
| type-param | ::= | [[ext-variance](#ext-variance)] ' [ident](lex#ident) |
| |
| ext-variance | ::= | [variance](#variance) [[injectivity](#injectivity)] |
| | ∣ | [injectivity](#injectivity) [[variance](#variance)] |
| |
| variance | ::= | + |
| | ∣ | - |
| |
| injectivity | ::= | ! |
| |
| record-decl | ::= | { [field-decl](#field-decl) { ; [field-decl](#field-decl) } [;] } |
| |
| constr-decl | ::= | ([constr-name](names#constr-name) ∣ [] ∣ (::)) [ of [constr-args](#constr-args) ] |
| |
| constr-args | ::= | [typexpr](types#typexpr) { \* [typexpr](types#typexpr) } |
| |
| field-decl | ::= | [mutable] [field-name](names#field-name) : [poly-typexpr](types#poly-typexpr) |
| |
| type-constraint | ::= | constraint [typexpr](types#typexpr) = [typexpr](types#typexpr) |
|
See also the following language extensions: [private types](privatetypes#s%3Aprivate-types), [generalized algebraic datatypes](gadts#s%3Agadts), [attributes](attributes#s%3Aattributes), [extension nodes](extensionnodes#s%3Aextension-nodes), [extensible variant types](extensiblevariants#s%3Aextensible-variants) and [inline records](inlinerecords#s%3Ainline-records).
Type definitions are introduced by the type keyword, and consist in one or several simple definitions, possibly mutually recursive, separated by the and keyword. Each simple definition defines one type constructor.
A simple definition consists in a lowercase identifier, possibly preceded by one or several type parameters, and followed by an optional type equation, then an optional type representation, and then a constraint clause. The identifier is the name of the type constructor being defined.
```
type colour =
| Red | Green | Blue | Yellow | Black | White
| RGB of {r : int; g : int; b : int}
type 'a tree = Lf | Br of 'a * 'a tree * 'a;;
type t = {decoration : string; substance : t'}
and t' = Int of int | List of t list
```
In the right-hand side of type definitions, references to one of the type constructor name being defined are considered as recursive, unless type is followed by nonrec. The nonrec keyword was introduced in OCaml 4.02.2.
The optional type parameters are either one type variable ' [ident](lex#ident), for type constructors with one parameter, or a list of type variables ('[ident](lex#ident)1,…,'[ident](lex#ident)n), for type constructors with several parameters. Each type parameter may be prefixed by a variance constraint + (resp. -) indicating that the parameter is covariant (resp. contravariant), and an injectivity annotation ! indicating that the parameter can be deduced from the whole type. These type parameters can appear in the type expressions of the right-hand side of the definition, optionally restricted by a variance constraint ; *i.e.* a covariant parameter may only appear on the right side of a functional arrow (more precisely, follow the left branch of an even number of arrows), and a contravariant parameter only the left side (left branch of an odd number of arrows). If the type has a representation or an equation, and the parameter is free (*i.e.* not bound via a type constraint to a constructed type), its variance constraint is checked but subtyping *etc.* will use the inferred variance of the parameter, which may be less restrictive; otherwise (*i.e.* for abstract types or non-free parameters), the variance must be given explicitly, and the parameter is invariant if no variance is given.
The optional type equation = [typexpr](types#typexpr) makes the defined type equivalent to the type expression [typexpr](types#typexpr): one can be substituted for the other during typing. If no type equation is given, a new type is generated: the defined type is incompatible with any other type.
The optional type representation describes the data structure representing the defined type, by giving the list of associated constructors (if it is a variant type) or associated fields (if it is a record type). If no type representation is given, nothing is assumed on the structure of the type besides what is stated in the optional type equation.
The type representation = [|] [constr-decl](#constr-decl) { | [constr-decl](#constr-decl) } describes a variant type. The constructor declarations [constr-decl](#constr-decl)1, …, [constr-decl](#constr-decl)n describe the constructors associated to this variant type. The constructor declaration [constr-name](names#constr-name) of [typexpr](types#typexpr)1 \* … \* [typexpr](types#typexpr)n declares the name [constr-name](names#constr-name) as a non-constant constructor, whose arguments have types [typexpr](types#typexpr)1 …[typexpr](types#typexpr)n. The constructor declaration [constr-name](names#constr-name) declares the name [constr-name](names#constr-name) as a constant constructor. Constructor names must be capitalized.
The type representation = { [field-decl](#field-decl) { ; [field-decl](#field-decl) } [;] } describes a record type. The field declarations [field-decl](#field-decl)1, …, [field-decl](#field-decl)n describe the fields associated to this record type. The field declaration [field-name](names#field-name) : [poly-typexpr](types#poly-typexpr) declares [field-name](names#field-name) as a field whose argument has type [poly-typexpr](types#poly-typexpr). The field declaration mutable [field-name](names#field-name) : [poly-typexpr](types#poly-typexpr) behaves similarly; in addition, it allows physical modification of this field. Immutable fields are covariant, mutable fields are non-variant. Both mutable and immutable fields may have explicitly polymorphic types. The polymorphism of the contents is statically checked whenever a record value is created or modified. Extracted values may have their types instantiated.
The two components of a type definition, the optional equation and the optional representation, can be combined independently, giving rise to four typical situations:
Abstract type: no equation, no representation.
When appearing in a module signature, this definition specifies nothing on the type constructor, besides its number of parameters: its representation is hidden and it is assumed incompatible with any other type.
Type abbreviation: an equation, no representation.
This defines the type constructor as an abbreviation for the type expression on the right of the = sign.
New variant type or record type: no equation, a representation.
This generates a new type constructor and defines associated constructors or fields, through which values of that type can be directly built or inspected.
Re-exported variant type or record type: an equation, a representation.
In this case, the type constructor is defined as an abbreviation for the type expression given in the equation, but in addition the constructors or fields given in the representation remain attached to the defined type constructor. The type expression in the equation part must agree with the representation: it must be of the same kind (record or variant) and have exactly the same constructors or fields, in the same order, with the same arguments. Moreover, the new type constructor must have the same arity and the same type constraints as the original type constructor.
The type variables appearing as type parameters can optionally be prefixed by + or - to indicate that the type constructor is covariant or contravariant with respect to this parameter. This variance information is used to decide subtyping relations when checking the validity of :> coercions (see section [11.7.7](expr#ss%3Aexpr-coercions)).
For instance, type +'a t declares t as an abstract type that is covariant in its parameter; this means that if the type τ is a subtype of the type σ, then τ t is a subtype of σ t. Similarly, type -'a t declares that the abstract type t is contravariant in its parameter: if τ is a subtype of σ, then σ t is a subtype of τ t. If no + or - variance annotation is given, the type constructor is assumed non-variant in the corresponding parameter. For instance, the abstract type declaration type 'a t means that τ t is neither a subtype nor a supertype of σ t if τ is subtype of σ.
The variance indicated by the + and - annotations on parameters is enforced only for abstract and private types, or when there are type constraints. Otherwise, for abbreviations, variant and record types without type constraints, the variance properties of the type constructor are inferred from its definition, and the variance annotations are only checked for conformance with the definition.
Injectivity annotations are only necessary for abstract types and private row types, since they can otherwise be deduced from the type declaration: all parameters are injective for record and variant type declarations (including extensible types); for type abbreviations a parameter is injective if it has an injective occurrence in its defining equation (be it private or not). For constrained type parameters in type abbreviations, they are injective if either they appear at an injective position in the body, or if all their type variables are injective; in particular, if a constrained type parameter contains a variable that doesn’t appear in the body, it cannot be injective.
The construct constraint ' [ident](lex#ident) = [typexpr](types#typexpr) allows the specification of type parameters. Any actual type argument corresponding to the type parameter [ident](lex#ident) has to be an instance of [typexpr](types#typexpr) (more precisely, [ident](lex#ident) and [typexpr](types#typexpr) are unified). Type variables of [typexpr](types#typexpr) can appear in the type equation and the type declaration.
###
[](#ss:exndef)11.8.2 Exception definitions
| | | | | | | |
| --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| exception-definition | ::= | exception [constr-decl](#constr-decl) |
| | ∣ | exception [constr-name](names#constr-name) = [constr](names#constr) |
|
Exception definitions add new constructors to the built-in variant type `exn` of exception values. The constructors are declared as for a definition of a variant type.
```
# exception E of int * string;;
exception E of int * string
```
The form exception [constr-decl](#constr-decl) generates a new exception, distinct from all other exceptions in the system. The form exception [constr-name](names#constr-name) = [constr](names#constr) gives an alternate name to an existing exception.
```
# exception E of int * string
exception F = E
let eq =
E (1, "one") = F (1, "one");;
exception E of int * string
exception F of int * string
val eq : bool = true
```
| programming_docs |
ocaml None
[](#s:modtypes)11.10 Module types (module specifications)
-----------------------------------------------------------
* [11.10.1 Simple module types](modtypes#ss%3Amty-simple)
* [11.10.2 Signatures](modtypes#ss%3Amty-signatures)
* [11.10.3 Functor types](modtypes#ss%3Amty-functors)
* [11.10.4 The with operator](modtypes#ss%3Amty-with)
Module types are the module-level equivalent of type expressions: they specify the general shape and type properties of modules.
| | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| module-type | ::= | [modtype-path](names#modtype-path) |
| | ∣ | sig { [specification](#specification) [;;] } end |
| | ∣ | functor ( [module-name](names#module-name) : [module-type](#module-type) ) -> [module-type](#module-type) |
| | ∣ | [module-type](#module-type) -> [module-type](#module-type) |
| | ∣ | [module-type](#module-type) with [mod-constraint](#mod-constraint) { and [mod-constraint](#mod-constraint) } |
| | ∣ | ( [module-type](#module-type) ) |
| |
| mod-constraint | ::= | type [[type-params](typedecl#type-params)] [typeconstr](names#typeconstr) [type-equation](typedecl#type-equation) { [type-constraint](typedecl#type-constraint) } |
| | ∣ | module [module-path](names#module-path) = [extended-module-path](names#extended-module-path) |
| |
|
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| specification | ::= | val [value-name](names#value-name) : [typexpr](types#typexpr) |
| | ∣ | external [value-name](names#value-name) : [typexpr](types#typexpr) = [external-declaration](intfc#external-declaration) |
| | ∣ | [type-definition](typedecl#type-definition) |
| | ∣ | exception [constr-decl](typedecl#constr-decl) |
| | ∣ | [class-specification](classes#class-specification) |
| | ∣ | [classtype-definition](classes#classtype-definition) |
| | ∣ | module [module-name](names#module-name) : [module-type](#module-type) |
| | ∣ | module [module-name](names#module-name) { ( [module-name](names#module-name) : [module-type](#module-type) ) } : [module-type](#module-type) |
| | ∣ | module type [modtype-name](names#modtype-name) |
| | ∣ | module type [modtype-name](names#modtype-name) = [module-type](#module-type) |
| | ∣ | open [module-path](names#module-path) |
| | ∣ | include [module-type](#module-type) |
|
See also the following language extensions: [recovering the type of a module](moduletypeof#s%3Amodule-type-of), [substitution inside a signature](signaturesubstitution#s%3Asignature-substitution), [type-level module aliases](modulealias#s%3Amodule-alias), [attributes](attributes#s%3Aattributes), [extension nodes](extensionnodes#s%3Aextension-nodes), [generative functors](generativefunctors#s%3Agenerative-functors), and [module type substitutions](signaturesubstitution#ss%3Amodule-type-substitution).
###
[](#ss:mty-simple)11.10.1 Simple module types
The expression [modtype-path](names#modtype-path) is equivalent to the module type bound to the name [modtype-path](names#modtype-path). The expression ( [module-type](#module-type) ) denotes the same type as [module-type](#module-type).
###
[](#ss:mty-signatures)11.10.2 Signatures
Signatures are type specifications for structures. Signatures sig … end are collections of type specifications for value names, type names, exceptions, module names and module type names. A structure will match a signature if the structure provides definitions (implementations) for all the names specified in the signature (and possibly more), and these definitions meet the type requirements given in the signature.
An optional ;; is allowed after each specification in a signature. It serves as a syntactic separator with no semantic meaning.
####
[](#sss:mty-values)Value specifications
A specification of a value component in a signature is written val [value-name](names#value-name) : [typexpr](types#typexpr), where [value-name](names#value-name) is the name of the value and [typexpr](types#typexpr) its expected type.
The form external [value-name](names#value-name) : [typexpr](types#typexpr) = [external-declaration](intfc#external-declaration) is similar, except that it requires in addition the name to be implemented as the external function specified in [external-declaration](intfc#external-declaration) (see chapter [22](intfc#c%3Aintf-c)).
####
[](#sss:mty-type)Type specifications
A specification of one or several type components in a signature is written type [typedef](typedecl#typedef) { and [typedef](typedecl#typedef) } and consists of a sequence of mutually recursive definitions of type names.
Each type definition in the signature specifies an optional type equation = [typexpr](types#typexpr) and an optional type representation = [constr-decl](typedecl#constr-decl) … or = { [field-decl](typedecl#field-decl) … }. The implementation of the type name in a matching structure must be compatible with the type expression specified in the equation (if given), and have the specified representation (if given). Conversely, users of that signature will be able to rely on the type equation or type representation, if given. More precisely, we have the following four situations:
Abstract type: no equation, no representation.
Names that are defined as abstract types in a signature can be implemented in a matching structure by any kind of type definition (provided it has the same number of type parameters). The exact implementation of the type will be hidden to the users of the structure. In particular, if the type is implemented as a variant type or record type, the associated constructors and fields will not be accessible to the users; if the type is implemented as an abbreviation, the type equality between the type name and the right-hand side of the abbreviation will be hidden from the users of the structure. Users of the structure consider that type as incompatible with any other type: a fresh type has been generated.
Type abbreviation: an equation = [typexpr](types#typexpr), no representation.
The type name must be implemented by a type compatible with [typexpr](types#typexpr). All users of the structure know that the type name is compatible with [typexpr](types#typexpr).
New variant type or record type: no equation, a representation.
The type name must be implemented by a variant type or record type with exactly the constructors or fields specified. All users of the structure have access to the constructors or fields, and can use them to create or inspect values of that type. However, users of the structure consider that type as incompatible with any other type: a fresh type has been generated.
Re-exported variant type or record type: an equation, a representation.
This case combines the previous two: the representation of the type is made visible to all users, and no fresh type is generated.
####
[](#sss:mty-exn)Exception specification
The specification exception [constr-decl](typedecl#constr-decl) in a signature requires the matching structure to provide an exception with the name and arguments specified in the definition, and makes the exception available to all users of the structure.
####
[](#sss:mty-class)Class specifications
A specification of one or several classes in a signature is written class [class-spec](classes#class-spec) { and [class-spec](classes#class-spec) } and consists of a sequence of mutually recursive definitions of class names.
Class specifications are described more precisely in section [11.9.4](classes#ss%3Aclass-spec).
####
[](#sss:mty-classtype)Class type specifications
A specification of one or several class types in a signature is written class type [classtype-def](classes#classtype-def) { and [classtype-def](classes#classtype-def) } and consists of a sequence of mutually recursive definitions of class type names. Class type specifications are described more precisely in section [11.9.5](classes#ss%3Aclasstype).
####
[](#sss:mty-module)Module specifications
A specification of a module component in a signature is written module [module-name](names#module-name) : [module-type](#module-type), where [module-name](names#module-name) is the name of the module component and [module-type](#module-type) its expected type. Modules can be nested arbitrarily; in particular, functors can appear as components of structures and functor types as components of signatures.
For specifying a module component that is a functor, one may write
module [module-name](names#module-name) ( name1 : [module-type](#module-type)1 ) … ( namen : [module-type](#module-type)n ) : [module-type](#module-type)
instead of
module [module-name](names#module-name) : functor ( name1 : [module-type](#module-type)1 ) -> … -> [module-type](#module-type)
####
[](#sss:mty-mty)Module type specifications
A module type component of a signature can be specified either as a manifest module type or as an abstract module type.
An abstract module type specification module type [modtype-name](names#modtype-name) allows the name [modtype-name](names#modtype-name) to be implemented by any module type in a matching signature, but hides the implementation of the module type to all users of the signature.
A manifest module type specification module type [modtype-name](names#modtype-name) = [module-type](#module-type) requires the name [modtype-name](names#modtype-name) to be implemented by the module type [module-type](#module-type) in a matching signature, but makes the equality between [modtype-name](names#modtype-name) and [module-type](#module-type) apparent to all users of the signature.
####
[](#sss:mty-open)Opening a module path
The expression open [module-path](names#module-path) in a signature does not specify any components. It simply affects the parsing of the following items of the signature, allowing components of the module denoted by [module-path](names#module-path) to be referred to by their simple names name instead of path accesses [module-path](names#module-path) . name. The scope of the open stops at the end of the signature expression.
####
[](#sss:mty-include)Including a signature
The expression include [module-type](#module-type) in a signature performs textual inclusion of the components of the signature denoted by [module-type](#module-type). It behaves as if the components of the included signature were copied at the location of the include. The [module-type](#module-type) argument must refer to a module type that is a signature, not a functor type.
###
[](#ss:mty-functors)11.10.3 Functor types
The module type expression functor ( [module-name](names#module-name) : [module-type](#module-type)1 ) -> [module-type](#module-type)2 is the type of functors (functions from modules to modules) that take as argument a module of type [module-type](#module-type)1 and return as result a module of type [module-type](#module-type)2. The module type [module-type](#module-type)2 can use the name [module-name](names#module-name) to refer to type components of the actual argument of the functor. If the type [module-type](#module-type)2 does not depend on type components of [module-name](names#module-name), the module type expression can be simplified with the alternative short syntax [module-type](#module-type)1 -> [module-type](#module-type)2 . No restrictions are placed on the type of the functor argument; in particular, a functor may take another functor as argument (“higher-order” functor).
When the result module type is itself a functor,
functor ( name1 : [module-type](#module-type)1 ) -> … -> functor ( namen : [module-type](#module-type)n ) -> [module-type](#module-type)
one may use the abbreviated form
functor ( name1 : [module-type](#module-type)1 ) … ( namen : [module-type](#module-type)n ) -> [module-type](#module-type) ###
[](#ss:mty-with)11.10.4 The with operator
Assuming [module-type](#module-type) denotes a signature, the expression [module-type](#module-type) with [mod-constraint](#mod-constraint) { and [mod-constraint](#mod-constraint) } denotes the same signature where type equations have been added to some of the type specifications, as described by the constraints following the with keyword. The constraint type [[type-parameters](classes#type-parameters)] [typeconstr](names#typeconstr) = [typexpr](types#typexpr) adds the type equation = [typexpr](types#typexpr) to the specification of the type component named [typeconstr](names#typeconstr) of the constrained signature. The constraint module [module-path](names#module-path) = [extended-module-path](names#extended-module-path) adds type equations to all type components of the sub-structure denoted by [module-path](names#module-path), making them equivalent to the corresponding type components of the structure denoted by [extended-module-path](names#extended-module-path).
For instance, if the module type name S is bound to the signature
```
sig type t module M: (sig type u end) end
```
then S with type t=int denotes the signature
```
sig type t=int module M: (sig type u end) end
```
and S with module M = N denotes the signature
```
sig type t module M: (sig type u=N.u end) end
```
A functor taking two arguments of type S that share their t component is written
```
functor (A: S) (B: S with type t = A.t) ...
```
Constraints are added left to right. After each constraint has been applied, the resulting signature must be a subtype of the signature before the constraint was applied. Thus, the with operator can only add information on the type components of a signature, but never remove information.
ocaml Chapter 21 Profiling (ocamlprof) Chapter 21 Profiling (ocamlprof)
================================
* [21.1 Compiling for profiling](profil#s%3Aocamlprof-compiling)
* [21.2 Profiling an execution](profil#s%3Aocamlprof-profiling)
* [21.3 Printing profiling information](profil#s%3Aocamlprof-printing)
* [21.4 Time profiling](profil#s%3Aocamlprof-time-profiling)
This chapter describes how the execution of OCaml programs can be profiled, by recording how many times functions are called, branches of conditionals are taken, …
[](#s:ocamlprof-compiling)21.1 Compiling for profiling
--------------------------------------------------------
Before profiling an execution, the program must be compiled in profiling mode, using the ocamlcp front-end to the ocamlc compiler (see chapter [13](comp#c%3Acamlc)) or the ocamloptp front-end to the ocamlopt compiler (see chapter [16](native#c%3Anativecomp)). When compiling modules separately, ocamlcp or ocamloptp must be used when compiling the modules (production of .cmo or .cmx files), and can also be used (though this is not strictly necessary) when linking them together.
#####
[](#p:ocamlprof-warning)Note
If a module (.ml file) doesn’t have a corresponding interface (.mli file), then compiling it with ocamlcp will produce object files (.cmi and .cmo) that are not compatible with the ones produced by ocamlc, which may lead to problems (if the .cmi or .cmo is still around) when switching between profiling and non-profiling compilations. To avoid this problem, you should always have a .mli file for each .ml file. The same problem exists with ocamloptp.
#####
[](#p:ocamlprof-reserved)Note
To make sure your programs can be compiled in profiling mode, avoid using any identifier that begins with \_\_ocaml\_prof.
The amount of profiling information can be controlled through the -P option to ocamlcp or ocamloptp, followed by one or several letters indicating which parts of the program should be profiled:
a
all options
f
function calls : a count point is set at the beginning of each function body
i
if …then …else … : count points are set in both then branch and else branch
l
while, for loops: a count point is set at the beginning of the loop body
m
match branches: a count point is set at the beginning of the body of each branch
t
try …with … branches: a count point is set at the beginning of the body of each branch
For instance, compiling with ocamlcp -P film profiles function calls, if…then…else…, loops and pattern matching.
Calling ocamlcp or ocamloptp without the -P option defaults to -P fm, meaning that only function calls and pattern matching are profiled.
#####
[](#sec466)Note
For compatibility with previous releases, ocamlcp also accepts the -p option, with the same arguments and behaviour as -P.
The ocamlcp and ocamloptp commands also accept all the options of the corresponding ocamlc or ocamlopt compiler, except the -pp (preprocessing) option.
[](#s:ocamlprof-profiling)21.2 Profiling an execution
-------------------------------------------------------
Running an executable that has been compiled with ocamlcp or ocamloptp records the execution counts for the specified parts of the program and saves them in a file called ocamlprof.dump in the current directory.
If the environment variable OCAMLPROF\_DUMP is set when the program exits, its value is used as the file name instead of ocamlprof.dump.
The dump file is written only if the program terminates normally (by calling exit or by falling through). It is not written if the program terminates with an uncaught exception.
If a compatible dump file already exists in the current directory, then the profiling information is accumulated in this dump file. This allows, for instance, the profiling of several executions of a program on different inputs. Note that dump files produced by byte-code executables (compiled with ocamlcp) are compatible with the dump files produced by native executables (compiled with ocamloptp).
[](#s:ocamlprof-printing)21.3 Printing profiling information
--------------------------------------------------------------
The ocamlprof command produces a source listing of the program modules where execution counts have been inserted as comments. For instance,
```
ocamlprof foo.ml
```
prints the source code for the foo module, with comments indicating how many times the functions in this module have been called. Naturally, this information is accurate only if the source file has not been modified after it was compiled.
The following options are recognized by ocamlprof:
-args filename
Read additional newline-terminated command line arguments from filename.
-args0 filename
Read additional null character terminated command line arguments from filename.
-f dumpfile
Specifies an alternate dump file of profiling information to be read.
-F string
Specifies an additional string to be output with profiling information. By default, ocamlprof will annotate programs with comments of the form (\* n \*) where n is the counter value for a profiling point. With option -F s, the annotation will be (\* sn \*).
-impl filename
Process the file filename as an implementation file, even if its extension is not .ml.
-intf filename
Process the file filename as an interface file, even if its extension is not .mli.
-version
Print version string and exit.
-vnum
Print short version number and exit.
-help or --help
Display a short usage summary and exit.
[](#s:ocamlprof-time-profiling)21.4 Time profiling
----------------------------------------------------
Profiling with ocamlprof only records execution counts, not the actual time spent within each function. There is currently no way to perform time profiling on bytecode programs generated by ocamlc. For time profiling of native code, users are recommended to use standard tools such as perf (on Linux), Instruments (on macOS) and DTrace. Profiling with gprof is no longer supported.
| programming_docs |
ocaml Chapter 13 Batch compilation (ocamlc) Chapter 13 Batch compilation (ocamlc)
=====================================
* [13.1 Overview of the compiler](comp#s%3Acomp-overview)
* [13.2 Options](comp#s%3Acomp-options)
* [13.3 Modules and the file system](comp#s%3Amodules-file-system)
* [13.4 Common errors](comp#s%3Acomp-errors)
* [13.5 Warning reference](comp#s%3Acomp-warnings)
This chapter describes the OCaml batch compiler ocamlc, which compiles OCaml source files to bytecode object files and links these object files to produce standalone bytecode executable files. These executable files are then run by the bytecode interpreter ocamlrun.
[](#s:comp-overview)13.1 Overview of the compiler
---------------------------------------------------
The ocamlc command has a command-line interface similar to the one of most C compilers. It accepts several types of arguments and processes them sequentially, after all options have been processed:
* Arguments ending in .mli are taken to be source files for compilation unit interfaces. Interfaces specify the names exported by compilation units: they declare value names with their types, define public data types, declare abstract data types, and so on. From the file x.mli, the ocamlc compiler produces a compiled interface in the file x.cmi.
* Arguments ending in .ml are taken to be source files for compilation unit implementations. Implementations provide definitions for the names exported by the unit, and also contain expressions to be evaluated for their side-effects. From the file x.ml, the ocamlc compiler produces compiled object bytecode in the file x.cmo.If the interface file x.mli exists, the implementation x.ml is checked against the corresponding compiled interface x.cmi, which is assumed to exist. If no interface x.mli is provided, the compilation of x.ml produces a compiled interface file x.cmi in addition to the compiled object code file x.cmo. The file x.cmi produced corresponds to an interface that exports everything that is defined in the implementation x.ml.
* Arguments ending in .cmo are taken to be compiled object bytecode. These files are linked together, along with the object files obtained by compiling .ml arguments (if any), and the OCaml standard library, to produce a standalone executable program. The order in which .cmo and .ml arguments are presented on the command line is relevant: compilation units are initialized in that order at run-time, and it is a link-time error to use a component of a unit before having initialized it. Hence, a given x.cmo file must come before all .cmo files that refer to the unit x.
* Arguments ending in .cma are taken to be libraries of object bytecode. A library of object bytecode packs in a single file a set of object bytecode files (.cmo files). Libraries are built with ocamlc -a (see the description of the -a option below). The object files contained in the library are linked as regular .cmo files (see above), in the order specified when the .cma file was built. The only difference is that if an object file contained in a library is not referenced anywhere in the program, then it is not linked in.
* Arguments ending in .c are passed to the C compiler, which generates a .o object file (.obj under Windows). This object file is linked with the program if the -custom flag is set (see the description of -custom below).
* Arguments ending in .o or .a (.obj or .lib under Windows) are assumed to be C object files and libraries. They are passed to the C linker when linking in -custom mode (see the description of -custom below).
* Arguments ending in .so (.dll under Windows) are assumed to be C shared libraries (DLLs). During linking, they are searched for external C functions referenced from the OCaml code, and their names are written in the generated bytecode executable. The run-time system ocamlrun then loads them dynamically at program start-up time.
The output of the linking phase is a file containing compiled bytecode that can be executed by the OCaml bytecode interpreter: the command named ocamlrun. If a.out is the name of the file produced by the linking phase, the command
```
ocamlrun a.out arg1 arg2 … argn
```
executes the compiled code contained in a.out, passing it as arguments the character strings arg1 to argn. (See chapter [15](runtime#c%3Aruntime) for more details.)
On most systems, the file produced by the linking phase can be run directly, as in:
```
./a.out arg1 arg2 … argn
```
The produced file has the executable bit set, and it manages to launch the bytecode interpreter by itself.
The compiler is able to emit some information on its internal stages. It can output .cmt files for the implementation of the compilation unit and .cmti for signatures if the option -bin-annot is passed to it (see the description of -bin-annot below). Each such file contains a typed abstract syntax tree (AST), that is produced during the type checking procedure. This tree contains all available information about the location and the specific type of each term in the source file. The AST is partial if type checking was unsuccessful.
These .cmt and .cmti files are typically useful for code inspection tools.
[](#s:comp-options)13.2 Options
---------------------------------
The following command-line options are recognized by ocamlc. The options -pack, -a, -c, -output-obj and -output-complete-obj are mutually exclusive.
-a
Build a library(.cma file) with the object files ( .cmo files) given on the command line, instead of linking them into an executable file. The name of the library must be set with the -o option.If -custom, -cclib or -ccopt options are passed on the command line, these options are stored in the resulting .cmalibrary. Then, linking with this library automatically adds back the -custom, -cclib and -ccopt options as if they had been provided on the command line, unless the -noautolink option is given.
-absname
Force error messages to show absolute paths for file names.
-annot
Deprecated since OCaml 4.11. Please use -bin-annot instead.
-args filename
Read additional newline-terminated command line arguments from filename.
-args0 filename
Read additional null character terminated command line arguments from filename.
-bin-annot
Dump detailed information about the compilation (types, bindings, tail-calls, etc) in binary format. The information for file src.ml (resp. src.mli) is put into file src.cmt (resp. src.cmti). In case of a type error, dump all the information inferred by the type-checker before the error. The \*.cmt and \*.cmti files produced by -bin-annot contain more information and are much more compact than the files produced by -annot.
-c
Compile only. Suppress the linking phase of the compilation. Source code files are turned into compiled files, but no executable file is produced. This option is useful to compile modules separately.
-cc ccomp
Use ccomp as the C linker when linking in “custom runtime” mode (see the -custom option) and as the C compiler for compiling .c source files.
-cclib -llibname
Pass the -llibname option to the C linker when linking in “custom runtime” mode (see the -custom option). This causes the given C library to be linked with the program.
-ccopt option
Pass the given option to the C compiler and linker. When linking in “custom runtime” mode, for instance -ccopt -Ldir causes the C linker to search for C libraries in directory dir. (See the -custom option.)
-cmi-file filename
Use the given interface file to type-check the ML source file to compile. When this option is not specified, the compiler looks for a .mli file with the same base name than the implementation it is compiling and in the same directory. If such a file is found, the compiler looks for a corresponding .cmi file in the included directories and reports an error if it fails to find one.
-color mode
Enable or disable colors in compiler messages (especially warnings and errors). The following modes are supported:
auto
use heuristics to enable colors only if the output supports them (an ANSI-compatible tty terminal);
always
enable colors unconditionally;
never
disable color output.
The environment variable OCAML\_COLOR is considered if -color is not provided. Its values are auto/always/never as above.
If -color is not provided, OCAML\_COLOR is not set and the environment variable NO\_COLOR is set, then color output is disabled. Otherwise, the default setting is ’auto’, and the current heuristic checks that the TERM environment variable exists and is not empty or dumb, and that ’isatty(stderr)’ holds.
-error-style mode
Control the way error messages and warnings are printed. The following modes are supported:
short
only print the error and its location;
contextual
like short, but also display the source code snippet corresponding to the location of the error.
The default setting is contextual.The environment variable OCAML\_ERROR\_STYLE is considered if -error-style is not provided. Its values are short/contextual as above.
-compat-32
Check that the generated bytecode executable can run on 32-bit platforms and signal an error if it cannot. This is useful when compiling bytecode on a 64-bit machine.
-config
Print the version number of ocamlc and a detailed summary of its configuration, then exit.
-config-var var
Print the value of a specific configuration variable from the -config output, then exit. If the variable does not exist, the exit code is non-zero. This option is only available since OCaml 4.08, so script authors should have a fallback for older versions.
-custom
Link in “custom runtime” mode. In the default linking mode, the linker produces bytecode that is intended to be executed with the shared runtime system, ocamlrun. In the custom runtime mode, the linker produces an output file that contains both the runtime system and the bytecode for the program. The resulting file is larger, but it can be executed directly, even if the ocamlrun command is not installed. Moreover, the “custom runtime” mode enables static linking of OCaml code with user-defined C functions, as described in chapter [22](intfc#c%3Aintf-c).
>
> Unix: Never use the strip command on executables produced by ocamlc -custom, this would remove the bytecode part of the executable.
>
> Unix: Security warning: never set the “setuid” or “setgid” bits on executables produced by ocamlc -custom, this would make them vulnerable to attacks.
-depend ocamldep-args
Compute dependencies, as the ocamldep command would do. The remaining arguments are interpreted as if they were given to the ocamldep command.
-dllib -llibname
Arrange for the C shared library dlllibname.so (dlllibname.dll under Windows) to be loaded dynamically by the run-time system ocamlrun at program start-up time.
-dllpath dir
Adds the directory dir to the run-time search path for shared C libraries. At link-time, shared libraries are searched in the standard search path (the one corresponding to the -I option). The -dllpath option simply stores dir in the produced executable file, where ocamlrun can find it and use it as described in section [15.3](runtime#s%3Aocamlrun-dllpath).
-for-pack module-path
Generate an object file (.cmo) that can later be included as a sub-module (with the given access path) of a compilation unit constructed with -pack. For instance, ocamlc -for-pack P -c A.ml will generate a..cmo that can later be used with ocamlc -pack -o P.cmo a.cmo. Note: you can still pack a module that was compiled without -for-pack but in this case exceptions will be printed with the wrong names.
-g
Add debugging information while compiling and linking. This option is required in order to be able to debug the program with ocamldebug (see chapter [20](debugger#c%3Adebugger)), and to produce stack backtraces when the program terminates on an uncaught exception (see section [15.2](runtime#s%3Aocamlrun-options)).
-i
Cause the compiler to print all defined names (with their inferred types or their definitions) when compiling an implementation (.ml file). No compiled files (.cmo and .cmi files) are produced. This can be useful to check the types inferred by the compiler. Also, since the output follows the syntax of interfaces, it can help in writing an explicit interface (.mli file) for a file: just redirect the standard output of the compiler to a .mli file, and edit that file to remove all declarations of unexported names.
-I directory
Add the given directory to the list of directories searched for compiled interface files (.cmi), compiled object code files .cmo, libraries (.cma) and C libraries specified with -cclib -lxxx. By default, the current directory is searched first, then the standard library directory. Directories added with -I are searched after the current directory, in the order in which they were given on the command line, but before the standard library directory. See also option -nostdlib.If the given directory starts with +, it is taken relative to the standard library directory. For instance, -I +unix adds the subdirectory unix of the standard library to the search path.
-impl filename
Compile the file filename as an implementation file, even if its extension is not .ml.
-intf filename
Compile the file filename as an interface file, even if its extension is not .mli.
-intf-suffix string
Recognize file names ending with string as interface files (instead of the default .mli).
-labels
Labels are not ignored in types, labels may be used in applications, and labelled parameters can be given in any order. This is the default.
-linkall
Force all modules contained in libraries to be linked in. If this flag is not given, unreferenced modules are not linked in. When building a library (option -a), setting the -linkall option forces all subsequent links of programs involving that library to link all the modules contained in the library. When compiling a module (option -c), setting the -linkall option ensures that this module will always be linked if it is put in a library and this library is linked.
-make-runtime
Build a custom runtime system (in the file specified by option -o) incorporating the C object files and libraries given on the command line. This custom runtime system can be used later to execute bytecode executables produced with the ocamlc -use-runtime runtime-name option. See section [22.1.6](intfc#ss%3Acustom-runtime) for more information.
-match-context-rows
Set the number of rows of context used for optimization during pattern matching compilation. The default value is 32. Lower values cause faster compilation, but less optimized code. This advanced option is meant for use in the event that a pattern-match-heavy program leads to significant increases in compilation time.
-no-alias-deps
Do not record dependencies for module aliases. See section [12.8](modulealias#s%3Amodule-alias) for more information.
-no-app-funct
Deactivates the applicative behaviour of functors. With this option, each functor application generates new types in its result and applying the same functor twice to the same argument yields two incompatible structures.
-noassert
Do not compile assertion checks. Note that the special form assert false is always compiled because it is typed specially. This flag has no effect when linking already-compiled files.
-noautolink
When linking .cmalibraries, ignore -custom, -cclib and -ccopt options potentially contained in the libraries (if these options were given when building the libraries). This can be useful if a library contains incorrect specifications of C libraries or C options; in this case, during linking, set -noautolink and pass the correct C libraries and options on the command line.
-nolabels
Ignore non-optional labels in types. Labels cannot be used in applications, and parameter order becomes strict.
-nostdlib
Do not include the standard library directory in the list of directories searched for compiled interface files (.cmi), compiled object code files (.cmo), libraries (.cma), and C libraries specified with -cclib -lxxx. See also option -I.
-o output-file
Specify the name of the output file to produce. For executable files, the default output name is a.out under Unix and camlprog.exe under Windows. If the -a option is given, specify the name of the library produced. If the -pack option is given, specify the name of the packed object file produced. If the -output-obj or -output-complete-obj options are given, specify the name of the produced object file. If the -c option is given, specify the name of the object file produced for the *next* source file that appears on the command line.
-opaque
When the native compiler compiles an implementation, by default it produces a .cmx file containing information for cross-module optimization. It also expects .cmx files to be present for the dependencies of the currently compiled source, and uses them for optimization. Since OCaml 4.03, the compiler will emit a warning if it is unable to locate the .cmx file of one of those dependencies.The -opaque option, available since 4.04, disables cross-module optimization information for the currently compiled unit. When compiling .mli interface, using -opaque marks the compiled .cmi interface so that subsequent compilations of modules that depend on it will not rely on the corresponding .cmx file, nor warn if it is absent. When the native compiler compiles a .ml implementation, using -opaque generates a .cmx that does not contain any cross-module optimization information.
Using this option may degrade the quality of generated code, but it reduces compilation time, both on clean and incremental builds. Indeed, with the native compiler, when the implementation of a compilation unit changes, all the units that depend on it may need to be recompiled – because the cross-module information may have changed. If the compilation unit whose implementation changed was compiled with -opaque, no such recompilation needs to occur. This option can thus be used, for example, to get faster edit-compile-test feedback loops.
-open Module
Opens the given module before processing the interface or implementation files. If several -open options are given, they are processed in order, just as if the statements open! Module1;; ... open! ModuleN;; were added at the top of each file.
-output-obj
Cause the linker to produce a C object file instead of a bytecode executable file. This is useful to wrap OCaml code as a C library, callable from any C program. See chapter [22](intfc#c%3Aintf-c), section [22.7.5](intfc#ss%3Ac-embedded-code). The name of the output object file must be set with the -o option. This option can also be used to produce a C source file (.c extension) or a compiled shared/dynamic library (.so extension, .dll under Windows).
-output-complete-exe
Build a self-contained executable by linking a C object file containing the bytecode program, the OCaml runtime system and any other static C code given to ocamlc. The resulting effect is similar to -custom, except that the bytecode is embedded in the C code so it is no longer accessible to tools such as ocamldebug. On the other hand, the resulting binary is resistant to strip.
-output-complete-obj
Same as -output-obj options except the object file produced includes the runtime and autolink libraries.
-pack
Build a bytecode object file (.cmo file) and its associated compiled interface (.cmi) that combines the object files given on the command line, making them appear as sub-modules of the output .cmo file. The name of the output .cmo file must be given with the -o option. For instance,
```
ocamlc -pack -o p.cmo a.cmo b.cmo c.cmo
```
generates compiled files p.cmo and p.cmi describing a compilation unit having three sub-modules A, B and C, corresponding to the contents of the object files a.cmo, b.cmo and c.cmo. These contents can be referenced as P.A, P.B and P.C in the remainder of the program.
-pp command
Cause the compiler to call the given command as a preprocessor for each source file. The output of command is redirected to an intermediate file, which is compiled. If there are no compilation errors, the intermediate file is deleted afterwards.
-ppx command
After parsing, pipe the abstract syntax tree through the preprocessor command. The module Ast\_mapper, described in chapter [29](parsing#c%3Aparsinglib): [Ast\_mapper](https://v2.ocaml.org/releases/5.0/htmlman/compilerlibref/Ast_mapper.html) , implements the external interface of a preprocessor.
-principal
Check information path during type-checking, to make sure that all types are derived in a principal way. When using labelled arguments and/or polymorphic methods, this flag is required to ensure future versions of the compiler will be able to infer types correctly, even if internal algorithms change. All programs accepted in -principal mode are also accepted in the default mode with equivalent types, but different binary signatures, and this may slow down type checking; yet it is a good idea to use it once before publishing source code.
-rectypes
Allow arbitrary recursive types during type-checking. By default, only recursive types where the recursion goes through an object type are supported. Note that once you have created an interface using this flag, you must use it again for all dependencies.
-runtime-variant suffix
Add the suffix string to the name of the runtime library used by the program. Currently, only one such suffix is supported: d, and only if the OCaml compiler was configured with option -with-debug-runtime. This suffix gives the debug version of the runtime, which is useful for debugging pointer problems in low-level code such as C stubs.
-stop-after pass
Stop compilation after the given compilation pass. The currently supported passes are: parsing, typing.
-safe-string
Enforce the separation between types string and bytes, thereby making strings read-only. This is the default, and enforced since OCaml 5.0.
-short-paths
When a type is visible under several module-paths, use the shortest one when printing the type’s name in inferred interfaces and error and warning messages. Identifier names starting with an underscore \_ or containing double underscores \_\_ incur a penalty of +10 when computing their length.
-strict-sequence
Force the left-hand part of each sequence to have type unit.
-strict-formats
Reject invalid formats that were accepted in legacy format implementations. You should use this flag to detect and fix such invalid formats, as they will be rejected by future OCaml versions.
-unboxed-types
When a type is unboxable (i.e. a record with a single argument or a concrete datatype with a single constructor of one argument) it will be unboxed unless annotated with [@@ocaml.boxed].
-no-unboxed-types
When a type is unboxable it will be boxed unless annotated with [@@ocaml.unboxed]. This is the default.
-unsafe
Turn bound checking off for array and string accesses (the v.(i) and s.[i] constructs). Programs compiled with -unsafe are therefore slightly faster, but unsafe: anything can happen if the program accesses an array or string outside of its bounds. Additionally, turn off the check for zero divisor in integer division and modulus operations. With -unsafe, an integer division (or modulus) by zero can halt the program or continue with an unspecified result instead of raising a Division\_by\_zero exception.
-unsafe-string
Identify the types string and bytes, thereby making strings writable. This is intended for compatibility with old source code and should not be used with new software. This option raises an error unconditionally since OCaml 5.0.
-use-runtime runtime-name
Generate a bytecode executable file that can be executed on the custom runtime system runtime-name, built earlier with ocamlc -make-runtime runtime-name. See section [22.1.6](intfc#ss%3Acustom-runtime) for more information.
-v
Print the version number of the compiler and the location of the standard library directory, then exit.
-verbose
Print all external commands before they are executed, in particular invocations of the C compiler and linker in -custom mode. Useful to debug C library problems.
-version or -vnum
Print the version number of the compiler in short form (e.g. 3.11.0), then exit.
-w warning-list
Enable, disable, or mark as fatal the warnings specified by the argument warning-list. Each warning can be *enabled* or *disabled*, and each warning can be *fatal* or *non-fatal*. If a warning is disabled, it isn’t displayed and doesn’t affect compilation in any way (even if it is fatal). If a warning is enabled, it is displayed normally by the compiler whenever the source code triggers it. If it is enabled and fatal, the compiler will also stop with an error after displaying it.The warning-list argument is a sequence of warning specifiers, with no separators between them. A warning specifier is one of the following:
+num
Enable warning number num.
-num
Disable warning number num.
@num
Enable and mark as fatal warning number num.
+num1..num2
Enable warnings in the given range.
-num1..num2
Disable warnings in the given range.
@num1..num2
Enable and mark as fatal warnings in the given range.
+letter
Enable the set of warnings corresponding to letter. The letter may be uppercase or lowercase.
-letter
Disable the set of warnings corresponding to letter. The letter may be uppercase or lowercase.
@letter
Enable and mark as fatal the set of warnings corresponding to letter. The letter may be uppercase or lowercase.
uppercase-letter
Enable the set of warnings corresponding to uppercase-letter.
lowercase-letter
Disable the set of warnings corresponding to lowercase-letter.
Alternatively, warning-list can specify a single warning using its mnemonic name (see below), as follows:
+name
Enable warning name.
-name
Disable warning name.
@name
Enable and mark as fatal warning name.
Warning numbers, letters and names which are not currently defined are ignored. The warnings are as follows (the name following each number specifies the mnemonic for that warning).
1 comment-start
Suspicious-looking start-of-comment mark.
2 comment-not-end
Suspicious-looking end-of-comment mark.
3
Deprecated synonym for the ’deprecated’ alert.
4 fragile-match
Fragile pattern matching: matching that will remain complete even if additional constructors are added to one of the variant types matched.
5 ignored-partial-application
Partially applied function: expression whose result has function type and is ignored.
6 labels-omitted
Label omitted in function application.
7 method-override
Method overridden.
8 partial-match
Partial match: missing cases in pattern-matching.
9 missing-record-field-pattern
Missing fields in a record pattern.
10 non-unit-statement
Expression on the left-hand side of a sequence that doesn’t have type unit (and that is not a function, see warning number 5).
11 redundant-case
Redundant case in a pattern matching (unused match case).
12 redundant-subpat
Redundant sub-pattern in a pattern-matching.
13 instance-variable-override
Instance variable overridden.
14 illegal-backslash
Illegal backslash escape in a string constant.
15 implicit-public-methods
Private method made public implicitly.
16 unerasable-optional-argument
Unerasable optional argument.
17 undeclared-virtual-method
Undeclared virtual method.
18 not-principal
Non-principal type.
19 non-principal-labels
Type without principality.
20 ignored-extra-argument
Unused function argument.
21 nonreturning-statement
Non-returning statement.
22 preprocessor
Preprocessor warning.
23 useless-record-with
Useless record with clause.
24 bad-module-name
Bad module name: the source file name is not a valid OCaml module name.
25
Ignored: now part of warning 8.
26 unused-var
Suspicious unused variable: unused variable that is bound with let or as, and doesn’t start with an underscore (\_) character.
27 unused-var-strict
Innocuous unused variable: unused variable that is not bound with let nor as, and doesn’t start with an underscore (\_) character.
28 wildcard-arg-to-constant-constr
Wildcard pattern given as argument to a constant constructor.
29 eol-in-string
Unescaped end-of-line in a string constant (non-portable code).
30 duplicate-definitions
Two labels or constructors of the same name are defined in two mutually recursive types.
31 module-linked-twice
A module is linked twice in the same executable. (since 4.00)
32 unused-value-declaration
Unused value declaration. (since 4.00)
33 unused-open
Unused open statement. (since 4.00)
34 unused-type-declaration
Unused type declaration. (since 4.00)
35 unused-for-index
Unused for-loop index. (since 4.00)
36 unused-ancestor
Unused ancestor variable. (since 4.00)
37 unused-constructor
Unused constructor. (since 4.00)
38 unused-extension
Unused extension constructor. (since 4.00)
39 unused-rec-flag
Unused rec flag. (since 4.00)
40 name-out-of-scope
Constructor or label name used out of scope. (since 4.01)
41 ambiguous-name
Ambiguous constructor or label name. (since 4.01)
42 disambiguated-name
Disambiguated constructor or label name (compatibility warning). (since 4.01)
43 nonoptional-label
Nonoptional label applied as optional. (since 4.01)
44 open-shadow-identifier
Open statement shadows an already defined identifier. (since 4.01)
45 open-shadow-label-constructor
Open statement shadows an already defined label or constructor. (since 4.01)
46 bad-env-variable
Error in environment variable. (since 4.01)
47 attribute-payload
Illegal attribute payload. (since 4.02)
48 eliminated-optional-arguments
Implicit elimination of optional arguments. (since 4.02)
49 no-cmi-file
Absent cmi file when looking up module alias. (since 4.02)
50 unexpected-docstring
Unexpected documentation comment. (since 4.03)
51 wrong-tailcall-expectation
Function call annotated with an incorrect @tailcall attribute. (since 4.03)
52 fragile-literal-pattern (see [13.5.3](#ss%3Awarn52))
Fragile constant pattern. (since 4.03)
53 misplaced-attribute
Attribute cannot appear in this context. (since 4.03)
54 duplicated-attribute
Attribute used more than once on an expression. (since 4.03)
55 inlining-impossible
Inlining impossible. (since 4.03)
56 unreachable-case
Unreachable case in a pattern-matching (based on type information). (since 4.03)
57 ambiguous-var-in-pattern-guard (see [13.5.4](#ss%3Awarn57))
Ambiguous or-pattern variables under guard. (since 4.03)
58 no-cmx-file
Missing cmx file. (since 4.03)
59 flambda-assignment-to-non-mutable-value
Assignment to non-mutable value. (since 4.03)
60 unused-module
Unused module declaration. (since 4.04)
61 unboxable-type-in-prim-decl
Unboxable type in primitive declaration. (since 4.04)
62 constraint-on-gadt
Type constraint on GADT type declaration. (since 4.06)
63 erroneous-printed-signature
Erroneous printed signature. (since 4.08)
64 unsafe-array-syntax-without-parsing
-unsafe used with a preprocessor returning a syntax tree. (since 4.08)
65 redefining-unit
Type declaration defining a new ’()’ constructor. (since 4.08)
66 unused-open-bang
Unused open! statement. (since 4.08)
67 unused-functor-parameter
Unused functor parameter. (since 4.10)
68 match-on-mutable-state-prevent-uncurry
Pattern-matching depending on mutable state prevents the remaining arguments from being uncurried. (since 4.12)
69 unused-field
Unused record field. (since 4.13)
70 missing-mli
Missing interface file. (since 4.13)
71 unused-tmc-attribute
Unused @tail\_mod\_cons attribute. (since 4.14)
72 tmc-breaks-tailcall
A tail call is turned into a non-tail call by the @tail\_mod\_cons transformation. (since 4.14)
A
all warnings
C
warnings 1, 2.
D
Alias for warning 3.
E
Alias for warning 4.
F
Alias for warning 5.
K
warnings 32, 33, 34, 35, 36, 37, 38, 39.
L
Alias for warning 6.
M
Alias for warning 7.
P
Alias for warning 8.
R
Alias for warning 9.
S
Alias for warning 10.
U
warnings 11, 12.
V
Alias for warning 13.
X
warnings 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 30.
Y
Alias for warning 26.
Z
Alias for warning 27.
The default setting is -w +a-4-6-7-9-27-29-32..42-44-45-48-50-60. It is displayed by ocamlc -help. Note that warnings 5 and 10 are not always triggered, depending on the internals of the type checker.
-warn-error warning-list
Mark as fatal the warnings specified in the argument warning-list. The compiler will stop with an error when one of these warnings is emitted. The warning-list has the same meaning as for the -w option: a + sign (or an uppercase letter) marks the corresponding warnings as fatal, a - sign (or a lowercase letter) turns them back into non-fatal warnings, and a @ sign both enables and marks as fatal the corresponding warnings.Note: it is not recommended to use warning sets (i.e. letters) as arguments to -warn-error in production code, because this can break your build when future versions of OCaml add some new warnings.
The default setting is -warn-error -a+31 (only warning 31 is fatal).
-warn-help
Show the description of all available warning numbers.
-where
Print the location of the standard library, then exit.
-with-runtime
Include the runtime system in the generated program. This is the default.
-without-runtime
The compiler does not include the runtime system (nor a reference to it) in the generated program; it must be supplied separately.
- file
Process file as a file name, even if it starts with a dash (-) character.
-help or --help
Display a short usage summary and exit.
#####
[](#sec339)contextual-cli-control
Contextual control of command-line options
The compiler command line can be modified “from the outside” with the following mechanisms. These are experimental and subject to change. They should be used only for experimental and development work, not in released packages.
OCAMLPARAM (environment variable)
A set of arguments that will be inserted before or after the arguments from the command line. Arguments are specified in a comma-separated list of name=value pairs. A \_ is used to specify the position of the command line arguments, i.e. a=x,\_,b=y means that a=x should be executed before parsing the arguments, and b=y after. Finally, an alternative separator can be specified as the first character of the string, within the set :|; ,.
ocaml\_compiler\_internal\_params (file in the stdlib directory)
A mapping of file names to lists of arguments that will be added to the command line (and OCAMLPARAM) arguments.
OCAML\_FLEXLINK (environment variable)
Alternative executable to use on native Windows for flexlink instead of the configured value. Primarily used for bootstrapping.
[](#s:modules-file-system)13.3 Modules and the file system
------------------------------------------------------------
This short section is intended to clarify the relationship between the names of the modules corresponding to compilation units and the names of the files that contain their compiled interface and compiled implementation.
The compiler always derives the module name by taking the capitalized base name of the source file (.ml or .mli file). That is, it strips the leading directory name, if any, as well as the .ml or .mli suffix; then, it set the first letter to uppercase, in order to comply with the requirement that module names must be capitalized. For instance, compiling the file mylib/misc.ml provides an implementation for the module named Misc. Other compilation units may refer to components defined in mylib/misc.ml under the names Misc.name; they can also do open Misc, then use unqualified names name.
The .cmi and .cmo files produced by the compiler have the same base name as the source file. Hence, the compiled files always have their base name equal (modulo capitalization of the first letter) to the name of the module they describe (for .cmi files) or implement (for .cmo files).
When the compiler encounters a reference to a free module identifier Mod, it looks in the search path for a file named Mod.cmi or mod.cmi and loads the compiled interface contained in that file. As a consequence, renaming .cmi files is not advised: the name of a .cmi file must always correspond to the name of the compilation unit it implements. It is admissible to move them to another directory, if their base name is preserved, and the correct -I options are given to the compiler. The compiler will flag an error if it loads a .cmi file that has been renamed.
Compiled bytecode files (.cmo files), on the other hand, can be freely renamed once created. That’s because the linker never attempts to find by itself the .cmo file that implements a module with a given name: it relies instead on the user providing the list of .cmo files by hand.
[](#s:comp-errors)13.4 Common errors
--------------------------------------
This section describes and explains the most frequently encountered error messages.
Cannot find file filename
The named file could not be found in the current directory, nor in the directories of the search path. The filename is either a compiled interface file (.cmi file), or a compiled bytecode file (.cmo file). If filename has the format mod.cmi, this means you are trying to compile a file that references identifiers from module mod, but you have not yet compiled an interface for module mod. Fix: compile mod.mli or mod.ml first, to create the compiled interface mod.cmi.If filename has the format mod.cmo, this means you are trying to link a bytecode object file that does not exist yet. Fix: compile mod.ml first.
If your program spans several directories, this error can also appear because you haven’t specified the directories to look into. Fix: add the correct -I options to the command line.
Corrupted compiled interface filename
The compiler produces this error when it tries to read a compiled interface file (.cmi file) that has the wrong structure. This means something went wrong when this .cmi file was written: the disk was full, the compiler was interrupted in the middle of the file creation, and so on. This error can also appear if a .cmi file is modified after its creation by the compiler. Fix: remove the corrupted .cmi file, and rebuild it.
This expression has type t1, but is used with type t2
This is by far the most common type error in programs. Type t1 is the type inferred for the expression (the part of the program that is displayed in the error message), by looking at the expression itself. Type t2 is the type expected by the context of the expression; it is deduced by looking at how the value of this expression is used in the rest of the program. If the two types t1 and t2 are not compatible, then the error above is produced.In some cases, it is hard to understand why the two types t1 and t2 are incompatible. For instance, the compiler can report that “expression of type foo cannot be used with type foo”, and it really seems that the two types foo are compatible. This is not always true. Two type constructors can have the same name, but actually represent different types. This can happen if a type constructor is redefined. Example:
```
type foo = A | B
let f = function A -> 0 | B -> 1
type foo = C | D
f C
```
This result in the error message “expression C of type foo cannot be used with type foo”.
The type of this expression, t, contains type variables that cannot be generalized
Type variables ('a, 'b, …) in a type t can be in either of two states: generalized (which means that the type t is valid for all possible instantiations of the variables) and not generalized (which means that the type t is valid only for one instantiation of the variables). In a let binding let name = expr, the type-checker normally generalizes as many type variables as possible in the type of expr. However, this leads to unsoundness (a well-typed program can crash) in conjunction with polymorphic mutable data structures. To avoid this, generalization is performed at let bindings only if the bound expression expr belongs to the class of “syntactic values”, which includes constants, identifiers, functions, tuples of syntactic values, etc. In all other cases (for instance, expr is a function application), a polymorphic mutable could have been created and generalization is therefore turned off for all variables occurring in contravariant or non-variant branches of the type. For instance, if the type of a non-value is 'a list the variable is generalizable (list is a covariant type constructor), but not in 'a list -> 'a list (the left branch of -> is contravariant) or 'a ref (ref is non-variant).Non-generalized type variables in a type cause no difficulties inside a given structure or compilation unit (the contents of a .ml file, or an interactive session), but they cannot be allowed inside signatures nor in compiled interfaces (.cmi file), because they could be used inconsistently later. Therefore, the compiler flags an error when a structure or compilation unit defines a value name whose type contains non-generalized type variables. There are two ways to fix this error:
* Add a type constraint or a .mli file to give a monomorphic type (without type variables) to name. For instance, instead of writing
```
let sort_int_list = List.sort Stdlib.compare
(* inferred type 'a list -> 'a list, with 'a not generalized *)
```
write
```
let sort_int_list = (List.sort Stdlib.compare : int list -> int list);;
```
* If you really need name to have a polymorphic type, turn its defining expression into a function by adding an extra parameter. For instance, instead of writing
```
let map_length = List.map Array.length
(* inferred type 'a array list -> int list, with 'a not generalized *)
```
write
```
let map_length lv = List.map Array.length lv
```
Reference to undefined global mod
This error appears when trying to link an incomplete or incorrectly ordered set of files. Either you have forgotten to provide an implementation for the compilation unit named mod on the command line (typically, the file named mod.cmo, or a library containing that file). Fix: add the missing .ml or .cmo file to the command line. Or, you have provided an implementation for the module named mod, but it comes too late on the command line: the implementation of mod must come before all bytecode object files that reference mod. Fix: change the order of .ml and .cmo files on the command line.Of course, you will always encounter this error if you have mutually recursive functions across modules. That is, function Mod1.f calls function Mod2.g, and function Mod2.g calls function Mod1.f. In this case, no matter what permutations you perform on the command line, the program will be rejected at link-time. Fixes:
* Put f and g in the same module.
* Parameterize one function by the other. That is, instead of having
```
mod1.ml: let f x = ... Mod2.g ...
mod2.ml: let g y = ... Mod1.f ...
```
define
```
mod1.ml: let f g x = ... g ...
mod2.ml: let rec g y = ... Mod1.f g ...
```
and link mod1.cmo before mod2.cmo.
* Use a reference to hold one of the two functions, as in :
```
mod1.ml: let forward_g =
ref((fun x -> failwith "forward_g") : <type>)
let f x = ... !forward_g ...
mod2.ml: let g y = ... Mod1.f ...
let _ = Mod1.forward_g := g
```
The external function f is not available
This error appears when trying to link code that calls external functions written in C. As explained in chapter [22](intfc#c%3Aintf-c), such code must be linked with C libraries that implement the required f C function. If the C libraries in question are not shared libraries (DLLs), the code must be linked in “custom runtime” mode. Fix: add the required C libraries to the command line, and possibly the -custom option.
[](#s:comp-warnings)13.5 Warning reference
--------------------------------------------
This section describes and explains in detail some warnings:
###
[](#ss:warn6)13.5.1 Warning 6: Label omitted in function application
OCaml supports labels-omitted full applications: if the function has a known arity, all the arguments are unlabeled, and their number matches the number of non-optional parameters, then labels are ignored and non-optional parameters are matched in their definition order. Optional arguments are defaulted.
```
let f ~x ~y = x + y
let test = f 2 3
> let test = f 2 3
> ^
> Warning 6 [labels-omitted]: labels x, y were omitted in the application of this function.
```
This support for labels-omitted application was introduced when labels were added to OCaml, to ease the progressive introduction of labels in a codebase. However, it has the downside of weakening the labeling discipline: if you use labels to prevent callers from mistakenly reordering two parameters of the same type, labels-omitted make this mistake possible again.
Warning 6 warns when labels-omitted applications are used, to discourage their use. When labels were introduced, this warning was not enabled by default, so users would use labels-omitted applications, often without noticing.
Over time, it has become idiomatic to enable this warning to avoid argument-order mistakes. The warning is now on by default, since OCaml 4.13. Labels-omitted applications are not recommended anymore, but users wishing to preserve this transitory style can disable the warning explicitly.
###
[](#ss:warn9)13.5.2 Warning 9: missing fields in a record pattern
When pattern matching on records, it can be useful to match only few fields of a record. Eliding fields can be done either implicitly or explicitly by ending the record pattern with ; \_. However, implicit field elision is at odd with pattern matching exhaustiveness checks. Enabling warning 9 prioritizes exhaustiveness checks over the convenience of implicit field elision and will warn on implicit field elision in record patterns. In particular, this warning can help to spot exhaustive record pattern that may need to be updated after the addition of new fields to a record type.
```
type 'a point = {x : 'a; y : 'a}
let dx { x } = x (* implicit field elision: trigger warning 9 *)
let dy { y; _ } = y (* explicit field elision: do not trigger warning 9 *)
```
###
[](#ss:warn52)13.5.3 Warning 52: fragile constant pattern
Some constructors, such as the exception constructors Failure and Invalid\_argument, take as parameter a string value holding a text message intended for the user.
These text messages are usually not stable over time: call sites building these constructors may refine the message in a future version to make it more explicit, etc. Therefore, it is dangerous to match over the precise value of the message. For example, until OCaml 4.02, Array.iter2 would raise the exception
```
Invalid_argument "arrays must have the same length"
```
Since 4.03 it raises the more helpful message
```
Invalid_argument "Array.iter2: arrays must have the same length"
```
but this means that any code of the form
```
try ...
with Invalid_argument "arrays must have the same length" -> ...
```
is now broken and may suffer from uncaught exceptions.
Warning 52 is there to prevent users from writing such fragile code in the first place. It does not occur on every matching on a literal string, but only in the case in which library authors expressed their intent to possibly change the constructor parameter value in the future, by using the attribute ocaml.warn\_on\_literal\_pattern (see the manual section on builtin attributes in [12.12.1](attributes#ss%3Abuiltin-attributes)):
```
type t =
| Foo of string [@ocaml.warn_on_literal_pattern]
| Bar of string
let no_warning = function
| Bar "specific value" -> 0
| _ -> 1
let warning = function
| Foo "specific value" -> 0
| _ -> 1
Warning 52 [fragile-literal-pattern]: Code should not depend on the actual values of
this constructor's arguments. They are only for information
and may change in future versions. (See manual section 13.5)
```
In particular, all built-in exceptions with a string argument have this attribute set: Invalid\_argument, Failure, Sys\_error will all raise this warning if you match for a specific string argument.
Additionally, built-in exceptions with a structured argument that includes a string also have the attribute set: Assert\_failure and Match\_failure will raise the warning for a pattern that uses a literal string to match the first element of their tuple argument.
If your code raises this warning, you should *not* change the way you test for the specific string to avoid the warning (for example using a string equality inside the right-hand-side instead of a literal pattern), as your code would remain fragile. You should instead enlarge the scope of the pattern by matching on all possible values.
```
let warning = function
| Foo _ -> 0
| _ -> 1
```
This may require some care: if the scrutinee may return several different cases of the same pattern, or raise distinct instances of the same exception, you may need to modify your code to separate those several cases.
For example,
```
try (int_of_string count_str, bool_of_string choice_str) with
| Failure "int_of_string" -> (0, true)
| Failure "bool_of_string" -> (-1, false)
```
should be rewritten into more atomic tests. For example, using the exception patterns documented in Section [11.6](patterns#sss%3Aexception-match), one can write:
```
match int_of_string count_str with
| exception (Failure _) -> (0, true)
| count ->
begin match bool_of_string choice_str with
| exception (Failure _) -> (-1, false)
| choice -> (count, choice)
end
```
The only case where that transformation is not possible is if a given function call may raise distinct exceptions with the same constructor but different string values. In this case, you will have to check for specific string values. This is dangerous API design and it should be discouraged: it’s better to define more precise exception constructors than store useful information in strings.
###
[](#ss:warn57)13.5.4 Warning 57: Ambiguous or-pattern variables under guard
The semantics of or-patterns in OCaml is specified with a left-to-right bias: a value v matches the pattern p | q if it matches p or q, but if it matches both, the environment captured by the match is the environment captured by p, never the one captured by q.
While this property is generally intuitive, there is at least one specific case where a different semantics might be expected. Consider a pattern followed by a when-guard: | p when g -> e, for example:
```
| ((Const x, _) | (_, Const x)) when is_neutral x -> branch
```
The semantics is clear: match the scrutinee against the pattern, if it matches, test the guard, and if the guard passes, take the branch. In particular, consider the input (Const a, Const b), where a fails the test is\_neutral a, while b passes the test is\_neutral b. With the left-to-right semantics, the clause above is *not* taken by its input: matching (Const a, Const b) against the or-pattern succeeds in the left branch, it returns the environment x -> a, and then the guard is\_neutral a is tested and fails, the branch is not taken.
However, another semantics may be considered more natural here: any pair that has one side passing the test will take the branch. With this semantics the previous code fragment would be equivalent to
```
| (Const x, _) when is_neutral x -> branch
| (_, Const x) when is_neutral x -> branch
```
This is *not* the semantics adopted by OCaml.
Warning 57 is dedicated to these confusing cases where the specified left-to-right semantics is not equivalent to a non-deterministic semantics (any branch can be taken) relatively to a specific guard. More precisely, it warns when guard uses “ambiguous” variables, that are bound to different parts of the scrutinees by different sides of a or-pattern.
| programming_docs |
ocaml Chapter 32 The runtime_events library Chapter 32 The runtime\_events library
======================================
The runtime\_events library provides an API for consuming runtime tracing and metrics information from the runtime. See chapter [25](runtime-tracing#c%3Aruntime-tracing) for more information.
Programs that use runtime\_events must be linked as follows:
```
ocamlc -I +runtime_events other options unix.cma runtime_events.cma other files
ocamlopt -I +runtime_events other options unix.cmxa runtime_events.cmxa other files
```
Compilation units that use the runtime\_events library must also be compiled with the -I +runtime\_events option (see chapter [13](comp#c%3Acamlc)).
* [Module Runtime\_events](libref/runtime_events): tracing system
ocaml Chapter 7 Generalized algebraic datatypes Chapter 7 Generalized algebraic datatypes
=========================================
* [7.1 Recursive functions](gadts-tutorial#s%3Agadts-recfun)
* [7.2 Type inference](gadts-tutorial#s%3Agadts-type-inference)
* [7.3 Refutation cases](gadts-tutorial#s%3Agadt-refutation-cases)
* [7.4 Advanced examples](gadts-tutorial#s%3Agadts-advexamples)
* [7.5 Existential type names in error messages](gadts-tutorial#s%3Aexistential-names)
* [7.6 Explicit naming of existentials](gadts-tutorial#s%3Aexplicit-existential-name)
* [7.7 Equations on non-local abstract types](gadts-tutorial#s%3Agadt-equation-nonlocal-abstract)
Generalized algebraic datatypes, or GADTs, extend usual sum types in two ways: constraints on type parameters may change depending on the value constructor, and some type variables may be existentially quantified. Adding constraints is done by giving an explicit return type, where type parameters are instantiated:
```
type _ term =
| Int : int -> int term
| Add : (int -> int -> int) term
| App : ('b -> 'a) term * 'b term -> 'a term
```
This return type must use the same type constructor as the type being defined, and have the same number of parameters. Variables are made existential when they appear inside a constructor’s argument, but not in its return type. Since the use of a return type often eliminates the need to name type parameters in the left-hand side of a type definition, one can replace them with anonymous types \_ in that case.
The constraints associated to each constructor can be recovered through pattern-matching. Namely, if the type of the scrutinee of a pattern-matching contains a locally abstract type, this type can be refined according to the constructor used. These extra constraints are only valid inside the corresponding branch of the pattern-matching. If a constructor has some existential variables, fresh locally abstract types are generated, and they must not escape the scope of this branch.
[](#s:gadts-recfun)7.1 Recursive functions
--------------------------------------------
We write an eval function:
```
let rec eval : type a. a term -> a = function
| Int n -> n (* a = int *)
| Add -> (fun x y -> x+y) (* a = int -> int -> int *)
| App(f,x) -> (eval f) (eval x)
(* eval called at types (b->a) and b for fresh b *)
```
And use it:
```
let two = eval (App (App (Add, Int 1), Int 1))
val two : int = 2
```
It is important to remark that the function eval is using the polymorphic syntax for locally abstract types. When defining a recursive function that manipulates a GADT, explicit polymorphic recursion should generally be used. For instance, the following definition fails with a type error:
```
let rec eval (type a) : a term -> a = function
| Int n -> n
| Add -> (fun x y -> x+y)
| App(f,x) -> (eval f) (eval x)
Error: This expression has type ($App_'b -> a) term
but an expression was expected of type 'a
The type constructor $App_'b would escape its scope
```
In absence of an explicit polymorphic annotation, a monomorphic type is inferred for the recursive function. If a recursive call occurs inside the function definition at a type that involves an existential GADT type variable, this variable flows to the type of the recursive function, and thus escapes its scope. In the above example, this happens in the branch App(f,x) when eval is called with f as an argument. In this branch, the type of f is ($App\_'b -> a) term. The prefix $ in $App\_'b denotes an existential type named by the compiler (see [7.5](#s%3Aexistential-names)). Since the type of eval is 'a term -> 'a, the call eval f makes the existential type $App\_'b flow to the type variable 'a and escape its scope. This triggers the above error.
[](#s:gadts-type-inference)7.2 Type inference
-----------------------------------------------
Type inference for GADTs is notoriously hard. This is due to the fact some types may become ambiguous when escaping from a branch. For instance, in the Int case above, n could have either type int or a, and they are not equivalent outside of that branch. As a first approximation, type inference will always work if a pattern-matching is annotated with types containing no free type variables (both on the scrutinee and the return type). This is the case in the above example, thanks to the type annotation containing only locally abstract types.
In practice, type inference is a bit more clever than that: type annotations do not need to be immediately on the pattern-matching, and the types do not have to be always closed. As a result, it is usually enough to only annotate functions, as in the example above. Type annotations are propagated in two ways: for the scrutinee, they follow the flow of type inference, in a way similar to polymorphic methods; for the return type, they follow the structure of the program, they are split on functions, propagated to all branches of a pattern matching, and go through tuples, records, and sum types. Moreover, the notion of ambiguity used is stronger: a type is only seen as ambiguous if it was mixed with incompatible types (equated by constraints), without type annotations between them. For instance, the following program types correctly.
```
let rec sum : type a. a term -> _ = fun x ->
let y =
match x with
| Int n -> n
| Add -> 0
| App(f,x) -> sum f + sum x
in y + 1
val sum : 'a term -> int =
```
Here the return type int is never mixed with a, so it is seen as non-ambiguous, and can be inferred. When using such partial type annotations we strongly suggest specifying the -principal mode, to check that inference is principal.
The exhaustiveness check is aware of GADT constraints, and can automatically infer that some cases cannot happen. For instance, the following pattern matching is correctly seen as exhaustive (the Add case cannot happen).
```
let get_int : int term -> int = function
| Int n -> n
| App(_,_) -> 0
```
[](#s:gadt-refutation-cases)7.3 Refutation cases
--------------------------------------------------
Usually, the exhaustiveness check only tries to check whether the cases omitted from the pattern matching are typable or not. However, you can force it to try harder by adding *refutation cases*, written as a full stop. In the presence of a refutation case, the exhaustiveness check will first compute the intersection of the pattern with the complement of the cases preceding it. It then checks whether the resulting patterns can really match any concrete values by trying to type-check them. Wild cards in the generated patterns are handled in a special way: if their type is a variant type with only GADT constructors, then the pattern is split into the different constructors, in order to check whether any of them is possible (this splitting is not done for arguments of these constructors, to avoid non-termination). We also split tuples and variant types with only one case, since they may contain GADTs inside. For instance, the following code is deemed exhaustive:
```
type _ t =
| Int : int t
| Bool : bool t
let deep : (char t * int) option -> char = function
| None -> 'c'
| _ -> .
```
Namely, the inferred remaining case is Some \_, which is split into Some (Int, \_) and Some (Bool, \_), which are both untypable because deep expects a non-existing char t as the first element of the tuple. Note that the refutation case could be omitted here, because it is automatically added when there is only one case in the pattern matching.
Another addition is that the redundancy check is now aware of GADTs: a case will be detected as redundant if it could be replaced by a refutation case using the same pattern.
[](#s:gadts-advexamples)7.4 Advanced examples
-----------------------------------------------
The term type we have defined above is an *indexed* type, where a type parameter reflects a property of the value contents. Another use of GADTs is *singleton* types, where a GADT value represents exactly one type. This value can be used as runtime representation for this type, and a function receiving it can have a polytypic behavior.
Here is an example of a polymorphic function that takes the runtime representation of some type t and a value of the same type, then pretty-prints the value as a string:
```
type _ typ =
| Int : int typ
| String : string typ
| Pair : 'a typ * 'b typ -> ('a * 'b) typ
let rec to_string: type t. t typ -> t -> string =
fun t x ->
match t with
| Int -> Int.to_string x
| String -> Printf.sprintf "%S" x
| Pair(t1,t2) ->
let (x1, x2) = x in
Printf.sprintf "(%s,%s)" (to_string t1 x1) (to_string t2 x2)
```
Another frequent application of GADTs is equality witnesses.
```
type (_,_) eq = Eq : ('a,'a) eq
let cast : type a b. (a,b) eq -> a -> b = fun Eq x -> x
```
Here type eq has only one constructor, and by matching on it one adds a local constraint allowing the conversion between a and b. By building such equality witnesses, one can make equal types which are syntactically different.
Here is an example using both singleton types and equality witnesses to implement dynamic types.
```
let rec eq_type : type a b. a typ -> b typ -> (a,b) eq option =
fun a b ->
match a, b with
| Int, Int -> Some Eq
| String, String -> Some Eq
| Pair(a1,a2), Pair(b1,b2) ->
begin match eq_type a1 b1, eq_type a2 b2 with
| Some Eq, Some Eq -> Some Eq
| _ -> None
end
| _ -> None
type dyn = Dyn : 'a typ * 'a -> dyn
let get_dyn : type a. a typ -> dyn -> a option =
fun a (Dyn(b,x)) ->
match eq_type a b with
| None -> None
| Some Eq -> Some x
```
[](#s:existential-names)7.5 Existential type names in error messages
----------------------------------------------------------------------
The typing of pattern matching in the presence of GADTs can generate many existential types. When necessary, error messages refer to these existential types using compiler-generated names. Currently, the compiler generates these names according to the following nomenclature:
* First, types whose name starts with a $ are existentials.
* $Constr\_'a denotes an existential type introduced for the type variable 'a of the GADT constructor Constr:
```
type any = Any : 'name -> any
let escape (Any x) = x
Error: This expression has type $Any_'name
but an expression was expected of type 'a
The type constructor $Any_'name would escape its scope
```
* $Constr denotes an existential type introduced for an anonymous type variable in the GADT constructor Constr:
```
type any = Any : _ -> any
let escape (Any x) = x
Error: This expression has type $Any but an expression was expected of type
'a
The type constructor $Any would escape its scope
```
* $'a if the existential variable was unified with the type variable 'a during typing:
```
type ('arg,'result,'aux) fn =
| Fun: ('a ->'b) -> ('a,'b,unit) fn
| Mem1: ('a ->'b) * 'a * 'b -> ('a, 'b, 'a * 'b) fn
let apply: ('arg,'result, _ ) fn -> 'arg -> 'result = fun f x ->
match f with
| Fun f -> f x
| Mem1 (f,y,fy) -> if x = y then fy else f x
Error: This pattern matches values of type
($'arg, 'result, $'arg * 'result) fn
but a pattern was expected which matches values of type
($'arg, 'result, unit) fn
The type constructor $'arg would escape its scope
```
* $n (n a number) is an internally generated existential which could not be named using one of the previous schemes.
As shown by the last item, the current behavior is imperfect and may be improved in future versions.
[](#s:explicit-existential-name)7.6 Explicit naming of existentials
---------------------------------------------------------------------
As explained above, pattern-matching on a GADT constructor may introduce existential types. Syntax has been introduced which allows them to be named explicitly. For instance, the following code names the type of the argument of f and uses this name.
```
type _ closure = Closure : ('a -> 'b) * 'a -> 'b closure
let eval = fun (Closure (type a) (f, x : (a -> _) * _)) -> f (x : a)
```
All existential type variables of the constructor must by introduced by the (type ...) construct and bound by a type annotation on the outside of the constructor argument.
[](#s:gadt-equation-nonlocal-abstract)7.7 Equations on non-local abstract types
---------------------------------------------------------------------------------
GADT pattern-matching may also add type equations to non-local abstract types. The behaviour is the same as with local abstract types. Reusing the above eq type, one can write:
```
module M : sig type t val x : t val e : (t,int) eq end = struct
type t = int
let x = 33
let e = Eq
end
let x : int = let Eq = M.e in M.x
```
Of course, not all abstract types can be refined, as this would contradict the exhaustiveness check. Namely, builtin types (those defined by the compiler itself, such as int or array), and abstract types defined by the local module, are non-instantiable, and as such cause a type error rather than introduce an equation.
ocaml Chapter 30 The unix library: Unix system calls Chapter 30 The unix library: Unix system calls
==============================================
The unix library makes many Unix system calls and system-related library functions available to OCaml programs. This chapter describes briefly the functions provided. Refer to sections 2 and 3 of the Unix manual for more details on the behavior of these functions.
* [Module Unix](libref/unix): Unix system calls
* [Module UnixLabels](libref/unixlabels): Labeled Unix system calls
Not all functions are provided by all Unix variants. If some functions are not available, they will raise Invalid\_arg when called.
Programs that use the unix library must be linked as follows:
```
ocamlc other options -I +unix unix.cma other files
ocamlopt other options -I +unix unix.cmxa other files
```
For interactive use of the unix library, do:
```
ocamlmktop -o mytop -I +unix unix.cma
./mytop
```
or (if dynamic linking of C libraries is supported on your platform), start ocaml and type
```
# #directory "+unix";;
```
```
# #load "unix.cma";;
```
>
> Windows: The Cygwin port of OCaml fully implements all functions from the Unix module. The native Win32 ports implement a subset of them. Below is a list of the functions that are not implemented, or only partially implemented, by the Win32 ports. Functions not mentioned are fully implemented and behave as described previously in this chapter.
| | |
| --- | --- |
| Functions | Comment |
| fork | not implemented, use create\_process or threads |
| wait | not implemented, use waitpid |
| waitpid | can only wait for a given PID, not any child process |
| getppid | not implemented (meaningless under Windows) |
| nice | not implemented |
| truncate, ftruncate | implemented (since 4.10.0) |
| link | implemented (since 3.02) |
| fchmod | not implemented |
| chown, fchown | not implemented (make no sense on a DOS file system) |
| umask | not implemented |
| access | execute permission X\_OK cannot be tested, it just tests for read permission instead |
| chroot | not implemented |
| mkfifo | not implemented |
| symlink, readlink | implemented (since 4.03.0) |
| kill | partially implemented (since 4.00.0): only the sigkill signal is implemented |
| sigprocmask, sigpending, sigsuspend | not implemented (no inter-process signals on Windows |
| pause | not implemented (no inter-process signals in Windows) |
| alarm | not implemented |
| times | partially implemented, will not report timings for child processes |
| getitimer, setitimer | not implemented |
| getuid, geteuid, getgid, getegid | always return 1 |
| setuid, setgid, setgroups, initgroups | not implemented |
| getgroups | always returns [|1|] (since 2.00) |
| getpwnam, getpwuid | always raise Not\_found |
| getgrnam, getgrgid | always raise Not\_found |
| type socket\_domain | PF\_INET is fully supported; PF\_INET6 is fully supported (since 4.01.0); PF\_UNIX is supported since 4.14.0, but only works on Windows 10 1803 and later. |
| establish\_server | not implemented; use threads |
| terminal functions (tc\*) | not implemented |
| setsid | not implemented |
ocaml None
[](#s:extensible-variants)12.14 Extensible variant types
----------------------------------------------------------
* [12.14.1 Private extensible variant types](extensiblevariants#ss%3Aprivate-extensible)
(Introduced in OCaml 4.02)
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [type-representation](typedecl#type-representation) | ::= | ... |
| | ∣ | = .. |
| |
| [specification](modtypes#specification) | ::= | ... |
| | ∣ | type [[type-params](typedecl#type-params)] [typeconstr](names#typeconstr) [type-extension-spec](#type-extension-spec) |
| |
| [definition](modules#definition) | ::= | ... |
| | ∣ | type [[type-params](typedecl#type-params)] [typeconstr](names#typeconstr) [type-extension-def](#type-extension-def) |
| |
| type-extension-spec | ::= | += [private] [|] [constr-decl](typedecl#constr-decl) { | [constr-decl](typedecl#constr-decl) } |
| |
| type-extension-def | ::= | += [private] [|] [constr-def](#constr-def) { | [constr-def](#constr-def) } |
| |
| constr-def | ::= | [constr-decl](typedecl#constr-decl) |
| | ∣ | [constr-name](names#constr-name) = [constr](names#constr) |
| |
|
Extensible variant types are variant types which can be extended with new variant constructors. Extensible variant types are defined using ... New variant constructors are added using +=.
```
module Expr = struct
type attr = ..
type attr += Str of string
type attr +=
| Int of int
| Float of float
end
```
Pattern matching on an extensible variant type requires a default case to handle unknown variant constructors:
```
let to_string = function
| Expr.Str s -> s
| Expr.Int i -> Int.to_string i
| Expr.Float f -> string_of_float f
| _ -> "?"
```
A preexisting example of an extensible variant type is the built-in exn type used for exceptions. Indeed, exception constructors can be declared using the type extension syntax:
```
type exn += Exc of int
```
Extensible variant constructors can be rebound to a different name. This allows exporting variants from another module.
```
# let not_in_scope = Str "Foo";;
Error: Unbound constructor Str
```
```
type Expr.attr += Str = Expr.Str
```
```
# let now_works = Str "foo";;
val now_works : Expr.attr = Expr.Str "foo"
```
Extensible variant constructors can be declared private. As with regular variants, this prevents them from being constructed directly by constructor application while still allowing them to be de-structured in pattern-matching.
```
module B : sig
type Expr.attr += private Bool of int
val bool : bool -> Expr.attr
end = struct
type Expr.attr += Bool of int
let bool p = if p then Bool 1 else Bool 0
end
```
```
# let inspection_works = function
| B.Bool p -> (p = 1)
| _ -> true;;
val inspection_works : Expr.attr -> bool =
```
```
# let construction_is_forbidden = B.Bool 1;;
Error: Cannot use private constructor Bool to create values of type Expr.attr
```
###
[](#ss:private-extensible)12.14.1 Private extensible variant types
(Introduced in OCaml 4.06)
| | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [type-representation](typedecl#type-representation) | ::= | ... |
| | ∣ | = private .. |
| |
|
Extensible variant types can be declared private. This prevents new constructors from being declared directly, but allows extension constructors to be referred to in interfaces.
```
module Msg : sig
type t = private ..
module MkConstr (X : sig type t end) : sig
type t += C of X.t
end
end = struct
type t = ..
module MkConstr (X : sig type t end) = struct
type t += C of X.t
end
end
```
| programming_docs |
ocaml Chapter 27 The core library Chapter 27 The core library
===========================
* [27.1 Built-in types and predefined exceptions](core#s%3Acore-builtins)
* [27.2 Module Stdlib: the initially opened module](core#s%3Astdlib-module)
This chapter describes the OCaml core library, which is composed of declarations for built-in types and exceptions, plus the module Stdlib that provides basic operations on these built-in types. The Stdlib module is special in two ways:
* It is automatically linked with the user’s object code files by the ocamlc command (chapter [13](comp#c%3Acamlc)).
* It is automatically “opened” when a compilation starts, or when the toplevel system is launched. Hence, it is possible to use unqualified identifiers to refer to the functions provided by the Stdlib module, without adding a open Stdlib directive.
[](#s:core-builtins)27.1 Built-in types and predefined exceptions
-------------------------------------------------------------------
The following built-in types and predefined exceptions are always defined in the compilation environment, but are not part of any module. As a consequence, they can only be referred by their short names.
###
[](#ss:builtin-types)Built-in types
```
type int
```
> The type of integer numbers.
```
type char
```
> The type of characters.
```
type bytes
```
> The type of (writable) byte sequences.
```
type string
```
> The type of (read-only) character strings.
```
type float
```
> The type of floating-point numbers.
```
type bool = false | true
```
> The type of booleans (truth values).
```
type unit = ()
```
> The type of the unit value.
```
type exn
```
> The type of exception values.
```
type 'a array
```
> The type of arrays whose elements have type 'a.
```
type 'a list = [] | :: of 'a * 'a list
```
> The type of lists whose elements have type 'a.
```
type 'a option = None | Some of 'a
```
> The type of optional values of type 'a.
```
type int32
```
> The type of signed 32-bit integers. Literals for 32-bit integers are suffixed by l. See the [Int32](libref/int32) module.
```
type int64
```
> The type of signed 64-bit integers. Literals for 64-bit integers are suffixed by L. See the [Int64](libref/int64) module.
```
type nativeint
```
> The type of signed, platform-native integers (32 bits on 32-bit processors, 64 bits on 64-bit processors). Literals for native integers are suffixed by n. See the [Nativeint](libref/nativeint) module.
```
type ('a, 'b, 'c, 'd, 'e, 'f) format6
```
> The type of format strings. 'a is the type of the parameters of the format, 'f is the result type for the printf-style functions, 'b is the type of the first argument given to %a and %t printing functions (see module [Printf](libref/printf)), 'c is the result type of these functions, and also the type of the argument transmitted to the first argument of kprintf-style functions, 'd is the result type for the scanf-style functions (see module [Scanf](libref/scanf)), and 'e is the type of the receiver function for the scanf-style functions.
```
type 'a lazy_t
```
> This type is used to implement the [Lazy](libref/lazy) module. It should not be used directly.
###
[](#ss:predef-exn)Predefined exceptions
```
exception Match_failure of (string * int * int)
```
> Exception raised when none of the cases of a pattern-matching apply. The arguments are the location of the match keyword in the source code (file name, line number, column number).
```
exception Assert_failure of (string * int * int)
```
> Exception raised when an assertion fails. The arguments are the location of the assert keyword in the source code (file name, line number, column number).
```
exception Invalid_argument of string
```
> Exception raised by library functions to signal that the given arguments do not make sense. The string gives some information to the programmer. As a general rule, this exception should not be caught, it denotes a programming error and the code should be modified not to trigger it.
```
exception Failure of string
```
> Exception raised by library functions to signal that they are undefined on the given arguments. The string is meant to give some information to the programmer; you must *not* pattern match on the string literal because it may change in future versions (use `Failure _` instead).
```
exception Not_found
```
> Exception raised by search functions when the desired object could not be found.
```
exception Out_of_memory
```
> Exception raised by the garbage collector when there is insufficient memory to complete the computation. (Not reliable for allocations on the minor heap.)
```
exception Stack_overflow
```
> Exception raised by the bytecode interpreter when the evaluation stack reaches its maximal size. This often indicates infinite or excessively deep recursion in the user’s program. Before 4.10, it was not fully implemented by the native-code compiler.
```
exception Sys_error of string
```
> Exception raised by the input/output functions to report an operating system error. The string is meant to give some information to the programmer; you must *not* pattern match on the string literal because it may change in future versions (use `Sys_error _` instead).
```
exception End_of_file
```
> Exception raised by input functions to signal that the end of file has been reached.
```
exception Division_by_zero
```
> Exception raised by integer division and remainder operations when their second argument is zero.
```
exception Sys_blocked_io
```
> A special case of Sys\_error raised when no I/O is possible on a non-blocking I/O channel.
```
exception Undefined_recursive_module of (string * int * int)
```
> Exception raised when an ill-founded recursive module definition is evaluated. (See section [12.2](recursivemodules#s%3Arecursive-modules).) The arguments are the location of the definition in the source code (file name, line number, column number).
[](#s:stdlib-module)27.2 Module Stdlib: the initially opened module
---------------------------------------------------------------------
* [Module Stdlib](libref/stdlib): the initially opened module
ocaml Contents Contents
========
* [Part I An introduction to OCaml](index#sec6)
+ [Chapter 1 The core language](coreexamples#sec7)
- [1.1 Basics](coreexamples#s%3Abasics)
- [1.2 Data types](coreexamples#s%3Adatatypes)
- [1.3 Functions as values](coreexamples#s%3Afunctions-as-values)
- [1.4 Records and variants](coreexamples#s%3Atut-recvariants)
* [1.4.1 Record and variant disambiguation](coreexamples#ss%3Arecord-and-variant-disambiguation)
- [1.5 Imperative features](coreexamples#s%3Aimperative-features)
- [1.6 Exceptions](coreexamples#s%3Aexceptions)
- [1.7 Lazy expressions](coreexamples#s%3Alazy-expr)
- [1.8 Symbolic processing of expressions](coreexamples#s%3Asymb-expr)
- [1.9 Pretty-printing](coreexamples#s%3Apretty-printing)
- [1.10 Printf formats](coreexamples#s%3Aprintf)
- [1.11 Standalone OCaml programs](coreexamples#s%3Astandalone-programs)
+ [Chapter 2 The module system](moduleexamples#sec20)
- [2.1 Structures](moduleexamples#s%3Amodule%3Astructures)
- [2.2 Signatures](moduleexamples#s%3Asignature)
- [2.3 Functors](moduleexamples#s%3Afunctors)
- [2.4 Functors and type abstraction](moduleexamples#s%3Afunctors-and-abstraction)
- [2.5 Modules and separate compilation](moduleexamples#s%3Aseparate-compilation)
+ [Chapter 3 Objects in OCaml](objectexamples#sec26)
- [3.1 Classes and objects](objectexamples#s%3Aclasses-and-objects)
- [3.2 Immediate objects](objectexamples#s%3Aimmediate-objects)
- [3.3 Reference to self](objectexamples#s%3Areference-to-self)
- [3.4 Initializers](objectexamples#s%3Ainitializers)
- [3.5 Virtual methods](objectexamples#s%3Avirtual-methods)
- [3.6 Private methods](objectexamples#s%3Aprivate-methods)
- [3.7 Class interfaces](objectexamples#s%3Aclass-interfaces)
- [3.8 Inheritance](objectexamples#s%3Ainheritance)
- [3.9 Multiple inheritance](objectexamples#s%3Amultiple-inheritance)
- [3.10 Parameterized classes](objectexamples#s%3Aparameterized-classes)
- [3.11 Polymorphic methods](objectexamples#s%3Apolymorphic-methods)
- [3.12 Using coercions](objectexamples#s%3Ausing-coercions)
- [3.13 Functional objects](objectexamples#s%3Afunctional-objects)
- [3.14 Cloning objects](objectexamples#s%3Acloning-objects)
- [3.15 Recursive classes](objectexamples#s%3Arecursive-classes)
- [3.16 Binary methods](objectexamples#s%3Abinary-methods)
- [3.17 Friends](objectexamples#s%3Afriends)
+ [Chapter 4 Labeled arguments](lablexamples#sec44)
- [4.1 Optional arguments](lablexamples#s%3Aoptional-arguments)
- [4.2 Labels and type inference](lablexamples#s%3Alabel-inference)
- [4.3 Suggestions for labeling](lablexamples#s%3Alabel-suggestions)
+ [Chapter 5 Polymorphic variants](polyvariant#sec48)
- [5.1 Basic use](polyvariant#s%3Apolyvariant%3Abasic-use)
- [5.2 Advanced use](polyvariant#s%3Apolyvariant-advanced)
- [5.3 Weaknesses of polymorphic variants](polyvariant#s%3Apolyvariant-weaknesses)
+ [Chapter 6 Polymorphism and its limitations](polymorphism#sec52)
- [6.1 Weak polymorphism and mutation](polymorphism#s%3Aweak-polymorphism)
* [6.1.1 Weakly polymorphic types](polymorphism#ss%3Aweak-types)
* [6.1.2 The value restriction](polymorphism#ss%3Avaluerestriction)
* [6.1.3 The relaxed value restriction](polymorphism#ss%3Arelaxed-value-restriction)
* [6.1.4 Variance and value restriction](polymorphism#ss%3Avariance-and-value-restriction)
* [6.1.5 Abstract data types](polymorphism#ss%3Avariance%3Aabstract-data-types)
- [6.2 Polymorphic recursion](polymorphism#s%3Apolymorphic-recursion)
* [6.2.1 Explicitly polymorphic annotations](polymorphism#ss%3Aexplicit-polymorphism)
* [6.2.2 More examples](polymorphism#ss%3Arecursive-poly-examples)
- [6.3 Higher-rank polymorphic functions](polymorphism#s%3Ahigher-rank-poly)
+ [Chapter 7 Generalized algebraic datatypes](gadts-tutorial#sec63)
- [7.1 Recursive functions](gadts-tutorial#s%3Agadts-recfun)
- [7.2 Type inference](gadts-tutorial#s%3Agadts-type-inference)
- [7.3 Refutation cases](gadts-tutorial#s%3Agadt-refutation-cases)
- [7.4 Advanced examples](gadts-tutorial#s%3Agadts-advexamples)
- [7.5 Existential type names in error messages](gadts-tutorial#s%3Aexistential-names)
- [7.6 Explicit naming of existentials](gadts-tutorial#s%3Aexplicit-existential-name)
- [7.7 Equations on non-local abstract types](gadts-tutorial#s%3Agadt-equation-nonlocal-abstract)
+ [Chapter 8 Advanced examples with classes and modules](advexamples#sec71)
- [8.1 Extended example: bank accounts](advexamples#s%3Aextended-bank-accounts)
- [8.2 Simple modules as classes](advexamples#s%3Amodules-as-classes)
* [8.2.1 Strings](advexamples#ss%3Astring-as-class)
* [8.2.2 Hashtbl](advexamples#ss%3Ahashtbl-as-class)
* [8.2.3 Sets](advexamples#ss%3Aset-as-class)
- [8.3 The subject/observer pattern](advexamples#s%3Asubject-observer)
+ [Chapter 9 Parallel programming](parallelism#sec79)
- [9.1 Domains](parallelism#s%3Apar_domains)
* [9.1.1 Joining domains](parallelism#s%3Apar_join)
- [9.2 Domainslib: A library for nested-parallel programming](parallelism#s%3Apar_parfib)
* [9.2.1 Parallelising Fibonacci using domainslib](parallelism#s%3Apar_parfib_domainslib)
* [9.2.2 Parallel iteration constructs](parallelism#s%3Apar_iterators)
- [9.3 Parallel garbage collection](parallelism#s%3Apar_gc)
- [9.4 Memory model: The easy bits](parallelism#s%3Apar_mm_easy)
- [9.5 Blocking synchronisation](parallelism#s%3Apar_sync)
* [9.5.1 Interaction with systhreads](parallelism#s%3Apar_systhread_interaction)
- [9.6 Interaction with C bindings](parallelism#s%3Apar_c_bindings)
- [9.7 Atomics](parallelism#s%3Apar_atomics)
* [9.7.1 Lock-free stack](parallelism#s%3Apar_lockfree_stack)
+ [Chapter 10 Memory model: The hard bits](memorymodel#sec92)
- [10.1 Why weakly consistent memory?](memorymodel#s%3Awhy_relaxed_memory)
* [10.1.1 Compiler optimisations](memorymodel#ss%3Amm_comp_opt)
* [10.1.2 Hardware optimisations](memorymodel#ss%3Amm_hw_opt)
- [10.2 Data race freedom implies sequential consistency](memorymodel#s%3Adrf_sc)
* [10.2.1 Memory locations](memorymodel#s%3Aatomics)
* [10.2.2 Happens-before relation](memorymodel#s%3Ahappens_before)
* [10.2.3 Data race](memorymodel#s%3Adatarace)
* [10.2.4 DRF-SC](memorymodel#ss%3Adrf_sc)
- [10.3 Reasoning with DRF-SC](memorymodel#s%3Adrf_reasoning)
- [10.4 Local data race freedom](memorymodel#s%3Alocal_drf)
- [10.5 An operational view of the memory model](memorymodel#s%3Amm_semantics)
* [10.5.1 Non-atomic locations](memorymodel#ss%3Amm_non_atomic)
* [10.5.2 Domains](memorymodel#ss%3Amm_domains)
* [10.5.3 Non-atomic accesses](memorymodel#ss%3Amm_na_access)
* [10.5.4 Atomic accesses](memorymodel#ss%3Amm_at_access)
* [10.5.5 Reasoning with the semantics](memorymodel#s%3Amm_semantics_reasoning)
- [10.6 Non-compliant operations](memorymodel#s%3Amm_tearing)
* [Part II The OCaml language](index#sec111)
+ [Chapter 11 The OCaml language](language#sec112)
- [11.1 Lexical conventions](lex#s%3Alexical-conventions)
- [11.2 Values](values#s%3Avalues)
* [11.2.1 Base values](values#ss%3Avalues%3Abase)
* [11.2.2 Tuples](values#ss%3Avalues%3Atuple)
* [11.2.3 Records](values#ss%3Avalues%3Arecords)
* [11.2.4 Arrays](values#ss%3Avalues%3Aarray)
* [11.2.5 Variant values](values#ss%3Avalues%3Avariant)
* [11.2.6 Polymorphic variants](values#ss%3Avalues%3Apolyvars)
* [11.2.7 Functions](values#ss%3Avalues%3Afun)
* [11.2.8 Objects](values#ss%3Avalues%3Aobj)
- [11.3 Names](names#s%3Anames)
- [11.4 Type expressions](types#s%3Atypexpr)
- [11.5 Constants](const#s%3Aconst)
- [11.6 Patterns](patterns#s%3Apatterns)
- [11.7 Expressions](expr#s%3Avalue-expr)
* [11.7.1 Precedence and associativity](expr#ss%3Aprecedence-and-associativity)
* [11.7.2 Basic expressions](expr#ss%3Aexpr-basic)
* [11.7.3 Control structures](expr#ss%3Aexpr-control)
* [11.7.4 Operations on data structures](expr#ss%3Aexpr-ops-on-data)
* [11.7.5 Operators](expr#ss%3Aexpr-operators)
* [11.7.6 Objects](expr#ss%3Aexpr-obj)
* [11.7.7 Coercions](expr#ss%3Aexpr-coercions)
* [11.7.8 Other](expr#ss%3Aexpr-other)
- [11.8 Type and exception definitions](typedecl#s%3Atydef)
* [11.8.1 Type definitions](typedecl#ss%3Atypedefs)
* [11.8.2 Exception definitions](typedecl#ss%3Aexndef)
- [11.9 Classes](classes#s%3Aclasses)
* [11.9.1 Class types](classes#ss%3Aclasses%3Aclass-types)
* [11.9.2 Class expressions](classes#ss%3Aclass-expr)
* [11.9.3 Class definitions](classes#ss%3Aclass-def)
* [11.9.4 Class specifications](classes#ss%3Aclass-spec)
* [11.9.5 Class type definitions](classes#ss%3Aclasstype)
- [11.10 Module types (module specifications)](modtypes#s%3Amodtypes)
* [11.10.1 Simple module types](modtypes#ss%3Amty-simple)
* [11.10.2 Signatures](modtypes#ss%3Amty-signatures)
* [11.10.3 Functor types](modtypes#ss%3Amty-functors)
* [11.10.4 The with operator](modtypes#ss%3Amty-with)
- [11.11 Module expressions (module implementations)](modules#s%3Amodule-expr)
* [11.11.1 Simple module expressions](modules#ss%3Amexpr-simple)
* [11.11.2 Structures](modules#ss%3Amexpr-structures)
* [11.11.3 Functors](modules#ss%3Amexpr-functors)
- [11.12 Compilation units](compunit#s%3Acompilation-units)
+ [Chapter 12 Language extensions](extn#sec278)
- [12.1 Recursive definitions of values](letrecvalues#s%3Aletrecvalues)
- [12.2 Recursive modules](recursivemodules#s%3Arecursive-modules)
- [12.3 Private types](privatetypes#s%3Aprivate-types)
* [12.3.1 Private variant and record types](privatetypes#ss%3Aprivate-types-variant)
* [12.3.2 Private type abbreviations](privatetypes#ss%3Aprivate-types-abbrev)
* [12.3.3 Private row types](privatetypes#ss%3Aprivate-rows)
- [12.4 Locally abstract types](locallyabstract#s%3Alocally-abstract)
- [12.5 First-class modules](firstclassmodules#s%3Afirst-class-modules)
- [12.6 Recovering the type of a module](moduletypeof#s%3Amodule-type-of)
- [12.7 Substituting inside a signature](signaturesubstitution#s%3Asignature-substitution)
* [12.7.1 Destructive substitutions](signaturesubstitution#ss%3Adestructive-substitution)
* [12.7.2 Local substitution declarations](signaturesubstitution#ss%3Alocal-substitution)
* [12.7.3 Module type substitutions](signaturesubstitution#ss%3Amodule-type-substitution)
- [12.8 Type-level module aliases](modulealias#s%3Amodule-alias)
- [12.9 Overriding in open statements](overridingopen#s%3Aexplicit-overriding-open)
- [12.10 Generalized algebraic datatypes](gadts#s%3Agadts)
- [12.11 Syntax for Bigarray access](bigarray#s%3Abigarray-access)
- [12.12 Attributes](attributes#s%3Aattributes)
* [12.12.1 Built-in attributes](attributes#ss%3Abuiltin-attributes)
- [12.13 Extension nodes](extensionnodes#s%3Aextension-nodes)
* [12.13.1 Built-in extension nodes](extensionnodes#ss%3Abuiltin-extension-nodes)
- [12.14 Extensible variant types](extensiblevariants#s%3Aextensible-variants)
* [12.14.1 Private extensible variant types](extensiblevariants#ss%3Aprivate-extensible)
- [12.15 Generative functors](generativefunctors#s%3Agenerative-functors)
- [12.16 Extension-only syntax](extensionsyntax#s%3Aextension-syntax)
* [12.16.1 Extension operators](extensionsyntax#ss%3Aextension-operators)
* [12.16.2 Extension literals](extensionsyntax#ss%3Aextension-literals)
- [12.17 Inline records](inlinerecords#s%3Ainline-records)
- [12.18 Documentation comments](doccomments#s%3Adoc-comments)
* [12.18.1 Floating comments](doccomments#ss%3Afloating-comments)
* [12.18.2 Item comments](doccomments#ss%3Aitem-comments)
* [12.18.3 Label comments](doccomments#ss%3Alabel-comments)
- [12.19 Extended indexing operators](indexops#s%3Aindex-operators)
* [12.19.1 Multi-index notation](indexops#ss%3Amultiindexing)
- [12.20 Empty variant types](emptyvariants#s%3Aempty-variants)
- [12.21 Alerts](alerts#s%3Aalerts)
- [12.22 Generalized open statements](generalizedopens#s%3Ageneralized-open)
- [12.23 Binding operators](bindingops#s%3Abinding-operators)
* [12.23.1 Short notation for variable bindings (let-punning)](bindingops#ss%3Aletops-punning)
* [12.23.2 Rationale](bindingops#ss%3Aletops-rationale)
- [12.24 Effect handlers](effects#s%3Aeffect-handlers)
* [12.24.1 Basics](effects#s%3Aeffects-basics)
* [12.24.2 Concurrency](effects#s%3Aeffects-concurrency)
* [12.24.3 User-level threads](effects#s%3Aeffects-user-threads)
* [12.24.4 Control inversion](effects#s%3Aeffects-sequence)
* [12.24.5 Semantics](effects#s%3Aeffects-semantics)
* [12.24.6 Shallow handlers](effects#s%3Aeffects-shallow)
* [Part III The OCaml tools](index#sec335)
+ [Chapter 13 Batch compilation (ocamlc)](comp#sec336)
- [13.1 Overview of the compiler](comp#s%3Acomp-overview)
- [13.2 Options](comp#s%3Acomp-options)
- [13.3 Modules and the file system](comp#s%3Amodules-file-system)
- [13.4 Common errors](comp#s%3Acomp-errors)
- [13.5 Warning reference](comp#s%3Acomp-warnings)
* [13.5.1 Warning 6: Label omitted in function application](comp#ss%3Awarn6)
* [13.5.2 Warning 9: missing fields in a record pattern](comp#ss%3Awarn9)
* [13.5.3 Warning 52: fragile constant pattern](comp#ss%3Awarn52)
* [13.5.4 Warning 57: Ambiguous or-pattern variables under guard](comp#ss%3Awarn57)
+ [Chapter 14 The toplevel system or REPL (ocaml)](toplevel#sec347)
- [14.1 Options](toplevel#s%3Atoplevel-options)
- [14.2 Toplevel directives](toplevel#s%3Atoplevel-directives)
- [14.3 The toplevel and the module system](toplevel#s%3Atoplevel-modules)
- [14.4 Common errors](toplevel#s%3Atoplevel-common-errors)
- [14.5 Building custom toplevel systems: ocamlmktop](toplevel#s%3Acustom-toplevel)
* [14.5.1 Options](toplevel#ss%3Aocamlmktop-options)
- [14.6 The native toplevel: ocamlnat (experimental)](toplevel#s%3Aocamlnat)
+ [Chapter 15 The runtime system (ocamlrun)](runtime#sec355)
- [15.1 Overview](runtime#s%3Aocamlrun-overview)
- [15.2 Options](runtime#s%3Aocamlrun-options)
- [15.3 Dynamic loading of shared libraries](runtime#s%3Aocamlrun-dllpath)
- [15.4 Common errors](runtime#s%3Aocamlrun-common-errors)
+ [Chapter 16 Native-code compilation (ocamlopt)](native#sec360)
- [16.1 Overview of the compiler](native#s%3Anative-overview)
- [16.2 Options](native#s%3Anative-options)
- [16.3 Common errors](native#s%3Anative-common-errors)
- [16.4 Running executables produced by ocamlopt](native#s%3Anative%3Arunning-executable)
- [16.5 Compatibility with the bytecode compiler](native#s%3Acompat-native-bytecode)
+ [Chapter 17 Lexer and parser generators (ocamllex, ocamlyacc)](lexyacc#sec370)
- [17.1 Overview of ocamllex](lexyacc#s%3Aocamllex-overview)
* [17.1.1 Options](lexyacc#ss%3Aocamllex-options)
- [17.2 Syntax of lexer definitions](lexyacc#s%3Aocamllex-syntax)
* [17.2.1 Header and trailer](lexyacc#ss%3Aocamllex-header-trailer)
* [17.2.2 Naming regular expressions](lexyacc#ss%3Aocamllex-named-regexp)
* [17.2.3 Entry points](lexyacc#ss%3Aocamllex-entry-points)
* [17.2.4 Regular expressions](lexyacc#ss%3Aocamllex-regexp)
* [17.2.5 Actions](lexyacc#ss%3Aocamllex-actions)
* [17.2.6 Variables in regular expressions](lexyacc#ss%3Aocamllex-variables)
* [17.2.7 Refill handlers](lexyacc#ss%3Arefill-handlers)
* [17.2.8 Reserved identifiers](lexyacc#ss%3Aocamllex-reserved-ident)
- [17.3 Overview of ocamlyacc](lexyacc#s%3Aocamlyacc-overview)
- [17.4 Syntax of grammar definitions](lexyacc#s%3Aocamlyacc-syntax)
* [17.4.1 Header and trailer](lexyacc#ss%3Aocamlyacc-header-trailer)
* [17.4.2 Declarations](lexyacc#ss%3Aocamlyacc-declarations)
* [17.4.3 Rules](lexyacc#ss%3Aocamlyacc-rules)
* [17.4.4 Error handling](lexyacc#ss%3Aocamlyacc-error-handling)
- [17.5 Options](lexyacc#s%3Aocamlyacc-options)
- [17.6 A complete example](lexyacc#s%3Alexyacc-example)
- [17.7 Common errors](lexyacc#s%3Alexyacc-common-errors)
+ [Chapter 18 Dependency generator (ocamldep)](depend#sec391)
- [18.1 Options](depend#s%3Aocamldep-options)
- [18.2 A typical Makefile](depend#s%3Aocamldep-makefile)
+ [Chapter 19 The documentation generator (ocamldoc)](ocamldoc#sec394)
- [19.1 Usage](ocamldoc#s%3Aocamldoc-usage)
* [19.1.1 Invocation](ocamldoc#ss%3Aocamldoc-invocation)
* [19.1.2 Merging of module information](ocamldoc#ss%3Aocamldoc-merge)
* [19.1.3 Coding rules](ocamldoc#ss%3Aocamldoc-rules)
- [19.2 Syntax of documentation comments](ocamldoc#s%3Aocamldoc-comments)
* [19.2.1 Placement of documentation comments](ocamldoc#ss%3Aocamldoc-placement)
* [19.2.2 The Stop special comment](ocamldoc#ss%3Aocamldoc-stop)
* [19.2.3 Syntax of documentation comments](ocamldoc#ss%3Aocamldoc-syntax)
* [19.2.4 Text formatting](ocamldoc#ss%3Aocamldoc-formatting)
* [19.2.5 Documentation tags (@-tags)](ocamldoc#ss%3Aocamldoc-tags)
- [19.3 Custom generators](ocamldoc#s%3Aocamldoc-custom-generators)
* [19.3.1 The generator modules](ocamldoc#ss%3Aocamldoc-generators)
* [19.3.2 Handling custom tags](ocamldoc#ss%3Aocamldoc-handling-custom-tags)
- [19.4 Adding command line options](ocamldoc#s%3Aocamldoc-adding-flags)
* [19.4.1 Compilation and usage](ocamldoc#ss%3Aocamldoc-compilation-and-usage)
+ [Chapter 20 The debugger (ocamldebug)](debugger#sec431)
- [20.1 Compiling for debugging](debugger#s%3Adebugger-compilation)
- [20.2 Invocation](debugger#s%3Adebugger-invocation)
* [20.2.1 Starting the debugger](debugger#ss%3Adebugger-start)
* [20.2.2 Initialization file](debugger#ss%3Adebugger-init-file)
* [20.2.3 Exiting the debugger](debugger#ss%3Adebugger-exut)
- [20.3 Commands](debugger#s%3Adebugger-commands)
* [20.3.1 Getting help](debugger#ss%3Adebugger-help)
* [20.3.2 Accessing the debugger state](debugger#ss%3Adebugger-state)
- [20.4 Executing a program](debugger#s%3Adebugger-execution)
* [20.4.1 Events](debugger#ss%3Adebugger-events)
* [20.4.2 Starting the debugged program](debugger#ss%3Adebugger-starting-program)
* [20.4.3 Running the program](debugger#ss%3Adebugger-running)
* [20.4.4 Time travel](debugger#ss%3Adebugger-time-travel)
* [20.4.5 Killing the program](debugger#ss%3Adebugger-kill)
- [20.5 Breakpoints](debugger#s%3Abreakpoints)
- [20.6 The call stack](debugger#s%3Adebugger-callstack)
- [20.7 Examining variable values](debugger#s%3Adebugger-examining-values)
- [20.8 Controlling the debugger](debugger#s%3Adebugger-control)
* [20.8.1 Setting the program name and arguments](debugger#ss%3Adebugger-name-and-arguments)
* [20.8.2 How programs are loaded](debugger#ss%3Adebugger-loading)
* [20.8.3 Search path for files](debugger#ss%3Adebugger-search-path)
* [20.8.4 Working directory](debugger#ss%3Adebugger-working-dir)
* [20.8.5 Turning reverse execution on and off](debugger#ss%3Adebugger-reverse-execution)
* [20.8.6 Behavior of the debugger with respect to fork](debugger#ss%3Adebugger-fork)
* [20.8.7 Stopping execution when new code is loaded](debugger#ss%3Adebugger-stop-at-new-load)
* [20.8.8 Communication between the debugger and the program](debugger#ss%3Adebugger-communication)
* [20.8.9 Fine-tuning the debugger](debugger#ss%3Adebugger-fine-tuning)
* [20.8.10 User-defined printers](debugger#ss%3Adebugger-printers)
- [20.9 Miscellaneous commands](debugger#s%3Adebugger-misc-cmds)
- [20.10 Running the debugger under Emacs](debugger#s%3Ainf-debugger)
+ [Chapter 21 Profiling (ocamlprof)](profil#sec462)
- [21.1 Compiling for profiling](profil#s%3Aocamlprof-compiling)
- [21.2 Profiling an execution](profil#s%3Aocamlprof-profiling)
- [21.3 Printing profiling information](profil#s%3Aocamlprof-printing)
- [21.4 Time profiling](profil#s%3Aocamlprof-time-profiling)
+ [Chapter 22 Interfacing C with OCaml](intfc#c%3Aintf-c)
- [22.1 Overview and compilation information](intfc#s%3Ac-overview)
* [22.1.1 Declaring primitives](intfc#ss%3Ac-prim-decl)
* [22.1.2 Implementing primitives](intfc#ss%3Ac-prim-impl)
* [22.1.3 Statically linking C code with OCaml code](intfc#ss%3Astaticlink-c-code)
* [22.1.4 Dynamically linking C code with OCaml code](intfc#ss%3Adynlink-c-code)
* [22.1.5 Choosing between static linking and dynamic linking](intfc#ss%3Ac-static-vs-dynamic)
* [22.1.6 Building standalone custom runtime systems](intfc#ss%3Acustom-runtime)
- [22.2 The value type](intfc#s%3Ac-value)
* [22.2.1 Integer values](intfc#ss%3Ac-int)
* [22.2.2 Blocks](intfc#ss%3Ac-blocks)
* [22.2.3 Pointers outside the heap](intfc#ss%3Ac-outside-head)
- [22.3 Representation of OCaml data types](intfc#s%3Ac-ocaml-datatype-repr)
* [22.3.1 Atomic types](intfc#ss%3Ac-atomic)
* [22.3.2 Tuples and records](intfc#ss%3Ac-tuples-and-records)
* [22.3.3 Arrays](intfc#ss%3Ac-arrays)
* [22.3.4 Concrete data types](intfc#ss%3Ac-concrete-datatypes)
* [22.3.5 Objects](intfc#ss%3Ac-objects)
* [22.3.6 Polymorphic variants](intfc#ss%3Ac-polyvar)
- [22.4 Operations on values](intfc#s%3Ac-ops-on-values)
* [22.4.1 Kind tests](intfc#ss%3Ac-kind-tests)
* [22.4.2 Operations on integers](intfc#ss%3Ac-int-ops)
* [22.4.3 Accessing blocks](intfc#ss%3Ac-block-access)
* [22.4.4 Allocating blocks](intfc#ss%3Ac-block-allocation)
* [22.4.5 Raising exceptions](intfc#ss%3Ac-exceptions)
- [22.5 Living in harmony with the garbage collector](intfc#s%3Ac-gc-harmony)
* [22.5.1 Simple interface](intfc#ss%3Ac-simple-gc-harmony)
* [22.5.2 Low-level interface](intfc#ss%3Ac-low-level-gc-harmony)
* [22.5.3 Pending actions and asynchronous exceptions](intfc#ss%3Ac-process-pending-actions)
- [22.6 A complete example](intfc#s%3Ac-intf-example)
- [22.7 Advanced topic: callbacks from C to OCaml](intfc#s%3Ac-callback)
* [22.7.1 Applying OCaml closures from C](intfc#ss%3Ac-callbacks)
* [22.7.2 Obtaining or registering OCaml closures for use in C functions](intfc#ss%3Ac-closures)
* [22.7.3 Registering OCaml exceptions for use in C functions](intfc#ss%3Ac-register-exn)
* [22.7.4 Main program in C](intfc#ss%3Amain-c)
* [22.7.5 Embedding the OCaml code in the C code](intfc#ss%3Ac-embedded-code)
- [22.8 Advanced example with callbacks](intfc#s%3Ac-advexample)
- [22.9 Advanced topic: custom blocks](intfc#s%3Ac-custom)
* [22.9.1 The struct custom\_operations](intfc#ss%3Ac-custom-ops)
* [22.9.2 Allocating custom blocks](intfc#ss%3Ac-custom-alloc)
* [22.9.3 Accessing custom blocks](intfc#ss%3Ac-custom-access)
* [22.9.4 Writing custom serialization and deserialization functions](intfc#ss%3Ac-custom-serialization)
* [22.9.5 Choosing identifiers](intfc#ss%3Ac-custom-idents)
* [22.9.6 Finalized blocks](intfc#ss%3Ac-finalized)
- [22.10 Advanced topic: Bigarrays and the OCaml-C interface](intfc#s%3AC-Bigarrays)
* [22.10.1 Include file](intfc#ss%3AC-Bigarrays-include)
* [22.10.2 Accessing an OCaml bigarray from C or Fortran](intfc#ss%3AC-Bigarrays-access)
* [22.10.3 Wrapping a C or Fortran array as an OCaml Bigarray](intfc#ss%3AC-Bigarrays-wrap)
- [22.11 Advanced topic: cheaper C call](intfc#s%3AC-cheaper-call)
* [22.11.1 Passing unboxed values](intfc#ss%3Ac-unboxed)
* [22.11.2 Direct C call](intfc#ss%3Ac-direct-call)
* [22.11.3 Example: calling C library functions without indirection](intfc#ss%3Ac-direct-call-example)
- [22.12 Advanced topic: multithreading](intfc#s%3AC-multithreading)
* [22.12.1 Registering threads created from C](intfc#ss%3Ac-thread-register)
* [22.12.2 Parallel execution of long-running C code with systhreads](intfc#ss%3Aparallel-execution-long-running-c-code)
- [22.13 Advanced topic: interfacing with Windows Unicode APIs](intfc#s%3Ainterfacing-windows-unicode-apis)
- [22.14 Building mixed C/OCaml libraries: ocamlmklib](intfc#s%3Aocamlmklib)
- [22.15 Cautionary words: the internal runtime API](intfc#s%3Ac-internal-guidelines)
* [22.15.1 Internal variables and CAML\_INTERNALS](intfc#ss%3Ac-internals)
* [22.15.2 OCaml version macros](intfc#ss%3Ac-internal-macros)
+ [Chapter 23 Optimisation with Flambda](flambda#sec546)
- [23.1 Overview](flambda#s%3Aflambda-overview)
- [23.2 Command-line flags](flambda#s%3Aflambda-cli)
* [23.2.1 Specification of optimisation parameters by round](flambda#ss%3Aflambda-rounds)
- [23.3 Inlining](flambda#s%3Aflambda-inlining)
* [23.3.1 Classic inlining heuristic](flambda#ss%3Aflambda-classic)
* [23.3.2 Overview of “Flambda” inlining heuristics](flambda#ss%3Aflambda-inlining-overview)
* [23.3.3 Handling of specific language constructs](flambda#ss%3Aflambda-by-constructs)
* [23.3.4 Inlining reports](flambda#ss%3Aflambda-inlining-reports)
* [23.3.5 Assessment of inlining benefit](flambda#ss%3Aflambda-assessment-inlining)
* [23.3.6 Control of speculation](flambda#ss%3Aflambda-speculation)
- [23.4 Specialisation](flambda#s%3Aflambda-specialisation)
* [23.4.1 Assessment of specialisation benefit](flambda#ss%3Aflambda-assessment-specialisation)
- [23.5 Default settings of parameters](flambda#s%3Aflambda-defaults)
* [23.5.1 Settings at -O2 optimisation level](flambda#ss%3Aflambda-o2)
* [23.5.2 Settings at -O3 optimisation level](flambda#ss%3Aflambda-o3)
- [23.6 Manual control of inlining and specialisation](flambda#s%3Aflambda-manual-control)
- [23.7 Simplification](flambda#s%3Aflambda-simplification)
- [23.8 Other code motion transformations](flambda#s%3Aflambda-other-transfs)
* [23.8.1 Lifting of constants](flambda#ss%3Aflambda-lift-const)
* [23.8.2 Lifting of toplevel let bindings](flambda#ss%3Aflambda-lift-toplevel-let)
- [23.9 Unboxing transformations](flambda#s%3Aflambda-unboxing)
* [23.9.1 Unboxing of closure variables](flambda#ss%3Aflambda-unbox-fvs)
* [23.9.2 Unboxing of specialised arguments](flambda#ss%3Aflambda-unbox-spec-args)
* [23.9.3 Unboxing of closures](flambda#ss%3Aflambda-unbox-closures)
- [23.10 Removal of unused code and values](flambda#s%3Aflambda-remove-unused)
* [23.10.1 Removal of redundant let expressions](flambda#ss%3Aflambda-redundant-let)
* [23.10.2 Removal of redundant program constructs](flambda#ss%3Aflambda-redundant)
* [23.10.3 Removal of unused arguments](flambda#ss%3Aflambda-remove-unused-args)
* [23.10.4 Removal of unused closure variables](flambda#ss%3Aflambda-removal-closure-vars)
- [23.11 Other code transformations](flambda#s%3Aflambda-other)
* [23.11.1 Transformation of non-escaping references into mutable variables](flambda#ss%3Aflambda-non-escaping-refs)
* [23.11.2 Substitution of closure variables for specialised arguments](flambda#ss%3Aflambda-subst-closure-vars)
- [23.12 Treatment of effects](flambda#s%3Aflambda-effects)
- [23.13 Compilation of statically-allocated modules](flambda#s%3Aflambda-static-modules)
- [23.14 Inhibition of optimisation](flambda#s%3Aflambda-inhibition)
- [23.15 Use of unsafe operations](flambda#s%3Aflambda-unsafe)
- [23.16 Glossary](flambda#s%3Aflambda-glossary)
+ [Chapter 24 Fuzzing with afl-fuzz](afl-fuzz#sec597)
- [24.1 Overview](afl-fuzz#s%3Aafl-overview)
- [24.2 Generating instrumentation](afl-fuzz#s%3Aafl-generate)
* [24.2.1 Advanced options](afl-fuzz#ss%3Aafl-advanced)
- [24.3 Example](afl-fuzz#s%3Aafl-example)
+ [Chapter 25 Runtime tracing with runtime events](runtime-tracing#sec602)
- [25.1 Overview](runtime-tracing#s%3Aruntime-tracing-overview)
- [25.2 Architecture](runtime-tracing#s%3Aruntime-tracing-architecture)
* [25.2.1 Probes](runtime-tracing#s%3Aruntime-tracing-probes)
* [25.2.2 Events transport](runtime-tracing#s%3Aruntime-tracing-ingestion)
- [25.3 Usage](runtime-tracing#s-runtime-tracing-usage)
* [25.3.1 With OCaml APIs](runtime-tracing#s-runtime-tracing-ocaml-apis)
* [25.3.2 With tooling](runtime-tracing#s-runtime-tracing-tooling)
+ [Chapter 26 The “Tail Modulo Constructor” program transformation](tail_mod_cons#sec615)
- [26.1 Disambiguation](tail_mod_cons#sec%3Adisambiguation)
- [26.2 Danger: getting out of tail-mod-cons](tail_mod_cons#sec%3Aout-of-tmc)
- [26.3 Details on the transformation](tail_mod_cons#sec%3Adetails)
- [26.4 Current limitations](tail_mod_cons#sec%3Alimitations)
* [Part IV The OCaml library](index#sec627)
+ [Chapter 27 The core library](core#sec628)
- [27.1 Built-in types and predefined exceptions](core#s%3Acore-builtins)
- [27.2 Module Stdlib: the initially opened module](core#s%3Astdlib-module)
+ [Chapter 28 The standard library](stdlib#sec633)
+ [Chapter 29 The compiler front-end](parsing#sec634)
+ [Chapter 30 The unix library: Unix system calls](libunix#sec635)
+ [Chapter 31 The str library: regular expressions and string processing](libstr#sec636)
+ [Chapter 32 The runtime\_events library](runtime_events#sec637)
+ [Chapter 33 The threads library](libthreads#sec638)
+ [Chapter 34 The dynlink library: dynamic loading and linking of object files](libdynlink#sec639)
+ [Chapter 35 Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk)](old#sec640)
- [35.1 The Graphics Library](old#s%3Agraphics-removed)
- [35.2 The Bigarray Library](old#s%3Abigarray-moved)
- [35.3 The Num Library](old#sec643)
- [35.4 The Labltk Library and OCamlBrowser](old#s%3Alabltk-removed)
* [Part V Indexes](index#sec645)
| programming_docs |
ocaml None
[](#s:names)11.3 Names
------------------------
Identifiers are used to give names to several classes of language objects and refer to these objects by name later:
* value names (syntactic class [value-name](#value-name)),
* value constructors and exception constructors (class [constr-name](#constr-name)),
* labels ([label-name](lex#label-name), defined in section [11.1](lex#sss%3Alabelname)),
* polymorphic variant tags ([tag-name](#tag-name)),
* type constructors ([typeconstr-name](#typeconstr-name)),
* record fields ([field-name](#field-name)),
* class names ([class-name](#class-name)),
* method names ([method-name](#method-name)),
* instance variable names ([inst-var-name](#inst-var-name)),
* module names ([module-name](#module-name)),
* module type names ([modtype-name](#modtype-name)).
These eleven name spaces are distinguished both by the context and by the capitalization of the identifier: whether the first letter of the identifier is in lowercase (written [lowercase-ident](lex#lowercase-ident) below) or in uppercase (written [capitalized-ident](lex#capitalized-ident)). Underscore is considered a lowercase letter for this purpose.
####
[](#sss:naming-objects)Naming objects
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| value-name | ::= | [lowercase-ident](lex#lowercase-ident) |
| | ∣ | ( [operator-name](#operator-name) ) |
| |
| operator-name | ::= | [prefix-symbol](lex#prefix-symbol) ∣ [infix-op](#infix-op) |
| |
| infix-op | ::= | [infix-symbol](lex#infix-symbol) |
| | ∣ | \* ∣ + ∣ - ∣ -. ∣ = ∣ != ∣ < ∣ > ∣ or ∣ || ∣ & ∣ && ∣ := |
| | ∣ | mod ∣ land ∣ lor ∣ lxor ∣ lsl ∣ lsr ∣ asr |
| |
| constr-name | ::= | [capitalized-ident](lex#capitalized-ident) |
| |
| tag-name | ::= | [capitalized-ident](lex#capitalized-ident) |
| |
| typeconstr-name | ::= | [lowercase-ident](lex#lowercase-ident) |
| |
| field-name | ::= | [lowercase-ident](lex#lowercase-ident) |
| |
| module-name | ::= | [capitalized-ident](lex#capitalized-ident) |
| |
| modtype-name | ::= | [ident](lex#ident) |
| |
| class-name | ::= | [lowercase-ident](lex#lowercase-ident) |
| |
| inst-var-name | ::= | [lowercase-ident](lex#lowercase-ident) |
| |
| method-name | ::= | [lowercase-ident](lex#lowercase-ident) |
|
See also the following language extension: [extended indexing operators](indexops#s%3Aindex-operators).
As shown above, prefix and infix symbols as well as some keywords can be used as value names, provided they are written between parentheses. The capitalization rules are summarized in the table below.
| | |
| --- | --- |
| Name space | Case of first letter |
| Values | lowercase |
| Constructors | uppercase |
| Labels | lowercase |
| Polymorphic variant tags | uppercase |
| Exceptions | uppercase |
| Type constructors | lowercase |
| Record fields | lowercase |
| Classes | lowercase |
| Instance variables | lowercase |
| Methods | lowercase |
| Modules | uppercase |
| Module types | any |
Note on polymorphic variant tags: the current implementation accepts lowercase variant tags in addition to capitalized variant tags, but we suggest you avoid lowercase variant tags for portability and compatibility with future OCaml versions.
####
[](#sss:refer-named)Referring to named objects
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| value-path | ::= | [ [module-path](#module-path) . ] [value-name](#value-name) |
| |
| constr | ::= | [ [module-path](#module-path) . ] [constr-name](#constr-name) |
| |
| typeconstr | ::= | [ [extended-module-path](#extended-module-path) . ] [typeconstr-name](#typeconstr-name) |
| |
| field | ::= | [ [module-path](#module-path) . ] [field-name](#field-name) |
| |
| modtype-path | ::= | [ [extended-module-path](#extended-module-path) . ] [modtype-name](#modtype-name) |
| |
| class-path | ::= | [ [module-path](#module-path) . ] [class-name](#class-name) |
| |
| classtype-path | ::= | [ [extended-module-path](#extended-module-path) . ] [class-name](#class-name) |
| |
| module-path | ::= | [module-name](#module-name) { . [module-name](#module-name) } |
| |
| extended-module-path | ::= | [extended-module-name](#extended-module-name) { . [extended-module-name](#extended-module-name) } |
| |
| extended-module-name | ::= | [module-name](#module-name) { ( [extended-module-path](#extended-module-path) ) } |
|
A named object can be referred to either by its name (following the usual static scoping rules for names) or by an access path prefix . name, where prefix designates a module and name is the name of an object defined in that module. The first component of the path, prefix, is either a simple module name or an access path name1 . name2 …, in case the defining module is itself nested inside other modules. For referring to type constructors, module types, or class types, the prefix can also contain simple functor applications (as in the syntactic class [extended-module-path](#extended-module-path) above) in case the defining module is the result of a functor application.
Label names, tag names, method names and instance variable names need not be qualified: the former three are global labels, while the latter are local to a class.
ocaml None
[](#s:binding-operators)12.23 Binding operators
-------------------------------------------------
* [12.23.1 Short notation for variable bindings (let-punning)](bindingops#ss%3Aletops-punning)
* [12.23.2 Rationale](bindingops#ss%3Aletops-rationale)
(Introduced in 4.08.0)
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| let-operator | ::= | |
| | ∣ | let ([core-operator-char](lex#core-operator-char) ∣ <) { [dot-operator-char](indexops#dot-operator-char) } |
| |
| and-operator | ::= | |
| | ∣ | and ([core-operator-char](lex#core-operator-char) ∣ <) { [dot-operator-char](indexops#dot-operator-char) } |
| |
| operator-name | ::= | ... |
| | ∣ | [let-operator](#let-operator) |
| | ∣ | [and-operator](#and-operator) |
| |
| letop-binding | ::= | [pattern](patterns#pattern) = [expr](expr#expr) |
| | ∣ | [value-name](names#value-name) |
| |
| [expr](expr#expr) | ::= | ... |
| | ∣ | [let-operator](#let-operator) [letop-binding](#letop-binding) { [and-operator](#and-operator) [letop-binding](#letop-binding) } in [expr](expr#expr) |
| |
|
Users can define *let operators*:
```
let ( let* ) o f =
match o with
| None -> None
| Some x -> f x
let return x = Some x
val ( let* ) : 'a option -> ('a -> 'b option) -> 'b option =
val return : 'a -> 'a option =
```
and then apply them using this convenient syntax:
```
let find_and_sum tbl k1 k2 =
let* x1 = Hashtbl.find_opt tbl k1 in
let* x2 = Hashtbl.find_opt tbl k2 in
return (x1 + x2)
val find_and_sum : ('a, int) Hashtbl.t -> 'a -> 'a -> int option =
```
which is equivalent to this expanded form:
```
let find_and_sum tbl k1 k2 =
( let* ) (Hashtbl.find_opt tbl k1)
(fun x1 ->
( let* ) (Hashtbl.find_opt tbl k2)
(fun x2 -> return (x1 + x2)))
val find_and_sum : ('a, int) Hashtbl.t -> 'a -> 'a -> int option =
```
Users can also define *and operators*:
```
module ZipSeq = struct
type 'a t = 'a Seq.t
open Seq
let rec return x =
fun () -> Cons(x, return x)
let rec prod a b =
fun () ->
match a (), b () with
| Nil, _ | _, Nil -> Nil
| Cons(x, a), Cons(y, b) -> Cons((x, y), prod a b)
let ( let+ ) f s = map s f
let ( and+ ) a b = prod a b
end
module ZipSeq :
sig
type 'a t = 'a Seq.t
val return : 'a -> 'a Seq.t
val prod : 'a Seq.t -> 'b Seq.t -> ('a * 'b) Seq.t
val ( let+ ) : 'a Seq.t -> ('a -> 'b) -> 'b Seq.t
val ( and+ ) : 'a Seq.t -> 'b Seq.t -> ('a * 'b) Seq.t
end
```
to support the syntax:
```
open ZipSeq
let sum3 z1 z2 z3 =
let+ x1 = z1
and+ x2 = z2
and+ x3 = z3 in
x1 + x2 + x3
val sum3 : int Seq.t -> int Seq.t -> int Seq.t -> int Seq.t =
```
which is equivalent to this expanded form:
```
open ZipSeq
let sum3 z1 z2 z3 =
( let+ ) (( and+ ) (( and+ ) z1 z2) z3)
(fun ((x1, x2), x3) -> x1 + x2 + x3)
val sum3 : int Seq.t -> int Seq.t -> int Seq.t -> int Seq.t =
```
###
[](#ss:letops-punning)12.23.1 Short notation for variable bindings (let-punning)
(Introduced in 4.13.0)
When the expression being bound is a variable, it can be convenient to use the shorthand notation let+ x in ..., which expands to let+ x = x in .... This notation, also known as let-punning, allows the sum3 function above can be written more concisely as:
```
open ZipSeq
let sum3 z1 z2 z3 =
let+ z1 and+ z2 and+ z3 in
z1 + z2 + z3
val sum3 : int Seq.t -> int Seq.t -> int Seq.t -> int Seq.t =
```
This notation is also supported for extension nodes, expanding let%foo x in ... to let%foo x = x in .... However, to avoid confusion, this notation is not supported for plain let bindings.
###
[](#ss:letops-rationale)12.23.2 Rationale
This extension is intended to provide a convenient syntax for working with monads and applicatives.
An applicative should provide a module implementing the following interface:
```
module type Applicative_syntax = sig
type 'a t
val ( let+ ) : 'a t -> ('a -> 'b) -> 'b t
val ( and+ ): 'a t -> 'b t -> ('a * 'b) t
end
```
where (let+) is bound to the map operation and (and+) is bound to the monoidal product operation.
A monad should provide a module implementing the following interface:
```
module type Monad_syntax = sig
include Applicative_syntax
val ( let* ) : 'a t -> ('a -> 'b t) -> 'b t
val ( and* ): 'a t -> 'b t -> ('a * 'b) t
end
```
where (let\*) is bound to the bind operation, and (and\*) is also bound to the monoidal product operation.
ocaml Chapter 29 The compiler front-end Chapter 29 The compiler front-end
=================================
This chapter describes the OCaml front-end, which declares the abstract syntax tree used by the compiler, provides a way to parse, print and pretty-print OCaml code, and ultimately allows one to write abstract syntax tree preprocessors invoked via the -ppx flag (see chapters [13](comp#c%3Acamlc) and [16](native#c%3Anativecomp)).
It is important to note that the exported front-end interface follows the evolution of the OCaml language and implementation, and thus does not provide any backwards compatibility guarantees.
The front-end is a part of compiler-libs library. Programs that use the compiler-libs library should be built as follows:
```
ocamlfind ocamlc other options -package compiler-libs.common other files
ocamlfind ocamlopt other options -package compiler-libs.common other files
```
Use of the ocamlfind utility is recommended. However, if this is not possible, an alternative method may be used:
```
ocamlc other options -I +compiler-libs ocamlcommon.cma other files
ocamlopt other options -I +compiler-libs ocamlcommon.cmxa other files
```
For interactive use of the compiler-libs library, start ocaml and type
#load "compiler-libs/ocamlcommon.cma";;.
* [Module Ast\_helper](https://v2.ocaml.org/releases/5.0/htmlman/compilerlibref/Ast_helper.html): helper functions for AST construction
* [Module Ast\_mapper](https://v2.ocaml.org/releases/5.0/htmlman/compilerlibref/Ast_mapper.html): -ppx rewriter interface
* [Module Asttypes](https://v2.ocaml.org/releases/5.0/htmlman/compilerlibref/Asttypes.html): auxiliary types used by Parsetree
* [Module Location](https://v2.ocaml.org/releases/5.0/htmlman/compilerlibref/Location.html): source code locations
* [Module Longident](https://v2.ocaml.org/releases/5.0/htmlman/compilerlibref/Longident.html): long identifiers
* [Module Parse](https://v2.ocaml.org/releases/5.0/htmlman/compilerlibref/Parse.html): OCaml syntax parsing
* [Module Parsetree](https://v2.ocaml.org/releases/5.0/htmlman/compilerlibref/Parsetree.html): OCaml syntax tree
* [Module Pprintast](https://v2.ocaml.org/releases/5.0/htmlman/compilerlibref/Pprintast.html): OCaml syntax printing
ocaml None
[](#s:empty-variants)12.20 Empty variant types
------------------------------------------------
(Introduced in 4.07.0)
| | | | | | | |
| --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [type-representation](typedecl#type-representation) | ::= | ... |
| | ∣ | = | |
|
This extension allows user to define empty variants. Empty variant type can be eliminated by refutation case of pattern matching.
```
type t = |
let f (x: t) = match x with _ -> .
```
ocaml Chapter 16 Native-code compilation (ocamlopt) Chapter 16 Native-code compilation (ocamlopt)
=============================================
* [16.1 Overview of the compiler](native#s%3Anative-overview)
* [16.2 Options](native#s%3Anative-options)
* [16.3 Common errors](native#s%3Anative-common-errors)
* [16.4 Running executables produced by ocamlopt](native#s%3Anative%3Arunning-executable)
* [16.5 Compatibility with the bytecode compiler](native#s%3Acompat-native-bytecode)
This chapter describes the OCaml high-performance native-code compiler ocamlopt, which compiles OCaml source files to native code object files and links these object files to produce standalone executables.
The native-code compiler is only available on certain platforms. It produces code that runs faster than the bytecode produced by ocamlc, at the cost of increased compilation time and executable code size. Compatibility with the bytecode compiler is extremely high: the same source code should run identically when compiled with ocamlc and ocamlopt.
It is not possible to mix native-code object files produced by ocamlopt with bytecode object files produced by ocamlc: a program must be compiled entirely with ocamlopt or entirely with ocamlc. Native-code object files produced by ocamlopt cannot be loaded in the toplevel system ocaml.
[](#s:native-overview)16.1 Overview of the compiler
-----------------------------------------------------
The ocamlopt command has a command-line interface very close to that of ocamlc. It accepts the same types of arguments, and processes them sequentially, after all options have been processed:
* Arguments ending in .mli are taken to be source files for compilation unit interfaces. Interfaces specify the names exported by compilation units: they declare value names with their types, define public data types, declare abstract data types, and so on. From the file x.mli, the ocamlopt compiler produces a compiled interface in the file x.cmi. The interface produced is identical to that produced by the bytecode compiler ocamlc.
* Arguments ending in .ml are taken to be source files for compilation unit implementations. Implementations provide definitions for the names exported by the unit, and also contain expressions to be evaluated for their side-effects. From the file x.ml, the ocamlopt compiler produces two files: x.o, containing native object code, and x.cmx, containing extra information for linking and optimization of the clients of the unit. The compiled implementation should always be referred to under the name x.cmx (when given a .o or .obj file, ocamlopt assumes that it contains code compiled from C, not from OCaml).The implementation is checked against the interface file x.mli (if it exists) as described in the manual for ocamlc (chapter [13](comp#c%3Acamlc)).
* Arguments ending in .cmx are taken to be compiled object code. These files are linked together, along with the object files obtained by compiling .ml arguments (if any), and the OCaml standard library, to produce a native-code executable program. The order in which .cmx and .ml arguments are presented on the command line is relevant: compilation units are initialized in that order at run-time, and it is a link-time error to use a component of a unit before having initialized it. Hence, a given x.cmx file must come before all .cmx files that refer to the unit x.
* Arguments ending in .cmxa are taken to be libraries of object code. Such a library packs in two files (lib.cmxa and lib.a/.lib) a set of object files (.cmx and .o/.obj files). Libraries are build with ocamlopt -a (see the description of the -a option below). The object files contained in the library are linked as regular .cmx files (see above), in the order specified when the library was built. The only difference is that if an object file contained in a library is not referenced anywhere in the program, then it is not linked in.
* Arguments ending in .c are passed to the C compiler, which generates a .o/.obj object file. This object file is linked with the program.
* Arguments ending in .o, .a or .so (.obj, .lib and .dll under Windows) are assumed to be C object files and libraries. They are linked with the program.
The output of the linking phase is a regular Unix or Windows executable file. It does not need ocamlrun to run.
The compiler is able to emit some information on its internal stages:
* .cmt files for the implementation of the compilation unit and .cmti for signatures if the option -bin-annot is passed to it (see the description of -bin-annot below). Each such file contains a typed abstract syntax tree (AST), that is produced during the type checking procedure. This tree contains all available information about the location and the specific type of each term in the source file. The AST is partial if type checking was unsuccessful.These .cmt and .cmti files are typically useful for code inspection tools.
* .cmir-linear files for the implementation of the compilation unit if the option -save-ir-after scheduling is passed to it. Each such file contains a low-level intermediate representation, produced by the instruction scheduling pass.An external tool can perform low-level optimisations, such as code layout, by transforming a .cmir-linear file. To continue compilation, the compiler can be invoked with (a possibly modified) .cmir-linear file as an argument, instead of the corresponding source file.
[](#s:native-options)16.2 Options
-----------------------------------
The following command-line options are recognized by ocamlopt. The options -pack, -a, -shared, -c, -output-obj and -output-complete-obj are mutually exclusive.
-a
Build a library(.cmxa and .a/.lib files) with the object files (.cmx and .o/.obj files) given on the command line, instead of linking them into an executable file. The name of the library must be set with the -o option.If -cclib or -ccopt options are passed on the command line, these options are stored in the resulting .cmxalibrary. Then, linking with this library automatically adds back the -cclib and -ccopt options as if they had been provided on the command line, unless the -noautolink option is given.
-absname
Force error messages to show absolute paths for file names.
-annot
Deprecated since OCaml 4.11. Please use -bin-annot instead.
-args filename
Read additional newline-terminated command line arguments from filename.
-args0 filename
Read additional null character terminated command line arguments from filename.
-bin-annot
Dump detailed information about the compilation (types, bindings, tail-calls, etc) in binary format. The information for file src.ml (resp. src.mli) is put into file src.cmt (resp. src.cmti). In case of a type error, dump all the information inferred by the type-checker before the error. The \*.cmt and \*.cmti files produced by -bin-annot contain more information and are much more compact than the files produced by -annot.
-c
Compile only. Suppress the linking phase of the compilation. Source code files are turned into compiled files, but no executable file is produced. This option is useful to compile modules separately.
-cc ccomp
Use ccomp as the C linker called to build the final executable and as the C compiler for compiling .c source files.
-cclib -llibname
Pass the -llibname option to the linker . This causes the given C library to be linked with the program.
-ccopt option
Pass the given option to the C compiler and linker. For instance, -ccopt -Ldir causes the C linker to search for C libraries in directory dir.
-cmi-file filename
Use the given interface file to type-check the ML source file to compile. When this option is not specified, the compiler looks for a .mli file with the same base name than the implementation it is compiling and in the same directory. If such a file is found, the compiler looks for a corresponding .cmi file in the included directories and reports an error if it fails to find one.
-color mode
Enable or disable colors in compiler messages (especially warnings and errors). The following modes are supported:
auto
use heuristics to enable colors only if the output supports them (an ANSI-compatible tty terminal);
always
enable colors unconditionally;
never
disable color output.
The environment variable OCAML\_COLOR is considered if -color is not provided. Its values are auto/always/never as above.
If -color is not provided, OCAML\_COLOR is not set and the environment variable NO\_COLOR is set, then color output is disabled. Otherwise, the default setting is ’auto’, and the current heuristic checks that the TERM environment variable exists and is not empty or dumb, and that ’isatty(stderr)’ holds.
-error-style mode
Control the way error messages and warnings are printed. The following modes are supported:
short
only print the error and its location;
contextual
like short, but also display the source code snippet corresponding to the location of the error.
The default setting is contextual.The environment variable OCAML\_ERROR\_STYLE is considered if -error-style is not provided. Its values are short/contextual as above.
-compact
Optimize the produced code for space rather than for time. This results in slightly smaller but slightly slower programs. The default is to optimize for speed.
-config
Print the version number of ocamlopt and a detailed summary of its configuration, then exit.
-config-var var
Print the value of a specific configuration variable from the -config output, then exit. If the variable does not exist, the exit code is non-zero. This option is only available since OCaml 4.08, so script authors should have a fallback for older versions.
-depend ocamldep-args
Compute dependencies, as the ocamldep command would do. The remaining arguments are interpreted as if they were given to the ocamldep command.
-for-pack module-path
Generate an object file (.cmx and .o/.obj files) that can later be included as a sub-module (with the given access path) of a compilation unit constructed with -pack. For instance, ocamlopt -for-pack P -c A.ml will generate a..cmx and a.o files that can later be used with ocamlopt -pack -o P.cmx a.cmx. Note: you can still pack a module that was compiled without -for-pack but in this case exceptions will be printed with the wrong names.
-g
Add debugging information while compiling and linking. This option is required in order to produce stack backtraces when the program terminates on an uncaught exception (see section [15.2](runtime#s%3Aocamlrun-options)).
-i
Cause the compiler to print all defined names (with their inferred types or their definitions) when compiling an implementation (.ml file). No compiled files (.cmo and .cmi files) are produced. This can be useful to check the types inferred by the compiler. Also, since the output follows the syntax of interfaces, it can help in writing an explicit interface (.mli file) for a file: just redirect the standard output of the compiler to a .mli file, and edit that file to remove all declarations of unexported names.
-I directory
Add the given directory to the list of directories searched for compiled interface files (.cmi), compiled object code files (.cmx), and libraries (.cmxa). By default, the current directory is searched first, then the standard library directory. Directories added with -I are searched after the current directory, in the order in which they were given on the command line, but before the standard library directory. See also option -nostdlib.If the given directory starts with +, it is taken relative to the standard library directory. For instance, -I +unix adds the subdirectory unix of the standard library to the search path.
-impl filename
Compile the file filename as an implementation file, even if its extension is not .ml.
-inline n
Set aggressiveness of inlining to n, where n is a positive integer. Specifying -inline 0 prevents all functions from being inlined, except those whose body is smaller than the call site. Thus, inlining causes no expansion in code size. The default aggressiveness, -inline 1, allows slightly larger functions to be inlined, resulting in a slight expansion in code size. Higher values for the -inline option cause larger and larger functions to become candidate for inlining, but can result in a serious increase in code size.
-intf filename
Compile the file filename as an interface file, even if its extension is not .mli.
-intf-suffix string
Recognize file names ending with string as interface files (instead of the default .mli).
-labels
Labels are not ignored in types, labels may be used in applications, and labelled parameters can be given in any order. This is the default.
-linkall
Force all modules contained in libraries to be linked in. If this flag is not given, unreferenced modules are not linked in. When building a library (option -a), setting the -linkall option forces all subsequent links of programs involving that library to link all the modules contained in the library. When compiling a module (option -c), setting the -linkall option ensures that this module will always be linked if it is put in a library and this library is linked.
-linscan
Use linear scan register allocation. Compiling with this allocator is faster than with the usual graph coloring allocator, sometimes quite drastically so for long functions and modules. On the other hand, the generated code can be a bit slower.
-match-context-rows
Set the number of rows of context used for optimization during pattern matching compilation. The default value is 32. Lower values cause faster compilation, but less optimized code. This advanced option is meant for use in the event that a pattern-match-heavy program leads to significant increases in compilation time.
-no-alias-deps
Do not record dependencies for module aliases. See section [12.8](modulealias#s%3Amodule-alias) for more information.
-no-app-funct
Deactivates the applicative behaviour of functors. With this option, each functor application generates new types in its result and applying the same functor twice to the same argument yields two incompatible structures.
-no-float-const-prop
Deactivates the constant propagation for floating-point operations. This option should be given if the program changes the float rounding mode during its execution.
-noassert
Do not compile assertion checks. Note that the special form assert false is always compiled because it is typed specially. This flag has no effect when linking already-compiled files.
-noautolink
When linking .cmxalibraries, ignore -cclib and -ccopt options potentially contained in the libraries (if these options were given when building the libraries). This can be useful if a library contains incorrect specifications of C libraries or C options; in this case, during linking, set -noautolink and pass the correct C libraries and options on the command line.
-nodynlink
Allow the compiler to use some optimizations that are valid only for code that is statically linked to produce a non-relocatable executable. The generated code cannot be linked to produce a shared library nor a position-independent executable (PIE). Many operating systems produce PIEs by default, causing errors when linking code compiled with -nodynlink. Either do not use -nodynlink or pass the option -ccopt -no-pie at link-time.
-nolabels
Ignore non-optional labels in types. Labels cannot be used in applications, and parameter order becomes strict.
-nostdlib
Do not automatically add the standard library directory to the list of directories searched for compiled interface files (.cmi), compiled object code files (.cmx), and libraries (.cmxa). See also option -I.
-o output-file
Specify the name of the output file to produce. For executable files, the default output name is a.out under Unix and camlprog.exe under Windows. If the -a option is given, specify the name of the library produced. If the -pack option is given, specify the name of the packed object file produced. If the -output-obj or -output-complete-obj options are given, specify the name of the produced object file. If the -shared option is given, specify the name of plugin file produced.
-opaque
When the native compiler compiles an implementation, by default it produces a .cmx file containing information for cross-module optimization. It also expects .cmx files to be present for the dependencies of the currently compiled source, and uses them for optimization. Since OCaml 4.03, the compiler will emit a warning if it is unable to locate the .cmx file of one of those dependencies.The -opaque option, available since 4.04, disables cross-module optimization information for the currently compiled unit. When compiling .mli interface, using -opaque marks the compiled .cmi interface so that subsequent compilations of modules that depend on it will not rely on the corresponding .cmx file, nor warn if it is absent. When the native compiler compiles a .ml implementation, using -opaque generates a .cmx that does not contain any cross-module optimization information.
Using this option may degrade the quality of generated code, but it reduces compilation time, both on clean and incremental builds. Indeed, with the native compiler, when the implementation of a compilation unit changes, all the units that depend on it may need to be recompiled – because the cross-module information may have changed. If the compilation unit whose implementation changed was compiled with -opaque, no such recompilation needs to occur. This option can thus be used, for example, to get faster edit-compile-test feedback loops.
-open Module
Opens the given module before processing the interface or implementation files. If several -open options are given, they are processed in order, just as if the statements open! Module1;; ... open! ModuleN;; were added at the top of each file.
-output-obj
Cause the linker to produce a C object file instead of an executable file. This is useful to wrap OCaml code as a C library, callable from any C program. See chapter [22](intfc#c%3Aintf-c), section [22.7.5](intfc#ss%3Ac-embedded-code). The name of the output object file must be set with the -o option. This option can also be used to produce a compiled shared/dynamic library (.so extension, .dll under Windows).
-output-complete-obj
Same as -output-obj options except the object file produced includes the runtime and autolink libraries.
-pack
Build an object file (.cmx and .o/.obj files) and its associated compiled interface (.cmi) that combines the .cmx object files given on the command line, making them appear as sub-modules of the output .cmx file. The name of the output .cmx file must be given with the -o option. For instance,
```
ocamlopt -pack -o P.cmx A.cmx B.cmx C.cmx
```
generates compiled files P.cmx, P.o and P.cmi describing a compilation unit having three sub-modules A, B and C, corresponding to the contents of the object files A.cmx, B.cmx and C.cmx. These contents can be referenced as P.A, P.B and P.C in the remainder of the program.The .cmx object files being combined must have been compiled with the appropriate -for-pack option. In the example above, A.cmx, B.cmx and C.cmx must have been compiled with ocamlopt -for-pack P.
Multiple levels of packing can be achieved by combining -pack with -for-pack. Consider the following example:
```
ocamlopt -for-pack P.Q -c A.ml
ocamlopt -pack -o Q.cmx -for-pack P A.cmx
ocamlopt -for-pack P -c B.ml
ocamlopt -pack -o P.cmx Q.cmx B.cmx
```
The resulting P.cmx object file has sub-modules P.Q, P.Q.A and P.B.
-pp command
Cause the compiler to call the given command as a preprocessor for each source file. The output of command is redirected to an intermediate file, which is compiled. If there are no compilation errors, the intermediate file is deleted afterwards.
-ppx command
After parsing, pipe the abstract syntax tree through the preprocessor command. The module Ast\_mapper, described in chapter [29](parsing#c%3Aparsinglib): [Ast\_mapper](https://v2.ocaml.org/releases/5.0/htmlman/compilerlibref/Ast_mapper.html) , implements the external interface of a preprocessor.
-principal
Check information path during type-checking, to make sure that all types are derived in a principal way. When using labelled arguments and/or polymorphic methods, this flag is required to ensure future versions of the compiler will be able to infer types correctly, even if internal algorithms change. All programs accepted in -principal mode are also accepted in the default mode with equivalent types, but different binary signatures, and this may slow down type checking; yet it is a good idea to use it once before publishing source code.
-rectypes
Allow arbitrary recursive types during type-checking. By default, only recursive types where the recursion goes through an object type are supported. Note that once you have created an interface using this flag, you must use it again for all dependencies.
-runtime-variant suffix
Add the suffix string to the name of the runtime library used by the program. Currently, only one such suffix is supported: d, and only if the OCaml compiler was configured with option -with-debug-runtime. This suffix gives the debug version of the runtime, which is useful for debugging pointer problems in low-level code such as C stubs.
-stop-after pass
Stop compilation after the given compilation pass. The currently supported passes are: parsing, typing, scheduling, emit.
-save-ir-after pass
Save intermediate representation after the given compilation pass to a file. The currently supported passes and the corresponding file extensions are: scheduling (.cmir-linear).This experimental feature enables external tools to inspect and manipulate compiler’s intermediate representation of the program using compiler-libs library (see chapter [29](parsing#c%3Aparsinglib) and [Compiler\_libs](https://v2.ocaml.org/releases/5.0/htmlman/compilerlibref/Compiler_libs.html) ).
-S
Keep the assembly code produced during the compilation. The assembly code for the source file x.ml is saved in the file x.s.
-shared
Build a plugin (usually .cmxs) that can be dynamically loaded with the Dynlink module. The name of the plugin must be set with the -o option. A plugin can include a number of OCaml modules and libraries, and extra native objects (.o, .obj, .a, .lib files). Building native plugins is only supported for some operating system. Under some systems (currently, only Linux AMD 64), all the OCaml code linked in a plugin must have been compiled without the -nodynlink flag. Some constraints might also apply to the way the extra native objects have been compiled (under Linux AMD 64, they must contain only position-independent code).
-safe-string
Enforce the separation between types string and bytes, thereby making strings read-only. This is the default, and enforced since OCaml 5.0.
-short-paths
When a type is visible under several module-paths, use the shortest one when printing the type’s name in inferred interfaces and error and warning messages. Identifier names starting with an underscore \_ or containing double underscores \_\_ incur a penalty of +10 when computing their length.
-strict-sequence
Force the left-hand part of each sequence to have type unit.
-strict-formats
Reject invalid formats that were accepted in legacy format implementations. You should use this flag to detect and fix such invalid formats, as they will be rejected by future OCaml versions.
-unboxed-types
When a type is unboxable (i.e. a record with a single argument or a concrete datatype with a single constructor of one argument) it will be unboxed unless annotated with [@@ocaml.boxed].
-no-unboxed-types
When a type is unboxable it will be boxed unless annotated with [@@ocaml.unboxed]. This is the default.
-unsafe
Turn bound checking off for array and string accesses (the v.(i) and s.[i] constructs). Programs compiled with -unsafe are therefore faster, but unsafe: anything can happen if the program accesses an array or string outside of its bounds. Additionally, turn off the check for zero divisor in integer division and modulus operations. With -unsafe, an integer division (or modulus) by zero can halt the program or continue with an unspecified result instead of raising a Division\_by\_zero exception.
-unsafe-string
Identify the types string and bytes, thereby making strings writable. This is intended for compatibility with old source code and should not be used with new software. This option raises an error unconditionally since OCaml 5.0.
-v
Print the version number of the compiler and the location of the standard library directory, then exit.
-verbose
Print all external commands before they are executed, in particular invocations of the assembler, C compiler, and linker. Useful to debug C library problems.
-version or -vnum
Print the version number of the compiler in short form (e.g. 3.11.0), then exit.
-w warning-list
Enable, disable, or mark as fatal the warnings specified by the argument warning-list. Each warning can be *enabled* or *disabled*, and each warning can be *fatal* or *non-fatal*. If a warning is disabled, it isn’t displayed and doesn’t affect compilation in any way (even if it is fatal). If a warning is enabled, it is displayed normally by the compiler whenever the source code triggers it. If it is enabled and fatal, the compiler will also stop with an error after displaying it.The warning-list argument is a sequence of warning specifiers, with no separators between them. A warning specifier is one of the following:
+num
Enable warning number num.
-num
Disable warning number num.
@num
Enable and mark as fatal warning number num.
+num1..num2
Enable warnings in the given range.
-num1..num2
Disable warnings in the given range.
@num1..num2
Enable and mark as fatal warnings in the given range.
+letter
Enable the set of warnings corresponding to letter. The letter may be uppercase or lowercase.
-letter
Disable the set of warnings corresponding to letter. The letter may be uppercase or lowercase.
@letter
Enable and mark as fatal the set of warnings corresponding to letter. The letter may be uppercase or lowercase.
uppercase-letter
Enable the set of warnings corresponding to uppercase-letter.
lowercase-letter
Disable the set of warnings corresponding to lowercase-letter.
Alternatively, warning-list can specify a single warning using its mnemonic name (see below), as follows:
+name
Enable warning name.
-name
Disable warning name.
@name
Enable and mark as fatal warning name.
Warning numbers, letters and names which are not currently defined are ignored. The warnings are as follows (the name following each number specifies the mnemonic for that warning).
1 comment-start
Suspicious-looking start-of-comment mark.
2 comment-not-end
Suspicious-looking end-of-comment mark.
3
Deprecated synonym for the ’deprecated’ alert.
4 fragile-match
Fragile pattern matching: matching that will remain complete even if additional constructors are added to one of the variant types matched.
5 ignored-partial-application
Partially applied function: expression whose result has function type and is ignored.
6 labels-omitted
Label omitted in function application.
7 method-override
Method overridden.
8 partial-match
Partial match: missing cases in pattern-matching.
9 missing-record-field-pattern
Missing fields in a record pattern.
10 non-unit-statement
Expression on the left-hand side of a sequence that doesn’t have type unit (and that is not a function, see warning number 5).
11 redundant-case
Redundant case in a pattern matching (unused match case).
12 redundant-subpat
Redundant sub-pattern in a pattern-matching.
13 instance-variable-override
Instance variable overridden.
14 illegal-backslash
Illegal backslash escape in a string constant.
15 implicit-public-methods
Private method made public implicitly.
16 unerasable-optional-argument
Unerasable optional argument.
17 undeclared-virtual-method
Undeclared virtual method.
18 not-principal
Non-principal type.
19 non-principal-labels
Type without principality.
20 ignored-extra-argument
Unused function argument.
21 nonreturning-statement
Non-returning statement.
22 preprocessor
Preprocessor warning.
23 useless-record-with
Useless record with clause.
24 bad-module-name
Bad module name: the source file name is not a valid OCaml module name.
25
Ignored: now part of warning 8.
26 unused-var
Suspicious unused variable: unused variable that is bound with let or as, and doesn’t start with an underscore (\_) character.
27 unused-var-strict
Innocuous unused variable: unused variable that is not bound with let nor as, and doesn’t start with an underscore (\_) character.
28 wildcard-arg-to-constant-constr
Wildcard pattern given as argument to a constant constructor.
29 eol-in-string
Unescaped end-of-line in a string constant (non-portable code).
30 duplicate-definitions
Two labels or constructors of the same name are defined in two mutually recursive types.
31 module-linked-twice
A module is linked twice in the same executable. (since 4.00)
32 unused-value-declaration
Unused value declaration. (since 4.00)
33 unused-open
Unused open statement. (since 4.00)
34 unused-type-declaration
Unused type declaration. (since 4.00)
35 unused-for-index
Unused for-loop index. (since 4.00)
36 unused-ancestor
Unused ancestor variable. (since 4.00)
37 unused-constructor
Unused constructor. (since 4.00)
38 unused-extension
Unused extension constructor. (since 4.00)
39 unused-rec-flag
Unused rec flag. (since 4.00)
40 name-out-of-scope
Constructor or label name used out of scope. (since 4.01)
41 ambiguous-name
Ambiguous constructor or label name. (since 4.01)
42 disambiguated-name
Disambiguated constructor or label name (compatibility warning). (since 4.01)
43 nonoptional-label
Nonoptional label applied as optional. (since 4.01)
44 open-shadow-identifier
Open statement shadows an already defined identifier. (since 4.01)
45 open-shadow-label-constructor
Open statement shadows an already defined label or constructor. (since 4.01)
46 bad-env-variable
Error in environment variable. (since 4.01)
47 attribute-payload
Illegal attribute payload. (since 4.02)
48 eliminated-optional-arguments
Implicit elimination of optional arguments. (since 4.02)
49 no-cmi-file
Absent cmi file when looking up module alias. (since 4.02)
50 unexpected-docstring
Unexpected documentation comment. (since 4.03)
51 wrong-tailcall-expectation
Function call annotated with an incorrect @tailcall attribute. (since 4.03)
52 fragile-literal-pattern (see [13.5.3](comp#ss%3Awarn52))
Fragile constant pattern. (since 4.03)
53 misplaced-attribute
Attribute cannot appear in this context. (since 4.03)
54 duplicated-attribute
Attribute used more than once on an expression. (since 4.03)
55 inlining-impossible
Inlining impossible. (since 4.03)
56 unreachable-case
Unreachable case in a pattern-matching (based on type information). (since 4.03)
57 ambiguous-var-in-pattern-guard (see [13.5.4](comp#ss%3Awarn57))
Ambiguous or-pattern variables under guard. (since 4.03)
58 no-cmx-file
Missing cmx file. (since 4.03)
59 flambda-assignment-to-non-mutable-value
Assignment to non-mutable value. (since 4.03)
60 unused-module
Unused module declaration. (since 4.04)
61 unboxable-type-in-prim-decl
Unboxable type in primitive declaration. (since 4.04)
62 constraint-on-gadt
Type constraint on GADT type declaration. (since 4.06)
63 erroneous-printed-signature
Erroneous printed signature. (since 4.08)
64 unsafe-array-syntax-without-parsing
-unsafe used with a preprocessor returning a syntax tree. (since 4.08)
65 redefining-unit
Type declaration defining a new ’()’ constructor. (since 4.08)
66 unused-open-bang
Unused open! statement. (since 4.08)
67 unused-functor-parameter
Unused functor parameter. (since 4.10)
68 match-on-mutable-state-prevent-uncurry
Pattern-matching depending on mutable state prevents the remaining arguments from being uncurried. (since 4.12)
69 unused-field
Unused record field. (since 4.13)
70 missing-mli
Missing interface file. (since 4.13)
71 unused-tmc-attribute
Unused @tail\_mod\_cons attribute. (since 4.14)
72 tmc-breaks-tailcall
A tail call is turned into a non-tail call by the @tail\_mod\_cons transformation. (since 4.14)
A
all warnings
C
warnings 1, 2.
D
Alias for warning 3.
E
Alias for warning 4.
F
Alias for warning 5.
K
warnings 32, 33, 34, 35, 36, 37, 38, 39.
L
Alias for warning 6.
M
Alias for warning 7.
P
Alias for warning 8.
R
Alias for warning 9.
S
Alias for warning 10.
U
warnings 11, 12.
V
Alias for warning 13.
X
warnings 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 30.
Y
Alias for warning 26.
Z
Alias for warning 27.
The default setting is -w +a-4-6-7-9-27-29-32..42-44-45-48-50-60. It is displayed by ocamlopt -help. Note that warnings 5 and 10 are not always triggered, depending on the internals of the type checker.
-warn-error warning-list
Mark as fatal the warnings specified in the argument warning-list. The compiler will stop with an error when one of these warnings is emitted. The warning-list has the same meaning as for the -w option: a + sign (or an uppercase letter) marks the corresponding warnings as fatal, a - sign (or a lowercase letter) turns them back into non-fatal warnings, and a @ sign both enables and marks as fatal the corresponding warnings.Note: it is not recommended to use warning sets (i.e. letters) as arguments to -warn-error in production code, because this can break your build when future versions of OCaml add some new warnings.
The default setting is -warn-error -a+31 (only warning 31 is fatal).
-warn-help
Show the description of all available warning numbers.
-where
Print the location of the standard library, then exit.
-with-runtime
Include the runtime system in the generated program. This is the default.
-without-runtime
The compiler does not include the runtime system (nor a reference to it) in the generated program; it must be supplied separately.
- file
Process file as a file name, even if it starts with a dash (-) character.
-help or --help
Display a short usage summary and exit.
#####
[](#sec363)Options for the 32-bit x86 architecture
The 32-bit code generator for Intel/AMD x86 processors (i386 architecture) supports the following additional option:
-ffast-math
Use the processor instructions to compute trigonometric and exponential functions, instead of calling the corresponding library routines. The functions affected are: atan, atan2, cos, log, log10, sin, sqrt and tan. The resulting code runs faster, but the range of supported arguments and the precision of the result can be reduced. In particular, trigonometric operations cos, sin, tan have their range reduced to [−264, 264].
#####
[](#sec364)Options for the 64-bit x86 architecture
The 64-bit code generator for Intel/AMD x86 processors (amd64 architecture) supports the following additional options:
-fPIC
Generate position-independent machine code. This is the default.
-fno-PIC
Generate position-dependent machine code.
#####
[](#sec365)Options for the PowerPC architecture
The PowerPC code generator supports the following additional options:
-flarge-toc
Enables the PowerPC large model allowing the TOC (table of contents) to be arbitrarily large. This is the default since 4.11.
-fsmall-toc
Enables the PowerPC small model allowing the TOC to be up to 64 kbytes per compilation unit. Prior to 4.11 this was the default behaviour.
#####
[](#sec366)Contextual control of command-line options
The compiler command line can be modified “from the outside” with the following mechanisms. These are experimental and subject to change. They should be used only for experimental and development work, not in released packages.
OCAMLPARAM (environment variable)
A set of arguments that will be inserted before or after the arguments from the command line. Arguments are specified in a comma-separated list of name=value pairs. A \_ is used to specify the position of the command line arguments, i.e. a=x,\_,b=y means that a=x should be executed before parsing the arguments, and b=y after. Finally, an alternative separator can be specified as the first character of the string, within the set :|; ,.
ocaml\_compiler\_internal\_params (file in the stdlib directory)
A mapping of file names to lists of arguments that will be added to the command line (and OCAMLPARAM) arguments.
OCAML\_FLEXLINK (environment variable)
Alternative executable to use on native Windows for flexlink instead of the configured value. Primarily used for bootstrapping.
[](#s:native-common-errors)16.3 Common errors
-----------------------------------------------
The error messages are almost identical to those of ocamlc. See section [13.4](comp#s%3Acomp-errors).
[](#s:native:running-executable)16.4 Running executables produced by ocamlopt
-------------------------------------------------------------------------------
Executables generated by ocamlopt are native, stand-alone executable files that can be invoked directly. They do not depend on the ocamlrun bytecode runtime system nor on dynamically-loaded C/OCaml stub libraries.
During execution of an ocamlopt-generated executable, the following environment variables are also consulted:
OCAMLRUNPARAM
Same usage as in ocamlrun (see section [15.2](runtime#s%3Aocamlrun-options)), except that option l is ignored (the operating system’s stack size limit is used instead).
CAMLRUNPARAM
If OCAMLRUNPARAM is not found in the environment, then CAMLRUNPARAM will be used instead. If CAMLRUNPARAM is not found, then the default values will be used.
[](#s:compat-native-bytecode)16.5 Compatibility with the bytecode compiler
----------------------------------------------------------------------------
This section lists the known incompatibilities between the bytecode compiler and the native-code compiler. Except on those points, the two compilers should generate code that behave identically.
* Signals are detected only when the program performs an allocation in the heap. That is, if a signal is delivered while in a piece of code that does not allocate, its handler will not be called until the next heap allocation.
* On ARM and PowerPC processors (32 and 64 bits), fused multiply-add (FMA) instructions can be generated for a floating-point multiplication followed by a floating-point addition or subtraction, as in x \*. y +. z. The FMA instruction avoids rounding the intermediate result x \*. y, which is generally beneficial, but produces floating-point results that differ slightly from those produced by the bytecode interpreter.
* On Intel/AMD x86 processors in 32-bit mode, some intermediate results in floating-point computations are kept in extended precision rather than being rounded to double precision like the bytecode compiler always does. Floating-point results can therefore differ slightly between bytecode and native code.
* The native-code compiler performs a number of optimizations that the bytecode compiler does not perform, especially when the Flambda optimizer is active. In particular, the native-code compiler identifies and eliminates “dead code”, i.e. computations that do not contribute to the results of the program. For example,
```
let _ = ignore M.f
```
contains a reference to compilation unit M when compiled to bytecode. This reference forces M to be linked and its initialization code to be executed. The native-code compiler eliminates the reference to M, hence the compilation unit M may not be linked and executed. A workaround is to compile M with the -linkall flag so that it will always be linked and executed, even if not referenced. See also the Sys.opaque\_identity function from the Sys standard library module.
* Before 4.10, stack overflows, typically caused by excessively deep recursion, are not always turned into a Stack\_overflow exception like with the bytecode compiler. The runtime system makes a best effort to trap stack overflows and raise the Stack\_overflow exception, but sometimes it fails and a “segmentation fault” or another system fault occurs instead.
| programming_docs |
ocaml None
[](#s:extension-nodes)12.13 Extension nodes
---------------------------------------------
* [12.13.1 Built-in extension nodes](extensionnodes#ss%3Abuiltin-extension-nodes)
(Introduced in OCaml 4.02, infix notations for constructs other than expressions added in 4.03, infix notation (e1 ;%ext e2) added in 4.04. )
Extension nodes are generic placeholders in the syntax tree. They are rejected by the type-checker and are intended to be “expanded” by external tools such as -ppx rewriters.
Extension nodes share the same notion of identifier and payload as attributes [12.12](attributes#s%3Aattributes).
The first form of extension node is used for “algebraic” categories:
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| extension | ::= | [% [attr-id](attributes#attr-id) [attr-payload](attributes#attr-payload) ] |
| |
| [expr](expr#expr) | ::= | ... |
| | ∣ | [extension](#extension) |
| |
| [typexpr](types#typexpr) | ::= | ... |
| | ∣ | [extension](#extension) |
| |
| [pattern](patterns#pattern) | ::= | ... |
| | ∣ | [extension](#extension) |
| |
| [module-expr](modules#module-expr) | ::= | ... |
| | ∣ | [extension](#extension) |
| |
| [module-type](modtypes#module-type) | ::= | ... |
| | ∣ | [extension](#extension) |
| |
| class-expr | ::= | ... |
| | ∣ | [extension](#extension) |
| |
| class-type | ::= | ... |
| | ∣ | [extension](#extension) |
| |
|
A second form of extension node can be used in structures and signatures, both in the module and object languages:
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| item-extension | ::= | [%% [attr-id](attributes#attr-id) [attr-payload](attributes#attr-payload) ] |
| |
| [definition](modules#definition) | ::= | ... |
| | ∣ | [item-extension](#item-extension) |
| |
| [specification](modtypes#specification) | ::= | ... |
| | ∣ | [item-extension](#item-extension) |
| |
| class-field-spec | ::= | ... |
| | ∣ | [item-extension](#item-extension) |
| |
| [class-field](classes#class-field) | ::= | ... |
| | ∣ | [item-extension](#item-extension) |
| |
|
An infix form is available for extension nodes when the payload is of the same kind (expression with expression, pattern with pattern ...).
Examples:
```
let%foo x = 2 in x + 1 === [%foo let x = 2 in x + 1]
begin%foo ... end === [%foo begin ... end]
x ;%foo 2 === [%foo x; 2]
module%foo M = .. === [%%foo module M = ... ]
val%foo x : t === [%%foo: val x : t]
```
When this form is used together with the infix syntax for attributes, the attributes are considered to apply to the payload:
```
fun%foo[@bar] x -> x + 1 === [%foo (fun x -> x + 1)[@bar ] ];
```
An additional shorthand let%foo x in ... is available for convenience when extension nodes are used to implement binding operators (See [12.23.1](bindingops#ss%3Aletops-punning)).
Furthermore, quoted strings {|...|} can be combined with extension nodes to embed foreign syntax fragments. Those fragments can be interpreted by a preprocessor and turned into OCaml code without requiring escaping quotes. A syntax shortcut is available for them:
```
{%%foo|...|} === [%%foo{|...|}]
let x = {%foo|...|} === let x = [%foo{|...|}]
let y = {%foo bar|...|bar} === let y = [%foo{bar|...|bar}]
```
For instance, you can use {%sql|...|} to represent arbitrary SQL statements – assuming you have a ppx-rewriter that recognizes the %sql extension.
Note that the word-delimited form, for example {sql|...|sql}, should not be used for signaling that an extension is in use. Indeed, the user cannot see from the code whether this string literal has different semantics than they expect. Moreover, giving semantics to a specific delimiter limits the freedom to change the delimiter to avoid escaping issues.
###
[](#ss:builtin-extension-nodes)12.13.1 Built-in extension nodes
(Introduced in OCaml 4.03)
Some extension nodes are understood by the compiler itself:
* “ocaml.extension\_constructor” or “extension\_constructor” take as payload a constructor from an extensible variant type (see [12.14](extensiblevariants#s%3Aextensible-variants)) and return its extension constructor slot.
```
type t = ..
type t += X of int | Y of string
let x = [%extension_constructor X]
let y = [%extension_constructor Y]
```
```
# x <> y;;
- : bool = true
```
ocaml None
[](#s:module-type-of)12.6 Recovering the type of a module
-----------------------------------------------------------
(Introduced in OCaml 3.12)
| | | | | | | |
| --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [module-type](modtypes#module-type) | ::= | ... |
| | ∣ | module type of [module-expr](modules#module-expr) |
|
The construction module type of [module-expr](modules#module-expr) expands to the module type (signature or functor type) inferred for the module expression [module-expr](modules#module-expr). To make this module type reusable in many situations, it is intentionally not strengthened: abstract types and datatypes are not explicitly related with the types of the original module. For the same reason, module aliases in the inferred type are expanded.
A typical use, in conjunction with the signature-level include construct, is to extend the signature of an existing structure. In that case, one wants to keep the types equal to types in the original module. This can done using the following idiom.
```
module type MYHASH = sig
include module type of struct include Hashtbl end
val replace: ('a, 'b) t -> 'a -> 'b -> unit
end
```
The signature MYHASH then contains all the fields of the signature of the module Hashtbl (with strengthened type definitions), plus the new field replace. An implementation of this signature can be obtained easily by using the include construct again, but this time at the structure level:
```
module MyHash : MYHASH = struct
include Hashtbl
let replace t k v = remove t k; add t k v
end
```
Another application where the absence of strengthening comes handy, is to provide an alternative implementation for an existing module.
```
module MySet : module type of Set = struct
…
end
```
This idiom guarantees that Myset is compatible with Set, but allows it to represent sets internally in a different way.
ocaml None
[](#s:recursive-modules)12.2 Recursive modules
------------------------------------------------
(Introduced in Objective Caml 3.07)
| | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [definition](modules#definition) | ::= | ... |
| | ∣ | module rec [module-name](names#module-name) : [module-type](modtypes#module-type) = [module-expr](modules#module-expr) { and [module-name](names#module-name) : [module-type](modtypes#module-type) = [module-expr](modules#module-expr) } |
| |
| [specification](modtypes#specification) | ::= | ... |
| | ∣ | module rec [module-name](names#module-name) : [module-type](modtypes#module-type) { and [module-name](names#module-name): [module-type](modtypes#module-type) } |
|
Recursive module definitions, introduced by the module rec …and … construction, generalize regular module definitions module [module-name](names#module-name) = [module-expr](modules#module-expr) and module specifications module [module-name](names#module-name) : [module-type](modtypes#module-type) by allowing the defining [module-expr](modules#module-expr) and the [module-type](modtypes#module-type) to refer recursively to the module identifiers being defined. A typical example of a recursive module definition is:
```
module rec A : sig
type t = Leaf of string | Node of ASet.t
val compare: t -> t -> int
end = struct
type t = Leaf of string | Node of ASet.t
let compare t1 t2 =
match (t1, t2) with
| (Leaf s1, Leaf s2) -> Stdlib.compare s1 s2
| (Leaf _, Node _) -> 1
| (Node _, Leaf _) -> -1
| (Node n1, Node n2) -> ASet.compare n1 n2
end
and ASet
: Set.S with type elt = A.t
= Set.Make(A)
```
It can be given the following specification:
```
module rec A : sig
type t = Leaf of string | Node of ASet.t
val compare: t -> t -> int
end
and ASet : Set.S with type elt = A.t
```
This is an experimental extension of OCaml: the class of recursive definitions accepted, as well as its dynamic semantics are not final and subject to change in future releases.
Currently, the compiler requires that all dependency cycles between the recursively-defined module identifiers go through at least one “safe” module. A module is “safe” if all value definitions that it contains have function types [typexpr](types#typexpr)1 -> [typexpr](types#typexpr)2. Evaluation of a recursive module definition proceeds by building initial values for the safe modules involved, binding all (functional) values to fun \_ -> raise Undefined\_recursive\_module. The defining module expressions are then evaluated, and the initial values for the safe modules are replaced by the values thus computed. If a function component of a safe module is applied during this computation (which corresponds to an ill-founded recursive definition), the Undefined\_recursive\_module exception is raised at runtime:
```
module rec M: sig val f: unit -> int end = struct let f () = N.x end
and N:sig val x: int end = struct let x = M.f () end
Exception:
Undefined_recursive_module ("extensions/recursivemodules.etex", 1, 43).
```
If there are no safe modules along a dependency cycle, an error is raised
```
module rec M: sig val x: int end = struct let x = N.y end
and N:sig val x: int val y:int end = struct let x = M.x let y = 0 end
Error: Cannot safely evaluate the definition of the following cycle
of recursively-defined modules: M -> N -> M.
There are no safe modules in this cycle (see manual section 12.2).
Module M defines an unsafe value, x .
Module N defines an unsafe value, x .
```
Note that, in the [specification](modtypes#specification) case, the [module-type](modtypes#module-type)s must be parenthesized if they use the with [mod-constraint](modtypes#mod-constraint) construct.
ocaml Chapter 18 Dependency generator (ocamldep) Chapter 18 Dependency generator (ocamldep)
==========================================
* [18.1 Options](depend#s%3Aocamldep-options)
* [18.2 A typical Makefile](depend#s%3Aocamldep-makefile)
The ocamldep command scans a set of OCaml source files (.ml and .mli files) for references to external compilation units, and outputs dependency lines in a format suitable for the make utility. This ensures that make will compile the source files in the correct order, and recompile those files that need to when a source file is modified.
The typical usage is:
```
ocamldep options *.mli *.ml > .depend
```
where \*.mli \*.ml expands to all source files in the current directory and .depend is the file that should contain the dependencies. (See below for a typical Makefile.)
Dependencies are generated both for compiling with the bytecode compiler ocamlc and with the native-code compiler ocamlopt.
[](#s:ocamldep-options)18.1 Options
-------------------------------------
The following command-line options are recognized by ocamldep.
-absname
Show absolute filenames in error messages.
-all
Generate dependencies on all required files, rather than assuming implicit dependencies.
-allow-approx
Allow falling back on a lexer-based approximation when parsing fails.
-args filename
Read additional newline-terminated command line arguments from filename.
-args0 filename
Read additional null character terminated command line arguments from filename.
-as-map
For the following files, do not include delayed dependencies for module aliases. This option assumes that they are compiled using options -no-alias-deps -w -49, and that those files or their interface are passed with the -map option when computing dependencies for other files. Note also that for dependencies to be correct in the implementation of a map file, its interface should not coerce any of the aliases it contains.
-debug-map
Dump the delayed dependency map for each map file.
-I directory
Add the given directory to the list of directories searched for source files. If a source file foo.ml mentions an external compilation unit Bar, a dependency on that unit’s interface bar.cmi is generated only if the source for bar is found in the current directory or in one of the directories specified with -I. Otherwise, Bar is assumed to be a module from the standard library, and no dependencies are generated. For programs that span multiple directories, it is recommended to pass ocamldep the same -I options that are passed to the compiler.
-nocwd
Do not add current working directory to the list of include directories.
-impl file
Process file as a .ml file.
-intf file
Process file as a .mli file.
-map file
Read and propagate the delayed dependencies for module aliases in file, so that the following files will depend on the exported aliased modules if they use them. See the example below.
-ml-synonym .ext
Consider the given extension (with leading dot) to be a synonym for .ml.
-mli-synonym .ext
Consider the given extension (with leading dot) to be a synonym for .mli.
-modules
Output raw dependencies of the form
```
filename: Module1 Module2 ... ModuleN
```
where Module1, …, ModuleN are the names of the compilation units referenced within the file filename, but these names are not resolved to source file names. Such raw dependencies cannot be used by make, but can be post-processed by other tools such as Omake.
-native
Generate dependencies for a pure native-code program (no bytecode version). When an implementation file (.ml file) has no explicit interface file (.mli file), ocamldep generates dependencies on the bytecode compiled file (.cmo file) to reflect interface changes. This can cause unnecessary bytecode recompilations for programs that are compiled to native-code only. The flag -native causes dependencies on native compiled files (.cmx) to be generated instead of on .cmo files. (This flag makes no difference if all source files have explicit .mli interface files.)
-one-line
Output one line per file, regardless of the length.
-open module
Assume that module module is opened before parsing each of the following files.
-pp command
Cause ocamldep to call the given command as a preprocessor for each source file.
-ppx command
Pipe abstract syntax trees through preprocessor command.
-shared
Generate dependencies for native plugin files (.cmxs) in addition to native compiled files (.cmx).
-slash
Under Windows, use a forward slash (/) as the path separator instead of the usual backward slash (\). Under Unix, this option does nothing.
-sort
Sort files according to their dependencies.
-version
Print version string and exit.
-vnum
Print short version number and exit.
-help or --help
Display a short usage summary and exit.
[](#s:ocamldep-makefile)18.2 A typical Makefile
-------------------------------------------------
Here is a template Makefile for a OCaml program.
```
OCAMLC=ocamlc
OCAMLOPT=ocamlopt
OCAMLDEP=ocamldep
INCLUDES= # all relevant -I options here
OCAMLFLAGS=$(INCLUDES) # add other options for ocamlc here
OCAMLOPTFLAGS=$(INCLUDES) # add other options for ocamlopt here
# prog1 should be compiled to bytecode, and is composed of three
# units: mod1, mod2 and mod3.
# The list of object files for prog1
PROG1_OBJS=mod1.cmo mod2.cmo mod3.cmo
prog1: $(PROG1_OBJS)
$(OCAMLC) -o prog1 $(OCAMLFLAGS) $(PROG1_OBJS)
# prog2 should be compiled to native-code, and is composed of two
# units: mod4 and mod5.
# The list of object files for prog2
PROG2_OBJS=mod4.cmx mod5.cmx
prog2: $(PROG2_OBJS)
$(OCAMLOPT) -o prog2 $(OCAMLFLAGS) $(PROG2_OBJS)
# Common rules
%.cmo: %.ml
$(OCAMLC) $(OCAMLFLAGS) -c $<
%.cmi: %.mli
$(OCAMLC) $(OCAMLFLAGS) -c $<
%.cmx: %.ml
$(OCAMLOPT) $(OCAMLOPTFLAGS) -c $<
# Clean up
clean:
rm -f prog1 prog2
rm -f *.cm[iox]
# Dependencies
depend:
$(OCAMLDEP) $(INCLUDES) *.mli *.ml > .depend
include .depend
```
If you use module aliases to give shorter names to modules, you need to change the above definitions. Assuming that your map file is called mylib.mli, here are minimal modifications.
```
OCAMLFLAGS=$(INCLUDES) -open Mylib
mylib.cmi: mylib.mli
$(OCAMLC) $(INCLUDES) -no-alias-deps -w -49 -c $<
depend:
$(OCAMLDEP) $(INCLUDES) -map mylib.mli $(PROG1_OBJS:.cmo=.ml) > .depend
```
Note that in this case you should not compute dependencies for mylib.mli together with the other files, hence the need to pass explicitly the list of files to process. If mylib.mli itself has dependencies, you should compute them using -as-map.
ocaml None
[](#s:explicit-overriding-open)12.9 Overriding in open statements
-------------------------------------------------------------------
(Introduced in OCaml 4.01)
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [definition](modules#definition) | ::= | ... |
| | ∣ | open! [module-path](names#module-path) |
| |
| [specification](modtypes#specification) | ::= | ... |
| | ∣ | open! [module-path](names#module-path) |
| |
| [expr](expr#expr) | ::= | ... |
| | ∣ | let open! [module-path](names#module-path) in [expr](expr#expr) |
| |
| class-body-type | ::= | ... |
| | ∣ | let open! [module-path](names#module-path) in [class-body-type](classes#class-body-type) |
| |
| class-expr | ::= | ... |
| | ∣ | let open! [module-path](names#module-path) in [class-expr](classes#class-expr) |
| |
|
Since OCaml 4.01, open statements shadowing an existing identifier (which is later used) trigger the warning 44. Adding a ! character after the open keyword indicates that such a shadowing is intentional and should not trigger the warning.
This is also available (since OCaml 4.06) for local opens in class expressions and class type expressions.
ocaml Chapter 17 Lexer and parser generators (ocamllex, ocamlyacc) Chapter 17 Lexer and parser generators (ocamllex, ocamlyacc)
============================================================
* [17.1 Overview of ocamllex](lexyacc#s%3Aocamllex-overview)
* [17.2 Syntax of lexer definitions](lexyacc#s%3Aocamllex-syntax)
* [17.3 Overview of ocamlyacc](lexyacc#s%3Aocamlyacc-overview)
* [17.4 Syntax of grammar definitions](lexyacc#s%3Aocamlyacc-syntax)
* [17.5 Options](lexyacc#s%3Aocamlyacc-options)
* [17.6 A complete example](lexyacc#s%3Alexyacc-example)
* [17.7 Common errors](lexyacc#s%3Alexyacc-common-errors)
This chapter describes two program generators: ocamllex, that produces a lexical analyzer from a set of regular expressions with associated semantic actions, and ocamlyacc, that produces a parser from a grammar with associated semantic actions.
These program generators are very close to the well-known lex and yacc commands that can be found in most C programming environments. This chapter assumes a working knowledge of lex and yacc: while it describes the input syntax for ocamllex and ocamlyacc and the main differences with lex and yacc, it does not explain the basics of writing a lexer or parser description in lex and yacc. Readers unfamiliar with lex and yacc are referred to “Compilers: principles, techniques, and tools” by Aho, Lam, Sethi and Ullman (Pearson, 2006), or “Lex & Yacc”, by Levine, Mason and Brown (O’Reilly, 1992).
[](#s:ocamllex-overview)17.1 Overview of ocamllex
---------------------------------------------------
The ocamllex command produces a lexical analyzer from a set of regular expressions with attached semantic actions, in the style of lex. Assuming the input file is lexer.mll, executing
```
ocamllex lexer.mll
```
produces OCaml code for a lexical analyzer in file lexer.ml. This file defines one lexing function per entry point in the lexer definition. These functions have the same names as the entry points. Lexing functions take as argument a lexer buffer, and return the semantic attribute of the corresponding entry point.
Lexer buffers are an abstract data type implemented in the standard library module Lexing. The functions Lexing.from\_channel, Lexing.from\_string and Lexing.from\_function create lexer buffers that read from an input channel, a character string, or any reading function, respectively. (See the description of module Lexing in chapter [28](stdlib#c%3Astdlib).)
When used in conjunction with a parser generated by ocamlyacc, the semantic actions compute a value belonging to the type token defined by the generated parsing module. (See the description of ocamlyacc below.)
###
[](#ss:ocamllex-options)17.1.1 Options
The following command-line options are recognized by ocamllex.
-ml
Output code that does not use OCaml’s built-in automata interpreter. Instead, the automaton is encoded by OCaml functions. This option improves performance when using the native compiler, but decreases it when using the bytecode compiler.
-o output-file
Specify the name of the output file produced by ocamllex. The default is the input file name with its extension replaced by .ml.
-q
Quiet mode. ocamllex normally outputs informational messages to standard output. They are suppressed if option -q is used.
-v or -version
Print version string and exit.
-vnum
Print short version number and exit.
-help or --help
Display a short usage summary and exit.
[](#s:ocamllex-syntax)17.2 Syntax of lexer definitions
--------------------------------------------------------
The format of lexer definitions is as follows:
```
{ header }
let ident = regexp …
[refill { refill-handler }]
rule entrypoint [arg1… argn] =
parse regexp { action }
| …
| regexp { action }
and entrypoint [arg1… argn] =
parse …
and …
{ trailer }
```
Comments are delimited by (\* and \*), as in OCaml. The parse keyword, can be replaced by the shortest keyword, with the semantic consequences explained below.
Refill handlers are a recent (optional) feature introduced in 4.02, documented below in subsection [17.2.7](#ss%3Arefill-handlers).
###
[](#ss:ocamllex-header-trailer)17.2.1 Header and trailer
The header and trailer sections are arbitrary OCaml text enclosed in curly braces. Either or both can be omitted. If present, the header text is copied as is at the beginning of the output file and the trailer text at the end. Typically, the header section contains the open directives required by the actions, and possibly some auxiliary functions used in the actions.
###
[](#ss:ocamllex-named-regexp)17.2.2 Naming regular expressions
Between the header and the entry points, one can give names to frequently-occurring regular expressions. This is written let [ident](lex#ident) = [regexp](#regexp). In regular expressions that follow this declaration, the identifier ident can be used as shorthand for regexp.
###
[](#ss:ocamllex-entry-points)17.2.3 Entry points
The names of the entry points must be valid identifiers for OCaml values (starting with a lowercase letter). Similarly, the arguments arg1… argn must be valid identifiers for OCaml. Each entry point becomes an OCaml function that takes n+1 arguments, the extra implicit last argument being of type Lexing.lexbuf. Characters are read from the Lexing.lexbuf argument and matched against the regular expressions provided in the rule, until a prefix of the input matches one of the rule. The corresponding action is then evaluated and returned as the result of the function.
If several regular expressions match a prefix of the input, the “longest match” rule applies: the regular expression that matches the longest prefix of the input is selected. In case of tie, the regular expression that occurs earlier in the rule is selected.
However, if lexer rules are introduced with the shortest keyword in place of the parse keyword, then the “shortest match” rule applies: the shortest prefix of the input is selected. In case of tie, the regular expression that occurs earlier in the rule is still selected. This feature is not intended for use in ordinary lexical analyzers, it may facilitate the use of ocamllex as a simple text processing tool.
###
[](#ss:ocamllex-regexp)17.2.4 Regular expressions
The regular expressions are in the style of lex, with a more OCaml-like syntax.
| | | | |
| --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| regexp | ::= | … |
|
' regular-char ∣ [escape-sequence](lex#escape-sequence) '
A character constant, with the same syntax as OCaml character constants. Match the denoted character.
\_
(underscore) Match any character.
eof
Match the end of the lexer input.
Note: On some systems, with interactive input, an end-of-file may be followed by more characters. However, ocamllex will not correctly handle regular expressions that contain eof followed by something else.
" { [string-character](lex#string-character) } "
A string constant, with the same syntax as OCaml string constants. Match the corresponding sequence of characters.
[ character-set ]
Match any single character belonging to the given character set. Valid character sets are: single character constants ' c '; ranges of characters ' c1 ' - ' c2 ' (all characters between c1 and c2, inclusive); and the union of two or more character sets, denoted by concatenation.
[ ^ character-set ]
Match any single character not belonging to the given character set.
[regexp](#regexp)1 # [regexp](#regexp)2
(difference of character sets) Regular expressions [regexp](#regexp)1 and [regexp](#regexp)2 must be character sets defined with [… ] (or a single character expression or underscore \_). Match the difference of the two specified character sets.
[regexp](#regexp) \*
(repetition) Match the concatenation of zero or more strings that match [regexp](#regexp).
[regexp](#regexp) +
(strict repetition) Match the concatenation of one or more strings that match [regexp](#regexp).
[regexp](#regexp) ?
(option) Match the empty string, or a string matching [regexp](#regexp).
[regexp](#regexp)1 | [regexp](#regexp)2
(alternative) Match any string that matches [regexp](#regexp)1 or [regexp](#regexp)2
[regexp](#regexp)1 [regexp](#regexp)2
(concatenation) Match the concatenation of two strings, the first matching [regexp](#regexp)1, the second matching [regexp](#regexp)2.
( [regexp](#regexp) )
Match the same strings as [regexp](#regexp).
[ident](lex#ident)
Reference the regular expression bound to [ident](lex#ident) by an earlier let [ident](lex#ident) = [regexp](#regexp) definition.
[regexp](#regexp) as [ident](lex#ident)
Bind the substring matched by [regexp](#regexp) to identifier [ident](lex#ident).
Concerning the precedences of operators, # has the highest precedence, followed by \*, + and ?, then concatenation, then | (alternation), then as.
###
[](#ss:ocamllex-actions)17.2.5 Actions
The actions are arbitrary OCaml expressions. They are evaluated in a context where the identifiers defined by using the as construct are bound to subparts of the matched string. Additionally, lexbuf is bound to the current lexer buffer. Some typical uses for lexbuf, in conjunction with the operations on lexer buffers provided by the Lexing standard library module, are listed below.
Lexing.lexeme lexbuf
Return the matched string.
Lexing.lexeme\_char lexbuf n
Return the nth character in the matched string. The first character corresponds to n = 0.
Lexing.lexeme\_start lexbuf
Return the absolute position in the input text of the beginning of the matched string (i.e. the offset of the first character of the matched string). The first character read from the input text has offset 0.
Lexing.lexeme\_end lexbuf
Return the absolute position in the input text of the end of the matched string (i.e. the offset of the first character after the matched string). The first character read from the input text has offset 0.
entrypoint [exp1… expn] lexbuf
(Where entrypoint is the name of another entry point in the same lexer definition.) Recursively call the lexer on the given entry point. Notice that lexbuf is the last argument. Useful for lexing nested comments, for example.
###
[](#ss:ocamllex-variables)17.2.6 Variables in regular expressions
The as construct is similar to “*groups*” as provided by numerous regular expression packages. The type of these variables can be string, char, string option or char option.
We first consider the case of linear patterns, that is the case when all as bound variables are distinct. In [regexp](#regexp) as [ident](lex#ident), the type of [ident](lex#ident) normally is string (or string option) except when [regexp](#regexp) is a character constant, an underscore, a string constant of length one, a character set specification, or an alternation of those. Then, the type of [ident](lex#ident) is char (or char option). Option types are introduced when overall rule matching does not imply matching of the bound sub-pattern. This is in particular the case of ( [regexp](#regexp) as [ident](lex#ident) ) ? and of [regexp](#regexp)1 | ( [regexp](#regexp)2 as [ident](lex#ident) ).
There is no linearity restriction over as bound variables. When a variable is bound more than once, the previous rules are to be extended as follows:
* A variable is a char variable when all its occurrences bind char occurrences in the previous sense.
* A variable is an option variable when the overall expression can be matched without binding this variable.
For instance, in ('a' as x) | ( 'a' (\_ as x) ) the variable x is of type char, whereas in ("ab" as x) | ( 'a' (\_ as x) ? ) the variable x is of type string option.
In some cases, a successful match may not yield a unique set of bindings. For instance the matching of `aba` by the regular expression (('a'|"ab") as x) (("ba"|'a') as y) may result in binding either `x` to `"ab"` and `y` to `"a"`, or `x` to `"a"` and `y` to `"ba"`. The automata produced ocamllex on such ambiguous regular expressions will select one of the possible resulting sets of bindings. The selected set of bindings is purposely left unspecified.
###
[](#ss:refill-handlers)17.2.7 Refill handlers
By default, when ocamllex reaches the end of its lexing buffer, it will silently call the refill\_buff function of lexbuf structure and continue lexing. It is sometimes useful to be able to take control of refilling action; typically, if you use a library for asynchronous computation, you may want to wrap the refilling action in a delaying function to avoid blocking synchronous operations.
Since OCaml 4.02, it is possible to specify a refill-handler, a function that will be called when refill happens. It is passed the continuation of the lexing, on which it has total control. The OCaml expression used as refill action should have a type that is an instance of
```
(Lexing.lexbuf -> 'a) -> Lexing.lexbuf -> 'a
```
where the first argument is the continuation which captures the processing ocamllex would usually perform (refilling the buffer, then calling the lexing function again), and the result type that instantiates [’a] should unify with the result type of all lexing rules.
As an example, consider the following lexer that is parametrized over an arbitrary monad:
```
{
type token = EOL | INT of int | PLUS
module Make (M : sig
type 'a t
val return: 'a -> 'a t
val bind: 'a t -> ('a -> 'b t) -> 'b t
val fail : string -> 'a t
(* Set up lexbuf *)
val on_refill : Lexing.lexbuf -> unit t
end)
= struct
let refill_handler k lexbuf =
M.bind (M.on_refill lexbuf) (fun () -> k lexbuf)
}
refill {refill_handler}
rule token = parse
| [' ' '\t']
{ token lexbuf }
| '\n'
{ M.return EOL }
| ['0'-'9']+ as i
{ M.return (INT (int_of_string i)) }
| '+'
{ M.return PLUS }
| _
{ M.fail "unexpected character" }
{
end
}
```
###
[](#ss:ocamllex-reserved-ident)17.2.8 Reserved identifiers
All identifiers starting with \_\_ocaml\_lex are reserved for use by ocamllex; do not use any such identifier in your programs.
[](#s:ocamlyacc-overview)17.3 Overview of ocamlyacc
-----------------------------------------------------
The ocamlyacc command produces a parser from a context-free grammar specification with attached semantic actions, in the style of yacc. Assuming the input file is grammar.mly, executing
```
ocamlyacc options grammar.mly
```
produces OCaml code for a parser in the file grammar.ml, and its interface in file grammar.mli.
The generated module defines one parsing function per entry point in the grammar. These functions have the same names as the entry points. Parsing functions take as arguments a lexical analyzer (a function from lexer buffers to tokens) and a lexer buffer, and return the semantic attribute of the corresponding entry point. Lexical analyzer functions are usually generated from a lexer specification by the ocamllex program. Lexer buffers are an abstract data type implemented in the standard library module Lexing. Tokens are values from the concrete type token, defined in the interface file grammar.mli produced by ocamlyacc.
[](#s:ocamlyacc-syntax)17.4 Syntax of grammar definitions
-----------------------------------------------------------
Grammar definitions have the following format:
```
%{
header
%}
declarations
%%
rules
%%
trailer
```
Comments are enclosed between `/*` and `*/` (as in C) in the “declarations” and “rules” sections, and between `(*` and `*)` (as in OCaml) in the “header” and “trailer” sections.
###
[](#ss:ocamlyacc-header-trailer)17.4.1 Header and trailer
The header and the trailer sections are OCaml code that is copied as is into file grammar.ml. Both sections are optional. The header goes at the beginning of the output file; it usually contains open directives and auxiliary functions required by the semantic actions of the rules. The trailer goes at the end of the output file.
###
[](#ss:ocamlyacc-declarations)17.4.2 Declarations
Declarations are given one per line. They all start with a `%` sign.
%token [constr](names#constr) … [constr](names#constr)
Declare the given symbols [constr](names#constr) … [constr](names#constr) as tokens (terminal symbols). These symbols are added as constant constructors for the token concrete type.
%token < [typexpr](types#typexpr) > [constr](names#constr) … [constr](names#constr)
Declare the given symbols [constr](names#constr) … [constr](names#constr) as tokens with an attached attribute of the given type. These symbols are added as constructors with arguments of the given type for the token concrete type. The [typexpr](types#typexpr) part is an arbitrary OCaml type expression, except that all type constructor names must be fully qualified (e.g. Modname.typename) for all types except standard built-in types, even if the proper `open` directives (e.g. `open Modname`) were given in the header section. That’s because the header is copied only to the .ml output file, but not to the .mli output file, while the [typexpr](types#typexpr) part of a `%token` declaration is copied to both.
%start symbol … symbol
Declare the given symbols as entry points for the grammar. For each entry point, a parsing function with the same name is defined in the output module. Non-terminals that are not declared as entry points have no such parsing function. Start symbols must be given a type with the `%type` directive below.
%type < [typexpr](types#typexpr) > symbol … symbol
Specify the type of the semantic attributes for the given symbols. This is mandatory for start symbols only. Other nonterminal symbols need not be given types by hand: these types will be inferred when running the output files through the OCaml compiler (unless the `-s` option is in effect). The [typexpr](types#typexpr) part is an arbitrary OCaml type expression, except that all type constructor names must be fully qualified, as explained above for %token.
%left symbol … symbol
%right symbol … symbol
%nonassoc symbol … symbol
Associate precedences and associativities to the given symbols. All symbols on the same line are given the same precedence. They have higher precedence than symbols declared before in a `%left`, `%right` or `%nonassoc` line. They have lower precedence than symbols declared after in a `%left`, `%right` or `%nonassoc` line. The symbols are declared to associate to the left (`%left`), to the right (`%right`), or to be non-associative (`%nonassoc`). The symbols are usually tokens. They can also be dummy nonterminals, for use with the `%prec` directive inside the rules.
The precedence declarations are used in the following way to resolve reduce/reduce and shift/reduce conflicts:
* Tokens and rules have precedences. By default, the precedence of a rule is the precedence of its rightmost terminal. You can override this default by using the %prec directive in the rule.
* A reduce/reduce conflict is resolved in favor of the first rule (in the order given by the source file), and ocamlyacc outputs a warning.
* A shift/reduce conflict is resolved by comparing the precedence of the rule to be reduced with the precedence of the token to be shifted. If the precedence of the rule is higher, then the rule will be reduced; if the precedence of the token is higher, then the token will be shifted.
* A shift/reduce conflict between a rule and a token with the same precedence will be resolved using the associativity: if the token is left-associative, then the parser will reduce; if the token is right-associative, then the parser will shift. If the token is non-associative, then the parser will declare a syntax error.
* When a shift/reduce conflict cannot be resolved using the above method, then ocamlyacc will output a warning and the parser will always shift.
###
[](#ss:ocamlyacc-rules)17.4.3 Rules
The syntax for rules is as usual:
```
nonterminal :
symbol … symbol { semantic-action }
| …
| symbol … symbol { semantic-action }
;
```
Rules can also contain the `%prec` symbol directive in the right-hand side part, to override the default precedence and associativity of the rule with the precedence and associativity of the given symbol.
Semantic actions are arbitrary OCaml expressions, that are evaluated to produce the semantic attribute attached to the defined nonterminal. The semantic actions can access the semantic attributes of the symbols in the right-hand side of the rule with the `$` notation: `$1` is the attribute for the first (leftmost) symbol, `$2` is the attribute for the second symbol, etc.
The rules may contain the special symbol error to indicate resynchronization points, as in yacc.
Actions occurring in the middle of rules are not supported.
Nonterminal symbols are like regular OCaml symbols, except that they cannot end with ' (single quote).
###
[](#ss:ocamlyacc-error-handling)17.4.4 Error handling
Error recovery is supported as follows: when the parser reaches an error state (no grammar rules can apply), it calls a function named parse\_error with the string "syntax error" as argument. The default parse\_error function does nothing and returns, thus initiating error recovery (see below). The user can define a customized parse\_error function in the header section of the grammar file.
The parser also enters error recovery mode if one of the grammar actions raises the Parsing.Parse\_error exception.
In error recovery mode, the parser discards states from the stack until it reaches a place where the error token can be shifted. It then discards tokens from the input until it finds three successive tokens that can be accepted, and starts processing with the first of these. If no state can be uncovered where the error token can be shifted, then the parser aborts by raising the Parsing.Parse\_error exception.
Refer to documentation on yacc for more details and guidance in how to use error recovery.
[](#s:ocamlyacc-options)17.5 Options
--------------------------------------
The ocamlyacc command recognizes the following options:
-bprefix
Name the output files prefix.ml, prefix.mli, prefix.output, instead of the default naming convention.
-q
This option has no effect.
-v
Generate a description of the parsing tables and a report on conflicts resulting from ambiguities in the grammar. The description is put in file grammar.output.
-version
Print version string and exit.
-vnum
Print short version number and exit.
-
Read the grammar specification from standard input. The default output file names are stdin.ml and stdin.mli.
-- file
Process file as the grammar specification, even if its name starts with a dash (-) character. This option must be the last on the command line.
At run-time, the ocamlyacc-generated parser can be debugged by setting the p option in the OCAMLRUNPARAM environment variable (see section [15.2](runtime#s%3Aocamlrun-options)). This causes the pushdown automaton executing the parser to print a trace of its action (tokens shifted, rules reduced, etc). The trace mentions rule numbers and state numbers that can be interpreted by looking at the file grammar.output generated by ocamlyacc -v.
[](#s:lexyacc-example)17.6 A complete example
-----------------------------------------------
The all-time favorite: a desk calculator. This program reads arithmetic expressions on standard input, one per line, and prints their values. Here is the grammar definition:
```
/* File parser.mly */
%token <int> INT
%token PLUS MINUS TIMES DIV
%token LPAREN RPAREN
%token EOL
%left PLUS MINUS /* lowest precedence */
%left TIMES DIV /* medium precedence */
%nonassoc UMINUS /* highest precedence */
%start main /* the entry point */
%type <int> main
%%
main:
expr EOL { $1 }
;
expr:
INT { $1 }
| LPAREN expr RPAREN { $2 }
| expr PLUS expr { $1 + $3 }
| expr MINUS expr { $1 - $3 }
| expr TIMES expr { $1 * $3 }
| expr DIV expr { $1 / $3 }
| MINUS expr %prec UMINUS { - $2 }
;
```
Here is the definition for the corresponding lexer:
```
(* File lexer.mll *)
{
open Parser (* The type token is defined in parser.mli *)
exception Eof
}
rule token = parse
[' ' '\t'] { token lexbuf } (* skip blanks *)
| ['\n' ] { EOL }
| ['0'-'9']+ as lxm { INT(int_of_string lxm) }
| '+' { PLUS }
| '-' { MINUS }
| '*' { TIMES }
| '/' { DIV }
| '(' { LPAREN }
| ')' { RPAREN }
| eof { raise Eof }
```
Here is the main program, that combines the parser with the lexer:
```
(* File calc.ml *)
let _ =
try
let lexbuf = Lexing.from_channel stdin in
while true do
let result = Parser.main Lexer.token lexbuf in
print_int result; print_newline(); flush stdout
done
with Lexer.Eof ->
exit 0
```
To compile everything, execute:
```
ocamllex lexer.mll # generates lexer.ml
ocamlyacc parser.mly # generates parser.ml and parser.mli
ocamlc -c parser.mli
ocamlc -c lexer.ml
ocamlc -c parser.ml
ocamlc -c calc.ml
ocamlc -o calc lexer.cmo parser.cmo calc.cmo
```
[](#s:lexyacc-common-errors)17.7 Common errors
------------------------------------------------
ocamllex: transition table overflow, automaton is too big
The deterministic automata generated by ocamllex are limited to at most 32767 transitions. The message above indicates that your lexer definition is too complex and overflows this limit. This is commonly caused by lexer definitions that have separate rules for each of the alphabetic keywords of the language, as in the following example.
```
rule token = parse
"keyword1" { KWD1 }
| "keyword2" { KWD2 }
| ...
| "keyword100" { KWD100 }
| ['A'-'Z' 'a'-'z'] ['A'-'Z' 'a'-'z' '0'-'9' '_'] * as id
{ IDENT id}
```
To keep the generated automata small, rewrite those definitions with only one general “identifier” rule, followed by a hashtable lookup to separate keywords from identifiers:
```
{ let keyword_table = Hashtbl.create 53
let _ =
List.iter (fun (kwd, tok) -> Hashtbl.add keyword_table kwd tok)
[ "keyword1", KWD1;
"keyword2", KWD2; ...
"keyword100", KWD100 ]
}
rule token = parse
['A'-'Z' 'a'-'z'] ['A'-'Z' 'a'-'z' '0'-'9' '_'] * as id
{ try
Hashtbl.find keyword_table id
with Not_found ->
IDENT id }
```
ocamllex: Position memory overflow, too many bindings
The deterministic automata generated by ocamllex maintain a table of positions inside the scanned lexer buffer. The size of this table is limited to at most 255 cells. This error should not show up in normal situations.
ocamlyacc: concurrency safety
Parsers generated by ocamlyacc are not thread-safe. Those parsers rely on an internal work state which is shared by all ocamlyacc generated parsers. The [menhir](https://cambium.inria.fr/~fpottier/menhir/) parser generator is a better option if you want thread-safe parsers.
| programming_docs |
ocaml None
[](#s:index-operators)12.19 Extended indexing operators
---------------------------------------------------------
* [12.19.1 Multi-index notation](indexops#ss%3Amultiindexing)
(Introduced in 4.06)
| | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| dot-ext | ::= | |
| | ∣ | [dot-operator-char](#dot-operator-char) { [operator-char](lex#operator-char) } |
| |
| dot-operator-char | ::= | ! ∣ ? ∣ [core-operator-char](lex#core-operator-char) ∣ % ∣ : |
| |
| [expr](expr#expr) | ::= | ... |
| | ∣ | [expr](expr#expr) . [[module-path](names#module-path) .] [dot-ext](#dot-ext) ( ( [expr](expr#expr) ) ∣ [ [expr](expr#expr) ] ∣ { [expr](expr#expr) } ) [ <- [expr](expr#expr) ] |
| |
| operator-name | ::= | ... |
| | ∣ | . [dot-ext](#dot-ext) (() ∣ [] ∣ {}) [<-] |
| |
|
This extension provides syntactic sugar for getting and setting elements for user-defined indexed types. For instance, we can define python-like dictionaries with
```
module Dict = struct
include Hashtbl
let ( .%{} ) tabl index = find tabl index
let ( .%{}<- ) tabl index value = add tabl index value
end
let dict =
let dict = Dict.create 10 in
let () =
dict.Dict.%{"one"} <- 1;
let open Dict in
dict.%{"two"} <- 2 in
dict
```
```
# dict.Dict.%{"one"};;
- : int = 1
```
```
# let open Dict in dict.%{"two"};;
- : int = 2
```
###
[](#ss:multiindexing)12.19.1 Multi-index notation
| | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [expr](expr#expr) | ::= | ... |
| | ∣ | [expr](expr#expr) . [[module-path](names#module-path) .] [dot-ext](#dot-ext) ( [expr](expr#expr) { ; [expr](expr#expr) }+ ) [ <- [expr](expr#expr) ] |
| | ∣ | [expr](expr#expr) . [[module-path](names#module-path) .] [dot-ext](#dot-ext) [ [expr](expr#expr) { ; [expr](expr#expr) }+ ] [ <- [expr](expr#expr) ] |
| | ∣ | [expr](expr#expr) . [[module-path](names#module-path) .] [dot-ext](#dot-ext) { [expr](expr#expr) { ; [expr](expr#expr) }+ } [ <- [expr](expr#expr) ] |
| |
| operator-name | ::= | ... |
| | ∣ | . [dot-ext](#dot-ext) ((;..) ∣ [;..] ∣ {;..}) [<-] |
| |
|
Multi-index are also supported through a second variant of indexing operators
```
let (.%[;..]) = Bigarray.Genarray.get
let (.%{;..}) = Bigarray.Genarray.get
let (.%(;..)) = Bigarray.Genarray.get
```
which is called when an index literals contain a semicolon separated list of expressions with two and more elements:
```
let sum x y = x.%[1;2;3] + y.%[1;2]
(* is equivalent to *)
let sum x y = (.%[;..]) x [|1;2;3|] + (.%[;..]) y [|1;2|]
```
In particular this multi-index notation makes it possible to uniformly handle indexing Genarray and other implementations of multidimensional arrays.
```
module A = Bigarray.Genarray
let (.%{;..}) = A.get
let (.%{;..}<- ) = A.set
let (.%{ }) a k = A.get a [|k|]
let (.%{ }<-) a k x = A.set a [|k|] x
let syntax_compare vec mat t3 t4 =
vec.%{0} = A.get vec [|0|]
&& mat.%{0;0} = A.get mat [|0;0|]
&& t3.%{0;0;0} = A.get t3 [|0;0;0|]
&& t4.%{0;0;0;0} = t4.{0,0,0,0}
```
Beware that the differentiation between the multi-index and single index operators is purely syntactic: multi-index operators are restricted to index expressions that contain one or more semicolons ;. For instance,
```
let pair vec mat = vec.%{0}, mat.%{0;0}
```
is equivalent to
```
let pair vec mat = (.%{ }) vec 0, (.%{;..}) mat [|0;0|]
```
Notice that in the vec case, we are calling the single index operator, (.%{}), and not the multi-index variant, (.{;..}). For this reason, it is expected that most users of multi-index operators will need to define conjointly a single index variant
```
let (.%{;..}) = A.get
let (.%{ }) a k = A.get a [|k|]
```
to handle both cases uniformly.
ocaml None
[](#s:effect-handlers)12.24 Effect handlers
---------------------------------------------
* [12.24.1 Basics](effects#s%3Aeffects-basics)
* [12.24.2 Concurrency](effects#s%3Aeffects-concurrency)
* [12.24.3 User-level threads](effects#s%3Aeffects-user-threads)
* [12.24.4 Control inversion](effects#s%3Aeffects-sequence)
* [12.24.5 Semantics](effects#s%3Aeffects-semantics)
* [12.24.6 Shallow handlers](effects#s%3Aeffects-shallow)
(Introduced in 5.0)
Note: Effect handlers in OCaml 5.0 should be considered experimental. Effect handlers are exposed in the standard library as a thin wrapper around their implementations in the runtime. They are not supported as a language feature with new syntax. You can rely on them to build non-local control-flow abstractions such as user-level threading that do not expose the effect handler primitives to the user. Expect breaking changes in the future.
Effect handlers are a mechanism for modular programming with user-defined effects. Effect handlers allow the programmers to describe computations that perform effectful operations, whose meaning is described by handlers that enclose the computations. Effect handlers are a generalization of exception handlers and enable non-local control-flow mechanisms such as resumable exceptions, lightweight threads, coroutines, generators and asynchronous I/O to be composably expressed. In this tutorial, we shall see how some of these mechanisms can be built using effect handlers.
###
[](#s:effects-basics)12.24.1 Basics
To understand the basics, let us define an effect (that is, an operation) that takes an integer argument and returns an integer result. We name this effect Xchg.
```
open Effect
open Effect.Deep
type _ Effect.t += Xchg: int -> int t
let comp1 () = perform (Xchg 0) + perform (Xchg 1)
```
We declare the exchange effect Xchg by extending the pre-defined extensible variant type Effect.t with a new constructor Xchg: int -> int t. The declaration may be intuitively read as “the Xchg effect takes an integer parameter, and when this effect is performed, it returns an integer”. The computation comp1 performs the effect twice using the perform primitive and returns their sum.
We can handle the Xchg effect by implementing a handler that always returns the successor of the offered value:
```
try_with comp1 ()
{ effc = fun (type a) (eff: a t) ->
match eff with
| Xchg n -> Some (fun (k: (a, _) continuation) ->
continue k (n+1))
| _ -> None }
- : int = 3
```
try\_with runs the computation comp1 () under an effect handler that handles the Xchg effect. As mentioned earlier, effect handlers are a generalization of exception handlers. Similar to exception handlers, when the computation performs the Xchg effect, the control jumps to the corresponding handler. However, unlike exception handlers, the handler is also provided with the delimited continuation k, which represents the suspended computation between the point of perform and this handler.
The handler uses the continue primitive to resume the suspended computation with the successor of the offered value. In this example, the computation comp1 performs Xchg 0 and Xchg 1 and receives the values 1 and 2 from the handler respectively. Hence, the whole expression evaluates to 3.
It is useful to note that the we must use locally abstract type (type a) in the effect handler. The type Effect.t is a GADT, and the effect declarations may have different type parameters for different effects. The type parameter a in the type a Effect.t represents the type of the value returned when performing the effect. From the fact that eff has type a Effect.t and from the fact that Xchg n has type int Effect.t, the type-checker deduces that a must be int, which is why we are allowed to pass the integer value n+1 as an argument to continue k.
Another point to note is that the catch-all case “| \_ -> None” is necessary when handling effects. This case may be intuitively read as “forward the unhandled effects to the outer handler”.
In this example, we use the *deep* version of the effect handlers here as opposed to the *shallow* version. A deep handler monitors a computation until the computation terminates (either normally or via an exception), and handles all of the effects performed (in sequence) by the computation. In contrast, a shallow handler monitors a computation until either the computation terminates or the computation performs one effect, and it handles this single effect only. In situations where they are applicable, deep handlers are usually preferred. An example that utilises shallow handlers is discussed later in [12.24.6](#s%3Aeffects-shallow).
###
[](#s:effects-concurrency)12.24.2 Concurrency
The expressive power of effect handlers comes from the delimited continuation. While the previous example immediately resumed the computation, the computation may be resumed later, running some other computation in the interim. Let us extend the previous example and implement message-passing concurrency between two concurrent computations using the Xchg effect. We call these concurrent computations tasks.
A task either is in a suspended state or is completed. We represent the task status as follows:
```
type 'a status =
Complete of 'a
| Suspended of {msg: int; cont: (int, 'a status) continuation}
```
A task either is complete, with a result of type 'a, or is suspended with the message msg to send and the continuation cont. The type (int,'a status) continuation says that the suspended computation expects an int value to resume and returns a 'a status value when resumed.
Next, we define a step function that executes one step of computation until it completes or suspends:
```
let step (f : unit -> 'a) () : 'a status =
match_with f ()
{ retc = (fun v -> Complete v);
exnc = raise;
effc = fun (type a) (eff: a t) ->
match eff with
| Xchg msg -> Some (fun (cont: (a, _) continuation) ->
Suspended {msg; cont})
| _ -> None }
```
The argument to the step function, f, is a computation that can perform an Xchg effect and returns a result of type 'a. The step function itself returns a 'a status value.
In the step function, we use the match\_with primitive. Like try\_with, match\_with primitive installs an effect handler. However, unlike try\_with, where only the effect case effc is provided, match\_with expects the handlers for the value (retc) and exceptional (exnc) return cases. In fact, try\_with can be defined using match\_with as follows: let try\_with f v {effc} = match\_with f v {retc = Fun.id; exnc = raise; effc}.
In the step function,
* Case retc: If the computation returns with a value v, we return Complete v.
* Case exnc: If the computation raises an exception, then the handler raises the same exception.
* Case effc: If the computation performs the effect Xchg msg with the continuation cont, then we return Suspended{msg;cont}. Thus, in this case, the continuation cont is not immediately invoked by the handler; instead, it is stored in a data structure for later use.
Since the step function handles the Xchg effect, step f is a computation that does not perform the Xchg effect. It may however perform other effects. Moreover, since we are using deep handlers, the continuation cont stored in the status does not perform the Xchg effect.
We can now write a simple scheduler that runs a pair of tasks to completion:
```
let rec run_both a b =
match a (), b () with
| Complete va, Complete vb -> (va, vb)
| Suspended {msg = m1; cont = k1},
Suspended {msg = m2; cont = k2} ->
run_both (fun () -> continue k1 m2)
(fun () -> continue k2 m1)
| _ -> failwith "Improper synchronization"
```
Both of the tasks may run to completion, or both may offer to exchange a message. In the latter case, each computation receives the value offered by the other computation. The situation where one computation offers an exchange while the other computation terminates is regarded as a programmer error, and causes the handler to raise an exception
We can now define a second computation that also exchanges two messages:
```
let comp2 () = perform (Xchg 21) * perform (Xchg 21)
```
Finally, we can run the two computations together:
```
run_both (step comp1) (step comp2)
- : int * int = (42, 0)
```
The computation comp1 offers the values 0 and 1 and in exchange receives the values 21 and 21, which it adds, producing 42. The computation comp2 offers the values 21 and 21 and in exchange receives the values 0 and 1, which it multiplies, producing 0. The communication between the two computations is programmed entirely inside run\_both. Indeed, the definitions of comp1 and comp2, alone, do not assign any meaning to the Xchg effect.
###
[](#s:effects-user-threads)12.24.3 User-level threads
Let us extend the previous example for an arbitrary number of tasks. Many languages such as GHC Haskell and Go provide user-level threads as a primitive feature implemented in the runtime system. With effect handlers, user-level threads and their schedulers can be implemented in OCaml itself. Typically, user-level threading systems provide a fork primitive to spawn off a new concurrent task and a yield primitive to yield control to some other task. Correspondingly, we shall declare two effects as follows:
```
type _ Effect.t += Fork : (unit -> unit) -> unit t
| Yield : unit t
```
The Fork effect takes a thunk (a suspended computation, represented as a function of type unit -> unit) and returns a unit to the performer. The Yield effect is unparameterized and returns a unit when performed. Let us consider that a task performing an Xchg effect may match with any other task also offering to exchange a value.
We shall also define helper functions that simply perform these effects:
```
let fork f = perform (Fork f)
let yield () = perform Yield
let xchg v = perform (Xchg v)
```
A top-level run function defines the scheduler:
```
(* A concurrent round-robin scheduler *)
let run (main : unit -> unit) : unit =
let exchanger = ref None in (* waiting exchanger *)
let run_q = Queue.create () in (* scheduler queue *)
let enqueue k v =
let task () = continue k v in
Queue.push task run_q
in
let dequeue () =
if Queue.is_empty run_q then () (* done *)
else begin
let task = Queue.pop run_q in
task ()
end
in
let rec spawn (f : unit -> unit) : unit =
match_with f () {
retc = dequeue;
exnc = (fun e ->
print_endline (Printexc.to_string e);
dequeue ());
effc = fun (type a) (eff : a t) ->
match eff with
| Yield -> Some (fun (k : (a, unit) continuation) ->
enqueue k (); dequeue ())
| Fork f -> Some (fun (k : (a, unit) continuation) ->
enqueue k (); spawn f)
| Xchg n -> Some (fun (k : (int, unit) continuation) ->
begin match !exchanger with
| Some (n', k') ->
exchanger := None; enqueue k' n; continue k n'
| None -> exchanger := Some (n, k); dequeue ()
end)
| _ -> None
}
in
spawn main
```
We use a mutable queue run\_q to hold the scheduler queue. The FIFO queue enables round-robin scheduling of tasks in the scheduler. enqueue inserts tasks into the queue, and dequeue extracts tasks from the queue and runs them. The reference cell exchanger holds a (suspended) task offering to exchange a value. At any time, there is either zero or one suspended task that is offering an exchange.
The heavy lifting is done by the spawn function. The spawn function runs the given computation f in an effect handler. If f returns with a value (case retc), we dequeue and run the next task from the scheduler queue. If the computation f raises an exception (case exnc), we print the exception and run the next task from the scheduler.
The computation f may also perform effects. If f performs the Yield effect, the current task is suspended (inserted into the queue of ready tasks), and the next task from the scheduler queue is run. If the effect is Fork f, then the current task is suspended, and the new task f is executed immediately via a tail call to spawn f. Note that this choice to run the new task first is arbitrary. We could very well have chosen instead to insert the task for f into the ready queue and resumed k immediately.
If the effect is Xchg, then we first check whether there is a task waiting to exchange. If so, we enqueue the waiting task with the current value being offered and immediately resume the current task with the value being offered. If not, we make the current task the waiting exchanger, and run the next task from the scheduler queue.
Note that this scheduler code is not perfect – it can leak resources. We shall explain and fix this in the next section [12.24.3](#s%3Aeffects-discontinue).
Now we can write a concurrent program that utilises the newly defined operations:
```
open Printf
let _ = run (fun _ ->
fork (fun _ ->
printf "[t1] Sending 0\n";
let v = xchg 0 in
printf "[t1] received %d\n" v);
fork (fun _ ->
printf "[t2] Sending 1\n";
let v = xchg 1 in
printf "[t2] received %d\n" v))
[t1] Sending 0
[t2] Sending 1
[t2] received 0
[t1] received 1
```
Observe that the messages from the two tasks are interleaved. Notice also that the snippet above makes no reference to the effect handlers and is in direct style (no monadic operations). This example illustrates that, with effect handlers, the user code in a concurrent program can remain in simple direct style, and the use of effect handlers can be fully contained within the concurrency library implementation.
####
[](#s:effects-discontinue)Resuming with an exception
In addition to resuming a continuation with a value, effect handlers also permit resuming by raising an effect at the point of perform. This is done with the help of the discontinue primitive. The discontinue primitive helps ensure that resources are always eventually deallocated, even in the presence of effects.
For example, consider the dequeue operation in the previous example reproduced below:
```
…
let dequeue () =
if Queue.is_empty run_q then () (* done *)
else (Queue.pop run_q) ()
```
If the scheduler queue is empty, dequeue considers that the scheduler is done and returns to the caller. However, there may still be a task waiting to exchange a value (stored in the reference cell exchanger), which remains blocked forever! If the blocked task holds onto resources, these resources are leaked. For example, consider the following task:
```
let leaky_task () =
fork (fun _ ->
let oc = open_out "secret.txt" in
Fun.protect ~finally:(fun _ -> close_out oc) (fun _ ->
output_value oc (xchg 0)))
```
The task writes the received message to the file secret.txt. It uses Fun.protect to ensure that the output channel oc is closed on both normal and exceptional return cases. Unfortunately, this is not sufficient. If the exchange effect xchg 0 cannot be matched with an exchange effect performed by some other thread, then this task remains blocked forever. Thus, the output channel oc is never closed.
To avoid this problem, one must adhere to a simple discipline: *every continuation must be eventually either continued or discontinued*. Here, we use discontinue to ensure that the blocked task does not remain blocked forever. By discontinuing this task, we force it to terminate (with an exception):
```
exception Improper_synchronization
let dequeue () =
if Queue.is_empty run_q then begin
match !exchanger with
| None -> () (* done *)
| Some (n, k) ->
exchanger := None;
discontinue k Improper_synchronization
end else (Queue.pop run_q) ()
```
When the scheduler queue is empty and there is a blocked exchanger thread, the dequeue function discontinues the blocked thread with an Improper\_synchronization exception. This exception is raised at the blocked xchg function call, which causes the finally block to be run and closes the output channel oc. From the point of view of the user, it seems as though the function call xchg 0 raises the exception Improper\_synchronization.
###
[](#s:effects-sequence)12.24.4 Control inversion
When it comes to performing traversals on a data structure, there are two fundamental ways depending on whether the producer or the consumer has the control over the traversal. For example, in List.iter f l, the producer List.iter has the control and pushes the element to the consumer f who processes them. On the other hand, the [Seq](libref/seq) module provides a mechanism similar to delayed lists where the consumer controls the traversal. For example, Seq.forever Random.bool returns an infinite sequence of random bits where every bit is produced (on demand) when queried by the consumer.
Naturally, producers such as List.iter are easier to write in the former style. The latter style is ergonomically better for the consumer since it is preferable and more natural to be in control. To have the best of both worlds, we would like to write a producer in the former style and automatically convert it to the latter style. The conversion can be written *once and for all* as a library function, thanks to effect handlers. Let us name this function invert. We will first look at how to use the invert function before looking at its implementation details. The type of this function is given below:
```
val invert : iter:(('a -> unit) -> unit) -> 'a Seq.t
```
The invert function takes an iter function (a producer that pushes elements to the consumer) and returns a sequence (where the consumer has the control). For example,
```
let lst_iter = Fun.flip List.iter [1;2;3]
val lst_iter : (int -> unit) -> unit =
```
is an iter function with type (int -> unit) -> unit. The expression lst\_iter f pushes the elements 1, 2 and 3 to the consumer f. For example,
```
lst_iter (fun i -> Printf.printf "%d\n" i)
1
2
3
- : unit = ()
```
The expression invert lst\_iter returns a sequence that allows the consumer to traverse the list on demand. For example,
```
let s = invert ~iter:lst_iter
let next = Seq.to_dispenser s;;
val s : int Seq.t =
val next : unit -> int option =
```
```
next();;
- : int option = Some 1
```
```
next();;
- : int option = Some 2
```
```
next();;
- : int option = Some 3
```
```
next();;
- : int option = None
```
We can use the same invert function on any iter function. For example,
```
let s = invert ~iter:(Fun.flip String.iter "OCaml")
let next = Seq.to_dispenser s;;
val s : char Seq.t =
val next : unit -> char option =
```
```
next();;
- : char option = Some 'O'
```
```
next();;
- : char option = Some 'C'
```
```
next();;
- : char option = Some 'a'
```
```
next();;
- : char option = Some 'm'
```
```
next();;
- : char option = Some 'l'
```
```
next();;
- : char option = None
```
####
[](#s:effects-sequence-implementation)Implementing control inversion
The implementation of the invert function is given below:
```
let invert (type a) ~(iter : (a -> unit) -> unit) : a Seq.t =
let module M = struct
type _ Effect.t += Yield : a -> unit t
end in
let yield v = perform (M.Yield v) in
fun () -> match_with iter yield
{ retc = (fun _ -> Seq.Nil);
exnc = raise;
effc = fun (type b) (eff : b Effect.t) ->
match eff with
| M.Yield v -> Some (fun (k: (b,_) continuation) ->
Seq.Cons (v, continue k))
| _ -> None }
```
The invert function declares an effect Yield that takes the element to be yielded as a parameter. The yield function performs the Yield effect. The lambda abstraction fun () -> ... delays all action until the first element of the sequence is demanded. Once this happens, the computation iter yield is executed under an effect handler. Every time the iter function pushes an element to the yield function, the computation is interrupted by the Yield effect. The Yield effect is handled by returning the value Seq.Cons(v,continue k) to the consumer. The consumer gets the element v as well as the suspended computation, which in the consumer’s eyes is just the tail of sequence.
When the consumer demands the next element from the sequence (by applying it to ()), the continuation k is resumed. This allows the computation iter yield to make progress, until it either yields another element or terminates normally. In the latter case, the value Seq.Nil is returned, indicating to the consumer that the iteration is over.
It is important to note that the sequence returned by the invert function is *ephemeral* (as defined by the [Seq](libref/seq) module) i.e., the sequence must be used at most once. Additionally, the sequence must be fully consumed (i.e., used at least once) so as to ensure that the captured continuation is used linearly.
###
[](#s:effects-semantics)12.24.5 Semantics
In this section, we shall see the semantics of effect handlers with the help of examples.
####
[](#s:effects-nesting)Nesting handlers
Like exception handlers, effect handlers can be nested.
```
type _ Effect.t += E : int t
| F : string t
let foo () = perform F
let bar () =
try_with foo ()
{ effc = fun (type a) (eff: a t) ->
match eff with
| E -> Some (fun (k: (a,_) continuation) ->
failwith "impossible")
| _ -> None }
let baz () =
try_with bar ()
{ effc = fun (type a) (eff: a t) ->
match eff with
| F -> Some (fun (k: (a,_) continuation) ->
continue k "Hello, world!")
| _ -> None }
```
In this example, the computation foo performs F, the inner handler handles only E and the outer handler handles F. The call to baz returns Hello, world!.
```
baz ()
- : string = "Hello, world!"
```
####
[](#s:effects-fibers)Fibers
It is useful to know a little bit about the implementation of effect handlers to appreciate the design choices and their performance characteristics. Effect handlers are implemented with the help of runtime-managed, dynamically growing segments of stack called fibers. The program stack in OCaml is a linked list of such fibers.
A new fiber is allocated for evaluating the computation enclosed by an effect handler. The fiber is freed when the computation returns to the caller either normally by returning a value or by raising an exception.
At the point of perform in foo in the previous example, the program stack looks like this:
```
+-----+ +-----+ +-----+
| | | | | |
| baz |<--| bar |<--| foo |
| | | | | |
| | | | | |
+-----+ +-----+ +-----+ <- stack_pointer
```
The two links correspond to the two effect handlers in the program. When the effect F is handled in baz, the program state looks as follows:
```
+-----+ +-----+ +-----+
| | | | | | +-+
| baz | | bar |<--| foo |<--|k|
| | | | | | +-+
+-----+ <- stack_pointer +-----+ +-----+
```
The delimited continuation k is an object on the heap that refers to the segment of the stack that corresponds to the suspended computation. Capturing a continuation does not involve copying stack frames. When the continuation is resumed, the stack is restored to the previous state by linking together the segment pointed to by k to the current stack. Since neither continuation capture nor resumption requires copying stack frames, suspending the execution using perform and resuming it using either continue or discontinue are fast.
####
[](#s:effects-unhandled)Unhandled effects
Unlike languages such as Eff and Koka, effect handlers in OCaml do not provide effect safety; the compiler does not statically ensure that all the effects performed by the program are handled. If effects do not have a matching handler, then an Effect.Unhandled exception is raised at the point of the corresponding perform. For example, in the previous example, bar does not handle the effect F. Hence, we will get an Effect.Unhandled F exception when we run bar.
```
try bar () with Effect.Unhandled F -> "Saw Effect.Unhandled exception"
- : string = "Saw Effect.Unhandled exception"
```
####
[](#s:effects-linearity)Linear continuations
As discussed earlier [12.24.3](#s%3Aeffects-discontinue), the delimited continuations in OCaml must be used linearly – *every captured continuation must be resumed either with a continue or discontinue exactly once*. Attempting to use a continuation more than once raises a Continuation\_already\_resumed exception. For example:
```
try_with perform (Xchg 0)
{ effc = fun (type a) (eff : a t) ->
match eff with
| Xchg n -> Some (fun (k: (a, _) continuation) ->
continue k 21 + continue k 21)
| _ -> None }
Exception: Stdlib.Effect.Continuation_already_resumed.
```
The primary motivation for adding effect handlers to OCaml is to enable concurrent programming. One-shot continuations are sufficient for almost all concurrent programming needs. They are also much cheaper to implement compared to multi-shot continuations since they do not require stack frames to be copied. Moreover, OCaml programs may also manipulate linear resources such as sockets and file descriptors. The linearity discipline is easily broken if the continuations are allowed to resume more than once. It would be quite hard to debug such linearity violations on resources due to the lack of static checks for linearity and the non-local nature of control flow. Hence, OCaml does not support multi-shot continuations.
While the “at most once resumption” property of continuations is ensured with a dynamic check, there is no check to ensure that the continuations are resumed “at least once”. It is left to the user to ensure that the captured continuations are resumed at least once. Not resuming continuations will leak the memory allocated for the fibers as well as any resources that the suspended computation may hold.
One may install a finaliser on the captured continuation to ensure that the resources are freed:
```
exception Unwind
Gc.finalise (fun k ->
try ignore (discontinue k Unwind) with _ -> ()) k
```
In this case, if k becomes unreachable, then the finaliser ensures that the continuation stack is unwound by discontinuing with an Unwind exception, allowing the computation to free up resources. However, the runtime cost of finalisers is much more than the cost of capturing a continuation. Hence, it is recommended that the user take care of resuming the continuation exactly once rather than relying on the finaliser.
###
[](#s:effects-shallow)12.24.6 Shallow handlers
The examples that we have seen so far have used deep handlers. A deep handler handles all the effects performed (in sequence) by the computation. Whenever a continuation is captured in a deep handler, the captured continuation also includes the handler. This means that, when the continuation is resumed, the effect handler is automatically re-installed, and will handle the effect(s) that the computation may perform in the future.
OCaml also provides shallow handlers. Compared to deep handlers, a shallow handler handles only the first effect performed by the computation. The continuation captured in a shallow handler does not include the handler. This means that, when the continuation is resumed, the handler is no longer present. For this reason, when the continuation is resumed, the user is expected to provide a new effect handler (possibly a different one) to handle the next effect that the computation may perform.
Shallow handlers make it easier to express certain kinds of programs. Let us implement a shallow handler that enforces a particular sequence of effects (a protocol) on a computation. For this example, let us consider that the computation may perform the following effects:
```
type _ Effect.t += Send : int -> unit Effect.t
| Recv : int Effect.t
```
Let us assume that we want to enforce a protocol that only permits an alternating sequence of Send and Recv effects that conform to the regular expression (Send;Recv)\*;Send?. Hence, the sequence of effects [] (the empty sequence), [Send], [Send;Recv], [Send;Recv;Send], etc., are allowed, but not [Recv], [Send;Send], [Send;Recv;Recv], etc. The key observation here is that the set of effects handled evolves over time. We can enforce this protocol quite naturally using shallow handlers as shown below:
```
open Effect.Shallow
let run (comp: unit -> unit) : unit =
let rec loop_send : type a. (a,unit) continuation -> a -> unit = fun k v ->
continue_with k v
{ retc = Fun.id;
exnc = raise;
effc = fun (type b) (eff : b Effect.t) ->
match eff with
| Send n -> Some (fun (k: (b,_) continuation) ->
loop_recv n k ())
| Recv -> failwith "protocol violation"
| _ -> None }
and loop_recv : type a. int -> (a,unit) continuation -> a -> unit = fun n k v ->
continue_with k v
{ retc = Fun.id;
exnc = raise;
effc = fun (type b) (eff : b Effect.t) ->
match eff with
| Recv -> Some (fun (k: (b,_) continuation) ->
loop_send k n)
| Send v -> failwith "protocol violation"
| _ -> None }
in
loop_send (fiber comp) ()
```
The run function executes the computation comp ensuring that it can only perform an alternating sequence of Send and Recv effects. The shallow handler uses a different set of primitives compared to the deep handler. The primitive fiber (on the last line) takes an 'a -> 'b function and returns a ('a,'b) Effects.Shallow.continuation. The expression continue\_with k v h resumes the continuation k with value v under the handler h.
The mutually recursive functions loop\_send and loop\_recv resume the given continuation k with value v under different handlers. The loop\_send function handles the Send effect and tail calls the loop\_recv function. If the computation performs the Recv effect, then loop\_send aborts the computation by raising an exception. Similarly, the loop\_recv function handles the Recv effect and tail calls the loop\_send function. If the computation performs the Send effect, then loop\_recv aborts the computation. Given that the continuation captured in the shallow handler do not include the handler, there is only ever one handler installed in the dynamic scope of the computation comp.
The computation is initially executed by the loop\_send function (see last line in the code above) which ensures that the first effect that the computation is allowed to perform is the Send effect. Note that the computation is free to perform effects other than Send and Recv, which may be handled by an outer handler.
We can see that the run function will permit a computation that follows the protocol:
```
run (fun () ->
printf "Send 42\n";
perform (Send 42);
printf "Recv: %d\n" (perform Recv);
printf "Send 43\n";
perform (Send 43);
printf "Recv: %d\n" (perform Recv))
Send 42
Recv: 42
Send 43
Recv: 43
- : unit = ()
```
and aborts those that do not:
```
run (fun () ->
Printf.printf "Send 0\n";
perform (Send 0);
Printf.printf "Send 1\n";
perform (Send 1) (* protocol violation *))
Send 0
Send 1
Exception: Failure "protocol violation".
```
We may implement the same example using deep handlers using reference cells (easy, but unsatisfying) or without them (harder). We leave this as an exercise to the reader.
| programming_docs |
ocaml Index of keywords Index of keywords
=================
| | |
| --- | --- |
| * and, [11.7](expr#hevea_manual.kwd21), [11.8.1](typedecl#hevea_manual.kwd93), [11.9.2](classes#hevea_manual.kwd122), [11.9.3](classes#hevea_manual.kwd144), [11.9.4](classes#hevea_manual.kwd146), [11.9.5](classes#hevea_manual.kwd149), [11.10](modtypes#hevea_manual.kwd154), [11.11](modules#hevea_manual.kwd183), [12.2](recursivemodules#hevea_manual.kwd207), [12.5](firstclassmodules#hevea_manual.kwd215)
* as, [11.4](types#hevea_manual.kwd7), [11.4](types#hevea_manual.kwd8), [11.4](types#hevea_manual.kwd9), [11.6](patterns#hevea_manual.kwd15), [11.6](patterns#hevea_manual.kwd16), [11.6](patterns#hevea_manual.kwd17), [11.9.2](classes#hevea_manual.kwd124), [11.9.2](classes#hevea_manual.kwd132)
* asr, [11.3](names#hevea_manual.kwd6), [11.7.1](expr#hevea_manual.kwd57), [11.7.5](expr#hevea_manual.kwd76), [11.7.5](expr#hevea_manual.kwd83)
* assert, [11.7.8](expr#hevea_manual.kwd86)
* begin, [11.5](const#hevea_manual.kwd13), [11.7](expr#hevea_manual.kwd38), [11.7.2](expr#hevea_manual.kwd58)
* class, [11.9.3](classes#hevea_manual.kwd143), [11.9.4](classes#hevea_manual.kwd145), [11.9.5](classes#hevea_manual.kwd147), [11.10](modtypes#hevea_manual.kwd159), [11.10.2](modtypes#hevea_manual.kwd169), [11.10.2](modtypes#hevea_manual.kwd170), [11.11](modules#hevea_manual.kwd187), [11.11.2](modules#hevea_manual.kwd197), [11.11.2](modules#hevea_manual.kwd198)
* constraint, [11.8.1](typedecl#hevea_manual.kwd97), [11.8.1](typedecl#hevea_manual.kwd99), [11.9.1](classes#hevea_manual.kwd109), [11.9.1](classes#hevea_manual.kwd117), [11.9.2](classes#hevea_manual.kwd129), [11.9.2](classes#hevea_manual.kwd141)
* do, see while, for
* done, see while, for
* downto, see for
* else, see if
* end, [11.5](const#hevea_manual.kwd14), [11.7](expr#hevea_manual.kwd39), [11.7.2](expr#hevea_manual.kwd59), [11.9.1](classes#hevea_manual.kwd102), [11.9.2](classes#hevea_manual.kwd119), [11.10](modtypes#hevea_manual.kwd151), [11.10.2](modtypes#hevea_manual.kwd164), [11.11](modules#hevea_manual.kwd180), [11.11.2](modules#hevea_manual.kwd192)
* exception, [11.8.2](typedecl#hevea_manual.kwd100), [11.10](modtypes#hevea_manual.kwd158), [11.10.2](modtypes#hevea_manual.kwd168), [11.11](modules#hevea_manual.kwd186), [11.11.2](modules#hevea_manual.kwd196)
* external, [11.10](modtypes#hevea_manual.kwd156), [11.10.2](modtypes#hevea_manual.kwd166), [11.11](modules#hevea_manual.kwd184), [11.11.2](modules#hevea_manual.kwd194)
* false, [11.5](const#hevea_manual.kwd11)
* for, [11.7](expr#hevea_manual.kwd32), [11.7.3](expr#hevea_manual.kwd68)
* fun, [11.7](expr#hevea_manual.kwd26), [11.7.1](expr#hevea_manual.kwd46), [11.7.2](expr#hevea_manual.kwd61), [11.9.2](classes#hevea_manual.kwd120), [12.4](locallyabstract#hevea_manual.kwd211)
* function, [11.7](expr#hevea_manual.kwd25), [11.7.1](expr#hevea_manual.kwd47), [11.7.2](expr#hevea_manual.kwd60)
* functor, [11.10](modtypes#hevea_manual.kwd152), [11.10.3](modtypes#hevea_manual.kwd177), [11.11](modules#hevea_manual.kwd181), [11.11.3](modules#hevea_manual.kwd205)
* if, [11.7](expr#hevea_manual.kwd35), [11.7.1](expr#hevea_manual.kwd45), [11.7.3](expr#hevea_manual.kwd64)
* in, see let
* include, [11.10](modtypes#hevea_manual.kwd162), [11.10.2](modtypes#hevea_manual.kwd176), [11.11](modules#hevea_manual.kwd190), [11.11.2](modules#hevea_manual.kwd204), [12.6](moduletypeof#hevea_manual.kwd219)
* inherit, [11.9.1](classes#hevea_manual.kwd103), [11.9.1](classes#hevea_manual.kwd110), [11.9.2](classes#hevea_manual.kwd123), [11.9.2](classes#hevea_manual.kwd131)
* initializer, [11.9.2](classes#hevea_manual.kwd130), [11.9.2](classes#hevea_manual.kwd142)
* land, [11.3](names#hevea_manual.kwd1), [11.7.1](expr#hevea_manual.kwd52), [11.7.5](expr#hevea_manual.kwd71), [11.7.5](expr#hevea_manual.kwd78)
* lazy, [11.6](patterns#hevea_manual.kwd18), [11.7](expr#hevea_manual.kwd43), [11.7.8](expr#hevea_manual.kwd87)
* let, [11.7](expr#hevea_manual.kwd23), [11.7.1](expr#hevea_manual.kwd50), [11.7.2](expr#hevea_manual.kwd63), [11.7.8](expr#hevea_manual.kwd88), [11.7.8](expr#hevea_manual.kwd90), [11.9.2](classes#hevea_manual.kwd121), [11.11](modules#hevea_manual.kwd182), [11.11.2](modules#hevea_manual.kwd193)
* lor, [11.3](names#hevea_manual.kwd2), [11.7.1](expr#hevea_manual.kwd53), [11.7.5](expr#hevea_manual.kwd72), [11.7.5](expr#hevea_manual.kwd79)
* lsl, [11.3](names#hevea_manual.kwd4), [11.7.1](expr#hevea_manual.kwd55), [11.7.5](expr#hevea_manual.kwd74), [11.7.5](expr#hevea_manual.kwd81)
* lsr, [11.3](names#hevea_manual.kwd5), [11.7.1](expr#hevea_manual.kwd56), [11.7.5](expr#hevea_manual.kwd75), [11.7.5](expr#hevea_manual.kwd82)
| * lxor, [11.3](names#hevea_manual.kwd3), [11.7.1](expr#hevea_manual.kwd54), [11.7.5](expr#hevea_manual.kwd73), [11.7.5](expr#hevea_manual.kwd80)
* match, [11.7](expr#hevea_manual.kwd37), [11.7.1](expr#hevea_manual.kwd48), [11.7.3](expr#hevea_manual.kwd65), [12.10](gadts#hevea_manual.kwd226)
* method, [11.9.1](classes#hevea_manual.kwd106), [11.9.1](classes#hevea_manual.kwd113), [11.9.1](classes#hevea_manual.kwd115), [11.9.2](classes#hevea_manual.kwd127), [11.9.2](classes#hevea_manual.kwd137), [11.9.2](classes#hevea_manual.kwd139)
* mod, [11.3](names#hevea_manual.kwd0), [11.7.1](expr#hevea_manual.kwd51), [11.7.5](expr#hevea_manual.kwd70), [11.7.5](expr#hevea_manual.kwd77)
* module, [11.7.8](expr#hevea_manual.kwd89), [11.10](modtypes#hevea_manual.kwd160), [11.10.2](modtypes#hevea_manual.kwd172), [11.10.2](modtypes#hevea_manual.kwd174), [11.11](modules#hevea_manual.kwd188), [11.11.2](modules#hevea_manual.kwd200), [11.11.2](modules#hevea_manual.kwd202), [12.2](recursivemodules#hevea_manual.kwd206), [12.5](firstclassmodules#hevea_manual.kwd212), [12.6](moduletypeof#hevea_manual.kwd216), [12.7](signaturesubstitution#hevea_manual.kwd221), [12.8](modulealias#hevea_manual.kwd223)
* open, [11.7.8](expr#hevea_manual.kwd91)
* mutable, [11.8.1](typedecl#hevea_manual.kwd96), [11.8.1](typedecl#hevea_manual.kwd98), [11.9.1](classes#hevea_manual.kwd105), [11.9.1](classes#hevea_manual.kwd112), [11.9.2](classes#hevea_manual.kwd126), [11.9.2](classes#hevea_manual.kwd134), [11.9.2](classes#hevea_manual.kwd136)
* new, [11.7](expr#hevea_manual.kwd41), [11.7.6](expr#hevea_manual.kwd84)
* nonrec, [11.8.1](typedecl#hevea_manual.kwd94)
* object, [11.7](expr#hevea_manual.kwd42), [11.7.6](expr#hevea_manual.kwd85), [11.9.1](classes#hevea_manual.kwd101), [11.9.2](classes#hevea_manual.kwd118)
* of, [11.4](types#hevea_manual.kwd10), [11.8.1](typedecl#hevea_manual.kwd95), [12.6](moduletypeof#hevea_manual.kwd218)
* open, [11.6](patterns#hevea_manual.kwd19), [11.10](modtypes#hevea_manual.kwd161), [11.10.2](modtypes#hevea_manual.kwd175), [11.11](modules#hevea_manual.kwd189), [11.11.2](modules#hevea_manual.kwd203)
* open!, [12.9](overridingopen#hevea_manual.kwd224)
* or, [11.7](expr#hevea_manual.kwd36), [11.7.1](expr#hevea_manual.kwd44), [11.7.3](expr#hevea_manual.kwd66)
* private, [11.9.1](classes#hevea_manual.kwd107), [11.9.1](classes#hevea_manual.kwd114), [11.9.1](classes#hevea_manual.kwd116), [11.9.2](classes#hevea_manual.kwd128), [11.9.2](classes#hevea_manual.kwd138), [11.9.2](classes#hevea_manual.kwd140), [12.3](privatetypes#hevea_manual.kwd208), [12.3.3](privatetypes#hevea_manual.kwd209)
* rec, see let, module
* sig, [11.10](modtypes#hevea_manual.kwd150), [11.10.2](modtypes#hevea_manual.kwd163)
* struct, [11.11](modules#hevea_manual.kwd179), [11.11.2](modules#hevea_manual.kwd191)
* then, see if
* to, see for
* true, [11.5](const#hevea_manual.kwd12)
* try, [11.7](expr#hevea_manual.kwd24), [11.7.1](expr#hevea_manual.kwd49), [11.7.3](expr#hevea_manual.kwd69)
* type, [11.8.1](typedecl#hevea_manual.kwd92), [11.9.5](classes#hevea_manual.kwd148), [11.10](modtypes#hevea_manual.kwd157), [11.10.2](modtypes#hevea_manual.kwd167), [11.10.2](modtypes#hevea_manual.kwd171), [11.10.2](modtypes#hevea_manual.kwd173), [11.11](modules#hevea_manual.kwd185), [11.11.2](modules#hevea_manual.kwd195), [11.11.2](modules#hevea_manual.kwd199), [11.11.2](modules#hevea_manual.kwd201), [12.4](locallyabstract#hevea_manual.kwd210), [12.6](moduletypeof#hevea_manual.kwd217), [12.7](signaturesubstitution#hevea_manual.kwd222), [12.10](gadts#hevea_manual.kwd225)
* val, [11.9.1](classes#hevea_manual.kwd104), [11.9.1](classes#hevea_manual.kwd111), [11.9.2](classes#hevea_manual.kwd125), [11.9.2](classes#hevea_manual.kwd133), [11.9.2](classes#hevea_manual.kwd135), [11.10](modtypes#hevea_manual.kwd155), [11.10.2](modtypes#hevea_manual.kwd165), [12.5](firstclassmodules#hevea_manual.kwd213)
* virtual, see val, method, class
* when, [11.7](expr#hevea_manual.kwd40), [11.7.2](expr#hevea_manual.kwd62), [12.12](attributes#hevea_manual.kwd227)
* while, [11.7.3](expr#hevea_manual.kwd67)
* with, [11.7](expr#hevea_manual.kwd27), [11.10](modtypes#hevea_manual.kwd153), [11.10.4](modtypes#hevea_manual.kwd178), [12.5](firstclassmodules#hevea_manual.kwd214), [12.7](signaturesubstitution#hevea_manual.kwd220)
|
ocaml None
[](#s:private-types)12.3 Private types
----------------------------------------
* [12.3.1 Private variant and record types](privatetypes#ss%3Aprivate-types-variant)
* [12.3.2 Private type abbreviations](privatetypes#ss%3Aprivate-types-abbrev)
* [12.3.3 Private row types](privatetypes#ss%3Aprivate-rows)
Private type declarations in module signatures, of the form type t = private ..., enable libraries to reveal some, but not all aspects of the implementation of a type to clients of the library. In this respect, they strike a middle ground between abstract type declarations, where no information is revealed on the type implementation, and data type definitions and type abbreviations, where all aspects of the type implementation are publicized. Private type declarations come in three flavors: for variant and record types (section [12.3.1](#ss%3Aprivate-types-variant)), for type abbreviations (section [12.3.2](#ss%3Aprivate-types-abbrev)), and for row types (section [12.3.3](#ss%3Aprivate-rows)).
###
[](#ss:private-types-variant)12.3.1 Private variant and record types
(Introduced in Objective Caml 3.07)
| | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [type-representation](typedecl#type-representation) | ::= | ... |
| | ∣ | = private [ | ] [constr-decl](typedecl#constr-decl) { | [constr-decl](typedecl#constr-decl) } |
| | ∣ | = private [record-decl](typedecl#record-decl) |
|
Values of a variant or record type declared private can be de-structured normally in pattern-matching or via the [expr](expr#expr) . [field](names#field) notation for record accesses. However, values of these types cannot be constructed directly by constructor application or record construction. Moreover, assignment on a mutable field of a private record type is not allowed.
The typical use of private types is in the export signature of a module, to ensure that construction of values of the private type always go through the functions provided by the module, while still allowing pattern-matching outside the defining module. For example:
```
module M : sig
type t = private A | B of int
val a : t
val b : int -> t
end = struct
type t = A | B of int
let a = A
let b n = assert (n > 0); B n
end
```
Here, the private declaration ensures that in any value of type M.t, the argument to the B constructor is always a positive integer.
With respect to the variance of their parameters, private types are handled like abstract types. That is, if a private type has parameters, their variance is the one explicitly given by prefixing the parameter by a ‘+’ or a ‘-’, it is invariant otherwise.
###
[](#ss:private-types-abbrev)12.3.2 Private type abbreviations
(Introduced in Objective Caml 3.11)
| | | | | | | |
| --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [type-equation](typedecl#type-equation) | ::= | ... |
| | ∣ | = private [typexpr](types#typexpr) |
|
Unlike a regular type abbreviation, a private type abbreviation declares a type that is distinct from its implementation type [typexpr](types#typexpr). However, coercions from the type to [typexpr](types#typexpr) are permitted. Moreover, the compiler “knows” the implementation type and can take advantage of this knowledge to perform type-directed optimizations.
The following example uses a private type abbreviation to define a module of nonnegative integers:
```
module N : sig
type t = private int
val of_int: int -> t
val to_int: t -> int
end = struct
type t = int
let of_int n = assert (n >= 0); n
let to_int n = n
end
```
The type N.t is incompatible with int, ensuring that nonnegative integers and regular integers are not confused. However, if x has type N.t, the coercion (x :> int) is legal and returns the underlying integer, just like N.to\_int x. Deep coercions are also supported: if l has type N.t list, the coercion (l :> int list) returns the list of underlying integers, like List.map N.to\_int l but without copying the list l.
Note that the coercion ( [expr](expr#expr) :> [typexpr](types#typexpr) ) is actually an abbreviated form, and will only work in presence of private abbreviations if neither the type of [expr](expr#expr) nor [typexpr](types#typexpr) contain any type variables. If they do, you must use the full form ( [expr](expr#expr) : [typexpr](types#typexpr)1 :> [typexpr](types#typexpr)2 ) where [typexpr](types#typexpr)1 is the expected type of [expr](expr#expr). Concretely, this would be (x : N.t :> int) and (l : N.t list :> int list) for the above examples.
###
[](#ss:private-rows)12.3.3 Private row types
(Introduced in Objective Caml 3.09)
| | | | | | | |
| --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [type-equation](typedecl#type-equation) | ::= | ... |
| | ∣ | = private [typexpr](types#typexpr) |
|
Private row types are type abbreviations where part of the structure of the type is left abstract. Concretely [typexpr](types#typexpr) in the above should denote either an object type or a polymorphic variant type, with some possibility of refinement left. If the private declaration is used in an interface, the corresponding implementation may either provide a ground instance, or a refined private type.
```
module M : sig type c = private < x : int; .. > val o : c end =
struct
class c = object method x = 3 method y = 2 end
let o = new c
end
```
This declaration does more than hiding the y method, it also makes the type c incompatible with any other closed object type, meaning that only o will be of type c. In that respect it behaves similarly to private record types. But private row types are more flexible with respect to incremental refinement. This feature can be used in combination with functors.
```
module F(X : sig type c = private < x : int; .. > end) =
struct
let get_x (o : X.c) = o#x
end
module G(X : sig type c = private < x : int; y : int; .. > end) =
struct
include F(X)
let get_y (o : X.c) = o#y
end
```
A polymorphic variant type [t], for example
```
type t = [ `A of int | `B of bool ]
```
can be refined in two ways. A definition [u] may add new field to [t], and the declaration
```
type u = private [> t]
```
will keep those new fields abstract. Construction of values of type [u] is possible using the known variants of [t], but any pattern-matching will require a default case to handle the potential extra fields. Dually, a declaration [u] may restrict the fields of [t] through abstraction: the declaration
```
type v = private [< t > `A]
```
corresponds to private variant types. One cannot create a value of the private type [v], except using the constructors that are explicitly listed as present, (`A n) in this example; yet, when patter-matching on a [v], one should assume that any of the constructors of [t] could be present.
Similarly to abstract types, the variance of type parameters is not inferred, and must be given explicitly.
ocaml Chapter 1 The core language Chapter 1 The core language
===========================
* [1.1 Basics](coreexamples#s%3Abasics)
* [1.2 Data types](coreexamples#s%3Adatatypes)
* [1.3 Functions as values](coreexamples#s%3Afunctions-as-values)
* [1.4 Records and variants](coreexamples#s%3Atut-recvariants)
* [1.5 Imperative features](coreexamples#s%3Aimperative-features)
* [1.6 Exceptions](coreexamples#s%3Aexceptions)
* [1.7 Lazy expressions](coreexamples#s%3Alazy-expr)
* [1.8 Symbolic processing of expressions](coreexamples#s%3Asymb-expr)
* [1.9 Pretty-printing](coreexamples#s%3Apretty-printing)
* [1.10 Printf formats](coreexamples#s%3Aprintf)
* [1.11 Standalone OCaml programs](coreexamples#s%3Astandalone-programs)
This part of the manual is a tutorial introduction to the OCaml language. A good familiarity with programming in a conventional languages (say, C or Java) is assumed, but no prior exposure to functional languages is required. The present chapter introduces the core language. Chapter [2](moduleexamples#c%3Amoduleexamples) deals with the module system, chapter [3](objectexamples#c%3Aobjectexamples) with the object-oriented features, chapter [4](lablexamples#c%3Alabl-examples) with labeled arguments, chapter [5](polyvariant#c%3Apoly-variant) with polymorphic variants, chapter [6](polymorphism#c%3Apolymorphism) with the limitations of polymorphism, and chapter [8](advexamples#c%3Aadvexamples) gives some advanced examples.
[](#s:basics)1.1 Basics
-------------------------
For this overview of OCaml, we use the interactive system, which is started by running ocaml from the Unix shell or Windows command prompt. This tutorial is presented as the transcript of a session with the interactive system: lines starting with # represent user input; the system responses are printed below, without a leading #.
Under the interactive system, the user types OCaml phrases terminated by ;; in response to the # prompt, and the system compiles them on the fly, executes them, and prints the outcome of evaluation. Phrases are either simple expressions, or let definitions of identifiers (either values or functions).
```
# 1 + 2 * 3;;
- : int = 7
```
```
# let pi = 4.0 *. atan 1.0;;
val pi : float = 3.14159265358979312
```
```
# let square x = x *. x;;
val square : float -> float =
```
```
# square (sin pi) +. square (cos pi);;
- : float = 1.
```
The OCaml system computes both the value and the type for each phrase. Even function parameters need no explicit type declaration: the system infers their types from their usage in the function. Notice also that integers and floating-point numbers are distinct types, with distinct operators: + and \* operate on integers, but +. and \*. operate on floats.
```
# 1.0 * 2;;
Error: This expression has type float but an expression was expected of type
int
```
Recursive functions are defined with the let rec binding:
```
# let rec fib n =
if n < 2 then n else fib (n - 1) + fib (n - 2);;
val fib : int -> int =
```
```
# fib 10;;
- : int = 55
```
[](#s:datatypes)1.2 Data types
--------------------------------
In addition to integers and floating-point numbers, OCaml offers the usual basic data types:
* booleans
```
# (1 < 2) = false;;
- : bool = false
```
```
# let one = if true then 1 else 2;;
val one : int = 1
```
* characters
```
# 'a';;
- : char = 'a'
```
```
# int_of_char '\n';;
- : int = 10
```
* immutable character strings
```
# "Hello" ^ " " ^ "world";;
- : string = "Hello world"
```
```
# {|This is a quoted string, here, neither \ nor " are special characters|};;
- : string =
"This is a quoted string, here, neither \\ nor \" are special characters"
```
```
# {|"\\"|}="\"\\\\\"";;
- : bool = true
```
```
# {delimiter|the end of this|}quoted string is here|delimiter}
= "the end of this|}quoted string is here";;
- : bool = true
```
Predefined data structures include tuples, arrays, and lists. There are also general mechanisms for defining your own data structures, such as records and variants, which will be covered in more detail later; for now, we concentrate on lists. Lists are either given in extension as a bracketed list of semicolon-separated elements, or built from the empty list [] (pronounce “nil”) by adding elements in front using the :: (“cons”) operator.
```
# let l = ["is"; "a"; "tale"; "told"; "etc."];;
val l : string list = ["is"; "a"; "tale"; "told"; "etc."]
```
```
# "Life" :: l;;
- : string list = ["Life"; "is"; "a"; "tale"; "told"; "etc."]
```
As with all other OCaml data structures, lists do not need to be explicitly allocated and deallocated from memory: all memory management is entirely automatic in OCaml. Similarly, there is no explicit handling of pointers: the OCaml compiler silently introduces pointers where necessary.
As with most OCaml data structures, inspecting and destructuring lists is performed by pattern-matching. List patterns have exactly the same form as list expressions, with identifiers representing unspecified parts of the list. As an example, here is insertion sort on a list:
```
# let rec sort lst =
match lst with
[] -> []
| head :: tail -> insert head (sort tail)
and insert elt lst =
match lst with
[] -> [elt]
| head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail
;;
val sort : 'a list -> 'a list =
val insert : 'a -> 'a list -> 'a list =
```
```
# sort l;;
- : string list = ["a"; "etc."; "is"; "tale"; "told"]
```
The type inferred for sort, 'a list -> 'a list, means that sort can actually apply to lists of any type, and returns a list of the same type. The type 'a is a *type variable*, and stands for any given type. The reason why sort can apply to lists of any type is that the comparisons (=, <=, etc.) are *polymorphic* in OCaml: they operate between any two values of the same type. This makes sort itself polymorphic over all list types.
```
# sort [6; 2; 5; 3];;
- : int list = [2; 3; 5; 6]
```
```
# sort [3.14; 2.718];;
- : float list = [2.718; 3.14]
```
The sort function above does not modify its input list: it builds and returns a new list containing the same elements as the input list, in ascending order. There is actually no way in OCaml to modify a list in-place once it is built: we say that lists are *immutable* data structures. Most OCaml data structures are immutable, but a few (most notably arrays) are *mutable*, meaning that they can be modified in-place at any time.
The OCaml notation for the type of a function with multiple arguments is
arg1\_type -> arg2\_type -> ... -> return\_type. For example, the type inferred for insert, 'a -> 'a list -> 'a list, means that insert takes two arguments, an element of any type 'a and a list with elements of the same type 'a and returns a list of the same type.
[](#s:functions-as-values)1.3 Functions as values
---------------------------------------------------
OCaml is a functional language: functions in the full mathematical sense are supported and can be passed around freely just as any other piece of data. For instance, here is a deriv function that takes any float function as argument and returns an approximation of its derivative function:
```
# let deriv f dx = fun x -> (f (x +. dx) -. f x) /. dx;;
val deriv : (float -> float) -> float -> float -> float =
```
```
# let sin' = deriv sin 1e-6;;
val sin' : float -> float =
```
```
# sin' pi;;
- : float = -1.00000000013961143
```
Even function composition is definable:
```
# let compose f g = fun x -> f (g x);;
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b =
```
```
# let cos2 = compose square cos;;
val cos2 : float -> float =
```
Functions that take other functions as arguments are called “functionals”, or “higher-order functions”. Functionals are especially useful to provide iterators or similar generic operations over a data structure. For instance, the standard OCaml library provides a List.map functional that applies a given function to each element of a list, and returns the list of the results:
```
# List.map (fun n -> n * 2 + 1) [0;1;2;3;4];;
- : int list = [1; 3; 5; 7; 9]
```
This functional, along with a number of other list and array functionals, is predefined because it is often useful, but there is nothing magic with it: it can easily be defined as follows.
```
# let rec map f l =
match l with
[] -> []
| hd :: tl -> f hd :: map f tl;;
val map : ('a -> 'b) -> 'a list -> 'b list =
```
[](#s:tut-recvariants)1.4 Records and variants
------------------------------------------------
User-defined data structures include records and variants. Both are defined with the type declaration. Here, we declare a record type to represent rational numbers.
```
# type ratio = {num: int; denom: int};;
type ratio = { num : int; denom : int; }
```
```
# let add_ratio r1 r2 =
{num = r1.num * r2.denom + r2.num * r1.denom;
denom = r1.denom * r2.denom};;
val add_ratio : ratio -> ratio -> ratio =
```
```
# add_ratio {num=1; denom=3} {num=2; denom=5};;
- : ratio = {num = 11; denom = 15}
```
Record fields can also be accessed through pattern-matching:
```
# let integer_part r =
match r with
{num=num; denom=denom} -> num / denom;;
val integer_part : ratio -> int =
```
Since there is only one case in this pattern matching, it is safe to expand directly the argument r in a record pattern:
```
# let integer_part {num=num; denom=denom} = num / denom;;
val integer_part : ratio -> int =
```
Unneeded fields can be omitted:
```
# let get_denom {denom=denom} = denom;;
val get_denom : ratio -> int =
```
Optionally, missing fields can be made explicit by ending the list of fields with a trailing wildcard \_::
```
# let get_num {num=num; _ } = num;;
val get_num : ratio -> int =
```
When both sides of the = sign are the same, it is possible to avoid repeating the field name by eliding the =field part:
```
# let integer_part {num; denom} = num / denom;;
val integer_part : ratio -> int =
```
This short notation for fields also works when constructing records:
```
# let ratio num denom = {num; denom};;
val ratio : int -> int -> ratio =
```
At last, it is possible to update few fields of a record at once:
```
# let integer_product integer ratio = { ratio with num = integer * ratio.num };;
val integer_product : int -> ratio -> ratio =
```
With this functional update notation, the record on the left-hand side of with is copied except for the fields on the right-hand side which are updated.
The declaration of a variant type lists all possible forms for values of that type. Each case is identified by a name, called a constructor, which serves both for constructing values of the variant type and inspecting them by pattern-matching. Constructor names are capitalized to distinguish them from variable names (which must start with a lowercase letter). For instance, here is a variant type for doing mixed arithmetic (integers and floats):
```
# type number = Int of int | Float of float | Error;;
type number = Int of int | Float of float | Error
```
This declaration expresses that a value of type number is either an integer, a floating-point number, or the constant Error representing the result of an invalid operation (e.g. a division by zero).
Enumerated types are a special case of variant types, where all alternatives are constants:
```
# type sign = Positive | Negative;;
type sign = Positive | Negative
```
```
# let sign_int n = if n >= 0 then Positive else Negative;;
val sign_int : int -> sign =
```
To define arithmetic operations for the number type, we use pattern-matching on the two numbers involved:
```
# let add_num n1 n2 =
match (n1, n2) with
(Int i1, Int i2) ->
(* Check for overflow of integer addition *)
if sign_int i1 = sign_int i2 && sign_int (i1 + i2) <> sign_int i1
then Float(float i1 +. float i2)
else Int(i1 + i2)
| (Int i1, Float f2) -> Float(float i1 +. f2)
| (Float f1, Int i2) -> Float(f1 +. float i2)
| (Float f1, Float f2) -> Float(f1 +. f2)
| (Error, _) -> Error
| (_, Error) -> Error;;
val add_num : number -> number -> number =
```
```
# add_num (Int 123) (Float 3.14159);;
- : number = Float 126.14159
```
Another interesting example of variant type is the built-in 'a option type which represents either a value of type 'a or an absence of value:
```
# type 'a option = Some of 'a | None;;
type 'a option = Some of 'a | None
```
This type is particularly useful when defining function that can fail in common situations, for instance
```
# let safe_square_root x = if x > 0. then Some(sqrt x) else None;;
val safe_square_root : float -> float option =
```
The most common usage of variant types is to describe recursive data structures. Consider for example the type of binary trees:
```
# type 'a btree = Empty | Node of 'a * 'a btree * 'a btree;;
type 'a btree = Empty | Node of 'a * 'a btree * 'a btree
```
This definition reads as follows: a binary tree containing values of type 'a (an arbitrary type) is either empty, or is a node containing one value of type 'a and two subtrees also containing values of type 'a, that is, two 'a btree.
Operations on binary trees are naturally expressed as recursive functions following the same structure as the type definition itself. For instance, here are functions performing lookup and insertion in ordered binary trees (elements increase from left to right):
```
# let rec member x btree =
match btree with
Empty -> false
| Node(y, left, right) ->
if x = y then true else
if x < y then member x left else member x right;;
val member : 'a -> 'a btree -> bool =
```
```
# let rec insert x btree =
match btree with
Empty -> Node(x, Empty, Empty)
| Node(y, left, right) ->
if x <= y then Node(y, insert x left, right)
else Node(y, left, insert x right);;
val insert : 'a -> 'a btree -> 'a btree =
```
###
[](#ss:record-and-variant-disambiguation)1.4.1 Record and variant disambiguation
( This subsection can be skipped on the first reading )
Astute readers may have wondered what happens when two or more record fields or constructors share the same name
```
# type first_record = { x:int; y:int; z:int }
type middle_record = { x:int; z:int }
type last_record = { x:int };;
```
```
# type first_variant = A | B | C
type last_variant = A;;
```
The answer is that when confronted with multiple options, OCaml tries to use locally available information to disambiguate between the various fields and constructors. First, if the type of the record or variant is known, OCaml can pick unambiguously the corresponding field or constructor. For instance:
```
# let look_at_x_then_z (r:first_record) =
let x = r.x in
x + r.z;;
val look_at_x_then_z : first_record -> int =
```
```
# let permute (x:first_variant) = match x with
| A -> (B:first_variant)
| B -> A
| C -> C;;
val permute : first_variant -> first_variant =
```
```
# type wrapped = First of first_record
let f (First r) = r, r.x;;
type wrapped = First of first_record
val f : wrapped -> first_record * int =
```
In the first example, (r:first\_record) is an explicit annotation telling OCaml that the type of r is first\_record. With this annotation, Ocaml knows that r.x refers to the x field of the first record type. Similarly, the type annotation in the second example makes it clear to OCaml that the constructors A, B and C come from the first variant type. Contrarily, in the last example, OCaml has inferred by itself that the type of r can only be first\_record and there are no needs for explicit type annotations.
Those explicit type annotations can in fact be used anywhere. Most of the time they are unnecessary, but they are useful to guide disambiguation, to debug unexpected type errors, or combined with some of the more advanced features of OCaml described in later chapters.
Secondly, for records, OCaml can also deduce the right record type by looking at the whole set of fields used in a expression or pattern:
```
# let project_and_rotate {x; y; _} = { x= - y; y = x; z = 0} ;;
val project_and_rotate : first_record -> first_record =
```
Since the fields x and y can only appear simultaneously in the first record type, OCaml infers that the type of project\_and\_rotate is first\_record -> first\_record.
In last resort, if there is not enough information to disambiguate between different fields or constructors, Ocaml picks the last defined type amongst all locally valid choices:
```
# let look_at_xz {x; z} = x;;
val look_at_xz : middle_record -> int =
```
Here, OCaml has inferred that the possible choices for the type of {x;z} are first\_record and middle\_record, since the type last\_record has no field z. Ocaml then picks the type middle\_record as the last defined type between the two possibilities.
Beware that this last resort disambiguation is local: once Ocaml has chosen a disambiguation, it sticks to this choice, even if it leads to an ulterior type error:
```
# let look_at_x_then_y r =
let x = r.x in (* Ocaml deduces [r: last_record] *)
x + r.y;;
Error: This expression has type last_record
There is no field y within type last_record
```
```
# let is_a_or_b x = match x with
| A -> true (* OCaml infers [x: last_variant] *)
| B -> true;;
Error: This variant pattern is expected to have type last_variant
There is no constructor B within type last_variant
```
Moreover, being the last defined type is a quite unstable position that may change surreptitiously after adding or moving around a type definition, or after opening a module (see chapter [2](moduleexamples#c%3Amoduleexamples)). Consequently, adding explicit type annotations to guide disambiguation is more robust than relying on the last defined type disambiguation.
[](#s:imperative-features)1.5 Imperative features
---------------------------------------------------
Though all examples so far were written in purely applicative style, OCaml is also equipped with full imperative features. This includes the usual while and for loops, as well as mutable data structures such as arrays. Arrays are either created by listing semicolon-separated element values between [| and |] brackets, or allocated and initialized with the Array.make function, then filled up later by assignments. For instance, the function below sums two vectors (represented as float arrays) componentwise.
```
# let add_vect v1 v2 =
let len = min (Array.length v1) (Array.length v2) in
let res = Array.make len 0.0 in
for i = 0 to len - 1 do
res.(i) <- v1.(i) +. v2.(i)
done;
res;;
val add_vect : float array -> float array -> float array =
```
```
# add_vect [| 1.0; 2.0 |] [| 3.0; 4.0 |];;
- : float array = [|4.; 6.|]
```
Record fields can also be modified by assignment, provided they are declared mutable in the definition of the record type:
```
# type mutable_point = { mutable x: float; mutable y: float };;
type mutable_point = { mutable x : float; mutable y : float; }
```
```
# let translate p dx dy =
p.x <- p.x +. dx; p.y <- p.y +. dy;;
val translate : mutable_point -> float -> float -> unit =
```
```
# let mypoint = { x = 0.0; y = 0.0 };;
val mypoint : mutable_point = {x = 0.; y = 0.}
```
```
# translate mypoint 1.0 2.0;;
- : unit = ()
```
```
# mypoint;;
- : mutable_point = {x = 1.; y = 2.}
```
OCaml has no built-in notion of variable – identifiers whose current value can be changed by assignment. (The let binding is not an assignment, it introduces a new identifier with a new scope.) However, the standard library provides references, which are mutable indirection cells, with operators ! to fetch the current contents of the reference and := to assign the contents. Variables can then be emulated by let-binding a reference. For instance, here is an in-place insertion sort over arrays:
```
# let insertion_sort a =
for i = 1 to Array.length a - 1 do
let val_i = a.(i) in
let j = ref i in
while !j > 0 && val_i < a.(!j - 1) do
a.(!j) <- a.(!j - 1);
j := !j - 1
done;
a.(!j) <- val_i
done;;
val insertion_sort : 'a array -> unit =
```
References are also useful to write functions that maintain a current state between two calls to the function. For instance, the following pseudo-random number generator keeps the last returned number in a reference:
```
# let current_rand = ref 0;;
val current_rand : int ref = {contents = 0}
```
```
# let random () =
current_rand := !current_rand * 25713 + 1345;
!current_rand;;
val random : unit -> int =
```
Again, there is nothing magical with references: they are implemented as a single-field mutable record, as follows.
```
# type 'a ref = { mutable contents: 'a };;
type 'a ref = { mutable contents : 'a; }
```
```
# let ( ! ) r = r.contents;;
val ( ! ) : 'a ref -> 'a =
```
```
# let ( := ) r newval = r.contents <- newval;;
val ( := ) : 'a ref -> 'a -> unit =
```
In some special cases, you may need to store a polymorphic function in a data structure, keeping its polymorphism. Doing this requires user-provided type annotations, since polymorphism is only introduced automatically for global definitions. However, you can explicitly give polymorphic types to record fields.
```
# type idref = { mutable id: 'a. 'a -> 'a };;
type idref = { mutable id : 'a. 'a -> 'a; }
```
```
# let r = {id = fun x -> x};;
val r : idref = {id = }
```
```
# let g s = (s.id 1, s.id true);;
val g : idref -> int * bool =
```
```
# r.id <- (fun x -> print_string "called id\n"; x);;
- : unit = ()
```
```
# g r;;
called id
called id
- : int * bool = (1, true)
```
[](#s:exceptions)1.6 Exceptions
---------------------------------
OCaml provides exceptions for signalling and handling exceptional conditions. Exceptions can also be used as a general-purpose non-local control structure, although this should not be overused since it can make the code harder to understand. Exceptions are declared with the exception construct, and signalled with the raise operator. For instance, the function below for taking the head of a list uses an exception to signal the case where an empty list is given.
```
# exception Empty_list;;
exception Empty_list
```
```
# let head l =
match l with
[] -> raise Empty_list
| hd :: tl -> hd;;
val head : 'a list -> 'a =
```
```
# head [1; 2];;
- : int = 1
```
```
# head [];;
Exception: Empty_list.
```
Exceptions are used throughout the standard library to signal cases where the library functions cannot complete normally. For instance, the List.assoc function, which returns the data associated with a given key in a list of (key, data) pairs, raises the predefined exception Not\_found when the key does not appear in the list:
```
# List.assoc 1 [(0, "zero"); (1, "one")];;
- : string = "one"
```
```
# List.assoc 2 [(0, "zero"); (1, "one")];;
Exception: Not_found.
```
Exceptions can be trapped with the try…with construct:
```
# let name_of_binary_digit digit =
try
List.assoc digit [0, "zero"; 1, "one"]
with Not_found ->
"not a binary digit";;
val name_of_binary_digit : int -> string =
```
```
# name_of_binary_digit 0;;
- : string = "zero"
```
```
# name_of_binary_digit (-1);;
- : string = "not a binary digit"
```
The with part does pattern matching on the exception value with the same syntax and behavior as match. Thus, several exceptions can be caught by one try…with construct:
```
# let rec first_named_value values names =
try
List.assoc (head values) names
with
| Empty_list -> "no named value"
| Not_found -> first_named_value (List.tl values) names;;
val first_named_value : 'a list -> ('a * string) list -> string =
```
```
# first_named_value [0; 10] [1, "one"; 10, "ten"];;
- : string = "ten"
```
Also, finalization can be performed by trapping all exceptions, performing the finalization, then re-raising the exception:
```
# let temporarily_set_reference ref newval funct =
let oldval = !ref in
try
ref := newval;
let res = funct () in
ref := oldval;
res
with x ->
ref := oldval;
raise x;;
val temporarily_set_reference : 'a ref -> 'a -> (unit -> 'b) -> 'b =
```
An alternative to try…with is to catch the exception while pattern matching:
```
# let assoc_may_map f x l =
match List.assoc x l with
| exception Not_found -> None
| y -> f y;;
val assoc_may_map : ('a -> 'b option) -> 'c -> ('c * 'a) list -> 'b option =
```
Note that this construction is only useful if the exception is raised between match…with. Exception patterns can be combined with ordinary patterns at the toplevel,
```
# let flat_assoc_opt x l =
match List.assoc x l with
| None | exception Not_found -> None
| Some _ as v -> v;;
val flat_assoc_opt : 'a -> ('a * 'b option) list -> 'b option =
```
but they cannot be nested inside other patterns. For instance, the pattern Some (exception A) is invalid.
When exceptions are used as a control structure, it can be useful to make them as local as possible by using a locally defined exception. For instance, with
```
# let fixpoint f x =
let exception Done in
let x = ref x in
try while true do
let y = f !x in
if !x = y then raise Done else x := y
done; assert false
with Done -> !x;;
val fixpoint : ('a -> 'a) -> 'a -> 'a =
```
the function f cannot raise a Done exception, which removes an entire class of misbehaving functions.
[](#s:lazy-expr)1.7 Lazy expressions
--------------------------------------
OCaml allows us to defer some computation until later when we need the result of that computation.
We use lazy (expr) to delay the evaluation of some expression expr. For example, we can defer the computation of 1+1 until we need the result of that expression, 2. Let us see how we initialize a lazy expression.
```
# let lazy_two = lazy (print_endline "lazy_two evaluation"; 1 + 1);;
val lazy_two : int lazy_t =
```
We added print\_endline "lazy\_two evaluation" to see when the lazy expression is being evaluated.
The value of lazy\_two is displayed as <lazy>, which means the expression has not been evaluated yet, and its final value is unknown.
Note that lazy\_two has type int lazy\_t. However, the type 'a lazy\_t is an internal type name, so the type 'a Lazy.t should be preferred when possible.
When we finally need the result of a lazy expression, we can call Lazy.force on that expression to force its evaluation. The function force comes from standard-library module [Lazy](libref/lazy).
```
# Lazy.force lazy_two;;
lazy_two evaluation
- : int = 2
```
Notice that our function call above prints “lazy\_two evaluation” and then returns the plain value of the computation.
Now if we look at the value of lazy\_two, we see that it is not displayed as <lazy> anymore but as lazy 2.
```
# lazy_two;;
- : int lazy_t = lazy 2
```
This is because Lazy.force memoizes the result of the forced expression. In other words, every subsequent call of Lazy.force on that expression returns the result of the first computation without recomputing the lazy expression. Let us force lazy\_two once again.
```
# Lazy.force lazy_two;;
- : int = 2
```
The expression is not evaluated this time; notice that “lazy\_two evaluation” is not printed. The result of the initial computation is simply returned.
Lazy patterns provide another way to force a lazy expression.
```
# let lazy_l = lazy ([1; 2] @ [3; 4]);;
val lazy_l : int list lazy_t =
```
```
# let lazy l = lazy_l;;
val l : int list = [1; 2; 3; 4]
```
We can also use lazy patterns in pattern matching.
```
# let maybe_eval lazy_guard lazy_expr =
match lazy_guard, lazy_expr with
| lazy false, _ -> "matches if (Lazy.force lazy_guard = false); lazy_expr not forced"
| lazy true, lazy _ -> "matches if (Lazy.force lazy_guard = true); lazy_expr forced";;
val maybe_eval : bool lazy_t -> 'a lazy_t -> string =
```
The lazy expression lazy\_expr is forced only if the lazy\_guard value yields true once computed. Indeed, a simple wildcard pattern (not lazy) never forces the lazy expression’s evaluation. However, a pattern with keyword lazy, even if it is wildcard, always forces the evaluation of the deferred computation.
[](#s:symb-expr)1.8 Symbolic processing of expressions
--------------------------------------------------------
We finish this introduction with a more complete example representative of the use of OCaml for symbolic processing: formal manipulations of arithmetic expressions containing variables. The following variant type describes the expressions we shall manipulate:
```
# type expression =
Const of float
| Var of string
| Sum of expression * expression (* e1 + e2 *)
| Diff of expression * expression (* e1 - e2 *)
| Prod of expression * expression (* e1 * e2 *)
| Quot of expression * expression (* e1 / e2 *)
;;
type expression =
Const of float
| Var of string
| Sum of expression * expression
| Diff of expression * expression
| Prod of expression * expression
| Quot of expression * expression
```
We first define a function to evaluate an expression given an environment that maps variable names to their values. For simplicity, the environment is represented as an association list.
```
# exception Unbound_variable of string;;
exception Unbound_variable of string
```
```
# let rec eval env exp =
match exp with
Const c -> c
| Var v ->
(try List.assoc v env with Not_found -> raise (Unbound_variable v))
| Sum(f, g) -> eval env f +. eval env g
| Diff(f, g) -> eval env f -. eval env g
| Prod(f, g) -> eval env f *. eval env g
| Quot(f, g) -> eval env f /. eval env g;;
val eval : (string * float) list -> expression -> float =
```
```
# eval [("x", 1.0); ("y", 3.14)] (Prod(Sum(Var "x", Const 2.0), Var "y"));;
- : float = 9.42
```
Now for a real symbolic processing, we define the derivative of an expression with respect to a variable dv:
```
# let rec deriv exp dv =
match exp with
Const c -> Const 0.0
| Var v -> if v = dv then Const 1.0 else Const 0.0
| Sum(f, g) -> Sum(deriv f dv, deriv g dv)
| Diff(f, g) -> Diff(deriv f dv, deriv g dv)
| Prod(f, g) -> Sum(Prod(f, deriv g dv), Prod(deriv f dv, g))
| Quot(f, g) -> Quot(Diff(Prod(deriv f dv, g), Prod(f, deriv g dv)),
Prod(g, g))
;;
val deriv : expression -> string -> expression =
```
```
# deriv (Quot(Const 1.0, Var "x")) "x";;
- : expression =
Quot (Diff (Prod (Const 0., Var "x"), Prod (Const 1., Const 1.)),
Prod (Var "x", Var "x"))
```
[](#s:pretty-printing)1.9 Pretty-printing
-------------------------------------------
As shown in the examples above, the internal representation (also called *abstract syntax*) of expressions quickly becomes hard to read and write as the expressions get larger. We need a printer and a parser to go back and forth between the abstract syntax and the *concrete syntax*, which in the case of expressions is the familiar algebraic notation (e.g. 2\*x+1).
For the printing function, we take into account the usual precedence rules (i.e. \* binds tighter than +) to avoid printing unnecessary parentheses. To this end, we maintain the current operator precedence and print parentheses around an operator only if its precedence is less than the current precedence.
```
# let print_expr exp =
(* Local function definitions *)
let open_paren prec op_prec =
if prec > op_prec then print_string "(" in
let close_paren prec op_prec =
if prec > op_prec then print_string ")" in
let rec print prec exp = (* prec is the current precedence *)
match exp with
Const c -> print_float c
| Var v -> print_string v
| Sum(f, g) ->
open_paren prec 0;
print 0 f; print_string " + "; print 0 g;
close_paren prec 0
| Diff(f, g) ->
open_paren prec 0;
print 0 f; print_string " - "; print 1 g;
close_paren prec 0
| Prod(f, g) ->
open_paren prec 2;
print 2 f; print_string " * "; print 2 g;
close_paren prec 2
| Quot(f, g) ->
open_paren prec 2;
print 2 f; print_string " / "; print 3 g;
close_paren prec 2
in print 0 exp;;
val print_expr : expression -> unit =
```
```
# let e = Sum(Prod(Const 2.0, Var "x"), Const 1.0);;
val e : expression = Sum (Prod (Const 2., Var "x"), Const 1.)
```
```
# print_expr e; print_newline ();;
2. * x + 1.
- : unit = ()
```
```
# print_expr (deriv e "x"); print_newline ();;
2. * 1. + 0. * x + 0.
- : unit = ()
```
[](#s:printf)1.10 Printf formats
----------------------------------
There is a printf function in the [Printf](libref/printf) module (see chapter [2](moduleexamples#c%3Amoduleexamples)) that allows you to make formatted output more concisely. It follows the behavior of the printf function from the C standard library. The printf function takes a format string that describes the desired output as a text interspersed with specifiers (for instance %d, %f). Next, the specifiers are substituted by the following arguments in their order of apparition in the format string:
```
# Printf.printf "%i + %i is an integer value, %F * %F is a float, %S\n"
3 2 4.5 1. "this is a string";;
3 + 2 is an integer value, 4.5 * 1. is a float, "this is a string"
- : unit = ()
```
The OCaml type system checks that the type of the arguments and the specifiers are compatible. If you pass it an argument of a type that does not correspond to the format specifier, the compiler will display an error message:
```
# Printf.printf "Float value: %F" 42;;
Error: This expression has type int but an expression was expected of type
float
Hint: Did you mean `42.'?
```
The fprintf function is like printf except that it takes an output channel as the first argument. The %a specifier can be useful to define custom printers (for custom types). For instance, we can create a printing template that converts an integer argument to signed decimal:
```
# let pp_int ppf n = Printf.fprintf ppf "%d" n;;
val pp_int : out_channel -> int -> unit =
```
```
# Printf.printf "Outputting an integer using a custom printer: %a " pp_int 42;;
Outputting an integer using a custom printer: 42 - : unit = ()
```
The advantage of those printers based on the %a specifier is that they can be composed together to create more complex printers step by step. We can define a combinator that can turn a printer for 'a type into a printer for 'a optional:
```
# let pp_option printer ppf = function
| None -> Printf.fprintf ppf "None"
| Some v -> Printf.fprintf ppf "Some(%a)" printer v;;
val pp_option :
(out_channel -> 'a -> unit) -> out_channel -> 'a option -> unit =
```
```
# Printf.fprintf stdout
"The current setting is %a. \nThere is only %a\n"
(pp_option pp_int) (Some 3)
(pp_option pp_int) None
;;
The current setting is Some(3).
There is only None
- : unit = ()
```
If the value of its argument its None, the printer returned by pp\_option printer prints None otherwise it uses the provided printer to print Some .
Here is how to rewrite the pretty-printer using fprintf:
```
# let pp_expr ppf expr =
let open_paren prec op_prec output =
if prec > op_prec then Printf.fprintf output "%s" "(" in
let close_paren prec op_prec output =
if prec > op_prec then Printf.fprintf output "%s" ")" in
let rec print prec ppf expr =
match expr with
| Const c -> Printf.fprintf ppf "%F" c
| Var v -> Printf.fprintf ppf "%s" v
| Sum(f, g) ->
open_paren prec 0 ppf;
Printf.fprintf ppf "%a + %a" (print 0) f (print 0) g;
close_paren prec 0 ppf
| Diff(f, g) ->
open_paren prec 0 ppf;
Printf.fprintf ppf "%a - %a" (print 0) f (print 1) g;
close_paren prec 0 ppf
| Prod(f, g) ->
open_paren prec 2 ppf;
Printf.fprintf ppf "%a * %a" (print 2) f (print 2) g;
close_paren prec 2 ppf
| Quot(f, g) ->
open_paren prec 2 ppf;
Printf.fprintf ppf "%a / %a" (print 2) f (print 3) g;
close_paren prec 2 ppf
in print 0 ppf expr;;
val pp_expr : out_channel -> expression -> unit =
```
```
# pp_expr stdout e; print_newline ();;
2. * x + 1.
- : unit = ()
```
```
# pp_expr stdout (deriv e "x"); print_newline ();;
2. * 1. + 0. * x + 0.
- : unit = ()
```
Due to the way that format strings are built, storing a format string requires an explicit type annotation:
```
# let str : _ format =
"%i is an integer value, %F is a float, %S\n";;
```
```
# Printf.printf str 3 4.5 "string value";;
3 is an integer value, 4.5 is a float, "string value"
- : unit = ()
```
[](#s:standalone-programs)1.11 Standalone OCaml programs
----------------------------------------------------------
All examples given so far were executed under the interactive system. OCaml code can also be compiled separately and executed non-interactively using the batch compilers ocamlc and ocamlopt. The source code must be put in a file with extension .ml. It consists of a sequence of phrases, which will be evaluated at runtime in their order of appearance in the source file. Unlike in interactive mode, types and values are not printed automatically; the program must call printing functions explicitly to produce some output. The ;; used in the interactive examples is not required in source files created for use with OCaml compilers, but can be helpful to mark the end of a top-level expression unambiguously even when there are syntax errors. Here is a sample standalone program to print the greatest common divisor (gcd) of two numbers:
```
(* File gcd.ml *)
let rec gcd a b =
if b = 0 then a
else gcd b (a mod b);;
let main () =
let a = int_of_string Sys.argv.(1) in
let b = int_of_string Sys.argv.(2) in
Printf.printf "%d\n" (gcd a b);
exit 0;;
main ();;
```
Sys.argv is an array of strings containing the command-line parameters. Sys.argv.(1) is thus the first command-line parameter. The program above is compiled and executed with the following shell commands:
```
$ ocamlc -o gcd gcd.ml
$ ./gcd 6 9
3
$ ./gcd 7 11
1
```
More complex standalone OCaml programs are typically composed of multiple source files, and can link with precompiled libraries. Chapters [13](comp#c%3Acamlc) and [16](native#c%3Anativecomp) explain how to use the batch compilers ocamlc and ocamlopt. Recompilation of multi-file OCaml projects can be automated using third-party build systems, such as [dune](https://github.com/ocaml/dune).
| programming_docs |
ocaml Chapter 34 The dynlink library: dynamic loading and linking of object files Chapter 34 The dynlink library: dynamic loading and linking of object files
===========================================================================
The dynlink library supports type-safe dynamic loading and linking of bytecode object files (.cmo and .cma files) in a running bytecode program, or of native plugins (usually .cmxs files) in a running native program. Type safety is ensured by limiting the set of modules from the running program that the loaded object file can access, and checking that the running program and the loaded object file have been compiled against the same interfaces for these modules. In native code, there are also some compatibility checks on the implementations (to avoid errors with cross-module optimizations); it might be useful to hide .cmx files when building native plugins so that they remain independent of the implementation of modules in the main program.
Programs that use the dynlink library simply need to include the dynlink library directory with -I +dynlink and link dynlink.cma or dynlink.cmxa with their object files and other libraries.
Note: in order to insure that the dynamically-loaded modules have access to all the libraries that are visible to the main program (and not just to the parts of those libraries that are actually used in the main program), programs using the dynlink library should be linked with -linkall.
* [Module Dynlink](libref/dynlink): dynamic loading of bytecode object files
ocaml None
[](#s:signature-substitution)12.7 Substituting inside a signature
-------------------------------------------------------------------
* [12.7.1 Destructive substitutions](signaturesubstitution#ss%3Adestructive-substitution)
* [12.7.2 Local substitution declarations](signaturesubstitution#ss%3Alocal-substitution)
* [12.7.3 Module type substitutions](signaturesubstitution#ss%3Amodule-type-substitution)
###
[](#ss:destructive-substitution)12.7.1 Destructive substitutions
(Introduced in OCaml 3.12, generalized in 4.06)
| | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [mod-constraint](modtypes#mod-constraint) | ::= | ... |
| | ∣ | type [[type-params](typedecl#type-params)] [typeconstr-name](names#typeconstr-name) := [typexpr](types#typexpr) |
| | ∣ | module [module-path](names#module-path) := [extended-module-path](names#extended-module-path) |
|
A “destructive” substitution (with ... := ...) behaves essentially like normal signature constraints (with ... = ...), but it additionally removes the redefined type or module from the signature.
Prior to OCaml 4.06, there were a number of restrictions: one could only remove types and modules at the outermost level (not inside submodules), and in the case of with type the definition had to be another type constructor with the same type parameters.
A natural application of destructive substitution is merging two signatures sharing a type name.
```
module type Printable = sig
type t
val print : Format.formatter -> t -> unit
end
module type Comparable = sig
type t
val compare : t -> t -> int
end
module type PrintableComparable = sig
include Printable
include Comparable with type t := t
end
```
One can also use this to completely remove a field:
```
module type S = Comparable with type t := int
module type S = sig val compare : int -> int -> int end
```
or to rename one:
```
module type S = sig
type u
include Comparable with type t := u
end
module type S = sig type u val compare : u -> u -> int end
```
Note that you can also remove manifest types, by substituting with the same type.
```
module type ComparableInt = Comparable with type t = int ;;
module type ComparableInt = sig type t = int val compare : t -> t -> int end
```
```
module type CompareInt = ComparableInt with type t := int
module type CompareInt = sig val compare : int -> int -> int end
```
###
[](#ss:local-substitution)12.7.2 Local substitution declarations
(Introduced in OCaml 4.08)
| | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [specification](modtypes#specification) | ::= | ... |
| | ∣ | type [type-subst](#type-subst) { and [type-subst](#type-subst) } |
| | ∣ | module [module-name](names#module-name) := [extended-module-path](names#extended-module-path) |
| | ∣ | module type [module-name](names#module-name) := [module-type](modtypes#module-type) |
| |
| type-subst | ::= | [[type-params](typedecl#type-params)] [typeconstr-name](names#typeconstr-name) := [typexpr](types#typexpr) { [type-constraint](typedecl#type-constraint) } |
|
Local substitutions behave like destructive substitutions (with ... := ...) but instead of being applied to a whole signature after the fact, they are introduced during the specification of the signature, and will apply to all the items that follow.
This provides a convenient way to introduce local names for types and modules when defining a signature:
```
module type S = sig
type t
module Sub : sig
type outer := t
type t
val to_outer : t -> outer
end
end
module type S =
sig type t module Sub : sig type t val to_outer : t/1 -> t/2 end end
```
Note that, unlike type declarations, type substitution declarations are not recursive, so substitutions like the following are rejected:
```
# module type S = sig
type 'a poly_list := [ `Cons of 'a * 'a poly_list | `Nil ]
end ;;
Error: Unbound type constructor poly_list
```
###
[](#ss:module-type-substitution)12.7.3 Module type substitutions
(Introduced in OCaml 4.13)
| | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [mod-constraint](modtypes#mod-constraint) | ::= | ... |
| | ∣ | module type [modtype-path](names#modtype-path) = [module-type](modtypes#module-type) |
| | ∣ | module type [modtype-path](names#modtype-path) := [module-type](modtypes#module-type) |
|
Module type substitution essentially behaves like type substitutions. They are useful to refine an abstract module type in a signature into a concrete module type,
```
# module type ENDO = sig
module type T
module F: T -> T
end
module Endo(X: sig module type T end): ENDO with module type T = X.T =
struct
module type T = X.T
module F(X:T) = X
end;;
module type ENDO = sig module type T module F : T -> T end
module Endo :
functor (X : sig module type T end) ->
sig module type T = X.T module F : T -> T end
```
It is also possible to substitute a concrete module type with an equivalent module types.
```
module type A = sig
type x
module type R = sig
type a = A of x
type b
end
end
module type S = sig
type a = A of int
type b
end
module type B = A with type x = int and module type R = S
```
However, such substitutions are never necessary.
Destructive module type substitution removes the module type substitution from the signature
```
# module type ENDO' = ENDO with module type T := ENDO;;
module type ENDO' = sig module F : ENDO -> ENDO end
```
If the right hand side of the substitution is not a path, then the destructive substitution is only valid if the left-hand side of the substitution is never used as the type of a first-class module in the original module type.
```
module type T = sig module type S val x: (module S) end
module type Error = T with module type S := sig end
Error: This `with' constraint S := sig end makes a packed module ill-formed.
```
ocaml None
[](#s:classes)11.9 Classes
----------------------------
* [11.9.1 Class types](classes#ss%3Aclasses%3Aclass-types)
* [11.9.2 Class expressions](classes#ss%3Aclass-expr)
* [11.9.3 Class definitions](classes#ss%3Aclass-def)
* [11.9.4 Class specifications](classes#ss%3Aclass-spec)
* [11.9.5 Class type definitions](classes#ss%3Aclasstype)
Classes are defined using a small language, similar to the module language.
###
[](#ss:classes:class-types)11.9.1 Class types
Class types are the class-level equivalent of type expressions: they specify the general shape and type properties of classes.
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| class-type | ::= | [[?][label-name](lex#label-name):] [typexpr](types#typexpr) -> [class-type](#class-type) |
| | ∣ | [class-body-type](#class-body-type) |
| |
| class-body-type | ::= | object [( [typexpr](types#typexpr) )] { [class-field-spec](#class-field-spec) } end |
| | ∣ | [[ [typexpr](types#typexpr) { , [typexpr](types#typexpr) } ]] [classtype-path](names#classtype-path) |
| | ∣ | let open [module-path](names#module-path) in [class-body-type](#class-body-type) |
| |
| class-field-spec | ::= | inherit [class-body-type](#class-body-type) |
| | ∣ | val [mutable] [virtual] [inst-var-name](names#inst-var-name) : [typexpr](types#typexpr) |
| | ∣ | val virtual mutable [inst-var-name](names#inst-var-name) : [typexpr](types#typexpr) |
| | ∣ | method [private] [virtual] [method-name](names#method-name) : [poly-typexpr](types#poly-typexpr) |
| | ∣ | method virtual private [method-name](names#method-name) : [poly-typexpr](types#poly-typexpr) |
| | ∣ | constraint [typexpr](types#typexpr) = [typexpr](types#typexpr) |
|
See also the following language extensions: [attributes](attributes#s%3Aattributes) and [extension nodes](extensionnodes#s%3Aextension-nodes).
####
[](#sss:clty:simple)Simple class expressions
The expression [classtype-path](names#classtype-path) is equivalent to the class type bound to the name [classtype-path](names#classtype-path). Similarly, the expression [ [typexpr](types#typexpr)1 , … [typexpr](types#typexpr)n ] [classtype-path](names#classtype-path) is equivalent to the parametric class type bound to the name [classtype-path](names#classtype-path), in which type parameters have been instantiated to respectively [typexpr](types#typexpr)1, …[typexpr](types#typexpr)n.
####
[](#sss:clty-fun)Class function type
The class type expression [typexpr](types#typexpr) -> [class-type](#class-type) is the type of class functions (functions from values to classes) that take as argument a value of type [typexpr](types#typexpr) and return as result a class of type [class-type](#class-type).
####
[](#sss:clty:body)Class body type
The class type expression object [( [typexpr](types#typexpr) )] { [class-field-spec](#class-field-spec) } end is the type of a class body. It specifies its instance variables and methods. In this type, [typexpr](types#typexpr) is matched against the self type, therefore providing a name for the self type.
A class body will match a class body type if it provides definitions for all the components specified in the class body type, and these definitions meet the type requirements given in the class body type. Furthermore, all methods either virtual or public present in the class body must also be present in the class body type (on the other hand, some instance variables and concrete private methods may be omitted). A virtual method will match a concrete method, which makes it possible to forget its implementation. An immutable instance variable will match a mutable instance variable.
####
[](#sss:clty-open)Local opens
Local opens are supported in class types since OCaml 4.06.
####
[](#sss:clty-inheritance)Inheritance
The inheritance construct inherit [class-body-type](#class-body-type) provides for inclusion of methods and instance variables from other class types. The instance variable and method types from [class-body-type](#class-body-type) are added into the current class type.
####
[](#sss:clty-variable)Instance variable specification
A specification of an instance variable is written val [mutable] [virtual] [inst-var-name](names#inst-var-name) : [typexpr](types#typexpr), where [inst-var-name](names#inst-var-name) is the name of the instance variable and [typexpr](types#typexpr) its expected type. The flag mutable indicates whether this instance variable can be physically modified. The flag virtual indicates that this instance variable is not initialized. It can be initialized later through inheritance.
An instance variable specification will hide any previous specification of an instance variable of the same name.
####
[](#sss:clty-meth)Method specification
The specification of a method is written method [private] [method-name](names#method-name) : [poly-typexpr](types#poly-typexpr), where [method-name](names#method-name) is the name of the method and [poly-typexpr](types#poly-typexpr) its expected type, possibly polymorphic. The flag private indicates that the method cannot be accessed from outside the object.
The polymorphism may be left implicit in public method specifications: any type variable which is not bound to a class parameter and does not appear elsewhere inside the class specification will be assumed to be universal, and made polymorphic in the resulting method type. Writing an explicit polymorphic type will disable this behaviour.
If several specifications are present for the same method, they must have compatible types. Any non-private specification of a method forces it to be public.
####
[](#sss:class-virtual-meth-spec)Virtual method specification
A virtual method specification is written method [private] virtual [method-name](names#method-name) : [poly-typexpr](types#poly-typexpr), where [method-name](names#method-name) is the name of the method and [poly-typexpr](types#poly-typexpr) its expected type.
####
[](#sss:class-constraints)Constraints on type parameters
The construct constraint [typexpr](types#typexpr)1 = [typexpr](types#typexpr)2 forces the two type expressions to be equal. This is typically used to specify type parameters: in this way, they can be bound to specific type expressions.
###
[](#ss:class-expr)11.9.2 Class expressions
Class expressions are the class-level equivalent of value expressions: they evaluate to classes, thus providing implementations for the specifications expressed in class types.
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| class-expr | ::= | [class-path](names#class-path) |
| | ∣ | [ [typexpr](types#typexpr) { , [typexpr](types#typexpr) } ] [class-path](names#class-path) |
| | ∣ | ( [class-expr](#class-expr) ) |
| | ∣ | ( [class-expr](#class-expr) : [class-type](#class-type) ) |
| | ∣ | [class-expr](#class-expr) { [argument](expr#argument) }+ |
| | ∣ | fun { [parameter](expr#parameter) }+ -> [class-expr](#class-expr) |
| | ∣ | let [rec] [let-binding](expr#let-binding) { and [let-binding](expr#let-binding) } in [class-expr](#class-expr) |
| | ∣ | object [class-body](#class-body) end |
| | ∣ | let open [module-path](names#module-path) in [class-expr](#class-expr) |
| |
|
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| class-field | ::= | inherit [class-expr](#class-expr) [as [lowercase-ident](lex#lowercase-ident)] |
| | ∣ | inherit! [class-expr](#class-expr) [as [lowercase-ident](lex#lowercase-ident)] |
| | ∣ | val [mutable] [inst-var-name](names#inst-var-name) [: [typexpr](types#typexpr)] = [expr](expr#expr) |
| | ∣ | val! [mutable] [inst-var-name](names#inst-var-name) [: [typexpr](types#typexpr)] = [expr](expr#expr) |
| | ∣ | val [mutable] virtual [inst-var-name](names#inst-var-name) : [typexpr](types#typexpr) |
| | ∣ | val virtual mutable [inst-var-name](names#inst-var-name) : [typexpr](types#typexpr) |
| | ∣ | method [private] [method-name](names#method-name) { [parameter](expr#parameter) } [: [typexpr](types#typexpr)] = [expr](expr#expr) |
| | ∣ | method! [private] [method-name](names#method-name) { [parameter](expr#parameter) } [: [typexpr](types#typexpr)] = [expr](expr#expr) |
| | ∣ | method [private] [method-name](names#method-name) : [poly-typexpr](types#poly-typexpr) = [expr](expr#expr) |
| | ∣ | method! [private] [method-name](names#method-name) : [poly-typexpr](types#poly-typexpr) = [expr](expr#expr) |
| | ∣ | method [private] virtual [method-name](names#method-name) : [poly-typexpr](types#poly-typexpr) |
| | ∣ | method virtual private [method-name](names#method-name) : [poly-typexpr](types#poly-typexpr) |
| | ∣ | constraint [typexpr](types#typexpr) = [typexpr](types#typexpr) |
| | ∣ | initializer [expr](expr#expr) |
|
See also the following language extensions: [locally abstract types](locallyabstract#s%3Alocally-abstract), [attributes](attributes#s%3Aattributes) and [extension nodes](extensionnodes#s%3Aextension-nodes).
####
[](#sss:class-simple)Simple class expressions
The expression [class-path](names#class-path) evaluates to the class bound to the name [class-path](names#class-path). Similarly, the expression [ [typexpr](types#typexpr)1 , … [typexpr](types#typexpr)n ] [class-path](names#class-path) evaluates to the parametric class bound to the name [class-path](names#class-path), in which type parameters have been instantiated respectively to [typexpr](types#typexpr)1, …[typexpr](types#typexpr)n.
The expression ( [class-expr](#class-expr) ) evaluates to the same module as [class-expr](#class-expr).
The expression ( [class-expr](#class-expr) : [class-type](#class-type) ) checks that [class-type](#class-type) matches the type of [class-expr](#class-expr) (that is, that the implementation [class-expr](#class-expr) meets the type specification [class-type](#class-type)). The whole expression evaluates to the same class as [class-expr](#class-expr), except that all components not specified in [class-type](#class-type) are hidden and can no longer be accessed.
####
[](#sss:class-app)Class application
Class application is denoted by juxtaposition of (possibly labeled) expressions. It denotes the class whose constructor is the first expression applied to the given arguments. The arguments are evaluated as for expression application, but the constructor itself will only be evaluated when objects are created. In particular, side-effects caused by the application of the constructor will only occur at object creation time.
####
[](#sss:class-fun)Class function
The expression fun [[?][label-name](lex#label-name):][pattern](patterns#pattern) -> [class-expr](#class-expr) evaluates to a function from values to classes. When this function is applied to a value v, this value is matched against the pattern [pattern](patterns#pattern) and the result is the result of the evaluation of [class-expr](#class-expr) in the extended environment.
Conversion from functions with default values to functions with patterns only works identically for class functions as for normal functions.
The expression
fun [parameter](expr#parameter)1 … [parameter](expr#parameter)n -> [class-expr](#class-expr)
is a short form for
fun [parameter](expr#parameter)1 -> … fun [parameter](expr#parameter)n -> [expr](expr#expr)
####
[](#sss:class-localdefs)Local definitions
The let and let rec constructs bind value names locally, as for the core language expressions.
If a local definition occurs at the very beginning of a class definition, it will be evaluated when the class is created (just as if the definition was outside of the class). Otherwise, it will be evaluated when the object constructor is called.
####
[](#sss:class-opens)Local opens
Local opens are supported in class expressions since OCaml 4.06.
####
[](#sss:class-body)Class body
| | | | |
| --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| class-body | ::= | [( [pattern](patterns#pattern) [: [typexpr](types#typexpr)] )] { [class-field](#class-field) } |
|
The expression object [class-body](#class-body) end denotes a class body. This is the prototype for an object : it lists the instance variables and methods of an object of this class.
A class body is a class value: it is not evaluated at once. Rather, its components are evaluated each time an object is created.
In a class body, the pattern ( [pattern](patterns#pattern) [: [typexpr](types#typexpr)] ) is matched against self, therefore providing a binding for self and self type. Self can only be used in method and initializers.
Self type cannot be a closed object type, so that the class remains extensible.
Since OCaml 4.01, it is an error if the same method or instance variable name is defined several times in the same class body.
####
[](#sss:class-inheritance)Inheritance
The inheritance construct inherit [class-expr](#class-expr) allows reusing methods and instance variables from other classes. The class expression [class-expr](#class-expr) must evaluate to a class body. The instance variables, methods and initializers from this class body are added into the current class. The addition of a method will override any previously defined method of the same name.
An ancestor can be bound by appending as [lowercase-ident](lex#lowercase-ident) to the inheritance construct. [lowercase-ident](lex#lowercase-ident) is not a true variable and can only be used to select a method, i.e. in an expression [lowercase-ident](lex#lowercase-ident) # [method-name](names#method-name). This gives access to the method [method-name](names#method-name) as it was defined in the parent class even if it is redefined in the current class. The scope of this ancestor binding is limited to the current class. The ancestor method may be called from a subclass but only indirectly.
####
[](#sss:class-variables)Instance variable definition
The definition val [mutable] [inst-var-name](names#inst-var-name) = [expr](expr#expr) adds an instance variable [inst-var-name](names#inst-var-name) whose initial value is the value of expression [expr](expr#expr). The flag mutable allows physical modification of this variable by methods.
An instance variable can only be used in the methods and initializers that follow its definition.
Since version 3.10, redefinitions of a visible instance variable with the same name do not create a new variable, but are merged, using the last value for initialization. They must have identical types and mutability. However, if an instance variable is hidden by omitting it from an interface, it will be kept distinct from other instance variables with the same name.
####
[](#sss:class-virtual-variable)Virtual instance variable definition
A variable specification is written val [mutable] virtual [inst-var-name](names#inst-var-name) : [typexpr](types#typexpr). It specifies whether the variable is modifiable, and gives its type.
Virtual instance variables were added in version 3.10.
####
[](#sss:class-method)Method definition
A method definition is written method [method-name](names#method-name) = [expr](expr#expr). The definition of a method overrides any previous definition of this method. The method will be public (that is, not private) if any of the definition states so.
A private method, method private [method-name](names#method-name) = [expr](expr#expr), is a method that can only be invoked on self (from other methods of the same object, defined in this class or one of its subclasses). This invocation is performed using the expression [value-name](names#value-name) # [method-name](names#method-name), where [value-name](names#value-name) is directly bound to self at the beginning of the class definition. Private methods do not appear in object types. A method may have both public and private definitions, but as soon as there is a public one, all subsequent definitions will be made public.
Methods may have an explicitly polymorphic type, allowing them to be used polymorphically in programs (even for the same object). The explicit declaration may be done in one of three ways: (1) by giving an explicit polymorphic type in the method definition, immediately after the method name, *i.e.* method [private] [method-name](names#method-name) : { ' [ident](lex#ident) }+ . [typexpr](types#typexpr) = [expr](expr#expr); (2) by a forward declaration of the explicit polymorphic type through a virtual method definition; (3) by importing such a declaration through inheritance and/or constraining the type of *self*.
Some special expressions are available in method bodies for manipulating instance variables and duplicating self:
| | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [expr](expr#expr) | ::= | … |
| | ∣ | [inst-var-name](names#inst-var-name) <- [expr](expr#expr) |
| | ∣ | {< [ [inst-var-name](names#inst-var-name) = [expr](expr#expr) { ; [inst-var-name](names#inst-var-name) = [expr](expr#expr) } [;] ] >} |
|
The expression [inst-var-name](names#inst-var-name) <- [expr](expr#expr) modifies in-place the current object by replacing the value associated to [inst-var-name](names#inst-var-name) by the value of [expr](expr#expr). Of course, this instance variable must have been declared mutable.
The expression {< [inst-var-name](names#inst-var-name)1 = [expr](expr#expr)1 ; … ; [inst-var-name](names#inst-var-name)n = [expr](expr#expr)n >} evaluates to a copy of the current object in which the values of instance variables [inst-var-name](names#inst-var-name)1, …, [inst-var-name](names#inst-var-name)n have been replaced by the values of the corresponding expressions [expr](expr#expr)1, …, [expr](expr#expr)n.
####
[](#sss:class-virtual-meth)Virtual method definition
A method specification is written method [private] virtual [method-name](names#method-name) : [poly-typexpr](types#poly-typexpr). It specifies whether the method is public or private, and gives its type. If the method is intended to be polymorphic, the type must be explicitly polymorphic.
####
[](#sss:class-explicit-overriding)Explicit overriding
Since Ocaml 3.12, the keywords inherit!, val! and method! have the same semantics as inherit, val and method, but they additionally require the definition they introduce to be overriding. Namely, method! requires [method-name](names#method-name) to be already defined in this class, val! requires [inst-var-name](names#inst-var-name) to be already defined in this class, and inherit! requires [class-expr](#class-expr) to override some definitions. If no such overriding occurs, an error is signaled.
As a side-effect, these 3 keywords avoid the warnings 7 (method override) and 13 (instance variable override). Note that warning 7 is disabled by default.
####
[](#sss:class-type-constraints)Constraints on type parameters
The construct constraint [typexpr](types#typexpr)1 = [typexpr](types#typexpr)2 forces the two type expressions to be equals. This is typically used to specify type parameters: in that way they can be bound to specific type expressions.
####
[](#sss:class-initializers)Initializers
A class initializer initializer [expr](expr#expr) specifies an expression that will be evaluated whenever an object is created from the class, once all its instance variables have been initialized.
###
[](#ss:class-def)11.9.3 Class definitions
| | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| class-definition | ::= | class [class-binding](#class-binding) { and [class-binding](#class-binding) } |
| |
| class-binding | ::= | [virtual] [[ [type-parameters](#type-parameters) ]] [class-name](names#class-name) { [parameter](expr#parameter) } [: [class-type](#class-type)] = [class-expr](#class-expr) |
| |
| type-parameters | ::= | ' [ident](lex#ident) { , ' [ident](lex#ident) } |
|
A class definition class [class-binding](#class-binding) { and [class-binding](#class-binding) } is recursive. Each [class-binding](#class-binding) defines a [class-name](names#class-name) that can be used in the whole expression except for inheritance. It can also be used for inheritance, but only in the definitions that follow its own.
A class binding binds the class name [class-name](names#class-name) to the value of expression [class-expr](#class-expr). It also binds the class type [class-name](names#class-name) to the type of the class, and defines two type abbreviations : [class-name](names#class-name) and # [class-name](names#class-name). The first one is the type of objects of this class, while the second is more general as it unifies with the type of any object belonging to a subclass (see section [11.4](types#sss%3Atypexpr-sharp-types)).
####
[](#sss:class-virtual)Virtual class
A class must be flagged virtual if one of its methods is virtual (that is, appears in the class type, but is not actually defined). Objects cannot be created from a virtual class.
####
[](#sss:class-type-params)Type parameters
The class type parameters correspond to the ones of the class type and of the two type abbreviations defined by the class binding. They must be bound to actual types in the class definition using type constraints. So that the abbreviations are well-formed, type variables of the inferred type of the class must either be type parameters or be bound in the constraint clause.
###
[](#ss:class-spec)11.9.4 Class specifications
| | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| class-specification | ::= | class [class-spec](#class-spec) { and [class-spec](#class-spec) } |
| |
| class-spec | ::= | [virtual] [[ [type-parameters](#type-parameters) ]] [class-name](names#class-name) : [class-type](#class-type) |
|
This is the counterpart in signatures of class definitions. A class specification matches a class definition if they have the same type parameters and their types match.
###
[](#ss:classtype)11.9.5 Class type definitions
| | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| classtype-definition | ::= | class type [classtype-def](#classtype-def) { and [classtype-def](#classtype-def) } |
| |
| classtype-def | ::= | [virtual] [[ [type-parameters](#type-parameters) ]] [class-name](names#class-name) = [class-body-type](#class-body-type) |
|
A class type definition class [class-name](names#class-name) = [class-body-type](#class-body-type) defines an abbreviation [class-name](names#class-name) for the class body type [class-body-type](#class-body-type). As for class definitions, two type abbreviations [class-name](names#class-name) and # [class-name](names#class-name) are also defined. The definition can be parameterized by some type parameters. If any method in the class type body is virtual, the definition must be flagged virtual.
Two class type definitions match if they have the same type parameters and they expand to matching types.
| programming_docs |
ocaml None
[](#s:typexpr)11.4 Type expressions
-------------------------------------
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| typexpr | ::= | ' [ident](lex#ident) |
| | ∣ | \_ |
| | ∣ | ( [typexpr](#typexpr) ) |
| | ∣ | [[?][label-name](lex#label-name):] [typexpr](#typexpr) -> [typexpr](#typexpr) |
| | ∣ | [typexpr](#typexpr) { \* [typexpr](#typexpr) }+ |
| | ∣ | [typeconstr](names#typeconstr) |
| | ∣ | [typexpr](#typexpr) [typeconstr](names#typeconstr) |
| | ∣ | ( [typexpr](#typexpr) { , [typexpr](#typexpr) } ) [typeconstr](names#typeconstr) |
| | ∣ | [typexpr](#typexpr) as ' [ident](lex#ident) |
| | ∣ | [polymorphic-variant-type](#polymorphic-variant-type) |
| | ∣ | < [..] > |
| | ∣ | < [method-type](#method-type) { ; [method-type](#method-type) } [; ∣ ; ..] > |
| | ∣ | # [classtype-path](names#classtype-path) |
| | ∣ | [typexpr](#typexpr) # [class-path](names#class-path) |
| | ∣ | ( [typexpr](#typexpr) { , [typexpr](#typexpr) } ) # [class-path](names#class-path) |
| |
| poly-typexpr | ::= | [typexpr](#typexpr) |
| | ∣ | { ' [ident](lex#ident) }+ . [typexpr](#typexpr) |
| |
| method-type | ::= | [method-name](names#method-name) : [poly-typexpr](#poly-typexpr) |
|
See also the following language extensions: [first-class modules](firstclassmodules#s%3Afirst-class-modules), [attributes](attributes#s%3Aattributes) and [extension nodes](extensionnodes#s%3Aextension-nodes).
The table below shows the relative precedences and associativity of operators and non-closed type constructions. The constructions with higher precedences come first.
| | |
| --- | --- |
| Operator | Associativity |
| Type constructor application | – |
| # | – |
| \* | – |
| -> | right |
| as | – |
Type expressions denote types in definitions of data types as well as in type constraints over patterns and expressions.
####
[](#sss:typexpr-variables)Type variables
The type expression ' [ident](lex#ident) stands for the type variable named [ident](lex#ident). The type expression \_ stands for either an anonymous type variable or anonymous type parameters. In data type definitions, type variables are names for the data type parameters. In type constraints, they represent unspecified types that can be instantiated by any type to satisfy the type constraint. In general the scope of a named type variable is the whole top-level phrase where it appears, and it can only be generalized when leaving this scope. Anonymous variables have no such restriction. In the following cases, the scope of named type variables is restricted to the type expression where they appear: 1) for universal (explicitly polymorphic) type variables; 2) for type variables that only appear in public method specifications (as those variables will be made universal, as described in section [11.9.1](classes#sss%3Aclty-meth)); 3) for variables used as aliases, when the type they are aliased to would be invalid in the scope of the enclosing definition (i.e. when it contains free universal type variables, or locally defined types.)
####
[](#sss:typexr:parenthesized)Parenthesized types
The type expression ( [typexpr](#typexpr) ) denotes the same type as [typexpr](#typexpr).
####
[](#sss:typexr-fun)Function types
The type expression [typexpr](#typexpr)1 -> [typexpr](#typexpr)2 denotes the type of functions mapping arguments of type [typexpr](#typexpr)1 to results of type [typexpr](#typexpr)2.
[label-name](lex#label-name) : [typexpr](#typexpr)1 -> [typexpr](#typexpr)2 denotes the same function type, but the argument is labeled [label](lex#label).
? [label-name](lex#label-name) : [typexpr](#typexpr)1 -> [typexpr](#typexpr)2 denotes the type of functions mapping an optional labeled argument of type [typexpr](#typexpr)1 to results of type [typexpr](#typexpr)2. That is, the physical type of the function will be [typexpr](#typexpr)1 option -> [typexpr](#typexpr)2.
####
[](#sss:typexpr-tuple)Tuple types
The type expression [typexpr](#typexpr)1 \* … \* [typexpr](#typexpr)n denotes the type of tuples whose elements belong to types [typexpr](#typexpr)1, … [typexpr](#typexpr)n respectively.
####
[](#sss:typexpr-constructed)Constructed types
Type constructors with no parameter, as in [typeconstr](names#typeconstr), are type expressions.
The type expression [typexpr](#typexpr) [typeconstr](names#typeconstr), where [typeconstr](names#typeconstr) is a type constructor with one parameter, denotes the application of the unary type constructor [typeconstr](names#typeconstr) to the type [typexpr](#typexpr).
The type expression ([typexpr](#typexpr)1,…,[typexpr](#typexpr)n) [typeconstr](names#typeconstr), where [typeconstr](names#typeconstr) is a type constructor with n parameters, denotes the application of the n-ary type constructor [typeconstr](names#typeconstr) to the types [typexpr](#typexpr)1 through [typexpr](#typexpr)n.
In the type expression \_ [typeconstr](names#typeconstr) , the anonymous type expression \_ stands in for anonymous type parameters and is equivalent to (\_, …,\_) with as many repetitions of \_ as the arity of [typeconstr](names#typeconstr).
####
[](#sss:typexpr-aliased-recursive)Aliased and recursive types
The type expression [typexpr](#typexpr) as ' [ident](lex#ident) denotes the same type as [typexpr](#typexpr), and also binds the type variable [ident](lex#ident) to type [typexpr](#typexpr) both in [typexpr](#typexpr) and in other types. In general the scope of an alias is the same as for a named type variable, and covers the whole enclosing definition. If the type variable [ident](lex#ident) actually occurs in [typexpr](#typexpr), a recursive type is created. Recursive types for which there exists a recursive path that does not contain an object or polymorphic variant type constructor are rejected, except when the -rectypes mode is selected.
If ' [ident](lex#ident) denotes an explicit polymorphic variable, and [typexpr](#typexpr) denotes either an object or polymorphic variant type, the row variable of [typexpr](#typexpr) is captured by ' [ident](lex#ident), and quantified upon.
####
[](#sss:typexpr-polyvar)Polymorphic variant types
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| polymorphic-variant-type | ::= | [ [tag-spec-first](#tag-spec-first) { | [tag-spec](#tag-spec) } ] |
| | ∣ | [> [ [tag-spec](#tag-spec) ] { | [tag-spec](#tag-spec) } ] |
| | ∣ | [< [|] [tag-spec-full](#tag-spec-full) { | [tag-spec-full](#tag-spec-full) } [ > { `[tag-name](names#tag-name) }+ ] ] |
| |
| tag-spec-first | ::= | `[tag-name](names#tag-name) [ of [typexpr](#typexpr) ] |
| | ∣ | [ [typexpr](#typexpr) ] | [tag-spec](#tag-spec) |
| |
| tag-spec | ::= | `[tag-name](names#tag-name) [ of [typexpr](#typexpr) ] |
| | ∣ | [typexpr](#typexpr) |
| |
| tag-spec-full | ::= | `[tag-name](names#tag-name) [ of [&] [typexpr](#typexpr) { & [typexpr](#typexpr) } ] |
| | ∣ | [typexpr](#typexpr) |
|
Polymorphic variant types describe the values a polymorphic variant may take.
The first case is an exact variant type: all possible tags are known, with their associated types, and they can all be present. Its structure is fully known.
The second case is an open variant type, describing a polymorphic variant value: it gives the list of all tags the value could take, with their associated types. This type is still compatible with a variant type containing more tags. A special case is the unknown type, which does not define any tag, and is compatible with any variant type.
The third case is a closed variant type. It gives information about all the possible tags and their associated types, and which tags are known to potentially appear in values. The exact variant type (first case) is just an abbreviation for a closed variant type where all possible tags are also potentially present.
In all three cases, tags may be either specified directly in the `[tag-name](names#tag-name) [of [typexpr](#typexpr)] form, or indirectly through a type expression, which must expand to an exact variant type, whose tag specifications are inserted in its place.
Full specifications of variant tags are only used for non-exact closed types. They can be understood as a conjunctive type for the argument: it is intended to have all the types enumerated in the specification.
Such conjunctive constraints may be unsatisfiable. In such a case the corresponding tag may not be used in a value of this type. This does not mean that the whole type is not valid: one can still use other available tags. Conjunctive constraints are mainly intended as output from the type checker. When they are used in source programs, unsolvable constraints may cause early failures.
####
[](#sss:typexpr-obj)Object types
An object type < [[method-type](#method-type) { ; [method-type](#method-type) }] > is a record of method types.
Each method may have an explicit polymorphic type: { ' [ident](lex#ident) }+ . [typexpr](#typexpr). Explicit polymorphic variables have a local scope, and an explicit polymorphic type can only be unified to an equivalent one, where only the order and names of polymorphic variables may change.
The type < { [method-type](#method-type) ; } .. > is the type of an object whose method names and types are described by [method-type](#method-type)1, …, [method-type](#method-type)n, and possibly some other methods represented by the ellipsis. This ellipsis actually is a special kind of type variable (called *row variable* in the literature) that stands for any number of extra method types.
####
[](#sss:typexpr-sharp-types)#-types
The type # [classtype-path](names#classtype-path) is a special kind of abbreviation. This abbreviation unifies with the type of any object belonging to a subclass of the class type [classtype-path](names#classtype-path). It is handled in a special way as it usually hides a type variable (an ellipsis, representing the methods that may be added in a subclass). In particular, it vanishes when the ellipsis gets instantiated. Each type expression # [classtype-path](names#classtype-path) defines a new type variable, so type # [classtype-path](names#classtype-path) -> # [classtype-path](names#classtype-path) is usually not the same as type (# [classtype-path](names#classtype-path) as ' [ident](lex#ident)) -> ' [ident](lex#ident).
Use of #-types to abbreviate polymorphic variant types is deprecated. If t is an exact variant type then #t translates to [< t], and #t[> `[tag](names#tag-name)1 …`[tag](names#tag-name)k] translates to [< t > `[tag](names#tag-name)1 …`[tag](names#tag-name)k]
####
[](#sss:typexpr-variant-record)Variant and record types
There are no type expressions describing (defined) variant types nor record types, since those are always named, i.e. defined before use and referred to by name. Type definitions are described in section [11.8.1](typedecl#ss%3Atypedefs).
ocaml None
[](#s:value-expr)11.7 Expressions
-----------------------------------
* [11.7.1 Precedence and associativity](expr#ss%3Aprecedence-and-associativity)
* [11.7.2 Basic expressions](expr#ss%3Aexpr-basic)
* [11.7.3 Control structures](expr#ss%3Aexpr-control)
* [11.7.4 Operations on data structures](expr#ss%3Aexpr-ops-on-data)
* [11.7.5 Operators](expr#ss%3Aexpr-operators)
* [11.7.6 Objects](expr#ss%3Aexpr-obj)
* [11.7.7 Coercions](expr#ss%3Aexpr-coercions)
* [11.7.8 Other](expr#ss%3Aexpr-other)
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| expr | ::= | [value-path](names#value-path) |
| | ∣ | [constant](const#constant) |
| | ∣ | ( [expr](#expr) ) |
| | ∣ | begin [expr](#expr) end |
| | ∣ | ( [expr](#expr) : [typexpr](types#typexpr) ) |
| | ∣ | [expr](#expr) { , [expr](#expr) }+ |
| | ∣ | [constr](names#constr) [expr](#expr) |
| | ∣ | `[tag-name](names#tag-name) [expr](#expr) |
| | ∣ | [expr](#expr) :: [expr](#expr) |
| | ∣ | [ [expr](#expr) { ; [expr](#expr) } [;] ] |
| | ∣ | [| [expr](#expr) { ; [expr](#expr) } [;] |] |
| | ∣ | { [field](names#field) [: [typexpr](types#typexpr)] [= [expr](#expr)]{ ; [field](names#field) [: [typexpr](types#typexpr)] [= [expr](#expr)] } [;] } |
| | ∣ | { [expr](#expr) with [field](names#field) [: [typexpr](types#typexpr)] [= [expr](#expr)]{ ; [field](names#field) [: [typexpr](types#typexpr)] [= [expr](#expr)] } [;] } |
| | ∣ | [expr](#expr) { [argument](#argument) }+ |
| | ∣ | [prefix-symbol](lex#prefix-symbol) [expr](#expr) |
| | ∣ | - [expr](#expr) |
| | ∣ | -. [expr](#expr) |
| | ∣ | [expr](#expr) [infix-op](names#infix-op) [expr](#expr) |
| | ∣ | [expr](#expr) . [field](names#field) |
| | ∣ | [expr](#expr) . [field](names#field) <- [expr](#expr) |
| | ∣ | [expr](#expr) .( [expr](#expr) ) |
| | ∣ | [expr](#expr) .( [expr](#expr) ) <- [expr](#expr) |
| | ∣ | [expr](#expr) .[ [expr](#expr) ] |
| | ∣ | [expr](#expr) .[ [expr](#expr) ] <- [expr](#expr) |
| | ∣ | if [expr](#expr) then [expr](#expr) [ else [expr](#expr) ] |
| | ∣ | while [expr](#expr) do [expr](#expr) done |
| | ∣ | for [value-name](names#value-name) = [expr](#expr) ( to ∣ downto ) [expr](#expr) do [expr](#expr) done |
| | ∣ | [expr](#expr) ; [expr](#expr) |
| | ∣ | match [expr](#expr) with [pattern-matching](#pattern-matching) |
| | ∣ | function [pattern-matching](#pattern-matching) |
| | ∣ | fun { [parameter](#parameter) }+ [ : [typexpr](types#typexpr) ] -> [expr](#expr) |
| | ∣ | try [expr](#expr) with [pattern-matching](#pattern-matching) |
| | ∣ | let [rec] [let-binding](#let-binding) { and [let-binding](#let-binding) } in [expr](#expr) |
| | ∣ | let exception [constr-decl](typedecl#constr-decl) in [expr](#expr) |
| | ∣ | let module [module-name](names#module-name) { ( [module-name](names#module-name) : [module-type](modtypes#module-type) ) } [ : [module-type](modtypes#module-type) ] = [module-expr](modules#module-expr) in [expr](#expr) |
| | ∣ | ( [expr](#expr) :> [typexpr](types#typexpr) ) |
| | ∣ | ( [expr](#expr) : [typexpr](types#typexpr) :> [typexpr](types#typexpr) ) |
| | ∣ | assert [expr](#expr) |
| | ∣ | lazy [expr](#expr) |
| | ∣ | [local-open](#local-open) |
| | ∣ | [object-expr](#object-expr) |
| |
|
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| argument | ::= | [expr](#expr) |
| | ∣ | ~ [label-name](lex#label-name) |
| | ∣ | ~ [label-name](lex#label-name) : [expr](#expr) |
| | ∣ | ? [label-name](lex#label-name) |
| | ∣ | ? [label-name](lex#label-name) : [expr](#expr) |
| |
| pattern-matching | ::= | [ | ] [pattern](patterns#pattern) [when [expr](#expr)] -> [expr](#expr) { | [pattern](patterns#pattern) [when [expr](#expr)] -> [expr](#expr) } |
| |
| let-binding | ::= | [pattern](patterns#pattern) = [expr](#expr) |
| | ∣ | [value-name](names#value-name) { [parameter](#parameter) } [: [typexpr](types#typexpr)] [:> [typexpr](types#typexpr)] = [expr](#expr) |
| | ∣ | [value-name](names#value-name) : [poly-typexpr](types#poly-typexpr) = [expr](#expr) |
| |
| parameter | ::= | [pattern](patterns#pattern) |
| | ∣ | ~ [label-name](lex#label-name) |
| | ∣ | ~ ( [label-name](lex#label-name) [: [typexpr](types#typexpr)] ) |
| | ∣ | ~ [label-name](lex#label-name) : [pattern](patterns#pattern) |
| | ∣ | ? [label-name](lex#label-name) |
| | ∣ | ? ( [label-name](lex#label-name) [: [typexpr](types#typexpr)] [= [expr](#expr)] ) |
| | ∣ | ? [label-name](lex#label-name) : [pattern](patterns#pattern) |
| | ∣ | ? [label-name](lex#label-name) : ( [pattern](patterns#pattern) [: [typexpr](types#typexpr)] [= [expr](#expr)] ) |
| |
| local-open | ::= | |
| | ∣ | let open [module-path](names#module-path) in [expr](#expr) |
| | ∣ | [module-path](names#module-path) .( [expr](#expr) ) |
| | ∣ | [module-path](names#module-path) .[ [expr](#expr) ] |
| | ∣ | [module-path](names#module-path) .[| [expr](#expr) |] |
| | ∣ | [module-path](names#module-path) .{ [expr](#expr) } |
| | ∣ | [module-path](names#module-path) .{< [expr](#expr) >} |
| |
| object-expr | ::= | |
| | ∣ | new [class-path](names#class-path) |
| | ∣ | object [class-body](classes#class-body) end |
| | ∣ | [expr](#expr) # [method-name](names#method-name) |
| | ∣ | [inst-var-name](names#inst-var-name) |
| | ∣ | [inst-var-name](names#inst-var-name) <- [expr](#expr) |
| | ∣ | {< [ [inst-var-name](names#inst-var-name) [= [expr](#expr)] { ; [inst-var-name](names#inst-var-name) [= [expr](#expr)] } [;] ] >} |
|
See also the following language extensions: [first-class modules](firstclassmodules#s%3Afirst-class-modules), [overriding in open statements](overridingopen#s%3Aexplicit-overriding-open), [syntax for Bigarray access](bigarray#s%3Abigarray-access), [attributes](attributes#s%3Aattributes), [extension nodes](extensionnodes#s%3Aextension-nodes) and [extended indexing operators](indexops#s%3Aindex-operators).
###
[](#ss:precedence-and-associativity)11.7.1 Precedence and associativity
The table below shows the relative precedences and associativity of operators and non-closed constructions. The constructions with higher precedence come first. For infix and prefix symbols, we write “\*…” to mean “any symbol starting with \*”.
| | |
| --- | --- |
| Construction or operator | Associativity |
| prefix-symbol | – |
| . .( .[ .{ (see section [12.11](bigarray#s%3Abigarray-access)) | – |
| #… | left |
| function application, constructor application, tag application, assert, lazy | left |
| - -. (prefix) | – |
| \*\*… lsl lsr asr | right |
| \*… /… %… mod land lor lxor | left |
| +… -… | left |
| :: | right |
| @… ^… | right |
| =… <… >… |… &… $… != | left |
| & && | right |
| or || | right |
| , | – |
| <- := | right |
| if | – |
| ; | right |
| let match fun function try | – |
It is simple to test or refresh one’s understanding:
```
# 3 + 3 mod 2, 3 + (3 mod 2), (3 + 3) mod 2;;
- : int * int * int = (4, 4, 0)
```
###
[](#ss:expr-basic)11.7.2 Basic expressions
####
[](#sss:expr-constants)Constants
An expression consisting in a constant evaluates to this constant. For example, 3.14 or [||].
####
[](#sss:expr-var)Value paths
An expression consisting in an access path evaluates to the value bound to this path in the current evaluation environment. The path can be either a value name or an access path to a value component of a module.
```
# Float.ArrayLabels.to_list;;
- : Float.ArrayLabels.t -> float list =
```
####
[](#sss:expr-parenthesized)Parenthesized expressions
The expressions ( [expr](#expr) ) and begin [expr](#expr) end have the same value as [expr](#expr). The two constructs are semantically equivalent, but it is good style to use begin … end inside control structures:
```
if … then begin … ; … end else begin … ; … end
```
and ( … ) for the other grouping situations.
```
# let x = 1 + 2 * 3
let y = (1 + 2) * 3;;
val x : int = 7
val y : int = 9
```
```
# let f a b =
if a = b then
print_endline "Equal"
else begin
print_string "Not Equal: ";
print_int a;
print_string " and ";
print_int b;
print_newline ()
end;;
val f : int -> int -> unit =
```
Parenthesized expressions can contain a type constraint, as in ( [expr](#expr) : [typexpr](types#typexpr) ). This constraint forces the type of [expr](#expr) to be compatible with [typexpr](types#typexpr).
Parenthesized expressions can also contain coercions ( [expr](#expr) [: [typexpr](types#typexpr)] :> [typexpr](types#typexpr)) (see subsection [11.7.7](#ss%3Aexpr-coercions) below).
####
[](#sss:expr-functions-application)Function application
Function application is denoted by juxtaposition of (possibly labeled) expressions. The expression [expr](#expr) [argument](#argument)1 … [argument](#argument)n evaluates the expression [expr](#expr) and those appearing in [argument](#argument)1 to [argument](#argument)n. The expression [expr](#expr) must evaluate to a functional value f, which is then applied to the values of [argument](#argument)1, …, [argument](#argument)n.
The order in which the expressions [expr](#expr), [argument](#argument)1, …, [argument](#argument)n are evaluated is not specified.
```
# List.fold_left ( + ) 0 [1; 2; 3; 4; 5];;
- : int = 15
```
Arguments and parameters are matched according to their respective labels. Argument order is irrelevant, except among arguments with the same label, or no label.
```
# ListLabels.fold_left ~f:( @ ) ~init:[] [[1; 2; 3]; [4; 5; 6]; [7; 8; 9]];;
- : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9]
```
If a parameter is specified as optional (label prefixed by ?) in the type of [expr](#expr), the corresponding argument will be automatically wrapped with the constructor Some, except if the argument itself is also prefixed by ?, in which case it is passed as is.
```
# let fullname ?title first second =
match title with
| Some t -> t ^ " " ^ first ^ " " ^ second
| None -> first ^ " " ^ second
let name = fullname ~title:"Mrs" "Jane" "Fisher"
let address ?title first second town =
fullname ?title first second ^ "\n" ^ town;;
val fullname : ?title:string -> string -> string -> string =
val name : string = "Mrs Jane Fisher"
val address : ?title:string -> string -> string -> string -> string =
```
If a non-labeled argument is passed, and its corresponding parameter is preceded by one or several optional parameters, then these parameters are *defaulted*, *i.e.* the value None will be passed for them. All other missing parameters (without corresponding argument), both optional and non-optional, will be kept, and the result of the function will still be a function of these missing parameters to the body of f.
```
# let fullname ?title first second =
match title with
| Some t -> t ^ " " ^ first ^ " " ^ second
| None -> first ^ " " ^ second
let name = fullname "Jane" "Fisher";;
val fullname : ?title:string -> string -> string -> string =
val name : string = "Jane Fisher"
```
In all cases but exact match of order and labels, without optional parameters, the function type should be known at the application point. This can be ensured by adding a type constraint. Principality of the derivation can be checked in the -principal mode.
As a special case, OCaml supports labels-omitted full applications: if the function has a known arity, all the arguments are unlabeled, and their number matches the number of non-optional parameters, then labels are ignored and non-optional parameters are matched in their definition order. Optional arguments are defaulted. This omission of labels is discouraged and results in a warning, see [13.5.1](comp#ss%3Awarn6).
####
[](#sss:expr-function-definition)Function definition
Two syntactic forms are provided to define functions. The first form is introduced by the keyword function:
| | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | | |
| --- | --- | --- | --- |
| function | pattern1 | -> | expr1 |
| | | … |
| | | patternn | -> | exprn |
|
This expression evaluates to a functional value with one argument. When this function is applied to a value v, this value is matched against each pattern [pattern](patterns#pattern)1 to [pattern](patterns#pattern)n. If one of these matchings succeeds, that is, if the value v matches the pattern [pattern](patterns#pattern)i for some i, then the expression [expr](#expr)i associated to the selected pattern is evaluated, and its value becomes the value of the function application. The evaluation of [expr](#expr)i takes place in an environment enriched by the bindings performed during the matching.
If several patterns match the argument v, the one that occurs first in the function definition is selected. If none of the patterns matches the argument, the exception Match\_failure is raised.
```
# (function (0, 0) -> "both zero"
| (0, _) -> "first only zero"
| (_, 0) -> "second only zero"
| (_, _) -> "neither zero")
(7, 0);;
- : string = "second only zero"
```
The other form of function definition is introduced by the keyword fun:
fun [parameter](#parameter)1 … [parameter](#parameter)n -> [expr](#expr)
This expression is equivalent to:
fun [parameter](#parameter)1 -> … fun [parameter](#parameter)n -> [expr](#expr)
```
# let f = (fun a -> fun b -> fun c -> a + b + c)
let g = (fun a b c -> a + b + c);;
val f : int -> int -> int -> int =
val g : int -> int -> int -> int =
```
An optional type constraint [typexpr](types#typexpr) can be added before -> to enforce the type of the result to be compatible with the constraint [typexpr](types#typexpr):
fun [parameter](#parameter)1 … [parameter](#parameter)n : [typexpr](types#typexpr) -> [expr](#expr)
is equivalent to
fun [parameter](#parameter)1 -> … fun [parameter](#parameter)n -> ([expr](#expr) : [typexpr](types#typexpr) )
Beware of the small syntactic difference between a type constraint on the last parameter
fun [parameter](#parameter)1 … ([parameter](#parameter)n:[typexpr](types#typexpr))-> [expr](#expr)
and one on the result
fun [parameter](#parameter)1 … [parameter](#parameter)n: [typexpr](types#typexpr) -> [expr](#expr)
```
# let eq = fun (a : int) (b : int) -> a = b
let eq2 = fun a b : bool -> a = b
let eq3 = fun (a : int) (b : int) : bool -> a = b;;
val eq : int -> int -> bool =
val eq2 : 'a -> 'a -> bool =
val eq3 : int -> int -> bool =
```
The parameter patterns ~[lab](lex#label-name) and ~([lab](lex#label-name) [: [typ](types#typexpr)]) are shorthands for respectively ~[lab](lex#label-name):[lab](lex#label-name) and ~[lab](lex#label-name):([lab](lex#label-name) [: [typ](types#typexpr)]), and similarly for their optional counterparts.
```
# let bool_map ~cmp:(cmp : int -> int -> bool) l =
List.map cmp l
let bool_map' ~(cmp : int -> int -> bool) l =
List.map cmp l;;
val bool_map : cmp:(int -> int -> bool) -> int list -> (int -> bool) list =
val bool\_map' : cmp:(int -> int -> bool) -> int list -> (int -> bool) list =
```
A function of the form fun ? [lab](lex#label-name) :( [pattern](patterns#pattern) = [expr](#expr)0 ) -> [expr](#expr) is equivalent to
fun ? [lab](lex#label-name) : [ident](lex#ident) -> let [pattern](patterns#pattern) = match [ident](lex#ident) with Some [ident](lex#ident) -> [ident](lex#ident) | None -> [expr](#expr)0 in [expr](#expr)
where [ident](lex#ident) is a fresh variable, except that it is unspecified when [expr](#expr)0 is evaluated.
```
# let open_file_for_input ?binary filename =
match binary with
| Some true -> open_in_bin filename
| Some false | None -> open_in filename
let open_file_for_input' ?(binary=false) filename =
if binary then open_in_bin filename else open_in filename;;
val open_file_for_input : ?binary:bool -> string -> in_channel =
val open\_file\_for\_input' : ?binary:bool -> string -> in\_channel =
```
After these two transformations, expressions are of the form
fun [[label](lex#label)1] [pattern](patterns#pattern)1 -> … fun [[label](lex#label)n] [pattern](patterns#pattern)n -> [expr](#expr)
If we ignore labels, which will only be meaningful at function application, this is equivalent to
function [pattern](patterns#pattern)1 -> … function [pattern](patterns#pattern)n -> [expr](#expr)
That is, the fun expression above evaluates to a curried function with n arguments: after applying this function n times to the values v1 … vn, the values will be matched in parallel against the patterns [pattern](patterns#pattern)1 … [pattern](patterns#pattern)n. If the matching succeeds, the function returns the value of [expr](#expr) in an environment enriched by the bindings performed during the matchings. If the matching fails, the exception Match\_failure is raised.
####
[](#sss:guards-in-pattern-matchings)Guards in pattern-matchings
The cases of a pattern matching (in the function, match and try constructs) can include guard expressions, which are arbitrary boolean expressions that must evaluate to true for the match case to be selected. Guards occur just before the -> token and are introduced by the when keyword:
| | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | | |
| --- | --- | --- | --- |
| function | pattern1 [when cond1] | -> | expr1 |
| | | … |
| | | patternn [when condn] | -> | exprn |
|
Matching proceeds as described before, except that if the value matches some pattern [pattern](patterns#pattern)i which has a guard condi, then the expression condi is evaluated (in an environment enriched by the bindings performed during matching). If condi evaluates to true, then [expr](#expr)i is evaluated and its value returned as the result of the matching, as usual. But if condi evaluates to false, the matching is resumed against the patterns following [pattern](patterns#pattern)i.
```
# let rec repeat f = function
| 0 -> ()
| n when n > 0 -> f (); repeat f (n - 1)
| _ -> raise (Invalid_argument "repeat");;
val repeat : (unit -> 'a) -> int -> unit =
```
####
[](#sss:expr-localdef)Local definitions
The let and let rec constructs bind value names locally. The construct
let [pattern](patterns#pattern)1 = [expr](#expr)1 and … and [pattern](patterns#pattern)n = [expr](#expr)n in [expr](#expr)
evaluates [expr](#expr)1 … [expr](#expr)n in some unspecified order and matches their values against the patterns [pattern](patterns#pattern)1 … [pattern](patterns#pattern)n. If the matchings succeed, [expr](#expr) is evaluated in the environment enriched by the bindings performed during matching, and the value of [expr](#expr) is returned as the value of the whole let expression. If one of the matchings fails, the exception Match\_failure is raised.
```
# let v =
let x = 1 in [x; x; x]
let v' =
let a, b = (1, 2) in a + b
let v'' =
let a = 1 and b = 2 in a + b;;
val v : int list = [1; 1; 1]
val v' : int = 3
val v'' : int = 3
```
An alternate syntax is provided to bind variables to functional values: instead of writing
let [ident](lex#ident) = fun [parameter](#parameter)1 … [parameter](#parameter)m -> [expr](#expr)
in a let expression, one may instead write
let [ident](lex#ident) [parameter](#parameter)1 … [parameter](#parameter)m = [expr](#expr)
```
# let f = fun x -> fun y -> fun z -> x + y + z
let f' = fun x y z -> x + y + z
let f'' x y z = x + y + z;;
val f : int -> int -> int -> int =
val f' : int -> int -> int -> int =
val f'' : int -> int -> int -> int =
```
Recursive definitions of names are introduced by let rec:
let rec [pattern](patterns#pattern)1 = [expr](#expr)1 and … and [pattern](patterns#pattern)n = [expr](#expr)n in [expr](#expr)
The only difference with the let construct described above is that the bindings of names to values performed by the pattern-matching are considered already performed when the expressions [expr](#expr)1 to [expr](#expr)n are evaluated. That is, the expressions [expr](#expr)1 to [expr](#expr)n can reference identifiers that are bound by one of the patterns [pattern](patterns#pattern)1, …, [pattern](patterns#pattern)n, and expect them to have the same value as in [expr](#expr), the body of the let rec construct.
```
# let rec even =
function 0 -> true | n -> odd (n - 1)
and odd =
function 0 -> false | n -> even (n - 1)
in
even 1000;;
- : bool = true
```
The recursive definition is guaranteed to behave as described above if the expressions [expr](#expr)1 to [expr](#expr)n are function definitions (fun … or function …), and the patterns [pattern](patterns#pattern)1 … [pattern](patterns#pattern)n are just value names, as in:
let rec name1 = fun … and … and namen = fun … in [expr](#expr)
This defines name1 … namen as mutually recursive functions local to [expr](#expr).
The behavior of other forms of let rec definitions is implementation-dependent. The current implementation also supports a certain class of recursive definitions of non-functional values, as explained in section [12.1](letrecvalues#s%3Aletrecvalues).
####
[](#sss:expr-let-exception)Local exceptions
(Introduced in OCaml 4.04)
It is possible to define local exceptions in expressions: let exception [constr-decl](typedecl#constr-decl) in [expr](#expr) .
```
# let map_empty_on_negative f l =
let exception Negative in
let aux x = if x < 0 then raise Negative else f x in
try List.map aux l with Negative -> [];;
val map_empty_on_negative : (int -> 'a) -> int list -> 'a list =
```
The syntactic scope of the exception constructor is the inner expression, but nothing prevents exception values created with this constructor from escaping this scope. Two executions of the definition above result in two incompatible exception constructors (as for any exception definition). For instance:
```
# let gen () = let exception A in A
let () = assert(gen () = gen ());;
Exception: Assert_failure ("expr.etex", 3, 9).
```
####
[](#sss:expr-explicit-polytype)Explicit polymorphic type annotations
(Introduced in OCaml 3.12)
Polymorphic type annotations in let-definitions behave in a way similar to polymorphic methods:
let [pattern](patterns#pattern)1 : [typ](types#typexpr)1 … [typ](types#typexpr)n . [typexpr](types#typexpr) = [expr](#expr)
These annotations explicitly require the defined value to be polymorphic, and allow one to use this polymorphism in recursive occurrences (when using let rec). Note however that this is a normal polymorphic type, unifiable with any instance of itself.
###
[](#ss:expr-control)11.7.3 Control structures
####
[](#sss:expr-sequence)Sequence
The expression [expr](#expr)1 ; [expr](#expr)2 evaluates [expr](#expr)1 first, then [expr](#expr)2, and returns the value of [expr](#expr)2.
```
# let print_pair (a, b) =
print_string "(";
print_string (string_of_int a);
print_string ",";
print_string (string_of_int b);
print_endline ")";;
val print_pair : int * int -> unit =
```
####
[](#sss:expr-conditional)Conditional
The expression if [expr](#expr)1 then [expr](#expr)2 else [expr](#expr)3 evaluates to the value of [expr](#expr)2 if [expr](#expr)1 evaluates to the boolean true, and to the value of [expr](#expr)3 if [expr](#expr)1 evaluates to the boolean false.
```
# let rec factorial x =
if x <= 1 then 1 else x * factorial (x - 1);;
val factorial : int -> int =
```
The else [expr](#expr)3 part can be omitted, in which case it defaults to else ().
```
# let debug = ref false
let log msg =
if !debug then prerr_endline msg;;
val debug : bool ref = {contents = false}
val log : string -> unit =
```
####
[](#sss:expr-case)Case expression
The expression
| | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | |
| --- | --- |
| match | expr |
| with | pattern1 | -> | expr1 |
| | | … |
| | | patternn | -> | exprn |
|
matches the value of [expr](#expr) against the patterns [pattern](patterns#pattern)1 to [pattern](patterns#pattern)n. If the matching against [pattern](patterns#pattern)i succeeds, the associated expression [expr](#expr)i is evaluated, and its value becomes the value of the whole match expression. The evaluation of [expr](#expr)i takes place in an environment enriched by the bindings performed during matching. If several patterns match the value of [expr](#expr), the one that occurs first in the match expression is selected.
```
# let rec sum l =
match l with
| [] -> 0
| h :: t -> h + sum t;;
val sum : int list -> int =
```
If none of the patterns match the value of [expr](#expr), the exception Match\_failure is raised.
```
# let unoption o =
match o with
| Some x -> x
let l = List.map unoption [Some 1; Some 10; None; Some 2];;
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
None
Exception: Match_failure ("expr.etex", 2, 2).
```
####
[](#sss:expr-boolean-operators)Boolean operators
The expression [expr](#expr)1 && [expr](#expr)2 evaluates to true if both [expr](#expr)1 and [expr](#expr)2 evaluate to true; otherwise, it evaluates to false. The first component, [expr](#expr)1, is evaluated first. The second component, [expr](#expr)2, is not evaluated if the first component evaluates to false. Hence, the expression [expr](#expr)1 && [expr](#expr)2 behaves exactly as
if [expr](#expr)1 then [expr](#expr)2 else false.
The expression [expr](#expr)1 || [expr](#expr)2 evaluates to true if one of the expressions [expr](#expr)1 and [expr](#expr)2 evaluates to true; otherwise, it evaluates to false. The first component, [expr](#expr)1, is evaluated first. The second component, [expr](#expr)2, is not evaluated if the first component evaluates to true. Hence, the expression [expr](#expr)1 || [expr](#expr)2 behaves exactly as
if [expr](#expr)1 then true else [expr](#expr)2.
The boolean operators & and or are deprecated synonyms for (respectively) && and ||.
```
# let xor a b =
(a || b) && not (a && b);;
val xor : bool -> bool -> bool =
```
####
[](#sss:expr-loops)Loops
The expression while [expr](#expr)1 do [expr](#expr)2 done repeatedly evaluates [expr](#expr)2 while [expr](#expr)1 evaluates to true. The loop condition [expr](#expr)1 is evaluated and tested at the beginning of each iteration. The whole while … done expression evaluates to the unit value ().
```
# let chars_of_string s =
let i = ref 0 in
let chars = ref [] in
while !i < String.length s do
chars := s.[!i] :: !chars;
i := !i + 1
done;
List.rev !chars;;
val chars_of_string : string -> char list =
```
The expression for name = [expr](#expr)1 to [expr](#expr)2 do [expr](#expr)3 done first evaluates the expressions [expr](#expr)1 and [expr](#expr)2 (the boundaries) into integer values n and p. Then, the loop body [expr](#expr)3 is repeatedly evaluated in an environment where name is successively bound to the values n, n+1, …, p−1, p. The loop body is never evaluated if n > p.
```
# let chars_of_string s =
let l = ref [] in
for p = 0 to String.length s - 1 do
l := s.[p] :: !l
done;
List.rev !l;;
val chars_of_string : string -> char list =
```
The expression for name = [expr](#expr)1 downto [expr](#expr)2 do [expr](#expr)3 done evaluates similarly, except that name is successively bound to the values n, n−1, …, p+1, p. The loop body is never evaluated if n < p.
```
# let chars_of_string s =
let l = ref [] in
for p = String.length s - 1 downto 0 do
l := s.[p] :: !l
done;
!l;;
val chars_of_string : string -> char list =
```
In both cases, the whole for expression evaluates to the unit value ().
####
[](#sss:expr-exception-handling)Exception handling
The expression
| | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | |
| --- | --- |
| try | expr |
| with | pattern1 | -> | expr1 |
| | | … |
| | | patternn | -> | exprn |
|
evaluates the expression [expr](#expr) and returns its value if the evaluation of [expr](#expr) does not raise any exception. If the evaluation of [expr](#expr) raises an exception, the exception value is matched against the patterns [pattern](patterns#pattern)1 to [pattern](patterns#pattern)n. If the matching against [pattern](patterns#pattern)i succeeds, the associated expression [expr](#expr)i is evaluated, and its value becomes the value of the whole try expression. The evaluation of [expr](#expr)i takes place in an environment enriched by the bindings performed during matching. If several patterns match the value of [expr](#expr), the one that occurs first in the try expression is selected. If none of the patterns matches the value of [expr](#expr), the exception value is raised again, thereby transparently “passing through” the try construct.
```
# let find_opt p l =
try Some (List.find p l) with Not_found -> None;;
val find_opt : ('a -> bool) -> 'a list -> 'a option =
```
###
[](#ss:expr-ops-on-data)11.7.4 Operations on data structures
####
[](#sss:expr-products)Products
The expression [expr](#expr)1 , … , [expr](#expr)n evaluates to the n-tuple of the values of expressions [expr](#expr)1 to [expr](#expr)n. The evaluation order of the subexpressions is not specified.
```
# (1 + 2 * 3, (1 + 2) * 3, 1 + (2 * 3));;
- : int * int * int = (7, 9, 7)
```
####
[](#sss:expr-variants)Variants
The expression [constr](names#constr) [expr](#expr) evaluates to the unary variant value whose constructor is [constr](names#constr), and whose argument is the value of [expr](#expr). Similarly, the expression [constr](names#constr) ( [expr](#expr)1 , … , [expr](#expr)n ) evaluates to the n-ary variant value whose constructor is [constr](names#constr) and whose arguments are the values of [expr](#expr)1, …, [expr](#expr)n.
The expression [constr](names#constr) ([expr](#expr)1, …, [expr](#expr)n) evaluates to the variant value whose constructor is [constr](names#constr), and whose arguments are the values of [expr](#expr)1 … [expr](#expr)n.
```
# type t = Var of string | Not of t | And of t * t | Or of t * t
let test = And (Var "x", Not (Or (Var "y", Var "z")));;
type t = Var of string | Not of t | And of t * t | Or of t * t
val test : t = And (Var "x", Not (Or (Var "y", Var "z")))
```
For lists, some syntactic sugar is provided. The expression [expr](#expr)1 :: [expr](#expr)2 stands for the constructor ( :: ) applied to the arguments ( [expr](#expr)1 , [expr](#expr)2 ), and therefore evaluates to the list whose head is the value of [expr](#expr)1 and whose tail is the value of [expr](#expr)2. The expression [ [expr](#expr)1 ; … ; [expr](#expr)n ] is equivalent to [expr](#expr)1 :: … :: [expr](#expr)n :: [], and therefore evaluates to the list whose elements are the values of [expr](#expr)1 to [expr](#expr)n.
```
# 0 :: [1; 2; 3] = 0 :: 1 :: 2 :: 3 :: [];;
- : bool = true
```
####
[](#sss:expr-polyvars)Polymorphic variants
The expression `[tag-name](names#tag-name) [expr](#expr) evaluates to the polymorphic variant value whose tag is [tag-name](names#tag-name), and whose argument is the value of [expr](#expr).
```
# let with_counter x = `V (x, ref 0);;
val with_counter : 'a -> [> `V of 'a * int ref ] =
```
####
[](#sss:expr-records)Records
The expression { [field](names#field)1 [= [expr](#expr)1] ; … ; [field](names#field)n [= [expr](#expr)n ]} evaluates to the record value { field1 = v1; …; fieldn = vn } where vi is the value of [expr](#expr)i for i = 1,… , n. A single identifier [field](names#field)k stands for [field](names#field)k = [field](names#field)k, and a qualified identifier [module-path](names#module-path) . [field](names#field)k stands for [module-path](names#module-path) . [field](names#field)k = [field](names#field)k. The fields [field](names#field)1 to [field](names#field)n must all belong to the same record type; each field of this record type must appear exactly once in the record expression, though they can appear in any order. The order in which [expr](#expr)1 to [expr](#expr)n are evaluated is not specified. Optional type constraints can be added after each field { [field](names#field)1 : [typexpr](types#typexpr)1 = [expr](#expr)1 ;… ; [field](names#field)n : [typexpr](types#typexpr)n = [expr](#expr)n } to force the type of [field](names#field)k to be compatible with [typexpr](types#typexpr)k.
```
# type t = {house_no : int; street : string; town : string; postcode : string}
let address x =
Printf.sprintf "The occupier\n%i %s\n%s\n%s"
x.house_no x.street x.town x.postcode;;
type t = {
house_no : int;
street : string;
town : string;
postcode : string;
}
val address : t -> string =
```
The expression { [expr](#expr) with [field](names#field)1 [= [expr](#expr)1] ; … ; [field](names#field)n [= [expr](#expr)n] } builds a fresh record with fields [field](names#field)1 … [field](names#field)n equal to [expr](#expr)1 … [expr](#expr)n, and all other fields having the same value as in the record [expr](#expr). In other terms, it returns a shallow copy of the record [expr](#expr), except for the fields [field](names#field)1 … [field](names#field)n, which are initialized to [expr](#expr)1 … [expr](#expr)n. As previously, single identifier [field](names#field)k stands for [field](names#field)k = [field](names#field)k, a qualified identifier [module-path](names#module-path) . [field](names#field)k stands for [module-path](names#module-path) . [field](names#field)k = [field](names#field)k and it is possible to add an optional type constraint on each field being updated with { [expr](#expr) with [field](names#field)1 : [typexpr](types#typexpr)1 = [expr](#expr)1 ; … ; [field](names#field)n : [typexpr](types#typexpr)n = [expr](#expr)n }.
```
# type t = {house_no : int; street : string; town : string; postcode : string}
let uppercase_town address =
{address with town = String.uppercase_ascii address.town};;
type t = {
house_no : int;
street : string;
town : string;
postcode : string;
}
val uppercase_town : t -> t =
```
The expression [expr](#expr)1 . [field](names#field) evaluates [expr](#expr)1 to a record value, and returns the value associated to [field](names#field) in this record value.
The expression [expr](#expr)1 . [field](names#field) <- [expr](#expr)2 evaluates [expr](#expr)1 to a record value, which is then modified in-place by replacing the value associated to [field](names#field) in this record by the value of [expr](#expr)2. This operation is permitted only if [field](names#field) has been declared mutable in the definition of the record type. The whole expression [expr](#expr)1 . [field](names#field) <- [expr](#expr)2 evaluates to the unit value ().
```
# type t = {mutable upper : int; mutable lower : int; mutable other : int}
let stats = {upper = 0; lower = 0; other = 0}
let collect =
String.iter
(function
| 'A'..'Z' -> stats.upper <- stats.upper + 1
| 'a'..'z' -> stats.lower <- stats.lower + 1
| _ -> stats.other <- stats.other + 1);;
type t = { mutable upper : int; mutable lower : int; mutable other : int; }
val stats : t = {upper = 0; lower = 0; other = 0}
val collect : string -> unit =
```
####
[](#sss:expr-arrays)Arrays
The expression [| [expr](#expr)1 ; … ; [expr](#expr)n |] evaluates to a n-element array, whose elements are initialized with the values of [expr](#expr)1 to [expr](#expr)n respectively. The order in which these expressions are evaluated is unspecified.
The expression [expr](#expr)1 .( [expr](#expr)2 ) returns the value of element number [expr](#expr)2 in the array denoted by [expr](#expr)1. The first element has number 0; the last element has number n−1, where n is the size of the array. The exception Invalid\_argument is raised if the access is out of bounds.
The expression [expr](#expr)1 .( [expr](#expr)2 ) <- [expr](#expr)3 modifies in-place the array denoted by [expr](#expr)1, replacing element number [expr](#expr)2 by the value of [expr](#expr)3. The exception Invalid\_argument is raised if the access is out of bounds. The value of the whole expression is ().
```
# let scale arr n =
for x = 0 to Array.length arr - 1 do
arr.(x) <- arr.(x) * n
done
let x = [|1; 10; 100|]
let _ = scale x 2;;
val scale : int array -> int -> unit =
val x : int array = [|2; 20; 200|]
```
####
[](#sss:expr-strings)Strings
The expression [expr](#expr)1 .[ [expr](#expr)2 ] returns the value of character number [expr](#expr)2 in the string denoted by [expr](#expr)1. The first character has number 0; the last character has number n−1, where n is the length of the string. The exception Invalid\_argument is raised if the access is out of bounds.
```
# let iter f s =
for x = 0 to String.length s - 1 do f s.[x] done;;
val iter : (char -> 'a) -> string -> unit =
```
The expression [expr](#expr)1 .[ [expr](#expr)2 ] <- [expr](#expr)3 modifies in-place the string denoted by [expr](#expr)1, replacing character number [expr](#expr)2 by the value of [expr](#expr)3. The exception Invalid\_argument is raised if the access is out of bounds. The value of the whole expression is (). Note: this possibility is offered only for backward compatibility with older versions of OCaml and will be removed in a future version. New code should use byte sequences and the Bytes.set function.
###
[](#ss:expr-operators)11.7.5 Operators
Symbols from the class [infix-symbol](lex#infix-symbol), as well as the keywords \*, +, -, -., =, !=, <, >, or, ||, &, &&, :=, mod, land, lor, lxor, lsl, lsr, and asr can appear in infix position (between two expressions). Symbols from the class [prefix-symbol](lex#prefix-symbol), as well as the keywords - and -. can appear in prefix position (in front of an expression).
```
# (( * ), ( := ), ( || ));;
- : (int -> int -> int) * ('a ref -> 'a -> unit) * (bool -> bool -> bool) =
(, , )
```
Infix and prefix symbols do not have a fixed meaning: they are simply interpreted as applications of functions bound to the names corresponding to the symbols. The expression [prefix-symbol](lex#prefix-symbol) [expr](#expr) is interpreted as the application ( [prefix-symbol](lex#prefix-symbol) ) [expr](#expr). Similarly, the expression [expr](#expr)1 [infix-symbol](lex#infix-symbol) [expr](#expr)2 is interpreted as the application ( [infix-symbol](lex#infix-symbol) ) [expr](#expr)1 [expr](#expr)2.
The table below lists the symbols defined in the initial environment and their initial meaning. (See the description of the core library module Stdlib in chapter [27](core#c%3Acorelib) for more details). Their meaning may be changed at any time using let ( [infix-op](names#infix-op) ) name1 name2 = …
```
# let ( + ), ( - ), ( * ), ( / ) = Int64.(add, sub, mul, div);;
val ( + ) : int64 -> int64 -> int64 =
val ( - ) : int64 -> int64 -> int64 =
val ( \* ) : int64 -> int64 -> int64 =
val ( / ) : int64 -> int64 -> int64 =
```
Note: the operators &&, ||, and ~- are handled specially and it is not advisable to change their meaning.
The keywords - and -. can appear both as infix and prefix operators. When they appear as prefix operators, they are interpreted respectively as the functions (~-) and (~-.).
| | |
| --- | --- |
| Operator | Initial meaning |
| + | Integer addition. |
| - (infix) | Integer subtraction. |
| ~- - (prefix) | Integer negation. |
| \* | Integer multiplication. |
| / | Integer division. Raise Division\_by\_zero if second argument is zero. |
| mod | Integer modulus. Raise Division\_by\_zero if second argument is zero. |
| land | Bitwise logical “and” on integers. |
| lor | Bitwise logical “or” on integers. |
| lxor | Bitwise logical “exclusive or” on integers. |
| lsl | Bitwise logical shift left on integers. |
| lsr | Bitwise logical shift right on integers. |
| asr | Bitwise arithmetic shift right on integers. |
| +. | Floating-point addition. |
| -. (infix) | Floating-point subtraction. |
| ~-. -. (prefix) | Floating-point negation. |
| \*. | Floating-point multiplication. |
| /. | Floating-point division. |
| \*\* | Floating-point exponentiation. |
| @ | List concatenation. |
| ^ | String concatenation. |
| ! | Dereferencing (return the current contents of a reference). |
| := | Reference assignment (update the reference given as first argument with the value of the second argument). |
| = | Structural equality test. |
| <> | Structural inequality test. |
| == | Physical equality test. |
| != | Physical inequality test. |
| < | Test “less than”. |
| <= | Test “less than or equal”. |
| > | Test “greater than”. |
| >= | Test “greater than or equal”. |
| && & | Boolean conjunction. |
| || or | Boolean disjunction. |
###
[](#ss:expr-obj)11.7.6 Objects
####
[](#sss:expr-obj-creation)Object creation
When [class-path](names#class-path) evaluates to a class body, new [class-path](names#class-path) evaluates to a new object containing the instance variables and methods of this class.
```
# class of_list (lst : int list) = object
val mutable l = lst
method next =
match l with
| [] -> raise (Failure "empty list");
| h::t -> l <- t; h
end
let a = new of_list [1; 1; 2; 3; 5; 8; 13]
let b = new of_list;;
class of_list :
int list -> object val mutable l : int list method next : int end
val a : of_list =
val b : int list -> of\_list =
```
When [class-path](names#class-path) evaluates to a class function, new [class-path](names#class-path) evaluates to a function expecting the same number of arguments and returning a new object of this class.
####
[](#sss:expr-obj-immediate)Immediate object creation
Creating directly an object through the object [class-body](classes#class-body) end construct is operationally equivalent to defining locally a class [class-name](names#class-name) = object [class-body](classes#class-body) end —see sections [11.9.2](classes#sss%3Aclass-body) and following for the syntax of [class-body](classes#class-body)— and immediately creating a single object from it by new [class-name](names#class-name).
```
# let o =
object
val secret = 99
val password = "unlock"
method get guess = if guess <> password then None else Some secret
end;;
val o : < get : string -> int option > =
```
The typing of immediate objects is slightly different from explicitly defining a class in two respects. First, the inferred object type may contain free type variables. Second, since the class body of an immediate object will never be extended, its self type can be unified with a closed object type.
####
[](#sss:expr-method)Method invocation
The expression [expr](#expr) # [method-name](names#method-name) invokes the method [method-name](names#method-name) of the object denoted by [expr](#expr).
```
# class of_list (lst : int list) = object
val mutable l = lst
method next =
match l with
| [] -> raise (Failure "empty list");
| h::t -> l <- t; h
end
let a = new of_list [1; 1; 2; 3; 5; 8; 13]
let third = ignore a#next; ignore a#next; a#next;;
class of_list :
int list -> object val mutable l : int list method next : int end
val a : of_list =
val third : int = 2
```
If [method-name](names#method-name) is a polymorphic method, its type should be known at the invocation site. This is true for instance if [expr](#expr) is the name of a fresh object (let [ident](lex#ident) = new [class-path](names#class-path) … ) or if there is a type constraint. Principality of the derivation can be checked in the -principal mode.
####
[](#sss:expr-obj-variables)Accessing and modifying instance variables
The instance variables of a class are visible only in the body of the methods defined in the same class or a class that inherits from the class defining the instance variables. The expression [inst-var-name](names#inst-var-name) evaluates to the value of the given instance variable. The expression [inst-var-name](names#inst-var-name) <- [expr](#expr) assigns the value of [expr](#expr) to the instance variable [inst-var-name](names#inst-var-name), which must be mutable. The whole expression [inst-var-name](names#inst-var-name) <- [expr](#expr) evaluates to ().
```
# class of_list (lst : int list) = object
val mutable l = lst
method next =
match l with (* access instance variable *)
| [] -> raise (Failure "empty list");
| h::t -> l <- t; h (* modify instance variable *)
end;;
class of_list :
int list -> object val mutable l : int list method next : int end
```
####
[](#sss:expr-obj-duplication)Object duplication
An object can be duplicated using the library function Oo.copy (see module [Oo](libref/oo)). Inside a method, the expression {< [[inst-var-name](names#inst-var-name) [= [expr](#expr)] { ; [inst-var-name](names#inst-var-name) [= [expr](#expr)] }] >} returns a copy of self with the given instance variables replaced by the values of the associated expressions. A single instance variable name id stands for id = id. Other instance variables have the same value in the returned object as in self.
```
# let o =
object
val secret = 99
val password = "unlock"
method get guess = if guess <> password then None else Some secret
method with_new_secret s = {< secret = s >}
end;;
val o : < get : string -> int option; with_new_secret : int -> 'a > as 'a =
```
###
[](#ss:expr-coercions)11.7.7 Coercions
Expressions whose type contains object or polymorphic variant types can be explicitly coerced (weakened) to a supertype. The expression ([expr](#expr) :> [typexpr](types#typexpr)) coerces the expression [expr](#expr) to type [typexpr](types#typexpr). The expression ([expr](#expr) : [typexpr](types#typexpr)1 :> [typexpr](types#typexpr)2) coerces the expression [expr](#expr) from type [typexpr](types#typexpr)1 to type [typexpr](types#typexpr)2.
The former operator will sometimes fail to coerce an expression [expr](#expr) from a type [typ](types#typexpr)1 to a type [typ](types#typexpr)2 even if type [typ](types#typexpr)1 is a subtype of type [typ](types#typexpr)2: in the current implementation it only expands two levels of type abbreviations containing objects and/or polymorphic variants, keeping only recursion when it is explicit in the class type (for objects). As an exception to the above algorithm, if both the inferred type of [expr](#expr) and [typ](types#typexpr) are ground (*i.e.* do not contain type variables), the former operator behaves as the latter one, taking the inferred type of [expr](#expr) as [typ](types#typexpr)1. In case of failure with the former operator, the latter one should be used.
It is only possible to coerce an expression [expr](#expr) from type [typ](types#typexpr)1 to type [typ](types#typexpr)2, if the type of [expr](#expr) is an instance of [typ](types#typexpr)1 (like for a type annotation), and [typ](types#typexpr)1 is a subtype of [typ](types#typexpr)2. The type of the coerced expression is an instance of [typ](types#typexpr)2. If the types contain variables, they may be instantiated by the subtyping algorithm, but this is only done after determining whether [typ](types#typexpr)1 is a potential subtype of [typ](types#typexpr)2. This means that typing may fail during this latter unification step, even if some instance of [typ](types#typexpr)1 is a subtype of some instance of [typ](types#typexpr)2. In the following paragraphs we describe the subtyping relation used.
####
[](#sss:expr-obj-types)Object types
A fixed object type admits as subtype any object type that includes all its methods. The types of the methods shall be subtypes of those in the supertype. Namely,
< [met](names#method-name)1 : [typ](types#typexpr)1 ; … ; [met](names#method-name)n : [typ](types#typexpr)n >
is a supertype of
< [met](names#method-name)1 : [typ](types#typexpr)′1 ; … ; [met](names#method-name)n : [typ](types#typexpr)′n ; [met](names#method-name)n+1 : [typ](types#typexpr)′n+1 ; … ; [met](names#method-name)n+m : [typ](types#typexpr)′n+m [; ..] >
which may contain an ellipsis .. if every [typ](types#typexpr)i is a supertype of the corresponding [typ](types#typexpr)′i.
A monomorphic method type can be a supertype of a polymorphic method type. Namely, if [typ](types#typexpr) is an instance of [typ](types#typexpr)′, then 'a1 … 'an . [typ](types#typexpr)′ is a subtype of [typ](types#typexpr).
Inside a class definition, newly defined types are not available for subtyping, as the type abbreviations are not yet completely defined. There is an exception for coercing self to the (exact) type of its class: this is allowed if the type of self does not appear in a contravariant position in the class type, *i.e.* if there are no binary methods.
####
[](#sss:expr-polyvar-types)Polymorphic variant types
A polymorphic variant type [typ](types#typexpr) is a subtype of another polymorphic variant type [typ](types#typexpr)′ if the upper bound of [typ](types#typexpr) (*i.e.* the maximum set of constructors that may appear in an instance of [typ](types#typexpr)) is included in the lower bound of [typ](types#typexpr)′, and the types of arguments for the constructors of [typ](types#typexpr) are subtypes of those in [typ](types#typexpr)′. Namely,
[[<] `[C](names#constr-name)1 of [typ](types#typexpr)1 | … | `[C](names#constr-name)n of [typ](types#typexpr)n ]
which may be a shrinkable type, is a subtype of
[[>] `[C](names#constr-name)1 of [typ](types#typexpr)′1 | … | `[C](names#constr-name)n of [typ](types#typexpr)′n | `[C](names#constr-name)n+1 of [typ](types#typexpr)′n+1 | … | `[C](names#constr-name)n+m of [typ](types#typexpr)′n+m ]
which may be an extensible type, if every [typ](types#typexpr)i is a subtype of [typ](types#typexpr)′i.
####
[](#sss:expr-variance)Variance
Other types do not introduce new subtyping, but they may propagate the subtyping of their arguments. For instance, [typ](types#typexpr)1 \* [typ](types#typexpr)2 is a subtype of [typ](types#typexpr)′1 \* [typ](types#typexpr)′2 when [typ](types#typexpr)1 and [typ](types#typexpr)2 are respectively subtypes of [typ](types#typexpr)′1 and [typ](types#typexpr)′2. For function types, the relation is more subtle: [typ](types#typexpr)1 -> [typ](types#typexpr)2 is a subtype of [typ](types#typexpr)′1 -> [typ](types#typexpr)′2 if [typ](types#typexpr)1 is a supertype of [typ](types#typexpr)′1 and [typ](types#typexpr)2 is a subtype of [typ](types#typexpr)′2. For this reason, function types are covariant in their second argument (like tuples), but contravariant in their first argument. Mutable types, like array or ref are neither covariant nor contravariant, they are nonvariant, that is they do not propagate subtyping.
For user-defined types, the variance is automatically inferred: a parameter is covariant if it has only covariant occurrences, contravariant if it has only contravariant occurrences, variance-free if it has no occurrences, and nonvariant otherwise. A variance-free parameter may change freely through subtyping, it does not have to be a subtype or a supertype. For abstract and private types, the variance must be given explicitly (see section [11.8.1](typedecl#ss%3Atypedefs)), otherwise the default is nonvariant. This is also the case for constrained arguments in type definitions.
###
[](#ss:expr-other)11.7.8 Other
####
[](#sss:expr-assertion)Assertion checking
OCaml supports the assert construct to check debugging assertions. The expression assert [expr](#expr) evaluates the expression [expr](#expr) and returns () if [expr](#expr) evaluates to true. If it evaluates to false the exception Assert\_failure is raised with the source file name and the location of [expr](#expr) as arguments. Assertion checking can be turned off with the -noassert compiler option. In this case, [expr](#expr) is not evaluated at all.
```
# let f a b c =
assert (a <= b && b <= c);
(b -. a) /. (c -. b);;
val f : float -> float -> float -> float =
```
As a special case, assert false is reduced to raise (Assert\_failure ...), which gives it a polymorphic type. This means that it can be used in place of any expression (for example as a branch of any pattern-matching). It also means that the assert false “assertions” cannot be turned off by the -noassert option.
```
# let min_known_nonempty = function
| [] -> assert false
| l -> List.hd (List.sort compare l);;
val min_known_nonempty : 'a list -> 'a =
```
####
[](#sss:expr-lazy)Lazy expressions
The expression lazy [expr](#expr) returns a value v of type Lazy.t that encapsulates the computation of [expr](#expr). The argument [expr](#expr) is not evaluated at this point in the program. Instead, its evaluation will be performed the first time the function Lazy.force is applied to the value v, returning the actual value of [expr](#expr). Subsequent applications of Lazy.force to v do not evaluate [expr](#expr) again. Applications of Lazy.force may be implicit through pattern matching (see [11.6](patterns#sss%3Apat-lazy)).
```
# let lazy_greeter = lazy (print_string "Hello, World!\n");;
val lazy_greeter : unit lazy_t =
```
```
# Lazy.force lazy_greeter;;
Hello, World!
- : unit = ()
```
####
[](#sss:expr-local-modules)Local modules
The expression let module [module-name](names#module-name) = [module-expr](modules#module-expr) in [expr](#expr) locally binds the module expression [module-expr](modules#module-expr) to the identifier [module-name](names#module-name) during the evaluation of the expression [expr](#expr). It then returns the value of [expr](#expr). For example:
```
# let remove_duplicates comparison_fun string_list =
let module StringSet =
Set.Make(struct type t = string
let compare = comparison_fun end)
in
StringSet.elements
(List.fold_right StringSet.add string_list StringSet.empty);;
val remove_duplicates :
(string -> string -> int) -> string list -> string list =
```
####
[](#sss:local-opens)Local opens
The expressions let open [module-path](names#module-path) in [expr](#expr) and [module-path](names#module-path).([expr](#expr)) are strictly equivalent. These constructions locally open the module referred to by the module path [module-path](names#module-path) in the respective scope of the expression [expr](#expr).
```
# let map_3d_matrix f m =
let open Array in
map (map (map f)) m
let map_3d_matrix' f =
Array.(map (map (map f)));;
val map_3d_matrix :
('a -> 'b) -> 'a array array array -> 'b array array array =
val map\_3d\_matrix' :
('a -> 'b) -> 'a array array array -> 'b array array array =
```
When the body of a local open expression is delimited by [ ], [| |], or { }, the parentheses can be omitted. For expression, parentheses can also be omitted for {< >}. For example, [module-path](names#module-path).[[expr](#expr)] is equivalent to [module-path](names#module-path).([[expr](#expr)]), and [module-path](names#module-path).[| [expr](#expr) |] is equivalent to [module-path](names#module-path).([| [expr](#expr) |]).
```
# let vector = Random.[|int 255; int 255; int 255; int 255|];;
val vector : int array = [|220; 90; 247; 144|]
```
| programming_docs |
ocaml Chapter 35 Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk) Chapter 35 Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk)
================================================================================
* [35.1 The Graphics Library](old#s%3Agraphics-removed)
* [35.2 The Bigarray Library](old#s%3Abigarray-moved)
* [35.3 The Num Library](old#sec643)
* [35.4 The Labltk Library and OCamlBrowser](old#s%3Alabltk-removed)
This chapter describes three libraries which were formerly part of the OCaml distribution (Graphics, Num, and LablTk), and a library which has now become part of OCaml’s standard library, and is documented there (Bigarray).
[](#s:graphics-removed)35.1 The Graphics Library
--------------------------------------------------
Since OCaml 4.09, the graphics library is distributed as an external package. Its new home is:
<https://github.com/ocaml/graphics>
If you are using the opam package manager, you should install the corresponding graphics package:
```
opam install graphics
```
Before OCaml 4.09, this package simply ensures that the graphics library was installed by the compiler, and starting from OCaml 4.09 this package effectively provides the graphics library.
[](#s:bigarray-moved)35.2 The Bigarray Library
------------------------------------------------
As of OCaml 4.07, the bigarray library has been integrated into OCaml’s standard library.
The bigarray functionality may now be found in the standard library [Bigarray module](libref/bigarray), except for the map\_file function which is now part of the [Unix library](libunix#c%3Aunix). The documentation has been integrated into the documentation for the standard library.
The legacy bigarray library bundled with the compiler is a compatibility library with exactly the same interface as before, i.e. with map\_file included.
We strongly recommend that you port your code to use the standard library version instead, as the changes required are minimal.
If you choose to use the compatibility library, you must link your programs as follows:
```
ocamlc other options bigarray.cma other files
ocamlopt other options bigarray.cmxa other files
```
For interactive use of the bigarray compatibility library, do:
```
ocamlmktop -o mytop bigarray.cma
./mytop
```
or (if dynamic linking of C libraries is supported on your platform), start ocaml and type #load "bigarray.cma";;.
[](#sec643)35.3 The Num Library
---------------------------------
The num library implements integer arithmetic and rational arithmetic in arbitrary precision. It was split off the core OCaml distribution starting with the 4.06.0 release, and can now be found at <https://github.com/ocaml/num>.
New applications that need arbitrary-precision arithmetic should use the Zarith library (<https://github.com/ocaml/Zarith>) instead of the Num library, and older applications that already use Num are encouraged to switch to Zarith. Zarith delivers much better performance than Num and has a nicer API.
[](#s:labltk-removed)35.4 The Labltk Library and OCamlBrowser
---------------------------------------------------------------
Since OCaml version 4.02, the OCamlBrowser tool and the Labltk library are distributed separately from the OCaml compiler. The project is now hosted at <https://github.com/garrigue/labltk>.
ocaml None
[](#s:module-alias)12.8 Type-level module aliases
---------------------------------------------------
(Introduced in OCaml 4.02)
| | | | | | | |
| --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [specification](modtypes#specification) | ::= | ... |
| | ∣ | module [module-name](names#module-name) = [module-path](names#module-path) |
|
The above specification, inside a signature, only matches a module definition equal to [module-path](names#module-path). Conversely, a type-level module alias can be matched by itself, or by any supertype of the type of the module it references.
There are several restrictions on [module-path](names#module-path):
1. it should be of the form M0.M1...Mn (*i.e.* without functor applications);
2. inside the body of a functor, M0 should not be one of the functor parameters;
3. inside a recursive module definition, M0 should not be one of the recursively defined modules.
Such specifications are also inferred. Namely, when P is a path satisfying the above constraints,
```
module N = P
```
has type
```
module N = P
```
Type-level module aliases are used when checking module path equalities. That is, in a context where module name N is known to be an alias for P, not only these two module paths check as equal, but F(N) and F(P) are also recognized as equal. In the default compilation mode, this is the only difference with the previous approach of module aliases having just the same module type as the module they reference.
When the compiler flag -no-alias-deps is enabled, type-level module aliases are also exploited to avoid introducing dependencies between compilation units. Namely, a module alias referring to a module inside another compilation unit does not introduce a link-time dependency on that compilation unit, as long as it is not dereferenced; it still introduces a compile-time dependency if the interface needs to be read, *i.e.* if the module is a submodule of the compilation unit, or if some type components are referred to. Additionally, accessing a module alias introduces a link-time dependency on the compilation unit containing the module referenced by the alias, rather than the compilation unit containing the alias. Note that these differences in link-time behavior may be incompatible with the previous behavior, as some compilation units might not be extracted from libraries, and their side-effects ignored.
These weakened dependencies make possible to use module aliases in place of the -pack mechanism. Suppose that you have a library Mylib composed of modules A and B. Using -pack, one would issue the command line
```
ocamlc -pack a.cmo b.cmo -o mylib.cmo
```
and as a result obtain a Mylib compilation unit, containing physically A and B as submodules, and with no dependencies on their respective compilation units. Here is a concrete example of a possible alternative approach:
1. Rename the files containing A and B to Mylib\_\_A and Mylib\_\_B.
2. Create a packing interface Mylib.ml, containing the following lines.
```
module A = Mylib__A
module B = Mylib__B
```
3. Compile Mylib.ml using -no-alias-deps, and the other files using -no-alias-deps and -open Mylib (the last one is equivalent to adding the line open! Mylib at the top of each file).
```
ocamlc -c -no-alias-deps Mylib.ml
ocamlc -c -no-alias-deps -open Mylib Mylib__*.mli Mylib__*.ml
```
4. Finally, create a library containing all the compilation units, and export all the compiled interfaces.
```
ocamlc -a Mylib*.cmo -o Mylib.cma
```
This approach lets you access A and B directly inside the library, and as Mylib.A and Mylib.B from outside. It also has the advantage that Mylib is no longer monolithic: if you use Mylib.A, only Mylib\_\_A will be linked in, not Mylib\_\_B.
Note the use of double underscores in Mylib\_\_A and Mylib\_\_B. These were chosen on purpose; the compiler uses the following heuristic when printing paths: given a path Lib\_\_fooBar, if Lib.FooBar exists and is an alias for Lib\_\_fooBar, then the compiler will always display Lib.FooBar instead of Lib\_\_fooBar. This way the long Mylib\_\_ names stay hidden and all the user sees is the nicer dot names. This is how the OCaml standard library is compiled.
ocaml Foreword Foreword
========
* [Conventions](foreword#conventions)
* [License](foreword#license)
* [Availability](foreword#availability)
This manual documents the release 5.0 of the OCaml system. It is organized as follows.
* Part [I](index#p%3Atutorials), “An introduction to OCaml”, gives an overview of the language.
* Part [II](index#p%3Arefman), “The OCaml language”, is the reference description of the language.
* Part [III](index#p%3Acommands), “The OCaml tools”, documents the compilers, toplevel system, and programming utilities.
* Part [IV](index#p%3Alibrary), “The OCaml library”, describes the modules provided in the standard library.
[](#conventions)Conventions
-----------------------------
OCaml runs on several operating systems. The parts of this manual that are specific to one operating system are presented as shown below:
>
> Unix: This is material specific to the Unix family of operating systems, including Linux and macOS.
>
> Windows: This is material specific to Microsoft Windows (Vista, 7, 8, 10).
[](#license)License
---------------------
The OCaml system is copyright © 1996–2022 Institut National de Recherche en Informatique et en Automatique (INRIA). INRIA holds all ownership rights to the OCaml system.
The OCaml system is open source and can be freely redistributed. See the file LICENSE in the distribution for licensing information.
The OCaml documentation and user’s manual is copyright © 2022 Institut National de Recherche en Informatique et en Automatique (INRIA).
The OCaml documentation and user's manual is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/).
[](#availability)Availability
-------------------------------
The complete OCaml distribution can be accessed via the [ocaml.org website](https://ocaml.org/). This site contains a lot of additional information on OCaml.
ocaml None
[](#s:first-class-modules)12.5 First-class modules
----------------------------------------------------
(Introduced in OCaml 3.12; pattern syntax and package type inference introduced in 4.00; structural comparison of package types introduced in 4.02.; fewer parens required starting from 4.05)
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [typexpr](types#typexpr) | ::= | ... |
| | ∣ | (module [package-type](#package-type)) |
| |
| [module-expr](modules#module-expr) | ::= | ... |
| | ∣ | (val [expr](expr#expr) [: [package-type](#package-type)]) |
| |
| [expr](expr#expr) | ::= | ... |
| | ∣ | (module [module-expr](modules#module-expr) [: [package-type](#package-type)]) |
| |
| [pattern](patterns#pattern) | ::= | ... |
| | ∣ | (module [module-name](names#module-name) [: [package-type](#package-type)]) |
| |
| package-type | ::= | [modtype-path](names#modtype-path) |
| | ∣ | [modtype-path](names#modtype-path) with [package-constraint](#package-constraint) { and [package-constraint](#package-constraint) } |
| |
| package-constraint | ::= | type [typeconstr](names#typeconstr) = [typexpr](types#typexpr) |
| |
|
Modules are typically thought of as static components. This extension makes it possible to pack a module as a first-class value, which can later be dynamically unpacked into a module.
The expression ( module [module-expr](modules#module-expr) : [package-type](#package-type) ) converts the module (structure or functor) denoted by module expression [module-expr](modules#module-expr) to a value of the core language that encapsulates this module. The type of this core language value is ( module [package-type](#package-type) ). The [package-type](#package-type) annotation can be omitted if it can be inferred from the context.
Conversely, the module expression ( val [expr](expr#expr) : [package-type](#package-type) ) evaluates the core language expression [expr](expr#expr) to a value, which must have type module [package-type](#package-type), and extracts the module that was encapsulated in this value. Again [package-type](#package-type) can be omitted if the type of [expr](expr#expr) is known. If the module expression is already parenthesized, like the arguments of functors are, no additional parens are needed: Map.Make(val key).
The pattern ( module [module-name](names#module-name) : [package-type](#package-type) ) matches a package with type [package-type](#package-type) and binds it to [module-name](names#module-name). It is not allowed in toplevel let bindings. Again [package-type](#package-type) can be omitted if it can be inferred from the enclosing pattern.
The [package-type](#package-type) syntactic class appearing in the ( module [package-type](#package-type) ) type expression and in the annotated forms represents a subset of module types. This subset consists of named module types with optional constraints of a limited form: only non-parametrized types can be specified.
For type-checking purposes (and starting from OCaml 4.02), package types are compared using the structural comparison of module types.
In general, the module expression ( val [expr](expr#expr) : [package-type](#package-type) ) cannot be used in the body of a functor, because this could cause unsoundness in conjunction with applicative functors. Since OCaml 4.02, this is relaxed in two ways: if [package-type](#package-type) does not contain nominal type declarations (*i.e.* types that are created with a proper identity), then this expression can be used anywhere, and even if it contains such types it can be used inside the body of a generative functor, described in section [12.15](generativefunctors#s%3Agenerative-functors). It can also be used anywhere in the context of a local module binding let module [module-name](names#module-name) = ( val [expr](expr#expr)1 : [package-type](#package-type) ) in [expr](expr#expr)2.
#####
[](#p:fst-mod-example)Basic example
A typical use of first-class modules is to select at run-time among several implementations of a signature. Each implementation is a structure that we can encapsulate as a first-class module, then store in a data structure such as a hash table:
```
type picture = …
module type DEVICE = sig
val draw : picture -> unit
…
end
let devices : (string, (module DEVICE)) Hashtbl.t = Hashtbl.create 17
module SVG = struct … end
let _ = Hashtbl.add devices "SVG" (module SVG : DEVICE)
module PDF = struct … end
let _ = Hashtbl.add devices "PDF" (module PDF : DEVICE)
```
We can then select one implementation based on command-line arguments, for instance:
```
let parse_cmdline () = …
module Device =
(val (let device_name = parse_cmdline () in
try Hashtbl.find devices device_name
with Not_found ->
Printf.eprintf "Unknown device %s\n" device_name;
exit 2)
: DEVICE)
```
Alternatively, the selection can be performed within a function:
```
let draw_using_device device_name picture =
let module Device =
(val (Hashtbl.find devices device_name) : DEVICE)
in
Device.draw picture
```
#####
[](#p:fst-mod-advexamples)Advanced examples
With first-class modules, it is possible to parametrize some code over the implementation of a module without using a functor.
```
let sort (type s) (module Set : Set.S with type elt = s) l =
Set.elements (List.fold_right Set.add l Set.empty)
val sort : (module Set.S with type elt = 's) -> 's list -> 's list =
```
To use this function, one can wrap the Set.Make functor:
```
let make_set (type s) cmp =
let module S = Set.Make(struct
type t = s
let compare = cmp
end) in
(module S : Set.S with type elt = s)
val make_set : ('s -> 's -> int) -> (module Set.S with type elt = 's) =
```
ocaml None
[](#s:doc-comments)12.18 Documentation comments
-------------------------------------------------
* [12.18.1 Floating comments](doccomments#ss%3Afloating-comments)
* [12.18.2 Item comments](doccomments#ss%3Aitem-comments)
* [12.18.3 Label comments](doccomments#ss%3Alabel-comments)
(Introduced in OCaml 4.03)
Comments which start with \*\* are treated specially by the compiler. They are automatically converted during parsing into attributes (see [12.12](attributes#s%3Aattributes)) to allow tools to process them as documentation.
Such comments can take three forms: *floating comments*, *item comments* and *label comments*. Any comment starting with \*\* which does not match one of these forms will cause the compiler to emit warning 50.
Comments which start with \*\* are also used by the ocamldoc documentation generator (see [19](ocamldoc#c%3Aocamldoc)). The three comment forms recognised by the compiler are a subset of the forms accepted by ocamldoc (see [19.2](ocamldoc#s%3Aocamldoc-comments)).
###
[](#ss:floating-comments)12.18.1 Floating comments
Comments surrounded by blank lines that appear within structures, signatures, classes or class types are converted into [floating-attribute](attributes#floating-attribute)s. For example:
```
type t = T
(** Now some definitions for [t] *)
let mkT = T
```
will be converted to:
```
type t = T
[@@@ocaml.text " Now some definitions for [t] "]
let mkT = T
```
###
[](#ss:item-comments)12.18.2 Item comments
Comments which appear *immediately before* or *immediately after* a structure item, signature item, class item or class type item are converted into [item-attribute](attributes#item-attribute)s. Immediately before or immediately after means that there must be no blank lines, ;;, or other documentation comments between them. For example:
```
type t = T
(** A description of [t] *)
```
or
```
(** A description of [t] *)
type t = T
```
will be converted to:
```
type t = T
[@@ocaml.doc " A description of [t] "]
```
Note that, if a comment appears immediately next to multiple items, as in:
```
type t = T
(** An ambiguous comment *)
type s = S
```
then it will be attached to both items:
```
type t = T
[@@ocaml.doc " An ambiguous comment "]
type s = S
[@@ocaml.doc " An ambiguous comment "]
```
and the compiler will emit warning 50.
###
[](#ss:label-comments)12.18.3 Label comments
Comments which appear *immediately after* a labelled argument, record field, variant constructor, object method or polymorphic variant constructor are are converted into [attribute](attributes#attribute)s. Immediately after means that there must be no blank lines or other documentation comments between them. For example:
```
type t1 = lbl:int (** Labelled argument *) -> unit
type t2 = {
fld: int; (** Record field *)
fld2: float;
}
type t3 =
| Cstr of string (** Variant constructor *)
| Cstr2 of string
type t4 = < meth: int * int; (** Object method *) >
type t5 = [
`PCstr (** Polymorphic variant constructor *)
]
```
will be converted to:
```
type t1 = lbl:(int [@ocaml.doc " Labelled argument "]) -> unit
type t2 = {
fld: int [@ocaml.doc " Record field "];
fld2: float;
}
type t3 =
| Cstr of string [@ocaml.doc " Variant constructor "]
| Cstr2 of string
type t4 = < meth : int * int [@ocaml.doc " Object method "] >
type t5 = [
`PCstr [@ocaml.doc " Polymorphic variant constructor "]
]
```
Note that label comments take precedence over item comments, so:
```
type t = T of string
(** Attaches to T not t *)
```
will be converted to:
```
type t = T of string [@ocaml.doc " Attaches to T not t "]
```
whilst:
```
type t = T of string
(** Attaches to T not t *)
(** Attaches to t *)
```
will be converted to:
```
type t = T of string [@ocaml.doc " Attaches to T not t "]
[@@ocaml.doc " Attaches to t "]
```
In the absence of meaningful comment on the last constructor of a type, an empty comment (\*\*) can be used instead:
```
type t = T of string
(**)
(** Attaches to t *)
```
will be converted directly to
```
type t = T of string
[@@ocaml.doc " Attaches to t "]
```
| programming_docs |
ocaml None
[](#s:extension-syntax)12.16 Extension-only syntax
----------------------------------------------------
* [12.16.1 Extension operators](extensionsyntax#ss%3Aextension-operators)
* [12.16.2 Extension literals](extensionsyntax#ss%3Aextension-literals)
(Introduced in OCaml 4.02.2, extended in 4.03)
Some syntactic constructions are accepted during parsing and rejected during type checking. These syntactic constructions can therefore not be used directly in vanilla OCaml. However, -ppx rewriters and other external tools can exploit this parser leniency to extend the language with these new syntactic constructions by rewriting them to vanilla constructions.
###
[](#ss:extension-operators)12.16.1 Extension operators
(Introduced in OCaml 4.02.2, extended to unary operators in OCaml 4.12.0)
| | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| infix-symbol | ::= | ... |
| | ∣ | # { [operator-char](lex#operator-char) } # { [operator-char](lex#operator-char) ∣ # } |
| |
| prefix-symbol | ::= | ... |
| | ∣ | (? ∣ ~ ∣ !) { [operator-char](lex#operator-char) } # { [operator-char](lex#operator-char) ∣ # } |
| |
|
There are two classes of operators available for extensions: infix operators with a name starting with a # character and containing more than one # character, and unary operators with a name (starting with a ?, ~, or ! character) containing at least one # character.
For instance:
```
# let infix x y = x##y;;
Error: '##' is not a valid value identifier.
```
```
# let prefix x = !#x;;
Error: '!#' is not a valid value identifier.
```
Note that both ## and !# must be eliminated by a ppx rewriter to make this example valid.
###
[](#ss:extension-literals)12.16.2 Extension literals
(Introduced in OCaml 4.03)
| | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| float-literal | ::= | ... |
| | ∣ | [-] (0…9) { 0…9 ∣ \_ } [. { 0…9 ∣ \_ }] [(e ∣ E) [+ ∣ -] (0…9) { 0…9 ∣ \_ }] [g…z ∣ G…Z] |
| | ∣ | [-] (0x ∣ 0X) (0…9 ∣ A…F ∣ a…f) { 0…9 ∣ A…F ∣ a…f ∣ \_ } [. { 0…9 ∣ A…F ∣ a…f ∣ \_ }] [(p ∣ P) [+ ∣ -] (0…9) { 0…9 ∣ \_ }] [g…z ∣ G…Z] |
| |
| int-literal | ::= | ... |
| | ∣ | [-] (0…9) { 0…9 ∣ \_ }[g…z ∣ G…Z] |
| | ∣ | [-] (0x ∣ 0X) (0…9 ∣ A…F ∣ a…f) { 0…9 ∣ A…F ∣ a…f ∣ \_ } [g…z ∣ G…Z] |
| | ∣ | [-] (0o ∣ 0O) (0…7) { 0…7 ∣ \_ } [g…z ∣ G…Z] |
| | ∣ | [-] (0b ∣ 0B) (0…1) { 0…1 ∣ \_ } [g…z ∣ G…Z] |
| |
|
Int and float literals followed by an one-letter identifier in the range [g..z∣G..Z] are extension-only literals.
ocaml Chapter 11 The OCaml language Chapter 11 The OCaml language
=============================
###
[](#ss:foreword)Foreword
This document is intended as a reference manual for the OCaml language. It lists the language constructs, and gives their precise syntax and informal semantics. It is by no means a tutorial introduction to the language. A good working knowledge of OCaml is assumed.
No attempt has been made at mathematical rigor: words are employed with their intuitive meaning, without further definition. As a consequence, the typing rules have been left out, by lack of the mathematical framework required to express them, while they are definitely part of a full formal definition of the language.
###
[](#ss:notations)Notations
The syntax of the language is given in BNF-like notation. Terminal symbols are set in typewriter font (like this). Non-terminal symbols are set in italic font (like that). Square brackets […] denote optional components. Curly brackets {…} denotes zero, one or several repetitions of the enclosed components. Curly brackets with a trailing plus sign {…}+ denote one or several repetitions of the enclosed components. Parentheses (…) denote grouping.
* [11.1 Lexical conventions](lex)
* [11.2 Values](values)
* [11.3 Names](names)
* [11.4 Type expressions](types)
* [11.5 Constants](const)
* [11.6 Patterns](patterns)
* [11.7 Expressions](expr)
* [11.8 Type and exception definitions](typedecl)
* [11.9 Classes](classes)
* [11.10 Module types (module specifications)](modtypes)
* [11.11 Module expressions (module implementations)](modules)
* [11.12 Compilation units](compunit)
ocaml Chapter 6 Polymorphism and its limitations Chapter 6 Polymorphism and its limitations
==========================================
* [6.1 Weak polymorphism and mutation](polymorphism#s%3Aweak-polymorphism)
* [6.2 Polymorphic recursion](polymorphism#s%3Apolymorphic-recursion)
* [6.3 Higher-rank polymorphic functions](polymorphism#s%3Ahigher-rank-poly)
This chapter covers more advanced questions related to the limitations of polymorphic functions and types. There are some situations in OCaml where the type inferred by the type checker may be less generic than expected. Such non-genericity can stem either from interactions between side-effects and typing or the difficulties of implicit polymorphic recursion and higher-rank polymorphism.
This chapter details each of these situations and, if it is possible, how to recover genericity.
[](#s:weak-polymorphism)6.1 Weak polymorphism and mutation
------------------------------------------------------------
###
[](#ss:weak-types)6.1.1 Weakly polymorphic types
Maybe the most frequent examples of non-genericity derive from the interactions between polymorphic types and mutation. A simple example appears when typing the following expression
```
# let store = ref None ;;
val store : '_weak1 option ref = {contents = None}
```
Since the type of None is 'a option and the function ref has type 'b -> 'b ref, a natural deduction for the type of store would be 'a option ref. However, the inferred type, '\_weak1 option ref, is different. Type variables whose names start with a \_weak prefix like '\_weak1 are weakly polymorphic type variables, sometimes shortened to “weak type variables”. A weak type variable is a placeholder for a single type that is currently unknown. Once the specific type t behind the placeholder type '\_weak1 is known, all occurrences of '\_weak1 will be replaced by t. For instance, we can define another option reference and store an int inside:
```
# let another_store = ref None ;;
val another_store : '_weak2 option ref = {contents = None}
```
```
# another_store := Some 0;
another_store ;;
- : int option ref = {contents = Some 0}
```
After storing an int inside another\_store, the type of another\_store has been updated from '\_weak2 option ref to int option ref. This distinction between weakly and generic polymorphic type variable protects OCaml programs from unsoundness and runtime errors. To understand from where unsoundness might come, consider this simple function which swaps a value x with the value stored inside a store reference, if there is such value:
```
# let swap store x = match !store with
| None -> store := Some x; x
| Some y -> store := Some x; y;;
val swap : 'a option ref -> 'a -> 'a =
```
We can apply this function to our store
```
# let one = swap store 1
let one_again = swap store 2
let two = swap store 3;;
val one : int = 1
val one_again : int = 1
val two : int = 2
```
After these three swaps the stored value is 3. Everything is fine up to now. We can then try to swap 3 with a more interesting value, for instance a function:
```
# let error = swap store (fun x -> x);;
Error: This expression should not be a function, the expected type is int
```
At this point, the type checker rightfully complains that it is not possible to swap an integer and a function, and that an int should always be traded for another int. Furthermore, the type checker prevents us from manually changing the type of the value stored by store:
```
# store := Some (fun x -> x);;
Error: This expression should not be a function, the expected type is int
```
Indeed, looking at the type of store, we see that the weak type '\_weak1 has been replaced by the type int
```
# store;;
- : int option ref = {contents = Some 3}
```
Therefore, after placing an int in store, we cannot use it to store any value other than an int. More generally, weak types protect the program from undue mutation of values with a polymorphic type.
Moreover, weak types cannot appear in the signature of toplevel modules: types must be known at compilation time. Otherwise, different compilation units could replace the weak type with different and incompatible types. For this reason, compiling the following small piece of code
```
let option_ref = ref None
```
yields a compilation error
```
Error: The type of this expression, '_weak1 option ref,
contains type variables that cannot be generalized
```
To solve this error, it is enough to add an explicit type annotation to specify the type at declaration time:
```
let option_ref: int option ref = ref None
```
This is in any case a good practice for such global mutable variables. Otherwise, they will pick out the type of first use. If there is a mistake at this point, it can result in confusing type errors when later, correct uses are flagged as errors.
###
[](#ss:valuerestriction)6.1.2 The value restriction
Identifying the exact context in which polymorphic types should be replaced by weak types in a modular way is a difficult question. Indeed the type system must handle the possibility that functions may hide persistent mutable states. For instance, the following function uses an internal reference to implement a delayed identity function
```
# let make_fake_id () =
let store = ref None in
fun x -> swap store x ;;
val make_fake_id : unit -> 'a -> 'a =
```
```
# let fake_id = make_fake_id();;
val fake_id : '_weak3 -> '_weak3 =
```
It would be unsound to apply this fake\_id function to values with different types. The function fake\_id is therefore rightfully assigned the type '\_weak3 -> '\_weak3 rather than 'a -> 'a. At the same time, it ought to be possible to use a local mutable state without impacting the type of a function.
To circumvent these dual difficulties, the type checker considers that any value returned by a function might rely on persistent mutable states behind the scene and should be given a weak type. This restriction on the type of mutable values and the results of function application is called the value restriction. Note that this value restriction is conservative: there are situations where the value restriction is too cautious and gives a weak type to a value that could be safely generalized to a polymorphic type:
```
# let not_id = (fun x -> x) (fun x -> x);;
val not_id : '_weak4 -> '_weak4 =
```
Quite often, this happens when defining functions using higher order functions. To avoid this problem, a solution is to add an explicit argument to the function:
```
# let id_again = fun x -> (fun x -> x) (fun x -> x) x;;
val id_again : 'a -> 'a =
```
With this argument, id\_again is seen as a function definition by the type checker and can therefore be generalized. This kind of manipulation is called eta-expansion in lambda calculus and is sometimes referred under this name.
###
[](#ss:relaxed-value-restriction)6.1.3 The relaxed value restriction
There is another partial solution to the problem of unnecessary weak types, which is implemented directly within the type checker. Briefly, it is possible to prove that weak types that only appear as type parameters in covariant positions –also called positive positions– can be safely generalized to polymorphic types. For instance, the type 'a list is covariant in 'a:
```
# let f () = [];;
val f : unit -> 'a list =
```
```
# let empty = f ();;
val empty : 'a list = []
```
Note that the type inferred for empty is 'a list and not the '\_weak5 list that should have occurred with the value restriction.
The value restriction combined with this generalization for covariant type parameters is called the relaxed value restriction.
###
[](#ss:variance-and-value-restriction)6.1.4 Variance and value restriction
Variance describes how type constructors behave with respect to subtyping. Consider for instance a pair of type x and xy with x a subtype of xy, denoted x :> xy:
```
# type x = [ `X ];;
type x = [ `X ]
```
```
# type xy = [ `X | `Y ];;
type xy = [ `X | `Y ]
```
As x is a subtype of xy, we can convert a value of type x to a value of type xy:
```
# let x:x = `X;;
val x : x = `X
```
```
# let x' = ( x :> xy);;
val x' : xy = `X
```
Similarly, if we have a value of type x list, we can convert it to a value of type xy list, since we could convert each element one by one:
```
# let l:x list = [`X; `X];;
val l : x list = [`X; `X]
```
```
# let l' = ( l :> xy list);;
val l' : xy list = [`X; `X]
```
In other words, x :> xy implies that x list :> xy list, therefore the type constructor 'a list is covariant (it preserves subtyping) in its parameter 'a.
Contrarily, if we have a function that can handle values of type xy
```
# let f: xy -> unit = function
| `X -> ()
| `Y -> ();;
val f : xy -> unit =
```
it can also handle values of type x:
```
# let f' = (f :> x -> unit);;
val f' : x -> unit =
```
Note that we can rewrite the type of f and f' as
```
# type 'a proc = 'a -> unit
let f' = (f: xy proc :> x proc);;
type 'a proc = 'a -> unit
val f' : x proc =
```
In this case, we have x :> xy implies xy proc :> x proc. Notice that the second subtyping relation reverse the order of x and xy: the type constructor 'a proc is contravariant in its parameter 'a. More generally, the function type constructor 'a -> 'b is covariant in its return type 'b and contravariant in its argument type 'a.
A type constructor can also be invariant in some of its type parameters, neither covariant nor contravariant. A typical example is a reference:
```
# let x: x ref = ref `X;;
val x : x ref = {contents = `X}
```
If we were able to coerce x to the type xy ref as a variable xy, we could use xy to store the value `Y inside the reference and then use the x value to read this content as a value of type x, which would break the type system.
More generally, as soon as a type variable appears in a position describing mutable state it becomes invariant. As a corollary, covariant variables will never denote mutable locations and can be safely generalized. For a better description, interested readers can consult the original article by Jacques Garrigue on <http://www.math.nagoya-u.ac.jp/~garrigue/papers/morepoly-long.pdf>
Together, the relaxed value restriction and type parameter covariance help to avoid eta-expansion in many situations.
###
[](#ss:variance:abstract-data-types)6.1.5 Abstract data types
Moreover, when the type definitions are exposed, the type checker is able to infer variance information on its own and one can benefit from the relaxed value restriction even unknowingly. However, this is not the case anymore when defining new abstract types. As an illustration, we can define a module type collection as:
```
# module type COLLECTION = sig
type 'a t
val empty: unit -> 'a t
end
module Implementation = struct
type 'a t = 'a list
let empty ()= []
end;;
module type COLLECTION = sig type 'a t val empty : unit -> 'a t end
module Implementation :
sig type 'a t = 'a list val empty : unit -> 'a list end
```
```
# module List2: COLLECTION = Implementation;;
module List2 : COLLECTION
```
In this situation, when coercing the module List2 to the module type COLLECTION, the type checker forgets that 'a List2.t was covariant in 'a. Consequently, the relaxed value restriction does not apply anymore:
```
# List2.empty ();;
- : '_weak5 List2.t =
```
To keep the relaxed value restriction, we need to declare the abstract type 'a COLLECTION.t as covariant in 'a:
```
# module type COLLECTION = sig
type +'a t
val empty: unit -> 'a t
end
module List2: COLLECTION = Implementation;;
module type COLLECTION = sig type +'a t val empty : unit -> 'a t end
module List2 : COLLECTION
```
We then recover polymorphism:
```
# List2.empty ();;
- : 'a List2.t =
```
[](#s:polymorphic-recursion)6.2 Polymorphic recursion
-------------------------------------------------------
The second major class of non-genericity is directly related to the problem of type inference for polymorphic functions. In some circumstances, the type inferred by OCaml might be not general enough to allow the definition of some recursive functions, in particular for recursive functions acting on non-regular algebraic data types.
With a regular polymorphic algebraic data type, the type parameters of the type constructor are constant within the definition of the type. For instance, we can look at arbitrarily nested list defined as:
```
# type 'a regular_nested = List of 'a list | Nested of 'a regular_nested list
let l = Nested[ List [1]; Nested [List[2;3]]; Nested[Nested[]] ];;
type 'a regular_nested = List of 'a list | Nested of 'a regular_nested list
val l : int regular_nested =
Nested [List [1]; Nested [List [2; 3]]; Nested [Nested []]]
```
Note that the type constructor regular\_nested always appears as 'a regular\_nested in the definition above, with the same parameter 'a. Equipped with this type, one can compute a maximal depth with a classic recursive function
```
# let rec maximal_depth = function
| List _ -> 1
| Nested [] -> 0
| Nested (a::q) -> 1 + max (maximal_depth a) (maximal_depth (Nested q));;
val maximal_depth : 'a regular_nested -> int =
```
Non-regular recursive algebraic data types correspond to polymorphic algebraic data types whose parameter types vary between the left and right side of the type definition. For instance, it might be interesting to define a datatype that ensures that all lists are nested at the same depth:
```
# type 'a nested = List of 'a list | Nested of 'a list nested;;
type 'a nested = List of 'a list | Nested of 'a list nested
```
Intuitively, a value of type 'a nested is a list of list …of list of elements a with k nested list. We can then adapt the maximal\_depth function defined on regular\_depth into a depth function that computes this k. As a first try, we may define
```
# let rec depth = function
| List _ -> 1
| Nested n -> 1 + depth n;;
Error: This expression has type 'a list nested
but an expression was expected of type 'a nested
The type variable 'a occurs inside 'a list
```
The type error here comes from the fact that during the definition of depth, the type checker first assigns to depth the type 'a -> 'b . When typing the pattern matching, 'a -> 'b becomes 'a nested -> 'b, then 'a nested -> int once the List branch is typed. However, when typing the application depth n in the Nested branch, the type checker encounters a problem: depth n is applied to 'a list nested, it must therefore have the type 'a list nested -> 'b. Unifying this constraint with the previous one leads to the impossible constraint 'a list nested = 'a nested. In other words, within its definition, the recursive function depth is applied to values of type 'a t with different types 'a due to the non-regularity of the type constructor nested. This creates a problem because the type checker had introduced a new type variable 'a only at the *definition* of the function depth whereas, here, we need a different type variable for every *application* of the function depth.
###
[](#ss:explicit-polymorphism)6.2.1 Explicitly polymorphic annotations
The solution of this conundrum is to use an explicitly polymorphic type annotation for the type 'a:
```
# let rec depth: 'a. 'a nested -> int = function
| List _ -> 1
| Nested n -> 1 + depth n;;
val depth : 'a nested -> int =
```
```
# depth ( Nested(List [ [7]; [8] ]) );;
- : int = 2
```
In the type of depth, 'a.'a nested -> int, the type variable 'a is universally quantified. In other words, 'a.'a nested -> int reads as “for all type 'a, depth maps 'a nested values to integers”. Whereas the standard type 'a nested -> int can be interpreted as “let be a type variable 'a, then depth maps 'a nested values to integers”. There are two major differences with these two type expressions. First, the explicit polymorphic annotation indicates to the type checker that it needs to introduce a new type variable every time the function depth is applied. This solves our problem with the definition of the function depth.
Second, it also notifies the type checker that the type of the function should be polymorphic. Indeed, without explicit polymorphic type annotation, the following type annotation is perfectly valid
```
# let sum: 'a -> 'b -> 'c = fun x y -> x + y;;
val sum : int -> int -> int =
```
since 'a,'b and 'c denote type variables that may or may not be polymorphic. Whereas, it is an error to unify an explicitly polymorphic type with a non-polymorphic type:
```
# let sum: 'a 'b 'c. 'a -> 'b -> 'c = fun x y -> x + y;;
Error: This definition has type int -> int -> int which is less general than
'a 'b 'c. 'a -> 'b -> 'c
```
An important remark here is that it is not needed to explicit fully the type of depth: it is sufficient to add annotations only for the universally quantified type variables:
```
# let rec depth: 'a. 'a nested -> _ = function
| List _ -> 1
| Nested n -> 1 + depth n;;
val depth : 'a nested -> int =
```
```
# depth ( Nested(List [ [7]; [8] ]) );;
- : int = 2
```
###
[](#ss:recursive-poly-examples)6.2.2 More examples
With explicit polymorphic annotations, it becomes possible to implement any recursive function that depends only on the structure of the nested lists and not on the type of the elements. For instance, a more complex example would be to compute the total number of elements of the nested lists:
```
# let len nested =
let map_and_sum f = List.fold_left (fun acc x -> acc + f x) 0 in
let rec len: 'a. ('a list -> int ) -> 'a nested -> int =
fun nested_len n ->
match n with
| List l -> nested_len l
| Nested n -> len (map_and_sum nested_len) n
in
len List.length nested;;
val len : 'a nested -> int =
```
```
# len (Nested(Nested(List [ [ [1;2]; [3] ]; [ []; [4]; [5;6;7]]; [[]] ])));;
- : int = 7
```
Similarly, it may be necessary to use more than one explicitly polymorphic type variables, like for computing the nested list of list lengths of the nested list:
```
# let shape n =
let rec shape: 'a 'b. ('a nested -> int nested) ->
('b list list -> 'a list) -> 'b nested -> int nested
= fun nest nested_shape ->
function
| List l -> raise
(Invalid_argument "shape requires nested_list of depth greater than 1")
| Nested (List l) -> nest @@ List (nested_shape l)
| Nested n ->
let nested_shape = List.map nested_shape in
let nest x = nest (Nested x) in
shape nest nested_shape n in
shape (fun n -> n ) (fun l -> List.map List.length l ) n;;
val shape : 'a nested -> int nested =
```
```
# shape (Nested(Nested(List [ [ [1;2]; [3] ]; [ []; [4]; [5;6;7]]; [[]] ])));;
- : int nested = Nested (List [[2; 1]; [0; 1; 3]; [0]])
```
[](#s:higher-rank-poly)6.3 Higher-rank polymorphic functions
--------------------------------------------------------------
Explicit polymorphic annotations are however not sufficient to cover all the cases where the inferred type of a function is less general than expected. A similar problem arises when using polymorphic functions as arguments of higher-order functions. For instance, we may want to compute the average depth or length of two nested lists:
```
# let average_depth x y = (depth x + depth y) / 2;;
val average_depth : 'a nested -> 'b nested -> int =
```
```
# let average_len x y = (len x + len y) / 2;;
val average_len : 'a nested -> 'b nested -> int =
```
```
# let one = average_len (List [2]) (List [[]]);;
val one : int = 1
```
It would be natural to factorize these two definitions as:
```
# let average f x y = (f x + f y) / 2;;
val average : ('a -> int) -> 'a -> 'a -> int =
```
However, the type of average len is less generic than the type of average\_len, since it requires the type of the first and second argument to be the same:
```
# average_len (List [2]) (List [[]]);;
- : int = 1
```
```
# average len (List [2]) (List [[]]);;
Error: This expression has type 'a list
but an expression was expected of type int
```
As previously with polymorphic recursion, the problem stems from the fact that type variables are introduced only at the start of the let definitions. When we compute both f x and f y, the type of x and y are unified together. To avoid this unification, we need to indicate to the type checker that f is polymorphic in its first argument. In some sense, we would want average to have type
```
val average: ('a. 'a nested -> int) -> 'a nested -> 'b nested -> int
```
Note that this syntax is not valid within OCaml: average has an universally quantified type 'a inside the type of one of its argument whereas for polymorphic recursion the universally quantified type was introduced before the rest of the type. This position of the universally quantified type means that average is a second-rank polymorphic function. This kind of higher-rank functions is not directly supported by OCaml: type inference for second-rank polymorphic function and beyond is undecidable; therefore using this kind of higher-rank functions requires to handle manually these universally quantified types.
In OCaml, there are two ways to introduce this kind of explicit universally quantified types: universally quantified record fields,
```
# type 'a nested_reduction = { f:'elt. 'elt nested -> 'a };;
type 'a nested_reduction = { f : 'elt. 'elt nested -> 'a; }
```
```
# let boxed_len = { f = len };;
val boxed_len : int nested_reduction = {f = }
```
and universally quantified object methods:
```
# let obj_len = object method f:'a. 'a nested -> 'b = len end;;
val obj_len : < f : 'a. 'a nested -> int > =
```
To solve our problem, we can therefore use either the record solution:
```
# let average nsm x y = (nsm.f x + nsm.f y) / 2 ;;
val average : int nested_reduction -> 'a nested -> 'b nested -> int =
```
or the object one:
```
# let average (obj:<f:'a. 'a nested -> _ > ) x y = (obj#f x + obj#f y) / 2 ;;
val average : < f : 'a. 'a nested -> int > -> 'b nested -> 'c nested -> int =
```
| programming_docs |
ocaml Chapter 22 Interfacing C with OCaml Chapter 22 Interfacing C with OCaml
===================================
* [22.1 Overview and compilation information](intfc#s%3Ac-overview)
* [22.2 The value type](intfc#s%3Ac-value)
* [22.3 Representation of OCaml data types](intfc#s%3Ac-ocaml-datatype-repr)
* [22.4 Operations on values](intfc#s%3Ac-ops-on-values)
* [22.5 Living in harmony with the garbage collector](intfc#s%3Ac-gc-harmony)
* [22.6 A complete example](intfc#s%3Ac-intf-example)
* [22.7 Advanced topic: callbacks from C to OCaml](intfc#s%3Ac-callback)
* [22.8 Advanced example with callbacks](intfc#s%3Ac-advexample)
* [22.9 Advanced topic: custom blocks](intfc#s%3Ac-custom)
* [22.10 Advanced topic: Bigarrays and the OCaml-C interface](intfc#s%3AC-Bigarrays)
* [22.11 Advanced topic: cheaper C call](intfc#s%3AC-cheaper-call)
* [22.12 Advanced topic: multithreading](intfc#s%3AC-multithreading)
* [22.13 Advanced topic: interfacing with Windows Unicode APIs](intfc#s%3Ainterfacing-windows-unicode-apis)
* [22.14 Building mixed C/OCaml libraries: ocamlmklib](intfc#s%3Aocamlmklib)
* [22.15 Cautionary words: the internal runtime API](intfc#s%3Ac-internal-guidelines)
This chapter describes how user-defined primitives, written in C, can be linked with OCaml code and called from OCaml functions, and how these C functions can call back to OCaml code.
[](#s:c-overview)22.1 Overview and compilation information
------------------------------------------------------------
###
[](#ss:c-prim-decl)22.1.1 Declaring primitives
| | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [definition](modules#definition) | ::= | ... |
| | ∣ | external [value-name](names#value-name) : [typexpr](types#typexpr) = [external-declaration](#external-declaration) |
| |
| external-declaration | ::= | [string-literal](lex#string-literal) [ [string-literal](lex#string-literal) [ [string-literal](lex#string-literal) ] ] |
|
User primitives are declared in an implementation file or struct…end module expression using the external keyword:
```
external name : type = C-function-name
```
This defines the value name name as a function with type type that executes by calling the given C function. For instance, here is how the seek\_in primitive is declared in the standard library module Stdlib:
```
external seek_in : in_channel -> int -> unit = "caml_ml_seek_in"
```
Primitives with several arguments are always curried. The C function does not necessarily have the same name as the ML function.
External functions thus defined can be specified in interface files or sig…end signatures either as regular values
```
val name : type
```
thus hiding their implementation as C functions, or explicitly as “manifest” external functions
```
external name : type = C-function-name
```
The latter is slightly more efficient, as it allows clients of the module to call directly the C function instead of going through the corresponding OCaml function. On the other hand, it should not be used in library modules if they have side-effects at toplevel, as this direct call interferes with the linker’s algorithm for removing unused modules from libraries at link-time.
The arity (number of arguments) of a primitive is automatically determined from its OCaml type in the external declaration, by counting the number of function arrows in the type. For instance, seek\_in above has arity 2, and the caml\_ml\_seek\_in C function is called with two arguments. Similarly,
```
external seek_in_pair: in_channel * int -> unit = "caml_ml_seek_in_pair"
```
has arity 1, and the caml\_ml\_seek\_in\_pair C function receives one argument (which is a pair of OCaml values).
Type abbreviations are not expanded when determining the arity of a primitive. For instance,
```
type int_endo = int -> int
external f : int_endo -> int_endo = "f"
external g : (int -> int) -> (int -> int) = "f"
```
f has arity 1, but g has arity 2. This allows a primitive to return a functional value (as in the f example above): just remember to name the functional return type in a type abbreviation.
The language accepts external declarations with one or two flag strings in addition to the C function’s name. These flags are reserved for the implementation of the standard library.
###
[](#ss:c-prim-impl)22.1.2 Implementing primitives
User primitives with arity n ≤ 5 are implemented by C functions that take n arguments of type value, and return a result of type value. The type value is the type of the representations for OCaml values. It encodes objects of several base types (integers, floating-point numbers, strings, …) as well as OCaml data structures. The type value and the associated conversion functions and macros are described in detail below. For instance, here is the declaration for the C function implementing the In\_channel.input primitive, which takes 4 arguments:
```
CAMLprim value input(value channel, value buffer, value offset, value length)
{
...
}
```
When the primitive function is applied in an OCaml program, the C function is called with the values of the expressions to which the primitive is applied as arguments. The value returned by the function is passed back to the OCaml program as the result of the function application.
User primitives with arity greater than 5 should be implemented by two C functions. The first function, to be used in conjunction with the bytecode compiler ocamlc, receives two arguments: a pointer to an array of OCaml values (the values for the arguments), and an integer which is the number of arguments provided. The other function, to be used in conjunction with the native-code compiler ocamlopt, takes its arguments directly. For instance, here are the two C functions for the 7-argument primitive Nat.add\_nat:
```
CAMLprim value add_nat_native(value nat1, value ofs1, value len1,
value nat2, value ofs2, value len2,
value carry_in)
{
...
}
CAMLprim value add_nat_bytecode(value * argv, int argn)
{
return add_nat_native(argv[0], argv[1], argv[2], argv[3],
argv[4], argv[5], argv[6]);
}
```
The names of the two C functions must be given in the primitive declaration, as follows:
```
external name : type =
bytecode-C-function-name native-code-C-function-name
```
For instance, in the case of add\_nat, the declaration is:
```
external add_nat: nat -> int -> int -> nat -> int -> int -> int -> int
= "add_nat_bytecode" "add_nat_native"
```
Implementing a user primitive is actually two separate tasks: on the one hand, decoding the arguments to extract C values from the given OCaml values, and encoding the return value as an OCaml value; on the other hand, actually computing the result from the arguments. Except for very simple primitives, it is often preferable to have two distinct C functions to implement these two tasks. The first function actually implements the primitive, taking native C values as arguments and returning a native C value. The second function, often called the “stub code”, is a simple wrapper around the first function that converts its arguments from OCaml values to C values, calls the first function, and converts the returned C value to an OCaml value. For instance, here is the stub code for the Int64.float\_of\_bits primitive:
```
CAMLprim value caml_int64_float_of_bits(value vi)
{
return caml_copy_double(caml_int64_float_of_bits_unboxed(Int64_val(vi)));
}
```
(Here, caml\_copy\_double and Int64\_val are conversion functions and macros for the type value, that will be described later. The CAMLprim macro expands to the required compiler directives to ensure that the function is exported and accessible from OCaml.) The hard work is performed by the function caml\_int64\_float\_of\_bits\_unboxed, which is declared as:
```
double caml_int64_float_of_bits_unboxed(int64_t i)
{
...
}
```
To write C code that operates on OCaml values, the following include files are provided:
| | |
| --- | --- |
| Include file | Provides |
| caml/mlvalues.h | definition of the value type, and conversion macros |
| caml/alloc.h | allocation functions (to create structured OCaml objects) |
| caml/memory.h | miscellaneous memory-related functions and macros (for GC interface, in-place modification of structures, etc). |
| caml/fail.h | functions for raising exceptions (see section [22.4.5](#ss%3Ac-exceptions)) |
| caml/callback.h | callback from C to OCaml (see section [22.7](#s%3Ac-callback)). |
| caml/custom.h | operations on custom blocks (see section [22.9](#s%3Ac-custom)). |
| caml/intext.h | operations for writing user-defined serialization and deserialization functions for custom blocks (see section [22.9](#s%3Ac-custom)). |
| caml/threads.h | operations for interfacing in the presence of multiple threads (see section [22.12](#s%3AC-multithreading)). |
These files reside in the caml/ subdirectory of the OCaml standard library directory, which is returned by the command ocamlc -where (usually /usr/local/lib/ocaml or /usr/lib/ocaml).
###
[](#ss:staticlink-c-code)22.1.3 Statically linking C code with OCaml code
The OCaml runtime system comprises three main parts: the bytecode interpreter, the memory manager, and a set of C functions that implement the primitive operations. Some bytecode instructions are provided to call these C functions, designated by their offset in a table of functions (the table of primitives).
In the default mode, the OCaml linker produces bytecode for the standard runtime system, with a standard set of primitives. References to primitives that are not in this standard set result in the “unavailable C primitive” error. (Unless dynamic loading of C libraries is supported – see section [22.1.4](#ss%3Adynlink-c-code) below.)
In the “custom runtime” mode, the OCaml linker scans the object files and determines the set of required primitives. Then, it builds a suitable runtime system, by calling the native code linker with:
* the table of the required primitives;
* a library that provides the bytecode interpreter, the memory manager, and the standard primitives;
* libraries and object code files (.o files) mentioned on the command line for the OCaml linker, that provide implementations for the user’s primitives.
This builds a runtime system with the required primitives. The OCaml linker generates bytecode for this custom runtime system. The bytecode is appended to the end of the custom runtime system, so that it will be automatically executed when the output file (custom runtime + bytecode) is launched.
To link in “custom runtime” mode, execute the ocamlc command with:
* the -custom option;
* the names of the desired OCaml object files (.cmo and .cma files) ;
* the names of the C object files and libraries (.o and .a files) that implement the required primitives. Under Unix and Windows, a library named libname.a (respectively, .lib) residing in one of the standard library directories can also be specified as -cclib -lname.
If you are using the native-code compiler ocamlopt, the -custom flag is not needed, as the final linking phase of ocamlopt always builds a standalone executable. To build a mixed OCaml/C executable, execute the ocamlopt command with:
* the names of the desired OCaml native object files (.cmx and .cmxa files);
* the names of the C object files and libraries (.o, .a, .so or .dll files) that implement the required primitives.
Starting with Objective Caml 3.00, it is possible to record the -custom option as well as the names of C libraries in an OCaml library file .cma or .cmxa. For instance, consider an OCaml library mylib.cma, built from the OCaml object files a.cmo and b.cmo, which reference C code in libmylib.a. If the library is built as follows:
```
ocamlc -a -o mylib.cma -custom a.cmo b.cmo -cclib -lmylib
```
users of the library can simply link with mylib.cma:
```
ocamlc -o myprog mylib.cma ...
```
and the system will automatically add the -custom and -cclib -lmylib options, achieving the same effect as
```
ocamlc -o myprog -custom a.cmo b.cmo ... -cclib -lmylib
```
The alternative is of course to build the library without extra options:
```
ocamlc -a -o mylib.cma a.cmo b.cmo
```
and then ask users to provide the -custom and -cclib -lmylib options themselves at link-time:
```
ocamlc -o myprog -custom mylib.cma ... -cclib -lmylib
```
The former alternative is more convenient for the final users of the library, however.
###
[](#ss:dynlink-c-code)22.1.4 Dynamically linking C code with OCaml code
Starting with Objective Caml 3.03, an alternative to static linking of C code using the -custom code is provided. In this mode, the OCaml linker generates a pure bytecode executable (no embedded custom runtime system) that simply records the names of dynamically-loaded libraries containing the C code. The standard OCaml runtime system ocamlrun then loads dynamically these libraries, and resolves references to the required primitives, before executing the bytecode.
This facility is currently available on all platforms supported by OCaml except Cygwin 64 bits.
To dynamically link C code with OCaml code, the C code must first be compiled into a shared library (under Unix) or DLL (under Windows). This involves 1- compiling the C files with appropriate C compiler flags for producing position-independent code (when required by the operating system), and 2- building a shared library from the resulting object files. The resulting shared library or DLL file must be installed in a place where ocamlrun can find it later at program start-up time (see section [15.3](runtime#s%3Aocamlrun-dllpath)). Finally (step 3), execute the ocamlc command with
* the names of the desired OCaml object files (.cmo and .cma files) ;
* the names of the C shared libraries (.so or .dll files) that implement the required primitives. Under Unix and Windows, a library named dllname.so (respectively, .dll) residing in one of the standard library directories can also be specified as -dllib -lname.
Do *not* set the -custom flag, otherwise you’re back to static linking as described in section [22.1.3](#ss%3Astaticlink-c-code). The ocamlmklib tool (see section [22.14](#s%3Aocamlmklib)) automates steps 2 and 3.
As in the case of static linking, it is possible (and recommended) to record the names of C libraries in an OCaml .cma library archive. Consider again an OCaml library mylib.cma, built from the OCaml object files a.cmo and b.cmo, which reference C code in dllmylib.so. If the library is built as follows:
```
ocamlc -a -o mylib.cma a.cmo b.cmo -dllib -lmylib
```
users of the library can simply link with mylib.cma:
```
ocamlc -o myprog mylib.cma ...
```
and the system will automatically add the -dllib -lmylib option, achieving the same effect as
```
ocamlc -o myprog a.cmo b.cmo ... -dllib -lmylib
```
Using this mechanism, users of the library mylib.cma do not need to know that it references C code, nor whether this C code must be statically linked (using -custom) or dynamically linked.
###
[](#ss:c-static-vs-dynamic)22.1.5 Choosing between static linking and dynamic linking
After having described two different ways of linking C code with OCaml code, we now review the pros and cons of each, to help developers of mixed OCaml/C libraries decide.
The main advantage of dynamic linking is that it preserves the platform-independence of bytecode executables. That is, the bytecode executable contains no machine code, and can therefore be compiled on platform A and executed on other platforms B, C, …, as long as the required shared libraries are available on all these platforms. In contrast, executables generated by ocamlc -custom run only on the platform on which they were created, because they embark a custom-tailored runtime system specific to that platform. In addition, dynamic linking results in smaller executables.
Another advantage of dynamic linking is that the final users of the library do not need to have a C compiler, C linker, and C runtime libraries installed on their machines. This is no big deal under Unix and Cygwin, but many Windows users are reluctant to install Microsoft Visual C just to be able to do ocamlc -custom.
There are two drawbacks to dynamic linking. The first is that the resulting executable is not stand-alone: it requires the shared libraries, as well as ocamlrun, to be installed on the machine executing the code. If you wish to distribute a stand-alone executable, it is better to link it statically, using ocamlc -custom -ccopt -static or ocamlopt -ccopt -static. Dynamic linking also raises the “DLL hell” problem: some care must be taken to ensure that the right versions of the shared libraries are found at start-up time.
The second drawback of dynamic linking is that it complicates the construction of the library. The C compiler and linker flags to compile to position-independent code and build a shared library vary wildly between different Unix systems. Also, dynamic linking is not supported on all Unix systems, requiring a fall-back case to static linking in the Makefile for the library. The ocamlmklib command (see section [22.14](#s%3Aocamlmklib)) tries to hide some of these system dependencies.
In conclusion: dynamic linking is highly recommended under the native Windows port, because there are no portability problems and it is much more convenient for the end users. Under Unix, dynamic linking should be considered for mature, frequently used libraries because it enhances platform-independence of bytecode executables. For new or rarely-used libraries, static linking is much simpler to set up in a portable way.
###
[](#ss:custom-runtime)22.1.6 Building standalone custom runtime systems
It is sometimes inconvenient to build a custom runtime system each time OCaml code is linked with C libraries, like ocamlc -custom does. For one thing, the building of the runtime system is slow on some systems (that have bad linkers or slow remote file systems); for another thing, the platform-independence of bytecode files is lost, forcing to perform one ocamlc -custom link per platform of interest.
An alternative to ocamlc -custom is to build separately a custom runtime system integrating the desired C libraries, then generate “pure” bytecode executables (not containing their own runtime system) that can run on this custom runtime. This is achieved by the -make-runtime and -use-runtime flags to ocamlc. For example, to build a custom runtime system integrating the C parts of the “Unix” and “Threads” libraries, do:
```
ocamlc -make-runtime -o /home/me/ocamlunixrun unix.cma threads.cma
```
To generate a bytecode executable that runs on this runtime system, do:
```
ocamlc -use-runtime /home/me/ocamlunixrun -o myprog \
unix.cma threads.cma your .cmo and .cma files
```
The bytecode executable myprog can then be launched as usual: myprog args or /home/me/ocamlunixrun myprog args.
Notice that the bytecode libraries unix.cma and threads.cma must be given twice: when building the runtime system (so that ocamlc knows which C primitives are required) and also when building the bytecode executable (so that the bytecode from unix.cma and threads.cma is actually linked in).
[](#s:c-value)22.2 The value type
-----------------------------------
All OCaml objects are represented by the C type value, defined in the include file caml/mlvalues.h, along with macros to manipulate values of that type. An object of type value is either:
* an unboxed integer;
* or a pointer to a block inside the heap, allocated through one of the `caml_alloc_*` functions described in section [22.4.4](#ss%3Ac-block-allocation).
###
[](#ss:c-int)22.2.1 Integer values
Integer values encode 63-bit signed integers (31-bit on 32-bit architectures). They are unboxed (unallocated).
###
[](#ss:c-blocks)22.2.2 Blocks
Blocks in the heap are garbage-collected, and therefore have strict structure constraints. Each block includes a header containing the size of the block (in words), and the tag of the block. The tag governs how the contents of the blocks are structured. A tag lower than No\_scan\_tag indicates a structured block, containing well-formed values, which is recursively traversed by the garbage collector. A tag greater than or equal to No\_scan\_tag indicates a raw block, whose contents are not scanned by the garbage collector. For the benefit of ad-hoc polymorphic primitives such as equality and structured input-output, structured and raw blocks are further classified according to their tags as follows:
| | |
| --- | --- |
| Tag | Contents of the block |
| 0 to No\_scan\_tag−1 | A structured block (an array of OCaml objects). Each field is a value. |
| Closure\_tag | A closure representing a functional value. The first word is a pointer to a piece of code, the remaining words are value containing the environment. |
| String\_tag | A character string or a byte sequence. |
| Double\_tag | A double-precision floating-point number. |
| Double\_array\_tag | An array or record of double-precision floating-point numbers. |
| Abstract\_tag | A block representing an abstract datatype. |
| Custom\_tag | A block representing an abstract datatype with user-defined finalization, comparison, hashing, serialization and deserialization functions attached. |
###
[](#ss:c-outside-head)22.2.3 Pointers outside the heap
In earlier versions of OCaml, it was possible to use word-aligned pointers to addresses outside the heap as OCaml values, just by casting the pointer to type value. This usage is no longer supported since OCaml 5.0.
A correct way to manipulate pointers to out-of-heap blocks from OCaml is to store those pointers in OCaml blocks with tag Abstract\_tag or Custom\_tag, then use the blocks as the OCaml values.
Here is an example of encapsulation of out-of-heap pointers of C type ty \* inside Abstract\_tag blocks. Section [22.6](#s%3Ac-intf-example) gives a more complete example using Custom\_tag blocks.
```
/* Create an OCaml value encapsulating the pointer p */
static value val_of_typtr(ty * p)
{
value v = caml_alloc(1, Abstract_tag);
*((ty **) Data_abstract_val(v)) = p;
return v;
}
/* Extract the pointer encapsulated in the given OCaml value */
static ty * typtr_of_val(value v)
{
return *((ty **) Data_abstract_val(v));
}
```
Alternatively, out-of-heap pointers can be treated as “native” integers, that is, boxed 32-bit integers on a 32-bit platform and boxed 64-bit integers on a 64-bit platform.
```
/* Create an OCaml value encapsulating the pointer p */
static value val_of_typtr(ty * p)
{
return caml_copy_nativeint((intnat) p);
}
/* Extract the pointer encapsulated in the given OCaml value */
static ty * typtr_of_val(value v)
{
return (ty *) Nativeint_val(v);
}
```
For pointers that are at least 2-aligned (the low bit is guaranteed to be zero), we have yet another valid representation as an OCaml tagged integer.
```
/* Create an OCaml value encapsulating the pointer p */
static value val_of_typtr(ty * p)
{
assert (((uintptr_t) p & 1) == 0); /* check correct alignment */
return (value) p | 1;
}
/* Extract the pointer encapsulated in the given OCaml value */
static ty * typtr_of_val(value v)
{
return (ty *) (v & ~1);
}
```
[](#s:c-ocaml-datatype-repr)22.3 Representation of OCaml data types
---------------------------------------------------------------------
This section describes how OCaml data types are encoded in the value type.
###
[](#ss:c-atomic)22.3.1 Atomic types
| | |
| --- | --- |
| OCaml type | Encoding |
| int | Unboxed integer values. |
| char | Unboxed integer values (ASCII code). |
| float | Blocks with tag Double\_tag. |
| bytes | Blocks with tag String\_tag. |
| string | Blocks with tag String\_tag. |
| int32 | Blocks with tag Custom\_tag. |
| int64 | Blocks with tag Custom\_tag. |
| nativeint | Blocks with tag Custom\_tag. |
###
[](#ss:c-tuples-and-records)22.3.2 Tuples and records
Tuples are represented by pointers to blocks, with tag 0.
Records are also represented by zero-tagged blocks. The ordering of labels in the record type declaration determines the layout of the record fields: the value associated to the label declared first is stored in field 0 of the block, the value associated to the second label goes in field 1, and so on.
As an optimization, records whose fields all have static type float are represented as arrays of floating-point numbers, with tag Double\_array\_tag. (See the section below on arrays.)
As another optimization, unboxable record types are represented specially; unboxable record types are the immutable record types that have only one field. An unboxable type will be represented in one of two ways: boxed or unboxed. Boxed record types are represented as described above (by a block with tag 0 or Double\_array\_tag). An unboxed record type is represented directly by the value of its field (i.e. there is no block to represent the record itself).
The representation is chosen according to the following, in decreasing order of priority:
* An attribute ([@@boxed] or [@@unboxed]) on the type declaration.
* A compiler option (-unboxed-types or -no-unboxed-types).
* The default representation. In the present version of OCaml, the default is the boxed representation.
###
[](#ss:c-arrays)22.3.3 Arrays
Arrays of integers and pointers are represented like tuples, that is, as pointers to blocks tagged 0. They are accessed with the Field macro for reading and the caml\_modify function for writing.
Arrays of floating-point numbers (type float array) have a special, unboxed, more efficient representation. These arrays are represented by pointers to blocks with tag Double\_array\_tag. They should be accessed with the Double\_field and Store\_double\_field macros.
###
[](#ss:c-concrete-datatypes)22.3.4 Concrete data types
Constructed terms are represented either by unboxed integers (for constant constructors) or by blocks whose tag encode the constructor (for non-constant constructors). The constant constructors and the non-constant constructors for a given concrete type are numbered separately, starting from 0, in the order in which they appear in the concrete type declaration. A constant constructor is represented by the unboxed integer equal to its constructor number. A non-constant constructor declared with n arguments is represented by a block of size n, tagged with the constructor number; the n fields contain its arguments. Example:
| | |
| --- | --- |
| Constructed term | Representation |
| () | Val\_int(0) |
| false | Val\_int(0) |
| true | Val\_int(1) |
| [] | Val\_int(0) |
| h::t | Block with size = 2 and tag = 0; first field contains h, second field t. |
As a convenience, caml/mlvalues.h defines the macros Val\_unit, Val\_false and Val\_true to refer to (), false and true.
The following example illustrates the assignment of integers and block tags to constructors:
```
type t =
| A (* First constant constructor -> integer "Val_int(0)" *)
| B of string (* First non-constant constructor -> block with tag 0 *)
| C (* Second constant constructor -> integer "Val_int(1)" *)
| D of bool (* Second non-constant constructor -> block with tag 1 *)
| E of t * t (* Third non-constant constructor -> block with tag 2 *)
```
As an optimization, unboxable concrete data types are represented specially; a concrete data type is unboxable if it has exactly one constructor and this constructor has exactly one argument. Unboxable concrete data types are represented in the same ways as unboxable record types: see the description in section [22.3.2](#ss%3Ac-tuples-and-records).
###
[](#ss:c-objects)22.3.5 Objects
Objects are represented as blocks with tag Object\_tag. The first field of the block refers to the object’s class and associated method suite, in a format that cannot easily be exploited from C. The second field contains a unique object ID, used for comparisons. The remaining fields of the object contain the values of the instance variables of the object. It is unsafe to access directly instance variables, as the type system provides no guarantee about the instance variables contained by an object.
One may extract a public method from an object using the C function caml\_get\_public\_method (declared in <caml/mlvalues.h>.) Since public method tags are hashed in the same way as variant tags, and methods are functions taking self as first argument, if you want to do the method call foo#bar from the C side, you should call:
```
callback(caml_get_public_method(foo, hash_variant("bar")), foo);
```
###
[](#ss:c-polyvar)22.3.6 Polymorphic variants
Like constructed terms, polymorphic variant values are represented either as integers (for polymorphic variants without argument), or as blocks (for polymorphic variants with an argument). Unlike constructed terms, variant constructors are not numbered starting from 0, but identified by a hash value (an OCaml integer), as computed by the C function hash\_variant (declared in <caml/mlvalues.h>): the hash value for a variant constructor named, say, VConstr is hash\_variant("VConstr").
The variant value `VConstr is represented by hash\_variant("VConstr"). The variant value `VConstr(v) is represented by a block of size 2 and tag 0, with field number 0 containing hash\_variant("VConstr") and field number 1 containing v.
Unlike constructed values, polymorphic variant values taking several arguments are not flattened. That is, `VConstr(v, w) is represented by a block of size 2, whose field number 1 contains the representation of the pair (v, w), rather than a block of size 3 containing v and w in fields 1 and 2.
[](#s:c-ops-on-values)22.4 Operations on values
-------------------------------------------------
###
[](#ss:c-kind-tests)22.4.1 Kind tests
* Is\_long(v) is true if value v is an immediate integer, false otherwise
* Is\_block(v) is true if value v is a pointer to a block, and false if it is an immediate integer.
* Is\_none(v) is true if value v is None.
* Is\_some(v) is true if value v (assumed to be of option type) corresponds to the Some constructor.
###
[](#ss:c-int-ops)22.4.2 Operations on integers
* Val\_long(l) returns the value encoding the long int l.
* Long\_val(v) returns the long int encoded in value v.
* Val\_int(i) returns the value encoding the int i.
* Int\_val(v) returns the int encoded in value v.
* Val\_bool(x) returns the OCaml boolean representing the truth value of the C integer x.
* Bool\_val(v) returns 0 if v is the OCaml boolean false, 1 if v is true.
* Val\_true, Val\_false represent the OCaml booleans true and false.
* Val\_none represents the OCaml value None.
###
[](#ss:c-block-access)22.4.3 Accessing blocks
* Wosize\_val(v) returns the size of the block v, in words, excluding the header.
* Tag\_val(v) returns the tag of the block v.
* Field(v, n) returns the value contained in the nth field of the structured block v. Fields are numbered from 0 to Wosize\_val(v)−1.
* Store\_field(b, n, v) stores the value v in the field number n of value b, which must be a structured block.
* Code\_val(v) returns the code part of the closure v.
* caml\_string\_length(v) returns the length (number of bytes) of the string or byte sequence v.
* Byte(v, n) returns the nth byte of the string or byte sequence v, with type char. Bytes are numbered from 0 to string\_length(v)−1.
* Byte\_u(v, n) returns the nth byte of the string or byte sequence v, with type unsigned char. Bytes are numbered from 0 to string\_length(v)−1.
* String\_val(v) returns a pointer to the first byte of the string v, with type const char \*. This pointer is a valid C string: there is a null byte after the last byte in the string. However, OCaml strings can contain embedded null bytes, which will confuse the usual C functions over strings.
* Bytes\_val(v) returns a pointer to the first byte of the byte sequence v, with type unsigned char \*.
* Double\_val(v) returns the floating-point number contained in value v, with type double.
* Double\_field(v, n) returns the nth element of the array of floating-point numbers v (a block tagged Double\_array\_tag).
* Store\_double\_field(v, n, d) stores the double precision floating-point number d in the nth element of the array of floating-point numbers v.
* Data\_custom\_val(v) returns a pointer to the data part of the custom block v. This pointer has type void \* and must be cast to the type of the data contained in the custom block.
* Int32\_val(v) returns the 32-bit integer contained in the int32 v.
* Int64\_val(v) returns the 64-bit integer contained in the int64 v.
* Nativeint\_val(v) returns the long integer contained in the nativeint v.
* caml\_field\_unboxed(v) returns the value of the field of a value v of any unboxed type (record or concrete data type).
* caml\_field\_boxed(v) returns the value of the field of a value v of any boxed type (record or concrete data type).
* caml\_field\_unboxable(v) calls either caml\_field\_unboxed or caml\_field\_boxed according to the default representation of unboxable types in the current version of OCaml.
* Some\_val(v) returns the argument \var{x} of a value v of the form Some(x).
The expressions Field(v, n), Byte(v, n) and Byte\_u(v, n) are valid l-values. Hence, they can be assigned to, resulting in an in-place modification of value v. Assigning directly to Field(v, n) must be done with care to avoid confusing the garbage collector (see below).
###
[](#ss:c-block-allocation)22.4.4 Allocating blocks
####
[](#sss:c-simple-allocation)Simple interface
* Atom(t) returns an “atom” (zero-sized block) with tag t. Zero-sized blocks are preallocated outside of the heap. It is incorrect to try and allocate a zero-sized block using the functions below. For instance, Atom(0) represents the empty array.
* caml\_alloc(n, t) returns a fresh block of size n with tag t. If t is less than No\_scan\_tag, then the fields of the block are initialized with a valid value in order to satisfy the GC constraints.
* caml\_alloc\_tuple(n) returns a fresh block of size n words, with tag 0.
* caml\_alloc\_string(n) returns a byte sequence (or string) value of length n bytes. The sequence initially contains uninitialized bytes.
* caml\_alloc\_initialized\_string(n, p) returns a byte sequence (or string) value of length n bytes. The value is initialized from the n bytes starting at address p.
* caml\_copy\_string(s) returns a string or byte sequence value containing a copy of the null-terminated C string s (a char \*).
* caml\_copy\_double(d) returns a floating-point value initialized with the double d.
* caml\_copy\_int32(i), caml\_copy\_int64(i) and caml\_copy\_nativeint(i) return a value of OCaml type int32, int64 and nativeint, respectively, initialized with the integer i.
* caml\_alloc\_array(f, a) allocates an array of values, calling function f over each element of the input array a to transform it into a value. The array a is an array of pointers terminated by the null pointer. The function f receives each pointer as argument, and returns a value. The zero-tagged block returned by alloc\_array(f, a) is filled with the values returned by the successive calls to f. (This function must not be used to build an array of floating-point numbers.)
* caml\_copy\_string\_array(p) allocates an array of strings or byte sequences, copied from the pointer to a string array p (a char \*\*). p must be NULL-terminated.
* caml\_alloc\_float\_array(n) allocates an array of floating point numbers of size n. The array initially contains uninitialized values.
* caml\_alloc\_unboxed(v) returns the value (of any unboxed type) whose field is the value v.
* caml\_alloc\_boxed(v) allocates and returns a value (of any boxed type) whose field is the value v.
* caml\_alloc\_unboxable(v) calls either caml\_alloc\_unboxed or caml\_alloc\_boxed according to the default representation of unboxable types in the current version of OCaml.
* caml\_alloc\_some(v) allocates a block representing Some(v).
####
[](#sss:c-low-level-alloc)Low-level interface
The following functions are slightly more efficient than caml\_alloc, but also much more difficult to use.
From the standpoint of the allocation functions, blocks are divided according to their size as zero-sized blocks, small blocks (with size less than or equal to `Max_young_wosize`), and large blocks (with size greater than `Max_young_wosize`). The constant `Max_young_wosize` is declared in the include file mlvalues.h. It is guaranteed to be at least 64 (words), so that any block with constant size less than or equal to 64 can be assumed to be small. For blocks whose size is computed at run-time, the size must be compared against `Max_young_wosize` to determine the correct allocation procedure.
* caml\_alloc\_small(n, t) returns a fresh small block of size n ≤ Max\_young\_wosize words, with tag t. If this block is a structured block (i.e. if t < No\_scan\_tag), then the fields of the block (initially containing garbage) must be initialized with legal values (using direct assignment to the fields of the block) before the next allocation.
* caml\_alloc\_shr(n, t) returns a fresh block of size n, with tag t. The size of the block can be greater than `Max_young_wosize`. (It can also be smaller, but in this case it is more efficient to call caml\_alloc\_small instead of caml\_alloc\_shr.) If this block is a structured block (i.e. if t < No\_scan\_tag), then the fields of the block (initially containing garbage) must be initialized with legal values (using the caml\_initialize function described below) before the next allocation.
###
[](#ss:c-exceptions)22.4.5 Raising exceptions
Two functions are provided to raise two standard exceptions:
* caml\_failwith(s), where s is a null-terminated C string (with type `char *`), raises exception Failure with argument s.
* caml\_invalid\_argument(s), where s is a null-terminated C string (with type `char *`), raises exception Invalid\_argument with argument s.
Raising arbitrary exceptions from C is more delicate: the exception identifier is dynamically allocated by the OCaml program, and therefore must be communicated to the C function using the registration facility described below in section [22.7.3](#ss%3Ac-register-exn). Once the exception identifier is recovered in C, the following functions actually raise the exception:
* caml\_raise\_constant(id) raises the exception id with no argument;
* caml\_raise\_with\_arg(id, v) raises the exception id with the OCaml value v as argument;
* caml\_raise\_with\_args(id, n, v) raises the exception id with the OCaml values v[0], …, v[n-1] as arguments;
* caml\_raise\_with\_string(id, s), where s is a null-terminated C string, raises the exception id with a copy of the C string s as argument.
[](#s:c-gc-harmony)22.5 Living in harmony with the garbage collector
----------------------------------------------------------------------
Unused blocks in the heap are automatically reclaimed by the garbage collector. This requires some cooperation from C code that manipulates heap-allocated blocks.
###
[](#ss:c-simple-gc-harmony)22.5.1 Simple interface
All the macros described in this section are declared in the memory.h header file.
Rule 1 *A function that has parameters or local variables of type value must begin with a call to one of the CAMLparam macros and return with CAMLreturn, CAMLreturn0, or CAMLreturnT. In particular, CAMLlocal and CAMLxparam can only be called* after *CAMLparam.*
There are six CAMLparam macros: CAMLparam0 to CAMLparam5, which take zero to five arguments respectively. If your function has no more than 5 parameters of type value, use the corresponding macros with these parameters as arguments. If your function has more than 5 parameters of type value, use CAMLparam5 with five of these parameters, and use one or more calls to the CAMLxparam macros for the remaining parameters (CAMLxparam1 to CAMLxparam5).
The macros CAMLreturn, CAMLreturn0, and CAMLreturnT are used to replace the C keyword return. Every occurrence of return x must be replaced by CAMLreturn (x) if x has type value, or CAMLreturnT (t, x) (where t is the type of x); every occurrence of return without argument must be replaced by CAMLreturn0. If your C function is a procedure (i.e. if it returns void), you must insert CAMLreturn0 at the end (to replace C’s implicit return).
#####
[](#sec499)Note:
some C compilers give bogus warnings about unused variables caml\_\_dummy\_xxx at each use of CAMLparam and CAMLlocal. You should ignore them.
Example:
```
void foo (value v1, value v2, value v3)
{
CAMLparam3 (v1, v2, v3);
...
CAMLreturn0;
}
```
#####
[](#sec500)Note:
if your function is a primitive with more than 5 arguments for use with the byte-code runtime, its arguments are not values and must not be declared (they have types value \* and int).
Rule 2 *Local variables of type value must be declared with one of the CAMLlocal macros. Arrays of values are declared with CAMLlocalN. These macros must be used at the beginning of the function, not in a nested block.*
The macros CAMLlocal1 to CAMLlocal5 declare and initialize one to five local variables of type value. The variable names are given as arguments to the macros. CAMLlocalN(x, n) declares and initializes a local variable of type value [n]. You can use several calls to these macros if you have more than 5 local variables.
Example:
```
CAMLprim value bar (value v1, value v2, value v3)
{
CAMLparam3 (v1, v2, v3);
CAMLlocal1 (result);
result = caml_alloc (3, 0);
...
CAMLreturn (result);
}
```
Rule 3 *Assignments to the fields of structured blocks must be done with the Store\_field macro (for normal blocks) or Store\_double\_field macro (for arrays and records of floating-point numbers). Other assignments must not use Store\_field nor Store\_double\_field.*
Store\_field (b, n, v) stores the value v in the field number n of value b, which must be a block (i.e. Is\_block(b) must be true).
Example:
```
CAMLprim value bar (value v1, value v2, value v3)
{
CAMLparam3 (v1, v2, v3);
CAMLlocal1 (result);
result = caml_alloc (3, 0);
Store_field (result, 0, v1);
Store_field (result, 1, v2);
Store_field (result, 2, v3);
CAMLreturn (result);
}
```
#####
[](#sec501)Warning:
The first argument of Store\_field and Store\_double\_field must be a variable declared by CAMLparam\* or a parameter declared by CAMLlocal\* to ensure that a garbage collection triggered by the evaluation of the other arguments will not invalidate the first argument after it is computed.
#####
[](#sec502)Use with CAMLlocalN:
Arrays of values declared using CAMLlocalN must not be written to using Store\_field. Use the normal C array syntax instead.
Rule 4 *Global variables containing values must be registered with the garbage collector using the caml\_register\_global\_root function, save that global variables and locations that will only ever contain OCaml integers (and never pointers) do not have to be registered.**The same is true for any memory location outside the OCaml heap that contains a value and is not guaranteed to be reachable—for as long as it contains such value—from either another registered global variable or location, local variable declared with CAMLlocal or function parameter declared with CAMLparam.*
Registration of a global variable v is achieved by calling caml\_register\_global\_root(&v) just before or just after a valid value is stored in v for the first time; likewise, registration of an arbitrary location p is achieved by calling caml\_register\_global\_root(p).
You must not call any of the OCaml runtime functions or macros between registering and storing the value. Neither must you store anything in the variable v (likewise, the location p) that is not a valid value.
The registration causes the contents of the variable or memory location to be updated by the garbage collector whenever the value in such variable or location is moved within the OCaml heap. In the presence of threads care must be taken to ensure appropriate synchronisation with the OCaml runtime to avoid a race condition against the garbage collector when reading or writing the value. (See section [22.12.2](#ss%3Aparallel-execution-long-running-c-code).)
A registered global variable v can be un-registered by calling caml\_remove\_global\_root(&v).
If the contents of the global variable v are seldom modified after registration, better performance can be achieved by calling caml\_register\_generational\_global\_root(&v) to register v (after its initialization with a valid value, but before any allocation or call to the GC functions), and caml\_remove\_generational\_global\_root(&v) to un-register it. In this case, you must not modify the value of v directly, but you must use caml\_modify\_generational\_global\_root(&v,x) to set it to x. The garbage collector takes advantage of the guarantee that v is not modified between calls to caml\_modify\_generational\_global\_root to scan it less often. This improves performance if the modifications of v happen less often than minor collections.
#####
[](#sec503)Note:
The CAML macros use identifiers (local variables, type identifiers, structure tags) that start with caml\_\_. Do not use any identifier starting with caml\_\_ in your programs.
###
[](#ss:c-low-level-gc-harmony)22.5.2 Low-level interface
We now give the GC rules corresponding to the low-level allocation functions caml\_alloc\_small and caml\_alloc\_shr. You can ignore those rules if you stick to the simplified allocation function caml\_alloc.
Rule 5 *After a structured block (a block with tag less than No\_scan\_tag) is allocated with the low-level functions, all fields of this block must be filled with well-formed values before the next allocation operation. If the block has been allocated with caml\_alloc\_small, filling is performed by direct assignment to the fields of the block:*
```
Field(v, n) = vn;
```
*If the block has been allocated with caml\_alloc\_shr, filling is performed through the caml\_initialize function:*
```
caml_initialize(&Field(v, n), vn);
```
The next allocation can trigger a garbage collection. The garbage collector assumes that all structured blocks contain well-formed values. Newly created blocks contain random data, which generally do not represent well-formed values.
If you really need to allocate before the fields can receive their final value, first initialize with a constant value (e.g. Val\_unit), then allocate, then modify the fields with the correct value (see rule 6).
Rule 6 *Direct assignment to a field of a block, as in*
```
Field(v, n) = w;
```
*is safe only if v is a block newly allocated by caml\_alloc\_small; that is, if no allocation took place between the allocation of v and the assignment to the field. In all other cases, never assign directly. If the block has just been allocated by caml\_alloc\_shr, use caml\_initialize to assign a value to a field for the first time:*
```
caml_initialize(&Field(v, n), w);
```
*Otherwise, you are updating a field that previously contained a well-formed value; then, call the caml\_modify function:*
```
caml_modify(&Field(v, n), w);
```
To illustrate the rules above, here is a C function that builds and returns a list containing the two integers given as parameters. First, we write it using the simplified allocation functions:
```
value alloc_list_int(int i1, int i2)
{
CAMLparam0 ();
CAMLlocal2 (result, r);
r = caml_alloc(2, 0); /* Allocate a cons cell */
Store_field(r, 0, Val_int(i2)); /* car = the integer i2 */
Store_field(r, 1, Val_int(0)); /* cdr = the empty list [] */
result = caml_alloc(2, 0); /* Allocate the other cons cell */
Store_field(result, 0, Val_int(i1)); /* car = the integer i1 */
Store_field(result, 1, r); /* cdr = the first cons cell */
CAMLreturn (result);
}
```
Here, the registering of result is not strictly needed, because no allocation takes place after it gets its value, but it’s easier and safer to simply register all the local variables that have type value.
Here is the same function written using the low-level allocation functions. We notice that the cons cells are small blocks and can be allocated with caml\_alloc\_small, and filled by direct assignments on their fields.
```
value alloc_list_int(int i1, int i2)
{
CAMLparam0 ();
CAMLlocal2 (result, r);
r = caml_alloc_small(2, 0); /* Allocate a cons cell */
Field(r, 0) = Val_int(i2); /* car = the integer i2 */
Field(r, 1) = Val_int(0); /* cdr = the empty list [] */
result = caml_alloc_small(2, 0); /* Allocate the other cons cell */
Field(result, 0) = Val_int(i1); /* car = the integer i1 */
Field(result, 1) = r; /* cdr = the first cons cell */
CAMLreturn (result);
}
```
In the two examples above, the list is built bottom-up. Here is an alternate way, that proceeds top-down. It is less efficient, but illustrates the use of caml\_modify.
```
value alloc_list_int(int i1, int i2)
{
CAMLparam0 ();
CAMLlocal2 (tail, r);
r = caml_alloc_small(2, 0); /* Allocate a cons cell */
Field(r, 0) = Val_int(i1); /* car = the integer i1 */
Field(r, 1) = Val_int(0); /* A dummy value
tail = caml_alloc_small(2, 0); /* Allocate the other cons cell */
Field(tail, 0) = Val_int(i2); /* car = the integer i2 */
Field(tail, 1) = Val_int(0); /* cdr = the empty list [] */
caml_modify(&Field(r, 1), tail); /* cdr of the result = tail */
CAMLreturn (r);
}
```
It would be incorrect to perform Field(r, 1) = tail directly, because the allocation of tail has taken place since r was allocated.
###
[](#ss:c-process-pending-actions)22.5.3 Pending actions and asynchronous exceptions
Since 4.10, allocation functions are guaranteed not to call any OCaml callbacks from C, including finalisers and signal handlers, and delay their execution instead.
The function `caml_process_pending_actions` from <caml/signals.h> executes any pending signal handlers and finalisers, Memprof callbacks, and requested minor and major garbage collections. In particular, it can raise asynchronous exceptions. It is recommended to call it regularly at safe points inside long-running non-blocking C code.
The variant `caml_process_pending_actions_exn` is provided, that returns the exception instead of raising it directly into OCaml code. Its result must be tested using Is\_exception\_result, and followed by Extract\_exception if appropriate. It is typically used for clean up before re-raising:
```
CAMLlocal1(exn);
...
exn = caml_process_pending_actions_exn();
if(Is_exception_result(exn)) {
exn = Extract_exception(exn);
...cleanup...
caml_raise(exn);
}
```
Correct use of exceptional return, in particular in the presence of garbage collection, is further detailed in Section [22.7.1](#ss%3Ac-callbacks).
[](#s:c-intf-example)22.6 A complete example
----------------------------------------------
This section outlines how the functions from the Unix curses library can be made available to OCaml programs. First of all, here is the interface curses.ml that declares the curses primitives and data types:
```
(* File curses.ml -- declaration of primitives and data types *)
type window (* The type "window" remains abstract *)
external initscr: unit -> window = "caml_curses_initscr"
external endwin: unit -> unit = "caml_curses_endwin"
external refresh: unit -> unit = "caml_curses_refresh"
external wrefresh : window -> unit = "caml_curses_wrefresh"
external newwin: int -> int -> int -> int -> window = "caml_curses_newwin"
external addch: char -> unit = "caml_curses_addch"
external mvwaddch: window -> int -> int -> char -> unit = "caml_curses_mvwaddch"
external addstr: string -> unit = "caml_curses_addstr"
external mvwaddstr: window -> int -> int -> string -> unit
= "caml_curses_mvwaddstr"
(* lots more omitted *)
```
To compile this interface:
```
ocamlc -c curses.ml
```
To implement these functions, we just have to provide the stub code; the core functions are already implemented in the curses library. The stub code file, curses\_stubs.c, looks like this:
```
/* File curses_stubs.c -- stub code for curses */
#include <curses.h>
#include <caml/mlvalues.h>
#include <caml/memory.h>
#include <caml/alloc.h>
#include <caml/custom.h>
/* Encapsulation of opaque window handles (of type WINDOW *)
as OCaml custom blocks. */
static struct custom_operations curses_window_ops = {
"fr.inria.caml.curses_windows",
custom_finalize_default,
custom_compare_default,
custom_hash_default,
custom_serialize_default,
custom_deserialize_default,
custom_compare_ext_default,
custom_fixed_length_default
};
/* Accessing the WINDOW * part of an OCaml custom block */
#define Window_val(v) (*((WINDOW **) Data_custom_val(v)))
/* Allocating an OCaml custom block to hold the given WINDOW * */
static value alloc_window(WINDOW * w)
{
value v = caml_alloc_custom(&curses_window_ops, sizeof(WINDOW *), 0, 1);
Window_val(v) = w;
return v;
}
CAMLprim value caml_curses_initscr(value unit)
{
CAMLparam1 (unit);
CAMLreturn (alloc_window(initscr()));
}
CAMLprim value caml_curses_endwin(value unit)
{
CAMLparam1 (unit);
endwin();
CAMLreturn (Val_unit);
}
CAMLprim value caml_curses_refresh(value unit)
{
CAMLparam1 (unit);
refresh();
CAMLreturn (Val_unit);
}
CAMLprim value caml_curses_wrefresh(value win)
{
CAMLparam1 (win);
wrefresh(Window_val(win));
CAMLreturn (Val_unit);
}
CAMLprim value caml_curses_newwin(value nlines, value ncols, value x0, value y0)
{
CAMLparam4 (nlines, ncols, x0, y0);
CAMLreturn (alloc_window(newwin(Int_val(nlines), Int_val(ncols),
Int_val(x0), Int_val(y0))));
}
CAMLprim value caml_curses_addch(value c)
{
CAMLparam1 (c);
addch(Int_val(c)); /* Characters are encoded like integers */
CAMLreturn (Val_unit);
}
CAMLprim value caml_curses_mvwaddch(value win, value x, value y, value c)
{
CAMLparam4 (win, x, y, c);
mvwaddch(Window_val(win), Int_val(x), Int_val(y), Int_val(c));
CAMLreturn (Val_unit);
}
CAMLprim value caml_curses_addstr(value s)
{
CAMLparam1 (s);
addstr(String_val(s));
CAMLreturn (Val_unit);
}
CAMLprim value caml_curses_mvwaddstr(value win, value x, value y, value s)
{
CAMLparam4 (win, x, y, s);
mvwaddstr(Window_val(win), Int_val(x), Int_val(y), String_val(s));
CAMLreturn (Val_unit);
}
/* This goes on for pages. */
```
The file curses\_stubs.c can be compiled with:
```
cc -c -I`ocamlc -where` curses_stubs.c
```
or, even simpler,
```
ocamlc -c curses_stubs.c
```
(When passed a .c file, the ocamlc command simply calls the C compiler on that file, with the right -I option.)
Now, here is a sample OCaml program prog.ml that uses the curses module:
```
(* File prog.ml -- main program using curses *)
open Curses;;
let main_window = initscr () in
let small_window = newwin 10 5 20 10 in
mvwaddstr main_window 10 2 "Hello";
mvwaddstr small_window 4 3 "world";
refresh();
Unix.sleep 5;
endwin()
```
To compile and link this program, run:
```
ocamlc -custom -o prog unix.cma curses.cmo prog.ml curses_stubs.o -cclib -lcurses
```
(On some machines, you may need to put -cclib -lcurses -cclib -ltermcap or -cclib -ltermcap instead of -cclib -lcurses.)
[](#s:c-callback)22.7 Advanced topic: callbacks from C to OCaml
-----------------------------------------------------------------
So far, we have described how to call C functions from OCaml. In this section, we show how C functions can call OCaml functions, either as callbacks (OCaml calls C which calls OCaml), or with the main program written in C.
###
[](#ss:c-callbacks)22.7.1 Applying OCaml closures from C
C functions can apply OCaml function values (closures) to OCaml values. The following functions are provided to perform the applications:
* caml\_callback(f, a) applies the functional value f to the value a and returns the value returned by f.
* caml\_callback2(f, a, b) applies the functional value f (which is assumed to be a curried OCaml function with two arguments) to a and b.
* caml\_callback3(f, a, b, c) applies the functional value f (a curried OCaml function with three arguments) to a, b and c.
* caml\_callbackN(f, n, args) applies the functional value f to the n arguments contained in the C array of values args.
If the function f does not return, but raises an exception that escapes the scope of the application, then this exception is propagated to the next enclosing OCaml code, skipping over the C code. That is, if an OCaml function f calls a C function g that calls back an OCaml function h that raises a stray exception, then the execution of g is interrupted and the exception is propagated back into f.
If the C code wishes to catch exceptions escaping the OCaml function, it can use the functions caml\_callback\_exn, caml\_callback2\_exn, caml\_callback3\_exn, caml\_callbackN\_exn. These functions take the same arguments as their non-\_exn counterparts, but catch escaping exceptions and return them to the C code. The return value v of the caml\_callback\*\_exn functions must be tested with the macro Is\_exception\_result(v). If the macro returns “false”, no exception occurred, and v is the value returned by the OCaml function. If Is\_exception\_result(v) returns “true”, an exception escaped, and its value (the exception descriptor) can be recovered using Extract\_exception(v).
#####
[](#sec509)Warning:
If the OCaml function returned with an exception, Extract\_exception should be applied to the exception result prior to calling a function that may trigger garbage collection. Otherwise, if v is reachable during garbage collection, the runtime can crash since v does not contain a valid value.
Example:
```
CAMLprim value call_caml_f_ex(value closure, value arg)
{
CAMLparam2(closure, arg);
CAMLlocal2(res, tmp);
res = caml_callback_exn(closure, arg);
if(Is_exception_result(res)) {
res = Extract_exception(res);
tmp = caml_alloc(3, 0); /* Safe to allocate: res contains valid value. */
...
}
CAMLreturn (res);
}
```
###
[](#ss:c-closures)22.7.2 Obtaining or registering OCaml closures for use in C functions
There are two ways to obtain OCaml function values (closures) to be passed to the callback functions described above. One way is to pass the OCaml function as an argument to a primitive function. For example, if the OCaml code contains the declaration
```
external apply : ('a -> 'b) -> 'a -> 'b = "caml_apply"
```
the corresponding C stub can be written as follows:
```
CAMLprim value caml_apply(value vf, value vx)
{
CAMLparam2(vf, vx);
CAMLlocal1(vy);
vy = caml_callback(vf, vx);
CAMLreturn(vy);
}
```
Another possibility is to use the registration mechanism provided by OCaml. This registration mechanism enables OCaml code to register OCaml functions under some global name, and C code to retrieve the corresponding closure by this global name.
On the OCaml side, registration is performed by evaluating Callback.register n v. Here, n is the global name (an arbitrary string) and v the OCaml value. For instance:
```
let f x = print_string "f is applied to "; print_int x; print_newline()
let _ = Callback.register "test function" f
```
On the C side, a pointer to the value registered under name n is obtained by calling caml\_named\_value(n). The returned pointer must then be dereferenced to recover the actual OCaml value. If no value is registered under the name n, the null pointer is returned. For example, here is a C wrapper that calls the OCaml function f above:
```
void call_caml_f(int arg)
{
caml_callback(*caml_named_value("test function"), Val_int(arg));
}
```
The pointer returned by caml\_named\_value is constant and can safely be cached in a C variable to avoid repeated name lookups. The value pointed to cannot be changed from C. However, it might change during garbage collection, so must always be recomputed at the point of use. Here is a more efficient variant of call\_caml\_f above that calls caml\_named\_value only once:
```
void call_caml_f(int arg)
{
static const value * closure_f = NULL;
if (closure_f == NULL) {
/* First time around, look up by name */
closure_f = caml_named_value("test function");
}
caml_callback(*closure_f, Val_int(arg));
}
```
###
[](#ss:c-register-exn)22.7.3 Registering OCaml exceptions for use in C functions
The registration mechanism described above can also be used to communicate exception identifiers from OCaml to C. The OCaml code registers the exception by evaluating Callback.register\_exception n exn, where n is an arbitrary name and exn is an exception value of the exception to register. For example:
```
exception Error of string
let _ = Callback.register_exception "test exception" (Error "any string")
```
The C code can then recover the exception identifier using caml\_named\_value and pass it as first argument to the functions raise\_constant, raise\_with\_arg, and raise\_with\_string (described in section [22.4.5](#ss%3Ac-exceptions)) to actually raise the exception. For example, here is a C function that raises the Error exception with the given argument:
```
void raise_error(char * msg)
{
caml_raise_with_string(*caml_named_value("test exception"), msg);
}
```
###
[](#ss:main-c)22.7.4 Main program in C
In normal operation, a mixed OCaml/C program starts by executing the OCaml initialization code, which then may proceed to call C functions. We say that the main program is the OCaml code. In some applications, it is desirable that the C code plays the role of the main program, calling OCaml functions when needed. This can be achieved as follows:
* The C part of the program must provide a main function, which will override the default main function provided by the OCaml runtime system. Execution will start in the user-defined main function just like for a regular C program.
* At some point, the C code must call caml\_main(argv) to initialize the OCaml code. The argv argument is a C array of strings (type char \*\*), terminated with a NULL pointer, which represents the command-line arguments, as passed as second argument to main. The OCaml array Sys.argv will be initialized from this parameter. For the bytecode compiler, argv[0] and argv[1] are also consulted to find the file containing the bytecode.
* The call to caml\_main initializes the OCaml runtime system, loads the bytecode (in the case of the bytecode compiler), and executes the initialization code of the OCaml program. Typically, this initialization code registers callback functions using Callback.register. Once the OCaml initialization code is complete, control returns to the C code that called caml\_main.
* The C code can then invoke OCaml functions using the callback mechanism (see section [22.7.1](#ss%3Ac-callbacks)).
###
[](#ss:c-embedded-code)22.7.5 Embedding the OCaml code in the C code
The bytecode compiler in custom runtime mode (ocamlc -custom) normally appends the bytecode to the executable file containing the custom runtime. This has two consequences. First, the final linking step must be performed by ocamlc. Second, the OCaml runtime library must be able to find the name of the executable file from the command-line arguments. When using caml\_main(argv) as in section [22.7.4](#ss%3Amain-c), this means that argv[0] or argv[1] must contain the executable file name.
An alternative is to embed the bytecode in the C code. The -output-obj and -output-complete-obj options to ocamlc are provided for this purpose. They cause the ocamlc compiler to output a C object file (.o file, .obj under Windows) containing the bytecode for the OCaml part of the program, as well as a caml\_startup function. The C object file produced by ocamlc -output-complete-obj also contains the runtime and autolink libraries. The C object file produced by ocamlc -output-obj or ocamlc -output-complete-obj can then be linked with C code using the standard C compiler, or stored in a C library.
The caml\_startup function must be called from the main C program in order to initialize the OCaml runtime and execute the OCaml initialization code. Just like caml\_main, it takes one argv parameter containing the command-line parameters. Unlike caml\_main, this argv parameter is used only to initialize Sys.argv, but not for finding the name of the executable file.
The caml\_startup function calls the uncaught exception handler (or enters the debugger, if running under ocamldebug) if an exception escapes from a top-level module initialiser. Such exceptions may be caught in the C code by instead using the caml\_startup\_exn function and testing the result using Is\_exception\_result (followed by Extract\_exception if appropriate).
The -output-obj and -output-complete-obj options can also be used to obtain the C source file. More interestingly, these options can also produce directly a shared library (.so file, .dll under Windows) that contains the OCaml code, the OCaml runtime system and any other static C code given to ocamlc (.o, .a, respectively, .obj, .lib). This use of -output-obj and -output-complete-obj is very similar to a normal linking step, but instead of producing a main program that automatically runs the OCaml code, it produces a shared library that can run the OCaml code on demand. The three possible behaviors of -output-obj and -output-complete-obj (to produce a C source code .c, a C object file .o, a shared library .so), are selected according to the extension of the resulting file (given with -o).
The native-code compiler ocamlopt also supports the -output-obj and -output-complete-obj options, causing it to output a C object file or a shared library containing the native code for all OCaml modules on the command-line, as well as the OCaml startup code. Initialization is performed by calling caml\_startup (or caml\_startup\_exn) as in the case of the bytecode compiler. The file produced by ocamlopt -output-complete-obj also contains the runtime and autolink libraries.
For the final linking phase, in addition to the object file produced by -output-obj, you will have to provide the OCaml runtime library (libcamlrun.a for bytecode, libasmrun.a for native-code), as well as all C libraries that are required by the OCaml libraries used. For instance, assume the OCaml part of your program uses the Unix library. With ocamlc, you should do:
```
ocamlc -output-obj -o camlcode.o unix.cma other .cmo and .cma files
cc -o myprog C objects and libraries \
camlcode.o -L‘ocamlc -where‘ -lunix -lcamlrun
```
With ocamlopt, you should do:
```
ocamlopt -output-obj -o camlcode.o unix.cmxa other .cmx and .cmxa files
cc -o myprog C objects and libraries \
camlcode.o -L‘ocamlc -where‘ -lunix -lasmrun
```
For the final linking phase, in addition to the object file produced by -output-complete-obj, you will have only to provide the C libraries required by the OCaml runtime.
For instance, assume the OCaml part of your program uses the Unix library. With ocamlc, you should do:
```
ocamlc -output-complete-obj -o camlcode.o unix.cma other .cmo and .cma files
cc -o myprog C objects and libraries \
camlcode.o C libraries required by the runtime, eg -lm -ldl -lcurses -lpthread
```
With ocamlopt, you should do:
```
ocamlopt -output-complete-obj -o camlcode.o unix.cmxa other .cmx and .cmxa files
cc -o myprog C objects and libraries \
camlcode.o C libraries required by the runtime, eg -lm -ldl
```
#####
[](#sec514)Warning:
On some ports, special options are required on the final linking phase that links together the object file produced by the -output-obj and -output-complete-obj options and the remainder of the program. Those options are shown in the configuration file Makefile.config generated during compilation of OCaml, as the variable OC\_LDFLAGS.
* Windows with the MSVC compiler: the object file produced by OCaml have been compiled with the /MD flag, and therefore all other object files linked with it should also be compiled with /MD.
* other systems: you may have to add one or both of -lm and -ldl, depending on your OS and C compiler.
#####
[](#sec515)Stack backtraces.
When OCaml bytecode produced by ocamlc -g is embedded in a C program, no debugging information is included, and therefore it is impossible to print stack backtraces on uncaught exceptions. This is not the case when native code produced by ocamlopt -g is embedded in a C program: stack backtrace information is available, but the backtrace mechanism needs to be turned on programmatically. This can be achieved from the OCaml side by calling Printexc.record\_backtrace true in the initialization of one of the OCaml modules. This can also be achieved from the C side by calling caml\_record\_backtraces(1); in the OCaml-C glue code. (caml\_record\_backtraces is declared in backtrace.h)
#####
[](#sec516)Unloading the runtime.
In case the shared library produced with -output-obj is to be loaded and unloaded repeatedly by a single process, care must be taken to unload the OCaml runtime explicitly, in order to avoid various system resource leaks.
Since 4.05, caml\_shutdown function can be used to shut the runtime down gracefully, which equals the following:
* Running the functions that were registered with Stdlib.at\_exit.
* Triggering finalization of allocated custom blocks (see section [22.9](#s%3Ac-custom)). For example, Stdlib.in\_channel and Stdlib.out\_channel are represented by custom blocks that enclose file descriptors, which are to be released.
* Unloading the dependent shared libraries that were loaded by the runtime, including dynlink plugins.
* Freeing the memory blocks that were allocated by the runtime with malloc. Inside C primitives, it is advised to use caml\_stat\_\* functions from memory.h for managing static (that is, non-moving) blocks of heap memory, as all the blocks allocated with these functions are automatically freed by caml\_shutdown. For ensuring compatibility with legacy C stubs that have used caml\_stat\_\* incorrectly, this behaviour is only enabled if the runtime is started with a specialized caml\_startup\_pooled function.
As a shared library may have several clients simultaneously, it is made for convenience that caml\_startup (and caml\_startup\_pooled) may be called multiple times, given that each such call is paired with a corresponding call to caml\_shutdown (in a nested fashion). The runtime will be unloaded once there are no outstanding calls to caml\_startup.
Once a runtime is unloaded, it cannot be started up again without reloading the shared library and reinitializing its static data. Therefore, at the moment, the facility is only useful for building reloadable shared libraries.
#####
[](#sec517)Unix signal handling.
Depending on the target platform and operating system, the native-code runtime system may install signal handlers for one or several of the SIGSEGV, SIGTRAP and SIGFPE signals when caml\_startup is called, and reset these signals to their default behaviors when caml\_shutdown is called. The main program written in C should not try to handle these signals itself.
[](#s:c-advexample)22.8 Advanced example with callbacks
---------------------------------------------------------
This section illustrates the callback facilities described in section [22.7](#s%3Ac-callback). We are going to package some OCaml functions in such a way that they can be linked with C code and called from C just like any C functions. The OCaml functions are defined in the following mod.ml OCaml source:
```
(* File mod.ml -- some "useful" OCaml functions *)
let rec fib n = if n < 2 then 1 else fib(n-1) + fib(n-2)
let format_result n = Printf.sprintf "Result is: %d\n" n
(* Export those two functions to C *)
let _ = Callback.register "fib" fib
let _ = Callback.register "format_result" format_result
```
Here is the C stub code for calling these functions from C:
```
/* File modwrap.c -- wrappers around the OCaml functions */
#include <stdio.h>
#include <string.h>
#include <caml/mlvalues.h>
#include <caml/callback.h>
int fib(int n)
{
static const value * fib_closure = NULL;
if (fib_closure == NULL) fib_closure = caml_named_value("fib");
return Int_val(caml_callback(*fib_closure, Val_int(n)));
}
char * format_result(int n)
{
static const value * format_result_closure = NULL;
if (format_result_closure == NULL)
format_result_closure = caml_named_value("format_result");
return strdup(String_val(caml_callback(*format_result_closure, Val_int(n))));
/* We copy the C string returned by String_val to the C heap
so that it remains valid after garbage collection. */
}
```
We now compile the OCaml code to a C object file and put it in a C library along with the stub code in modwrap.c and the OCaml runtime system:
```
ocamlc -custom -output-obj -o modcaml.o mod.ml
ocamlc -c modwrap.c
cp `ocamlc -where`/libcamlrun.a mod.a && chmod +w mod.a
ar r mod.a modcaml.o modwrap.o
```
(One can also use ocamlopt -output-obj instead of ocamlc -custom -output-obj. In this case, replace libcamlrun.a (the bytecode runtime library) by libasmrun.a (the native-code runtime library).)
Now, we can use the two functions fib and format\_result in any C program, just like regular C functions. Just remember to call caml\_startup (or caml\_startup\_exn) once before.
```
/* File main.c -- a sample client for the OCaml functions */
#include <stdio.h>
#include <caml/callback.h>
extern int fib(int n);
extern char * format_result(int n);
int main(int argc, char ** argv)
{
int result;
/* Initialize OCaml code */
caml_startup(argv);
/* Do some computation */
result = fib(10);
printf("fib(10) = %s\n", format_result(result));
return 0;
}
```
To build the whole program, just invoke the C compiler as follows:
```
cc -o prog -I `ocamlc -where` main.c mod.a -lcurses
```
(On some machines, you may need to put -ltermcap or -lcurses -ltermcap instead of -lcurses.)
[](#s:c-custom)22.9 Advanced topic: custom blocks
---------------------------------------------------
Blocks with tag Custom\_tag contain both arbitrary user data and a pointer to a C struct, with type struct custom\_operations, that associates user-provided finalization, comparison, hashing, serialization and deserialization functions to this block.
###
[](#ss:c-custom-ops)22.9.1 The struct custom\_operations
The struct custom\_operations is defined in <caml/custom.h> and contains the following fields:
* char \*identifier
A zero-terminated character string serving as an identifier for serialization and deserialization operations.
* void (\*finalize)(value v)
The finalize field contains a pointer to a C function that is called when the block becomes unreachable and is about to be reclaimed. The block is passed as first argument to the function. The finalize field can also be custom\_finalize\_default to indicate that no finalization function is associated with the block.
* int (\*compare)(value v1, value v2)
The compare field contains a pointer to a C function that is called whenever two custom blocks are compared using OCaml’s generic comparison operators (=, <>, <=, >=, <, > and compare). The C function should return 0 if the data contained in the two blocks are structurally equal, a negative integer if the data from the first block is less than the data from the second block, and a positive integer if the data from the first block is greater than the data from the second block.The compare field can be set to custom\_compare\_default; this default comparison function simply raises Failure.
* int (\*compare\_ext)(value v1, value v2)
(Since 3.12.1) The compare\_ext field contains a pointer to a C function that is called whenever one custom block and one unboxed integer are compared using OCaml’s generic comparison operators (=, <>, <=, >=, <, > and compare). As in the case of the compare field, the C function should return 0 if the two arguments are structurally equal, a negative integer if the first argument compares less than the second argument, and a positive integer if the first argument compares greater than the second argument.The compare\_ext field can be set to custom\_compare\_ext\_default; this default comparison function simply raises Failure.
* intnat (\*hash)(value v)
The hash field contains a pointer to a C function that is called whenever OCaml’s generic hash operator (see module [Hashtbl](libref/hashtbl)) is applied to a custom block. The C function can return an arbitrary integer representing the hash value of the data contained in the given custom block. The hash value must be compatible with the compare function, in the sense that two structurally equal data (that is, two custom blocks for which compare returns 0) must have the same hash value.The hash field can be set to custom\_hash\_default, in which case the custom block is ignored during hash computation.
* void (\*serialize)(value v, uintnat \* bsize\_32, uintnat \* bsize\_64)
The serialize field contains a pointer to a C function that is called whenever the custom block needs to be serialized (marshaled) using the OCaml functions output\_value or Marshal.to\_.... For a custom block, those functions first write the identifier of the block (as given by the identifier field) to the output stream, then call the user-provided serialize function. That function is responsible for writing the data contained in the custom block, using the serialize\_... functions defined in <caml/intext.h> and listed below. The user-provided serialize function must then store in its bsize\_32 and bsize\_64 parameters the sizes in bytes of the data part of the custom block on a 32-bit architecture and on a 64-bit architecture, respectively.The serialize field can be set to custom\_serialize\_default, in which case the Failure exception is raised when attempting to serialize the custom block.
* uintnat (\*deserialize)(void \* dst)
The deserialize field contains a pointer to a C function that is called whenever a custom block with identifier identifier needs to be deserialized (un-marshaled) using the OCaml functions input\_value or Marshal.from\_.... This user-provided function is responsible for reading back the data written by the serialize operation, using the deserialize\_... functions defined in <caml/intext.h> and listed below. It must then rebuild the data part of the custom block and store it at the pointer given as the dst argument. Finally, it returns the size in bytes of the data part of the custom block. This size must be identical to the wsize\_32 result of the serialize operation if the architecture is 32 bits, or wsize\_64 if the architecture is 64 bits.The deserialize field can be set to custom\_deserialize\_default to indicate that deserialization is not supported. In this case, do not register the struct custom\_operations with the deserializer using register\_custom\_operations (see below).
* const struct custom\_fixed\_length\* fixed\_length
(Since 4.08.0) Normally, space in the serialized output is reserved to write the bsize\_32 and bsize\_64 fields returned by serialize. However, for very short custom blocks, this space can be larger than the data itself! As a space optimisation, if serialize always returns the same values for bsize\_32 and bsize\_64, then these values may be specified in the fixed\_length structure, and do not consume space in the serialized output.
Note: the finalize, compare, hash, serialize and deserialize functions attached to custom block descriptors must never trigger a garbage collection. Within these functions, do not call any of the OCaml allocation functions, and do not perform a callback into OCaml code. Do not use CAMLparam to register the parameters to these functions, and do not use CAMLreturn to return the result.
###
[](#ss:c-custom-alloc)22.9.2 Allocating custom blocks
Custom blocks must be allocated via caml\_alloc\_custom or caml\_alloc\_custom\_mem:
caml\_alloc\_custom(ops, size, used, max)
returns a fresh custom block, with room for size bytes of user data, and whose associated operations are given by ops (a pointer to a struct custom\_operations, usually statically allocated as a C global variable).
The two parameters used and max are used to control the speed of garbage collection when the finalized object contains pointers to out-of-heap resources. Generally speaking, the OCaml incremental major collector adjusts its speed relative to the allocation rate of the program. The faster the program allocates, the harder the GC works in order to reclaim quickly unreachable blocks and avoid having large amount of “floating garbage” (unreferenced objects that the GC has not yet collected).
Normally, the allocation rate is measured by counting the in-heap size of allocated blocks. However, it often happens that finalized objects contain pointers to out-of-heap memory blocks and other resources (such as file descriptors, X Windows bitmaps, etc.). For those blocks, the in-heap size of blocks is not a good measure of the quantity of resources allocated by the program.
The two arguments used and max give the GC an idea of how much out-of-heap resources are consumed by the finalized block being allocated: you give the amount of resources allocated to this object as parameter used, and the maximum amount that you want to see in floating garbage as parameter max. The units are arbitrary: the GC cares only about the ratio used / max.
For instance, if you are allocating a finalized block holding an X Windows bitmap of w by h pixels, and you’d rather not have more than 1 mega-pixels of unreclaimed bitmaps, specify used = w \* h and max = 1000000.
Another way to describe the effect of the used and max parameters is in terms of full GC cycles. If you allocate many custom blocks with used / max = 1 / N, the GC will then do one full cycle (examining every object in the heap and calling finalization functions on those that are unreachable) every N allocations. For instance, if used = 1 and max = 1000, the GC will do one full cycle at least every 1000 allocations of custom blocks.
If your finalized blocks contain no pointers to out-of-heap resources, or if the previous discussion made little sense to you, just take used = 0 and max = 1. But if you later find that the finalization functions are not called “often enough”, consider increasing the used / max ratio.
caml\_alloc\_custom\_mem(ops, size, used)
Use this function when your custom block holds only out-of-heap memory (memory allocated with malloc or caml\_stat\_alloc) and no other resources. used should be the number of bytes of out-of-heap memory that are held by your custom block. This function works like caml\_alloc\_custom except that the max parameter is under the control of the user (via the custom\_major\_ratio, custom\_minor\_ratio, and custom\_minor\_max\_size parameters) and proportional to the heap sizes. It has been available since OCaml 4.08.0.
###
[](#ss:c-custom-access)22.9.3 Accessing custom blocks
The data part of a custom block v can be accessed via the pointer Data\_custom\_val(v). This pointer has type void \* and should be cast to the actual type of the data stored in the custom block.
The contents of custom blocks are not scanned by the garbage collector, and must therefore not contain any pointer inside the OCaml heap. In other terms, never store an OCaml value in a custom block, and do not use Field, Store\_field nor caml\_modify to access the data part of a custom block. Conversely, any C data structure (not containing heap pointers) can be stored in a custom block.
###
[](#ss:c-custom-serialization)22.9.4 Writing custom serialization and deserialization functions
The following functions, defined in <caml/intext.h>, are provided to write and read back the contents of custom blocks in a portable way. Those functions handle endianness conversions when e.g. data is written on a little-endian machine and read back on a big-endian machine.
| | |
| --- | --- |
| Function | Action |
| caml\_serialize\_int\_1 | Write a 1-byte integer |
| caml\_serialize\_int\_2 | Write a 2-byte integer |
| caml\_serialize\_int\_4 | Write a 4-byte integer |
| caml\_serialize\_int\_8 | Write a 8-byte integer |
| caml\_serialize\_float\_4 | Write a 4-byte float |
| caml\_serialize\_float\_8 | Write a 8-byte float |
| caml\_serialize\_block\_1 | Write an array of 1-byte quantities |
| caml\_serialize\_block\_2 | Write an array of 2-byte quantities |
| caml\_serialize\_block\_4 | Write an array of 4-byte quantities |
| caml\_serialize\_block\_8 | Write an array of 8-byte quantities |
| caml\_deserialize\_uint\_1 | Read an unsigned 1-byte integer |
| caml\_deserialize\_sint\_1 | Read a signed 1-byte integer |
| caml\_deserialize\_uint\_2 | Read an unsigned 2-byte integer |
| caml\_deserialize\_sint\_2 | Read a signed 2-byte integer |
| caml\_deserialize\_uint\_4 | Read an unsigned 4-byte integer |
| caml\_deserialize\_sint\_4 | Read a signed 4-byte integer |
| caml\_deserialize\_uint\_8 | Read an unsigned 8-byte integer |
| caml\_deserialize\_sint\_8 | Read a signed 8-byte integer |
| caml\_deserialize\_float\_4 | Read a 4-byte float |
| caml\_deserialize\_float\_8 | Read an 8-byte float |
| caml\_deserialize\_block\_1 | Read an array of 1-byte quantities |
| caml\_deserialize\_block\_2 | Read an array of 2-byte quantities |
| caml\_deserialize\_block\_4 | Read an array of 4-byte quantities |
| caml\_deserialize\_block\_8 | Read an array of 8-byte quantities |
| caml\_deserialize\_error | Signal an error during deserialization; input\_value or Marshal.from\_... raise a Failure exception after cleaning up their internal data structures |
Serialization functions are attached to the custom blocks to which they apply. Obviously, deserialization functions cannot be attached this way, since the custom block does not exist yet when deserialization begins! Thus, the struct custom\_operations that contain deserialization functions must be registered with the deserializer in advance, using the register\_custom\_operations function declared in <caml/custom.h>. Deserialization proceeds by reading the identifier off the input stream, allocating a custom block of the size specified in the input stream, searching the registered struct custom\_operation blocks for one with the same identifier, and calling its deserialize function to fill the data part of the custom block.
###
[](#ss:c-custom-idents)22.9.5 Choosing identifiers
Identifiers in struct custom\_operations must be chosen carefully, since they must identify uniquely the data structure for serialization and deserialization operations. In particular, consider including a version number in the identifier; this way, the format of the data can be changed later, yet backward-compatible deserialisation functions can be provided.
Identifiers starting with \_ (an underscore character) are reserved for the OCaml runtime system; do not use them for your custom data. We recommend to use a URL (http://mymachine.mydomain.com/mylibrary/version-number) or a Java-style package name (com.mydomain.mymachine.mylibrary.version-number) as identifiers, to minimize the risk of identifier collision.
###
[](#ss:c-finalized)22.9.6 Finalized blocks
Custom blocks generalize the finalized blocks that were present in OCaml prior to version 3.00. For backward compatibility, the format of custom blocks is compatible with that of finalized blocks, and the alloc\_final function is still available to allocate a custom block with a given finalization function, but default comparison, hashing and serialization functions. caml\_alloc\_final(n, f, used, max) returns a fresh custom block of size n+1 words, with finalization function f. The first word is reserved for storing the custom operations; the other n words are available for your data. The two parameters used and max are used to control the speed of garbage collection, as described for caml\_alloc\_custom.
[](#s:C-Bigarrays)22.10 Advanced topic: Bigarrays and the OCaml-C interface
-----------------------------------------------------------------------------
This section explains how C stub code that interfaces C or Fortran code with OCaml code can use Bigarrays.
###
[](#ss:C-Bigarrays-include)22.10.1 Include file
The include file <caml/bigarray.h> must be included in the C stub file. It declares the functions, constants and macros discussed below.
###
[](#ss:C-Bigarrays-access)22.10.2 Accessing an OCaml bigarray from C or Fortran
If v is a OCaml value representing a Bigarray, the expression Caml\_ba\_data\_val(v) returns a pointer to the data part of the array. This pointer is of type void \* and can be cast to the appropriate C type for the array (e.g. double [], char [][10], etc).
Various characteristics of the OCaml Bigarray can be consulted from C as follows:
| | |
| --- | --- |
| C expression | Returns |
| Caml\_ba\_array\_val(v)->num\_dims | number of dimensions |
| Caml\_ba\_array\_val(v)->dim[i] | i-th dimension |
| Caml\_ba\_array\_val(v)->flags & BIGARRAY\_KIND\_MASK | kind of array elements |
The kind of array elements is one of the following constants:
| | |
| --- | --- |
| Constant | Element kind |
| CAML\_BA\_FLOAT32 | 32-bit single-precision floats |
| CAML\_BA\_FLOAT64 | 64-bit double-precision floats |
| CAML\_BA\_SINT8 | 8-bit signed integers |
| CAML\_BA\_UINT8 | 8-bit unsigned integers |
| CAML\_BA\_SINT16 | 16-bit signed integers |
| CAML\_BA\_UINT16 | 16-bit unsigned integers |
| CAML\_BA\_INT32 | 32-bit signed integers |
| CAML\_BA\_INT64 | 64-bit signed integers |
| CAML\_BA\_CAML\_INT | 31- or 63-bit signed integers |
| CAML\_BA\_NATIVE\_INT | 32- or 64-bit (platform-native) integers |
| CAML\_BA\_COMPLEX32 | 32-bit single-precision complex numbers |
| CAML\_BA\_COMPLEX64 | 64-bit double-precision complex numbers |
| CAML\_BA\_CHAR | 8-bit characters |
#####
[](#sec529)Warning:
Caml\_ba\_array\_val(v) must always be dereferenced immediately and not stored anywhere, including local variables. It resolves to a derived pointer: it is not a valid OCaml value but points to a memory region managed by the GC. For this reason this value must not be stored in any memory location that could be live cross a GC.
The following example shows the passing of a two-dimensional Bigarray to a C function and a Fortran function.
```
extern void my_c_function(double * data, int dimx, int dimy);
extern void my_fortran_function_(double * data, int * dimx, int * dimy);
CAMLprim value caml_stub(value bigarray)
{
int dimx = Caml_ba_array_val(bigarray)->dim[0];
int dimy = Caml_ba_array_val(bigarray)->dim[1];
/* C passes scalar parameters by value */
my_c_function(Caml_ba_data_val(bigarray), dimx, dimy);
/* Fortran passes all parameters by reference */
my_fortran_function_(Caml_ba_data_val(bigarray), &dimx, &dimy);
return Val_unit;
}
```
###
[](#ss:C-Bigarrays-wrap)22.10.3 Wrapping a C or Fortran array as an OCaml Bigarray
A pointer p to an already-allocated C or Fortran array can be wrapped and returned to OCaml as a Bigarray using the caml\_ba\_alloc or caml\_ba\_alloc\_dims functions.
* caml\_ba\_alloc(kind | layout, numdims, p, dims)Return an OCaml Bigarray wrapping the data pointed to by p. kind is the kind of array elements (one of the CAML\_BA\_ kind constants above). layout is CAML\_BA\_C\_LAYOUT for an array with C layout and CAML\_BA\_FORTRAN\_LAYOUT for an array with Fortran layout. numdims is the number of dimensions in the array. dims is an array of numdims long integers, giving the sizes of the array in each dimension.
* caml\_ba\_alloc\_dims(kind | layout, numdims, p, (long) dim1, (long) dim2, …, (long) dimnumdims)Same as caml\_ba\_alloc, but the sizes of the array in each dimension are listed as extra arguments in the function call, rather than being passed as an array.
The following example illustrates how statically-allocated C and Fortran arrays can be made available to OCaml.
```
extern long my_c_array[100][200];
extern float my_fortran_array_[300][400];
CAMLprim value caml_get_c_array(value unit)
{
long dims[2];
dims[0] = 100; dims[1] = 200;
return caml_ba_alloc(CAML_BA_NATIVE_INT | CAML_BA_C_LAYOUT,
2, my_c_array, dims);
}
CAMLprim value caml_get_fortran_array(value unit)
{
return caml_ba_alloc_dims(CAML_BA_FLOAT32 | CAML_BA_FORTRAN_LAYOUT,
2, my_fortran_array_, 300L, 400L);
}
```
[](#s:C-cheaper-call)22.11 Advanced topic: cheaper C call
-----------------------------------------------------------
This section describe how to make calling C functions cheaper.
Note: this only applies to the native compiler. So whenever you use any of these methods, you have to provide an alternative byte-code stub that ignores all the special annotations.
###
[](#ss:c-unboxed)22.11.1 Passing unboxed values
We said earlier that all OCaml objects are represented by the C type value, and one has to use macros such as Int\_val to decode data from the value type. It is however possible to tell the OCaml native-code compiler to do this for us and pass arguments unboxed to the C function. Similarly it is possible to tell OCaml to expect the result unboxed and box it for us.
The motivation is that, by letting ‘ocamlopt‘ deal with boxing, it can often decide to suppress it entirely.
For instance let’s consider this example:
```
external foo : float -> float -> float = "foo"
let f a b =
let len = Array.length a in
assert (Array.length b = len);
let res = Array.make len 0. in
for i = 0 to len - 1 do
res.(i) <- foo a.(i) b.(i)
done
```
Float arrays are unboxed in OCaml, however the C function foo expect its arguments as boxed floats and returns a boxed float. Hence the OCaml compiler has no choice but to box a.(i) and b.(i) and unbox the result of foo. This results in the allocation of 3 \* len temporary float values.
Now if we annotate the arguments and result with [@unboxed], the native-code compiler will be able to avoid all these allocations:
```
external foo
: (float [@unboxed])
-> (float [@unboxed])
-> (float [@unboxed])
= "foo_byte" "foo"
```
In this case the C functions must look like:
```
CAMLprim double foo(double a, double b)
{
...
}
CAMLprim value foo_byte(value a, value b)
{
return caml_copy_double(foo(Double_val(a), Double_val(b)))
}
```
For convenience, when all arguments and the result are annotated with [@unboxed], it is possible to put the attribute only once on the declaration itself. So we can also write instead:
```
external foo : float -> float -> float = "foo_byte" "foo" [@@unboxed]
```
The following table summarize what OCaml types can be unboxed, and what C types should be used in correspondence:
| | |
| --- | --- |
| OCaml type | C type |
| float | double |
| int32 | int32\_t |
| int64 | int64\_t |
| nativeint | intnat |
Similarly, it is possible to pass untagged OCaml integers between OCaml and C. This is done by annotating the arguments and/or result with [@untagged]:
```
external f : string -> (int [@untagged]) = "f_byte" "f"
```
The corresponding C type must be intnat.
Note: do not use the C int type in correspondence with (int [@untagged]). This is because they often differ in size.
###
[](#ss:c-direct-call)22.11.2 Direct C call
In order to be able to run the garbage collector in the middle of a C function, the OCaml native-code compiler generates some bookkeeping code around C calls. Technically it wraps every C call with the C function caml\_c\_call which is part of the OCaml runtime.
For small functions that are called repeatedly, this indirection can have a big impact on performances. However this is not needed if we know that the C function doesn’t allocate, doesn’t raise exceptions, and doesn’t release the domain lock (see section [22.12.2](#ss%3Aparallel-execution-long-running-c-code)). We can instruct the OCaml native-code compiler of this fact by annotating the external declaration with the attribute [@@noalloc]:
```
external bar : int -> int -> int = "foo" [@@noalloc]
```
In this case calling bar from OCaml is as cheap as calling any other OCaml function, except for the fact that the OCaml compiler can’t inline C functions...
###
[](#ss:c-direct-call-example)22.11.3 Example: calling C library functions without indirection
Using these attributes, it is possible to call C library functions with no indirection. For instance many math functions are defined this way in the OCaml standard library:
```
external sqrt : float -> float = "caml_sqrt_float" "sqrt"
[@@unboxed] [@@noalloc]
(** Square root. *)
external exp : float -> float = "caml_exp_float" "exp" [@@unboxed] [@@noalloc]
(** Exponential. *)
external log : float -> float = "caml_log_float" "log" [@@unboxed] [@@noalloc]
(** Natural logarithm. *)
```
[](#s:C-multithreading)22.12 Advanced topic: multithreading
-------------------------------------------------------------
Using multiple threads (shared-memory concurrency) in a mixed OCaml/C application requires special precautions, which are described in this section.
###
[](#ss:c-thread-register)22.12.1 Registering threads created from C
Callbacks from C to OCaml are possible only if the calling thread is known to the OCaml run-time system. Threads created from OCaml (through the Thread.create function of the system threads library) are automatically known to the run-time system. If the application creates additional threads from C and wishes to callback into OCaml code from these threads, it must first register them with the run-time system. The following functions are declared in the include file <caml/threads.h>.
* caml\_c\_thread\_register() registers the calling thread with the OCaml run-time system. Returns 1 on success, 0 on error. Registering an already-registered thread does nothing and returns 0.
* caml\_c\_thread\_unregister() must be called before the thread terminates, to unregister it from the OCaml run-time system. Returns 1 on success, 0 on error. If the calling thread was not previously registered, does nothing and returns 0.
###
[](#ss:parallel-execution-long-running-c-code)22.12.2 Parallel execution of long-running C code with systhreads
Domains are the unit of parallelism for OCaml programs. When using the systhreads library, multiple threads might be attached to the same domain. However, at any time, at most one of those thread can be executing OCaml code or C code that uses the OCaml run-time system by domain. Technically, this is enforced by a “domain lock” that any thread must hold while executing such code within a domain.
When OCaml calls the C code implementing a primitive, the domain lock is held, therefore the C code has full access to the facilities of the run-time system. However, no other thread in the same domain can execute OCaml code concurrently with the C code of the primitive. See also chapter [9.6](parallelism#s%3Apar_c_bindings) for the behaviour with multiple domains.
If a C primitive runs for a long time or performs potentially blocking input-output operations, it can explicitly release the domain lock, enabling other OCaml threads in the same domain to run concurrently with its operations. The C code must re-acquire the domain lock before returning to OCaml. This is achieved with the following functions, declared in the include file <caml/threads.h>.
* caml\_release\_runtime\_system() The calling thread releases the domain lock and other OCaml resources, enabling other threads to run OCaml code in parallel with the execution of the calling thread.
* caml\_acquire\_runtime\_system() The calling thread re-acquires the domain lock and other OCaml resources. It may block until no other thread in the same domain uses the OCaml run-time system.
These functions poll for pending signals by calling asynchronous callbacks (section [22.5.3](#ss%3Ac-process-pending-actions)) before releasing and after acquiring the lock. They can therefore execute arbitrary OCaml code including raising an asynchronous exception.
After caml\_release\_runtime\_system() was called and until caml\_acquire\_runtime\_system() is called, the C code must not access any OCaml data, nor call any function of the run-time system, nor call back into OCaml code. Consequently, arguments provided by OCaml to the C primitive must be copied into C data structures before calling caml\_release\_runtime\_system(), and results to be returned to OCaml must be encoded as OCaml values after caml\_acquire\_runtime\_system() returns.
Example: the following C primitive invokes gethostbyname to find the IP address of a host name. The gethostbyname function can block for a long time, so we choose to release the OCaml run-time system while it is running.
```
CAMLprim stub_gethostbyname(value vname)
{
CAMLparam1 (vname);
CAMLlocal1 (vres);
struct hostent * h;
char * name;
/* Copy the string argument to a C string, allocated outside the
OCaml heap. */
name = caml_stat_strdup(String_val(vname));
/* Release the OCaml run-time system */
caml_release_runtime_system();
/* Resolve the name */
h = gethostbyname(name);
/* Free the copy of the string, which we might as well do before
acquiring the runtime system to benefit from parallelism. */
caml_stat_free(name);
/* Re-acquire the OCaml run-time system */
caml_acquire_runtime_system();
/* Encode the relevant fields of h as the OCaml value vres */
... /* Omitted */
/* Return to OCaml */
CAMLreturn (vres);
}
```
The macro Caml\_state evaluates to the domain state variable, and checks in debug mode that the domain lock is held. Such a check is also placed in normal mode at key entry points of the C API; this is why calling some of the runtime functions and macros without correctly owning the domain lock can result in a fatal error: no domain lock held. The variant Caml\_state\_opt does not perform any check but evaluates to NULL when the domain lock is not held. This lets you determine whether a thread belonging to a domain currently holds its domain lock, for various purposes.
Callbacks from C to OCaml must be performed while holding the domain lock to the OCaml run-time system. This is naturally the case if the callback is performed by a C primitive that did not release the run-time system. If the C primitive released the run-time system previously, or the callback is performed from other C code that was not invoked from OCaml (e.g. an event loop in a GUI application), the run-time system must be acquired before the callback and released after:
```
caml_acquire_runtime_system();
/* Resolve OCaml function vfun to be invoked */
/* Build OCaml argument varg to the callback */
vres = callback(vfun, varg);
/* Copy relevant parts of result vres to C data structures */
caml_release_runtime_system();
```
Note: the acquire and release functions described above were introduced in OCaml 3.12. Older code uses the following historical names, declared in <caml/signals.h>:
* caml\_enter\_blocking\_section as an alias for caml\_release\_runtime\_system
* caml\_leave\_blocking\_section as an alias for caml\_acquire\_runtime\_system
Intuition: a “blocking section” is a piece of C code that does not use the OCaml run-time system, typically a blocking input/output operation.
[](#s:interfacing-windows-unicode-apis)22.13 Advanced topic: interfacing with Windows Unicode APIs
----------------------------------------------------------------------------------------------------
This section contains some general guidelines for writing C stubs that use Windows Unicode APIs.
The OCaml system under Windows can be configured at build time in one of two modes:
* legacy mode: All path names, environment variables, command line arguments, etc. on the OCaml side are assumed to be encoded using the current 8-bit code page of the system.
* Unicode mode: All path names, environment variables, command line arguments, etc. on the OCaml side are assumed to be encoded using UTF-8.
In what follows, we say that a string has the *OCaml encoding* if it is encoded in UTF-8 when in Unicode mode, in the current code page in legacy mode, or is an arbitrary string under Unix. A string has the *platform encoding* if it is encoded in UTF-16 under Windows or is an arbitrary string under Unix.
From the point of view of the writer of C stubs, the challenges of interacting with Windows Unicode APIs are twofold:
* The Windows API uses the UTF-16 encoding to support Unicode. The runtime system performs the necessary conversions so that the OCaml programmer only needs to deal with the OCaml encoding. C stubs that call Windows Unicode APIs need to use specific runtime functions to perform the necessary conversions in a compatible way.
* When writing stubs that need to be compiled under both Windows and Unix, the stubs need to be written in a way that allow the necessary conversions under Windows but that also work under Unix, where typically nothing particular needs to be done to support Unicode.
The native C character type under Windows is WCHAR, two bytes wide, while under Unix it is char, one byte wide. A type char\_os is defined in <caml/misc.h> that stands for the concrete C character type of each platform. Strings in the platform encoding are of type char\_os \*.
The following functions are exposed to help write compatible C stubs. To use them, you need to include both <caml/misc.h> and <caml/osdeps.h>.
* char\_os\* caml\_stat\_strdup\_to\_os(const char \*) copies the argument while translating from OCaml encoding to the platform encoding. This function is typically used to convert the char \* underlying an OCaml string before passing it to an operating system API that takes a Unicode argument. Under Unix, it is equivalent to caml\_stat\_strdup.Note: For maximum backwards compatibility in Unicode mode, if the argument is not a valid UTF-8 string, this function will fall back to assuming that it is encoded in the current code page.
* char\* caml\_stat\_strdup\_of\_os(const char\_os \*) copies the argument while translating from the platform encoding to the OCaml encoding. It is the inverse of caml\_stat\_strdup\_to\_os. This function is typically used to convert a string obtained from the operating system before passing it on to OCaml code. Under Unix, it is equivalent to caml\_stat\_strdup.
* value caml\_copy\_string\_of\_os(char\_os \*) allocates an OCaml string with contents equal to the argument string converted to the OCaml encoding. This function is essentially equivalent to caml\_stat\_strdup\_of\_os followed by caml\_copy\_string, except that it avoids the allocation of the intermediate string returned by caml\_stat\_strdup\_of\_os. Under Unix, it is equivalent to caml\_copy\_string.
Note: The strings returned by caml\_stat\_strdup\_to\_os and caml\_stat\_strdup\_of\_os are allocated using caml\_stat\_alloc, so they need to be deallocated using caml\_stat\_free when they are no longer needed.
#####
[](#sec539)Example
We want to bind the function getenv in a way that works both under Unix and Windows. Under Unix this function has the prototype:
```
char *getenv(const char *);
```
While the Unicode version under Windows has the prototype:
```
WCHAR *_wgetenv(const WCHAR *);
```
In terms of char\_os, both functions take an argument of type char\_os \* and return a result of the same type. We begin by choosing the right implementation of the function to bind:
```
#ifdef _WIN32
#define getenv_os _wgetenv
#else
#define getenv_os getenv
#endif
```
The rest of the binding is the same for both platforms:
```
#include <caml/mlvalues.h>
#include <caml/misc.h>
#include <caml/alloc.h>
#include <caml/fail.h>
#include <caml/osdeps.h>
#include <stdlib.h>
CAMLprim value stub_getenv(value var_name)
{
CAMLparam1(var_name);
CAMLlocal1(var_value);
char_os *var_name_os, *var_value_os;
var_name_os = caml_stat_strdup_to_os(String_val(var_name));
var_value_os = getenv_os(var_name_os);
caml_stat_free(var_name_os);
if (var_value_os == NULL)
caml_raise_not_found();
var_value = caml_copy_string_of_os(var_value_os);
CAMLreturn(var_value);
}
```
[](#s:ocamlmklib)22.14 Building mixed C/OCaml libraries: ocamlmklib
---------------------------------------------------------------------
The ocamlmklib command facilitates the construction of libraries containing both OCaml code and C code, and usable both in static linking and dynamic linking modes. This command is available under Windows since Objective Caml 3.11 and under other operating systems since Objective Caml 3.03.
The ocamlmklib command takes three kinds of arguments:
* OCaml source files and object files (.cmo, .cmx, .ml) comprising the OCaml part of the library;
* C object files (.o, .a, respectively, .obj, .lib) comprising the C part of the library;
* Support libraries for the C part (-llib).
It generates the following outputs:
* An OCaml bytecode library .cma incorporating the .cmo and .ml OCaml files given as arguments, and automatically referencing the C library generated with the C object files.
* An OCaml native-code library .cmxa incorporating the .cmx and .ml OCaml files given as arguments, and automatically referencing the C library generated with the C object files.
* If dynamic linking is supported on the target platform, a .so (respectively, .dll) shared library built from the C object files given as arguments, and automatically referencing the support libraries.
* A C static library .a(respectively, .lib) built from the C object files.
In addition, the following options are recognized:
-cclib, -ccopt, -I, -linkall
These options are passed as is to ocamlc or ocamlopt. See the documentation of these commands.
-rpath, -R, -Wl,-rpath, -Wl,-R
These options are passed as is to the C compiler. Refer to the documentation of the C compiler.
-custom
Force the construction of a statically linked library only, even if dynamic linking is supported.
-failsafe
Fall back to building a statically linked library if a problem occurs while building the shared library (e.g. some of the support libraries are not available as shared libraries).
-Ldir
Add dir to the search path for support libraries (-llib).
-ocamlc cmd
Use cmd instead of ocamlc to call the bytecode compiler.
-ocamlopt cmd
Use cmd instead of ocamlopt to call the native-code compiler.
-o output
Set the name of the generated OCaml library. ocamlmklib will generate output.cma and/or output.cmxa. If not specified, defaults to a.
-oc outputc
Set the name of the generated C library. ocamlmklib will generate liboutputc.so (if shared libraries are supported) and liboutputc.a. If not specified, defaults to the output name given with -o.
On native Windows, the following environment variable is also consulted:
OCAML\_FLEXLINK
Alternative executable to use instead of the configured value. Primarily used for bootstrapping.
#####
[](#sec541)Example
Consider an OCaml interface to the standard libz C library for reading and writing compressed files. Assume this library resides in /usr/local/zlib. This interface is composed of an OCaml part zip.cmo/zip.cmx and a C part zipstubs.o containing the stub code around the libz entry points. The following command builds the OCaml libraries zip.cma and zip.cmxa, as well as the companion C libraries dllzip.so and libzip.a:
```
ocamlmklib -o zip zip.cmo zip.cmx zipstubs.o -lz -L/usr/local/zlib
```
If shared libraries are supported, this performs the following commands:
```
ocamlc -a -o zip.cma zip.cmo -dllib -lzip \
-cclib -lzip -cclib -lz -ccopt -L/usr/local/zlib
ocamlopt -a -o zip.cmxa zip.cmx -cclib -lzip \
-cclib -lzip -cclib -lz -ccopt -L/usr/local/zlib
gcc -shared -o dllzip.so zipstubs.o -lz -L/usr/local/zlib
ar rc libzip.a zipstubs.o
```
Note: This example is on a Unix system. The exact command lines may be different on other systems.
If shared libraries are not supported, the following commands are performed instead:
```
ocamlc -a -custom -o zip.cma zip.cmo -cclib -lzip \
-cclib -lz -ccopt -L/usr/local/zlib
ocamlopt -a -o zip.cmxa zip.cmx -lzip \
-cclib -lz -ccopt -L/usr/local/zlib
ar rc libzip.a zipstubs.o
```
Instead of building simultaneously the bytecode library, the native-code library and the C libraries, ocamlmklib can be called three times to build each separately. Thus,
```
ocamlmklib -o zip zip.cmo -lz -L/usr/local/zlib
```
builds the bytecode library zip.cma, and
```
ocamlmklib -o zip zip.cmx -lz -L/usr/local/zlib
```
builds the native-code library zip.cmxa, and
```
ocamlmklib -o zip zipstubs.o -lz -L/usr/local/zlib
```
builds the C libraries dllzip.so and libzip.a. Notice that the support libraries (-lz) and the corresponding options (-L/usr/local/zlib) must be given on all three invocations of ocamlmklib, because they are needed at different times depending on whether shared libraries are supported.
[](#s:c-internal-guidelines)22.15 Cautionary words: the internal runtime API
------------------------------------------------------------------------------
Not all header available in the caml/ directory were described in previous sections. All those unmentioned headers are part of the internal runtime API, for which there is *no* stability guarantee. If you really need access to this internal runtime API, this section provides some guidelines that may help you to write code that might not break on every new version of OCaml.
#####
[](#sec543)Note
Programmers which come to rely on the internal API for a use-case which they find realistic and useful are encouraged to open a request for improvement on the bug tracker.
###
[](#ss:c-internals)22.15.1 Internal variables and CAML\_INTERNALS
Since OCaml 4.04, it is possible to get access to every part of the internal runtime API by defining the CAML\_INTERNALS macro before loading caml header files. If this macro is not defined, parts of the internal runtime API are hidden.
If you are using internal C variables, do not redefine them by hand. You should import those variables by including the corresponding header files. The representation of those variables has already changed once in OCaml 4.10, and is still under evolution. If your code relies on such internal and brittle properties, it will be broken at some point in time.
For instance, rather than redefining caml\_young\_limit:
```
extern int caml_young_limit;
```
which breaks in OCaml ≥ 4.10, you should include the minor\_gc header:
```
#include <caml/minor_gc.h>
```
###
[](#ss:c-internal-macros)22.15.2 OCaml version macros
Finally, if including the right headers is not enough, or if you need to support version older than OCaml 4.04, the header file caml/version.h should help you to define your own compatibility layer. This file provides few macros defining the current OCaml version. In particular, the OCAML\_VERSION macro describes the current version, its format is MmmPP. For example, if you need some specific handling for versions older than 4.10.0, you could write
```
#include <caml/version.h>
#if OCAML_VERSION >= 41000
...
#else
...
#endif
```
| programming_docs |
ocaml None
[](#s:letrecvalues)12.1 Recursive definitions of values
---------------------------------------------------------
(Introduced in Objective Caml 1.00)
As mentioned in section [11.7.2](expr#sss%3Aexpr-localdef), the let rec binding construct, in addition to the definition of recursive functions, also supports a certain class of recursive definitions of non-functional values, such as
let rec name1 = 1 :: name2 and name2 = 2 :: name1 in [expr](expr#expr)
which binds name1 to the cyclic list 1::2::1::2::…, and name2 to the cyclic list 2::1::2::1::…Informally, the class of accepted definitions consists of those definitions where the defined names occur only inside function bodies or as argument to a data constructor.
More precisely, consider the expression:
let rec name1 = [expr](expr#expr)1 and … and namen = [expr](expr#expr)n in [expr](expr#expr)
It will be accepted if each one of [expr](expr#expr)1 … [expr](expr#expr)n is statically constructive with respect to name1 … namen, is not immediately linked to any of name1 … namen, and is not an array constructor whose arguments have abstract type.
An expression e is said to be *statically constructive with respect to* the variables name1 … namen if at least one of the following conditions is true:
* e has no free occurrence of any of name1 … namen
* e is a variable
* e has the form fun … -> …
* e has the form function … -> …
* e has the form lazy ( … )
* e has one of the following forms, where each one of [expr](expr#expr)1 … [expr](expr#expr)m is statically constructive with respect to name1 … namen, and [expr](expr#expr)0 is statically constructive with respect to name1 … namen, xname1 … xnamem:
+ let [rec] xname1 = [expr](expr#expr)1 and … and xnamem = [expr](expr#expr)m in [expr](expr#expr)0
+ let module … in [expr](expr#expr)1
+ [constr](names#constr) ([expr](expr#expr)1, … , [expr](expr#expr)m)
+ `[tag-name](names#tag-name) ([expr](expr#expr)1, … , [expr](expr#expr)m)
+ [| [expr](expr#expr)1; … ; [expr](expr#expr)m |]
+ { [field](names#field)1 = [expr](expr#expr)1; … ; [field](names#field)m = [expr](expr#expr)m }
+ { [expr](expr#expr)1 with [field](names#field)2 = [expr](expr#expr)2; … ; [field](names#field)m = [expr](expr#expr)m } where [expr](expr#expr)1 is not immediately linked to name1 … namen
+ ( [expr](expr#expr)1, … , [expr](expr#expr)m )
+ [expr](expr#expr)1; … ; [expr](expr#expr)m
An expression e is said to be *immediately linked to* the variable name in the following cases:
* e is name
* e has the form [expr](expr#expr)1; … ; [expr](expr#expr)m where [expr](expr#expr)m is immediately linked to name
* e has the form let [rec] xname1 = [expr](expr#expr)1 and … and xnamem = [expr](expr#expr)m in [expr](expr#expr)0 where [expr](expr#expr)0 is immediately linked to name or to one of the xnamei such that [expr](expr#expr)i is immediately linked to name.
ocaml Chapter 4 Labeled arguments Chapter 4 Labeled arguments
===========================
* [4.1 Optional arguments](lablexamples#s%3Aoptional-arguments)
* [4.2 Labels and type inference](lablexamples#s%3Alabel-inference)
* [4.3 Suggestions for labeling](lablexamples#s%3Alabel-suggestions)
(Chapter written by Jacques Garrigue)
If you have a look at modules ending in Labels in the standard library, you will see that function types have annotations you did not have in the functions you defined yourself.
```
# ListLabels.map;;
- : f:('a -> 'b) -> 'a list -> 'b list =
```
```
# StringLabels.sub;;
- : string -> pos:int -> len:int -> string =
```
Such annotations of the form name: are called *labels*. They are meant to document the code, allow more checking, and give more flexibility to function application. You can give such names to arguments in your programs, by prefixing them with a tilde ~.
```
# let f ~x ~y = x - y;;
val f : x:int -> y:int -> int =
```
```
# let x = 3 and y = 2 in f ~x ~y;;
- : int = 1
```
When you want to use distinct names for the variable and the label appearing in the type, you can use a naming label of the form ~name:. This also applies when the argument is not a variable.
```
# let f ~x:x1 ~y:y1 = x1 - y1;;
val f : x:int -> y:int -> int =
```
```
# f ~x:3 ~y:2;;
- : int = 1
```
Labels obey the same rules as other identifiers in OCaml, that is you cannot use a reserved keyword (like in or to) as a label.
Formal parameters and arguments are matched according to their respective labels, the absence of label being interpreted as the empty label. This allows commuting arguments in applications. One can also partially apply a function on any argument, creating a new function of the remaining parameters.
```
# let f ~x ~y = x - y;;
val f : x:int -> y:int -> int =
```
```
# f ~y:2 ~x:3;;
- : int = 1
```
```
# ListLabels.fold_left;;
- : f:('a -> 'b -> 'a) -> init:'a -> 'b list -> 'a =
```
```
# ListLabels.fold_left [1;2;3] ~init:0 ~f:( + );;
- : int = 6
```
```
# ListLabels.fold_left ~init:0;;
- : f:(int -> 'a -> int) -> 'a list -> int =
```
If several arguments of a function bear the same label (or no label), they will not commute among themselves, and order matters. But they can still commute with other arguments.
```
# let hline ~x:x1 ~x:x2 ~y = (x1, x2, y);;
val hline : x:'a -> x:'b -> y:'c -> 'a * 'b * 'c =
```
```
# hline ~x:3 ~y:2 ~x:5;;
- : int * int * int = (3, 5, 2)
```
[](#s:optional-arguments)4.1 Optional arguments
-------------------------------------------------
An interesting feature of labeled arguments is that they can be made optional. For optional parameters, the question mark ? replaces the tilde ~ of non-optional ones, and the label is also prefixed by ? in the function type. Default values may be given for such optional parameters.
```
# let bump ?(step = 1) x = x + step;;
val bump : ?step:int -> int -> int =
```
```
# bump 2;;
- : int = 3
```
```
# bump ~step:3 2;;
- : int = 5
```
A function taking some optional arguments must also take at least one non-optional argument. The criterion for deciding whether an optional argument has been omitted is the non-labeled application of an argument appearing after this optional argument in the function type. Note that if that argument is labeled, you will only be able to eliminate optional arguments by totally applying the function, omitting all optional arguments and omitting all labels for all remaining arguments.
```
# let test ?(x = 0) ?(y = 0) () ?(z = 0) () = (x, y, z);;
val test : ?x:int -> ?y:int -> unit -> ?z:int -> unit -> int * int * int =
```
```
# test ();;
- : ?z:int -> unit -> int * int * int =
```
```
# test ~x:2 () ~z:3 ();;
- : int * int * int = (2, 0, 3)
```
Optional parameters may also commute with non-optional or unlabeled ones, as long as they are applied simultaneously. By nature, optional arguments do not commute with unlabeled arguments applied independently.
```
# test ~y:2 ~x:3 () ();;
- : int * int * int = (3, 2, 0)
```
```
# test () () ~z:1 ~y:2 ~x:3;;
- : int * int * int = (3, 2, 1)
```
```
# (test () ()) ~z:1 ;;
Error: This expression has type int * int * int
This is not a function; it cannot be applied.
```
Here (test () ()) is already (0,0,0) and cannot be further applied.
Optional arguments are actually implemented as option types. If you do not give a default value, you have access to their internal representation, type 'a option = None | Some of 'a. You can then provide different behaviors when an argument is present or not.
```
# let bump ?step x =
match step with
| None -> x * 2
| Some y -> x + y
;;
val bump : ?step:int -> int -> int =
```
It may also be useful to relay an optional argument from a function call to another. This can be done by prefixing the applied argument with ?. This question mark disables the wrapping of optional argument in an option type.
```
# let test2 ?x ?y () = test ?x ?y () ();;
val test2 : ?x:int -> ?y:int -> unit -> int * int * int =
```
```
# test2 ?x:None;;
- : ?y:int -> unit -> int * int * int =
```
[](#s:label-inference)4.2 Labels and type inference
-----------------------------------------------------
While they provide an increased comfort for writing function applications, labels and optional arguments have the pitfall that they cannot be inferred as completely as the rest of the language.
You can see it in the following two examples.
```
# let h' g = g ~y:2 ~x:3;;
val h' : (y:int -> x:int -> 'a) -> 'a =
```
```
# h' f ;;
Error: This expression has type x:int -> y:int -> int
but an expression was expected of type y:int -> x:int -> 'a
```
```
# let bump_it bump x =
bump ~step:2 x;;
val bump_it : (step:int -> 'a -> 'b) -> 'a -> 'b =
```
```
# bump_it bump 1 ;;
Error: This expression has type ?step:int -> int -> int
but an expression was expected of type step:int -> 'a -> 'b
```
The first case is simple: g is passed ~y and then ~x, but f expects ~x and then ~y. This is correctly handled if we know the type of g to be x:int -> y:int -> int in advance, but otherwise this causes the above type clash. The simplest workaround is to apply formal parameters in a standard order.
The second example is more subtle: while we intended the argument bump to be of type ?step:int -> int -> int, it is inferred as step:int -> int -> 'a. These two types being incompatible (internally normal and optional arguments are different), a type error occurs when applying bump\_it to the real bump.
We will not try here to explain in detail how type inference works. One must just understand that there is not enough information in the above program to deduce the correct type of g or bump. That is, there is no way to know whether an argument is optional or not, or which is the correct order, by looking only at how a function is applied. The strategy used by the compiler is to assume that there are no optional arguments, and that applications are done in the right order.
The right way to solve this problem for optional parameters is to add a type annotation to the argument bump.
```
# let bump_it (bump : ?step:int -> int -> int) x =
bump ~step:2 x;;
val bump_it : (?step:int -> int -> int) -> int -> int =
```
```
# bump_it bump 1;;
- : int = 3
```
In practice, such problems appear mostly when using objects whose methods have optional arguments, so writing the type of object arguments is often a good idea.
Normally the compiler generates a type error if you attempt to pass to a function a parameter whose type is different from the expected one. However, in the specific case where the expected type is a non-labeled function type, and the argument is a function expecting optional parameters, the compiler will attempt to transform the argument to have it match the expected type, by passing None for all optional parameters.
```
# let twice f (x : int) = f(f x);;
val twice : (int -> int) -> int -> int =
```
```
# twice bump 2;;
- : int = 8
```
This transformation is coherent with the intended semantics, including side-effects. That is, if the application of optional parameters shall produce side-effects, these are delayed until the received function is really applied to an argument.
[](#s:label-suggestions)4.3 Suggestions for labeling
------------------------------------------------------
Like for names, choosing labels for functions is not an easy task. A good labeling is one which
* makes programs more readable,
* is easy to remember,
* when possible, allows useful partial applications.
We explain here the rules we applied when labeling OCaml libraries.
To speak in an “object-oriented” way, one can consider that each function has a main argument, its *object*, and other arguments related with its action, the *parameters*. To permit the combination of functions through functionals in commuting label mode, the object will not be labeled. Its role is clear from the function itself. The parameters are labeled with names reminding of their nature or their role. The best labels combine nature and role. When this is not possible the role is to be preferred, since the nature will often be given by the type itself. Obscure abbreviations should be avoided.
```
ListLabels.map : f:('a -> 'b) -> 'a list -> 'b list
UnixLabels.write : file_descr -> buf:bytes -> pos:int -> len:int -> unit
```
When there are several objects of same nature and role, they are all left unlabeled.
```
ListLabels.iter2 : f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit
```
When there is no preferable object, all arguments are labeled.
```
BytesLabels.blit :
src:bytes -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
```
However, when there is only one argument, it is often left unlabeled.
```
BytesLabels.create : int -> bytes
```
This principle also applies to functions of several arguments whose return type is a type variable, as long as the role of each argument is not ambiguous. Labeling such functions may lead to awkward error messages when one attempts to omit labels in an application, as we have seen with ListLabels.fold\_left.
Here are some of the label names you will find throughout the libraries.
| | |
| --- | --- |
| Label | Meaning |
| f: | a function to be applied |
| pos: | a position in a string, array or byte sequence |
| len: | a length |
| buf: | a byte sequence or string used as buffer |
| src: | the source of an operation |
| dst: | the destination of an operation |
| init: | the initial value for an iterator |
| cmp: | a comparison function, e.g. Stdlib.compare |
| mode: | an operation mode or a flag list |
All these are only suggestions, but keep in mind that the choice of labels is essential for readability. Bizarre choices will make the program harder to maintain.
In the ideal, the right function name with right labels should be enough to understand the function’s meaning. Since one can get this information with OCamlBrowser or the ocaml toplevel, the documentation is only used when a more detailed specification is needed.
ocaml Chapter 15 The runtime system (ocamlrun) Chapter 15 The runtime system (ocamlrun)
========================================
* [15.1 Overview](runtime#s%3Aocamlrun-overview)
* [15.2 Options](runtime#s%3Aocamlrun-options)
* [15.3 Dynamic loading of shared libraries](runtime#s%3Aocamlrun-dllpath)
* [15.4 Common errors](runtime#s%3Aocamlrun-common-errors)
The ocamlrun command executes bytecode files produced by the linking phase of the ocamlc command.
[](#s:ocamlrun-overview)15.1 Overview
---------------------------------------
The ocamlrun command comprises three main parts: the bytecode interpreter, that actually executes bytecode files; the memory allocator and garbage collector; and a set of C functions that implement primitive operations such as input/output.
The usage for ocamlrun is:
```
ocamlrun options bytecode-executable arg1 ... argn
```
The first non-option argument is taken to be the name of the file containing the executable bytecode. (That file is searched in the executable path as well as in the current directory.) The remaining arguments are passed to the OCaml program, in the string array Sys.argv. Element 0 of this array is the name of the bytecode executable file; elements 1 to n are the remaining arguments arg1 to argn.
As mentioned in chapter [13](comp#c%3Acamlc), the bytecode executable files produced by the ocamlc command are self-executable, and manage to launch the ocamlrun command on themselves automatically. That is, assuming a.out is a bytecode executable file,
```
a.out arg1 ... argn
```
works exactly as
```
ocamlrun a.out arg1 ... argn
```
Notice that it is not possible to pass options to ocamlrun when invoking a.out directly.
>
> Windows: Under several versions of Windows, bytecode executable files are self-executable only if their name ends in .exe. It is recommended to always give .exe names to bytecode executables, e.g. compile with ocamlc -o myprog.exe ... rather than ocamlc -o myprog ....
[](#s:ocamlrun-options)15.2 Options
-------------------------------------
The following command-line options are recognized by ocamlrun.
-b
When the program aborts due to an uncaught exception, print a detailed “back trace” of the execution, showing where the exception was raised and which function calls were outstanding at this point. The back trace is printed only if the bytecode executable contains debugging information, i.e. was compiled and linked with the -g option to ocamlc set. This is equivalent to setting the b flag in the OCAMLRUNPARAM environment variable (see below).
-config
Print the version number of ocamlrun and a detailed summary of its configuration, then exit.
-I dir
Search the directory dir for dynamically-loaded libraries, in addition to the standard search path (see section [15.3](#s%3Aocamlrun-dllpath)).
-m
Print the magic number of the bytecode executable given as argument and exit.
-M
Print the magic number expected for bytecode executables by this version of the runtime and exit.
-p
Print the names of the primitives known to this version of ocamlrun and exit.
-t
Increments the trace level for the debug runtime (ignored otherwise).
-v
Direct the memory manager to print some progress messages on standard error. This is equivalent to setting v=61 in the OCAMLRUNPARAM environment variable (see below).
-version
Print version string and exit.
-vnum
Print short version number and exit.
The following environment variables are also consulted:
CAML\_LD\_LIBRARY\_PATH
Additional directories to search for dynamically-loaded libraries (see section [15.3](#s%3Aocamlrun-dllpath)).
OCAMLLIB
The directory containing the OCaml standard library. (If OCAMLLIB is not set, CAMLLIB will be used instead.) Used to locate the ld.conf configuration file for dynamic loading (see section [15.3](#s%3Aocamlrun-dllpath)). If not set, default to the library directory specified when compiling OCaml.
OCAMLRUNPARAM
Set the runtime system options and garbage collection parameters. (If OCAMLRUNPARAM is not set, CAMLRUNPARAM will be used instead.) This variable must be a sequence of parameter specifications separated by commas. For convenience, commas at the beginning of the variable are ignored, and multiple runs of commas are interpreted as a single one. A parameter specification is an option letter followed by an = sign, a decimal number (or an hexadecimal number prefixed by 0x), and an optional multiplier. The options are documented below; the options a, i, l, m, M, n, o, O, s, v, w correspond to the fields of the control record documented in [Module Gc](libref/gc).
b
(backtrace) Trigger the printing of a stack backtrace when an uncaught exception aborts the program. An optional argument can be provided: b=0 turns backtrace printing off; b=1 is equivalent to b and turns backtrace printing on; b=2 turns backtrace printing on and forces the runtime system to load debugging information at program startup time instead of at backtrace printing time. b=2 can be used if the runtime is unable to load debugging information at backtrace printing time, for example if there are no file descriptors available.
c
(cleanup\_on\_exit) Shut the runtime down gracefully on exit (see caml\_shutdown in section [22.7.5](intfc#ss%3Ac-embedded-code)). The option also enables pooling (as in caml\_startup\_pooled). This mode can be used to detect leaks with a third-party memory debugger.
e
(runtime\_events\_log\_wsize) Size of the per-domain runtime events ring buffers in log powers of two words. Defaults to 16, giving 64k word or 512kb buffers on 64-bit systems.
l
(stack\_limit) The limit (in words) of the stack size. This is only relevant to the byte-code runtime, as the native code runtime uses the operating system’s stack.
m
(custom\_minor\_ratio) Bound on floating garbage for out-of-heap memory held by custom values in the minor heap. A minor GC is triggered when this much memory is held by custom values located in the minor heap. Expressed as a percentage of minor heap size. Default: 100. Note: this only applies to values allocated with caml\_alloc\_custom\_mem.
M
(custom\_major\_ratio) Target ratio of floating garbage to major heap size for out-of-heap memory held by custom values (e.g. bigarrays) located in the major heap. The GC speed is adjusted to try to use this much memory for dead values that are not yet collected. Expressed as a percentage of major heap size. Default: 44. Note: this only applies to values allocated with caml\_alloc\_custom\_mem.
n
(custom\_minor\_max\_size) Maximum amount of out-of-heap memory for each custom value allocated in the minor heap. When a custom value is allocated on the minor heap and holds more than this many bytes, only this value is counted against custom\_minor\_ratio and the rest is directly counted against custom\_major\_ratio. Default: 8192 bytes. Note: this only applies to values allocated with caml\_alloc\_custom\_mem.
The multiplier is k, M, or G, for multiplication by 210, 220, and 230 respectively.
o
(space\_overhead) The major GC speed setting. See the Gc module documentation for details.
p
(parser trace) Turn on debugging support for ocamlyacc-generated parsers. When this option is on, the pushdown automaton that executes the parsers prints a trace of its actions. This option takes no argument.
R
(randomize) Turn on randomization of all hash tables by default (see [Module Hashtbl](libref/hashtbl)). This option takes no argument.
s
(minor\_heap\_size) Size of the minor heap. (in words)
t
Set the trace level for the debug runtime (ignored by the standard runtime).
v
(verbose) What GC messages to print to stderr. This is a sum of values selected from the following:
1 (= 0x001)
Start and end of major GC cycle.
2 (= 0x002)
Minor collection and major GC slice.
4 (= 0x004)
Growing and shrinking of the heap.
8 (= 0x008)
Resizing of stacks and memory manager tables.
16 (= 0x010)
Heap compaction.
32 (= 0x020)
Change of GC parameters.
64 (= 0x040)
Computation of major GC slice size.
128 (= 0x080)
Calling of finalization functions
256 (= 0x100)
Startup messages (loading the bytecode executable file, resolving shared libraries).
512 (= 0x200)
Computation of compaction-triggering condition.
1024 (= 0x400)
Output GC statistics at program exit.
2048 (= 0x800)
GC debugging messages.
V
(verify\_heap) runs an integrity check on the heap just after the completion of a major GC cycle
W
Print runtime warnings to stderr (such as Channel opened on file dies without being closed, unflushed data, etc.)If the option letter is not recognized, the whole parameter is ignored; if the equal sign or the number is missing, the value is taken as 1; if the multiplier is not recognized, it is ignored.
For example, on a 32-bit machine, under bash the command
```
export OCAMLRUNPARAM='b,s=256k,v=0x015'
```
tells a subsequent ocamlrun to print backtraces for uncaught exceptions, set its initial minor heap size to 1 megabyte and print a message at the start of each major GC cycle, when the heap size changes, and when compaction is triggered.
CAMLRUNPARAM
If OCAMLRUNPARAM is not found in the environment, then CAMLRUNPARAM will be used instead. If CAMLRUNPARAM is also not found, then the default values will be used.
PATH
List of directories searched to find the bytecode executable file.
[](#s:ocamlrun-dllpath)15.3 Dynamic loading of shared libraries
-----------------------------------------------------------------
On platforms that support dynamic loading, ocamlrun can link dynamically with C shared libraries (DLLs) providing additional C primitives beyond those provided by the standard runtime system. The names for these libraries are provided at link time as described in section [22.1.4](intfc#ss%3Adynlink-c-code)), and recorded in the bytecode executable file; ocamlrun, then, locates these libraries and resolves references to their primitives when the bytecode executable program starts.
The ocamlrun command searches shared libraries in the following directories, in the order indicated:
1. Directories specified on the ocamlrun command line with the -I option.
2. Directories specified in the CAML\_LD\_LIBRARY\_PATH environment variable.
3. Directories specified at link-time via the -dllpath option to ocamlc. (These directories are recorded in the bytecode executable file.)
4. Directories specified in the file ld.conf. This file resides in the OCaml standard library directory, and lists directory names (one per line) to be searched. Typically, it contains only one line naming the stublibs subdirectory of the OCaml standard library directory. Users can add there the names of other directories containing frequently-used shared libraries; however, for consistency of installation, we recommend that shared libraries are installed directly in the system stublibs directory, rather than adding lines to the ld.conf file.
5. Default directories searched by the system dynamic loader. Under Unix, these generally include /lib and /usr/lib, plus the directories listed in the file /etc/ld.so.conf and the environment variable LD\_LIBRARY\_PATH. Under Windows, these include the Windows system directories, plus the directories listed in the PATH environment variable.
[](#s:ocamlrun-common-errors)15.4 Common errors
-------------------------------------------------
This section describes and explains the most frequently encountered error messages.
filename: no such file or directory
If filename is the name of a self-executable bytecode file, this means that either that file does not exist, or that it failed to run the ocamlrun bytecode interpreter on itself. The second possibility indicates that OCaml has not been properly installed on your system.
Cannot exec ocamlrun
(When launching a self-executable bytecode file.) The ocamlrun could not be found in the executable path. Check that OCaml has been properly installed on your system.
Cannot find the bytecode file
The file that ocamlrun is trying to execute (e.g. the file given as first non-option argument to ocamlrun) either does not exist, or is not a valid executable bytecode file.
Truncated bytecode file
The file that ocamlrun is trying to execute is not a valid executable bytecode file. Probably it has been truncated or mangled since created. Erase and rebuild it.
Uncaught exception
The program being executed contains a “stray” exception. That is, it raises an exception at some point, and this exception is never caught. This causes immediate termination of the program. The name of the exception is printed, along with its string, byte sequence, and integer arguments (arguments of more complex types are not correctly printed). To locate the context of the uncaught exception, compile the program with the -g option and either run it again under the ocamldebug debugger (see chapter [20](debugger#c%3Adebugger)), or run it with ocamlrun -b or with the OCAMLRUNPARAM environment variable set to b=1.
Out of memory
The program being executed requires more memory than available. Either the program builds excessively large data structures; or the program contains too many nested function calls, and the stack overflows. In some cases, your program is perfectly correct, it just requires more memory than your machine provides. In other cases, the “out of memory” message reveals an error in your program: non-terminating recursive function, allocation of an excessively large array, string or byte sequence, attempts to build an infinite list or other data structure, …To help you diagnose this error, run your program with the -v option to ocamlrun, or with the OCAMLRUNPARAM environment variable set to v=63. If it displays lots of “Growing stack…” messages, this is probably a looping recursive function. If it displays lots of “Growing heap…” messages, with the heap size growing slowly, this is probably an attempt to construct a data structure with too many (infinitely many?) cells. If it displays few “Growing heap…” messages, but with a huge increment in the heap size, this is probably an attempt to build an excessively large array, string or byte sequence.
| programming_docs |
ocaml None
[](#s:const)11.5 Constants
----------------------------
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| constant | ::= | [integer-literal](lex#integer-literal) |
| | ∣ | [int32-literal](lex#int32-literal) |
| | ∣ | [int64-literal](lex#int64-literal) |
| | ∣ | [nativeint-literal](lex#nativeint-literal) |
| | ∣ | [float-literal](lex#float-literal) |
| | ∣ | [char-literal](lex#char-literal) |
| | ∣ | [string-literal](lex#string-literal) |
| | ∣ | [constr](names#constr) |
| | ∣ | false |
| | ∣ | true |
| | ∣ | () |
| | ∣ | begin end |
| | ∣ | [] |
| | ∣ | [||] |
| | ∣ | `[tag-name](names#tag-name) |
|
See also the following language extension: [extension literals](extensionsyntax#ss%3Aextension-literals).
The syntactic class of constants comprises literals from the four base types (integers, floating-point numbers, characters, character strings), the integer variants, and constant constructors from both normal and polymorphic variants, as well as the special constants false, true, (), [], and [||], which behave like constant constructors, and begin end, which is equivalent to ().
ocaml Chapter 19 The documentation generator (ocamldoc) Chapter 19 The documentation generator (ocamldoc)
=================================================
* [19.1 Usage](ocamldoc#s%3Aocamldoc-usage)
* [19.2 Syntax of documentation comments](ocamldoc#s%3Aocamldoc-comments)
* [19.3 Custom generators](ocamldoc#s%3Aocamldoc-custom-generators)
* [19.4 Adding command line options](ocamldoc#s%3Aocamldoc-adding-flags)
This chapter describes OCamldoc, a tool that generates documentation from special comments embedded in source files. The comments used by OCamldoc are of the form (\*\*…\*) and follow the format described in section [19.2](#s%3Aocamldoc-comments).
OCamldoc can produce documentation in various formats: HTML, LATEX, TeXinfo, Unix man pages, and dot dependency graphs. Moreover, users can add their own custom generators, as explained in section [19.3](#s%3Aocamldoc-custom-generators).
In this chapter, we use the word *element* to refer to any of the following parts of an OCaml source file: a type declaration, a value, a module, an exception, a module type, a type constructor, a record field, a class, a class type, a class method, a class value or a class inheritance clause.
[](#s:ocamldoc-usage)19.1 Usage
---------------------------------
###
[](#ss:ocamldoc-invocation)19.1.1 Invocation
OCamldoc is invoked via the command ocamldoc, as follows:
```
ocamldoc options sourcefiles
```
####
[](#sss:ocamldoc-output)Options for choosing the output format
The following options determine the format for the generated documentation.
-html
Generate documentation in HTML default format. The generated HTML pages are stored in the current directory, or in the directory specified with the -d option. You can customize the style of the generated pages by editing the generated style.css file, or by providing your own style sheet using option -css-style. The file style.css is not generated if it already exists or if -css-style is used.
-latex
Generate documentation in LATEX default format. The generated LATEX document is saved in file ocamldoc.out, or in the file specified with the -o option. The document uses the style file ocamldoc.sty. This file is generated when using the -latex option, if it does not already exist. You can change this file to customize the style of your LATEX documentation.
-texi
Generate documentation in TeXinfo default format. The generated LATEX document is saved in file ocamldoc.out, or in the file specified with the -o option.
-man
Generate documentation as a set of Unix man pages. The generated pages are stored in the current directory, or in the directory specified with the -d option.
-dot
Generate a dependency graph for the toplevel modules, in a format suitable for displaying and processing by dot. The dot tool is available from <https://graphviz.org/>. The textual representation of the graph is written to the file ocamldoc.out, or to the file specified with the -o option. Use dot ocamldoc.out to display it.
-g file.cm[o,a,xs]
Dynamically load the given file, which defines a custom documentation generator. See section [19.4.1](#ss%3Aocamldoc-compilation-and-usage). This option is supported by the ocamldoc command (to load .cmo and .cma files) and by its native-code version ocamldoc.opt (to load .cmxs files). If the given file is a simple one and does not exist in the current directory, then ocamldoc looks for it in the custom generators default directory, and in the directories specified with optional -i options.
-customdir
Display the custom generators default directory.
-i directory
Add the given directory to the path where to look for custom generators.
####
[](#sss:ocamldoc-options)General options
-d dir
Generate files in directory dir, rather than the current directory.
-dump file
Dump collected information into file. This information can be read with the -load option in a subsequent invocation of ocamldoc.
-hide modules
Hide the given complete module names in the generated documentation. modules is a list of complete module names separated by ’,’, without blanks. For instance: Stdlib,M2.M3.
-inv-merge-ml-mli
Reverse the precedence of implementations and interfaces when merging. All elements in implementation files are kept, and the -m option indicates which parts of the comments in interface files are merged with the comments in implementation files.
-keep-code
Always keep the source code for values, methods and instance variables, when available.
-load file
Load information from file, which has been produced by ocamldoc -dump. Several -load options can be given.
-m flags
Specify merge options between interfaces and implementations. (see section [19.1.2](#ss%3Aocamldoc-merge) for details). flags can be one or several of the following characters:
d
merge description
a
merge @author
v
merge @version
l
merge @see
s
merge @since
b
merge @before
o
merge @deprecated
p
merge @param
e
merge @raise
r
merge @return
A
merge everything
-no-custom-tags
Do not allow custom @-tags (see section [19.2.5](#ss%3Aocamldoc-tags)).
-no-stop
Keep elements placed after/between the (\*\*/\*\*) special comment(s) (see section [19.2](#s%3Aocamldoc-comments)).
-o file
Output the generated documentation to file instead of ocamldoc.out. This option is meaningful only in conjunction with the -latex, -texi, or -dot options.
-pp command
Pipe sources through preprocessor command.
-impl filename
Process the file filename as an implementation file, even if its extension is not .ml.
-intf filename
Process the file filename as an interface file, even if its extension is not .mli.
-text filename
Process the file filename as a text file, even if its extension is not .txt.
-sort
Sort the list of top-level modules before generating the documentation.
-stars
Remove blank characters until the first asterisk (’\*’) in each line of comments.
-t title
Use title as the title for the generated documentation.
-intro file
Use content of file as ocamldoc text to use as introduction (HTML, LATEX and TeXinfo only). For HTML, the file is used to create the whole index.html file.
-v
Verbose mode. Display progress information.
-version
Print version string and exit.
-vnum
Print short version number and exit.
-warn-error
Treat Ocamldoc warnings as errors.
-hide-warnings
Do not print OCamldoc warnings.
-help or --help
Display a short usage summary and exit.
####
[](#sss:ocamldoc-type-checking)Type-checking options
OCamldoc calls the OCaml type-checker to obtain type information. The following options impact the type-checking phase. They have the same meaning as for the ocamlc and ocamlopt commands.
-I directory
Add directory to the list of directories search for compiled interface files (.cmi files).
-nolabels
Ignore non-optional labels in types.
-rectypes
Allow arbitrary recursive types. (See the -rectypes option to ocamlc.)
####
[](#sss:ocamldoc-html)Options for generating HTML pages
The following options apply in conjunction with the -html option:
-all-params
Display the complete list of parameters for functions and methods.
-charset charset
Add information about character encoding being charset (default is iso-8859-1).
-colorize-code
Colorize the OCaml code enclosed in [ ] and {[ ]}, using colors to emphasize keywords, etc. If the code fragments are not syntactically correct, no color is added.
-css-style filename
Use filename as the Cascading Style Sheet file.
-index-only
Generate only index files.
-short-functors
Use a short form to display functors:
```
module M : functor (A:Module) -> functor (B:Module2) -> sig .. end
```
is displayed as:
```
module M (A:Module) (B:Module2) : sig .. end
```
####
[](#sss:ocamldoc-latex)Options for generating LATEX files
The following options apply in conjunction with the -latex option:
-latex-value-prefix prefix
Give a prefix to use for the labels of the values in the generated LATEX document. The default prefix is the empty string. You can also use the options -latex-type-prefix, -latex-exception-prefix, -latex-module-prefix, -latex-module-type-prefix, -latex-class-prefix, -latex-class-type-prefix, -latex-attribute-prefix and -latex-method-prefix.These options are useful when you have, for example, a type and a value with the same name. If you do not specify prefixes, LATEX will complain about multiply defined labels.
-latextitle n,style
Associate style number n to the given LATEX sectioning command style, e.g. section or subsection. (LATEX only.) This is useful when including the generated document in another LATEX document, at a given sectioning level. The default association is 1 for section, 2 for subsection, 3 for subsubsection, 4 for paragraph and 5 for subparagraph.
-noheader
Suppress header in generated documentation.
-notoc
Do not generate a table of contents.
-notrailer
Suppress trailer in generated documentation.
-sepfiles
Generate one .tex file per toplevel module, instead of the global ocamldoc.out file.
####
[](#sss:ocamldoc-info)Options for generating TeXinfo files
The following options apply in conjunction with the -texi option:
-esc8
Escape accented characters in Info files.
-info-entry
Specify Info directory entry.
-info-section
Specify section of Info directory.
-noheader
Suppress header in generated documentation.
-noindex
Do not build index for Info files.
-notrailer
Suppress trailer in generated documentation.
####
[](#sss:ocamldoc-dot)Options for generating dot graphs
The following options apply in conjunction with the -dot option:
-dot-colors colors
Specify the colors to use in the generated dot code. When generating module dependencies, ocamldoc uses different colors for modules, depending on the directories in which they reside. When generating types dependencies, ocamldoc uses different colors for types, depending on the modules in which they are defined. colors is a list of color names separated by ’,’, as in Red,Blue,Green. The available colors are the ones supported by the dot tool.
-dot-include-all
Include all modules in the dot output, not only modules given on the command line or loaded with the -load option.
-dot-reduce
Perform a transitive reduction of the dependency graph before outputting the dot code. This can be useful if there are a lot of transitive dependencies that clutter the graph.
-dot-types
Output dot code describing the type dependency graph instead of the module dependency graph.
####
[](#sss:ocamldoc-man)Options for generating man files
The following options apply in conjunction with the -man option:
-man-mini
Generate man pages only for modules, module types, classes and class types, instead of pages for all elements.
-man-suffix suffix
Set the suffix used for generated man filenames. Default is ’3o’, as in List.3o.
-man-section section
Set the section number used for generated man filenames. Default is ’3’.
###
[](#ss:ocamldoc-merge)19.1.2 Merging of module information
Information on a module can be extracted either from the .mli or .ml file, or both, depending on the files given on the command line. When both .mli and .ml files are given for the same module, information extracted from these files is merged according to the following rules:
* Only elements (values, types, classes, ...) declared in the .mli file are kept. In other terms, definitions from the .ml file that are not exported in the .mli file are not documented.
* Descriptions of elements and descriptions in @-tags are handled as follows. If a description for the same element or in the same @-tag of the same element is present in both files, then the description of the .ml file is concatenated to the one in the .mli file, if the corresponding -m flag is given on the command line. If a description is present in the .ml file and not in the .mli file, the .ml description is kept. In either case, all the information given in the .mli file is kept.
###
[](#ss:ocamldoc-rules)19.1.3 Coding rules
The following rules must be respected in order to avoid name clashes resulting in cross-reference errors:
* In a module, there must not be two modules, two module types or a module and a module type with the same name. In the default HTML generator, modules ab and AB will be printed to the same file on case insensitive file systems.
* In a module, there must not be two classes, two class types or a class and a class type with the same name.
* In a module, there must not be two values, two types, or two exceptions with the same name.
* Values defined in tuple, as in let (x,y,z) = (1,2,3) are not kept by OCamldoc.
* Avoid the following construction:
```
open Foo (* which has a module Bar with a value x *)
module Foo =
struct
module Bar =
struct
let x = 1
end
end
let dummy = Bar.x
```
In this case, OCamldoc will associate Bar.x to the x of module Foo defined just above, instead of to the Bar.x defined in the opened module Foo.
[](#s:ocamldoc-comments)19.2 Syntax of documentation comments
---------------------------------------------------------------
Comments containing documentation material are called *special comments* and are written between (\*\* and \*). Special comments must start exactly with (\*\*. Comments beginning with ( and more than two \* are ignored.
###
[](#ss:ocamldoc-placement)19.2.1 Placement of documentation comments
OCamldoc can associate comments to some elements of the language encountered in the source files. The association is made according to the locations of comments with respect to the language elements. The locations of comments in .mli and .ml files are different.
####
[](#sss:ocamldoc-mli)Comments in .mli files
A special comment is associated to an element if it is placed before or after the element.
A special comment before an element is associated to this element if :
* There is no blank line or another special comment between the special comment and the element. However, a regular comment can occur between the special comment and the element.
* The special comment is not already associated to the previous element.
* The special comment is not the first one of a toplevel module.
A special comment after an element is associated to this element if there is no blank line or comment between the special comment and the element.
There are two exceptions: for constructors and record fields in type definitions, the associated comment can only be placed after the constructor or field definition, without blank lines or other comments between them. The special comment for a constructor with another constructor following must be placed before the ’|’ character separating the two constructors.
The following sample interface file foo.mli illustrates the placement rules for comments in .mli files.
```
(** The first special comment of the file is the comment associated
with the whole module.*)
(** Special comments can be placed between elements and are kept
by the OCamldoc tool, but are not associated to any element.
@-tags in these comments are ignored.*)
(*******************************************************************)
(** Comments like the one above, with more than two asterisks,
are ignored. *)
(** The comment for function f. *)
val f : int -> int -> int
(** The continuation of the comment for function f. *)
(** Comment for exception My_exception, even with a simple comment
between the special comment and the exception.*)
(* Hello, I'm a simple comment :-) *)
exception My_exception of (int -> int) * int
(** Comment for type weather *)
type weather =
| Rain of int (** The comment for constructor Rain *)
| Sun (** The comment for constructor Sun *)
(** Comment for type weather2 *)
type weather2 =
| Rain of int (** The comment for constructor Rain *)
| Sun (** The comment for constructor Sun *)
(** I can continue the comment for type weather2 here
because there is already a comment associated to the last constructor.*)
(** The comment for type my_record *)
type my_record = {
foo : int ; (** Comment for field foo *)
bar : string ; (** Comment for field bar *)
}
(** Continuation of comment for type my_record *)
(** Comment for foo *)
val foo : string
(** This comment is associated to foo and not to bar. *)
val bar : string
(** This comment is associated to bar. *)
(** The comment for class my_class *)
class my_class :
object
(** A comment to describe inheritance from cl *)
inherit cl
(** The comment for attribute tutu *)
val mutable tutu : string
(** The comment for attribute toto. *)
val toto : int
(** This comment is not attached to titi since
there is a blank line before titi, but is kept
as a comment in the class. *)
val titi : string
(** Comment for method toto *)
method toto : string
(** Comment for method m *)
method m : float -> int
end
(** The comment for the class type my_class_type *)
class type my_class_type =
object
(** The comment for variable x. *)
val mutable x : int
(** The comment for method m. *)
method m : int -> int
end
(** The comment for module Foo *)
module Foo :
sig
(** The comment for x *)
val x : int
(** A special comment that is kept but not associated to any element *)
end
(** The comment for module type my_module_type. *)
module type my_module_type =
sig
(** The comment for value x. *)
val x : int
(** The comment for module M. *)
module M :
sig
(** The comment for value y. *)
val y : int
(* ... *)
end
end
```
####
[](#sss:ocamldoc-comments-ml)Comments in .ml files
A special comment is associated to an element if it is placed before the element and there is no blank line between the comment and the element. Meanwhile, there can be a simple comment between the special comment and the element. There are two exceptions, for constructors and record fields in type definitions, whose associated comment must be placed after the constructor or field definition, without blank line between them. The special comment for a constructor with another constructor following must be placed before the ’|’ character separating the two constructors.
The following example of file toto.ml shows where to place comments in a .ml file.
```
(** The first special comment of the file is the comment associated
to the whole module. *)
(** The comment for function f *)
let f x y = x + y
(** This comment is not attached to any element since there is another
special comment just before the next element. *)
(** Comment for exception My_exception, even with a simple comment
between the special comment and the exception.*)
(* A simple comment. *)
exception My_exception of (int -> int) * int
(** Comment for type weather *)
type weather =
| Rain of int (** The comment for constructor Rain *)
| Sun (** The comment for constructor Sun *)
(** The comment for type my_record *)
type my_record = {
foo : int ; (** Comment for field foo *)
bar : string ; (** Comment for field bar *)
}
(** The comment for class my_class *)
class my_class =
object
(** A comment to describe inheritance from cl *)
inherit cl
(** The comment for the instance variable tutu *)
val mutable tutu = "tutu"
(** The comment for toto *)
val toto = 1
val titi = "titi"
(** Comment for method toto *)
method toto = tutu ^ "!"
(** Comment for method m *)
method m (f : float) = 1
end
(** The comment for class type my_class_type *)
class type my_class_type =
object
(** The comment for the instance variable x. *)
val mutable x : int
(** The comment for method m. *)
method m : int -> int
end
(** The comment for module Foo *)
module Foo =
struct
(** The comment for x *)
let x = 0
(** A special comment in the class, but not associated to any element. *)
end
(** The comment for module type my_module_type. *)
module type my_module_type =
sig
(* Comment for value x. *)
val x : int
(* ... *)
end
```
###
[](#ss:ocamldoc-stop)19.2.2 The Stop special comment
The special comment (\*\*/\*\*) tells OCamldoc to discard elements placed after this comment, up to the end of the current class, class type, module or module type, or up to the next stop comment. For instance:
```
class type foo =
object
(** comment for method m *)
method m : string
(**/**)
(** This method won't appear in the documentation *)
method bar : int
end
(** This value appears in the documentation, since the Stop special comment
in the class does not affect the parent module of the class.*)
val foo : string
(**/**)
(** The value bar does not appear in the documentation.*)
val bar : string
(**/**)
(** The type t appears since in the documentation since the previous stop comment
toggled off the "no documentation mode". *)
type t = string
```
The -no-stop option to ocamldoc causes the Stop special comments to be ignored.
###
[](#ss:ocamldoc-syntax)19.2.3 Syntax of documentation comments
The inside of documentation comments (\*\*…\*) consists of free-form text with optional formatting annotations, followed by optional *tags* giving more specific information about parameters, version, authors, … The tags are distinguished by a leading @ character. Thus, a documentation comment has the following shape:
```
(** The comment begins with a description, which is text formatted
according to the rules described in the next section.
The description continues until the first non-escaped '@' character.
@author Mr Smith
@param x description for parameter x
*)
```
Some elements support only a subset of all @-tags. Tags that are not relevant to the documented element are simply ignored. For instance, all tags are ignored when documenting type constructors, record fields, and class inheritance clauses. Similarly, a @param tag on a class instance variable is ignored.
At last, (\*\*) is the empty documentation comment.
###
[](#ss:ocamldoc-formatting)19.2.4 Text formatting
Here is the BNF grammar for the simple markup language used to format text descriptions.
| | | | | |
| --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| text | ::= | {[text-element](#text-element)}+ |
| |
|
| | | | | |
| --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| inline-text | ::= | {[inline-text-element](#inline-text-element)}+ |
| |
|
| | |
| --- | --- |
| text-element | ::= |
| | | |
| --- | --- | --- |
| ∣ | [inline-text-element](#inline-text-element) | |
| ∣ | blank-line | force a new line. |
| | |
| --- | --- |
| inline-text-element | ::= |
| | | |
| --- | --- | --- |
| ∣ | { { 0 … 9 }+ [inline-text](#inline-text) } | format [text](#text) as a section header; the integer following { indicates the sectioning level. |
| ∣ | { { 0 … 9 }+ : label [inline-text](#inline-text) } | same, but also associate the name label to the current point. This point can be referenced by its fully-qualified label in a {! command, just like any other element. |
| ∣ | {b [inline-text](#inline-text) } | set [text](#text) in bold. |
| ∣ | {i [inline-text](#inline-text) } | set [text](#text) in italic. |
| ∣ | {e [inline-text](#inline-text) } | emphasize [text](#text). |
| ∣ | {C [inline-text](#inline-text) } | center [text](#text). |
| ∣ | {L [inline-text](#inline-text) } | left align [text](#text). |
| ∣ | {R [inline-text](#inline-text) } | right align [text](#text). |
| ∣ | {ul [list](#list) } | build a list. |
| ∣ | {ol [list](#list) } | build an enumerated list. |
| ∣ | {{: string } [inline-text](#inline-text) } | put a link to the given address (given as string) on the given [text](#text). |
| ∣ | [ string ] | set the given string in source code style. |
| ∣ | {[ string ]} | set the given string in preformatted source code style. |
| ∣ | {v string v} | set the given string in verbatim style. |
| ∣ | {% string %} | target-specific content (LATEX code by default, see details in [19.2.4.4](#sss%3Aocamldoc-target-specific-syntax)) |
| ∣ | {! string } | insert a cross-reference to an element (see section [19.2.4.2](#sss%3Aocamldoc-crossref) for the syntax of cross-references). |
| ∣ | {{! string } [inline-text](#inline-text) } | insert a cross-reference with the given text. |
| ∣ | {!modules: string string ... } | insert an index table for the given module names. Used in HTML only. |
| ∣ | {!indexlist} | insert a table of links to the various indexes (types, values, modules, ...). Used in HTML only. |
| ∣ | {^ [inline-text](#inline-text) } | set text in superscript. |
| ∣ | {\_ [inline-text](#inline-text) } | set text in subscript. |
| ∣ | escaped-string | typeset the given string as is; special characters (’{’, ’}’, ’[’, ’]’ and ’@’) must be escaped by a ’\’ |
####
[](#sss:ocamldoc-list)19.2.4.1 List formatting
| | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| list | ::= | |
| | ∣ | { {- [inline-text](#inline-text) } }+ |
| | ∣ | { {li [inline-text](#inline-text) } }+ |
|
A shortcut syntax exists for lists and enumerated lists:
```
(** Here is a {b list}
- item 1
- item 2
- item 3
The list is ended by the blank line.*)
```
is equivalent to:
```
(** Here is a {b list}
{ul {- item 1}
{- item 2}
{- item 3}}
The list is ended by the blank line.*)
```
The same shortcut is available for enumerated lists, using ’+’ instead of ’-’. Note that only one list can be defined by this shortcut in nested lists.
####
[](#sss:ocamldoc-crossref)19.2.4.2 Cross-reference formatting
Cross-references are fully qualified element names, as in the example {!Foo.Bar.t}. This is an ambiguous reference as it may designate a type name, a value name, a class name, etc. It is possible to make explicit the intended syntactic class, using {!type:Foo.Bar.t} to designate a type, and {!val:Foo.Bar.t} a value of the same name.
The list of possible syntactic class is as follows:
| | |
| --- | --- |
| tag | syntactic class |
| |
| module: | module |
| modtype: | module type |
| class: | class |
| classtype: | class type |
| val: | value |
| type: | type |
| exception: | exception |
| attribute: | attribute |
| method: | class method |
| section: | ocamldoc section |
| const: | variant constructor |
| recfield: | record field |
In the case of variant constructors or record field, the constructor or field name should be preceded by the name of the correspond type – to avoid the ambiguity of several types having the same constructor names. For example, the constructor Node of the type tree will be referenced as {!tree.Node} or {!const:tree.Node}, or possibly {!Mod1.Mod2.tree.Node} from outside the module.
####
[](#sss:ocamldoc-preamble)19.2.4.3 First sentence
In the description of a value, type, exception, module, module type, class or class type, the *first sentence* is sometimes used in indexes, or when just a part of the description is needed. The first sentence is composed of the first characters of the description, until
* the first dot followed by a blank, or
* the first blank line
outside of the following text formatting : {ul [list](#list) } , {ol [list](#list) } , [ string ] , {[ string ]} , {v string v} , {% string %} , {! string } , {^ [text](#text) } , {\_ [text](#text) } .
####
[](#sss:ocamldoc-target-specific-syntax)19.2.4.4 Target-specific formatting
The content inside {%foo: ... %} is target-specific and will only be interpreted by the backend foo, and ignored by the others. The backends of the distribution are latex, html, texi and man. If no target is specified (syntax {% ... %}), latex is chosen by default. Custom generators may support their own target prefix.
####
[](#sss:ocamldoc-html-tags)19.2.4.5 Recognized HTML tags
The HTML tags <b>..</b>, <code>..</code>, <i>..</i>, <ul>..</ul>, <ol>..</ol>, <li>..</li>, <center>..</center> and <h[0-9]>..</h[0-9]> can be used instead of, respectively, {b ..} , [..] , {i ..} , {ul ..} , {ol ..} , {li ..} , {C ..} and {[0-9] ..}.
###
[](#ss:ocamldoc-tags)19.2.5 Documentation tags (@-tags)
####
[](#sss:ocamldoc-builtin-tags)Predefined tags
The following table gives the list of predefined @-tags, with their syntax and meaning.
| | |
| --- | --- |
| @author string | The author of the element. One author per @author tag. There may be several @author tags for the same element. |
| @deprecated [text](#text) | The [text](#text) should describe when the element was deprecated, what to use as a replacement, and possibly the reason for deprecation. |
| @param id [text](#text) | Associate the given description ([text](#text)) to the given parameter name id. This tag is used for functions, methods, classes and functors. |
| @raise Exc [text](#text) | Explain that the element may raise the exception Exc. |
| @return [text](#text) | Describe the return value and its possible values. This tag is used for functions and methods. |
| @see < URL > [text](#text) | Add a reference to the URL with the given [text](#text) as comment. |
| @see 'filename' [text](#text) | Add a reference to the given file name (written between single quotes), with the given [text](#text) as comment. |
| @see "document-name" [text](#text) | Add a reference to the given document name (written between double quotes), with the given [text](#text) as comment. |
| @since string | Indicate when the element was introduced. |
| @before version [text](#text) | Associate the given description ([text](#text)) to the given version in order to document compatibility issues. |
| @version string | The version number for the element. |
####
[](#sss:ocamldoc-custom-tags)Custom tags
You can use custom tags in the documentation comments, but they will have no effect if the generator used does not handle them. To use a custom tag, for example foo, just put @foo with some text in your comment, as in:
```
(** My comment to show you a custom tag.
@foo this is the text argument to the [foo] custom tag.
*)
```
To handle custom tags, you need to define a custom generator, as explained in section [19.3.2](#ss%3Aocamldoc-handling-custom-tags).
[](#s:ocamldoc-custom-generators)19.3 Custom generators
---------------------------------------------------------
OCamldoc operates in two steps:
1. analysis of the source files;
2. generation of documentation, through a documentation generator, which is an object of class Odoc\_args.class\_generator.
Users can provide their own documentation generator to be used during step 2 instead of the default generators. All the information retrieved during the analysis step is available through the Odoc\_info module, which gives access to all the types and functions representing the elements found in the given modules, with their associated description.
The files you can use to define custom generators are installed in the ocamldoc sub-directory of the OCaml standard library.
###
[](#ss:ocamldoc-generators)19.3.1 The generator modules
The type of a generator module depends on the kind of generated documentation. Here is the list of generator module types, with the name of the generator class in the module :
* for HTML : Odoc\_html.Html\_generator (class html),
* for LATEX : Odoc\_latex.Latex\_generator (class latex),
* for TeXinfo : Odoc\_texi.Texi\_generator (class texi),
* for man pages : Odoc\_man.Man\_generator (class man),
* for graphviz (dot) : Odoc\_dot.Dot\_generator (class dot),
* for other kinds : Odoc\_gen.Base (class generator).
That is, to define a new generator, one must implement a module with the expected signature, and with the given generator class, providing the generate method as entry point to make the generator generates documentation for a given list of modules :
```
method generate : Odoc_info.Module.t_module list -> unit
```
This method will be called with the list of analysed and possibly merged Odoc\_info.t\_module structures.
It is recommended to inherit from the current generator of the same kind as the one you want to define. Doing so, it is possible to load various custom generators to combine improvements brought by each one.
This is done using first class modules (see chapter [12.5](firstclassmodules#s%3Afirst-class-modules)).
The easiest way to define a custom generator is the following this example, here extending the current HTML generator. We don’t have to know if this is the original HTML generator defined in ocamldoc or if it has been extended already by a previously loaded custom generator :
```
module Generator (G : Odoc_html.Html_generator) =
struct
class html =
object(self)
inherit G.html as html
(* ... *)
method generate module_list =
(* ... *)
()
(* ... *)
end
end;;
let _ = Odoc_args.extend_html_generator (module Generator : Odoc_gen.Html_functor);;
```
To know which methods to override and/or which methods are available, have a look at the different base implementations, depending on the kind of generator you are extending :
* for HTML : [odoc\_html.ml](https://github.com/ocaml/ocaml/blob/5.0/ocamldoc/odoc_html.ml),
* for LATEX : [odoc\_latex.ml](https://github.com/ocaml/ocaml/blob/5.0/ocamldoc/odoc_latex.ml),
* for TeXinfo : [odoc\_texi.ml](https://github.com/ocaml/ocaml/blob/5.0/ocamldoc/odoc_texi.ml),
* for man pages : [odoc\_man.ml](https://github.com/ocaml/ocaml/blob/5.0/ocamldoc/odoc_man.ml),
* for graphviz (dot) : [odoc\_dot.ml](https://github.com/ocaml/ocaml/blob/5.0/ocamldoc/odoc_dot.ml).
###
[](#ss:ocamldoc-handling-custom-tags)19.3.2 Handling custom tags
Making a custom generator handle custom tags (see [19.2.5](#sss%3Aocamldoc-custom-tags)) is very simple.
####
[](#sss:ocamldoc-html-generator)For HTML
Here is how to develop a HTML generator handling your custom tags.
The class Odoc\_html.Generator.html inherits from the class Odoc\_html.info, containing a field tag\_functions which is a list pairs composed of a custom tag (e.g. "foo") and a function taking a text and returning HTML code (of type string). To handle a new tag bar, extend the current HTML generator and complete the tag\_functions field:
```
module Generator (G : Odoc_html.Html_generator) =
struct
class html =
object(self)
inherit G.html
(** Return HTML code for the given text of a bar tag. *)
method html_of_bar t = (* your code here *)
initializer
tag_functions <- ("bar", self#html_of_bar) :: tag_functions
end
end
let _ = Odoc_args.extend_html_generator (module Generator : Odoc_gen.Html_functor);;
```
Another method of the class Odoc\_html.info will look for the function associated to a custom tag and apply it to the text given to the tag. If no function is associated to a custom tag, then the method prints a warning message on stderr.
####
[](#sss:ocamldoc-other-generators)For other generators
You can act the same way for other kinds of generators.
[](#s:ocamldoc-adding-flags)19.4 Adding command line options
--------------------------------------------------------------
The command line analysis is performed after loading the module containing the documentation generator, thus allowing command line options to be added to the list of existing ones. Adding an option can be done with the function
```
Odoc_args.add_option : string * Arg.spec * string -> unit
```
Note: Existing command line options can be redefined using this function.
###
[](#ss:ocamldoc-compilation-and-usage)19.4.1 Compilation and usage
####
[](#sss:ocamldoc-generator-class)Defining a custom generator class in one file
Let custom.ml be the file defining a new generator class. Compilation of custom.ml can be performed by the following command :
```
ocamlc -I +ocamldoc -c custom.ml
```
The file custom.cmo is created and can be used this way :
```
ocamldoc -g custom.cmo other-options source-files
```
Options selecting a built-in generator to ocamldoc, such as -html, have no effect if a custom generator of the same kind is provided using -g. If the kinds do not match, the selected built-in generator is used and the custom one is ignored.
####
[](#sss:ocamldoc-modular-generator)Defining a custom generator class in several files
It is possible to define a generator class in several modules, which are defined in several files file1.ml[i], file2.ml[i], ..., filen.ml[i]. A .cma library file must be created, including all these files.
The following commands create the custom.cma file from files file1.ml[i], ..., filen.ml[i] :
```
ocamlc -I +ocamldoc -c file1.ml[i]
ocamlc -I +ocamldoc -c file2.ml[i]
...
ocamlc -I +ocamldoc -c filen.ml[i]
ocamlc -o custom.cma -a file1.cmo file2.cmo ... filen.cmo
```
Then, the following command uses custom.cma as custom generator:
```
ocamldoc -g custom.cma other-options source-files
```
| programming_docs |
ocaml None
[](#s:alerts)12.21 Alerts
---------------------------
(Introduced in 4.08)
Since OCaml 4.08, it is possible to mark components (such as value or type declarations) in signatures with “alerts” that will be reported when those components are referenced. This generalizes the notion of “deprecated” components which were previously reported as warning 3. Those alerts can be used for instance to report usage of unsafe features, or of features which are only available on some platforms, etc.
Alert categories are identified by a symbolic identifier (a lowercase identifier, following the usual lexical rules) and an optional message. The identifier is used to control which alerts are enabled, and which ones are turned into fatal errors. The message is reported to the user when the alert is triggered (i.e. when the marked component is referenced).
The ocaml.alert or alert attribute serves two purposes: (i) to mark component with an alert to be triggered when the component is referenced, and (ii) to control which alert names are enabled. In the first form, the attribute takes an identifier possibly followed by a message. Here is an example of a value declaration marked with an alert:
```
module U: sig
val fork: unit -> bool
[@@alert unix "This function is only available under Unix."]
end
```
Here unix is the identifier for the alert. If this alert category is enabled, any reference to U.fork will produce a message at compile time, which can be turned or not into a fatal error.
And here is another example as a floating attribute on top of an “.mli” file (i.e. before any other non-attribute item) or on top of an “.ml” file without a corresponding interface file, so that any reference to that unit will trigger the alert:
```
[@@@alert unsafe "This module is unsafe!"]
```
Controlling which alerts are enabled and whether they are turned into fatal errors is done either through the compiler’s command-line option -alert <spec> or locally in the code through the alert or ocaml.alert attribute taking a single string payload <spec>. In both cases, the syntax for <spec> is a concatenation of items of the form:
* +id enables alert id.
* -id disables alert id.
* ++id turns alert id into a fatal error.
* --id turns alert id into non-fatal mode.
* @id equivalent to ++id+id (enables id and turns it into a fatal-error)
As a special case, if id is all, it stands for all alerts.
Here are some examples:
```
(* Disable all alerts, reenables just unix (as a soft alert) and window
(as a fatal-error), for the rest of the current structure *)
[@@@alert "-all--all+unix@window"]
...
let x =
(* Locally disable the window alert *)
begin[@alert "-window"]
...
end
```
Before OCaml 4.08, there was support for a single kind of deprecation alert. It is now known as the deprecated alert, but legacy attributes to trigger it and the legacy ways to control it as warning 3 are still supported. For instance, passing -w +3 on the command-line is equivant to -alert +deprecated, and:
```
val x: int
[@@@ocaml.deprecated "Please do something else"]
```
is equivalent to:
```
val x: int
[@@@ocaml.alert deprecated "Please do something else"]
```
ocaml Chapter 20 The debugger (ocamldebug) Chapter 20 The debugger (ocamldebug)
====================================
* [20.1 Compiling for debugging](debugger#s%3Adebugger-compilation)
* [20.2 Invocation](debugger#s%3Adebugger-invocation)
* [20.3 Commands](debugger#s%3Adebugger-commands)
* [20.4 Executing a program](debugger#s%3Adebugger-execution)
* [20.5 Breakpoints](debugger#s%3Abreakpoints)
* [20.6 The call stack](debugger#s%3Adebugger-callstack)
* [20.7 Examining variable values](debugger#s%3Adebugger-examining-values)
* [20.8 Controlling the debugger](debugger#s%3Adebugger-control)
* [20.9 Miscellaneous commands](debugger#s%3Adebugger-misc-cmds)
* [20.10 Running the debugger under Emacs](debugger#s%3Ainf-debugger)
This chapter describes the OCaml source-level replay debugger ocamldebug.
>
> Unix: The debugger is available on Unix systems that provide BSD sockets.
>
> Windows: The debugger is available under the Cygwin port of OCaml, but not under the native Win32 ports.
[](#s:debugger-compilation)20.1 Compiling for debugging
---------------------------------------------------------
Before the debugger can be used, the program must be compiled and linked with the -g option: all .cmo and .cma files that are part of the program should have been created with ocamlc -g, and they must be linked together with ocamlc -g.
Compiling with -g entails no penalty on the running time of programs: object files and bytecode executable files are bigger and take longer to produce, but the executable files run at exactly the same speed as if they had been compiled without -g.
[](#s:debugger-invocation)20.2 Invocation
-------------------------------------------
###
[](#ss:debugger-start)20.2.1 Starting the debugger
The OCaml debugger is invoked by running the program ocamldebug with the name of the bytecode executable file as first argument:
```
ocamldebug [options] program [arguments]
```
The arguments following program are optional, and are passed as command-line arguments to the program being debugged. (See also the set arguments command.)
The following command-line options are recognized:
-c count
Set the maximum number of simultaneously live checkpoints to count.
-cd dir
Run the debugger program from the working directory dir, instead of the current directory. (See also the cd command.)
-emacs
Tell the debugger it is executed under Emacs. (See section [20.10](#s%3Ainf-debugger) for information on how to run the debugger under Emacs.)
-I directory
Add directory to the list of directories searched for source files and compiled files. (See also the directory command.)
-s socket
Use socket for communicating with the debugged program. See the description of the command set socket (section [20.8.8](#ss%3Adebugger-communication)) for the format of socket.
-version
Print version string and exit.
-vnum
Print short version number and exit.
-help or --help
Display a short usage summary and exit.
###
[](#ss:debugger-init-file)20.2.2 Initialization file
On start-up, the debugger will read commands from an initialization file before giving control to the user. The default file is .ocamldebug in the current directory if it exists, otherwise .ocamldebug in the user’s home directory.
###
[](#ss:debugger-exut)20.2.3 Exiting the debugger
The command quit exits the debugger. You can also exit the debugger by typing an end-of-file character (usually ctrl-D).
Typing an interrupt character (usually ctrl-C) will not exit the debugger, but will terminate the action of any debugger command that is in progress and return to the debugger command level.
[](#s:debugger-commands)20.3 Commands
---------------------------------------
A debugger command is a single line of input. It starts with a command name, which is followed by arguments depending on this name. Examples:
```
run
goto 1000
set arguments arg1 arg2
```
A command name can be truncated as long as there is no ambiguity. For instance, go 1000 is understood as goto 1000, since there are no other commands whose name starts with go. For the most frequently used commands, ambiguous abbreviations are allowed. For instance, r stands for run even though there are others commands starting with r. You can test the validity of an abbreviation using the help command.
If the previous command has been successful, a blank line (typing just RET) will repeat it.
###
[](#ss:debugger-help)20.3.1 Getting help
The OCaml debugger has a simple on-line help system, which gives a brief description of each command and variable.
help
Print the list of commands.
help command
Give help about the command command.
help set variable, help show variable
Give help about the variable variable. The list of all debugger variables can be obtained with help set.
help info topic
Give help about topic. Use help info to get a list of known topics.
###
[](#ss:debugger-state)20.3.2 Accessing the debugger state
set variable value
Set the debugger variable variable to the value value.
show variable
Print the value of the debugger variable variable.
info subject
Give information about the given subject. For instance, info breakpoints will print the list of all breakpoints.
[](#s:debugger-execution)20.4 Executing a program
---------------------------------------------------
###
[](#ss:debugger-events)20.4.1 Events
Events are “interesting” locations in the source code, corresponding to the beginning or end of evaluation of “interesting” sub-expressions. Events are the unit of single-stepping (stepping goes to the next or previous event encountered in the program execution). Also, breakpoints can only be set at events. Thus, events play the role of line numbers in debuggers for conventional languages.
During program execution, a counter is incremented at each event encountered. The value of this counter is referred as the *current time*. Thanks to reverse execution, it is possible to jump back and forth to any time of the execution.
Here is where the debugger events (written ⋈) are located in the source code:
* Following a function application:
```
(f arg)⋈
```
* On entrance to a function:
```
fun x y z -> ⋈ ...
```
* On each case of a pattern-matching definition (function, match…with construct, try…with construct):
```
function pat1 -> ⋈ expr1
| ...
| patN -> ⋈ exprN
```
* Between subexpressions of a sequence:
```
expr1; ⋈ expr2; ⋈ ...; ⋈ exprN
```
* In the two branches of a conditional expression:
```
if cond then ⋈ expr1 else ⋈ expr2
```
* At the beginning of each iteration of a loop:
```
while cond do ⋈ body done
for i = a to b do ⋈ body done
```
Exceptions: A function application followed by a function return is replaced by the compiler by a jump (tail-call optimization). In this case, no event is put after the function application.
###
[](#ss:debugger-starting-program)20.4.2 Starting the debugged program
The debugger starts executing the debugged program only when needed. This allows setting breakpoints or assigning debugger variables before execution starts. There are several ways to start execution:
run
Run the program until a breakpoint is hit, or the program terminates.
goto 0
Load the program and stop on the first event.
goto time
Load the program and execute it until the given time. Useful when you already know approximately at what time the problem appears. Also useful to set breakpoints on function values that have not been computed at time 0 (see section [20.5](#s%3Abreakpoints)).
The execution of a program is affected by certain information it receives when the debugger starts it, such as the command-line arguments to the program and its working directory. The debugger provides commands to specify this information (set arguments and cd). These commands must be used before program execution starts. If you try to change the arguments or the working directory after starting your program, the debugger will kill the program (after asking for confirmation).
###
[](#ss:debugger-running)20.4.3 Running the program
The following commands execute the program forward or backward, starting at the current time. The execution will stop either when specified by the command or when a breakpoint is encountered.
run
Execute the program forward from current time. Stops at next breakpoint or when the program terminates.
reverse
Execute the program backward from current time. Mostly useful to go to the last breakpoint encountered before the current time.
step [count]
Run the program and stop at the next event. With an argument, do it count times. If count is 0, run until the program terminates or a breakpoint is hit.
backstep [count]
Run the program backward and stop at the previous event. With an argument, do it count times.
next [count]
Run the program and stop at the next event, skipping over function calls. With an argument, do it count times.
previous [count]
Run the program backward and stop at the previous event, skipping over function calls. With an argument, do it count times.
finish
Run the program until the current function returns.
start
Run the program backward and stop at the first event before the current function invocation.
###
[](#ss:debugger-time-travel)20.4.4 Time travel
You can jump directly to a given time, without stopping on breakpoints, using the goto command.
As you move through the program, the debugger maintains an history of the successive times you stop at. The last command can be used to revisit these times: each last command moves one step back through the history. That is useful mainly to undo commands such as step and next.
goto time
Jump to the given time.
last [count]
Go back to the latest time recorded in the execution history. With an argument, do it count times.
set history size
Set the size of the execution history.
###
[](#ss:debugger-kill)20.4.5 Killing the program
kill
Kill the program being executed. This command is mainly useful if you wish to recompile the program without leaving the debugger.
[](#s:breakpoints)20.5 Breakpoints
------------------------------------
A breakpoint causes the program to stop whenever a certain point in the program is reached. It can be set in several ways using the break command. Breakpoints are assigned numbers when set, for further reference. The most comfortable way to set breakpoints is through the Emacs interface (see section [20.10](#s%3Ainf-debugger)).
break
Set a breakpoint at the current position in the program execution. The current position must be on an event (i.e., neither at the beginning, nor at the end of the program).
break function
Set a breakpoint at the beginning of function. This works only when the functional value of the identifier function has been computed and assigned to the identifier. Hence this command cannot be used at the very beginning of the program execution, when all identifiers are still undefined; use goto time to advance execution until the functional value is available.
break @ [module] line
Set a breakpoint in module module (or in the current module if module is not given), at the first event of line line.
break @ [module] line column
Set a breakpoint in module module (or in the current module if module is not given), at the event closest to line line, column column.
break @ [module] # character
Set a breakpoint in module module at the event closest to character number character.
break frag:pc, break pc
Set a breakpoint at code address frag:pc. The integer frag is the identifier of a code fragment, a set of modules that have been loaded at once, either initially or with the Dynlink module. The integer pc is the instruction counter within this code fragment. If frag is omitted, it defaults to 0, which is the code fragment of the program loaded initially.
delete [breakpoint-numbers]
Delete the specified breakpoints. Without argument, all breakpoints are deleted (after asking for confirmation).
info breakpoints
Print the list of all breakpoints.
[](#s:debugger-callstack)20.6 The call stack
----------------------------------------------
Each time the program performs a function application, it saves the location of the application (the return address) in a block of data called a stack frame. The frame also contains the local variables of the caller function. All the frames are allocated in a region of memory called the call stack. The command backtrace (or bt) displays parts of the call stack.
At any time, one of the stack frames is “selected” by the debugger; several debugger commands refer implicitly to the selected frame. In particular, whenever you ask the debugger for the value of a local variable, the value is found in the selected frame. The commands frame, up and down select whichever frame you are interested in.
When the program stops, the debugger automatically selects the currently executing frame and describes it briefly as the frame command does.
frame
Describe the currently selected stack frame.
frame frame-number
Select a stack frame by number and describe it. The frame currently executing when the program stopped has number 0; its caller has number 1; and so on up the call stack.
backtrace [count], bt [count]
Print the call stack. This is useful to see which sequence of function calls led to the currently executing frame. With a positive argument, print only the innermost count frames. With a negative argument, print only the outermost -count frames.
up [count]
Select and display the stack frame just “above” the selected frame, that is, the frame that called the selected frame. An argument says how many frames to go up.
down [count]
Select and display the stack frame just “below” the selected frame, that is, the frame that was called by the selected frame. An argument says how many frames to go down.
[](#s:debugger-examining-values)20.7 Examining variable values
----------------------------------------------------------------
The debugger can print the current value of simple expressions. The expressions can involve program variables: all the identifiers that are in scope at the selected program point can be accessed.
Expressions that can be printed are a subset of OCaml expressions, as described by the following grammar:
| | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| simple-expr | ::= | [lowercase-ident](lex#lowercase-ident) |
| | ∣ | { [capitalized-ident](lex#capitalized-ident) . } [lowercase-ident](lex#lowercase-ident) |
| | ∣ | \* |
| | ∣ | $ integer |
| | ∣ | [simple-expr](#simple-expr) . [lowercase-ident](lex#lowercase-ident) |
| | ∣ | [simple-expr](#simple-expr) .( integer ) |
| | ∣ | [simple-expr](#simple-expr) .[ integer ] |
| | ∣ | ! [simple-expr](#simple-expr) |
| | ∣ | ( [simple-expr](#simple-expr) ) |
|
The first two cases refer to a value identifier, either unqualified or qualified by the path to the structure that define it. \* refers to the result just computed (typically, the value of a function application), and is valid only if the selected event is an “after” event (typically, a function application). $ integer refer to a previously printed value. The remaining four forms select part of an expression: respectively, a record field, an array element, a string element, and the current contents of a reference.
print variables
Print the values of the given variables. print can be abbreviated as p.
display variables
Same as print, but limit the depth of printing to 1. Useful to browse large data structures without printing them in full. display can be abbreviated as d.
When printing a complex expression, a name of the form $integer is automatically assigned to its value. Such names are also assigned to parts of the value that cannot be printed because the maximal printing depth is exceeded. Named values can be printed later on with the commands p $integer or d $integer. Named values are valid only as long as the program is stopped. They are forgotten as soon as the program resumes execution.
set print\_depth d
Limit the printing of values to a maximal depth of d.
set print\_length l
Limit the printing of values to at most l nodes printed.
[](#s:debugger-control)20.8 Controlling the debugger
------------------------------------------------------
###
[](#ss:debugger-name-and-arguments)20.8.1 Setting the program name and arguments
set program file
Set the program name to file.
set arguments arguments
Give arguments as command-line arguments for the program.
A shell is used to pass the arguments to the debugged program. You can therefore use wildcards, shell variables, and file redirections inside the arguments. To debug programs that read from standard input, it is recommended to redirect their input from a file (using set arguments < input-file), otherwise input to the program and input to the debugger are not properly separated, and inputs are not properly replayed when running the program backwards.
###
[](#ss:debugger-loading)20.8.2 How programs are loaded
The loadingmode variable controls how the program is executed.
set loadingmode direct
The program is run directly by the debugger. This is the default mode.
set loadingmode runtime
The debugger execute the OCaml runtime ocamlrun on the program. Rarely useful; moreover it prevents the debugging of programs compiled in “custom runtime” mode.
set loadingmode manual
The user starts manually the program, when asked by the debugger. Allows remote debugging (see section [20.8.8](#ss%3Adebugger-communication)).
###
[](#ss:debugger-search-path)20.8.3 Search path for files
The debugger searches for source files and compiled interface files in a list of directories, the search path. The search path initially contains the current directory . and the standard library directory. The directory command adds directories to the path.
Whenever the search path is modified, the debugger will clear any information it may have cached about the files.
directory directorynames
Add the given directories to the search path. These directories are added at the front, and will therefore be searched first.
directory directorynames for modulename
Same as directory directorynames, but the given directories will be searched only when looking for the source file of a module that has been packed into modulename.
directory
Reset the search path. This requires confirmation.
###
[](#ss:debugger-working-dir)20.8.4 Working directory
Each time a program is started in the debugger, it inherits its working directory from the current working directory of the debugger. This working directory is initially whatever it inherited from its parent process (typically the shell), but you can specify a new working directory in the debugger with the cd command or the -cd command-line option.
cd directory
Set the working directory for ocamldebug to directory.
pwd
Print the working directory for ocamldebug.
###
[](#ss:debugger-reverse-execution)20.8.5 Turning reverse execution on and off
In some cases, you may want to turn reverse execution off. This speeds up the program execution, and is also sometimes useful for interactive programs.
Normally, the debugger takes checkpoints of the program state from time to time. That is, it makes a copy of the current state of the program (using the Unix system call fork). If the variable checkpoints is set to off, the debugger will not take any checkpoints.
set checkpoints on/off
Select whether the debugger makes checkpoints or not.
###
[](#ss:debugger-fork)20.8.6 Behavior of the debugger with respect to fork
When the program issues a call to fork, the debugger can either follow the child or the parent. By default, the debugger follows the parent process. The variable follow\_fork\_mode controls this behavior:
set follow\_fork\_mode child/parent
Select whether to follow the child or the parent in case of a call to fork.
###
[](#ss:debugger-stop-at-new-load)20.8.7 Stopping execution when new code is loaded
The debugger is compatible with the Dynlink module. However, when an external module is not yet loaded, it is impossible to set a breakpoint in its code. In order to facilitate setting breakpoints in dynamically loaded code, the debugger stops the program each time new modules are loaded. This behavior can be disabled using the break\_on\_load variable:
set break\_on\_load on/off
Select whether to stop after loading new code.
###
[](#ss:debugger-communication)20.8.8 Communication between the debugger and the program
The debugger communicate with the program being debugged through a Unix socket. You may need to change the socket name, for example if you need to run the debugger on a machine and your program on another.
set socket socket
Use socket for communication with the program. socket can be either a file name, or an Internet port specification host:port, where host is a host name or an Internet address in dot notation, and port is a port number on the host.
On the debugged program side, the socket name is passed through the CAML\_DEBUG\_SOCKET environment variable.
###
[](#ss:debugger-fine-tuning)20.8.9 Fine-tuning the debugger
Several variables enables to fine-tune the debugger. Reasonable defaults are provided, and you should normally not have to change them.
set processcount count
Set the maximum number of checkpoints to count. More checkpoints facilitate going far back in time, but use more memory and create more Unix processes.
As checkpointing is quite expensive, it must not be done too often. On the other hand, backward execution is faster when checkpoints are taken more often. In particular, backward single-stepping is more responsive when many checkpoints have been taken just before the current time. To fine-tune the checkpointing strategy, the debugger does not take checkpoints at the same frequency for long displacements (e.g. run) and small ones (e.g. step). The two variables bigstep and smallstep contain the number of events between two checkpoints in each case.
set bigstep count
Set the number of events between two checkpoints for long displacements.
set smallstep count
Set the number of events between two checkpoints for small displacements.
The following commands display information on checkpoints and events:
info checkpoints
Print a list of checkpoints.
info events [module]
Print the list of events in the given module (the current module, by default).
###
[](#ss:debugger-printers)20.8.10 User-defined printers
Just as in the toplevel system (section [14.2](toplevel#s%3Atoplevel-directives)), the user can register functions for printing values of certain types. For technical reasons, the debugger cannot call printing functions that reside in the program being debugged. The code for the printing functions must therefore be loaded explicitly in the debugger.
load\_printer "file-name"
Load in the debugger the indicated .cmo or .cma object file. The file is loaded in an environment consisting only of the OCaml standard library plus the definitions provided by object files previously loaded using load\_printer. If this file depends on other object files not yet loaded, the debugger automatically loads them if it is able to find them in the search path. The loaded file does not have direct access to the modules of the program being debugged.
install\_printer printer-name
Register the function named printer-name (a value path) as a printer for objects whose types match the argument type of the function. That is, the debugger will call printer-name when it has such an object to print. The printing function printer-name must use the Format library module to produce its output, otherwise its output will not be correctly located in the values printed by the toplevel loop.The value path printer-name must refer to one of the functions defined by the object files loaded using load\_printer. It cannot reference the functions of the program being debugged.
remove\_printer printer-name
Remove the named function from the table of value printers.
[](#s:debugger-misc-cmds)20.9 Miscellaneous commands
------------------------------------------------------
list [module] [beginning] [end]
List the source of module module, from line number beginning to line number end. By default, 20 lines of the current module are displayed, starting 10 lines before the current position.
source filename
Read debugger commands from the script filename.
[](#s:inf-debugger)20.10 Running the debugger under Emacs
-----------------------------------------------------------
The most user-friendly way to use the debugger is to run it under Emacs with the OCaml mode available through MELPA and also at <https://github.com/ocaml/caml-mode>.
The OCaml debugger is started under Emacs by the command M-x camldebug, with argument the name of the executable file progname to debug. Communication with the debugger takes place in an Emacs buffer named \*camldebug-progname\*. The editing and history facilities of Shell mode are available for interacting with the debugger.
In addition, Emacs displays the source files containing the current event (the current position in the program execution) and highlights the location of the event. This display is updated synchronously with the debugger action.
The following bindings for the most common debugger commands are available in the \*camldebug-progname\* buffer:
C-c C-s
(command step): execute the program one step forward.
C-c C-k
(command backstep): execute the program one step backward.
C-c C-n
(command next): execute the program one step forward, skipping over function calls.
Middle mouse button
(command display): display named value. $n under mouse cursor (support incremental browsing of large data structures).
C-c C-p
(command print): print value of identifier at point.
C-c C-d
(command display): display value of identifier at point.
C-c C-r
(command run): execute the program forward to next breakpoint.
C-c C-v
(command reverse): execute the program backward to latest breakpoint.
C-c C-l
(command last): go back one step in the command history.
C-c C-t
(command backtrace): display backtrace of function calls.
C-c C-f
(command finish): run forward till the current function returns.
C-c <
(command up): select the stack frame below the current frame.
C-c >
(command down): select the stack frame above the current frame.
In all buffers in OCaml editing mode, the following debugger commands are also available:
C-x C-a C-b
(command break): set a breakpoint at event closest to point
C-x C-a C-p
(command print): print value of identifier at point
C-x C-a C-d
(command display): display value of identifier at point
| programming_docs |
ocaml None
[](#s:generative-functors)12.15 Generative functors
-----------------------------------------------------
(Introduced in OCaml 4.02)
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [module-expr](modules#module-expr) | ::= | ... |
| | ∣ | functor () -> [module-expr](modules#module-expr) |
| | ∣ | [module-expr](modules#module-expr) () |
| |
| [definition](modules#definition) | ::= | ... |
| | ∣ | module [module-name](names#module-name) { ( [module-name](names#module-name) : [module-type](modtypes#module-type) ) ∣ () } [ : [module-type](modtypes#module-type) ] = [module-expr](modules#module-expr) |
| |
| [module-type](modtypes#module-type) | ::= | ... |
| | ∣ | functor () -> [module-type](modtypes#module-type) |
| |
| [specification](modtypes#specification) | ::= | ... |
| | ∣ | module [module-name](names#module-name) { ( [module-name](names#module-name) : [module-type](modtypes#module-type) ) ∣ () } : [module-type](modtypes#module-type) |
| |
|
A generative functor takes a unit () argument. In order to use it, one must necessarily apply it to this unit argument, ensuring that all type components in the result of the functor behave in a generative way, *i.e.* they are different from types obtained by other applications of the same functor. This is equivalent to taking an argument of signature sig end, and always applying to struct end, but not to some defined module (in the latter case, applying twice to the same module would return identical types).
As a side-effect of this generativity, one is allowed to unpack first-class modules in the body of generative functors.
ocaml Chapter 9 Parallel programming Chapter 9 Parallel programming
==============================
* [9.1 Domains](parallelism#s%3Apar_domains)
* [9.2 Domainslib: A library for nested-parallel programming](parallelism#s%3Apar_parfib)
* [9.3 Parallel garbage collection](parallelism#s%3Apar_gc)
* [9.4 Memory model: The easy bits](parallelism#s%3Apar_mm_easy)
* [9.5 Blocking synchronisation](parallelism#s%3Apar_sync)
* [9.6 Interaction with C bindings](parallelism#s%3Apar_c_bindings)
* [9.7 Atomics](parallelism#s%3Apar_atomics)
In this chapter, we shall look at the parallel programming facilities in OCaml. The OCaml standard library exposes low-level primitives for parallel programming. We recommend the users to utilise higher-level parallel programming libraries such as [domainslib](https://github.com/ocaml-multicore/domainslib). This tutorial will first cover the high-level parallel programming using domainslib followed by low-level primitives exposed by the compiler.
OCaml distinguishes concurrency and parallelism and provides distinct mechanisms for expressing them. Concurrency is overlapped execution of tasks (section [12.24.2](effects#s%3Aeffects-concurrency)) whereas parallelism is simultaneous execution of tasks. In particular, parallel tasks overlap in time but concurrent tasks may or may not overlap in time. Tasks may execute concurrently by yielding control to each other. While concurrency is a program structuring mechanism, parallelism is a mechanism to make your programs run faster. If you are interested in the concurrent programming mechanisms in OCaml, please refer to the section [12.24](effects#s%3Aeffect-handlers) on effect handlers and the chapter [33](libthreads#c%3Athreads) on the threads library.
[](#s:par_domains)9.1 Domains
-------------------------------
Domains are the units of parallelism in OCaml. The module [Domain](libref/domain) provides the primitives to create and manage domains. New domains can be spawned using the spawn function.
```
Domain.spawn (fun _ -> print_endline "I ran in parallel")
I ran in parallel
- : unit Domain.t =
```
The spawn function executes the given computation in parallel with the calling domain.
Domains are heavy-weight entities. Each domain maps 1:1 to an operating system thread. Each domain also has its own runtime state, which includes domain-local structures for allocating memory. Hence, they are relatively expensive to create and tear down.
*It is recommended that the programs do not spawn more domains than cores available*.
In this tutorial, we shall be implementing, running and measuring the performance of parallel programs. The results observed are dependent on the number of cores available on the target machine. This tutorial is being written on a 2.3 GHz Quad-Core Intel Core i7 MacBook Pro with 4 cores and 8 hardware threads. It is reasonable to expect roughly 4x performance on 4 domains for parallel programs with little coordination between the domains, and when the machine is not under load. Beyond 4 domains, the speedup is likely to be less than linear. We shall also use the command-line benchmarking tool [hyperfine](https://github.com/sharkdp/hyperfine) for benchmarking our programs.
###
[](#s:par_join)9.1.1 Joining domains
We shall use the program to compute the nth Fibonacci number using recursion as a running example. The sequential program for computing the nth Fibonacci number is given below.
```
(* fib.ml *)
let n = try int_of_string Sys.argv.(1) with _ -> 1
let rec fib n = if n < 2 then 1 else fib (n - 1) + fib (n - 2)
let main () =
let r = fib n in
Printf.printf "fib(%d) = %d\n%!" n r
let _ = main ()
```
The program can be compiled and benchmarked as follows.
```
$ ocamlopt -o fib.exe fib.ml
$ ./fib.exe 42
fib(42) = 433494437
$ hyperfine './fib.exe 42' # Benchmarking
Benchmark 1: ./fib.exe 42
Time (mean ± sd): 1.193 s ± 0.006 s [User: 1.186 s, System: 0.003 s]
Range (min … max): 1.181 s … 1.202 s 10 runs
```
We see that it takes around 1.2 seconds to compute the 42nd Fibonacci number.
Spawned domains can be joined using the join function to get their results. The join function waits for target domain to terminate. The following program computes the nth Fibonacci number twice in parallel.
```
(* fib_twice.ml *)
let n = int_of_string Sys.argv.(1)
let rec fib n = if n < 2 then 1 else fib (n - 1) + fib (n - 2)
let main () =
let d1 = Domain.spawn (fun _ -> fib n) in
let d2 = Domain.spawn (fun _ -> fib n) in
let r1 = Domain.join d1 in
Printf.printf "fib(%d) = %d\n%!" n r1;
let r2 = Domain.join d2 in
Printf.printf "fib(%d) = %d\n%!" n r2
let _ = main ()
```
The program spawns two domains which compute the nth Fibonacci number. The spawn function returns a Domain.t value which can be joined to get the result of the parallel computation. The join function blocks until the computation runs to completion.
```
$ ocamlopt -o fib_twice.exe fib_twice.ml
$ ./fib_twice.exe 42
fib(42) = 433494437
fib(42) = 433494437
$ hyperfine './fib_twice.exe 42'
Benchmark 1: ./fib_twice.exe 42
Time (mean ± sd): 1.249 s ± 0.025 s [User: 2.451 s, System: 0.012 s]
Range (min … max): 1.221 s … 1.290 s 10 runs
```
As one can see that computing the nth Fibonacci number twice almost took the same time as computing it once thanks to parallelism.
[](#s:par_parfib)9.2 Domainslib: A library for nested-parallel programming
----------------------------------------------------------------------------
Let us attempt to parallelise the Fibonacci function. The two recursive calls may be executed in parallel. However, naively parallelising the recursive calls by spawning domains for each one will not work as it spawns too many domains.
```
(* fib_par1.ml *)
let n = try int_of_string Sys.argv.(1) with _ -> 1
let rec fib n =
if n < 2 then 1 else begin
let d1 = Domain.spawn (fun _ -> fib (n - 1)) in
let d2 = Domain.spawn (fun _ -> fib (n - 2)) in
Domain.join d1 + Domain.join d2
end
let main () =
let r = fib n in
Printf.printf "fib(%d) = %d\n%!" n r
let _ = main ()
fib(1) = 1
val n : int = 1
val fib : int -> int =
val main : unit -> unit =
```
```
$ ocamlopt -o fib_par1.exe fib_par1.ml
$ ./fib_par1.exe 42
Fatal error: exception Failure("failed to allocate domain")
```
OCaml has a limit of 128 domains that can be active at the same time. An attempt to spawn more domains will raise an exception. How then can we parallelise the Fibonacci function?
###
[](#s:par_parfib_domainslib)9.2.1 Parallelising Fibonacci using domainslib
The OCaml standard library provides only low-level primitives for concurrent and parallel programming, leaving high-level programming libraries to be developed and distributed outside the core compiler distribution. [Domainslib](https://github.com/ocaml-multicore/domainslib) is such a library for nested-parallel programming, which is epitomised by the parallelism available in the recursive Fibonacci computation. Let us use domainslib to parallelise the recursive Fibonacci program. It is recommended that you install domainslib using the [opam](https://opam.ocaml.org/) package manager. This tutorial uses domainslib version 0.4.2.
Domainslib provides an async/await mechanism for spawning parallel tasks and awaiting their results. On top of this mechanism, domainslib provides parallel iterators. At its core, domainslib has an efficient implementation of work-stealing queue in order to efficiently share tasks with other domains. A parallel implementation of the Fibonacci program is given below.
```
(* fib_par2.ml *)
let num_domains = int_of_string Sys.argv.(1)
let n = int_of_string Sys.argv.(2)
let rec fib n = if n < 2 then 1 else fib (n - 1) + fib (n - 2)
module T = Domainslib.Task
let rec fib_par pool n =
if n > 20 then begin
let a = T.async pool (fun _ -> fib_par pool (n-1)) in
let b = T.async pool (fun _ -> fib_par pool (n-2)) in
T.await pool a + T.await pool b
end else fib n
let main () =
let pool = T.setup_pool ~num_additional_domains:(num_domains - 1) () in
let res = T.run pool (fun _ -> fib_par pool n) in
T.teardown_pool pool;
Printf.printf "fib(%d) = %d\n" n res
let _ = main ()
```
The program takes the number of domains and the input to the Fibonacci function as the first and the second command-line arguments respectively.
Let us start with the main function. First, we set up a pool of domains on which the nested parallel tasks will run. The domain invoking the run function will also participate in executing the tasks submitted to the pool. We invoke the parallel Fibonacci function fib\_par in the run function. Finally, we tear down the pool and print the result.
For sufficiently large inputs (n > 20), the fib\_par function spawns the left and the right recursive calls asynchronously in the pool using the async function. The async function returns a promise for the result. The result of an asynchronous computation is obtained by awaiting the promise using the await function. The await function call blocks until the promise is resolved.
For small inputs, the fib\_par function simply calls the sequential Fibonacci function fib. It is important to switch to sequential mode for small problem sizes. If not, the cost of parallelisation will outweigh the work available.
For simplicity, we use ocamlfind to compile this program. It is recommended that the users use [dune](https://github.com/ocaml/dune) to build their programs that utilise libraries installed through [opam](https://opam.ocaml.org/).
```
$ ocamlfind ocamlopt -package domainslib -linkpkg -o fib_par2.exe fib_par2.ml
$ ./fib_par2.exe 1 42
fib(42) = 433494437
$ hyperfine './fib.exe 42' './fib_par2.exe 2 42' \
'./fib_par2.exe 4 42' './fib_par2.exe 8 42'
Benchmark 1: ./fib.exe 42
Time (mean ± sd): 1.217 s ± 0.018 s [User: 1.203 s, System: 0.004 s]
Range (min … max): 1.202 s … 1.261 s 10 runs
Benchmark 2: ./fib_par2.exe 2 42
Time (mean ± sd): 628.2 ms ± 2.9 ms [User: 1243.1 ms, System: 4.9 ms]
Range (min … max): 625.7 ms … 634.5 ms 10 runs
Benchmark 3: ./fib_par2.exe 4 42
Time (mean ± sd): 337.6 ms ± 23.4 ms [User: 1321.8 ms, System: 8.4 ms]
Range (min … max): 318.5 ms … 377.6 ms 10 runs
Benchmark 4: ./fib_par2.exe 8 42
Time (mean ± sd): 250.0 ms ± 9.4 ms [User: 1877.1 ms, System: 12.6 ms]
Range (min … max): 242.5 ms … 277.3 ms 11 runs
Summary
'./fib_par2.exe 8 42' ran
1.35 ± 0.11 times faster than './fib_par2.exe 4 42'
2.51 ± 0.10 times faster than './fib_par2.exe 2 42'
4.87 ± 0.20 times faster than './fib.exe 42'
```
The results show that, with 8 domains, the parallel Fibonacci program runs 4.87 times faster than the sequential version.
###
[](#s:par_iterators)9.2.2 Parallel iteration constructs
Many numerical algorithms use for-loops. The parallel-for primitive provides a straight-forward way to parallelise such code. Let us take the [spectral-norm](https://benchmarksgame-team.pages.debian.net/benchmarksgame/description/spectralnorm.html#spectralnorm) benchmark from the computer language benchmarks game and parallelise it. The sequential version of the program is given below.
```
(* spectralnorm.ml *)
let n = try int_of_string Sys.argv.(1) with _ -> 32
let eval_A i j = 1. /. float((i+j)*(i+j+1)/2+i+1)
let eval_A_times_u u v =
let n = Array.length v - 1 in
for i = 0 to n do
let vi = ref 0. in
for j = 0 to n do vi := !vi +. eval_A i j *. u.(j) done;
v.(i) <- !vi
done
let eval_At_times_u u v =
let n = Array.length v - 1 in
for i = 0 to n do
let vi = ref 0. in
for j = 0 to n do vi := !vi +. eval_A j i *. u.(j) done;
v.(i) <- !vi
done
let eval_AtA_times_u u v =
let w = Array.make (Array.length u) 0.0 in
eval_A_times_u u w; eval_At_times_u w v
let () =
let u = Array.make n 1.0 and v = Array.make n 0.0 in
for _i = 0 to 9 do
eval_AtA_times_u u v; eval_AtA_times_u v u
done;
let vv = ref 0.0 and vBv = ref 0.0 in
for i=0 to n-1 do
vv := !vv +. v.(i) *. v.(i);
vBv := !vBv +. u.(i) *. v.(i)
done;
Printf.printf "%0.9f\n" (sqrt(!vBv /. !vv))
```
Observe that the program has nested loops in eval\_A\_times\_u and eval\_At\_times\_u. Each iteration of the outer loop body reads from u but writes to disjoint memory locations in v. Hence, the iterations of the outer loop are not dependent on each other and can be executed in parallel.
The parallel version of spectral norm is shown below.
```
(* spectralnorm_par.ml *)
let num_domains = try int_of_string Sys.argv.(1) with _ -> 1
let n = try int_of_string Sys.argv.(2) with _ -> 32
let eval_A i j = 1. /. float((i+j)*(i+j+1)/2+i+1)
module T = Domainslib.Task
let eval_A_times_u pool u v =
let n = Array.length v - 1 in
T.parallel_for pool ~start:0 ~finish:n ~body:(fun i ->
let vi = ref 0. in
for j = 0 to n do vi := !vi +. eval_A i j *. u.(j) done;
v.(i) <- !vi
)
let eval_At_times_u pool u v =
let n = Array.length v - 1 in
T.parallel_for pool ~start:0 ~finish:n ~body:(fun i ->
let vi = ref 0. in
for j = 0 to n do vi := !vi +. eval_A j i *. u.(j) done;
v.(i) <- !vi
)
let eval_AtA_times_u pool u v =
let w = Array.make (Array.length u) 0.0 in
eval_A_times_u pool u w; eval_At_times_u pool w v
let () =
let pool = T.setup_pool ~num_additional_domains:(num_domains - 1) () in
let u = Array.make n 1.0 and v = Array.make n 0.0 in
T.run pool (fun _ ->
for _i = 0 to 9 do
eval_AtA_times_u pool u v; eval_AtA_times_u pool v u
done);
let vv = ref 0.0 and vBv = ref 0.0 in
for i=0 to n-1 do
vv := !vv +. v.(i) *. v.(i);
vBv := !vBv +. u.(i) *. v.(i)
done;
T.teardown_pool pool;
Printf.printf "%0.9f\n" (sqrt(!vBv /. !vv))
```
Observe that the parallel\_for function is isomorphic to the for-loop in the sequential version. No other change is required except for the boiler plate code to set up and tear down the pools.
```
$ ocamlopt -o spectralnorm.exe spectralnorm.ml
$ ocamlfind ocamlopt -package domainslib -linkpkg -o spectralnorm_par.exe \
spectralnorm_par.ml
$ hyperfine './spectralnorm.exe 4096' './spectralnorm_par.exe 2 4096' \
'./spectralnorm_par.exe 4 4096' './spectralnorm_par.exe 8 4096'
Benchmark 1: ./spectralnorm.exe 4096
Time (mean ± sd): 1.989 s ± 0.013 s [User: 1.972 s, System: 0.007 s]
Range (min … max): 1.975 s … 2.018 s 10 runs
Benchmark 2: ./spectralnorm_par.exe 2 4096
Time (mean ± sd): 1.083 s ± 0.015 s [User: 2.140 s, System: 0.009 s]
Range (min … max): 1.064 s … 1.102 s 10 runs
Benchmark 3: ./spectralnorm_par.exe 4 4096
Time (mean ± sd): 698.7 ms ± 10.3 ms [User: 2730.8 ms, System: 18.3 ms]
Range (min … max): 680.9 ms … 721.7 ms 10 runs
Benchmark 4: ./spectralnorm_par.exe 8 4096
Time (mean ± sd): 921.8 ms ± 52.1 ms [User: 6711.6 ms, System: 51.0 ms]
Range (min … max): 838.6 ms … 989.2 ms 10 runs
Summary
'./spectralnorm_par.exe 4 4096' ran
1.32 ± 0.08 times faster than './spectralnorm_par.exe 8 4096'
1.55 ± 0.03 times faster than './spectralnorm_par.exe 2 4096'
2.85 ± 0.05 times faster than './spectralnorm.exe 4096'
```
On the author’s machine, the program scales reasonably well up to 4 domains but performs worse with 8 domains. Recall that the machine only has 4 physical cores. Debugging and fixing this performance issue is beyond the scope of this tutorial.
[](#s:par_gc)9.3 Parallel garbage collection
----------------------------------------------
An important aspect of the scalability of parallel OCaml programs is the scalability of the garbage collector (GC). The OCaml GC is designed to have both low latency and good parallel scalability. OCaml has a generational garbage collector with a small minor heap and a large major heap. New objects (upto a certain size) are allocated in the minor heap. Each domain has its own domain-local minor heap arena into which new objects are allocated without synchronising with the other domains. When a domain exhausts its minor heap arena, it calls for a stop-the-world collection of the minor heaps. In the stop-the-world section, all the domains collect their minor heap arenas in parallel evacuating the survivors to the major heap.
For the major heap, each domain maintains domain-local, size-segmented pools of memory into which large objects and survivors from the minor collection are allocated. Having domain-local pools avoids synchronisation for most major heap allocations. The major heap is collected by a concurrent mark-and-sweep algorithm that involves a few short stop-the-world pauses for each major cycle.
Overall, the users should expect the garbage collector to scale well with increasing number of domains, with the latency remaining low. For more information on the design and evaluation of the garbage collector, please have a look at the ICFP 2020 paper on [Retrofitting Parallelism onto OCaml](https://arxiv.org/abs/2004.11663).
[](#s:par_mm_easy)9.4 Memory model: The easy bits
---------------------------------------------------
Modern processors and compilers aggressively optimise programs. These optimisations accelerate without otherwise affecting sequential programs, but cause surprising behaviours to be visible in parallel programs. To benefit from these optimisations, OCaml adopts a relaxed memory model that precisely specifies which of these *relaxed behaviours* programs may observe. While these models are difficult to program against directly, the OCaml memory model provides recipes that retain the simplicity of sequential reasoning.
Firstly, immutable values may be freely shared between multiple domains and may be accessed in parallel. For mutable data structures such as reference cells, arrays and mutable record fields, programmers should avoid *data races*. Reference cells, arrays and mutable record fields are said to be *non-atomic* data structures. A data race is said to occur when two domains concurrently access a non-atomic memory location without *synchronisation* and at least one of the accesses is a write. OCaml provides a number of ways to introduce synchronisation including atomic variables (section [9.7](#s%3Apar_atomics)) and mutexes (section [9.5](#s%3Apar_sync)).
Importantly, for data race free (DRF) programs, OCaml provides sequentially consistent (SC) semantics – the observed behaviour of such programs can be explained by the interleaving of operations from different domains. This property is known as DRF-SC guarantee. Moreover, in OCaml, DRF-SC guarantee is modular – if a part of a program is data race free, then the OCaml memory model ensures that those parts have sequential consistency despite other parts of the program having data races. Even for programs with data races, OCaml provides strong guarantees. While the user may observe non sequentially consistent behaviours, there are no crashes.
For more details on the relaxed behaviours in the presence of data races, please have a look at the chapter on the hard bits of the memory model (chapter [10](memorymodel#c%3Amemorymodel)).
[](#s:par_sync)9.5 Blocking synchronisation
---------------------------------------------
Domains may perform blocking synchronisation with the help of [Mutex](libref/mutex), [Condition](libref/condition) and [Semaphore](libref/semaphore) modules. These modules are the same as those used to synchronise threads created by the threads library (chapter [33](libthreads#c%3Athreads)). For clarity, in the rest of this chapter, we shall call the threads created by the threads library as *systhreads*. The following program implements a concurrent stack using mutex and condition variables.
```
module Blocking_stack : sig
type 'a t
val make : unit -> 'a t
val push : 'a t -> 'a -> unit
val pop : 'a t -> 'a
end = struct
type 'a t = {
mutable contents: 'a list;
mutex : Mutex.t;
nonempty : Condition.t
}
let make () = {
contents = [];
mutex = Mutex.create ();
nonempty = Condition.create ()
}
let push r v =
Mutex.lock r.mutex;
r.contents <- v::r.contents;
Condition.signal r.nonempty;
Mutex.unlock r.mutex
let pop r =
Mutex.lock r.mutex;
let rec loop () =
match r.contents with
| [] ->
Condition.wait r.nonempty r.mutex;
loop ()
| x::xs -> r.contents <- xs; x
in
let res = loop () in
Mutex.unlock r.mutex;
res
end
```
The concurrent stack is implemented using a record with three fields: a mutable field contents which stores the elements in the stack, a mutex to control access to the contents field, and a condition variable nonempty, which is used to signal blocked domains waiting for the stack to become non-empty.
The push operation locks the mutex, updates the contents field with a new list whose head is the element being pushed and the tail is the old list. The condition variable nonempty is signalled while the lock is held in order to wake up any domains waiting on this condition. If there are waiting domains, one of the domains is woken up. If there are none, then the signal operation has no effect.
The pop operation locks the mutex and checks whether the stack is empty. If so, the calling domain waits on the condition variable nonempty using the wait primitive. The wait call atomically suspends the execution of the current domain and unlocks the mutex. When this domain is woken up again (when the wait call returns), it holds the lock on mutex. The domain tries to read the contents of the stack again. If the pop operation sees that the stack is non-empty, it updates the contents to the tail of the old list, and returns the head.
The use of mutex to control access to the shared resource contents introduces sufficient synchronisation between multiple domains using the stack. Hence, there are no data races when multiple domains use the stack in parallel.
###
[](#s:par_systhread_interaction)9.5.1 Interaction with systhreads
How do systhreads interact with domains? The systhreads created on a particular domain remain pinned to that domain. Only one systhread at a time is allowed to run OCaml code on a particular domain. However, systhreads belonging to a particular domain may run C library or system code in parallel. Systhreads belonging to different domains may execute in parallel.
When using systhreads, the thread created for executing the computation given to Domain.spawn is also treated as a systhread. For example, the following program creates in total two domains (including the initial domain) with two systhreads each (including the initial systhread for each of the domains).
```
(* dom_thr.ml *)
let m = Mutex.create ()
let r = ref None (* protected by m *)
let task () =
let my_thr_id = Thread.(id (self ())) in
let my_dom_id :> int = Domain.self () in
Mutex.lock m;
begin match !r with
| None ->
Printf.printf "Thread %d running on domain %d saw initial write\n%!"
my_thr_id my_dom_id
| Some their_thr_id ->
Printf.printf "Thread %d running on domain %d saw the write by thread %d\n%!"
my_thr_id my_dom_id their_thr_id;
end;
r := Some my_thr_id;
Mutex.unlock m
let task' () =
let t = Thread.create task () in
task ();
Thread.join t
let main () =
let d = Domain.spawn task' in
task' ();
Domain.join d
let _ = main ()
```
```
$ ocamlopt -I +threads unix.cmxa threads.cmxa -o dom_thr.exe dom_thr.ml
$ ./dom_thr.exe
Thread 1 running on domain 1 saw initial write
Thread 0 running on domain 0 saw the write by thread 1
Thread 2 running on domain 1 saw the write by thread 0
Thread 3 running on domain 0 saw the write by thread 2
```
This program uses a shared reference cell protected by a mutex to communicate between the different systhreads running on two different domains. The systhread identifiers uniquely identify systhreads in the program. The initial domain gets the domain id and the thread id as 0. The newly spawned domain gets domain id as 1.
[](#s:par_c_bindings)9.6 Interaction with C bindings
------------------------------------------------------
During parallel execution with multiple domains, C code running on a domain may run in parallel with any C code running in other domains even if neither of them has released the “domain lock”. Prior to OCaml 5.0, C bindings may have assumed that if the OCaml runtime lock is not released, then it would be safe to manipulate global C state (e.g. initialise a function-local static value). This is no longer true in the presence of parallel execution with multiple domains.
[](#s:par_atomics)9.7 Atomics
-------------------------------
Mutex, condition variables and semaphores are used to implement blocking synchronisation between domains. For non-blocking synchronisation, OCaml provides [Atomic](libref/atomic) variables. As the name suggests, non-blocking synchronisation does not provide mechanisms for suspending and waking up domains. On the other hand, primitives used in non-blocking synchronisation are often compiled to atomic read-modify-write primitives that the hardware provides. As an example, the following program increments a non-atomic counter and an atomic counter in parallel.
```
(* incr.ml *)
let twice_in_parallel f =
let d1 = Domain.spawn f in
let d2 = Domain.spawn f in
Domain.join d1;
Domain.join d2
let plain_ref n =
let r = ref 0 in
let f () = for _i=1 to n do incr r done in
twice_in_parallel f;
Printf.printf "Non-atomic ref count: %d\n" !r
let atomic_ref n =
let r = Atomic.make 0 in
let f () = for _i=1 to n do Atomic.incr r done in
twice_in_parallel f;
Printf.printf "Atomic ref count: %d\n" (Atomic.get r)
let main () =
let n = try int_of_string Sys.argv.(1) with _ -> 1 in
plain_ref n;
atomic_ref n
let _ = main ()
```
```
$ ocamlopt -o incr.exe incr.ml
$ ./incr.exe 1_000_000
Non-atomic ref count: 1187193
Atomic ref count: 2000000
```
Observe that the result from using the non-atomic counter is lower than what one would naively expect. This is because the non-atomic incr function is equivalent to:
```
let incr r =
let curr = !r in
r := curr + 1
```
Observe that the load and the store are two separate operations, and the increment operation as a whole is not performed atomically. When two domains execute this code in parallel, both of them may read the same value of the counter curr and update it to curr + 1. Hence, instead of two increments, the effect will be that of a single increment. On the other hand, the atomic counter performs the load and the store atomically with the help of hardware support for atomicity. The atomic counter returns the expected result.
The atomic variables can be used for low-level synchronisation between the domains. The following example uses an atomic variable to exchange a message between two domains.
```
let r = Atomic.make None
let sender () = Atomic.set r (Some "Hello")
let rec receiver () =
match Atomic.get r with
| None -> Domain.cpu_relax (); receiver ()
| Some m -> print_endline m
let main () =
let s = Domain.spawn sender in
let d = Domain.spawn receiver in
Domain.join s;
Domain.join d
let _ = main ()
Hello
val r : string option Atomic.t =
val sender : unit -> unit =
val receiver : unit -> unit =
val main : unit -> unit =
```
While the sender and the receiver compete to access r, this is not a data race since r is an atomic reference.
###
[](#s:par_lockfree_stack)9.7.1 Lock-free stack
The Atomic module is used to implement non-blocking, lock-free data structures. The following program implements a lock-free stack.
```
module Lockfree_stack : sig
type 'a t
val make : unit -> 'a t
val push : 'a t -> 'a -> unit
val pop : 'a t -> 'a option
end = struct
type 'a t = 'a list Atomic.t
let make () = Atomic.make []
let rec push r v =
let s = Atomic.get r in
if Atomic.compare_and_set r s (v::s) then ()
else (Domain.cpu_relax (); push r v)
let rec pop r =
let s = Atomic.get r in
match s with
| [] -> None
| x::xs ->
if Atomic.compare_and_set r s xs then Some x
else (Domain.cpu_relax (); pop r)
end
```
The atomic stack is represented by an atomic reference that holds a list. The push and pop operations use the compare\_and\_set primitive to attempt to atomically update the atomic reference. The expression compare\_and\_set r seen v sets the value of r to v if and only if its current value is physically equal to seen. Importantly, the comparison and the update occur atomically. The expression evaluates to true if the comparison succeeded (and the update happened) and false otherwise.
If the compare\_and\_set fails, then some other domain is also attempting to update the atomic reference at the same time. In this case, the push and pop operations call Domain.cpu\_relax to back off for a short duration allowing competing domains to make progress before retrying the failed operation. This lock-free stack implementation is also known as Treiber stack.
| programming_docs |
ocaml Chapter 5 Polymorphic variants Chapter 5 Polymorphic variants
==============================
* [5.1 Basic use](polyvariant#s%3Apolyvariant%3Abasic-use)
* [5.2 Advanced use](polyvariant#s%3Apolyvariant-advanced)
* [5.3 Weaknesses of polymorphic variants](polyvariant#s%3Apolyvariant-weaknesses)
(Chapter written by Jacques Garrigue)
Variants as presented in section [1.4](coreexamples#s%3Atut-recvariants) are a powerful tool to build data structures and algorithms. However they sometimes lack flexibility when used in modular programming. This is due to the fact that every constructor is assigned to a unique type when defined and used. Even if the same name appears in the definition of multiple types, the constructor itself belongs to only one type. Therefore, one cannot decide that a given constructor belongs to multiple types, or consider a value of some type to belong to some other type with more constructors.
With polymorphic variants, this original assumption is removed. That is, a variant tag does not belong to any type in particular, the type system will just check that it is an admissible value according to its use. You need not define a type before using a variant tag. A variant type will be inferred independently for each of its uses.
[](#s:polyvariant:basic-use)5.1 Basic use
-------------------------------------------
In programs, polymorphic variants work like usual ones. You just have to prefix their names with a backquote character `.
```
# [`On; `Off];;
- : [> `Off | `On ] list = [`On; `Off]
```
```
# `Number 1;;
- : [> `Number of int ] = `Number 1
```
```
# let f = function `On -> 1 | `Off -> 0 | `Number n -> n;;
val f : [< `Number of int | `Off | `On ] -> int =
```
```
# List.map f [`On; `Off];;
- : int list = [1; 0]
```
[>`Off|`On] list means that to match this list, you should at least be able to match `Off and `On, without argument. [<`On|`Off|`Number of int] means that f may be applied to `Off, `On (both without argument), or `Number n where n is an integer. The > and < inside the variant types show that they may still be refined, either by defining more tags or by allowing less. As such, they contain an implicit type variable. Because each of the variant types appears only once in the whole type, their implicit type variables are not shown.
The above variant types were polymorphic, allowing further refinement. When writing type annotations, one will most often describe fixed variant types, that is types that cannot be refined. This is also the case for type abbreviations. Such types do not contain < or >, but just an enumeration of the tags and their associated types, just like in a normal datatype definition.
```
# type 'a vlist = [`Nil | `Cons of 'a * 'a vlist];;
type 'a vlist = [ `Cons of 'a * 'a vlist | `Nil ]
```
```
# let rec map f : 'a vlist -> 'b vlist = function
| `Nil -> `Nil
| `Cons(a, l) -> `Cons(f a, map f l)
;;
val map : ('a -> 'b) -> 'a vlist -> 'b vlist =
```
[](#s:polyvariant-advanced)5.2 Advanced use
---------------------------------------------
Type-checking polymorphic variants is a subtle thing, and some expressions may result in more complex type information.
```
# let f = function `A -> `C | `B -> `D | x -> x;;
val f : ([> `A | `B | `C | `D ] as 'a) -> 'a =
```
```
# f `E;;
- : [> `A | `B | `C | `D | `E ] = `E
```
Here we are seeing two phenomena. First, since this matching is open (the last case catches any tag), we obtain the type [> `A | `B] rather than [< `A | `B] in a closed matching. Then, since x is returned as is, input and return types are identical. The notation as 'a denotes such type sharing. If we apply f to yet another tag `E, it gets added to the list.
```
# let f1 = function `A x -> x = 1 | `B -> true | `C -> false
let f2 = function `A x -> x = "a" | `B -> true ;;
val f1 : [< `A of int | `B | `C ] -> bool =
val f2 : [< `A of string | `B ] -> bool =
```
```
# let f x = f1 x && f2 x;;
val f : [< `A of string & int | `B ] -> bool =
```
Here f1 and f2 both accept the variant tags `A and `B, but the argument of `A is int for f1 and string for f2. In f’s type `C, only accepted by f1, disappears, but both argument types appear for `A as int & string. This means that if we pass the variant tag `A to f, its argument should be *both* int and string. Since there is no such value, f cannot be applied to `A, and `B is the only accepted input.
Even if a value has a fixed variant type, one can still give it a larger type through coercions. Coercions are normally written with both the source type and the destination type, but in simple cases the source type may be omitted.
```
# type 'a wlist = [`Nil | `Cons of 'a * 'a wlist | `Snoc of 'a wlist * 'a];;
type 'a wlist = [ `Cons of 'a * 'a wlist | `Nil | `Snoc of 'a wlist * 'a ]
```
```
# let wlist_of_vlist l = (l : 'a vlist :> 'a wlist);;
val wlist_of_vlist : 'a vlist -> 'a wlist =
```
```
# let open_vlist l = (l : 'a vlist :> [> 'a vlist]);;
val open_vlist : 'a vlist -> [> 'a vlist ] =
```
```
# fun x -> (x :> [`A|`B|`C]);;
- : [< `A | `B | `C ] -> [ `A | `B | `C ] =
```
You may also selectively coerce values through pattern matching.
```
# let split_cases = function
| `Nil | `Cons _ as x -> `A x
| `Snoc _ as x -> `B x
;;
val split_cases :
[< `Cons of 'a | `Nil | `Snoc of 'b ] ->
[> `A of [> `Cons of 'a | `Nil ] | `B of [> `Snoc of 'b ] ] =
```
When an or-pattern composed of variant tags is wrapped inside an alias-pattern, the alias is given a type containing only the tags enumerated in the or-pattern. This allows for many useful idioms, like incremental definition of functions.
```
# let num x = `Num x
let eval1 eval (`Num x) = x
let rec eval x = eval1 eval x ;;
val num : 'a -> [> `Num of 'a ] =
val eval1 : 'a -> [< `Num of 'b ] -> 'b =
val eval : [< `Num of 'a ] -> 'a =
```
```
# let plus x y = `Plus(x,y)
let eval2 eval = function
| `Plus(x,y) -> eval x + eval y
| `Num _ as x -> eval1 eval x
let rec eval x = eval2 eval x ;;
val plus : 'a -> 'b -> [> `Plus of 'a * 'b ] =
val eval2 : ('a -> int) -> [< `Num of int | `Plus of 'a \* 'a ] -> int =
val eval : ([< `Num of int | `Plus of 'a \* 'a ] as 'a) -> int =
```
To make this even more comfortable, you may use type definitions as abbreviations for or-patterns. That is, if you have defined type myvariant = [`Tag1 of int | `Tag2 of bool], then the pattern #myvariant is equivalent to writing (`Tag1(\_ : int) | `Tag2(\_ : bool)).
Such abbreviations may be used alone,
```
# let f = function
| #myvariant -> "myvariant"
| `Tag3 -> "Tag3";;
val f : [< `Tag1 of int | `Tag2 of bool | `Tag3 ] -> string =
```
or combined with with aliases.
```
# let g1 = function `Tag1 _ -> "Tag1" | `Tag2 _ -> "Tag2";;
val g1 : [< `Tag1 of 'a | `Tag2 of 'b ] -> string =
```
```
# let g = function
| #myvariant as x -> g1 x
| `Tag3 -> "Tag3";;
val g : [< `Tag1 of int | `Tag2 of bool | `Tag3 ] -> string =
```
[](#s:polyvariant-weaknesses)5.3 Weaknesses of polymorphic variants
---------------------------------------------------------------------
After seeing the power of polymorphic variants, one may wonder why they were added to core language variants, rather than replacing them.
The answer is twofold. The first aspect is that while being pretty efficient, the lack of static type information allows for less optimizations, and makes polymorphic variants slightly heavier than core language ones. However noticeable differences would only appear on huge data structures.
More important is the fact that polymorphic variants, while being type-safe, result in a weaker type discipline. That is, core language variants do actually much more than ensuring type-safety, they also check that you use only declared constructors, that all constructors present in a data-structure are compatible, and they enforce typing constraints to their parameters.
For this reason, you must be more careful about making types explicit when you use polymorphic variants. When you write a library, this is easy since you can describe exact types in interfaces, but for simple programs you are probably better off with core language variants.
Beware also that some idioms make trivial errors very hard to find. For instance, the following code is probably wrong but the compiler has no way to see it.
```
# type abc = [`A | `B | `C] ;;
type abc = [ `A | `B | `C ]
```
```
# let f = function
| `As -> "A"
| #abc -> "other" ;;
val f : [< `A | `As | `B | `C ] -> string =
```
```
# let f : abc -> string = f ;;
val f : abc -> string =
```
You can avoid such risks by annotating the definition itself.
```
# let f : abc -> string = function
| `As -> "A"
| #abc -> "other" ;;
Error: This pattern matches values of type [? `As ]
but a pattern was expected which matches values of type abc
The second variant type does not allow tag(s) `As
```
ocaml Chapter 33 The threads library Chapter 33 The threads library
==============================
The threads library allows concurrent programming in OCaml. It provides multiple threads of control (also called lightweight processes) that execute concurrently in the same memory space. Threads communicate by in-place modification of shared data structures, or by sending and receiving data on communication channels.
The threads library is implemented on top of the threading facilities provided by the operating system: POSIX 1003.1c threads for Linux, MacOS, and other Unix-like systems; Win32 threads for Windows. Only one thread at a time is allowed to run OCaml code on a particular domain [9.5.1](parallelism#s%3Apar_systhread_interaction). Hence, opportunities for parallelism are limited to the parts of the program that run system or C library code. However, threads provide concurrency and can be used to structure programs as several communicating processes. Threads also efficiently support concurrent, overlapping I/O operations.
Programs that use threads must be linked as follows:
```
ocamlc -I +unix -I +threads other options unix.cma threads.cma other files
ocamlopt -I +unix -I +threads other options unix.cmxa threads.cmxa other files
```
Compilation units that use the threads library must also be compiled with the -I +threads option (see chapter [13](comp#c%3Acamlc)).
* [Module Thread](libref/thread): lightweight threads
* [Module Event](libref/event): first-class synchronous communication
ocaml None
[](#s:gadts)12.10 Generalized algebraic datatypes
---------------------------------------------------
Generalized algebraic datatypes, or GADTs, extend usual sum types in two ways: constraints on type parameters may change depending on the value constructor, and some type variables may be existentially quantified. They are described in chapter [7](gadts-tutorial#c%3Agadts-tutorial).
(Introduced in OCaml 4.00)
| | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [constr-decl](typedecl#constr-decl) | ::= | ... |
| | ∣ | [constr-name](names#constr-name) : [ [constr-args](typedecl#constr-args) -> ] [typexpr](types#typexpr) |
| |
| [type-param](typedecl#type-param) | ::= | ... |
| | ∣ | [[variance](typedecl#variance)] \_ |
|
Refutation cases. (Introduced in OCaml 4.03)
| | | | | | | |
| --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| matching-case | ::= | [pattern](patterns#pattern) [when [expr](expr#expr)] -> [expr](expr#expr) |
| | ∣ | [pattern](patterns#pattern) -> . |
|
Explicit naming of existentials. (Introduced in OCaml 4.13.0)
| | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [pattern](patterns#pattern) | ::= | ... |
| | ∣ | [constr](names#constr) ( type { [typeconstr-name](names#typeconstr-name) }+ ) ( [pattern](patterns#pattern) ) |
| |
|
ocaml None
[](#s:generalized-open)12.22 Generalized open statements
----------------------------------------------------------
(Introduced in 4.08)
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [definition](modules#definition) | ::= | ... |
| | ∣ | open [module-expr](modules#module-expr) |
| | ∣ | open! [module-expr](modules#module-expr) |
| |
| [specification](modtypes#specification) | ::= | ... |
| | ∣ | open [extended-module-path](names#extended-module-path) |
| | ∣ | open! [extended-module-path](names#extended-module-path) |
| |
| [expr](expr#expr) | ::= | ... |
| | ∣ | let open [module-expr](modules#module-expr) in [expr](expr#expr) |
| | ∣ | let open! [module-expr](modules#module-expr) in [expr](expr#expr) |
| |
|
This extension makes it possible to open any module expression in module structures and expressions. A similar mechanism is also available inside module types, but only for extended module paths (e.g. F(X).G(Y)).
For instance, a module can be constrained when opened with
```
module M = struct let x = 0 let hidden = 1 end
open (M:sig val x: int end)
let y = hidden
Error: Unbound value hidden
```
Another possibility is to immediately open the result of a functor application
```
let sort (type x) (x:x list) =
let open Set.Make(struct type t = x let compare=compare end) in
elements (of_list x)
val sort : 'x list -> 'x list =
```
Going further, this construction can introduce local components inside a structure,
```
module M = struct
let x = 0
open! struct
let x = 0
let y = 1
end
let w = x + y
end
module M : sig val x : int val w : int end
```
One important restriction is that types introduced by open struct ... end cannot appear in the signature of the enclosing structure, unless they are defined equal to some non-local type. So:
```
module M = struct
open struct type 'a t = 'a option = None | Some of 'a end
let x : int t = Some 1
end
module M : sig val x : int option end
```
is OK, but:
```
module M = struct
open struct type t = A end
let x = A
end
Error: The type t/568 introduced by this open appears in the signature
File "extensions/generalizedopens.etex", line 3, characters 6-7:
The value x has no valid type if t/568 is hidden
```
is not because x cannot be given any type other than t, which only exists locally. Although the above would be OK if x too was local:
```
module M: sig end = struct
open struct
type t = A
end
…
open struct let x = A end
…
end
module M : sig end
```
Inside signatures, extended opens are limited to extended module paths,
```
module type S = sig
module F: sig end -> sig type t end
module X: sig end
open F(X)
val f: t
end
module type S =
sig
module F : sig end -> sig type t end
module X : sig end
val f : F(X).t
end
```
and not
```
open struct type t = int end
```
In those situations, local substitutions(see [12.7.2](signaturesubstitution#ss%3Alocal-substitution)) can be used instead.
Beware that this extension is not available inside class definitions:
```
class c =
let open Set.Make(Int) in
...
```
ocaml None
[](#s:locally-abstract)12.4 Locally abstract types
----------------------------------------------------
(Introduced in OCaml 3.12, short syntax added in 4.03)
| | | | | | | |
| --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [parameter](expr#parameter) | ::= | ... |
| | ∣ | ( type { [typeconstr-name](names#typeconstr-name) }+ ) |
|
The expression fun ( type [typeconstr-name](names#typeconstr-name) ) -> [expr](expr#expr) introduces a type constructor named [typeconstr-name](names#typeconstr-name) which is considered abstract in the scope of the sub-expression, but then replaced by a fresh type variable. Note that contrary to what the syntax could suggest, the expression fun ( type [typeconstr-name](names#typeconstr-name) ) -> [expr](expr#expr) itself does not suspend the evaluation of [expr](expr#expr) as a regular abstraction would. The syntax has been chosen to fit nicely in the context of function declarations, where it is generally used. It is possible to freely mix regular function parameters with pseudo type parameters, as in:
```
let f = fun (type t) (foo : t list) -> …
```
and even use the alternative syntax for declaring functions:
```
let f (type t) (foo : t list) = …
```
If several locally abstract types need to be introduced, it is possible to use the syntax fun ( type [typeconstr-name](names#typeconstr-name)1 … [typeconstr-name](names#typeconstr-name)n ) -> [expr](expr#expr) as syntactic sugar for fun ( type [typeconstr-name](names#typeconstr-name)1 ) -> … -> fun ( type [typeconstr-name](names#typeconstr-name)n ) -> [expr](expr#expr). For instance,
```
let f = fun (type t u v) -> fun (foo : (t * u * v) list) -> …
let f' (type t u v) (foo : (t * u * v) list) = …
```
This construction is useful because the type constructors it introduces can be used in places where a type variable is not allowed. For instance, one can use it to define an exception in a local module within a polymorphic function.
```
let f (type t) () =
let module M = struct exception E of t end in
(fun x -> M.E x), (function M.E x -> Some x | _ -> None)
```
Here is another example:
```
let sort_uniq (type s) (cmp : s -> s -> int) =
let module S = Set.Make(struct type t = s let compare = cmp end) in
fun l ->
S.elements (List.fold_right S.add l S.empty)
```
It is also extremely useful for first-class modules (see section [12.5](firstclassmodules#s%3Afirst-class-modules)) and generalized algebraic datatypes (GADTs: see section [12.10](gadts#s%3Agadts)).
#####
[](#p:polymorpic-locally-abstract)Polymorphic syntax
(Introduced in OCaml 4.00)
| | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| [let-binding](expr#let-binding) | ::= | ... |
| | ∣ | [value-name](names#value-name) : type { [typeconstr-name](names#typeconstr-name) }+ . [typexpr](types#typexpr) = [expr](expr#expr) |
| |
| [class-field](classes#class-field) | ::= | ... |
| | ∣ | method [private] [method-name](names#method-name) : type { [typeconstr-name](names#typeconstr-name) }+ . [typexpr](types#typexpr) = [expr](expr#expr) |
| | ∣ | method! [private] [method-name](names#method-name) : type { [typeconstr-name](names#typeconstr-name) }+ . [typexpr](types#typexpr) = [expr](expr#expr) |
|
The (type [typeconstr-name](names#typeconstr-name)) syntax construction by itself does not make polymorphic the type variable it introduces, but it can be combined with explicit polymorphic annotations where needed. The above rule is provided as syntactic sugar to make this easier:
```
let rec f : type t1 t2. t1 * t2 list -> t1 = …
```
is automatically expanded into
```
let rec f : 't1 't2. 't1 * 't2 list -> 't1 =
fun (type t1) (type t2) -> ( … : t1 * t2 list -> t1)
```
This syntax can be very useful when defining recursive functions involving GADTs, see the section [12.10](gadts#s%3Agadts) for a more detailed explanation.
The same feature is provided for method definitions.
ocaml None
[](#s:compilation-units)11.12 Compilation units
-------------------------------------------------
| | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- |
|
| | | |
| --- | --- | --- |
| unit-interface | ::= | { [specification](modtypes#specification) [;;] } |
| |
| unit-implementation | ::= | [ [module-items](modules#module-items) ] |
|
Compilation units bridge the module system and the separate compilation system. A compilation unit is composed of two parts: an interface and an implementation. The interface contains a sequence of specifications, just as the inside of a sig … end signature expression. The implementation contains a sequence of definitions and expressions, just as the inside of a struct … end module expression. A compilation unit also has a name unit-name, derived from the names of the files containing the interface and the implementation (see chapter [13](comp#c%3Acamlc) for more details). A compilation unit behaves roughly as the module definition
module unit-name : sig [unit-interface](#unit-interface) end = struct [unit-implementation](#unit-implementation) end
A compilation unit can refer to other compilation units by their names, as if they were regular modules. For instance, if U is a compilation unit that defines a type t, other compilation units can refer to that type under the name U.t; they can also refer to U as a whole structure. Except for names of other compilation units, a unit interface or unit implementation must not have any other free variables. In other terms, the type-checking and compilation of an interface or implementation proceeds in the initial environment
name1 : sig [specification](modtypes#specification)1 end … namen : sig [specification](modtypes#specification)n end
where name1 … namen are the names of the other compilation units available in the search path (see chapter [13](comp#c%3Acamlc) for more details) and [specification](modtypes#specification)1 … [specification](modtypes#specification)n are their respective interfaces.
| programming_docs |
ocaml Module Obj.Extension_constructor Module Obj.Extension\_constructor
=================================
```
module Extension_constructor: sig .. end
```
```
type t = extension_constructor
```
```
val of_val : 'a -> t
```
```
val name : t -> string
```
```
val id : t -> int
```
ocaml Functor Sys.Immediate64.Make Functor Sys.Immediate64.Make
============================
```
module Make: functor (Immediate : Immediate) -> functor (Non_immediate : Non_immediate) -> sig .. end
```
| | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- |
| **Parameters:** |
| | | |
| --- | --- | --- |
| `Immediate` | : | `[Immediate](sys.immediate64.immediate)` |
| `Non_immediate` | : | `[Non\_immediate](sys.immediate64.non_immediate)` |
|
```
type t
```
```
type 'a repr =
```
| | |
| --- | --- |
| `|` | `Immediate : `[Sys.Immediate64.Immediate.t](sys.immediate64.immediate#TYPEt) [repr](sys.immediate64.make#TYPErepr)`` |
| `|` | `Non\_immediate : `[Sys.Immediate64.Non\_immediate.t](sys.immediate64.non_immediate#TYPEt) [repr](sys.immediate64.make#TYPErepr)`` |
```
val repr : t repr
```
ocaml Module StdLabels.Array Module StdLabels.Array
======================
```
module Array: ArrayLabels
```
```
type 'a t = 'a array
```
An alias for the type of arrays.
```
val length : 'a array -> int
```
Return the length (number of elements) of the given array.
```
val get : 'a array -> int -> 'a
```
`get a n` returns the element number `n` of array `a`. The first element has number 0. The last element has number `length a - 1`. You can also write `a.(n)` instead of `get a n`.
* **Raises** `Invalid_argument` if `n` is outside the range 0 to `(length a - 1)`.
```
val set : 'a array -> int -> 'a -> unit
```
`set a n x` modifies array `a` in place, replacing element number `n` with `x`. You can also write `a.(n) <- x` instead of `set a n x`.
* **Raises** `Invalid_argument` if `n` is outside the range 0 to `length a - 1`.
```
val make : int -> 'a -> 'a array
```
`make n x` returns a fresh array of length `n`, initialized with `x`. All the elements of this new array are initially physically equal to `x` (in the sense of the `==` predicate). Consequently, if `x` is mutable, it is shared among all elements of the array, and modifying `x` through one of the array entries will modify all other entries at the same time.
* **Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_array_length`. If the value of `x` is a floating-point number, then the maximum size is only `Sys.max_array_length / 2`.
```
val create_float : int -> float array
```
`create_float n` returns a fresh float array of length `n`, with uninitialized data.
* **Since** 4.03
```
val init : int -> f:(int -> 'a) -> 'a array
```
`init n ~f` returns a fresh array of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n ~f` tabulates the results of `f` applied to the integers `0` to `n-1`.
* **Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_array_length`. If the return type of `f` is `float`, then the maximum size is only `Sys.max_array_length / 2`.
```
val make_matrix : dimx:int -> dimy:int -> 'a -> 'a array array
```
`make_matrix ~dimx ~dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. All the elements of this new matrix are initially physically equal to `e`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`.
* **Raises** `Invalid_argument` if `dimx` or `dimy` is negative or greater than [`Sys.max_array_length`](sys#VALmax_array_length). If the value of `e` is a floating-point number, then the maximum size is only `Sys.max_array_length / 2`.
```
val append : 'a array -> 'a array -> 'a array
```
`append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`.
* **Raises** `Invalid_argument` if `length v1 + length v2 > Sys.max_array_length`.
```
val concat : 'a array list -> 'a array
```
Same as [`ArrayLabels.append`](arraylabels#VALappend), but concatenates a list of arrays.
```
val sub : 'a array -> pos:int -> len:int -> 'a array
```
`sub a ~pos ~len` returns a fresh array of length `len`, containing the elements number `pos` to `pos + len - 1` of array `a`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid subarray of `a`; that is, if `pos < 0`, or `len < 0`, or `pos + len > length a`.
```
val copy : 'a array -> 'a array
```
`copy a` returns a copy of `a`, that is, a fresh array containing the same elements as `a`.
```
val fill : 'a array -> pos:int -> len:int -> 'a -> unit
```
`fill a ~pos ~len x` modifies the array `a` in place, storing `x` in elements number `pos` to `pos + len - 1`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid subarray of `a`.
```
val blit : src:'a array -> src_pos:int -> dst:'a array -> dst_pos:int -> len:int -> unit
```
`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` elements from array `src`, starting at element number `src_pos`, to array `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap.
* **Raises** `Invalid_argument` if `src_pos` and `len` do not designate a valid subarray of `src`, or if `dst_pos` and `len` do not designate a valid subarray of `dst`.
```
val to_list : 'a array -> 'a list
```
`to_list a` returns the list of all the elements of `a`.
```
val of_list : 'a list -> 'a array
```
`of_list l` returns a fresh array containing the elements of `l`.
* **Raises** `Invalid_argument` if the length of `l` is greater than `Sys.max_array_length`.
Iterators
---------
```
val iter : f:('a -> unit) -> 'a array -> unit
```
`iter ~f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`.
```
val iteri : f:(int -> 'a -> unit) -> 'a array -> unit
```
Same as [`ArrayLabels.iter`](arraylabels#VALiter), but the function is applied to the index of the element as first argument, and the element itself as second argument.
```
val map : f:('a -> 'b) -> 'a array -> 'b array
```
`map ~f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`.
```
val mapi : f:(int -> 'a -> 'b) -> 'a array -> 'b array
```
Same as [`ArrayLabels.map`](arraylabels#VALmap), but the function is applied to the index of the element as first argument, and the element itself as second argument.
```
val fold_left : f:('a -> 'b -> 'a) -> init:'a -> 'b array -> 'a
```
`fold_left ~f ~init a` computes `f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)`, where `n` is the length of the array `a`.
```
val fold_left_map : f:('a -> 'b -> 'a * 'c) -> init:'a -> 'b array -> 'a * 'c array
```
`fold_left_map` is a combination of [`ArrayLabels.fold_left`](arraylabels#VALfold_left) and [`ArrayLabels.map`](arraylabels#VALmap) that threads an accumulator through calls to `f`.
* **Since** 4.13.0
```
val fold_right : f:('b -> 'a -> 'a) -> 'b array -> init:'a -> 'a
```
`fold_right ~f a ~init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the array `a`.
Iterators on two arrays
-----------------------
```
val iter2 : f:('a -> 'b -> unit) -> 'a array -> 'b array -> unit
```
`iter2 ~f a b` applies function `f` to all the elements of `a` and `b`.
* **Since** 4.05.0
* **Raises** `Invalid_argument` if the arrays are not the same size.
```
val map2 : f:('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array
```
`map2 ~f a b` applies function `f` to all the elements of `a` and `b`, and builds an array with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`.
* **Since** 4.05.0
* **Raises** `Invalid_argument` if the arrays are not the same size.
Array scanning
--------------
```
val for_all : f:('a -> bool) -> 'a array -> bool
```
`for_all ~f [|a1; ...; an|]` checks if all elements of the array satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`.
* **Since** 4.03.0
```
val exists : f:('a -> bool) -> 'a array -> bool
```
`exists ~f [|a1; ...; an|]` checks if at least one element of the array satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`.
* **Since** 4.03.0
```
val for_all2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool
```
Same as [`ArrayLabels.for_all`](arraylabels#VALfor_all), but for a two-argument predicate.
* **Since** 4.11.0
* **Raises** `Invalid_argument` if the two arrays have different lengths.
```
val exists2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool
```
Same as [`ArrayLabels.exists`](arraylabels#VALexists), but for a two-argument predicate.
* **Since** 4.11.0
* **Raises** `Invalid_argument` if the two arrays have different lengths.
```
val mem : 'a -> set:'a array -> bool
```
`mem a ~set` is true if and only if `a` is structurally equal to an element of `l` (i.e. there is an `x` in `l` such that `compare a x = 0`).
* **Since** 4.03.0
```
val memq : 'a -> set:'a array -> bool
```
Same as [`ArrayLabels.mem`](arraylabels#VALmem), but uses physical equality instead of structural equality to compare list elements.
* **Since** 4.03.0
```
val find_opt : f:('a -> bool) -> 'a array -> 'a option
```
`find_opt ~f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`.
* **Since** 4.13.0
```
val find_map : f:('a -> 'b option) -> 'a array -> 'b option
```
`find_map ~f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist.
* **Since** 4.13.0
Arrays of pairs
---------------
```
val split : ('a * 'b) array -> 'a array * 'b array
```
`split [|(a1,b1); ...; (an,bn)|]` is `([|a1; ...; an|], [|b1; ...; bn|])`.
* **Since** 4.13.0
```
val combine : 'a array -> 'b array -> ('a * 'b) array
```
`combine [|a1; ...; an|] [|b1; ...; bn|]` is `[|(a1,b1); ...; (an,bn)|]`. Raise `Invalid\_argument` if the two arrays have different lengths.
* **Since** 4.13.0
Sorting
-------
```
val sort : cmp:('a -> 'a -> int) -> 'a array -> unit
```
Sort an array in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`compare`](stdlib#VALcompare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant stack space.
Specification of the comparison function: Let `a` be the array and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` :
* `cmp x y` > 0 if and only if `cmp y x` < 0
* if `cmp x y` >= 0 and `cmp y z` >= 0 then `cmp x z` >= 0
When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` :
* `cmp a.(i) a.(j)` >= 0 if and only if i >= j
```
val stable_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
```
Same as [`ArrayLabels.sort`](arraylabels#VALsort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space.
The current implementation uses Merge Sort. It uses a temporary array of length `n/2`, where `n` is the length of the array. It is usually faster than the current implementation of [`ArrayLabels.sort`](arraylabels#VALsort).
```
val fast_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
```
Same as [`ArrayLabels.sort`](arraylabels#VALsort) or [`ArrayLabels.stable_sort`](arraylabels#VALstable_sort), whichever is faster on typical input.
Arrays and Sequences
--------------------
```
val to_seq : 'a array -> 'a Seq.t
```
Iterate on the array, in increasing order. Modifications of the array during iteration will be reflected in the sequence.
* **Since** 4.07
```
val to_seqi : 'a array -> (int * 'a) Seq.t
```
Iterate on the array, in increasing order, yielding indices along elements. Modifications of the array during iteration will be reflected in the sequence.
* **Since** 4.07
```
val of_seq : 'a Seq.t -> 'a array
```
Create an array from the generator
* **Since** 4.07
Arrays and concurrency safety
-----------------------------
Care must be taken when concurrently accessing arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.
### Atomicity
Every array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays.
For example, consider the following program:
```
let size = 100_000_000
let a = ArrayLabels.make size 1
let d1 = Domain.spawn (fun () ->
ArrayLabels.iteri ~f:(fun i x -> a.(i) <- x + 1) a
)
let d2 = Domain.spawn (fun () ->
ArrayLabels.iteri ~f:(fun i x -> a.(i) <- 2 * x + 1) a
)
let () = Domain.join d1; Domain.join d2
```
After executing this code, each field of the array `a` is either `2`, `3`, `4` or `5`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](mutex#TYPEt)).
### Data races
If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.
A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location (with a few exceptions for float arrays).
### Float arrays
Float arrays have two supplementary caveats in the presence of data races.
First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution.
For instance, at the end of
```
let zeros = Array.make size 0.
let max_floats = Array.make size Float.max_float
let res = Array.copy zeros
let d1 = Domain.spawn (fun () -> Array.blit zeros 0 res 0 size)
let d2 = Domain.spawn (fun () -> Array.blit max_floats 0 res 0 size)
let () = Domain.join d1; Domain.join d2
```
the `res` array might contain values that are neither `0.` nor `max_float`.
Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation.
ocaml Module Unix.LargeFile Module Unix.LargeFile
=====================
```
module LargeFile: sig .. end
```
File operations on large files. This sub-module provides 64-bit variants of the functions [`Unix.LargeFile.lseek`](unix.largefile#VALlseek) (for positioning a file descriptor), [`Unix.LargeFile.truncate`](unix.largefile#VALtruncate) and [`Unix.LargeFile.ftruncate`](unix.largefile#VALftruncate) (for changing the size of a file), and [`Unix.LargeFile.stat`](unix.largefile#VALstat), [`Unix.LargeFile.lstat`](unix.largefile#VALlstat) and [`Unix.LargeFile.fstat`](unix.largefile#VALfstat) (for obtaining information on files). These alternate functions represent positions and sizes by 64-bit integers (type `int64`) instead of regular integers (type `int`), thus allowing operating on files whose sizes are greater than `max_int`.
```
val lseek : Unix.file_descr -> int64 -> Unix.seek_command -> int64
```
See `lseek`.
```
val truncate : string -> int64 -> unit
```
See `truncate`.
```
val ftruncate : Unix.file_descr -> int64 -> unit
```
See `ftruncate`.
```
type stats = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `st\_dev : `int`;` | `(*` | Device number | `*)` |
| | `st\_ino : `int`;` | `(*` | Inode number | `*)` |
| | `st\_kind : `[Unix.file\_kind](unix#TYPEfile_kind)`;` | `(*` | Kind of the file | `*)` |
| | `st\_perm : `[Unix.file\_perm](unix#TYPEfile_perm)`;` | `(*` | Access rights | `*)` |
| | `st\_nlink : `int`;` | `(*` | Number of links | `*)` |
| | `st\_uid : `int`;` | `(*` | User id of the owner | `*)` |
| | `st\_gid : `int`;` | `(*` | Group ID of the file's group | `*)` |
| | `st\_rdev : `int`;` | `(*` | Device ID (if special file) | `*)` |
| | `st\_size : `int64`;` | `(*` | Size in bytes | `*)` |
| | `st\_atime : `float`;` | `(*` | Last access time | `*)` |
| | `st\_mtime : `float`;` | `(*` | Last modification time | `*)` |
| | `st\_ctime : `float`;` | `(*` | Last status change time | `*)` |
`}`
```
val stat : string -> stats
```
```
val lstat : string -> stats
```
```
val fstat : Unix.file_descr -> stats
```
ocaml Module type MoreLabels.Hashtbl.S Module type MoreLabels.Hashtbl.S
================================
```
module type S = sig .. end
```
The output signature of the functor [`MoreLabels.Hashtbl.Make`](morelabels.hashtbl.make).
```
type key
```
```
type 'a t
```
```
val create : int -> 'a t
```
```
val clear : 'a t -> unit
```
```
val reset : 'a t -> unit
```
* **Since** 4.00.0
```
val copy : 'a t -> 'a t
```
```
val add : 'a t -> key:key -> data:'a -> unit
```
```
val remove : 'a t -> key -> unit
```
```
val find : 'a t -> key -> 'a
```
```
val find_opt : 'a t -> key -> 'a option
```
* **Since** 4.05.0
```
val find_all : 'a t -> key -> 'a list
```
```
val replace : 'a t -> key:key -> data:'a -> unit
```
```
val mem : 'a t -> key -> bool
```
```
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
```
```
val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit
```
* **Since** 4.03.0
```
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
```
```
val length : 'a t -> int
```
```
val stats : 'a t -> MoreLabels.Hashtbl.statistics
```
* **Since** 4.00.0
```
val to_seq : 'a t -> (key * 'a) Seq.t
```
* **Since** 4.07
```
val to_seq_keys : 'a t -> key Seq.t
```
* **Since** 4.07
```
val to_seq_values : 'a t -> 'a Seq.t
```
* **Since** 4.07
```
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
```
* **Since** 4.07
```
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
```
* **Since** 4.07
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
* **Since** 4.07
ocaml Module Bigarray Module Bigarray
===============
```
module Bigarray: sig .. end
```
Large, multi-dimensional, numerical arrays.
This module implements multi-dimensional arrays of integers and floating-point numbers, thereafter referred to as 'Bigarrays', to distinguish them from the standard OCaml arrays described in [`Array`](array).
The implementation allows efficient sharing of large numerical arrays between OCaml code and C or Fortran numerical libraries.
The main differences between 'Bigarrays' and standard OCaml arrays are as follows:
* Bigarrays are not limited in size, unlike OCaml arrays. (Normal float arrays are limited to 2,097,151 elements on a 32-bit platform, and normal arrays of other types to 4,194,303 elements.)
* Bigarrays are multi-dimensional. Any number of dimensions between 0 and 16 is supported. In contrast, OCaml arrays are mono-dimensional and require encoding multi-dimensional arrays as arrays of arrays.
* Bigarrays can only contain integers and floating-point numbers, while OCaml arrays can contain arbitrary OCaml data types.
* Bigarrays provide more space-efficient storage of integer and floating-point elements than normal OCaml arrays, in particular because they support 'small' types such as single-precision floats and 8 and 16-bit integers, in addition to the standard OCaml types of double-precision floats and 32 and 64-bit integers.
* The memory layout of Bigarrays is entirely compatible with that of arrays in C and Fortran, allowing large arrays to be passed back and forth between OCaml code and C / Fortran code with no data copying at all.
* Bigarrays support interesting high-level operations that normal arrays do not provide efficiently, such as extracting sub-arrays and 'slicing' a multi-dimensional array along certain dimensions, all without any copying.
Users of this module are encouraged to do `open Bigarray` in their source, then refer to array types and operations via short dot notation, e.g. `Array1.t` or `Array2.sub`.
Bigarrays support all the OCaml ad-hoc polymorphic operations:
* comparisons (`=`, `<>`, `<=`, etc, as well as [`compare`](stdlib#VALcompare));
* hashing (module `Hash`);
* and structured input-output (the functions from the [`Marshal`](marshal) module, as well as [`output_value`](stdlib#VALoutput_value) and [`input_value`](stdlib#VALinput_value)).
Element kinds
-------------
Bigarrays can contain elements of the following kinds:
* IEEE single precision (32 bits) floating-point numbers ([`Bigarray.float32_elt`](bigarray#TYPEfloat32_elt)),
* IEEE double precision (64 bits) floating-point numbers ([`Bigarray.float64_elt`](bigarray#TYPEfloat64_elt)),
* IEEE single precision (2 \* 32 bits) floating-point complex numbers ([`Bigarray.complex32_elt`](bigarray#TYPEcomplex32_elt)),
* IEEE double precision (2 \* 64 bits) floating-point complex numbers ([`Bigarray.complex64_elt`](bigarray#TYPEcomplex64_elt)),
* 8-bit integers (signed or unsigned) ([`Bigarray.int8_signed_elt`](bigarray#TYPEint8_signed_elt) or [`Bigarray.int8_unsigned_elt`](bigarray#TYPEint8_unsigned_elt)),
* 16-bit integers (signed or unsigned) ([`Bigarray.int16_signed_elt`](bigarray#TYPEint16_signed_elt) or [`Bigarray.int16_unsigned_elt`](bigarray#TYPEint16_unsigned_elt)),
* OCaml integers (signed, 31 bits on 32-bit architectures, 63 bits on 64-bit architectures) ([`Bigarray.int_elt`](bigarray#TYPEint_elt)),
* 32-bit signed integers ([`Bigarray.int32_elt`](bigarray#TYPEint32_elt)),
* 64-bit signed integers ([`Bigarray.int64_elt`](bigarray#TYPEint64_elt)),
* platform-native signed integers (32 bits on 32-bit architectures, 64 bits on 64-bit architectures) ([`Bigarray.nativeint_elt`](bigarray#TYPEnativeint_elt)).
Each element kind is represented at the type level by one of the `*_elt` types defined below (defined with a single constructor instead of abstract types for technical injectivity reasons).
```
type float32_elt =
```
| | |
| --- | --- |
| `|` | `Float32\_elt` |
```
type float64_elt =
```
| | |
| --- | --- |
| `|` | `Float64\_elt` |
```
type int8_signed_elt =
```
| | |
| --- | --- |
| `|` | `Int8\_signed\_elt` |
```
type int8_unsigned_elt =
```
| | |
| --- | --- |
| `|` | `Int8\_unsigned\_elt` |
```
type int16_signed_elt =
```
| | |
| --- | --- |
| `|` | `Int16\_signed\_elt` |
```
type int16_unsigned_elt =
```
| | |
| --- | --- |
| `|` | `Int16\_unsigned\_elt` |
```
type int32_elt =
```
| | |
| --- | --- |
| `|` | `Int32\_elt` |
```
type int64_elt =
```
| | |
| --- | --- |
| `|` | `Int64\_elt` |
```
type int_elt =
```
| | |
| --- | --- |
| `|` | `Int\_elt` |
```
type nativeint_elt =
```
| | |
| --- | --- |
| `|` | `Nativeint\_elt` |
```
type complex32_elt =
```
| | |
| --- | --- |
| `|` | `Complex32\_elt` |
```
type complex64_elt =
```
| | |
| --- | --- |
| `|` | `Complex64\_elt` |
```
type ('a, 'b) kind =
```
| | |
| --- | --- |
| `|` | `Float32 : `(float, [float32\_elt](bigarray#TYPEfloat32_elt)) [kind](bigarray#TYPEkind)`` |
| `|` | `Float64 : `(float, [float64\_elt](bigarray#TYPEfloat64_elt)) [kind](bigarray#TYPEkind)`` |
| `|` | `Int8\_signed : `(int, [int8\_signed\_elt](bigarray#TYPEint8_signed_elt)) [kind](bigarray#TYPEkind)`` |
| `|` | `Int8\_unsigned : `(int, [int8\_unsigned\_elt](bigarray#TYPEint8_unsigned_elt)) [kind](bigarray#TYPEkind)`` |
| `|` | `Int16\_signed : `(int, [int16\_signed\_elt](bigarray#TYPEint16_signed_elt)) [kind](bigarray#TYPEkind)`` |
| `|` | `Int16\_unsigned : `(int, [int16\_unsigned\_elt](bigarray#TYPEint16_unsigned_elt)) [kind](bigarray#TYPEkind)`` |
| `|` | `Int32 : `(int32, [int32\_elt](bigarray#TYPEint32_elt)) [kind](bigarray#TYPEkind)`` |
| `|` | `Int64 : `(int64, [int64\_elt](bigarray#TYPEint64_elt)) [kind](bigarray#TYPEkind)`` |
| `|` | `Int : `(int, [int\_elt](bigarray#TYPEint_elt)) [kind](bigarray#TYPEkind)`` |
| `|` | `Nativeint : `(nativeint, [nativeint\_elt](bigarray#TYPEnativeint_elt)) [kind](bigarray#TYPEkind)`` |
| `|` | `Complex32 : `([Complex.t](complex#TYPEt), [complex32\_elt](bigarray#TYPEcomplex32_elt)) [kind](bigarray#TYPEkind)`` |
| `|` | `Complex64 : `([Complex.t](complex#TYPEt), [complex64\_elt](bigarray#TYPEcomplex64_elt)) [kind](bigarray#TYPEkind)`` |
| `|` | `Char : `(char, [int8\_unsigned\_elt](bigarray#TYPEint8_unsigned_elt)) [kind](bigarray#TYPEkind)`` |
To each element kind is associated an OCaml type, which is the type of OCaml values that can be stored in the Bigarray or read back from it. This type is not necessarily the same as the type of the array elements proper: for instance, a Bigarray whose elements are of kind `float32_elt` contains 32-bit single precision floats, but reading or writing one of its elements from OCaml uses the OCaml type `float`, which is 64-bit double precision floats.
The GADT type `('a, 'b) kind` captures this association of an OCaml type `'a` for values read or written in the Bigarray, and of an element kind `'b` which represents the actual contents of the Bigarray. Its constructors list all possible associations of OCaml types with element kinds, and are re-exported below for backward-compatibility reasons.
Using a generalized algebraic datatype (GADT) here allows writing well-typed polymorphic functions whose return type depend on the argument type, such as:
```
let zero : type a b. (a, b) kind -> a = function
| Float32 -> 0.0 | Complex32 -> Complex.zero
| Float64 -> 0.0 | Complex64 -> Complex.zero
| Int8_signed -> 0 | Int8_unsigned -> 0
| Int16_signed -> 0 | Int16_unsigned -> 0
| Int32 -> 0l | Int64 -> 0L
| Int -> 0 | Nativeint -> 0n
| Char -> '\000'
```
```
val float32 : (float, float32_elt) kind
```
See [`Bigarray.char`](bigarray#VALchar).
```
val float64 : (float, float64_elt) kind
```
See [`Bigarray.char`](bigarray#VALchar).
```
val complex32 : (Complex.t, complex32_elt) kind
```
See [`Bigarray.char`](bigarray#VALchar).
```
val complex64 : (Complex.t, complex64_elt) kind
```
See [`Bigarray.char`](bigarray#VALchar).
```
val int8_signed : (int, int8_signed_elt) kind
```
See [`Bigarray.char`](bigarray#VALchar).
```
val int8_unsigned : (int, int8_unsigned_elt) kind
```
See [`Bigarray.char`](bigarray#VALchar).
```
val int16_signed : (int, int16_signed_elt) kind
```
See [`Bigarray.char`](bigarray#VALchar).
```
val int16_unsigned : (int, int16_unsigned_elt) kind
```
See [`Bigarray.char`](bigarray#VALchar).
```
val int : (int, int_elt) kind
```
See [`Bigarray.char`](bigarray#VALchar).
```
val int32 : (int32, int32_elt) kind
```
See [`Bigarray.char`](bigarray#VALchar).
```
val int64 : (int64, int64_elt) kind
```
See [`Bigarray.char`](bigarray#VALchar).
```
val nativeint : (nativeint, nativeint_elt) kind
```
See [`Bigarray.char`](bigarray#VALchar).
```
val char : (char, int8_unsigned_elt) kind
```
As shown by the types of the values above, Bigarrays of kind `float32_elt` and `float64_elt` are accessed using the OCaml type `float`. Bigarrays of complex kinds `complex32_elt`, `complex64_elt` are accessed with the OCaml type [`Complex.t`](complex#TYPEt). Bigarrays of integer kinds are accessed using the smallest OCaml integer type large enough to represent the array elements: `int` for 8- and 16-bit integer Bigarrays, as well as OCaml-integer Bigarrays; `int32` for 32-bit integer Bigarrays; `int64` for 64-bit integer Bigarrays; and `nativeint` for platform-native integer Bigarrays. Finally, Bigarrays of kind `int8_unsigned_elt` can also be accessed as arrays of characters instead of arrays of small integers, by using the kind value `char` instead of `int8_unsigned`.
```
val kind_size_in_bytes : ('a, 'b) kind -> int
```
`kind_size_in_bytes k` is the number of bytes used to store an element of type `k`.
* **Since** 4.03.0
Array layouts
-------------
```
type c_layout =
```
| | |
| --- | --- |
| `|` | `C\_layout\_typ` |
See [`Bigarray.fortran_layout`](bigarray#TYPEfortran_layout).
```
type fortran_layout =
```
| | |
| --- | --- |
| `|` | `Fortran\_layout\_typ` |
To facilitate interoperability with existing C and Fortran code, this library supports two different memory layouts for Bigarrays, one compatible with the C conventions, the other compatible with the Fortran conventions.
In the C-style layout, array indices start at 0, and multi-dimensional arrays are laid out in row-major format. That is, for a two-dimensional array, all elements of row 0 are contiguous in memory, followed by all elements of row 1, etc. In other terms, the array elements at `(x,y)` and `(x, y+1)` are adjacent in memory.
In the Fortran-style layout, array indices start at 1, and multi-dimensional arrays are laid out in column-major format. That is, for a two-dimensional array, all elements of column 0 are contiguous in memory, followed by all elements of column 1, etc. In other terms, the array elements at `(x,y)` and `(x+1, y)` are adjacent in memory.
Each layout style is identified at the type level by the phantom types [`Bigarray.c_layout`](bigarray#TYPEc_layout) and [`Bigarray.fortran_layout`](bigarray#TYPEfortran_layout) respectively.
### Supported layouts
The GADT type `'a layout` represents one of the two supported memory layouts: C-style or Fortran-style. Its constructors are re-exported as values below for backward-compatibility reasons.
```
type 'a layout =
```
| | |
| --- | --- |
| `|` | `C\_layout : `[c\_layout](bigarray#TYPEc_layout) [layout](bigarray#TYPElayout)`` |
| `|` | `Fortran\_layout : `[fortran\_layout](bigarray#TYPEfortran_layout) [layout](bigarray#TYPElayout)`` |
```
val c_layout : c_layout layout
```
```
val fortran_layout : fortran_layout layout
```
Generic arrays (of arbitrarily many dimensions)
-----------------------------------------------
```
module Genarray: sig .. end
```
Zero-dimensional arrays
-----------------------
```
module Array0: sig .. end
```
Zero-dimensional arrays.
One-dimensional arrays
----------------------
```
module Array1: sig .. end
```
One-dimensional arrays.
Two-dimensional arrays
----------------------
```
module Array2: sig .. end
```
Two-dimensional arrays.
Three-dimensional arrays
------------------------
```
module Array3: sig .. end
```
Three-dimensional arrays.
Coercions between generic Bigarrays and fixed-dimension Bigarrays
-----------------------------------------------------------------
```
val genarray_of_array0 : ('a, 'b, 'c) Array0.t -> ('a, 'b, 'c) Genarray.t
```
Return the generic Bigarray corresponding to the given zero-dimensional Bigarray.
* **Since** 4.05.0
```
val genarray_of_array1 : ('a, 'b, 'c) Array1.t -> ('a, 'b, 'c) Genarray.t
```
Return the generic Bigarray corresponding to the given one-dimensional Bigarray.
```
val genarray_of_array2 : ('a, 'b, 'c) Array2.t -> ('a, 'b, 'c) Genarray.t
```
Return the generic Bigarray corresponding to the given two-dimensional Bigarray.
```
val genarray_of_array3 : ('a, 'b, 'c) Array3.t -> ('a, 'b, 'c) Genarray.t
```
Return the generic Bigarray corresponding to the given three-dimensional Bigarray.
```
val array0_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array0.t
```
Return the zero-dimensional Bigarray corresponding to the given generic Bigarray.
* **Since** 4.05.0
* **Raises** `Invalid_argument` if the generic Bigarray does not have exactly zero dimension.
```
val array1_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array1.t
```
Return the one-dimensional Bigarray corresponding to the given generic Bigarray.
* **Raises** `Invalid_argument` if the generic Bigarray does not have exactly one dimension.
```
val array2_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array2.t
```
Return the two-dimensional Bigarray corresponding to the given generic Bigarray.
* **Raises** `Invalid_argument` if the generic Bigarray does not have exactly two dimensions.
```
val array3_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array3.t
```
Return the three-dimensional Bigarray corresponding to the given generic Bigarray.
* **Raises** `Invalid_argument` if the generic Bigarray does not have exactly three dimensions.
Re-shaping Bigarrays
--------------------
```
val reshape : ('a, 'b, 'c) Genarray.t -> int array -> ('a, 'b, 'c) Genarray.t
```
`reshape b [|d1;...;dN|]` converts the Bigarray `b` to a `N`-dimensional array of dimensions `d1`...`dN`. The returned array and the original array `b` share their data and have the same layout. For instance, assuming that `b` is a one-dimensional array of dimension 12, `reshape b [|3;4|]` returns a two-dimensional array `b'` of dimensions 3 and 4. If `b` has C layout, the element `(x,y)` of `b'` corresponds to the element `x * 3 + y` of `b`. If `b` has Fortran layout, the element `(x,y)` of `b'` corresponds to the element `x + (y - 1) * 4` of `b`. The returned Bigarray must have exactly the same number of elements as the original Bigarray `b`. That is, the product of the dimensions of `b` must be equal to `i1 * ... * iN`. Otherwise, `Invalid\_argument` is raised.
```
val reshape_0 : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array0.t
```
Specialized version of [`Bigarray.reshape`](bigarray#VALreshape) for reshaping to zero-dimensional arrays.
* **Since** 4.05.0
```
val reshape_1 : ('a, 'b, 'c) Genarray.t -> int -> ('a, 'b, 'c) Array1.t
```
Specialized version of [`Bigarray.reshape`](bigarray#VALreshape) for reshaping to one-dimensional arrays.
```
val reshape_2 : ('a, 'b, 'c) Genarray.t -> int -> int -> ('a, 'b, 'c) Array2.t
```
Specialized version of [`Bigarray.reshape`](bigarray#VALreshape) for reshaping to two-dimensional arrays.
```
val reshape_3 : ('a, 'b, 'c) Genarray.t -> int -> int -> int -> ('a, 'b, 'c) Array3.t
```
Specialized version of [`Bigarray.reshape`](bigarray#VALreshape) for reshaping to three-dimensional arrays.
Bigarrays and concurrency safety
--------------------------------
Care must be taken when concurrently accessing bigarrays from multiple domains: accessing a bigarray will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.
### Atomicity
Every bigarray operation that accesses more than one array element is not atomic. This includes slicing, bliting, and filling bigarrays.
For example, consider the following program:
```
open Bigarray
let size = 100_000_000
let a = Array1.init Int C_layout size (fun _ -> 1)
let update f a () =
for i = 0 to size - 1 do a.{i} <- f a.{i} done
let d1 = Domain.spawn (update (fun x -> x + 1) a)
let d2 = Domain.spawn (update (fun x -> 2 * x + 1) a)
let () = Domain.join d1; Domain.join d2
```
After executing this code, each field of the bigarray `a` is either `2`, `3`, `4` or `5`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](mutex#TYPEt)).
### Data races
If two domains only access disjoint parts of the bigarray, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.
A data race is said to occur when two domains access the same bigarray element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the bigarray elements.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains.
### Tearing
Bigarrays have a distinct caveat in the presence of data races: concurrent bigarray operations might produce surprising values due to tearing. More precisely, the interleaving of partial writes and reads might create values that would not exist with a sequential execution. For instance, at the end of
```
let res = Array1.init Complex64 c_layout size (fun _ -> Complex.zero)
let d1 = Domain.spawn (fun () -> Array1.fill res Complex.one)
let d2 = Domain.spawn (fun () -> Array1.fill res Complex.i)
let () = Domain.join d1; Domain.join d2
```
the `res` bigarray might contain values that are neither `Complex.i` nor `Complex.one` (for instance `1 + i`).
| programming_docs |
ocaml Module type MoreLabels.Hashtbl.SeededS Module type MoreLabels.Hashtbl.SeededS
======================================
```
module type SeededS = sig .. end
```
The output signature of the functor [`MoreLabels.Hashtbl.MakeSeeded`](morelabels.hashtbl.makeseeded).
* **Since** 4.00.0
```
type key
```
```
type 'a t
```
```
val create : ?random:bool -> int -> 'a t
```
```
val clear : 'a t -> unit
```
```
val reset : 'a t -> unit
```
```
val copy : 'a t -> 'a t
```
```
val add : 'a t -> key:key -> data:'a -> unit
```
```
val remove : 'a t -> key -> unit
```
```
val find : 'a t -> key -> 'a
```
```
val find_opt : 'a t -> key -> 'a option
```
* **Since** 4.05.0
```
val find_all : 'a t -> key -> 'a list
```
```
val replace : 'a t -> key:key -> data:'a -> unit
```
```
val mem : 'a t -> key -> bool
```
```
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
```
```
val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit
```
* **Since** 4.03.0
```
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
```
```
val length : 'a t -> int
```
```
val stats : 'a t -> MoreLabels.Hashtbl.statistics
```
```
val to_seq : 'a t -> (key * 'a) Seq.t
```
* **Since** 4.07
```
val to_seq_keys : 'a t -> key Seq.t
```
* **Since** 4.07
```
val to_seq_values : 'a t -> 'a Seq.t
```
* **Since** 4.07
```
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
```
* **Since** 4.07
```
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
```
* **Since** 4.07
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
* **Since** 4.07
ocaml Module Stdlib Module Stdlib
=============
```
module Stdlib: sig .. end
```
The OCaml Standard library.
This module is automatically opened at the beginning of each compilation. All components of this module can therefore be referred by their short name, without prefixing them by `Stdlib`.
In particular, it provides the basic operations over the built-in types (numbers, booleans, byte sequences, strings, exceptions, references, lists, arrays, input-output channels, ...) and the [standard library modules](stdlib#modules).
Exceptions
----------
```
val raise : exn -> 'a
```
Raise the given exception value
```
val raise_notrace : exn -> 'a
```
A faster version `raise` which does not record the backtrace.
* **Since** 4.02.0
```
val invalid_arg : string -> 'a
```
Raise exception `Invalid\_argument` with the given string.
```
val failwith : string -> 'a
```
Raise exception `Failure` with the given string.
```
exception Exit
```
The `Exit` exception is not raised by any library function. It is provided for use in your programs.
```
exception Match_failure of (string * int * int)
```
Exception raised when none of the cases of a pattern-matching apply. The arguments are the location of the match keyword in the source code (file name, line number, column number).
```
exception Assert_failure of (string * int * int)
```
Exception raised when an assertion fails. The arguments are the location of the assert keyword in the source code (file name, line number, column number).
```
exception Invalid_argument of string
```
Exception raised by library functions to signal that the given arguments do not make sense. The string gives some information to the programmer. As a general rule, this exception should not be caught, it denotes a programming error and the code should be modified not to trigger it.
```
exception Failure of string
```
Exception raised by library functions to signal that they are undefined on the given arguments. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Failure \_ instead).
```
exception Not_found
```
Exception raised by search functions when the desired object could not be found.
```
exception Out_of_memory
```
Exception raised by the garbage collector when there is insufficient memory to complete the computation. (Not reliable for allocations on the minor heap.)
```
exception Stack_overflow
```
Exception raised by the bytecode interpreter when the evaluation stack reaches its maximal size. This often indicates infinite or excessively deep recursion in the user's program.
Before 4.10, it was not fully implemented by the native-code compiler.
```
exception Sys_error of string
```
Exception raised by the input/output functions to report an operating system error. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Sys\_error \_ instead).
```
exception End_of_file
```
Exception raised by input functions to signal that the end of file has been reached.
```
exception Division_by_zero
```
Exception raised by integer division and remainder operations when their second argument is zero.
```
exception Sys_blocked_io
```
A special case of Sys\_error raised when no I/O is possible on a non-blocking I/O channel.
```
exception Undefined_recursive_module of (string * int * int)
```
Exception raised when an ill-founded recursive module definition is evaluated. The arguments are the location of the definition in the source code (file name, line number, column number).
Comparisons
-----------
```
val (=) : 'a -> 'a -> bool
```
`e1 = e2` tests for structural equality of `e1` and `e2`. Mutable structures (e.g. references and arrays) are equal if and only if their current contents are structurally equal, even if the two mutable objects are not the same physical object. Equality between functional values raises `Invalid\_argument`. Equality between cyclic data structures may not terminate. Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (<>) : 'a -> 'a -> bool
```
Negation of [`(=)`](stdlib#VAL(=)). Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (<) : 'a -> 'a -> bool
```
See [`(>=)`](#). Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (>) : 'a -> 'a -> bool
```
See [`(>=)`](#). Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (<=) : 'a -> 'a -> bool
```
See [`(>=)`](#). Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (>=) : 'a -> 'a -> bool
```
Structural ordering functions. These functions coincide with the usual orderings over integers, characters, strings, byte sequences and floating-point numbers, and extend them to a total ordering over all types. The ordering is compatible with `( = )`. As in the case of `( = )`, mutable structures are compared by contents. Comparison between functional values raises `Invalid\_argument`. Comparison between cyclic structures may not terminate. Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val compare : 'a -> 'a -> int
```
`compare x y` returns `0` if `x` is equal to `y`, a negative integer if `x` is less than `y`, and a positive integer if `x` is greater than `y`. The ordering implemented by `compare` is compatible with the comparison predicates `=`, `<` and `>` defined above, with one difference on the treatment of the float value [`nan`](stdlib#VALnan). Namely, the comparison predicates treat `nan` as different from any other float value, including itself; while `compare` treats `nan` as equal to itself and less than any other float value. This treatment of `nan` ensures that `compare` defines a total ordering relation.
`compare` applied to functional values may raise `Invalid\_argument`. `compare` applied to cyclic structures may not terminate.
The `compare` function can be used as the comparison function required by the [`Set.Make`](set.make) and [`Map.Make`](map.make) functors, as well as the [`List.sort`](list#VALsort) and [`Array.sort`](array#VALsort) functions.
```
val min : 'a -> 'a -> 'a
```
Return the smaller of the two arguments. The result is unspecified if one of the arguments contains the float value `nan`.
```
val max : 'a -> 'a -> 'a
```
Return the greater of the two arguments. The result is unspecified if one of the arguments contains the float value `nan`.
```
val (==) : 'a -> 'a -> bool
```
`e1 == e2` tests for physical equality of `e1` and `e2`. On mutable types such as references, arrays, byte sequences, records with mutable fields and objects with mutable instance variables, `e1 == e2` is true if and only if physical modification of `e1` also affects `e2`. On non-mutable types, the behavior of `( == )` is implementation-dependent; however, it is guaranteed that `e1 == e2` implies `compare e1 e2 = 0`. Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (!=) : 'a -> 'a -> bool
```
Negation of [`(==)`](stdlib#VAL(==)). Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
Boolean operations
------------------
```
val not : bool -> bool
```
The boolean negation.
```
val (&&) : bool -> bool -> bool
```
The boolean 'and'. Evaluation is sequential, left-to-right: in `e1 && e2`, `e1` is evaluated first, and if it returns `false`, `e2` is not evaluated at all. Right-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (||) : bool -> bool -> bool
```
The boolean 'or'. Evaluation is sequential, left-to-right: in `e1 || e2`, `e1` is evaluated first, and if it returns `true`, `e2` is not evaluated at all. Right-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
Debugging
---------
```
val __LOC__ : string
```
`__LOC__` returns the location at which this expression appears in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d".
* **Since** 4.02.0
```
val __FILE__ : string
```
`__FILE__` returns the name of the file currently being parsed by the compiler.
* **Since** 4.02.0
```
val __LINE__ : int
```
`__LINE__` returns the line number at which this expression appears in the file currently being parsed by the compiler.
* **Since** 4.02.0
```
val __MODULE__ : string
```
`__MODULE__` returns the module name of the file being parsed by the compiler.
* **Since** 4.02.0
```
val __POS__ : string * int * int * int
```
`__POS__` returns a tuple `(file,lnum,cnum,enum)`, corresponding to the location at which this expression appears in the file currently being parsed by the compiler. `file` is the current filename, `lnum` the line number, `cnum` the character position in the line and `enum` the last character position in the line.
* **Since** 4.02.0
```
val __FUNCTION__ : string
```
`__FUNCTION__` returns the name of the current function or method, including any enclosing modules or classes.
* **Since** 4.12.0
```
val __LOC_OF__ : 'a -> string * 'a
```
`__LOC_OF__ expr` returns a pair `(loc, expr)` where `loc` is the location of `expr` in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d".
* **Since** 4.02.0
```
val __LINE_OF__ : 'a -> int * 'a
```
`__LINE_OF__ expr` returns a pair `(line, expr)`, where `line` is the line number at which the expression `expr` appears in the file currently being parsed by the compiler.
* **Since** 4.02.0
```
val __POS_OF__ : 'a -> (string * int * int * int) * 'a
```
`__POS_OF__ expr` returns a pair `(loc,expr)`, where `loc` is a tuple `(file,lnum,cnum,enum)` corresponding to the location at which the expression `expr` appears in the file currently being parsed by the compiler. `file` is the current filename, `lnum` the line number, `cnum` the character position in the line and `enum` the last character position in the line.
* **Since** 4.02.0
Composition operators
---------------------
```
val (|>) : 'a -> ('a -> 'b) -> 'b
```
Reverse-application operator: `x |> f |> g` is exactly equivalent to `g (f (x))`. Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
* **Since** 4.01
```
val (@@) : ('a -> 'b) -> 'a -> 'b
```
Application operator: `g @@ f @@ x` is exactly equivalent to `g (f (x))`. Right-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
* **Since** 4.01
Integer arithmetic
------------------
Integers are `Sys.int_size` bits wide. All operations are taken modulo 2`Sys.int_size`. They do not fail on overflow.
```
val (~-) : int -> int
```
Unary negation. You can also write `- e` instead of `~- e`. Unary operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (~+) : int -> int
```
Unary addition. You can also write `+ e` instead of `~+ e`. Unary operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
* **Since** 3.12.0
```
val succ : int -> int
```
`succ x` is `x + 1`.
```
val pred : int -> int
```
`pred x` is `x - 1`.
```
val (+) : int -> int -> int
```
Integer addition. Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (-) : int -> int -> int
```
Integer subtraction. Left-associative operator, , see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val ( * ) : int -> int -> int
```
Integer multiplication. Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (/) : int -> int -> int
```
Integer division. Integer division rounds the real quotient of its arguments towards zero. More precisely, if `x >= 0` and `y > 0`, `x / y` is the greatest integer less than or equal to the real quotient of `x` by `y`. Moreover, `(- x) / y = x / (- y) = - (x / y)`. Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
* **Raises** `Division_by_zero` if the second argument is 0.
```
val (mod) : int -> int -> int
```
Integer remainder. If `y` is not zero, the result of `x mod y` satisfies the following properties: `x = (x / y) * y + x mod y` and `abs(x mod y) <= abs(y) - 1`. If `y = 0`, `x mod y` raises `Division\_by\_zero`. Note that `x mod y` is negative only if `x < 0`. Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
* **Raises** `Division_by_zero` if `y` is zero.
```
val abs : int -> int
```
`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative.
```
val max_int : int
```
The greatest representable integer.
```
val min_int : int
```
The smallest representable integer.
### Bitwise operations
```
val (land) : int -> int -> int
```
Bitwise logical and. Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (lor) : int -> int -> int
```
Bitwise logical or. Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (lxor) : int -> int -> int
```
Bitwise logical exclusive or. Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val lnot : int -> int
```
Bitwise logical negation.
```
val (lsl) : int -> int -> int
```
`n lsl m` shifts `n` to the left by `m` bits. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (lsr) : int -> int -> int
```
`n lsr m` shifts `n` to the right by `m` bits. This is a logical shift: zeroes are inserted regardless of the sign of `n`. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (asr) : int -> int -> int
```
`n asr m` shifts `n` to the right by `m` bits. This is an arithmetic shift: the sign bit of `n` is replicated. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
Floating-point arithmetic
-------------------------
OCaml's floating-point numbers follow the IEEE 754 standard, using double precision (64 bits) numbers. Floating-point operations never raise an exception on overflow, underflow, division by zero, etc. Instead, special IEEE numbers are returned as appropriate, such as `infinity` for `1.0 /. 0.0`, `neg_infinity` for `-1.0 /. 0.0`, and `nan` ('not a number') for `0.0 /. 0.0`. These special numbers then propagate through floating-point computations as expected: for instance, `1.0 /. infinity` is `0.0`, basic arithmetic operations (`+.`, `-.`, `*.`, `/.`) with `nan` as an argument return `nan`, ...
```
val (~-.) : float -> float
```
Unary negation. You can also write `-. e` instead of `~-. e`. Unary operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (~+.) : float -> float
```
Unary addition. You can also write `+. e` instead of `~+. e`. Unary operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
* **Since** 3.12.0
```
val (+.) : float -> float -> float
```
Floating-point addition. Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (-.) : float -> float -> float
```
Floating-point subtraction. Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val ( *. ) : float -> float -> float
```
Floating-point multiplication. Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (/.) : float -> float -> float
```
Floating-point division. Left-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val ( ** ) : float -> float -> float
```
Exponentiation. Right-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val sqrt : float -> float
```
Square root.
```
val exp : float -> float
```
Exponential.
```
val log : float -> float
```
Natural logarithm.
```
val log10 : float -> float
```
Base 10 logarithm.
```
val expm1 : float -> float
```
`expm1 x` computes `exp x -. 1.0`, giving numerically-accurate results even if `x` is close to `0.0`.
* **Since** 3.12.0
```
val log1p : float -> float
```
`log1p x` computes `log(1.0 +. x)` (natural logarithm), giving numerically-accurate results even if `x` is close to `0.0`.
* **Since** 3.12.0
```
val cos : float -> float
```
Cosine. Argument is in radians.
```
val sin : float -> float
```
Sine. Argument is in radians.
```
val tan : float -> float
```
Tangent. Argument is in radians.
```
val acos : float -> float
```
Arc cosine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `0.0` and `pi`.
```
val asin : float -> float
```
Arc sine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `-pi/2` and `pi/2`.
```
val atan : float -> float
```
Arc tangent. Result is in radians and is between `-pi/2` and `pi/2`.
```
val atan2 : float -> float -> float
```
`atan2 y x` returns the arc tangent of `y /. x`. The signs of `x` and `y` are used to determine the quadrant of the result. Result is in radians and is between `-pi` and `pi`.
```
val hypot : float -> float -> float
```
`hypot x y` returns `sqrt(x *. x + y *. y)`, that is, the length of the hypotenuse of a right-angled triangle with sides of length `x` and `y`, or, equivalently, the distance of the point `(x,y)` to origin. If one of `x` or `y` is infinite, returns `infinity` even if the other is `nan`.
* **Since** 4.00.0
```
val cosh : float -> float
```
Hyperbolic cosine. Argument is in radians.
```
val sinh : float -> float
```
Hyperbolic sine. Argument is in radians.
```
val tanh : float -> float
```
Hyperbolic tangent. Argument is in radians.
```
val acosh : float -> float
```
Hyperbolic arc cosine. The argument must fall within the range `[1.0, inf]`. Result is in radians and is between `0.0` and `inf`.
* **Since** 4.13.0
```
val asinh : float -> float
```
Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians.
* **Since** 4.13.0
```
val atanh : float -> float
```
Hyperbolic arc tangent. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and ranges over the entire real line.
* **Since** 4.13.0
```
val ceil : float -> float
```
Round above to an integer value. `ceil f` returns the least integer value greater than or equal to `f`. The result is returned as a float.
```
val floor : float -> float
```
Round below to an integer value. `floor f` returns the greatest integer value less than or equal to `f`. The result is returned as a float.
```
val abs_float : float -> float
```
`abs_float f` returns the absolute value of `f`.
```
val copysign : float -> float -> float
```
`copysign x y` returns a float whose absolute value is that of `x` and whose sign is that of `y`. If `x` is `nan`, returns `nan`. If `y` is `nan`, returns either `x` or `-. x`, but it is not specified which.
* **Since** 4.00.0
```
val mod_float : float -> float -> float
```
`mod_float a b` returns the remainder of `a` with respect to `b`. The returned value is `a -. n *. b`, where `n` is the quotient `a /. b` rounded towards zero to an integer.
```
val frexp : float -> float * int
```
`frexp f` returns the pair of the significant and the exponent of `f`. When `f` is zero, the significant `x` and the exponent `n` of `f` are equal to zero. When `f` is non-zero, they are defined by `f = x *. 2 ** n` and `0.5 <= x < 1.0`.
```
val ldexp : float -> int -> float
```
`ldexp x n` returns `x *. 2 ** n`.
```
val modf : float -> float * float
```
`modf f` returns the pair of the fractional and integral part of `f`.
```
val float : int -> float
```
Same as [`float_of_int`](stdlib#VALfloat_of_int).
```
val float_of_int : int -> float
```
Convert an integer to floating-point.
```
val truncate : float -> int
```
Same as [`int_of_float`](stdlib#VALint_of_float).
```
val int_of_float : float -> int
```
Truncate the given floating-point number to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers.
```
val infinity : float
```
Positive infinity.
```
val neg_infinity : float
```
Negative infinity.
```
val nan : float
```
A special floating-point value denoting the result of an undefined operation such as `0.0 /. 0.0`. Stands for 'not a number'. Any floating-point operation with `nan` as argument returns `nan` as result. As for floating-point comparisons, `=`, `<`, `<=`, `>` and `>=` return `false` and `<>` returns `true` if one or both of their arguments is `nan`.
```
val max_float : float
```
The largest positive finite value of type `float`.
```
val min_float : float
```
The smallest positive, non-zero, non-denormalized value of type `float`.
```
val epsilon_float : float
```
The difference between `1.0` and the smallest exactly representable floating-point number greater than `1.0`.
```
type fpclass =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `FP\_normal` | `(*` | Normal number, none of the below | `*)` |
| `|` | `FP\_subnormal` | `(*` | Number very close to 0.0, has reduced precision | `*)` |
| `|` | `FP\_zero` | `(*` | Number is 0.0 or -0.0 | `*)` |
| `|` | `FP\_infinite` | `(*` | Number is positive or negative infinity | `*)` |
| `|` | `FP\_nan` | `(*` | Not a number: result of an undefined operation | `*)` |
The five classes of floating-point numbers, as determined by the [`classify_float`](stdlib#VALclassify_float) function.
```
val classify_float : float -> fpclass
```
Return the class of the given floating-point number: normal, subnormal, zero, infinite, or not a number.
String operations
-----------------
More string operations are provided in module [`String`](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.String.html).
```
val (^) : string -> string -> string
```
String concatenation. Right-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
* **Raises** `Invalid_argument` if the result is longer then than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
Character operations
--------------------
More character operations are provided in module [`Char`](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.Char.html).
```
val int_of_char : char -> int
```
Return the ASCII code of the argument.
```
val char_of_int : int -> char
```
Return the character with the given ASCII code.
* **Raises** `Invalid_argument` if the argument is outside the range 0--255.
Unit operations
---------------
```
val ignore : 'a -> unit
```
Discard the value of its argument and return `()`. For instance, `ignore(f x)` discards the result of the side-effecting function `f`. It is equivalent to `f x; ()`, except that the latter may generate a compiler warning; writing `ignore(f x)` instead avoids the warning.
String conversion functions
---------------------------
```
val string_of_bool : bool -> string
```
Return the string representation of a boolean. As the returned values may be shared, the user should not modify them directly.
```
val bool_of_string_opt : string -> bool option
```
Convert the given string to a boolean.
Return `None` if the string is not `"true"` or `"false"`.
* **Since** 4.05
```
val bool_of_string : string -> bool
```
Same as [`bool_of_string_opt`](stdlib#VALbool_of_string_opt), but raise `Invalid\_argument "bool\_of\_string"` instead of returning `None`.
```
val string_of_int : int -> string
```
Return the string representation of an integer, in decimal.
```
val int_of_string_opt : string -> int option
```
Convert the given string to an integer. The string is read in decimal (by default, or if the string begins with `0u`), in hexadecimal (if it begins with `0x` or `0X`), in octal (if it begins with `0o` or `0O`), or in binary (if it begins with `0b` or `0B`).
The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*max_int+1]`. If the input exceeds [`max_int`](stdlib#VALmax_int) it is converted to the signed integer `min_int + input - max_int - 1`.
The `_` (underscore) character can appear anywhere in the string and is ignored.
Return `None` if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type `int`.
* **Since** 4.05
```
val int_of_string : string -> int
```
Same as [`int_of_string_opt`](stdlib#VALint_of_string_opt), but raise `Failure "int\_of\_string"` instead of returning `None`.
```
val string_of_float : float -> string
```
Return a string representation of a floating-point number.
This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see [`Printf`](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.Printf.html).
```
val float_of_string_opt : string -> float option
```
Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by `0x` or `0X`).
The format of decimal floating-point numbers is `[-] dd.ddd (e|E) [+|-] dd`, where `d` stands for a decimal digit.
The format of hexadecimal floating-point numbers is `[-] 0(x|X) hh.hhh (p|P) [+|-] dd`, where `h` stands for an hexadecimal digit and `d` for a decimal digit.
In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional.
The `_` (underscore) character can appear anywhere in the string and is ignored.
Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon.
Return `None` if the given string is not a valid representation of a float.
* **Since** 4.05
```
val float_of_string : string -> float
```
Same as [`float_of_string_opt`](stdlib#VALfloat_of_string_opt), but raise `Failure "float\_of\_string"` instead of returning `None`.
Pair operations
---------------
```
val fst : 'a * 'b -> 'a
```
Return the first component of a pair.
```
val snd : 'a * 'b -> 'b
```
Return the second component of a pair.
List operations
---------------
More list operations are provided in module [`List`](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.List.html).
```
val (@) : 'a list -> 'a list -> 'a list
```
List concatenation. Not tail-recursive (length of the first argument). Right-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
Input/output
------------
Note: all input/output functions can raise `Sys\_error` when the system calls they invoke fail.
```
type in_channel
```
The type of input channel.
```
type out_channel
```
The type of output channel.
```
val stdin : in_channel
```
The standard input for the process.
```
val stdout : out_channel
```
The standard output for the process.
```
val stderr : out_channel
```
The standard error output for the process.
### Output functions on standard output
```
val print_char : char -> unit
```
Print a character on standard output.
```
val print_string : string -> unit
```
Print a string on standard output.
```
val print_bytes : bytes -> unit
```
Print a byte sequence on standard output.
* **Since** 4.02.0
```
val print_int : int -> unit
```
Print an integer, in decimal, on standard output.
```
val print_float : float -> unit
```
Print a floating-point number, in decimal, on standard output.
The conversion of the number to a string uses [`string_of_float`](stdlib#VALstring_of_float) and can involve a loss of precision.
```
val print_endline : string -> unit
```
Print a string, followed by a newline character, on standard output and flush standard output.
```
val print_newline : unit -> unit
```
Print a newline character on standard output, and flush standard output. This can be used to simulate line buffering of standard output.
### Output functions on standard error
```
val prerr_char : char -> unit
```
Print a character on standard error.
```
val prerr_string : string -> unit
```
Print a string on standard error.
```
val prerr_bytes : bytes -> unit
```
Print a byte sequence on standard error.
* **Since** 4.02.0
```
val prerr_int : int -> unit
```
Print an integer, in decimal, on standard error.
```
val prerr_float : float -> unit
```
Print a floating-point number, in decimal, on standard error.
The conversion of the number to a string uses [`string_of_float`](stdlib#VALstring_of_float) and can involve a loss of precision.
```
val prerr_endline : string -> unit
```
Print a string, followed by a newline character on standard error and flush standard error.
```
val prerr_newline : unit -> unit
```
Print a newline character on standard error, and flush standard error.
### Input functions on standard input
```
val read_line : unit -> string
```
Flush standard output, then read characters from standard input until a newline character is encountered.
Return the string of all characters read, without the newline character at the end.
* **Raises** `End_of_file` if the end of the file is reached at the beginning of line.
```
val read_int_opt : unit -> int option
```
Flush standard output, then read one line from standard input and convert it to an integer.
Return `None` if the line read is not a valid representation of an integer.
* **Since** 4.05
```
val read_int : unit -> int
```
Same as [`read_int_opt`](stdlib#VALread_int_opt), but raise `Failure "int\_of\_string"` instead of returning `None`.
```
val read_float_opt : unit -> float option
```
Flush standard output, then read one line from standard input and convert it to a floating-point number.
Return `None` if the line read is not a valid representation of a floating-point number.
* **Since** 4.05.0
```
val read_float : unit -> float
```
Same as [`read_float_opt`](stdlib#VALread_float_opt), but raise `Failure "float\_of\_string"` instead of returning `None`.
### General output functions
```
type open_flag =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `Open\_rdonly` | `(*` | open for reading. | `*)` |
| `|` | `Open\_wronly` | `(*` | open for writing. | `*)` |
| `|` | `Open\_append` | `(*` | open for appending: always write at end of file. | `*)` |
| `|` | `Open\_creat` | `(*` | create the file if it does not exist. | `*)` |
| `|` | `Open\_trunc` | `(*` | empty the file if it already exists. | `*)` |
| `|` | `Open\_excl` | `(*` | fail if Open\_creat and the file already exists. | `*)` |
| `|` | `Open\_binary` | `(*` | open in binary mode (no conversion). | `*)` |
| `|` | `Open\_text` | `(*` | open in text mode (may perform conversions). | `*)` |
| `|` | `Open\_nonblock` | `(*` | open in non-blocking mode. | `*)` |
Opening modes for [`open_out_gen`](stdlib#VALopen_out_gen) and [`open_in_gen`](stdlib#VALopen_in_gen).
```
val open_out : string -> out_channel
```
Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists.
```
val open_out_bin : string -> out_channel
```
Same as [`open_out`](stdlib#VALopen_out), but the file is opened in binary mode, so that no translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`open_out`](stdlib#VALopen_out).
```
val open_out_gen : open_flag list -> int -> string -> out_channel
```
`open_out_gen mode perm filename` opens the named file for writing, as described above. The extra argument `mode` specifies the opening mode. The extra argument `perm` specifies the file permissions, in case the file must be created. [`open_out`](stdlib#VALopen_out) and [`open_out_bin`](stdlib#VALopen_out_bin) are special cases of this function.
```
val flush : out_channel -> unit
```
Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time.
```
val flush_all : unit -> unit
```
Flush all open output channels; ignore errors.
```
val output_char : out_channel -> char -> unit
```
Write the character on the given output channel.
```
val output_string : out_channel -> string -> unit
```
Write the string on the given output channel.
```
val output_bytes : out_channel -> bytes -> unit
```
Write the byte sequence on the given output channel.
* **Since** 4.02.0
```
val output : out_channel -> bytes -> int -> int -> unit
```
`output oc buf pos len` writes `len` characters from byte sequence `buf`, starting at offset `pos`, to the given output channel `oc`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid range of `buf`.
```
val output_substring : out_channel -> string -> int -> int -> unit
```
Same as `output` but take a string as argument instead of a byte sequence.
* **Since** 4.02.0
```
val output_byte : out_channel -> int -> unit
```
Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256.
```
val output_binary_int : out_channel -> int -> unit
```
Write one integer in binary format (4 bytes, big-endian) on the given output channel. The given integer is taken modulo 232. The only reliable way to read it back is through the [`input_binary_int`](stdlib#VALinput_binary_int) function. The format is compatible across all machines for a given version of OCaml.
```
val output_value : out_channel -> 'a -> unit
```
Write the representation of a structured value of any type to a channel. Circularities and sharing inside the value are detected and preserved. The object can be read back, by the function [`input_value`](stdlib#VALinput_value). See the description of module [`Marshal`](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.Marshal.html) for more information. [`output_value`](stdlib#VALoutput_value) is equivalent to [`Marshal.to_channel`](marshal#VALto_channel) with an empty list of flags.
```
val seek_out : out_channel -> int -> unit
```
`seek_out chan pos` sets the current writing position to `pos` for channel `chan`. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified.
```
val pos_out : out_channel -> int
```
Return the current writing position for the given channel. Does not work on channels opened with the `Open\_append` flag (returns unspecified results). For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with `pos_out`, then going back to this position using `seek_out` will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode.
```
val out_channel_length : out_channel -> int
```
Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless.
```
val close_out : out_channel -> unit
```
Close the given channel, flushing all buffered write operations. Output functions raise a `Sys\_error` exception when they are applied to a closed output channel, except `close_out` and `flush`, which do nothing when applied to an already closed channel. Note that `close_out` may raise `Sys\_error` if the operating system signals an error when flushing or closing.
```
val close_out_noerr : out_channel -> unit
```
Same as `close_out`, but ignore all errors.
```
val set_binary_mode_out : out_channel -> bool -> unit
```
`set_binary_mode_out oc true` sets the channel `oc` to binary mode: no translations take place during output. `set_binary_mode_out oc false` sets the channel `oc` to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from `\n` to `\r\n`. This function has no effect under operating systems that do not distinguish between text mode and binary mode.
### General input functions
```
val open_in : string -> in_channel
```
Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file.
```
val open_in_bin : string -> in_channel
```
Same as [`open_in`](stdlib#VALopen_in), but the file is opened in binary mode, so that no translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`open_in`](stdlib#VALopen_in).
```
val open_in_gen : open_flag list -> int -> string -> in_channel
```
`open_in_gen mode perm filename` opens the named file for reading, as described above. The extra arguments `mode` and `perm` specify the opening mode and file permissions. [`open_in`](stdlib#VALopen_in) and [`open_in_bin`](stdlib#VALopen_in_bin) are special cases of this function.
```
val input_char : in_channel -> char
```
Read one character from the given input channel.
* **Raises** `End_of_file` if there are no more characters to read.
```
val input_line : in_channel -> string
```
Read characters from the given input channel, until a newline character is encountered. Return the string of all characters read, without the newline character at the end.
* **Raises** `End_of_file` if the end of the file is reached at the beginning of line.
```
val input : in_channel -> bytes -> int -> int -> int
```
`input ic buf pos len` reads up to `len` characters from the given channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. It returns the actual number of characters read, between 0 and `len` (inclusive). A return value of 0 means that the end of file was reached. A return value between 0 and `len` exclusive means that not all requested `len` characters were read, either because no more characters were available at that time, or because the implementation found it convenient to do a partial read; `input` must be called again to read the remaining characters, if desired. (See also [`really_input`](stdlib#VALreally_input) for reading exactly `len` characters.) Exception `Invalid\_argument "input"` is raised if `pos` and `len` do not designate a valid range of `buf`.
```
val really_input : in_channel -> bytes -> int -> int -> unit
```
`really_input ic buf pos len` reads `len` characters from channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`.
* **Raises**
+ `End_of_file` if the end of file is reached before `len` characters have been read.
+ `Invalid_argument` if `pos` and `len` do not designate a valid range of `buf`.
```
val really_input_string : in_channel -> int -> string
```
`really_input_string ic len` reads `len` characters from channel `ic` and returns them in a new string.
* **Since** 4.02.0
* **Raises** `End_of_file` if the end of file is reached before `len` characters have been read.
```
val input_byte : in_channel -> int
```
Same as [`input_char`](stdlib#VALinput_char), but return the 8-bit integer representing the character.
* **Raises** `End_of_file` if the end of file was reached.
```
val input_binary_int : in_channel -> int
```
Read an integer encoded in binary format (4 bytes, big-endian) from the given input channel. See [`output_binary_int`](stdlib#VALoutput_binary_int).
* **Raises** `End_of_file` if the end of file was reached while reading the integer.
```
val input_value : in_channel -> 'a
```
Read the representation of a structured value, as produced by [`output_value`](stdlib#VALoutput_value), and return the corresponding value. This function is identical to [`Marshal.from_channel`](marshal#VALfrom_channel); see the description of module [`Marshal`](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.Marshal.html) for more information, in particular concerning the lack of type safety.
```
val seek_in : in_channel -> int -> unit
```
`seek_in chan pos` sets the current reading position to `pos` for channel `chan`. This works only for regular files. On files of other kinds, the behavior is unspecified.
```
val pos_in : in_channel -> int
```
Return the current reading position for the given channel. For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with `pos_in`, then going back to this position using `seek_in` will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode.
```
val in_channel_length : in_channel -> int
```
Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode.
```
val close_in : in_channel -> unit
```
Close the given channel. Input functions raise a `Sys\_error` exception when they are applied to a closed input channel, except `close_in`, which does nothing when applied to an already closed channel.
```
val close_in_noerr : in_channel -> unit
```
Same as `close_in`, but ignore all errors.
```
val set_binary_mode_in : in_channel -> bool -> unit
```
`set_binary_mode_in ic true` sets the channel `ic` to binary mode: no translations take place during input. `set_binary_mode_out ic false` sets the channel `ic` to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from `\r\n` to `\n`. This function has no effect under operating systems that do not distinguish between text mode and binary mode.
### Operations on large files
```
module LargeFile: sig .. end
```
Operations on large files.
References
----------
```
type 'a ref = {
```
| | |
| --- | --- |
| | `mutable contents : `'a`;` |
`}` The type of references (mutable indirection cells) containing a value of type `'a`.
```
val ref : 'a -> 'a ref
```
Return a fresh reference containing the given value.
```
val (!) : 'a ref -> 'a
```
`!r` returns the current contents of reference `r`. Equivalent to `fun r -> r.contents`. Unary operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val (:=) : 'a ref -> 'a -> unit
```
`r := a` stores the value of `a` in reference `r`. Equivalent to `fun r v -> r.contents <- v`. Right-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
```
val incr : int ref -> unit
```
Increment the integer contained in the given reference. Equivalent to `fun r -> r := succ !r`.
```
val decr : int ref -> unit
```
Decrement the integer contained in the given reference. Equivalent to `fun r -> r := pred !r`.
Result type
-----------
```
type ('a, 'b) result =
```
| | |
| --- | --- |
| `|` | `Ok of `'a`` |
| `|` | `Error of `'b`` |
* **Since** 4.03.0
Operations on format strings
----------------------------
Format strings are character strings with special lexical conventions that defines the functionality of formatted input/output functions. Format strings are used to read data with formatted input functions from module [`Scanf`](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.Scanf.html) and to print data with formatted output functions from modules [`Printf`](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.Printf.html) and [`Format`](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.Format.html).
Format strings are made of three kinds of entities:
* *conversions specifications*, introduced by the special character `'%'` followed by one or more characters specifying what kind of argument to read or print,
* *formatting indications*, introduced by the special character `'@'` followed by one or more characters specifying how to read or print the argument,
* *plain characters* that are regular characters with usual lexical conventions. Plain characters specify string literals to be read in the input or printed in the output.
There is an additional lexical rule to escape the special characters `'%'` and `'@'` in format strings: if a special character follows a `'%'` character, it is treated as a plain character. In other words, `"%%"` is considered as a plain `'%'` and `"%@"` as a plain `'@'`.
For more information about conversion specifications and formatting indications available, read the documentation of modules [`Scanf`](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.Scanf.html), [`Printf`](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.Printf.html) and [`Format`](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.Format.html).
Format strings have a general and highly polymorphic type `('a, 'b, 'c, 'd, 'e, 'f) format6`. The two simplified types, `format` and `format4` below are included for backward compatibility with earlier releases of OCaml.
The meaning of format string type parameters is as follows:
* `'a` is the type of the parameters of the format for formatted output functions (`printf`-style functions); `'a` is the type of the values read by the format for formatted input functions (`scanf`-style functions).
* `'b` is the type of input source for formatted input functions and the type of output target for formatted output functions. For `printf`-style functions from module [`Printf`](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.Printf.html), `'b` is typically `out_channel`; for `printf`-style functions from module [`Format`](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.Format.html), `'b` is typically [`Format.formatter`](format#TYPEformatter); for `scanf`-style functions from module [`Scanf`](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.Scanf.html), `'b` is typically [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel).
Type argument `'b` is also the type of the first argument given to user's defined printing functions for `%a` and `%t` conversions, and user's defined reading functions for `%r` conversion.
* `'c` is the type of the result of the `%a` and `%t` printing functions, and also the type of the argument transmitted to the first argument of `kprintf`-style functions or to the `kscanf`-style functions.
* `'d` is the type of parameters for the `scanf`-style functions.
* `'e` is the type of the receiver function for the `scanf`-style functions.
* `'f` is the final result type of a formatted input/output function invocation: for the `printf`-style functions, it is typically `unit`; for the `scanf`-style functions, it is typically the result type of the receiver function.
```
type ('a, 'b, 'c, 'd, 'e, 'f) format6 = ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6
```
```
type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6
```
```
type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4
```
```
val string_of_format : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string
```
Converts a format string into a string.
```
val format_of_string : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> ('a, 'b, 'c, 'd, 'e, 'f) format6
```
`format_of_string s` returns a format string read from the string literal `s`. Note: `format_of_string` can not convert a string argument that is not a literal. If you need this functionality, use the more general [`Scanf.format_from_string`](scanf#VALformat_from_string) function.
```
val (^^) : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> ('f, 'b, 'c, 'e, 'g, 'h) format6 -> ('a, 'b, 'c, 'd, 'g, 'h) format6
```
`f1 ^^ f2` catenates format strings `f1` and `f2`. The result is a format string that behaves as the concatenation of format strings `f1` and `f2`: in case of formatted output, it accepts arguments from `f1`, then arguments from `f2`; in case of formatted input, it returns results from `f1`, then results from `f2`. Right-associative operator, see [`Ocaml\_operators`](ocaml_operators) for more information.
Program termination
-------------------
```
val exit : int -> 'a
```
Terminate the process, returning the given status code to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. All open output channels are flushed with `flush_all`. The callbacks registered with [`Domain.at_exit`](domain#VALat_exit) are called followed by those registered with [`at_exit`](stdlib#VALat_exit).
An implicit `exit 0` is performed each time a program terminates normally. An implicit `exit 2` is performed if the program terminates early because of an uncaught exception.
```
val at_exit : (unit -> unit) -> unit
```
Register the given function to be called at program termination time. The functions registered with `at_exit` will be called when the program does any of the following:
* executes [`exit`](stdlib#VALexit)
* terminates, either normally or because of an uncaught exception
* executes the C function `caml_shutdown`. The functions are called in 'last in, first out' order: the function most recently added with `at_exit` is called first.
Standard library modules
------------------------
```
module Arg: Arg
```
```
module Array: Array
```
```
module ArrayLabels: ArrayLabels
```
```
module Atomic: Atomic
```
```
module Bigarray: Bigarray
```
```
module Bool: Bool
```
```
module Buffer: Buffer
```
```
module Bytes: Bytes
```
```
module BytesLabels: BytesLabels
```
```
module Callback: Callback
```
```
module Char: Char
```
```
module Complex: Complex
```
```
module Condition: Condition
```
```
module Digest: Digest
```
```
module Domain: Domain
```
```
module Effect: Effect
```
```
module Either: Either
```
```
module Ephemeron: Ephemeron
```
```
module Filename: Filename
```
```
module Float: Float
```
```
module Format: Format
```
```
module Fun: Fun
```
```
module Gc: Gc
```
```
module Hashtbl: Hashtbl
```
```
module In_channel: In_channel
```
```
module Int: Int
```
```
module Int32: Int32
```
```
module Int64: Int64
```
```
module Lazy: Lazy
```
```
module Lexing: Lexing
```
```
module List: List
```
```
module ListLabels: ListLabels
```
```
module Map: Map
```
```
module Marshal: Marshal
```
```
module MoreLabels: MoreLabels
```
```
module Mutex: Mutex
```
```
module Nativeint: Nativeint
```
```
module Obj: Obj
```
```
module Oo: Oo
```
```
module Option: Option
```
```
module Out_channel: Out_channel
```
```
module Parsing: Parsing
```
```
module Printexc: Printexc
```
```
module Printf: Printf
```
```
module Queue: Queue
```
```
module Random: Random
```
```
module Result: Result
```
```
module Scanf: Scanf
```
```
module Semaphore: Semaphore
```
```
module Seq: Seq
```
```
module Set: Set
```
```
module Stack: Stack
```
```
module StdLabels: StdLabels
```
```
module String: String
```
```
module StringLabels: StringLabels
```
```
module Sys: Sys
```
```
module Uchar: Uchar
```
```
module Unit: Unit
```
```
module Weak: Weak
```
| programming_docs |
ocaml Functor MoreLabels.Map.Make Functor MoreLabels.Map.Make
===========================
```
module Make: functor (Ord : OrderedType) -> S
with type key = Ord.t
and type 'a t = 'a Map.Make(Ord).t
```
Functor building an implementation of the map structure given a totally ordered type.
| | | | | |
| --- | --- | --- | --- | --- |
| **Parameters:** |
| | | |
| --- | --- | --- |
| `Ord` | : | `[OrderedType](morelabels.map.orderedtype)` |
|
```
type key
```
The type of the map keys.
```
type +'a t
```
The type of maps from type `key` to type `'a`.
```
val empty : 'a t
```
The empty map.
```
val is_empty : 'a t -> bool
```
Test whether a map is empty or not.
```
val mem : key -> 'a t -> bool
```
`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise.
```
val add : key:key -> data:'a -> 'a t -> 'a t
```
`add ~key ~data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears.
* **Before 4.03** Physical equality was not ensured.
```
val update : key:key -> f:('a option -> 'a option) -> 'a t -> 'a t
```
`update ~key ~f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`).
* **Since** 4.06.0
```
val singleton : key -> 'a -> 'a t
```
`singleton x y` returns the one-element map that contains a binding `y` for `x`.
* **Since** 3.12.0
```
val remove : key -> 'a t -> 'a t
```
`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`).
* **Before 4.03** Physical equality was not ensured.
```
val merge : f:(key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t
```
`merge ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`.
* **Since** 3.12.0
```
val union : f:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t
```
`union ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where
* `f' _key None None = None`
* `f' _key (Some v) None = Some v`
* `f' _key None (Some v) = Some v`
* `f' key (Some v1) (Some v2) = f key v1 v2`
* **Since** 4.03.0
```
val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int
```
Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps.
```
val equal : cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool
```
`equal ~cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys.
```
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
```
`iter ~f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys.
```
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
```
`fold ~f m ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data.
```
val for_all : f:(key -> 'a -> bool) -> 'a t -> bool
```
`for_all ~f m` checks if all the bindings of the map satisfy the predicate `f`.
* **Since** 3.12.0
```
val exists : f:(key -> 'a -> bool) -> 'a t -> bool
```
`exists ~f m` checks if at least one binding of the map satisfies the predicate `f`.
* **Since** 3.12.0
```
val filter : f:(key -> 'a -> bool) -> 'a t -> 'a t
```
`filter ~f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`)
* **Before 4.03** Physical equality was not ensured.
* **Since** 3.12.0
```
val filter_map : f:(key -> 'a -> 'b option) -> 'a t -> 'b t
```
`filter_map ~f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map:
* if `f k v` is `None` then `k` is not in the result,
* if `f k v` is `Some v'` then the binding `(k, v')` is in the output map.
For example, the following function on maps whose values are lists
```
filter_map
(fun _k li -> match li with [] -> None | _::tl -> Some tl)
m
```
drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty.
* **Since** 4.11.0
```
val partition : f:(key -> 'a -> bool) -> 'a t -> 'a t * 'a t
```
`partition ~f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`.
* **Since** 3.12.0
```
val cardinal : 'a t -> int
```
Return the number of bindings of a map.
* **Since** 3.12.0
```
val bindings : 'a t -> (key * 'a) list
```
Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`MoreLabels.Map.Make`](morelabels.map.make).
* **Since** 3.12.0
```
val min_binding : 'a t -> key * 'a
```
Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not\_found` if the map is empty.
* **Since** 3.12.0
```
val min_binding_opt : 'a t -> (key * 'a) option
```
Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty.
* **Since** 4.05
```
val max_binding : 'a t -> key * 'a
```
Same as [`MoreLabels.Map.S.min_binding`](morelabels.map.s#VALmin_binding), but returns the binding with the largest key in the given map.
* **Since** 3.12.0
```
val max_binding_opt : 'a t -> (key * 'a) option
```
Same as [`MoreLabels.Map.S.min_binding_opt`](morelabels.map.s#VALmin_binding_opt), but returns the binding with the largest key in the given map.
* **Since** 4.05
```
val choose : 'a t -> key * 'a
```
Return one binding of the given map, or raise `Not\_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
* **Since** 3.12.0
```
val choose_opt : 'a t -> (key * 'a) option
```
Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
* **Since** 4.05
```
val split : key -> 'a t -> 'a t * 'a option * 'a t
```
`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`.
* **Since** 3.12.0
```
val find : key -> 'a t -> 'a
```
`find x m` returns the current value of `x` in `m`, or raises `Not\_found` if no binding for `x` exists.
```
val find_opt : key -> 'a t -> 'a option
```
`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists.
* **Since** 4.05
```
val find_first : f:(key -> bool) -> 'a t -> key * 'a
```
`find_first ~f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not\_found` if no such key exists.
For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not\_found` if `x` is greater than any element of `m`.
* **Since** 4.05
```
val find_first_opt : f:(key -> bool) -> 'a t -> (key * 'a) option
```
`find_first_opt ~f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists.
* **Since** 4.05
```
val find_last : f:(key -> bool) -> 'a t -> key * 'a
```
`find_last ~f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not\_found` if no such key exists.
* **Since** 4.05
```
val find_last_opt : f:(key -> bool) -> 'a t -> (key * 'a) option
```
`find_last_opt ~f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists.
* **Since** 4.05
```
val map : f:('a -> 'b) -> 'a t -> 'b t
```
`map ~f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys.
```
val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t
```
Same as [`MoreLabels.Map.S.map`](morelabels.map.s#VALmap), but the function receives as arguments both the key and the associated value for each binding of the map.
Maps and Sequences
------------------
```
val to_seq : 'a t -> (key * 'a) Seq.t
```
Iterate on the whole map, in ascending order of keys
* **Since** 4.07
```
val to_rev_seq : 'a t -> (key * 'a) Seq.t
```
Iterate on the whole map, in descending order of keys
* **Since** 4.12
```
val to_seq_from : key -> 'a t -> (key * 'a) Seq.t
```
`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above.
* **Since** 4.07
```
val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t
```
Add the given bindings to the map, in order.
* **Since** 4.07
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
Build a map from the given bindings
* **Since** 4.07
ocaml Module StringLabels Module StringLabels
===================
```
module StringLabels: sig .. end
```
Strings.
A string `s` of length `n` is an indexable and immutable sequence of `n` bytes. For historical reasons these bytes are referred to as characters.
The semantics of string functions is defined in terms of indices and positions. These are depicted and described as follows.
```
positions 0 1 2 3 4 n-1 n
+---+---+---+---+ +-----+
indices | 0 | 1 | 2 | 3 | ... | n-1 |
+---+---+---+---+ +-----+
```
* An *index* `i` of `s` is an integer in the range [`0`;`n-1`]. It represents the `i`th byte (character) of `s` which can be accessed using the constant time string indexing operator `s.[i]`.
* A *position* `i` of `s` is an integer in the range [`0`;`n`]. It represents either the point at the beginning of the string, or the point between two indices, or the point at the end of the string. The `i`th byte index is between position `i` and `i+1`.
Two integers `start` and `len` are said to define a *valid substring* of `s` if `len >= 0` and `start`, `start+len` are positions of `s`.
**Unicode text.** Strings being arbitrary sequences of bytes, they can hold any kind of textual encoding. However the recommended encoding for storing Unicode text in OCaml strings is UTF-8. This is the encoding used by Unicode escapes in string literals. For example the string `"\u{1F42B}"` is the UTF-8 encoding of the Unicode character U+1F42B.
**Past mutability.** Before OCaml 4.02, strings used to be modifiable in place like [`Bytes.t`](bytes#TYPEt) mutable sequences of bytes. OCaml 4 had various compiler flags and configuration options to support the transition period from mutable to immutable strings. Those options are no longer available, and strings are now always immutable.
The labeled version of this module can be used as described in the [`StdLabels`](stdlabels) module.
Strings
-------
```
type t = string
```
The type for strings.
```
val make : int -> char -> string
```
`make n c` is a string of length `n` with each index holding the character `c`.
* **Raises** `Invalid_argument` if `n < 0` or `n >`[`Sys.max_string_length`](sys#VALmax_string_length).
```
val init : int -> f:(int -> char) -> string
```
`init n ~f` is a string of length `n` with index `i` holding the character `f i` (called in increasing index order).
* **Since** 4.02.0
* **Raises** `Invalid_argument` if `n < 0` or `n >`[`Sys.max_string_length`](sys#VALmax_string_length).
```
val empty : string
```
The empty string.
* **Since** 4.13.0
```
val of_bytes : bytes -> string
```
Return a new string that contains the same bytes as the given byte sequence.
* **Since** 4.13.0
```
val to_bytes : string -> bytes
```
Return a new byte sequence that contains the same bytes as the given string.
* **Since** 4.13.0
```
val length : string -> int
```
`length s` is the length (number of bytes/characters) of `s`.
```
val get : string -> int -> char
```
`get s i` is the character at index `i` in `s`. This is the same as writing `s.[i]`.
* **Raises** `Invalid_argument` if `i` not an index of `s`.
Concatenating
-------------
**Note.** The [`(^)`](#) binary operator concatenates two strings.
```
val concat : sep:string -> string list -> string
```
`concat ~sep ss` concatenates the list of strings `ss`, inserting the separator string `sep` between each.
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val cat : string -> string -> string
```
`cat s1 s2` concatenates s1 and s2 (`s1 ^ s2`).
* **Since** 4.13.0
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
Predicates and comparisons
--------------------------
```
val equal : t -> t -> bool
```
`equal s0 s1` is `true` if and only if `s0` and `s1` are character-wise equal.
* **Since** 4.05.0
```
val compare : t -> t -> int
```
`compare s0 s1` sorts `s0` and `s1` in lexicographical order. `compare` behaves like [`compare`](stdlib#VALcompare) on strings but may be more efficient.
```
val starts_with : prefix:string -> string -> bool
```
`starts_with``~prefix s` is `true` if and only if `s` starts with `prefix`.
* **Since** 4.13.0
```
val ends_with : suffix:string -> string -> bool
```
`ends_with``~suffix s` is `true` if and only if `s` ends with `suffix`.
* **Since** 4.13.0
```
val contains_from : string -> int -> char -> bool
```
`contains_from s start c` is `true` if and only if `c` appears in `s` after position `start`.
* **Raises** `Invalid_argument` if `start` is not a valid position in `s`.
```
val rcontains_from : string -> int -> char -> bool
```
`rcontains_from s stop c` is `true` if and only if `c` appears in `s` before position `stop+1`.
* **Raises** `Invalid_argument` if `stop < 0` or `stop+1` is not a valid position in `s`.
```
val contains : string -> char -> bool
```
`contains s c` is [`String.contains_from`](string#VALcontains_from)`s 0 c`.
Extracting substrings
---------------------
```
val sub : string -> pos:int -> len:int -> string
```
`sub s ~pos ~len` is a string of length `len`, containing the substring of `s` that starts at position `pos` and has length `len`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid substring of `s`.
```
val split_on_char : sep:char -> string -> string list
```
`split_on_char ~sep s` is the list of all (possibly empty) substrings of `s` that are delimited by the character `sep`.
The function's result is specified by the following invariants:
* The list is not empty.
* Concatenating its elements using `sep` as a separator returns a string equal to the input (`concat (make 1 sep)
(split_on_char sep s) = s`).
* No string in the result contains the `sep` character.
* **Since** 4.05.0
Transforming
------------
```
val map : f:(char -> char) -> string -> string
```
`map f s` is the string resulting from applying `f` to all the characters of `s` in increasing order.
* **Since** 4.00.0
```
val mapi : f:(int -> char -> char) -> string -> string
```
`mapi ~f s` is like [`StringLabels.map`](stringlabels#VALmap) but the index of the character is also passed to `f`.
* **Since** 4.02.0
```
val fold_left : f:('a -> char -> 'a) -> init:'a -> string -> 'a
```
`fold_left f x s` computes `f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]`, where `n` is the length of the string `s`.
* **Since** 4.13.0
```
val fold_right : f:(char -> 'a -> 'a) -> string -> init:'a -> 'a
```
`fold_right f s x` computes `f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))`, where `n` is the length of the string `s`.
* **Since** 4.13.0
```
val for_all : f:(char -> bool) -> string -> bool
```
`for_all p s` checks if all characters in `s` satisfy the predicate `p`.
* **Since** 4.13.0
```
val exists : f:(char -> bool) -> string -> bool
```
`exists p s` checks if at least one character of `s` satisfies the predicate `p`.
* **Since** 4.13.0
```
val trim : string -> string
```
`trim s` is `s` without leading and trailing whitespace. Whitespace characters are: `' '`, `'\x0C'` (form feed), `'\n'`, `'\r'`, and `'\t'`.
* **Since** 4.00.0
```
val escaped : string -> string
```
`escaped s` is `s` with special characters represented by escape sequences, following the lexical conventions of OCaml.
All characters outside the US-ASCII printable range [0x20;0x7E] are escaped, as well as backslash (0x2F) and double-quote (0x22).
The function [`Scanf.unescaped`](scanf#VALunescaped) is a left inverse of `escaped`, i.e. `Scanf.unescaped (escaped s) = s` for any string `s` (unless `escaped s` fails).
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val uppercase_ascii : string -> string
```
`uppercase_ascii s` is `s` with all lowercase letters translated to uppercase, using the US-ASCII character set.
* **Since** 4.05.0
```
val lowercase_ascii : string -> string
```
`lowercase_ascii s` is `s` with all uppercase letters translated to lowercase, using the US-ASCII character set.
* **Since** 4.05.0
```
val capitalize_ascii : string -> string
```
`capitalize_ascii s` is `s` with the first character set to uppercase, using the US-ASCII character set.
* **Since** 4.05.0
```
val uncapitalize_ascii : string -> string
```
`uncapitalize_ascii s` is `s` with the first character set to lowercase, using the US-ASCII character set.
* **Since** 4.05.0
Traversing
----------
```
val iter : f:(char -> unit) -> string -> unit
```
`iter ~f s` applies function `f` in turn to all the characters of `s`. It is equivalent to `f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()`.
```
val iteri : f:(int -> char -> unit) -> string -> unit
```
`iteri` is like [`StringLabels.iter`](stringlabels#VALiter), but the function is also given the corresponding character index.
* **Since** 4.00.0
Searching
---------
```
val index_from : string -> int -> char -> int
```
`index_from s i c` is the index of the first occurrence of `c` in `s` after position `i`.
* **Raises**
+ `Not_found` if `c` does not occur in `s` after position `i`.
+ `Invalid_argument` if `i` is not a valid position in `s`.
```
val index_from_opt : string -> int -> char -> int option
```
`index_from_opt s i c` is the index of the first occurrence of `c` in `s` after position `i` (if any).
* **Since** 4.05
* **Raises** `Invalid_argument` if `i` is not a valid position in `s`.
```
val rindex_from : string -> int -> char -> int
```
`rindex_from s i c` is the index of the last occurrence of `c` in `s` before position `i+1`.
* **Raises**
+ `Not_found` if `c` does not occur in `s` before position `i+1`.
+ `Invalid_argument` if `i+1` is not a valid position in `s`.
```
val rindex_from_opt : string -> int -> char -> int option
```
`rindex_from_opt s i c` is the index of the last occurrence of `c` in `s` before position `i+1` (if any).
* **Since** 4.05
* **Raises** `Invalid_argument` if `i+1` is not a valid position in `s`.
```
val index : string -> char -> int
```
`index s c` is [`String.index_from`](string#VALindex_from)`s 0 c`.
```
val index_opt : string -> char -> int option
```
`index_opt s c` is [`String.index_from_opt`](string#VALindex_from_opt)`s 0 c`.
* **Since** 4.05
```
val rindex : string -> char -> int
```
`rindex s c` is [`String.rindex_from`](string#VALrindex_from)`s (length s - 1) c`.
```
val rindex_opt : string -> char -> int option
```
`rindex_opt s c` is [`String.rindex_from_opt`](string#VALrindex_from_opt)`s (length s - 1) c`.
* **Since** 4.05
Strings and Sequences
---------------------
```
val to_seq : t -> char Seq.t
```
`to_seq s` is a sequence made of the string's characters in increasing order. In `"unsafe-string"` mode, modifications of the string during iteration will be reflected in the sequence.
* **Since** 4.07
```
val to_seqi : t -> (int * char) Seq.t
```
`to_seqi s` is like [`StringLabels.to_seq`](stringlabels#VALto_seq) but also tuples the corresponding index.
* **Since** 4.07
```
val of_seq : char Seq.t -> t
```
`of_seq s` is a string made of the sequence's characters.
* **Since** 4.07
UTF decoding and validations
----------------------------
### UTF-8
```
val get_utf_8_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_8_uchar b i` decodes an UTF-8 character at index `i` in `b`.
```
val is_valid_utf_8 : t -> bool
```
`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data.
### UTF-16BE
```
val get_utf_16be_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_16be_uchar b i` decodes an UTF-16BE character at index `i` in `b`.
```
val is_valid_utf_16be : t -> bool
```
`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data.
### UTF-16LE
```
val get_utf_16le_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_16le_uchar b i` decodes an UTF-16LE character at index `i` in `b`.
```
val is_valid_utf_16le : t -> bool
```
`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data.
```
val blit : src:string -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
```
`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from the string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at character number `dst_pos`.
* **Raises** `Invalid_argument` if `src_pos` and `len` do not designate a valid range of `src`, or if `dst_pos` and `len` do not designate a valid range of `dst`.
Binary decoding of integers
---------------------------
The functions in this section binary decode integers from strings.
All following functions raise `Invalid\_argument` if the characters needed at index `i` to decode the integer are not available.
Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](sys#VALbig_endian).
32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers.
8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are sign-extended (or zero-extended) for functions which decode 8-bit or 16-bit integers and represented them with `int` values.
```
val get_uint8 : string -> int -> int
```
`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int8 : string -> int -> int
```
`get_int8 b i` is `b`'s signed 8-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_uint16_ne : string -> int -> int
```
`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_uint16_be : string -> int -> int
```
`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_uint16_le : string -> int -> int
```
`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int16_ne : string -> int -> int
```
`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int16_be : string -> int -> int
```
`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int16_le : string -> int -> int
```
`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int32_ne : string -> int -> int32
```
`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val hash : t -> int
```
An unseeded hash function for strings, with the same output value as [`Hashtbl.hash`](hashtbl#VALhash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](hashtbl.make).
* **Since** 5.0.0
```
val seeded_hash : int -> t -> int
```
A seeded hash function for strings, with the same output value as [`Hashtbl.seeded_hash`](hashtbl#VALseeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](hashtbl.makeseeded).
* **Since** 5.0.0
```
val get_int32_be : string -> int -> int32
```
`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int32_le : string -> int -> int32
```
`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int64_ne : string -> int -> int64
```
`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int64_be : string -> int -> int64
```
`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int64_le : string -> int -> int64
```
`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at character index `i`.
* **Since** 4.13.0
| programming_docs |
ocaml Module Uchar Module Uchar
============
```
module Uchar: sig .. end
```
Unicode characters.
* **Since** 4.03
```
type t
```
The type for Unicode characters.
A value of this type represents a Unicode [scalar value](http://unicode.org/glossary/#unicode_scalar_value) which is an integer in the ranges `0x0000`...`0xD7FF` or `0xE000`...`0x10FFFF`.
```
val min : t
```
`min` is U+0000.
```
val max : t
```
`max` is U+10FFFF.
```
val bom : t
```
`bom` is U+FEFF, the [byte order mark](http://unicode.org/glossary/#byte_order_mark) (BOM) character.
* **Since** 4.06.0
```
val rep : t
```
`rep` is U+FFFD, the [replacement](http://unicode.org/glossary/#replacement_character) character.
* **Since** 4.06.0
```
val succ : t -> t
```
`succ u` is the scalar value after `u` in the set of Unicode scalar values.
* **Raises** `Invalid_argument` if `u` is [`Uchar.max`](uchar#VALmax).
```
val pred : t -> t
```
`pred u` is the scalar value before `u` in the set of Unicode scalar values.
* **Raises** `Invalid_argument` if `u` is [`Uchar.min`](uchar#VALmin).
```
val is_valid : int -> bool
```
`is_valid n` is `true` if and only if `n` is a Unicode scalar value (i.e. in the ranges `0x0000`...`0xD7FF` or `0xE000`...`0x10FFFF`).
```
val of_int : int -> t
```
`of_int i` is `i` as a Unicode character.
* **Raises** `Invalid_argument` if `i` does not satisfy [`Uchar.is_valid`](uchar#VALis_valid).
```
val to_int : t -> int
```
`to_int u` is `u` as an integer.
```
val is_char : t -> bool
```
`is_char u` is `true` if and only if `u` is a latin1 OCaml character.
```
val of_char : char -> t
```
`of_char c` is `c` as a Unicode character.
```
val to_char : t -> char
```
`to_char u` is `u` as an OCaml latin1 character.
* **Raises** `Invalid_argument` if `u` does not satisfy [`Uchar.is_char`](uchar#VALis_char).
```
val equal : t -> t -> bool
```
`equal u u'` is `u = u'`.
```
val compare : t -> t -> int
```
`compare u u'` is `Stdlib.compare u u'`.
```
val hash : t -> int
```
`hash u` associates a non-negative integer to `u`.
UTF codecs tools
----------------
```
type utf_decode
```
The type for UTF decode results. Values of this type represent the result of a Unicode Transformation Format decoding attempt.
```
val utf_decode_is_valid : utf_decode -> bool
```
`utf_decode_is_valid d` is `true` if and only if `d` holds a valid decode.
```
val utf_decode_uchar : utf_decode -> t
```
`utf_decode_uchar d` is the Unicode character decoded by `d` if `utf_decode_is_valid d` is `true` and [`Uchar.rep`](uchar#VALrep) otherwise.
```
val utf_decode_length : utf_decode -> int
```
`utf_decode_length d` is the number of elements from the source that were consumed by the decode `d`. This is always strictly positive and smaller or equal to `4`. The kind of source elements depends on the actual decoder; for the decoders of the standard library this function always returns a length in bytes.
```
val utf_decode : int -> t -> utf_decode
```
`utf_decode n u` is a valid UTF decode for `u` that consumed `n` elements from the source for decoding. `n` must be positive and smaller or equal to `4` (this is not checked by the module).
```
val utf_decode_invalid : int -> utf_decode
```
`utf_decode_invalid n` is an invalid UTF decode that consumed `n` elements from the source to error. `n` must be positive and smaller or equal to `4` (this is not checked by the module). The resulting decode has [`Uchar.rep`](uchar#VALrep) as the decoded Unicode character.
```
val utf_8_byte_length : t -> int
```
`utf_8_byte_length u` is the number of bytes needed to encode `u` in UTF-8.
```
val utf_16_byte_length : t -> int
```
`utf_16_byte_length u` is the number of bytes needed to encode `u` in UTF-16.
ocaml Module Bigarray.Array2 Module Bigarray.Array2
======================
```
module Array2: sig .. end
```
Two-dimensional arrays. The `Array2` structure provides operations similar to those of [`Bigarray.Genarray`](bigarray.genarray), but specialized to the case of two-dimensional arrays.
```
type ('a, 'b, 'c) t
```
The type of two-dimensional Bigarrays whose elements have OCaml type `'a`, representation kind `'b`, and memory layout `'c`.
```
val create : ('a, 'b) Bigarray.kind -> 'c Bigarray.layout -> int -> int -> ('a, 'b, 'c) t
```
`Array2.create kind layout dim1 dim2` returns a new Bigarray of two dimensions, whose size is `dim1` in the first dimension and `dim2` in the second dimension. `kind` and `layout` determine the array element kind and the array layout as described for [`Bigarray.Genarray.create`](bigarray.genarray#VALcreate).
```
val init : ('a, 'b) Bigarray.kind -> 'c Bigarray.layout -> int -> int -> (int -> int -> 'a) -> ('a, 'b, 'c) t
```
`Array2.init kind layout dim1 dim2 f` returns a new Bigarray `b` of two dimensions, whose size is `dim2` in the first dimension and `dim2` in the second dimension. `kind` and `layout` determine the array element kind and the array layout as described for [`Bigarray.Genarray.create`](bigarray.genarray#VALcreate).
Each element `Array2.get b i j` of the array is initialized to the result of `f i j`.
In other words, `Array2.init kind layout dim1 dim2 f` tabulates the results of `f` applied to the indices of a new Bigarray whose layout is described by `kind`, `layout`, `dim1` and `dim2`.
* **Since** 4.12.0
```
val dim1 : ('a, 'b, 'c) t -> int
```
Return the first dimension of the given two-dimensional Bigarray.
```
val dim2 : ('a, 'b, 'c) t -> int
```
Return the second dimension of the given two-dimensional Bigarray.
```
val kind : ('a, 'b, 'c) t -> ('a, 'b) Bigarray.kind
```
Return the kind of the given Bigarray.
```
val layout : ('a, 'b, 'c) t -> 'c Bigarray.layout
```
Return the layout of the given Bigarray.
```
val change_layout : ('a, 'b, 'c) t -> 'd Bigarray.layout -> ('a, 'b, 'd) t
```
`Array2.change_layout a layout` returns a Bigarray with the specified `layout`, sharing the data with `a` (and hence having the same dimensions as `a`). No copying of elements is involved: the new array and the original array share the same storage space. The dimensions are reversed, such that `get v [| a; b |]` in C layout becomes `get v [| b+1; a+1 |]` in Fortran layout.
* **Since** 4.06.0
```
val size_in_bytes : ('a, 'b, 'c) t -> int
```
`size_in_bytes a` is the number of elements in `a` multiplied by `a`'s [`Bigarray.kind_size_in_bytes`](bigarray#VALkind_size_in_bytes).
* **Since** 4.03.0
```
val get : ('a, 'b, 'c) t -> int -> int -> 'a
```
`Array2.get a x y`, also written `a.{x,y}`, returns the element of `a` at coordinates (`x`, `y`). `x` and `y` must be within the bounds of `a`, as described for [`Bigarray.Genarray.get`](bigarray.genarray#VALget); otherwise, `Invalid\_argument` is raised.
```
val set : ('a, 'b, 'c) t -> int -> int -> 'a -> unit
```
`Array2.set a x y v`, or alternatively `a.{x,y} <- v`, stores the value `v` at coordinates (`x`, `y`) in `a`. `x` and `y` must be within the bounds of `a`, as described for [`Bigarray.Genarray.set`](bigarray.genarray#VALset); otherwise, `Invalid\_argument` is raised.
```
val sub_left : ('a, 'b, Bigarray.c_layout) t -> int -> int -> ('a, 'b, Bigarray.c_layout) t
```
Extract a two-dimensional sub-array of the given two-dimensional Bigarray by restricting the first dimension. See [`Bigarray.Genarray.sub_left`](bigarray.genarray#VALsub_left) for more details. `Array2.sub_left` applies only to arrays with C layout.
```
val sub_right : ('a, 'b, Bigarray.fortran_layout) t -> int -> int -> ('a, 'b, Bigarray.fortran_layout) t
```
Extract a two-dimensional sub-array of the given two-dimensional Bigarray by restricting the second dimension. See [`Bigarray.Genarray.sub_right`](bigarray.genarray#VALsub_right) for more details. `Array2.sub_right` applies only to arrays with Fortran layout.
```
val slice_left : ('a, 'b, Bigarray.c_layout) t -> int -> ('a, 'b, Bigarray.c_layout) Bigarray.Array1.t
```
Extract a row (one-dimensional slice) of the given two-dimensional Bigarray. The integer parameter is the index of the row to extract. See [`Bigarray.Genarray.slice_left`](bigarray.genarray#VALslice_left) for more details. `Array2.slice_left` applies only to arrays with C layout.
```
val slice_right : ('a, 'b, Bigarray.fortran_layout) t -> int -> ('a, 'b, Bigarray.fortran_layout) Bigarray.Array1.t
```
Extract a column (one-dimensional slice) of the given two-dimensional Bigarray. The integer parameter is the index of the column to extract. See [`Bigarray.Genarray.slice_right`](bigarray.genarray#VALslice_right) for more details. `Array2.slice_right` applies only to arrays with Fortran layout.
```
val blit : ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
```
Copy the first Bigarray to the second Bigarray. See [`Bigarray.Genarray.blit`](bigarray.genarray#VALblit) for more details.
```
val fill : ('a, 'b, 'c) t -> 'a -> unit
```
Fill the given Bigarray with the given value. See [`Bigarray.Genarray.fill`](bigarray.genarray#VALfill) for more details.
```
val of_array : ('a, 'b) Bigarray.kind -> 'c Bigarray.layout -> 'a array array -> ('a, 'b, 'c) t
```
Build a two-dimensional Bigarray initialized from the given array of arrays.
```
val unsafe_get : ('a, 'b, 'c) t -> int -> int -> 'a
```
Like [`Bigarray.Array2.get`](bigarray.array2#VALget), but bounds checking is not always performed.
```
val unsafe_set : ('a, 'b, 'c) t -> int -> int -> 'a -> unit
```
Like [`Bigarray.Array2.set`](bigarray.array2#VALset), but bounds checking is not always performed.
ocaml Module Ephemeron.K1.Bucket Module Ephemeron.K1.Bucket
==========================
```
module Bucket: sig .. end
```
```
type ('k, 'd) t
```
A bucket is a mutable "list" of ephemerons.
```
val make : unit -> ('k, 'd) t
```
Create a new bucket.
```
val add : ('k, 'd) t -> 'k -> 'd -> unit
```
Add an ephemeron to the bucket.
```
val remove : ('k, 'd) t -> 'k -> unit
```
`remove b k` removes from `b` the most-recently added ephemeron with key `k`, or does nothing if there is no such ephemeron.
```
val find : ('k, 'd) t -> 'k -> 'd option
```
Returns the data of the most-recently added ephemeron with the given key, or `None` if there is no such ephemeron.
```
val length : ('k, 'd) t -> int
```
Returns an upper bound on the length of the bucket.
```
val clear : ('k, 'd) t -> unit
```
Remove all ephemerons from the bucket.
ocaml Module Digest Module Digest
=============
```
module Digest: sig .. end
```
MD5 message digest.
This module provides functions to compute 128-bit 'digests' of arbitrary-length strings or files. The algorithm used is MD5.
The MD5 hash function is not cryptographically secure. Hence, this module should not be used for security-sensitive applications. More recent, stronger cryptographic primitives should be used instead.
```
type t = string
```
The type of digests: 16-character strings.
```
val compare : t -> t -> int
```
The comparison function for 16-character digest, with the same specification as [`compare`](stdlib#VALcompare) and the implementation shared with [`String.compare`](string#VALcompare). Along with the type `t`, this function `compare` allows the module `Digest` to be passed as argument to the functors [`Set.Make`](set.make) and [`Map.Make`](map.make).
* **Since** 4.00.0
```
val equal : t -> t -> bool
```
The equal function for 16-character digest.
* **Since** 4.03.0
```
val string : string -> t
```
Return the digest of the given string.
```
val bytes : bytes -> t
```
Return the digest of the given byte sequence.
* **Since** 4.02.0
```
val substring : string -> int -> int -> t
```
`Digest.substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters.
```
val subbytes : bytes -> int -> int -> t
```
`Digest.subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes.
* **Since** 4.02.0
```
val channel : in_channel -> int -> t
```
If `len` is nonnegative, `Digest.channel ic len` reads `len` characters from channel `ic` and returns their digest, or raises `End\_of\_file` if end-of-file is reached before `len` characters are read. If `len` is negative, `Digest.channel ic len` reads all characters from `ic` until end-of-file is reached and return their digest.
```
val file : string -> t
```
Return the digest of the file whose name is given.
```
val output : out_channel -> t -> unit
```
Write a digest on the given output channel.
```
val input : in_channel -> t
```
Read a digest from the given input channel.
```
val to_hex : t -> string
```
Return the printable hexadecimal representation of the given digest.
* **Raises** `Invalid_argument` if the argument is not exactly 16 bytes.
```
val from_hex : string -> t
```
Convert a hexadecimal representation back into the corresponding digest.
* **Since** 4.00.0
* **Raises** `Invalid_argument` if the argument is not exactly 32 hexadecimal characters.
ocaml Module Semaphore Module Semaphore
================
```
module Semaphore: sig .. end
```
Semaphores
A semaphore is a thread synchronization device that can be used to control access to a shared resource.
Two flavors of semaphores are provided: counting semaphores and binary semaphores.
* **Since** 4.12
### Counting semaphores
A counting semaphore is a counter that can be accessed concurrently by several threads. The typical use is to synchronize producers and consumers of a resource by counting how many units of the resource are available.
The two basic operations on semaphores are:
* "release" (also called "V", "post", "up", and "signal"), which increments the value of the counter. This corresponds to producing one more unit of the shared resource and making it available to others.
* "acquire" (also called "P", "wait", "down", and "pend"), which waits until the counter is greater than zero and decrements it. This corresponds to consuming one unit of the shared resource.
```
module Counting: sig .. end
```
### Binary semaphores
Binary semaphores are a variant of counting semaphores where semaphores can only take two values, 0 and 1.
A binary semaphore can be used to control access to a single shared resource, with value 1 meaning "resource is available" and value 0 meaning "resource is unavailable".
The "release" operation of a binary semaphore sets its value to 1, and "acquire" waits until the value is 1 and sets it to 0.
A binary semaphore can be used instead of a mutex (see module [`Mutex`](mutex)) when the mutex discipline (of unlocking the mutex from the thread that locked it) is too restrictive. The "acquire" operation corresponds to locking the mutex, and the "release" operation to unlocking it, but "release" can be performed in a thread different than the one that performed the "acquire". Likewise, it is safe to release a binary semaphore that is already available.
```
module Binary: sig .. end
```
ocaml Module type Hashtbl.HashedType Module type Hashtbl.HashedType
==============================
```
module type HashedType = sig .. end
```
The input signature of the functor [`Hashtbl.Make`](hashtbl.make).
```
type t
```
The type of the hashtable keys.
```
val equal : t -> t -> bool
```
The equality predicate used to compare keys.
```
val hash : t -> int
```
A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include
* (`(=)`, [`Hashtbl.HashedType.hash`](hashtbl.hashedtype#VALhash)) for comparing objects by structure (provided objects do not contain floats)
* (`(fun x y -> compare x y = 0)`, [`Hashtbl.HashedType.hash`](hashtbl.hashedtype#VALhash)) for comparing objects by structure and handling [`nan`](stdlib#VALnan) correctly
* (`(==)`, [`Hashtbl.HashedType.hash`](hashtbl.hashedtype#VALhash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects).
ocaml Module Fun Module Fun
==========
```
module Fun: sig .. end
```
Function manipulation.
* **Since** 4.08
Combinators
-----------
```
val id : 'a -> 'a
```
`id` is the identity function. For any argument `x`, `id x` is `x`.
```
val const : 'a -> 'b -> 'a
```
`const c` is a function that always returns the value `c`. For any argument `x`, `(const c) x` is `c`.
```
val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c
```
`flip f` reverses the argument order of the binary function `f`. For any arguments `x` and `y`, `(flip f) x y` is `f y x`.
```
val negate : ('a -> bool) -> 'a -> bool
```
`negate p` is the negation of the predicate function `p`. For any argument `x`, `(negate p) x` is `not (p x)`.
Exception handling
------------------
```
val protect : finally:(unit -> unit) -> (unit -> 'a) -> 'a
```
`protect ~finally work` invokes `work ()` and then `finally ()` before `work ()` returns with its value or an exception. In the latter case the exception is re-raised after `finally ()`. If `finally ()` raises an exception, then the exception [`Fun.Finally\_raised`](fun#EXCEPTIONFinally_raised) is raised instead.
`protect` can be used to enforce local invariants whether `work ()` returns normally or raises an exception. However, it does not protect against unexpected exceptions raised inside `finally ()` such as [`Out\_of\_memory`](stdlib#EXCEPTIONOut_of_memory), [`Stack\_overflow`](stdlib#EXCEPTIONStack_overflow), or asynchronous exceptions raised by signal handlers (e.g. [`Sys.Break`](sys#EXCEPTIONBreak)).
Note: It is a *programming error* if other kinds of exceptions are raised by `finally`, as any exception raised in `work ()` will be lost in the event of a [`Fun.Finally\_raised`](fun#EXCEPTIONFinally_raised) exception. Therefore, one should make sure to handle those inside the finally.
```
exception Finally_raised of exn
```
`Finally\_raised exn` is raised by `protect ~finally work` when `finally` raises an exception `exn`. This exception denotes either an unexpected exception or a programming error. As a general rule, one should not catch a `Finally\_raised` exception except as part of a catch-all handler.
ocaml Module Map Module Map
==========
```
module Map: sig .. end
```
Association tables over ordered types.
This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map.
For instance:
```
module IntPairs =
struct
type t = int * int
let compare (x0,y0) (x1,y1) =
match Stdlib.compare x0 x1 with
0 -> Stdlib.compare y0 y1
| c -> c
end
module PairsMap = Map.Make(IntPairs)
let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world")
```
This creates a new module `PairsMap`, with a new type `'a PairsMap.t` of maps from `int * int` to `'a`. In this example, `m` contains `string` values so its type is `string PairsMap.t`.
```
module type OrderedType = sig .. end
```
Input signature of the functor [`Map.Make`](map.make).
```
module type S = sig .. end
```
Output signature of the functor [`Map.Make`](map.make).
```
module Make: functor (Ord : OrderedType) -> S with type key = Ord.t
```
Functor building an implementation of the map structure given a totally ordered type.
| programming_docs |
ocaml Module Arg Module Arg
==========
```
module Arg: sig .. end
```
Parsing of command line arguments.
This module provides a general mechanism for extracting options and arguments from the command line to the program. For example:
```
let usage_msg = "append [-verbose] <file1> [<file2>] ... -o <output>"
let verbose = ref false
let input_files = ref []
let output_file = ref ""
let anon_fun filename =
input_files := filename::!input_files
let speclist =
[("-verbose", Arg.Set verbose, "Output debug information");
("-o", Arg.Set_string output_file, "Set output file name")]
let () =
Arg.parse speclist anon_fun usage_msg;
(* Main functionality here *)
```
Syntax of command lines: A keyword is a character string starting with a `-`. An option is a keyword alone or followed by an argument. The types of keywords are: `Unit`, `Bool`, `Set`, `Clear`, `String`, `Set\_string`, `Int`, `Set\_int`, `Float`, `Set\_float`, `Tuple`, `Symbol`, `Rest`, `Rest\_all` and `Expand`.
`Unit`, `Set` and `Clear` keywords take no argument.
A `Rest` or `Rest\_all` keyword takes the remainder of the command line as arguments. (More explanations below.)
Every other keyword takes the following word on the command line as argument. For compatibility with GNU getopt\_long, `keyword=arg` is also allowed. Arguments not preceded by a keyword are called anonymous arguments.
Examples (`cmd` is assumed to be the command name):
* `cmd -flag`(a unit option)
* `cmd -int 1`(an int option with argument `1`)
* `cmd -string foobar`(a string option with argument `"foobar"`)
* `cmd -float 12.34`(a float option with argument `12.34`)
* `cmd a b c`(three anonymous arguments: `"a"`, `"b"`, and `"c"`)
* `cmd a b -- c d`(two anonymous arguments and a rest option with two arguments)
`Rest` takes a function that is called repeatedly for each remaining command line argument. `Rest\_all` takes a function that is called once, with the list of all remaining arguments.
Note that if no arguments follow a `Rest` keyword then the function is not called at all whereas the function for a `Rest\_all` keyword is called with an empty list.
* **Alert unsynchronized\_access.** The Arg module relies on a mutable global state, parsing functions should only be called from a single domain.
```
type spec =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `Unit of `(unit -> unit)`` | `(*` | Call the function with unit argument | `*)` |
| `|` | `Bool of `(bool -> unit)`` | `(*` | Call the function with a bool argument | `*)` |
| `|` | `Set of `bool [ref](stdlib#TYPEref)`` | `(*` | Set the reference to true | `*)` |
| `|` | `Clear of `bool [ref](stdlib#TYPEref)`` | `(*` | Set the reference to false | `*)` |
| `|` | `String of `(string -> unit)`` | `(*` | Call the function with a string argument | `*)` |
| `|` | `Set\_string of `string [ref](stdlib#TYPEref)`` | `(*` | Set the reference to the string argument | `*)` |
| `|` | `Int of `(int -> unit)`` | `(*` | Call the function with an int argument | `*)` |
| `|` | `Set\_int of `int [ref](stdlib#TYPEref)`` | `(*` | Set the reference to the int argument | `*)` |
| `|` | `Float of `(float -> unit)`` | `(*` | Call the function with a float argument | `*)` |
| `|` | `Set\_float of `float [ref](stdlib#TYPEref)`` | `(*` | Set the reference to the float argument | `*)` |
| `|` | `Tuple of `[spec](arg#TYPEspec) list`` | `(*` | Take several arguments according to the spec list | `*)` |
| `|` | `Symbol of `string list * (string -> unit)`` | `(*` | Take one of the symbols as argument and call the function with the symbol | `*)` |
| `|` | `Rest of `(string -> unit)`` | `(*` | Stop interpreting keywords and call the function with each remaining argument | `*)` |
| `|` | `Rest\_all of `(string list -> unit)`` | `(*` | Stop interpreting keywords and call the function with all remaining arguments | `*)` |
| `|` | `Expand of `(string -> string array)`` | `(*` | If the remaining arguments to process are of the form `["-foo"; "arg"] @ rest` where "foo" is registered as `Expand f`, then the arguments `f "arg" @ rest` are processed. Only allowed in `parse_and_expand_argv_dynamic`. | `*)` |
The concrete type describing the behavior associated with a keyword.
```
type key = string
```
```
type doc = string
```
```
type usage_msg = string
```
```
type anon_fun = string -> unit
```
```
val parse : (key * spec * doc) list -> anon_fun -> usage_msg -> unit
```
`Arg.parse speclist anon_fun usage_msg` parses the command line. `speclist` is a list of triples `(key, spec, doc)`. `key` is the option keyword, it must start with a `'-'` character. `spec` gives the option type and the function to call when this option is found on the command line. `doc` is a one-line description of this option. `anon_fun` is called on anonymous arguments. The functions in `spec` and `anon_fun` are called in the same order as their arguments appear on the command line.
If an error occurs, `Arg.parse` exits the program, after printing to standard error an error message as follows:
* The reason for the error: unknown option, invalid or missing argument, etc.
* `usage_msg`
* The list of options, each followed by the corresponding `doc` string. Beware: options that have an empty `doc` string will not be included in the list.
For the user to be able to specify anonymous arguments starting with a `-`, include for example `("-", String anon_fun, doc)` in `speclist`.
By default, `parse` recognizes two unit options, `-help` and `--help`, which will print to standard output `usage_msg` and the list of options, and exit the program. You can override this behaviour by specifying your own `-help` and `--help` options in `speclist`.
```
val parse_dynamic : (key * spec * doc) list ref -> anon_fun -> usage_msg -> unit
```
Same as [`Arg.parse`](arg#VALparse), except that the `speclist` argument is a reference and may be updated during the parsing. A typical use for this feature is to parse command lines of the form:
* command subcommand `options` where the list of options depends on the value of the subcommand argument.
* **Since** 4.01.0
```
val parse_argv : ?current:int ref -> string array -> (key * spec * doc) list -> anon_fun -> usage_msg -> unit
```
`Arg.parse_argv ~current args speclist anon_fun usage_msg` parses the array `args` as if it were the command line. It uses and updates the value of `~current` (if given), or [`Arg.current`](arg#VALcurrent). You must set it before calling `parse_argv`. The initial value of `current` is the index of the program name (argument 0) in the array. If an error occurs, `Arg.parse_argv` raises [`Arg.Bad`](arg#EXCEPTIONBad) with the error message as argument. If option `-help` or `--help` is given, `Arg.parse_argv` raises [`Arg.Help`](arg#EXCEPTIONHelp) with the help message as argument.
```
val parse_argv_dynamic : ?current:int ref -> string array -> (key * spec * doc) list ref -> anon_fun -> string -> unit
```
Same as [`Arg.parse_argv`](arg#VALparse_argv), except that the `speclist` argument is a reference and may be updated during the parsing. See [`Arg.parse_dynamic`](arg#VALparse_dynamic).
* **Since** 4.01.0
```
val parse_and_expand_argv_dynamic : int ref -> string array ref -> (key * spec * doc) list ref -> anon_fun -> string -> unit
```
Same as [`Arg.parse_argv_dynamic`](arg#VALparse_argv_dynamic), except that the `argv` argument is a reference and may be updated during the parsing of `Expand` arguments. See [`Arg.parse_argv_dynamic`](arg#VALparse_argv_dynamic).
* **Since** 4.05.0
```
val parse_expand : (key * spec * doc) list -> anon_fun -> usage_msg -> unit
```
Same as [`Arg.parse`](arg#VALparse), except that the `Expand` arguments are allowed and the [`Arg.current`](arg#VALcurrent) reference is not updated.
* **Since** 4.05.0
```
exception Help of string
```
Raised by `Arg.parse_argv` when the user asks for help.
```
exception Bad of string
```
Functions in `spec` or `anon_fun` can raise `Arg.Bad` with an error message to reject invalid arguments. `Arg.Bad` is also raised by [`Arg.parse_argv`](arg#VALparse_argv) in case of an error.
```
val usage : (key * spec * doc) list -> usage_msg -> unit
```
`Arg.usage speclist usage_msg` prints to standard error an error message that includes the list of valid options. This is the same message that [`Arg.parse`](arg#VALparse) prints in case of error. `speclist` and `usage_msg` are the same as for [`Arg.parse`](arg#VALparse).
```
val usage_string : (key * spec * doc) list -> usage_msg -> string
```
Returns the message that would have been printed by [`Arg.usage`](arg#VALusage), if provided with the same parameters.
```
val align : ?limit:int -> (key * spec * doc) list -> (key * spec * doc) list
```
Align the documentation strings by inserting spaces at the first alignment separator (tab or, if tab is not found, space), according to the length of the keyword. Use a alignment separator as the first character in a doc string if you want to align the whole string. The doc strings corresponding to `Symbol` arguments are aligned on the next line.
`limit` : options with keyword and message longer than `limit` will not be used to compute the alignment.
```
val current : int ref
```
Position (in [`Sys.argv`](sys#VALargv)) of the argument being processed. You can change this value, e.g. to force [`Arg.parse`](arg#VALparse) to skip some arguments. [`Arg.parse`](arg#VALparse) uses the initial value of [`Arg.current`](arg#VALcurrent) as the index of argument 0 (the program name) and starts parsing arguments at the next element.
```
val read_arg : string -> string array
```
`Arg.read_arg file` reads newline-terminated command line arguments from file `file`.
* **Since** 4.05.0
```
val read_arg0 : string -> string array
```
Identical to [`Arg.read_arg`](arg#VALread_arg) but assumes null character terminated command line arguments.
* **Since** 4.05.0
```
val write_arg : string -> string array -> unit
```
`Arg.write_arg file args` writes the arguments `args` newline-terminated into the file `file`. If the any of the arguments in `args` contains a newline, use [`Arg.write_arg0`](arg#VALwrite_arg0) instead.
* **Since** 4.05.0
```
val write_arg0 : string -> string array -> unit
```
Identical to [`Arg.write_arg`](arg#VALwrite_arg) but uses the null character for terminator instead of newline.
* **Since** 4.05.0
ocaml Module type Set.S Module type Set.S
=================
```
module type S = sig .. end
```
Output signature of the functor [`Set.Make`](set.make).
```
type elt
```
The type of the set elements.
```
type t
```
The type of sets.
```
val empty : t
```
The empty set.
```
val is_empty : t -> bool
```
Test whether a set is empty or not.
```
val mem : elt -> t -> bool
```
`mem x s` tests whether `x` belongs to the set `s`.
```
val add : elt -> t -> t
```
`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`).
* **Before 4.03** Physical equality was not ensured.
```
val singleton : elt -> t
```
`singleton x` returns the one-element set containing only `x`.
```
val remove : elt -> t -> t
```
`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`).
* **Before 4.03** Physical equality was not ensured.
```
val union : t -> t -> t
```
Set union.
```
val inter : t -> t -> t
```
Set intersection.
```
val disjoint : t -> t -> bool
```
Test if two sets are disjoint.
* **Since** 4.08.0
```
val diff : t -> t -> t
```
Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`.
```
val compare : t -> t -> int
```
Total ordering between sets. Can be used as the ordering function for doing sets of sets.
```
val equal : t -> t -> bool
```
`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements.
```
val subset : t -> t -> bool
```
`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`.
```
val iter : (elt -> unit) -> t -> unit
```
`iter f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements.
```
val map : (elt -> elt) -> t -> t
```
`map f s` is the set whose elements are `f a0`,`f a1`... `f
aN`, where `a0`,`a1`...`aN` are the elements of `s`.
The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements.
If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.)
* **Since** 4.04.0
```
val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a
```
`fold f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order.
```
val for_all : (elt -> bool) -> t -> bool
```
`for_all f s` checks if all elements of the set satisfy the predicate `f`.
```
val exists : (elt -> bool) -> t -> bool
```
`exists f s` checks if at least one element of the set satisfies the predicate `f`.
```
val filter : (elt -> bool) -> t -> t
```
`filter f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`).
* **Before 4.03** Physical equality was not ensured.
```
val filter_map : (elt -> elt option) -> t -> t
```
`filter_map f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`.
For example,
```
filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s
```
is the set of halves of the even elements of `s`.
If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`.
* **Since** 4.11.0
```
val partition : (elt -> bool) -> t -> t * t
```
`partition f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`.
```
val cardinal : t -> int
```
Return the number of elements of a set.
```
val elements : t -> elt list
```
Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](set.make).
```
val min_elt : t -> elt
```
Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not\_found` if the set is empty.
```
val min_elt_opt : t -> elt option
```
Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty.
* **Since** 4.05
```
val max_elt : t -> elt
```
Same as [`Set.S.min_elt`](set.s#VALmin_elt), but returns the largest element of the given set.
```
val max_elt_opt : t -> elt option
```
Same as [`Set.S.min_elt_opt`](set.s#VALmin_elt_opt), but returns the largest element of the given set.
* **Since** 4.05
```
val choose : t -> elt
```
Return one element of the given set, or raise `Not\_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
```
val choose_opt : t -> elt option
```
Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
* **Since** 4.05
```
val split : elt -> t -> t * bool * t
```
`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`.
```
val find : elt -> t -> elt
```
`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not\_found` if no such element exists.
* **Since** 4.01.0
```
val find_opt : elt -> t -> elt option
```
`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists.
* **Since** 4.05
```
val find_first : (elt -> bool) -> t -> elt
```
`find_first f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not\_found` if no such element exists.
For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not\_found` if `x` is greater than any element of `s`.
* **Since** 4.05
```
val find_first_opt : (elt -> bool) -> t -> elt option
```
`find_first_opt f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists.
* **Since** 4.05
```
val find_last : (elt -> bool) -> t -> elt
```
`find_last f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not\_found` if no such element exists.
* **Since** 4.05
```
val find_last_opt : (elt -> bool) -> t -> elt option
```
`find_last_opt f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists.
* **Since** 4.05
```
val of_list : elt list -> t
```
`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements.
* **Since** 4.02.0
Iterators
---------
```
val to_seq_from : elt -> t -> elt Seq.t
```
`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above.
* **Since** 4.07
```
val to_seq : t -> elt Seq.t
```
Iterate on the whole set, in ascending order
* **Since** 4.07
```
val to_rev_seq : t -> elt Seq.t
```
Iterate on the whole set, in descending order
* **Since** 4.12
```
val add_seq : elt Seq.t -> t -> t
```
Add the given elements to the set, in order.
* **Since** 4.07
```
val of_seq : elt Seq.t -> t
```
Build a set from the given bindings
* **Since** 4.07
ocaml Module type Sys.Immediate64.Immediate Module type Sys.Immediate64.Immediate
=====================================
```
module type Immediate = sig .. end
```
```
type t
```
ocaml Module Scanf Module Scanf
============
```
module Scanf: sig .. end
```
Formatted input functions.
* **Alert unsynchronized\_access.** Unsynchronized accesses to Scanning.in\_channel are a programming error.
Introduction
------------
### Functional input with format strings
The module [`Scanf`](scanf) provides formatted input functions or *scanners*.
The formatted input functions can read from any kind of input, including strings, files, or anything that can return characters. The more general source of characters is named a *formatted input channel* (or *scanning buffer*) and has type [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel). The more general formatted input function reads from any scanning buffer and is named `bscanf`.
Generally speaking, the formatted input functions have 3 arguments:
* the first argument is a source of characters for the input,
* the second argument is a format string that specifies the values to read,
* the third argument is a *receiver function* that is applied to the values read.
Hence, a typical call to the formatted input function [`Scanf.bscanf`](scanf#VALbscanf) is `bscanf ic fmt f`, where:
* `ic` is a source of characters (typically a *formatted input channel* with type [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel)),
* `fmt` is a format string (the same format strings as those used to print material with module [`Printf`](printf) or [`Format`](format)),
* `f` is a function that has as many arguments as the number of values to read in the input according to `fmt`.
### A simple example
As suggested above, the expression `bscanf ic "%d" f` reads a decimal integer `n` from the source of characters `ic` and returns `f n`.
For instance,
* if we use `stdin` as the source of characters ([`Scanf.Scanning.stdin`](scanf.scanning#VALstdin) is the predefined formatted input channel that reads from standard input),
* if we define the receiver `f` as `let f x = x + 1`,
then `bscanf Scanning.stdin "%d" f` reads an integer `n` from the standard input and returns `f n` (that is `n + 1`). Thus, if we evaluate `bscanf stdin "%d" f`, and then enter `41` at the keyboard, the result we get is `42`.
### Formatted input as a functional feature
The OCaml scanning facility is reminiscent of the corresponding C feature. However, it is also largely different, simpler, and yet more powerful: the formatted input functions are higher-order functionals and the parameter passing mechanism is just the regular function application not the variable assignment based mechanism which is typical for formatted input in imperative languages; the OCaml format strings also feature useful additions to easily define complex tokens; as expected within a functional programming language, the formatted input functions also support polymorphism, in particular arbitrary interaction with polymorphic user-defined scanners. Furthermore, the OCaml formatted input facility is fully type-checked at compile time.
**Unsynchronized accesses**
Unsynchronized accesses to a [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) may lead to an invalid [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) state. Thus, concurrent accesses to [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel)s must be synchronized (for instance with a [`Mutex.t`](mutex#TYPEt)).
Formatted input channel
-----------------------
```
module Scanning: sig .. end
```
Type of formatted input functions
---------------------------------
```
type ('a, 'b, 'c, 'd) scanner = ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd, 'd) format6 -> 'c
```
The type of formatted input scanners: `('a, 'b, 'c, 'd) scanner` is the type of a formatted input function that reads from some formatted input channel according to some format string; more precisely, if `scan` is some formatted input function, then `scan
ic fmt f` applies `f` to all the arguments specified by format string `fmt`, when `scan` has read those arguments from the [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel `ic`.
For instance, the [`Scanf.scanf`](scanf#VALscanf) function below has type `('a, 'b, 'c, 'd) scanner`, since it is a formatted input function that reads from [`Scanf.Scanning.stdin`](scanf.scanning#VALstdin): `scanf fmt f` applies `f` to the arguments specified by `fmt`, reading those arguments from [`stdin`](stdlib#VALstdin) as expected.
If the format `fmt` has some `%r` indications, the corresponding formatted input functions must be provided *before* receiver function `f`. For instance, if `read_elem` is an input function for values of type `t`, then `bscanf ic "%r;" read_elem f` reads a value `v` of type `t` followed by a `';'` character, and returns `f v`.
* **Since** 3.10.0
```
type ('a, 'b, 'c, 'd) scanner_opt = ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd option, 'd) format6 -> 'c
```
```
exception Scan_failure of string
```
When the input can not be read according to the format string specification, formatted input functions typically raise exception `Scan\_failure`.
The general formatted input function
------------------------------------
```
val bscanf : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner
```
`bscanf ic fmt r1 ... rN f` reads characters from the [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel `ic` and converts them to values according to format string `fmt`. As a final step, receiver function `f` is applied to the values read and gives the result of the `bscanf` call.
For instance, if `f` is the function `fun s i -> i + 1`, then `Scanf.sscanf "x = 1" "%s = %i" f` returns `2`.
Arguments `r1` to `rN` are user-defined input functions that read the argument corresponding to the `%r` conversions specified in the format string.
```
val bscanf_opt : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner_opt
```
Same as [`Scanf.bscanf`](scanf#VALbscanf), but returns `None` in case of scanning failure.
* **Since** 5.0
Format string description
-------------------------
The format string is a character string which contains three types of objects:
* plain characters, which are simply matched with the characters of the input (with a special case for space and line feed, see [*The space character in format strings*](scanf#space)),
* conversion specifications, each of which causes reading and conversion of one argument for the function `f` (see [*Conversion specifications in format strings*](scanf#conversion)),
* scanning indications to specify boundaries of tokens (see scanning [*Scanning indications in format strings*](scanf#indication)).
### The space character in format strings
As mentioned above, a plain character in the format string is just matched with the next character of the input; however, two characters are special exceptions to this rule: the space character (`' '` or ASCII code 32) and the line feed character (`'\n'` or ASCII code 10). A space does not match a single space character, but any amount of 'whitespace' in the input. More precisely, a space inside the format string matches *any number* of tab, space, line feed and carriage return characters. Similarly, a line feed character in the format string matches either a single line feed or a carriage return followed by a line feed.
Matching *any* amount of whitespace, a space in the format string also matches no amount of whitespace at all; hence, the call `bscanf ib
"Price = %d $" (fun p -> p)` succeeds and returns `1` when reading an input with various whitespace in it, such as `Price = 1 $`, `Price = 1 $`, or even `Price=1$`.
### Conversion specifications in format strings
Conversion specifications consist in the `%` character, followed by an optional flag, an optional field width, and followed by one or two conversion characters.
The conversion characters and their meanings are:
* `d`: reads an optionally signed decimal integer (`0-9`+).
* `i`: reads an optionally signed integer (usual input conventions for decimal (`0-9`+), hexadecimal (`0x[0-9a-f]+` and `0X[0-9A-F]+`), octal (`0o[0-7]+`), and binary (`0b[0-1]+`) notations are understood).
* `u`: reads an unsigned decimal integer.
* `x` or `X`: reads an unsigned hexadecimal integer (`[0-9a-fA-F]+`).
* `o`: reads an unsigned octal integer (`[0-7]+`).
* `s`: reads a string argument that spreads as much as possible, until the following bounding condition holds:
+ a whitespace has been found (see [*The space character in format strings*](scanf#space)),
+ a scanning indication (see scanning [*Scanning indications in format strings*](scanf#indication)) has been encountered,
+ the end-of-input has been reached. Hence, this conversion always succeeds: it returns an empty string if the bounding condition holds when the scan begins.
* `S`: reads a delimited string argument (delimiters and special escaped characters follow the lexical conventions of OCaml).
* `c`: reads a single character. To test the current input character without reading it, specify a null field width, i.e. use specification `%0c`. Raise `Invalid\_argument`, if the field width specification is greater than 1.
* `C`: reads a single delimited character (delimiters and special escaped characters follow the lexical conventions of OCaml).
* `f`, `e`, `E`, `g`, `G`: reads an optionally signed floating-point number in decimal notation, in the style `dddd.ddd
e/E+-dd`.
* `h`, `H`: reads an optionally signed floating-point number in hexadecimal notation.
* `F`: reads a floating point number according to the lexical conventions of OCaml (hence the decimal point is mandatory if the exponent part is not mentioned).
* `B`: reads a boolean argument (`true` or `false`).
* `b`: reads a boolean argument (for backward compatibility; do not use in new programs).
* `ld`, `li`, `lu`, `lx`, `lX`, `lo`: reads an `int32` argument to the format specified by the second letter for regular integers.
* `nd`, `ni`, `nu`, `nx`, `nX`, `no`: reads a `nativeint` argument to the format specified by the second letter for regular integers.
* `Ld`, `Li`, `Lu`, `Lx`, `LX`, `Lo`: reads an `int64` argument to the format specified by the second letter for regular integers.
* `[ range ]`: reads characters that matches one of the characters mentioned in the range of characters `range` (or not mentioned in it, if the range starts with `^`). Reads a `string` that can be empty, if the next input character does not match the range. The set of characters from `c1` to `c2` (inclusively) is denoted by `c1-c2`. Hence, `%[0-9]` returns a string representing a decimal number or an empty string if no decimal digit is found; similarly, `%[0-9a-f]` returns a string of hexadecimal digits. If a closing bracket appears in a range, it must occur as the first character of the range (or just after the `^` in case of range negation); hence `[]]` matches a `]` character and `[^]]` matches any character that is not `]`. Use `%%` and `%@` to include a `%` or a `@` in a range.
* `r`: user-defined reader. Takes the next `ri` formatted input function and applies it to the scanning buffer `ib` to read the next argument. The input function `ri` must therefore have type `Scanning.in_channel -> 'a` and the argument read has type `'a`.
* `{ fmt %}`: reads a format string argument. The format string read must have the same type as the format string specification `fmt`. For instance, `"%{ %i %}"` reads any format string that can read a value of type `int`; hence, if `s` is the string `"fmt:\"number is %u\""`, then `Scanf.sscanf s "fmt: %{%i%}"` succeeds and returns the format string `"number is %u"`.
* `( fmt %)`: scanning sub-format substitution. Reads a format string `rf` in the input, then goes on scanning with `rf` instead of scanning with `fmt`. The format string `rf` must have the same type as the format string specification `fmt` that it replaces. For instance, `"%( %i %)"` reads any format string that can read a value of type `int`. The conversion returns the format string read `rf`, and then a value read using `rf`. Hence, if `s` is the string `"\"%4d\"1234.00"`, then `Scanf.sscanf s "%(%i%)" (fun fmt i -> fmt, i)` evaluates to `("%4d", 1234)`. This behaviour is not mere format substitution, since the conversion returns the format string read as additional argument. If you need pure format substitution, use special flag `_` to discard the extraneous argument: conversion `%_( fmt %)` reads a format string `rf` and then behaves the same as format string `rf`. Hence, if `s` is the string `"\"%4d\"1234.00"`, then `Scanf.sscanf s "%\_(%i%)"` is simply equivalent to `Scanf.sscanf "1234.00" "%4d"`.
* `l`: returns the number of lines read so far.
* `n`: returns the number of characters read so far.
* `N` or `L`: returns the number of tokens read so far.
* `!`: matches the end of input condition.
* `%`: matches one `%` character in the input.
* `@`: matches one `@` character in the input.
* `,`: does nothing.
Following the `%` character that introduces a conversion, there may be the special flag `_`: the conversion that follows occurs as usual, but the resulting value is discarded. For instance, if `f` is the function `fun i -> i + 1`, and `s` is the string `"x = 1"`, then `Scanf.sscanf s "%\_s = %i" f` returns `2`.
The field width is composed of an optional integer literal indicating the maximal width of the token to read. For instance, `%6d` reads an integer, having at most 6 decimal digits; `%4f` reads a float with at most 4 characters; and `%8[\000-\255]` returns the next 8 characters (or all the characters still available, if fewer than 8 characters are available in the input).
Notes:
* as mentioned above, a `%s` conversion always succeeds, even if there is nothing to read in the input: in this case, it simply returns `""`.
* in addition to the relevant digits, `'\_'` characters may appear inside numbers (this is reminiscent to the usual OCaml lexical conventions). If stricter scanning is desired, use the range conversion facility instead of the number conversions.
* the `scanf` facility is not intended for heavy duty lexical analysis and parsing. If it appears not expressive enough for your needs, several alternative exists: regular expressions (module [`Str`](str)), stream parsers, `ocamllex`-generated lexers, `ocamlyacc`-generated parsers.
### Scanning indications in format strings
Scanning indications appear just after the string conversions `%s` and `%[ range ]` to delimit the end of the token. A scanning indication is introduced by a `@` character, followed by some plain character `c`. It means that the string token should end just before the next matching `c` (which is skipped). If no `c` character is encountered, the string token spreads as much as possible. For instance, `"%s@\t"` reads a string up to the next tab character or to the end of input. If a `@` character appears anywhere else in the format string, it is treated as a plain character.
Note:
* As usual in format strings, `%` and `@` characters must be escaped using `%%` and `%@`; this rule still holds within range specifications and scanning indications. For instance, format `"%s@%%"` reads a string up to the next `%` character, and format `"%s@%@"` reads a string up to the next `@`.
* The scanning indications introduce slight differences in the syntax of [`Scanf`](scanf) format strings, compared to those used for the [`Printf`](printf) module. However, the scanning indications are similar to those used in the [`Format`](format) module; hence, when producing formatted text to be scanned by [`Scanf.bscanf`](scanf#VALbscanf), it is wise to use printing functions from the [`Format`](format) module (or, if you need to use functions from [`Printf`](printf), banish or carefully double check the format strings that contain `'@'` characters).
### Exceptions during scanning
Scanners may raise the following exceptions when the input cannot be read according to the format string:
* Raise [`Scanf.Scan\_failure`](scanf#EXCEPTIONScan_failure) if the input does not match the format.
* Raise `Failure` if a conversion to a number is not possible.
* Raise `End\_of\_file` if the end of input is encountered while some more characters are needed to read the current conversion specification.
* Raise `Invalid\_argument` if the format string is invalid.
Note:
* as a consequence, scanning a `%s` conversion never raises exception `End\_of\_file`: if the end of input is reached the conversion succeeds and simply returns the characters read so far, or `""` if none were ever read.
Specialised formatted input functions
-------------------------------------
```
val sscanf : string -> ('a, 'b, 'c, 'd) scanner
```
Same as [`Scanf.bscanf`](scanf#VALbscanf), but reads from the given string.
```
val sscanf_opt : string -> ('a, 'b, 'c, 'd) scanner_opt
```
Same as [`Scanf.sscanf`](scanf#VALsscanf), but returns `None` in case of scanning failure.
* **Since** 5.0
```
val scanf : ('a, 'b, 'c, 'd) scanner
```
Same as [`Scanf.bscanf`](scanf#VALbscanf), but reads from the predefined formatted input channel [`Scanf.Scanning.stdin`](scanf.scanning#VALstdin) that is connected to [`stdin`](stdlib#VALstdin).
```
val scanf_opt : ('a, 'b, 'c, 'd) scanner_opt
```
Same as [`Scanf.scanf`](scanf#VALscanf), but returns `None` in case of scanning failure.
* **Since** 5.0
```
val kscanf : Scanning.in_channel -> (Scanning.in_channel -> exn -> 'd) -> ('a, 'b, 'c, 'd) scanner
```
Same as [`Scanf.bscanf`](scanf#VALbscanf), but takes an additional function argument `ef` that is called in case of error: if the scanning process or some conversion fails, the scanning function aborts and calls the error handling function `ef` with the formatted input channel and the exception that aborted the scanning process as arguments.
```
val ksscanf : string -> (Scanning.in_channel -> exn -> 'd) -> ('a, 'b, 'c, 'd) scanner
```
Same as [`Scanf.kscanf`](scanf#VALkscanf) but reads from the given string.
* **Since** 4.02.0
Reading format strings from input
---------------------------------
```
val bscanf_format : Scanning.in_channel -> ('a, 'b, 'c, 'd, 'e, 'f) format6 -> (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g
```
`bscanf_format ic fmt f` reads a format string token from the formatted input channel `ic`, according to the given format string `fmt`, and applies `f` to the resulting format string value.
* **Since** 3.09.0
* **Raises** `Scan_failure` if the format string value read does not have the same type as `fmt`.
```
val sscanf_format : string -> ('a, 'b, 'c, 'd, 'e, 'f) format6 -> (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g
```
Same as [`Scanf.bscanf_format`](scanf#VALbscanf_format), but reads from the given string.
* **Since** 3.09.0
```
val format_from_string : string -> ('a, 'b, 'c, 'd, 'e, 'f) format6 -> ('a, 'b, 'c, 'd, 'e, 'f) format6
```
`format_from_string s fmt` converts a string argument to a format string, according to the given format string `fmt`.
* **Since** 3.10.0
* **Raises** `Scan_failure` if `s`, considered as a format string, does not have the same type as `fmt`.
```
val unescaped : string -> string
```
`unescaped s` return a copy of `s` with escape sequences (according to the lexical conventions of OCaml) replaced by their corresponding special characters. More precisely, `Scanf.unescaped` has the following property: for all string `s`, `Scanf.unescaped (String.escaped s) = s`.
Always return a copy of the argument, even if there is no escape sequence in the argument.
* **Since** 4.00.0
* **Raises** `Scan_failure` if `s` is not properly escaped (i.e. `s` has invalid escape sequences or special characters that are not properly escaped). For instance, `Scanf.unescaped "\""` will fail.
| programming_docs |
ocaml Module Format Module Format
=============
```
module Format: sig .. end
```
Pretty-printing.
This module implements a pretty-printing facility to format values within ['pretty-printing boxes'](format#boxes) and ['semantic tags'](format#tags) combined with a set of [printf-like functions](format#fpp). The pretty-printer splits lines at specified [break hints](format#breaks), and indents lines according to the box structure. Similarly, [semantic tags](format#tags) can be used to decouple text presentation from its contents.
This pretty-printing facility is implemented as an overlay on top of abstract [formatters](format#formatter) which provide basic output functions. Some formatters are predefined, notably:
* [`Format.std_formatter`](format#VALstd_formatter) outputs to [stdout](stdlib#VALstdout)
* [`Format.err_formatter`](format#VALerr_formatter) outputs to [stderr](stdlib#VALstderr)
Most functions in the [`Format`](format) module come in two variants: a short version that operates on the current domain's standard formatter as obtained using [`Format.get_std_formatter`](format#VALget_std_formatter) and the generic version prefixed by `pp_` that takes a formatter as its first argument. For the version that operates on the current domain's standard formatter, the call to [`Format.get_std_formatter`](format#VALget_std_formatter) is delayed until the last argument is received.
More formatters can be created with [`Format.formatter_of_out_channel`](format#VALformatter_of_out_channel), [`Format.formatter_of_buffer`](format#VALformatter_of_buffer), [`Format.formatter_of_symbolic_output_buffer`](format#VALformatter_of_symbolic_output_buffer) or using [custom formatters](format#formatter).
Warning: Since [formatters](format#formatter) contain mutable state, it is not thread-safe to use the same formatter on multiple domains in parallel without synchronization.
If multiple domains write to the same output channel using the predefined formatters (as obtained by [`Format.get_std_formatter`](format#VALget_std_formatter) or [`Format.get_err_formatter`](format#VALget_err_formatter)), the output from the domains will be interleaved with each other at points where the formatters are flushed, such as with [`Format.print_flush`](format#VALprint_flush). This synchronization is not performed by formatters obtained from [`Format.formatter_of_out_channel`](format#VALformatter_of_out_channel) (on the standard out channels or others).
Introduction
------------
You may consider this module as providing an extension to the `printf` facility to provide automatic line splitting. The addition of pretty-printing annotations to your regular `printf` format strings gives you fancy indentation and line breaks. Pretty-printing annotations are described below in the documentation of the function [`Format.fprintf`](format#VALfprintf).
You may also use the explicit pretty-printing box management and printing functions provided by this module. This style is more basic but more verbose than the concise `fprintf` format strings.
For instance, the sequence `open_box 0; print_string "x ="; print_space ();
print_int 1; close_box (); print_newline ()` that prints `x = 1` within a pretty-printing box, can be abbreviated as `printf "@[%s@ %i@]@." "x =" 1`, or even shorter `printf "@[x =@ %i@]@." 1`.
Rule of thumb for casual users of this library:
* use simple pretty-printing boxes (as obtained by `open_box 0`);
* use simple break hints as obtained by `print_cut ()` that outputs a simple break hint, or by `print_space ()` that outputs a space indicating a break hint;
* once a pretty-printing box is open, display its material with basic printing functions (e. g. `print_int` and `print_string`);
* when the material for a pretty-printing box has been printed, call `close_box ()` to close the box;
* at the end of pretty-printing, flush the pretty-printer to display all the remaining material, e.g. evaluate `print_newline ()`.
The behavior of pretty-printing commands is unspecified if there is no open pretty-printing box. Each box opened by one of the `open_` functions below must be closed using `close_box` for proper formatting. Otherwise, some of the material printed in the boxes may not be output, or may be formatted incorrectly.
In case of interactive use, each phrase is executed in the initial state of the standard pretty-printer: after each phrase execution, the interactive system closes all open pretty-printing boxes, flushes all pending text, and resets the standard pretty-printer.
Warning: mixing calls to pretty-printing functions of this module with calls to [`Stdlib`](stdlib) low level output functions is error prone.
The pretty-printing functions output material that is delayed in the pretty-printer queue and stacks in order to compute proper line splitting. In contrast, basic I/O output functions write directly in their output device. As a consequence, the output of a basic I/O function may appear before the output of a pretty-printing function that has been called before. For instance, `Stdlib.print_string "<";
Format.print_string "PRETTY";
Stdlib.print_string ">";
Format.print_string "TEXT";` leads to output `<>PRETTYTEXT`.
Formatters
----------
```
type formatter
```
Abstract data corresponding to a pretty-printer (also called a formatter) and all its machinery. See also [*Defining formatters*](format#formatter).
Pretty-printing boxes
---------------------
The pretty-printing engine uses the concepts of pretty-printing box and break hint to drive indentation and line splitting behavior of the pretty-printer.
Each different pretty-printing box kind introduces a specific line splitting policy:
* within an *horizontal* box, break hints never split the line (but the line may be split in a box nested deeper),
* within a *vertical* box, break hints always split the line,
* within an *horizontal/vertical* box, if the box fits on the current line then break hints never split the line, otherwise break hint always split the line,
* within a *compacting* box, a break hint never splits the line, unless there is no more room on the current line.
Note that line splitting policy is box specific: the policy of a box does not rule the policy of inner boxes. For instance, if a vertical box is nested in an horizontal box, all break hints within the vertical box will split the line.
Moreover, opening a box after the [maximum indentation limit](format#maxindent) splits the line whether or not the box would end up fitting on the line.
```
val pp_open_box : formatter -> int -> unit
```
```
val open_box : int -> unit
```
`pp_open_box ppf d` opens a new compacting pretty-printing box with offset `d` in the formatter `ppf`.
Within this box, the pretty-printer prints as much as possible material on every line.
A break hint splits the line if there is no more room on the line to print the remainder of the box.
Within this box, the pretty-printer emphasizes the box structure: if a structural box does not fit fully on a simple line, a break hint also splits the line if the splitting ``moves to the left'' (i.e. the new line gets an indentation smaller than the one of the current line).
This box is the general purpose pretty-printing box.
If the pretty-printer splits the line in the box, offset `d` is added to the current indentation.
```
val pp_close_box : formatter -> unit -> unit
```
```
val close_box : unit -> unit
```
Closes the most recently open pretty-printing box.
```
val pp_open_hbox : formatter -> unit -> unit
```
```
val open_hbox : unit -> unit
```
`pp_open_hbox ppf ()` opens a new 'horizontal' pretty-printing box.
This box prints material on a single line.
Break hints in a horizontal box never split the line. (Line splitting may still occur inside boxes nested deeper).
```
val pp_open_vbox : formatter -> int -> unit
```
```
val open_vbox : int -> unit
```
`pp_open_vbox ppf d` opens a new 'vertical' pretty-printing box with offset `d`.
This box prints material on as many lines as break hints in the box.
Every break hint in a vertical box splits the line.
If the pretty-printer splits the line in the box, `d` is added to the current indentation.
```
val pp_open_hvbox : formatter -> int -> unit
```
```
val open_hvbox : int -> unit
```
`pp_open_hvbox ppf d` opens a new 'horizontal/vertical' pretty-printing box with offset `d`.
This box behaves as an horizontal box if it fits on a single line, otherwise it behaves as a vertical box.
If the pretty-printer splits the line in the box, `d` is added to the current indentation.
```
val pp_open_hovbox : formatter -> int -> unit
```
```
val open_hovbox : int -> unit
```
`pp_open_hovbox ppf d` opens a new 'horizontal-or-vertical' pretty-printing box with offset `d`.
This box prints material as much as possible on every line.
A break hint splits the line if there is no more room on the line to print the remainder of the box.
If the pretty-printer splits the line in the box, `d` is added to the current indentation.
Formatting functions
--------------------
```
val pp_print_string : formatter -> string -> unit
```
```
val print_string : string -> unit
```
`pp_print_string ppf s` prints `s` in the current pretty-printing box.
```
val pp_print_bytes : formatter -> bytes -> unit
```
```
val print_bytes : bytes -> unit
```
`pp_print_bytes ppf b` prints `b` in the current pretty-printing box.
* **Since** 4.13.0
```
val pp_print_as : formatter -> int -> string -> unit
```
```
val print_as : int -> string -> unit
```
`pp_print_as ppf len s` prints `s` in the current pretty-printing box. The pretty-printer formats `s` as if it were of length `len`.
```
val pp_print_int : formatter -> int -> unit
```
```
val print_int : int -> unit
```
Print an integer in the current pretty-printing box.
```
val pp_print_float : formatter -> float -> unit
```
```
val print_float : float -> unit
```
Print a floating point number in the current pretty-printing box.
```
val pp_print_char : formatter -> char -> unit
```
```
val print_char : char -> unit
```
Print a character in the current pretty-printing box.
```
val pp_print_bool : formatter -> bool -> unit
```
```
val print_bool : bool -> unit
```
Print a boolean in the current pretty-printing box.
Break hints
-----------
A 'break hint' tells the pretty-printer to output some space or split the line whichever way is more appropriate to the current pretty-printing box splitting rules.
Break hints are used to separate printing items and are mandatory to let the pretty-printer correctly split lines and indent items.
Simple break hints are:
* the 'space': output a space or split the line if appropriate,
* the 'cut': split the line if appropriate.
Note: the notions of space and line splitting are abstract for the pretty-printing engine, since those notions can be completely redefined by the programmer. However, in the pretty-printer default setting, ``output a space'' simply means printing a space character (ASCII code 32) and ``split the line'' means printing a newline character (ASCII code 10).
```
val pp_print_space : formatter -> unit -> unit
```
```
val print_space : unit -> unit
```
`pp_print_space ppf ()` emits a 'space' break hint: the pretty-printer may split the line at this point, otherwise it prints one space.
`pp_print_space ppf ()` is equivalent to `pp_print_break ppf 1 0`.
```
val pp_print_cut : formatter -> unit -> unit
```
```
val print_cut : unit -> unit
```
`pp_print_cut ppf ()` emits a 'cut' break hint: the pretty-printer may split the line at this point, otherwise it prints nothing.
`pp_print_cut ppf ()` is equivalent to `pp_print_break ppf 0 0`.
```
val pp_print_break : formatter -> int -> int -> unit
```
```
val print_break : int -> int -> unit
```
`pp_print_break ppf nspaces offset` emits a 'full' break hint: the pretty-printer may split the line at this point, otherwise it prints `nspaces` spaces.
If the pretty-printer splits the line, `offset` is added to the current indentation.
```
val pp_print_custom_break : formatter -> fits:string * int * string -> breaks:string * int * string -> unit
```
`pp_print_custom_break ppf ~fits:(s1, n, s2) ~breaks:(s3, m, s4)` emits a custom break hint: the pretty-printer may split the line at this point.
If it does not split the line, then the `s1` is emitted, then `n` spaces, then `s2`.
If it splits the line, then it emits the `s3` string, then an indent (according to the box rules), then an offset of `m` spaces, then the `s4` string.
While `n` and `m` are handled by `formatter_out_functions.out_indent`, the strings will be handled by `formatter_out_functions.out_string`. This allows for a custom formatter that handles indentation distinctly, for example, outputs `<br/>` tags or ` ` entities.
The custom break is useful if you want to change which visible (non-whitespace) characters are printed in case of break or no break. For example, when printing a list `[a; b; c]`, you might want to add a trailing semicolon when it is printed vertically:
```
[
a;
b;
c;
]
```
You can do this as follows:
```
printf "@[<v 0>[@;<0 2>@[<v 0>a;@,b;@,c@]%t]@]@\n"
(pp_print_custom_break ~fits:("", 0, "") ~breaks:(";", 0, ""))
```
* **Since** 4.08.0
```
val pp_force_newline : formatter -> unit -> unit
```
```
val force_newline : unit -> unit
```
Force a new line in the current pretty-printing box.
The pretty-printer must split the line at this point,
Not the normal way of pretty-printing, since imperative line splitting may interfere with current line counters and box size calculation. Using break hints within an enclosing vertical box is a better alternative.
```
val pp_print_if_newline : formatter -> unit -> unit
```
```
val print_if_newline : unit -> unit
```
Execute the next formatting command if the preceding line has just been split. Otherwise, ignore the next formatting command.
Pretty-printing termination
---------------------------
```
val pp_print_flush : formatter -> unit -> unit
```
```
val print_flush : unit -> unit
```
End of pretty-printing: resets the pretty-printer to initial state.
All open pretty-printing boxes are closed, all pending text is printed. In addition, the pretty-printer low level output device is flushed to ensure that all pending text is really displayed.
Note: never use `print_flush` in the normal course of a pretty-printing routine, since the pretty-printer uses a complex buffering machinery to properly indent the output; manually flushing those buffers at random would conflict with the pretty-printer strategy and result to poor rendering.
Only consider using `print_flush` when displaying all pending material is mandatory (for instance in case of interactive use when you want the user to read some text) and when resetting the pretty-printer state will not disturb further pretty-printing.
Warning: If the output device of the pretty-printer is an output channel, repeated calls to `print_flush` means repeated calls to [`flush`](stdlib#VALflush) to flush the out channel; these explicit flush calls could foil the buffering strategy of output channels and could dramatically impact efficiency.
```
val pp_print_newline : formatter -> unit -> unit
```
```
val print_newline : unit -> unit
```
End of pretty-printing: resets the pretty-printer to initial state.
All open pretty-printing boxes are closed, all pending text is printed.
Equivalent to [`Format.print_flush`](format#VALprint_flush) followed by a new line. See corresponding words of caution for [`Format.print_flush`](format#VALprint_flush).
Note: this is not the normal way to output a new line; the preferred method is using break hints within a vertical pretty-printing box.
Margin
------
```
val pp_set_margin : formatter -> int -> unit
```
```
val set_margin : int -> unit
```
`pp_set_margin ppf d` sets the right margin to `d` (in characters): the pretty-printer splits lines that overflow the right margin according to the break hints given. Setting the margin to `d` means that the formatting engine aims at printing at most `d-1` characters per line. Nothing happens if `d` is smaller than 2. If `d` is too large, the right margin is set to the maximum admissible value (which is greater than `10 ^ 9`). If `d` is less than the current maximum indentation limit, the maximum indentation limit is decreased while trying to preserve a minimal ratio `max_indent/margin>=50%` and if possible the current difference `margin - max_indent`.
See also [`Format.pp_set_geometry`](format#VALpp_set_geometry).
```
val pp_get_margin : formatter -> unit -> int
```
```
val get_margin : unit -> int
```
Returns the position of the right margin.
Maximum indentation limit
-------------------------
```
val pp_set_max_indent : formatter -> int -> unit
```
```
val set_max_indent : int -> unit
```
`pp_set_max_indent ppf d` sets the maximum indentation limit of lines to `d` (in characters): once this limit is reached, new pretty-printing boxes are rejected to the left, unless the enclosing box fully fits on the current line. As an illustration,
```
set_margin 10; set_max_indent 5; printf "@[123456@[7@]89A@]@."
```
yields
```
123456
789A
```
because the nested box `"@[7@]"` is opened after the maximum indentation limit (`7>5`) and its parent box does not fit on the current line. Either decreasing the length of the parent box to make it fit on a line:
```
printf "@[123456@[7@]89@]@."
```
or opening an intermediary box before the maximum indentation limit which fits on the current line
```
printf "@[123@[456@[7@]89@]A@]@."
```
avoids the rejection to the left of the inner boxes and print respectively `"123456789"` and `"123456789A"` . Note also that vertical boxes never fit on a line whereas horizontal boxes always fully fit on the current line. Opening a box may split a line whereas the contents may have fit. If this behavior is problematic, it can be curtailed by setting the maximum indentation limit to `margin - 1`. Note that setting the maximum indentation limit to `margin` is invalid.
Nothing happens if `d` is smaller than 2.
If `d` is too large, the limit is set to the maximum admissible value (which is greater than `10 ^ 9`).
If `d` is greater or equal than the current margin, it is ignored, and the current maximum indentation limit is kept.
See also [`Format.pp_set_geometry`](format#VALpp_set_geometry).
```
val pp_get_max_indent : formatter -> unit -> int
```
```
val get_max_indent : unit -> int
```
Return the maximum indentation limit (in characters).
Geometry
--------
Geometric functions can be used to manipulate simultaneously the coupled variables, margin and maxixum indentation limit.
```
type geometry = {
```
| | |
| --- | --- |
| | `max\_indent : `int`;` |
| | `margin : `int`;` |
`}` * **Since** 4.08
```
val check_geometry : geometry -> bool
```
Check if the formatter geometry is valid: `1 < max_indent < margin`
* **Since** 4.08
```
val pp_set_geometry : formatter -> max_indent:int -> margin:int -> unit
```
```
val set_geometry : max_indent:int -> margin:int -> unit
```
```
val pp_safe_set_geometry : formatter -> max_indent:int -> margin:int -> unit
```
```
val safe_set_geometry : max_indent:int -> margin:int -> unit
```
`pp_set_geometry ppf ~max_indent ~margin` sets both the margin and maximum indentation limit for `ppf`.
When `1 < max_indent < margin`, `pp_set_geometry ppf ~max_indent ~margin` is equivalent to `pp_set_margin ppf margin; pp_set_max_indent ppf max_indent`; and avoids the subtly incorrect `pp_set_max_indent ppf max_indent; pp_set_margin ppf margin`;
Outside of this domain, `pp_set_geometry` raises an invalid argument exception whereas `pp_safe_set_geometry` does nothing.
* **Since** 4.08.0
```
val pp_update_geometry : formatter -> (geometry -> geometry) -> unit
```
`pp_update_geometry ppf (fun geo -> { geo with ... })` lets you update a formatter's geometry in a way that is robust to extension of the `geometry` record with new fields.
Raises an invalid argument exception if the returned geometry does not satisfy [`Format.check_geometry`](format#VALcheck_geometry).
* **Since** 4.11.0
```
val update_geometry : (geometry -> geometry) -> unit
```
```
val pp_get_geometry : formatter -> unit -> geometry
```
```
val get_geometry : unit -> geometry
```
Return the current geometry of the formatter
* **Since** 4.08.0
Maximum formatting depth
------------------------
The maximum formatting depth is the maximum number of pretty-printing boxes simultaneously open.
Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by [`Format.get_ellipsis_text`](format#VALget_ellipsis_text) `()`).
```
val pp_set_max_boxes : formatter -> int -> unit
```
```
val set_max_boxes : int -> unit
```
`pp_set_max_boxes ppf max` sets the maximum number of pretty-printing boxes simultaneously open.
Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by [`Format.get_ellipsis_text`](format#VALget_ellipsis_text) `()`).
Nothing happens if `max` is smaller than 2.
```
val pp_get_max_boxes : formatter -> unit -> int
```
```
val get_max_boxes : unit -> int
```
Returns the maximum number of pretty-printing boxes allowed before ellipsis.
```
val pp_over_max_boxes : formatter -> unit -> bool
```
```
val over_max_boxes : unit -> bool
```
Tests if the maximum number of pretty-printing boxes allowed have already been opened.
Tabulation boxes
----------------
A *tabulation box* prints material on lines divided into cells of fixed length. A tabulation box provides a simple way to display vertical columns of left adjusted text.
This box features command `set_tab` to define cell boundaries, and command `print_tab` to move from cell to cell and split the line when there is no more cells to print on the line.
Note: printing within tabulation box is line directed, so arbitrary line splitting inside a tabulation box leads to poor rendering. Yet, controlled use of tabulation boxes allows simple printing of columns within module [`Format`](format).
```
val pp_open_tbox : formatter -> unit -> unit
```
```
val open_tbox : unit -> unit
```
`open_tbox ()` opens a new tabulation box.
This box prints lines separated into cells of fixed width.
Inside a tabulation box, special *tabulation markers* defines points of interest on the line (for instance to delimit cell boundaries). Function [`Format.set_tab`](format#VALset_tab) sets a tabulation marker at insertion point.
A tabulation box features specific *tabulation breaks* to move to next tabulation marker or split the line. Function [`Format.print_tbreak`](format#VALprint_tbreak) prints a tabulation break.
```
val pp_close_tbox : formatter -> unit -> unit
```
```
val close_tbox : unit -> unit
```
Closes the most recently opened tabulation box.
```
val pp_set_tab : formatter -> unit -> unit
```
```
val set_tab : unit -> unit
```
Sets a tabulation marker at current insertion point.
```
val pp_print_tab : formatter -> unit -> unit
```
```
val print_tab : unit -> unit
```
`print_tab ()` emits a 'next' tabulation break hint: if not already set on a tabulation marker, the insertion point moves to the first tabulation marker on the right, or the pretty-printer splits the line and insertion point moves to the leftmost tabulation marker.
It is equivalent to `print_tbreak 0 0`.
```
val pp_print_tbreak : formatter -> int -> int -> unit
```
```
val print_tbreak : int -> int -> unit
```
`print_tbreak nspaces offset` emits a 'full' tabulation break hint.
If not already set on a tabulation marker, the insertion point moves to the first tabulation marker on the right and the pretty-printer prints `nspaces` spaces.
If there is no next tabulation marker on the right, the pretty-printer splits the line at this point, then insertion point moves to the leftmost tabulation marker of the box.
If the pretty-printer splits the line, `offset` is added to the current indentation.
Ellipsis
--------
```
val pp_set_ellipsis_text : formatter -> string -> unit
```
```
val set_ellipsis_text : string -> unit
```
Set the text of the ellipsis printed when too many pretty-printing boxes are open (a single dot, `.`, by default).
```
val pp_get_ellipsis_text : formatter -> unit -> string
```
```
val get_ellipsis_text : unit -> string
```
Return the text of the ellipsis.
Semantic tags
-------------
```
type stag = ..
```
*Semantic tags* (or simply *tags*) are user's defined annotations to associate user's specific operations to printed entities.
Common usage of semantic tags is text decoration to get specific font or text size rendering for a display device, or marking delimitation of entities (e.g. HTML or TeX elements or terminal escape sequences). More sophisticated usage of semantic tags could handle dynamic modification of the pretty-printer behavior to properly print the material within some specific tags. For instance, we can define an RGB tag like so:
```
type stag += RGB of {r:int;g:int;b:int}
```
In order to properly delimit printed entities, a semantic tag must be opened before and closed after the entity. Semantic tags must be properly nested like parentheses using [`Format.pp_open_stag`](format#VALpp_open_stag) and [`Format.pp_close_stag`](format#VALpp_close_stag).
Tag specific operations occur any time a tag is opened or closed, At each occurrence, two kinds of operations are performed *tag-marking* and *tag-printing*:
* The tag-marking operation is the simpler tag specific operation: it simply writes a tag specific string into the output device of the formatter. Tag-marking does not interfere with line-splitting computation.
* The tag-printing operation is the more involved tag specific operation: it can print arbitrary material to the formatter. Tag-printing is tightly linked to the current pretty-printer operations.
Roughly speaking, tag-marking is commonly used to get a better rendering of texts in the rendering device, while tag-printing allows fine tuning of printing routines to print the same entity differently according to the semantic tags (i.e. print additional material or even omit parts of the output).
More precisely: when a semantic tag is opened or closed then both and successive 'tag-printing' and 'tag-marking' operations occur:
* Tag-printing a semantic tag means calling the formatter specific function `print_open_stag` (resp. `print_close_stag`) with the name of the tag as argument: that tag-printing function can then print any regular material to the formatter (so that this material is enqueued as usual in the formatter queue for further line splitting computation).
* Tag-marking a semantic tag means calling the formatter specific function `mark_open_stag` (resp. `mark_close_stag`) with the name of the tag as argument: that tag-marking function can then return the 'tag-opening marker' (resp. `tag-closing marker') for direct output into the output device of the formatter.
Being written directly into the output device of the formatter, semantic tag marker strings are not considered as part of the printing material that drives line splitting (in other words, the length of the strings corresponding to tag markers is considered as zero for line splitting).
Thus, semantic tag handling is in some sense transparent to pretty-printing and does not interfere with usual indentation. Hence, a single pretty-printing routine can output both simple 'verbatim' material or richer decorated output depending on the treatment of tags. By default, tags are not active, hence the output is not decorated with tag information. Once `set_tags` is set to `true`, the pretty-printer engine honors tags and decorates the output accordingly.
Default tag-marking functions behave the HTML way: [string tags](format#TYPEtag) are enclosed in "<" and ">" while other tags are ignored; hence, opening marker for tag string `"t"` is `"<t>"` and closing marker is `"</t>"`.
Default tag-printing functions just do nothing.
Tag-marking and tag-printing functions are user definable and can be set by calling [`Format.set_formatter_stag_functions`](format#VALset_formatter_stag_functions).
Semantic tag operations may be set on or off with [`Format.set_tags`](format#VALset_tags). Tag-marking operations may be set on or off with [`Format.set_mark_tags`](format#VALset_mark_tags). Tag-printing operations may be set on or off with [`Format.set_print_tags`](format#VALset_print_tags).
* **Since** 4.08.0
```
type tag = string
```
```
type stag +=
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `String\_tag of `[tag](format#TYPEtag)`` | `(*` | `String\_tag s` is a string tag `s`. String tags can be inserted either by explicitly using the constructor `String\_tag` or by using the dedicated format syntax `"@{<s> ... @}"`. * **Since** 4.08.0
| `*)` |
```
val pp_open_stag : formatter -> stag -> unit
```
```
val open_stag : stag -> unit
```
`pp_open_stag ppf t` opens the semantic tag named `t`.
The `print_open_stag` tag-printing function of the formatter is called with `t` as argument; then the opening tag marker for `t`, as given by `mark_open_stag t`, is written into the output device of the formatter.
* **Since** 4.08.0
```
val pp_close_stag : formatter -> unit -> unit
```
```
val close_stag : unit -> unit
```
`pp_close_stag ppf ()` closes the most recently opened semantic tag `t`.
The closing tag marker, as given by `mark_close_stag t`, is written into the output device of the formatter; then the `print_close_stag` tag-printing function of the formatter is called with `t` as argument.
* **Since** 4.08.0
```
val pp_set_tags : formatter -> bool -> unit
```
```
val set_tags : bool -> unit
```
`pp_set_tags ppf b` turns on or off the treatment of semantic tags (default is off).
```
val pp_set_print_tags : formatter -> bool -> unit
```
```
val set_print_tags : bool -> unit
```
`pp_set_print_tags ppf b` turns on or off the tag-printing operations.
```
val pp_set_mark_tags : formatter -> bool -> unit
```
```
val set_mark_tags : bool -> unit
```
`pp_set_mark_tags ppf b` turns on or off the tag-marking operations.
```
val pp_get_print_tags : formatter -> unit -> bool
```
```
val get_print_tags : unit -> bool
```
Return the current status of tag-printing operations.
```
val pp_get_mark_tags : formatter -> unit -> bool
```
```
val get_mark_tags : unit -> bool
```
Return the current status of tag-marking operations.
```
val pp_set_formatter_out_channel : formatter -> out_channel -> unit
```
Redirecting the standard formatter output
-----------------------------------------
```
val set_formatter_out_channel : out_channel -> unit
```
Redirect the standard pretty-printer output to the given channel. (All the output functions of the standard formatter are set to the default output functions printing to the given channel.)
`set_formatter_out_channel` is equivalent to [`Format.pp_set_formatter_out_channel`](format#VALpp_set_formatter_out_channel) `std_formatter`.
```
val pp_set_formatter_output_functions : formatter -> (string -> int -> int -> unit) -> (unit -> unit) -> unit
```
```
val set_formatter_output_functions : (string -> int -> int -> unit) -> (unit -> unit) -> unit
```
`pp_set_formatter_output_functions ppf out flush` redirects the standard pretty-printer output functions to the functions `out` and `flush`.
The `out` function performs all the pretty-printer string output. It is called with a string `s`, a start position `p`, and a number of characters `n`; it is supposed to output characters `p` to `p + n - 1` of `s`.
The `flush` function is called whenever the pretty-printer is flushed (via conversion `%!`, or pretty-printing indications `@?` or `@.`, or using low level functions `print_flush` or `print_newline`).
```
val pp_get_formatter_output_functions : formatter -> unit -> (string -> int -> int -> unit) * (unit -> unit)
```
```
val get_formatter_output_functions : unit -> (string -> int -> int -> unit) * (unit -> unit)
```
Return the current output functions of the standard pretty-printer.
Redefining formatter output
---------------------------
The `Format` module is versatile enough to let you completely redefine the meaning of pretty-printing output: you may provide your own functions to define how to handle indentation, line splitting, and even printing of all the characters that have to be printed!
### Redefining output functions
```
type formatter_out_functions = {
```
| | |
| --- | --- |
| | `out\_string : `string -> int -> int -> unit`;` |
| | `out\_flush : `unit -> unit`;` |
| | `out\_newline : `unit -> unit`;` |
| | `out\_spaces : `int -> unit`;` |
| | `out\_indent : `int -> unit`;` | `(*` | * **Since** 4.06.0
| `*)` |
`}` The set of output functions specific to a formatter:
* the `out_string` function performs all the pretty-printer string output. It is called with a string `s`, a start position `p`, and a number of characters `n`; it is supposed to output characters `p` to `p + n - 1` of `s`.
* the `out_flush` function flushes the pretty-printer output device.
* `out_newline` is called to open a new line when the pretty-printer splits the line.
* the `out_spaces` function outputs spaces when a break hint leads to spaces instead of a line split. It is called with the number of spaces to output.
* the `out_indent` function performs new line indentation when the pretty-printer splits the line. It is called with the indentation value of the new line.
By default:
* fields `out_string` and `out_flush` are output device specific; (e.g. [`output_string`](stdlib#VALoutput_string) and [`flush`](stdlib#VALflush) for a [`out_channel`](stdlib#TYPEout_channel) device, or `Buffer.add_substring` and [`ignore`](stdlib#VALignore) for a `Buffer.t` output device),
* field `out_newline` is equivalent to `out_string "\n" 0 1`;
* fields `out_spaces` and `out_indent` are equivalent to `out_string (String.make n ' ') 0 n`.
* **Since** 4.01.0
```
val pp_set_formatter_out_functions : formatter -> formatter_out_functions -> unit
```
```
val set_formatter_out_functions : formatter_out_functions -> unit
```
`pp_set_formatter_out_functions ppf out_funs` Set all the pretty-printer output functions of `ppf` to those of argument `out_funs`,
This way, you can change the meaning of indentation (which can be something else than just printing space characters) and the meaning of new lines opening (which can be connected to any other action needed by the application at hand).
Reasonable defaults for functions `out_spaces` and `out_newline` are respectively `out_funs.out_string (String.make n ' ') 0 n` and `out_funs.out_string "\n" 0 1`.
* **Since** 4.01.0
```
val pp_get_formatter_out_functions : formatter -> unit -> formatter_out_functions
```
```
val get_formatter_out_functions : unit -> formatter_out_functions
```
Return the current output functions of the pretty-printer, including line splitting and indentation functions. Useful to record the current setting and restore it afterwards.
* **Since** 4.01.0
Redefining semantic tag operations
----------------------------------
```
type formatter_stag_functions = {
```
| | |
| --- | --- |
| | `mark\_open\_stag : `[stag](format#TYPEstag) -> string`;` |
| | `mark\_close\_stag : `[stag](format#TYPEstag) -> string`;` |
| | `print\_open\_stag : `[stag](format#TYPEstag) -> unit`;` |
| | `print\_close\_stag : `[stag](format#TYPEstag) -> unit`;` |
`}` The semantic tag handling functions specific to a formatter: `mark` versions are the 'tag-marking' functions that associate a string marker to a tag in order for the pretty-printing engine to write those markers as 0 length tokens in the output device of the formatter. `print` versions are the 'tag-printing' functions that can perform regular printing when a tag is closed or opened.
* **Since** 4.08.0
```
val pp_set_formatter_stag_functions : formatter -> formatter_stag_functions -> unit
```
```
val set_formatter_stag_functions : formatter_stag_functions -> unit
```
`pp_set_formatter_stag_functions ppf tag_funs` changes the meaning of opening and closing semantic tag operations to use the functions in `tag_funs` when printing on `ppf`.
When opening a semantic tag with name `t`, the string `t` is passed to the opening tag-marking function (the `mark_open_stag` field of the record `tag_funs`), that must return the opening tag marker for that name. When the next call to `close_stag ()` happens, the semantic tag name `t` is sent back to the closing tag-marking function (the `mark_close_stag` field of record `tag_funs`), that must return a closing tag marker for that name.
The `print_` field of the record contains the tag-printing functions that are called at tag opening and tag closing time, to output regular material in the pretty-printer queue.
* **Since** 4.08.0
```
val pp_get_formatter_stag_functions : formatter -> unit -> formatter_stag_functions
```
```
val get_formatter_stag_functions : unit -> formatter_stag_functions
```
Return the current semantic tag operation functions of the standard pretty-printer.
* **Since** 4.08.0
Defining formatters
-------------------
Defining new formatters permits unrelated output of material in parallel on several output devices. All the parameters of a formatter are local to the formatter: right margin, maximum indentation limit, maximum number of pretty-printing boxes simultaneously open, ellipsis, and so on, are specific to each formatter and may be fixed independently.
For instance, given a [`Buffer.t`](buffer#TYPEt) buffer `b`, [`Format.formatter_of_buffer`](format#VALformatter_of_buffer) `b` returns a new formatter using buffer `b` as its output device. Similarly, given a [`out_channel`](stdlib#TYPEout_channel) output channel `oc`, [`Format.formatter_of_out_channel`](format#VALformatter_of_out_channel) `oc` returns a new formatter using channel `oc` as its output device.
Alternatively, given `out_funs`, a complete set of output functions for a formatter, then [`Format.formatter_of_out_functions`](format#VALformatter_of_out_functions) `out_funs` computes a new formatter using those functions for output.
```
val formatter_of_out_channel : out_channel -> formatter
```
`formatter_of_out_channel oc` returns a new formatter writing to the corresponding output channel `oc`.
```
val synchronized_formatter_of_out_channel : out_channel -> formatter Domain.DLS.key
```
`synchronized_formatter_of_out_channel oc` returns the key to the domain-local state that holds the domain-local formatter for writing to the corresponding output channel `oc`.
When the formatter is used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`Format.print_flush`](format#VALprint_flush).
* **Alert unstable.**
```
val std_formatter : formatter
```
The initial domain's standard formatter to write to standard output.
It is defined as [`Format.formatter_of_out_channel`](format#VALformatter_of_out_channel) [`stdout`](stdlib#VALstdout).
```
val get_std_formatter : unit -> formatter
```
`get_std_formatter ()` returns the current domain's standard formatter used to write to standard output.
* **Since** 5.0
```
val err_formatter : formatter
```
The initial domain's formatter to write to standard error.
It is defined as [`Format.formatter_of_out_channel`](format#VALformatter_of_out_channel) [`stderr`](stdlib#VALstderr).
```
val get_err_formatter : unit -> formatter
```
`get_err_formatter ()` returns the current domain's formatter used to write to standard error.
* **Since** 5.0
```
val formatter_of_buffer : Buffer.t -> formatter
```
`formatter_of_buffer b` returns a new formatter writing to buffer `b`. At the end of pretty-printing, the formatter must be flushed using [`Format.pp_print_flush`](format#VALpp_print_flush) or [`Format.pp_print_newline`](format#VALpp_print_newline), to print all the pending material into the buffer.
```
val stdbuf : Buffer.t
```
The initial domain's string buffer in which `str_formatter` writes.
```
val get_stdbuf : unit -> Buffer.t
```
`get_stdbuf ()` returns the current domain's string buffer in which the current domain's string formatter writes.
* **Since** 5.0
```
val str_formatter : formatter
```
The initial domain's formatter to output to the [`Format.stdbuf`](format#VALstdbuf) string buffer.
`str_formatter` is defined as [`Format.formatter_of_buffer`](format#VALformatter_of_buffer) [`Format.stdbuf`](format#VALstdbuf).
```
val get_str_formatter : unit -> formatter
```
The current domain's formatter to output to the current domains string buffer.
* **Since** 5.0
```
val flush_str_formatter : unit -> string
```
Returns the material printed with `str_formatter` of the current domain, flushes the formatter and resets the corresponding buffer.
```
val make_formatter : (string -> int -> int -> unit) -> (unit -> unit) -> formatter
```
`make_formatter out flush` returns a new formatter that outputs with function `out`, and flushes with function `flush`.
For instance,
```
make_formatter
(Stdlib.output oc)
(fun () -> Stdlib.flush oc)
```
returns a formatter to the [`out_channel`](stdlib#TYPEout_channel) `oc`.
```
val make_synchronized_formatter : (string -> int -> int -> unit) -> (unit -> unit) -> formatter Domain.DLS.key
```
`make_synchronized_formatter out flush` returns the key to the domain-local state that holds the domain-local formatter that outputs with function `out`, and flushes with function `flush`.
When the formatter is used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`Format.print_flush`](format#VALprint_flush).
* **Since** 5.0
* **Alert unstable.**
```
val formatter_of_out_functions : formatter_out_functions -> formatter
```
`formatter_of_out_functions out_funs` returns a new formatter that writes with the set of output functions `out_funs`.
See definition of type [`Format.formatter_out_functions`](format#TYPEformatter_out_functions) for the meaning of argument `out_funs`.
* **Since** 4.06.0
### Symbolic pretty-printing
Symbolic pretty-printing is pretty-printing using a symbolic formatter, i.e. a formatter that outputs symbolic pretty-printing items.
When using a symbolic formatter, all regular pretty-printing activities occur but output material is symbolic and stored in a buffer of output items. At the end of pretty-printing, flushing the output buffer allows post-processing of symbolic output before performing low level output operations.
In practice, first define a symbolic output buffer `b` using:
* `let sob = make_symbolic_output_buffer ()`. Then define a symbolic formatter with:
* `let ppf = formatter_of_symbolic_output_buffer sob`
Use symbolic formatter `ppf` as usual, and retrieve symbolic items at end of pretty-printing by flushing symbolic output buffer `sob` with:
* `flush_symbolic_output_buffer sob`.
```
type symbolic_output_item =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `Output\_flush` | `(*` | symbolic flush command | `*)` |
| `|` | `Output\_newline` | `(*` | symbolic newline command | `*)` |
| `|` | `Output\_string of `string`` | `(*` | `Output\_string s`: symbolic output for string `s` | `*)` |
| `|` | `Output\_spaces of `int`` | `(*` | `Output\_spaces n`: symbolic command to output `n` spaces | `*)` |
| `|` | `Output\_indent of `int`` | `(*` | `Output\_indent i`: symbolic indentation of size `i` | `*)` |
Items produced by symbolic pretty-printers
* **Since** 4.06.0
```
type symbolic_output_buffer
```
The output buffer of a symbolic pretty-printer.
* **Since** 4.06.0
```
val make_symbolic_output_buffer : unit -> symbolic_output_buffer
```
`make_symbolic_output_buffer ()` returns a fresh buffer for symbolic output.
* **Since** 4.06.0
```
val clear_symbolic_output_buffer : symbolic_output_buffer -> unit
```
`clear_symbolic_output_buffer sob` resets buffer `sob`.
* **Since** 4.06.0
```
val get_symbolic_output_buffer : symbolic_output_buffer -> symbolic_output_item list
```
`get_symbolic_output_buffer sob` returns the contents of buffer `sob`.
* **Since** 4.06.0
```
val flush_symbolic_output_buffer : symbolic_output_buffer -> symbolic_output_item list
```
`flush_symbolic_output_buffer sob` returns the contents of buffer `sob` and resets buffer `sob`. `flush_symbolic_output_buffer sob` is equivalent to `let items = get_symbolic_output_buffer sob in
clear_symbolic_output_buffer sob; items`
* **Since** 4.06.0
```
val add_symbolic_output_item : symbolic_output_buffer -> symbolic_output_item -> unit
```
`add_symbolic_output_item sob itm` adds item `itm` to buffer `sob`.
* **Since** 4.06.0
```
val formatter_of_symbolic_output_buffer : symbolic_output_buffer -> formatter
```
`formatter_of_symbolic_output_buffer sob` returns a symbolic formatter that outputs to `symbolic_output_buffer` `sob`.
* **Since** 4.06.0
Convenience formatting functions.
---------------------------------
```
val pp_print_list : ?pp_sep:(formatter -> unit -> unit) -> (formatter -> 'a -> unit) -> formatter -> 'a list -> unit
```
`pp_print_list ?pp_sep pp_v ppf l` prints items of list `l`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`Format.pp_print_cut`](format#VALpp_print_cut). Does nothing on empty lists.
* **Since** 4.02.0
```
val pp_print_seq : ?pp_sep:(formatter -> unit -> unit) -> (formatter -> 'a -> unit) -> formatter -> 'a Seq.t -> unit
```
`pp_print_seq ?pp_sep pp_v ppf s` prints items of sequence `s`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`Format.pp_print_cut`](format#VALpp_print_cut). Does nothing on empty sequences.
This function does not terminate on infinite sequences.
* **Since** 4.12
```
val pp_print_text : formatter -> string -> unit
```
`pp_print_text ppf s` prints `s` with spaces and newlines respectively printed using [`Format.pp_print_space`](format#VALpp_print_space) and [`Format.pp_force_newline`](format#VALpp_force_newline).
* **Since** 4.02.0
```
val pp_print_option : ?none:(formatter -> unit -> unit) -> (formatter -> 'a -> unit) -> formatter -> 'a option -> unit
```
`pp_print_option ?none pp_v ppf o` prints `o` on `ppf` using `pp_v` if `o` is `Some v` and `none` if it is `None`. `none` prints nothing by default.
* **Since** 4.08
```
val pp_print_result : ok:(formatter -> 'a -> unit) -> error:(formatter -> 'e -> unit) -> formatter -> ('a, 'e) result -> unit
```
`pp_print_result ~ok ~error ppf r` prints `r` on `ppf` using `ok` if `r` is `Ok _` and `error` if `r` is `Error _`.
* **Since** 4.08
```
val pp_print_either : left:(formatter -> 'a -> unit) -> right:(formatter -> 'b -> unit) -> formatter -> ('a, 'b) Either.t -> unit
```
`pp_print_either ~left ~right ppf e` prints `e` on `ppf` using `left` if `e` is `Either.Left _` and `right` if `e` is `Either.Right _`.
* **Since** 4.13
Formatted pretty-printing
-------------------------
Module `Format` provides a complete set of `printf` like functions for pretty-printing using format string specifications.
Specific annotations may be added in the format strings to give pretty-printing commands to the pretty-printing engine.
Those annotations are introduced in the format strings using the `@` character. For instance, `@` means a space break, `@,` means a cut, `@[` opens a new box, and `@]` closes the last open box.
```
val fprintf : formatter -> ('a, formatter, unit) format -> 'a
```
`fprintf ff fmt arg1 ... argN` formats the arguments `arg1` to `argN` according to the format string `fmt`, and outputs the resulting string on the formatter `ff`.
The format string `fmt` is a character string which contains three types of objects: plain characters and conversion specifications as specified in the [`Printf`](printf) module, and pretty-printing indications specific to the `Format` module.
The pretty-printing indication characters are introduced by a `@` character, and their meanings are:
* `@[`: open a pretty-printing box. The type and offset of the box may be optionally specified with the following syntax: the `<` character, followed by an optional box type indication, then an optional integer offset, and the closing `>` character. Pretty-printing box type is one of `h`, `v`, `hv`, `b`, or `hov`. '`h`' stands for an 'horizontal' pretty-printing box, '`v`' stands for a 'vertical' pretty-printing box, '`hv`' stands for an 'horizontal/vertical' pretty-printing box, '`b`' stands for an 'horizontal-or-vertical' pretty-printing box demonstrating indentation, '`hov`' stands a simple 'horizontal-or-vertical' pretty-printing box. For instance, `@[<hov 2>` opens an 'horizontal-or-vertical' pretty-printing box with indentation 2 as obtained with `open_hovbox 2`. For more details about pretty-printing boxes, see the various box opening functions `open_*box`.
* `@]`: close the most recently opened pretty-printing box.
* `@,`: output a 'cut' break hint, as with `print_cut ()`.
* `@`: output a 'space' break hint, as with `print_space ()`.
* `@;`: output a 'full' break hint as with `print_break`. The `nspaces` and `offset` parameters of the break hint may be optionally specified with the following syntax: the `<` character, followed by an integer `nspaces` value, then an integer `offset`, and a closing `>` character. If no parameters are provided, the good break defaults to a 'space' break hint.
* `@.`: flush the pretty-printer and split the line, as with `print_newline ()`.
* `@<n>`: print the following item as if it were of length `n`. Hence, `printf "@<0>%s" arg` prints `arg` as a zero length string. If `@<n>` is not followed by a conversion specification, then the following character of the format is printed as if it were of length `n`.
* `@{`: open a semantic tag. The name of the tag may be optionally specified with the following syntax: the `<` character, followed by an optional string specification, and the closing `>` character. The string specification is any character string that does not contain the closing character `'>'`. If omitted, the tag name defaults to the empty string. For more details about semantic tags, see the functions [`Format.open_stag`](format#VALopen_stag) and [`Format.close_stag`](format#VALclose_stag).
* `@}`: close the most recently opened semantic tag.
* `@?`: flush the pretty-printer as with `print_flush ()`. This is equivalent to the conversion `%!`.
* `@\n`: force a newline, as with `force_newline ()`, not the normal way of pretty-printing, you should prefer using break hints inside a vertical pretty-printing box.
Note: To prevent the interpretation of a `@` character as a pretty-printing indication, escape it with a `%` character. Old quotation mode `@@` is deprecated since it is not compatible with formatted input interpretation of character `'@'`.
Example: `printf "@[%s@ %d@]@." "x =" 1` is equivalent to `open_box (); print_string "x ="; print_space ();
print_int 1; close_box (); print_newline ()`. It prints `x = 1` within a pretty-printing 'horizontal-or-vertical' box.
```
val printf : ('a, formatter, unit) format -> 'a
```
Same as `fprintf` above, but output on `get_std_formatter ()`.
It is defined similarly to `fun fmt -> fprintf (get_std_formatter ()) fmt` but delays calling `get_std_formatter` until after the final argument required by the `format` is received. When used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`Format.print_flush`](format#VALprint_flush).
```
val eprintf : ('a, formatter, unit) format -> 'a
```
Same as `fprintf` above, but output on `get_err_formatter ()`.
It is defined similarly to `fun fmt -> fprintf (get_err_formatter ()) fmt` but delays calling `get_err_formatter` until after the final argument required by the `format` is received. When used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`Format.print_flush`](format#VALprint_flush).
```
val sprintf : ('a, unit, string) format -> 'a
```
Same as `printf` above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. Note that the pretty-printer queue is flushed at the end of *each call* to `sprintf`.
In case of multiple and related calls to `sprintf` to output material on a single string, you should consider using `fprintf` with the predefined formatter `str_formatter` and call `flush_str_formatter ()` to get the final result.
Alternatively, you can use `Format.fprintf` with a formatter writing to a buffer of your own: flushing the formatter and the buffer at the end of pretty-printing returns the desired string.
```
val asprintf : ('a, formatter, unit, string) format4 -> 'a
```
Same as `printf` above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. The type of `asprintf` is general enough to interact nicely with `%a` conversions.
* **Since** 4.01.0
```
val dprintf : ('a, formatter, unit, formatter -> unit) format4 -> 'a
```
Same as [`Format.fprintf`](format#VALfprintf), except the formatter is the last argument. `dprintf "..." a b c` is a function of type `formatter -> unit` which can be given to a format specifier `%t`.
This can be used as a replacement for [`Format.asprintf`](format#VALasprintf) to delay formatting decisions. Using the string returned by [`Format.asprintf`](format#VALasprintf) in a formatting context forces formatting decisions to be taken in isolation, and the final string may be created prematurely. [`Format.dprintf`](format#VALdprintf) allows delay of formatting decisions until the final formatting context is known. For example:
```
let t = Format.dprintf "%i@ %i@ %i" 1 2 3 in
...
Format.printf "@[<v>%t@]" t
```
* **Since** 4.08.0
```
val ifprintf : formatter -> ('a, formatter, unit) format -> 'a
```
Same as `fprintf` above, but does not print anything. Useful to ignore some material when conditionally printing.
* **Since** 3.10.0
Formatted Pretty-Printing with continuations.
```
val kfprintf : (formatter -> 'a) -> formatter -> ('b, formatter, unit, 'a) format4 -> 'b
```
Same as `fprintf` above, but instead of returning immediately, passes the formatter to its first argument at the end of printing.
```
val kdprintf : ((formatter -> unit) -> 'a) -> ('b, formatter, unit, 'a) format4 -> 'b
```
Same as [`Format.dprintf`](format#VALdprintf) above, but instead of returning immediately, passes the suspended printer to its first argument at the end of printing.
* **Since** 4.08.0
```
val ikfprintf : (formatter -> 'a) -> formatter -> ('b, formatter, unit, 'a) format4 -> 'b
```
Same as `kfprintf` above, but does not print anything. Useful to ignore some material when conditionally printing.
* **Since** 3.12.0
```
val ksprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b
```
Same as `sprintf` above, but instead of returning the string, passes it to the first argument.
```
val kasprintf : (string -> 'a) -> ('b, formatter, unit, 'a) format4 -> 'b
```
Same as `asprintf` above, but instead of returning the string, passes it to the first argument.
* **Since** 4.03
| programming_docs |
ocaml Module Ephemeron.K2 Module Ephemeron.K2
===================
```
module K2: sig .. end
```
Ephemerons with two keys.
```
type ('k1, 'k2, 'd) t
```
an ephemeron with two keys
```
val make : 'k1 -> 'k2 -> 'd -> ('k1, 'k2, 'd) t
```
Same as [`Ephemeron.K1.make`](ephemeron.k1#VALmake)
```
val query : ('k1, 'k2, 'd) t -> 'k1 -> 'k2 -> 'd option
```
Same as [`Ephemeron.K1.query`](ephemeron.k1#VALquery)
```
module Make: functor (H1 : Hashtbl.HashedType) -> functor (H2 : Hashtbl.HashedType) -> Ephemeron.S with type key = H1.t * H2.t
```
Functor building an implementation of a weak hash table
```
module MakeSeeded: functor (H1 : Hashtbl.SeededHashedType) -> functor (H2 : Hashtbl.SeededHashedType) -> Ephemeron.SeededS with type key = H1.t * H2.t
```
Functor building an implementation of a weak hash table.
```
module Bucket: sig .. end
```
ocaml Module Weak Module Weak
===========
```
module Weak: sig .. end
```
Arrays of weak pointers and hash sets of weak pointers.
Low-level functions
-------------------
```
type 'a t
```
The type of arrays of weak pointers (weak arrays). A weak pointer is a value that the garbage collector may erase whenever the value is not used any more (through normal pointers) by the program. Note that finalisation functions are run before the weak pointers are erased, because the finalisation functions can make values alive again (before 4.03 the finalisation functions were run after).
A weak pointer is said to be full if it points to a value, empty if the value was erased by the GC.
Notes:
* Integers are not allocated and cannot be stored in weak arrays.
* Weak arrays cannot be marshaled using [`output_value`](stdlib#VALoutput_value) nor the functions of the [`Marshal`](marshal) module.
```
val create : int -> 'a t
```
`Weak.create n` returns a new weak array of length `n`. All the pointers are initially empty.
* **Raises** `Invalid_argument` if `n` is not comprised between zero and [`Obj.Ephemeron.max_ephe_length`](obj.ephemeron#VALmax_ephe_length) (limits included).
```
val length : 'a t -> int
```
`Weak.length ar` returns the length (number of elements) of `ar`.
```
val set : 'a t -> int -> 'a option -> unit
```
`Weak.set ar n (Some el)` sets the `n`th cell of `ar` to be a (full) pointer to `el`; `Weak.set ar n None` sets the `n`th cell of `ar` to empty.
* **Raises** `Invalid_argument` if `n` is not in the range 0 to [`Weak.length`](weak#VALlength)`ar - 1`.
```
val get : 'a t -> int -> 'a option
```
`Weak.get ar n` returns None if the `n`th cell of `ar` is empty, `Some x` (where `x` is the value) if it is full.
* **Raises** `Invalid_argument` if `n` is not in the range 0 to [`Weak.length`](weak#VALlength)`ar - 1`.
```
val get_copy : 'a t -> int -> 'a option
```
`Weak.get_copy ar n` returns None if the `n`th cell of `ar` is empty, `Some x` (where `x` is a (shallow) copy of the value) if it is full. In addition to pitfalls with mutable values, the interesting difference with `get` is that `get_copy` does not prevent the incremental GC from erasing the value in its current cycle (`get` may delay the erasure to the next GC cycle).
* **Raises** `Invalid_argument` if `n` is not in the range 0 to [`Weak.length`](weak#VALlength)`ar - 1`. If the element is a custom block it is not copied.
```
val check : 'a t -> int -> bool
```
`Weak.check ar n` returns `true` if the `n`th cell of `ar` is full, `false` if it is empty. Note that even if `Weak.check ar n` returns `true`, a subsequent [`Weak.get`](weak#VALget)`ar n` can return `None`.
* **Raises** `Invalid_argument` if `n` is not in the range 0 to [`Weak.length`](weak#VALlength)`ar - 1`.
```
val fill : 'a t -> int -> int -> 'a option -> unit
```
`Weak.fill ar ofs len el` sets to `el` all pointers of `ar` from `ofs` to `ofs + len - 1`.
* **Raises** `Invalid_argument` if `ofs` and `len` do not designate a valid subarray of `ar`.
```
val blit : 'a t -> int -> 'a t -> int -> int -> unit
```
`Weak.blit ar1 off1 ar2 off2 len` copies `len` weak pointers from `ar1` (starting at `off1`) to `ar2` (starting at `off2`). It works correctly even if `ar1` and `ar2` are the same.
* **Raises** `Invalid_argument` if `off1` and `len` do not designate a valid subarray of `ar1`, or if `off2` and `len` do not designate a valid subarray of `ar2`.
Weak hash sets
--------------
A weak hash set is a hashed set of values. Each value may magically disappear from the set when it is not used by the rest of the program any more. This is normally used to share data structures without inducing memory leaks. Weak hash sets are defined on values from a [`Hashtbl.HashedType`](hashtbl.hashedtype) module; the `equal` relation and `hash` function are taken from that module. We will say that `v` is an instance of `x` if `equal x v` is `true`.
The `equal` relation must be able to work on a shallow copy of the values and give the same result as with the values themselves.
**Unsynchronized accesses**
Unsynchronized accesses to weak hash sets are a programming error. Unsynchronized accesses to a weak hash set may lead to an invalid weak hash set state. Thus, concurrent accesses to weak hash sets must be synchronized (for instance with a [`Mutex.t`](mutex#TYPEt)).
```
module type S = sig .. end
```
The output signature of the functor [`Weak.Make`](weak.make).
```
module Make: functor (H : Hashtbl.HashedType) -> S with type data = H.t
```
Functor building an implementation of the weak hash set structure.
ocaml Module Mutex Module Mutex
============
```
module Mutex: sig .. end
```
Locks for mutual exclusion.
Mutexes (mutual-exclusion locks) are used to implement critical sections and protect shared mutable data structures against concurrent accesses. The typical use is (if `m` is the mutex associated with the data structure `D`):
```
Mutex.lock m;
(* Critical section that operates over D *);
Mutex.unlock m
```
```
type t
```
The type of mutexes.
```
val create : unit -> t
```
Return a new mutex.
```
val lock : t -> unit
```
Lock the given mutex. Only one thread can have the mutex locked at any time. A thread that attempts to lock a mutex already locked by another thread will suspend until the other thread unlocks the mutex.
* **Before 4.12** `Sys\_error` was not raised for recursive locking (platform-dependent behaviour)
* **Raises** `Sys_error` if the mutex is already locked by the thread calling [`Mutex.lock`](mutex#VALlock).
```
val try_lock : t -> bool
```
Same as [`Mutex.lock`](mutex#VALlock), but does not suspend the calling thread if the mutex is already locked: just return `false` immediately in that case. If the mutex is unlocked, lock it and return `true`.
```
val unlock : t -> unit
```
Unlock the given mutex. Other threads suspended trying to lock the mutex will restart. The mutex must have been previously locked by the thread that calls [`Mutex.unlock`](mutex#VALunlock).
* **Before 4.12** `Sys\_error` was not raised when unlocking an unlocked mutex or when unlocking a mutex from a different thread.
* **Raises** `Sys_error` if the mutex is unlocked or was locked by another thread.
ocaml Module StdLabels Module StdLabels
================
```
module StdLabels: sig .. end
```
Standard labeled libraries.
This meta-module provides versions of the [`StdLabels.Array`](stdlabels.array), [`StdLabels.Bytes`](stdlabels.bytes), [`StdLabels.List`](stdlabels.list) and [`StdLabels.String`](stdlabels.string) modules where function arguments are systematically labeled. It is intended to be opened at the top of source files, as shown below.
```
open StdLabels
let to_upper = String.map ~f:Char.uppercase_ascii
let seq len = List.init ~f:(fun i -> i) ~len
let everything = Array.create_matrix ~dimx:42 ~dimy:42 42
```
```
module Array: ArrayLabels
```
```
module Bytes: BytesLabels
```
```
module List: ListLabels
```
```
module String: StringLabels
```
ocaml Module Float.ArrayLabels Module Float.ArrayLabels
========================
```
module ArrayLabels: sig .. end
```
Float arrays with packed representation (labeled functions).
```
type t = floatarray
```
The type of float arrays with packed representation.
* **Since** 4.08.0
```
val length : t -> int
```
Return the length (number of elements) of the given floatarray.
```
val get : t -> int -> float
```
`get a n` returns the element number `n` of floatarray `a`.
* **Raises** `Invalid_argument` if `n` is outside the range 0 to `(length a - 1)`.
```
val set : t -> int -> float -> unit
```
`set a n x` modifies floatarray `a` in place, replacing element number `n` with `x`.
* **Raises** `Invalid_argument` if `n` is outside the range 0 to `(length a - 1)`.
```
val make : int -> float -> t
```
`make n x` returns a fresh floatarray of length `n`, initialized with `x`.
* **Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_floatarray_length`.
```
val create : int -> t
```
`create n` returns a fresh floatarray of length `n`, with uninitialized data.
* **Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_floatarray_length`.
```
val init : int -> f:(int -> float) -> t
```
`init n ~f` returns a fresh floatarray of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n ~f` tabulates the results of `f` applied to the integers `0` to `n-1`.
* **Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_floatarray_length`.
```
val append : t -> t -> t
```
`append v1 v2` returns a fresh floatarray containing the concatenation of the floatarrays `v1` and `v2`.
* **Raises** `Invalid_argument` if `length v1 + length v2 > Sys.max_floatarray_length`.
```
val concat : t list -> t
```
Same as [`Float.ArrayLabels.append`](float.arraylabels#VALappend), but concatenates a list of floatarrays.
```
val sub : t -> pos:int -> len:int -> t
```
`sub a ~pos ~len` returns a fresh floatarray of length `len`, containing the elements number `pos` to `pos + len - 1` of floatarray `a`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid subarray of `a`; that is, if `pos < 0`, or `len < 0`, or `pos + len > length a`.
```
val copy : t -> t
```
`copy a` returns a copy of `a`, that is, a fresh floatarray containing the same elements as `a`.
```
val fill : t -> pos:int -> len:int -> float -> unit
```
`fill a ~pos ~len x` modifies the floatarray `a` in place, storing `x` in elements number `pos` to `pos + len - 1`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid subarray of `a`.
```
val blit : src:t -> src_pos:int -> dst:t -> dst_pos:int -> len:int -> unit
```
`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` elements from floatarray `src`, starting at element number `src_pos`, to floatarray `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same floatarray, and the source and destination chunks overlap.
* **Raises** `Invalid_argument` if `src_pos` and `len` do not designate a valid subarray of `src`, or if `dst_pos` and `len` do not designate a valid subarray of `dst`.
```
val to_list : t -> float list
```
`to_list a` returns the list of all the elements of `a`.
```
val of_list : float list -> t
```
`of_list l` returns a fresh floatarray containing the elements of `l`.
* **Raises** `Invalid_argument` if the length of `l` is greater than `Sys.max_floatarray_length`.
### Iterators
```
val iter : f:(float -> unit) -> t -> unit
```
`iter ~f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`.
```
val iteri : f:(int -> float -> unit) -> t -> unit
```
Same as [`Float.ArrayLabels.iter`](float.arraylabels#VALiter), but the function is applied with the index of the element as first argument, and the element itself as second argument.
```
val map : f:(float -> float) -> t -> t
```
`map ~f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`.
```
val mapi : f:(int -> float -> float) -> t -> t
```
Same as [`Float.ArrayLabels.map`](float.arraylabels#VALmap), but the function is applied to the index of the element as first argument, and the element itself as second argument.
```
val fold_left : f:('a -> float -> 'a) -> init:'a -> t -> 'a
```
`fold_left ~f x ~init` computes `f (... (f (f x init.(0)) init.(1)) ...) init.(n-1)`, where `n` is the length of the floatarray `init`.
```
val fold_right : f:(float -> 'a -> 'a) -> t -> init:'a -> 'a
```
`fold_right f a init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the floatarray `a`.
### Iterators on two arrays
```
val iter2 : f:(float -> float -> unit) -> t -> t -> unit
```
`Array.iter2 ~f a b` applies function `f` to all the elements of `a` and `b`.
* **Raises** `Invalid_argument` if the floatarrays are not the same size.
```
val map2 : f:(float -> float -> float) -> t -> t -> t
```
`map2 ~f a b` applies function `f` to all the elements of `a` and `b`, and builds a floatarray with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`.
* **Raises** `Invalid_argument` if the floatarrays are not the same size.
### Array scanning
```
val for_all : f:(float -> bool) -> t -> bool
```
`for_all ~f [|a1; ...; an|]` checks if all elements of the floatarray satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`.
```
val exists : f:(float -> bool) -> t -> bool
```
`exists f [|a1; ...; an|]` checks if at least one element of the floatarray satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`.
```
val mem : float -> set:t -> bool
```
`mem a ~set` is true if and only if there is an element of `set` that is structurally equal to `a`, i.e. there is an `x` in `set` such that `compare a x = 0`.
```
val mem_ieee : float -> set:t -> bool
```
Same as [`Float.ArrayLabels.mem`](float.arraylabels#VALmem), but uses IEEE equality instead of structural equality.
### Sorting
```
val sort : cmp:(float -> float -> int) -> t -> unit
```
Sort a floatarray in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`compare`](stdlib#VALcompare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant stack space.
Specification of the comparison function: Let `a` be the floatarray and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` :
* `cmp x y` > 0 if and only if `cmp y x` < 0
* if `cmp x y` >= 0 and `cmp y z` >= 0 then `cmp x z` >= 0
When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` :
* `cmp a.(i) a.(j)` >= 0 if and only if i >= j
```
val stable_sort : cmp:(float -> float -> int) -> t -> unit
```
Same as [`Float.ArrayLabels.sort`](float.arraylabels#VALsort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space.
The current implementation uses Merge Sort. It uses a temporary floatarray of length `n/2`, where `n` is the length of the floatarray. It is usually faster than the current implementation of [`Float.ArrayLabels.sort`](float.arraylabels#VALsort).
```
val fast_sort : cmp:(float -> float -> int) -> t -> unit
```
Same as [`Float.ArrayLabels.sort`](float.arraylabels#VALsort) or [`Float.ArrayLabels.stable_sort`](float.arraylabels#VALstable_sort), whichever is faster on typical input.
### Float arrays and Sequences
```
val to_seq : t -> float Seq.t
```
Iterate on the floatarray, in increasing order. Modifications of the floatarray during iteration will be reflected in the sequence.
```
val to_seqi : t -> (int * float) Seq.t
```
Iterate on the floatarray, in increasing order, yielding indices along elements. Modifications of the floatarray during iteration will be reflected in the sequence.
```
val of_seq : float Seq.t -> t
```
Create an array from the generator.
```
val map_to_array : f:(float -> 'a) -> t -> 'a array
```
`map_to_array ~f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`.
```
val map_from_array : f:('a -> float) -> 'a array -> t
```
`map_from_array ~f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`.
Arrays and concurrency safety
-----------------------------
Care must be taken when concurrently accessing float arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.
### Atomicity
Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays.
For example, consider the following program:
```
let size = 100_000_000
let a = Float.ArrayLabels.make size 1.
let update a f () =
Float.ArrayLabels.iteri ~f:(fun i x -> Float.Array.set a i (f x)) a
let d1 = Domain.spawn (update a (fun x -> x +. 1.))
let d2 = Domain.spawn (update a (fun x -> 2. *. x +. 1.))
let () = Domain.join d1; Domain.join d2
```
After executing this code, each field of the float array `a` is either `2.`, `3.`, `4.` or `5.`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](mutex#TYPEt)).
### Data races
If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.
A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions.
### Tearing
Float arrays have two supplementary caveats in the presence of data races.
First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution.
For instance, at the end of
```
let zeros = Float.Array.make size 0.
let max_floats = Float.Array.make size Float.max_float
let res = Float.Array.copy zeros
let d1 = Domain.spawn (fun () -> Float.Array.blit zeros 0 res 0 size)
let d2 = Domain.spawn (fun () -> Float.Array.blit max_floats 0 res 0 size)
let () = Domain.join d1; Domain.join d2
```
the `res` float array might contain values that are neither `0.` nor `max_float`.
Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation.
| programming_docs |
ocaml Format_tutorial Format\_tutorial
================
Using the Format module
=======================
Principles
----------
Line breaking is based on three concepts:
* **boxes** : a box is a logical pretty-printing unit, which defines a behaviour of the pretty-printing engine to display the material inside the box.
* **break hints**: a break hint is a directive to the pretty-printing engine that proposes to break the line here, if it is necessary to properly print the rest of the material. Otherwise, the pretty-printing engine never break lines (except "in case of emergency" to avoid very bad output). In short, a break hint tells the pretty printer that a line break here may be appropriate.
* **indentation rules**: When a line break occurs, the pretty-printing engines fixes the indentation (or amount of leading spaces) of the new line using indentation rules, as follows:
+ A box can state the extra indentation of every new line opened in its scope. This extra indentation is named **box breaking indentation**.
+ A break hint can also set the additional indentation of the new line it may fire. This extra indentation is named **hint breaking indentation**.
+ If break hint `bh` fires a new line within box `b`, then the indentation of the new line is simply the sum of: the current indentation of box `b` + the additional box breaking indentation, as defined by box `b` + the additional hint breaking indentation, as defined by break hint `bh`.
Boxes
-----
There are 4 types of boxes. (The most often used is the "hov" box type, so skip the rest at first reading).
* **horizontal box** (*h* box, as obtained by the [`Format.open_hbox`](format#VALopen_hbox) procedure): within this box, break hints do not lead to line breaks.
* **vertical box** (*v* box, as obtained by the [`Format.open_vbox`](format#VALopen_vbox) procedure): within this box, every break hint lead to a new line.
* **vertical/horizontal box** (*hv* box, as obtained by the [`Format.open_hvbox`](format#VALopen_hvbox) procedure): if it is possible, the entire box is written on a single line; otherwise, every break hint within the box leads to a new line.
* **vertical or horizontal box** (*hov* box, as obtained by the [`Format.open_box`](format#VALopen_box) or [`Format.open_hovbox`](format#VALopen_hovbox) procedures): within this box, break hints are used to cut the line when there is no more room on the line. There are two kinds of "hov" boxes, you can find the details below. In first approximation, let me consider these two kinds of "hov" boxes as equivalent and obtained by calling the [`Format.open_box`](format#VALopen_box) procedure.
Let me give an example. Suppose we can write 10 chars before the right margin (that indicates no more room). We represent any char as a `-` sign; characters `[` and `]` indicates the opening and closing of a box and `b` stands for a break hint given to the pretty-printing engine.
The output "--b--b--" is displayed like this (the `b` symbol stands for the value of the break that is explained below):
Within a "h" box:
```
--b--b--
```
Within a "v" box:
```
--b
--b
--
```
Within a "hv" box:
If there is enough room to print the box on the line:
```
--b--b--
```
But "---b---b---" that cannot fit on the line is written
```
---b
---b
---
```
Within a "hov" box:
If there is enough room to print the box on the line:
```
--b--b--
```
But if "---b---b---" cannot fit on the line, it is written as
```
---b---b
---
```
The first break hint does not lead to a new line, since there is enough room on the line. The second one leads to a new line since there is no more room to print the material following it. If the room left on the line were even shorter, the first break hint may lead to a new line and "---b---b---" is written as:
```
---b
---b
---
```
Printing spaces
---------------
Break hints are also used to output spaces (if the line is not split when the break is encountered, otherwise the new line indicates properly the separation between printing items). You output a break hint using `print_break sp indent`, and this sp integer is used to print "sp" spaces. Thus `print_break sp ...` may be thought as: print `sp` spaces or output a new line.
For instance, if b is `break 1 0` in the output "--b--b--", we get
within a "h" box:
```
-- -- --
```
within a "v" box:
```
--
--
--
```
within a "hv" box:
```
-- -- --
```
or, according to the remaining room on the line:
```
--
--
--
```
and similarly for "hov" boxes.
Generally speaking, a printing routine using "format", should not directly output white spaces: the routine should use break hints instead. (For instance `print_space ()` that is a convenient abbreviation for `print_break 1 0` and outputs a single space or break the line.)
Indentation of new lines
------------------------
The user gets 2 ways to fix the indentation of new lines:
**When defining the box**: when you open a box, you can fix the indentation added to each new line opened within that box.
For instance: `open_hovbox 1` opens a "hov" box with new lines indented 1 more than the initial indentation of the box. With output "---[--b--b--b--", we get:
```
---[--b--b
--b--
```
with open\_hovbox 2, we get
```
---[--b--b
--b--
```
Note: the [ sign in the display is not visible on the screen, it is just there to materialise the aperture of the pretty-printing box. Last "screen" stands for:
```
-----b--b
--b--
```
**When defining the break that makes the new line**. As said above, you output a break hint using `print_break sp indent`. The `indent` integer is used to fix the additional indentation of the new line. Namely, it is added to the default indentation offset of the box where the break occurs.
For instance, if [ stands for the opening of a "hov" box with 1 as extra indentation (as obtained by `open_hovbox 1`), and b is `print_break 1 2`, then from output "---[--b--b--b--", we get:
```
---[-- --
--
--
```
Refinement on "hov" boxes
-------------------------
The "hov" box type is refined into two categories.
* **the vertical or horizontal *packing* box** (as obtained by the [`Format.open_hovbox`](format#VALopen_hovbox) procedure): break hints are used to cut the line when there is no more room on the line; no new line occurs if there is enough room on the line.
* **vertical or horizontal *structural* box** (as obtained by the [`Format.open_box`](format#VALopen_box) procedure): similar to the "hov" packing box, the break hints are used to cut the line when there is no more room on the line; in addition, break hints that can show the box structure lead to new lines even if there is enough room on the current line.
The difference between a packing and a structural "hov" box is shown by a routine that closes boxes and parentheses at the end of printing: with packing boxes, the closure of boxes and parentheses do not lead to new lines if there is enough room on the line, whereas with structural boxes each break hint will lead to a new line. For instance, when printing "[(---[(----[(---b)]b)]b)]", where "b" is a break hint without extra indentation (`print_cut ()`). If "[" means opening of a packing "hov" box ([`Format.open_hovbox`](format#VALopen_hovbox)), "[(---[(----[(---b)]b)]b)]" is printed as follows:
```
(---
(----
(---)))
```
If we replace the packing boxes by structural boxes ([`Format.open_box`](format#VALopen_box)), each break hint that precedes a closing parenthesis can show the boxes structure, if it leads to a new line; hence "[(---[(----[(---b)]b)]b)]" is printed like this:
```
(---
(----
(---
)
)
)
```
Practical advice
----------------
When writing a pretty-printing routine, follow these simple rules:
1. Boxes must be opened and closed consistently (`open_*` and [`Format.close_box`](format#VALclose_box) must be nested like parentheses).
2. Never hesitate to open a box.
3. Output many break hints, otherwise the pretty-printer is in a bad situation where it tries to do its best, which is always "worse than your bad".
4. Do not try to force spacing using explicit spaces in the character strings. For each space you want in the output emit a break hint (`print_space ()`), unless you explicitly don't want the line to be broken here. For instance, imagine you want to pretty print an OCaml definition, more precisely a `let rec
ident = expression` value definition. You will probably treat the first three spaces as "unbreakable spaces" and write them directly in the string constants for keywords, and print `"let rec"` before the identifier, and similarly write `=` to get an unbreakable space after the identifier; in contrast, the space after the `=` sign is certainly a break hint, since breaking the line after `=` is a usual (and elegant) way to indent the expression part of a definition. In short, it is often necessary to print unbreakable spaces; however, most of the time a space should be considered a break hint.
5. Do not try to force new lines, let the pretty-printer do it for you: that's its only job. In particular, do not use [`Format.force_newline`](format#VALforce_newline): this procedure effectively leads to a newline, but it also as the unfortunate side effect to partially reinitialise the pretty-printing engine, so that the rest of the printing material is noticeably messed up.
6. Never put newline characters directly in the strings to be printed: pretty printing engine will consider this newline character as any other character written on the current line and this will completely mess up the output. Instead of new line characters use line break hints: if those break hints must always result in new lines, it just means that the surrounding box must be a vertical box!
7. End your main program by a `print_newline ()` call, that flushes the pretty-printer tables (hence the output). (Note that the top-level loop of the interactive system does it as well, just before a new input.)
Printing to stdout: using printf
--------------------------------
The format module provides a general printing facility "a la" printf. In addition to the usual conversion facility provided by printf, you can write pretty-printing indications directly inside the format string (opening and closing boxes, indicating breaking hints, etc).
Pretty-printing annotations are introduced by the `@` symbol, directly into the string format. Almost any function of the `Format` module can be called from within a `printf` format string. For instance
* "`@[`" open a box (open\_box 0). You may precise the type as an extra argument. For instance `@[<hov n>` is equivalent to `open_hovbox n`.
* "`@]`" close a box (`close_box ()`).
* "`@`" output a breakable space (`print_space ()`).
* "`@,`" output a break hint (`print_cut ()`).
* "`@;<n m>`" emit a "full" break hint (`print_break n m`).
* "`@.`" end the pretty-printing, closing all the boxes still opened (`print_newline ()`).
For instance
```
printf "@[<1>%s@ =@ %d@ %s@]@." "Prix TTC" 100 "Euros";;
Prix TTC = 100 Euros
- : unit = ()
```
A concrete example
-------------------
Let me give a full example: the shortest non trivial example you could imagine, that is the lambda calculus :)
Thus the problem is to pretty-print the values of a concrete data type that models a language of expressions that defines functions and their applications to arguments.
First, I give the abstract syntax of lambda-terms:
```
type lambda =
| Lambda of string * lambda
| Var of string
| Apply of lambda * lambda
;;
```
I use the format library to print the lambda-terms:
```
open Format;;
let ident = print_string;;
let kwd = print_string;;
val ident : string -> unit = <fun>
val kwd : string -> unit = <fun>
let rec print_exp0 = function
| Var s -> ident s
| lam -> open_hovbox 1; kwd "("; print_lambda lam; kwd ")"; close_box ()
and print_app = function
| e -> open_hovbox 2; print_other_applications e; close_box ()
and print_other_applications f =
match f with
| Apply (f, arg) -> print_app f; print_space (); print_exp0 arg
| f -> print_exp0 f
and print_lambda = function
| Lambda (s, lam) ->
open_hovbox 1;
kwd "\\"; ident s; kwd "."; print_space(); print_lambda lam;
close_box()
| e -> print_app e;;
val print_app : lambda -> unit = <fun>
val print_other_applications : lambda -> unit = <fun>
val print_lambda : lambda -> unit = <fun>
```
### Most general pretty-printing: using fprintf
We use the `fprintf` function to write the most versatile version of the pretty-printing functions for lambda-terms. Now, the functions get an extra argument, namely a pretty-printing formatter (the ppf argument) where printing will occur. This way the printing routines are more general, since they can print on any formatter defined in the program (either printing to a file, or to `stdout`, to `stderr`, or even to a string). Furthermore, the pretty-printing functions are now compositional, since they may be used in conjunction with the special `%a` conversion, that prints a `fprintf` argument with a user's supplied function (these user's supplied functions also have a formatter as first argument).
Using `fprintf`, the lambda-terms printing routines can be written as follows:
```
open Format;;
let ident ppf s = fprintf ppf "%s" s;;
let kwd ppf s = fprintf ppf "%s" s;;
val ident : Format.formatter -> string -> unit
val kwd : Format.formatter -> string -> unit
let rec pr_exp0 ppf = function
| Var s -> fprintf ppf "%a" ident s
| lam -> fprintf ppf "@[<1>(%a)@]" pr_lambda lam
and pr_app ppf = function
| e -> fprintf ppf "@[<2>%a@]" pr_other_applications e
and pr_other_applications ppf f =
match f with
| Apply (f, arg) -> fprintf ppf "%a@ %a" pr_app f pr_exp0 arg
| f -> pr_exp0 ppf f
and pr_lambda ppf = function
| Lambda (s, lam) ->
fprintf ppf "@[<1>%a%a%a@ %a@]" kwd "\\" ident s kwd "." pr_lambda lam
| e -> pr_app ppf e
;;
val pr_app : Format.formatter -> lambda -> unit
val pr_other_applications : Format.formatter -> lambda -> unit
val pr_lambda : Format.formatter -> lambda -> unit
```
Given those general printing routines, procedures to print to `stdout` or `stderr` is just a matter of partial application:
```
let print_lambda = pr_lambda std_formatter;;
let eprint_lambda = pr_lambda err_formatter;;
val print_lambda : lambda -> unit
val eprint_lambda : lambda -> unit
```
ocaml Module Unix Module Unix
===========
```
module Unix: sig .. end
```
Interface to the Unix system.
To use the labeled version of this module, add `module Unix``=``UnixLabels` in your implementation.
Note: all the functions of this module (except [`Unix.error_message`](unix#VALerror_message) and [`Unix.handle_unix_error`](unix#VALhandle_unix_error)) are liable to raise the [`Unix.Unix\_error`](unix#EXCEPTIONUnix_error) exception whenever the underlying system call signals an error.
Error report
------------
```
type error =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `E2BIG` | `(*` | Argument list too long | `*)` |
| `|` | `EACCES` | `(*` | Permission denied | `*)` |
| `|` | `EAGAIN` | `(*` | Resource temporarily unavailable; try again | `*)` |
| `|` | `EBADF` | `(*` | Bad file descriptor | `*)` |
| `|` | `EBUSY` | `(*` | Resource unavailable | `*)` |
| `|` | `ECHILD` | `(*` | No child process | `*)` |
| `|` | `EDEADLK` | `(*` | Resource deadlock would occur | `*)` |
| `|` | `EDOM` | `(*` | Domain error for math functions, etc. | `*)` |
| `|` | `EEXIST` | `(*` | File exists | `*)` |
| `|` | `EFAULT` | `(*` | Bad address | `*)` |
| `|` | `EFBIG` | `(*` | File too large | `*)` |
| `|` | `EINTR` | `(*` | Function interrupted by signal | `*)` |
| `|` | `EINVAL` | `(*` | Invalid argument | `*)` |
| `|` | `EIO` | `(*` | Hardware I/O error | `*)` |
| `|` | `EISDIR` | `(*` | Is a directory | `*)` |
| `|` | `EMFILE` | `(*` | Too many open files by the process | `*)` |
| `|` | `EMLINK` | `(*` | Too many links | `*)` |
| `|` | `ENAMETOOLONG` | `(*` | Filename too long | `*)` |
| `|` | `ENFILE` | `(*` | Too many open files in the system | `*)` |
| `|` | `ENODEV` | `(*` | No such device | `*)` |
| `|` | `ENOENT` | `(*` | No such file or directory | `*)` |
| `|` | `ENOEXEC` | `(*` | Not an executable file | `*)` |
| `|` | `ENOLCK` | `(*` | No locks available | `*)` |
| `|` | `ENOMEM` | `(*` | Not enough memory | `*)` |
| `|` | `ENOSPC` | `(*` | No space left on device | `*)` |
| `|` | `ENOSYS` | `(*` | Function not supported | `*)` |
| `|` | `ENOTDIR` | `(*` | Not a directory | `*)` |
| `|` | `ENOTEMPTY` | `(*` | Directory not empty | `*)` |
| `|` | `ENOTTY` | `(*` | Inappropriate I/O control operation | `*)` |
| `|` | `ENXIO` | `(*` | No such device or address | `*)` |
| `|` | `EPERM` | `(*` | Operation not permitted | `*)` |
| `|` | `EPIPE` | `(*` | Broken pipe | `*)` |
| `|` | `ERANGE` | `(*` | Result too large | `*)` |
| `|` | `EROFS` | `(*` | Read-only file system | `*)` |
| `|` | `ESPIPE` | `(*` | Invalid seek e.g. on a pipe | `*)` |
| `|` | `ESRCH` | `(*` | No such process | `*)` |
| `|` | `EXDEV` | `(*` | Invalid link | `*)` |
| `|` | `EWOULDBLOCK` | `(*` | Operation would block | `*)` |
| `|` | `EINPROGRESS` | `(*` | Operation now in progress | `*)` |
| `|` | `EALREADY` | `(*` | Operation already in progress | `*)` |
| `|` | `ENOTSOCK` | `(*` | Socket operation on non-socket | `*)` |
| `|` | `EDESTADDRREQ` | `(*` | Destination address required | `*)` |
| `|` | `EMSGSIZE` | `(*` | Message too long | `*)` |
| `|` | `EPROTOTYPE` | `(*` | Protocol wrong type for socket | `*)` |
| `|` | `ENOPROTOOPT` | `(*` | Protocol not available | `*)` |
| `|` | `EPROTONOSUPPORT` | `(*` | Protocol not supported | `*)` |
| `|` | `ESOCKTNOSUPPORT` | `(*` | Socket type not supported | `*)` |
| `|` | `EOPNOTSUPP` | `(*` | Operation not supported on socket | `*)` |
| `|` | `EPFNOSUPPORT` | `(*` | Protocol family not supported | `*)` |
| `|` | `EAFNOSUPPORT` | `(*` | Address family not supported by protocol family | `*)` |
| `|` | `EADDRINUSE` | `(*` | Address already in use | `*)` |
| `|` | `EADDRNOTAVAIL` | `(*` | Can't assign requested address | `*)` |
| `|` | `ENETDOWN` | `(*` | Network is down | `*)` |
| `|` | `ENETUNREACH` | `(*` | Network is unreachable | `*)` |
| `|` | `ENETRESET` | `(*` | Network dropped connection on reset | `*)` |
| `|` | `ECONNABORTED` | `(*` | Software caused connection abort | `*)` |
| `|` | `ECONNRESET` | `(*` | Connection reset by peer | `*)` |
| `|` | `ENOBUFS` | `(*` | No buffer space available | `*)` |
| `|` | `EISCONN` | `(*` | Socket is already connected | `*)` |
| `|` | `ENOTCONN` | `(*` | Socket is not connected | `*)` |
| `|` | `ESHUTDOWN` | `(*` | Can't send after socket shutdown | `*)` |
| `|` | `ETOOMANYREFS` | `(*` | Too many references: can't splice | `*)` |
| `|` | `ETIMEDOUT` | `(*` | Connection timed out | `*)` |
| `|` | `ECONNREFUSED` | `(*` | Connection refused | `*)` |
| `|` | `EHOSTDOWN` | `(*` | Host is down | `*)` |
| `|` | `EHOSTUNREACH` | `(*` | No route to host | `*)` |
| `|` | `ELOOP` | `(*` | Too many levels of symbolic links | `*)` |
| `|` | `EOVERFLOW` | `(*` | File size or position not representable | `*)` |
| `|` | `EUNKNOWNERR of `int`` | `(*` | Unknown error | `*)` |
The type of error codes. Errors defined in the POSIX standard and additional errors from UNIX98 and BSD. All other errors are mapped to EUNKNOWNERR.
```
exception Unix_error of error * string * string
```
Raised by the system calls below when an error is encountered. The first component is the error code; the second component is the function name; the third component is the string parameter to the function, if it has one, or the empty string otherwise.
[`UnixLabels.Unix\_error`](unixlabels#EXCEPTIONUnix_error) and [`Unix.Unix\_error`](unix#EXCEPTIONUnix_error) are the same, and catching one will catch the other.
```
val error_message : error -> string
```
Return a string describing the given error code.
```
val handle_unix_error : ('a -> 'b) -> 'a -> 'b
```
`handle_unix_error f x` applies `f` to `x` and returns the result. If the exception [`Unix.Unix\_error`](unix#EXCEPTIONUnix_error) is raised, it prints a message describing the error and exits with code 2.
Access to the process environment
---------------------------------
```
val environment : unit -> string array
```
Return the process environment, as an array of strings with the format ``variable=value''. The returned array is empty if the process has special privileges.
```
val unsafe_environment : unit -> string array
```
Return the process environment, as an array of strings with the format ``variable=value''. Unlike [`Unix.environment`](unix#VALenvironment), this function returns a populated array even if the process has special privileges. See the documentation for [`Unix.unsafe_getenv`](unix#VALunsafe_getenv) for more details.
* **Since** 4.06.0 (4.12.0 in UnixLabels)
```
val getenv : string -> string
```
Return the value associated to a variable in the process environment, unless the process has special privileges.
* **Raises** `Not_found` if the variable is unbound or the process has special privileges. This function is identical to [`Sys.getenv`](sys#VALgetenv).
```
val unsafe_getenv : string -> string
```
Return the value associated to a variable in the process environment.
Unlike [`Unix.getenv`](unix#VALgetenv), this function returns the value even if the process has special privileges. It is considered unsafe because the programmer of a setuid or setgid program must be careful to avoid using maliciously crafted environment variables in the search path for executables, the locations for temporary files or logs, and the like.
* **Since** 4.06.0
* **Raises** `Not_found` if the variable is unbound.
```
val putenv : string -> string -> unit
```
`putenv name value` sets the value associated to a variable in the process environment. `name` is the name of the environment variable, and `value` its new associated value.
Process handling
----------------
```
type process_status =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `WEXITED of `int`` | `(*` | The process terminated normally by `exit`; the argument is the return code. | `*)` |
| `|` | `WSIGNALED of `int`` | `(*` | The process was killed by a signal; the argument is the signal number. | `*)` |
| `|` | `WSTOPPED of `int`` | `(*` | The process was stopped by a signal; the argument is the signal number. | `*)` |
The termination status of a process. See module [`Sys`](sys) for the definitions of the standard signal numbers. Note that they are not the numbers used by the OS.
```
type wait_flag =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `WNOHANG` | `(*` | Do not block if no child has died yet, but immediately return with a pid equal to 0. | `*)` |
| `|` | `WUNTRACED` | `(*` | Report also the children that receive stop signals. | `*)` |
Flags for [`Unix.waitpid`](unix#VALwaitpid).
```
val execv : string -> string array -> 'a
```
`execv prog args` execute the program in file `prog`, with the arguments `args`, and the current process environment. These `execv*` functions never return: on success, the current program is replaced by the new one.
* **Raises** `Unix_error` on failure
```
val execve : string -> string array -> string array -> 'a
```
Same as [`Unix.execv`](unix#VALexecv), except that the third argument provides the environment to the program executed.
```
val execvp : string -> string array -> 'a
```
Same as [`Unix.execv`](unix#VALexecv), except that the program is searched in the path.
```
val execvpe : string -> string array -> string array -> 'a
```
Same as [`Unix.execve`](unix#VALexecve), except that the program is searched in the path.
```
val fork : unit -> int
```
Fork a new process. The returned integer is 0 for the child process, the pid of the child process for the parent process.
* **Raises** `Invalid_argument` on Windows. Use [`Unix.create_process`](unix#VALcreate_process) or threads instead.
```
val wait : unit -> int * process_status
```
Wait until one of the children processes die, and return its pid and termination status.
* **Raises** `Invalid_argument` on Windows. Use [`Unix.waitpid`](unix#VALwaitpid) instead.
```
val waitpid : wait_flag list -> int -> int * process_status
```
Same as [`Unix.wait`](unix#VALwait), but waits for the child process whose pid is given. A pid of `-1` means wait for any child. A pid of `0` means wait for any child in the same process group as the current process. Negative pid arguments represent process groups. The list of options indicates whether `waitpid` should return immediately without waiting, and whether it should report stopped children.
On Windows: can only wait for a given PID, not any child process.
```
val system : string -> process_status
```
Execute the given command, wait until it terminates, and return its termination status. The string is interpreted by the shell `/bin/sh` (or the command interpreter `cmd.exe` on Windows) and therefore can contain redirections, quotes, variables, etc. To properly quote whitespace and shell special characters occurring in file names or command arguments, the use of [`Filename.quote_command`](filename#VALquote_command) is recommended. The result `WEXITED 127` indicates that the shell couldn't be executed.
```
val _exit : int -> 'a
```
Terminate the calling process immediately, returning the given status code to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. Unlike [`exit`](stdlib#VALexit), [`Unix._exit`](unix#VAL_exit) performs no finalization whatsoever: functions registered with [`at_exit`](stdlib#VALat_exit) are not called, input/output channels are not flushed, and the C run-time system is not finalized either.
The typical use of [`Unix._exit`](unix#VAL_exit) is after a [`Unix.fork`](unix#VALfork) operation, when the child process runs into a fatal error and must exit. In this case, it is preferable to not perform any finalization action in the child process, as these actions could interfere with similar actions performed by the parent process. For example, output channels should not be flushed by the child process, as the parent process may flush them again later, resulting in duplicate output.
* **Since** 4.12.0
```
val getpid : unit -> int
```
Return the pid of the process.
```
val getppid : unit -> int
```
Return the pid of the parent process.
* **Raises** `Invalid_argument` on Windows (because it is meaningless)
```
val nice : int -> int
```
Change the process priority. The integer argument is added to the ``nice'' value. (Higher values of the ``nice'' value mean lower priorities.) Return the new nice value.
* **Raises** `Invalid_argument` on Windows
Basic file input/output
-----------------------
```
type file_descr
```
The abstract type of file descriptors.
```
val stdin : file_descr
```
File descriptor for standard input.
```
val stdout : file_descr
```
File descriptor for standard output.
```
val stderr : file_descr
```
File descriptor for standard error.
```
type open_flag =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `O\_RDONLY` | `(*` | Open for reading | `*)` |
| `|` | `O\_WRONLY` | `(*` | Open for writing | `*)` |
| `|` | `O\_RDWR` | `(*` | Open for reading and writing | `*)` |
| `|` | `O\_NONBLOCK` | `(*` | Open in non-blocking mode | `*)` |
| `|` | `O\_APPEND` | `(*` | Open for append | `*)` |
| `|` | `O\_CREAT` | `(*` | Create if nonexistent | `*)` |
| `|` | `O\_TRUNC` | `(*` | Truncate to 0 length if existing | `*)` |
| `|` | `O\_EXCL` | `(*` | Fail if existing | `*)` |
| `|` | `O\_NOCTTY` | `(*` | Don't make this dev a controlling tty | `*)` |
| `|` | `O\_DSYNC` | `(*` | Writes complete as `Synchronised I/O data integrity completion' | `*)` |
| `|` | `O\_SYNC` | `(*` | Writes complete as `Synchronised I/O file integrity completion' | `*)` |
| `|` | `O\_RSYNC` | `(*` | Reads complete as writes (depending on O\_SYNC/O\_DSYNC) | `*)` |
| `|` | `O\_SHARE\_DELETE` | `(*` | Windows only: allow the file to be deleted while still open | `*)` |
| `|` | `O\_CLOEXEC` | `(*` | Set the close-on-exec flag on the descriptor returned by [`Unix.openfile`](unix#VALopenfile). See [`Unix.set_close_on_exec`](unix#VALset_close_on_exec) for more information. | `*)` |
| `|` | `O\_KEEPEXEC` | `(*` | Clear the close-on-exec flag. This is currently the default. | `*)` |
The flags to [`Unix.openfile`](unix#VALopenfile).
```
type file_perm = int
```
The type of file access rights, e.g. `0o640` is read and write for user, read for group, none for others
```
val openfile : string -> open_flag list -> file_perm -> file_descr
```
Open the named file with the given flags. Third argument is the permissions to give to the file if it is created (see [`Unix.umask`](unix#VALumask)). Return a file descriptor on the named file.
```
val close : file_descr -> unit
```
Close a file descriptor.
```
val fsync : file_descr -> unit
```
Flush file buffers to disk.
* **Since** 4.08.0 (4.12.0 in UnixLabels)
```
val read : file_descr -> bytes -> int -> int -> int
```
`read fd buf pos len` reads `len` bytes from descriptor `fd`, storing them in byte sequence `buf`, starting at position `pos` in `buf`. Return the number of bytes actually read.
```
val write : file_descr -> bytes -> int -> int -> int
```
`write fd buf pos len` writes `len` bytes to descriptor `fd`, taking them from byte sequence `buf`, starting at position `pos` in `buff`. Return the number of bytes actually written. `write` repeats the writing operation until all bytes have been written or an error occurs.
```
val single_write : file_descr -> bytes -> int -> int -> int
```
Same as [`Unix.write`](unix#VALwrite), but attempts to write only once. Thus, if an error occurs, `single_write` guarantees that no data has been written.
```
val write_substring : file_descr -> string -> int -> int -> int
```
Same as [`Unix.write`](unix#VALwrite), but take the data from a string instead of a byte sequence.
* **Since** 4.02.0
```
val single_write_substring : file_descr -> string -> int -> int -> int
```
Same as [`Unix.single_write`](unix#VALsingle_write), but take the data from a string instead of a byte sequence.
* **Since** 4.02.0
Interfacing with the standard input/output library
--------------------------------------------------
```
val in_channel_of_descr : file_descr -> in_channel
```
Create an input channel reading from the given descriptor. The channel is initially in binary mode; use `set_binary_mode_in ic false` if text mode is desired. Text mode is supported only if the descriptor refers to a file or pipe, but is not supported if it refers to a socket.
On Windows: [`set_binary_mode_in`](stdlib#VALset_binary_mode_in) always fails on channels created with this function.
Beware that input channels are buffered, so more characters may have been read from the descriptor than those accessed using channel functions. Channels also keep a copy of the current position in the file.
Closing the channel `ic` returned by `in_channel_of_descr fd` using `close_in ic` also closes the underlying descriptor `fd`. It is incorrect to close both the channel `ic` and the descriptor `fd`.
If several channels are created on the same descriptor, one of the channels must be closed, but not the others. Consider for example a descriptor `s` connected to a socket and two channels `ic = in_channel_of_descr s` and `oc = out_channel_of_descr s`. The recommended closing protocol is to perform `close_out oc`, which flushes buffered output to the socket then closes the socket. The `ic` channel must not be closed and will be collected by the GC eventually.
```
val out_channel_of_descr : file_descr -> out_channel
```
Create an output channel writing on the given descriptor. The channel is initially in binary mode; use `set_binary_mode_out oc false` if text mode is desired. Text mode is supported only if the descriptor refers to a file or pipe, but is not supported if it refers to a socket.
On Windows: [`set_binary_mode_out`](stdlib#VALset_binary_mode_out) always fails on channels created with this function.
Beware that output channels are buffered, so you may have to call [`flush`](stdlib#VALflush) to ensure that all data has been sent to the descriptor. Channels also keep a copy of the current position in the file.
Closing the channel `oc` returned by `out_channel_of_descr fd` using `close_out oc` also closes the underlying descriptor `fd`. It is incorrect to close both the channel `ic` and the descriptor `fd`.
See [`Unix.in_channel_of_descr`](unix#VALin_channel_of_descr) for a discussion of the closing protocol when several channels are created on the same descriptor.
```
val descr_of_in_channel : in_channel -> file_descr
```
Return the descriptor corresponding to an input channel.
```
val descr_of_out_channel : out_channel -> file_descr
```
Return the descriptor corresponding to an output channel.
Seeking and truncating
----------------------
```
type seek_command =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `SEEK\_SET` | `(*` | indicates positions relative to the beginning of the file | `*)` |
| `|` | `SEEK\_CUR` | `(*` | indicates positions relative to the current position | `*)` |
| `|` | `SEEK\_END` | `(*` | indicates positions relative to the end of the file | `*)` |
Positioning modes for [`Unix.lseek`](unix#VALlseek).
```
val lseek : file_descr -> int -> seek_command -> int
```
Set the current position for a file descriptor, and return the resulting offset (from the beginning of the file).
```
val truncate : string -> int -> unit
```
Truncates the named file to the given size.
```
val ftruncate : file_descr -> int -> unit
```
Truncates the file corresponding to the given descriptor to the given size.
File status
-----------
```
type file_kind =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `S\_REG` | `(*` | Regular file | `*)` |
| `|` | `S\_DIR` | `(*` | Directory | `*)` |
| `|` | `S\_CHR` | `(*` | Character device | `*)` |
| `|` | `S\_BLK` | `(*` | Block device | `*)` |
| `|` | `S\_LNK` | `(*` | Symbolic link | `*)` |
| `|` | `S\_FIFO` | `(*` | Named pipe | `*)` |
| `|` | `S\_SOCK` | `(*` | Socket | `*)` |
```
type stats = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `st\_dev : `int`;` | `(*` | Device number | `*)` |
| | `st\_ino : `int`;` | `(*` | Inode number | `*)` |
| | `st\_kind : `[file\_kind](unix#TYPEfile_kind)`;` | `(*` | Kind of the file | `*)` |
| | `st\_perm : `[file\_perm](unix#TYPEfile_perm)`;` | `(*` | Access rights | `*)` |
| | `st\_nlink : `int`;` | `(*` | Number of links | `*)` |
| | `st\_uid : `int`;` | `(*` | User id of the owner | `*)` |
| | `st\_gid : `int`;` | `(*` | Group ID of the file's group | `*)` |
| | `st\_rdev : `int`;` | `(*` | Device ID (if special file) | `*)` |
| | `st\_size : `int`;` | `(*` | Size in bytes | `*)` |
| | `st\_atime : `float`;` | `(*` | Last access time | `*)` |
| | `st\_mtime : `float`;` | `(*` | Last modification time | `*)` |
| | `st\_ctime : `float`;` | `(*` | Last status change time | `*)` |
`}` The information returned by the [`Unix.stat`](unix#VALstat) calls.
```
val stat : string -> stats
```
Return the information for the named file.
```
val lstat : string -> stats
```
Same as [`Unix.stat`](unix#VALstat), but in case the file is a symbolic link, return the information for the link itself.
```
val fstat : file_descr -> stats
```
Return the information for the file associated with the given descriptor.
```
val isatty : file_descr -> bool
```
Return `true` if the given file descriptor refers to a terminal or console window, `false` otherwise.
File operations on large files
------------------------------
```
module LargeFile: sig .. end
```
File operations on large files.
Mapping files into memory
-------------------------
```
val map_file : file_descr -> ?pos:int64 -> ('a, 'b) Bigarray.kind -> 'c Bigarray.layout -> bool -> int array -> ('a, 'b, 'c) Bigarray.Genarray.t
```
Memory mapping of a file as a Bigarray. `map_file fd kind layout shared dims` returns a Bigarray of kind `kind`, layout `layout`, and dimensions as specified in `dims`. The data contained in this Bigarray are the contents of the file referred to by the file descriptor `fd` (as opened previously with [`Unix.openfile`](unix#VALopenfile), for example). The optional `pos` parameter is the byte offset in the file of the data being mapped; it defaults to 0 (map from the beginning of the file).
If `shared` is `true`, all modifications performed on the array are reflected in the file. This requires that `fd` be opened with write permissions. If `shared` is `false`, modifications performed on the array are done in memory only, using copy-on-write of the modified pages; the underlying file is not affected.
[`Unix.map_file`](unix#VALmap_file) is much more efficient than reading the whole file in a Bigarray, modifying that Bigarray, and writing it afterwards.
To adjust automatically the dimensions of the Bigarray to the actual size of the file, the major dimension (that is, the first dimension for an array with C layout, and the last dimension for an array with Fortran layout) can be given as `-1`. [`Unix.map_file`](unix#VALmap_file) then determines the major dimension from the size of the file. The file must contain an integral number of sub-arrays as determined by the non-major dimensions, otherwise `Failure` is raised.
If all dimensions of the Bigarray are given, the file size is matched against the size of the Bigarray. If the file is larger than the Bigarray, only the initial portion of the file is mapped to the Bigarray. If the file is smaller than the big array, the file is automatically grown to the size of the Bigarray. This requires write permissions on `fd`.
Array accesses are bounds-checked, but the bounds are determined by the initial call to `map_file`. Therefore, you should make sure no other process modifies the mapped file while you're accessing it, or a SIGBUS signal may be raised. This happens, for instance, if the file is shrunk.
`Invalid\_argument` or `Failure` may be raised in cases where argument validation fails.
* **Since** 4.06.0
Operations on file names
------------------------
```
val unlink : string -> unit
```
Removes the named file.
If the named file is a directory, raises:
* `EPERM` on POSIX compliant system
* `EISDIR` on Linux >= 2.1.132
* `EACCESS` on Windows
```
val rename : string -> string -> unit
```
`rename src dst` changes the name of a file from `src` to `dst`, moving it between directories if needed. If `dst` already exists, its contents will be replaced with those of `src`. Depending on the operating system, the metadata (permissions, owner, etc) of `dst` can either be preserved or be replaced by those of `src`.
```
val link : ?follow:bool -> string -> string -> unit
```
`link ?follow src dst` creates a hard link named `dst` to the file named `src`.
* **Raises**
+ `ENOSYS` On *Unix* if `~follow:_` is requested, but linkat is unavailable.
+ `ENOSYS` On *Windows* if `~follow:false` is requested.
`follow` : indicates whether a `src` symlink is followed or a hardlink to `src` itself will be created. On *Unix* systems this is done using the `linkat(2)` function. If `?follow` is not provided, then the `link(2)` function is used whose behaviour is OS-dependent, but more widely available.
```
val realpath : string -> string
```
`realpath p` is an absolute pathname for `p` obtained by resolving all extra `/` characters, relative path segments and symbolic links.
* **Since** 4.13.0
File permissions and ownership
------------------------------
```
type access_permission =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `R\_OK` | `(*` | Read permission | `*)` |
| `|` | `W\_OK` | `(*` | Write permission | `*)` |
| `|` | `X\_OK` | `(*` | Execution permission | `*)` |
| `|` | `F\_OK` | `(*` | File exists | `*)` |
Flags for the [`Unix.access`](unix#VALaccess) call.
```
val chmod : string -> file_perm -> unit
```
Change the permissions of the named file.
```
val fchmod : file_descr -> file_perm -> unit
```
Change the permissions of an opened file.
* **Raises** `Invalid_argument` on Windows
```
val chown : string -> int -> int -> unit
```
Change the owner uid and owner gid of the named file.
* **Raises** `Invalid_argument` on Windows
```
val fchown : file_descr -> int -> int -> unit
```
Change the owner uid and owner gid of an opened file.
* **Raises** `Invalid_argument` on Windows
```
val umask : int -> int
```
Set the process's file mode creation mask, and return the previous mask.
* **Raises** `Invalid_argument` on Windows
```
val access : string -> access_permission list -> unit
```
Check that the process has the given permissions over the named file.
On Windows: execute permission `X\_OK` cannot be tested, just tests for read permission instead.
* **Raises** `Unix_error` otherwise.
Operations on file descriptors
------------------------------
```
val dup : ?cloexec:bool -> file_descr -> file_descr
```
Return a new file descriptor referencing the same file as the given descriptor. See [`Unix.set_close_on_exec`](unix#VALset_close_on_exec) for documentation on the `cloexec` optional argument.
```
val dup2 : ?cloexec:bool -> file_descr -> file_descr -> unit
```
`dup2 src dst` duplicates `src` to `dst`, closing `dst` if already opened. See [`Unix.set_close_on_exec`](unix#VALset_close_on_exec) for documentation on the `cloexec` optional argument.
```
val set_nonblock : file_descr -> unit
```
Set the ``non-blocking'' flag on the given descriptor. When the non-blocking flag is set, reading on a descriptor on which there is temporarily no data available raises the `EAGAIN` or `EWOULDBLOCK` error instead of blocking; writing on a descriptor on which there is temporarily no room for writing also raises `EAGAIN` or `EWOULDBLOCK`.
```
val clear_nonblock : file_descr -> unit
```
Clear the ``non-blocking'' flag on the given descriptor. See [`Unix.set_nonblock`](unix#VALset_nonblock).
```
val set_close_on_exec : file_descr -> unit
```
Set the ``close-on-exec'' flag on the given descriptor. A descriptor with the close-on-exec flag is automatically closed when the current process starts another program with one of the `exec`, `create_process` and `open_process` functions.
It is often a security hole to leak file descriptors opened on, say, a private file to an external program: the program, then, gets access to the private file and can do bad things with it. Hence, it is highly recommended to set all file descriptors ``close-on-exec'', except in the very few cases where a file descriptor actually needs to be transmitted to another program.
The best way to set a file descriptor ``close-on-exec'' is to create it in this state. To this end, the `openfile` function has `O\_CLOEXEC` and `O\_KEEPEXEC` flags to enforce ``close-on-exec'' mode or ``keep-on-exec'' mode, respectively. All other operations in the Unix module that create file descriptors have an optional argument `?cloexec:bool` to indicate whether the file descriptor should be created in ``close-on-exec'' mode (by writing `~cloexec:true`) or in ``keep-on-exec'' mode (by writing `~cloexec:false`). For historical reasons, the default file descriptor creation mode is ``keep-on-exec'', if no `cloexec` optional argument is given. This is not a safe default, hence it is highly recommended to pass explicit `cloexec` arguments to operations that create file descriptors.
The `cloexec` optional arguments and the `O\_KEEPEXEC` flag were introduced in OCaml 4.05. Earlier, the common practice was to create file descriptors in the default, ``keep-on-exec'' mode, then call `set_close_on_exec` on those freshly-created file descriptors. This is not as safe as creating the file descriptor in ``close-on-exec'' mode because, in multithreaded programs, a window of vulnerability exists between the time when the file descriptor is created and the time `set_close_on_exec` completes. If another thread spawns another program during this window, the descriptor will leak, as it is still in the ``keep-on-exec'' mode.
Regarding the atomicity guarantees given by `~cloexec:true` or by the use of the `O\_CLOEXEC` flag: on all platforms it is guaranteed that a concurrently-executing Caml thread cannot leak the descriptor by starting a new process. On Linux, this guarantee extends to concurrently-executing C threads. As of Feb 2017, other operating systems lack the necessary system calls and still expose a window of vulnerability during which a C thread can see the newly-created file descriptor in ``keep-on-exec'' mode.
```
val clear_close_on_exec : file_descr -> unit
```
Clear the ``close-on-exec'' flag on the given descriptor. See [`Unix.set_close_on_exec`](unix#VALset_close_on_exec).
Directories
-----------
```
val mkdir : string -> file_perm -> unit
```
Create a directory with the given permissions (see [`Unix.umask`](unix#VALumask)).
```
val rmdir : string -> unit
```
Remove an empty directory.
```
val chdir : string -> unit
```
Change the process working directory.
```
val getcwd : unit -> string
```
Return the name of the current working directory.
```
val chroot : string -> unit
```
Change the process root directory.
* **Raises** `Invalid_argument` on Windows
```
type dir_handle
```
The type of descriptors over opened directories.
```
val opendir : string -> dir_handle
```
Open a descriptor on a directory
```
val readdir : dir_handle -> string
```
Return the next entry in a directory.
* **Raises** `End_of_file` when the end of the directory has been reached.
```
val rewinddir : dir_handle -> unit
```
Reposition the descriptor to the beginning of the directory
```
val closedir : dir_handle -> unit
```
Close a directory descriptor.
Pipes and redirections
----------------------
```
val pipe : ?cloexec:bool -> unit -> file_descr * file_descr
```
Create a pipe. The first component of the result is opened for reading, that's the exit to the pipe. The second component is opened for writing, that's the entrance to the pipe. See [`Unix.set_close_on_exec`](unix#VALset_close_on_exec) for documentation on the `cloexec` optional argument.
```
val mkfifo : string -> file_perm -> unit
```
Create a named pipe with the given permissions (see [`Unix.umask`](unix#VALumask)).
* **Raises** `Invalid_argument` on Windows
High-level process and redirection management
---------------------------------------------
```
val create_process : string -> string array -> file_descr -> file_descr -> file_descr -> int
```
`create_process prog args stdin stdout stderr` forks a new process that executes the program in file `prog`, with arguments `args`. The pid of the new process is returned immediately; the new process executes concurrently with the current process. The standard input and outputs of the new process are connected to the descriptors `stdin`, `stdout` and `stderr`. Passing e.g. [`Unix.stdout`](unix#VALstdout) for `stdout` prevents the redirection and causes the new process to have the same standard output as the current process. The executable file `prog` is searched in the path. The new process has the same environment as the current process.
```
val create_process_env : string -> string array -> string array -> file_descr -> file_descr -> file_descr -> int
```
`create_process_env prog args env stdin stdout stderr` works as [`Unix.create_process`](unix#VALcreate_process), except that the extra argument `env` specifies the environment passed to the program.
```
val open_process_in : string -> in_channel
```
High-level pipe and process management. This function runs the given command in parallel with the program. The standard output of the command is redirected to a pipe, which can be read via the returned input channel. The command is interpreted by the shell `/bin/sh` (or `cmd.exe` on Windows), cf. [`Unix.system`](unix#VALsystem). The [`Filename.quote_command`](filename#VALquote_command) function can be used to quote the command and its arguments as appropriate for the shell being used. If the command does not need to be run through the shell, [`Unix.open_process_args_in`](unix#VALopen_process_args_in) can be used as a more robust and more efficient alternative to [`Unix.open_process_in`](unix#VALopen_process_in).
```
val open_process_out : string -> out_channel
```
Same as [`Unix.open_process_in`](unix#VALopen_process_in), but redirect the standard input of the command to a pipe. Data written to the returned output channel is sent to the standard input of the command. Warning: writes on output channels are buffered, hence be careful to call [`flush`](stdlib#VALflush) at the right times to ensure correct synchronization. If the command does not need to be run through the shell, [`Unix.open_process_args_out`](unix#VALopen_process_args_out) can be used instead of [`Unix.open_process_out`](unix#VALopen_process_out).
```
val open_process : string -> in_channel * out_channel
```
Same as [`Unix.open_process_out`](unix#VALopen_process_out), but redirects both the standard input and standard output of the command to pipes connected to the two returned channels. The input channel is connected to the output of the command, and the output channel to the input of the command. If the command does not need to be run through the shell, [`Unix.open_process_args`](unix#VALopen_process_args) can be used instead of [`Unix.open_process`](unix#VALopen_process).
```
val open_process_full : string -> string array -> in_channel * out_channel * in_channel
```
Similar to [`Unix.open_process`](unix#VALopen_process), but the second argument specifies the environment passed to the command. The result is a triple of channels connected respectively to the standard output, standard input, and standard error of the command. If the command does not need to be run through the shell, [`Unix.open_process_args_full`](unix#VALopen_process_args_full) can be used instead of [`Unix.open_process_full`](unix#VALopen_process_full).
```
val open_process_args_in : string -> string array -> in_channel
```
`open_process_args_in prog args` runs the program `prog` with arguments `args`. The new process executes concurrently with the current process. The standard output of the new process is redirected to a pipe, which can be read via the returned input channel.
The executable file `prog` is searched in the path. This behaviour changed in 4.12; previously `prog` was looked up only in the current directory.
The new process has the same environment as the current process.
* **Since** 4.08.0
```
val open_process_args_out : string -> string array -> out_channel
```
Same as [`Unix.open_process_args_in`](unix#VALopen_process_args_in), but redirect the standard input of the new process to a pipe. Data written to the returned output channel is sent to the standard input of the program. Warning: writes on output channels are buffered, hence be careful to call [`flush`](stdlib#VALflush) at the right times to ensure correct synchronization.
* **Since** 4.08.0
```
val open_process_args : string -> string array -> in_channel * out_channel
```
Same as [`Unix.open_process_args_out`](unix#VALopen_process_args_out), but redirects both the standard input and standard output of the new process to pipes connected to the two returned channels. The input channel is connected to the output of the program, and the output channel to the input of the program.
* **Since** 4.08.0
```
val open_process_args_full : string -> string array -> string array -> in_channel * out_channel * in_channel
```
Similar to [`Unix.open_process_args`](unix#VALopen_process_args), but the third argument specifies the environment passed to the new process. The result is a triple of channels connected respectively to the standard output, standard input, and standard error of the program.
* **Since** 4.08.0
```
val process_in_pid : in_channel -> int
```
Return the pid of a process opened via [`Unix.open_process_in`](unix#VALopen_process_in) or [`Unix.open_process_args_in`](unix#VALopen_process_args_in).
* **Since** 4.08.0 (4.12.0 in UnixLabels)
```
val process_out_pid : out_channel -> int
```
Return the pid of a process opened via [`Unix.open_process_out`](unix#VALopen_process_out) or [`Unix.open_process_args_out`](unix#VALopen_process_args_out).
* **Since** 4.08.0 (4.12.0 in UnixLabels)
```
val process_pid : in_channel * out_channel -> int
```
Return the pid of a process opened via [`Unix.open_process`](unix#VALopen_process) or [`Unix.open_process_args`](unix#VALopen_process_args).
* **Since** 4.08.0 (4.12.0 in UnixLabels)
```
val process_full_pid : in_channel * out_channel * in_channel -> int
```
Return the pid of a process opened via [`Unix.open_process_full`](unix#VALopen_process_full) or [`Unix.open_process_args_full`](unix#VALopen_process_args_full).
* **Since** 4.08.0 (4.12.0 in UnixLabels)
```
val close_process_in : in_channel -> process_status
```
Close channels opened by [`Unix.open_process_in`](unix#VALopen_process_in), wait for the associated command to terminate, and return its termination status.
```
val close_process_out : out_channel -> process_status
```
Close channels opened by [`Unix.open_process_out`](unix#VALopen_process_out), wait for the associated command to terminate, and return its termination status.
```
val close_process : in_channel * out_channel -> process_status
```
Close channels opened by [`Unix.open_process`](unix#VALopen_process), wait for the associated command to terminate, and return its termination status.
```
val close_process_full : in_channel * out_channel * in_channel -> process_status
```
Close channels opened by [`Unix.open_process_full`](unix#VALopen_process_full), wait for the associated command to terminate, and return its termination status.
Symbolic links
--------------
```
val symlink : ?to_dir:bool -> string -> string -> unit
```
`symlink ?to_dir src dst` creates the file `dst` as a symbolic link to the file `src`. On Windows, `~to_dir` indicates if the symbolic link points to a directory or a file; if omitted, `symlink` examines `src` using `stat` and picks appropriately, if `src` does not exist then `false` is assumed (for this reason, it is recommended that the `~to_dir` parameter be specified in new code). On Unix, `~to_dir` is ignored.
Windows symbolic links are available in Windows Vista onwards. There are some important differences between Windows symlinks and their POSIX counterparts.
Windows symbolic links come in two flavours: directory and regular, which designate whether the symbolic link points to a directory or a file. The type must be correct - a directory symlink which actually points to a file cannot be selected with chdir and a file symlink which actually points to a directory cannot be read or written (note that Cygwin's emulation layer ignores this distinction).
When symbolic links are created to existing targets, this distinction doesn't matter and `symlink` will automatically create the correct kind of symbolic link. The distinction matters when a symbolic link is created to a non-existent target.
The other caveat is that by default symbolic links are a privileged operation. Administrators will always need to be running elevated (or with UAC disabled) and by default normal user accounts need to be granted the SeCreateSymbolicLinkPrivilege via Local Security Policy (secpol.msc) or via Active Directory.
[`Unix.has_symlink`](unix#VALhas_symlink) can be used to check that a process is able to create symbolic links.
```
val has_symlink : unit -> bool
```
Returns `true` if the user is able to create symbolic links. On Windows, this indicates that the user not only has the SeCreateSymbolicLinkPrivilege but is also running elevated, if necessary. On other platforms, this is simply indicates that the symlink system call is available.
* **Since** 4.03.0
```
val readlink : string -> string
```
Read the contents of a symbolic link.
Polling
-------
```
val select : file_descr list -> file_descr list -> file_descr list -> float -> file_descr list * file_descr list * file_descr list
```
Wait until some input/output operations become possible on some channels. The three list arguments are, respectively, a set of descriptors to check for reading (first argument), for writing (second argument), or for exceptional conditions (third argument). The fourth argument is the maximal timeout, in seconds; a negative fourth argument means no timeout (unbounded wait). The result is composed of three sets of descriptors: those ready for reading (first component), ready for writing (second component), and over which an exceptional condition is pending (third component).
Locking
-------
```
type lock_command =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `F\_ULOCK` | `(*` | Unlock a region | `*)` |
| `|` | `F\_LOCK` | `(*` | Lock a region for writing, and block if already locked | `*)` |
| `|` | `F\_TLOCK` | `(*` | Lock a region for writing, or fail if already locked | `*)` |
| `|` | `F\_TEST` | `(*` | Test a region for other process locks | `*)` |
| `|` | `F\_RLOCK` | `(*` | Lock a region for reading, and block if already locked | `*)` |
| `|` | `F\_TRLOCK` | `(*` | Lock a region for reading, or fail if already locked | `*)` |
Commands for [`Unix.lockf`](unix#VALlockf).
```
val lockf : file_descr -> lock_command -> int -> unit
```
`lockf fd mode len` puts a lock on a region of the file opened as `fd`. The region starts at the current read/write position for `fd` (as set by [`Unix.lseek`](unix#VALlseek)), and extends `len` bytes forward if `len` is positive, `len` bytes backwards if `len` is negative, or to the end of the file if `len` is zero. A write lock prevents any other process from acquiring a read or write lock on the region. A read lock prevents any other process from acquiring a write lock on the region, but lets other processes acquire read locks on it.
The `F\_LOCK` and `F\_TLOCK` commands attempts to put a write lock on the specified region. The `F\_RLOCK` and `F\_TRLOCK` commands attempts to put a read lock on the specified region. If one or several locks put by another process prevent the current process from acquiring the lock, `F\_LOCK` and `F\_RLOCK` block until these locks are removed, while `F\_TLOCK` and `F\_TRLOCK` fail immediately with an exception. The `F\_ULOCK` removes whatever locks the current process has on the specified region. Finally, the `F\_TEST` command tests whether a write lock can be acquired on the specified region, without actually putting a lock. It returns immediately if successful, or fails otherwise.
What happens when a process tries to lock a region of a file that is already locked by the same process depends on the OS. On POSIX-compliant systems, the second lock operation succeeds and may "promote" the older lock from read lock to write lock. On Windows, the second lock operation will block or fail.
Signals
-------
Note: installation of signal handlers is performed via the functions [`Sys.signal`](sys#VALsignal) and [`Sys.set_signal`](sys#VALset_signal).
```
val kill : int -> int -> unit
```
`kill pid signal` sends signal number `signal` to the process with id `pid`.
On Windows: only the [`Sys.sigkill`](sys#VALsigkill) signal is emulated.
```
type sigprocmask_command =
```
| | |
| --- | --- |
| `|` | `SIG\_SETMASK` |
| `|` | `SIG\_BLOCK` |
| `|` | `SIG\_UNBLOCK` |
```
val sigprocmask : sigprocmask_command -> int list -> int list
```
`sigprocmask mode sigs` changes the set of blocked signals. If `mode` is `SIG\_SETMASK`, blocked signals are set to those in the list `sigs`. If `mode` is `SIG\_BLOCK`, the signals in `sigs` are added to the set of blocked signals. If `mode` is `SIG\_UNBLOCK`, the signals in `sigs` are removed from the set of blocked signals. `sigprocmask` returns the set of previously blocked signals.
When the systhreads version of the `Thread` module is loaded, this function redirects to `Thread.sigmask`. I.e., `sigprocmask` only changes the mask of the current thread.
* **Raises** `Invalid_argument` on Windows (no inter-process signals on Windows)
```
val sigpending : unit -> int list
```
Return the set of blocked signals that are currently pending.
* **Raises** `Invalid_argument` on Windows (no inter-process signals on Windows)
```
val sigsuspend : int list -> unit
```
`sigsuspend sigs` atomically sets the blocked signals to `sigs` and waits for a non-ignored, non-blocked signal to be delivered. On return, the blocked signals are reset to their initial value.
* **Raises** `Invalid_argument` on Windows (no inter-process signals on Windows)
```
val pause : unit -> unit
```
Wait until a non-ignored, non-blocked signal is delivered.
* **Raises** `Invalid_argument` on Windows (no inter-process signals on Windows)
Time functions
--------------
```
type process_times = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `tms\_utime : `float`;` | `(*` | User time for the process | `*)` |
| | `tms\_stime : `float`;` | `(*` | System time for the process | `*)` |
| | `tms\_cutime : `float`;` | `(*` | User time for the children processes | `*)` |
| | `tms\_cstime : `float`;` | `(*` | System time for the children processes | `*)` |
`}` The execution times (CPU times) of a process.
```
type tm = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `tm\_sec : `int`;` | `(*` | Seconds 0..60 | `*)` |
| | `tm\_min : `int`;` | `(*` | Minutes 0..59 | `*)` |
| | `tm\_hour : `int`;` | `(*` | Hours 0..23 | `*)` |
| | `tm\_mday : `int`;` | `(*` | Day of month 1..31 | `*)` |
| | `tm\_mon : `int`;` | `(*` | Month of year 0..11 | `*)` |
| | `tm\_year : `int`;` | `(*` | Year - 1900 | `*)` |
| | `tm\_wday : `int`;` | `(*` | Day of week (Sunday is 0) | `*)` |
| | `tm\_yday : `int`;` | `(*` | Day of year 0..365 | `*)` |
| | `tm\_isdst : `bool`;` | `(*` | Daylight time savings in effect | `*)` |
`}` The type representing wallclock time and calendar date.
```
val time : unit -> float
```
Return the current time since 00:00:00 GMT, Jan. 1, 1970, in seconds.
```
val gettimeofday : unit -> float
```
Same as [`Unix.time`](unix#VALtime), but with resolution better than 1 second.
```
val gmtime : float -> tm
```
Convert a time in seconds, as returned by [`Unix.time`](unix#VALtime), into a date and a time. Assumes UTC (Coordinated Universal Time), also known as GMT. To perform the inverse conversion, set the TZ environment variable to "UTC", use [`Unix.mktime`](unix#VALmktime), and then restore the original value of TZ.
```
val localtime : float -> tm
```
Convert a time in seconds, as returned by [`Unix.time`](unix#VALtime), into a date and a time. Assumes the local time zone. The function performing the inverse conversion is [`Unix.mktime`](unix#VALmktime).
```
val mktime : tm -> float * tm
```
Convert a date and time, specified by the `tm` argument, into a time in seconds, as returned by [`Unix.time`](unix#VALtime). The `tm_isdst`, `tm_wday` and `tm_yday` fields of `tm` are ignored. Also return a normalized copy of the given `tm` record, with the `tm_wday`, `tm_yday`, and `tm_isdst` fields recomputed from the other fields, and the other fields normalized (so that, e.g., 40 October is changed into 9 November). The `tm` argument is interpreted in the local time zone.
```
val alarm : int -> int
```
Schedule a `SIGALRM` signal after the given number of seconds.
* **Raises** `Invalid_argument` on Windows
```
val sleep : int -> unit
```
Stop execution for the given number of seconds.
```
val sleepf : float -> unit
```
Stop execution for the given number of seconds. Like `sleep`, but fractions of seconds are supported.
* **Since** 4.03.0 (4.12.0 in UnixLabels)
```
val times : unit -> process_times
```
Return the execution times of the process.
On Windows: partially implemented, will not report timings for child processes.
```
val utimes : string -> float -> float -> unit
```
Set the last access time (second arg) and last modification time (third arg) for a file. Times are expressed in seconds from 00:00:00 GMT, Jan. 1, 1970. If both times are `0.0`, the access and last modification times are both set to the current time.
```
type interval_timer =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `ITIMER\_REAL` | `(*` | decrements in real time, and sends the signal `SIGALRM` when expired. | `*)` |
| `|` | `ITIMER\_VIRTUAL` | `(*` | decrements in process virtual time, and sends `SIGVTALRM` when expired. | `*)` |
| `|` | `ITIMER\_PROF` | `(*` | (for profiling) decrements both when the process is running and when the system is running on behalf of the process; it sends `SIGPROF` when expired. | `*)` |
The three kinds of interval timers.
```
type interval_timer_status = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `it\_interval : `float`;` | `(*` | Period | `*)` |
| | `it\_value : `float`;` | `(*` | Current value of the timer | `*)` |
`}` The type describing the status of an interval timer
```
val getitimer : interval_timer -> interval_timer_status
```
Return the current status of the given interval timer.
* **Raises** `Invalid_argument` on Windows
```
val setitimer : interval_timer -> interval_timer_status -> interval_timer_status
```
`setitimer t s` sets the interval timer `t` and returns its previous status. The `s` argument is interpreted as follows: `s.it_value`, if nonzero, is the time to the next timer expiration; `s.it_interval`, if nonzero, specifies a value to be used in reloading `it_value` when the timer expires. Setting `s.it_value` to zero disables the timer. Setting `s.it_interval` to zero causes the timer to be disabled after its next expiration.
* **Raises** `Invalid_argument` on Windows
User id, group id
-----------------
```
val getuid : unit -> int
```
Return the user id of the user executing the process.
On Windows: always returns `1`.
```
val geteuid : unit -> int
```
Return the effective user id under which the process runs.
On Windows: always returns `1`.
```
val setuid : int -> unit
```
Set the real user id and effective user id for the process.
* **Raises** `Invalid_argument` on Windows
```
val getgid : unit -> int
```
Return the group id of the user executing the process.
On Windows: always returns `1`.
```
val getegid : unit -> int
```
Return the effective group id under which the process runs.
On Windows: always returns `1`.
```
val setgid : int -> unit
```
Set the real group id and effective group id for the process.
* **Raises** `Invalid_argument` on Windows
```
val getgroups : unit -> int array
```
Return the list of groups to which the user executing the process belongs.
On Windows: always returns `[|1|]`.
```
val setgroups : int array -> unit
```
`setgroups groups` sets the supplementary group IDs for the calling process. Appropriate privileges are required.
* **Raises** `Invalid_argument` on Windows
```
val initgroups : string -> int -> unit
```
`initgroups user group` initializes the group access list by reading the group database /etc/group and using all groups of which `user` is a member. The additional group `group` is also added to the list.
* **Raises** `Invalid_argument` on Windows
```
type passwd_entry = {
```
| | |
| --- | --- |
| | `pw\_name : `string`;` |
| | `pw\_passwd : `string`;` |
| | `pw\_uid : `int`;` |
| | `pw\_gid : `int`;` |
| | `pw\_gecos : `string`;` |
| | `pw\_dir : `string`;` |
| | `pw\_shell : `string`;` |
`}` Structure of entries in the `passwd` database.
```
type group_entry = {
```
| | |
| --- | --- |
| | `gr\_name : `string`;` |
| | `gr\_passwd : `string`;` |
| | `gr\_gid : `int`;` |
| | `gr\_mem : `string array`;` |
`}` Structure of entries in the `groups` database.
```
val getlogin : unit -> string
```
Return the login name of the user executing the process.
```
val getpwnam : string -> passwd_entry
```
Find an entry in `passwd` with the given name.
* **Raises** `Not_found` if no such entry exists, or always on Windows.
```
val getgrnam : string -> group_entry
```
Find an entry in `group` with the given name.
* **Raises** `Not_found` if no such entry exists, or always on Windows.
```
val getpwuid : int -> passwd_entry
```
Find an entry in `passwd` with the given user id.
* **Raises** `Not_found` if no such entry exists, or always on Windows.
```
val getgrgid : int -> group_entry
```
Find an entry in `group` with the given group id.
* **Raises** `Not_found` if no such entry exists, or always on Windows.
Internet addresses
------------------
```
type inet_addr
```
The abstract type of Internet addresses.
```
val inet_addr_of_string : string -> inet_addr
```
Conversion from the printable representation of an Internet address to its internal representation. The argument string consists of 4 numbers separated by periods (`XXX.YYY.ZZZ.TTT`) for IPv4 addresses, and up to 8 numbers separated by colons for IPv6 addresses.
* **Raises** `Failure` when given a string that does not match these formats.
```
val string_of_inet_addr : inet_addr -> string
```
Return the printable representation of the given Internet address. See [`Unix.inet_addr_of_string`](unix#VALinet_addr_of_string) for a description of the printable representation.
```
val inet_addr_any : inet_addr
```
A special IPv4 address, for use only with `bind`, representing all the Internet addresses that the host machine possesses.
```
val inet_addr_loopback : inet_addr
```
A special IPv4 address representing the host machine (`127.0.0.1`).
```
val inet6_addr_any : inet_addr
```
A special IPv6 address, for use only with `bind`, representing all the Internet addresses that the host machine possesses.
```
val inet6_addr_loopback : inet_addr
```
A special IPv6 address representing the host machine (`::1`).
```
val is_inet6_addr : inet_addr -> bool
```
Whether the given `inet_addr` is an IPv6 address.
* **Since** 4.12.0
Sockets
-------
```
type socket_domain =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `PF\_UNIX` | `(*` | Unix domain | `*)` |
| `|` | `PF\_INET` | `(*` | Internet domain (IPv4) | `*)` |
| `|` | `PF\_INET6` | `(*` | Internet domain (IPv6) | `*)` |
The type of socket domains. Not all platforms support IPv6 sockets (type `PF\_INET6`).
On Windows: `PF\_UNIX` supported since 4.14.0 on Windows 10 1803 and later.
```
type socket_type =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `SOCK\_STREAM` | `(*` | Stream socket | `*)` |
| `|` | `SOCK\_DGRAM` | `(*` | Datagram socket | `*)` |
| `|` | `SOCK\_RAW` | `(*` | Raw socket | `*)` |
| `|` | `SOCK\_SEQPACKET` | `(*` | Sequenced packets socket | `*)` |
The type of socket kinds, specifying the semantics of communications. `SOCK\_SEQPACKET` is included for completeness, but is rarely supported by the OS, and needs system calls that are not available in this library.
```
type sockaddr =
```
| | |
| --- | --- |
| `|` | `ADDR\_UNIX of `string`` |
| `|` | `ADDR\_INET of `[inet\_addr](unix#TYPEinet_addr) * int`` |
The type of socket addresses. `ADDR\_UNIX name` is a socket address in the Unix domain; `name` is a file name in the file system. `ADDR\_INET(addr,port)` is a socket address in the Internet domain; `addr` is the Internet address of the machine, and `port` is the port number.
```
val socket : ?cloexec:bool -> socket_domain -> socket_type -> int -> file_descr
```
Create a new socket in the given domain, and with the given kind. The third argument is the protocol type; 0 selects the default protocol for that kind of sockets. See [`Unix.set_close_on_exec`](unix#VALset_close_on_exec) for documentation on the `cloexec` optional argument.
```
val domain_of_sockaddr : sockaddr -> socket_domain
```
Return the socket domain adequate for the given socket address.
```
val socketpair : ?cloexec:bool -> socket_domain -> socket_type -> int -> file_descr * file_descr
```
Create a pair of unnamed sockets, connected together. See [`Unix.set_close_on_exec`](unix#VALset_close_on_exec) for documentation on the `cloexec` optional argument.
```
val accept : ?cloexec:bool -> file_descr -> file_descr * sockaddr
```
Accept connections on the given socket. The returned descriptor is a socket connected to the client; the returned address is the address of the connecting client. See [`Unix.set_close_on_exec`](unix#VALset_close_on_exec) for documentation on the `cloexec` optional argument.
```
val bind : file_descr -> sockaddr -> unit
```
Bind a socket to an address.
```
val connect : file_descr -> sockaddr -> unit
```
Connect a socket to an address.
```
val listen : file_descr -> int -> unit
```
Set up a socket for receiving connection requests. The integer argument is the maximal number of pending requests.
```
type shutdown_command =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `SHUTDOWN\_RECEIVE` | `(*` | Close for receiving | `*)` |
| `|` | `SHUTDOWN\_SEND` | `(*` | Close for sending | `*)` |
| `|` | `SHUTDOWN\_ALL` | `(*` | Close both | `*)` |
The type of commands for `shutdown`.
```
val shutdown : file_descr -> shutdown_command -> unit
```
Shutdown a socket connection. `SHUTDOWN\_SEND` as second argument causes reads on the other end of the connection to return an end-of-file condition. `SHUTDOWN\_RECEIVE` causes writes on the other end of the connection to return a closed pipe condition (`SIGPIPE` signal).
```
val getsockname : file_descr -> sockaddr
```
Return the address of the given socket.
```
val getpeername : file_descr -> sockaddr
```
Return the address of the host connected to the given socket.
```
type msg_flag =
```
| | |
| --- | --- |
| `|` | `MSG\_OOB` |
| `|` | `MSG\_DONTROUTE` |
| `|` | `MSG\_PEEK` |
The flags for [`Unix.recv`](unix#VALrecv), [`Unix.recvfrom`](unix#VALrecvfrom), [`Unix.send`](unix#VALsend) and [`Unix.sendto`](unix#VALsendto).
```
val recv : file_descr -> bytes -> int -> int -> msg_flag list -> int
```
Receive data from a connected socket.
```
val recvfrom : file_descr -> bytes -> int -> int -> msg_flag list -> int * sockaddr
```
Receive data from an unconnected socket.
```
val send : file_descr -> bytes -> int -> int -> msg_flag list -> int
```
Send data over a connected socket.
```
val send_substring : file_descr -> string -> int -> int -> msg_flag list -> int
```
Same as `send`, but take the data from a string instead of a byte sequence.
* **Since** 4.02.0
```
val sendto : file_descr -> bytes -> int -> int -> msg_flag list -> sockaddr -> int
```
Send data over an unconnected socket.
```
val sendto_substring : file_descr -> string -> int -> int -> msg_flag list -> sockaddr -> int
```
Same as `sendto`, but take the data from a string instead of a byte sequence.
* **Since** 4.02.0
Socket options
--------------
```
type socket_bool_option =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `SO\_DEBUG` | `(*` | Record debugging information | `*)` |
| `|` | `SO\_BROADCAST` | `(*` | Permit sending of broadcast messages | `*)` |
| `|` | `SO\_REUSEADDR` | `(*` | Allow reuse of local addresses for bind | `*)` |
| `|` | `SO\_KEEPALIVE` | `(*` | Keep connection active | `*)` |
| `|` | `SO\_DONTROUTE` | `(*` | Bypass the standard routing algorithms | `*)` |
| `|` | `SO\_OOBINLINE` | `(*` | Leave out-of-band data in line | `*)` |
| `|` | `SO\_ACCEPTCONN` | `(*` | Report whether socket listening is enabled | `*)` |
| `|` | `TCP\_NODELAY` | `(*` | Control the Nagle algorithm for TCP sockets | `*)` |
| `|` | `IPV6\_ONLY` | `(*` | Forbid binding an IPv6 socket to an IPv4 address | `*)` |
| `|` | `SO\_REUSEPORT` | `(*` | Allow reuse of address and port bindings | `*)` |
The socket options that can be consulted with [`Unix.getsockopt`](unix#VALgetsockopt) and modified with [`Unix.setsockopt`](unix#VALsetsockopt). These options have a boolean (`true`/`false`) value.
```
type socket_int_option =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `SO\_SNDBUF` | `(*` | Size of send buffer | `*)` |
| `|` | `SO\_RCVBUF` | `(*` | Size of received buffer | `*)` |
| `|` | `SO\_ERROR` | `(*` | Deprecated. Use Unix.getsockopt\_error instead. Deprecated. Use [`Unix.getsockopt_error`](unix#VALgetsockopt_error) instead. | `*)` |
| `|` | `SO\_TYPE` | `(*` | Report the socket type | `*)` |
| `|` | `SO\_RCVLOWAT` | `(*` | Minimum number of bytes to process for input operations | `*)` |
| `|` | `SO\_SNDLOWAT` | `(*` | Minimum number of bytes to process for output operations | `*)` |
The socket options that can be consulted with [`Unix.getsockopt_int`](unix#VALgetsockopt_int) and modified with [`Unix.setsockopt_int`](unix#VALsetsockopt_int). These options have an integer value.
```
type socket_optint_option =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `SO\_LINGER` | `(*` | Whether to linger on closed connections that have data present, and for how long (in seconds) | `*)` |
The socket options that can be consulted with [`Unix.getsockopt_optint`](unix#VALgetsockopt_optint) and modified with [`Unix.setsockopt_optint`](unix#VALsetsockopt_optint). These options have a value of type `int option`, with `None` meaning ``disabled''.
```
type socket_float_option =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `SO\_RCVTIMEO` | `(*` | Timeout for input operations | `*)` |
| `|` | `SO\_SNDTIMEO` | `(*` | Timeout for output operations | `*)` |
The socket options that can be consulted with [`Unix.getsockopt_float`](unix#VALgetsockopt_float) and modified with [`Unix.setsockopt_float`](unix#VALsetsockopt_float). These options have a floating-point value representing a time in seconds. The value 0 means infinite timeout.
```
val getsockopt : file_descr -> socket_bool_option -> bool
```
Return the current status of a boolean-valued option in the given socket.
```
val setsockopt : file_descr -> socket_bool_option -> bool -> unit
```
Set or clear a boolean-valued option in the given socket.
```
val getsockopt_int : file_descr -> socket_int_option -> int
```
Same as [`Unix.getsockopt`](unix#VALgetsockopt) for an integer-valued socket option.
```
val setsockopt_int : file_descr -> socket_int_option -> int -> unit
```
Same as [`Unix.setsockopt`](unix#VALsetsockopt) for an integer-valued socket option.
```
val getsockopt_optint : file_descr -> socket_optint_option -> int option
```
Same as [`Unix.getsockopt`](unix#VALgetsockopt) for a socket option whose value is an `int option`.
```
val setsockopt_optint : file_descr -> socket_optint_option -> int option -> unit
```
Same as [`Unix.setsockopt`](unix#VALsetsockopt) for a socket option whose value is an `int option`.
```
val getsockopt_float : file_descr -> socket_float_option -> float
```
Same as [`Unix.getsockopt`](unix#VALgetsockopt) for a socket option whose value is a floating-point number.
```
val setsockopt_float : file_descr -> socket_float_option -> float -> unit
```
Same as [`Unix.setsockopt`](unix#VALsetsockopt) for a socket option whose value is a floating-point number.
```
val getsockopt_error : file_descr -> error option
```
Return the error condition associated with the given socket, and clear it.
High-level network connection functions
---------------------------------------
```
val open_connection : sockaddr -> in_channel * out_channel
```
Connect to a server at the given address. Return a pair of buffered channels connected to the server. Remember to call [`flush`](stdlib#VALflush) on the output channel at the right times to ensure correct synchronization.
The two channels returned by `open_connection` share a descriptor to a socket. Therefore, when the connection is over, you should call [`close_out`](stdlib#VALclose_out) on the output channel, which will also close the underlying socket. Do not call [`close_in`](stdlib#VALclose_in) on the input channel; it will be collected by the GC eventually.
```
val shutdown_connection : in_channel -> unit
```
``Shut down'' a connection established with [`Unix.open_connection`](unix#VALopen_connection); that is, transmit an end-of-file condition to the server reading on the other side of the connection. This does not close the socket and the channels used by the connection. See [`Unix.open_connection`](unix#VALopen_connection) for how to close them once the connection is over.
```
val establish_server : (in_channel -> out_channel -> unit) -> sockaddr -> unit
```
Establish a server on the given address. The function given as first argument is called for each connection with two buffered channels connected to the client. A new process is created for each connection. The function [`Unix.establish_server`](unix#VALestablish_server) never returns normally.
The two channels given to the function share a descriptor to a socket. The function does not need to close the channels, since this occurs automatically when the function returns. If the function prefers explicit closing, it should close the output channel using [`close_out`](stdlib#VALclose_out) and leave the input channel unclosed, for reasons explained in [`Unix.in_channel_of_descr`](unix#VALin_channel_of_descr).
* **Raises** `Invalid_argument` on Windows. Use threads instead.
Host and protocol databases
---------------------------
```
type host_entry = {
```
| | |
| --- | --- |
| | `h\_name : `string`;` |
| | `h\_aliases : `string array`;` |
| | `h\_addrtype : `[socket\_domain](unix#TYPEsocket_domain)`;` |
| | `h\_addr\_list : `[inet\_addr](unix#TYPEinet_addr) array`;` |
`}` Structure of entries in the `hosts` database.
```
type protocol_entry = {
```
| | |
| --- | --- |
| | `p\_name : `string`;` |
| | `p\_aliases : `string array`;` |
| | `p\_proto : `int`;` |
`}` Structure of entries in the `protocols` database.
```
type service_entry = {
```
| | |
| --- | --- |
| | `s\_name : `string`;` |
| | `s\_aliases : `string array`;` |
| | `s\_port : `int`;` |
| | `s\_proto : `string`;` |
`}` Structure of entries in the `services` database.
```
val gethostname : unit -> string
```
Return the name of the local host.
```
val gethostbyname : string -> host_entry
```
Find an entry in `hosts` with the given name.
* **Raises** `Not_found` if no such entry exists.
```
val gethostbyaddr : inet_addr -> host_entry
```
Find an entry in `hosts` with the given address.
* **Raises** `Not_found` if no such entry exists.
```
val getprotobyname : string -> protocol_entry
```
Find an entry in `protocols` with the given name.
* **Raises** `Not_found` if no such entry exists.
```
val getprotobynumber : int -> protocol_entry
```
Find an entry in `protocols` with the given protocol number.
* **Raises** `Not_found` if no such entry exists.
```
val getservbyname : string -> string -> service_entry
```
Find an entry in `services` with the given name.
* **Raises** `Not_found` if no such entry exists.
```
val getservbyport : int -> string -> service_entry
```
Find an entry in `services` with the given service number.
* **Raises** `Not_found` if no such entry exists.
```
type addr_info = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `ai\_family : `[socket\_domain](unix#TYPEsocket_domain)`;` | `(*` | Socket domain | `*)` |
| | `ai\_socktype : `[socket\_type](unix#TYPEsocket_type)`;` | `(*` | Socket type | `*)` |
| | `ai\_protocol : `int`;` | `(*` | Socket protocol number | `*)` |
| | `ai\_addr : `[sockaddr](unix#TYPEsockaddr)`;` | `(*` | Address | `*)` |
| | `ai\_canonname : `string`;` | `(*` | Canonical host name | `*)` |
`}` Address information returned by [`Unix.getaddrinfo`](unix#VALgetaddrinfo).
```
type getaddrinfo_option =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `AI\_FAMILY of `[socket\_domain](unix#TYPEsocket_domain)`` | `(*` | Impose the given socket domain | `*)` |
| `|` | `AI\_SOCKTYPE of `[socket\_type](unix#TYPEsocket_type)`` | `(*` | Impose the given socket type | `*)` |
| `|` | `AI\_PROTOCOL of `int`` | `(*` | Impose the given protocol | `*)` |
| `|` | `AI\_NUMERICHOST` | `(*` | Do not call name resolver, expect numeric IP address | `*)` |
| `|` | `AI\_CANONNAME` | `(*` | Fill the `ai_canonname` field of the result | `*)` |
| `|` | `AI\_PASSIVE` | `(*` | Set address to ``any'' address for use with [`Unix.bind`](unix#VALbind) | `*)` |
Options to [`Unix.getaddrinfo`](unix#VALgetaddrinfo).
```
val getaddrinfo : string -> string -> getaddrinfo_option list -> addr_info list
```
`getaddrinfo host service opts` returns a list of [`Unix.addr_info`](unix#TYPEaddr_info) records describing socket parameters and addresses suitable for communicating with the given host and service. The empty list is returned if the host or service names are unknown, or the constraints expressed in `opts` cannot be satisfied.
`host` is either a host name or the string representation of an IP address. `host` can be given as the empty string; in this case, the ``any'' address or the ``loopback'' address are used, depending whether `opts` contains `AI\_PASSIVE`. `service` is either a service name or the string representation of a port number. `service` can be given as the empty string; in this case, the port field of the returned addresses is set to 0. `opts` is a possibly empty list of options that allows the caller to force a particular socket domain (e.g. IPv6 only or IPv4 only) or a particular socket type (e.g. TCP only or UDP only).
```
type name_info = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `ni\_hostname : `string`;` | `(*` | Name or IP address of host | `*)` |
| | `ni\_service : `string`;` | `(*` | Name of service or port number | `*)` |
`}` Host and service information returned by [`Unix.getnameinfo`](unix#VALgetnameinfo).
```
type getnameinfo_option =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `NI\_NOFQDN` | `(*` | Do not qualify local host names | `*)` |
| `|` | `NI\_NUMERICHOST` | `(*` | Always return host as IP address | `*)` |
| `|` | `NI\_NAMEREQD` | `(*` | Fail if host name cannot be determined | `*)` |
| `|` | `NI\_NUMERICSERV` | `(*` | Always return service as port number | `*)` |
| `|` | `NI\_DGRAM` | `(*` | Consider the service as UDP-based instead of the default TCP | `*)` |
Options to [`Unix.getnameinfo`](unix#VALgetnameinfo).
```
val getnameinfo : sockaddr -> getnameinfo_option list -> name_info
```
`getnameinfo addr opts` returns the host name and service name corresponding to the socket address `addr`. `opts` is a possibly empty list of options that governs how these names are obtained.
* **Raises** `Not_found` if an error occurs.
Terminal interface
------------------
The following functions implement the POSIX standard terminal interface. They provide control over asynchronous communication ports and pseudo-terminals. Refer to the `termios` man page for a complete description.
```
type terminal_io = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `mutable c\_ignbrk : `bool`;` | `(*` | Ignore the break condition. | `*)` |
| | `mutable c\_brkint : `bool`;` | `(*` | Signal interrupt on break condition. | `*)` |
| | `mutable c\_ignpar : `bool`;` | `(*` | Ignore characters with parity errors. | `*)` |
| | `mutable c\_parmrk : `bool`;` | `(*` | Mark parity errors. | `*)` |
| | `mutable c\_inpck : `bool`;` | `(*` | Enable parity check on input. | `*)` |
| | `mutable c\_istrip : `bool`;` | `(*` | Strip 8th bit on input characters. | `*)` |
| | `mutable c\_inlcr : `bool`;` | `(*` | Map NL to CR on input. | `*)` |
| | `mutable c\_igncr : `bool`;` | `(*` | Ignore CR on input. | `*)` |
| | `mutable c\_icrnl : `bool`;` | `(*` | Map CR to NL on input. | `*)` |
| | `mutable c\_ixon : `bool`;` | `(*` | Recognize XON/XOFF characters on input. | `*)` |
| | `mutable c\_ixoff : `bool`;` | `(*` | Emit XON/XOFF chars to control input flow. | `*)` |
| | `mutable c\_opost : `bool`;` | `(*` | Enable output processing. | `*)` |
| | `mutable c\_obaud : `int`;` | `(*` | Output baud rate (0 means close connection). | `*)` |
| | `mutable c\_ibaud : `int`;` | `(*` | Input baud rate. | `*)` |
| | `mutable c\_csize : `int`;` | `(*` | Number of bits per character (5-8). | `*)` |
| | `mutable c\_cstopb : `int`;` | `(*` | Number of stop bits (1-2). | `*)` |
| | `mutable c\_cread : `bool`;` | `(*` | Reception is enabled. | `*)` |
| | `mutable c\_parenb : `bool`;` | `(*` | Enable parity generation and detection. | `*)` |
| | `mutable c\_parodd : `bool`;` | `(*` | Specify odd parity instead of even. | `*)` |
| | `mutable c\_hupcl : `bool`;` | `(*` | Hang up on last close. | `*)` |
| | `mutable c\_clocal : `bool`;` | `(*` | Ignore modem status lines. | `*)` |
| | `mutable c\_isig : `bool`;` | `(*` | Generate signal on INTR, QUIT, SUSP. | `*)` |
| | `mutable c\_icanon : `bool`;` | `(*` | Enable canonical processing (line buffering and editing) | `*)` |
| | `mutable c\_noflsh : `bool`;` | `(*` | Disable flush after INTR, QUIT, SUSP. | `*)` |
| | `mutable c\_echo : `bool`;` | `(*` | Echo input characters. | `*)` |
| | `mutable c\_echoe : `bool`;` | `(*` | Echo ERASE (to erase previous character). | `*)` |
| | `mutable c\_echok : `bool`;` | `(*` | Echo KILL (to erase the current line). | `*)` |
| | `mutable c\_echonl : `bool`;` | `(*` | Echo NL even if c\_echo is not set. | `*)` |
| | `mutable c\_vintr : `char`;` | `(*` | Interrupt character (usually ctrl-C). | `*)` |
| | `mutable c\_vquit : `char`;` | `(*` | Quit character (usually ctrl-\). | `*)` |
| | `mutable c\_verase : `char`;` | `(*` | Erase character (usually DEL or ctrl-H). | `*)` |
| | `mutable c\_vkill : `char`;` | `(*` | Kill line character (usually ctrl-U). | `*)` |
| | `mutable c\_veof : `char`;` | `(*` | End-of-file character (usually ctrl-D). | `*)` |
| | `mutable c\_veol : `char`;` | `(*` | Alternate end-of-line char. (usually none). | `*)` |
| | `mutable c\_vmin : `int`;` | `(*` | Minimum number of characters to read before the read request is satisfied. | `*)` |
| | `mutable c\_vtime : `int`;` | `(*` | Maximum read wait (in 0.1s units). | `*)` |
| | `mutable c\_vstart : `char`;` | `(*` | Start character (usually ctrl-Q). | `*)` |
| | `mutable c\_vstop : `char`;` | `(*` | Stop character (usually ctrl-S). | `*)` |
`}`
```
val tcgetattr : file_descr -> terminal_io
```
Return the status of the terminal referred to by the given file descriptor.
* **Raises** `Invalid_argument` on Windows
```
type setattr_when =
```
| | |
| --- | --- |
| `|` | `TCSANOW` |
| `|` | `TCSADRAIN` |
| `|` | `TCSAFLUSH` |
```
val tcsetattr : file_descr -> setattr_when -> terminal_io -> unit
```
Set the status of the terminal referred to by the given file descriptor. The second argument indicates when the status change takes place: immediately (`TCSANOW`), when all pending output has been transmitted (`TCSADRAIN`), or after flushing all input that has been received but not read (`TCSAFLUSH`). `TCSADRAIN` is recommended when changing the output parameters; `TCSAFLUSH`, when changing the input parameters.
* **Raises** `Invalid_argument` on Windows
```
val tcsendbreak : file_descr -> int -> unit
```
Send a break condition on the given file descriptor. The second argument is the duration of the break, in 0.1s units; 0 means standard duration (0.25s).
* **Raises** `Invalid_argument` on Windows
```
val tcdrain : file_descr -> unit
```
Waits until all output written on the given file descriptor has been transmitted.
* **Raises** `Invalid_argument` on Windows
```
type flush_queue =
```
| | |
| --- | --- |
| `|` | `TCIFLUSH` |
| `|` | `TCOFLUSH` |
| `|` | `TCIOFLUSH` |
```
val tcflush : file_descr -> flush_queue -> unit
```
Discard data written on the given file descriptor but not yet transmitted, or data received but not yet read, depending on the second argument: `TCIFLUSH` flushes data received but not read, `TCOFLUSH` flushes data written but not transmitted, and `TCIOFLUSH` flushes both.
* **Raises** `Invalid_argument` on Windows
```
type flow_action =
```
| | |
| --- | --- |
| `|` | `TCOOFF` |
| `|` | `TCOON` |
| `|` | `TCIOFF` |
| `|` | `TCION` |
```
val tcflow : file_descr -> flow_action -> unit
```
Suspend or restart reception or transmission of data on the given file descriptor, depending on the second argument: `TCOOFF` suspends output, `TCOON` restarts output, `TCIOFF` transmits a STOP character to suspend input, and `TCION` transmits a START character to restart input.
* **Raises** `Invalid_argument` on Windows
```
val setsid : unit -> int
```
Put the calling process in a new session and detach it from its controlling terminal.
* **Raises** `Invalid_argument` on Windows
| programming_docs |
ocaml Functor Ephemeron.Kn.MakeSeeded Functor Ephemeron.Kn.MakeSeeded
===============================
```
module MakeSeeded: functor (H : Hashtbl.SeededHashedType) -> Ephemeron.SeededS with type key = H.t array
```
Functor building an implementation of a weak hash table. The seed is similar to the one of [`Hashtbl.MakeSeeded`](hashtbl.makeseeded).
| | | | | |
| --- | --- | --- | --- | --- |
| **Parameters:** |
| | | |
| --- | --- | --- |
| `H` | : | `[Hashtbl.SeededHashedType](hashtbl.seededhashedtype)` |
|
```
type key
```
```
type 'a t
```
```
val create : ?random:bool -> int -> 'a t
```
```
val clear : 'a t -> unit
```
```
val reset : 'a t -> unit
```
```
val copy : 'a t -> 'a t
```
```
val add : 'a t -> key -> 'a -> unit
```
```
val remove : 'a t -> key -> unit
```
```
val find : 'a t -> key -> 'a
```
```
val find_opt : 'a t -> key -> 'a option
```
```
val find_all : 'a t -> key -> 'a list
```
```
val replace : 'a t -> key -> 'a -> unit
```
```
val mem : 'a t -> key -> bool
```
```
val length : 'a t -> int
```
```
val stats : 'a t -> Hashtbl.statistics
```
```
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
```
```
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
```
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
```
val clean : 'a t -> unit
```
remove all dead bindings. Done automatically during automatic resizing.
```
val stats_alive : 'a t -> Hashtbl.statistics
```
same as [`Hashtbl.SeededS.stats`](hashtbl.seededs#VALstats) but only count the alive bindings
ocaml Module type Ephemeron.S Module type Ephemeron.S
=======================
```
module type S = sig .. end
```
The output signature of the functors [`Ephemeron.K1.Make`](ephemeron.k1.make) and [`Ephemeron.K2.Make`](ephemeron.k2.make). These hash tables are weak in the keys. If all the keys of a binding are alive the binding is kept, but if one of the keys of the binding is dead then the binding is removed.
Propose the same interface as usual hash table. However since the bindings are weak, even if `mem h k` is true, a subsequent `find h k` may raise `Not\_found` because the garbage collector can run between the two.
```
type key
```
```
type 'a t
```
```
val create : int -> 'a t
```
```
val clear : 'a t -> unit
```
```
val reset : 'a t -> unit
```
```
val copy : 'a t -> 'a t
```
```
val add : 'a t -> key -> 'a -> unit
```
```
val remove : 'a t -> key -> unit
```
```
val find : 'a t -> key -> 'a
```
```
val find_opt : 'a t -> key -> 'a option
```
```
val find_all : 'a t -> key -> 'a list
```
```
val replace : 'a t -> key -> 'a -> unit
```
```
val mem : 'a t -> key -> bool
```
```
val length : 'a t -> int
```
```
val stats : 'a t -> Hashtbl.statistics
```
```
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
```
```
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
```
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
```
val clean : 'a t -> unit
```
remove all dead bindings. Done automatically during automatic resizing.
```
val stats_alive : 'a t -> Hashtbl.statistics
```
same as [`Hashtbl.SeededS.stats`](hashtbl.seededs#VALstats) but only count the alive bindings
ocaml Module type MoreLabels.Map.OrderedType Module type MoreLabels.Map.OrderedType
======================================
```
module type OrderedType = sig .. end
```
Input signature of the functor [`MoreLabels.Map.Make`](morelabels.map.make).
```
type t
```
The type of the map keys.
```
val compare : t -> t -> int
```
A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`compare`](stdlib#VALcompare).
ocaml Module MoreLabels.Map Module MoreLabels.Map
=====================
```
module Map: sig .. end
```
Association tables over ordered types.
This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map.
For instance:
```
module IntPairs =
struct
type t = int * int
let compare (x0,y0) (x1,y1) =
match Stdlib.compare x0 x1 with
0 -> Stdlib.compare y0 y1
| c -> c
end
module PairsMap = Map.Make(IntPairs)
let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world")
```
This creates a new module `PairsMap`, with a new type `'a PairsMap.t` of maps from `int * int` to `'a`. In this example, `m` contains `string` values so its type is `string PairsMap.t`.
```
module type OrderedType = sig .. end
```
Input signature of the functor [`MoreLabels.Map.Make`](morelabels.map.make).
```
module type S = sig .. end
```
Output signature of the functor [`MoreLabels.Map.Make`](morelabels.map.make).
```
module Make: functor (Ord : OrderedType) -> S
with type key = Ord.t
and type 'a t = 'a Map.Make(Ord).t
```
Functor building an implementation of the map structure given a totally ordered type.
ocaml Module type MoreLabels.Hashtbl.SeededHashedType Module type MoreLabels.Hashtbl.SeededHashedType
===============================================
```
module type SeededHashedType = sig .. end
```
The input signature of the functor [`MoreLabels.Hashtbl.MakeSeeded`](morelabels.hashtbl.makeseeded).
* **Since** 4.00.0
```
type t
```
The type of the hashtable keys.
```
val equal : t -> t -> bool
```
The equality predicate used to compare keys.
```
val seeded_hash : int -> t -> int
```
A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`MoreLabels.Hashtbl.seeded_hash`](morelabels.hashtbl#VALseeded_hash) below.
ocaml Index of module types Index of module types
=====================
| |
| --- |
| H |
| [HashedType](morelabels.hashtbl.hashedtype) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | The input signature of the functor [`MoreLabels.Hashtbl.Make`](morelabels.hashtbl.make). |
| [HashedType](hashtbl.hashedtype) [[Hashtbl](hashtbl)] | The input signature of the functor [`Hashtbl.Make`](hashtbl.make). |
| I |
| [Immediate](sys.immediate64.immediate) [[Sys.Immediate64](sys.immediate64)] | |
| N |
| [Non\_immediate](sys.immediate64.non_immediate) [[Sys.Immediate64](sys.immediate64)] | |
| O |
| [OrderedType](set.orderedtype) [[Set](set)] | Input signature of the functor [`Set.Make`](set.make). |
| [OrderedType](morelabels.set.orderedtype) [[MoreLabels.Set](morelabels.set)] | Input signature of the functor [`MoreLabels.Set.Make`](morelabels.set.make). |
| [OrderedType](morelabels.map.orderedtype) [[MoreLabels.Map](morelabels.map)] | Input signature of the functor [`MoreLabels.Map.Make`](morelabels.map.make). |
| [OrderedType](map.orderedtype) [[Map](map)] | Input signature of the functor [`Map.Make`](map.make). |
| S |
| [S](weak.s) [[Weak](weak)] | The output signature of the functor [`Weak.Make`](weak.make). |
| [S](set.s) [[Set](set)] | Output signature of the functor [`Set.Make`](set.make). |
| [S](morelabels.set.s) [[MoreLabels.Set](morelabels.set)] | Output signature of the functor [`MoreLabels.Set.Make`](morelabels.set.make). |
| [S](morelabels.map.s) [[MoreLabels.Map](morelabels.map)] | Output signature of the functor [`MoreLabels.Map.Make`](morelabels.map.make). |
| [S](morelabels.hashtbl.s) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | The output signature of the functor [`MoreLabels.Hashtbl.Make`](morelabels.hashtbl.make). |
| [S](map.s) [[Map](map)] | Output signature of the functor [`Map.Make`](map.make). |
| [S](hashtbl.s) [[Hashtbl](hashtbl)] | The output signature of the functor [`Hashtbl.Make`](hashtbl.make). |
| [S](ephemeron.s) [[Ephemeron](ephemeron)] | The output signature of the functors [`Ephemeron.K1.Make`](ephemeron.k1.make) and [`Ephemeron.K2.Make`](ephemeron.k2.make). |
| [SeededHashedType](morelabels.hashtbl.seededhashedtype) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | The input signature of the functor [`MoreLabels.Hashtbl.MakeSeeded`](morelabels.hashtbl.makeseeded). |
| [SeededHashedType](hashtbl.seededhashedtype) [[Hashtbl](hashtbl)] | The input signature of the functor [`Hashtbl.MakeSeeded`](hashtbl.makeseeded). |
| [SeededS](morelabels.hashtbl.seededs) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | The output signature of the functor [`MoreLabels.Hashtbl.MakeSeeded`](morelabels.hashtbl.makeseeded). |
| [SeededS](hashtbl.seededs) [[Hashtbl](hashtbl)] | The output signature of the functor [`Hashtbl.MakeSeeded`](hashtbl.makeseeded). |
| [SeededS](ephemeron.seededs) [[Ephemeron](ephemeron)] | The output signature of the functors [`Ephemeron.K1.MakeSeeded`](ephemeron.k1.makeseeded) and [`Ephemeron.K2.MakeSeeded`](ephemeron.k2.makeseeded). |
ocaml Module type Sys.Immediate64.Non_immediate Module type Sys.Immediate64.Non\_immediate
==========================================
```
module type Non_immediate = sig .. end
```
```
type t
```
ocaml Module type Hashtbl.SeededHashedType Module type Hashtbl.SeededHashedType
====================================
```
module type SeededHashedType = sig .. end
```
The input signature of the functor [`Hashtbl.MakeSeeded`](hashtbl.makeseeded).
* **Since** 4.00.0
```
type t
```
The type of the hashtable keys.
```
val equal : t -> t -> bool
```
The equality predicate used to compare keys.
```
val seeded_hash : int -> t -> int
```
A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](hashtbl#VALseeded_hash) below.
ocaml Module Bigarray.Array3 Module Bigarray.Array3
======================
```
module Array3: sig .. end
```
Three-dimensional arrays. The `Array3` structure provides operations similar to those of [`Bigarray.Genarray`](bigarray.genarray), but specialized to the case of three-dimensional arrays.
```
type ('a, 'b, 'c) t
```
The type of three-dimensional Bigarrays whose elements have OCaml type `'a`, representation kind `'b`, and memory layout `'c`.
```
val create : ('a, 'b) Bigarray.kind -> 'c Bigarray.layout -> int -> int -> int -> ('a, 'b, 'c) t
```
`Array3.create kind layout dim1 dim2 dim3` returns a new Bigarray of three dimensions, whose size is `dim1` in the first dimension, `dim2` in the second dimension, and `dim3` in the third. `kind` and `layout` determine the array element kind and the array layout as described for [`Bigarray.Genarray.create`](bigarray.genarray#VALcreate).
```
val init : ('a, 'b) Bigarray.kind -> 'c Bigarray.layout -> int -> int -> int -> (int -> int -> int -> 'a) -> ('a, 'b, 'c) t
```
`Array3.init kind layout dim1 dim2 dim3 f` returns a new Bigarray `b` of three dimensions, whose size is `dim1` in the first dimension, `dim2` in the second dimension, and `dim3` in the third. `kind` and `layout` determine the array element kind and the array layout as described for [`Bigarray.Genarray.create`](bigarray.genarray#VALcreate).
Each element `Array3.get b i j k` of the array is initialized to the result of `f i j k`.
In other words, `Array3.init kind layout dim1 dim2 dim3 f` tabulates the results of `f` applied to the indices of a new Bigarray whose layout is described by `kind`, `layout`, `dim1`, `dim2` and `dim3`.
* **Since** 4.12.0
```
val dim1 : ('a, 'b, 'c) t -> int
```
Return the first dimension of the given three-dimensional Bigarray.
```
val dim2 : ('a, 'b, 'c) t -> int
```
Return the second dimension of the given three-dimensional Bigarray.
```
val dim3 : ('a, 'b, 'c) t -> int
```
Return the third dimension of the given three-dimensional Bigarray.
```
val kind : ('a, 'b, 'c) t -> ('a, 'b) Bigarray.kind
```
Return the kind of the given Bigarray.
```
val layout : ('a, 'b, 'c) t -> 'c Bigarray.layout
```
Return the layout of the given Bigarray.
```
val change_layout : ('a, 'b, 'c) t -> 'd Bigarray.layout -> ('a, 'b, 'd) t
```
`Array3.change_layout a layout` returns a Bigarray with the specified `layout`, sharing the data with `a` (and hence having the same dimensions as `a`). No copying of elements is involved: the new array and the original array share the same storage space. The dimensions are reversed, such that `get v [| a; b; c |]` in C layout becomes `get v [| c+1; b+1; a+1 |]` in Fortran layout.
* **Since** 4.06.0
```
val size_in_bytes : ('a, 'b, 'c) t -> int
```
`size_in_bytes a` is the number of elements in `a` multiplied by `a`'s [`Bigarray.kind_size_in_bytes`](bigarray#VALkind_size_in_bytes).
* **Since** 4.03.0
```
val get : ('a, 'b, 'c) t -> int -> int -> int -> 'a
```
`Array3.get a x y z`, also written `a.{x,y,z}`, returns the element of `a` at coordinates (`x`, `y`, `z`). `x`, `y` and `z` must be within the bounds of `a`, as described for [`Bigarray.Genarray.get`](bigarray.genarray#VALget); otherwise, `Invalid\_argument` is raised.
```
val set : ('a, 'b, 'c) t -> int -> int -> int -> 'a -> unit
```
`Array3.set a x y v`, or alternatively `a.{x,y,z} <- v`, stores the value `v` at coordinates (`x`, `y`, `z`) in `a`. `x`, `y` and `z` must be within the bounds of `a`, as described for [`Bigarray.Genarray.set`](bigarray.genarray#VALset); otherwise, `Invalid\_argument` is raised.
```
val sub_left : ('a, 'b, Bigarray.c_layout) t -> int -> int -> ('a, 'b, Bigarray.c_layout) t
```
Extract a three-dimensional sub-array of the given three-dimensional Bigarray by restricting the first dimension. See [`Bigarray.Genarray.sub_left`](bigarray.genarray#VALsub_left) for more details. `Array3.sub_left` applies only to arrays with C layout.
```
val sub_right : ('a, 'b, Bigarray.fortran_layout) t -> int -> int -> ('a, 'b, Bigarray.fortran_layout) t
```
Extract a three-dimensional sub-array of the given three-dimensional Bigarray by restricting the second dimension. See [`Bigarray.Genarray.sub_right`](bigarray.genarray#VALsub_right) for more details. `Array3.sub_right` applies only to arrays with Fortran layout.
```
val slice_left_1 : ('a, 'b, Bigarray.c_layout) t -> int -> int -> ('a, 'b, Bigarray.c_layout) Bigarray.Array1.t
```
Extract a one-dimensional slice of the given three-dimensional Bigarray by fixing the first two coordinates. The integer parameters are the coordinates of the slice to extract. See [`Bigarray.Genarray.slice_left`](bigarray.genarray#VALslice_left) for more details. `Array3.slice_left_1` applies only to arrays with C layout.
```
val slice_right_1 : ('a, 'b, Bigarray.fortran_layout) t -> int -> int -> ('a, 'b, Bigarray.fortran_layout) Bigarray.Array1.t
```
Extract a one-dimensional slice of the given three-dimensional Bigarray by fixing the last two coordinates. The integer parameters are the coordinates of the slice to extract. See [`Bigarray.Genarray.slice_right`](bigarray.genarray#VALslice_right) for more details. `Array3.slice_right_1` applies only to arrays with Fortran layout.
```
val slice_left_2 : ('a, 'b, Bigarray.c_layout) t -> int -> ('a, 'b, Bigarray.c_layout) Bigarray.Array2.t
```
Extract a two-dimensional slice of the given three-dimensional Bigarray by fixing the first coordinate. The integer parameter is the first coordinate of the slice to extract. See [`Bigarray.Genarray.slice_left`](bigarray.genarray#VALslice_left) for more details. `Array3.slice_left_2` applies only to arrays with C layout.
```
val slice_right_2 : ('a, 'b, Bigarray.fortran_layout) t -> int -> ('a, 'b, Bigarray.fortran_layout) Bigarray.Array2.t
```
Extract a two-dimensional slice of the given three-dimensional Bigarray by fixing the last coordinate. The integer parameter is the coordinate of the slice to extract. See [`Bigarray.Genarray.slice_right`](bigarray.genarray#VALslice_right) for more details. `Array3.slice_right_2` applies only to arrays with Fortran layout.
```
val blit : ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
```
Copy the first Bigarray to the second Bigarray. See [`Bigarray.Genarray.blit`](bigarray.genarray#VALblit) for more details.
```
val fill : ('a, 'b, 'c) t -> 'a -> unit
```
Fill the given Bigarray with the given value. See [`Bigarray.Genarray.fill`](bigarray.genarray#VALfill) for more details.
```
val of_array : ('a, 'b) Bigarray.kind -> 'c Bigarray.layout -> 'a array array array -> ('a, 'b, 'c) t
```
Build a three-dimensional Bigarray initialized from the given array of arrays of arrays.
```
val unsafe_get : ('a, 'b, 'c) t -> int -> int -> int -> 'a
```
Like [`Bigarray.Array3.get`](bigarray.array3#VALget), but bounds checking is not always performed.
```
val unsafe_set : ('a, 'b, 'c) t -> int -> int -> int -> 'a -> unit
```
Like [`Bigarray.Array3.set`](bigarray.array3#VALset), but bounds checking is not always performed.
ocaml Module Effect Module Effect
=============
```
module Effect: sig .. end
```
* **Alert unstable.** The Effect interface may change in incompatible ways in the future.
Effects.
See 'Language extensions/Effect handlers' section in the manual.
```
type '_ t = ..
```
The type of effects.
```
exception Unhandled : 'a t -> exn
```
`Unhandled e` is raised when effect `e` is performed and there is no handler for it.
```
exception Continuation_already_resumed
```
Exception raised when a continuation is continued or discontinued more than once.
```
val perform : 'a t -> 'a
```
`perform e` performs an effect `e`.
* **Raises** `Unhandled` if there is no handler for `e`.
```
module Deep: sig .. end
```
```
module Shallow: sig .. end
```
ocaml Functor Hashtbl.MakeSeeded Functor Hashtbl.MakeSeeded
==========================
```
module MakeSeeded: functor (H : SeededHashedType) -> SeededS with type key = H.t
```
Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](hashtbl#VALrandomize)).
* **Since** 4.00.0
| | | | | |
| --- | --- | --- | --- | --- |
| **Parameters:** |
| | | |
| --- | --- | --- |
| `H` | : | `[SeededHashedType](hashtbl.seededhashedtype)` |
|
```
type key
```
```
type 'a t
```
```
val create : ?random:bool -> int -> 'a t
```
```
val clear : 'a t -> unit
```
```
val reset : 'a t -> unit
```
```
val copy : 'a t -> 'a t
```
```
val add : 'a t -> key -> 'a -> unit
```
```
val remove : 'a t -> key -> unit
```
```
val find : 'a t -> key -> 'a
```
```
val find_opt : 'a t -> key -> 'a option
```
* **Since** 4.05.0
```
val find_all : 'a t -> key -> 'a list
```
```
val replace : 'a t -> key -> 'a -> unit
```
```
val mem : 'a t -> key -> bool
```
```
val iter : (key -> 'a -> unit) -> 'a t -> unit
```
```
val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit
```
* **Since** 4.03.0
```
val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
```
```
val length : 'a t -> int
```
```
val stats : 'a t -> Hashtbl.statistics
```
```
val to_seq : 'a t -> (key * 'a) Seq.t
```
* **Since** 4.07
```
val to_seq_keys : 'a t -> key Seq.t
```
* **Since** 4.07
```
val to_seq_values : 'a t -> 'a Seq.t
```
* **Since** 4.07
```
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
```
* **Since** 4.07
```
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
```
* **Since** 4.07
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
* **Since** 4.07
| programming_docs |
ocaml Module Unit Module Unit
===========
```
module Unit: sig .. end
```
Unit values.
* **Since** 4.08
The unit type
-------------
```
type t = unit =
```
| | |
| --- | --- |
| `|` | `()` |
The unit type.
The constructor `()` is included here so that it has a path, but it is not intended to be used in user-defined data types.
```
val equal : t -> t -> bool
```
`equal u1 u2` is `true`.
```
val compare : t -> t -> int
```
`compare u1 u2` is `0`.
```
val to_string : t -> string
```
`to_string b` is `"()"`.
ocaml Module Semaphore.Binary Module Semaphore.Binary
=======================
```
module Binary: sig .. end
```
```
type t
```
The type of binary semaphores.
```
val make : bool -> t
```
`make b` returns a new binary semaphore. If `b` is `true`, the initial value of the semaphore is 1, meaning "available". If `b` is `false`, the initial value of the semaphore is 0, meaning "unavailable".
```
val release : t -> unit
```
`release s` sets the value of semaphore `s` to 1, putting it in the "available" state. If other threads are waiting on `s`, one of them is restarted.
```
val acquire : t -> unit
```
`acquire s` blocks the calling thread until the semaphore `s` has value 1 (is available), then atomically sets it to 0 and returns.
```
val try_acquire : t -> bool
```
`try_acquire s` immediately returns `false` if the semaphore `s` has value 0. If `s` has value 1, its value is atomically set to 0 and `try_acquire s` returns `true`.
ocaml Module Seq Module Seq
==========
```
module Seq: sig .. end
```
Sequences.
A sequence of type `'a Seq.t` can be thought of as a **delayed list**, that is, a list whose elements are computed only when they are demanded by a consumer. This allows sequences to be produced and transformed lazily (one element at a time) rather than eagerly (all elements at once). This also allows constructing conceptually infinite sequences.
The type `'a Seq.t` is defined as a synonym for `unit -> 'a Seq.node`. This is a function type: therefore, it is opaque. The consumer can **query** a sequence in order to request the next element (if there is one), but cannot otherwise inspect the sequence in any way.
Because it is opaque, the type `'a Seq.t` does *not* reveal whether a sequence is:
* **persistent**, which means that the sequence can be used as many times as desired, producing the same elements every time, just like an immutable list; or
* **ephemeral**, which means that the sequence is not persistent. Querying an ephemeral sequence might have an observable side effect, such as incrementing a mutable counter. As a common special case, an ephemeral sequence can be **affine**, which means that it must be queried at most once.
It also does *not* reveal whether the elements of the sequence are:
* **pre-computed and stored** in memory, which means that querying the sequence is cheap;
* **computed when first demanded and then stored** in memory, which means that querying the sequence once can be expensive, but querying the same sequence again is cheap; or
* **re-computed every time they are demanded**, which may or may not be cheap.
It is up to the programmer to keep these distinctions in mind so as to understand the time and space requirements of sequences.
For the sake of simplicity, most of the documentation that follows is written under the implicit assumption that the sequences at hand are persistent. We normally do not point out *when* or *how many times* each function is invoked, because that would be too verbose. For instance, in the description of `map`, we write: "if `xs` is the sequence `x0; x1; ...` then `map f xs` is the sequence `f x0; f x1; ...`". If we wished to be more explicit, we could point out that the transformation takes place on demand: that is, the elements of `map f xs` are computed only when they are demanded. In other words, the definition `let ys = map f xs` terminates immediately and does not invoke `f`. The function call `f x0` takes place only when the first element of `ys` is demanded, via the function call `ys()`. Furthermore, calling `ys()` twice causes `f x0` to be called twice as well. If one wishes for `f` to be applied at most once to each element of `xs`, even in scenarios where `ys` is queried more than once, then one should use `let ys = memoize (map f xs)`.
As a general rule, the functions that build sequences, such as `map`, `filter`, `scan`, `take`, etc., produce sequences whose elements are computed only on demand. The functions that eagerly consume sequences, such as `is_empty`, `find`, `length`, `iter`, `fold_left`, etc., are the functions that force computation to take place.
When possible, we recommend using sequences rather than dispensers (functions of type `unit -> 'a option` that produce elements upon demand). Whereas sequences can be persistent or ephemeral, dispensers are always ephemeral, and are typically more difficult to work with than sequences. Two conversion functions, [`Seq.to_dispenser`](seq#VALto_dispenser) and [`Seq.of_dispenser`](seq#VALof_dispenser), are provided.
* **Since** 4.07
```
type 'a t = unit -> 'a node
```
A sequence `xs` of type `'a t` is a delayed list of elements of type `'a`. Such a sequence is queried by performing a function application `xs()`. This function application returns a node, allowing the caller to determine whether the sequence is empty or nonempty, and in the latter case, to obtain its head and tail.
```
type 'a node =
```
| | |
| --- | --- |
| `|` | `Nil` |
| `|` | `Cons of `'a * 'a [t](seq#TYPEt)`` |
A node is either `Nil`, which means that the sequence is empty, or `Cons (x, xs)`, which means that `x` is the first element of the sequence and that `xs` is the remainder of the sequence.
Consuming sequences
-------------------
The functions in this section consume their argument, a sequence, either partially or completely:
* `is_empty` and `uncons` consume the sequence down to depth 1. That is, they demand the first argument of the sequence, if there is one.
* `iter`, `fold_left`, `length`, etc., consume the sequence all the way to its end. They terminate only if the sequence is finite.
* `for_all`, `exists`, `find`, etc. consume the sequence down to a certain depth, which is a priori unpredictable.
Similarly, among the functions that consume two sequences, one can distinguish two groups:
* `iter2` and `fold_left2` consume both sequences all the way to the end, provided the sequences have the same length.
* `for_all2`, `exists2`, `equal`, `compare` consume the sequences down to a certain depth, which is a priori unpredictable.
The functions that consume two sequences can be applied to two sequences of distinct lengths: in that case, the excess elements in the longer sequence are ignored. (It may be the case that one excess element is demanded, even though this element is not used.)
None of the functions in this section is lazy. These functions are consumers: they force some computation to take place.
```
val is_empty : 'a t -> bool
```
`is_empty xs` determines whether the sequence `xs` is empty.
It is recommended that the sequence `xs` be persistent. Indeed, `is_empty xs` demands the head of the sequence `xs`, so, if `xs` is ephemeral, it may be the case that `xs` cannot be used any more after this call has taken place.
* **Since** 4.14
```
val uncons : 'a t -> ('a * 'a t) option
```
If `xs` is empty, then `uncons xs` is `None`.
If `xs` is nonempty, then `uncons xs` is `Some (x, ys)` where `x` is the head of the sequence and `ys` its tail.
* **Since** 4.14
```
val length : 'a t -> int
```
`length xs` is the length of the sequence `xs`.
The sequence `xs` must be finite.
* **Since** 4.14
```
val iter : ('a -> unit) -> 'a t -> unit
```
`iter f xs` invokes `f x` successively for every element `x` of the sequence `xs`, from left to right.
It terminates only if the sequence `xs` is finite.
```
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b t -> 'a
```
`fold_left f _ xs` invokes `f _ x` successively for every element `x` of the sequence `xs`, from left to right.
An accumulator of type `'a` is threaded through the calls to `f`.
It terminates only if the sequence `xs` is finite.
```
val iteri : (int -> 'a -> unit) -> 'a t -> unit
```
`iteri f xs` invokes `f i x` successively for every element `x` located at index `i` in the sequence `xs`.
It terminates only if the sequence `xs` is finite.
`iteri f xs` is equivalent to `iter (fun (i, x) -> f i x) (zip (ints 0) xs)`.
* **Since** 4.14
```
val fold_lefti : ('b -> int -> 'a -> 'b) -> 'b -> 'a t -> 'b
```
`fold_lefti f _ xs` invokes `f _ i x` successively for every element `x` located at index `i` of the sequence `xs`.
An accumulator of type `'b` is threaded through the calls to `f`.
It terminates only if the sequence `xs` is finite.
`fold_lefti f accu xs` is equivalent to `fold_left (fun accu (i, x) -> f accu i x) accu (zip (ints 0) xs)`.
* **Since** 4.14
```
val for_all : ('a -> bool) -> 'a t -> bool
```
`for_all p xs` determines whether all elements `x` of the sequence `xs` satisfy `p x`.
The sequence `xs` must be finite.
* **Since** 4.14
```
val exists : ('a -> bool) -> 'a t -> bool
```
`exists xs p` determines whether at least one element `x` of the sequence `xs` satisfies `p x`.
The sequence `xs` must be finite.
* **Since** 4.14
```
val find : ('a -> bool) -> 'a t -> 'a option
```
`find p xs` returns `Some x`, where `x` is the first element of the sequence `xs` that satisfies `p x`, if there is such an element.
It returns `None` if there is no such element.
The sequence `xs` must be finite.
* **Since** 4.14
```
val find_map : ('a -> 'b option) -> 'a t -> 'b option
```
`find_map f xs` returns `Some y`, where `x` is the first element of the sequence `xs` such that `f x = Some _`, if there is such an element, and where `y` is defined by `f x = Some y`.
It returns `None` if there is no such element.
The sequence `xs` must be finite.
* **Since** 4.14
```
val iter2 : ('a -> 'b -> unit) -> 'a t -> 'b t -> unit
```
`iter2 f xs ys` invokes `f x y` successively for every pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys`.
If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
Iteration terminates only if at least one of the sequences `xs` and `ys` is finite.
`iter2 f xs ys` is equivalent to `iter (fun (x, y) -> f x y) (zip xs ys)`.
* **Since** 4.14
```
val fold_left2 : ('a -> 'b -> 'c -> 'a) -> 'a -> 'b t -> 'c t -> 'a
```
`fold_left2 f _ xs ys` invokes `f _ x y` successively for every pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys`.
An accumulator of type `'a` is threaded through the calls to `f`.
If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
Iteration terminates only if at least one of the sequences `xs` and `ys` is finite.
`fold_left2 f accu xs ys` is equivalent to `fold_left (fun accu (x, y) -> f accu x y) (zip xs ys)`.
* **Since** 4.14
```
val for_all2 : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool
```
`for_all2 p xs ys` determines whether all pairs `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys` satisfy `p x y`.
If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. In particular, if `xs` or `ys` is empty, then `for_all2 p xs ys` is true. This is where `for_all2` and `equal` differ: `equal eq xs ys` can be true only if `xs` and `ys` have the same length.
At least one of the sequences `xs` and `ys` must be finite.
`for_all2 p xs ys` is equivalent to `for_all (fun b -> b) (map2 p xs ys)`.
* **Since** 4.14
```
val exists2 : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool
```
`exists2 p xs ys` determines whether some pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys` satisfies `p x y`.
If the sequences `xs` and `ys` have different lengths, then iteration must stop as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
At least one of the sequences `xs` and `ys` must be finite.
`exists2 p xs ys` is equivalent to `exists (fun b -> b) (map2 p xs ys)`.
* **Since** 4.14
```
val equal : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool
```
Provided the function `eq` defines an equality on elements, `equal eq xs ys` determines whether the sequences `xs` and `ys` are pointwise equal.
At least one of the sequences `xs` and `ys` must be finite.
* **Since** 4.14
```
val compare : ('a -> 'b -> int) -> 'a t -> 'b t -> int
```
Provided the function `cmp` defines a preorder on elements, `compare cmp xs ys` compares the sequences `xs` and `ys` according to the lexicographic preorder.
For more details on comparison functions, see [`Array.sort`](array#VALsort).
At least one of the sequences `xs` and `ys` must be finite.
* **Since** 4.14
Constructing sequences
----------------------
The functions in this section are lazy: that is, they return sequences whose elements are computed only when demanded.
```
val empty : 'a t
```
`empty` is the empty sequence. It has no elements. Its length is 0.
```
val return : 'a -> 'a t
```
`return x` is the sequence whose sole element is `x`. Its length is 1.
```
val cons : 'a -> 'a t -> 'a t
```
`cons x xs` is the sequence that begins with the element `x`, followed with the sequence `xs`.
Writing `cons (f()) xs` causes the function call `f()` to take place immediately. For this call to be delayed until the sequence is queried, one must instead write `(fun () -> Cons(f(), xs))`.
* **Since** 4.11
```
val init : int -> (int -> 'a) -> 'a t
```
`init n f` is the sequence `f 0; f 1; ...; f (n-1)`.
`n` must be nonnegative.
If desired, the infinite sequence `f 0; f 1; ...` can be defined as `map f (ints 0)`.
* **Since** 4.14
* **Raises** `Invalid_argument` if `n` is negative.
```
val unfold : ('b -> ('a * 'b) option) -> 'b -> 'a t
```
`unfold` constructs a sequence out of a step function and an initial state.
If `f u` is `None` then `unfold f u` is the empty sequence. If `f u` is `Some (x, u')` then `unfold f u` is the nonempty sequence `cons x (unfold f u')`.
For example, `unfold (function [] -> None | h :: t -> Some (h, t)) l` is equivalent to `List.to_seq l`.
* **Since** 4.11
```
val repeat : 'a -> 'a t
```
`repeat x` is the infinite sequence where the element `x` is repeated indefinitely.
`repeat x` is equivalent to `cycle (return x)`.
* **Since** 4.14
```
val forever : (unit -> 'a) -> 'a t
```
`forever f` is an infinite sequence where every element is produced (on demand) by the function call `f()`.
For instance, `forever Random.bool` is an infinite sequence of random bits.
`forever f` is equivalent to `map f (repeat ())`.
* **Since** 4.14
```
val cycle : 'a t -> 'a t
```
`cycle xs` is the infinite sequence that consists of an infinite number of repetitions of the sequence `xs`.
If `xs` is an empty sequence, then `cycle xs` is empty as well.
Consuming (a prefix of) the sequence `cycle xs` once can cause the sequence `xs` to be consumed more than once. Therefore, `xs` must be persistent.
* **Since** 4.14
```
val iterate : ('a -> 'a) -> 'a -> 'a t
```
`iterate f x` is the infinite sequence whose elements are `x`, `f x`, `f (f x)`, and so on.
In other words, it is the orbit of the function `f`, starting at `x`.
* **Since** 4.14
Transforming sequences
----------------------
The functions in this section are lazy: that is, they return sequences whose elements are computed only when demanded.
```
val map : ('a -> 'b) -> 'a t -> 'b t
```
`map f xs` is the image of the sequence `xs` through the transformation `f`.
If `xs` is the sequence `x0; x1; ...` then `map f xs` is the sequence `f x0; f x1; ...`.
```
val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t
```
`mapi` is analogous to `map`, but applies the function `f` to an index and an element.
`mapi f xs` is equivalent to `map2 f (ints 0) xs`.
* **Since** 4.14
```
val filter : ('a -> bool) -> 'a t -> 'a t
```
`filter p xs` is the sequence of the elements `x` of `xs` that satisfy `p x`.
In other words, `filter p xs` is the sequence `xs`, deprived of the elements `x` such that `p x` is false.
```
val filter_map : ('a -> 'b option) -> 'a t -> 'b t
```
`filter_map f xs` is the sequence of the elements `y` such that `f x = Some y`, where `x` ranges over `xs`.
`filter_map f xs` is equivalent to `map Option.get (filter Option.is_some (map f xs))`.
```
val scan : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b t
```
If `xs` is a sequence `[x0; x1; x2; ...]`, then `scan f a0 xs` is a sequence of accumulators `[a0; a1; a2; ...]` where `a1` is `f a0 x0`, `a2` is `f a1 x1`, and so on.
Thus, `scan f a0 xs` is conceptually related to `fold_left f a0 xs`. However, instead of performing an eager iteration and immediately returning the final accumulator, it returns a sequence of accumulators.
For instance, `scan (+) 0` transforms a sequence of integers into the sequence of its partial sums.
If `xs` has length `n` then `scan f a0 xs` has length `n+1`.
* **Since** 4.14
```
val take : int -> 'a t -> 'a t
```
`take n xs` is the sequence of the first `n` elements of `xs`.
If `xs` has fewer than `n` elements, then `take n xs` is equivalent to `xs`.
`n` must be nonnegative.
* **Since** 4.14
* **Raises** `Invalid_argument` if `n` is negative.
```
val drop : int -> 'a t -> 'a t
```
`drop n xs` is the sequence `xs`, deprived of its first `n` elements.
If `xs` has fewer than `n` elements, then `drop n xs` is empty.
`n` must be nonnegative.
`drop` is lazy: the first `n+1` elements of the sequence `xs` are demanded only when the first element of `drop n xs` is demanded. For this reason, `drop 1 xs` is *not* equivalent to `tail xs`, which queries `xs` immediately.
* **Since** 4.14
* **Raises** `Invalid_argument` if `n` is negative.
```
val take_while : ('a -> bool) -> 'a t -> 'a t
```
`take_while p xs` is the longest prefix of the sequence `xs` where every element `x` satisfies `p x`.
* **Since** 4.14
```
val drop_while : ('a -> bool) -> 'a t -> 'a t
```
`drop_while p xs` is the sequence `xs`, deprived of the prefix `take_while p xs`.
* **Since** 4.14
```
val group : ('a -> 'a -> bool) -> 'a t -> 'a t t
```
Provided the function `eq` defines an equality on elements, `group eq xs` is the sequence of the maximal runs of adjacent duplicate elements of the sequence `xs`.
Every element of `group eq xs` is a nonempty sequence of equal elements.
The concatenation `concat (group eq xs)` is equal to `xs`.
Consuming `group eq xs`, and consuming the sequences that it contains, can cause `xs` to be consumed more than once. Therefore, `xs` must be persistent.
* **Since** 4.14
```
val memoize : 'a t -> 'a t
```
The sequence `memoize xs` has the same elements as the sequence `xs`.
Regardless of whether `xs` is ephemeral or persistent, `memoize xs` is persistent: even if it is queried several times, `xs` is queried at most once.
The construction of the sequence `memoize xs` internally relies on suspensions provided by the module [`Lazy`](lazy). These suspensions are *not* thread-safe. Therefore, the sequence `memoize xs` must *not* be queried by multiple threads concurrently.
* **Since** 4.14
```
exception Forced_twice
```
This exception is raised when a sequence returned by [`Seq.once`](seq#VALonce) (or a suffix of it) is queried more than once.
* **Since** 4.14
```
val once : 'a t -> 'a t
```
The sequence `once xs` has the same elements as the sequence `xs`.
Regardless of whether `xs` is ephemeral or persistent, `once xs` is an ephemeral sequence: it can be queried at most once. If it (or a suffix of it) is queried more than once, then the exception `Forced\_twice` is raised. This can be useful, while debugging or testing, to ensure that a sequence is consumed at most once.
* **Since** 4.14
* **Raises** `Forced_twice` if `once xs`, or a suffix of it, is queried more than once.
```
val transpose : 'a t t -> 'a t t
```
If `xss` is a matrix (a sequence of rows), then `transpose xss` is the sequence of the columns of the matrix `xss`.
The rows of the matrix `xss` are not required to have the same length.
The matrix `xss` is not required to be finite (in either direction).
The matrix `xss` must be persistent.
* **Since** 4.14
Combining sequences
-------------------
```
val append : 'a t -> 'a t -> 'a t
```
`append xs ys` is the concatenation of the sequences `xs` and `ys`.
Its elements are the elements of `xs`, followed by the elements of `ys`.
* **Since** 4.11
```
val concat : 'a t t -> 'a t
```
If `xss` is a sequence of sequences, then `concat xss` is its concatenation.
If `xss` is the sequence `xs0; xs1; ...` then `concat xss` is the sequence `xs0 @ xs1 @ ...`.
* **Since** 4.13
```
val flat_map : ('a -> 'b t) -> 'a t -> 'b t
```
`flat_map f xs` is equivalent to `concat (map f xs)`.
```
val concat_map : ('a -> 'b t) -> 'a t -> 'b t
```
`concat_map f xs` is equivalent to `concat (map f xs)`.
`concat_map` is an alias for `flat_map`.
* **Since** 4.13
```
val zip : 'a t -> 'b t -> ('a * 'b) t
```
`zip xs ys` is the sequence of pairs `(x, y)` drawn synchronously from the sequences `xs` and `ys`.
If the sequences `xs` and `ys` have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
`zip xs ys` is equivalent to `map2 (fun a b -> (a, b)) xs ys`.
* **Since** 4.14
```
val map2 : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t
```
`map2 f xs ys` is the sequence of the elements `f x y`, where the pairs `(x, y)` are drawn synchronously from the sequences `xs` and `ys`.
If the sequences `xs` and `ys` have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
`map2 f xs ys` is equivalent to `map (fun (x, y) -> f x y) (zip xs ys)`.
* **Since** 4.14
```
val interleave : 'a t -> 'a t -> 'a t
```
`interleave xs ys` is the sequence that begins with the first element of `xs`, continues with the first element of `ys`, and so on.
When one of the sequences `xs` and `ys` is exhausted, `interleave xs ys` continues with the rest of the other sequence.
* **Since** 4.14
```
val sorted_merge : ('a -> 'a -> int) -> 'a t -> 'a t -> 'a t
```
If the sequences `xs` and `ys` are sorted according to the total preorder `cmp`, then `sorted_merge cmp xs ys` is the sorted sequence obtained by merging the sequences `xs` and `ys`.
For more details on comparison functions, see [`Array.sort`](array#VALsort).
* **Since** 4.14
```
val product : 'a t -> 'b t -> ('a * 'b) t
```
`product xs ys` is the Cartesian product of the sequences `xs` and `ys`.
For every element `x` of `xs` and for every element `y` of `ys`, the pair `(x, y)` appears once as an element of `product xs ys`.
The order in which the pairs appear is unspecified.
The sequences `xs` and `ys` are not required to be finite.
The sequences `xs` and `ys` must be persistent.
* **Since** 4.14
```
val map_product : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t
```
The sequence `map_product f xs ys` is the image through `f` of the Cartesian product of the sequences `xs` and `ys`.
For every element `x` of `xs` and for every element `y` of `ys`, the element `f x y` appears once as an element of `map_product f xs ys`.
The order in which these elements appear is unspecified.
The sequences `xs` and `ys` are not required to be finite.
The sequences `xs` and `ys` must be persistent.
`map_product f xs ys` is equivalent to `map (fun (x, y) -> f x y) (product xs ys)`.
* **Since** 4.14
Splitting a sequence into two sequences
---------------------------------------
```
val unzip : ('a * 'b) t -> 'a t * 'b t
```
`unzip` transforms a sequence of pairs into a pair of sequences.
`unzip xs` is equivalent to `(map fst xs, map snd xs)`.
Querying either of the sequences returned by `unzip xs` causes `xs` to be queried. Therefore, querying both of them causes `xs` to be queried twice. Thus, `xs` must be persistent and cheap. If that is not the case, use `unzip (memoize xs)`.
* **Since** 4.14
```
val split : ('a * 'b) t -> 'a t * 'b t
```
`split` is an alias for `unzip`.
* **Since** 4.14
```
val partition_map : ('a -> ('b, 'c) Either.t) -> 'a t -> 'b t * 'c t
```
`partition_map f xs` returns a pair of sequences `(ys, zs)`, where:
* `ys` is the sequence of the elements `y` such that `f x = Left y`, where `x` ranges over `xs`;
* `zs` is the sequence of the elements `z` such that `f x = Right z`, where `x` ranges over `xs`.
`partition_map f xs` is equivalent to a pair of `filter_map Either.find_left (map f xs)` and `filter_map Either.find_right (map f xs)`.
Querying either of the sequences returned by `partition_map f xs` causes `xs` to be queried. Therefore, querying both of them causes `xs` to be queried twice. Thus, `xs` must be persistent and cheap. If that is not the case, use `partition_map f (memoize xs)`.
* **Since** 4.14
```
val partition : ('a -> bool) -> 'a t -> 'a t * 'a t
```
`partition p xs` returns a pair of the subsequence of the elements of `xs` that satisfy `p` and the subsequence of the elements of `xs` that do not satisfy `p`.
`partition p xs` is equivalent to `filter p xs, filter (fun x -> not (p x)) xs`.
Consuming both of the sequences returned by `partition p xs` causes `xs` to be consumed twice and causes the function `f` to be applied twice to each element of the list. Therefore, `f` should be pure and cheap. Furthermore, `xs` should be persistent and cheap. If that is not the case, use `partition p (memoize xs)`.
* **Since** 4.14
Converting between sequences and dispensers
-------------------------------------------
A dispenser is a representation of a sequence as a function of type `unit -> 'a option`. Every time this function is invoked, it returns the next element of the sequence. When there are no more elements, it returns `None`. A dispenser has mutable internal state, therefore is ephemeral: the sequence that it represents can be consumed at most once.
```
val of_dispenser : (unit -> 'a option) -> 'a t
```
`of_dispenser it` is the sequence of the elements produced by the dispenser `it`. It is an ephemeral sequence: it can be consumed at most once. If a persistent sequence is needed, use `memoize (of_dispenser it)`.
* **Since** 4.14
```
val to_dispenser : 'a t -> unit -> 'a option
```
`to_dispenser xs` is a fresh dispenser on the sequence `xs`.
This dispenser has mutable internal state, which is not protected by a lock; so, it must not be used by several threads concurrently.
* **Since** 4.14
Sequences of integers
---------------------
```
val ints : int -> int t
```
`ints i` is the infinite sequence of the integers beginning at `i` and counting up.
* **Since** 4.14
| programming_docs |
ocaml Module CamlinternalLazy Module CamlinternalLazy
=======================
```
module CamlinternalLazy: sig .. end
```
Run-time support for lazy values. All functions in this module are for system use only, not for the casual user.
```
type 'a t = 'a lazy_t
```
```
exception Undefined
```
```
val force_lazy_block : 'a lazy_t -> 'a
```
```
val force_gen : only_val:bool -> 'a lazy_t -> 'a
```
ocaml Module Printexc Module Printexc
===============
```
module Printexc: sig .. end
```
Facilities for printing exceptions and inspecting current call stack.
```
type t = exn = ..
```
The type of exception values.
```
val to_string : exn -> string
```
`Printexc.to_string e` returns a string representation of the exception `e`.
```
val to_string_default : exn -> string
```
`Printexc.to_string_default e` returns a string representation of the exception `e`, ignoring all registered exception printers.
* **Since** 4.09
```
val print : ('a -> 'b) -> 'a -> 'b
```
`Printexc.print fn x` applies `fn` to `x` and returns the result. If the evaluation of `fn x` raises any exception, the name of the exception is printed on standard error output, and the exception is raised again. The typical use is to catch and report exceptions that escape a function application.
```
val catch : ('a -> 'b) -> 'a -> 'b
```
Deprecated. This function is no longer needed. `Printexc.catch fn x` is similar to [`Printexc.print`](printexc#VALprint), but aborts the program with exit code 2 after printing the uncaught exception. This function is deprecated: the runtime system is now able to print uncaught exceptions as precisely as `Printexc.catch` does. Moreover, calling `Printexc.catch` makes it harder to track the location of the exception using the debugger or the stack backtrace facility. So, do not use `Printexc.catch` in new code.
```
val print_backtrace : out_channel -> unit
```
`Printexc.print_backtrace oc` prints an exception backtrace on the output channel `oc`. The backtrace lists the program locations where the most-recently raised exception was raised and where it was propagated through function calls.
If the call is not inside an exception handler, the returned backtrace is unspecified. If the call is after some exception-catching code (before in the handler, or in a when-guard during the matching of the exception handler), the backtrace may correspond to a later exception than the handled one.
* **Since** 3.11.0
```
val get_backtrace : unit -> string
```
`Printexc.get_backtrace ()` returns a string containing the same exception backtrace that `Printexc.print_backtrace` would print. Same restriction usage than [`Printexc.print_backtrace`](printexc#VALprint_backtrace).
* **Since** 3.11.0
```
val record_backtrace : bool -> unit
```
`Printexc.record_backtrace b` turns recording of exception backtraces on (if `b = true`) or off (if `b = false`). Initially, backtraces are not recorded, unless the `b` flag is given to the program through the `OCAMLRUNPARAM` variable.
* **Since** 3.11.0
```
val backtrace_status : unit -> bool
```
`Printexc.backtrace_status()` returns `true` if exception backtraces are currently recorded, `false` if not.
* **Since** 3.11.0
```
val register_printer : (exn -> string option) -> unit
```
`Printexc.register_printer fn` registers `fn` as an exception printer. The printer should return `None` or raise an exception if it does not know how to convert the passed exception, and `Some
s` with `s` the resulting string if it can convert the passed exception. Exceptions raised by the printer are ignored.
When converting an exception into a string, the printers will be invoked in the reverse order of their registrations, until a printer returns a `Some s` value (if no such printer exists, the runtime will use a generic printer).
When using this mechanism, one should be aware that an exception backtrace is attached to the thread that saw it raised, rather than to the exception itself. Practically, it means that the code related to `fn` should not use the backtrace if it has itself raised an exception before.
* **Since** 3.11.2
```
val use_printers : exn -> string option
```
`Printexc.use_printers e` returns `None` if there are no registered printers and `Some s` with else as the resulting string otherwise.
* **Since** 4.09
Raw backtraces
--------------
```
type raw_backtrace
```
The type `raw_backtrace` stores a backtrace in a low-level format, which can be converted to usable form using `raw_backtrace_entries` and `backtrace_slots_of_raw_entry` below.
Converting backtraces to `backtrace_slot`s is slower than capturing the backtraces. If an application processes many backtraces, it can be useful to use `raw_backtrace` to avoid or delay conversion.
Raw backtraces cannot be marshalled. If you need marshalling, you should use the array returned by the `backtrace_slots` function of the next section.
* **Since** 4.01.0
```
type raw_backtrace_entry = private int
```
A `raw_backtrace_entry` is an element of a `raw_backtrace`.
Each `raw_backtrace_entry` is an opaque integer, whose value is not stable between different programs, or even between different runs of the same binary.
A `raw_backtrace_entry` can be converted to a usable form using `backtrace_slots_of_raw_entry` below. Note that, due to inlining, a single `raw_backtrace_entry` may convert to several `backtrace_slot`s. Since the values of a `raw_backtrace_entry` are not stable, they cannot be marshalled. If they are to be converted, the conversion must be done by the process that generated them.
Again due to inlining, there may be multiple distinct raw\_backtrace\_entry values that convert to equal `backtrace_slot`s. However, if two `raw_backtrace_entry`s are equal as integers, then they represent the same `backtrace_slot`s.
* **Since** 4.12.0
```
val raw_backtrace_entries : raw_backtrace -> raw_backtrace_entry array
```
* **Since** 4.12.0
```
val get_raw_backtrace : unit -> raw_backtrace
```
`Printexc.get_raw_backtrace ()` returns the same exception backtrace that `Printexc.print_backtrace` would print, but in a raw format. Same restriction usage than [`Printexc.print_backtrace`](printexc#VALprint_backtrace).
* **Since** 4.01.0
```
val print_raw_backtrace : out_channel -> raw_backtrace -> unit
```
Print a raw backtrace in the same format `Printexc.print_backtrace` uses.
* **Since** 4.01.0
```
val raw_backtrace_to_string : raw_backtrace -> string
```
Return a string from a raw backtrace, in the same format `Printexc.get_backtrace` uses.
* **Since** 4.01.0
```
val raise_with_backtrace : exn -> raw_backtrace -> 'a
```
Reraise the exception using the given raw\_backtrace for the origin of the exception
* **Since** 4.05.0
Current call stack
------------------
```
val get_callstack : int -> raw_backtrace
```
`Printexc.get_callstack n` returns a description of the top of the call stack on the current program point (for the current thread), with at most `n` entries. (Note: this function is not related to exceptions at all, despite being part of the `Printexc` module.)
* **Since** 4.01.0
Uncaught exceptions
-------------------
```
val default_uncaught_exception_handler : exn -> raw_backtrace -> unit
```
`Printexc.default_uncaught_exception_handler` prints the exception and backtrace on standard error output.
* **Since** 4.11
```
val set_uncaught_exception_handler : (exn -> raw_backtrace -> unit) -> unit
```
`Printexc.set_uncaught_exception_handler fn` registers `fn` as the handler for uncaught exceptions. The default handler is [`Printexc.default_uncaught_exception_handler`](printexc#VALdefault_uncaught_exception_handler).
Note that when `fn` is called all the functions registered with [`at_exit`](stdlib#VALat_exit) have already been called. Because of this you must make sure any output channel `fn` writes on is flushed.
Also note that exceptions raised by user code in the interactive toplevel are not passed to this function as they are caught by the toplevel itself.
If `fn` raises an exception, both the exceptions passed to `fn` and raised by `fn` will be printed with their respective backtrace.
* **Since** 4.02.0
Manipulation of backtrace information
-------------------------------------
These functions are used to traverse the slots of a raw backtrace and extract information from them in a programmer-friendly format.
```
type backtrace_slot
```
The abstract type `backtrace_slot` represents a single slot of a backtrace.
* **Since** 4.02
```
val backtrace_slots : raw_backtrace -> backtrace_slot array option
```
Returns the slots of a raw backtrace, or `None` if none of them contain useful information.
In the return array, the slot at index `0` corresponds to the most recent function call, raise, or primitive `get_backtrace` call in the trace.
Some possible reasons for returning `None` are as follow:
* none of the slots in the trace come from modules compiled with debug information (`-g`)
* the program is a bytecode program that has not been linked with debug information enabled (`ocamlc -g`)
* **Since** 4.02.0
```
val backtrace_slots_of_raw_entry : raw_backtrace_entry -> backtrace_slot array option
```
Returns the slots of a single raw backtrace entry, or `None` if this entry lacks debug information.
Slots are returned in the same order as `backtrace_slots`: the slot at index `0` is the most recent call, raise, or primitive, and subsequent slots represent callers.
* **Since** 4.12
```
type location = {
```
| | |
| --- | --- |
| | `filename : `string`;` |
| | `line\_number : `int`;` |
| | `start\_char : `int`;` |
| | `end\_char : `int`;` |
`}` The type of location information found in backtraces. `start_char` and `end_char` are positions relative to the beginning of the line.
* **Since** 4.02
```
module Slot: sig .. end
```
Raw backtrace slots
-------------------
```
type raw_backtrace_slot
```
This type is used to iterate over the slots of a `raw_backtrace`. For most purposes, `backtrace_slots_of_raw_entry` is easier to use.
Like `raw_backtrace_entry`, values of this type are process-specific and must absolutely not be marshalled, and are unsafe to use for this reason (marshalling them may not fail, but un-marshalling and using the result will result in undefined behavior).
Elements of this type can still be compared and hashed: when two elements are equal, then they represent the same source location (the converse is not necessarily true in presence of inlining, for example).
* **Since** 4.02.0
```
val raw_backtrace_length : raw_backtrace -> int
```
`raw_backtrace_length bckt` returns the number of slots in the backtrace `bckt`.
* **Since** 4.02
```
val get_raw_backtrace_slot : raw_backtrace -> int -> raw_backtrace_slot
```
`get_raw_backtrace_slot bckt pos` returns the slot in position `pos` in the backtrace `bckt`.
* **Since** 4.02
```
val convert_raw_backtrace_slot : raw_backtrace_slot -> backtrace_slot
```
Extracts the user-friendly `backtrace_slot` from a low-level `raw_backtrace_slot`.
* **Since** 4.02
```
val get_raw_backtrace_next_slot : raw_backtrace_slot -> raw_backtrace_slot option
```
`get_raw_backtrace_next_slot slot` returns the next slot inlined, if any.
Sample code to iterate over all frames (inlined and non-inlined):
```
(* Iterate over inlined frames *)
let rec iter_raw_backtrace_slot f slot =
f slot;
match get_raw_backtrace_next_slot slot with
| None -> ()
| Some slot' -> iter_raw_backtrace_slot f slot'
(* Iterate over stack frames *)
let iter_raw_backtrace f bt =
for i = 0 to raw_backtrace_length bt - 1 do
iter_raw_backtrace_slot f (get_raw_backtrace_slot bt i)
done
```
* **Since** 4.04.0
Exception slots
---------------
```
val exn_slot_id : exn -> int
```
`Printexc.exn_slot_id` returns an integer which uniquely identifies the constructor used to create the exception value `exn` (in the current runtime).
* **Since** 4.02.0
```
val exn_slot_name : exn -> string
```
`Printexc.exn_slot_name exn` returns the internal name of the constructor used to create the exception value `exn`.
* **Since** 4.02.0
ocaml Module Obj.Ephemeron Module Obj.Ephemeron
====================
```
module Ephemeron: sig .. end
```
Ephemeron with arbitrary arity and untyped
```
type obj_t = Obj.t
```
alias for [`Obj.t`](obj#TYPEt)
```
type t
```
an ephemeron cf [`Obj.Ephemeron`](obj.ephemeron)
```
val create : int -> t
```
`create n` returns an ephemeron with `n` keys. All the keys and the data are initially empty. The argument `n` must be between zero and [`Obj.Ephemeron.max_ephe_length`](obj.ephemeron#VALmax_ephe_length) (limits included).
```
val length : t -> int
```
return the number of keys
```
val get_key : t -> int -> obj_t option
```
```
val get_key_copy : t -> int -> obj_t option
```
```
val set_key : t -> int -> obj_t -> unit
```
```
val unset_key : t -> int -> unit
```
```
val check_key : t -> int -> bool
```
```
val blit_key : t -> int -> t -> int -> int -> unit
```
```
val get_data : t -> obj_t option
```
```
val get_data_copy : t -> obj_t option
```
```
val set_data : t -> obj_t -> unit
```
```
val unset_data : t -> unit
```
```
val check_data : t -> bool
```
```
val blit_data : t -> t -> unit
```
```
val max_ephe_length : int
```
Maximum length of an ephemeron, ie the maximum number of keys an ephemeron could contain
ocaml Module Int32 Module Int32
============
```
module Int32: sig .. end
```
32-bit integers.
This module provides operations on the type `int32` of signed 32-bit integers. Unlike the built-in `int` type, the type `int32` is guaranteed to be exactly 32-bit wide on all platforms. All arithmetic operations over `int32` are taken modulo 232.
Performance notice: values of type `int32` occupy more memory space than values of type `int`, and arithmetic operations on `int32` are generally slower than those on `int`. Use `int32` only when the application requires exact 32-bit arithmetic.
Literals for 32-bit integers are suffixed by l:
```
let zero: int32 = 0l
let one: int32 = 1l
let m_one: int32 = -1l
```
```
val zero : int32
```
The 32-bit integer 0.
```
val one : int32
```
The 32-bit integer 1.
```
val minus_one : int32
```
The 32-bit integer -1.
```
val neg : int32 -> int32
```
Unary negation.
```
val add : int32 -> int32 -> int32
```
Addition.
```
val sub : int32 -> int32 -> int32
```
Subtraction.
```
val mul : int32 -> int32 -> int32
```
Multiplication.
```
val div : int32 -> int32 -> int32
```
Integer division. This division rounds the real quotient of its arguments towards zero, as specified for [`(/)`](stdlib#VAL(/)).
* **Raises** `Division_by_zero` if the second argument is zero.
```
val unsigned_div : int32 -> int32 -> int32
```
Same as [`Int32.div`](int32#VALdiv), except that arguments and result are interpreted as *unsigned* 32-bit integers.
* **Since** 4.08.0
```
val rem : int32 -> int32 -> int32
```
Integer remainder. If `y` is not zero, the result of `Int32.rem x y` satisfies the following property: `x = Int32.add (Int32.mul (Int32.div x y) y) (Int32.rem x y)`. If `y = 0`, `Int32.rem x y` raises `Division\_by\_zero`.
```
val unsigned_rem : int32 -> int32 -> int32
```
Same as [`Int32.rem`](int32#VALrem), except that arguments and result are interpreted as *unsigned* 32-bit integers.
* **Since** 4.08.0
```
val succ : int32 -> int32
```
Successor. `Int32.succ x` is `Int32.add x Int32.one`.
```
val pred : int32 -> int32
```
Predecessor. `Int32.pred x` is `Int32.sub x Int32.one`.
```
val abs : int32 -> int32
```
`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative.
```
val max_int : int32
```
The greatest representable 32-bit integer, 231 - 1.
```
val min_int : int32
```
The smallest representable 32-bit integer, -231.
```
val logand : int32 -> int32 -> int32
```
Bitwise logical and.
```
val logor : int32 -> int32 -> int32
```
Bitwise logical or.
```
val logxor : int32 -> int32 -> int32
```
Bitwise logical exclusive or.
```
val lognot : int32 -> int32
```
Bitwise logical negation.
```
val shift_left : int32 -> int -> int32
```
`Int32.shift_left x y` shifts `x` to the left by `y` bits. The result is unspecified if `y < 0` or `y >= 32`.
```
val shift_right : int32 -> int -> int32
```
`Int32.shift_right x y` shifts `x` to the right by `y` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `y < 0` or `y >= 32`.
```
val shift_right_logical : int32 -> int -> int32
```
`Int32.shift_right_logical x y` shifts `x` to the right by `y` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `y < 0` or `y >= 32`.
```
val of_int : int -> int32
```
Convert the given integer (type `int`) to a 32-bit integer (type `int32`). On 64-bit platforms, the argument is taken modulo 232.
```
val to_int : int32 -> int
```
Convert the given 32-bit integer (type `int32`) to an integer (type `int`). On 32-bit platforms, the 32-bit integer is taken modulo 231, i.e. the high-order bit is lost during the conversion. On 64-bit platforms, the conversion is exact.
```
val unsigned_to_int : int32 -> int option
```
Same as [`Int32.to_int`](int32#VALto_int), but interprets the argument as an *unsigned* integer. Returns `None` if the unsigned value of the argument cannot fit into an `int`.
* **Since** 4.08.0
```
val of_float : float -> int32
```
Convert the given floating-point number to a 32-bit integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range [[`Int32.min_int`](int32#VALmin_int), [`Int32.max_int`](int32#VALmax_int)], no exception is raised, and an unspecified, platform-dependent integer is returned.
```
val to_float : int32 -> float
```
Convert the given 32-bit integer to a floating-point number.
```
val of_string : string -> int32
```
Convert the given string to a 32-bit integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively.
The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*Int32.max_int+1]`. If the input exceeds [`Int32.max_int`](int32#VALmax_int) it is converted to the signed integer `Int32.min_int + input - Int32.max_int - 1`.
The `_` (underscore) character can appear anywhere in the string and is ignored.
* **Raises** `Failure` if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type `int32`.
```
val of_string_opt : string -> int32 option
```
Same as `of_string`, but return `None` instead of raising.
* **Since** 4.05
```
val to_string : int32 -> string
```
Return the string representation of its argument, in signed decimal.
```
val bits_of_float : float -> int32
```
Return the internal representation of the given float according to the IEEE 754 floating-point 'single format' bit layout. Bit 31 of the result represents the sign of the float; bits 30 to 23 represent the (biased) exponent; bits 22 to 0 represent the mantissa.
```
val float_of_bits : int32 -> float
```
Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'single format' bit layout, is the given `int32`.
```
type t = int32
```
An alias for the type of 32-bit integers.
```
val compare : t -> t -> int
```
The comparison function for 32-bit integers, with the same specification as [`compare`](stdlib#VALcompare). Along with the type `t`, this function `compare` allows the module `Int32` to be passed as argument to the functors [`Set.Make`](set.make) and [`Map.Make`](map.make).
```
val unsigned_compare : t -> t -> int
```
Same as [`Int32.compare`](int32#VALcompare), except that arguments are interpreted as *unsigned* 32-bit integers.
* **Since** 4.08.0
```
val equal : t -> t -> bool
```
The equal function for int32s.
* **Since** 4.03.0
```
val min : t -> t -> t
```
Return the smaller of the two arguments.
* **Since** 4.13.0
```
val max : t -> t -> t
```
Return the greater of the two arguments.
* **Since** 4.13.0
| programming_docs |
ocaml Module List Module List
===========
```
module List: sig .. end
```
List operations.
Some functions are flagged as not tail-recursive. A tail-recursive function uses constant stack space, while a non-tail-recursive function uses stack space proportional to the length of its list argument, which can be a problem with very long lists. When the function takes several list arguments, an approximate formula giving stack usage (in some unspecified constant unit) is shown in parentheses.
The above considerations can usually be ignored if your lists are not longer than about 10000 elements.
The labeled version of this module can be used as described in the [`StdLabels`](stdlabels) module.
```
type 'a t = 'a list =
```
| | |
| --- | --- |
| `|` | `[]` |
| `|` | `(::) of `'a * 'a list`` |
An alias for the type of lists.
```
val length : 'a list -> int
```
Return the length (number of elements) of the given list.
```
val compare_lengths : 'a list -> 'b list -> int
```
Compare the lengths of two lists. `compare_lengths l1 l2` is equivalent to `compare (length l1) (length l2)`, except that the computation stops after reaching the end of the shortest list.
* **Since** 4.05.0
```
val compare_length_with : 'a list -> int -> int
```
Compare the length of a list to an integer. `compare_length_with l len` is equivalent to `compare (length l) len`, except that the computation stops after at most `len` iterations on the list.
* **Since** 4.05.0
```
val cons : 'a -> 'a list -> 'a list
```
`cons x xs` is `x :: xs`
* **Since** 4.03.0 (4.05.0 in ListLabels)
```
val hd : 'a list -> 'a
```
Return the first element of the given list.
* **Raises** `Failure` if the list is empty.
```
val tl : 'a list -> 'a list
```
Return the given list without its first element.
* **Raises** `Failure` if the list is empty.
```
val nth : 'a list -> int -> 'a
```
Return the `n`-th element of the given list. The first element (head of the list) is at position 0.
* **Raises**
+ `Failure` if the list is too short.
+ `Invalid_argument` if `n` is negative.
```
val nth_opt : 'a list -> int -> 'a option
```
Return the `n`-th element of the given list. The first element (head of the list) is at position 0. Return `None` if the list is too short.
* **Since** 4.05
* **Raises** `Invalid_argument` if `n` is negative.
```
val rev : 'a list -> 'a list
```
List reversal.
```
val init : int -> (int -> 'a) -> 'a list
```
`init len f` is `[f 0; f 1; ...; f (len-1)]`, evaluated left to right.
* **Since** 4.06.0
* **Raises** `Invalid_argument` if `len < 0`.
```
val append : 'a list -> 'a list -> 'a list
```
Concatenate two lists. Same function as the infix operator `@`. Not tail-recursive (length of the first argument). The `@` operator is not tail-recursive either.
```
val rev_append : 'a list -> 'a list -> 'a list
```
`rev_append l1 l2` reverses `l1` and concatenates it with `l2`. This is equivalent to `(`[`List.rev`](list#VALrev)`l1) @ l2`, but `rev_append` is tail-recursive and more efficient.
```
val concat : 'a list list -> 'a list
```
Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument + length of the longest sub-list).
```
val flatten : 'a list list -> 'a list
```
Same as [`List.concat`](list#VALconcat). Not tail-recursive (length of the argument + length of the longest sub-list).
Comparison
----------
```
val equal : ('a -> 'a -> bool) -> 'a list -> 'a list -> bool
```
`equal eq [a1; ...; an] [b1; ..; bm]` holds when the two input lists have the same length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`.
Note: the `eq` function may be called even if the lists have different length. If you know your equality function is costly, you may want to check [`List.compare_lengths`](list#VALcompare_lengths) first.
* **Since** 4.12.0
```
val compare : ('a -> 'a -> int) -> 'a list -> 'a list -> int
```
`compare cmp [a1; ...; an] [b1; ...; bm]` performs a lexicographic comparison of the two input lists, using the same `'a -> 'a -> int` interface as [`compare`](stdlib#VALcompare):
* `a1 :: l1` is smaller than `a2 :: l2` (negative result) if `a1` is smaller than `a2`, or if they are equal (0 result) and `l1` is smaller than `l2`
* the empty list `[]` is strictly smaller than non-empty lists
Note: the `cmp` function will be called even if the lists have different lengths.
* **Since** 4.12.0
Iterators
---------
```
val iter : ('a -> unit) -> 'a list -> unit
```
`iter f [a1; ...; an]` applies function `f` in turn to `[a1; ...; an]`. It is equivalent to `f a1; f a2; ...; f an`.
```
val iteri : (int -> 'a -> unit) -> 'a list -> unit
```
Same as [`List.iter`](list#VALiter), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
* **Since** 4.00.0
```
val map : ('a -> 'b) -> 'a list -> 'b list
```
`map f [a1; ...; an]` applies function `f` to `a1, ..., an`, and builds the list `[f a1; ...; f an]` with the results returned by `f`. Not tail-recursive.
```
val mapi : (int -> 'a -> 'b) -> 'a list -> 'b list
```
Same as [`List.map`](list#VALmap), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. Not tail-recursive.
* **Since** 4.00.0
```
val rev_map : ('a -> 'b) -> 'a list -> 'b list
```
`rev_map f l` gives the same result as [`List.rev`](list#VALrev)`(`[`List.map`](list#VALmap)`f l)`, but is tail-recursive and more efficient.
```
val filter_map : ('a -> 'b option) -> 'a list -> 'b list
```
`filter_map f l` applies `f` to every element of `l`, filters out the `None` elements and returns the list of the arguments of the `Some` elements.
* **Since** 4.08.0
```
val concat_map : ('a -> 'b list) -> 'a list -> 'b list
```
`concat_map f l` gives the same result as [`List.concat`](list#VALconcat)`(`[`List.map`](list#VALmap)`f l)`. Tail-recursive.
* **Since** 4.10.0
```
val fold_left_map : ('a -> 'b -> 'a * 'c) -> 'a -> 'b list -> 'a * 'c list
```
`fold_left_map` is a combination of `fold_left` and `map` that threads an accumulator through calls to `f`.
* **Since** 4.11.0
```
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a
```
`fold_left f init [b1; ...; bn]` is `f (... (f (f init b1) b2) ...) bn`.
```
val fold_right : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b
```
`fold_right f [a1; ...; an] init` is `f a1 (f a2 (... (f an init) ...))`. Not tail-recursive.
Iterators on two lists
----------------------
```
val iter2 : ('a -> 'b -> unit) -> 'a list -> 'b list -> unit
```
`iter2 f [a1; ...; an] [b1; ...; bn]` calls in turn `f a1 b1; ...; f an bn`.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths.
```
val map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
```
`map2 f [a1; ...; an] [b1; ...; bn]` is `[f a1 b1; ...; f an bn]`.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths. Not tail-recursive.
```
val rev_map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
```
`rev_map2 f l1 l2` gives the same result as [`List.rev`](list#VALrev)`(`[`List.map2`](list#VALmap2)`f l1 l2)`, but is tail-recursive and more efficient.
```
val fold_left2 : ('a -> 'b -> 'c -> 'a) -> 'a -> 'b list -> 'c list -> 'a
```
`fold_left2 f init [a1; ...; an] [b1; ...; bn]` is `f (... (f (f init a1 b1) a2 b2) ...) an bn`.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths.
```
val fold_right2 : ('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> 'c -> 'c
```
`fold_right2 f [a1; ...; an] [b1; ...; bn] init` is `f a1 b1 (f a2 b2 (... (f an bn init) ...))`.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths. Not tail-recursive.
List scanning
-------------
```
val for_all : ('a -> bool) -> 'a list -> bool
```
`for_all f [a1; ...; an]` checks if all elements of the list satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)` for a non-empty list and `true` if the list is empty.
```
val exists : ('a -> bool) -> 'a list -> bool
```
`exists f [a1; ...; an]` checks if at least one element of the list satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)` for a non-empty list and `false` if the list is empty.
```
val for_all2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool
```
Same as [`List.for_all`](list#VALfor_all), but for a two-argument predicate.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths.
```
val exists2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool
```
Same as [`List.exists`](list#VALexists), but for a two-argument predicate.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths.
```
val mem : 'a -> 'a list -> bool
```
`mem a set` is true if and only if `a` is equal to an element of `set`.
```
val memq : 'a -> 'a list -> bool
```
Same as [`List.mem`](list#VALmem), but uses physical equality instead of structural equality to compare list elements.
List searching
--------------
```
val find : ('a -> bool) -> 'a list -> 'a
```
`find f l` returns the first element of the list `l` that satisfies the predicate `f`.
* **Raises** `Not_found` if there is no value that satisfies `f` in the list `l`.
```
val find_opt : ('a -> bool) -> 'a list -> 'a option
```
`find f l` returns the first element of the list `l` that satisfies the predicate `f`. Returns `None` if there is no value that satisfies `f` in the list `l`.
* **Since** 4.05
```
val find_map : ('a -> 'b option) -> 'a list -> 'b option
```
`find_map f l` applies `f` to the elements of `l` in order, and returns the first result of the form `Some v`, or `None` if none exist.
* **Since** 4.10.0
```
val filter : ('a -> bool) -> 'a list -> 'a list
```
`filter f l` returns all the elements of the list `l` that satisfy the predicate `f`. The order of the elements in the input list is preserved.
```
val find_all : ('a -> bool) -> 'a list -> 'a list
```
`find_all` is another name for [`List.filter`](list#VALfilter).
```
val filteri : (int -> 'a -> bool) -> 'a list -> 'a list
```
Same as [`List.filter`](list#VALfilter), but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
* **Since** 4.11.0
```
val partition : ('a -> bool) -> 'a list -> 'a list * 'a list
```
`partition f l` returns a pair of lists `(l1, l2)`, where `l1` is the list of all the elements of `l` that satisfy the predicate `f`, and `l2` is the list of all the elements of `l` that do not satisfy `f`. The order of the elements in the input list is preserved.
```
val partition_map : ('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list
```
`partition_map f l` returns a pair of lists `(l1, l2)` such that, for each element `x` of the input list `l`:
* if `f x` is `Left y1`, then `y1` is in `l1`, and
* if `f x` is `Right y2`, then `y2` is in `l2`.
The output elements are included in `l1` and `l2` in the same relative order as the corresponding input elements in `l`.
In particular, `partition_map (fun x -> if f x then Left x else Right x) l` is equivalent to `partition f l`.
* **Since** 4.12.0
Association lists
-----------------
```
val assoc : 'a -> ('a * 'b) list -> 'b
```
`assoc a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc a [ ...; (a,b); ...] = b` if `(a,b)` is the leftmost binding of `a` in list `l`.
* **Raises** `Not_found` if there is no value associated with `a` in the list `l`.
```
val assoc_opt : 'a -> ('a * 'b) list -> 'b option
```
`assoc_opt a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc_opt a [ ...; (a,b); ...] = Some b` if `(a,b)` is the leftmost binding of `a` in list `l`. Returns `None` if there is no value associated with `a` in the list `l`.
* **Since** 4.05
```
val assq : 'a -> ('a * 'b) list -> 'b
```
Same as [`List.assoc`](list#VALassoc), but uses physical equality instead of structural equality to compare keys.
```
val assq_opt : 'a -> ('a * 'b) list -> 'b option
```
Same as [`List.assoc_opt`](list#VALassoc_opt), but uses physical equality instead of structural equality to compare keys.
* **Since** 4.05.0
```
val mem_assoc : 'a -> ('a * 'b) list -> bool
```
Same as [`List.assoc`](list#VALassoc), but simply return `true` if a binding exists, and `false` if no bindings exist for the given key.
```
val mem_assq : 'a -> ('a * 'b) list -> bool
```
Same as [`List.mem_assoc`](list#VALmem_assoc), but uses physical equality instead of structural equality to compare keys.
```
val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list
```
`remove_assoc a l` returns the list of pairs `l` without the first pair with key `a`, if any. Not tail-recursive.
```
val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list
```
Same as [`List.remove_assoc`](list#VALremove_assoc), but uses physical equality instead of structural equality to compare keys. Not tail-recursive.
Lists of pairs
--------------
```
val split : ('a * 'b) list -> 'a list * 'b list
```
Transform a list of pairs into a pair of lists: `split [(a1,b1); ...; (an,bn)]` is `([a1; ...; an], [b1; ...; bn])`. Not tail-recursive.
```
val combine : 'a list -> 'b list -> ('a * 'b) list
```
Transform a pair of lists into a list of pairs: `combine [a1; ...; an] [b1; ...; bn]` is `[(a1,b1); ...; (an,bn)]`.
* **Raises** `Invalid_argument` if the two lists have different lengths. Not tail-recursive.
Sorting
-------
```
val sort : ('a -> 'a -> int) -> 'a list -> 'a list
```
Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, [`compare`](stdlib#VALcompare) is a suitable comparison function. The resulting list is sorted in increasing order. [`List.sort`](list#VALsort) is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space.
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
```
val stable_sort : ('a -> 'a -> int) -> 'a list -> 'a list
```
Same as [`List.sort`](list#VALsort), but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order).
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
```
val fast_sort : ('a -> 'a -> int) -> 'a list -> 'a list
```
Same as [`List.sort`](list#VALsort) or [`List.stable_sort`](list#VALstable_sort), whichever is faster on typical input.
```
val sort_uniq : ('a -> 'a -> int) -> 'a list -> 'a list
```
Same as [`List.sort`](list#VALsort), but also remove duplicates.
* **Since** 4.02.0 (4.03.0 in ListLabels)
```
val merge : ('a -> 'a -> int) -> 'a list -> 'a list -> 'a list
```
Merge two lists: Assuming that `l1` and `l2` are sorted according to the comparison function `cmp`, `merge cmp l1 l2` will return a sorted list containing all the elements of `l1` and `l2`. If several elements compare equal, the elements of `l1` will be before the elements of `l2`. Not tail-recursive (sum of the lengths of the arguments).
Lists and Sequences
-------------------
```
val to_seq : 'a list -> 'a Seq.t
```
Iterate on the list.
* **Since** 4.07
```
val of_seq : 'a Seq.t -> 'a list
```
Create a list from a sequence.
* **Since** 4.07
ocaml Ocaml_operators Ocaml\_operators
================
Precedence level and associativity of operators
===============================================
The following table lists the precedence level of all operator classes from the highest to the lowest precedence. A few other syntactic constructions are also listed as references.
| Operator class | Associativity |
| --- | --- |
| `!… ~…` | – |
| `.…() .…[] .…{}` | – |
| `#…` | left |
| `function application` | left |
| `- -.` | – |
| `**… lsl lsr asr` | right |
| `*… /… %… mod land lor lxor` | left |
| `+… -…` | left |
| `::` | right |
| `@… ^…` | right |
| `=… <…
>… |… &… $… !=` | left |
| `& &&` | right |
| `or ||` | right |
| `,` | – |
| `<- :=` | right |
| `if` | – |
| `;` | right |
ocaml Module Bytes Module Bytes
============
```
module Bytes: sig .. end
```
Byte sequence operations.
A byte sequence is a mutable data structure that contains a fixed-length sequence of bytes. Each byte can be indexed in constant time for reading or writing.
Given a byte sequence `s` of length `l`, we can access each of the `l` bytes of `s` via its index in the sequence. Indexes start at `0`, and we will call an index valid in `s` if it falls within the range `[0...l-1]` (inclusive). A position is the point between two bytes or at the beginning or end of the sequence. We call a position valid in `s` if it falls within the range `[0...l]` (inclusive). Note that the byte at index `n` is between positions `n` and `n+1`.
Two parameters `start` and `len` are said to designate a valid range of `s` if `len >= 0` and `start` and `start+len` are valid positions in `s`.
Byte sequences can be modified in place, for instance via the `set` and `blit` functions described below. See also strings (module [`String`](string)), which are almost the same data structure, but cannot be modified in place.
Bytes are represented by the OCaml type `char`.
The labeled version of this module can be used as described in the [`StdLabels`](stdlabels) module.
* **Since** 4.02.0
```
val length : bytes -> int
```
Return the length (number of bytes) of the argument.
```
val get : bytes -> int -> char
```
`get s n` returns the byte at index `n` in argument `s`.
* **Raises** `Invalid_argument` if `n` is not a valid index in `s`.
```
val set : bytes -> int -> char -> unit
```
`set s n c` modifies `s` in place, replacing the byte at index `n` with `c`.
* **Raises** `Invalid_argument` if `n` is not a valid index in `s`.
```
val create : int -> bytes
```
`create n` returns a new byte sequence of length `n`. The sequence is uninitialized and contains arbitrary bytes.
* **Raises** `Invalid_argument` if `n < 0` or `n >`[`Sys.max_string_length`](sys#VALmax_string_length).
```
val make : int -> char -> bytes
```
`make n c` returns a new byte sequence of length `n`, filled with the byte `c`.
* **Raises** `Invalid_argument` if `n < 0` or `n >`[`Sys.max_string_length`](sys#VALmax_string_length).
```
val init : int -> (int -> char) -> bytes
```
`init n f` returns a fresh byte sequence of length `n`, with character `i` initialized to the result of `f i` (in increasing index order).
* **Raises** `Invalid_argument` if `n < 0` or `n >`[`Sys.max_string_length`](sys#VALmax_string_length).
```
val empty : bytes
```
A byte sequence of size 0.
```
val copy : bytes -> bytes
```
Return a new byte sequence that contains the same bytes as the argument.
```
val of_string : string -> bytes
```
Return a new byte sequence that contains the same bytes as the given string.
```
val to_string : bytes -> string
```
Return a new string that contains the same bytes as the given byte sequence.
```
val sub : bytes -> int -> int -> bytes
```
`sub s pos len` returns a new byte sequence of length `len`, containing the subsequence of `s` that starts at position `pos` and has length `len`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid range of `s`.
```
val sub_string : bytes -> int -> int -> string
```
Same as [`Bytes.sub`](bytes#VALsub) but return a string instead of a byte sequence.
```
val extend : bytes -> int -> int -> bytes
```
`extend s left right` returns a new byte sequence that contains the bytes of `s`, with `left` uninitialized bytes prepended and `right` uninitialized bytes appended to it. If `left` or `right` is negative, then bytes are removed (instead of appended) from the corresponding side of `s`.
* **Since** 4.05.0 in BytesLabels
* **Raises** `Invalid_argument` if the result length is negative or longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val fill : bytes -> int -> int -> char -> unit
```
`fill s pos len c` modifies `s` in place, replacing `len` characters with `c`, starting at `pos`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid range of `s`.
```
val blit : bytes -> int -> bytes -> int -> int -> unit
```
`blit src src_pos dst dst_pos len` copies `len` bytes from sequence `src`, starting at index `src_pos`, to sequence `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same byte sequence, and the source and destination intervals overlap.
* **Raises** `Invalid_argument` if `src_pos` and `len` do not designate a valid range of `src`, or if `dst_pos` and `len` do not designate a valid range of `dst`.
```
val blit_string : string -> int -> bytes -> int -> int -> unit
```
`blit src src_pos dst dst_pos len` copies `len` bytes from string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`.
* **Since** 4.05.0 in BytesLabels
* **Raises** `Invalid_argument` if `src_pos` and `len` do not designate a valid range of `src`, or if `dst_pos` and `len` do not designate a valid range of `dst`.
```
val concat : bytes -> bytes list -> bytes
```
`concat sep sl` concatenates the list of byte sequences `sl`, inserting the separator byte sequence `sep` between each, and returns the result as a new byte sequence.
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val cat : bytes -> bytes -> bytes
```
`cat s1 s2` concatenates `s1` and `s2` and returns the result as a new byte sequence.
* **Since** 4.05.0 in BytesLabels
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val iter : (char -> unit) -> bytes -> unit
```
`iter f s` applies function `f` in turn to all the bytes of `s`. It is equivalent to `f (get s 0); f (get s 1); ...; f (get s
(length s - 1)); ()`.
```
val iteri : (int -> char -> unit) -> bytes -> unit
```
Same as [`Bytes.iter`](bytes#VALiter), but the function is applied to the index of the byte as first argument and the byte itself as second argument.
```
val map : (char -> char) -> bytes -> bytes
```
`map f s` applies function `f` in turn to all the bytes of `s` (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result.
```
val mapi : (int -> char -> char) -> bytes -> bytes
```
`mapi f s` calls `f` with each character of `s` and its index (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result.
```
val fold_left : ('a -> char -> 'a) -> 'a -> bytes -> 'a
```
`fold_left f x s` computes `f (... (f (f x (get s 0)) (get s 1)) ...) (get s (n-1))`, where `n` is the length of `s`.
* **Since** 4.13.0
```
val fold_right : (char -> 'a -> 'a) -> bytes -> 'a -> 'a
```
`fold_right f s x` computes `f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x) ...))`, where `n` is the length of `s`.
* **Since** 4.13.0
```
val for_all : (char -> bool) -> bytes -> bool
```
`for_all p s` checks if all characters in `s` satisfy the predicate `p`.
* **Since** 4.13.0
```
val exists : (char -> bool) -> bytes -> bool
```
`exists p s` checks if at least one character of `s` satisfies the predicate `p`.
* **Since** 4.13.0
```
val trim : bytes -> bytes
```
Return a copy of the argument, without leading and trailing whitespace. The bytes regarded as whitespace are the ASCII characters `' '`, `'\012'`, `'\n'`, `'\r'`, and `'\t'`.
```
val escaped : bytes -> bytes
```
Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash and double-quote.
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val index : bytes -> char -> int
```
`index s c` returns the index of the first occurrence of byte `c` in `s`.
* **Raises** `Not_found` if `c` does not occur in `s`.
```
val index_opt : bytes -> char -> int option
```
`index_opt s c` returns the index of the first occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`.
* **Since** 4.05
```
val rindex : bytes -> char -> int
```
`rindex s c` returns the index of the last occurrence of byte `c` in `s`.
* **Raises** `Not_found` if `c` does not occur in `s`.
```
val rindex_opt : bytes -> char -> int option
```
`rindex_opt s c` returns the index of the last occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`.
* **Since** 4.05
```
val index_from : bytes -> int -> char -> int
```
`index_from s i c` returns the index of the first occurrence of byte `c` in `s` after position `i`. `index s c` is equivalent to `index_from s 0 c`.
* **Raises**
+ `Invalid_argument` if `i` is not a valid position in `s`.
+ `Not_found` if `c` does not occur in `s` after position `i`.
```
val index_from_opt : bytes -> int -> char -> int option
```
`index_from_opt s i c` returns the index of the first occurrence of byte `c` in `s` after position `i` or `None` if `c` does not occur in `s` after position `i`. `index_opt s c` is equivalent to `index_from_opt s 0 c`.
* **Since** 4.05
* **Raises** `Invalid_argument` if `i` is not a valid position in `s`.
```
val rindex_from : bytes -> int -> char -> int
```
`rindex_from s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1`. `rindex s c` is equivalent to `rindex_from s (length s - 1) c`.
* **Raises**
+ `Invalid_argument` if `i+1` is not a valid position in `s`.
+ `Not_found` if `c` does not occur in `s` before position `i+1`.
```
val rindex_from_opt : bytes -> int -> char -> int option
```
`rindex_from_opt s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1` or `None` if `c` does not occur in `s` before position `i+1`. `rindex_opt s c` is equivalent to `rindex_from s (length s - 1) c`.
* **Since** 4.05
* **Raises** `Invalid_argument` if `i+1` is not a valid position in `s`.
```
val contains : bytes -> char -> bool
```
`contains s c` tests if byte `c` appears in `s`.
```
val contains_from : bytes -> int -> char -> bool
```
`contains_from s start c` tests if byte `c` appears in `s` after position `start`. `contains s c` is equivalent to `contains_from
s 0 c`.
* **Raises** `Invalid_argument` if `start` is not a valid position in `s`.
```
val rcontains_from : bytes -> int -> char -> bool
```
`rcontains_from s stop c` tests if byte `c` appears in `s` before position `stop+1`.
* **Raises** `Invalid_argument` if `stop < 0` or `stop+1` is not a valid position in `s`.
```
val uppercase_ascii : bytes -> bytes
```
Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set.
* **Since** 4.03.0 (4.05.0 in BytesLabels)
```
val lowercase_ascii : bytes -> bytes
```
Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set.
* **Since** 4.03.0 (4.05.0 in BytesLabels)
```
val capitalize_ascii : bytes -> bytes
```
Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character set.
* **Since** 4.03.0 (4.05.0 in BytesLabels)
```
val uncapitalize_ascii : bytes -> bytes
```
Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character set.
* **Since** 4.03.0 (4.05.0 in BytesLabels)
```
type t = bytes
```
An alias for the type of byte sequences.
```
val compare : t -> t -> int
```
The comparison function for byte sequences, with the same specification as [`compare`](stdlib#VALcompare). Along with the type `t`, this function `compare` allows the module `Bytes` to be passed as argument to the functors [`Set.Make`](set.make) and [`Map.Make`](map.make).
```
val equal : t -> t -> bool
```
The equality function for byte sequences.
* **Since** 4.03.0 (4.05.0 in BytesLabels)
```
val starts_with : prefix:bytes -> bytes -> bool
```
`starts_with``~prefix s` is `true` if and only if `s` starts with `prefix`.
* **Since** 4.13.0
```
val ends_with : suffix:bytes -> bytes -> bool
```
`ends_with``~suffix s` is `true` if and only if `s` ends with `suffix`.
* **Since** 4.13.0
Unsafe conversions (for advanced users)
---------------------------------------
This section describes unsafe, low-level conversion functions between `bytes` and `string`. They do not copy the internal data; used improperly, they can break the immutability invariant on strings provided by the `-safe-string` option. They are available for expert library authors, but for most purposes you should use the always-correct [`Bytes.to_string`](bytes#VALto_string) and [`Bytes.of_string`](bytes#VALof_string) instead.
```
val unsafe_to_string : bytes -> string
```
Unsafely convert a byte sequence into a string.
To reason about the use of `unsafe_to_string`, it is convenient to consider an "ownership" discipline. A piece of code that manipulates some data "owns" it; there are several disjoint ownership modes, including:
* Unique ownership: the data may be accessed and mutated
* Shared ownership: the data has several owners, that may only access it, not mutate it.
Unique ownership is linear: passing the data to another piece of code means giving up ownership (we cannot write the data again). A unique owner may decide to make the data shared (giving up mutation rights on it), but shared data may not become uniquely-owned again.
`unsafe_to_string s` can only be used when the caller owns the byte sequence `s` -- either uniquely or as shared immutable data. The caller gives up ownership of `s`, and gains ownership of the returned string.
There are two valid use-cases that respect this ownership discipline:
1. Creating a string by initializing and mutating a byte sequence that is never changed after initialization is performed.
```
let string_init len f : string =
let s = Bytes.create len in
for i = 0 to len - 1 do Bytes.set s i (f i) done;
Bytes.unsafe_to_string s
```
This function is safe because the byte sequence `s` will never be accessed or mutated after `unsafe_to_string` is called. The `string_init` code gives up ownership of `s`, and returns the ownership of the resulting string to its caller.
Note that it would be unsafe if `s` was passed as an additional parameter to the function `f` as it could escape this way and be mutated in the future -- `string_init` would give up ownership of `s` to pass it to `f`, and could not call `unsafe_to_string` safely.
We have provided the [`String.init`](string#VALinit), [`String.map`](string#VALmap) and [`String.mapi`](string#VALmapi) functions to cover most cases of building new strings. You should prefer those over `to_string` or `unsafe_to_string` whenever applicable.
2. Temporarily giving ownership of a byte sequence to a function that expects a uniquely owned string and returns ownership back, so that we can mutate the sequence again after the call ended.
```
let bytes_length (s : bytes) =
String.length (Bytes.unsafe_to_string s)
```
In this use-case, we do not promise that `s` will never be mutated after the call to `bytes_length s`. The [`String.length`](string#VALlength) function temporarily borrows unique ownership of the byte sequence (and sees it as a `string`), but returns this ownership back to the caller, which may assume that `s` is still a valid byte sequence after the call. Note that this is only correct because we know that [`String.length`](string#VALlength) does not capture its argument -- it could escape by a side-channel such as a memoization combinator.
The caller may not mutate `s` while the string is borrowed (it has temporarily given up ownership). This affects concurrent programs, but also higher-order functions: if [`String.length`](string#VALlength) returned a closure to be called later, `s` should not be mutated until this closure is fully applied and returns ownership.
```
val unsafe_of_string : string -> bytes
```
Unsafely convert a shared string to a byte sequence that should not be mutated.
The same ownership discipline that makes `unsafe_to_string` correct applies to `unsafe_of_string`: you may use it if you were the owner of the `string` value, and you will own the return `bytes` in the same mode.
In practice, unique ownership of string values is extremely difficult to reason about correctly. You should always assume strings are shared, never uniquely owned.
For example, string literals are implicitly shared by the compiler, so you never uniquely own them.
```
let incorrect = Bytes.unsafe_of_string "hello"
let s = Bytes.of_string "hello"
```
The first declaration is incorrect, because the string literal `"hello"` could be shared by the compiler with other parts of the program, and mutating `incorrect` is a bug. You must always use the second version, which performs a copy and is thus correct.
Assuming unique ownership of strings that are not string literals, but are (partly) built from string literals, is also incorrect. For example, mutating `unsafe_of_string ("foo" ^ s)` could mutate the shared string `"foo"` -- assuming a rope-like representation of strings. More generally, functions operating on strings will assume shared ownership, they do not preserve unique ownership. It is thus incorrect to assume unique ownership of the result of `unsafe_of_string`.
The only case we have reasonable confidence is safe is if the produced `bytes` is shared -- used as an immutable byte sequence. This is possibly useful for incremental migration of low-level programs that manipulate immutable sequences of bytes (for example [`Marshal.from_bytes`](marshal#VALfrom_bytes)) and previously used the `string` type for this purpose.
```
val split_on_char : char -> bytes -> bytes list
```
`split_on_char sep s` returns the list of all (possibly empty) subsequences of `s` that are delimited by the `sep` character.
The function's output is specified by the following invariants:
* The list is not empty.
* Concatenating its elements using `sep` as a separator returns a byte sequence equal to the input (`Bytes.concat (Bytes.make 1 sep)
(Bytes.split_on_char sep s) = s`).
* No byte sequence in the result contains the `sep` character.
* **Since** 4.13.0
Iterators
---------
```
val to_seq : t -> char Seq.t
```
Iterate on the string, in increasing index order. Modifications of the string during iteration will be reflected in the sequence.
* **Since** 4.07
```
val to_seqi : t -> (int * char) Seq.t
```
Iterate on the string, in increasing order, yielding indices along chars
* **Since** 4.07
```
val of_seq : char Seq.t -> t
```
Create a string from the generator
* **Since** 4.07
UTF codecs and validations
--------------------------
### UTF-8
```
val get_utf_8_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_8_uchar b i` decodes an UTF-8 character at index `i` in `b`.
```
val set_utf_8_uchar : t -> int -> Uchar.t -> int
```
`set_utf_8_uchar b i u` UTF-8 encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`.
```
val is_valid_utf_8 : t -> bool
```
`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data.
### UTF-16BE
```
val get_utf_16be_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_16be_uchar b i` decodes an UTF-16BE character at index `i` in `b`.
```
val set_utf_16be_uchar : t -> int -> Uchar.t -> int
```
`set_utf_16be_uchar b i u` UTF-16BE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`.
```
val is_valid_utf_16be : t -> bool
```
`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data.
### UTF-16LE
```
val get_utf_16le_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_16le_uchar b i` decodes an UTF-16LE character at index `i` in `b`.
```
val set_utf_16le_uchar : t -> int -> Uchar.t -> int
```
`set_utf_16le_uchar b i u` UTF-16LE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`.
```
val is_valid_utf_16le : t -> bool
```
`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data.
Binary encoding/decoding of integers
------------------------------------
The functions in this section binary encode and decode integers to and from byte sequences.
All following functions raise `Invalid\_argument` if the space needed at index `i` to decode or encode the integer is not available.
Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](sys#VALbig_endian).
32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers.
8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are handled as follows:
* Functions that decode signed (resp. unsigned) 8-bit or 16-bit integers represented by `int` values sign-extend (resp. zero-extend) their result.
* Functions that encode 8-bit or 16-bit integers represented by `int` values truncate their input to their least significant bytes.
```
val get_uint8 : bytes -> int -> int
```
`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int8 : bytes -> int -> int
```
`get_int8 b i` is `b`'s signed 8-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_uint16_ne : bytes -> int -> int
```
`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_uint16_be : bytes -> int -> int
```
`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_uint16_le : bytes -> int -> int
```
`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int16_ne : bytes -> int -> int
```
`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int16_be : bytes -> int -> int
```
`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int16_le : bytes -> int -> int
```
`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int32_ne : bytes -> int -> int32
```
`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int32_be : bytes -> int -> int32
```
`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int32_le : bytes -> int -> int32
```
`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int64_ne : bytes -> int -> int64
```
`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int64_be : bytes -> int -> int64
```
`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int64_le : bytes -> int -> int64
```
`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at byte index `i`.
* **Since** 4.08
```
val set_uint8 : bytes -> int -> int -> unit
```
`set_uint8 b i v` sets `b`'s unsigned 8-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int8 : bytes -> int -> int -> unit
```
`set_int8 b i v` sets `b`'s signed 8-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_uint16_ne : bytes -> int -> int -> unit
```
`set_uint16_ne b i v` sets `b`'s native-endian unsigned 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_uint16_be : bytes -> int -> int -> unit
```
`set_uint16_be b i v` sets `b`'s big-endian unsigned 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_uint16_le : bytes -> int -> int -> unit
```
`set_uint16_le b i v` sets `b`'s little-endian unsigned 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int16_ne : bytes -> int -> int -> unit
```
`set_int16_ne b i v` sets `b`'s native-endian signed 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int16_be : bytes -> int -> int -> unit
```
`set_int16_be b i v` sets `b`'s big-endian signed 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int16_le : bytes -> int -> int -> unit
```
`set_int16_le b i v` sets `b`'s little-endian signed 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int32_ne : bytes -> int -> int32 -> unit
```
`set_int32_ne b i v` sets `b`'s native-endian 32-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int32_be : bytes -> int -> int32 -> unit
```
`set_int32_be b i v` sets `b`'s big-endian 32-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int32_le : bytes -> int -> int32 -> unit
```
`set_int32_le b i v` sets `b`'s little-endian 32-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int64_ne : bytes -> int -> int64 -> unit
```
`set_int64_ne b i v` sets `b`'s native-endian 64-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int64_be : bytes -> int -> int64 -> unit
```
`set_int64_be b i v` sets `b`'s big-endian 64-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int64_le : bytes -> int -> int64 -> unit
```
`set_int64_le b i v` sets `b`'s little-endian 64-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
Byte sequences and concurrency safety
-------------------------------------
Care must be taken when concurrently accessing byte sequences from multiple domains: accessing a byte sequence will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.
### Atomicity
Every byte sequence operation that accesses more than one byte is not atomic. This includes iteration and scanning.
For example, consider the following program:
```
let size = 100_000_000
let b = Bytes.make size ' '
let update b f () =
Bytes.iteri (fun i x -> Bytes.set b i (Char.chr (f (Char.code x)))) b
let d1 = Domain.spawn (update b (fun x -> x + 1))
let d2 = Domain.spawn (update b (fun x -> 2 * x + 1))
let () = Domain.join d1; Domain.join d2
```
the bytes sequence `b` may contain a non-deterministic mixture of `'!'`, `'A'`, `'B'`, and `'C'` values.
After executing this code, each byte of the sequence `b` is either `'!'`, `'A'`, `'B'`, or `'C'`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](mutex#TYPEt)).
### Data races
If two domains only access disjoint parts of a byte sequence, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.
A data race is said to occur when two domains access the same byte without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the elements of the sequence.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location.
### Mixed-size accesses
Another subtle point is that if a data race involves mixed-size writes and reads to the same location, the order in which those writes and reads are observed by domains is not specified. For instance, the following code write sequentially a 32-bit integer and a `char` to the same index
```
let b = Bytes.make 10 '\000'
let d1 = Domain.spawn (fun () -> Bytes.set_int32_ne b 0 100; b.[0] <- 'd' )
```
In this situation, a domain that observes the write of 'd' to b.`0` is not guaranteed to also observe the write to indices `1`, `2`, or `3`.
| programming_docs |
ocaml Module Runtime_events.Timestamp Module Runtime\_events.Timestamp
================================
```
module Timestamp: sig .. end
```
```
type t
```
Type for the int64 timestamp to allow for future changes
```
val to_int64 : t -> int64
```
ocaml Module StdLabels.List Module StdLabels.List
=====================
```
module List: ListLabels
```
```
type 'a t = 'a list =
```
| | |
| --- | --- |
| `|` | `[]` |
| `|` | `(::) of `'a * 'a list`` |
An alias for the type of lists.
```
val length : 'a list -> int
```
Return the length (number of elements) of the given list.
```
val compare_lengths : 'a list -> 'b list -> int
```
Compare the lengths of two lists. `compare_lengths l1 l2` is equivalent to `compare (length l1) (length l2)`, except that the computation stops after reaching the end of the shortest list.
* **Since** 4.05.0
```
val compare_length_with : 'a list -> len:int -> int
```
Compare the length of a list to an integer. `compare_length_with l len` is equivalent to `compare (length l) len`, except that the computation stops after at most `len` iterations on the list.
* **Since** 4.05.0
```
val cons : 'a -> 'a list -> 'a list
```
`cons x xs` is `x :: xs`
* **Since** 4.05.0
```
val hd : 'a list -> 'a
```
Return the first element of the given list.
* **Raises** `Failure` if the list is empty.
```
val tl : 'a list -> 'a list
```
Return the given list without its first element.
* **Raises** `Failure` if the list is empty.
```
val nth : 'a list -> int -> 'a
```
Return the `n`-th element of the given list. The first element (head of the list) is at position 0.
* **Raises**
+ `Failure` if the list is too short.
+ `Invalid_argument` if `n` is negative.
```
val nth_opt : 'a list -> int -> 'a option
```
Return the `n`-th element of the given list. The first element (head of the list) is at position 0. Return `None` if the list is too short.
* **Since** 4.05
* **Raises** `Invalid_argument` if `n` is negative.
```
val rev : 'a list -> 'a list
```
List reversal.
```
val init : len:int -> f:(int -> 'a) -> 'a list
```
`init ~len ~f` is `[f 0; f 1; ...; f (len-1)]`, evaluated left to right.
* **Since** 4.06.0
* **Raises** `Invalid_argument` if `len < 0`.
```
val append : 'a list -> 'a list -> 'a list
```
Concatenate two lists. Same function as the infix operator `@`. Not tail-recursive (length of the first argument). The `@` operator is not tail-recursive either.
```
val rev_append : 'a list -> 'a list -> 'a list
```
`rev_append l1 l2` reverses `l1` and concatenates it with `l2`. This is equivalent to `(`[`ListLabels.rev`](listlabels#VALrev)`l1) @ l2`, but `rev_append` is tail-recursive and more efficient.
```
val concat : 'a list list -> 'a list
```
Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument + length of the longest sub-list).
```
val flatten : 'a list list -> 'a list
```
Same as [`ListLabels.concat`](listlabels#VALconcat). Not tail-recursive (length of the argument + length of the longest sub-list).
Comparison
----------
```
val equal : eq:('a -> 'a -> bool) -> 'a list -> 'a list -> bool
```
`equal eq [a1; ...; an] [b1; ..; bm]` holds when the two input lists have the same length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`.
Note: the `eq` function may be called even if the lists have different length. If you know your equality function is costly, you may want to check [`ListLabels.compare_lengths`](listlabels#VALcompare_lengths) first.
* **Since** 4.12.0
```
val compare : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> int
```
`compare cmp [a1; ...; an] [b1; ...; bm]` performs a lexicographic comparison of the two input lists, using the same `'a -> 'a -> int` interface as [`compare`](stdlib#VALcompare):
* `a1 :: l1` is smaller than `a2 :: l2` (negative result) if `a1` is smaller than `a2`, or if they are equal (0 result) and `l1` is smaller than `l2`
* the empty list `[]` is strictly smaller than non-empty lists
Note: the `cmp` function will be called even if the lists have different lengths.
* **Since** 4.12.0
Iterators
---------
```
val iter : f:('a -> unit) -> 'a list -> unit
```
`iter ~f [a1; ...; an]` applies function `f` in turn to `[a1; ...; an]`. It is equivalent to `f a1; f a2; ...; f an`.
```
val iteri : f:(int -> 'a -> unit) -> 'a list -> unit
```
Same as [`ListLabels.iter`](listlabels#VALiter), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
* **Since** 4.00.0
```
val map : f:('a -> 'b) -> 'a list -> 'b list
```
`map ~f [a1; ...; an]` applies function `f` to `a1, ..., an`, and builds the list `[f a1; ...; f an]` with the results returned by `f`. Not tail-recursive.
```
val mapi : f:(int -> 'a -> 'b) -> 'a list -> 'b list
```
Same as [`ListLabels.map`](listlabels#VALmap), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. Not tail-recursive.
* **Since** 4.00.0
```
val rev_map : f:('a -> 'b) -> 'a list -> 'b list
```
`rev_map ~f l` gives the same result as [`ListLabels.rev`](listlabels#VALrev)`(`[`ListLabels.map`](listlabels#VALmap)`f l)`, but is tail-recursive and more efficient.
```
val filter_map : f:('a -> 'b option) -> 'a list -> 'b list
```
`filter_map ~f l` applies `f` to every element of `l`, filters out the `None` elements and returns the list of the arguments of the `Some` elements.
* **Since** 4.08.0
```
val concat_map : f:('a -> 'b list) -> 'a list -> 'b list
```
`concat_map ~f l` gives the same result as [`ListLabels.concat`](listlabels#VALconcat)`(`[`ListLabels.map`](listlabels#VALmap)`f l)`. Tail-recursive.
* **Since** 4.10.0
```
val fold_left_map : f:('a -> 'b -> 'a * 'c) -> init:'a -> 'b list -> 'a * 'c list
```
`fold_left_map` is a combination of `fold_left` and `map` that threads an accumulator through calls to `f`.
* **Since** 4.11.0
```
val fold_left : f:('a -> 'b -> 'a) -> init:'a -> 'b list -> 'a
```
`fold_left ~f ~init [b1; ...; bn]` is `f (... (f (f init b1) b2) ...) bn`.
```
val fold_right : f:('a -> 'b -> 'b) -> 'a list -> init:'b -> 'b
```
`fold_right ~f [a1; ...; an] ~init` is `f a1 (f a2 (... (f an init) ...))`. Not tail-recursive.
Iterators on two lists
----------------------
```
val iter2 : f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit
```
`iter2 ~f [a1; ...; an] [b1; ...; bn]` calls in turn `f a1 b1; ...; f an bn`.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths.
```
val map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
```
`map2 ~f [a1; ...; an] [b1; ...; bn]` is `[f a1 b1; ...; f an bn]`.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths. Not tail-recursive.
```
val rev_map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
```
`rev_map2 ~f l1 l2` gives the same result as [`ListLabels.rev`](listlabels#VALrev)`(`[`ListLabels.map2`](listlabels#VALmap2)`f l1 l2)`, but is tail-recursive and more efficient.
```
val fold_left2 : f:('a -> 'b -> 'c -> 'a) -> init:'a -> 'b list -> 'c list -> 'a
```
`fold_left2 ~f ~init [a1; ...; an] [b1; ...; bn]` is `f (... (f (f init a1 b1) a2 b2) ...) an bn`.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths.
```
val fold_right2 : f:('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> init:'c -> 'c
```
`fold_right2 ~f [a1; ...; an] [b1; ...; bn] ~init` is `f a1 b1 (f a2 b2 (... (f an bn init) ...))`.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths. Not tail-recursive.
List scanning
-------------
```
val for_all : f:('a -> bool) -> 'a list -> bool
```
`for_all ~f [a1; ...; an]` checks if all elements of the list satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)` for a non-empty list and `true` if the list is empty.
```
val exists : f:('a -> bool) -> 'a list -> bool
```
`exists ~f [a1; ...; an]` checks if at least one element of the list satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)` for a non-empty list and `false` if the list is empty.
```
val for_all2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool
```
Same as [`ListLabels.for_all`](listlabels#VALfor_all), but for a two-argument predicate.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths.
```
val exists2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool
```
Same as [`ListLabels.exists`](listlabels#VALexists), but for a two-argument predicate.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths.
```
val mem : 'a -> set:'a list -> bool
```
`mem a ~set` is true if and only if `a` is equal to an element of `set`.
```
val memq : 'a -> set:'a list -> bool
```
Same as [`ListLabels.mem`](listlabels#VALmem), but uses physical equality instead of structural equality to compare list elements.
List searching
--------------
```
val find : f:('a -> bool) -> 'a list -> 'a
```
`find ~f l` returns the first element of the list `l` that satisfies the predicate `f`.
* **Raises** `Not_found` if there is no value that satisfies `f` in the list `l`.
```
val find_opt : f:('a -> bool) -> 'a list -> 'a option
```
`find ~f l` returns the first element of the list `l` that satisfies the predicate `f`. Returns `None` if there is no value that satisfies `f` in the list `l`.
* **Since** 4.05
```
val find_map : f:('a -> 'b option) -> 'a list -> 'b option
```
`find_map ~f l` applies `f` to the elements of `l` in order, and returns the first result of the form `Some v`, or `None` if none exist.
* **Since** 4.10.0
```
val filter : f:('a -> bool) -> 'a list -> 'a list
```
`filter ~f l` returns all the elements of the list `l` that satisfy the predicate `f`. The order of the elements in the input list is preserved.
```
val find_all : f:('a -> bool) -> 'a list -> 'a list
```
`find_all` is another name for [`ListLabels.filter`](listlabels#VALfilter).
```
val filteri : f:(int -> 'a -> bool) -> 'a list -> 'a list
```
Same as [`ListLabels.filter`](listlabels#VALfilter), but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
* **Since** 4.11.0
```
val partition : f:('a -> bool) -> 'a list -> 'a list * 'a list
```
`partition ~f l` returns a pair of lists `(l1, l2)`, where `l1` is the list of all the elements of `l` that satisfy the predicate `f`, and `l2` is the list of all the elements of `l` that do not satisfy `f`. The order of the elements in the input list is preserved.
```
val partition_map : f:('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list
```
`partition_map f l` returns a pair of lists `(l1, l2)` such that, for each element `x` of the input list `l`:
* if `f x` is `Left y1`, then `y1` is in `l1`, and
* if `f x` is `Right y2`, then `y2` is in `l2`.
The output elements are included in `l1` and `l2` in the same relative order as the corresponding input elements in `l`.
In particular, `partition_map (fun x -> if f x then Left x else Right x) l` is equivalent to `partition f l`.
* **Since** 4.12.0
Association lists
-----------------
```
val assoc : 'a -> ('a * 'b) list -> 'b
```
`assoc a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc a [ ...; (a,b); ...] = b` if `(a,b)` is the leftmost binding of `a` in list `l`.
* **Raises** `Not_found` if there is no value associated with `a` in the list `l`.
```
val assoc_opt : 'a -> ('a * 'b) list -> 'b option
```
`assoc_opt a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc_opt a [ ...; (a,b); ...] = Some b` if `(a,b)` is the leftmost binding of `a` in list `l`. Returns `None` if there is no value associated with `a` in the list `l`.
* **Since** 4.05
```
val assq : 'a -> ('a * 'b) list -> 'b
```
Same as [`ListLabels.assoc`](listlabels#VALassoc), but uses physical equality instead of structural equality to compare keys.
```
val assq_opt : 'a -> ('a * 'b) list -> 'b option
```
Same as [`ListLabels.assoc_opt`](listlabels#VALassoc_opt), but uses physical equality instead of structural equality to compare keys.
* **Since** 4.05.0
```
val mem_assoc : 'a -> map:('a * 'b) list -> bool
```
Same as [`ListLabels.assoc`](listlabels#VALassoc), but simply return `true` if a binding exists, and `false` if no bindings exist for the given key.
```
val mem_assq : 'a -> map:('a * 'b) list -> bool
```
Same as [`ListLabels.mem_assoc`](listlabels#VALmem_assoc), but uses physical equality instead of structural equality to compare keys.
```
val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list
```
`remove_assoc a l` returns the list of pairs `l` without the first pair with key `a`, if any. Not tail-recursive.
```
val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list
```
Same as [`ListLabels.remove_assoc`](listlabels#VALremove_assoc), but uses physical equality instead of structural equality to compare keys. Not tail-recursive.
Lists of pairs
--------------
```
val split : ('a * 'b) list -> 'a list * 'b list
```
Transform a list of pairs into a pair of lists: `split [(a1,b1); ...; (an,bn)]` is `([a1; ...; an], [b1; ...; bn])`. Not tail-recursive.
```
val combine : 'a list -> 'b list -> ('a * 'b) list
```
Transform a pair of lists into a list of pairs: `combine [a1; ...; an] [b1; ...; bn]` is `[(a1,b1); ...; (an,bn)]`.
* **Raises** `Invalid_argument` if the two lists have different lengths. Not tail-recursive.
Sorting
-------
```
val sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
```
Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, [`compare`](stdlib#VALcompare) is a suitable comparison function. The resulting list is sorted in increasing order. [`ListLabels.sort`](listlabels#VALsort) is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space.
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
```
val stable_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
```
Same as [`ListLabels.sort`](listlabels#VALsort), but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order).
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
```
val fast_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
```
Same as [`ListLabels.sort`](listlabels#VALsort) or [`ListLabels.stable_sort`](listlabels#VALstable_sort), whichever is faster on typical input.
```
val sort_uniq : cmp:('a -> 'a -> int) -> 'a list -> 'a list
```
Same as [`ListLabels.sort`](listlabels#VALsort), but also remove duplicates.
* **Since** 4.03.0
```
val merge : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> 'a list
```
Merge two lists: Assuming that `l1` and `l2` are sorted according to the comparison function `cmp`, `merge ~cmp l1 l2` will return a sorted list containing all the elements of `l1` and `l2`. If several elements compare equal, the elements of `l1` will be before the elements of `l2`. Not tail-recursive (sum of the lengths of the arguments).
Lists and Sequences
-------------------
```
val to_seq : 'a list -> 'a Seq.t
```
Iterate on the list.
* **Since** 4.07
```
val of_seq : 'a Seq.t -> 'a list
```
Create a list from a sequence.
* **Since** 4.07
ocaml Module CamlinternalFormat Module CamlinternalFormat
=========================
```
module CamlinternalFormat: sig .. end
```
```
val is_in_char_set : CamlinternalFormatBasics.char_set -> char -> bool
```
```
val rev_char_set : CamlinternalFormatBasics.char_set -> CamlinternalFormatBasics.char_set
```
```
type mutable_char_set = bytes
```
```
val create_char_set : unit -> mutable_char_set
```
```
val add_in_char_set : mutable_char_set -> char -> unit
```
```
val freeze_char_set : mutable_char_set -> CamlinternalFormatBasics.char_set
```
```
type ('a, 'b, 'c, 'd, 'e, 'f) param_format_ebb =
```
| | |
| --- | --- |
| `|` | `Param\_format\_EBB : `('x -> 'a0, 'b0, 'c0, 'd0, 'e0, 'f0) [CamlinternalFormatBasics.fmt](camlinternalformatbasics#TYPEfmt)` -> `('a0, 'b0, 'c0, 'd0, 'e0, 'f0) [param\_format\_ebb](camlinternalformat#TYPEparam_format_ebb)`` |
```
val param_format_of_ignored_format : ('a, 'b, 'c, 'd, 'y, 'x) CamlinternalFormatBasics.ignored -> ('x, 'b, 'c, 'y, 'e, 'f) CamlinternalFormatBasics.fmt -> ('a, 'b, 'c, 'd, 'e, 'f) param_format_ebb
```
```
type ('b, 'c) acc_formatting_gen =
```
| | |
| --- | --- |
| `|` | `Acc\_open\_tag of `('b, 'c) [acc](camlinternalformat#TYPEacc)`` |
| `|` | `Acc\_open\_box of `('b, 'c) [acc](camlinternalformat#TYPEacc)`` |
```
type ('b, 'c) acc =
```
| | |
| --- | --- |
| `|` | `Acc\_formatting\_lit of `('b, 'c) [acc](camlinternalformat#TYPEacc) * [CamlinternalFormatBasics.formatting\_lit](camlinternalformatbasics#TYPEformatting_lit)`` |
| `|` | `Acc\_formatting\_gen of `('b, 'c) [acc](camlinternalformat#TYPEacc) * ('b, 'c) [acc\_formatting\_gen](camlinternalformat#TYPEacc_formatting_gen)`` |
| `|` | `Acc\_string\_literal of `('b, 'c) [acc](camlinternalformat#TYPEacc) * string`` |
| `|` | `Acc\_char\_literal of `('b, 'c) [acc](camlinternalformat#TYPEacc) * char`` |
| `|` | `Acc\_data\_string of `('b, 'c) [acc](camlinternalformat#TYPEacc) * string`` |
| `|` | `Acc\_data\_char of `('b, 'c) [acc](camlinternalformat#TYPEacc) * char`` |
| `|` | `Acc\_delay of `('b, 'c) [acc](camlinternalformat#TYPEacc) * ('b -> 'c)`` |
| `|` | `Acc\_flush of `('b, 'c) [acc](camlinternalformat#TYPEacc)`` |
| `|` | `Acc\_invalid\_arg of `('b, 'c) [acc](camlinternalformat#TYPEacc) * string`` |
| `|` | `End\_of\_acc` |
```
type ('a, 'b) heter_list =
```
| | |
| --- | --- |
| `|` | `Cons : `'c * ('a0, 'b0) [heter\_list](camlinternalformat#TYPEheter_list)` -> `('c -> 'a0, 'b0) [heter\_list](camlinternalformat#TYPEheter_list)`` |
| `|` | `Nil : `('b1, 'b1) [heter\_list](camlinternalformat#TYPEheter_list)`` |
```
type ('b, 'c, 'e, 'f) fmt_ebb =
```
| | |
| --- | --- |
| `|` | `Fmt\_EBB : `('a, 'b0, 'c0, 'd, 'e0, 'f0) [CamlinternalFormatBasics.fmt](camlinternalformatbasics#TYPEfmt)` -> `('b0, 'c0, 'e0, 'f0) [fmt\_ebb](camlinternalformat#TYPEfmt_ebb)`` |
```
val make_printf : (('b, 'c) acc -> 'd) -> ('b, 'c) acc -> ('a, 'b, 'c, 'c, 'c, 'd) CamlinternalFormatBasics.fmt -> 'a
```
```
val make_iprintf : ('s -> 'f) -> 's -> ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.fmt -> 'a
```
```
val output_acc : out_channel -> (out_channel, unit) acc -> unit
```
```
val bufput_acc : Buffer.t -> (Buffer.t, unit) acc -> unit
```
```
val strput_acc : Buffer.t -> (unit, string) acc -> unit
```
```
val type_format : ('x, 'b, 'c, 't, 'u, 'v) CamlinternalFormatBasics.fmt -> ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.fmtty -> ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.fmt
```
```
val fmt_ebb_of_string : ?legacy_behavior:bool -> string -> ('b, 'c, 'e, 'f) fmt_ebb
```
```
val format_of_string_fmtty : string -> ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.fmtty -> ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6
```
```
val format_of_string_format : string -> ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6 -> ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6
```
```
val char_of_iconv : CamlinternalFormatBasics.int_conv -> char
```
```
val string_of_formatting_lit : CamlinternalFormatBasics.formatting_lit -> string
```
```
val string_of_fmtty : ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.fmtty -> string
```
```
val string_of_fmt : ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.fmt -> string
```
```
val open_box_of_string : string -> int * CamlinternalFormatBasics.block_type
```
```
val symm : ('a1, 'b1, 'c1, 'd1, 'e1, 'f1, 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) CamlinternalFormatBasics.fmtty_rel -> ('a2, 'b2, 'c2, 'd2, 'e2, 'f2, 'a1, 'b1, 'c1, 'd1, 'e1, 'f1) CamlinternalFormatBasics.fmtty_rel
```
```
val trans : ('a1, 'b1, 'c1, 'd1, 'e1, 'f1, 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) CamlinternalFormatBasics.fmtty_rel -> ('a2, 'b2, 'c2, 'd2, 'e2, 'f2, 'a3, 'b3, 'c3, 'd3, 'e3, 'f3) CamlinternalFormatBasics.fmtty_rel -> ('a1, 'b1, 'c1, 'd1, 'e1, 'f1, 'a3, 'b3, 'c3, 'd3, 'e3, 'f3) CamlinternalFormatBasics.fmtty_rel
```
```
val recast : ('a1, 'b1, 'c1, 'd1, 'e1, 'f1) CamlinternalFormatBasics.fmt -> ('a1, 'b1, 'c1, 'd1, 'e1, 'f1, 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) CamlinternalFormatBasics.fmtty_rel -> ('a2, 'b2, 'c2, 'd2, 'e2, 'f2) CamlinternalFormatBasics.fmt
```
| programming_docs |
ocaml Module Hashtbl Module Hashtbl
==============
```
module Hashtbl: sig .. end
```
Hash tables and hash functions.
Hash tables are hashed association tables, with in-place modification.
* **Alert unsynchronized\_access.** Unsynchronized accesses to hash tables are a programming error.
**Unsynchronized accesses**
Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a [`Mutex.t`](mutex#TYPEt)).
Generic interface
-----------------
```
type ('a, 'b) t
```
The type of hash tables from type `'a` to type `'b`.
```
val create : ?random:bool -> int -> ('a, 'b) t
```
`Hashtbl.create n` creates a new, empty hash table, with initial size `n`. For best results, `n` should be on the order of the expected number of elements that will be in the table. The table grows as needed, so `n` is just an initial guess.
The optional `~random` parameter (a boolean) controls whether the internal organization of the hash table is randomized at each execution of `Hashtbl.create` or deterministic over all executions.
A hash table that is created with `~random` set to `false` uses a fixed hash function ([`Hashtbl.hash`](hashtbl#VALhash)) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down.
A hash table that is created with `~random` set to `true` uses the seeded hash function [`Hashtbl.seeded_hash`](hashtbl#VALseeded_hash) with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among `2^{30}` different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using [`Hashtbl.fold`](hashtbl#VALfold) or [`Hashtbl.iter`](hashtbl#VALiter) is no longer deterministic: elements are enumerated in different orders at different runs of the program.
If no `~random` parameter is given, hash tables are created in non-random mode by default. This default can be changed either programmatically by calling [`Hashtbl.randomize`](hashtbl#VALrandomize) or by setting the `R` flag in the `OCAMLRUNPARAM` environment variable.
* **Before 4.00.0** the `~random` parameter was not present and all hash tables were created in non-randomized mode.
```
val clear : ('a, 'b) t -> unit
```
Empty a hash table. Use `reset` instead of `clear` to shrink the size of the bucket table to its initial size.
```
val reset : ('a, 'b) t -> unit
```
Empty a hash table and shrink the size of the bucket table to its initial size.
* **Since** 4.00.0
```
val copy : ('a, 'b) t -> ('a, 'b) t
```
Return a copy of the given hashtable.
```
val add : ('a, 'b) t -> 'a -> 'b -> unit
```
`Hashtbl.add tbl key data` adds a binding of `key` to `data` in table `tbl`. Previous bindings for `key` are not removed, but simply hidden. That is, after performing [`Hashtbl.remove`](hashtbl#VALremove)`tbl key`, the previous binding for `key`, if any, is restored. (Same behavior as with association lists.)
```
val find : ('a, 'b) t -> 'a -> 'b
```
`Hashtbl.find tbl x` returns the current binding of `x` in `tbl`, or raises `Not\_found` if no such binding exists.
```
val find_opt : ('a, 'b) t -> 'a -> 'b option
```
`Hashtbl.find_opt tbl x` returns the current binding of `x` in `tbl`, or `None` if no such binding exists.
* **Since** 4.05
```
val find_all : ('a, 'b) t -> 'a -> 'b list
```
`Hashtbl.find_all tbl x` returns the list of all data associated with `x` in `tbl`. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table.
```
val mem : ('a, 'b) t -> 'a -> bool
```
`Hashtbl.mem tbl x` checks if `x` is bound in `tbl`.
```
val remove : ('a, 'b) t -> 'a -> unit
```
`Hashtbl.remove tbl x` removes the current binding of `x` in `tbl`, restoring the previous binding if it exists. It does nothing if `x` is not bound in `tbl`.
```
val replace : ('a, 'b) t -> 'a -> 'b -> unit
```
`Hashtbl.replace tbl key data` replaces the current binding of `key` in `tbl` by a binding of `key` to `data`. If `key` is unbound in `tbl`, a binding of `key` to `data` is added to `tbl`. This is functionally equivalent to [`Hashtbl.remove`](hashtbl#VALremove)`tbl key` followed by [`Hashtbl.add`](hashtbl#VALadd)`tbl key data`.
```
val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit
```
`Hashtbl.iter f tbl` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`.
The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.
The behavior is not specified if the hash table is modified by `f` during the iteration.
```
val filter_map_inplace : ('a -> 'b -> 'b option) -> ('a, 'b) t -> unit
```
`Hashtbl.filter_map_inplace f tbl` applies `f` to all bindings in table `tbl` and update each binding depending on the result of `f`. If `f` returns `None`, the binding is discarded. If it returns `Some new_val`, the binding is update to associate the key to `new_val`.
Other comments for [`Hashtbl.iter`](hashtbl#VALiter) apply as well.
* **Since** 4.03.0
```
val fold : ('a -> 'b -> 'c -> 'c) -> ('a, 'b) t -> 'c -> 'c
```
`Hashtbl.fold f tbl init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`.
The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.
The behavior is not specified if the hash table is modified by `f` during the iteration.
```
val length : ('a, 'b) t -> int
```
`Hashtbl.length tbl` returns the number of bindings in `tbl`. It takes constant time. Multiple bindings are counted once each, so `Hashtbl.length` gives the number of times `Hashtbl.iter` calls its first argument.
```
val randomize : unit -> unit
```
After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: [`Hashtbl.create`](hashtbl#VALcreate) returns randomized hash tables, unless the `~random:false` optional parameter is given. The same effect can be achieved by setting the `R` parameter in the `OCAMLRUNPARAM` environment variable.
It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in [`Hashtbl.create`](hashtbl#VALcreate) call `Hashtbl.randomize()` at initialization time before any domains are created.
Note that once `Hashtbl.randomize()` was called, there is no way to revert to the non-randomized default behavior of [`Hashtbl.create`](hashtbl#VALcreate). This is intentional. Non-randomized hash tables can still be created using `Hashtbl.create ~random:false`.
* **Since** 4.00.0
```
val is_randomized : unit -> bool
```
Return `true` if the tables are currently created in randomized mode by default, `false` otherwise.
* **Since** 4.03.0
```
val rebuild : ?random:bool -> ('a, 'b) t -> ('a, 'b) t
```
Return a copy of the given hashtable. Unlike [`Hashtbl.copy`](hashtbl#VALcopy), [`Hashtbl.rebuild`](hashtbl#VALrebuild)`h` re-hashes all the (key, value) entries of the original table `h`. The returned hash table is randomized if `h` was randomized, or the optional `random` parameter is true, or if the default is to create randomized hash tables; see [`Hashtbl.create`](hashtbl#VALcreate) for more information.
[`Hashtbl.rebuild`](hashtbl#VALrebuild) can safely be used to import a hash table built by an old version of the [`Hashtbl`](hashtbl) module, then marshaled to persistent storage. After unmarshaling, apply [`Hashtbl.rebuild`](hashtbl#VALrebuild) to produce a hash table for the current version of the [`Hashtbl`](hashtbl) module.
* **Since** 4.12.0
```
type statistics = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `num\_bindings : `int`;` | `(*` | Number of bindings present in the table. Same value as returned by [`Hashtbl.length`](hashtbl#VALlength). | `*)` |
| | `num\_buckets : `int`;` | `(*` | Number of buckets in the table. | `*)` |
| | `max\_bucket\_length : `int`;` | `(*` | Maximal number of bindings per bucket. | `*)` |
| | `bucket\_histogram : `int array`;` | `(*` | Histogram of bucket sizes. This array `histo` has length `max_bucket_length + 1`. The value of `histo.(i)` is the number of buckets whose size is `i`. | `*)` |
`}` * **Since** 4.00.0
```
val stats : ('a, 'b) t -> statistics
```
`Hashtbl.stats tbl` returns statistics about the table `tbl`: number of buckets, size of the biggest bucket, distribution of buckets by size.
* **Since** 4.00.0
Hash tables and Sequences
-------------------------
```
val to_seq : ('a, 'b) t -> ('a * 'b) Seq.t
```
Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first.
The behavior is not specified if the hash table is modified during the iteration.
* **Since** 4.07
```
val to_seq_keys : ('a, 'b) t -> 'a Seq.t
```
Same as `Seq.map fst (to_seq m)`
* **Since** 4.07
```
val to_seq_values : ('a, 'b) t -> 'b Seq.t
```
Same as `Seq.map snd (to_seq m)`
* **Since** 4.07
```
val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit
```
Add the given bindings to the table, using [`Hashtbl.add`](hashtbl#VALadd)
* **Since** 4.07
```
val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit
```
Add the given bindings to the table, using [`Hashtbl.replace`](hashtbl#VALreplace)
* **Since** 4.07
```
val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t
```
Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using [`Hashtbl.replace_seq`](hashtbl#VALreplace_seq), which means that if two pairs have the same key, only the latest one will appear in the table.
* **Since** 4.07
Functorial interface
--------------------
The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins.
For instance, one might want to specialize a table for integer keys:
```
module IntHash =
struct
type t = int
let equal i j = i=j
let hash i = i land max_int
end
module IntHashtbl = Hashtbl.Make(IntHash)
let h = IntHashtbl.create 17 in
IntHashtbl.add h 12 "hello"
```
This creates a new module `IntHashtbl`, with a new type `'a
IntHashtbl.t` of tables from `int` to `'a`. In this example, `h` contains `string` values so its type is `string IntHashtbl.t`.
Note that the new type `'a IntHashtbl.t` is not compatible with the type `('a,'b) Hashtbl.t` of the generic interface. For example, `Hashtbl.length h` would not type-check, you must use `IntHashtbl.length`.
```
module type HashedType = sig .. end
```
The input signature of the functor [`Hashtbl.Make`](hashtbl.make).
```
module type S = sig .. end
```
The output signature of the functor [`Hashtbl.Make`](hashtbl.make).
```
module Make: functor (H : HashedType) -> S with type key = H.t
```
Functor building an implementation of the hashtable structure.
```
module type SeededHashedType = sig .. end
```
The input signature of the functor [`Hashtbl.MakeSeeded`](hashtbl.makeseeded).
```
module type SeededS = sig .. end
```
The output signature of the functor [`Hashtbl.MakeSeeded`](hashtbl.makeseeded).
```
module MakeSeeded: functor (H : SeededHashedType) -> SeededS with type key = H.t
```
Functor building an implementation of the hashtable structure.
The polymorphic hash functions
------------------------------
```
val hash : 'a -> int
```
`Hashtbl.hash x` associates a nonnegative integer to any value of any type. It is guaranteed that if `x = y` or `Stdlib.compare x y = 0`, then `hash x = hash y`. Moreover, `hash` always terminates, even on cyclic structures.
```
val seeded_hash : int -> 'a -> int
```
A variant of [`Hashtbl.hash`](hashtbl#VALhash) that is further parameterized by an integer seed.
* **Since** 4.00.0
```
val hash_param : int -> int -> 'a -> int
```
`Hashtbl.hash_param meaningful total x` computes a hash value for `x`, with the same properties as for `hash`. The two extra integer parameters `meaningful` and `total` give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure `x`, stopping after `meaningful` meaningful nodes were encountered, or `total` nodes (meaningful or not) were encountered. If `total` as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of `meaningful` and `total` means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters `meaningful` and `total` govern the tradeoff between accuracy and speed. As default choices, [`Hashtbl.hash`](hashtbl#VALhash) and [`Hashtbl.seeded_hash`](hashtbl#VALseeded_hash) take `meaningful = 10` and `total = 100`.
```
val seeded_hash_param : int -> int -> int -> 'a -> int
```
A variant of [`Hashtbl.hash_param`](hashtbl#VALhash_param) that is further parameterized by an integer seed. Usage: `Hashtbl.seeded_hash_param meaningful total seed x`.
* **Since** 4.00.0
ocaml Functor Ephemeron.K1.Make Functor Ephemeron.K1.Make
=========================
```
module Make: functor (H : Hashtbl.HashedType) -> Ephemeron.S with type key = H.t
```
Functor building an implementation of a weak hash table
| | | | | |
| --- | --- | --- | --- | --- |
| **Parameters:** |
| | | |
| --- | --- | --- |
| `H` | : | `[Hashtbl.HashedType](hashtbl.hashedtype)` |
|
Propose the same interface as usual hash table. However since the bindings are weak, even if `mem h k` is true, a subsequent `find h k` may raise `Not\_found` because the garbage collector can run between the two.
```
type key
```
```
type 'a t
```
```
val create : int -> 'a t
```
```
val clear : 'a t -> unit
```
```
val reset : 'a t -> unit
```
```
val copy : 'a t -> 'a t
```
```
val add : 'a t -> key -> 'a -> unit
```
```
val remove : 'a t -> key -> unit
```
```
val find : 'a t -> key -> 'a
```
```
val find_opt : 'a t -> key -> 'a option
```
```
val find_all : 'a t -> key -> 'a list
```
```
val replace : 'a t -> key -> 'a -> unit
```
```
val mem : 'a t -> key -> bool
```
```
val length : 'a t -> int
```
```
val stats : 'a t -> Hashtbl.statistics
```
```
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
```
```
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
```
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
```
val clean : 'a t -> unit
```
remove all dead bindings. Done automatically during automatic resizing.
```
val stats_alive : 'a t -> Hashtbl.statistics
```
same as [`Hashtbl.SeededS.stats`](hashtbl.seededs#VALstats) but only count the alive bindings
ocaml Module Int Module Int
==========
```
module Int: sig .. end
```
Integer values.
Integers are [`Sys.int_size`](sys#VALint_size) bits wide and use two's complement representation. All operations are taken modulo 2`Sys.int_size`. They do not fail on overflow.
* **Since** 4.08
Integers
--------
```
type t = int
```
The type for integer values.
```
val zero : int
```
`zero` is the integer `0`.
```
val one : int
```
`one` is the integer `1`.
```
val minus_one : int
```
`minus_one` is the integer `-1`.
```
val neg : int -> int
```
`neg x` is `~-x`.
```
val add : int -> int -> int
```
`add x y` is the addition `x + y`.
```
val sub : int -> int -> int
```
`sub x y` is the subtraction `x - y`.
```
val mul : int -> int -> int
```
`mul x y` is the multiplication `x * y`.
```
val div : int -> int -> int
```
`div x y` is the division `x / y`. See [`(/)`](stdlib#VAL(/)) for details.
```
val rem : int -> int -> int
```
`rem x y` is the remainder `x mod y`. See [`(mod)`](stdlib#VAL(mod)) for details.
```
val succ : int -> int
```
`succ x` is `add x 1`.
```
val pred : int -> int
```
`pred x` is `sub x 1`.
```
val abs : int -> int
```
`abs x` is the absolute value of `x`. That is `x` if `x` is positive and `neg x` if `x` is negative. **Warning.** This may be negative if the argument is [`Int.min_int`](int#VALmin_int).
```
val max_int : int
```
`max_int` is the greatest representable integer, `2{^[Sys.int_size - 1]} - 1`.
```
val min_int : int
```
`min_int` is the smallest representable integer, `-2{^[Sys.int_size - 1]}`.
```
val logand : int -> int -> int
```
`logand x y` is the bitwise logical and of `x` and `y`.
```
val logor : int -> int -> int
```
`logor x y` is the bitwise logical or of `x` and `y`.
```
val logxor : int -> int -> int
```
`logxor x y` is the bitwise logical exclusive or of `x` and `y`.
```
val lognot : int -> int
```
`lognot x` is the bitwise logical negation of `x`.
```
val shift_left : int -> int -> int
```
`shift_left x n` shifts `x` to the left by `n` bits. The result is unspecified if `n < 0` or `n >`[`Sys.int_size`](sys#VALint_size).
```
val shift_right : int -> int -> int
```
`shift_right x n` shifts `x` to the right by `n` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `n < 0` or `n >`[`Sys.int_size`](sys#VALint_size).
```
val shift_right_logical : int -> int -> int
```
`shift_right x n` shifts `x` to the right by `n` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `n < 0` or `n >`[`Sys.int_size`](sys#VALint_size).
Predicates and comparisons
--------------------------
```
val equal : int -> int -> bool
```
`equal x y` is `true` if and only if `x = y`.
```
val compare : int -> int -> int
```
`compare x y` is [`compare`](stdlib#VALcompare)`x y` but more efficient.
```
val min : int -> int -> int
```
Return the smaller of the two arguments.
* **Since** 4.13.0
```
val max : int -> int -> int
```
Return the greater of the two arguments.
* **Since** 4.13.0
Converting
----------
```
val to_float : int -> float
```
`to_float x` is `x` as a floating point number.
```
val of_float : float -> int
```
`of_float x` truncates `x` to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers.
```
val to_string : int -> string
```
`to_string x` is the written representation of `x` in decimal.
| programming_docs |
ocaml Functor Ephemeron.K2.MakeSeeded Functor Ephemeron.K2.MakeSeeded
===============================
```
module MakeSeeded: functor (H1 : Hashtbl.SeededHashedType) -> functor (H2 : Hashtbl.SeededHashedType) -> Ephemeron.SeededS with type key = H1.t * H2.t
```
Functor building an implementation of a weak hash table. The seed is similar to the one of [`Hashtbl.MakeSeeded`](hashtbl.makeseeded).
| | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- |
| **Parameters:** |
| | | |
| --- | --- | --- |
| `H1` | : | `[Hashtbl.SeededHashedType](hashtbl.seededhashedtype)` |
| `H2` | : | `[Hashtbl.SeededHashedType](hashtbl.seededhashedtype)` |
|
```
type key
```
```
type 'a t
```
```
val create : ?random:bool -> int -> 'a t
```
```
val clear : 'a t -> unit
```
```
val reset : 'a t -> unit
```
```
val copy : 'a t -> 'a t
```
```
val add : 'a t -> key -> 'a -> unit
```
```
val remove : 'a t -> key -> unit
```
```
val find : 'a t -> key -> 'a
```
```
val find_opt : 'a t -> key -> 'a option
```
```
val find_all : 'a t -> key -> 'a list
```
```
val replace : 'a t -> key -> 'a -> unit
```
```
val mem : 'a t -> key -> bool
```
```
val length : 'a t -> int
```
```
val stats : 'a t -> Hashtbl.statistics
```
```
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
```
```
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
```
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
```
val clean : 'a t -> unit
```
remove all dead bindings. Done automatically during automatic resizing.
```
val stats_alive : 'a t -> Hashtbl.statistics
```
same as [`Hashtbl.SeededS.stats`](hashtbl.seededs#VALstats) but only count the alive bindings
ocaml Module type Set.OrderedType Module type Set.OrderedType
===========================
```
module type OrderedType = sig .. end
```
Input signature of the functor [`Set.Make`](set.make).
```
type t
```
The type of the set elements.
```
val compare : t -> t -> int
```
A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`compare`](stdlib#VALcompare).
ocaml Module Option Module Option
=============
```
module Option: sig .. end
```
Option values.
Option values explicitly indicate the presence or absence of a value.
* **Since** 4.08
Options
-------
```
type 'a t = 'a option =
```
| | |
| --- | --- |
| `|` | `None` |
| `|` | `Some of `'a`` |
The type for option values. Either `None` or a value `Some v`.
```
val none : 'a option
```
`none` is `None`.
```
val some : 'a -> 'a option
```
`some v` is `Some v`.
```
val value : 'a option -> default:'a -> 'a
```
`value o ~default` is `v` if `o` is `Some v` and `default` otherwise.
```
val get : 'a option -> 'a
```
`get o` is `v` if `o` is `Some v` and raise otherwise.
* **Raises** `Invalid_argument` if `o` is `None`.
```
val bind : 'a option -> ('a -> 'b option) -> 'b option
```
`bind o f` is `f v` if `o` is `Some v` and `None` if `o` is `None`.
```
val join : 'a option option -> 'a option
```
`join oo` is `Some v` if `oo` is `Some (Some v)` and `None` otherwise.
```
val map : ('a -> 'b) -> 'a option -> 'b option
```
`map f o` is `None` if `o` is `None` and `Some (f v)` if `o` is `Some v`.
```
val fold : none:'a -> some:('b -> 'a) -> 'b option -> 'a
```
`fold ~none ~some o` is `none` if `o` is `None` and `some v` if `o` is `Some v`.
```
val iter : ('a -> unit) -> 'a option -> unit
```
`iter f o` is `f v` if `o` is `Some v` and `()` otherwise.
Predicates and comparisons
--------------------------
```
val is_none : 'a option -> bool
```
`is_none o` is `true` if and only if `o` is `None`.
```
val is_some : 'a option -> bool
```
`is_some o` is `true` if and only if `o` is `Some o`.
```
val equal : ('a -> 'a -> bool) -> 'a option -> 'a option -> bool
```
`equal eq o0 o1` is `true` if and only if `o0` and `o1` are both `None` or if they are `Some v0` and `Some v1` and `eq v0 v1` is `true`.
```
val compare : ('a -> 'a -> int) -> 'a option -> 'a option -> int
```
`compare cmp o0 o1` is a total order on options using `cmp` to compare values wrapped by `Some _`. `None` is smaller than `Some _` values.
Converting
----------
```
val to_result : none:'e -> 'a option -> ('a, 'e) result
```
`to_result ~none o` is `Ok v` if `o` is `Some v` and `Error none` otherwise.
```
val to_list : 'a option -> 'a list
```
`to_list o` is `[]` if `o` is `None` and `[v]` if `o` is `Some v`.
```
val to_seq : 'a option -> 'a Seq.t
```
`to_seq o` is `o` as a sequence. `None` is the empty sequence and `Some v` is the singleton sequence containing `v`.
ocaml Module type MoreLabels.Hashtbl.HashedType Module type MoreLabels.Hashtbl.HashedType
=========================================
```
module type HashedType = sig .. end
```
The input signature of the functor [`MoreLabels.Hashtbl.Make`](morelabels.hashtbl.make).
```
type t
```
The type of the hashtable keys.
```
val equal : t -> t -> bool
```
The equality predicate used to compare keys.
```
val hash : t -> int
```
A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include
* (`(=)`, [`MoreLabels.Hashtbl.HashedType.hash`](morelabels.hashtbl.hashedtype#VALhash)) for comparing objects by structure (provided objects do not contain floats)
* (`(fun x y -> compare x y = 0)`, [`MoreLabels.Hashtbl.HashedType.hash`](morelabels.hashtbl.hashedtype#VALhash)) for comparing objects by structure and handling [`nan`](stdlib#VALnan) correctly
* (`(==)`, [`MoreLabels.Hashtbl.HashedType.hash`](morelabels.hashtbl.hashedtype#VALhash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects).
ocaml Module Runtime_events Module Runtime\_events
======================
```
module Runtime_events: sig .. end
```
Runtime events - ring buffer-based runtime tracing
This module enables users to enable and subscribe to tracing events from the Garbage Collector and other parts of the OCaml runtime. This can be useful for diagnostic or performance monitoring purposes. This module can be used to subscribe to events for the current process or external processes asynchronously.
When enabled (either via setting the OCAML\_RUNTIME\_EVENTS\_START environment variable or calling Runtime\_events.start) a file with the pid of the process and extension .events will be created. By default this is in the current directory but can be over-ridden by the OCAML\_RUNTIME\_EVENTS\_DIR environment variable. Each domain maintains its own ring buffer in a section of the larger file into which it emits events.
There is additionally a set of C APIs in runtime\_events.h that can enable zero-impact monitoring of the current process or bindings for other languages.
The runtime events system's behaviour can be controlled by the following environment variables:
* OCAML\_RUNTIME\_EVENTS\_START if set will cause the runtime events system to be started as part of the OCaml runtime initialization.
* OCAML\_RUNTIME\_EVENTS\_DIR sets the directory where the runtime events ring buffers will be located. If not present the program's working directory will be used.
* OCAML\_RUNTIME\_EVENTS\_PRESERVE if set will prevent the OCaml runtime from removing its ring buffers when it terminates. This can help if monitoring very short running programs.
```
type runtime_counter =
```
| | |
| --- | --- |
| `|` | `EV\_C\_FORCE\_MINOR\_ALLOC\_SMALL` |
| `|` | `EV\_C\_FORCE\_MINOR\_MAKE\_VECT` |
| `|` | `EV\_C\_FORCE\_MINOR\_SET\_MINOR\_HEAP\_SIZE` |
| `|` | `EV\_C\_FORCE\_MINOR\_MEMPROF` |
| `|` | `EV\_C\_MINOR\_PROMOTED` |
| `|` | `EV\_C\_MINOR\_ALLOCATED` |
| `|` | `EV\_C\_REQUEST\_MAJOR\_ALLOC\_SHR` |
| `|` | `EV\_C\_REQUEST\_MAJOR\_ADJUST\_GC\_SPEED` |
| `|` | `EV\_C\_REQUEST\_MINOR\_REALLOC\_REF\_TABLE` |
| `|` | `EV\_C\_REQUEST\_MINOR\_REALLOC\_EPHE\_REF\_TABLE` |
| `|` | `EV\_C\_REQUEST\_MINOR\_REALLOC\_CUSTOM\_TABLE` |
The type for counter events emitted by the runtime
```
type runtime_phase =
```
| | |
| --- | --- |
| `|` | `EV\_EXPLICIT\_GC\_SET` |
| `|` | `EV\_EXPLICIT\_GC\_STAT` |
| `|` | `EV\_EXPLICIT\_GC\_MINOR` |
| `|` | `EV\_EXPLICIT\_GC\_MAJOR` |
| `|` | `EV\_EXPLICIT\_GC\_FULL\_MAJOR` |
| `|` | `EV\_EXPLICIT\_GC\_COMPACT` |
| `|` | `EV\_MAJOR` |
| `|` | `EV\_MAJOR\_SWEEP` |
| `|` | `EV\_MAJOR\_MARK\_ROOTS` |
| `|` | `EV\_MAJOR\_MARK` |
| `|` | `EV\_MINOR` |
| `|` | `EV\_MINOR\_LOCAL\_ROOTS` |
| `|` | `EV\_MINOR\_FINALIZED` |
| `|` | `EV\_EXPLICIT\_GC\_MAJOR\_SLICE` |
| `|` | `EV\_FINALISE\_UPDATE\_FIRST` |
| `|` | `EV\_FINALISE\_UPDATE\_LAST` |
| `|` | `EV\_INTERRUPT\_REMOTE` |
| `|` | `EV\_MAJOR\_EPHE\_MARK` |
| `|` | `EV\_MAJOR\_EPHE\_SWEEP` |
| `|` | `EV\_MAJOR\_FINISH\_MARKING` |
| `|` | `EV\_MAJOR\_GC\_CYCLE\_DOMAINS` |
| `|` | `EV\_MAJOR\_GC\_PHASE\_CHANGE` |
| `|` | `EV\_MAJOR\_GC\_STW` |
| `|` | `EV\_MAJOR\_MARK\_OPPORTUNISTIC` |
| `|` | `EV\_MAJOR\_SLICE` |
| `|` | `EV\_MAJOR\_FINISH\_CYCLE` |
| `|` | `EV\_MINOR\_CLEAR` |
| `|` | `EV\_MINOR\_FINALIZERS\_OLDIFY` |
| `|` | `EV\_MINOR\_GLOBAL\_ROOTS` |
| `|` | `EV\_MINOR\_LEAVE\_BARRIER` |
| `|` | `EV\_STW\_API\_BARRIER` |
| `|` | `EV\_STW\_HANDLER` |
| `|` | `EV\_STW\_LEADER` |
| `|` | `EV\_MAJOR\_FINISH\_SWEEPING` |
| `|` | `EV\_MINOR\_FINALIZERS\_ADMIN` |
| `|` | `EV\_MINOR\_REMEMBERED\_SET` |
| `|` | `EV\_MINOR\_REMEMBERED\_SET\_PROMOTE` |
| `|` | `EV\_MINOR\_LOCAL\_ROOTS\_PROMOTE` |
| `|` | `EV\_DOMAIN\_CONDITION\_WAIT` |
| `|` | `EV\_DOMAIN\_RESIZE\_HEAP\_RESERVATION` |
The type for span events emitted by the runtime
```
type lifecycle =
```
| | |
| --- | --- |
| `|` | `EV\_RING\_START` |
| `|` | `EV\_RING\_STOP` |
| `|` | `EV\_RING\_PAUSE` |
| `|` | `EV\_RING\_RESUME` |
| `|` | `EV\_FORK\_PARENT` |
| `|` | `EV\_FORK\_CHILD` |
| `|` | `EV\_DOMAIN\_SPAWN` |
| `|` | `EV\_DOMAIN\_TERMINATE` |
Lifecycle events for the ring itself
```
val lifecycle_name : lifecycle -> string
```
Return a string representation of a given lifecycle event type
```
val runtime_phase_name : runtime_phase -> string
```
Return a string representation of a given runtime phase event type
```
val runtime_counter_name : runtime_counter -> string
```
Return a string representation of a given runtime counter type
```
type cursor
```
Type of the cursor used when consuming
```
module Timestamp: sig .. end
```
```
module Callbacks: sig .. end
```
```
val start : unit -> unit
```
`start ()` will start the collection of events in the runtime if not already started.
Events can be consumed by creating a cursor with `create_cursor` and providing a set of callbacks to be called for each type of event.
```
val pause : unit -> unit
```
`pause ()` will pause the collection of events in the runtime. Traces are collected if the program has called `Runtime\_events.start ()` or the OCAML\_RUNTIME\_EVENTS\_START environment variable has been set.
```
val resume : unit -> unit
```
`resume ()` will resume the collection of events in the runtime. Traces are collected if the program has called `Runtime\_events.start ()` or the OCAML\_RUNTIME\_EVENTS\_START environment variable has been set.
```
val create_cursor : (string * int) option -> cursor
```
`create_cursor path_pid` creates a cursor to read from an runtime\_events. Cursors can be created for runtime\_events in and out of process. A runtime\_events ring-buffer may have multiple cursors reading from it at any point in time and a program may have multiple cursors open concurrently (for example if multiple consumers want different sets of events). If `path_pid` is None then a cursor is created for the current process. Otherwise the pair contains a string `path` to the directory that contains the `pid`.events file and int `pid` for the runtime\_events of an external process to monitor.
```
val free_cursor : cursor -> unit
```
Free a previously created runtime\_events cursor
```
val read_poll : cursor -> Callbacks.t -> int option -> int
```
`read_poll cursor callbacks max_option` calls the corresponding functions on `callbacks` for up to `max_option` events read off `cursor`'s runtime\_events and returns the number of events read.
ocaml Module Queue Module Queue
============
```
module Queue: sig .. end
```
First-in first-out queues.
This module implements queues (FIFOs), with in-place modification.
* **Alert unsynchronized\_access.** Unsynchronized accesses to queues are a programming error.
**Unsynchronized accesses**
Unsynchronized accesses to a queue may lead to an invalid queue state. Thus, concurrent accesses to queues must be synchronized (for instance with a [`Mutex.t`](mutex#TYPEt)).
```
type 'a t
```
The type of queues containing elements of type `'a`.
```
exception Empty
```
Raised when [`Queue.take`](queue#VALtake) or [`Queue.peek`](queue#VALpeek) is applied to an empty queue.
```
val create : unit -> 'a t
```
Return a new queue, initially empty.
```
val add : 'a -> 'a t -> unit
```
`add x q` adds the element `x` at the end of the queue `q`.
```
val push : 'a -> 'a t -> unit
```
`push` is a synonym for `add`.
```
val take : 'a t -> 'a
```
`take q` removes and returns the first element in queue `q`, or raises [`Queue.Empty`](queue#EXCEPTIONEmpty) if the queue is empty.
```
val take_opt : 'a t -> 'a option
```
`take_opt q` removes and returns the first element in queue `q`, or returns `None` if the queue is empty.
* **Since** 4.08
```
val pop : 'a t -> 'a
```
`pop` is a synonym for `take`.
```
val peek : 'a t -> 'a
```
`peek q` returns the first element in queue `q`, without removing it from the queue, or raises [`Queue.Empty`](queue#EXCEPTIONEmpty) if the queue is empty.
```
val peek_opt : 'a t -> 'a option
```
`peek_opt q` returns the first element in queue `q`, without removing it from the queue, or returns `None` if the queue is empty.
* **Since** 4.08
```
val top : 'a t -> 'a
```
`top` is a synonym for `peek`.
```
val clear : 'a t -> unit
```
Discard all elements from a queue.
```
val copy : 'a t -> 'a t
```
Return a copy of the given queue.
```
val is_empty : 'a t -> bool
```
Return `true` if the given queue is empty, `false` otherwise.
```
val length : 'a t -> int
```
Return the number of elements in a queue.
```
val iter : ('a -> unit) -> 'a t -> unit
```
`iter f q` applies `f` in turn to all elements of `q`, from the least recently entered to the most recently entered. The queue itself is unchanged.
```
val fold : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b
```
`fold f accu q` is equivalent to `List.fold_left f accu l`, where `l` is the list of `q`'s elements. The queue remains unchanged.
```
val transfer : 'a t -> 'a t -> unit
```
`transfer q1 q2` adds all of `q1`'s elements at the end of the queue `q2`, then clears `q1`. It is equivalent to the sequence `iter (fun x -> add x q2) q1; clear q1`, but runs in constant time.
Iterators
---------
```
val to_seq : 'a t -> 'a Seq.t
```
Iterate on the queue, in front-to-back order. The behavior is not specified if the queue is modified during the iteration.
* **Since** 4.07
```
val add_seq : 'a t -> 'a Seq.t -> unit
```
Add the elements from a sequence to the end of the queue.
* **Since** 4.07
```
val of_seq : 'a Seq.t -> 'a t
```
Create a queue from a sequence.
* **Since** 4.07
ocaml Module Runtime_events.Callbacks Module Runtime\_events.Callbacks
================================
```
module Callbacks: sig .. end
```
```
type t
```
Type of callbacks
```
val create : ?runtime_begin:(int -> Runtime_events.Timestamp.t -> Runtime_events.runtime_phase -> unit) -> ?runtime_end:(int -> Runtime_events.Timestamp.t -> Runtime_events.runtime_phase -> unit) -> ?runtime_counter:(int -> Runtime_events.Timestamp.t -> Runtime_events.runtime_counter -> int -> unit) -> ?alloc:(int -> Runtime_events.Timestamp.t -> int array -> unit) -> ?lifecycle:(int -> Runtime_events.Timestamp.t -> Runtime_events.lifecycle -> int option -> unit) -> ?lost_events:(int -> int -> unit) -> unit -> t
```
Create a `Callback` that optionally subscribes to one or more runtime events. The first int supplied to callbacks is the ring buffer index. Each domain owns a single ring buffer for the duration of the domain's existence. After a domain terminates, a newly spawned domain may take ownership of the ring buffer. A `runtime_begin` callback is called when the runtime enters a new phase (e.g a runtime\_begin with EV\_MINOR is called at the start of a minor GC). A `runtime_end` callback is called when the runtime leaves a certain phase. The `runtime_counter` callback is called when a counter is emitted by the runtime. `lifecycle` callbacks are called when the ring undergoes a change in lifecycle and a consumer may need to respond. `alloc` callbacks are currently only called on the instrumented runtime. `lost_events` callbacks are called if the consumer code detects some unconsumed events have been overwritten.
ocaml Module Float Module Float
============
```
module Float: sig .. end
```
Floating-point arithmetic.
OCaml's floating-point numbers follow the IEEE 754 standard, using double precision (64 bits) numbers. Floating-point operations never raise an exception on overflow, underflow, division by zero, etc. Instead, special IEEE numbers are returned as appropriate, such as `infinity` for `1.0 /. 0.0`, `neg_infinity` for `-1.0 /. 0.0`, and `nan` ('not a number') for `0.0 /. 0.0`. These special numbers then propagate through floating-point computations as expected: for instance, `1.0 /. infinity` is `0.0`, basic arithmetic operations (`+.`, `-.`, `*.`, `/.`) with `nan` as an argument return `nan`, ...
* **Since** 4.07.0
```
val zero : float
```
The floating point 0.
* **Since** 4.08.0
```
val one : float
```
The floating-point 1.
* **Since** 4.08.0
```
val minus_one : float
```
The floating-point -1.
* **Since** 4.08.0
```
val neg : float -> float
```
Unary negation.
```
val add : float -> float -> float
```
Floating-point addition.
```
val sub : float -> float -> float
```
Floating-point subtraction.
```
val mul : float -> float -> float
```
Floating-point multiplication.
```
val div : float -> float -> float
```
Floating-point division.
```
val fma : float -> float -> float -> float
```
`fma x y z` returns `x * y + z`, with a best effort for computing this expression with a single rounding, using either hardware instructions (providing full IEEE compliance) or a software emulation.
On 64-bit Cygwin, 64-bit mingw-w64 and MSVC 2017 and earlier, this function may be emulated owing to known bugs on limitations on these platforms. Note: since software emulation of the fma is costly, make sure that you are using hardware fma support if performance matters.
* **Since** 4.08.0
```
val rem : float -> float -> float
```
`rem a b` returns the remainder of `a` with respect to `b`. The returned value is `a -. n *. b`, where `n` is the quotient `a /. b` rounded towards zero to an integer.
```
val succ : float -> float
```
`succ x` returns the floating point number right after `x` i.e., the smallest floating-point number greater than `x`. See also [`Float.next_after`](float#VALnext_after).
* **Since** 4.08.0
```
val pred : float -> float
```
`pred x` returns the floating-point number right before `x` i.e., the greatest floating-point number smaller than `x`. See also [`Float.next_after`](float#VALnext_after).
* **Since** 4.08.0
```
val abs : float -> float
```
`abs f` returns the absolute value of `f`.
```
val infinity : float
```
Positive infinity.
```
val neg_infinity : float
```
Negative infinity.
```
val nan : float
```
A special floating-point value denoting the result of an undefined operation such as `0.0 /. 0.0`. Stands for 'not a number'. Any floating-point operation with `nan` as argument returns `nan` as result. As for floating-point comparisons, `=`, `<`, `<=`, `>` and `>=` return `false` and `<>` returns `true` if one or both of their arguments is `nan`.
```
val pi : float
```
The constant pi.
```
val max_float : float
```
The largest positive finite value of type `float`.
```
val min_float : float
```
The smallest positive, non-zero, non-denormalized value of type `float`.
```
val epsilon : float
```
The difference between `1.0` and the smallest exactly representable floating-point number greater than `1.0`.
```
val is_finite : float -> bool
```
`is_finite x` is `true` if and only if `x` is finite i.e., not infinite and not [`Float.nan`](float#VALnan).
* **Since** 4.08.0
```
val is_infinite : float -> bool
```
`is_infinite x` is `true` if and only if `x` is [`Float.infinity`](float#VALinfinity) or [`Float.neg_infinity`](float#VALneg_infinity).
* **Since** 4.08.0
```
val is_nan : float -> bool
```
`is_nan x` is `true` if and only if `x` is not a number (see [`Float.nan`](float#VALnan)).
* **Since** 4.08.0
```
val is_integer : float -> bool
```
`is_integer x` is `true` if and only if `x` is an integer.
* **Since** 4.08.0
```
val of_int : int -> float
```
Convert an integer to floating-point.
```
val to_int : float -> int
```
Truncate the given floating-point number to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers.
```
val of_string : string -> float
```
Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by `0x` or `0X`). The format of decimal floating-point numbers is `[-] dd.ddd (e|E) [+|-] dd`, where `d` stands for a decimal digit. The format of hexadecimal floating-point numbers is `[-] 0(x|X) hh.hhh (p|P) [+|-] dd`, where `h` stands for an hexadecimal digit and `d` for a decimal digit. In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional. The `_` (underscore) character can appear anywhere in the string and is ignored. Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon.
* **Raises** `Failure` if the given string is not a valid representation of a float.
```
val of_string_opt : string -> float option
```
Same as `of_string`, but returns `None` instead of raising.
```
val to_string : float -> string
```
Return a string representation of a floating-point number.
This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see [`Printf`](printf).
This function is an alias for [`string_of_float`](stdlib#VALstring_of_float).
```
type fpclass = fpclass =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `FP\_normal` | `(*` | Normal number, none of the below | `*)` |
| `|` | `FP\_subnormal` | `(*` | Number very close to 0.0, has reduced precision | `*)` |
| `|` | `FP\_zero` | `(*` | Number is 0.0 or -0.0 | `*)` |
| `|` | `FP\_infinite` | `(*` | Number is positive or negative infinity | `*)` |
| `|` | `FP\_nan` | `(*` | Not a number: result of an undefined operation | `*)` |
The five classes of floating-point numbers, as determined by the [`Float.classify_float`](float#VALclassify_float) function.
```
val classify_float : float -> fpclass
```
Return the class of the given floating-point number: normal, subnormal, zero, infinite, or not a number.
```
val pow : float -> float -> float
```
Exponentiation.
```
val sqrt : float -> float
```
Square root.
```
val cbrt : float -> float
```
Cube root.
* **Since** 4.13.0
```
val exp : float -> float
```
Exponential.
```
val exp2 : float -> float
```
Base 2 exponential function.
* **Since** 4.13.0
```
val log : float -> float
```
Natural logarithm.
```
val log10 : float -> float
```
Base 10 logarithm.
```
val log2 : float -> float
```
Base 2 logarithm.
* **Since** 4.13.0
```
val expm1 : float -> float
```
`expm1 x` computes `exp x -. 1.0`, giving numerically-accurate results even if `x` is close to `0.0`.
```
val log1p : float -> float
```
`log1p x` computes `log(1.0 +. x)` (natural logarithm), giving numerically-accurate results even if `x` is close to `0.0`.
```
val cos : float -> float
```
Cosine. Argument is in radians.
```
val sin : float -> float
```
Sine. Argument is in radians.
```
val tan : float -> float
```
Tangent. Argument is in radians.
```
val acos : float -> float
```
Arc cosine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `0.0` and `pi`.
```
val asin : float -> float
```
Arc sine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `-pi/2` and `pi/2`.
```
val atan : float -> float
```
Arc tangent. Result is in radians and is between `-pi/2` and `pi/2`.
```
val atan2 : float -> float -> float
```
`atan2 y x` returns the arc tangent of `y /. x`. The signs of `x` and `y` are used to determine the quadrant of the result. Result is in radians and is between `-pi` and `pi`.
```
val hypot : float -> float -> float
```
`hypot x y` returns `sqrt(x *. x + y *. y)`, that is, the length of the hypotenuse of a right-angled triangle with sides of length `x` and `y`, or, equivalently, the distance of the point `(x,y)` to origin. If one of `x` or `y` is infinite, returns `infinity` even if the other is `nan`.
```
val cosh : float -> float
```
Hyperbolic cosine. Argument is in radians.
```
val sinh : float -> float
```
Hyperbolic sine. Argument is in radians.
```
val tanh : float -> float
```
Hyperbolic tangent. Argument is in radians.
```
val acosh : float -> float
```
Hyperbolic arc cosine. The argument must fall within the range `[1.0, inf]`. Result is in radians and is between `0.0` and `inf`.
* **Since** 4.13.0
```
val asinh : float -> float
```
Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians.
* **Since** 4.13.0
```
val atanh : float -> float
```
Hyperbolic arc tangent. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and ranges over the entire real line.
* **Since** 4.13.0
```
val erf : float -> float
```
Error function. The argument ranges over the entire real line. The result is always within `[-1.0, 1.0]`.
* **Since** 4.13.0
```
val erfc : float -> float
```
Complementary error function (`erfc x = 1 - erf x`). The argument ranges over the entire real line. The result is always within `[-1.0, 1.0]`.
* **Since** 4.13.0
```
val trunc : float -> float
```
`trunc x` rounds `x` to the nearest integer whose absolute value is less than or equal to `x`.
* **Since** 4.08.0
```
val round : float -> float
```
`round x` rounds `x` to the nearest integer with ties (fractional values of 0.5) rounded away from zero, regardless of the current rounding direction. If `x` is an integer, `+0.`, `-0.`, `nan`, or infinite, `x` itself is returned.
On 64-bit mingw-w64, this function may be emulated owing to a bug in the C runtime library (CRT) on this platform.
* **Since** 4.08.0
```
val ceil : float -> float
```
Round above to an integer value. `ceil f` returns the least integer value greater than or equal to `f`. The result is returned as a float.
```
val floor : float -> float
```
Round below to an integer value. `floor f` returns the greatest integer value less than or equal to `f`. The result is returned as a float.
```
val next_after : float -> float -> float
```
`next_after x y` returns the next representable floating-point value following `x` in the direction of `y`. More precisely, if `y` is greater (resp. less) than `x`, it returns the smallest (resp. largest) representable number greater (resp. less) than `x`. If `x` equals `y`, the function returns `y`. If `x` or `y` is `nan`, a `nan` is returned. Note that `next_after max_float infinity = infinity` and that `next_after 0. infinity` is the smallest denormalized positive number. If `x` is the smallest denormalized positive number, `next_after x 0. = 0.`
* **Since** 4.08.0
```
val copy_sign : float -> float -> float
```
`copy_sign x y` returns a float whose absolute value is that of `x` and whose sign is that of `y`. If `x` is `nan`, returns `nan`. If `y` is `nan`, returns either `x` or `-. x`, but it is not specified which.
```
val sign_bit : float -> bool
```
`sign_bit x` is `true` if and only if the sign bit of `x` is set. For example `sign_bit 1.` and `signbit 0.` are `false` while `sign_bit (-1.)` and `sign_bit (-0.)` are `true`.
* **Since** 4.08.0
```
val frexp : float -> float * int
```
`frexp f` returns the pair of the significant and the exponent of `f`. When `f` is zero, the significant `x` and the exponent `n` of `f` are equal to zero. When `f` is non-zero, they are defined by `f = x *. 2 ** n` and `0.5 <= x < 1.0`.
```
val ldexp : float -> int -> float
```
`ldexp x n` returns `x *. 2 ** n`.
```
val modf : float -> float * float
```
`modf f` returns the pair of the fractional and integral part of `f`.
```
type t = float
```
An alias for the type of floating-point numbers.
```
val compare : t -> t -> int
```
`compare x y` returns `0` if `x` is equal to `y`, a negative integer if `x` is less than `y`, and a positive integer if `x` is greater than `y`. `compare` treats `nan` as equal to itself and less than any other float value. This treatment of `nan` ensures that `compare` defines a total ordering relation.
```
val equal : t -> t -> bool
```
The equal function for floating-point numbers, compared using [`Float.compare`](float#VALcompare).
```
val min : t -> t -> t
```
`min x y` returns the minimum of `x` and `y`. It returns `nan` when `x` or `y` is `nan`. Moreover `min (-0.) (+0.) = -0.`
* **Since** 4.08.0
```
val max : float -> float -> float
```
`max x y` returns the maximum of `x` and `y`. It returns `nan` when `x` or `y` is `nan`. Moreover `max (-0.) (+0.) = +0.`
* **Since** 4.08.0
```
val min_max : float -> float -> float * float
```
`min_max x y` is `(min x y, max x y)`, just more efficient.
* **Since** 4.08.0
```
val min_num : t -> t -> t
```
`min_num x y` returns the minimum of `x` and `y` treating `nan` as missing values. If both `x` and `y` are `nan`, `nan` is returned. Moreover `min_num (-0.) (+0.) = -0.`
* **Since** 4.08.0
```
val max_num : t -> t -> t
```
`max_num x y` returns the maximum of `x` and `y` treating `nan` as missing values. If both `x` and `y` are `nan` `nan` is returned. Moreover `max_num (-0.) (+0.) = +0.`
* **Since** 4.08.0
```
val min_max_num : float -> float -> float * float
```
`min_max_num x y` is `(min_num x y, max_num x y)`, just more efficient. Note that in particular `min_max_num x nan = (x, x)` and `min_max_num nan y = (y, y)`.
* **Since** 4.08.0
```
val hash : t -> int
```
The hash function for floating-point numbers.
```
module Array: sig .. end
```
Float arrays with packed representation.
```
module ArrayLabels: sig .. end
```
Float arrays with packed representation (labeled functions).
| programming_docs |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.