code
stringlengths
1
25.8M
language
stringclasses
18 values
source
stringclasses
4 values
repo
stringclasses
78 values
path
stringlengths
0
268
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2017 Orcun Gumus # """A function for calculate the communicability of two nodes of a big big graph""" import networkx import numpy import math import fastremover import time from scipy.sparse import csr_matrix, lil_matrix from bigmultiplier import bigmultiplier def timer(function, *args, **kwargs): start = time.time() kreturn = function(*args, **kwargs) end = time.time(); print("{} {} seconds".format(function.__name__, end - start)) return kreturn def communicability(network, nodes_list_1, nodes_list_2, walk=1): """ A function for calculate apprx communicability of two group of node on a graph total_point: Total point within two list of nodes walk_total_points: Total points at the end of the walks points: Distribution of points at the end :param walk: Total walk lenth, longer walks are harder to compute :type walk: int :param network: A giant network :type network: networkx.Graph :param nodes_list_1: A group of nodes :type nodes_list_1: list(int) :param nodes_list_2: A group of nodes :type nodes_list_2: list(int) :rtype total_point: float :rtype walk_total_points: list(float) :rtype points: list(float) """ walk = walk + 1 network = fastremover.fastremover(network, 1, WIDTH=100) print("SHAPE1:", len(network.nodes())) adj_sparse = networkx.to_scipy_sparse_matrix(network, dtype=numpy.float32) print("SHAPE2:", adj_sparse.shape) print("Sparse matrix created") assert isinstance(adj_sparse, csr_matrix) nodes = network.nodes() x_ = []; y_ = [] for x in nodes_list_1: for y in nodes_list_2: try: xx = nodes.index(x) yy = nodes.index(y) except ValueError as e: pass else: x_.append(xx) y_.append(yy) print("Nodes created") adj_sparse_ = adj_sparse.copy() result_sparse = csr_matrix(adj_sparse.shape, dtype=numpy.float32) print("Copied") walk_total_points = [] for i in range(1, walk): start = time.time() result_sparse = result_sparse + adj_sparse_ / math.factorial(i) end = time.time(); print("{} {} seconds".format("Sum divide", end - start)) walk_total_points.append(result_sparse[x_, y_].sum()) start = time.time() adj_sparse_ = bigmultiplier(adj_sparse_, adj_sparse) end = time.time(); print("{} {} seconds".format("bigmultiplier", end - start)) print("Walk completed") start = time.time() result_sparse = result_sparse + adj_sparse_ / math.factorial(walk) end = time.time(); print("{} {} seconds".format("Sum divide", end - start)) walk_total_points.append(result_sparse[x_, y_].sum()) assert isinstance(result_sparse, csr_matrix) assert isinstance(adj_sparse_, csr_matrix) start = time.time() total_point = float(result_sparse[x_, y_].sum()) end = time.time(); print("{} {} seconds".format("total point", end - start)) start = time.time() points = [item for sublist in result_sparse[x_, y_].tolist() for item in sublist] end = time.time();print("{} {} seconds".format("points dist", end - start)) return total_point, walk_total_points, points
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import datetime from helpers import unittest import luigi from luigi.parameter import DateIntervalParameter as DI class DateIntervalTest(unittest.TestCase): def test_date(self): di = DI().parse('2012-01-01') self.assertEqual(di.dates(), [datetime.date(2012, 1, 1)]) self.assertEqual(di.next().dates(), [datetime.date(2012, 1, 2)]) self.assertEqual(di.prev().dates(), [datetime.date(2011, 12, 31)]) self.assertEqual(str(di), '2012-01-01') def test_month(self): di = DI().parse('2012-01') self.assertEqual(di.dates(), [datetime.date(2012, 1, 1) + datetime.timedelta(i) for i in range(31)]) self.assertEqual(di.next().dates(), [datetime.date(2012, 2, 1) + datetime.timedelta(i) for i in range(29)]) self.assertEqual(di.prev().dates(), [datetime.date(2011, 12, 1) + datetime.timedelta(i) for i in range(31)]) self.assertEqual(str(di), '2012-01') def test_year(self): di = DI().parse('2012') self.assertEqual(di.dates(), [datetime.date(2012, 1, 1) + datetime.timedelta(i) for i in range(366)]) self.assertEqual(di.next().dates(), [datetime.date(2013, 1, 1) + datetime.timedelta(i) for i in range(365)]) self.assertEqual(di.prev().dates(), [datetime.date(2011, 1, 1) + datetime.timedelta(i) for i in range(365)]) self.assertEqual(str(di), '2012') def test_week(self): # >>> datetime.date(2012, 1, 1).isocalendar() # (2011, 52, 7) # >>> datetime.date(2012, 12, 31).isocalendar() # (2013, 1, 1) di = DI().parse('2011-W52') self.assertEqual(di.dates(), [datetime.date(2011, 12, 26) + datetime.timedelta(i) for i in range(7)]) self.assertEqual(di.next().dates(), [datetime.date(2012, 1, 2) + datetime.timedelta(i) for i in range(7)]) self.assertEqual(str(di), '2011-W52') di = DI().parse('2013-W01') self.assertEqual(di.dates(), [datetime.date(2012, 12, 31) + datetime.timedelta(i) for i in range(7)]) self.assertEqual(di.prev().dates(), [datetime.date(2012, 12, 24) + datetime.timedelta(i) for i in range(7)]) self.assertEqual(str(di), '2013-W01') def test_interval(self): di = DI().parse('2012-01-01-2012-02-01') self.assertEqual(di.dates(), [datetime.date(2012, 1, 1) + datetime.timedelta(i) for i in range(31)]) self.assertRaises(NotImplementedError, di.next) self.assertRaises(NotImplementedError, di.prev) self.assertEquals(di.to_string(), '2012-01-01-2012-02-01') def test_exception(self): self.assertRaises(ValueError, DI().parse, 'xyz') def test_comparison(self): a = DI().parse('2011') b = DI().parse('2013') c = DI().parse('2012') self.assertTrue(a < b) self.assertTrue(a < c) self.assertTrue(b > c) d = DI().parse('2012') self.assertTrue(d == c) self.assertEqual(d, min(c, b)) self.assertEqual(3, len(set([a, b, c, d]))) def test_comparison_different_types(self): x = DI().parse('2012') y = DI().parse('2012-01-01-2013-01-01') self.assertRaises(TypeError, lambda: x == y) def test_parameter_parse_and_default(self): month = luigi.date_interval.Month(2012, 11) other = luigi.date_interval.Month(2012, 10) class MyTask(luigi.Task): di = DI(default=month) class MyTaskNoDefault(luigi.Task): di = DI() task = luigi.interface.ArgParseInterface().parse(["MyTask"])[0] self.assertEqual(task.di, month) task = luigi.interface.ArgParseInterface().parse(["MyTask", "--di", "2012-10"])[0] self.assertEqual(task.di, other) task = MyTask(month) self.assertEqual(task.di, month) task = MyTask(di=month) self.assertEqual(task.di, month) task = MyTask(other) self.assertNotEquals(task.di, month) def fail1(): luigi.interface.ArgParseInterface().parse(["MyTaskNoDefault"])[0] self.assertRaises(luigi.parameter.MissingParameterException, fail1) task = luigi.interface.ArgParseInterface().parse(["MyTaskNoDefault", "--di", "2012-10"])[0] self.assertEqual(task.di, other) def test_hours(self): d = DI().parse('2015') self.assertEquals(len(list(d.hours())), 24 * 365) def test_cmp(self): operators = [lambda x, y: x == y, lambda x, y: x != y, lambda x, y: x < y, lambda x, y: x > y, lambda x, y: x <= y, lambda x, y: x >= y] dates = [(1, 30, DI().parse('2015-01-01-2015-01-30')), (1, 15, DI().parse('2015-01-01-2015-01-15')), (10, 20, DI().parse('2015-01-10-2015-01-20')), (20, 30, DI().parse('2015-01-20-2015-01-30'))] for from_a, to_a, di_a in dates: for from_b, to_b, di_b in dates: for op in operators: self.assertEquals( op((from_a, to_a), (from_b, to_b)), op(di_a, di_b))
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import unittest from idl_lexer import IDLLexer from idl_ppapi_lexer import IDLPPAPILexer # # FileToTokens # # From a source file generate a list of tokens. # def FileToTokens(lexer, filename): with open(filename, 'rb') as srcfile: lexer.Tokenize(srcfile.read(), filename) return lexer.GetTokens() # # TextToTokens # # From a source file generate a list of tokens. # def TextToTokens(lexer, text): lexer.Tokenize(text) return lexer.GetTokens() class WebIDLLexer(unittest.TestCase): def setUp(self): self.lexer = IDLLexer() cur_dir = os.path.dirname(os.path.realpath(__file__)) self.filenames = [ os.path.join(cur_dir, 'test_lexer/values.in'), os.path.join(cur_dir, 'test_lexer/keywords.in') ] # # testRebuildText # # From a set of tokens, generate a new source text by joining with a # single space. The new source is then tokenized and compared against the # old set. # def testRebuildText(self): for filename in self.filenames: tokens1 = FileToTokens(self.lexer, filename) to_text = '\n'.join(['%s' % t.value for t in tokens1]) tokens2 = TextToTokens(self.lexer, to_text) count1 = len(tokens1) count2 = len(tokens2) self.assertEqual(count1, count2) for i in range(count1): msg = 'Value %s does not match original %s on line %d of %s.' % ( tokens2[i].value, tokens1[i].value, tokens1[i].lineno, filename) self.assertEqual(tokens1[i].value, tokens2[i].value, msg) # # testExpectedType # # From a set of tokens pairs, verify the type field of the second matches # the value of the first, so that: # integer 123 float 1.1 ... # will generate a passing test, when the first token has both the type and # value of the keyword integer and the second has the type of integer and # value of 123 and so on. # def testExpectedType(self): for filename in self.filenames: tokens = FileToTokens(self.lexer, filename) count = len(tokens) self.assertTrue(count > 0) self.assertFalse(count & 1) index = 0 while index < count: expect_type = tokens[index].value actual_type = tokens[index + 1].type msg = 'Type %s does not match expected %s on line %d of %s.' % ( actual_type, expect_type, tokens[index].lineno, filename) index += 2 self.assertEqual(expect_type, actual_type, msg) class PepperIDLLexer(WebIDLLexer): def setUp(self): self.lexer = IDLPPAPILexer() cur_dir = os.path.dirname(os.path.realpath(__file__)) self.filenames = [ os.path.join(cur_dir, 'test_lexer/values_ppapi.in'), os.path.join(cur_dir, 'test_lexer/keywords_ppapi.in') ] if __name__ == '__main__': unittest.main()
unknown
codeparrot/codeparrot-clean
--- c: Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. SPDX-License-Identifier: curl Title: CURLOPT_NEW_DIRECTORY_PERMS Section: 3 Source: libcurl See-also: - CURLOPT_FTP_CREATE_MISSING_DIRS (3) - CURLOPT_NEW_FILE_PERMS (3) - CURLOPT_UPLOAD (3) Protocol: - SFTP - SCP - FILE Added-in: 7.16.4 --- # NAME CURLOPT_NEW_DIRECTORY_PERMS - permissions for remotely created directories # SYNOPSIS ~~~c #include <curl/curl.h> CURLcode curl_easy_setopt(CURL *handle, CURLOPT_NEW_DIRECTORY_PERMS, long mode); ~~~ # DESCRIPTION Pass a long as a parameter, containing the value of the permissions that is set on newly created directories on the remote server. The default value is *0755*, but any valid value can be used. The only protocols that can use this are *sftp://*, *scp://*, and *file://*. # DEFAULT 0755 # %PROTOCOLS% # EXAMPLE ~~~c int main(void) { CURL *curl = curl_easy_init(); if(curl) { CURLcode result; curl_easy_setopt(curl, CURLOPT_URL, "sftp://upload.example.com/newdir/file.zip"); curl_easy_setopt(curl, CURLOPT_FTP_CREATE_MISSING_DIRS, 1L); curl_easy_setopt(curl, CURLOPT_NEW_DIRECTORY_PERMS, 0644L); result = curl_easy_perform(curl); } } ~~~ # %AVAILABILITY% # RETURN VALUE curl_easy_setopt(3) returns a CURLcode indicating success or error. CURLE_OK (0) means everything was OK, non-zero means an error occurred, see libcurl-errors(3).
unknown
github
https://github.com/curl/curl
docs/libcurl/opts/CURLOPT_NEW_DIRECTORY_PERMS.md
import time from django.http import Http404 from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from jay.utils import superadmin from django.core.urlresolvers import reverse from settings.models import VotingSystem from settings.forms import EditSystemForm SETTINGS_SYSTEMS_TEMPLATE = "systems/systems_overview.html" SETTINGS_SYSTEMS_EDIT_TEMPLATE = "systems/systems_edit.html" @login_required @superadmin def systems(request, alert_type=None, alert_head=None, alert_text=None): voting_system_list = VotingSystem.objects.all() ctx = {'voting_system_list': voting_system_list} # add an alert state if needed if alert_head or alert_text or alert_type: ctx['alert_type'] = alert_type ctx['alert_head'] = alert_head ctx['alert_text'] = alert_text return render(request, SETTINGS_SYSTEMS_TEMPLATE, ctx) @login_required @superadmin def system_edit(request, system_id): # get the voting system object vs = get_object_or_404(VotingSystem, id=system_id) # make a context ctx = {'vs': vs} if request.method == "POST": try: # parse the form form = EditSystemForm(request.POST) if not form.is_valid(): raise Exception except Exception as e: ctx['alert_head'] = 'Saving failed' ctx['alert_text'] = 'Invalid data submitted' print(e) return render(request, SETTINGS_SYSTEMS_EDIT_TEMPLATE, ctx) try: # store the fields vs.machine_name = form.cleaned_data['machine_name'] vs.simple_name = form.cleaned_data['simple_name'] # and try to clean + save vs.clean() vs.save() except Exception as e: ctx['alert_head'] = 'Saving failed' ctx['alert_text'] = str(e) return render(request, SETTINGS_SYSTEMS_EDIT_TEMPLATE, ctx) ctx['alert_type'] = 'success' ctx['alert_head'] = 'Saving suceeded' ctx['alert_text'] = 'Voting System saved' # render the response return render(request, SETTINGS_SYSTEMS_EDIT_TEMPLATE, ctx) @login_required @superadmin def system_delete(request, system_id): # only POST is supported if request.method != "POST": raise Http404 # get the voting system object vs = get_object_or_404(VotingSystem, id=system_id) # if the vote set is not empty if vs.vote_set.count() != 0: return systems(request, alert_head="Deletion failed", alert_text="Voting System is not empty. " "Please delete all votes first. ") # try to delete try: vs.delete() except: return systems(request, alert_head="Deletion failed") # done return systems(request, alert_type="success", alert_head="Deletion succeeded", alert_text="Voting System Deleted. ") @login_required @superadmin def system_new(request): # only POST is supported if request.method != "POST": raise Http404 # TODO: Sensible defaults now = str(int(time.time())) simple_name = 'Voting System ' + now machine_name = 'voting_system_' + now # Create a new voting system vs = VotingSystem(simple_name=simple_name, machine_name=machine_name) # try to save and clean try: vs.clean() vs.save() except: return systems(request, alert_head="Creation failed. ", alert_text="Unable to save new VotingSystem. ") # redirect to the edit page return redirect(reverse('settings:edit', kwargs={'system_id': str(vs.id)}))
unknown
codeparrot/codeparrot-clean
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional from typing_extensions import Literal from .._models import BaseModel from .file_object import FileObject __all__ = ["Upload"] class Upload(BaseModel): """The Upload object can accept byte chunks in the form of Parts.""" id: str """The Upload unique identifier, which can be referenced in API endpoints.""" bytes: int """The intended number of bytes to be uploaded.""" created_at: int """The Unix timestamp (in seconds) for when the Upload was created.""" expires_at: int """The Unix timestamp (in seconds) for when the Upload will expire.""" filename: str """The name of the file to be uploaded.""" object: Literal["upload"] """The object type, which is always "upload".""" purpose: str """The intended purpose of the file. [Please refer here](https://platform.openai.com/docs/api-reference/files/object#files/object-purpose) for acceptable values. """ status: Literal["pending", "completed", "cancelled", "expired"] """The status of the Upload.""" file: Optional[FileObject] = None """The `File` object represents a document that has been uploaded to OpenAI."""
python
github
https://github.com/openai/openai-python
src/openai/types/upload.py
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ Title: Dumpscript management command Project: Hardytools (queryset-refactor version) Author: Will Hardy (http://willhardy.com.au) Date: June 2008 Usage: python manage.py dumpscript appname > scripts/scriptname.py $Revision: 217 $ Description: Generates a Python script that will repopulate the database using objects. The advantage of this approach is that it is easy to understand, and more flexible than directly populating the database, or using XML. * It also allows for new defaults to take effect and only transfers what is needed. * If a new database schema has a NEW ATTRIBUTE, it is simply not populated (using a default value will make the transition smooth :) * If a new database schema REMOVES AN ATTRIBUTE, it is simply ignored and the data moves across safely (I'm assuming we don't want this attribute anymore. * Problems may only occur if there is a new model and is now a required ForeignKey for an existing model. But this is easy to fix by editing the populate script :) Improvements: See TODOs and FIXMEs scattered throughout :-) """ import sys from django.db import models from django.core.exceptions import ObjectDoesNotExist from django.core.management.base import BaseCommand from django.utils.encoding import smart_unicode, force_unicode from django.contrib.contenttypes.models import ContentType class Command(BaseCommand): help = 'Dumps the data as a customised python script.' args = '[appname ...]' def handle(self, *app_labels, **options): # Get the models we want to export models = get_models(app_labels) # A dictionary is created to keep track of all the processed objects, # so that foreign key references can be made using python variable names. # This variable "context" will be passed around like the town bicycle. context = {} # Create a dumpscript object and let it format itself as a string print Script(models=models, context=context) def get_models(app_labels): """ Gets a list of models for the given app labels, with some exceptions. TODO: If a required model is referenced, it should also be included. Or at least discovered with a get_or_create() call. """ from django.db.models import get_app, get_apps, get_model from django.db.models import get_models as get_all_models # These models are not to be output, e.g. because they can be generated automatically # TODO: This should be "appname.modelname" string from django.contrib.contenttypes.models import ContentType EXCLUDED_MODELS = (ContentType, ) models = [] # If no app labels are given, return all if not app_labels: for app in get_apps(): models += [ m for m in get_all_models(app) if m not in EXCLUDED_MODELS ] # Get all relevant apps for app_label in app_labels: # If a specific model is mentioned, get only that model if "." in app_label: app_label, model_name = app_label.split(".", 1) models.append(get_model(app_label, model_name)) # Get all models for a given app else: models += [ m for m in get_all_models(get_app(app_label)) if m not in EXCLUDED_MODELS ] return models class Code(object): """ A snippet of python script. This keeps track of import statements and can be output to a string. In the future, other features such as custom indentation might be included in this class. """ def __init__(self): self.imports = {} self.indent = -1 def __str__(self): """ Returns a string representation of this script. """ if self.imports: sys.stderr.write(repr(self.import_lines)) return flatten_blocks([""] + self.import_lines + [""] + self.lines, num_indents=self.indent) else: return flatten_blocks(self.lines, num_indents=self.indent) def get_import_lines(self): """ Takes the stored imports and converts them to lines """ if self.imports: return [ "from %s import %s" % (value, key) for key, value in self.imports.items() ] else: return [] import_lines = property(get_import_lines) class ModelCode(Code): " Produces a python script that can recreate data for a given model class. " def __init__(self, model, context={}): self.model = model self.context = context self.instances = [] self.indent = 0 def get_imports(self): """ Returns a dictionary of import statements, with the variable being defined as the key. """ return { self.model.__name__: smart_unicode(self.model.__module__) } imports = property(get_imports) def get_lines(self): """ Returns a list of lists or strings, representing the code body. Each list is a block, each string is a statement. """ code = [] for counter, item in enumerate(self.model.objects.all()): instance = InstanceCode(instance=item, id=counter+1, context=self.context) self.instances.append(instance) if instance.waiting_list: code += instance.lines # After each instance has been processed, try again. # This allows self referencing fields to work. for instance in self.instances: if instance.waiting_list: code += instance.lines return code lines = property(get_lines) class InstanceCode(Code): " Produces a python script that can recreate data for a given model instance. " def __init__(self, instance, id, context={}): """ We need the instance in question and an id """ self.instance = instance self.model = self.instance.__class__ self.context = context self.variable_name = "%s_%s" % (self.instance._meta.db_table, id) self.skip_me = None self.instantiated = False self.indent = 0 self.imports = {} self.waiting_list = list(self.model._meta.fields) self.many_to_many_waiting_list = {} for field in self.model._meta.many_to_many: self.many_to_many_waiting_list[field] = list(getattr(self.instance, field.name).all()) def get_lines(self, force=False): """ Returns a list of lists or strings, representing the code body. Each list is a block, each string is a statement. force (True or False): if an attribute object cannot be included, it is usually skipped to be processed later. With 'force' set, there will be no waiting: a get_or_create() call is written instead. """ code_lines = [] # Don't return anything if this is an instance that should be skipped if self.skip(): return [] # Initialise our new object # e.g. model_name_35 = Model() code_lines += self.instantiate() # Add each field # e.g. model_name_35.field_one = 1034.91 # model_name_35.field_two = "text" code_lines += self.get_waiting_list() if force: # TODO: Check that M2M are not affected code_lines += self.get_waiting_list(force=force) # Print the save command for our new object # e.g. model_name_35.save() if code_lines: code_lines.append("%s.save()\n" % (self.variable_name)) code_lines += self.get_many_to_many_lines(force=force) return code_lines lines = property(get_lines) def skip(self): """ Determine whether or not this object should be skipped. If this model is a parent of a single subclassed instance, skip it. The subclassed instance will create this parent instance for us. TODO: Allow the user to force its creation? """ if self.skip_me is not None: return self.skip_me try: # Django trunk since r7722 uses CollectedObjects instead of dict from django.db.models.query import CollectedObjects sub_objects = CollectedObjects() except ImportError: # previous versions don't have CollectedObjects sub_objects = {} self.instance._collect_sub_objects(sub_objects) if reduce(lambda x, y: x+y, [self.model in so._meta.parents for so in sub_objects.keys()]) == 1: pk_name = self.instance._meta.pk.name key = '%s_%s' % (self.model.__name__, getattr(self.instance, pk_name)) self.context[key] = None self.skip_me = True else: self.skip_me = False return self.skip_me def instantiate(self): " Write lines for instantiation " # e.g. model_name_35 = Model() code_lines = [] if not self.instantiated: code_lines.append("%s = %s()" % (self.variable_name, self.model.__name__)) self.instantiated = True # Store our variable name for future foreign key references pk_name = self.instance._meta.pk.name key = '%s_%s' % (self.model.__name__, getattr(self.instance, pk_name)) self.context[key] = self.variable_name return code_lines def get_waiting_list(self, force=False): " Add lines for any waiting fields that can be completed now. " code_lines = [] # Process normal fields for field in list(self.waiting_list): try: # Find the value, add the line, remove from waiting list and move on value = get_attribute_value(self.instance, field, self.context, force=force) code_lines.append('%s.%s = %s' % (self.variable_name, field.name, value)) self.waiting_list.remove(field) except SkipValue, e: # Remove from the waiting list and move on self.waiting_list.remove(field) continue except DoLater, e: # Move on, maybe next time continue return code_lines def get_many_to_many_lines(self, force=False): """ Generates lines that define many to many relations for this instance. """ lines = [] for field, rel_items in self.many_to_many_waiting_list.items(): for rel_item in list(rel_items): try: pk_name = rel_item._meta.pk.name key = '%s_%s' % (rel_item.__class__.__name__, getattr(rel_item, pk_name)) value = "%s" % self.context[key] lines.append('%s.%s.add(%s)' % (self.variable_name, field.name, value)) self.many_to_many_waiting_list[field].remove(rel_item) except KeyError: if force: value = "%s.objects.get(%s=%s)" % (rel_item._meta.object_name, pk_name, getattr(rel_item, pk_name)) lines.append('%s.%s.add(%s)' % (self.variable_name, field.name, value)) self.many_to_many_waiting_list[field].remove(rel_item) if lines: lines.append("") return lines class Script(Code): " Produces a complete python script that can recreate data for the given apps. " def __init__(self, models, context={}): self.models = models self.context = context self.indent = -1 self.imports = {} def get_lines(self): """ Returns a list of lists or strings, representing the code body. Each list is a block, each string is a statement. """ code = [ self.FILE_HEADER.strip() ] # Queue and process the required models for model_class in queue_models(self.models, context=self.context): sys.stderr.write('Processing model: %s\n' % model_class.model.__name__) code.append(model_class.import_lines) code.append("") code.append(model_class.lines) # Process left over foreign keys from cyclic models for model in self.models: sys.stderr.write('Re-processing model: %s\n' % model.model.__name__) for instance in model.instances: if instance.waiting_list or instance.many_to_many_waiting_list: code.append(instance.get_lines(force=True)) return code lines = property(get_lines) # A user-friendly file header FILE_HEADER = """ #!/usr/bin/env python # -*- coding: utf-8 -*- # This file has been automatically generated, changes may be lost if you # go and generate it again. It was generated with the following command: # %s import datetime from decimal import Decimal from django.contrib.contenttypes.models import ContentType def run(): """ % " ".join(sys.argv) # HELPER FUNCTIONS #------------------------------------------------------------------------------- def flatten_blocks(lines, num_indents=-1): """ Takes a list (block) or string (statement) and flattens it into a string with indentation. """ # The standard indent is four spaces INDENTATION = " " * 4 if not lines: return "" # If this is a string, add the indentation and finish here if isinstance(lines, basestring): return INDENTATION * num_indents + lines # If this is not a string, join the lines and recurse return "\n".join([ flatten_blocks(line, num_indents+1) for line in lines ]) def get_attribute_value(item, field, context, force=False): """ Gets a string version of the given attribute's value, like repr() might. """ # Find the value of the field, catching any database issues try: value = getattr(item, field.name) except ObjectDoesNotExist: raise SkipValue('Could not find object for %s.%s, ignoring.\n' % (item.__class__.__name__, field.name)) # AutoField: We don't include the auto fields, they'll be automatically recreated if isinstance(field, models.AutoField): raise SkipValue() # Some databases (eg MySQL) might store boolean values as 0/1, this needs to be cast as a bool elif isinstance(field, models.BooleanField) and value is not None: return repr(bool(value)) # Post file-storage-refactor, repr() on File/ImageFields no longer returns the path elif isinstance(field, models.FileField): return repr(force_unicode(value)) # ForeignKey fields, link directly using our stored python variable name elif isinstance(field, models.ForeignKey) and value is not None: # Special case for contenttype foreign keys: no need to output any # content types in this script, as they can be generated again # automatically. # NB: Not sure if "is" will always work if field.rel.to is ContentType: return 'ContentType.objects.get(app_label="%s", model="%s")' % (value.app_label, value.model) # Generate an identifier (key) for this foreign object pk_name = value._meta.pk.name key = '%s_%s' % (value.__class__.__name__, getattr(value, pk_name)) if key in context: variable_name = context[key] # If the context value is set to None, this should be skipped. # This identifies models that have been skipped (inheritance) if variable_name is None: raise SkipValue() # Return the variable name listed in the context return "%s" % variable_name elif force: return "%s.objects.get(%s=%s)" % (value._meta.object_name, pk_name, getattr(value, pk_name)) else: raise DoLater('(FK) %s.%s\n' % (item.__class__.__name__, field.name)) # A normal field (e.g. a python built-in) else: return repr(value) def queue_models(models, context): """ Works an an appropriate ordering for the models. This isn't essential, but makes the script look nicer because more instances can be defined on their first try. """ # Max number of cycles allowed before we call it an infinite loop. MAX_CYCLES = 5 model_queue = [] number_remaining_models = len(models) allowed_cycles = MAX_CYCLES while number_remaining_models > 0: previous_number_remaining_models = number_remaining_models model = models.pop(0) # If the model is ready to be processed, add it to the list if check_dependencies(model, model_queue): model_class = ModelCode(model=model, context=context) model_queue.append(model_class) # Otherwise put the model back at the end of the list else: models.append(model) # Check for infinite loops. # This means there is a cyclic foreign key structure # That cannot be resolved by re-ordering number_remaining_models = len(models) if number_remaining_models == previous_number_remaining_models: allowed_cycles -= 1 if allowed_cycles <= 0: # Add the remaining models, but do not remove them from the model list missing_models = [ ModelCode(model=m, context=context) for m in models ] model_queue += missing_models # Replace the models with the model class objects # (sure, this is a little bit of hackery) models[:] = missing_models break else: allowed_cycles = MAX_CYCLES return model_queue def check_dependencies(model, model_queue): " Check that all the depenedencies for this model are already in the queue. " # A list of allowed links: existing fields, itself and the special case ContentType allowed_links = [ m.model.__name__ for m in model_queue ] + [model.__name__, 'ContentType'] # For each ForeignKey or ManyToMany field, check that a link is possible for field in model._meta.fields + model._meta.many_to_many: if field.rel and field.rel.to.__name__ not in allowed_links: return False return True # EXCEPTIONS #------------------------------------------------------------------------------- class SkipValue(Exception): """ Value could not be parsed or should simply be skipped. """ class DoLater(Exception): """ Value could not be parsed or should simply be skipped. """
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- from configs.module import Module import running import time def init(options): options['server'].state['lastpong'] = time.time() m = Module('ping') m.set_help('Reply to PING messages from the IRC server.') m.add_base_hook('recv', recv) m.add_base_hook('ctcp.ping', ctcp_ping) m.add_timer_hook(10 * 1000, timer) return m def ctcp_ping(fp): fp.replyctcp('PING %s' % fp.ctcptext) def recv(fp): try: if fp.sp.splitmessage[0].upper() == 'PING': fp.server.write_cmd('PONG', fp.sp.splitmessage[1]) elif fp.sp.splitmessage[1].upper() == 'PONG': fp.server.state['lastpong'] = time.time() except IndexError: pass def timer(): for server in running.working_servers: if server.type == 'irc': if time.time() - server.state['lastpong'] > 15: server.write_cmd('PING', server.nick) if time.time() - server.state['lastpong'] > 255: server.reconnect()
unknown
codeparrot/codeparrot-clean
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # from boto.pyami.scriptbase import ScriptBase class HelloWorld(ScriptBase): def main(self): self.log('Hello World!!!')
unknown
codeparrot/codeparrot-clean
# Software License Agreement (BSD License) # # Copyright (c) 2009-2011, Eucalyptus Systems, Inc. # All rights reserved. # # Redistribution and use of this software in source and binary forms, with or # without modification, are permitted provided that the following conditions # are met: # # Redistributions of source code must retain the above # copyright notice, this list of conditions and the # following disclaimer. # # Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the # following disclaimer in the documentation and/or other # materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Author: matt.clark@eucalyptus.com ''' Created on Mar 7, 2012 @author: clarkmatthew Place holder for volume test specific convenience methods+objects to extend boto's volume class ''' from boto.ec2.volume import Volume from boto.exception import EC2ResponseError from eutester.taggedresource import TaggedResource from prettytable import PrettyTable, ALL import eucaops import time class EuVolume(Volume, TaggedResource): tag_md5_key = 'md5' tag_md5len_key = 'md5len' tag_instance_id_key = 'instance_id' tag_guestdev_key = 'guestdev' ''' Note: Different hypervisors will honor the requested cloud dev differently, so the requested device can not be relied up as the device it attached to on the guest 'guestdev' ''' @classmethod def make_euvol_from_vol(cls,volume, tester=None, cmdstart=None): newvol = EuVolume(volume.connection) newvol.__dict__ = volume.__dict__ newvol.tester = tester newvol.guestdev = "" #the guest device name in use by this attached volume newvol.clouddev = "" #the device name given to the cloud as a request to be used. newvol.md5 = None newvol.md5len = 1024 newvol.eutest_failmsg = None newvol.eutest_laststatus = newvol.status newvol.eutest_ageatstatus = 0 newvol.eutest_cmdstart = cmdstart or eucaops.EC2ops.get_volume_time_created(volume) newvol.eutest_createorder = None newvol.eutest_cmdtime = None newvol.eutest_attached_instance_id = None if newvol.tags.has_key(newvol.tag_md5_key): newvol.md5 = newvol.tags[newvol.tag_md5_key] if newvol.tags.has_key(newvol.tag_md5len_key): newvol.md5len = newvol.tags[newvol.tag_md5len_key] newvol.set_attached_status() newvol.update() return newvol def update(self): try: super(EuVolume, self).update() except EC2ResponseError as ER: if ER.status == 400 and ER.error_code == 'InvalidVolume.NotFound': self.status = 'deleted' if (self.tags.has_key(self.tag_md5_key) and (self.md5 != self.tags[self.tag_md5_key])) or \ (self.tags.has_key(self.tag_md5len_key) and (self.md5len != self.tags[self.tag_md5len_key])): self.update_volume_attach_info_tags() self.set_last_status() def set_last_status(self,status=None): self.eutest_laststatus = status or self.status self.eutest_laststatustime = time.time() self.set_attached_status() self.eutest_ageatstatus = "{0:.2f}".format(time.time() - self.eutest_cmdstart) def set_attached_status(self): if self.attach_data: self.eutest_attached_status = self.attach_data.status self.eutest_attached_instance_id = self.attach_data.instance_id if self.tags.has_key(self.tag_instance_id_key) and self.tags[self.tag_instance_id_key] != self.eutest_attached_instance_id: self.remove_tag(self.tag_instance_id_key) self.remove_tag(self.tag_guestdev_key) else: if not self.guestdev and self.tags.has_key(self.tag_guestdev_key): self.guestdev = self.tags[self.tag_guestdev_key] else: self.eutest_attached_status = None self.eutest_attached_instance_id = None def printself(self, printmethod=None, printme=True): pt = PrettyTable(['VOL_ID', 'ORDER', 'TESTSTATUS', 'AGE', 'SIZE', 'SRC_SNAP', 'MD5/(LEN)', 'ZONE', 'INSTANCE']) pt.padding_width=0 pt.add_row([self.id, self.eutest_createorder, self.eutest_laststatus or self.status, self.eutest_ageatstatus, self.size, self.snapshot_id, "{0}/({1})".format(self.md5, self.md5len), self.zone, self.attach_data.instance_id]) if printme: printmethod = printmethod or self.debug printmethod(str(pt)) else: return pt def update_volume_attach_info_tags(self, md5=None, md5len=None, instance_id=None, guestdev=None): md5 = md5 or self.md5 md5len = md5len or self.md5len self.add_tag(self.tag_md5_key, md5) self.add_tag(self.tag_md5len_key, md5len) if self.status == 'in-use' and hasattr(self,'attach_data') and self.attach_data: instance_id = instance_id or self.eutest_attached_instance_id guestdev = guestdev or self.guestdev self.add_tag(self.tag_instance_id_key, instance_id) self.add_tag(self.tag_guestdev_key, guestdev) else: self.set_volume_detached_tags() def set_volume_detached_tags(self): self.remove_tag(self.tag_instance_id_key) self.remove_tag(self.tag_guestdev_key)
unknown
codeparrot/codeparrot-clean
from django import forms from territori.fields import TerritoriChoices, TerritoriClusterChoices, TerritoriChoicesClassifiche from django.utils.translation import ugettext_lazy as _ class TerritoriSearchFormHome(forms.Form): territori = TerritoriChoices( to_field_name = 'slug', required=True, label='', widget=TerritoriChoices.widget( select2_options={ 'width': '48em', 'placeholder': _(u"CERCA UN COMUNE, ENTRA NEI BILANCI, CONDIVIDI QUELLO CHE SCOPRI"), # 'allowClear': 'false', } ) ) class TerritoriSearchFormClassifiche(forms.Form): territorio_id = TerritoriChoicesClassifiche( to_field_name = 'pk', required=True, label='', widget=TerritoriChoicesClassifiche.widget( select2_options={ 'width': '100%', 'placeholder': _(u"CERCA UN COMUNE"), } ) ) selected_year = forms.MultiValueField(widget=forms.HiddenInput()) selected_par_type = forms.MultiValueField(widget=forms.HiddenInput()) selected_parameter = forms.MultiValueField(widget=forms.HiddenInput()) selected_regioni = forms.MultiValueField(widget=forms.HiddenInput()) selected_cluster = forms.MultiValueField(widget=forms.HiddenInput()) class TerritoriSearchForm(forms.Form): territori = TerritoriChoices( to_field_name = 'slug', required=True, label='', widget=TerritoriChoices.widget( select2_options={ 'width': '20em', 'placeholder': _(u"CERCA UN COMUNE"), # 'allowClear': None, } ) ) class TerritoriComparisonSearchForm(forms.Form): territorio_1 = TerritoriClusterChoices( to_field_name = 'slug', required=True, label='', widget=TerritoriClusterChoices.widget( select2_options={ 'containerCssClass': 'form-control', 'width': '100%', 'placeholder': _(u"UN COMUNE"), } ) ) territorio_2 = TerritoriClusterChoices( to_field_name = 'slug', required=True, label='', widget=TerritoriClusterChoices.widget( select2_options={ 'containerCssClass': 'form-control', 'width': '100%', 'placeholder': _(u"UN ALTRO COMUNE"), } ) ) class EarlyBirdForm(forms.Form): my_default_errors = { 'required': 'Campo richiesto', 'invalid': 'Attenzione: il valore inserito non &egrave; valido', } nome = forms.CharField(max_length=200, error_messages=my_default_errors, required=True) cognome = forms.CharField(max_length=200, error_messages=my_default_errors, required=True) email = forms.EmailField(max_length=200, error_messages=my_default_errors, required=True)
unknown
codeparrot/codeparrot-clean
# These are versions of the functions in django.utils.translation.trans_real # that don't actually do anything. This is purely for performance, so that # settings.USE_I18N = False can use this module rather than trans_real.py. from django.conf import settings from django.utils.encoding import force_text from django.utils.safestring import mark_safe, SafeData def ngettext(singular, plural, number): if number == 1: return singular return plural ngettext_lazy = ngettext def ungettext(singular, plural, number): return force_text(ngettext(singular, plural, number)) def pgettext(context, message): return ugettext(message) def npgettext(context, singular, plural, number): return ungettext(singular, plural, number) activate = lambda x: None deactivate = deactivate_all = lambda: None get_language = lambda: settings.LANGUAGE_CODE get_language_bidi = lambda: settings.LANGUAGE_CODE in settings.LANGUAGES_BIDI check_for_language = lambda x: True def gettext(message): if isinstance(message, SafeData): return mark_safe(message) return message def ugettext(message): return force_text(gettext(message)) gettext_noop = gettext_lazy = _ = gettext def to_locale(language): p = language.find('-') if p >= 0: return language[:p].lower() + '_' + language[p + 1:].upper() else: return language.lower() def get_language_from_request(request, check_path=False): return settings.LANGUAGE_CODE def get_language_from_path(request): return None
unknown
codeparrot/codeparrot-clean
#! /usr/bin/env python import vcsn from test import * # Check both syntaxes: `aut.multiply(n)` and `aut ** n`. def check(aut, n, exp): CHECK_EQ(exp, aut ** n) CHECK_EQ(exp, aut.multiply(n)) a = vcsn.B.expression('a').standard() check(a, 0, vcsn.B.expression('\e').standard()) check(a, 5, '''digraph { vcsn_context = "letterset<char_letters(a)>, b" rankdir = LR edge [arrowhead = vee, arrowsize = .6] { node [shape = point, width = 0] I0 F5 } { node [shape = circle, style = rounded, width = 0.5] 0 1 2 3 4 5 } I0 -> 0 0 -> 1 [label = "a"] 1 -> 2 [label = "a"] 2 -> 3 [label = "a"] 3 -> 4 [label = "a"] 4 -> 5 [label = "a"] 5 -> F5 }''') a = vcsn.automaton(''' digraph { vcsn_context = "letterset<char_letters(ab)>, b" rankdir = LR edge [arrowhead = vee, arrowsize = .6] { node [shape = point, width = 0] I F1 F2 } { node [shape = circle, style = rounded, width = 0.5] 0 1 2 } I -> 0 0 -> 1 [label = "a"] 0 -> 2 [label = "b"] 2 -> F2 1 -> F1 } ''') check(a, 3, '''digraph { vcsn_context = "letterset<char_letters(ab)>, b" rankdir = LR edge [arrowhead = vee, arrowsize = .6] { node [shape = point, width = 0] I0 F5 F6 } { node [shape = circle, style = rounded, width = 0.5] 0 1 2 3 4 5 6 } I0 -> 0 0 -> 1 [label = "a"] 0 -> 2 [label = "b"] 1 -> 3 [label = "a"] 1 -> 4 [label = "b"] 2 -> 3 [label = "a"] 2 -> 4 [label = "b"] 3 -> 5 [label = "a"] 3 -> 6 [label = "b"] 4 -> 5 [label = "a"] 4 -> 6 [label = "b"] 5 -> F5 6 -> F6 }''') ## ------------------------------------------------- ## ## Repeated multiply on expressions vs on automata. ## ## ------------------------------------------------- ## ctx = vcsn.context('lal_char(ab), z') r = ctx.expression('a') a = r.standard() def check(*args): "Check that standard and multiply commute." CHECK_ISOMORPHIC(a ** args, (r ** args).standard()) check(0) check(0, 1) check(1) check(3) check(0, 3) check(3, -1) check(-1) XFAIL(lambda: a ** (2, 1))
unknown
codeparrot/codeparrot-clean
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import sys from pbr import find_package from pbr.hooks import base def get_manpath(): manpath = 'share/man' if os.path.exists(os.path.join(sys.prefix, 'man')): # This works around a bug with install where it expects every node # in the relative data directory to be an actual directory, since at # least Debian derivatives (and probably other platforms as well) # like to symlink Unixish /usr/local/man to /usr/local/share/man. manpath = 'man' return manpath def get_man_section(section): return os.path.join(get_manpath(), 'man%s' % section) class FilesConfig(base.BaseConfig): section = 'files' def __init__(self, config, name): super(FilesConfig, self).__init__(config) self.name = name self.data_files = self.config.get('data_files', '') def save(self): self.config['data_files'] = self.data_files super(FilesConfig, self).save() def expand_globs(self): finished = [] for line in self.data_files.split("\n"): if line.rstrip().endswith('*') and '=' in line: (target, source_glob) = line.split('=') source_prefix = source_glob.strip()[:-1] target = target.strip() if not target.endswith(os.path.sep): target += os.path.sep for (dirpath, dirnames, fnames) in os.walk(source_prefix): finished.append( "%s = " % dirpath.replace(source_prefix, target)) finished.extend( [" %s" % os.path.join(dirpath, f) for f in fnames]) else: finished.append(line) self.data_files = "\n".join(finished) def add_man_path(self, man_path): self.data_files = "%s\n%s =" % (self.data_files, man_path) def add_man_page(self, man_page): self.data_files = "%s\n %s" % (self.data_files, man_page) def get_man_sections(self): man_sections = dict() manpages = self.pbr_config['manpages'] for manpage in manpages.split(): section_number = manpage.strip()[-1] section = man_sections.get(section_number, list()) section.append(manpage.strip()) man_sections[section_number] = section return man_sections def hook(self): package = self.config.get('packages', self.name).strip() if os.path.isdir(package): self.config['packages'] = find_package.smart_find_packages(package) self.expand_globs() if 'manpages' in self.pbr_config: man_sections = self.get_man_sections() for (section, pages) in man_sections.items(): manpath = get_man_section(section) self.add_man_path(manpath) for page in pages: self.add_man_page(page)
unknown
codeparrot/codeparrot-clean
package kotlinx.coroutines.internal import kotlinx.coroutines.testing.* import junit.framework.Assert.* import kotlinx.coroutines.* import kotlinx.coroutines.debug.internal.* import org.junit.* import kotlin.concurrent.* class ConcurrentWeakMapCollectionStressTest : TestBase() { private data class Key(val i: Int) private val nElements = 100_000 * stressTestMultiplier private val size = 100_000 @Test fun testCollected() { // use very big arrays as values, we'll need a queue and a cleaner thread to handle them val m = ConcurrentWeakMap<Key, ByteArray>(weakRefQueue = true) val cleaner = thread(name = "ConcurrentWeakMapCollectionStressTest-Cleaner") { m.runWeakRefQueueCleaningLoopUntilInterrupted() } for (i in 1..nElements) { m.put(Key(i), ByteArray(size)) } assertTrue(m.size < nElements) // some of it was collected for sure cleaner.interrupt() cleaner.join() } }
kotlin
github
https://github.com/Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/jvm/test/internal/ConcurrentWeakMapCollectionStressTest.kt
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from __future__ import annotations import contextlib import inspect import logging import os import pathlib import re import sys import textwrap import warnings import zipfile from copy import deepcopy from datetime import datetime, timedelta, timezone from unittest import mock from unittest.mock import patch import pytest from sqlalchemy import select from airflow import settings from airflow.dag_processing.dagbag import ( BundleDagBag, DagBag, _capture_with_reraise, _validate_executor_fields, ) from airflow.exceptions import UnknownExecutorException from airflow.executors.executor_loader import ExecutorLoader from airflow.models.dag import DagModel from airflow.models.dagwarning import DagWarning, DagWarningType from airflow.models.serialized_dag import SerializedDagModel from airflow.sdk import DAG, BaseOperator from tests_common.pytest_plugin import AIRFLOW_ROOT_PATH from tests_common.test_utils import db from tests_common.test_utils.config import conf_vars from unit import cluster_policies from unit.models import TEST_DAGS_FOLDER pytestmark = pytest.mark.db_test example_dags_folder = AIRFLOW_ROOT_PATH / "airflow-core" / "src" / "airflow" / "example_dags" / "standard" PY311 = sys.version_info >= (3, 11) PY313 = sys.version_info >= (3, 13) # Include the words "airflow" and "dag" in the file contents, # tricking airflow into thinking these # files contain a DAG (otherwise Airflow will skip them) INVALID_DAG_WITH_DEPTH_FILE_CONTENTS = "def something():\n return airflow_DAG\nsomething()" def db_clean_up(): db.clear_db_dags() db.clear_db_runs() db.clear_db_serialized_dags() db.clear_dag_specific_permissions() class TestValidateExecutorFields: """Comprehensive tests for _validate_executor_fields function.""" @patch.object(ExecutorLoader, "lookup_executor_name_by_str") def test_multi_team_disabled_ignores_bundle_name(self, mock_lookup): """Test that when multi_team is disabled, bundle_name is ignored and no team lookup occurs.""" with DAG("test-dag", schedule=None) as dag: BaseOperator(task_id="t1", executor="test.executor") # multi_team disabled by default, no need to add conf_vars _validate_executor_fields(dag, bundle_name="some_bundle") # Should call ExecutorLoader without team_name (defaults to None) mock_lookup.assert_called_once_with("test.executor", team_name=None) @patch("airflow.dag_processing.bundles.manager.DagBundlesManager") @patch.object(ExecutorLoader, "lookup_executor_name_by_str") def test_multi_team_enabled_bundle_exists_with_team(self, mock_lookup, mock_manager_class): """Test successful team lookup when bundle exists and has team_name.""" # Setup mock bundle manager mock_bundle_config = mock.MagicMock() mock_bundle_config.team_name = "test_team" mock_manager = mock_manager_class.return_value mock_manager._bundle_config = {"test_bundle": mock_bundle_config} with DAG("test-dag", schedule=None) as dag: BaseOperator(task_id="t1", executor="team.executor") with conf_vars({("core", "multi_team"): "True"}): _validate_executor_fields(dag, bundle_name="test_bundle") # Should call ExecutorLoader with team from bundle config mock_lookup.assert_called_once_with("team.executor", team_name="test_team") @patch("airflow.dag_processing.bundles.manager.DagBundlesManager") @patch.object(ExecutorLoader, "lookup_executor_name_by_str") def test_multi_team_enabled_bundle_exists_no_team(self, mock_lookup, mock_manager_class): """Test when bundle exists but has no team_name (None or empty).""" mock_bundle_config = mock.MagicMock() mock_bundle_config.team_name = None # No team associated mock_manager = mock_manager_class.return_value mock_manager._bundle_config = {"test_bundle": mock_bundle_config} with DAG("test-dag", schedule=None) as dag: BaseOperator(task_id="t1", executor="test.executor") with conf_vars({("core", "multi_team"): "True"}): _validate_executor_fields(dag, bundle_name="test_bundle") mock_lookup.assert_called_once_with("test.executor", team_name=None) @patch.object(ExecutorLoader, "lookup_executor_name_by_str") def test_multiple_tasks_with_executors(self, mock_lookup): """Test that all tasks with executors are validated.""" with DAG("test-dag", schedule=None) as dag: BaseOperator(task_id="t1", executor="executor1") BaseOperator(task_id="t2", executor="executor2") BaseOperator(task_id="t3") # No executor, should be skipped with conf_vars({("core", "multi_team"): "True"}): _validate_executor_fields(dag) # Should be called for each task with executor assert mock_lookup.call_count == 2 mock_lookup.assert_any_call("executor1", team_name=None) mock_lookup.assert_any_call("executor2", team_name=None) @patch("airflow.dag_processing.bundles.manager.DagBundlesManager") @patch.object(ExecutorLoader, "lookup_executor_name_by_str") def test_executor_validation_failure_with_team(self, mock_lookup, mock_manager_class): """Test executor validation failure when team is associated (team-specific error).""" mock_bundle_config = mock.MagicMock() mock_bundle_config.team_name = "test_team" mock_manager = mock_manager_class.return_value mock_manager._bundle_config = {"test_bundle": mock_bundle_config} # ExecutorLoader raises exception mock_lookup.side_effect = UnknownExecutorException("Executor not found") with DAG("test-dag", schedule=None) as dag: BaseOperator(task_id="task1", executor="invalid.executor") with conf_vars({("core", "multi_team"): "True"}): with pytest.raises( UnknownExecutorException, match=re.escape( "Task 'task1' specifies executor 'invalid.executor', which is not available " "for team 'test_team' (the team associated with DAG 'test-dag') or as a global executor. " "Make sure 'invalid.executor' is configured for team 'test_team' or globally in your " "[core] executors configuration, or update the task's executor to use one of the " "configured executors for team 'test_team' or available global executors." ), ): _validate_executor_fields(dag, bundle_name="test_bundle") @patch.object(ExecutorLoader, "lookup_executor_name_by_str") def test_executor_validation_failure_no_team(self, mock_lookup): """Test executor validation failure when no team is associated (generic error).""" mock_lookup.side_effect = UnknownExecutorException("Executor not found") with DAG("test-dag", schedule=None) as dag: BaseOperator(task_id="task1", executor="invalid.executor") with conf_vars({("core", "multi_team"): "True"}): with pytest.raises( UnknownExecutorException, match=re.escape( "Task 'task1' specifies executor 'invalid.executor', which is not available. " "Make sure it is listed in your [core] executors configuration, or update the task's " "executor to use one of the configured executors." ), ): _validate_executor_fields(dag) # No bundle_name @patch("airflow.dag_processing.bundles.manager.DagBundlesManager") @patch.object(ExecutorLoader, "lookup_executor_name_by_str") def test_global_executor_fallback_success(self, mock_lookup, mock_manager_class): """Test that team-specific executor failure falls back to global executor successfully.""" mock_bundle_config = mock.MagicMock() mock_bundle_config.team_name = "test_team" mock_manager = mock_manager_class.return_value mock_manager._bundle_config = {"test_bundle": mock_bundle_config} # First call (team-specific) fails, second call (global) succeeds mock_lookup.side_effect = [UnknownExecutorException("Team executor not found"), None] with DAG("test-dag", schedule=None) as dag: BaseOperator(task_id="task1", executor="global.executor") with conf_vars({("core", "multi_team"): "True"}): # Should not raise exception due to global fallback _validate_executor_fields(dag, bundle_name="test_bundle") # Should call lookup twice: first for team, then for global assert mock_lookup.call_count == 2 mock_lookup.assert_any_call("global.executor", team_name="test_team") mock_lookup.assert_any_call("global.executor", team_name=None) @patch("airflow.dag_processing.bundles.manager.DagBundlesManager") @patch.object(ExecutorLoader, "lookup_executor_name_by_str") def test_global_executor_fallback_failure(self, mock_lookup, mock_manager_class): """Test that when both team-specific and global executors fail, appropriate error is raised.""" mock_bundle_config = mock.MagicMock() mock_bundle_config.team_name = "test_team" mock_manager = mock_manager_class.return_value mock_manager._bundle_config = {"test_bundle": mock_bundle_config} # Both calls fail mock_lookup.side_effect = UnknownExecutorException("Executor not found") with DAG("test-dag", schedule=None) as dag: BaseOperator(task_id="task1", executor="unknown.executor") with conf_vars({("core", "multi_team"): "True"}): with pytest.raises( UnknownExecutorException, match=re.escape( "Task 'task1' specifies executor 'unknown.executor', which is not available " "for team 'test_team' (the team associated with DAG 'test-dag') or as a global executor. " "Make sure 'unknown.executor' is configured for team 'test_team' or globally in your " "[core] executors configuration, or update the task's executor to use one of the " "configured executors for team 'test_team' or available global executors." ), ): _validate_executor_fields(dag, bundle_name="test_bundle") # Should call lookup twice: first for team, then for global fallback assert mock_lookup.call_count == 2 mock_lookup.assert_any_call("unknown.executor", team_name="test_team") mock_lookup.assert_any_call("unknown.executor", team_name=None) @patch("airflow.dag_processing.bundles.manager.DagBundlesManager") @patch.object(ExecutorLoader, "lookup_executor_name_by_str") def test_team_specific_executor_success_no_fallback(self, mock_lookup, mock_manager_class): """Test that when team-specific executor succeeds, global fallback is not attempted.""" mock_bundle_config = mock.MagicMock() mock_bundle_config.team_name = "test_team" mock_manager = mock_manager_class.return_value mock_manager._bundle_config = {"test_bundle": mock_bundle_config} # First call (team-specific) succeeds mock_lookup.return_value = None with DAG("test-dag", schedule=None) as dag: BaseOperator(task_id="task1", executor="team.executor") with conf_vars({("core", "multi_team"): "True"}): _validate_executor_fields(dag, bundle_name="test_bundle") # Should only call lookup once for team-specific executor mock_lookup.assert_called_once_with("team.executor", team_name="test_team") def test_validate_executor_field_executor_not_configured(): with DAG("test-dag", schedule=None) as dag: BaseOperator(task_id="t1", executor="test.custom.executor") with pytest.raises( UnknownExecutorException, match=re.escape( "Task 't1' specifies executor 'test.custom.executor', which is not available. " "Make sure it is listed in your [core] executors configuration, or update the task's " "executor to use one of the configured executors." ), ): _validate_executor_fields(dag) def test_validate_executor_field(): with DAG("test-dag", schedule=None) as dag: BaseOperator(task_id="t1", executor="test.custom.executor") with patch.object(ExecutorLoader, "lookup_executor_name_by_str"): _validate_executor_fields(dag) class TestDagBag: def setup_class(self): db_clean_up() def teardown_class(self): db_clean_up() def test_dagbag_with_bundle_name(self, tmp_path): """Test that DagBag constructor accepts and stores bundle_name parameter.""" dagbag = DagBag(dag_folder=os.fspath(tmp_path), include_examples=False, bundle_name="test_bundle") assert dagbag.bundle_name == "test_bundle" # Test with None (default) dagbag2 = DagBag(dag_folder=os.fspath(tmp_path), include_examples=False) assert dagbag2.bundle_name is None def test_get_existing_dag(self, tmp_path): """ Test that we're able to parse some example DAGs and retrieve them """ dagbag = DagBag(dag_folder=os.fspath(tmp_path), include_examples=True, bundle_name="test_bundle") some_expected_dag_ids = ["example_bash_operator", "example_branch_operator"] for dag_id in some_expected_dag_ids: dag = dagbag.get_dag(dag_id) assert dag is not None assert dag_id == dag.dag_id assert dagbag.size() >= 7 def test_get_non_existing_dag(self, tmp_path): """ test that retrieving a non existing dag id returns None without crashing """ dagbag = DagBag(dag_folder=os.fspath(tmp_path), include_examples=False) non_existing_dag_id = "non_existing_dag_id" assert dagbag.get_dag(non_existing_dag_id) is None def test_serialized_dag_not_existing_doesnt_raise(self, tmp_path, session): """ test that retrieving a non existing dag id returns None without crashing """ non_existing_dag_id = "non_existing_dag_id" assert session.scalar(select(True).where(SerializedDagModel.dag_id == non_existing_dag_id)) is None def test_dont_load_example(self, tmp_path): """ test that the example are not loaded """ dagbag = DagBag(dag_folder=os.fspath(tmp_path), include_examples=False) assert dagbag.size() == 0 def test_safe_mode_heuristic_match(self, tmp_path): """ With safe mode enabled, a file matching the discovery heuristics should be discovered. """ path = tmp_path / "testfile.py" path.write_text("# airflow\n# DAG") with conf_vars({("core", "dags_folder"): os.fspath(path.parent)}): dagbag = DagBag(include_examples=False, safe_mode=True) assert len(dagbag.dagbag_stats) == 1 assert dagbag.dagbag_stats[0].file == path.name def test_safe_mode_heuristic_mismatch(self, tmp_path): """ With safe mode enabled, a file not matching the discovery heuristics should not be discovered. """ path = tmp_path / "testfile.py" path.write_text("") with conf_vars({("core", "dags_folder"): os.fspath(path.parent)}): dagbag = DagBag(include_examples=False, safe_mode=True) assert len(dagbag.dagbag_stats) == 0 def test_safe_mode_disabled(self, tmp_path): """With safe mode disabled, an empty python file should be discovered.""" path = tmp_path / "testfile.py" path.write_text("") with conf_vars({("core", "dags_folder"): os.fspath(path.parent)}): dagbag = DagBag(include_examples=False, safe_mode=False) assert len(dagbag.dagbag_stats) == 1 assert dagbag.dagbag_stats[0].file == path.name def test_dagbag_stats_file_is_relative_path_with_mixed_separators(self, tmp_path): """ Test that dagbag_stats.file contains a relative path even when DAGS_FOLDER and filepath have different path separators (simulates Windows behavior). On Windows, settings.DAGS_FOLDER may use forward slashes (e.g., 'C:/foo/dags') while filepath from os.path operations uses backslashes (e.g., 'C:\\foo\\dags\\my_dag.py'). This test verifies that path normalization works correctly in such cases. See: https://github.com/apache/airflow/issues/XXXXX """ path = tmp_path / "testfile.py" path.write_text("# airflow\n# DAG") # Simulate the Windows scenario where DAGS_FOLDER has forward slashes # but the filesystem returns paths with backslashes dags_folder_with_forward_slashes = path.parent.as_posix() with conf_vars({("core", "dags_folder"): dags_folder_with_forward_slashes}): dagbag = DagBag(include_examples=False, safe_mode=True) assert len(dagbag.dagbag_stats) == 1 assert dagbag.dagbag_stats[0].file == path.name def test_dagbag_stats_includes_bundle_info(self, tmp_path): """Test that FileLoadStat includes bundle_path and bundle_name from DagBag.""" path = tmp_path / "testfile.py" path.write_text("# airflow\n# DAG") bundle_path = tmp_path / "bundle" bundle_path.mkdir() bundle_name = "test_bundle" with conf_vars({("core", "dags_folder"): os.fspath(path.parent)}): dagbag = DagBag( include_examples=False, safe_mode=True, bundle_path=bundle_path, bundle_name=bundle_name, ) assert len(dagbag.dagbag_stats) == 1 stat = dagbag.dagbag_stats[0] assert stat.bundle_path == bundle_path assert stat.bundle_name == bundle_name def test_dagbag_stats_bundle_info_none_when_not_provided(self, tmp_path): """Test that FileLoadStat has None for bundle_path and bundle_name when not provided.""" path = tmp_path / "testfile.py" path.write_text("# airflow\n# DAG") with conf_vars({("core", "dags_folder"): os.fspath(path.parent)}): dagbag = DagBag(include_examples=False, safe_mode=True) assert len(dagbag.dagbag_stats) == 1 stat = dagbag.dagbag_stats[0] assert stat.bundle_path is None assert stat.bundle_name is None def test_process_file_that_contains_multi_bytes_char(self, tmp_path): """ test that we're able to parse file that contains multi-byte char """ path = tmp_path / "testfile.py" path.write_text("\u3042") # write multi-byte char (hiragana) dagbag = DagBag(dag_folder=os.fspath(path.parent), include_examples=False) assert dagbag.process_file(os.fspath(path)) == [] def test_process_file_duplicated_dag_id(self, tmp_path): """Loading a DAG with ID that already existed in a DAG bag should result in an import error.""" dagbag = DagBag(dag_folder=os.fspath(tmp_path), include_examples=False) def create_dag(): from airflow.sdk import dag @dag(schedule=None, default_args={"owner": "owner1"}) def my_flow(): pass my_dag = my_flow() # noqa: F841 source_lines = [line[12:] for line in inspect.getsource(create_dag).splitlines(keepends=True)[1:]] path1 = tmp_path / "testfile1.py" path2 = tmp_path / "testfile2.py" path1.write_text("".join(source_lines)) path2.write_text("".join(source_lines)) found_1 = dagbag.process_file(os.fspath(path1)) assert len(found_1) == 1 assert found_1[0].dag_id == "my_flow" assert dagbag.import_errors == {} dags_in_bag = dagbag.dags found_2 = dagbag.process_file(os.fspath(path2)) assert len(found_2) == 0 assert dagbag.import_errors[os.fspath(path2)].startswith( "AirflowDagDuplicatedIdException: Ignoring DAG" ) assert dagbag.dags == dags_in_bag # Should not change. def test_import_errors_use_relative_path_with_bundle(self, tmp_path): """Import errors should use relative paths when bundle_path is set.""" bundle_path = tmp_path / "bundle" bundle_path.mkdir() dag_path = bundle_path / "subdir" / "my_dag.py" dag_path.parent.mkdir(parents=True) dag_path.write_text("from airflow.sdk import DAG\nraise ImportError('test error')") dagbag = DagBag( dag_folder=os.fspath(dag_path), include_examples=False, bundle_path=bundle_path, bundle_name="test_bundle", ) expected_relative_path = "subdir/my_dag.py" assert expected_relative_path in dagbag.import_errors # Absolute path should NOT be a key assert os.fspath(dag_path) not in dagbag.import_errors assert "test error" in dagbag.import_errors[expected_relative_path] def test_import_errors_use_relative_path_for_bagging_errors(self, tmp_path): """Errors during DAG bagging should use relative paths when bundle_path is set.""" bundle_path = tmp_path / "bundle" bundle_path.mkdir() def create_dag(): from airflow.sdk import dag @dag(schedule=None, default_args={"owner": "owner1"}) def my_flow(): pass my_flow() source_lines = [line[12:] for line in inspect.getsource(create_dag).splitlines(keepends=True)[1:]] path1 = bundle_path / "testfile1.py" path2 = bundle_path / "testfile2.py" path1.write_text("".join(source_lines)) path2.write_text("".join(source_lines)) dagbag = DagBag( dag_folder=os.fspath(bundle_path), include_examples=False, bundle_path=bundle_path, bundle_name="test_bundle", ) # The DAG should load successfully from one file assert "my_flow" in dagbag.dags # One file should have a duplicate DAG error - file order is not guaranteed assert len(dagbag.import_errors) == 1 error_path = next(iter(dagbag.import_errors.keys())) # The error key should be a relative path (not absolute) # and of any of the two test files assert error_path in ("testfile1.py", "testfile2.py") # Absolute paths should NOT be keys assert os.fspath(path1) not in dagbag.import_errors assert os.fspath(path2) not in dagbag.import_errors assert "AirflowDagDuplicatedIdException" in dagbag.import_errors[error_path] def test_zip_skip_log(self, caplog, test_zip_path): """ test the loading of a DAG from within a zip file that skips another file because it doesn't have "airflow" and "DAG" """ caplog.set_level(logging.INFO) dagbag = DagBag(dag_folder=test_zip_path, include_examples=False) assert dagbag.has_logged assert ( f"File {test_zip_path}:file_no_airflow_dag.py " "assumed to contain no DAGs. Skipping." in caplog.text ) def test_zip(self, tmp_path, test_zip_path): """ test the loading of a DAG within a zip file that includes dependencies """ syspath_before = deepcopy(sys.path) dagbag = DagBag(dag_folder=os.fspath(tmp_path), include_examples=False) dagbag.process_file(test_zip_path) assert dagbag.get_dag("test_zip_dag") assert sys.path == syspath_before # sys.path doesn't change assert not dagbag.import_errors @patch("airflow.dag_processing.importers.python_importer._timeout") @patch("airflow.dag_processing.dagbag.settings.get_dagbag_import_timeout") def test_process_dag_file_without_timeout( self, mocked_get_dagbag_import_timeout, mocked_timeout, tmp_path ): """ Test dag file parsing without timeout """ mocked_get_dagbag_import_timeout.return_value = 0 dagbag = DagBag(dag_folder=os.fspath(tmp_path), include_examples=False) dagbag.process_file(os.path.join(TEST_DAGS_FOLDER, "test_sensor.py")) mocked_timeout.assert_not_called() mocked_get_dagbag_import_timeout.return_value = -1 dagbag = DagBag(dag_folder=os.fspath(tmp_path), include_examples=False) dagbag.process_file(os.path.join(TEST_DAGS_FOLDER, "test_sensor.py")) mocked_timeout.assert_not_called() @patch("airflow.dag_processing.importers.python_importer._timeout") @patch("airflow.dag_processing.dagbag.settings.get_dagbag_import_timeout") def test_process_dag_file_with_non_default_timeout( self, mocked_get_dagbag_import_timeout, mocked_timeout, tmp_path ): """ Test customized dag file parsing timeout """ timeout_value = 100 mocked_get_dagbag_import_timeout.return_value = timeout_value # ensure the test value is not equal to the default value assert timeout_value != settings.conf.getfloat("core", "DAGBAG_IMPORT_TIMEOUT") dagbag = DagBag(dag_folder=os.fspath(tmp_path), include_examples=False) dagbag.process_file(os.path.join(TEST_DAGS_FOLDER, "test_sensor.py")) mocked_timeout.assert_called_once_with(timeout_value, error_message=mock.ANY) @patch("airflow.dag_processing.importers.python_importer.settings.get_dagbag_import_timeout") def test_check_value_type_from_get_dagbag_import_timeout( self, mocked_get_dagbag_import_timeout, tmp_path ): """ Test correctness of value from get_dagbag_import_timeout """ mocked_get_dagbag_import_timeout.return_value = "1" dagbag = DagBag(dag_folder=os.fspath(tmp_path), include_examples=False) with pytest.raises( TypeError, match=r"Value \(1\) from get_dagbag_import_timeout must be int or float" ): dagbag.process_file(os.path.join(TEST_DAGS_FOLDER, "test_sensor.py")) @pytest.fixture def invalid_cron_dag(self) -> str: return os.path.join(TEST_DAGS_FOLDER, "test_invalid_cron.py") @pytest.fixture def invalid_cron_zipped_dag(self, invalid_cron_dag: str, tmp_path: pathlib.Path) -> str: zipped = tmp_path / "test_zip_invalid_cron.zip" with zipfile.ZipFile(zipped, "w") as zf: zf.write(invalid_cron_dag, os.path.basename(invalid_cron_dag)) return os.fspath(zipped) @pytest.mark.parametrize("invalid_dag_name", ["invalid_cron_dag", "invalid_cron_zipped_dag"]) def test_process_file_cron_validity_check( self, request: pytest.FixtureRequest, invalid_dag_name: str, tmp_path ): """Test if an invalid cron expression as schedule interval can be identified""" dagbag = DagBag(dag_folder=os.fspath(tmp_path), include_examples=False) assert len(dagbag.import_errors) == 0 dagbag.process_file(request.getfixturevalue(invalid_dag_name)) assert len(dagbag.import_errors) == 1 assert len(dagbag.dags) == 0 def test_process_file_invalid_param_check(self, tmp_path): """ test if an invalid param in the dags can be identified """ invalid_dag_files = [ "test_invalid_param.py", "test_invalid_param2.py", "test_invalid_param3.py", "test_invalid_param4.py", ] dagbag = DagBag(dag_folder=os.fspath(tmp_path), include_examples=False) assert len(dagbag.import_errors) == 0 for file in invalid_dag_files: dagbag.process_file(os.path.join(TEST_DAGS_FOLDER, file)) assert len(dagbag.import_errors) == len(invalid_dag_files) assert len(dagbag.dags) == 0 def test_process_file_valid_param_check(self, tmp_path): """ test if valid params in the dags param can be validated (positive test) """ valid_dag_files = [ "test_valid_param.py", "test_valid_param2.py", ] dagbag = DagBag(dag_folder=os.fspath(tmp_path), include_examples=False) assert len(dagbag.import_errors) == 0 for file in valid_dag_files: dagbag.process_file(os.path.join(TEST_DAGS_FOLDER, file)) assert len(dagbag.import_errors) == 0 assert len(dagbag.dags) == len(valid_dag_files) @patch.object(DagModel, "get_current") def test_get_dag_without_refresh(self, mock_dagmodel): """ Test that, once a DAG is loaded, it doesn't get refreshed again if it hasn't been expired. """ dag_id = "example_bash_operator" mock_dagmodel.return_value = DagModel() mock_dagmodel.return_value.last_expired = None mock_dagmodel.return_value.fileloc = "foo" class _TestDagBag(DagBag): process_file_calls = 0 def process_file(self, filepath, only_if_updated=True, safe_mode=True): if os.path.basename(filepath) == "example_bash_operator.py": _TestDagBag.process_file_calls += 1 super().process_file(filepath, only_if_updated, safe_mode) dagbag = _TestDagBag(include_examples=True) dagbag.process_file_calls # Should not call process_file again, since it's already loaded during init. assert dagbag.process_file_calls == 1 assert dagbag.get_dag(dag_id) is not None assert dagbag.process_file_calls == 1 @pytest.mark.parametrize( ("file_to_load", "expected"), ( pytest.param( pathlib.Path(example_dags_folder) / "example_bash_operator.py", { "example_bash_operator": f"{example_dags_folder.relative_to(AIRFLOW_ROOT_PATH) / 'example_bash_operator.py'}" }, id="example_bash_operator", ), ), ) def test_get_dag_registration(self, file_to_load, expected): pytest.importorskip("system.standard") dagbag = DagBag(dag_folder=os.devnull, include_examples=False) dagbag.process_file(os.fspath(file_to_load)) for dag_id, path in expected.items(): dag = dagbag.get_dag(dag_id) assert dag, f"{dag_id} was bagged" assert dag.fileloc.endswith(path) @pytest.mark.parametrize( ("expected"), ( pytest.param( { "test_zip_dag": "test_zip.zip/test_zip.py", "test_zip_autoregister": "test_zip.zip/test_zip.py", }, id="test_zip.zip", ), ), ) def test_get_zip_dag_registration(self, test_zip_path, expected): dagbag = DagBag(dag_folder=os.devnull, include_examples=False) dagbag.process_file(test_zip_path) for dag_id, path in expected.items(): dag = dagbag.get_dag(dag_id) assert dag, f"{dag_id} was bagged" assert dag.fileloc.endswith(f"{pathlib.Path(test_zip_path).parent}/{path}") def test_dag_registration_with_failure(self): dagbag = DagBag(dag_folder=os.devnull, include_examples=False) found = dagbag.process_file(str(TEST_DAGS_FOLDER / "test_invalid_dup_task.py")) assert found == [] @pytest.fixture def zip_with_valid_dag_and_dup_tasks(self, tmp_path: pathlib.Path) -> str: failing_dag_file = TEST_DAGS_FOLDER / "test_invalid_dup_task.py" working_dag_file = TEST_DAGS_FOLDER / "test_example_bash_operator.py" zipped = tmp_path / "test_zip_invalid_dup_task.zip" with zipfile.ZipFile(zipped, "w") as zf: zf.write(failing_dag_file, failing_dag_file.name) zf.write(working_dag_file, working_dag_file.name) return os.fspath(zipped) def test_dag_registration_with_failure_zipped(self, zip_with_valid_dag_and_dup_tasks): dagbag = DagBag(dag_folder=os.devnull, include_examples=False) found = dagbag.process_file(zip_with_valid_dag_and_dup_tasks) assert len(found) == 1 assert [dag.dag_id for dag in found] == ["test_example_bash_operator"] @patch.object(DagModel, "get_current") def test_refresh_py_dag(self, mock_dagmodel, tmp_path): """ Test that we can refresh an ordinary .py DAG """ dag_id = "example_bash_operator" fileloc = str(example_dags_folder / "example_bash_operator.py") mock_dagmodel.return_value = DagModel() mock_dagmodel.return_value.last_expired = datetime.max.replace(tzinfo=timezone.utc) mock_dagmodel.return_value.fileloc = fileloc class _TestDagBag(DagBag): process_file_calls = 0 def process_file(self, filepath, only_if_updated=True, safe_mode=True): if filepath == fileloc: _TestDagBag.process_file_calls += 1 return super().process_file(filepath, only_if_updated, safe_mode) dagbag = _TestDagBag(dag_folder=os.fspath(tmp_path), include_examples=True) assert dagbag.process_file_calls == 1 dag = dagbag.get_dag(dag_id) assert dag is not None assert dag_id == dag.dag_id assert dagbag.process_file_calls == 2 @patch.object(DagModel, "get_current") def test_refresh_packaged_dag(self, mock_dagmodel, test_zip_path): """ Test that we can refresh a packaged DAG """ dag_id = "test_zip_dag" fileloc = os.path.realpath(os.path.join(test_zip_path, "test_zip.py")) mock_dagmodel.return_value = DagModel() mock_dagmodel.return_value.last_expired = datetime.max.replace(tzinfo=timezone.utc) mock_dagmodel.return_value.fileloc = fileloc class _TestDagBag(DagBag): process_file_calls = 0 def process_file(self, filepath, only_if_updated=True, safe_mode=True): if filepath in fileloc: _TestDagBag.process_file_calls += 1 return super().process_file(filepath, only_if_updated, safe_mode) dagbag = _TestDagBag(dag_folder=os.path.realpath(test_zip_path), include_examples=False) assert dagbag.process_file_calls == 1 dag = dagbag.get_dag(dag_id) assert dag is not None assert dag_id == dag.dag_id assert dagbag.process_file_calls == 2 def process_dag(self, create_dag, tmp_path): """ Helper method to process a file generated from the input create_dag function. """ # write source to file source = textwrap.dedent("".join(inspect.getsource(create_dag).splitlines(True)[1:-1])) path = tmp_path / "testfile.py" path.write_text(source) dagbag = DagBag(dag_folder=os.fspath(path.parent), include_examples=False) found_dags = dagbag.process_file(os.fspath(path)) return dagbag, found_dags, os.fspath(path) def validate_dags(self, expected_dag, actual_found_dags, actual_dagbag, should_be_found=True): actual_found_dag_ids = [dag.dag_id for dag in actual_found_dags] dag_id = expected_dag.dag_id actual_dagbag.log.info("validating %s", dag_id) assert (dag_id in actual_found_dag_ids) == should_be_found, ( f'dag "{dag_id}" should {"" if should_be_found else "not "}' f'have been found after processing dag "{expected_dag.dag_id}"' ) assert (dag_id in actual_dagbag.dags) == should_be_found, ( f'dag "{dag_id}" should {"" if should_be_found else "not "}' f'be in dagbag.dags after processing dag "{expected_dag.dag_id}"' ) def test_skip_cycle_dags(self, tmp_path): """ Don't crash when loading an invalid (contains a cycle) DAG file. Don't load the dag into the DagBag either """ # Define Dag to load def basic_cycle(): import datetime from airflow.models.dag import DAG from airflow.providers.standard.operators.empty import EmptyOperator dag_name = "cycle_dag" default_args = {"owner": "owner1", "start_date": datetime.datetime(2016, 1, 1)} dag = DAG(dag_name, schedule=timedelta(days=1), default_args=default_args) # A -> A with dag: op_a = EmptyOperator(task_id="A") op_a.set_downstream(op_a) return dag test_dag = basic_cycle() # Perform processing dag dagbag, found_dags, file_path = self.process_dag(basic_cycle, tmp_path) # #Validate correctness # None of the dags should be found self.validate_dags(test_dag, found_dags, dagbag, should_be_found=False) assert file_path in dagbag.import_errors def test_process_file_with_none(self, tmp_path): """ test that process_file can handle Nones """ dagbag = DagBag(dag_folder=os.fspath(tmp_path), include_examples=False) assert dagbag.process_file(None) == [] def test_timeout_dag_errors_are_import_errors(self, tmp_path, caplog): """ Test that if the DAG contains Timeout error it will be still loaded to DB as import_errors """ dag_file = tmp_path / "timeout_dag.py" dag_file.write_text(""" import datetime import time import airflow from airflow.providers.standard.operators.python import PythonOperator time.sleep(1) # Exceeds DAGBAG_IMPORT_TIMEOUT (0.01s), triggers timeout with airflow.DAG( "import_timeout", start_date=datetime.datetime(2022, 1, 1), schedule=None) as dag: pass """) with conf_vars({("core", "DAGBAG_IMPORT_TIMEOUT"): "0.01"}): dagbag = DagBag(dag_folder=os.fspath(tmp_path), include_examples=False) assert dag_file.as_posix() in dagbag.import_errors assert "DagBag import timeout for" in caplog.text @staticmethod def _make_test_traceback(unparseable_filename: str, depth=None) -> str: python_311_marker = " ^^^^^^^^^^^\n" if PY311 else "" python_313_marker = [" ~~~~~~~~~^^\n"] if PY313 else [] frames = ( f' File "{unparseable_filename}", line 3, in <module>\n something()\n', *python_313_marker, f' File "{unparseable_filename}", line 2, in something\n return airflow_DAG\n{python_311_marker}', ) depth = 0 if depth is None else -depth return ( "Traceback (most recent call last):\n" + "".join(frames[depth:]) + "NameError: name 'airflow_DAG' is not defined\n" ) @pytest.mark.parametrize("depth", (None, 1)) def test_import_error_tracebacks(self, tmp_path, depth): unparseable_filename = tmp_path.joinpath("dag.py").as_posix() with open(unparseable_filename, "w") as unparseable_file: unparseable_file.writelines(INVALID_DAG_WITH_DEPTH_FILE_CONTENTS) with contextlib.ExitStack() as cm: if depth is not None: cm.enter_context(conf_vars({("core", "dagbag_import_error_traceback_depth"): str(depth)})) dagbag = DagBag(dag_folder=unparseable_filename, include_examples=False) import_errors = dagbag.import_errors assert unparseable_filename in import_errors assert import_errors[unparseable_filename] == self._make_test_traceback(unparseable_filename, depth) @pytest.mark.parametrize("depth", (None, 1)) def test_import_error_tracebacks_zip(self, tmp_path, depth): invalid_zip_filename = (tmp_path / "test_zip_invalid.zip").as_posix() invalid_dag_filename = os.path.join(invalid_zip_filename, "dag.py") with zipfile.ZipFile(invalid_zip_filename, "w") as invalid_zip_file: invalid_zip_file.writestr("dag.py", INVALID_DAG_WITH_DEPTH_FILE_CONTENTS) with contextlib.ExitStack() as cm: if depth is not None: cm.enter_context(conf_vars({("core", "dagbag_import_error_traceback_depth"): str(depth)})) dagbag = DagBag(dag_folder=invalid_zip_filename, include_examples=False) import_errors = dagbag.import_errors assert invalid_dag_filename in import_errors assert import_errors[invalid_dag_filename] == self._make_test_traceback(invalid_dag_filename, depth) @patch("airflow.settings.task_policy", cluster_policies.example_task_policy) def test_task_cluster_policy_violation(self): """ test that file processing results in import error when task does not obey cluster policy. """ dag_file = os.path.join(TEST_DAGS_FOLDER, "test_missing_owner.py") dag_id = "test_missing_owner" err_cls_name = "AirflowClusterPolicyViolation" dagbag = DagBag(dag_folder=dag_file, include_examples=False) assert set() == set(dagbag.dag_ids) expected_import_errors = { dag_file: ( f"""{err_cls_name}: DAG policy violation (DAG ID: {dag_id}, Path: {dag_file}):\n""" """Notices:\n""" """ * Task must have non-None non-default owner. Current value: airflow""" ) } assert expected_import_errors == dagbag.import_errors @patch("airflow.settings.task_policy", cluster_policies.example_task_policy) def test_task_cluster_policy_nonstring_owner(self): """ test that file processing results in import error when task does not obey cluster policy and has owner whose type is not string. """ TEST_DAGS_CORRUPTED_FOLDER = pathlib.Path(__file__).parent.with_name("dags_corrupted") dag_file = os.path.join(TEST_DAGS_CORRUPTED_FOLDER, "test_nonstring_owner.py") dag_id = "test_nonstring_owner" err_cls_name = "AirflowClusterPolicyViolation" dagbag = DagBag(dag_folder=dag_file, include_examples=False) assert set() == set(dagbag.dag_ids) expected_import_errors = { dag_file: ( f"""{err_cls_name}: DAG policy violation (DAG ID: {dag_id}, Path: {dag_file}):\n""" """Notices:\n""" """ * owner should be a string. Current value: ['a']""" ) } assert expected_import_errors == dagbag.import_errors @patch("airflow.settings.task_policy", cluster_policies.example_task_policy) def test_task_cluster_policy_obeyed(self): """ test that dag successfully imported without import errors when tasks obey cluster policy. """ dag_file = os.path.join(TEST_DAGS_FOLDER, "test_with_non_default_owner.py") dagbag = DagBag(dag_folder=dag_file, include_examples=False) assert {"test_with_non_default_owner"} == set(dagbag.dag_ids) assert dagbag.import_errors == {} @patch("airflow.settings.dag_policy", cluster_policies.dag_policy) def test_dag_cluster_policy_obeyed(self): dag_file = os.path.join(TEST_DAGS_FOLDER, "test_dag_with_no_tags.py") dagbag = DagBag(dag_folder=dag_file, include_examples=False) assert len(dagbag.dag_ids) == 0 assert "has no tags" in dagbag.import_errors[dag_file] def test_dagbag_dag_collection(self): dagbag = DagBag( dag_folder=TEST_DAGS_FOLDER, include_examples=False, collect_dags=False, bundle_name="test_collection", ) # since collect_dags is False, dagbag.dags should be empty assert not dagbag.dags dagbag.collect_dags() assert dagbag.dags # test that dagbag.dags is not empty if collect_dags is True dagbag = DagBag(dag_folder=TEST_DAGS_FOLDER, include_examples=False, bundle_name="test_collection") assert dagbag.dags def test_dabgag_captured_warnings(self): dag_file = os.path.join(TEST_DAGS_FOLDER, "test_dag_warnings.py") dagbag = DagBag(dag_folder=dag_file, include_examples=False, collect_dags=False) assert dag_file not in dagbag.captured_warnings dagbag.collect_dags(dag_folder=dagbag.dag_folder, include_examples=False, only_if_updated=False) assert dagbag.dagbag_stats[0].warning_num == 2 assert dagbag.captured_warnings == { dag_file: ( f"{dag_file}:46: DeprecationWarning: Deprecated Parameter", f"{dag_file}:48: UserWarning: Some Warning", ) } with warnings.catch_warnings(): # Disable capture DeprecationWarning, and it should be reflected in captured warnings warnings.simplefilter("ignore", DeprecationWarning) dagbag.collect_dags(dag_folder=dagbag.dag_folder, include_examples=False, only_if_updated=False) assert dag_file in dagbag.captured_warnings assert len(dagbag.captured_warnings[dag_file]) == 1 assert dagbag.dagbag_stats[0].warning_num == 1 # Disable all warnings, no captured warnings expected warnings.simplefilter("ignore") dagbag.collect_dags(dag_folder=dagbag.dag_folder, include_examples=False, only_if_updated=False) assert dag_file not in dagbag.captured_warnings assert dagbag.dagbag_stats[0].warning_num == 0 @pytest.fixture def warning_zipped_dag_path(self, tmp_path: pathlib.Path) -> str: warnings_dag_file = TEST_DAGS_FOLDER / "test_dag_warnings.py" zipped = tmp_path / "test_dag_warnings.zip" with zipfile.ZipFile(zipped, "w") as zf: zf.write(warnings_dag_file, warnings_dag_file.name) return os.fspath(zipped) def test_dabgag_captured_warnings_zip(self, warning_zipped_dag_path: str): in_zip_dag_file = f"{warning_zipped_dag_path}/test_dag_warnings.py" dagbag = DagBag(dag_folder=warning_zipped_dag_path, include_examples=False) assert dagbag.dagbag_stats[0].warning_num == 2 assert dagbag.captured_warnings == { warning_zipped_dag_path: ( f"{in_zip_dag_file}:46: DeprecationWarning: Deprecated Parameter", f"{in_zip_dag_file}:48: UserWarning: Some Warning", ) } @pytest.mark.parametrize( ("known_pools", "expected"), ( pytest.param(None, set(), id="disabled"), pytest.param( {"default_pool"}, { DagWarning( "test", DagWarningType.NONEXISTENT_POOL, "Dag 'test' references non-existent pools: ['pool1']", ), }, id="only-default", ), pytest.param( {"default_pool", "pool1"}, set(), id="known-pools", ), ), ) def test_dag_warnings_invalid_pool(self, known_pools, expected): with DAG(dag_id="test") as dag: BaseOperator(task_id="1") BaseOperator(task_id="2", pool="pool1") dagbag = DagBag(dag_folder="", include_examples=False, collect_dags=False, known_pools=known_pools) dagbag.bag_dag(dag) assert dagbag.dag_warnings == expected def test_sigsegv_handling(self, tmp_path, caplog): """ Test that a SIGSEGV in a DAG file is handled gracefully and does not crash the process. """ # Create a DAG file that will raise a SIGSEGV dag_file = tmp_path / "bad_dag.py" dag_file.write_text( textwrap.dedent( """\ import signal from airflow import DAG import os from airflow.decorators import task os.kill(os.getpid(), signal.SIGSEGV) with DAG('testbug'): @task def mytask(): print(1) mytask() """ ) ) dagbag = DagBag(dag_folder=os.fspath(tmp_path), include_examples=False) assert "Received SIGSEGV signal while processing" in caplog.text assert dag_file.as_posix() in dagbag.import_errors def test_failed_signal_registration_does_not_crash_the_process(self, tmp_path, caplog): """Test that a ValueError raised by a signal setting on child process does not crash the main process. This was raised in test_dag_report.py module in api_fastapi/core_api/routes/public tests """ dag_file = tmp_path / "test_dag.py" dag_file.write_text( textwrap.dedent( """\ from airflow import DAG from airflow.decorators import task with DAG('testbug'): @task def mytask(): print(1) mytask() """ ) ) with mock.patch("airflow.dag_processing.importers.python_importer.signal.signal") as mock_signal: mock_signal.side_effect = ValueError("Invalid signal setting") DagBag(dag_folder=os.fspath(tmp_path), include_examples=False) assert "SIGSEGV signal handler registration failed. Not in the main thread" in caplog.text class TestCaptureWithReraise: @staticmethod def raise_warnings(): warnings.warn("Foo", UserWarning, stacklevel=2) warnings.warn("Bar", UserWarning, stacklevel=2) warnings.warn("Baz", UserWarning, stacklevel=2) def test_capture_no_warnings(self): with warnings.catch_warnings(): warnings.simplefilter("error") with _capture_with_reraise() as cw: pass assert cw == [] def test_capture_warnings(self): with pytest.warns(UserWarning, match="(Foo|Bar|Baz)") as ctx: with _capture_with_reraise() as cw: self.raise_warnings() assert len(cw) == 3 assert len(ctx.list) == 3 def test_capture_warnings_with_parent_error_filter(self): with warnings.catch_warnings(record=True) as records: warnings.filterwarnings("error", message="Bar") with _capture_with_reraise() as cw: with pytest.raises(UserWarning, match="Bar"): self.raise_warnings() assert len(cw) == 1 assert len(records) == 1 def test_capture_warnings_with_parent_ignore_filter(self): with warnings.catch_warnings(record=True) as records: warnings.filterwarnings("ignore", message="Baz") with _capture_with_reraise() as cw: self.raise_warnings() assert len(cw) == 2 assert len(records) == 2 def test_capture_warnings_with_filters(self): with warnings.catch_warnings(record=True) as records: with _capture_with_reraise() as cw: warnings.filterwarnings("ignore", message="Foo") self.raise_warnings() assert len(cw) == 2 assert len(records) == 2 def test_capture_warnings_with_error_filters(self): with warnings.catch_warnings(record=True) as records: with _capture_with_reraise() as cw: warnings.filterwarnings("error", message="Bar") with pytest.raises(UserWarning, match="Bar"): self.raise_warnings() assert len(cw) == 1 assert len(records) == 1 class TestBundlePathSysPath: """Tests for bundle_path sys.path handling in BundleDagBag.""" def test_bundle_path_added_to_syspath(self, tmp_path): """Test that BundleDagBag adds bundle_path to sys.path when provided.""" util_file = tmp_path / "bundle_util.py" util_file.write_text('def get_message(): return "Hello from bundle!"') dag_file = tmp_path / "test_dag.py" dag_file.write_text( textwrap.dedent( """\ from airflow.sdk import DAG from airflow.operators.empty import EmptyOperator import sys import bundle_util with DAG('test_import', description=f"DAG with sys.path: {sys.path}"): EmptyOperator(task_id="mytask") """ ) ) assert str(tmp_path) not in sys.path dagbag = BundleDagBag(dag_folder=str(dag_file), bundle_path=tmp_path, bundle_name="test-bundle") # Check import was successful assert len(dagbag.dags) == 1 assert not dagbag.import_errors dag = dagbag.get_dag("test_import") assert dag is not None assert str(tmp_path) in dag.description # sys.path was enhanced during parse # Path remains in sys.path (no cleanup - intentional for ephemeral processes) assert str(tmp_path) in sys.path # Cleanup for other tests sys.path.remove(str(tmp_path)) def test_bundle_path_not_duplicated(self, tmp_path): """Test that bundle_path is not added to sys.path if already present.""" dag_file = tmp_path / "simple_dag.py" dag_file.write_text( textwrap.dedent( """\ from airflow.sdk import DAG from airflow.operators.empty import EmptyOperator with DAG("simple_dag"): EmptyOperator(task_id="mytask") """ ) ) # Pre-add the path sys.path.append(str(tmp_path)) count_before = sys.path.count(str(tmp_path)) BundleDagBag(dag_folder=str(dag_file), bundle_path=tmp_path, bundle_name="test-bundle") # Should not add duplicate assert sys.path.count(str(tmp_path)) == count_before # Cleanup for other tests sys.path.remove(str(tmp_path)) def test_dagbag_no_bundle_path_no_syspath_modification(self, tmp_path): """Test that no sys.path modification occurs when DagBag is used without bundle_path.""" dag_file = tmp_path / "simple_dag.py" dag_file.write_text( textwrap.dedent( """\ from airflow.sdk import DAG from airflow.operators.empty import EmptyOperator import sys with DAG("simple_dag", description=f"DAG with sys.path: {sys.path}") as dag: EmptyOperator(task_id="mytask") """ ) ) syspath_before = deepcopy(sys.path) dagbag = DagBag(dag_folder=str(dag_file), include_examples=False) dag = dagbag.get_dag("simple_dag") assert str(tmp_path) not in dag.description assert sys.path == syspath_before
python
github
https://github.com/apache/airflow
airflow-core/tests/unit/dag_processing/test_dagbag.py
/* * Copyright 2002-present the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.docs.integration.jms.jmsreceivingasyncmessagelisteneradapter; import org.springframework.web.socket.TextMessage; // tag::snippet[] public interface TextMessageDelegate { void receive(TextMessage message); } // end::snippet[]
java
github
https://github.com/spring-projects/spring-framework
framework-docs/src/main/java/org/springframework/docs/integration/jms/jmsreceivingasyncmessagelisteneradapter/TextMessageDelegate.java
from __future__ import unicode_literals from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation ) from django.contrib.contenttypes.models import ContentType from django.db import models from django.test import TestCase from django.utils.encoding import python_2_unicode_compatible from rest_framework import serializers @python_2_unicode_compatible class Tag(models.Model): """ Tags have a descriptive slug, and are attached to an arbitrary object. """ tag = models.SlugField() content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() tagged_item = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.tag @python_2_unicode_compatible class Bookmark(models.Model): """ A URL bookmark that may have multiple tags attached. """ url = models.URLField() tags = GenericRelation(Tag) def __str__(self): return 'Bookmark: %s' % self.url @python_2_unicode_compatible class Note(models.Model): """ A textual note that may have multiple tags attached. """ text = models.TextField() tags = GenericRelation(Tag) def __str__(self): return 'Note: %s' % self.text class TestGenericRelations(TestCase): def setUp(self): self.bookmark = Bookmark.objects.create(url='https://www.djangoproject.com/') Tag.objects.create(tagged_item=self.bookmark, tag='django') Tag.objects.create(tagged_item=self.bookmark, tag='python') self.note = Note.objects.create(text='Remember the milk') Tag.objects.create(tagged_item=self.note, tag='reminder') def test_generic_relation(self): """ Test a relationship that spans a GenericRelation field. IE. A reverse generic relationship. """ class BookmarkSerializer(serializers.ModelSerializer): tags = serializers.StringRelatedField(many=True) class Meta: model = Bookmark fields = ('tags', 'url') serializer = BookmarkSerializer(self.bookmark) expected = { 'tags': ['django', 'python'], 'url': 'https://www.djangoproject.com/' } self.assertEqual(serializer.data, expected) def test_generic_fk(self): """ Test a relationship that spans a GenericForeignKey field. IE. A forward generic relationship. """ class TagSerializer(serializers.ModelSerializer): tagged_item = serializers.StringRelatedField() class Meta: model = Tag fields = ('tag', 'tagged_item') serializer = TagSerializer(Tag.objects.all(), many=True) expected = [ { 'tag': 'django', 'tagged_item': 'Bookmark: https://www.djangoproject.com/' }, { 'tag': 'python', 'tagged_item': 'Bookmark: https://www.djangoproject.com/' }, { 'tag': 'reminder', 'tagged_item': 'Note: Remember the milk' } ] self.assertEqual(serializer.data, expected)
unknown
codeparrot/codeparrot-clean
#include <gtest/gtest.h> #include <ATen/ATen.h> #include <ATen/test/test_assert.h> #include <cmath> #include <iostream> #include <limits> #include <sstream> #include <type_traits> using namespace at; TEST(TestHalf, Arithmetic) { Half zero = 0; Half one = 1; ASSERT_EQ(zero + one, one); ASSERT_EQ(zero + zero, zero); ASSERT_EQ(zero * one, zero); ASSERT_EQ(one * one, one); ASSERT_EQ(one / one, one); ASSERT_EQ(one - one, zero); ASSERT_EQ(one - zero, one); ASSERT_EQ(zero - one, -one); ASSERT_EQ(one + one, Half(2)); ASSERT_EQ(one + one, 2); } TEST(TestHalf, Comparisons) { Half zero = 0; Half one = 1; ASSERT_LT(zero, one); ASSERT_LT(zero, 1); ASSERT_GT(1, zero); ASSERT_GE(0, zero); ASSERT_NE(0, one); ASSERT_EQ(zero, 0); ASSERT_EQ(zero, zero); ASSERT_EQ(zero, -zero); } TEST(TestHalf, Cast) { Half value = 1.5f; ASSERT_EQ((int)value, 1); ASSERT_EQ((short)value, 1); ASSERT_EQ((long long)value, 1LL); ASSERT_EQ((float)value, 1.5f); ASSERT_EQ((double)value, 1.5); ASSERT_EQ((bool)value, true); ASSERT_EQ((bool)Half(0.0f), false); } TEST(TestHalf, Construction) { ASSERT_EQ(Half((short)3), Half(3.0f)); ASSERT_EQ(Half((unsigned short)3), Half(3.0f)); ASSERT_EQ(Half(3), Half(3.0f)); ASSERT_EQ(Half(3U), Half(3.0f)); ASSERT_EQ(Half(3LL), Half(3.0f)); ASSERT_EQ(Half(3ULL), Half(3.0f)); ASSERT_EQ(Half(3.5), Half(3.5f)); } static std::string to_string(const Half& h) { std::stringstream ss; ss << h; return ss.str(); } TEST(TestHalf, Half2String) { ASSERT_EQ(to_string(Half(3.5f)), "3.5"); ASSERT_EQ(to_string(Half(-100.0f)), "-100"); } TEST(TestHalf, HalfNumericLimits) { using limits = std::numeric_limits<Half>; ASSERT_EQ(limits::lowest(), -65504.0f); ASSERT_EQ(limits::max(), 65504.0f); ASSERT_GT(limits::min(), 0); ASSERT_LT(limits::min(), 1); ASSERT_GT(limits::denorm_min(), 0); ASSERT_EQ(limits::denorm_min() / 2, 0); ASSERT_EQ(limits::infinity(), std::numeric_limits<float>::infinity()); ASSERT_NE(limits::quiet_NaN(), limits::quiet_NaN()); ASSERT_NE(limits::signaling_NaN(), limits::signaling_NaN()); } // Check the declared type of members of numeric_limits<Half> matches // the declared type of that member on numeric_limits<float> #define ASSERT_SAME_TYPE(name) \ static_assert( \ std::is_same_v< \ decltype(std::numeric_limits<Half>::name), \ decltype(std::numeric_limits<float>::name)>, \ "decltype(" #name ") differs") ASSERT_SAME_TYPE(is_specialized); ASSERT_SAME_TYPE(is_signed); ASSERT_SAME_TYPE(is_integer); ASSERT_SAME_TYPE(is_exact); ASSERT_SAME_TYPE(has_infinity); ASSERT_SAME_TYPE(has_quiet_NaN); ASSERT_SAME_TYPE(has_signaling_NaN); ASSERT_SAME_TYPE(has_denorm); ASSERT_SAME_TYPE(has_denorm_loss); ASSERT_SAME_TYPE(round_style); ASSERT_SAME_TYPE(is_iec559); ASSERT_SAME_TYPE(is_bounded); ASSERT_SAME_TYPE(is_modulo); ASSERT_SAME_TYPE(digits); ASSERT_SAME_TYPE(digits10); ASSERT_SAME_TYPE(max_digits10); ASSERT_SAME_TYPE(radix); ASSERT_SAME_TYPE(min_exponent); ASSERT_SAME_TYPE(min_exponent10); ASSERT_SAME_TYPE(max_exponent); ASSERT_SAME_TYPE(max_exponent10); ASSERT_SAME_TYPE(traps); ASSERT_SAME_TYPE(tinyness_before); TEST(TestHalf, CommonMath) { #ifndef NDEBUG float threshold = 0.00001; #endif assert(std::abs(std::lgamma(Half(10.0)) - std::lgamma(10.0f)) <= threshold); assert(std::abs(std::exp(Half(1.0)) - std::exp(1.0f)) <= threshold); assert(std::abs(std::log(Half(1.0)) - std::log(1.0f)) <= threshold); assert(std::abs(std::log10(Half(1000.0)) - std::log10(1000.0f)) <= threshold); assert(std::abs(std::log1p(Half(0.0)) - std::log1p(0.0f)) <= threshold); assert(std::abs(std::log2(Half(1000.0)) - std::log2(1000.0f)) <= threshold); assert(std::abs(std::expm1(Half(1.0)) - std::expm1(1.0f)) <= threshold); assert(std::abs(std::cos(Half(0.0)) - std::cos(0.0f)) <= threshold); assert(std::abs(std::sin(Half(0.0)) - std::sin(0.0f)) <= threshold); assert(std::abs(std::sqrt(Half(100.0)) - std::sqrt(100.0f)) <= threshold); assert(std::abs(std::ceil(Half(2.4)) - std::ceil(2.4f)) <= threshold); assert(std::abs(std::floor(Half(2.7)) - std::floor(2.7f)) <= threshold); assert(std::abs(std::trunc(Half(2.7)) - std::trunc(2.7f)) <= threshold); assert(std::abs(std::acos(Half(-1.0)) - std::acos(-1.0f)) <= threshold); assert(std::abs(std::cosh(Half(1.0)) - std::cosh(1.0f)) <= threshold); assert(std::abs(std::acosh(Half(1.0)) - std::acosh(1.0f)) <= threshold); assert(std::abs(std::asin(Half(1.0)) - std::asin(1.0f)) <= threshold); assert(std::abs(std::sinh(Half(1.0)) - std::sinh(1.0f)) <= threshold); assert(std::abs(std::asinh(Half(1.0)) - std::asinh(1.0f)) <= threshold); assert(std::abs(std::tan(Half(0.0)) - std::tan(0.0f)) <= threshold); assert(std::abs(std::atan(Half(1.0)) - std::atan(1.0f)) <= threshold); assert(std::abs(std::tanh(Half(1.0)) - std::tanh(1.0f)) <= threshold); assert(std::abs(std::erf(Half(10.0)) - std::erf(10.0f)) <= threshold); assert(std::abs(std::erfc(Half(10.0)) - std::erfc(10.0f)) <= threshold); assert(std::abs(std::abs(Half(-3.0)) - std::abs(-3.0f)) <= threshold); assert(std::abs(std::round(Half(2.3)) - std::round(2.3f)) <= threshold); assert( std::abs(std::pow(Half(2.0), Half(10.0)) - std::pow(2.0f, 10.0f)) <= threshold); assert( std::abs(std::atan2(Half(7.0), Half(0.0)) - std::atan2(7.0f, 0.0f)) <= threshold); #ifdef __APPLE__ // @TODO: can macos do implicit conversion of Half? assert( std::abs(std::isnan(static_cast<float>(Half(0.0))) - std::isnan(0.0f)) <= threshold); assert( std::abs(std::isinf(static_cast<float>(Half(0.0))) - std::isinf(0.0f)) <= threshold); #else assert(std::abs(std::isnan(Half(0.0)) - std::isnan(0.0f)) <= threshold); assert(std::abs(std::isinf(Half(0.0)) - std::isinf(0.0f)) <= threshold); #endif } TEST(TestHalf, ComplexHalf) { Half real = 3.0f; Half imag = -10.0f; auto complex = c10::complex<Half>(real, imag); ASSERT_EQ(complex.real(), real); ASSERT_EQ(complex.imag(), imag); }
cpp
github
https://github.com/pytorch/pytorch
aten/src/ATen/test/half_test.cpp
/* Copyright 2013 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ /* Sliding window over the input data. */ #ifndef BROTLI_ENC_RINGBUFFER_H_ #define BROTLI_ENC_RINGBUFFER_H_ #include "../common/platform.h" #include "memory.h" #include "params.h" #include "quality.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* A RingBuffer(window_bits, tail_bits) contains `1 << window_bits' bytes of data in a circular manner: writing a byte writes it to: `position() % (1 << window_bits)'. For convenience, the RingBuffer array contains another copy of the first `1 << tail_bits' bytes: buffer_[i] == buffer_[i + (1 << window_bits)], if i < (1 << tail_bits), and another copy of the last two bytes: buffer_[-1] == buffer_[(1 << window_bits) - 1] and buffer_[-2] == buffer_[(1 << window_bits) - 2]. */ typedef struct RingBuffer { /* Size of the ring-buffer is (1 << window_bits) + tail_size_. */ const uint32_t size_; const uint32_t mask_; const uint32_t tail_size_; const uint32_t total_size_; uint32_t cur_size_; /* Position to write in the ring buffer. */ uint32_t pos_; /* The actual ring buffer containing the copy of the last two bytes, the data, and the copy of the beginning as a tail. */ uint8_t* data_; /* The start of the ring-buffer. */ uint8_t* buffer_; } RingBuffer; static BROTLI_INLINE void RingBufferInit(RingBuffer* rb) { rb->cur_size_ = 0; rb->pos_ = 0; rb->data_ = 0; rb->buffer_ = 0; } static BROTLI_INLINE void RingBufferSetup( const BrotliEncoderParams* params, RingBuffer* rb) { int window_bits = ComputeRbBits(params); int tail_bits = params->lgblock; *(uint32_t*)&rb->size_ = 1u << window_bits; *(uint32_t*)&rb->mask_ = (1u << window_bits) - 1; *(uint32_t*)&rb->tail_size_ = 1u << tail_bits; *(uint32_t*)&rb->total_size_ = rb->size_ + rb->tail_size_; } static BROTLI_INLINE void RingBufferFree(MemoryManager* m, RingBuffer* rb) { BROTLI_FREE(m, rb->data_); } /* Allocates or re-allocates data_ to the given length + plus some slack region before and after. Fills the slack regions with zeros. */ static BROTLI_INLINE void RingBufferInitBuffer( MemoryManager* m, const uint32_t buflen, RingBuffer* rb) { static const size_t kSlackForEightByteHashingEverywhere = 7; uint8_t* new_data = BROTLI_ALLOC( m, uint8_t, 2 + buflen + kSlackForEightByteHashingEverywhere); size_t i; if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(new_data)) return; if (rb->data_) { memcpy(new_data, rb->data_, 2 + rb->cur_size_ + kSlackForEightByteHashingEverywhere); BROTLI_FREE(m, rb->data_); } rb->data_ = new_data; rb->cur_size_ = buflen; rb->buffer_ = rb->data_ + 2; rb->buffer_[-2] = rb->buffer_[-1] = 0; for (i = 0; i < kSlackForEightByteHashingEverywhere; ++i) { rb->buffer_[rb->cur_size_ + i] = 0; } } static BROTLI_INLINE void RingBufferWriteTail( const uint8_t* bytes, size_t n, RingBuffer* rb) { const size_t masked_pos = rb->pos_ & rb->mask_; if (BROTLI_PREDICT_FALSE(masked_pos < rb->tail_size_)) { /* Just fill the tail buffer with the beginning data. */ const size_t p = rb->size_ + masked_pos; memcpy(&rb->buffer_[p], bytes, BROTLI_MIN(size_t, n, rb->tail_size_ - masked_pos)); } } /* Push bytes into the ring buffer. */ static BROTLI_INLINE void RingBufferWrite( MemoryManager* m, const uint8_t* bytes, size_t n, RingBuffer* rb) { if (rb->pos_ == 0 && n < rb->tail_size_) { /* Special case for the first write: to process the first block, we don't need to allocate the whole ring-buffer and we don't need the tail either. However, we do this memory usage optimization only if the first write is less than the tail size, which is also the input block size, otherwise it is likely that other blocks will follow and we will need to reallocate to the full size anyway. */ rb->pos_ = (uint32_t)n; RingBufferInitBuffer(m, rb->pos_, rb); if (BROTLI_IS_OOM(m)) return; memcpy(rb->buffer_, bytes, n); return; } if (rb->cur_size_ < rb->total_size_) { /* Lazily allocate the full buffer. */ RingBufferInitBuffer(m, rb->total_size_, rb); if (BROTLI_IS_OOM(m)) return; /* Initialize the last two bytes to zero, so that we don't have to worry later when we copy the last two bytes to the first two positions. */ rb->buffer_[rb->size_ - 2] = 0; rb->buffer_[rb->size_ - 1] = 0; /* Initialize tail; might be touched by "best_len++" optimization when ring buffer is "full". */ rb->buffer_[rb->size_] = 241; } { const size_t masked_pos = rb->pos_ & rb->mask_; /* The length of the writes is limited so that we do not need to worry about a write */ RingBufferWriteTail(bytes, n, rb); if (BROTLI_PREDICT_TRUE(masked_pos + n <= rb->size_)) { /* A single write fits. */ memcpy(&rb->buffer_[masked_pos], bytes, n); } else { /* Split into two writes. Copy into the end of the buffer, including the tail buffer. */ memcpy(&rb->buffer_[masked_pos], bytes, BROTLI_MIN(size_t, n, rb->total_size_ - masked_pos)); /* Copy into the beginning of the buffer */ memcpy(&rb->buffer_[0], bytes + (rb->size_ - masked_pos), n - (rb->size_ - masked_pos)); } } { BROTLI_BOOL not_first_lap = (rb->pos_ & (1u << 31)) != 0; uint32_t rb_pos_mask = (1u << 31) - 1; rb->buffer_[-2] = rb->buffer_[rb->size_ - 2]; rb->buffer_[-1] = rb->buffer_[rb->size_ - 1]; rb->pos_ = (rb->pos_ & rb_pos_mask) + (uint32_t)(n & rb_pos_mask); if (not_first_lap) { /* Wrap, but preserve not-a-first-lap feature. */ rb->pos_ |= 1u << 31; } } } #if defined(__cplusplus) || defined(c_plusplus) } /* extern "C" */ #endif #endif /* BROTLI_ENC_RINGBUFFER_H_ */
c
github
https://github.com/nodejs/node
deps/brotli/c/enc/ringbuffer.h
# SPDX-License-Identifier: (GPL-2.0 OR BSD-2-Clause) %YAML 1.2 --- $id: http://devicetree.org/schemas/cache/starfive,jh8100-starlink-cache.yaml# $schema: http://devicetree.org/meta-schemas/core.yaml# title: StarFive StarLink Cache Controller maintainers: - Joshua Yeong <joshua.yeong@starfivetech.com> description: StarFive's StarLink Cache Controller manages the L3 cache shared between clusters of CPU cores. The cache driver enables RISC-V non-standard cache management as an alternative to instructions in the RISC-V Zicbom extension. allOf: - $ref: /schemas/cache-controller.yaml# # We need a select here so we don't match all nodes with 'cache' select: properties: compatible: contains: enum: - starfive,jh8100-starlink-cache required: - compatible properties: compatible: items: - const: starfive,jh8100-starlink-cache - const: cache reg: maxItems: 1 unevaluatedProperties: false required: - compatible - reg - cache-block-size - cache-level - cache-sets - cache-size - cache-unified examples: - | soc { #address-cells = <2>; #size-cells = <2>; cache-controller@15000000 { compatible = "starfive,jh8100-starlink-cache", "cache"; reg = <0x0 0x15000000 0x0 0x278>; cache-block-size = <64>; cache-level = <3>; cache-sets = <8192>; cache-size = <0x400000>; cache-unified; }; };
unknown
github
https://github.com/torvalds/linux
Documentation/devicetree/bindings/cache/starfive,jh8100-starlink-cache.yaml
// These just test that serde_derive is able to produce code that compiles // successfully when there are a variety of generics and non-(de)serializable // types involved. #![deny(warnings)] #![allow( confusable_idents, unknown_lints, mixed_script_confusables, clippy::derive_partial_eq_without_eq, clippy::extra_unused_type_parameters, clippy::items_after_statements, clippy::missing_errors_doc, clippy::missing_panics_doc, clippy::must_use_candidate, // Clippy bug: https://github.com/rust-lang/rust-clippy/issues/7422 clippy::nonstandard_macro_braces, clippy::ptr_arg, clippy::too_many_lines, clippy::trivially_copy_pass_by_ref, clippy::type_repetition_in_bounds, // We use lots of declarations inside function bodies to avoid conflicts, // but they aren't used. We just want to make sure they compile. dead_code, )] #![deny(clippy::collection_is_never_read)] use serde::de::{Deserialize, DeserializeOwned, Deserializer}; use serde::ser::{Serialize, Serializer}; use serde_derive::{Deserialize, Serialize}; use std::borrow::Cow; use std::marker::PhantomData; use std::option::Option as StdOption; use std::result::Result as StdResult; // Try to trip up the generated code if it fails to use fully qualified paths. #[allow(dead_code)] struct Result; #[allow(dead_code)] struct Ok; #[allow(dead_code)] struct Err; #[allow(dead_code)] struct Option; #[allow(dead_code)] struct Some; #[allow(dead_code)] struct None; ////////////////////////////////////////////////////////////////////////// #[test] fn test_gen() { #[derive(Serialize, Deserialize)] struct With<T> { t: T, #[serde(serialize_with = "ser_x", deserialize_with = "de_x")] x: X, } assert::<With<i32>>(); #[derive(Serialize, Deserialize)] struct WithTogether<T> { t: T, #[serde(with = "both_x")] x: X, } assert::<WithTogether<i32>>(); #[derive(Serialize, Deserialize)] struct WithRef<'a, T: 'a> { #[serde(skip_deserializing)] t: StdOption<&'a T>, #[serde(serialize_with = "ser_x", deserialize_with = "de_x")] x: X, } assert::<WithRef<i32>>(); #[derive(Serialize, Deserialize)] struct PhantomX { x: PhantomData<X>, } assert::<PhantomX>(); #[derive(Serialize, Deserialize)] struct PhantomT<T> { t: PhantomData<T>, } assert::<PhantomT<X>>(); #[derive(Serialize, Deserialize)] struct NoBounds<T> { t: T, option: StdOption<T>, boxed: Box<T>, option_boxed: StdOption<Box<T>>, } assert::<NoBounds<i32>>(); #[derive(Serialize, Deserialize)] enum EnumWith<T> { Unit, Newtype(#[serde(serialize_with = "ser_x", deserialize_with = "de_x")] X), Tuple( T, #[serde(serialize_with = "ser_x", deserialize_with = "de_x")] X, ), Struct { t: T, #[serde(serialize_with = "ser_x", deserialize_with = "de_x")] x: X, }, } assert::<EnumWith<i32>>(); #[derive(Serialize)] struct MultipleRef<'a, 'b, 'c, T> where T: 'c, 'c: 'b, 'b: 'a, { t: T, rrrt: &'a &'b &'c T, } assert_ser::<MultipleRef<i32>>(); #[derive(Serialize, Deserialize)] struct Newtype(#[serde(serialize_with = "ser_x", deserialize_with = "de_x")] X); assert::<Newtype>(); #[derive(Serialize, Deserialize)] struct Tuple<T>( T, #[serde(serialize_with = "ser_x", deserialize_with = "de_x")] X, ); assert::<Tuple<i32>>(); #[derive(Serialize, Deserialize)] enum TreeNode<D> { Split { left: Box<TreeNode<D>>, right: Box<TreeNode<D>>, }, Leaf { data: D, }, } assert::<TreeNode<i32>>(); #[derive(Serialize, Deserialize)] struct ListNode<D> { data: D, next: Box<ListNode<D>>, } assert::<ListNode<i32>>(); #[derive(Serialize, Deserialize)] struct RecursiveA { b: Box<RecursiveB>, } assert::<RecursiveA>(); #[derive(Serialize, Deserialize)] enum RecursiveB { A(RecursiveA), } assert::<RecursiveB>(); #[derive(Serialize, Deserialize)] struct RecursiveGenericA<T> { t: T, b: Box<RecursiveGenericB<T>>, } assert::<RecursiveGenericA<i32>>(); #[derive(Serialize, Deserialize)] enum RecursiveGenericB<T> { T(T), A(RecursiveGenericA<T>), } assert::<RecursiveGenericB<i32>>(); #[derive(Serialize)] struct OptionStatic<'a> { a: StdOption<&'a str>, b: StdOption<&'static str>, } assert_ser::<OptionStatic>(); #[derive(Serialize, Deserialize)] #[serde(bound = "D: SerializeWith + DeserializeWith")] struct WithTraits1<D, E> { #[serde( serialize_with = "SerializeWith::serialize_with", deserialize_with = "DeserializeWith::deserialize_with" )] d: D, #[serde( serialize_with = "SerializeWith::serialize_with", deserialize_with = "DeserializeWith::deserialize_with", bound = "E: SerializeWith + DeserializeWith" )] e: E, } assert::<WithTraits1<X, X>>(); #[derive(Serialize, Deserialize)] #[serde(bound(serialize = "D: SerializeWith", deserialize = "D: DeserializeWith"))] struct WithTraits2<D, E> { #[serde( serialize_with = "SerializeWith::serialize_with", deserialize_with = "DeserializeWith::deserialize_with" )] d: D, #[serde( serialize_with = "SerializeWith::serialize_with", bound(serialize = "E: SerializeWith") )] #[serde( deserialize_with = "DeserializeWith::deserialize_with", bound(deserialize = "E: DeserializeWith") )] e: E, } assert::<WithTraits2<X, X>>(); #[derive(Serialize, Deserialize)] #[serde(bound = "D: SerializeWith + DeserializeWith")] enum VariantWithTraits1<D, E> { #[serde( serialize_with = "SerializeWith::serialize_with", deserialize_with = "DeserializeWith::deserialize_with" )] D(D), #[serde( serialize_with = "SerializeWith::serialize_with", deserialize_with = "DeserializeWith::deserialize_with", bound = "E: SerializeWith + DeserializeWith" )] E(E), } assert::<VariantWithTraits1<X, X>>(); #[derive(Serialize, Deserialize)] #[serde(bound(serialize = "D: SerializeWith", deserialize = "D: DeserializeWith"))] enum VariantWithTraits2<D, E> { #[serde( serialize_with = "SerializeWith::serialize_with", deserialize_with = "DeserializeWith::deserialize_with" )] D(D), #[serde( serialize_with = "SerializeWith::serialize_with", bound(serialize = "E: SerializeWith") )] #[serde( deserialize_with = "DeserializeWith::deserialize_with", bound(deserialize = "E: DeserializeWith") )] E(E), } assert::<VariantWithTraits2<X, X>>(); type PhantomDataAlias<T> = PhantomData<T>; #[derive(Serialize, Deserialize)] #[serde(bound = "")] struct PhantomDataWrapper<T> { #[serde(default)] field: PhantomDataAlias<T>, } assert::<PhantomDataWrapper<X>>(); #[derive(Serialize, Deserialize)] struct CowStr<'a>(Cow<'a, str>); assert::<CowStr>(); #[derive(Serialize, Deserialize)] #[serde(bound(deserialize = "T::Owned: DeserializeOwned"))] struct CowT<'a, T: ?Sized + 'a + ToOwned>(Cow<'a, T>); assert::<CowT<str>>(); #[derive(Serialize, Deserialize)] struct EmptyStruct {} assert::<EmptyStruct>(); #[derive(Serialize, Deserialize)] enum EmptyEnumVariant { EmptyStruct {}, } assert::<EmptyEnumVariant>(); #[derive(Serialize, Deserialize)] pub struct NonAsciiIdents { σ: f64, } #[derive(Serialize, Deserialize)] pub struct EmptyBraced {} #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct EmptyBracedDenyUnknown {} #[derive(Serialize, Deserialize)] pub struct BracedSkipAll { #[serde(skip_deserializing)] f: u8, } #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct BracedSkipAllDenyUnknown { #[serde(skip_deserializing)] f: u8, } #[derive(Serialize, Deserialize)] pub struct EmptyTuple(); #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct EmptyTupleDenyUnknown(); #[derive(Serialize, Deserialize)] pub struct TupleSkipAll(#[serde(skip_deserializing)] u8); #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct TupleSkipAllDenyUnknown(#[serde(skip_deserializing)] u8); #[derive(Serialize, Deserialize)] pub enum EmptyEnum {} #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub enum EmptyEnumDenyUnknown {} #[derive(Serialize, Deserialize)] pub enum EnumSkipAll { #[serde(skip_deserializing)] #[allow(dead_code)] Variant, } #[derive(Serialize, Deserialize)] pub enum EmptyVariants { Braced {}, Tuple(), BracedSkip { #[serde(skip_deserializing)] f: u8, }, TupleSkip(#[serde(skip_deserializing)] u8), } #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub enum EmptyVariantsDenyUnknown { Braced {}, Tuple(), BracedSkip { #[serde(skip_deserializing)] f: u8, }, TupleSkip(#[serde(skip_deserializing)] u8), } #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct UnitDenyUnknown; #[derive(Serialize, Deserialize)] pub struct EmptyArray { empty: [X; 0], } pub enum Or<A, B> { A(A), B(B), } #[derive(Serialize, Deserialize)] #[serde(untagged, remote = "Or")] pub enum OrDef<A, B> { A(A), B(B), } struct Str<'a>(&'a str); #[derive(Serialize, Deserialize)] #[serde(remote = "Str")] struct StrDef<'a>(&'a str); #[derive(Serialize, Deserialize)] pub struct Remote<'a> { #[serde(with = "OrDef")] or: Or<u8, bool>, #[serde(borrow, with = "StrDef")] s: Str<'a>, } #[derive(Serialize, Deserialize)] pub enum BorrowVariant<'a> { #[serde(borrow, with = "StrDef")] S(Str<'a>), } mod vis { use serde_derive::{Deserialize, Serialize}; pub struct S; #[derive(Serialize, Deserialize)] #[serde(remote = "S")] pub struct SDef; } // This would not work if SDef::serialize / deserialize are private. #[derive(Serialize, Deserialize)] pub struct RemoteVisibility { #[serde(with = "vis::SDef")] s: vis::S, } #[derive(Serialize, Deserialize)] #[serde(remote = "Self")] pub struct RemoteSelf; #[derive(Serialize, Deserialize)] enum ExternallyTaggedVariantWith { #[serde(serialize_with = "ser_x")] #[serde(deserialize_with = "de_x")] #[allow(dead_code)] Newtype(X), #[serde(serialize_with = "serialize_some_other_variant")] #[serde(deserialize_with = "deserialize_some_other_variant")] #[allow(dead_code)] Tuple(String, u8), #[serde(serialize_with = "ser_x")] #[serde(deserialize_with = "de_x")] #[allow(dead_code)] Struct1 { x: X }, #[serde(serialize_with = "serialize_some_other_variant")] #[serde(deserialize_with = "deserialize_some_other_variant")] #[allow(dead_code)] Struct { f1: String, f2: u8 }, #[serde(serialize_with = "serialize_some_unit_variant")] #[serde(deserialize_with = "deserialize_some_unit_variant")] #[allow(dead_code)] Unit, } assert_ser::<ExternallyTaggedVariantWith>(); #[derive(Serialize, Deserialize)] #[serde(tag = "t")] enum InternallyTaggedVariantWith { #[serde(serialize_with = "ser_x")] #[serde(deserialize_with = "de_x")] #[allow(dead_code)] Newtype(X), #[serde(serialize_with = "ser_x")] #[serde(deserialize_with = "de_x")] #[allow(dead_code)] Struct1 { x: X }, #[serde(serialize_with = "serialize_some_other_variant")] #[serde(deserialize_with = "deserialize_some_other_variant")] #[allow(dead_code)] Struct { f1: String, f2: u8 }, #[serde(serialize_with = "serialize_some_unit_variant")] #[serde(deserialize_with = "deserialize_some_unit_variant")] #[allow(dead_code)] Unit, } assert_ser::<InternallyTaggedVariantWith>(); #[derive(Serialize, Deserialize)] #[serde(tag = "t", content = "c")] enum AdjacentlyTaggedVariantWith { #[serde(serialize_with = "ser_x")] #[serde(deserialize_with = "de_x")] #[allow(dead_code)] Newtype(X), #[serde(serialize_with = "serialize_some_other_variant")] #[serde(deserialize_with = "deserialize_some_other_variant")] #[allow(dead_code)] Tuple(String, u8), #[serde(serialize_with = "ser_x")] #[serde(deserialize_with = "de_x")] #[allow(dead_code)] Struct1 { x: X }, #[serde(serialize_with = "serialize_some_other_variant")] #[serde(deserialize_with = "deserialize_some_other_variant")] #[allow(dead_code)] Struct { f1: String, f2: u8 }, #[serde(serialize_with = "serialize_some_unit_variant")] #[serde(deserialize_with = "deserialize_some_unit_variant")] #[allow(dead_code)] Unit, } assert_ser::<AdjacentlyTaggedVariantWith>(); #[derive(Serialize, Deserialize)] #[serde(untagged)] enum UntaggedVariantWith { #[serde(serialize_with = "ser_x")] #[serde(deserialize_with = "de_x")] #[allow(dead_code)] Newtype(X), #[serde(serialize_with = "serialize_some_other_variant")] #[serde(deserialize_with = "deserialize_some_other_variant")] #[allow(dead_code)] Tuple(String, u8), #[serde(serialize_with = "ser_x")] #[serde(deserialize_with = "de_x")] #[allow(dead_code)] Struct1 { x: X }, #[serde(serialize_with = "serialize_some_other_variant")] #[serde(deserialize_with = "deserialize_some_other_variant")] #[allow(dead_code)] Struct { f1: String, f2: u8 }, #[serde(serialize_with = "serialize_some_unit_variant")] #[serde(deserialize_with = "deserialize_some_unit_variant")] #[allow(dead_code)] Unit, } assert_ser::<UntaggedVariantWith>(); #[derive(Serialize, Deserialize)] struct FlattenWith { #[serde(flatten, serialize_with = "ser_x", deserialize_with = "de_x")] x: X, } assert::<FlattenWith>(); #[derive(Serialize, Deserialize)] pub struct Flatten<T> { #[serde(flatten)] t: T, } #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct FlattenDenyUnknown<T> { #[serde(flatten)] t: T, } #[derive(Serialize, Deserialize)] pub struct SkipDeserializing<T> { #[serde(skip_deserializing)] flat: T, } #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct SkipDeserializingDenyUnknown<T> { #[serde(skip_deserializing)] flat: T, } #[derive(Serialize, Deserialize)] pub struct StaticStrStruct<'a> { a: &'a str, b: &'static str, } #[derive(Serialize, Deserialize)] pub struct StaticStrTupleStruct<'a>(&'a str, &'static str); #[derive(Serialize, Deserialize)] pub struct StaticStrNewtypeStruct(&'static str); #[derive(Serialize, Deserialize)] pub enum StaticStrEnum<'a> { Struct { a: &'a str, b: &'static str }, Tuple(&'a str, &'static str), Newtype(&'static str), } #[derive(Serialize, Deserialize)] struct SkippedStaticStr { #[serde(skip_deserializing)] skipped: &'static str, other: isize, } assert::<SkippedStaticStr>(); macro_rules! T { () => { () }; } #[derive(Serialize, Deserialize)] struct TypeMacro<T> { mac: T!(), marker: PhantomData<T>, } assert::<TypeMacro<X>>(); #[derive(Serialize)] struct BigArray { #[serde(serialize_with = "<[_]>::serialize")] array: [u8; 256], } assert_ser::<BigArray>(); trait AssocSerde { type Assoc; } struct NoSerdeImpl; impl AssocSerde for NoSerdeImpl { type Assoc = u32; } #[derive(Serialize, Deserialize)] struct AssocDerive<T: AssocSerde> { assoc: T::Assoc, } assert::<AssocDerive<NoSerdeImpl>>(); #[derive(Serialize, Deserialize)] struct AssocDeriveMulti<S, T: AssocSerde> { s: S, assoc: T::Assoc, } assert::<AssocDeriveMulti<i32, NoSerdeImpl>>(); #[derive(Serialize)] #[serde(tag = "t", content = "c")] enum EmptyAdjacentlyTagged { #[allow(dead_code)] Struct {}, #[allow(dead_code)] Tuple(), } assert_ser::<EmptyAdjacentlyTagged>(); mod restricted { mod inner { use serde_derive::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] #[allow(dead_code)] struct Restricted { pub(super) a: usize, pub(in super::inner) b: usize, } } } #[derive(Deserialize)] #[serde(tag = "t", content = "c")] pub enum AdjacentlyTaggedVoid {} #[derive(Serialize, Deserialize)] enum SkippedVariant<T> { #[serde(skip)] #[allow(dead_code)] T(T), Unit, } assert::<SkippedVariant<X>>(); #[derive(Deserialize)] pub struct ImplicitlyBorrowedOption<'a> { option: std::option::Option<&'a str>, } #[derive(Serialize, Deserialize)] #[serde(untagged)] #[allow(dead_code)] pub enum UntaggedNewtypeVariantWith { Newtype( #[serde(serialize_with = "ser_x")] #[serde(deserialize_with = "de_x")] X, ), } #[derive(Serialize, Deserialize)] #[serde(transparent)] #[allow(dead_code)] pub struct TransparentWith { #[serde(serialize_with = "ser_x")] #[serde(deserialize_with = "de_x")] x: X, } #[derive(Deserialize)] #[serde(untagged)] #[allow(dead_code)] pub enum UntaggedWithBorrow<'a> { Single( #[serde(borrow)] #[allow(dead_code)] RelObject<'a>, ), Many( #[serde(borrow)] #[allow(dead_code)] Vec<RelObject<'a>>, ), } #[derive(Deserialize)] pub struct RelObject<'a> { ty: &'a str, id: String, } #[derive(Serialize, Deserialize)] pub struct FlattenSkipSerializing<T> { #[serde(flatten, skip_serializing)] #[allow(dead_code)] flat: T, } #[derive(Serialize, Deserialize)] pub struct FlattenSkipSerializingIf<T> { #[serde(flatten, skip_serializing_if = "StdOption::is_none")] flat: StdOption<T>, } #[derive(Serialize, Deserialize)] pub struct FlattenSkipDeserializing<T> { #[serde(flatten, skip_deserializing)] flat: T, } #[derive(Serialize, Deserialize)] #[serde(untagged)] pub enum Inner<T> { Builder { s: T, #[serde(flatten)] o: T, }, Default { s: T, }, } // https://github.com/serde-rs/serde/issues/1804 #[derive(Serialize, Deserialize)] pub enum Message { #[serde(skip)] #[allow(dead_code)] String(String), #[serde(other)] Unknown, } #[derive(Serialize)] #[repr(C, packed)] #[allow(dead_code)] struct Packed { x: u8, y: u16, } macro_rules! deriving { ($field:ty) => { #[derive(Deserialize)] pub struct MacroRules<'a> { field: $field, } }; } deriving!(&'a str); macro_rules! mac { ($($tt:tt)*) => { $($tt)* }; } #[derive(Deserialize)] pub struct BorrowLifetimeInsideMacro<'a> { #[serde(borrow = "'a")] pub f: mac!(Cow<'a, str>), } #[derive(Serialize)] pub struct Struct { #[serde(serialize_with = "vec_first_element")] pub vec: Vec<Self>, } assert_ser::<Struct>(); #[derive(Deserialize)] #[serde(bound(deserialize = "[&'de str; N]: Copy"))] pub struct GenericUnitStruct<const N: usize>; } ////////////////////////////////////////////////////////////////////////// fn assert<T: Serialize + DeserializeOwned>() {} fn assert_ser<T: Serialize>() {} trait SerializeWith { fn serialize_with<S: Serializer>(_: &Self, _: S) -> StdResult<S::Ok, S::Error>; } trait DeserializeWith: Sized { fn deserialize_with<'de, D: Deserializer<'de>>(_: D) -> StdResult<Self, D::Error>; } // Implements neither Serialize nor Deserialize pub struct X; pub fn ser_x<S: Serializer>(_: &X, _: S) -> StdResult<S::Ok, S::Error> { unimplemented!() } pub fn de_x<'de, D: Deserializer<'de>>(_: D) -> StdResult<X, D::Error> { unimplemented!() } mod both_x { pub use super::{de_x as deserialize, ser_x as serialize}; } impl SerializeWith for X { fn serialize_with<S: Serializer>(_: &Self, _: S) -> StdResult<S::Ok, S::Error> { unimplemented!() } } impl DeserializeWith for X { fn deserialize_with<'de, D: Deserializer<'de>>(_: D) -> StdResult<Self, D::Error> { unimplemented!() } } pub fn serialize_some_unit_variant<S>(_: S) -> StdResult<S::Ok, S::Error> where S: Serializer, { unimplemented!() } pub fn deserialize_some_unit_variant<'de, D>(_: D) -> StdResult<(), D::Error> where D: Deserializer<'de>, { unimplemented!() } pub fn serialize_some_other_variant<S>(_: &str, _: &u8, _: S) -> StdResult<S::Ok, S::Error> where S: Serializer, { unimplemented!() } pub fn deserialize_some_other_variant<'de, D>(_: D) -> StdResult<(String, u8), D::Error> where D: Deserializer<'de>, { unimplemented!() } pub fn is_zero(n: &u8) -> bool { *n == 0 } fn vec_first_element<T, S>(vec: &[T], serializer: S) -> StdResult<S::Ok, S::Error> where T: Serialize, S: Serializer, { vec.first().serialize(serializer) } ////////////////////////////////////////////////////////////////////////// #[derive(Debug, PartialEq, Deserialize)] #[serde(tag = "tag")] pub enum InternallyTagged { #[serde(deserialize_with = "deserialize_generic")] Unit, #[serde(deserialize_with = "deserialize_generic")] Newtype(i32), #[serde(deserialize_with = "deserialize_generic")] Struct { f1: String, f2: u8 }, } fn deserialize_generic<'de, T, D>(deserializer: D) -> StdResult<T, D::Error> where T: Deserialize<'de>, D: Deserializer<'de>, { T::deserialize(deserializer) } ////////////////////////////////////////////////////////////////////////// #[repr(C, packed)] pub struct RemotePacked { pub a: u16, pub b: u32, } #[derive(Serialize)] #[repr(C, packed)] #[serde(remote = "RemotePacked")] pub struct RemotePackedDef { a: u16, b: u32, } impl Drop for RemotePackedDef { fn drop(&mut self) {} } #[repr(C, packed)] pub struct RemotePackedNonCopy { pub a: u16, pub b: String, } #[derive(Deserialize)] #[repr(C, packed)] #[serde(remote = "RemotePackedNonCopy")] pub struct RemotePackedNonCopyDef { a: u16, b: String, } impl Drop for RemotePackedNonCopyDef { fn drop(&mut self) {} }
rust
github
https://github.com/serde-rs/serde
test_suite/tests/test_gen.rs
/* * LibXDiff by Davide Libenzi ( File Differential Library ) * Copyright (C) 2003 Davide Libenzi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/>. * * Davide Libenzi <davidel@xmailserver.org> * */ #if !defined(XPREPARE_H) #define XPREPARE_H int xdl_prepare_env(mmfile_t *mf1, mmfile_t *mf2, xpparam_t const *xpp, xdfenv_t *xe); void xdl_free_env(xdfenv_t *xe); #endif /* #if !defined(XPREPARE_H) */
c
github
https://github.com/git/git
xdiff/xprepare.h
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # qutebrowser is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see <http://www.gnu.org/licenses/>. """Utilities related to QWebHistory.""" from PyQt5.QtCore import QByteArray, QDataStream, QIODevice, QUrl from qutebrowser.utils import qtutils def _encode_url(url): """Encode a QUrl suitable to pass to QWebHistory.""" data = bytes(QUrl.toPercentEncoding(url.toString(), b':/#?&+=@%*')) return data.decode('ascii') def _serialize_ng(items, current_idx, stream): # {'currentItemIndex': 0, # 'history': [{'children': [], # 'documentSequenceNumber': 1485030525573123, # 'documentState': [], # 'formContentType': '', # 'itemSequenceNumber': 1485030525573122, # 'originalURLString': 'about:blank', # 'pageScaleFactor': 0.0, # 'referrer': '', # 'scrollPosition': {'x': 0, 'y': 0}, # 'target': '', # 'title': '', # 'urlString': 'about:blank'}]} data = {'currentItemIndex': current_idx, 'history': []} for item in items: data['history'].append(_serialize_item_ng(item)) stream.writeInt(3) # history stream version stream.writeQVariantMap(data) def _serialize_item_ng(item): data = { 'originalURLString': item.original_url.toString(QUrl.FullyEncoded), 'scrollPosition': {'x': 0, 'y': 0}, 'title': item.title, 'urlString': item.url.toString(QUrl.FullyEncoded), } try: data['scrollPosition']['x'] = item.user_data['scroll-pos'].x() data['scrollPosition']['y'] = item.user_data['scroll-pos'].y() except (KeyError, TypeError): pass return data def _serialize_old(items, current_idx, stream): ### Source/WebKit/qt/Api/qwebhistory.cpp operator<< stream.writeInt(2) # history stream version stream.writeInt(len(items)) stream.writeInt(current_idx) for i, item in enumerate(items): _serialize_item_old(i, item, stream) def _serialize_item_old(i, item, stream): """Serialize a single WebHistoryItem into a QDataStream. Args: i: The index of the current item. item: The WebHistoryItem to write. stream: The QDataStream to write to. """ ### Source/WebCore/history/qt/HistoryItemQt.cpp restoreState ## urlString stream.writeQString(_encode_url(item.url)) ## title stream.writeQString(item.title) ## originalURLString stream.writeQString(_encode_url(item.original_url)) ### Source/WebCore/history/HistoryItem.cpp decodeBackForwardTree ## backForwardTreeEncodingVersion stream.writeUInt32(2) ## size (recursion stack) stream.writeUInt64(0) ## node->m_documentSequenceNumber # If two HistoryItems have the same document sequence number, then they # refer to the same instance of a document. Traversing history from one # such HistoryItem to another preserves the document. stream.writeInt64(i + 1) ## size (node->m_documentState) stream.writeUInt64(0) ## node->m_formContentType # info used to repost form data stream.writeQString(None) ## hasFormData stream.writeBool(False) ## node->m_itemSequenceNumber # If two HistoryItems have the same item sequence number, then they are # clones of one another. Traversing history from one such HistoryItem to # another is a no-op. HistoryItem clones are created for parent and # sibling frames when only a subframe navigates. stream.writeInt64(i + 1) ## node->m_referrer stream.writeQString(None) ## node->m_scrollPoint (x) try: stream.writeInt32(item.user_data['scroll-pos'].x()) except (KeyError, TypeError): stream.writeInt32(0) ## node->m_scrollPoint (y) try: stream.writeInt32(item.user_data['scroll-pos'].y()) except (KeyError, TypeError): stream.writeInt32(0) ## node->m_pageScaleFactor stream.writeFloat(1) ## hasStateObject # Support for HTML5 History stream.writeBool(False) ## node->m_target stream.writeQString(None) ### Source/WebCore/history/qt/HistoryItemQt.cpp restoreState ## validUserData # We could restore the user data here, but we prefer to use the # QWebHistoryItem API for that. stream.writeBool(False) def serialize(items): """Serialize a list of QWebHistoryItems to a data stream. Args: items: An iterable of WebHistoryItems. Return: A (stream, data, user_data) tuple. stream: The reset QDataStream. data: The QByteArray with the raw data. user_data: A list with each item's user data. Warning: If 'data' goes out of scope, reading from 'stream' will result in a segfault! """ data = QByteArray() stream = QDataStream(data, QIODevice.ReadWrite) user_data = [] current_idx = None for i, item in enumerate(items): if item.active: if current_idx is not None: raise ValueError("Multiple active items ({} and {}) " "found!".format(current_idx, i)) else: current_idx = i if items: if current_idx is None: raise ValueError("No active item found!") else: current_idx = 0 if qtutils.is_qtwebkit_ng(): _serialize_ng(items, current_idx, stream) else: _serialize_old(items, current_idx, stream) user_data += [item.user_data for item in items] stream.device().reset() qtutils.check_qdatastream(stream) return stream, data, user_data
unknown
codeparrot/codeparrot-clean
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal from ..._models import BaseModel __all__ = ["ResponseAudioDoneEvent"] class ResponseAudioDoneEvent(BaseModel): """Returned when the model-generated audio is done. Also emitted when a Response is interrupted, incomplete, or cancelled. """ content_index: int """The index of the content part in the item's content array.""" event_id: str """The unique ID of the server event.""" item_id: str """The ID of the item.""" output_index: int """The index of the output item in the response.""" response_id: str """The ID of the response.""" type: Literal["response.output_audio.done"] """The event type, must be `response.output_audio.done`."""
python
github
https://github.com/openai/openai-python
src/openai/types/realtime/response_audio_done_event.py
//// [tests/cases/conformance/constEnums/constEnum4.ts] //// //// [constEnum4.ts] if (1) const enum A { } else if (2) const enum B { } else const enum C { } //// [constEnum4.js] "use strict"; if (1) ; else if (2) ; else ;
javascript
github
https://github.com/microsoft/TypeScript
tests/baselines/reference/constEnum4.js
#!/usr/bin/env python3 import unittest from test import support import smtplib ssl = support.import_module("ssl") support.requires("network") class SmtpTest(unittest.TestCase): testServer = 'smtp.gmail.com' remotePort = 25 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) def test_connect_starttls(self): support.get_attribute(smtplib, 'SMTP_SSL') with support.transient_internet(self.testServer): server = smtplib.SMTP(self.testServer, self.remotePort) try: server.starttls(context=self.context) except smtplib.SMTPException as e: if e.args[0] == 'STARTTLS extension not supported by server.': unittest.skip(e.args[0]) else: raise server.ehlo() server.quit() class SmtpSSLTest(unittest.TestCase): testServer = 'smtp.gmail.com' remotePort = 465 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) def test_connect(self): support.get_attribute(smtplib, 'SMTP_SSL') with support.transient_internet(self.testServer): server = smtplib.SMTP_SSL(self.testServer, self.remotePort) server.ehlo() server.quit() def test_connect_default_port(self): support.get_attribute(smtplib, 'SMTP_SSL') with support.transient_internet(self.testServer): server = smtplib.SMTP_SSL(self.testServer) server.ehlo() server.quit() def test_connect_using_sslcontext(self): support.get_attribute(smtplib, 'SMTP_SSL') with support.transient_internet(self.testServer): server = smtplib.SMTP_SSL(self.testServer, self.remotePort, context=self.context) server.ehlo() server.quit() def test_main(): support.run_unittest(SmtpTest, SmtpSSLTest) if __name__ == "__main__": test_main()
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python ############################################################################### # # # compare.py # # # # Makes comparisons between ScaffoldM and SSPACE for improvement # # # # Copyright (C) Alexander Baker # # # ############################################################################### # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### __author__ = "Alexander Baker" __copyright__ = "Copyright 2015" __credits__ = ["Alexander Baker"] __license__ = "GPLv3" __maintainer__ = "Alexander Baker" __email__ = "Alexander.baker@uqconnect.edu.au" ############################################################################### ############################################################################### ############################################################################### import os import argparse #from dataloader import DataLoader #from dataparser import DataParser #from scaffold import Scaffold import matplotlib.pyplot as plt import numpy as np import scipy as sp ############################################################################### #First step - parse input to make library file for sspace_basic #Library name readsfile1 readsfile2 insert size tolerated error, read orientation #of form Lib1 file.1.1.fasta file.1.2.fasta 400 0.25 FR # the above indicates that library 1 has first set of reads in file1.1.1 and second set of pair #in file.1.2 and insert size of 400 and is willing to tolerate a 25% error (100), and reads #map F(------>)R(<---------) onto the contigs. def makelibrary(filename,libnames,pairedend1, pairedend2, insertsize,error,orientation,tab=False): import os import sys if not os.path.isfile(filename): scaffile=open(filename+".txt",'w') scaffile.close() with open(filename+".txt",'a+') as library: for i,libname in enumerate(libnames): if tab==False: library.write("{0} bwa {1} {2} {3} {4} {5}\n".\ format(libname,pairedend1[i]+".fasta", pairedend2[i]+".fasta",\ insertsize[i],error[i],orientation[i])) else: library.write("{0} TAB {1} {2} {3} {4}\n".\ format(libname,TABfile+".tab",\ insertsize[i],error[i],orientation[i])) def splitter(interleavedreads): import sys try: with open(interleavedreads+".fna",'r') as reads: head=reads.readline() if not head.startswith('>'): raise TypeError("Not a FASTA file:") reads.seek(0) firstreads=[] secondreads=[] firstread=False secondread=False for line in reads: if line.startswith('>'): firstread=False secondread=False if ".1" in line: firstread=True elif ".2" in line: secondread=True if firstread: firstreads.append(line) elif secondread: secondreads.append(line) elif not line.startswith('>'): if firstread: firstreads.append(line) elif secondread: secondreads.append(line) read1=''.join(firstreads) read2=''.join(secondreads) with open(interleavedreads+"_1.fasta",'a+') as reads: reads.write(read1) with open(interleavedreads+"_2.fasta",'a+') as reads: reads.write(read2) return interleavedreads+"_1",interleavedreads+"_2" except: print "Error opening file:", interleavedreads, sys.exc_info()[0] raise def chunker(string,chunksize,end): ''' Creates chunks from string and appends an end term Note this return generator - should be iterated over''' try: stringmod=string.translate(None,end) for i in xrange(0,len(stringmod),chunksize): if len(stringmod)>=i+chunksize: yield stringmod[i:i+chunksize]+end else: yield stringmod[i:i+chunksize] except TypeError: print "end must be concatenable to string, \ intended use is type(str) for both" def getfastalen(fastaname): try: with open(fastaname+".fasta",'r+') as fasta: fasta.readline() linelen=len(fasta.readline().strip('\n')) fasta.seek(0) for i, l in enumerate(fasta): pass return (i)*linelen #lose 1 due to header_assuming one header for this type except IOError: with open(fastaname,'r+') as fasta: fasta.readline() linelen=len(fasta.readline().strip('\n')) fasta.seek(0) for i, l in enumerate(fasta): pass return (i)*linelen #lose 1 due to header_assuming one header for this type def slicer(slices,filename): ''' slices are of form start, end, reps, orientation. This function will take those slices out of a specified fasta file and then print them as contigs''' import os import sys slices=[int(ele) for ele in slices] #print slices try: with open(filename,'r+') as Genome: linelen=len(Genome.readlines()[3].strip("\n")) start=min([slices[i] for i in range(len(slices)) if i%4==0]) ends=max(slices) #assumes no reps or orientation greater than max contig position - reasonable seqslice=[] Genome.seek(0) header=Genome.readline().strip('>').rstrip('\n') refhead=header[0:min(24,len(header))] sequence=''.join([line.translate(None,"\n") for line in Genome.readlines() if not line.startswith('>')]) for i in range(0,len(slices),4): if int(slices[i+3])==-1: seqslice.append(reversecompliment(sequence[int(slices[i]):int(slices[i+1])]*int(slices[i+2]))) elif int(slices[i+3])==1: seqslice.append(sequence[int(slices[i]):int(slices[i+1])]*int(slices[i+2])) except IOError: #If not openable try for file in folder one level up with open('..'+os.sep+filename,'r+') as Genome: linelen=len(Genome.readlines()[3].strip("\n")) start=min([slices[i] for i in range(len(slices)) if i%4==0]) ends=max(slices) #assumes no reps or orientation greater than max contig position - reasonable seqslice=[] Genome.seek(0) header=Genome.readline().strip('>').rstrip('\n') refhead=header[0:min(24,len(header))] sequence=''.join([line.translate(None,"\n") for line in Genome.readlines() if not line.startswith('>')]) for i in range(0,len(slices),4): seqslice.append(sequence[int(slices[i]):int(slices[i+1])][::int(slices[i+2])]*int(slices[i+3])) parts=filename.split(os.sep) fileend=parts[-1].split(".fasta")[0] slicefilename=fileend+"slices.fna" completefilename="{0}S:{1}_E:{2}".format(fileend,start,ends)+"complete.fna" if not os.path.isfile(slicefilename): tigfile=open(slicefilename,'w') tigfile=tigfile.close() if not os.path.isfile(completefilename): tigfile=open(completefilename,'w') tigfile=tigfile.close() with open(slicefilename,'a+') as tigfile: for i,seq in enumerate(seqslice): tigname=refhead+"contig"+str(i+1)+"|"+header[int(min(24,len(header))):] tigfile.write(">{0}, S:{1}:E:{2}:R:{3}:OR:{4}\n".format(tigname,slices[i*4],slices[i*4+1],slices[i*4+3],slices[i*4+2])) for chunk in chunker(seq,linelen,"\n"): tigfile.write(chunk) tigfile.write('\n') with open(completefilename,'a+') as tigfile: tigname=refhead+"complete|"+header[min(24,len(header)):] tigfile.write(">{0}, S:{1}:E:{2}\n".format(tigname,start,ends)) for chunk in chunker(sequence[start:ends],linelen,"\n"): tigfile.write(chunk) tigfile.write('\n') return slicefilename,completefilename def reversecompliment(seq): compliment={'A':'T','G':'C','T':'A','C':'G','a':'t','g':'c','t':'a','c':'g'} try: newseq="".join([compliment[char] for char in reversed(seq)]) return newseq except: print "This sequence has illegal characters" raise def randcuts(gap,seqlen,noslices=10,rep=False,ori=False,steps=100,gapvar=False,randgaps=True): import random starts=[] ends=[] orientation=[] reps=[] m=[1]*90+10*[-1] replist=[1,2,3,4] starts.append(random.randint(0,seqlen/4)) upperlen=(seqlen-starts[0])//noslices for i in range(noslices): ends.append(random.randint(starts[i]+steps,starts[i]+upperlen+steps)) if i!=(noslices-1): if randgaps: starts.append(ends[i]+int(random.gauss(gap,gap/5))) else: starts.append(ends[i]+gap) if ori: orientation.append(random.sample(m,1)[0]) else: orientation.append(1) if rep: reps.append(random.sample(replist,1)[0]) else: reps.append(1) weave=zip(starts,ends,reps,orientation) return [int(zipdat) for zipped in weave for zipdat in zipped] def makereads(readnumber,readlength,\ meaninsert,stdinsert,filename,readmaker="metasim"): if readmaker=="metasim": statoscom=("/home/baker/Packages/metasim/MetaSim cmd -r {0} -m \ -g /home/baker/Packages/metasim/examples/errormodel-100bp.mconf \ -2 /home/baker/Packages/metasim/examples/errormodel-100bp.mconf \ --empirical-pe-probability {1} --clones-mean {2} --clones-param2 {3} \ {4}").format(readnumber,readlength,meaninsert,stdinsert,\ filename) elif readmaker=="gemsim": pass os.system(statoscom) def makereadswrap(readnumber,readlength,\ meaninsert,stdinsert,filename,readmaker="metasim"): makereads(readnumber,readlength,\ meaninsert,stdinsert,filename,readmaker="metasim") if readmaker=='metasim': readname=filename.split(".fna")[0]+"-Empirical.fna" print "This is the read name", readname setreads(readname) def setreads(filename,clean=True): import os tempname=filename.split(".fna")[0]+"redone.fna" print tempname, "This is the temporary name" os.rename(filename,tempname) #Make a new file for writing output with open(filename,'w') as make: pass with open(tempname) as reads: seq=[] Ind=False with open(filename,'a+') as oldfile: for line in reads: if line.startswith('>'): Ind=False if seq!=[]: oldfile.write("".join(seq)+"\n") if clean: oldfile.write(line.split(" ")[0]+"\n") else: oldfile.write(line) seq=[] else: seq.append(line.translate(None,'\n')) oldfile.write("".join(seq)+"\n") seq=[] os.remove(tempname) return def makesummary(cuts): ''' Takes the cuts used for genome slicing and makes a summary file detailing changes''' return def scaffoldparse(scaffoldloc,scaffoldloc2,truegaps,trueorientations): '''Given two scaffold locations of predefined structure extract information from it and compare''' return def Falsejoins(type1errors): with open("ScafMFalseJoins.fasta",'a+') as Joins: Joins.write("Mistake1,Mistake2\n") for tup in type1errors: ind=False for tig in tup: if ind==False: Joins.write(str(tig)+",") elif ind: Joins.write(str(tig)+"\n") ind=True def trackdecisions(Truepos,Falsepos,falseneg,notigs=False,N_joins=False): import os if not os.path.isfile("../Results.txt"): with open("../Results.txt",'w') as data: data.write("{0},{1},{2}\n".format("TruePositive","FalsePositive","FalseNegative")) with open("../Results.txt",'a+') as data: data.write("{0},{1},{2}\n".format(len(Truepos),len(Falsepos),len(falseneg))) return def Visualise(scaffoldnames,gaps,contigloc,covplot=False): import matplotlib.pyplot as plt import numpy as np import scipy as sp import pandas as pd scaffoldMgap,scaffoldMTjoins,scaffoldMFjoins,scaffoldMFNeg=validcheck(contigloc=contigloc) data={} Falsejoins(scaffoldMFjoins) trackdecisions(scaffoldMTjoins,scaffoldMFjoins,scaffoldMFNeg) sortMgap=sorted(scaffoldMgap,key=lambda x: min(x[0])) pairs=[(min(x[0])-1,x[1]) for x in sortMgap] minscafind,gap2=zip(*pairs) pairedgaps=[gap for i,gap in enumerate(gaps) if i in minscafind] for scaffold in scaffoldnames: data[scaffold]=[contiglen(scaffold)] data[scaffold]+=[[NXcalc(X*0.1,data[scaffold][0]) for X in range(1,11)]] data[scaffold]+=[[len(data[scaffold])-1]] #print data standardplot(gap2,pairedgaps,"The predicted gapsize(nt)","The actual gapsize(nt)","","ScaffoldMVTrueGap") multiplot([[X*0.1 for X in range(1,11)] for i in range(0,len(scaffoldnames))],[data[scaffold][-2] \ for scaffold in scaffoldnames],"X","NX Value for the scaffold",\ "The NX metric for various scaffolds", ["Contigs","ScaffoldM","SSPACE"],"N50Metric_Scaffolds") if covplot: for scaffold in scaffoldnames: plotcoverage(scaffold) return def contigmap(evidencefile,coveragefile='covs.tsv'): Scaffolds={} with open(evidencefile,'r+') as SSPACE: for line in SSPACE: if line.startswith(">"): parts=line.split('|') scaffold=parts[0].strip('>') Scaffolds[scaffold]=[] else: parts=line.split('|')[0] #tig name - in form f_tign if parts!='\n': if parts.startswith('r'): parts='f'+parts[1:] Scaffolds[scaffold]+=[parts] with open(coveragefile,'r+') as covs: covs.readline() #Move paste header orderedtigs=[] for line in covs: orderedtigs.append(line.split('\t')[0]) #Contig name N_tigs=len(orderedtigs) #Number of contigs #map f_tigi to orderedtigs[i] in dictionary Swapdict={"{0}{1}".format('f_tig',i):orderedtigs[i-1] for i in range(1,N_tigs+1)} Mapped={scaffold:[Swapdict[contig] for contig in contigs] for scaffold,contigs in Scaffolds.iteritems()} print Mapped return Mapped def scaffoldtoedges(mapped): SS_data=np.zeros((1,3)) for i,(scaffold,contigs) in enumerate(mapped.iteritems()): for j,contig in enumerate(contigs): if j<len(contigs)-1: SS_data=np.vstack((SS_data,np.array([contig,'(0,1)',contigs[j+1]]))) SS_data=SS_data[1:,:] #Remove initial dummy row np.savetxt('SSPACE_Edges.txt',SS_data,fmt='%s',delimiter='\t',newline='\n', header='Edge1\trel\tEdge2\n') return SS_data def graphtosif(graph,graphname,removed=False): #print graphname, "This is the supposed graph being parsed" #print "\n",graph done=set([]) with tryopen("{0}{1}".format(graphname,"_links"),"Contig1\tRelationship\tContig2\n",".txt",True) as network2: for contig1,connected in graph.iteritems(): for contig2 in connected: if (contig1,contig2) not in done and (contig2,contig1) not in done: network2.write("{0}\t{1}\t{3}\n".format()) done|=set([(contig1,contig2)]) #Add current pair done|=set([(contig1,contig2)[::-1]]) #Reverse of current pair with tryopen("{0}{1}".format(graphname,"_contigs"),"Contig\n",".txt") as contigs: for contig in graph: contigs.write("{0}".format(contig)) return def addcol(filename,column_s,header,d='\t'): '''Takes a text file containing tab separated columns and adds tab-separated columns to the end. This is primarily for updating the .txt files using in Cytoscape with additional info such as bin allocation etc. Loads whole file into memory.''' with tryopen(filename,'','') as oldfile: olf=oldfile.readlines() Newfile=[] for i,line in enumerate(olf): if i==0: processedline=[x.rstrip('\n') for x in line.split('\t')] processedline+=[head for head in header] processedline[-1]=processedline[-1]+"\n" Newfile+=processedline else: processedline=[x.rstrip('\n') for x in line.split('\t')] processedline+=[column[i] for column in column_s] processedline[-1]=processedline[-1]+"\n" #Add endline Newfile+=processedline with tryopen(filename,'','',True) as newfile: for line in Newfile: newfile.write(("{0}".format(d)).join(line)) return def sspaceconvert(evidencefile,coveragefile='covs.tsv'): Mapped=scaffoldtoedges(contigmap(evidencefile,coveragefile='covs.tsv')) return Mapped def plotcoverage(name): return #Simply comparison - one scaffolder and preprocessed dataset def standardplot(x,y,xname,yname,title,saveloc,log=False): import matplotlib.pyplot as plt plt.gca().set_color_cycle(['blue', 'black']) plt.plot(x,y,'o') plt.plot(y,y,'-') plt.xlabel(xname) plt.ylabel(yname) plt.title(title) plt.savefig('./graphs/'+saveloc+'.png',bbox_inches='tight') plt.close() return #More complicated comparisions - Likely between multiple scaffolders def multiplot(x,y,xname,yname,title,legend,saveloc,log=False): '''For plotting lists of lists for x and y, along with an appropiate legend''' import matplotlib.pyplot as plt plt.gca().set_color_cycle(['red', 'blue', 'black']) print x, "This is the x variable" print y, "This is the y variable" for i,xdat in enumerate(x): plt.plot(x[i],y[i]) plt.xlabel(xname) plt.ylabel(yname) plt.title(title) plt.xticks([0.1*X for X in range(0,11)]) plt.axis([min(xv for xval in x for xv in xval),max(xv for xval in x for xv in xval),0,1.05*max(yv for yval in y for yv in yval)]) leg=plt.legend(legend, loc='upper right',title='Scaffolder') leg.get_frame().set_alpha(0) plt.savefig('./graphs/'+saveloc+'.png',bbox_inches='tight') plt.close() def multibar(x,y,xlab,ylab,title,saveloc,legend): #Sourced from :http://matplotlib.org/examples/api/barchart_demo.html #To be modified heavily later import numpy as np import matplotlib.pyplot as plt N = 5 menMeans = (20, 35, 30, 35, 27) menStd = (2, 3, 4, 1, 2) ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd) womenMeans = (25, 32, 34, 20, 25) womenStd = (3, 5, 2, 3, 3) rects2 = ax.bar(ind+width, womenMeans, width, color='y', yerr=womenStd) # add some text for labels, title and axes ticks ax.set_ylabel('Scores') ax.set_title('Scores by group and gender') ax.set_xticks(ind+width) ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') ) ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') ) def autolabel(rects): # attach some text labels for rect in rects: height = rect.get_height() ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height), ha='center', va='bottom') autolabel(rects1) autolabel(rects2) plt.show() def validcheck(gapdataloc="Gapdata.txt",contigloc='MG1655refslices.fna'): '''Uses Gapdata.txt to compare observed scaffolds to known scaffold''' validgaps=[] truejoins=[] falsejoins=[] falsenegs=[] truepairs=[(i,i+1) for i in range(1,len(contiglen(contigloc)))] with open(gapdataloc) as gaps: gaps.readline() #Move past header for line in gaps: compsplit=line.split(",") tig1=compsplit[0].rstrip("|").split("|")[-1] tig2=compsplit[1].rstrip("|").split("|")[-1] #print compsplit[-1] gap=int(compsplit[-1]) tig1ind=int(tig1.split('g')[-1]) tig2ind=int(tig2.split('g')[-1]) if abs(tig1ind-tig2ind)==1: validgaps.append(((tig1ind,tig2ind),gap)) truejoins.append((tig1,tig2)) else: falsejoins.append((tig1,tig2)) print "THESE ARE THE FALSENEGATIVES" falsenegs=[x for x in truepairs if x not in zip(*validgaps)[0]] print falsenegs, "The Reject|True" return [validgaps,truejoins,falsejoins,falsenegs] def NXcalc(X,tiglengths): tot=sum(tiglengths) S_tig=sorted(tiglengths) N50=0 runtot=0 if X==0: return S_tig[-1] for i in range(len(S_tig)): N50=S_tig[-(i+1)] runtot+=N50 if runtot>tot*X: return N50 def parsetsv(filename='links.tsv',delim=',',header=False): parsed=[] with open(filename) as tsv: if header==False: tsv.readline() for line in tsv: parsed.append(line.split(delim)) return parsed def getlinks(contig1,contig2,filename='links.tsv'): links=parsetsv(filename,delim='\t') flags=[] for link in links[1:]: tig1=0 tig2=0 for col in link: #Need to change for simple contig names since I stripped the full name earlier if contig1 in col: tig1=1 if contig2 in col: tig2=1 if tig1+tig2==2: flags.append(link) #print flags return flags def linkdist(onelink): '''distance from relevant edge for each contig in the link''' orientation1=int(onelink[4]) orientation2=int(onelink[7]) if orientation1==1: dist1=int(onelink[3]) else: dist1=int(onelink[2])-int(onelink[3]) if orientation2==1: dist2=int(onelink[6]) else: dist2=int(onelink[5])-int(onelink[6]) #Returns tuple of distances and contig names return ((dist1,onelink[0]),(dist2,onelink[1])) def extracttigs(filename='ScafMFalseJoins.fasta',outfile='mislinkseq.fasta',contigloc='MG1655refslices.fna'): missjoins=parsetsv(filename,delim=',',header=False) missjoins=[[y.rstrip('\n') for y in x] for x in missjoins] print "THe faulty contig pair",missjoins print "You are right before the loop" for line in missjoins: #print line #print line[0], tigs=getlinks(line[0],line[1]) #Extract missjoins #print "This is the links",tigs orientation=(tigs[0][4],tigs[0][7]) #Assuming only one orientation present - risky #print "This is the orientation",orientation #Fix this assumption later dists=[linkdist(x) for x in tigs] #Get links distances #print "This is the distance",dists #Works with assumption that joins are always in same order - they are maximum=[max(x) for x in zip(*dists)] #Unzips tuple into list for each contig #print "This is the maximum",maximum #GEts maximum distance from edge W_faultylink(maximum[0][0],maximum[1][0],maximum[0][1],maximum[1][1],orientation,outfile,contigloc) def W_faultylink(distance1,distance2,contig1,contig2,orientation,filename='mislinkseq.fasta',contigloc='MG1655refslices.fna'): import os import sys print "Did I make it this far" try: if not os.path.isfile("../{0}".format(filename)): with open("../{0}".format(filename),'w') as test: pass with open("../{0}".format(filename),'a+') as mislink: mislink.write(">{0}|Distance:{1}bp_from_edge\n".format(contig1,distance1)) for chunk in chunker(cut(extractcontigs(contig1,contigloc,header=False).translate(None,'\n'),distance1,orientation,0),70,'\n'): mislink.write(chunk) mislink.write('\n') mislink.write(">{0}|Distance:{1}bp_from_edge\n".format(contig2,distance2)) for chunk in chunker(cut(extractcontigs(contig2,contigloc,header=False).translate(None,'\n'),distance2,orientation,1),70,'\n'): mislink.write(chunk) mislink.write('\n') except: print "Errors opening file or running stuff" raise ValueError def cut(seq,slicesize,orientation,tigpairno): or1=int(orientation[0]) or2=int(orientation[1]) if tigpairno==0: if or1==1: return seq[:slicesize] else: return seq[-slicesize:] elif tigpairno==1: if or2==1: return seq[:slicesize] else: return seq[-slicesize:] def extractcontigs(contigname,contigloc,header=True): '''Just assigns contigs file via contigloc. Temporary just for use when making scaffold Will extract the text for that contig''' import sys try: with open(contigloc,'r') as Contigs: head=Contigs.readline() if not head.startswith('>'): raise TypeError("Not a FASTA file:") Contigs.seek(0) title=head[1:].rstrip() ##Strips whitespace and > record=0 contigseq=[] for line in Contigs: if line.startswith('>') and line.find(contigname)>=0: record=1 if header: contigseq.append(line) elif line.startswith('>') and contigname not in line: record=0 elif record==1: contigseq.append(line) else: pass seq=''.join(contigseq) return seq except: print "Error opening file:", contigloc,sys.exc_info()[0] raise def contiglen(contigloc): '''Just goes through multi-fasta file, and works out sequence length for eahc entry''' import sys try: lengths=[] with open(contigloc,'r+') as Contigs: head=Contigs.readline() if not head.startswith('>'): raise TypeError("Not a FASTA file:") Contigs.seek(0) contigseq=[] for line in Contigs: if line.startswith('>'): if contigseq!=[]: lengths.append(len("".join(contigseq))) contigseq=[] else: contigseq.append(line.translate(None,"\n")) lengths.append(len("".join(contigseq))) return lengths except: print "Error opening file:", contigloc,sys.exc_info()[0] raise def writeout(data): return def postprocess(sifloc,trueloc,final=False): with tryopen(trueloc,'','.txt') as correct: correct.readline() #Move past header Truescaf={} for line in correct.readlines(): curline=line.split('\t') if curline[0] not in Truescaf: Truescaf[curline[0]]=[] if curline[1].rstrip('\n') not in Truescaf: Truescaf[curline[1].rstrip('\n')]=[] if curline[1].rstrip('\n') not in Truescaf[curline[0]]: Truescaf[curline[0]]+=[curline[1].rstrip('\n')] if curline[0] not in Truescaf[curline[1].rstrip('\n')]: Truescaf[curline[1].rstrip('\n')]+=[curline[0]] Newdata=[] with tryopen(sifloc,'','.txt') as olddata: if not final: header=olddata.readline().translate(None,'\n')+"\tTrueEdge\tDecision\n" else: header=olddata.readline().translate(None,'\n')+"\tTrueEdge\n" for line in olddata.readlines(): curline=line.split('\t') tig1=curline[0] tig2=curline[2] if tig1 in Truescaf: if tig2 in Truescaf[tig1]: TrueEdge="True" else: TrueEdge="False" else: TrueEdge="False" if not final: remove=curline[4].rstrip('\n') #print remove if remove=="True" and TrueEdge=="True": Decision="FalseNeg" elif remove=="True" and TrueEdge=="False": Decision="TrueNeg" elif remove=="False" and TrueEdge=="True": Decision="TruePos" elif remove=="False" and TrueEdge=="False": Decision="FalsePos" Newdata+=[[x.rstrip('\n') for x in curline]+[TrueEdge]+[Decision]] else: Newdata+=[[x.rstrip('\n') for x in curline]+[TrueEdge]] with tryopen(sifloc,header,'.txt',True) as final: for line in Newdata: final.write("{0}\n".format("\t".join(line))) return def totprocess(sifloc1,sifloc2,sifloc3,trueloc="TrueEdges"): postprocess(sifloc1,trueloc,False) postprocess(sifloc2,trueloc,False) postprocess(sifloc3,trueloc,True) return def maketrueedges(): '''Assumes that contigslices file is both ordered by position withiin each species and by species''' TrueEdges=[] with tryopen("covs",'','.tsv') as covs: i=1 prevtig=False curtig=False donetigs=[] TrueEdge=[] covs.readline() #Move past header for line in covs: prevtig=curtig curtig=line.split('\t')[0] #print "This is the current Contig", curtig #print "This is the current line", line.split('\t')[0] tignumber='{0}{1}'.format('tig',i) if tignumber in curtig: i+=1 if tignumber in donetigs: donetigs=[] i=2 elif prevtig!=False: TrueEdge+=[(prevtig,curtig)] donetigs+=[tignumber] else: i=2 donetigs=[] #print tignumber #print curtig with tryopen("TrueEdges",'contig1\tcontig2\n','.txt',True) as Edge: for edge in TrueEdge: #print edge Edge.write("{0}\t{1}\n".format(edge[0],edge[1])) return def binstotxt(checkdir,fileend='.fa'): import os files=os.listdir(checkdir) bins=[File for File in files if File.endswith('.fa')] #Should get those with .fa in name binpaths=[os.path.join(checkdir,binfile) for binfile in bins] contigbinmap={} for i,binloc in enumerate(binpaths): contigbinmap[bins[i].strip(fileend)]=getfastaheaders(binloc) #Maps the set of contigs in #bin file to that bin in a graph return contigbinmap def writelis(filename,header,rows): with tryopen(filename,header,'') as newfile: for row in rows: newfile.write("\t".join(row)+"\n") return def binwrapper(writedir,filename,checkdir,fileend='.fa'): import os bins=binstotxt(checkdir,fileend) rows=[(item,key) for key,items in bins.iteritems() for item in items] columns=zip(rows) writelis(os.path.join(writedir,filename),"Contig\tBin\n",rows) def getfastaheaders(filename): try: Names=[] with tryopen(filename,'','') as fasta: for line in fasta: if line.startswith('>'): #print line Names+=[line.strip('>').rstrip('\n')] else: pass return Names except: raise def screenbins(binsfile,contamlevel, completeness): return def tryopen(filename,header,filetype,expunge=False): '''Looks for a file, if its not there, it makes the file, if it is there then it returns the opened file. Remember to close the file if you call this function or use: with tryopen(stuff) as morestuff.''' import os try: if not os.path.isfile(filename+filetype): with open(filename+filetype,'w') as newfile: newfile.write(header) elif os.path.isfile(filename+filetype): if expunge: temp=open(filename+filetype,'w+') temp.write(header) temp.close() return open(filename+filetype,'a+') return open(filename+filetype,'a+') except: print "Either could not create or open the file" raise def makeboolean(string): Val_T=("true",'t','1','yes') Val_F=("false","f",'0','no') try: if isinstance(string,bool): return string if string.lower() in Val_T: return True elif string.lower() in Val_F: return False except: raise TypeError("This does not appear to even be an attempt at a boolean") if __name__ == "__main__": ###Check if arguments coming in from command line import matplotlib.pyplot as plt import numpy as np import scipy as sp import os import sys import datetime parser = argparse.ArgumentParser(description='Takes a Genome in Fasta format and then parse it into predefined chunks\ These reads and gaps are then parsed to both SSPace and ScaffoldM which then have there output extracted and compared.\ These comparisons have formed the basis for improvements on ScaffoldM.') parser.add_argument('-N','--name', type=str, nargs='?', \ help='The name of the file',default='/home/baker/Documents/Geneslab/TestFunctions/ReferenceFasta/MG1655ref.fasta') parser.add_argument('-P','--path', type=str, nargs='?', \ default='/home/baker/Packages/SSPACE-STANDARD-3.0/SSPACE_Standard_v3.0.pl', \ help='The name of absolute path') parser.add_argument('-L','--lists', type=int, nargs='*', help='Test',default=False) parser.add_argument('-l','--readlength',type=int,nargs='?', help='The length of reads in the simulated library',default=100) parser.add_argument('-c','--coverage',type=int,nargs='?', help='Coverage in simulated library',default=30) parser.add_argument('-b','--bams',type=str,nargs='*', help='Coverage in simulated library',default="NA") parser.add_argument('-m','--meaninsert',type=int,nargs='?', help='The mean insert size of the library, this is the expected gap between two paired reads',default=300) parser.add_argument('-s','--stdinsert',type=int,nargs='?', help='The standard deviation of the insert size between paired reads',default=30) parser.add_argument('-g','--gap',type=int,nargs='?', help='The gap between contigs',default=50) parser.add_argument('-lim','--linklimit',type=int,nargs='?', help='The number of linking reads needed to link contigs',default=5) parser.add_argument('-r','--ratio',type=int,nargs='?', help='If one contig is linked to multiple others a comparison is made between the number of linking reads. \ this ratio is the value at which both links will be rejected to avoid false positives',default=0.7) parser.add_argument('-ln','--libno',type=int,nargs='?', help='The number of libraries expected to be found in a bamm file',default=[1]) parser.add_argument('-ns','--nslice',type=int,nargs='?', help='The number of slices to use for data simulation',default=100) parser.add_argument('-t','--trim',type=int,nargs='?', help='Whether or not',default=0.2) parser.add_argument('-e','--error',type=int,nargs='?', help='Whether or not',default=0.75) parser.add_argument('-w','--wrapperp',type=str,nargs='?', help='The path to ScaffoldM wrapper',default="~/Documents/Geneslab/ScaffoldM/scaffoldm/") parser.add_argument('-si','--sim',type=str,nargs='?', help='Whether or not to simulate',default=True) parser.add_argument('-C','--contiglocation',type=str,nargs='?', help='The path to contigs',default="") parser.add_argument('-O','--randominversions',type=bool,nargs='?', help='The path to contigs',default=False) parser.add_argument('-rep','--rep',type=bool,nargs='?', help='Boolean- whether to repeat sequences',default=False) parser.add_argument('-Tig','--tigname',type=str,nargs='?', help='Name of Fasta file for mapping',default="mergedslices.fasta") args = parser.parse_args() parser.add_argument('-Rsim','--simreads',type=str,nargs='?', help='Name of Fasta file for mapping',default=False) args = parser.parse_args() ###Stuff for Simulation sim=makeboolean(args.sim) #Whether or not to simulate path=args.path #path to sspace Name=args.name #Path to reference genome contigloc=args.contiglocation #path to contigs prename=os.sep.join(Name.split(os.sep)[:-1]) #Strips last layer of path if len(Name.split(os.sep)[-1].split(".fasta"))>1: postname=Name.split(os.sep)[-1].split(".fasta")[0] #Should be name of reference file - path and file type elif len(Name.split(os.sep)[-1].split(".fna"))>1: postname=Name.split(os.sep)[-1].split(".fna")[0] refpath="../{0}".format(Name.split(os.sep)[-2]) newname="../{0}/{1}".format(Name.split(os.sep)[-2],Name.split(os.sep)[-1].split(".fasta")[0]) #For moving up and into reference folder coverage=args.coverage # A specified amount of coverage for simulation readlength=args.readlength #Simulated read length meaninsert=args.meaninsert #Mean insert size stdinsert=args.stdinsert #Std deviation in insert size lists=args.lists #THe list of cuts to be made to the reference genome linklimit=args.linklimit #The lower limit to accpet a pairing - eg ignore all pairs with less than k links ratio=args.ratio #Ratio for SSPACE algorithm gap=args.gap #Mean value for simulated gap size libno=args.libno #THe number of libraries BAMM should search for amongst the reads N_slices=args.nslice #THe number of slices to make error=args.error #The error for SSPACE to accept read inserts trim=args.trim #Can't remember what this does ori=args.randominversions #Whether or not to randomly take the reverse compliment rep=args.rep #Whether or not to randomly repeat sequence in the simulation wrapperpath=args.wrapperp #The path to the python wrapper seqlen=getfastalen(Name) #Approximate length of the genome bams=args.bams #name of bams contigname=args.tigname #name of fasta file simreads=makeboolean(args.simreads) #STuff for all comparisons if sim: if trim==True: #Trim overall length randomly for more variability pass #Turn long list of cut locations into a string suitable for os.system if lists==False: slices=randcuts(gap,seqlen,N_slices,ori=ori) #print slices slices=[str(i) for i in slices] readcuts=" ".join(slices) else: slices=lists readcuts=" ".join(lists) start=min([int(j) for i,j in enumerate(slices) if i%4==0]) #Starting position of cuts end=max([int(j) for i,j in enumerate(slices) if i%4==1]) #Starting position of cuts os.mkdir(postname+"cuts_S:{0}_E:{1}".format(start,end)) os.chdir(postname+"cuts_S:{0}_E:{1}".format(start,end)) slicename,completename=slicer(slices,Name) #Make reads via metasim if simreads: readnumber=coverage*(end-start)/readlength makereadswrap(readnumber,readlength,meaninsert,stdinsert,\ completename) #splits the reads into a format suitable for completename=completename.split(".fna")[0] file1,file2=splitter(completename+"-Empirical") else: #print os.getcwd() file1='{0}/{1}-Empirical_1'.format(refpath,postname) file2='{0}/{1}-Empirical_2'.format(refpath,postname) completename=newname contigloc=slicename #Make libraries.txts makelibrary("library",['Lib1'], [file1],[file2],[meaninsert],[error],orientation=['FR']) else: contigloc=contigname pass #To separate from SIM - needs a library file #perl SSPACE_Basic.pl -l libraries.txt -s contigs.fasta -x 0 -m 32 -o 20 -t 0 -k 5 -a 0.70 -n 15 -p 0 -v 0 -z 0 -g 0 -T 1 -b standard_out mapreads=False if mapreads: print "SSPACE", contigloc, "The contig file" print "perl {4} -l {0} -s {1} -x 0 \ -k {2} -a {3} -b standard_out"\ .format("library.txt",contigloc,linklimit,ratio,path) os.system("perl {4} -l {0} -s {1} -x 0 \ -k {2} -a {3} -b standard_out"\ .format("library.txt",contigloc,linklimit,ratio,path)) print "Onto BamM" if sim: os.system("bamm make -d {0} -i {1} --quiet".format(slicename,completename+"-Empirical.fna")) libno=[str(ele) for ele in libno] librarynumbers=' '.join(libno) bamname="{0}{1}{2}".format(slicename.split(".fna")[0],".",postname)+"-Empirical" contigname=slicename print "The current time: ", datetime.datetime.now().time().isoformat() if type(bams)!=str: #Check if default is being used libno=[str(ele) for ele in libno] librarynumbers=' '.join(libno) print "The Bams", ' '.join(bams) os.system("python {0}wrapper.py -b {1} -f {2} -n {3}".format(wrapperpath,' '.join(bams),contigname,librarynumbers)) real=True if not real: maketrueedges() totprocess("Initial_links","Threshold_links","Cov_Links_links") #print os.getcwd() if os.path.isdir('./standard_out'): #Only go if SSPACE worked SSPACEgraph=sspaceconvert("./standard_out/standard_out.final.evidence") graphtosif(SSPACEgraph,"SSPACE_CONNECTIONS") #os.procces() - make the graphs to compare SSPACE and ScaffoldM os.system("python ./process.py") binned=True if binned: binwrapper('.','Node_BinClass.txt','bins_raw/') print "You made it pass checking the nodes" #Separate those with high enough completeness/quality scores #Visualise the remaining #Work out how to colour based on this in cytoscape #Bam, done, can compare into and out of binning occurrences print "This is the real end now" elif sim: #Should only occur on defaults os.system("python {0}wrapper.py -b {1} -f {2} -n {3}".format(wrapperpath,bamname,contigname,librarynumbers)) maketrueedges() totprocess("Initial_links","Threshold_links","Cov_Links_links") print "This is the real end now" comparisons=False if comparisons: #Make some comparisons between SSPACE and ScaffoldM os.mkdir('graphs') Visualise([slicename,"testScaffold.fasta","./standard_out/standard_out.final.scaffolds.fasta"],\ [int(slices[i+4])-int(slices[i+1]) for i in range(0,len(slices)-4,4)],contigloc) if sim: print "You made it to the link error extractions" extracttigs(contigloc=slicename) else: pass
unknown
codeparrot/codeparrot-clean
from typing import TYPE_CHECKING, Any from langchain_classic._api import create_importer if TYPE_CHECKING: from langchain_community.callbacks.trubrics_callback import TrubricsCallbackHandler # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling optional imports. DEPRECATED_LOOKUP = { "TrubricsCallbackHandler": "langchain_community.callbacks.trubrics_callback", } _import_attribute = create_importer(__file__, deprecated_lookups=DEPRECATED_LOOKUP) def __getattr__(name: str) -> Any: """Look up attributes dynamically.""" return _import_attribute(name) __all__ = [ "TrubricsCallbackHandler", ]
python
github
https://github.com/langchain-ai/langchain
libs/langchain/langchain_classic/callbacks/trubrics_callback.py
import os import tempfile import socket import subprocess import mock import pytest import shentry class _Any(object): def __eq__(self, other): return True def __ne__(self, other): return False ANY = _Any() @pytest.mark.parametrize('argv,expected_full_command,expected_command_ws,expected_shell', ( (['/foo/bar'], ['/bin/bash', '-c', '/foo/bar'], '/foo/bar', '/bin/bash'), (['/foo/bar', 'arg1', 'arg2'], ['/bin/bash', '-c', '/foo/bar arg1 arg2'], '/foo/bar arg1 arg2', '/bin/bash'), (['-c', 'ls | head'], ['/bin/sh', '-c', 'ls | head'], 'ls | head', '/bin/sh'), )) def test_get_command(mocker, argv, expected_full_command, expected_command_ws, expected_shell): mocker.patch('os.environ', autospec=True) os.environ.get.return_value = '/bin/bash' assert shentry.get_command(argv) == (expected_full_command, expected_command_ws, expected_shell) os.environ.get.assert_called_once_with('SHELL', '/bin/sh') class TestSimpleSentryClient(object): def test_new_from_environment(self, mocker): mocker.patch.dict('os.environ', {'SHELL_SENTRY_DSN': 'https://pub:priv@sentry.test/1'}) client = shentry.SimpleSentryClient.new_from_environment() assert client.uri == 'https://sentry.test/api/1/store/' assert client.public == 'pub' assert client.secret == 'priv' assert client.project_id == '1' def test_new_from_environment_regular_dsn(self, mocker): mocker.patch.dict('os.environ', {'SENTRY_DSN': 'https://pub:priv@sentry.test/3'}) client = shentry.SimpleSentryClient.new_from_environment() assert client.uri == 'https://sentry.test/api/3/store/' assert client.public == 'pub' assert client.secret == 'priv' assert client.project_id == '3' def test_new_from_environment_with_file(self, mocker): mocker.patch.dict('os.environ', {'SHELL_SENTRY_DSN': ''}) mocker.patch.object(shentry, 'read_systemwide_config', return_value='https://pub:priv@sentry.test/2') client = shentry.SimpleSentryClient.new_from_environment() assert client.uri == 'https://sentry.test/api/2/store/' assert client.public == 'pub' assert client.secret == 'priv' assert client.project_id == '2' def test_main(mocker, tmpdir): mock_client = mock.Mock(autospec=shentry.SimpleSentryClient) mocker.patch('shentry.SimpleSentryClient.new_from_environment', return_value=mock_client) mocker.patch('tempfile.mkdtemp', return_value=str(tmpdir)) mocker.patch.dict('os.environ', {'SHELL': '/bin/fish', 'PATH': 'A_PATH', 'TZ': 'UTC'}) mock_popen = mock.Mock(autospec=subprocess.Popen) mocker.patch('subprocess.Popen', return_value=mock_popen) mock_popen.wait.return_value = 1 mock_popen.returncode = 1 shentry.main(['shentry', '/bin/ls']) tempfile.mkdtemp.assert_called_once_with() mock_client.send_event.assert_called_once_with( message='Command `/bin/ls` failed with code 1.\n', level='error', fingerprint=[socket.gethostname(), '/bin/ls'], extra_context={ 'username': ANY, 'shell': '/bin/fish', 'load_average_at_exit': ANY, 'start_time': ANY, 'command': '/bin/ls', 'duration': ANY, 'PATH': 'A_PATH', 'TZ': 'UTC', 'returncode': 1, 'working_directory': ANY, '_sent_with': ANY, } )
unknown
codeparrot/codeparrot-clean
<?php namespace Illuminate\Tests\Database; use Illuminate\Database\Capsule\Manager as DB; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model as Eloquent; use Illuminate\Database\Eloquent\Relations\MorphOne; use Illuminate\Database\Eloquent\Relations\MorphTo; use PHPUnit\Framework\TestCase; class DatabaseEloquentInverseRelationMorphOneTest extends TestCase { /** * Setup the database schema. * * @return void */ protected function setUp(): void { $db = new DB; $db->addConnection([ 'driver' => 'sqlite', 'database' => ':memory:', ]); $db->bootEloquent(); $db->setAsGlobal(); $this->createSchema(); } protected function createSchema() { $this->schema()->create('test_posts', function ($table) { $table->increments('id'); $table->timestamps(); }); $this->schema()->create('test_images', function ($table) { $table->increments('id'); $table->morphs('imageable'); $table->timestamps(); }); } /** * Tear down the database schema. * * @return void */ protected function tearDown(): void { $this->schema()->drop('test_posts'); $this->schema()->drop('test_images'); parent::tearDown(); } public function testMorphOneInverseRelationIsProperlySetToParentWhenLazyLoaded() { MorphOneInverseImageModel::factory(6)->create(); $posts = MorphOneInversePostModel::all(); foreach ($posts as $post) { $this->assertFalse($post->relationLoaded('image')); $image = $post->image; $this->assertTrue($image->relationLoaded('imageable')); $this->assertSame($post, $image->imageable); } } public function testMorphOneInverseRelationIsProperlySetToParentWhenEagerLoaded() { MorphOneInverseImageModel::factory(6)->create(); $posts = MorphOneInversePostModel::with('image')->get(); foreach ($posts as $post) { $image = $post->getRelation('image'); $this->assertTrue($image->relationLoaded('imageable')); $this->assertSame($post, $image->imageable); } } public function testMorphOneGuessedInverseRelationIsProperlySetToParentWhenLazyLoaded() { MorphOneInverseImageModel::factory(6)->create(); $posts = MorphOneInversePostModel::all(); foreach ($posts as $post) { $this->assertFalse($post->relationLoaded('guessedImage')); $image = $post->guessedImage; $this->assertTrue($image->relationLoaded('imageable')); $this->assertSame($post, $image->imageable); } } public function testMorphOneGuessedInverseRelationIsProperlySetToParentWhenEagerLoaded() { MorphOneInverseImageModel::factory(6)->create(); $posts = MorphOneInversePostModel::with('guessedImage')->get(); foreach ($posts as $post) { $image = $post->getRelation('guessedImage'); $this->assertTrue($image->relationLoaded('imageable')); $this->assertSame($post, $image->imageable); } } public function testMorphOneInverseRelationIsProperlySetToParentWhenMaking() { $post = MorphOneInversePostModel::create(); $image = $post->image()->make(); $this->assertTrue($image->relationLoaded('imageable')); $this->assertSame($post, $image->imageable); } public function testMorphOneInverseRelationIsProperlySetToParentWhenCreating() { $post = MorphOneInversePostModel::create(); $image = $post->image()->create(); $this->assertTrue($image->relationLoaded('imageable')); $this->assertSame($post, $image->imageable); } public function testMorphOneInverseRelationIsProperlySetToParentWhenCreatingQuietly() { $post = MorphOneInversePostModel::create(); $image = $post->image()->createQuietly(); $this->assertTrue($image->relationLoaded('imageable')); $this->assertSame($post, $image->imageable); } public function testMorphOneInverseRelationIsProperlySetToParentWhenForceCreating() { $post = MorphOneInversePostModel::create(); $image = $post->image()->forceCreate(); $this->assertTrue($image->relationLoaded('imageable')); $this->assertSame($post, $image->imageable); } public function testMorphOneInverseRelationIsProperlySetToParentWhenSaving() { $post = MorphOneInversePostModel::create(); $image = MorphOneInverseImageModel::make(); $this->assertFalse($image->relationLoaded('imageable')); $post->image()->save($image); $this->assertTrue($image->relationLoaded('imageable')); $this->assertSame($post, $image->imageable); } public function testMorphOneInverseRelationIsProperlySetToParentWhenSavingQuietly() { $post = MorphOneInversePostModel::create(); $image = MorphOneInverseImageModel::make(); $this->assertFalse($image->relationLoaded('imageable')); $post->image()->saveQuietly($image); $this->assertTrue($image->relationLoaded('imageable')); $this->assertSame($post, $image->imageable); } public function testMorphOneInverseRelationIsProperlySetToParentWhenUpdating() { $post = MorphOneInversePostModel::create(); $image = MorphOneInverseImageModel::factory()->create(); $this->assertTrue($post->isNot($image->imageable)); $post->image()->save($image); $this->assertTrue($post->is($image->imageable)); $this->assertSame($post, $image->imageable); } /** * Helpers... */ /** * Get a database connection instance. * * @return \Illuminate\Database\Connection */ protected function connection($connection = 'default') { return Eloquent::getConnectionResolver()->connection($connection); } /** * Get a schema builder instance. * * @return \Illuminate\Database\Schema\Builder */ protected function schema($connection = 'default') { return $this->connection($connection)->getSchemaBuilder(); } } class MorphOneInversePostModel extends Model { use HasFactory; protected $table = 'test_posts'; protected $fillable = ['id']; protected static function newFactory() { return new MorphOneInversePostModelFactory(); } public function image(): MorphOne { return $this->morphOne(MorphOneInverseImageModel::class, 'imageable')->inverse('imageable'); } public function guessedImage(): MorphOne { return $this->morphOne(MorphOneInverseImageModel::class, 'imageable')->inverse(); } } class MorphOneInversePostModelFactory extends Factory { protected $model = MorphOneInversePostModel::class; public function definition() { return []; } } class MorphOneInverseImageModel extends Model { use HasFactory; protected $table = 'test_images'; protected $fillable = ['id', 'imageable_type', 'imageable_id']; protected static function newFactory() { return new MorphOneInverseImageModelFactory(); } public function imageable(): MorphTo { return $this->morphTo('imageable'); } } class MorphOneInverseImageModelFactory extends Factory { protected $model = MorphOneInverseImageModel::class; public function definition() { return [ 'imageable_type' => MorphOneInversePostModel::class, 'imageable_id' => MorphOneInversePostModel::factory(), ]; } }
php
github
https://github.com/laravel/framework
tests/Database/DatabaseEloquentInverseRelationMorphOneTest.php
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package phases import ( "fmt" "os" "path/filepath" "k8s.io/klog/v2" kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/scheme" kubeadmapiv1 "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta4" "k8s.io/kubernetes/cmd/kubeadm/app/cmd/options" "k8s.io/kubernetes/cmd/kubeadm/app/cmd/phases/workflow" kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants" etcdphase "k8s.io/kubernetes/cmd/kubeadm/app/phases/etcd" "k8s.io/kubernetes/cmd/kubeadm/app/util/errors" utilstaticpod "k8s.io/kubernetes/cmd/kubeadm/app/util/staticpod" ) // NewRemoveETCDMemberPhase creates a kubeadm workflow phase for remove-etcd-member func NewRemoveETCDMemberPhase() workflow.Phase { return workflow.Phase{ Name: "remove-etcd-member", Short: "Remove a local etcd member.", Long: "Remove a local etcd member for a control plane node.", Run: runRemoveETCDMemberPhase, InheritFlags: []string{ options.KubeconfigPath, options.DryRun, }, } } func runRemoveETCDMemberPhase(c workflow.RunData) error { r, ok := c.(resetData) if !ok { return errors.New("remove-etcd-member-phase phase invoked with an invalid data struct") } cfg := r.Cfg() // Only clear etcd data when using local etcd. klog.V(1).Infoln("[reset] Checking for etcd config") etcdManifestPath := filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.ManifestsSubDirName, "etcd.yaml") etcdDataDir, err := getEtcdDataDir(etcdManifestPath, cfg) if err == nil { if cfg != nil { if !r.DryRun() { err := etcdphase.RemoveStackedEtcdMemberFromCluster(r.Client(), cfg) if err != nil { klog.Warningf("[reset] Failed to remove etcd member: %v, please manually remove this etcd member using etcdctl", err) } else { if err := CleanDir(etcdDataDir); err != nil { klog.Warningf("[reset] Failed to delete contents of the etcd directory: %q, error: %v", etcdDataDir, err) } else { fmt.Printf("[reset] Deleted contents of the etcd data directory: %v\n", etcdDataDir) } } } else { fmt.Println("[dryrun] Would remove the etcd member on this node from the etcd cluster") fmt.Printf("[dryrun] Would delete contents of the etcd data directory: %v\n", etcdDataDir) } } // This could happen if the phase `cleanup-node` is run before the `remove-etcd-member`. // Cleanup the data in the etcd data dir to avoid some stale files which might cause the failure to build cluster in the next time. empty, _ := IsDirEmpty(etcdDataDir) if !empty && !r.DryRun() { if err := CleanDir(etcdDataDir); err != nil { klog.Warningf("[reset] Failed to delete contents of the etcd directory: %q, error: %v", etcdDataDir, err) } else { fmt.Printf("[reset] Deleted contents of the etcd data directory: %v\n", etcdDataDir) } } } else { fmt.Println("[reset] No etcd config found. Assuming external etcd") fmt.Println("[reset] Please, manually reset etcd to prevent further issues") } return nil } func getEtcdDataDir(manifestPath string, cfg *kubeadmapi.InitConfiguration) (string, error) { const etcdVolumeName = "etcd-data" var dataDir string if cfg != nil && cfg.Etcd.Local != nil { return cfg.Etcd.Local.DataDir, nil } klog.Warningln("[reset] No kubeadm config, using etcd pod spec to get data directory") if _, err := os.Stat(manifestPath); os.IsNotExist(err) { // Fall back to use the default cluster config if etcd.yaml doesn't exist, this could happen that // etcd.yaml is removed by other reset phases, e.g. cleanup-node. cfg := &kubeadmapiv1.ClusterConfiguration{} scheme.Scheme.Default(cfg) return cfg.Etcd.Local.DataDir, nil } etcdPod, err := utilstaticpod.ReadStaticPodFromDisk(manifestPath) if err != nil { return "", err } for _, volumeMount := range etcdPod.Spec.Volumes { if volumeMount.Name == etcdVolumeName { dataDir = volumeMount.HostPath.Path break } } if dataDir == "" { return dataDir, errors.New("invalid etcd pod manifest") } return dataDir, nil }
go
github
https://github.com/kubernetes/kubernetes
cmd/kubeadm/app/cmd/phases/reset/removeetcdmember.go
Version 1.93.1 (2026-02-12) =========================== <a id="1.93.1"></a> - [Don't try to recover keyword as non-keyword identifier](https://github.com/rust-lang/rust/pull/150590), fixing an ICE that especially [affected rustfmt](https://github.com/rust-lang/rustfmt/issues/6739). - [Fix `clippy::panicking_unwrap` false-positive on field access with implicit deref](https://github.com/rust-lang/rust-clippy/pull/16196). - [Revert "Update wasm-related dependencies in CI"](https://github.com/rust-lang/rust/pull/152259), fixing file descriptor leaks on the `wasm32-wasip2` target. Version 1.93.0 (2026-01-22) ========================== <a id="1.93.0-Language"></a> Language -------- - [Stabilize several s390x `vector`-related target features and the `is_s390x_feature_detected!` macro](https://github.com/rust-lang/rust/pull/145656) - [Stabilize declaration of C-style variadic functions for the `system` ABI](https://github.com/rust-lang/rust/pull/145954) - [Emit error when using some keyword as a `cfg` predicate](https://github.com/rust-lang/rust/pull/146978) - [Stabilize `asm_cfg`](https://github.com/rust-lang/rust/pull/147736) - [During const-evaluation, support copying pointers byte-by-byte](https://github.com/rust-lang/rust/pull/148259) - [LUB coercions now correctly handle function item types, and functions with differing safeties](https://github.com/rust-lang/rust/pull/148602) - [Allow `const` items that contain mutable references to `static` (which is *very* unsafe, but not *always* UB)](https://github.com/rust-lang/rust/pull/148746) - [Add warn-by-default `const_item_interior_mutations` lint to warn against calls which mutate interior mutable `const` items](https://github.com/rust-lang/rust/pull/148407) - [Add warn-by-default `function_casts_as_integer` lint](https://github.com/rust-lang/rust/pull/141470) <a id="1.93.0-Compiler"></a> Compiler -------- - [Stabilize `-Cjump-tables=bool`](https://github.com/rust-lang/rust/pull/145974). The flag was previously called `-Zno-jump-tables`. <a id="1.93.0-Platform-Support"></a> Platform Support ---------------- - [Promote `riscv64a23-unknown-linux-gnu` to Tier 2 (without host tools)](https://github.com/rust-lang/rust/pull/148435) Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. [platform-support-doc]: https://doc.rust-lang.org/rustc/platform-support.html <a id="1.93.0-Libraries"></a> Libraries --------- - [Stop internally using `specialization` on the `Copy` trait as it is unsound in the presence of lifetime dependent `Copy` implementations. This may result in some performance regressions as some standard library APIs may now call `Clone::clone` instead of performing bitwise copies](https://github.com/rust-lang/rust/pull/135634) - [Allow the global allocator to use thread-local storage and `std::thread::current()`](https://github.com/rust-lang/rust/pull/144465) - [Make `BTree::append` not update existing keys when appending an entry which already exists](https://github.com/rust-lang/rust/pull/145628) - [Don't require `T: RefUnwindSafe` for `vec::IntoIter<T>: UnwindSafe`](https://github.com/rust-lang/rust/pull/145665) <a id="1.93.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`<[MaybeUninit<T>]>::assume_init_drop`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.assume_init_drop) - [`<[MaybeUninit<T>]>::assume_init_ref`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.assume_init_ref) - [`<[MaybeUninit<T>]>::assume_init_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.assume_init_mut) - [`<[MaybeUninit<T>]>::write_copy_of_slice`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.write_copy_of_slice) - [`<[MaybeUninit<T>]>::write_clone_of_slice`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.write_clone_of_slice) - [`String::into_raw_parts`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.into_raw_parts) - [`Vec::into_raw_parts`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.into_raw_parts) - [`<iN>::unchecked_neg`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.unchecked_neg) - [`<iN>::unchecked_shl`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.unchecked_shl) - [`<iN>::unchecked_shr`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.unchecked_shr) - [`<uN>::unchecked_shl`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.unchecked_shl) - [`<uN>::unchecked_shr`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.unchecked_shr) - [`<[T]>::as_array`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_array) - [`<[T]>::as_mut_array`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_mut_array) - [`<*const [T]>::as_array`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.as_array) - [`<*mut [T]>::as_mut_array`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.as_mut_array) - [`VecDeque::pop_front_if`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html#method.pop_front_if) - [`VecDeque::pop_back_if`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html#method.pop_back_if) - [`Duration::from_nanos_u128`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_nanos_u128) - [`char::MAX_LEN_UTF8`](https://doc.rust-lang.org/stable/std/primitive.char.html#associatedconstant.MAX_LEN_UTF8) - [`char::MAX_LEN_UTF16`](https://doc.rust-lang.org/stable/std/primitive.char.html#associatedconstant.MAX_LEN_UTF16) - [`std::fmt::from_fn`](https://doc.rust-lang.org/stable/std/fmt/fn.from_fn.html) - [`std::fmt::FromFn`](https://doc.rust-lang.org/stable/std/fmt/struct.FromFn.html) <a id="1.93.0-Cargo"></a> Cargo ----- - [Enable CARGO_CFG_DEBUG_ASSERTIONS in build scripts based on profile](https://github.com/rust-lang/cargo/pull/16160/) - [In `cargo tree`, support long forms for `--format` variables](https://github.com/rust-lang/cargo/pull/16204/) - [Add `--workspace` to `cargo clean`](https://github.com/rust-lang/cargo/pull/16263/) <a id="1.93.0-Rustdoc"></a> Rustdoc ----- - [Remove `#![doc(document_private_items)]`](https://github.com/rust-lang/rust/pull/146495) - [Include attribute and derive macros in search filters for "macros"](https://github.com/rust-lang/rust/pull/148176) - [Include extern crates in search filters for `import`](https://github.com/rust-lang/rust/pull/148301) - [Validate usage of crate-level doc attributes](https://github.com/rust-lang/rust/pull/149197). This means if any of `html_favicon_url`, `html_logo_url`, `html_playground_url`, `issue_tracker_base_url`, or `html_no_source` either has a missing value, an unexpected value, or a value of the wrong type, rustdoc will emit the deny-by-default lint `rustdoc::invalid_doc_attributes`. <a id="1.93.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Introduce `pin_v2` into the builtin attributes namespace](https://github.com/rust-lang/rust/pull/139751) - [Update bundled musl to 1.2.5](https://github.com/rust-lang/rust/pull/142682) - [On Emscripten, the unwinding ABI used when compiling with `panic=unwind` was changed from the JS exception handling ABI to the wasm exception handling ABI.](https://github.com/rust-lang/rust/pull/147224) If linking C/C++ object files with Rust objects, `-fwasm-exceptions` must be passed to the linker now. On nightly Rust, it is possible to get the old behavior with `-Zwasm-emscripten-eh=false -Zbuild-std`, but it will be removed in a future release. - The `#[test]` attribute, used to define tests, was previously ignored in various places where it had no meaning (e.g on trait methods or types). Putting the `#[test]` attribute in these places is no longer ignored, and will now result in an error; this may also result in errors when generating rustdoc. [Error when `test` attribute is applied to structs](https://github.com/rust-lang/rust/pull/147841) - Cargo now sets the `CARGO_CFG_DEBUG_ASSERTIONS` environment variable in more situations. This will cause crates depending on `static-init` versions 1.0.1 to 1.0.3 to fail compilation with "failed to resolve: use of unresolved module or unlinked crate `parking_lot`". See [the linked issue](https://github.com/rust-lang/rust/issues/150646#issuecomment-3718964342) for details. - [User written types in the `offset_of!` macro are now checked to be well formed.](https://github.com/rust-lang/rust/issues/150465/) - `cargo publish` no longer emits `.crate` files as a final artifact for user access when the `build.build-dir` config is unset - [Upgrade the `deref_nullptr` lint from warn-by-default to deny-by-default](https://github.com/rust-lang/rust/pull/148122) - [Add future-incompatibility warning for `...` function parameters without a pattern outside of `extern` blocks](https://github.com/rust-lang/rust/pull/143619) - [Introduce future-compatibility warning for `repr(C)` enums whose discriminant values do not fit into a `c_int` or `c_uint`](https://github.com/rust-lang/rust/pull/147017) - [Introduce future-compatibility warning against ignoring `repr(C)` types as part of `repr(transparent)`](https://github.com/rust-lang/rust/pull/147185) Version 1.92.0 (2025-12-11) ========================== <a id="1.92.0-Language"></a> Language -------- - [Document `MaybeUninit` representation and validity](https://github.com/rust-lang/rust/pull/140463) - [Allow `&raw [mut | const]` for union field in safe code](https://github.com/rust-lang/rust/pull/141469) - [Prefer item bounds of associated types over where-bounds for auto-traits and `Sized`](https://github.com/rust-lang/rust/pull/144064) - [Do not materialize `X` in `[X; 0]` when `X` is unsizing a const](https://github.com/rust-lang/rust/pull/145277) - [Support combining `#[track_caller]` and `#[no_mangle]` (requires every declaration specifying `#[track_caller]` as well)](https://github.com/rust-lang/rust/pull/145724) - [Make never type lints `never_type_fallback_flowing_into_unsafe` and `dependency_on_unit_never_type_fallback` deny-by-default](https://github.com/rust-lang/rust/pull/146167) - [Allow specifying multiple bounds for same associated item, except in trait objects](https://github.com/rust-lang/rust/pull/146593) - [Slightly strengthen higher-ranked region handling in coherence](https://github.com/rust-lang/rust/pull/146725) - [The `unused_must_use` lint no longer warns on `Result<(), Uninhabited>` (for instance, `Result<(), !>`), or `ControlFlow<Uninhabited, ()>`](https://github.com/rust-lang/rust/pull/147382). This avoids having to check for an error that can never happen. <a id="1.92.0-Compiler"></a> Compiler -------- - [Make `mips64el-unknown-linux-muslabi64` link dynamically](https://github.com/rust-lang/rust/pull/146858) - [Remove current code for embedding command-line args in PDB](https://github.com/rust-lang/rust/pull/147022) Command-line information is typically not needed by debugging tools, and the removed code was causing problems for incremental builds even on targets that don't use PDB debuginfo. <a id="1.92.0-Libraries"></a> Libraries --------- - [Specialize `Iterator::eq{_by}` for `TrustedLen` iterators](https://github.com/rust-lang/rust/pull/137122) - [Simplify `Extend` for tuples](https://github.com/rust-lang/rust/pull/138799) - [Added details to `Debug` for `EncodeWide`](https://github.com/rust-lang/rust/pull/140153). - [`iter::Repeat::last`](https://github.com/rust-lang/rust/pull/147258) and [`count`](https://github.com/rust-lang/rust/pull/146410) will now panic, rather than looping infinitely. <a id="1.92.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`NonZero<u{N}>::div_ceil`](https://doc.rust-lang.org/stable/std/num/struct.NonZero.html#method.div_ceil) - [`Location::file_as_c_str`](https://doc.rust-lang.org/stable/std/panic/struct.Location.html#method.file_as_c_str) - [`RwLockWriteGuard::downgrade`](https://doc.rust-lang.org/stable/std/sync/struct.RwLockWriteGuard.html#method.downgrade) - [`Box::new_zeroed`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.new_zeroed) - [`Box::new_zeroed_slice`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.new_zeroed_slice) - [`Rc::new_zeroed`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#method.new_zeroed) - [`Rc::new_zeroed_slice`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#method.new_zeroed_slice) - [`Arc::new_zeroed`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#method.new_zeroed) - [`Arc::new_zeroed_slice`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#method.new_zeroed_slice) - [`btree_map::Entry::insert_entry`](https://doc.rust-lang.org/stable/std/collections/btree_map/enum.Entry.html#method.insert_entry) - [`btree_map::VacantEntry::insert_entry`](https://doc.rust-lang.org/stable/std/collections/btree_map/struct.VacantEntry.html#method.insert_entry) - [`impl Extend<proc_macro::Group> for proc_macro::TokenStream`](https://doc.rust-lang.org/stable/proc_macro/struct.TokenStream.html#impl-Extend%3CGroup%3E-for-TokenStream) - [`impl Extend<proc_macro::Literal> for proc_macro::TokenStream`](https://doc.rust-lang.org/stable/proc_macro/struct.TokenStream.html#impl-Extend%3CLiteral%3E-for-TokenStream) - [`impl Extend<proc_macro::Punct> for proc_macro::TokenStream`](https://doc.rust-lang.org/stable/proc_macro/struct.TokenStream.html#impl-Extend%3CPunct%3E-for-TokenStream) - [`impl Extend<proc_macro::Ident> for proc_macro::TokenStream`](https://doc.rust-lang.org/stable/proc_macro/struct.TokenStream.html#impl-Extend%3CIdent%3E-for-TokenStream) These previously stable APIs are now stable in const contexts: - [`<[_]>::rotate_left`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.rotate_left) - [`<[_]>::rotate_right`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.rotate_right) <a id="1.92.0-Cargo"></a> Cargo ----- - [Added a new chapter](https://github.com/rust-lang/cargo/issues/16119) to the Cargo book, ["Optimizing Build Performance"](https://doc.rust-lang.org/stable/cargo/guide/build-performance.html). <a id="1.92.0-Rustdoc"></a> Rustdoc ----- - [If a trait item appears in rustdoc search, hide the corresponding impl items](https://github.com/rust-lang/rust/pull/145898). Previously a search for "last" would show both `Iterator::last` as well as impl methods like `std::vec::IntoIter::last`. Now these impl methods will be hidden, freeing up space for inherent methods like `BTreeSet::last`. - [Relax rules for identifiers in search](https://github.com/rust-lang/rust/pull/147860). Previously you could only search for identifiers that were valid in rust code, now searches only need to be valid as part of an identifier. For example, you can now perform a search that starts with a digit. <a id="1.92.0-Compatibility-Notes"></a> Compatibility Notes ------------------- * [Fix backtraces with `-C panic=abort` on Linux by generating unwind tables by default](https://github.com/rust-lang/rust/pull/143613). Build with `-C force-unwind-tables=no` to keep omitting unwind tables. - As part of the larger effort refactoring compiler built-in attributes and their diagnostics, [the future-compatibility lint `invalid_macro_export_arguments` is upgraded to deny-by-default and will be reported in dependencies too.](https://github.com/rust-lang/rust/pull/143857) - [Update the minimum external LLVM to 20](https://github.com/rust-lang/rust/pull/145071) - [Prevent downstream `impl DerefMut for Pin<LocalType>`](https://github.com/rust-lang/rust/pull/145608) - [Don't apply temporary lifetime extension rules to the arguments of non-extended `pin!` and formatting macros](https://github.com/rust-lang/rust/pull/145838) Version 1.91.1 (2025-11-10) =========================== <a id="1.91.1"></a> - [Enable file locking support in illumos](https://github.com/rust-lang/rust/pull/148322). This fixes Cargo not locking the build directory on illumos. - [Fix `wasm_import_module` attribute cross-crate](https://github.com/rust-lang/rust/pull/148363). This fixes linker errors on WASM targets. Version 1.91.0 (2025-10-30) ========================== <a id="1.91.0-Language"></a> Language -------- - [Lower pattern bindings in the order they're written and base drop order on primary bindings' order](https://github.com/rust-lang/rust/pull/143764) - [Stabilize declaration of C-style variadic functions for `sysv64`, `win64`, `efiapi`, and `aapcs` ABIs](https://github.com/rust-lang/rust/pull/144066). This brings these ABIs in line with the C ABI: variadic functions can be declared in extern blocks but not defined. - [Add `dangling_pointers_from_locals` lint to warn against dangling pointers from local variables](https://github.com/rust-lang/rust/pull/144322) - [Upgrade `semicolon_in_expressions_from_macros` from warn to deny](https://github.com/rust-lang/rust/pull/144369) - [Stabilize LoongArch32 inline assembly](https://github.com/rust-lang/rust/pull/144402) - [Add warn-by-default `integer_to_ptr_transmutes` lint against integer-to-pointer transmutes](https://github.com/rust-lang/rust/pull/144531) - [Stabilize `sse4a` and `tbm` target features](https://github.com/rust-lang/rust/pull/144542) - [Add `target_env = "macabi"` and `target_env = "sim"` cfgs](https://github.com/rust-lang/rust/pull/139451) as replacements for the `target_abi` cfgs with the same values. <a id="1.91.0-Compiler"></a> Compiler -------- - [Don't warn on never-to-any `as` casts as unreachable](https://github.com/rust-lang/rust/pull/144804) <a id="1.91.0-Platform-Support"></a> Platform Support ---------------- - [Promote `aarch64-pc-windows-gnullvm` and `x86_64-pc-windows-gnullvm` to Tier 2 with host tools.](https://github.com/rust-lang/rust/pull/143031) Note: llvm-tools and MSI installers are missing but will be added in future releases. - [Promote `aarch64-pc-windows-msvc` to Tier 1](https://github.com/rust-lang/rust/pull/145682) Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. [platform-support-doc]: https://doc.rust-lang.org/rustc/platform-support.html <a id="1.91.0-Libraries"></a> Libraries --------- - [Print thread ID in panic message](https://github.com/rust-lang/rust/pull/115746) - [Fix overly restrictive lifetime in `core::panic::Location::file` return type](https://github.com/rust-lang/rust/pull/132087) - [Guarantee parameter order for `_by()` variants of `min` / `max`/ `minmax` in `std::cmp`](https://github.com/rust-lang/rust/pull/139357) - [Document assumptions about `Clone` and `Eq` traits](https://github.com/rust-lang/rust/pull/144330/) - [`std::thread`: Return error if setting thread stack size fails](https://github.com/rust-lang/rust/pull/144210) This used to panic within the standard library. <a id="1.91.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`Path::file_prefix`](https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.file_prefix) - [`AtomicPtr::fetch_ptr_add`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html#method.fetch_ptr_add) - [`AtomicPtr::fetch_ptr_sub`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html#method.fetch_ptr_sub) - [`AtomicPtr::fetch_byte_add`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html#method.fetch_byte_add) - [`AtomicPtr::fetch_byte_sub`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html#method.fetch_byte_sub) - [`AtomicPtr::fetch_or`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html#method.fetch_or) - [`AtomicPtr::fetch_and`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html#method.fetch_and) - [`AtomicPtr::fetch_xor`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html#method.fetch_xor) - [`{integer}::strict_add`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_add) - [`{integer}::strict_sub`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_sub) - [`{integer}::strict_mul`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_mul) - [`{integer}::strict_div`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.strict_div) - [`{integer}::strict_div_euclid`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.strict_div_euclid) - [`{integer}::strict_rem`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.strict_rem) - [`{integer}::strict_rem_euclid`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.strict_rem_euclid) - [`{integer}::strict_neg`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_neg) - [`{integer}::strict_shl`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_shl) - [`{integer}::strict_shr`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_shr) - [`{integer}::strict_pow`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_pow) - [`i{N}::strict_add_unsigned`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.strict_add_unsigned) - [`i{N}::strict_sub_unsigned`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.strict_sub_unsigned) - [`i{N}::strict_abs`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.strict_abs) - [`u{N}::strict_add_signed`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_add_signed) - [`u{N}::strict_sub_signed`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_sub_signed) - [`PanicHookInfo::payload_as_str`](https://doc.rust-lang.org/stable/std/panic/struct.PanicHookInfo.html#method.payload_as_str) - [`core::iter::chain`](https://doc.rust-lang.org/stable/core/iter/fn.chain.html) - [`u{N}::checked_signed_diff`](https://doc.rust-lang.org/stable/std/primitive.u16.html#method.checked_signed_diff) - [`core::array::repeat`](https://doc.rust-lang.org/stable/core/array/fn.repeat.html) - [`PathBuf::add_extension`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.add_extension) - [`PathBuf::with_added_extension`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.with_added_extension) - [`Duration::from_mins`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_mins) - [`Duration::from_hours`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_hours) - [`impl PartialEq<str> for PathBuf`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#impl-PartialEq%3Cstr%3E-for-PathBuf) - [`impl PartialEq<String> for PathBuf`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#impl-PartialEq%3CString%3E-for-PathBuf) - [`impl PartialEq<str> for Path`](https://doc.rust-lang.org/stable/std/path/struct.Path.html#impl-PartialEq%3Cstr%3E-for-Path) - [`impl PartialEq<String> for Path`](https://doc.rust-lang.org/stable/std/path/struct.Path.html#impl-PartialEq%3CString%3E-for-Path) - [`impl PartialEq<PathBuf> for String`](https://doc.rust-lang.org/stable/std/string/struct.String.html#impl-PartialEq%3CPathBuf%3E-for-String) - [`impl PartialEq<Path> for String`](https://doc.rust-lang.org/stable/std/string/struct.String.html#impl-PartialEq%3CPath%3E-for-String) - [`impl PartialEq<PathBuf> for str`](https://doc.rust-lang.org/stable/std/primitive.str.html#impl-PartialEq%3CPathBuf%3E-for-str) - [`impl PartialEq<Path> for str`](https://doc.rust-lang.org/stable/std/primitive.str.html#impl-PartialEq%3CPath%3E-for-str) - [`Ipv4Addr::from_octets`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.from_octets) - [`Ipv6Addr::from_octets`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.from_octets) - [`Ipv6Addr::from_segments`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.from_segments) - [`impl<T> Default for Pin<Box<T>> where Box<T>: Default, T: ?Sized`](https://doc.rust-lang.org/stable/std/default/trait.Default.html#impl-Default-for-Pin%3CBox%3CT%3E%3E) - [`impl<T> Default for Pin<Rc<T>> where Rc<T>: Default, T: ?Sized`](https://doc.rust-lang.org/stable/std/default/trait.Default.html#impl-Default-for-Pin%3CRc%3CT%3E%3E) - [`impl<T> Default for Pin<Arc<T>> where Arc<T>: Default, T: ?Sized`](https://doc.rust-lang.org/stable/std/default/trait.Default.html#impl-Default-for-Pin%3CArc%3CT%3E%3E) - [`Cell::as_array_of_cells`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.as_array_of_cells) - [`u{N}::carrying_add`](https://doc.rust-lang.org/stable/std/primitive.u64.html#method.carrying_add) - [`u{N}::borrowing_sub`](https://doc.rust-lang.org/stable/std/primitive.u64.html#method.borrowing_sub) - [`u{N}::carrying_mul`](https://doc.rust-lang.org/stable/std/primitive.u64.html#method.carrying_mul) - [`u{N}::carrying_mul_add`](https://doc.rust-lang.org/stable/std/primitive.u64.html#method.carrying_mul_add) - [`BTreeMap::extract_if`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html#method.extract_if) - [`BTreeSet::extract_if`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeSet.html#method.extract_if) - [`impl Debug for windows::ffi::EncodeWide<'_>`](https://doc.rust-lang.org/stable/std/os/windows/ffi/struct.EncodeWide.html#impl-Debug-for-EncodeWide%3C'_%3E) - [`str::ceil_char_boundary`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.ceil_char_boundary) - [`str::floor_char_boundary`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.floor_char_boundary) - [`impl Sum for Saturating<u{N}>`](https://doc.rust-lang.org/stable/std/num/struct.Saturating.html#impl-Sum-for-Saturating%3Cu32%3E) - [`impl Sum<&Self> for Saturating<u{N}>`](https://doc.rust-lang.org/stable/std/num/struct.Saturating.html#impl-Sum%3C%26Saturating%3Cu32%3E%3E-for-Saturating%3Cu32%3E) - [`impl Product for Saturating<u{N}>`](https://doc.rust-lang.org/stable/std/num/struct.Saturating.html#impl-Product-for-Saturating%3Cu32%3E) - [`impl Product<&Self> for Saturating<u{N}>`](https://doc.rust-lang.org/stable/std/num/struct.Saturating.html#impl-Product%3C%26Saturating%3Cu32%3E%3E-for-Saturating%3Cu32%3E) These previously stable APIs are now stable in const contexts: - [`<[T; N]>::each_ref`](https://doc.rust-lang.org/stable/std/primitive.array.html#method.each_ref) - [`<[T; N]>::each_mut`](https://doc.rust-lang.org/stable/std/primitive.array.html#method.each_mut) - [`OsString::new`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.new) - [`PathBuf::new`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.new) - [`TypeId::of`](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.of) - [`ptr::with_exposed_provenance`](https://doc.rust-lang.org/stable/std/ptr/fn.with_exposed_provenance.html) - [`ptr::with_exposed_provenance_mut`](https://doc.rust-lang.org/stable/std/ptr/fn.with_exposed_provenance_mut.html) <a id="1.91.0-Cargo"></a> Cargo ----- - 🎉 Stabilize `build.build-dir`. This config sets the directory where intermediate build artifacts are stored. These artifacts are produced by Cargo and rustc during the build process. End users usually won't need to interact with them, and the layout inside `build-dir` is an implementation detail that may change without notice. ([config doc](https://doc.rust-lang.org/stable/cargo/reference/config.html#buildbuild-dir)) ([build cache doc](https://doc.rust-lang.org/stable/cargo/reference/build-cache.html)) [#15833](https://github.com/rust-lang/cargo/pull/15833) [#15840](https://github.com/rust-lang/cargo/pull/15840) - The `--target` flag and the `build.target` configuration can now take literal `"host-tuple"` string, which will internally be substituted by the host machine's target triple. [#15838](https://github.com/rust-lang/cargo/pull/15838) [#16003](https://github.com/rust-lang/cargo/pull/16003) [#16032](https://github.com/rust-lang/cargo/pull/16032) <a id="1.91.0-Rustdoc"></a> Rustdoc ----- - [In search results, rank doc aliases lower than non-alias items with the same name](https://github.com/rust-lang/rust/pull/145100) - [Raw pointers now work in type-based search like references](https://github.com/rust-lang/rust/pull/145731). This means you can now search for things like `*const u8 ->`, and additionally functions that take or return raw pointers will now display their signature properly in search results. <a id="1.91.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Always require coroutine captures to be drop-live](https://github.com/rust-lang/rust/pull/144156) - [Apple: Always pass SDK root when linking with `cc`, and pass it via `SDKROOT` env var](https://github.com/rust-lang/rust/pull/131477). This should fix linking issues with `rustc` running inside Xcode. Libraries in `/usr/local/lib` may no longer be linked automatically, if you develop or use a crate that relies on this, you should explicitly set `cargo::rustc-link-search=/usr/local/lib` in a `build.rs` script. - [Relaxed bounds in associated type bound position like in `TraitRef<AssocTy: ?Sized>` are now correctly forbidden](https://github.com/rust-lang/rust/pull/135331) - [Add unstable `#[sanitize(xyz = "on|off")]` built-in attribute that shadows procedural macros with the same name](https://github.com/rust-lang/rust/pull/142681) - [Fix the drop checker being more permissive for bindings declared with let-else](https://github.com/rust-lang/rust/pull/143028) - [Be more strict when parsing attributes, erroring on many invalid attributes](https://github.com/rust-lang/rust/pull/144689) - [Error on invalid `#[should_panic]` attributes](https://github.com/rust-lang/rust/pull/143808) - [Error on invalid `#[link]` attributes](https://github.com/rust-lang/rust/pull/143193) - [Mark all deprecation lints in name resolution as deny-by-default and also report in dependencies](https://github.com/rust-lang/rust/pull/143929) - The lint `semicolon_in_expressions_from_macros`, for `macro_rules!` macros in expression position that expand to end in a semicolon (`;`), is now deny-by-default. It was already warn-by-default, and a future compatibility warning (FCW) that warned even in dependencies. This lint will become a hard error in the future. - [Trait impl modifiers (e.g., `unsafe`, `!`, `default`) in inherent impls are no longer syntactically valid](https://github.com/rust-lang/rust/pull/144386) - [Start reporting future breakage for `ill_formed_attribute_input` in dependencies](https://github.com/rust-lang/rust/pull/144544) - [Restrict the scope of temporaries created by the macros `pin!`, `format_args!`, `write!`, and `writeln!` in `if let` scrutinees in Rust Edition 2024.](https://github.com/rust-lang/rust/pull/145342) This applies [Rust Edition 2024's `if let` temporary scope rules](https://doc.rust-lang.org/edition-guide/rust-2024/temporary-if-let-scope.html) to these temporaries, which previously could live past the `if` expression regardless of Edition. - [Invalid numeric literal suffixes in tuple indexing, tuple struct indexing, and struct field name positions are now correctly rejected](https://github.com/rust-lang/rust/pull/145463) - [Closures marked with the keyword `static` are now syntactically invalid](https://github.com/rust-lang/rust/pull/145604) - [Shebangs inside `--cfg` and `--check-cfg` arguments are no longer allowed](https://github.com/rust-lang/rust/pull/146211) - [Add future incompatibility lint for temporary lifetime shortening in Rust 1.92](https://github.com/rust-lang/rust/pull/147056) Cargo compatibility notes: - `cargo publish` no longer keeps `.crate` tarballs as final build artifacts when `build.build-dir` is set. These tarballs were previously included due to an oversight and are now treated as intermediate artifacts. To get `.crate` tarballs as final artifacts, use `cargo package`. In a future version, this change will apply regardless of `build.build-dir`. [#15910](https://github.com/rust-lang/cargo/pull/15910) - Adjust Cargo messages to match rustc diagnostic style. This changes some of the terminal colors used by Cargo messages. [#15928](https://github.com/rust-lang/cargo/pull/15928) - Tools and projects relying on the [internal details of Cargo's `build-dir`](https://doc.rust-lang.org/cargo/reference/build-cache.html) may not work for users changing their `build-dir` layout. For those doing so, we'd recommend proactively testing these cases particularly as we are considering changing the default location of the `build-dir` in the future ([cargo#16147](https://github.com/rust-lang/cargo/issues/16147)). If you can't migrate off of Cargo's internal details, we'd like to learn more about your use case as we prepare to change the layout of the `build-dir` ([cargo#15010](https://github.com/rust-lang/cargo/issues/15010)). <a id="1.91.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Update to LLVM 21](https://github.com/rust-lang/rust/pull/143684) Version 1.90.0 (2025-09-18) =========================== <a id="1.90-Language"></a> Language -------- - [Split up the `unknown_or_malformed_diagnostic_attributes` lint](https://github.com/rust-lang/rust/pull/140717). This lint has been split up into four finer-grained lints, with `unknown_or_malformed_diagnostic_attributes` now being the lint group that contains these lints: 1. `unknown_diagnostic_attributes`: unknown to the current compiler 2. `misplaced_diagnostic_attributes`: placed on the wrong item 3. `malformed_diagnostic_attributes`: malformed attribute syntax or options 4. `malformed_diagnostic_format_literals`: malformed format string literal - [Allow constants whose final value has references to mutable/external memory, but reject such constants as patterns](https://github.com/rust-lang/rust/pull/140942) - [Allow volatile access to non-Rust memory, including address 0](https://github.com/rust-lang/rust/pull/141260) <a id="1.90-Compiler"></a> Compiler -------- - [Use `lld` by default on `x86_64-unknown-linux-gnu`](https://github.com/rust-lang/rust/pull/140525). - [Tier 3 `musl` targets now link dynamically by default](https://github.com/rust-lang/rust/pull/144410). Affected targets: - `mips64-unknown-linux-muslabi64` - `powerpc64-unknown-linux-musl` - `powerpc-unknown-linux-musl` - `powerpc-unknown-linux-muslspe` - `riscv32gc-unknown-linux-musl` - `s390x-unknown-linux-musl` - `thumbv7neon-unknown-linux-musleabihf` <a id="1.90-Platform-Support"></a> Platform Support ---------------- - [Demote `x86_64-apple-darwin` to Tier 2 with host tools](https://github.com/rust-lang/rust/pull/145252) Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. [platform-support-doc]: https://doc.rust-lang.org/rustc/platform-support.html <a id="1.90-Libraries"></a> Libraries --------- - [Stabilize `u*::{checked,overflowing,saturating,wrapping}_sub_signed`](https://github.com/rust-lang/rust/issues/126043) - [Allow comparisons between `CStr`, `CString`, and `Cow<CStr>`](https://github.com/rust-lang/rust/pull/137268) - [Remove some unsized tuple impls since unsized tuples can't be constructed](https://github.com/rust-lang/rust/pull/138340) - [Set `MSG_NOSIGNAL` for `UnixStream`](https://github.com/rust-lang/rust/pull/140005) - [`proc_macro::Ident::new` now supports `$crate`.](https://github.com/rust-lang/rust/pull/141996) - [Guarantee the pointer returned from `Thread::into_raw` has at least 8 bytes of alignment](https://github.com/rust-lang/rust/pull/143859) <a id="1.90-Stabilized-APIs"></a> Stabilized APIs --------------- - [`u{n}::checked_sub_signed`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.checked_sub_signed) - [`u{n}::overflowing_sub_signed`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.overflowing_sub_signed) - [`u{n}::saturating_sub_signed`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.saturating_sub_signed) - [`u{n}::wrapping_sub_signed`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.wrapping_sub_signed) - [`impl Copy for IntErrorKind`](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-Copy-for-IntErrorKind) - [`impl Hash for IntErrorKind`](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-Hash-for-IntErrorKind) - [`impl PartialEq<&CStr> for CStr`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#impl-PartialEq%3C%26CStr%3E-for-CStr) - [`impl PartialEq<CString> for CStr`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#impl-PartialEq%3CCString%3E-for-CStr) - [`impl PartialEq<Cow<CStr>> for CStr`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#impl-PartialEq%3CCow%3C'_,+CStr%3E%3E-for-CStr) - [`impl PartialEq<&CStr> for CString`](https://doc.rust-lang.org/stable/std/ffi/struct.CString.html#impl-PartialEq%3C%26CStr%3E-for-CString) - [`impl PartialEq<CStr> for CString`](https://doc.rust-lang.org/stable/std/ffi/struct.CString.html#impl-PartialEq%3CCStr%3E-for-CString) - [`impl PartialEq<Cow<CStr>> for CString`](https://doc.rust-lang.org/stable/std/ffi/struct.CString.html#impl-PartialEq%3CCow%3C'_,+CStr%3E%3E-for-CString) - [`impl PartialEq<&CStr> for Cow<CStr>`](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html#impl-PartialEq%3C%26CStr%3E-for-Cow%3C'_,+CStr%3E) - [`impl PartialEq<CStr> for Cow<CStr>`](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html#impl-PartialEq%3CCStr%3E-for-Cow%3C'_,+CStr%3E) - [`impl PartialEq<CString> for Cow<CStr>`](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html#impl-PartialEq%3CCString%3E-for-Cow%3C'_,+CStr%3E) These previously stable APIs are now stable in const contexts: - [`<[T]>::reverse`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.reverse) - [`f32::floor`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.floor) - [`f32::ceil`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.ceil) - [`f32::trunc`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.trunc) - [`f32::fract`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.fract) - [`f32::round`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.round) - [`f32::round_ties_even`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.round_ties_even) - [`f64::floor`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.floor) - [`f64::ceil`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.ceil) - [`f64::trunc`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.trunc) - [`f64::fract`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.fract) - [`f64::round`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.round) - [`f64::round_ties_even`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.round_ties_even) <a id="1.90-Cargo"></a> Cargo ----- - [Add `http.proxy-cainfo` config for proxy certs](https://github.com/rust-lang/cargo/pull/15374/) - [Use `gix` for `cargo package`](https://github.com/rust-lang/cargo/pull/15534/) - [feat(publish): Stabilize multi-package publishing](https://github.com/rust-lang/cargo/pull/15636/) <a id="1.90-Rustdoc"></a> Rustdoc ----- - [Add ways to collapse all impl blocks](https://github.com/rust-lang/rust/pull/141663). Previously the "Summary" button and "-" keyboard shortcut would never collapse `impl` blocks, now they do when shift is held - [Display unsafe attributes with `unsafe()` wrappers](https://github.com/rust-lang/rust/pull/143662) <a id="1.90-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Use `lld` by default on `x86_64-unknown-linux-gnu`](https://github.com/rust-lang/rust/pull/140525). See also <https://blog.rust-lang.org/2025/09/01/rust-lld-on-1.90.0-stable/>. - [Make `core::iter::Fuse`'s `Default` impl construct `I::default()` internally as promised in the docs instead of always being empty](https://github.com/rust-lang/rust/pull/140985) - [Set `MSG_NOSIGNAL` for `UnixStream`](https://github.com/rust-lang/rust/pull/140005) This may change program behavior but results in the same behavior as other primitives (e.g., stdout, network sockets). Programs relying on signals to terminate them should update handling of sockets to handle errors on write by exiting. - [On Unix `std::env::home_dir` will use the fallback if the `HOME` environment variable is empty](https://github.com/rust-lang/rust/pull/141840) - We now [reject unsupported `extern "{abi}"`s consistently in all positions](https://github.com/rust-lang/rust/pull/142134). This primarily affects the use of implementing traits on an `extern "{abi}"` function pointer, like `extern "stdcall" fn()`, on a platform that doesn't support that, like aarch64-unknown-linux-gnu. Direct usage of these unsupported ABI strings by declaring or defining functions was already rejected, so this is only a change for consistency. - [const-eval: error when initializing a static writes to that static](https://github.com/rust-lang/rust/pull/143084) - [Check that the `proc_macro_derive` macro has correct arguments when applied to the crate root](https://github.com/rust-lang/rust/pull/143607) Version 1.89.0 (2025-08-07) ========================== <a id="1.89.0-Language"></a> Language -------- - [Stabilize explicitly inferred const arguments (`feature(generic_arg_infer)`)](https://github.com/rust-lang/rust/pull/141610) - [Add a warn-by-default `mismatched_lifetime_syntaxes` lint.](https://github.com/rust-lang/rust/pull/138677) This lint detects when the same lifetime is referred to by different syntax categories between function arguments and return values, which can be confusing to read, especially in unsafe code. This lint supersedes the warn-by-default `elided_named_lifetimes` lint. - [Expand `unpredictable_function_pointer_comparisons` to also lint on function pointer comparisons in external macros](https://github.com/rust-lang/rust/pull/134536) - [Make the `dangerous_implicit_autorefs` lint deny-by-default](https://github.com/rust-lang/rust/pull/141661) - [Stabilize the avx512 target features](https://github.com/rust-lang/rust/pull/138940) - [Stabilize `kl` and `widekl` target features for x86](https://github.com/rust-lang/rust/pull/140766) - [Stabilize `sha512`, `sm3` and `sm4` target features for x86](https://github.com/rust-lang/rust/pull/140767) - [Stabilize LoongArch target features `f`, `d`, `frecipe`, `lasx`, `lbt`, `lsx`, and `lvz`](https://github.com/rust-lang/rust/pull/135015) - [Remove `i128` and `u128` from `improper_ctypes_definitions`](https://github.com/rust-lang/rust/pull/137306) - [Stabilize `repr128` (`#[repr(u128)]`, `#[repr(i128)]`)](https://github.com/rust-lang/rust/pull/138285) - [Allow `#![doc(test(attr(..)))]` everywhere](https://github.com/rust-lang/rust/pull/140560) - [Extend temporary lifetime extension to also go through tuple struct and tuple variant constructors](https://github.com/rust-lang/rust/pull/140593) - [`extern "C"` functions on the `wasm32-unknown-unknown` target now have a standards compliant ABI](https://blog.rust-lang.org/2025/04/04/c-abi-changes-for-wasm32-unknown-unknown/) <a id="1.89.0-Compiler"></a> Compiler -------- - [Default to non-leaf frame pointers on aarch64-linux](https://github.com/rust-lang/rust/pull/140832) - [Enable non-leaf frame pointers for Arm64EC Windows](https://github.com/rust-lang/rust/pull/140862) - [Set Apple frame pointers by architecture](https://github.com/rust-lang/rust/pull/141797) <a id="1.89.0-Platform-Support"></a> Platform Support ---------------- - [Add new Tier-3 targets `loongarch32-unknown-none` and `loongarch32-unknown-none-softfloat`](https://github.com/rust-lang/rust/pull/142053) - [`x86_64-apple-darwin` is in the process of being demoted to Tier 2 with host tools](https://github.com/rust-lang/rfcs/pull/3841) Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. [platform-support-doc]: https://doc.rust-lang.org/rustc/platform-support.html <a id="1.89.0-Libraries"></a> Libraries --------- - [Specify the base path for `file!`](https://github.com/rust-lang/rust/pull/134442) - [Allow storing `format_args!()` in a variable](https://github.com/rust-lang/rust/pull/140748) - [Add `#[must_use]` to `[T; N]::map`](https://github.com/rust-lang/rust/pull/140957) - [Implement `DerefMut` for `Lazy{Cell,Lock}`](https://github.com/rust-lang/rust/pull/129334) - [Implement `Default` for `array::IntoIter`](https://github.com/rust-lang/rust/pull/141574) - [Implement `Clone` for `slice::ChunkBy`](https://github.com/rust-lang/rust/pull/138016) - [Implement `io::Seek` for `io::Take`](https://github.com/rust-lang/rust/pull/138023) <a id="1.89.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`NonZero<char>`](https://doc.rust-lang.org/stable/std/num/struct.NonZero.html) - Many intrinsics for x86, not enumerated here - [AVX512 intrinsics](https://github.com/rust-lang/rust/issues/111137) - [`SHA512`, `SM3` and `SM4` intrinsics](https://github.com/rust-lang/rust/issues/126624) - [`File::lock`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.lock) - [`File::lock_shared`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.lock_shared) - [`File::try_lock`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.try_lock) - [`File::try_lock_shared`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.try_lock_shared) - [`File::unlock`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.unlock) - [`NonNull::from_ref`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.from_ref) - [`NonNull::from_mut`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.from_mut) - [`NonNull::without_provenance`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.without_provenance) - [`NonNull::with_exposed_provenance`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.with_exposed_provenance) - [`NonNull::expose_provenance`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.expose_provenance) - [`OsString::leak`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.leak) - [`PathBuf::leak`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.leak) - [`Result::flatten`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.flatten) - [`std::os::linux::net::TcpStreamExt::quickack`](https://doc.rust-lang.org/stable/std/os/linux/net/trait.TcpStreamExt.html#tymethod.quickack) - [`std::os::linux::net::TcpStreamExt::set_quickack`](https://doc.rust-lang.org/stable/std/os/linux/net/trait.TcpStreamExt.html#tymethod.set_quickack) These previously stable APIs are now stable in const contexts: - [`<[T; N]>::as_mut_slice`](https://doc.rust-lang.org/stable/std/primitive.array.html#method.as_mut_slice) - [`<[u8]>::eq_ignore_ascii_case`](https://doc.rust-lang.org/stable/std/primitive.slice.html#impl-%5Bu8%5D/method.eq_ignore_ascii_case) - [`str::eq_ignore_ascii_case`](https://doc.rust-lang.org/stable/std/primitive.str.html#impl-str/method.eq_ignore_ascii_case) <a id="1.89.0-Cargo"></a> Cargo ----- - [`cargo fix` and `cargo clippy --fix` now default to the same Cargo target selection as other build commands.](https://github.com/rust-lang/cargo/pull/15192/) Previously it would apply to all targets (like binaries, examples, tests, etc.). The `--edition` flag still applies to all targets. - [Stabilize doctest-xcompile.](https://github.com/rust-lang/cargo/pull/15462/) Doctests are now tested when cross-compiling. Just like other tests, it will use the [`runner` setting](https://doc.rust-lang.org/cargo/reference/config.html#targettriplerunner) to run the tests. If you need to disable tests for a target, you can use the [ignore doctest attribute](https://doc.rust-lang.org/rustdoc/write-documentation/documentation-tests.html#ignoring-targets) to specify the targets to ignore. <a id="1.89.0-Rustdoc"></a> Rustdoc ----- - [On mobile, make the sidebar full width and linewrap](https://github.com/rust-lang/rust/pull/139831). This makes long section and item names much easier to deal with on mobile. <a id="1.89.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Make `missing_fragment_specifier` an unconditional error](https://github.com/rust-lang/rust/pull/128425) - [Enabling the `neon` target feature on `aarch64-unknown-none-softfloat` causes a warning](https://github.com/rust-lang/rust/pull/135160) because mixing code with and without that target feature is not properly supported by LLVM - [Sized Hierarchy: Part I](https://github.com/rust-lang/rust/pull/137944) - Introduces a small breaking change affecting `?Sized` bounds on impls on recursive types which contain associated type projections. It is not expected to affect any existing published crates. Can be fixed by refactoring the involved types or opting into the `sized_hierarchy` unstable feature. See the [FCP report](https://github.com/rust-lang/rust/pull/137944#issuecomment-2912207485) for a code example. - The warn-by-default `elided_named_lifetimes` lint is [superseded by the warn-by-default `mismatched_lifetime_syntaxes` lint.](https://github.com/rust-lang/rust/pull/138677) - [Error on recursive opaque types earlier in the type checker](https://github.com/rust-lang/rust/pull/139419) - [Type inference side effects from requiring element types of array repeat expressions are `Copy` are now only available at the end of type checking](https://github.com/rust-lang/rust/pull/139635) - [The deprecated accidentally-stable `std::intrinsics::{copy,copy_nonoverlapping,write_bytes}` are now proper intrinsics](https://github.com/rust-lang/rust/pull/139916). There are no debug assertions guarding against UB, and they cannot be coerced to function pointers. - [Remove long-deprecated `std::intrinsics::drop_in_place`](https://github.com/rust-lang/rust/pull/140151) - [Make well-formedness predicates no longer coinductive](https://github.com/rust-lang/rust/pull/140208) - [Remove hack when checking impl method compatibility](https://github.com/rust-lang/rust/pull/140557) - [Remove unnecessary type inference due to built-in trait object impls](https://github.com/rust-lang/rust/pull/141352) - [Lint against "stdcall", "fastcall", and "cdecl" on non-x86-32 targets](https://github.com/rust-lang/rust/pull/141435) - [Future incompatibility warnings relating to the never type (`!`) are now reported in dependencies](https://github.com/rust-lang/rust/pull/141937) - [Ensure `std::ptr::copy_*` intrinsics also perform the static self-init checks](https://github.com/rust-lang/rust/pull/142575) - [`extern "C"` functions on the `wasm32-unknown-unknown` target now have a standards compliant ABI](https://blog.rust-lang.org/2025/04/04/c-abi-changes-for-wasm32-unknown-unknown/) <a id="1.89.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Correctly un-remap compiler sources paths with the `rustc-dev` component](https://github.com/rust-lang/rust/pull/142377) Version 1.88.0 (2025-06-26) ========================== <a id="1.88.0-Language"></a> Language -------- - [Stabilize `#![feature(let_chains)]` in the 2024 edition.](https://github.com/rust-lang/rust/pull/132833) This feature allows `&&`-chaining `let` statements inside `if` and `while`, allowing intermixture with boolean expressions. The patterns inside the `let` sub-expressions can be irrefutable or refutable. - [Stabilize `#![feature(naked_functions)]`.](https://github.com/rust-lang/rust/pull/134213) Naked functions allow writing functions with no compiler-generated epilogue and prologue, allowing full control over the generated assembly for a particular function. - [Stabilize `#![feature(cfg_boolean_literals)]`.](https://github.com/rust-lang/rust/pull/138632) This allows using boolean literals as `cfg` predicates, e.g. `#[cfg(true)]` and `#[cfg(false)]`. - [Fully de-stabilize the `#[bench]` attribute](https://github.com/rust-lang/rust/pull/134273). Usage of `#[bench]` without `#![feature(custom_test_frameworks)]` already triggered a deny-by-default future-incompatibility lint since Rust 1.77, but will now become a hard error. - [Add warn-by-default `dangerous_implicit_autorefs` lint against implicit autoref of raw pointer dereference.](https://github.com/rust-lang/rust/pull/123239) The lint [will be bumped to deny-by-default](https://github.com/rust-lang/rust/pull/141661) in the next version of Rust. - [Add `invalid_null_arguments` lint to prevent invalid usage of null pointers.](https://github.com/rust-lang/rust/pull/119220) This lint is uplifted from `clippy::invalid_null_ptr_usage`. - [Change trait impl candidate preference for builtin impls and trivial where-clauses.](https://github.com/rust-lang/rust/pull/138176) - [Check types of generic const parameter defaults](https://github.com/rust-lang/rust/pull/139646) <a id="1.88.0-Compiler"></a> Compiler -------- - [Stabilize `-Cdwarf-version` for selecting the version of DWARF debug information to generate.](https://github.com/rust-lang/rust/pull/136926) <a id="1.88.0-Platform-Support"></a> Platform Support ---------------- - [Demote `i686-pc-windows-gnu` to Tier 2.](https://blog.rust-lang.org/2025/05/26/demoting-i686-pc-windows-gnu/) Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. [platform-support-doc]: https://doc.rust-lang.org/rustc/platform-support.html <a id="1.88.0-Libraries"></a> Libraries --------- - [Remove backticks from `#[should_panic]` test failure message.](https://github.com/rust-lang/rust/pull/136160) - [Guarantee that `[T; N]::from_fn` is generated in order of increasing indices.](https://github.com/rust-lang/rust/pull/139099), for those passing it a stateful closure. - [The libtest flag `--nocapture` is deprecated in favor of the more consistent `--no-capture` flag.](https://github.com/rust-lang/rust/pull/139224) - [Guarantee that `{float}::NAN` is a quiet NaN.](https://github.com/rust-lang/rust/pull/139483) <a id="1.88.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`Cell::update`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.update) - [`impl Default for *const T`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#impl-Default-for-*const+T) - [`impl Default for *mut T`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#impl-Default-for-*mut+T) - [`HashMap::extract_if`](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html#method.extract_if) - [`HashSet::extract_if`](https://doc.rust-lang.org/stable/std/collections/struct.HashSet.html#method.extract_if) - [`hint::select_unpredictable`](https://doc.rust-lang.org/stable/std/hint/fn.select_unpredictable.html) - [`proc_macro::Span::line`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.line) - [`proc_macro::Span::column`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.column) - [`proc_macro::Span::start`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.start) - [`proc_macro::Span::end`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.end) - [`proc_macro::Span::file`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.file) - [`proc_macro::Span::local_file`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.local_file) - [`<[T]>::as_chunks`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_chunks) - [`<[T]>::as_chunks_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_chunks_mut) - [`<[T]>::as_chunks_unchecked`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_chunks_unchecked) - [`<[T]>::as_chunks_unchecked_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_chunks_unchecked_mut) - [`<[T]>::as_rchunks`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_rchunks) - [`<[T]>::as_rchunks_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_rchunks_mut) - [`mod ffi::c_str`](https://doc.rust-lang.org/stable/std/ffi/c_str/index.html) These previously stable APIs are now stable in const contexts: - [`NonNull<T>::replace`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.replace) - [`<*mut T>::replace`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.replace) - [`std::ptr::swap_nonoverlapping`](https://doc.rust-lang.org/stable/std/ptr/fn.swap_nonoverlapping.html) - [`Cell::replace`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.replace) - [`Cell::get`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.get) - [`Cell::get_mut`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.get_mut) - [`Cell::from_mut`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.from_mut) - [`Cell::as_slice_of_cells`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.as_slice_of_cells) <a id="1.88.0-Cargo"></a> Cargo ----- - [Stabilize automatic garbage collection.](https://github.com/rust-lang/cargo/pull/14287/) - [use `zlib-rs` for gzip compression in rust code](https://github.com/rust-lang/cargo/pull/15417/) <a id="1.88.0-Rustdoc"></a> Rustdoc ----- - [Doctests can be ignored based on target names using `ignore-*` attributes.](https://github.com/rust-lang/rust/pull/137096) - [Stabilize the `--test-runtool` and `--test-runtool-arg` CLI options to specify a program (like qemu) and its arguments to run a doctest.](https://github.com/rust-lang/rust/pull/137096) <a id="1.88.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Finish changing the internal representation of pasted tokens](https://github.com/rust-lang/rust/pull/124141). Certain invalid declarative macros that were previously accepted in obscure circumstances are now correctly rejected by the compiler. Use of a `tt` fragment specifier can often fix these macros. - [Fully de-stabilize the `#[bench]` attribute](https://github.com/rust-lang/rust/pull/134273). Usage of `#[bench]` without `#![feature(custom_test_frameworks)]` already triggered a deny-by-default future-incompatibility lint since Rust 1.77, but will now become a hard error. - [Fix borrow checking some always-true patterns.](https://github.com/rust-lang/rust/pull/139042) The borrow checker was overly permissive in some cases, allowing programs that shouldn't have compiled. - [Update the minimum external LLVM to 19.](https://github.com/rust-lang/rust/pull/139275) - [Make it a hard error to use a vector type with a non-Rust ABI without enabling the required target feature.](https://github.com/rust-lang/rust/pull/139309) Version 1.87.0 (2025-05-15) ========================== <a id="1.87.0-Language"></a> Language -------- - [Stabilize `asm_goto` feature](https://github.com/rust-lang/rust/pull/133870) - [Allow parsing open beginning ranges (`..EXPR`) after unary operators `!`, `-`, and `*`](https://github.com/rust-lang/rust/pull/134900). - [Don't require method impls for methods with `Self: Sized` bounds in `impl`s for unsized types](https://github.com/rust-lang/rust/pull/135480) - [Stabilize `feature(precise_capturing_in_traits)` allowing `use<...>` bounds on return position `impl Trait` in `trait`s](https://github.com/rust-lang/rust/pull/138128) <a id="1.87.0-Compiler"></a> Compiler -------- - [x86: make SSE2 required for i686 targets and use it to pass SIMD types](https://github.com/rust-lang/rust/pull/135408) <a id="1.87.0-Platform-Support"></a> Platform Support ---------------- - [Remove `i586-pc-windows-msvc` target](https://github.com/rust-lang/rust/pull/137957) Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. [platform-support-doc]: https://doc.rust-lang.org/rustc/platform-support.html <a id="1.87.0-Libraries"></a> Libraries --------- - [Stabilize the anonymous pipe API](https://github.com/rust-lang/rust/issues/127154) - [Add support for unbounded left/right shift operations](https://github.com/rust-lang/rust/issues/129375) - [Print pointer metadata in `Debug` impl of raw pointers](https://github.com/rust-lang/rust/pull/135080) - [`Vec::with_capacity` guarantees it allocates with the amount requested, even if `Vec::capacity` returns a different number.](https://github.com/rust-lang/rust/pull/135933) - Most `std::arch` intrinsics which don't take pointer arguments can now be called from safe code if the caller has the appropriate target features already enabled (https://github.com/rust-lang/stdarch/pull/1714, https://github.com/rust-lang/stdarch/pull/1716, https://github.com/rust-lang/stdarch/pull/1717) - [Undeprecate `env::home_dir`](https://github.com/rust-lang/rust/pull/137327) - [Denote `ControlFlow` as `#[must_use]`](https://github.com/rust-lang/rust/pull/137449) - [Macros such as `assert_eq!` and `vec!` now support `const {...}` expressions](https://github.com/rust-lang/rust/pull/138162) <a id="1.87.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`Vec::extract_if`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.extract_if) - [`vec::ExtractIf`](https://doc.rust-lang.org/stable/std/vec/struct.ExtractIf.html) - [`LinkedList::extract_if`](https://doc.rust-lang.org/stable/std/collections/struct.LinkedList.html#method.extract_if) - [`linked_list::ExtractIf`](https://doc.rust-lang.org/stable/std/collections/linked_list/struct.ExtractIf.html) - [`<[T]>::split_off`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_off) - [`<[T]>::split_off_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_off_mut) - [`<[T]>::split_off_first`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_off_first) - [`<[T]>::split_off_first_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_off_first_mut) - [`<[T]>::split_off_last`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_off_last) - [`<[T]>::split_off_last_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_off_last_mut) - [`String::extend_from_within`](https://doc.rust-lang.org/stable/alloc/string/struct.String.html#method.extend_from_within) - [`os_str::Display`](https://doc.rust-lang.org/stable/std/ffi/os_str/struct.Display.html) - [`OsString::display`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.display) - [`OsStr::display`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html#method.display) - [`io::pipe`](https://doc.rust-lang.org/stable/std/io/fn.pipe.html) - [`io::PipeReader`](https://doc.rust-lang.org/stable/std/io/struct.PipeReader.html) - [`io::PipeWriter`](https://doc.rust-lang.org/stable/std/io/struct.PipeWriter.html) - [`impl From<PipeReader> for OwnedHandle`](https://doc.rust-lang.org/stable/std/os/windows/io/struct.OwnedHandle.html#impl-From%3CPipeReader%3E-for-OwnedHandle) - [`impl From<PipeWriter> for OwnedHandle`](https://doc.rust-lang.org/stable/std/os/windows/io/struct.OwnedHandle.html#impl-From%3CPipeWriter%3E-for-OwnedHandle) - [`impl From<PipeReader> for Stdio`](https://doc.rust-lang.org/stable/std/process/struct.Stdio.html) - [`impl From<PipeWriter> for Stdio`](https://doc.rust-lang.org/stable/std/process/struct.Stdio.html#impl-From%3CPipeWriter%3E-for-Stdio) - [`impl From<PipeReader> for OwnedFd`](https://doc.rust-lang.org/stable/std/os/fd/struct.OwnedFd.html#impl-From%3CPipeReader%3E-for-OwnedFd) - [`impl From<PipeWriter> for OwnedFd`](https://doc.rust-lang.org/stable/std/os/fd/struct.OwnedFd.html#impl-From%3CPipeWriter%3E-for-OwnedFd) - [`Box<MaybeUninit<T>>::write`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.write) - [`impl TryFrom<Vec<u8>> for String`](https://doc.rust-lang.org/stable/std/string/struct.String.html#impl-TryFrom%3CVec%3Cu8%3E%3E-for-String) - [`<*const T>::offset_from_unsigned`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.offset_from_unsigned) - [`<*const T>::byte_offset_from_unsigned`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.byte_offset_from_unsigned) - [`<*mut T>::offset_from_unsigned`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.offset_from_unsigned-1) - [`<*mut T>::byte_offset_from_unsigned`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.byte_offset_from_unsigned-1) - [`NonNull::offset_from_unsigned`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.offset_from_unsigned) - [`NonNull::byte_offset_from_unsigned`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.byte_offset_from_unsigned) - [`<uN>::cast_signed`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.cast_signed) - [`NonZero::<uN>::cast_signed`](https://doc.rust-lang.org/stable/std/num/struct.NonZero.html#method.cast_signed-5). - [`<iN>::cast_unsigned`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.cast_unsigned). - [`NonZero::<iN>::cast_unsigned`](https://doc.rust-lang.org/stable/std/num/struct.NonZero.html#method.cast_unsigned-5). - [`<uN>::is_multiple_of`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.is_multiple_of) - [`<uN>::unbounded_shl`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.unbounded_shl) - [`<uN>::unbounded_shr`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.unbounded_shr) - [`<iN>::unbounded_shl`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.unbounded_shl) - [`<iN>::unbounded_shr`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.unbounded_shr) - [`<iN>::midpoint`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.midpoint) - [`<str>::from_utf8`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.from_utf8) - [`<str>::from_utf8_mut`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.from_utf8_mut) - [`<str>::from_utf8_unchecked`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.from_utf8_unchecked) - [`<str>::from_utf8_unchecked_mut`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.from_utf8_unchecked_mut) These previously stable APIs are now stable in const contexts: - [`core::str::from_utf8_mut`](https://doc.rust-lang.org/stable/std/str/fn.from_utf8_mut.html) - [`<[T]>::copy_from_slice`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.copy_from_slice) - [`SocketAddr::set_ip`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.set_ip) - [`SocketAddr::set_port`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.set_port), - [`SocketAddrV4::set_ip`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.set_ip) - [`SocketAddrV4::set_port`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.set_port), - [`SocketAddrV6::set_ip`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.set_ip) - [`SocketAddrV6::set_port`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.set_port) - [`SocketAddrV6::set_flowinfo`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.set_flowinfo) - [`SocketAddrV6::set_scope_id`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.set_scope_id) - [`char::is_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) - [`char::is_whitespace`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_whitespace) - [`<[[T; N]]>::as_flattened`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_flattened) - [`<[[T; N]]>::as_flattened_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_flattened_mut) - [`String::into_bytes`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.into_bytes) - [`String::as_str`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.as_str) - [`String::capacity`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.capacity) - [`String::as_bytes`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.as_bytes) - [`String::len`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.len) - [`String::is_empty`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.is_empty) - [`String::as_mut_str`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.as_mut_str) - [`String::as_mut_vec`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.as_mut_vec) - [`Vec::as_ptr`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.as_ptr) - [`Vec::as_slice`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.as_slice) - [`Vec::capacity`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.capacity) - [`Vec::len`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.len) - [`Vec::is_empty`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.is_empty) - [`Vec::as_mut_slice`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.as_mut_slice) - [`Vec::as_mut_ptr`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.as_mut_ptr) <a id="1.87.0-Cargo"></a> Cargo ----- - [Add terminal integration via ANSI OSC 9;4 sequences](https://github.com/rust-lang/cargo/pull/14615/) - [chore: bump openssl to v3](https://github.com/rust-lang/cargo/pull/15232/) - [feat(package): add --exclude-lockfile flag](https://github.com/rust-lang/cargo/pull/15234/) <a id="1.87.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Rust now raises an error for macro invocations inside the `#![crate_name]` attribute](https://github.com/rust-lang/rust/pull/127581) - [Unstable fields are now always considered to be inhabited](https://github.com/rust-lang/rust/pull/133889) - [Macro arguments of unary operators followed by open beginning ranges may now be matched differently](https://github.com/rust-lang/rust/pull/134900) - [Make `Debug` impl of raw pointers print metadata if present](https://github.com/rust-lang/rust/pull/135080) - [Warn against function pointers using unsupported ABI strings in dependencies](https://github.com/rust-lang/rust/pull/135767) - [Associated types on `dyn` types are no longer deduplicated](https://github.com/rust-lang/rust/pull/136458) - [Forbid attributes on `..` inside of struct patterns (`let Struct { #[attribute] .. }) =`](https://github.com/rust-lang/rust/pull/136490) - [Make `ptr_cast_add_auto_to_object` lint into hard error](https://github.com/rust-lang/rust/pull/136764) - Many `std::arch` intrinsics are now safe to call in some contexts, there may now be new `unused_unsafe` warnings in existing codebases. - [Limit `width` and `precision` formatting options to 16 bits on all targets](https://github.com/rust-lang/rust/pull/136932) - [Turn order dependent trait objects future incompat warning into a hard error](https://github.com/rust-lang/rust/pull/136968) - [Denote `ControlFlow` as `#[must_use]`](https://github.com/rust-lang/rust/pull/137449) - [Windows: The standard library no longer links `advapi32`, except on win7.](https://github.com/rust-lang/rust/pull/138233) Code such as C libraries that were relying on this assumption may need to explicitly link advapi32. - [Proc macros can no longer observe expanded `cfg(true)` attributes.](https://github.com/rust-lang/rust/pull/138844) - [Start changing the internal representation of pasted tokens](https://github.com/rust-lang/rust/pull/124141). Certain invalid declarative macros that were previously accepted in obscure circumstances are now correctly rejected by the compiler. Use of a `tt` fragment specifier can often fix these macros. - [Don't allow flattened format_args in const.](https://github.com/rust-lang/rust/pull/139624) <a id="1.87.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Update to LLVM 20](https://github.com/rust-lang/rust/pull/135763) Version 1.86.0 (2025-04-03) ========================== <a id="1.86.0-Language"></a> Language -------- - [Stabilize upcasting trait objects to supertraits.](https://github.com/rust-lang/rust/pull/134367) - [Allow safe functions to be marked with the `#[target_feature]` attribute.](https://github.com/rust-lang/rust/pull/134090) - [The `missing_abi` lint now warns-by-default.](https://github.com/rust-lang/rust/pull/132397) - Rust now lints about double negations, to catch cases that might have intended to be a prefix decrement operator (`--x`) as written in other languages. This was previously a clippy lint, `clippy::double_neg`, and is [now available directly in Rust as `double_negations`.](https://github.com/rust-lang/rust/pull/126604) - [More pointers are now detected as definitely not-null based on their alignment in const eval.](https://github.com/rust-lang/rust/pull/133700) - [Empty `repr()` attribute applied to invalid items are now correctly rejected.](https://github.com/rust-lang/rust/pull/133925) - [Inner attributes `#![test]` and `#![rustfmt::skip]` are no longer accepted in more places than intended.](https://github.com/rust-lang/rust/pull/134276) <a id="1.86.0-Compiler"></a> Compiler -------- - [Debug-assert that raw pointers are non-null on access.](https://github.com/rust-lang/rust/pull/134424) - [Change `-O` to mean `-C opt-level=3` instead of `-C opt-level=2` to match Cargo's defaults.](https://github.com/rust-lang/rust/pull/135439) - [Fix emission of `overflowing_literals` under certain macro environments.](https://github.com/rust-lang/rust/pull/136393) <a id="1.86.0-Platform-Support"></a> Platform Support ---------------- - [Replace `i686-unknown-redox` target with `i586-unknown-redox`.](https://github.com/rust-lang/rust/pull/136698) - [Increase baseline CPU of `i686-unknown-hurd-gnu` to Pentium 4.](https://github.com/rust-lang/rust/pull/136700) - New tier 3 targets: - [`{aarch64-unknown,x86_64-pc}-nto-qnx710_iosock`](https://github.com/rust-lang/rust/pull/133631). For supporting Neutrino QNX 7.1 with `io-socket` network stack. - [`{aarch64-unknown,x86_64-pc}-nto-qnx800`](https://github.com/rust-lang/rust/pull/133631). For supporting Neutrino QNX 8.0 (`no_std`-only). - [`{x86_64,i686}-win7-windows-gnu`](https://github.com/rust-lang/rust/pull/134609). Intended for backwards compatibility with Windows 7. `{x86_64,i686}-win7-windows-msvc` are the Windows MSVC counterparts that already exist as Tier 3 targets. - [`amdgcn-amd-amdhsa`](https://github.com/rust-lang/rust/pull/134740). - [`x86_64-pc-cygwin`](https://github.com/rust-lang/rust/pull/134999). - [`{mips,mipsel}-mti-none-elf`](https://github.com/rust-lang/rust/pull/135074). Initial bare-metal support. - [`m68k-unknown-none-elf`](https://github.com/rust-lang/rust/pull/135085). - [`armv7a-nuttx-{eabi,eabihf}`, `aarch64-unknown-nuttx`, and `thumbv7a-nuttx-{eabi,eabihf}`](https://github.com/rust-lang/rust/pull/135757). Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. <a id="1.86.0-Libraries"></a> Libraries --------- - The type of `FromBytesWithNulError` in `CStr::from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, FromBytesWithNulError>` was [changed from an opaque struct to an enum](https://github.com/rust-lang/rust/pull/134143), allowing users to examine why the conversion failed. - [Remove `RustcDecodable` and `RustcEncodable`.](https://github.com/rust-lang/rust/pull/134272) - [Deprecate libtest's `--logfile` option.](https://github.com/rust-lang/rust/pull/134283) - [On recent versions of Windows, `std::fs::remove_file` will now remove read-only files.](https://github.com/rust-lang/rust/pull/134679) <a id="1.86.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`{float}::next_down`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.next_down) - [`{float}::next_up`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.next_up) - [`<[_]>::get_disjoint_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.get_disjoint_mut) - [`<[_]>::get_disjoint_unchecked_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.get_disjoint_unchecked_mut) - [`slice::GetDisjointMutError`](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html) - [`HashMap::get_disjoint_mut`](https://doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#method.get_disjoint_mut) - [`HashMap::get_disjoint_unchecked_mut`](https://doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#method.get_disjoint_unchecked_mut) - [`NonZero::count_ones`](https://doc.rust-lang.org/stable/std/num/struct.NonZero.html#method.count_ones) - [`Vec::pop_if`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.pop_if) - [`sync::Once::wait`](https://doc.rust-lang.org/stable/std/sync/struct.Once.html#method.wait) - [`sync::Once::wait_force`](https://doc.rust-lang.org/stable/std/sync/struct.Once.html#method.wait_force) - [`sync::OnceLock::wait`](https://doc.rust-lang.org/stable/std/sync/struct.OnceLock.html#method.wait) These APIs are now stable in const contexts: - [`hint::black_box`](https://doc.rust-lang.org/stable/std/hint/fn.black_box.html) - [`io::Cursor::get_mut`](https://doc.rust-lang.org/stable/std/io/struct.Cursor.html#method.get_mut) - [`io::Cursor::set_position`](https://doc.rust-lang.org/stable/std/io/struct.Cursor.html#method.set_position) - [`str::is_char_boundary`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.is_char_boundary) - [`str::split_at`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.split_at) - [`str::split_at_checked`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.split_at_checked) - [`str::split_at_mut`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.split_at_mut) - [`str::split_at_mut_checked`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.split_at_mut_checked) <a id="1.86.0-Cargo"></a> Cargo ----- - [When merging, replace rather than combine configuration keys that refer to a program path and its arguments.](https://github.com/rust-lang/cargo/pull/15066/) - [Error if both `--package` and `--workspace` are passed but the requested package is missing.](https://github.com/rust-lang/cargo/pull/15071/) This was previously silently ignored, which was considered a bug since missing packages should be reported. - [Deprecate the token argument in `cargo login` to avoid shell history leaks.](https://github.com/rust-lang/cargo/pull/15057/) - [Simplify the implementation of `SourceID` comparisons.](https://github.com/rust-lang/cargo/pull/14980/) This may potentially change behavior if the canonicalized URL compares differently in alternative registries. <a id="1.86.0-Rustdoc"></a> Rustdoc ----- - [Add a sans-serif font setting.](https://github.com/rust-lang/rust/pull/133636) <a id="1.86.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [The `wasm_c_abi` future compatibility warning is now a hard error.](https://github.com/rust-lang/rust/pull/133951) Users of `wasm-bindgen` should upgrade to at least version 0.2.89, otherwise compilation will fail. - [Remove long-deprecated no-op attributes `#![no_start]` and `#![crate_id]`.](https://github.com/rust-lang/rust/pull/134300) - [The future incompatibility lint `cenum_impl_drop_cast` has been made into a hard error.](https://github.com/rust-lang/rust/pull/135964) This means it is now an error to cast a field-less enum to an integer if the enum implements `Drop`. - [SSE2 is now required for "i686" 32-bit x86 hard-float targets; disabling it causes a warning that will become a hard error eventually.](https://github.com/rust-lang/rust/pull/137037) To compile for pre-SSE2 32-bit x86, use a "i586" target instead. <a id="1.86.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Build the rustc on AArch64 Linux with ThinLTO + PGO.](https://github.com/rust-lang/rust/pull/133807) The ARM 64-bit compiler (AArch64) on Linux is now optimized with ThinLTO and PGO, similar to the optimizations we have already performed for the x86-64 compiler on Linux. This should make it up to 30% faster. Version 1.85.1 (2025-03-18) ========================== <a id="1.85.1"></a> - [Fix the doctest-merging feature of the 2024 Edition.](https://github.com/rust-lang/rust/pull/137899/) - [Relax some `target_feature` checks when generating docs.](https://github.com/rust-lang/rust/pull/137632/) - [Fix errors in `std::fs::rename` on Windows 10, version 1607.](https://github.com/rust-lang/rust/pull/137528/) - [Downgrade bootstrap `cc` to fix custom targets.](https://github.com/rust-lang/rust/pull/137460/) - [Skip submodule updates when building Rust from a source tarball.](https://github.com/rust-lang/rust/pull/137338/) Version 1.85.0 (2025-02-20) ========================== <a id="1.85.0-Language"></a> Language -------- - [The 2024 Edition is now stable.](https://github.com/rust-lang/rust/pull/133349) See [the edition guide](https://doc.rust-lang.org/nightly/edition-guide/rust-2024/index.html) for more details. - [Stabilize async closures](https://github.com/rust-lang/rust/pull/132706) See [RFC 3668](https://rust-lang.github.io/rfcs/3668-async-closures.html) for more details. - [Stabilize `#[diagnostic::do_not_recommend]`](https://github.com/rust-lang/rust/pull/132056) - [Add `unpredictable_function_pointer_comparisons` lint to warn against function pointer comparisons](https://github.com/rust-lang/rust/pull/118833) - [Lint on combining `#[no_mangle]` and `#[export_name]` attributes.](https://github.com/rust-lang/rust/pull/131558) <a id="1.85.0-Compiler"></a> Compiler -------- - [The unstable flag `-Zpolymorphize` has been removed](https://github.com/rust-lang/rust/pull/133883), see https://github.com/rust-lang/compiler-team/issues/810 for some background. <a id="1.85.0-Platform-Support"></a> Platform Support ---------------- - [Promote `powerpc64le-unknown-linux-musl` to tier 2 with host tools](https://github.com/rust-lang/rust/pull/133801) Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. <a id="1.85.0-Libraries"></a> Libraries --------- - [Panics in the standard library now have a leading `library/` in their path](https://github.com/rust-lang/rust/pull/132390) - [`std::env::home_dir()` on Windows now ignores the non-standard `$HOME` environment variable](https://github.com/rust-lang/rust/pull/132515) It will be un-deprecated in a subsequent release. - [Add `AsyncFn*` to the prelude in all editions.](https://github.com/rust-lang/rust/pull/132611) <a id="1.85.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`BuildHasherDefault::new`](https://doc.rust-lang.org/stable/std/hash/struct.BuildHasherDefault.html#method.new) - [`ptr::fn_addr_eq`](https://doc.rust-lang.org/std/ptr/fn.fn_addr_eq.html) - [`io::ErrorKind::QuotaExceeded`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.QuotaExceeded) - [`io::ErrorKind::CrossesDevices`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.CrossesDevices) - [`{float}::midpoint`](https://doc.rust-lang.org/core/primitive.f32.html#method.midpoint) - [Unsigned `{integer}::midpoint`](https://doc.rust-lang.org/std/primitive.u64.html#method.midpoint) - [`NonZeroU*::midpoint`](https://doc.rust-lang.org/std/num/type.NonZeroU32.html#method.midpoint) - [impl `std::iter::Extend` for tuples with arity 1 through 12](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#impl-Extend%3C(A,)%3E-for-(EA,)) - [`FromIterator<(A, ...)>` for tuples with arity 1 through 12](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html#impl-FromIterator%3C(EA,)%3E-for-(A,)) - [`std::task::Waker::noop`](https://doc.rust-lang.org/stable/std/task/struct.Waker.html#method.noop) These APIs are now stable in const contexts: - [`mem::size_of_val`](https://doc.rust-lang.org/stable/std/mem/fn.size_of_val.html) - [`mem::align_of_val`](https://doc.rust-lang.org/stable/std/mem/fn.align_of_val.html) - [`Layout::for_value`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.for_value) - [`Layout::align_to`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.align_to) - [`Layout::pad_to_align`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.pad_to_align) - [`Layout::extend`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.extend) - [`Layout::array`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.array) - [`std::mem::swap`](https://doc.rust-lang.org/stable/std/mem/fn.swap.html) - [`std::ptr::swap`](https://doc.rust-lang.org/stable/std/ptr/fn.swap.html) - [`NonNull::new`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.new) - [`HashMap::with_hasher`](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html#method.with_hasher) - [`HashSet::with_hasher`](https://doc.rust-lang.org/stable/std/collections/struct.HashSet.html#method.with_hasher) - [`BuildHasherDefault::new`](https://doc.rust-lang.org/stable/std/hash/struct.BuildHasherDefault.html#method.new) - [`<float>::recip`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.recip) - [`<float>::to_degrees`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.to_degrees) - [`<float>::to_radians`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.to_radians) - [`<float>::max`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.max) - [`<float>::min`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.min) - [`<float>::clamp`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.clamp) - [`<float>::abs`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.abs) - [`<float>::signum`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.signum) - [`<float>::copysign`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.copysign) - [`MaybeUninit::write`](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.write) <a id="1.85.0-Cargo"></a> Cargo ----- - [Add future-incompatibility warning against keywords in cfgs and add raw-idents](https://github.com/rust-lang/cargo/pull/14671/) - [Stabilize higher precedence trailing flags](https://github.com/rust-lang/cargo/pull/14900/) - [Pass `CARGO_CFG_FEATURE` to build scripts](https://github.com/rust-lang/cargo/pull/14902/) <a id="1.85.0-Rustdoc"></a> Rustdoc ----- - [Doc comment on impl blocks shows the first line, even when the impl block is collapsed](https://github.com/rust-lang/rust/pull/132155) <a id="1.85.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [`rustc` no longer treats the `test` cfg as a well known check-cfg](https://github.com/rust-lang/rust/pull/131729), instead it is up to the build systems and users of `--check-cfg`[^check-cfg] to set it as a well known cfg using `--check-cfg=cfg(test)`. This is done to enable build systems like Cargo to set it conditionally, as not all source files are suitable for unit tests. [Cargo (for now) unconditionally sets the `test` cfg as a well known cfg](https://github.com/rust-lang/cargo/pull/14963). [^check-cfg]: https://doc.rust-lang.org/nightly/rustc/check-cfg.html - [Disable potentially incorrect type inference if there are trivial and non-trivial where-clauses](https://github.com/rust-lang/rust/pull/132325) - `std::env::home_dir()` has been deprecated for years, because it can give surprising results in some Windows configurations if the `HOME` environment variable is set (which is not the normal configuration on Windows). We had previously avoided changing its behavior, out of concern for compatibility with code depending on this non-standard configuration. Given how long this function has been deprecated, we're now fixing its behavior as a bugfix. A subsequent release will remove the deprecation for this function. - [Make `core::ffi::c_char` signedness more closely match that of the platform-default `char`](https://github.com/rust-lang/rust/pull/132975) This changed `c_char` from an `i8` to `u8` or vice versa on many Tier 2 and 3 targets (mostly Arm and RISC-V embedded targets). The new definition may result in compilation failures but fixes compatibility issues with C. The `libc` crate matches this change as of its 0.2.169 release. - [When compiling a nested `macro_rules` macro from an external crate, the content of the inner `macro_rules` is now built with the edition of the external crate, not the local crate.](https://github.com/rust-lang/rust/pull/133274) - [Increase `sparcv9-sun-solaris` and `x86_64-pc-solaris` Solaris baseline to 11.4.](https://github.com/rust-lang/rust/pull/133293) - [Show `abi_unsupported_vector_types` lint in future breakage reports](https://github.com/rust-lang/rust/pull/133374) - [Error if multiple super-trait instantiations of `dyn Trait` need associated types to be specified but only one is provided](https://github.com/rust-lang/rust/pull/133392) - [Change `powerpc64-ibm-aix` default `codemodel` to large](https://github.com/rust-lang/rust/pull/133811) <a id="1.85.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Build `x86_64-unknown-linux-gnu` with LTO for C/C++ code (e.g., `jemalloc`)](https://github.com/rust-lang/rust/pull/134690) Version 1.84.1 (2025-01-30) ========================== <a id="1.84.1"></a> - [Fix ICE 132920 in duplicate-crate diagnostics.](https://github.com/rust-lang/rust/pull/133304/) - [Fix errors for overlapping impls in incremental rebuilds.](https://github.com/rust-lang/rust/pull/133828/) - [Fix slow compilation related to the next-generation trait solver.](https://github.com/rust-lang/rust/pull/135618/) - [Fix debuginfo when LLVM's location discriminator value limit is exceeded.](https://github.com/rust-lang/rust/pull/135643/) - Fixes for building Rust from source: - [Only try to distribute `llvm-objcopy` if llvm tools are enabled.](https://github.com/rust-lang/rust/pull/134240/) - [Add Profile Override for Non-Git Sources.](https://github.com/rust-lang/rust/pull/135433/) - [Resolve symlinks of LLVM tool binaries before copying them.](https://github.com/rust-lang/rust/pull/135585/) - [Make it possible to use ci-rustc on tarball sources.](https://github.com/rust-lang/rust/pull/135722/) Version 1.84.0 (2025-01-09) ========================== <a id="1.84.0-Language"></a> Language -------- - [Allow `#[deny]` inside `#[forbid]` as a no-op](https://github.com/rust-lang/rust/pull/121560/) - [Show a warning when `-Ctarget-feature` is used to toggle features that can lead to unsoundness due to ABI mismatches](https://github.com/rust-lang/rust/pull/129884) - [Use the next-generation trait solver in coherence](https://github.com/rust-lang/rust/pull/130654) - [Allow coercions to drop the principal of trait objects](https://github.com/rust-lang/rust/pull/131857) - [Support `/` as the path separator for `include!()` in all cases on Windows](https://github.com/rust-lang/rust/pull/125205) - [Taking a raw ref (`raw (const|mut)`) of a deref of a pointer (`*ptr`) is now safe](https://github.com/rust-lang/rust/pull/129248) - [Stabilize s390x inline assembly](https://github.com/rust-lang/rust/pull/131258) - [Stabilize Arm64EC inline assembly](https://github.com/rust-lang/rust/pull/131781) - [Lint against creating pointers to immediately dropped temporaries](https://github.com/rust-lang/rust/pull/128985) - [Execute drop glue when unwinding in an `extern "C"` function](https://github.com/rust-lang/rust/pull/129582) <a id="1.84.0-Compiler"></a> Compiler -------- - [Add `--print host-tuple` flag to print the host target tuple and affirm the "target tuple" terminology over "target triple"](https://github.com/rust-lang/rust/pull/125579) - [Declaring functions with a calling convention not supported on the current target now triggers a hard error](https://github.com/rust-lang/rust/pull/129935) - [Set up indirect access to external data for `loongarch64-unknown-linux-{musl,ohos}`](https://github.com/rust-lang/rust/pull/131583) - [Enable XRay instrumentation for LoongArch Linux targets](https://github.com/rust-lang/rust/pull/131818) - [Extend the `unexpected_cfgs` lint to also warn in external macros](https://github.com/rust-lang/rust/pull/132577) - [Stabilize WebAssembly `multivalue`, `reference-types`, and `tail-call` target features](https://github.com/rust-lang/rust/pull/131080) - [Added Tier 2 support for the `wasm32v1-none` target](https://github.com/rust-lang/rust/pull/131487) <a id="1.84.0-Libraries"></a> Libraries --------- - [Implement `From<&mut {slice}>` for `Box/Rc/Arc<{slice}>`](https://github.com/rust-lang/rust/pull/129329) - [Move `<float>::copysign`, `<float>::abs`, `<float>::signum` to `core`](https://github.com/rust-lang/rust/pull/131304) - [Add `LowerExp` and `UpperExp` implementations to `NonZero`](https://github.com/rust-lang/rust/pull/131377) - [Implement `FromStr` for `CString` and `TryFrom<CString>` for `String`](https://github.com/rust-lang/rust/pull/130608) - [`std::os::darwin` has been made public](https://github.com/rust-lang/rust/pull/123723) <a id="1.84.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`Ipv6Addr::is_unique_local`](https://doc.rust-lang.org/stable/core/net/struct.Ipv6Addr.html#method.is_unique_local) - [`Ipv6Addr::is_unicast_link_local`](https://doc.rust-lang.org/stable/core/net/struct.Ipv6Addr.html#method.is_unicast_link_local) - [`core::ptr::with_exposed_provenance`](https://doc.rust-lang.org/stable/core/ptr/fn.with_exposed_provenance.html) - [`core::ptr::with_exposed_provenance_mut`](https://doc.rust-lang.org/stable/core/ptr/fn.with_exposed_provenance_mut.html) - [`<ptr>::addr`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.addr) - [`<ptr>::expose_provenance`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.expose_provenance) - [`<ptr>::with_addr`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.with_addr) - [`<ptr>::map_addr`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.map_addr) - [`<int>::isqrt`](https://doc.rust-lang.org/stable/core/primitive.i32.html#method.isqrt) - [`<int>::checked_isqrt`](https://doc.rust-lang.org/stable/core/primitive.i32.html#method.checked_isqrt) - [`<uint>::isqrt`](https://doc.rust-lang.org/stable/core/primitive.u32.html#method.isqrt) - [`NonZero::isqrt`](https://doc.rust-lang.org/stable/core/num/struct.NonZero.html#impl-NonZero%3Cu128%3E/method.isqrt) - [`core::ptr::without_provenance`](https://doc.rust-lang.org/stable/core/ptr/fn.without_provenance.html) - [`core::ptr::without_provenance_mut`](https://doc.rust-lang.org/stable/core/ptr/fn.without_provenance_mut.html) - [`core::ptr::dangling`](https://doc.rust-lang.org/stable/core/ptr/fn.dangling.html) - [`core::ptr::dangling_mut`](https://doc.rust-lang.org/stable/core/ptr/fn.dangling_mut.html) - [`Pin::as_deref_mut`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.as_deref_mut) These APIs are now stable in const contexts - [`AtomicBool::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicBool.html#method.from_ptr) - [`AtomicPtr::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicPtr.html#method.from_ptr) - [`AtomicU8::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicU8.html#method.from_ptr) - [`AtomicU16::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicU16.html#method.from_ptr) - [`AtomicU32::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicU32.html#method.from_ptr) - [`AtomicU64::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicU64.html#method.from_ptr) - [`AtomicUsize::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicUsize.html#method.from_ptr) - [`AtomicI8::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicI8.html#method.from_ptr) - [`AtomicI16::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicI16.html#method.from_ptr) - [`AtomicI32::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicI32.html#method.from_ptr) - [`AtomicI64::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicI64.html#method.from_ptr) - [`AtomicIsize::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicIsize.html#method.from_ptr) - [`<ptr>::is_null`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.is_null-1) - [`<ptr>::as_ref`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.as_ref-1) - [`<ptr>::as_mut`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.as_mut) - [`Pin::new`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.new) - [`Pin::new_unchecked`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.new_unchecked) - [`Pin::get_ref`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.get_ref) - [`Pin::into_ref`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.into_ref) - [`Pin::get_mut`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.get_mut) - [`Pin::get_unchecked_mut`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.get_unchecked_mut) - [`Pin::static_ref`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.static_ref) - [`Pin::static_mut`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.static_mut) <a id="1.84.0-Cargo"></a> Cargo ----- - [Stabilize MSRV-aware resolver config](https://github.com/rust-lang/cargo/pull/14639/) - [Stabilize resolver v3](https://github.com/rust-lang/cargo/pull/14754/) <a id="1.84-Rustdoc"></a> Rustdoc ------- - [rustdoc-search: improve type-driven search](https://github.com/rust-lang/rust/pull/127589) <a id="1.84.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Enable by default the `LSX` target feature for LoongArch Linux targets](https://github.com/rust-lang/rust/pull/132140) - [The unstable `-Zprofile` flag (“gcov-style” coverage instrumentation) has been removed.](https://github.com/rust-lang/rust/pull/131829) This does not affect the stable flags for coverage instrumentation (`-Cinstrument-coverage`) and profile-guided optimization (`-Cprofile-generate`, `-Cprofile-use`), which are unrelated and remain available. - Support for the target named `wasm32-wasi` has been removed as the target is now named `wasm32-wasip1`. This completes the [transition](https://github.com/rust-lang/compiler-team/issues/607) [plan](https://github.com/rust-lang/compiler-team/issues/695) for this target following [the introduction of `wasm32-wasip1`](https://github.com/rust-lang/rust/pull/120468) in Rust 1.78. Compiler warnings on [use of `wasm32-wasi`](https://github.com/rust-lang/rust/pull/126662) introduced in Rust 1.81 are now gone as well as the target is removed. - [The syntax `&pin (mut|const) T` is now parsed as a type which in theory could affect macro expansion results in some edge cases](https://github.com/rust-lang/rust/pull/130635#issuecomment-2375462821) - [Legacy syntax for calling `std::arch` functions is no longer permitted to declare items or bodies (such as closures, inline consts, or async blocks).](https://github.com/rust-lang/rust/pull/130443#issuecomment-2445678945) - [Declaring functions with a calling convention not supported on the current target now triggers a hard error](https://github.com/rust-lang/rust/pull/129935) - [The next-generation trait solver is now enabled for coherence, fixing multiple soundness issues](https://github.com/rust-lang/rust/pull/130654) Version 1.83.0 (2024-11-28) ========================== <a id="1.83.0-Language"></a> Language -------- - [Stabilize `&mut`, `*mut`, `&Cell`, and `*const Cell` in const.](https://github.com/rust-lang/rust/pull/129195) - [Allow creating references to statics in `const` initializers.](https://github.com/rust-lang/rust/pull/129759) - [Implement raw lifetimes and labels (`'r#ident`).](https://github.com/rust-lang/rust/pull/126452) - [Define behavior when atomic and non-atomic reads race.](https://github.com/rust-lang/rust/pull/128778) - [Non-exhaustive structs may now be empty.](https://github.com/rust-lang/rust/pull/128934) - [Disallow implicit coercions from places of type `!`](https://github.com/rust-lang/rust/pull/129392) - [`const extern` functions can now be defined for other calling conventions.](https://github.com/rust-lang/rust/pull/129753) - [Stabilize `expr_2021` macro fragment specifier in all editions.](https://github.com/rust-lang/rust/pull/129972) - [The `non_local_definitions` lint now fires on less code and warns by default.](https://github.com/rust-lang/rust/pull/127117) <a id="1.83.0-Compiler"></a> Compiler -------- - [Deprecate unsound `-Csoft-float` flag.](https://github.com/rust-lang/rust/pull/129897) - Add many new tier 3 targets: - [`aarch64_unknown_nto_qnx700`](https://github.com/rust-lang/rust/pull/127897) - [`arm64e-apple-tvos`](https://github.com/rust-lang/rust/pull/130614) - [`armv7-rtems-eabihf`](https://github.com/rust-lang/rust/pull/127021) - [`loongarch64-unknown-linux-ohos`](https://github.com/rust-lang/rust/pull/130750) - [`riscv32-wrs-vxworks` and `riscv64-wrs-vxworks`](https://github.com/rust-lang/rust/pull/130549) - [`riscv32{e|em|emc}-unknown-none-elf`](https://github.com/rust-lang/rust/pull/130555) - [`x86_64-unknown-hurd-gnu`](https://github.com/rust-lang/rust/pull/128345) - [`x86_64-unknown-trusty`](https://github.com/rust-lang/rust/pull/130453) Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. <a id="1.83.0-Libraries"></a> Libraries --------- - [Implement `PartialEq` for `ExitCode`.](https://github.com/rust-lang/rust/pull/127633) - [Document that `catch_unwind` can deal with foreign exceptions without UB, although the exact behavior is unspecified.](https://github.com/rust-lang/rust/pull/128321) - [Implement `Default` for `HashMap`/`HashSet` iterators that don't already have it.](https://github.com/rust-lang/rust/pull/128711) - [Bump Unicode to version 16.0.0.](https://github.com/rust-lang/rust/pull/130183) - [Change documentation of `ptr::add`/`sub` to not claim equivalence with `offset`.](https://github.com/rust-lang/rust/pull/130229) <a id="1.83.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`BufRead::skip_until`](https://doc.rust-lang.org/stable/std/io/trait.BufRead.html#method.skip_until) - [`ControlFlow::break_value`](https://doc.rust-lang.org/stable/core/ops/enum.ControlFlow.html#method.break_value) - [`ControlFlow::continue_value`](https://doc.rust-lang.org/stable/core/ops/enum.ControlFlow.html#method.continue_value) - [`ControlFlow::map_break`](https://doc.rust-lang.org/stable/core/ops/enum.ControlFlow.html#method.map_break) - [`ControlFlow::map_continue`](https://doc.rust-lang.org/stable/core/ops/enum.ControlFlow.html#method.map_continue) - [`DebugList::finish_non_exhaustive`](https://doc.rust-lang.org/stable/core/fmt/struct.DebugList.html#method.finish_non_exhaustive) - [`DebugMap::finish_non_exhaustive`](https://doc.rust-lang.org/stable/core/fmt/struct.DebugMap.html#method.finish_non_exhaustive) - [`DebugSet::finish_non_exhaustive`](https://doc.rust-lang.org/stable/core/fmt/struct.DebugSet.html#method.finish_non_exhaustive) - [`DebugTuple::finish_non_exhaustive`](https://doc.rust-lang.org/stable/core/fmt/struct.DebugTuple.html#method.finish_non_exhaustive) - [`ErrorKind::ArgumentListTooLong`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.ArgumentListTooLong) - [`ErrorKind::Deadlock`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.Deadlock) - [`ErrorKind::DirectoryNotEmpty`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.DirectoryNotEmpty) - [`ErrorKind::ExecutableFileBusy`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.ExecutableFileBusy) - [`ErrorKind::FileTooLarge`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.FileTooLarge) - [`ErrorKind::HostUnreachable`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.HostUnreachable) - [`ErrorKind::IsADirectory`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.IsADirectory) - [`ErrorKind::NetworkDown`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.NetworkDown) - [`ErrorKind::NetworkUnreachable`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.NetworkUnreachable) - [`ErrorKind::NotADirectory`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.NotADirectory) - [`ErrorKind::NotSeekable`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.NotSeekable) - [`ErrorKind::ReadOnlyFilesystem`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.ReadOnlyFilesystem) - [`ErrorKind::ResourceBusy`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.ResourceBusy) - [`ErrorKind::StaleNetworkFileHandle`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.StaleNetworkFileHandle) - [`ErrorKind::StorageFull`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.StorageFull) - [`ErrorKind::TooManyLinks`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.TooManyLinks) - [`Option::get_or_insert_default`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.get_or_insert_default) - [`Waker::data`](https://doc.rust-lang.org/stable/core/task/struct.Waker.html#method.data) - [`Waker::new`](https://doc.rust-lang.org/stable/core/task/struct.Waker.html#method.new) - [`Waker::vtable`](https://doc.rust-lang.org/stable/core/task/struct.Waker.html#method.vtable) - [`char::MIN`](https://doc.rust-lang.org/stable/core/primitive.char.html#associatedconstant.MIN) - [`hash_map::Entry::insert_entry`](https://doc.rust-lang.org/stable/std/collections/hash_map/enum.Entry.html#method.insert_entry) - [`hash_map::VacantEntry::insert_entry`](https://doc.rust-lang.org/stable/std/collections/hash_map/struct.VacantEntry.html#method.insert_entry) These APIs are now stable in const contexts: - [`Cell::into_inner`](https://doc.rust-lang.org/stable/core/cell/struct.Cell.html#method.into_inner) - [`Duration::as_secs_f32`](https://doc.rust-lang.org/stable/core/time/struct.Duration.html#method.as_secs_f32) - [`Duration::as_secs_f64`](https://doc.rust-lang.org/stable/core/time/struct.Duration.html#method.as_secs_f64) - [`Duration::div_duration_f32`](https://doc.rust-lang.org/stable/core/time/struct.Duration.html#method.div_duration_f32) - [`Duration::div_duration_f64`](https://doc.rust-lang.org/stable/core/time/struct.Duration.html#method.div_duration_f64) - [`MaybeUninit::as_mut_ptr`](https://doc.rust-lang.org/stable/core/mem/union.MaybeUninit.html#method.as_mut_ptr) - [`NonNull::as_mut`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.as_mut) - [`NonNull::copy_from`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.copy_from) - [`NonNull::copy_from_nonoverlapping`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.copy_from_nonoverlapping) - [`NonNull::copy_to`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.copy_to) - [`NonNull::copy_to_nonoverlapping`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.copy_to_nonoverlapping) - [`NonNull::slice_from_raw_parts`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.slice_from_raw_parts) - [`NonNull::write`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.write) - [`NonNull::write_bytes`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.write_bytes) - [`NonNull::write_unaligned`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.write_unaligned) - [`OnceCell::into_inner`](https://doc.rust-lang.org/stable/core/cell/struct.OnceCell.html#method.into_inner) - [`Option::as_mut`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.as_mut) - [`Option::expect`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.expect) - [`Option::replace`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.replace) - [`Option::take`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.take) - [`Option::unwrap`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.unwrap) - [`Option::unwrap_unchecked`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.unwrap_unchecked) - [`Option::<&_>::copied`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.copied) - [`Option::<&mut _>::copied`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.copied-1) - [`Option::<Option<_>>::flatten`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.flatten) - [`Option::<Result<_, _>>::transpose`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.transpose) - [`RefCell::into_inner`](https://doc.rust-lang.org/stable/core/cell/struct.RefCell.html#method.into_inner) - [`Result::as_mut`](https://doc.rust-lang.org/stable/core/result/enum.Result.html#method.as_mut) - [`Result::<&_, _>::copied`](https://doc.rust-lang.org/stable/core/result/enum.Result.html#method.copied) - [`Result::<&mut _, _>::copied`](https://doc.rust-lang.org/stable/core/result/enum.Result.html#method.copied-1) - [`Result::<Option<_>, _>::transpose`](https://doc.rust-lang.org/stable/core/result/enum.Result.html#method.transpose) - [`UnsafeCell::get_mut`](https://doc.rust-lang.org/stable/core/cell/struct.UnsafeCell.html#method.get_mut) - [`UnsafeCell::into_inner`](https://doc.rust-lang.org/stable/core/cell/struct.UnsafeCell.html#method.into_inner) - [`array::from_mut`](https://doc.rust-lang.org/stable/core/array/fn.from_mut.html) - [`char::encode_utf8`](https://doc.rust-lang.org/stable/core/primitive.char.html#method.encode_utf8) - [`{float}::classify`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.classify) - [`{float}::is_finite`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.is_finite) - [`{float}::is_infinite`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.is_infinite) - [`{float}::is_nan`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.is_nan) - [`{float}::is_normal`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.is_normal) - [`{float}::is_sign_negative`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.is_sign_negative) - [`{float}::is_sign_positive`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.is_sign_positive) - [`{float}::is_subnormal`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.is_subnormal) - [`{float}::from_bits`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.from_bits) - [`{float}::from_be_bytes`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.from_be_bytes) - [`{float}::from_le_bytes`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.from_le_bytes) - [`{float}::from_ne_bytes`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.from_ne_bytes) - [`{float}::to_bits`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.to_bits) - [`{float}::to_be_bytes`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.to_be_bytes) - [`{float}::to_le_bytes`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.to_le_bytes) - [`{float}::to_ne_bytes`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.to_ne_bytes) - [`mem::replace`](https://doc.rust-lang.org/stable/core/mem/fn.replace.html) - [`ptr::replace`](https://doc.rust-lang.org/stable/core/ptr/fn.replace.html) - [`ptr::slice_from_raw_parts_mut`](https://doc.rust-lang.org/stable/core/ptr/fn.slice_from_raw_parts_mut.html) - [`ptr::write`](https://doc.rust-lang.org/stable/core/ptr/fn.write.html) - [`ptr::write_unaligned`](https://doc.rust-lang.org/stable/core/ptr/fn.write_unaligned.html) - [`<*const _>::copy_to`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.copy_to) - [`<*const _>::copy_to_nonoverlapping`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.copy_to_nonoverlapping) - [`<*mut _>::copy_from`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.copy_from) - [`<*mut _>::copy_from_nonoverlapping`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.copy_from_nonoverlapping) - [`<*mut _>::copy_to`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.copy_to-1) - [`<*mut _>::copy_to_nonoverlapping`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.copy_to_nonoverlapping-1) - [`<*mut _>::write`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.write) - [`<*mut _>::write_bytes`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.write_bytes) - [`<*mut _>::write_unaligned`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.write_unaligned) - [`slice::from_mut`](https://doc.rust-lang.org/stable/core/slice/fn.from_mut.html) - [`slice::from_raw_parts_mut`](https://doc.rust-lang.org/stable/core/slice/fn.from_raw_parts_mut.html) - [`<[_]>::first_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.first_mut) - [`<[_]>::last_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.last_mut) - [`<[_]>::first_chunk_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.first_chunk_mut) - [`<[_]>::last_chunk_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.last_chunk_mut) - [`<[_]>::split_at_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_at_mut) - [`<[_]>::split_at_mut_checked`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_at_mut_checked) - [`<[_]>::split_at_mut_unchecked`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_at_mut_unchecked) - [`<[_]>::split_first_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_first_mut) - [`<[_]>::split_last_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_last_mut) - [`<[_]>::split_first_chunk_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_first_chunk_mut) - [`<[_]>::split_last_chunk_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_last_chunk_mut) - [`str::as_bytes_mut`](https://doc.rust-lang.org/stable/core/primitive.str.html#method.as_bytes_mut) - [`str::as_mut_ptr`](https://doc.rust-lang.org/stable/core/primitive.str.html#method.as_mut_ptr) - [`str::from_utf8_unchecked_mut`](https://doc.rust-lang.org/stable/core/str/fn.from_utf8_unchecked_mut.html) <a id="1.83.0-Cargo"></a> Cargo ----- - [Introduced a new `CARGO_MANIFEST_PATH` environment variable, similar to `CARGO_MANIFEST_DIR` but pointing directly to the manifest file.](https://github.com/rust-lang/cargo/pull/14404/) - [Added `package.autolib` to the manifest, allowing `[lib]` auto-discovery to be disabled.](https://github.com/rust-lang/cargo/pull/14591/) - [Declare support level for each crate in Cargo's Charter / crate docs.](https://github.com/rust-lang/cargo/pull/14600/) - [Declare new Intentional Artifacts as 'small' changes.](https://github.com/rust-lang/cargo/pull/14599/) <a id="1.83-Rustdoc"></a> Rustdoc ------- - [The sidebar / hamburger menu table of contents now includes the `# headers` from the main item's doc comment](https://github.com/rust-lang/rust/pull/120736). This is similar to a third-party feature provided by the rustdoc-search-enhancements browser extension. <a id="1.83.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Warn against function pointers using unsupported ABI strings.](https://github.com/rust-lang/rust/pull/128784) - [Check well-formedness of the source type's signature in fn pointer casts.](https://github.com/rust-lang/rust/pull/129021) This partly closes a soundness hole that comes when casting a function item to function pointer - [Use equality instead of subtyping when resolving type dependent paths.](https://github.com/rust-lang/rust/pull/129073) - Linking on macOS now correctly includes Rust's default deployment target. Due to a linker bug, you might have to pass `MACOSX_DEPLOYMENT_TARGET` or fix your `#[link]` attributes to point to the correct frameworks. See <https://github.com/rust-lang/rust/pull/129369>. - [Rust will now correctly raise an error for `repr(Rust)` written on non-`struct`/`enum`/`union` items, since it previously did not have any effect.](https://github.com/rust-lang/rust/pull/129422) - The future incompatibility lint `deprecated_cfg_attr_crate_type_name` [has been made into a hard error](https://github.com/rust-lang/rust/pull/129670). It was used to deny usage of `#![crate_type]` and `#![crate_name]` attributes in `#![cfg_attr]`, which required a hack in the compiler to be able to change the used crate type and crate name after cfg expansion. Users can use `--crate-type` instead of `#![cfg_attr(..., crate_type = "...")]` and `--crate-name` instead of `#![cfg_attr(..., crate_name = "...")]` when running `rustc`/`cargo rustc` on the command line. Use of those two attributes outside of `#![cfg_attr]` continue to be fully supported. - Until now, paths into the sysroot were always prefixed with `/rustc/$hash` in diagnostics, codegen, backtrace, e.g. ``` thread 'main' panicked at 'hello world', map-panic.rs:2:50 stack backtrace: 0: std::panicking::begin_panic at /rustc/a55dd71d5fb0ec5a6a3a9e8c27b2127ba491ce52/library/std/src/panicking.rs:616:12 1: map_panic::main::{{closure}} at ./map-panic.rs:2:50 2: core::option::Option<T>::map at /rustc/a55dd71d5fb0ec5a6a3a9e8c27b2127ba491ce52/library/core/src/option.rs:929:29 3: map_panic::main at ./map-panic.rs:2:30 4: core::ops::function::FnOnce::call_once at /rustc/a55dd71d5fb0ec5a6a3a9e8c27b2127ba491ce52/library/core/src/ops/function.rs:248:5 note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace. ``` [RFC 3127 said](https://rust-lang.github.io/rfcs/3127-trim-paths.html#changing-handling-of-sysroot-path-in-rustc) > We want to change this behaviour such that, when `rust-src` source files can be discovered, the virtual path is discarded and therefore the local path will be embedded, unless there is a `--remap-path-prefix` that causes this local path to be remapped in the usual way. [#129687](https://github.com/rust-lang/rust/pull/129687) implements this behaviour, when `rust-src` is present at compile time, `rustc` replaces `/rustc/$hash` with a real path into the local `rust-src` component with best effort. To sanitize this, users must explicitly supply `--remap-path-prefix=<path to rust-src>=foo` or not have the `rust-src` component installed. - The allow-by-default `missing_docs` lint used to disable itself when invoked through `rustc --test`/`cargo test`, resulting in `#[expect(missing_docs)]` emitting false positives due to the expectation being wrongly unfulfilled. This behavior [has now been removed](https://github.com/rust-lang/rust/pull/130025), which allows `#[expect(missing_docs)]` to be fulfilled in all scenarios, but will also report new `missing_docs` diagnostics for publicly reachable `#[cfg(test)]` items, [integration test](https://doc.rust-lang.org/cargo/reference/cargo-targets.html#integration-tests) crate-level documentation, and publicly reachable items in integration tests. - [The `armv8r-none-eabihf` target now uses the Armv8-R required set of floating-point features.](https://github.com/rust-lang/rust/pull/130295) - [Fix a soundness bug where rustc wouldn't detect unconstrained higher-ranked lifetimes in a `dyn Trait`'s associated types that occur due to supertraits.](https://github.com/rust-lang/rust/pull/130367) - [Update the minimum external LLVM version to 18.](https://github.com/rust-lang/rust/pull/130487) - [Remove `aarch64-fuchsia` and `x86_64-fuchsia` target aliases in favor of `aarch64-unknown-fuchsia` and `x86_64-unknown-fuchsia` respectively.](https://github.com/rust-lang/rust/pull/130657) - [The ABI-level exception class of a Rust panic is now encoded with native-endian bytes, so it is legible in hex dumps.](https://github.com/rust-lang/rust/pull/130897) - [Visual Studio 2013 is no longer supported for MSVC targets.](https://github.com/rust-lang/rust/pull/131070) - [The sysroot no longer contains the `std` dynamic library in its top-level `lib/` dir.](https://github.com/rust-lang/rust/pull/131188) Version 1.82.0 (2024-10-17) ========================== <a id="1.82.0-Language"></a> Language -------- - [Don't make statement nonterminals match pattern nonterminals](https://github.com/rust-lang/rust/pull/120221/) - [Patterns matching empty types can now be omitted in common cases](https://github.com/rust-lang/rust/pull/122792) - [Enforce supertrait outlives obligations when using trait impls](https://github.com/rust-lang/rust/pull/124336) - [`addr_of(_mut)!` macros and the newly stabilized `&raw (const|mut)` are now safe to use with all static items](https://github.com/rust-lang/rust/pull/125834) - [size_of_val_raw: for length 0 this is safe to call](https://github.com/rust-lang/rust/pull/126152/) - [Reorder trait bound modifiers *after* `for<...>` binder in trait bounds](https://github.com/rust-lang/rust/pull/127054/) - [Stabilize `+ use<'lt>` opaque type precise capturing (RFC 3617)](https://github.com/rust-lang/rust/pull/127672) - [Stabilize `&raw const` and `&raw mut` operators (RFC 2582)](https://github.com/rust-lang/rust/pull/127679) - [Stabilize unsafe extern blocks (RFC 3484)](https://github.com/rust-lang/rust/pull/127921) - [Stabilize nested field access in `offset_of!`](https://github.com/rust-lang/rust/pull/128284) - [Do not require `T` to be live when dropping `[T; 0]`](https://github.com/rust-lang/rust/pull/128438) - [Stabilize `const` operands in inline assembly](https://github.com/rust-lang/rust/pull/128570) - [Stabilize floating-point arithmetic in `const fn`](https://github.com/rust-lang/rust/pull/128596) - [Stabilize explicit opt-in to unsafe attributes](https://github.com/rust-lang/rust/pull/128771) - [Document NaN bit patterns guarantees](https://github.com/rust-lang/rust/pull/129559) <a id="1.82.0-Compiler"></a> Compiler -------- - [Promote riscv64gc-unknown-linux-musl to tier 2](https://github.com/rust-lang/rust/pull/122049) - [Promote Mac Catalyst targets `aarch64-apple-ios-macabi` and `x86_64-apple-ios-macabi` to Tier 2, and ship them with rustup](https://github.com/rust-lang/rust/pull/126450) - [Add tier 3 NuttX based targets for RISC-V and ARM](https://github.com/rust-lang/rust/pull/127755) - [Add tier 3 powerpc-unknown-linux-muslspe target](https://github.com/rust-lang/rust/pull/127905) - [Improved diagnostics to explain why a pattern is unreachable](https://github.com/rust-lang/rust/pull/128034) - [The compiler now triggers the unreachable code warning properly for async functions that don't return/are `-> !`](https://github.com/rust-lang/rust/pull/128443) - [Promote `aarch64-apple-darwin` to Tier 1](https://github.com/rust-lang/rust/pull/128592) - [Add Trusty OS target `aarch64-unknown-trusty` and `armv7-unknown-trusty` as tier 3 targets](https://github.com/rust-lang/rust/pull/129490) - [Promote `wasm32-wasip2` to Tier 2.](https://github.com/rust-lang/rust/pull/126967/) <a id="1.82.0-Libraries"></a> Libraries --------- - [Generalize `{Rc,Arc}::make_mut()` to `Path`, `OsStr`, and `CStr`.](https://github.com/rust-lang/rust/pull/126877) <a id="1.82.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`std::thread::Builder::spawn_unchecked`](https://doc.rust-lang.org/stable/std/thread/struct.Builder.html#method.spawn_unchecked) - [`std::str::CharIndices::offset`](https://doc.rust-lang.org/nightly/std/str/struct.CharIndices.html#method.offset) - [`std::option::Option::is_none_or`](https://doc.rust-lang.org/nightly/std/option/enum.Option.html#method.is_none_or) - [`[T]::is_sorted`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.is_sorted) - [`[T]::is_sorted_by`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.is_sorted_by) - [`[T]::is_sorted_by_key`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.is_sorted_by_key) - [`Iterator::is_sorted`](https://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#method.is_sorted) - [`Iterator::is_sorted_by`](https://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#method.is_sorted_by) - [`Iterator::is_sorted_by_key`](https://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#method.is_sorted_by_key) - [`std::future::Ready::into_inner`](https://doc.rust-lang.org/nightly/std/future/struct.Ready.html#method.into_inner) - [`std::iter::repeat_n`](https://doc.rust-lang.org/nightly/std/iter/fn.repeat_n.html) - [`impl<T: Clone> DoubleEndedIterator for Take<Repeat<T>>`](https://doc.rust-lang.org/nightly/std/iter/struct.Take.html#impl-DoubleEndedIterator-for-Take%3CRepeat%3CT%3E%3E) - [`impl<T: Clone> ExactSizeIterator for Take<Repeat<T>>`](https://doc.rust-lang.org/nightly/std/iter/struct.Take.html#impl-ExactSizeIterator-for-Take%3CRepeat%3CT%3E%3E) - [`impl<T: Clone> ExactSizeIterator for Take<RepeatWith<T>>`](https://doc.rust-lang.org/nightly/std/iter/struct.Take.html#impl-ExactSizeIterator-for-Take%3CRepeatWith%3CF%3E%3E) - [`impl Default for std::collections::binary_heap::Iter`](https://doc.rust-lang.org/nightly/std/collections/binary_heap/struct.Iter.html#impl-Default-for-Iter%3C'_,+T%3E) - [`impl Default for std::collections::btree_map::RangeMut`](https://doc.rust-lang.org/nightly/std/collections/btree_map/struct.RangeMut.html#impl-Default-for-RangeMut%3C'_,+K,+V%3E) - [`impl Default for std::collections::btree_map::ValuesMut`](https://doc.rust-lang.org/nightly/std/collections/btree_map/struct.ValuesMut.html#impl-Default-for-ValuesMut%3C'_,+K,+V%3E) - [`impl Default for std::collections::vec_deque::Iter`](https://doc.rust-lang.org/nightly/std/collections/vec_deque/struct.Iter.html#impl-Default-for-Iter%3C'_,+T%3E) - [`impl Default for std::collections::vec_deque::IterMut`](https://doc.rust-lang.org/nightly/std/collections/vec_deque/struct.IterMut.html#impl-Default-for-IterMut%3C'_,+T%3E) - [`Rc<T>::new_uninit`](https://doc.rust-lang.org/nightly/std/rc/struct.Rc.html#method.new_uninit) - [`Rc<MaybeUninit<T>>::assume_init`](https://doc.rust-lang.org/nightly/std/rc/struct.Rc.html#method.assume_init) - [`Rc<[T]>::new_uninit_slice`](https://doc.rust-lang.org/nightly/std/rc/struct.Rc.html#method.new_uninit_slice) - [`Rc<[MaybeUninit<T>]>::assume_init`](https://doc.rust-lang.org/nightly/std/rc/struct.Rc.html#method.assume_init-1) - [`Arc<T>::new_uninit`](https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.new_uninit) - [`Arc<MaybeUninit<T>>::assume_init`](https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.assume_init) - [`Arc<[T]>::new_uninit_slice`](https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.new_uninit_slice) - [`Arc<[MaybeUninit<T>]>::assume_init`](https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.assume_init-1) - [`Box<T>::new_uninit`](https://doc.rust-lang.org/nightly/std/boxed/struct.Box.html#method.new_uninit) - [`Box<MaybeUninit<T>>::assume_init`](https://doc.rust-lang.org/nightly/std/boxed/struct.Box.html#method.assume_init) - [`Box<[T]>::new_uninit_slice`](https://doc.rust-lang.org/nightly/std/boxed/struct.Box.html#method.new_uninit_slice) - [`Box<[MaybeUninit<T>]>::assume_init`](https://doc.rust-lang.org/nightly/std/boxed/struct.Box.html#method.assume_init-1) - [`core::arch::x86_64::_bextri_u64`](https://doc.rust-lang.org/stable/core/arch/x86_64/fn._bextri_u64.html) - [`core::arch::x86_64::_bextri_u32`](https://doc.rust-lang.org/stable/core/arch/x86_64/fn._bextri_u32.html) - [`core::arch::x86::_mm_broadcastsi128_si256`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm_broadcastsi128_si256.html) - [`core::arch::x86::_mm256_stream_load_si256`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm256_stream_load_si256.html) - [`core::arch::x86::_tzcnt_u16`](https://doc.rust-lang.org/stable/core/arch/x86/fn._tzcnt_u16.html) - [`core::arch::x86::_mm_extracti_si64`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm_extracti_si64.html) - [`core::arch::x86::_mm_inserti_si64`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm_inserti_si64.html) - [`core::arch::x86::_mm_storeu_si16`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm_storeu_si16.html) - [`core::arch::x86::_mm_storeu_si32`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm_storeu_si32.html) - [`core::arch::x86::_mm_storeu_si64`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm_storeu_si64.html) - [`core::arch::x86::_mm_loadu_si16`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm_loadu_si16.html) - [`core::arch::x86::_mm_loadu_si32`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm_loadu_si32.html) - [`core::arch::wasm32::u8x16_relaxed_swizzle`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u8x16_relaxed_swizzle.html) - [`core::arch::wasm32::i8x16_relaxed_swizzle`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i8x16_relaxed_swizzle.html) - [`core::arch::wasm32::i32x4_relaxed_trunc_f32x4`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i32x4_relaxed_trunc_f32x4.html) - [`core::arch::wasm32::u32x4_relaxed_trunc_f32x4`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u32x4_relaxed_trunc_f32x4.html) - [`core::arch::wasm32::i32x4_relaxed_trunc_f64x2_zero`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i32x4_relaxed_trunc_f64x2_zero.html) - [`core::arch::wasm32::u32x4_relaxed_trunc_f64x2_zero`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u32x4_relaxed_trunc_f64x2_zero.html) - [`core::arch::wasm32::f32x4_relaxed_madd`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.f32x4_relaxed_madd.html) - [`core::arch::wasm32::f32x4_relaxed_nmadd`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.f32x4_relaxed_nmadd.html) - [`core::arch::wasm32::f64x2_relaxed_madd`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.f64x2_relaxed_madd.html) - [`core::arch::wasm32::f64x2_relaxed_nmadd`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.f64x2_relaxed_nmadd.html) - [`core::arch::wasm32::i8x16_relaxed_laneselect`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i8x16_relaxed_laneselect.html) - [`core::arch::wasm32::u8x16_relaxed_laneselect`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u8x16_relaxed_laneselect.html) - [`core::arch::wasm32::i16x8_relaxed_laneselect`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i16x8_relaxed_laneselect.html) - [`core::arch::wasm32::u16x8_relaxed_laneselect`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u16x8_relaxed_laneselect.html) - [`core::arch::wasm32::i32x4_relaxed_laneselect`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i32x4_relaxed_laneselect.html) - [`core::arch::wasm32::u32x4_relaxed_laneselect`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u32x4_relaxed_laneselect.html) - [`core::arch::wasm32::i64x2_relaxed_laneselect`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i64x2_relaxed_laneselect.html) - [`core::arch::wasm32::u64x2_relaxed_laneselect`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u64x2_relaxed_laneselect.html) - [`core::arch::wasm32::f32x4_relaxed_min`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.f32x4_relaxed_min.html) - [`core::arch::wasm32::f32x4_relaxed_max`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.f32x4_relaxed_max.html) - [`core::arch::wasm32::f64x2_relaxed_min`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.f64x2_relaxed_min.html) - [`core::arch::wasm32::f64x2_relaxed_max`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.f64x2_relaxed_max.html) - [`core::arch::wasm32::i16x8_relaxed_q15mulr`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i16x8_relaxed_q15mulr.html) - [`core::arch::wasm32::u16x8_relaxed_q15mulr`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u16x8_relaxed_q15mulr.html) - [`core::arch::wasm32::i16x8_relaxed_dot_i8x16_i7x16`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i16x8_relaxed_dot_i8x16_i7x16.html) - [`core::arch::wasm32::u16x8_relaxed_dot_i8x16_i7x16`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u16x8_relaxed_dot_i8x16_i7x16.html) - [`core::arch::wasm32::i32x4_relaxed_dot_i8x16_i7x16_add`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i32x4_relaxed_dot_i8x16_i7x16_add.html) - [`core::arch::wasm32::u32x4_relaxed_dot_i8x16_i7x16_add`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u32x4_relaxed_dot_i8x16_i7x16_add.html) These APIs are now stable in const contexts: - [`std::task::Waker::from_raw`](https://doc.rust-lang.org/nightly/std/task/struct.Waker.html#method.from_raw) - [`std::task::Context::from_waker`](https://doc.rust-lang.org/nightly/std/task/struct.Context.html#method.from_waker) - [`std::task::Context::waker`](https://doc.rust-lang.org/nightly/std/task/struct.Context.html#method.waker) - [`{integer}::from_str_radix`](https://doc.rust-lang.org/nightly/std/primitive.u32.html#method.from_str_radix) - [`std::num::ParseIntError::kind`](https://doc.rust-lang.org/nightly/std/num/struct.ParseIntError.html#method.kind) <a id="1.82.0-Cargo"></a> Cargo ----- - [feat: Add `info` cargo subcommand](https://github.com/rust-lang/cargo/pull/14141/) <a id="1.82.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - We now [disallow setting some built-in cfgs via the command-line](https://github.com/rust-lang/rust/pull/126158) with the newly added [`explicit_builtin_cfgs_in_flags`](https://doc.rust-lang.org/rustc/lints/listing/deny-by-default.html#explicit-builtin-cfgs-in-flags) lint in order to prevent incoherent state, eg. `windows` cfg active but target is Linux based. The appropriate [`rustc` flag](https://doc.rust-lang.org/rustc/command-line-arguments.html) should be used instead. - The standard library has a new implementation of `binary_search` which significantly improves performance ([#128254](https://github.com/rust-lang/rust/pull/128254)). However when a sorted slice has multiple values which compare equal, the new implementation may select a different value among the equal ones than the old implementation. - [illumos/Solaris now sets `MSG_NOSIGNAL` when writing to sockets](https://github.com/rust-lang/rust/pull/128259). This avoids killing the process with SIGPIPE when writing to a closed socket, which matches the existing behavior on other UNIX targets. - [Removes a problematic hack that always passed the --whole-archive linker flag for tests, which may cause linker errors for code accidentally relying on it.](https://github.com/rust-lang/rust/pull/128400) - The WebAssembly target features `multivalue` and `reference-types` are now both enabled by default. These two features both have subtle changes implied for generated WebAssembly binaries. For the `multivalue` feature, WebAssembly target support has changed when upgrading to LLVM 19. Support for generating functions with multiple returns no longer works and `-Ctarget-feature=+multivalue` has a different meaning than it did in LLVM 18 and prior. There is no longer any supported means to generate a module that has a function with multiple returns in WebAssembly from Rust source code. For the `reference-types` feature the encoding of immediates in the `call_indirect`, a commonly used instruction by the WebAssembly backend, has changed. Validators and parsers which don't understand the `reference-types` proposal will no longer accept modules produced by LLVM due to this change in encoding of immediates. Additionally these features being enabled are encoded in the `target_features` custom section and may affect downstream tooling such as `wasm-opt` consuming the module. Generating a WebAssembly module that disables default features requires `-Zbuild-std` support from Cargo and more information can be found at [rust-lang/rust#128511](https://github.com/rust-lang/rust/pull/128511). - [Rust now raises unsafety errors for union patterns in parameter-position](https://github.com/rust-lang/rust/pull/130531) <a id="1.82.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Update to LLVM 19](https://github.com/rust-lang/rust/pull/127513) Version 1.81.0 (2024-09-05) ========================== <a id="1.81.0-Language"></a> Language -------- - [Abort on uncaught panics in `extern "C"` functions.](https://github.com/rust-lang/rust/pull/116088/) - [Fix ambiguous cases of multiple `&` in elided self lifetimes.](https://github.com/rust-lang/rust/pull/117967/) - [Stabilize `#[expect]` for lints (RFC 2383),](https://github.com/rust-lang/rust/pull/120924/) like `#[allow]` with a warning if the lint is _not_ fulfilled. - [Change method resolution to constrain hidden types instead of rejecting method candidates.](https://github.com/rust-lang/rust/pull/123962/) - [Bump `elided_lifetimes_in_associated_constant` to deny.](https://github.com/rust-lang/rust/pull/124211/) - [`offset_from`: always allow pointers to point to the same address.](https://github.com/rust-lang/rust/pull/124921/) - [Allow constraining opaque types during subtyping in the trait system.](https://github.com/rust-lang/rust/pull/125447/) - [Allow constraining opaque types during various unsizing casts.](https://github.com/rust-lang/rust/pull/125610/) - [Deny keyword lifetimes pre-expansion.](https://github.com/rust-lang/rust/pull/126762/) <a id="1.81.0-Compiler"></a> Compiler -------- - [Make casts of pointers to trait objects stricter.](https://github.com/rust-lang/rust/pull/120248/) - [Check alias args for well-formedness even if they have escaping bound vars.](https://github.com/rust-lang/rust/pull/123737/) - [Deprecate no-op codegen option `-Cinline-threshold=...`.](https://github.com/rust-lang/rust/pull/124712/) - [Re-implement a type-size based limit.](https://github.com/rust-lang/rust/pull/125507/) - [Properly account for alignment in `transmute` size checks.](https://github.com/rust-lang/rust/pull/125740/) - [Remove the `box_pointers` lint.](https://github.com/rust-lang/rust/pull/126018/) - [Ensure the interpreter checks bool/char for validity when they are used in a cast.](https://github.com/rust-lang/rust/pull/126265/) - [Improve coverage instrumentation for functions containing nested items.](https://github.com/rust-lang/rust/pull/127199/) - Target changes: - [Add Tier 3 `no_std` Xtensa targets:](https://github.com/rust-lang/rust/pull/125141/) `xtensa-esp32-none-elf`, `xtensa-esp32s2-none-elf`, `xtensa-esp32s3-none-elf` - [Add Tier 3 `std` Xtensa targets:](https://github.com/rust-lang/rust/pull/126380/) `xtensa-esp32-espidf`, `xtensa-esp32s2-espidf`, `xtensa-esp32s3-espidf` - [Add Tier 3 i686 Redox OS target:](https://github.com/rust-lang/rust/pull/126192/) `i686-unknown-redox` - [Promote `arm64ec-pc-windows-msvc` to Tier 2.](https://github.com/rust-lang/rust/pull/126039/) - [Promote `loongarch64-unknown-linux-musl` to Tier 2 with host tools.](https://github.com/rust-lang/rust/pull/126298/) - [Enable full tools and profiler for LoongArch Linux targets.](https://github.com/rust-lang/rust/pull/127078/) - [Unconditionally warn on usage of `wasm32-wasi`.](https://github.com/rust-lang/rust/pull/126662/) (see compatibility note below) - Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. <a id="1.81.0-Libraries"></a> Libraries --------- - [Split core's `PanicInfo` and std's `PanicInfo`.](https://github.com/rust-lang/rust/pull/115974/) (see compatibility note below) - [Generalize `{Rc,Arc}::make_mut()` to unsized types.](https://github.com/rust-lang/rust/pull/116113/) - [Replace sort implementations with stable `driftsort` and unstable `ipnsort`.](https://github.com/rust-lang/rust/pull/124032/) All `slice::sort*` and `slice::select_nth*` methods are expected to see significant performance improvements. See the [research project](https://github.com/Voultapher/sort-research-rs) for more details. - [Document behavior of `create_dir_all` with respect to empty paths.](https://github.com/rust-lang/rust/pull/125112/) - [Fix interleaved output in the default panic hook when multiple threads panic simultaneously.](https://github.com/rust-lang/rust/pull/127397/) - Fix `Command`'s batch files argument escaping not working when file name has trailing whitespace or periods (CVE-2024-43402). <a id="1.81.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`core::error`](https://doc.rust-lang.org/stable/core/error/index.html) - [`hint::assert_unchecked`](https://doc.rust-lang.org/stable/core/hint/fn.assert_unchecked.html) - [`fs::exists`](https://doc.rust-lang.org/stable/std/fs/fn.exists.html) - [`AtomicBool::fetch_not`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicBool.html#method.fetch_not) - [`Duration::abs_diff`](https://doc.rust-lang.org/stable/core/time/struct.Duration.html#method.abs_diff) - [`IoSlice::advance`](https://doc.rust-lang.org/stable/std/io/struct.IoSlice.html#method.advance) - [`IoSlice::advance_slices`](https://doc.rust-lang.org/stable/std/io/struct.IoSlice.html#method.advance_slices) - [`IoSliceMut::advance`](https://doc.rust-lang.org/stable/std/io/struct.IoSliceMut.html#method.advance) - [`IoSliceMut::advance_slices`](https://doc.rust-lang.org/stable/std/io/struct.IoSliceMut.html#method.advance_slices) - [`PanicHookInfo`](https://doc.rust-lang.org/stable/std/panic/struct.PanicHookInfo.html) - [`PanicInfo::message`](https://doc.rust-lang.org/stable/core/panic/struct.PanicInfo.html#method.message) - [`PanicMessage`](https://doc.rust-lang.org/stable/core/panic/struct.PanicMessage.html) These APIs are now stable in const contexts: - [`char::from_u32_unchecked`](https://doc.rust-lang.org/stable/core/char/fn.from_u32_unchecked.html) (function) - [`char::from_u32_unchecked`](https://doc.rust-lang.org/stable/core/primitive.char.html#method.from_u32_unchecked) (method) - [`CStr::count_bytes`](https://doc.rust-lang.org/stable/core/ffi/c_str/struct.CStr.html#method.count_bytes) - [`CStr::from_ptr`](https://doc.rust-lang.org/stable/core/ffi/c_str/struct.CStr.html#method.from_ptr) <a id="1.81.0-Cargo"></a> Cargo ----- - [Generated `.cargo_vcs_info.json` is always included, even when `--allow-dirty` is passed.](https://github.com/rust-lang/cargo/pull/13960/) - [Disallow `package.license-file` and `package.readme` pointing to non-existent files during packaging.](https://github.com/rust-lang/cargo/pull/13921/) - [Disallow passing `--release`/`--debug` flag along with the `--profile` flag.](https://github.com/rust-lang/cargo/pull/13971/) - [Remove `lib.plugin` key support in `Cargo.toml`. Rust plugin support has been deprecated for four years and was removed in 1.75.0.](https://github.com/rust-lang/cargo/pull/13902/) <a id="1.81.0-Compatibility-Notes"></a> Compatibility Notes ------------------- * Usage of the `wasm32-wasi` target will now issue a compiler warning and request users switch to the `wasm32-wasip1` target instead. Both targets are the same, `wasm32-wasi` is only being renamed, and this [change to the WASI target](https://blog.rust-lang.org/2024/04/09/updates-to-rusts-wasi-targets.html) is being done to enable removing `wasm32-wasi` in January 2025. * We have renamed `std::panic::PanicInfo` to `std::panic::PanicHookInfo`. The old name will continue to work as an alias, but will result in a deprecation warning starting in Rust 1.82.0. `core::panic::PanicInfo` will remain unchanged, however, as this is now a *different type*. The reason is that these types have different roles: `std::panic::PanicHookInfo` is the argument to the [panic hook](https://doc.rust-lang.org/stable/std/panic/fn.set_hook.html) in std context (where panics can have an arbitrary payload), while `core::panic::PanicInfo` is the argument to the [`#[panic_handler]`](https://doc.rust-lang.org/nomicon/panic-handler.html) in no_std context (where panics always carry a formatted *message*). Separating these types allows us to add more useful methods to these types, such as `std::panic::PanicHookInfo::payload_as_str()` and `core::panic::PanicInfo::message()`. * The new sort implementations may panic if a type's implementation of [`Ord`](https://doc.rust-lang.org/std/cmp/trait.Ord.html) (or the given comparison function) does not implement a [total order](https://en.wikipedia.org/wiki/Total_order) as the trait requires. `Ord`'s supertraits (`PartialOrd`, `Eq`, and `PartialEq`) must also be consistent. The previous implementations would not "notice" any problem, but the new implementations have a good chance of detecting inconsistencies, throwing a panic rather than returning knowingly unsorted data. * [In very rare cases, a change in the internal evaluation order of the trait solver may result in new fatal overflow errors.](https://github.com/rust-lang/rust/pull/126128) <a id="1.81.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Add a Rust-for-Linux `auto` CI job to check kernel builds.](https://github.com/rust-lang/rust/pull/125209/) Version 1.80.1 (2024-08-08) =========================== <a id="1.80.1"></a> - [Fix miscompilation in the jump threading MIR optimization when comparing floats](https://github.com/rust-lang/rust/pull/128271) - [Revert changes to the `dead_code` lint from 1.80.0](https://github.com/rust-lang/rust/pull/128618) Version 1.80.0 (2024-07-25) ========================== <a id="1.80-Language"></a> Language -------- - [Document maximum allocation size](https://github.com/rust-lang/rust/pull/116675/) - [Allow zero-byte offsets and ZST read/writes on arbitrary pointers](https://github.com/rust-lang/rust/pull/117329/) - [Support C23's variadics without a named parameter](https://github.com/rust-lang/rust/pull/124048/) - [Stabilize `exclusive_range_pattern` feature](https://github.com/rust-lang/rust/pull/124459/) - [Guarantee layout and ABI of `Result` in some scenarios](https://github.com/rust-lang/rust/pull/124870) <a id="1.80-Compiler"></a> Compiler -------- - [Update cc crate to v1.0.97 allowing additional spectre mitigations on MSVC targets](https://github.com/rust-lang/rust/pull/124892/) - [Allow field reordering on types marked `repr(packed(1))`](https://github.com/rust-lang/rust/pull/125360/) - [Add a lint against never type fallback affecting unsafe code](https://github.com/rust-lang/rust/pull/123939/) - [Disallow cast with trailing braced macro in let-else](https://github.com/rust-lang/rust/pull/125049/) - [Expand `for_loops_over_fallibles` lint to lint on fallibles behind references.](https://github.com/rust-lang/rust/pull/125156/) - [self-contained linker: retry linking without `-fuse-ld=lld` on CCs that don't support it](https://github.com/rust-lang/rust/pull/125417/) - [Do not parse CVarArgs (`...`) as a type in trait bounds](https://github.com/rust-lang/rust/pull/125863/) - Improvements to LLDB formatting [#124458](https://github.com/rust-lang/rust/pull/124458) [#124500](https://github.com/rust-lang/rust/pull/124500) - [For the wasm32-wasip2 target default to PIC and do not use `-fuse-ld=lld`](https://github.com/rust-lang/rust/pull/124858/) - [Add x86_64-unknown-linux-none as a tier 3 target](https://github.com/rust-lang/rust/pull/125023/) - [Lint on `foo.into_iter()` resolving to `&Box<[T]>: IntoIterator`](https://github.com/rust-lang/rust/pull/124097/) <a id="1.80-Libraries"></a> Libraries --------- - [Add `size_of` and `size_of_val` and `align_of` and `align_of_val` to the prelude](https://github.com/rust-lang/rust/pull/123168/) - [Abort a process when FD ownership is violated](https://github.com/rust-lang/rust/pull/124210/) - [io::Write::write_fmt: panic if the formatter fails when the stream does not fail](https://github.com/rust-lang/rust/pull/125012/) - [Panic if `PathBuf::set_extension` would add a path separator](https://github.com/rust-lang/rust/pull/125070/) - [Add assert_unsafe_precondition to unchecked_{add,sub,neg,mul,shl,shr} methods](https://github.com/rust-lang/rust/pull/121571/) - [Update `c_char` on AIX to use the correct type](https://github.com/rust-lang/rust/pull/122986/) - [`offset_of!` no longer returns a temporary](https://github.com/rust-lang/rust/pull/124484/) - [Handle sigma in `str.to_lowercase` correctly](https://github.com/rust-lang/rust/pull/124773/) - [Raise `DEFAULT_MIN_STACK_SIZE` to at least 64KiB](https://github.com/rust-lang/rust/pull/126059/) <a id="1.80-Stabilized-APIs"></a> Stabilized APIs --------------- - [`impl Default for Rc<CStr>`](https://doc.rust-lang.org/beta/alloc/rc/struct.Rc.html#impl-Default-for-Rc%3CCStr%3E) - [`impl Default for Rc<str>`](https://doc.rust-lang.org/beta/alloc/rc/struct.Rc.html#impl-Default-for-Rc%3Cstr%3E) - [`impl Default for Rc<[T]>`](https://doc.rust-lang.org/beta/alloc/rc/struct.Rc.html#impl-Default-for-Rc%3C%5BT%5D%3E) - [`impl Default for Arc<str>`](https://doc.rust-lang.org/beta/alloc/sync/struct.Arc.html#impl-Default-for-Arc%3Cstr%3E) - [`impl Default for Arc<CStr>`](https://doc.rust-lang.org/beta/alloc/sync/struct.Arc.html#impl-Default-for-Arc%3CCStr%3E) - [`impl Default for Arc<[T]>`](https://doc.rust-lang.org/beta/alloc/sync/struct.Arc.html#impl-Default-for-Arc%3C%5BT%5D%3E) - [`impl IntoIterator for Box<[T]>`](https://doc.rust-lang.org/beta/alloc/boxed/struct.Box.html#impl-IntoIterator-for-Box%3C%5BI%5D,+A%3E) - [`impl FromIterator<String> for Box<str>`](https://doc.rust-lang.org/beta/alloc/boxed/struct.Box.html#impl-FromIterator%3CString%3E-for-Box%3Cstr%3E) - [`impl FromIterator<char> for Box<str>`](https://doc.rust-lang.org/beta/alloc/boxed/struct.Box.html#impl-FromIterator%3Cchar%3E-for-Box%3Cstr%3E) - [`LazyCell`](https://doc.rust-lang.org/beta/core/cell/struct.LazyCell.html) - [`LazyLock`](https://doc.rust-lang.org/beta/std/sync/struct.LazyLock.html) - [`Duration::div_duration_f32`](https://doc.rust-lang.org/beta/std/time/struct.Duration.html#method.div_duration_f32) - [`Duration::div_duration_f64`](https://doc.rust-lang.org/beta/std/time/struct.Duration.html#method.div_duration_f64) - [`Option::take_if`](https://doc.rust-lang.org/beta/std/option/enum.Option.html#method.take_if) - [`Seek::seek_relative`](https://doc.rust-lang.org/beta/std/io/trait.Seek.html#method.seek_relative) - [`BinaryHeap::as_slice`](https://doc.rust-lang.org/beta/std/collections/struct.BinaryHeap.html#method.as_slice) - [`NonNull::offset`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.offset) - [`NonNull::byte_offset`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.byte_offset) - [`NonNull::add`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.add) - [`NonNull::byte_add`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.byte_add) - [`NonNull::sub`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.sub) - [`NonNull::byte_sub`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.byte_sub) - [`NonNull::offset_from`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.offset_from) - [`NonNull::byte_offset_from`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.byte_offset_from) - [`NonNull::read`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.read) - [`NonNull::read_volatile`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.read_volatile) - [`NonNull::read_unaligned`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.read_unaligned) - [`NonNull::write`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.write) - [`NonNull::write_volatile`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.write_volatile) - [`NonNull::write_unaligned`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.write_unaligned) - [`NonNull::write_bytes`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.write_bytes) - [`NonNull::copy_to`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.copy_to) - [`NonNull::copy_to_nonoverlapping`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.copy_to_nonoverlapping) - [`NonNull::copy_from`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.copy_from) - [`NonNull::copy_from_nonoverlapping`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.copy_from_nonoverlapping) - [`NonNull::replace`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.replace) - [`NonNull::swap`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.swap) - [`NonNull::drop_in_place`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.drop_in_place) - [`NonNull::align_offset`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.align_offset) - [`<[T]>::split_at_checked`](https://doc.rust-lang.org/beta/std/primitive.slice.html#method.split_at_checked) - [`<[T]>::split_at_mut_checked`](https://doc.rust-lang.org/beta/std/primitive.slice.html#method.split_at_mut_checked) - [`str::split_at_checked`](https://doc.rust-lang.org/beta/std/primitive.str.html#method.split_at_checked) - [`str::split_at_mut_checked`](https://doc.rust-lang.org/beta/std/primitive.str.html#method.split_at_mut_checked) - [`str::trim_ascii`](https://doc.rust-lang.org/beta/std/primitive.str.html#method.trim_ascii) - [`str::trim_ascii_start`](https://doc.rust-lang.org/beta/std/primitive.str.html#method.trim_ascii_start) - [`str::trim_ascii_end`](https://doc.rust-lang.org/beta/std/primitive.str.html#method.trim_ascii_end) - [`<[u8]>::trim_ascii`](https://doc.rust-lang.org/beta/core/primitive.slice.html#method.trim_ascii) - [`<[u8]>::trim_ascii_start`](https://doc.rust-lang.org/beta/core/primitive.slice.html#method.trim_ascii_start) - [`<[u8]>::trim_ascii_end`](https://doc.rust-lang.org/beta/core/primitive.slice.html#method.trim_ascii_end) - [`Ipv4Addr::BITS`](https://doc.rust-lang.org/beta/core/net/struct.Ipv4Addr.html#associatedconstant.BITS) - [`Ipv4Addr::to_bits`](https://doc.rust-lang.org/beta/core/net/struct.Ipv4Addr.html#method.to_bits) - [`Ipv4Addr::from_bits`](https://doc.rust-lang.org/beta/core/net/struct.Ipv4Addr.html#method.from_bits) - [`Ipv6Addr::BITS`](https://doc.rust-lang.org/beta/core/net/struct.Ipv6Addr.html#associatedconstant.BITS) - [`Ipv6Addr::to_bits`](https://doc.rust-lang.org/beta/core/net/struct.Ipv6Addr.html#method.to_bits) - [`Ipv6Addr::from_bits`](https://doc.rust-lang.org/beta/core/net/struct.Ipv6Addr.html#method.from_bits) - [`Vec::<[T; N]>::into_flattened`](https://doc.rust-lang.org/beta/alloc/vec/struct.Vec.html#method.into_flattened) - [`<[[T; N]]>::as_flattened`](https://doc.rust-lang.org/beta/core/primitive.slice.html#method.as_flattened) - [`<[[T; N]]>::as_flattened_mut`](https://doc.rust-lang.org/beta/core/primitive.slice.html#method.as_flattened_mut) These APIs are now stable in const contexts: - [`<[T]>::last_chunk`](https://doc.rust-lang.org/beta/core/primitive.slice.html#method.last_chunk) - [`BinaryHeap::new`](https://doc.rust-lang.org/beta/std/collections/struct.BinaryHeap.html#method.new) <a id="1.80-Cargo"></a> Cargo ----- - [Stabilize `-Zcheck-cfg` as always enabled](https://github.com/rust-lang/cargo/pull/13571/) - [Warn, rather than fail publish, if a target is excluded](https://github.com/rust-lang/cargo/pull/13713/) - [Add special `check-cfg` lint config for the `unexpected_cfgs` lint](https://github.com/rust-lang/cargo/pull/13913/) - [Stabilize `cargo update --precise <yanked>`](https://github.com/rust-lang/cargo/pull/13974/) - [Don't change file permissions on `Cargo.toml` when using `cargo add`](https://github.com/rust-lang/cargo/pull/13898/) - [Support using `cargo fix` on IPv6-only networks](https://github.com/rust-lang/cargo/pull/13907/) <a id="1.80-Rustdoc"></a> Rustdoc ----- - [Allow searching for references](https://github.com/rust-lang/rust/pull/124148/) - [Stabilize `custom_code_classes_in_docs` feature](https://github.com/rust-lang/rust/pull/124577/) - [fix: In cross-crate scenarios show enum variants on type aliases of enums](https://github.com/rust-lang/rust/pull/125300/) <a id="1.80-Compatibility-Notes"></a> Compatibility Notes ------------------- - [rustfmt estimates line lengths differently when using non-ascii characters](https://github.com/rust-lang/rustfmt/issues/6203) - [Type aliases are now handled correctly in orphan check](https://github.com/rust-lang/rust/pull/117164/) - [Allow instructing rustdoc to read from stdin via `-`](https://github.com/rust-lang/rust/pull/124611/) - [`std::env::{set_var, remove_var}` can no longer be converted to safe function pointers and no longer implement the `Fn` family of traits](https://github.com/rust-lang/rust/pull/124636) - [Warn (or error) when `Self` constructor from outer item is referenced in inner nested item](https://github.com/rust-lang/rust/pull/124187/) - [Turn `indirect_structural_match` and `pointer_structural_match` lints into hard errors](https://github.com/rust-lang/rust/pull/124661/) - [Make `where_clause_object_safety` lint a regular object safety violation](https://github.com/rust-lang/rust/pull/125380/) - [Turn `proc_macro_back_compat` lint into a hard error.](https://github.com/rust-lang/rust/pull/125596/) - [Detect unused structs even when implementing private traits](https://github.com/rust-lang/rust/pull/122382/) - [`std::sync::ReentrantLockGuard<T>` is no longer `Sync` if `T: !Sync`](https://github.com/rust-lang/rust/pull/125527) which means [`std::io::StdoutLock` and `std::io::StderrLock` are no longer Sync](https://github.com/rust-lang/rust/issues/127340) - [Type inference will fail in some cases due to new implementations of `FromIterator for Box<str>`.](https://github.com/rust-lang/rust/pull/99969/) Notably, this breaks versions of the `time` crate before 0.3.35, due to no longer inferring the implementation for `Box<[_]>`. <a id="1.80-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - Misc improvements to size of generated html by rustdoc e.g. [#124738](https://github.com/rust-lang/rust/pull/124738/) and [#123734](https://github.com/rust-lang/rust/pull/123734/) - [MSVC targets no longer depend on libc](https://github.com/rust-lang/rust/pull/124050/) Version 1.79.0 (2024-06-13) ========================== <a id="1.79.0-Language"></a> Language -------- - [Stabilize inline `const {}` expressions.](https://github.com/rust-lang/rust/pull/104087/) - [Prevent opaque types being instantiated twice with different regions within the same function.](https://github.com/rust-lang/rust/pull/116935/) - [Stabilize WebAssembly target features that are in phase 4 and 5.](https://github.com/rust-lang/rust/pull/117457/) - [Add the `redundant_lifetimes` lint to detect lifetimes which are semantically redundant.](https://github.com/rust-lang/rust/pull/118391/) - [Stabilize the `unnameable_types` lint for public types that can't be named.](https://github.com/rust-lang/rust/pull/120144/) - [Enable debuginfo in macros, and stabilize `-C collapse-macro-debuginfo` and `#[collapse_debuginfo]`.](https://github.com/rust-lang/rust/pull/120845/) - [Propagate temporary lifetime extension into `if` and `match` expressions.](https://github.com/rust-lang/rust/pull/121346/) - [Restrict promotion of `const fn` calls.](https://github.com/rust-lang/rust/pull/121557/) - [Warn against refining impls of crate-private traits with `refining_impl_trait` lint.](https://github.com/rust-lang/rust/pull/121720/) - [Stabilize associated type bounds (RFC 2289).](https://github.com/rust-lang/rust/pull/122055/) - [Stabilize importing `main` from other modules or crates.](https://github.com/rust-lang/rust/pull/122060/) - [Check return types of function types for well-formedness](https://github.com/rust-lang/rust/pull/115538) - [Rework `impl Trait` lifetime inference](https://github.com/rust-lang/rust/pull/116891/) - [Change inductive trait solver cycles to be ambiguous](https://github.com/rust-lang/rust/pull/122791) <a id="1.79.0-Compiler"></a> Compiler -------- - [Define `-C strip` to only affect binaries, not artifacts like `.pdb`.](https://github.com/rust-lang/rust/pull/115120/) - [Stabilize `-Crelro-level` for controlling runtime link hardening.](https://github.com/rust-lang/rust/pull/121694/) - [Stabilize checking of `cfg` names and values at compile-time with `--check-cfg`.](https://github.com/rust-lang/rust/pull/123501/) *Note that this only stabilizes the compiler part, the Cargo part is still unstable in this release.* - [Add `aarch64-apple-visionos` and `aarch64-apple-visionos-sim` tier 3 targets.](https://github.com/rust-lang/rust/pull/121419/) - [Add `riscv32ima-unknown-none-elf` tier 3 target.](https://github.com/rust-lang/rust/pull/122696/) - [Promote several Windows targets to tier 2](https://github.com/rust-lang/rust/pull/121712): `aarch64-pc-windows-gnullvm`, `i686-pc-windows-gnullvm`, and `x86_64-pc-windows-gnullvm`. Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. <a id="1.79.0-Libraries"></a> Libraries --------- - [Implement `FromIterator` for `(impl Default + Extend, impl Default + Extend)`.](https://github.com/rust-lang/rust/pull/107462/) - [Implement `{Div,Rem}Assign<NonZero<X>>` on `X`.](https://github.com/rust-lang/rust/pull/121952/) - [Document overrides of `clone_from()` in core/std.](https://github.com/rust-lang/rust/pull/122201/) - [Link MSVC default lib in core.](https://github.com/rust-lang/rust/pull/122268/) - [Caution against using `transmute` between pointers and integers.](https://github.com/rust-lang/rust/pull/122379/) - [Enable frame pointers for the standard library.](https://github.com/rust-lang/rust/pull/122646/) <a id="1.79.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`{integer}::unchecked_add`](https://doc.rust-lang.org/stable/core/primitive.i32.html#method.unchecked_add) - [`{integer}::unchecked_mul`](https://doc.rust-lang.org/stable/core/primitive.i32.html#method.unchecked_mul) - [`{integer}::unchecked_sub`](https://doc.rust-lang.org/stable/core/primitive.i32.html#method.unchecked_sub) - [`<[T]>::split_at_unchecked`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_at_unchecked) - [`<[T]>::split_at_mut_unchecked`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_at_mut_unchecked) - [`<[u8]>::utf8_chunks`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.utf8_chunks) - [`str::Utf8Chunks`](https://doc.rust-lang.org/stable/core/str/struct.Utf8Chunks.html) - [`str::Utf8Chunk`](https://doc.rust-lang.org/stable/core/str/struct.Utf8Chunk.html) - [`<*const T>::is_aligned`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.is_aligned) - [`<*mut T>::is_aligned`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.is_aligned-1) - [`NonNull::is_aligned`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.is_aligned) - [`<*const [T]>::len`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.len) - [`<*mut [T]>::len`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.len-1) - [`<*const [T]>::is_empty`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.is_empty) - [`<*mut [T]>::is_empty`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.is_empty-1) - [`NonNull::<[T]>::is_empty`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.is_empty) - [`CStr::count_bytes`](https://doc.rust-lang.org/stable/core/ffi/c_str/struct.CStr.html#method.count_bytes) - [`io::Error::downcast`](https://doc.rust-lang.org/stable/std/io/struct.Error.html#method.downcast) - [`num::NonZero<T>`](https://doc.rust-lang.org/stable/core/num/struct.NonZero.html) - [`path::absolute`](https://doc.rust-lang.org/stable/std/path/fn.absolute.html) - [`proc_macro::Literal::byte_character`](https://doc.rust-lang.org/stable/proc_macro/struct.Literal.html#method.byte_character) - [`proc_macro::Literal::c_string`](https://doc.rust-lang.org/stable/proc_macro/struct.Literal.html#method.c_string) These APIs are now stable in const contexts: - [`Atomic*::into_inner`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicUsize.html#method.into_inner) - [`io::Cursor::new`](https://doc.rust-lang.org/stable/std/io/struct.Cursor.html#method.new) - [`io::Cursor::get_ref`](https://doc.rust-lang.org/stable/std/io/struct.Cursor.html#method.get_ref) - [`io::Cursor::position`](https://doc.rust-lang.org/stable/std/io/struct.Cursor.html#method.position) - [`io::empty`](https://doc.rust-lang.org/stable/std/io/fn.empty.html) - [`io::repeat`](https://doc.rust-lang.org/stable/std/io/fn.repeat.html) - [`io::sink`](https://doc.rust-lang.org/stable/std/io/fn.sink.html) - [`panic::Location::caller`](https://doc.rust-lang.org/stable/std/panic/struct.Location.html#method.caller) - [`panic::Location::file`](https://doc.rust-lang.org/stable/std/panic/struct.Location.html#method.file) - [`panic::Location::line`](https://doc.rust-lang.org/stable/std/panic/struct.Location.html#method.line) - [`panic::Location::column`](https://doc.rust-lang.org/stable/std/panic/struct.Location.html#method.column) <a id="1.79.0-Cargo"></a> Cargo ----- - [Prevent dashes in `lib.name`, always normalizing to `_`.](https://github.com/rust-lang/cargo/pull/12783/) - [Stabilize MSRV-aware version requirement selection in `cargo add`.](https://github.com/rust-lang/cargo/pull/13608/) - [Switch to using `gitoxide` by default for listing files.](https://github.com/rust-lang/cargo/pull/13696/) <a id="1.79.0-Rustdoc"></a> Rustdoc ----- - [Always display stability version even if it's the same as the containing item.](https://github.com/rust-lang/rust/pull/118441/) - [Show a single search result for items with multiple paths.](https://github.com/rust-lang/rust/pull/119912/) - [Support typing `/` in docs to begin a search.](https://github.com/rust-lang/rust/pull/123355/) <a id="1.79.0-Misc"></a> Misc ---- <a id="1.79.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Update the minimum external LLVM to 17.](https://github.com/rust-lang/rust/pull/122649/) - [`RustcEncodable` and `RustcDecodable` are soft-destabilized, to be removed from the prelude in next edition.](https://github.com/rust-lang/rust/pull/116016/) - [The `wasm_c_abi` future-incompatibility lint will warn about use of the non-spec-compliant C ABI.](https://github.com/rust-lang/rust/pull/117918/) Use `wasm-bindgen v0.2.88` to generate forward-compatible bindings. - [Check return types of function types for well-formedness](https://github.com/rust-lang/rust/pull/115538) Version 1.78.0 (2024-05-02) ========================== <a id="1.78.0-Language"></a> Language -------- - [Stabilize `#[cfg(target_abi = ...)]`](https://github.com/rust-lang/rust/pull/119590/) - [Stabilize the `#[diagnostic]` namespace and `#[diagnostic::on_unimplemented]` attribute](https://github.com/rust-lang/rust/pull/119888/) - [Make async-fn-in-trait implementable with concrete signatures](https://github.com/rust-lang/rust/pull/120103/) - [Make matching on NaN a hard error, and remove the rest of `illegal_floating_point_literal_pattern`](https://github.com/rust-lang/rust/pull/116284/) - [static mut: allow mutable reference to arbitrary types, not just slices and arrays](https://github.com/rust-lang/rust/pull/117614/) - [Extend `invalid_reference_casting` to include references casting to bigger memory layout](https://github.com/rust-lang/rust/pull/118983/) - [Add `non_contiguous_range_endpoints` lint for singleton gaps after exclusive ranges](https://github.com/rust-lang/rust/pull/118879/) - [Add `wasm_c_abi` lint for use of older wasm-bindgen versions](https://github.com/rust-lang/rust/pull/117918/) This lint currently only works when using Cargo. - [Update `indirect_structural_match` and `pointer_structural_match` lints to match RFC](https://github.com/rust-lang/rust/pull/120423/) - [Make non-`PartialEq`-typed consts as patterns a hard error](https://github.com/rust-lang/rust/pull/120805/) - [Split `refining_impl_trait` lint into `_reachable`, `_internal` variants](https://github.com/rust-lang/rust/pull/121720/) - [Remove unnecessary type inference when using associated types inside of higher ranked `where`-bounds](https://github.com/rust-lang/rust/pull/119849) - [Weaken eager detection of cyclic types during type inference](https://github.com/rust-lang/rust/pull/119989) - [`trait Trait: Auto {}`: allow upcasting from `dyn Trait` to `dyn Trait + Auto`](https://github.com/rust-lang/rust/pull/119338) <a id="1.78.0-Compiler"></a> Compiler -------- - [Made `INVALID_DOC_ATTRIBUTES` lint deny by default](https://github.com/rust-lang/rust/pull/111505/) - [Increase accuracy of redundant `use` checking](https://github.com/rust-lang/rust/pull/117772/) - [Suggest moving definition if non-found macro_rules! is defined later](https://github.com/rust-lang/rust/pull/121130/) - [Lower transmutes from int to pointer type as gep on null](https://github.com/rust-lang/rust/pull/121282/) Target changes: - [Windows tier 1 targets now require at least Windows 10](https://github.com/rust-lang/rust/pull/115141/) - [Enable CMPXCHG16B, SSE3, SAHF/LAHF and 128-bit Atomics in tier 1 Windows](https://github.com/rust-lang/rust/pull/120820/) - [Add `wasm32-wasip1` tier 2 (without host tools) target](https://github.com/rust-lang/rust/pull/120468/) - [Add `wasm32-wasip2` tier 3 target](https://github.com/rust-lang/rust/pull/119616/) - [Rename `wasm32-wasi-preview1-threads` to `wasm32-wasip1-threads`](https://github.com/rust-lang/rust/pull/122170/) - [Add `arm64ec-pc-windows-msvc` tier 3 target](https://github.com/rust-lang/rust/pull/119199/) - [Add `armv8r-none-eabihf` tier 3 target for the Cortex-R52](https://github.com/rust-lang/rust/pull/110482/) - [Add `loongarch64-unknown-linux-musl` tier 3 target](https://github.com/rust-lang/rust/pull/121832/) Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. <a id="1.78.0-Libraries"></a> Libraries --------- - [Bump Unicode to version 15.1.0, regenerate tables](https://github.com/rust-lang/rust/pull/120777/) - [Make align_offset, align_to well-behaved in all cases](https://github.com/rust-lang/rust/pull/121201/) - [PartialEq, PartialOrd: document expectations for transitive chains](https://github.com/rust-lang/rust/pull/115386/) - [Optimize away poison guards when std is built with panic=abort](https://github.com/rust-lang/rust/pull/100603/) - [Replace pthread `RwLock` with custom implementation](https://github.com/rust-lang/rust/pull/110211/) - [Implement unwind safety for Condvar on all platforms](https://github.com/rust-lang/rust/pull/121768/) - [Add ASCII fast-path for `char::is_grapheme_extended`](https://github.com/rust-lang/rust/pull/121138/) <a id="1.78.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`impl Read for &Stdin`](https://doc.rust-lang.org/stable/std/io/struct.Stdin.html#impl-Read-for-%26Stdin) - [Accept non `'static` lifetimes for several `std::error::Error` related implementations](https://github.com/rust-lang/rust/pull/113833/) - [Make `impl<Fd: AsFd>` impl take `?Sized`](https://github.com/rust-lang/rust/pull/114655/) - [`impl From<TryReserveError> for io::Error`](https://doc.rust-lang.org/stable/std/io/struct.Error.html#impl-From%3CTryReserveError%3E-for-Error) These APIs are now stable in const contexts: - [`Barrier::new()`](https://doc.rust-lang.org/stable/std/sync/struct.Barrier.html#method.new) <a id="1.78.0-Cargo"></a> Cargo ----- - [Stabilize lockfile v4](https://github.com/rust-lang/cargo/pull/12852/) - [Respect `rust-version` when generating lockfile](https://github.com/rust-lang/cargo/pull/12861/) - [Control `--charset` via auto-detecting config value](https://github.com/rust-lang/cargo/pull/13337/) - [Support `target.<triple>.rustdocflags` officially](https://github.com/rust-lang/cargo/pull/13197/) - [Stabilize global cache data tracking](https://github.com/rust-lang/cargo/pull/13492/) <a id="1.78.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Many unsafe precondition checks now run for user code with debug assertions enabled](https://github.com/rust-lang/rust/pull/120594/) This change helps users catch undefined behavior in their code, though the details of how much is checked are generally not stable. - [riscv only supports split_debuginfo=off for now](https://github.com/rust-lang/rust/pull/120518/) - [Consistently check bounds on hidden types of `impl Trait`](https://github.com/rust-lang/rust/pull/121679) - [Change equality of higher ranked types to not rely on subtyping](https://github.com/rust-lang/rust/pull/118247) - [When called, additionally check bounds on normalized function return type](https://github.com/rust-lang/rust/pull/118882) - [Expand coverage for `arithmetic_overflow` lint](https://github.com/rust-lang/rust/pull/119432/) - [Fix detection of potential interior mutability in `const` initializers](https://github.com/rust-lang/rust/issues/121250) This code was accidentally accepted. The fix can break generic code that borrows a value of unknown type, as there is currently no way to declare "this type has no interior mutability". In the future, stabilizing the [`Freeze` trait](https://github.com/rust-lang/rust/issues/121675) will allow proper support for such code. <a id="1.78.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Update to LLVM 18](https://github.com/rust-lang/rust/pull/120055/) - [Build `rustc` with 1CGU on `x86_64-pc-windows-msvc`](https://github.com/rust-lang/rust/pull/112267/) - [Build `rustc` with 1CGU on `x86_64-apple-darwin`](https://github.com/rust-lang/rust/pull/112268/) - [Introduce `run-make` V2 infrastructure, a `run_make_support` library and port over 2 tests as example](https://github.com/rust-lang/rust/pull/113026/) - [Windows: Implement condvar, mutex and rwlock using futex](https://github.com/rust-lang/rust/pull/121956/) Version 1.77.2 (2024-04-09) =========================== <a id="1.77.2"></a> - [CVE-2024-24576: fix escaping of Windows batch file arguments in `std::process::Command`](https://blog.rust-lang.org/2024/04/09/cve-2024-24576.html) Version 1.77.1 (2024-03-28) =========================== <a id="1.77.1"></a> - [Revert stripping debuginfo by default for Windows](https://github.com/rust-lang/cargo/pull/13654) This fixes a regression in 1.77 by reverting to the previous default. Platforms other than Windows are not affected. - Internal: [Fix heading anchor rendering in doc pages](https://github.com/rust-lang/rust/pull/122693) Version 1.77.0 (2024-03-21) ========================== <a id="1.77.0-Language"></a> Language -------- - [Reveal opaque types within the defining body for exhaustiveness checking.](https://github.com/rust-lang/rust/pull/116821/) - [Stabilize C-string literals.](https://github.com/rust-lang/rust/pull/117472/) - [Stabilize THIR unsafeck.](https://github.com/rust-lang/rust/pull/117673/) - [Add lint `static_mut_refs` to warn on references to mutable statics.](https://github.com/rust-lang/rust/pull/117556/) - [Support async recursive calls (as long as they have indirection).](https://github.com/rust-lang/rust/pull/117703/) - [Undeprecate lint `unstable_features` and make use of it in the compiler.](https://github.com/rust-lang/rust/pull/118639/) - [Make inductive cycles in coherence ambiguous always.](https://github.com/rust-lang/rust/pull/118649/) - [Get rid of type-driven traversal in const-eval interning](https://github.com/rust-lang/rust/pull/119044/), only as a [future compatibility lint](https://github.com/rust-lang/rust/pull/122204) for now. - [Deny braced macro invocations in let-else.](https://github.com/rust-lang/rust/pull/119062/) <a id="1.77.0-Compiler"></a> Compiler -------- - [Include lint `soft_unstable` in future breakage reports.](https://github.com/rust-lang/rust/pull/116274/) - [Make `i128` and `u128` 16-byte aligned on x86-based targets.](https://github.com/rust-lang/rust/pull/116672/) - [Use `--verbose` in diagnostic output.](https://github.com/rust-lang/rust/pull/119129/) - [Improve spacing between printed tokens.](https://github.com/rust-lang/rust/pull/120227/) - [Merge the `unused_tuple_struct_fields` lint into `dead_code`.](https://github.com/rust-lang/rust/pull/118297/) - [Error on incorrect implied bounds in well-formedness check](https://github.com/rust-lang/rust/pull/118553/), with a temporary exception for Bevy. - [Fix coverage instrumentation/reports for non-ASCII source code.](https://github.com/rust-lang/rust/pull/119033/) - [Fix `fn`/`const` items implied bounds and well-formedness check.](https://github.com/rust-lang/rust/pull/120019/) - [Promote `riscv32{im|imafc}-unknown-none-elf` targets to tier 2.](https://github.com/rust-lang/rust/pull/118704/) - Add several new tier 3 targets: - [`aarch64-unknown-illumos`](https://github.com/rust-lang/rust/pull/112936/) - [`hexagon-unknown-none-elf`](https://github.com/rust-lang/rust/pull/117601/) - [`riscv32imafc-esp-espidf`](https://github.com/rust-lang/rust/pull/119738/) - [`riscv32im-risc0-zkvm-elf`](https://github.com/rust-lang/rust/pull/117958/) Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. <a id="1.77.0-Libraries"></a> Libraries --------- - [Implement `From<&[T; N]>` for `Cow<[T]>`.](https://github.com/rust-lang/rust/pull/113489/) - [Remove special-case handling of `vec.split_off(0)`.](https://github.com/rust-lang/rust/pull/119917/) <a id="1.77.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`array::each_ref`](https://doc.rust-lang.org/stable/std/primitive.array.html#method.each_ref) - [`array::each_mut`](https://doc.rust-lang.org/stable/std/primitive.array.html#method.each_mut) - [`core::net`](https://doc.rust-lang.org/stable/core/net/index.html) - [`f32::round_ties_even`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.round_ties_even) - [`f64::round_ties_even`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.round_ties_even) - [`mem::offset_of!`](https://doc.rust-lang.org/stable/std/mem/macro.offset_of.html) - [`slice::first_chunk`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.first_chunk) - [`slice::first_chunk_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.first_chunk_mut) - [`slice::split_first_chunk`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_first_chunk) - [`slice::split_first_chunk_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_first_chunk_mut) - [`slice::last_chunk`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.last_chunk) - [`slice::last_chunk_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.last_chunk_mut) - [`slice::split_last_chunk`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_last_chunk) - [`slice::split_last_chunk_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_last_chunk_mut) - [`slice::chunk_by`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.chunk_by) - [`slice::chunk_by_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.chunk_by_mut) - [`Bound::map`](https://doc.rust-lang.org/stable/std/ops/enum.Bound.html#method.map) - [`File::create_new`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.create_new) - [`Mutex::clear_poison`](https://doc.rust-lang.org/stable/std/sync/struct.Mutex.html#method.clear_poison) - [`RwLock::clear_poison`](https://doc.rust-lang.org/stable/std/sync/struct.RwLock.html#method.clear_poison) <a id="1.77.0-Cargo"></a> Cargo ----- - [Extend the build directive syntax with `cargo::`.](https://github.com/rust-lang/cargo/pull/12201/) - [Stabilize metadata `id` format as `PackageIDSpec`.](https://github.com/rust-lang/cargo/pull/12914/) - [Pull out `cargo-util-schemas` as a crate.](https://github.com/rust-lang/cargo/pull/13178/) - [Strip all debuginfo when debuginfo is not requested.](https://github.com/rust-lang/cargo/pull/13257/) - [Inherit jobserver from env for all kinds of runners.](https://github.com/rust-lang/cargo/pull/12776/) - [Deprecate rustc plugin support in cargo.](https://github.com/rust-lang/cargo/pull/13248/) <a id="1.77.0-Rustdoc"></a> Rustdoc ----- - [Allows links in markdown headings.](https://github.com/rust-lang/rust/pull/117662/) - [Search for tuples and unit by type with `()`.](https://github.com/rust-lang/rust/pull/118194/) - [Clean up the source sidebar's hide button.](https://github.com/rust-lang/rust/pull/119066/) - [Prevent JS injection from `localStorage`.](https://github.com/rust-lang/rust/pull/120250/) <a id="1.77.0-Misc"></a> Misc ---- - [Recommend version-sorting for all sorting in style guide.](https://github.com/rust-lang/rust/pull/115046/) <a id="1.77.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Add more weirdness to `weird-exprs.rs`.](https://github.com/rust-lang/rust/pull/119028/) Version 1.76.0 (2024-02-08) ========================== <a id="1.76.0-Language"></a> Language -------- - [Document Rust ABI compatibility between various types](https://github.com/rust-lang/rust/pull/115476/) - [Also: guarantee that char and u32 are ABI-compatible](https://github.com/rust-lang/rust/pull/118032/) - [Add lint `ambiguous_wide_pointer_comparisons` that supersedes `clippy::vtable_address_comparisons`](https://github.com/rust-lang/rust/pull/117758) <a id="1.76.0-Compiler"></a> Compiler -------- - [Lint pinned `#[must_use]` pointers (in particular, `Box<T>` where `T` is `#[must_use]`) in `unused_must_use`.](https://github.com/rust-lang/rust/pull/118054/) - [Soundness fix: fix computing the offset of an unsized field in a packed struct](https://github.com/rust-lang/rust/pull/118540/) - [Soundness fix: fix dynamic size/align computation logic for packed types with dyn Trait tail](https://github.com/rust-lang/rust/pull/118538/) - [Add `$message_type` field to distinguish json diagnostic outputs](https://github.com/rust-lang/rust/pull/115691/) - [Enable Rust to use the EHCont security feature of Windows](https://github.com/rust-lang/rust/pull/118013/) - [Add tier 3 {x86_64,i686}-win7-windows-msvc targets](https://github.com/rust-lang/rust/pull/118150/) - [Add tier 3 aarch64-apple-watchos target](https://github.com/rust-lang/rust/pull/119074/) - [Add tier 3 arm64e-apple-ios & arm64e-apple-darwin targets](https://github.com/rust-lang/rust/pull/115526/) Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. <a id="1.76.0-Libraries"></a> Libraries --------- - [Add a column number to `dbg!()`](https://github.com/rust-lang/rust/pull/114962/) - [Add `std::hash::{DefaultHasher, RandomState}` exports](https://github.com/rust-lang/rust/pull/115694/) - [Fix rounding issue with exponents in fmt](https://github.com/rust-lang/rust/pull/116301/) - [Add T: ?Sized to `RwLockReadGuard` and `RwLockWriteGuard`'s Debug impls.](https://github.com/rust-lang/rust/pull/117138/) - [Windows: Allow `File::create` to work on hidden files](https://github.com/rust-lang/rust/pull/116438/) <a id="1.76.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`Arc::unwrap_or_clone`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#method.unwrap_or_clone) - [`Rc::unwrap_or_clone`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#method.unwrap_or_clone) - [`Result::inspect`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.inspect) - [`Result::inspect_err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.inspect_err) - [`Option::inspect`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.inspect) - [`type_name_of_val`](https://doc.rust-lang.org/stable/std/any/fn.type_name_of_val.html) - [`std::hash::{DefaultHasher, RandomState}`](https://doc.rust-lang.org/stable/std/hash/index.html#structs) These were previously available only through `std::collections::hash_map`. - [`ptr::{from_ref, from_mut}`](https://doc.rust-lang.org/stable/std/ptr/fn.from_ref.html) - [`ptr::addr_eq`](https://doc.rust-lang.org/stable/std/ptr/fn.addr_eq.html) <a id="1.76.0-Cargo"></a> Cargo ----- See [Cargo release notes](https://github.com/rust-lang/cargo/blob/master/CHANGELOG.md#cargo-176-2024-02-08). <a id="1.76.0-Rustdoc"></a> Rustdoc ------- - [Don't merge cfg and doc(cfg) attributes for re-exports](https://github.com/rust-lang/rust/pull/113091/) - [rustdoc: allow resizing the sidebar / hiding the top bar](https://github.com/rust-lang/rust/pull/115660/) - [rustdoc-search: add support for traits and associated types](https://github.com/rust-lang/rust/pull/116085/) - [rustdoc: Add highlighting for comments in items declaration](https://github.com/rust-lang/rust/pull/117869/) <a id="1.76.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Add allow-by-default lint for unit bindings](https://github.com/rust-lang/rust/pull/112380/) This is expected to be upgraded to a warning by default in a future Rust release. Some macros emit bindings with type `()` with user-provided spans, which means that this lint will warn for user code. - [Remove x86_64-sun-solaris target.](https://github.com/rust-lang/rust/pull/118091/) - [Remove asmjs-unknown-emscripten target](https://github.com/rust-lang/rust/pull/117338/) - [Report errors in jobserver inherited through environment variables](https://github.com/rust-lang/rust/pull/113730/) This [may warn](https://github.com/rust-lang/rust/issues/120515) on benign problems too. - [Update the minimum external LLVM to 16.](https://github.com/rust-lang/rust/pull/117947/) - [Improve `print_tts`](https://github.com/rust-lang/rust/pull/114571/) This change can break some naive manual parsing of token trees in proc macro code which expect a particular structure after `.to_string()`, rather than just arbitrary Rust code. - [Make `IMPLIED_BOUNDS_ENTAILMENT` into a hard error from a lint](https://github.com/rust-lang/rust/pull/117984/) - [Vec's allocation behavior was changed when collecting some iterators](https://github.com/rust-lang/rust/pull/110353) Allocation behavior is currently not specified, nevertheless changes can be surprising. See [`impl FromIterator for Vec`](https://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#impl-FromIterator%3CT%3E-for-Vec%3CT%3E) for more details. - [Properly reject `default` on free const items](https://github.com/rust-lang/rust/pull/117818/) Version 1.75.0 (2023-12-28) ========================== <a id="1.75.0-Language"></a> Language -------- - [Stabilize `async fn` and return-position `impl Trait` in traits.](https://github.com/rust-lang/rust/pull/115822/) - [Allow function pointer signatures containing `&mut T` in `const` contexts.](https://github.com/rust-lang/rust/pull/116015/) - [Match `usize`/`isize` exhaustively with half-open ranges.](https://github.com/rust-lang/rust/pull/116692/) - [Guarantee that `char` has the same size and alignment as `u32`.](https://github.com/rust-lang/rust/pull/116894/) - [Document that the null pointer has the 0 address.](https://github.com/rust-lang/rust/pull/116988/) - [Allow partially moved values in `match`.](https://github.com/rust-lang/rust/pull/103208/) - [Add notes about non-compliant FP behavior on 32bit x86 targets.](https://github.com/rust-lang/rust/pull/113053/) - [Stabilize ratified RISC-V target features.](https://github.com/rust-lang/rust/pull/116485/) <a id="1.75.0-Compiler"></a> Compiler -------- - [Rework negative coherence to properly consider impls that only partly overlap.](https://github.com/rust-lang/rust/pull/112875/) - [Bump `COINDUCTIVE_OVERLAP_IN_COHERENCE` to deny, and warn in dependencies.](https://github.com/rust-lang/rust/pull/116493/) - [Consider alias bounds when computing liveness in NLL.](https://github.com/rust-lang/rust/pull/116733/) - [Add the V (vector) extension to the `riscv64-linux-android` target spec.](https://github.com/rust-lang/rust/pull/116618/) - [Automatically enable cross-crate inlining for small functions](https://github.com/rust-lang/rust/pull/116505) - Add several new tier 3 targets: - [`csky-unknown-linux-gnuabiv2hf`](https://github.com/rust-lang/rust/pull/117049/) - [`i586-unknown-netbsd`](https://github.com/rust-lang/rust/pull/117170/) - [`mipsel-unknown-netbsd`](https://github.com/rust-lang/rust/pull/117356/) Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. <a id="1.75.0-Libraries"></a> Libraries --------- - [Override `Waker::clone_from` to avoid cloning `Waker`s unnecessarily.](https://github.com/rust-lang/rust/pull/96979/) - [Implement `BufRead` for `VecDeque<u8>`.](https://github.com/rust-lang/rust/pull/110604/) - [Implement `FusedIterator` for `DecodeUtf16` when the inner iterator does.](https://github.com/rust-lang/rust/pull/110729/) - [Implement `Not, Bit{And,Or}{,Assign}` for IP addresses.](https://github.com/rust-lang/rust/pull/113747/) - [Implement `Default` for `ExitCode`.](https://github.com/rust-lang/rust/pull/114589/) - [Guarantee representation of None in NPO](https://github.com/rust-lang/rust/pull/115333/) - [Document when atomic loads are guaranteed read-only.](https://github.com/rust-lang/rust/pull/115577/) - [Broaden the consequences of recursive TLS initialization.](https://github.com/rust-lang/rust/pull/116172/) - [Windows: Support sub-millisecond sleep.](https://github.com/rust-lang/rust/pull/116461/) - [Fix generic bound of `str::SplitInclusive`'s `DoubleEndedIterator` impl](https://github.com/rust-lang/rust/pull/100806/) - [Fix exit status / wait status on non-Unix `cfg(unix)` platforms.](https://github.com/rust-lang/rust/pull/115108/) <a id="1.75.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`Atomic*::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicUsize.html#method.from_ptr) - [`FileTimes`](https://doc.rust-lang.org/stable/std/fs/struct.FileTimes.html) - [`FileTimesExt`](https://doc.rust-lang.org/stable/std/os/windows/fs/trait.FileTimesExt.html) - [`File::set_modified`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.set_modified) - [`File::set_times`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.set_times) - [`IpAddr::to_canonical`](https://doc.rust-lang.org/stable/core/net/enum.IpAddr.html#method.to_canonical) - [`Ipv6Addr::to_canonical`](https://doc.rust-lang.org/stable/core/net/struct.Ipv6Addr.html#method.to_canonical) - [`Option::as_slice`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.as_slice) - [`Option::as_mut_slice`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.as_mut_slice) - [`pointer::byte_add`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.byte_add) - [`pointer::byte_offset`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.byte_offset) - [`pointer::byte_offset_from`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.byte_offset_from) - [`pointer::byte_sub`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.byte_sub) - [`pointer::wrapping_byte_add`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.wrapping_byte_add) - [`pointer::wrapping_byte_offset`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.wrapping_byte_offset) - [`pointer::wrapping_byte_sub`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.wrapping_byte_sub) These APIs are now stable in const contexts: - [`Ipv6Addr::to_ipv4_mapped`](https://doc.rust-lang.org/stable/core/net/struct.Ipv6Addr.html#method.to_ipv4_mapped) - [`MaybeUninit::assume_init_read`](https://doc.rust-lang.org/stable/core/mem/union.MaybeUninit.html#method.assume_init_read) - [`MaybeUninit::zeroed`](https://doc.rust-lang.org/stable/core/mem/union.MaybeUninit.html#method.zeroed) - [`mem::discriminant`](https://doc.rust-lang.org/stable/core/mem/fn.discriminant.html) - [`mem::zeroed`](https://doc.rust-lang.org/stable/core/mem/fn.zeroed.html) <a id="1.75.0-Cargo"></a> Cargo ----- - [Add new packages to `[workspace.members]` automatically.](https://github.com/rust-lang/cargo/pull/12779/) - [Allow version-less `Cargo.toml` manifests.](https://github.com/rust-lang/cargo/pull/12786/) - [Make browser links out of HTML file paths.](https://github.com/rust-lang/cargo/pull/12889) <a id="1.75.0-Rustdoc"></a> Rustdoc ------- - [Accept less invalid Rust in rustdoc.](https://github.com/rust-lang/rust/pull/117450/) - [Document lack of object safety on affected traits.](https://github.com/rust-lang/rust/pull/113241/) - [Hide `#[repr(transparent)]` if it isn't part of the public ABI.](https://github.com/rust-lang/rust/pull/115439/) - [Show enum discriminant if it is a C-like variant.](https://github.com/rust-lang/rust/pull/116142/) <a id="1.75.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [FreeBSD targets now require at least version 12.](https://github.com/rust-lang/rust/pull/114521/) - [Formally demote tier 2 MIPS targets to tier 3.](https://github.com/rust-lang/rust/pull/115238/) - [Make misalignment a hard error in `const` contexts.](https://github.com/rust-lang/rust/pull/115524/) - [Fix detecting references to packed unsized fields.](https://github.com/rust-lang/rust/pull/115583/) - [Remove support for compiler plugins.](https://github.com/rust-lang/rust/pull/116412/) <a id="1.75.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Optimize `librustc_driver.so` with BOLT.](https://github.com/rust-lang/rust/pull/116352/) - [Enable parallel rustc front end in dev and nightly builds.](https://github.com/rust-lang/rust/pull/117435/) - [Distribute `rustc-codegen-cranelift` as rustup component on the nightly channel.](https://github.com/rust-lang/rust/pull/81746/) Version 1.74.1 (2023-12-07) =========================== - [Resolved spurious STATUS_ACCESS_VIOLATIONs in LLVM](https://github.com/rust-lang/rust/pull/118464) - [Clarify guarantees for std::mem::discriminant](https://github.com/rust-lang/rust/pull/118006) - [Fix some subtyping-related regressions](https://github.com/rust-lang/rust/pull/116415) Version 1.74.0 (2023-11-16) ========================== <a id="1.74.0-Language"></a> Language -------- - [Codify that `std::mem::Discriminant<T>` does not depend on any lifetimes in T](https://github.com/rust-lang/rust/pull/104299/) - [Replace `private_in_public` lint with `private_interfaces` and `private_bounds` per RFC 2145.](https://github.com/rust-lang/rust/pull/113126/) Read more in [RFC 2145](https://rust-lang.github.io/rfcs/2145-type-privacy.html). - [Allow explicit `#[repr(Rust)]`](https://github.com/rust-lang/rust/pull/114201/) - [closure field capturing: don't depend on alignment of packed fields](https://github.com/rust-lang/rust/pull/115315/) - [Enable MIR-based drop-tracking for `async` blocks](https://github.com/rust-lang/rust/pull/107421/) - [Stabilize `impl_trait_projections`](https://github.com/rust-lang/rust/pull/115659) <a id="1.74.0-Compiler"></a> Compiler -------- - [stabilize combining +bundle and +whole-archive link modifiers](https://github.com/rust-lang/rust/pull/113301/) - [Stabilize `PATH` option for `--print KIND=PATH`](https://github.com/rust-lang/rust/pull/114183/) - [Enable ASAN/LSAN/TSAN for `*-apple-ios-macabi`](https://github.com/rust-lang/rust/pull/115644/) - [Promote loongarch64-unknown-none* to Tier 2](https://github.com/rust-lang/rust/pull/115368/) - [Add `i686-pc-windows-gnullvm` as a tier 3 target](https://github.com/rust-lang/rust/pull/115687/) <a id="1.74.0-Libraries"></a> Libraries --------- - [Implement `From<OwnedFd/Handle>` for ChildStdin/out/err](https://github.com/rust-lang/rust/pull/98704/) - [Implement `From<{&,&mut} [T; N]>` for `Vec<T>` where `T: Clone`](https://github.com/rust-lang/rust/pull/111278/) - [impl Step for IP addresses](https://github.com/rust-lang/rust/pull/113748/) - [Implement `From<[T; N]>` for `Rc<[T]>` and `Arc<[T]>`](https://github.com/rust-lang/rust/pull/114041/) - [`impl TryFrom<char> for u16`](https://github.com/rust-lang/rust/pull/114065/) - [Stabilize `io_error_other` feature](https://github.com/rust-lang/rust/pull/115453/) - [Stabilize the `Saturating` type](https://github.com/rust-lang/rust/pull/115477/) - [Stabilize const_transmute_copy](https://github.com/rust-lang/rust/pull/115520/) <a id="1.74.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`core::num::Saturating`](https://doc.rust-lang.org/stable/std/num/struct.Saturating.html) - [`impl From<io::Stdout> for std::process::Stdio`](https://doc.rust-lang.org/stable/std/process/struct.Stdio.html#impl-From%3CStdout%3E-for-Stdio) - [`impl From<io::Stderr> for std::process::Stdio`](https://doc.rust-lang.org/stable/std/process/struct.Stdio.html#impl-From%3CStderr%3E-for-Stdio) - [`impl From<OwnedHandle> for std::process::Child{Stdin, Stdout, Stderr}`](https://doc.rust-lang.org/stable/std/process/struct.ChildStderr.html#impl-From%3COwnedHandle%3E-for-ChildStderr) - [`impl From<OwnedFd> for std::process::Child{Stdin, Stdout, Stderr}`](https://doc.rust-lang.org/stable/std/process/struct.ChildStderr.html#impl-From%3COwnedFd%3E-for-ChildStderr) - [`std::ffi::OsString::from_encoded_bytes_unchecked`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.from_encoded_bytes_unchecked) - [`std::ffi::OsString::into_encoded_bytes`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.into_encoded_bytes) - [`std::ffi::OsStr::from_encoded_bytes_unchecked`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html#method.from_encoded_bytes_unchecked) - [`std::ffi::OsStr::as_encoded_bytes`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html#method.as_encoded_bytes) - [`std::io::Error::other`](https://doc.rust-lang.org/stable/std/io/struct.Error.html#method.other) - [`impl TryFrom<char> for u16`](https://doc.rust-lang.org/stable/std/primitive.u16.html#impl-TryFrom%3Cchar%3E-for-u16) - [`impl<T: Clone, const N: usize> From<&[T; N]> for Vec<T>`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#impl-From%3C%26%5BT;+N%5D%3E-for-Vec%3CT,+Global%3E) - [`impl<T: Clone, const N: usize> From<&mut [T; N]> for Vec<T>`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#impl-From%3C%26mut+%5BT;+N%5D%3E-for-Vec%3CT,+Global%3E) - [`impl<T, const N: usize> From<[T; N]> for Arc<[T]>`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#impl-From%3C%5BT;+N%5D%3E-for-Arc%3C%5BT%5D,+Global%3E) - [`impl<T, const N: usize> From<[T; N]> for Rc<[T]>`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#impl-From%3C%5BT;+N%5D%3E-for-Rc%3C%5BT%5D,+Global%3E) These APIs are now stable in const contexts: - [`core::mem::transmute_copy`](https://doc.rust-lang.org/beta/std/mem/fn.transmute_copy.html) - [`str::is_ascii`](https://doc.rust-lang.org/beta/std/primitive.str.html#method.is_ascii) - [`[u8]::is_ascii`](https://doc.rust-lang.org/beta/std/primitive.slice.html#method.is_ascii) <a id="1.74.0-Cargo"></a> Cargo ----- - [In `Cargo.toml`, stabilize `[lints]`](https://github.com/rust-lang/cargo/pull/12648/) - [Stabilize credential-process and registry-auth](https://github.com/rust-lang/cargo/pull/12649/) - [Stabilize `--keep-going` build flag](https://github.com/rust-lang/cargo/pull/12568/) - [Add styling to `--help` output](https://github.com/rust-lang/cargo/pull/12578/) - [For `cargo clean`, add `--dry-run` flag and summary line at the end](https://github.com/rust-lang/cargo/pull/12638) - [For `cargo update`, make `--package` more convenient by being positional](https://github.com/rust-lang/cargo/pull/12545/) - [For `cargo update`, clarify meaning of --aggressive as --recursive](https://github.com/rust-lang/cargo/pull/12544/) - [Add '-n' as an alias for `--dry-run`](https://github.com/rust-lang/cargo/pull/12660/) - [Allow version-prefixes in pkgid's (e.g. `--package` flags) to resolve ambiguities](https://github.com/rust-lang/cargo/pull/12614/) - [In `.cargo/config.toml`, merge lists in precedence order](https://github.com/rust-lang/cargo/pull/12515/) - [Add support for `target.'cfg(..)'.linker`](https://github.com/rust-lang/cargo/pull/12535/) <a id="1.74.0-Rustdoc"></a> Rustdoc ------- - [Add warning block support in rustdoc](https://github.com/rust-lang/rust/pull/106561/) - [rustdoc-search: add support for type parameters](https://github.com/rust-lang/rust/pull/112725/) - [rustdoc: show inner enum and struct in type definition for concrete type](https://github.com/rust-lang/rust/pull/114855/) <a id="1.74.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Raise minimum supported Apple OS versions](https://github.com/rust-lang/rust/pull/104385/) - [make Cell::swap panic if the Cells partially overlap](https://github.com/rust-lang/rust/pull/114795/) - [Reject invalid crate names in `--extern`](https://github.com/rust-lang/rust/pull/116001/) - [Don't resolve generic impls that may be shadowed by dyn built-in impls](https://github.com/rust-lang/rust/pull/114941/) - [The new `impl From<{&,&mut} [T; N]> for Vec<T>` is known to cause some inference failures with overly-generic code.](https://github.com/rust-lang/rust/issues/117054) In those examples using the `tui` crate, the combination of `AsRef<_>` and `Into<Vec>` leaves the middle type ambiguous, and the new `impl` adds another possibility, so it now requires an explicit type annotation. <a id="1.74.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. None this cycle. Version 1.73.0 (2023-10-05) ========================== <a id="1.73.0-Language"></a> Language -------- - [Uplift `clippy::fn_null_check` lint as `useless_ptr_null_checks`.](https://github.com/rust-lang/rust/pull/111717/) - [Make `noop_method_call` warn by default.](https://github.com/rust-lang/rust/pull/111916/) - [Support interpolated block for `try` and `async` in macros.](https://github.com/rust-lang/rust/pull/112953/) - [Make `unconditional_recursion` lint detect recursive drops.](https://github.com/rust-lang/rust/pull/113902/) - [Future compatibility warning for some impls being incorrectly considered not overlapping.](https://github.com/rust-lang/rust/pull/114023/) - [The `invalid_reference_casting` lint is now **deny-by-default** (instead of allow-by-default)](https://github.com/rust-lang/rust/pull/112431) <a id="1.73.0-Compiler"></a> Compiler -------- - [Write version information in a `.comment` section like GCC/Clang.](https://github.com/rust-lang/rust/pull/97550/) - [Add documentation on v0 symbol mangling.](https://github.com/rust-lang/rust/pull/97571/) - [Stabilize `extern "thiscall"` and `"thiscall-unwind"` ABIs.](https://github.com/rust-lang/rust/pull/114562/) - [Only check outlives goals on impl compared to trait.](https://github.com/rust-lang/rust/pull/109356/) - [Infer type in irrefutable slice patterns with fixed length as array.](https://github.com/rust-lang/rust/pull/113199/) - [Discard default auto trait impls if explicit ones exist.](https://github.com/rust-lang/rust/pull/113312/) - Add several new tier 3 targets: - [`aarch64-unknown-teeos`](https://github.com/rust-lang/rust/pull/113480/) - [`csky-unknown-linux-gnuabiv2`](https://github.com/rust-lang/rust/pull/113658/) - [`riscv64-linux-android`](https://github.com/rust-lang/rust/pull/112858/) - [`riscv64gc-unknown-hermit`](https://github.com/rust-lang/rust/pull/114004/) - [`x86_64-unikraft-linux-musl`](https://github.com/rust-lang/rust/pull/113411/) - [`x86_64-unknown-linux-ohos`](https://github.com/rust-lang/rust/pull/113061/) - [Add `wasm32-wasi-preview1-threads` as a tier 2 target.](https://github.com/rust-lang/rust/pull/112922/) Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. <a id="1.73.0-Libraries"></a> Libraries --------- - [Add `Read`, `Write` and `Seek` impls for `Arc<File>`.](https://github.com/rust-lang/rust/pull/94748/) - [Merge functionality of `io::Sink` into `io::Empty`.](https://github.com/rust-lang/rust/pull/98154/) - [Implement `RefUnwindSafe` for `Backtrace`](https://github.com/rust-lang/rust/pull/100455/) - [Make `ExitStatus` implement `Default`](https://github.com/rust-lang/rust/pull/106425/) - [`impl SliceIndex<str> for (Bound<usize>, Bound<usize>)`](https://github.com/rust-lang/rust/pull/111081/) - [Change default panic handler message format.](https://github.com/rust-lang/rust/pull/112849/) - [Cleaner `assert_eq!` & `assert_ne!` panic messages.](https://github.com/rust-lang/rust/pull/111071/) - [Correct the (deprecated) Android `stat` struct definitions.](https://github.com/rust-lang/rust/pull/113130/) <a id="1.73.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [Unsigned `{integer}::div_ceil`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.div_ceil) - [Unsigned `{integer}::next_multiple_of`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.next_multiple_of) - [Unsigned `{integer}::checked_next_multiple_of`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.checked_next_multiple_of) - [`std::ffi::FromBytesUntilNulError`](https://doc.rust-lang.org/stable/std/ffi/struct.FromBytesUntilNulError.html) - [`std::os::unix::fs::chown`](https://doc.rust-lang.org/stable/std/os/unix/fs/fn.chown.html) - [`std::os::unix::fs::fchown`](https://doc.rust-lang.org/stable/std/os/unix/fs/fn.fchown.html) - [`std::os::unix::fs::lchown`](https://doc.rust-lang.org/stable/std/os/unix/fs/fn.lchown.html) - [`LocalKey::<Cell<T>>::get`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.get) - [`LocalKey::<Cell<T>>::set`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.set) - [`LocalKey::<Cell<T>>::take`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.take) - [`LocalKey::<Cell<T>>::replace`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.replace) - [`LocalKey::<RefCell<T>>::with_borrow`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.with_borrow) - [`LocalKey::<RefCell<T>>::with_borrow_mut`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.with_borrow_mut) - [`LocalKey::<RefCell<T>>::set`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.set-1) - [`LocalKey::<RefCell<T>>::take`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.take-1) - [`LocalKey::<RefCell<T>>::replace`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.replace-1) These APIs are now stable in const contexts: - [`rc::Weak::new`](https://doc.rust-lang.org/stable/alloc/rc/struct.Weak.html#method.new) - [`sync::Weak::new`](https://doc.rust-lang.org/stable/alloc/sync/struct.Weak.html#method.new) - [`NonNull::as_ref`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.as_ref) <a id="1.73.0-Cargo"></a> Cargo ----- - [Bail out an error when using `cargo::` in custom build script.](https://github.com/rust-lang/cargo/pull/12332/) <a id="1.73.0-Misc"></a> Misc ---- <a id="1.73.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Update the minimum external LLVM to 15.](https://github.com/rust-lang/rust/pull/114148/) - [Check for non-defining uses of return position `impl Trait`.](https://github.com/rust-lang/rust/pull/112842/) <a id="1.73.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Remove LLVM pointee types, supporting only opaque pointers.](https://github.com/rust-lang/rust/pull/105545/) - [Port PGO/LTO/BOLT optimized build pipeline to Rust.](https://github.com/rust-lang/rust/pull/112235/) - [Replace in-tree `rustc_apfloat` with the new version of the crate.](https://github.com/rust-lang/rust/pull/113843/) - [Update to LLVM 17.](https://github.com/rust-lang/rust/pull/114048/) - [Add `internal_features` lint for internal unstable features.](https://github.com/rust-lang/rust/pull/108955/) - [Mention style for new syntax in tracking issue template.](https://github.com/rust-lang/rust/pull/113586/) Version 1.72.1 (2023-09-19) =========================== - [Adjust codegen change to improve LLVM codegen](https://github.com/rust-lang/rust/pull/115236) - [rustdoc: Fix self ty params in objects with lifetimes](https://github.com/rust-lang/rust/pull/115276) - [Fix regression in compile times](https://github.com/rust-lang/rust/pull/114948) - Resolve some ICE regressions in the compiler: - [#115215](https://github.com/rust-lang/rust/pull/115215) - [#115559](https://github.com/rust-lang/rust/pull/115559) Version 1.72.0 (2023-08-24) ========================== <a id="1.72.0-Language"></a> Language -------- - [Replace const eval limit by a lint and add an exponential backoff warning](https://github.com/rust-lang/rust/pull/103877/) - [expand: Change how `#![cfg(FALSE)]` behaves on crate root](https://github.com/rust-lang/rust/pull/110141/) - [Stabilize inline asm for LoongArch64](https://github.com/rust-lang/rust/pull/111235/) - [Uplift `clippy::undropped_manually_drops` lint](https://github.com/rust-lang/rust/pull/111530/) - [Uplift `clippy::invalid_utf8_in_unchecked` lint](https://github.com/rust-lang/rust/pull/111543/) as `invalid_from_utf8_unchecked` and `invalid_from_utf8` - [Uplift `clippy::cast_ref_to_mut` lint](https://github.com/rust-lang/rust/pull/111567/) as `invalid_reference_casting` - [Uplift `clippy::cmp_nan` lint](https://github.com/rust-lang/rust/pull/111818/) as `invalid_nan_comparisons` - [resolve: Remove artificial import ambiguity errors](https://github.com/rust-lang/rust/pull/112086/) - [Don't require associated types with Self: Sized bounds in `dyn Trait` objects](https://github.com/rust-lang/rust/pull/112319/) <a id="1.72.0-Compiler"></a> Compiler -------- - [Remember names of `cfg`-ed out items to mention them in diagnostics](https://github.com/rust-lang/rust/pull/109005/) - [Support for native WASM exceptions](https://github.com/rust-lang/rust/pull/111322/) - [Add support for NetBSD/aarch64-be (big-endian arm64).](https://github.com/rust-lang/rust/pull/111326/) - [Write to stdout if `-` is given as output file](https://github.com/rust-lang/rust/pull/111626/) - [Force all native libraries to be statically linked when linking a static binary](https://github.com/rust-lang/rust/pull/111698/) - [Add Tier 3 support for `loongarch64-unknown-none*`](https://github.com/rust-lang/rust/pull/112310/) - [Prevent `.eh_frame` from being emitted for `-C panic=abort`](https://github.com/rust-lang/rust/pull/112403/) - [Support 128-bit enum variant in debuginfo codegen](https://github.com/rust-lang/rust/pull/112474/) - [compiler: update solaris/illumos to enable tsan support.](https://github.com/rust-lang/rust/pull/112039/) Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. <a id="1.72.0-Libraries"></a> Libraries --------- - [Document memory orderings of `thread::{park, unpark}`](https://github.com/rust-lang/rust/pull/99587/) - [io: soften ‘at most one write attempt’ requirement in io::Write::write](https://github.com/rust-lang/rust/pull/107200/) - [Specify behavior of HashSet::insert](https://github.com/rust-lang/rust/pull/107619/) - [Relax implicit `T: Sized` bounds on `BufReader<T>`, `BufWriter<T>` and `LineWriter<T>`](https://github.com/rust-lang/rust/pull/111074/) - [Update runtime guarantee for `select_nth_unstable`](https://github.com/rust-lang/rust/pull/111974/) - [Return `Ok` on kill if process has already exited](https://github.com/rust-lang/rust/pull/112594/) - [Implement PartialOrd for `Vec`s over different allocators](https://github.com/rust-lang/rust/pull/112632/) - [Use 128 bits for TypeId hash](https://github.com/rust-lang/rust/pull/109953/) - [Don't drain-on-drop in DrainFilter impls of various collections.](https://github.com/rust-lang/rust/pull/104455/) - [Make `{Arc,Rc,Weak}::ptr_eq` ignore pointer metadata](https://github.com/rust-lang/rust/pull/106450/) <a id="1.72.0-Rustdoc"></a> Rustdoc ------- - [Allow whitespace as path separator like double colon](https://github.com/rust-lang/rust/pull/108537/) - [Add search result item types after their name](https://github.com/rust-lang/rust/pull/110688/) - [Search for slices and arrays by type with `[]`](https://github.com/rust-lang/rust/pull/111958/) - [Clean up type unification and "unboxing"](https://github.com/rust-lang/rust/pull/112233/) <a id="1.72.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`impl<T: Send> Sync for mpsc::Sender<T>`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Sender.html#impl-Sync-for-Sender%3CT%3E) - [`impl TryFrom<&OsStr> for &str`](https://doc.rust-lang.org/stable/std/primitive.str.html#impl-TryFrom%3C%26'a+OsStr%3E-for-%26'a+str) - [`String::leak`](https://doc.rust-lang.org/stable/alloc/string/struct.String.html#method.leak) These APIs are now stable in const contexts: - [`CStr::from_bytes_with_nul`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#method.from_bytes_with_nul) - [`CStr::to_bytes`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#method.to_bytes) - [`CStr::to_bytes_with_nul`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#method.to_bytes_with_nul) - [`CStr::to_str`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#method.to_str) <a id="1.72.0-Cargo"></a> Cargo ----- - Enable `-Zdoctest-in-workspace` by default. When running each documentation test, the working directory is set to the root directory of the package the test belongs to. [docs](https://doc.rust-lang.org/nightly/cargo/commands/cargo-test.html#working-directory-of-tests) [#12221](https://github.com/rust-lang/cargo/pull/12221) [#12288](https://github.com/rust-lang/cargo/pull/12288) - Add support of the "default" keyword to reset previously set `build.jobs` parallelism back to the default. [#12222](https://github.com/rust-lang/cargo/pull/12222) <a id="1.72.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Alter `Display` for `Ipv6Addr` for IPv4-compatible addresses](https://github.com/rust-lang/rust/pull/112606/) - Cargo changed feature name validation check to a hard error. The warning was added in Rust 1.49. These extended characters aren't allowed on crates.io, so this should only impact users of other registries, or people who don't publish to a registry. [#12291](https://github.com/rust-lang/cargo/pull/12291) - [Demoted `mips*-unknown-linux-gnu*` targets from host tier 2 to target tier 3 support.](https://github.com/rust-lang/rust/pull/113274) Version 1.71.1 (2023-08-03) =========================== - [Fix CVE-2023-38497: Cargo did not respect the umask when extracting dependencies](https://github.com/rust-lang/cargo/security/advisories/GHSA-j3xp-wfr4-hx87) - [Fix bash completion for users of Rustup](https://github.com/rust-lang/rust/pull/113579) - [Do not show `suspicious_double_ref_op` lint when calling `borrow()`](https://github.com/rust-lang/rust/pull/112517) - [Fix ICE: substitute types before checking inlining compatibility](https://github.com/rust-lang/rust/pull/113802) - [Fix ICE: don't use `can_eq` in `derive(..)` suggestion for missing method](https://github.com/rust-lang/rust/pull/111516) - [Fix building Rust 1.71.0 from the source tarball](https://github.com/rust-lang/rust/issues/113678) Version 1.71.0 (2023-07-13) ========================== <a id="1.71.0-Language"></a> Language -------- - [Stabilize `raw-dylib`, `link_ordinal`, `import_name_type` and `-Cdlltool`.](https://github.com/rust-lang/rust/pull/109677/) - [Uplift `clippy::{drop,forget}_{ref,copy}` lints.](https://github.com/rust-lang/rust/pull/109732/) - [Type inference is more conservative around constrained vars.](https://github.com/rust-lang/rust/pull/110100/) - [Use fulfillment to check `Drop` impl compatibility](https://github.com/rust-lang/rust/pull/110577/) <a id="1.71.0-Compiler"></a> Compiler -------- - [Evaluate place expression in `PlaceMention`](https://github.com/rust-lang/rust/pull/104844/), making `let _ =` patterns more consistent with respect to the borrow checker. - [Add `--print deployment-target` flag for Apple targets.](https://github.com/rust-lang/rust/pull/105354/) - [Stabilize `extern "C-unwind"` and friends.](https://github.com/rust-lang/rust/pull/106075/) The existing `extern "C"` etc. may change behavior for cross-language unwinding in a future release. - [Update the version of musl used on `*-linux-musl` targets to 1.2.3](https://github.com/rust-lang/rust/pull/107129/), enabling [time64](https://musl.libc.org/time64.html) on 32-bit systems. - [Stabilize `debugger_visualizer`](https://github.com/rust-lang/rust/pull/108668/) for embedding metadata like Microsoft's Natvis. - [Enable flatten-format-args by default.](https://github.com/rust-lang/rust/pull/109999/) - [Make `Self` respect tuple constructor privacy.](https://github.com/rust-lang/rust/pull/111245/) - [Improve niche placement by trying two strategies and picking the better result.](https://github.com/rust-lang/rust/pull/108106/) - [Use `apple-m1` as the target CPU for `aarch64-apple-darwin`.](https://github.com/rust-lang/rust/pull/109899/) - [Add Tier 3 support for the `x86_64h-apple-darwin` target.](https://github.com/rust-lang/rust/pull/108795/) - [Promote `loongarch64-unknown-linux-gnu` to Tier 2 with host tools.](https://github.com/rust-lang/rust/pull/110936/) Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. <a id="1.71.0-Libraries"></a> Libraries --------- - [Rework handling of recursive panics.](https://github.com/rust-lang/rust/pull/110975/) Additional panics are allowed while unwinding, as long as they are caught before escaping a `Drop` implementation, but panicking within a panic hook is now an immediate abort. - [Loosen `From<&[T]> for Box<[T]>` bound to `T: Clone`.](https://github.com/rust-lang/rust/pull/103406/) - [Remove unnecessary `T: Send` bound](https://github.com/rust-lang/rust/pull/111134/) in `Error for mpsc::SendError<T>` and `TrySendError<T>`. - [Fix docs for `alloc::realloc`](https://github.com/rust-lang/rust/pull/108630/) to match `Layout` requirements that the size must not exceed `isize::MAX`. - [Document `const {}` syntax for `std::thread_local`.](https://github.com/rust-lang/rust/pull/110620/) This syntax was stabilized in Rust 1.59, but not previously mentioned in release notes. <a id="1.71.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`CStr::is_empty`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#method.is_empty) - [`BuildHasher::hash_one`](https://doc.rust-lang.org/stable/std/hash/trait.BuildHasher.html#method.hash_one) - [`NonZeroI*::is_positive`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI32.html#method.is_positive) - [`NonZeroI*::is_negative`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI32.html#method.is_negative) - [`NonZeroI*::checked_neg`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI32.html#method.checked_neg) - [`NonZeroI*::overflowing_neg`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI32.html#method.overflowing_neg) - [`NonZeroI*::saturating_neg`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI32.html#method.saturating_neg) - [`NonZeroI*::wrapping_neg`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI32.html#method.wrapping_neg) - [`Neg for NonZeroI*`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI32.html#impl-Neg-for-NonZeroI32) - [`Neg for &NonZeroI*`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI32.html#impl-Neg-for-%26NonZeroI32) - [`From<[T; N]> for (T...)`](https://doc.rust-lang.org/stable/std/primitive.array.html#impl-From%3C%5BT;+1%5D%3E-for-(T,)) (array to N-tuple for N in 1..=12) - [`From<(T...)> for [T; N]`](https://doc.rust-lang.org/stable/std/primitive.array.html#impl-From%3C(T,)%3E-for-%5BT;+1%5D) (N-tuple to array for N in 1..=12) - [`windows::io::AsHandle for Box<T>`](https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsHandle.html#impl-AsHandle-for-Box%3CT%3E) - [`windows::io::AsHandle for Rc<T>`](https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsHandle.html#impl-AsHandle-for-Rc%3CT%3E) - [`windows::io::AsHandle for Arc<T>`](https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsHandle.html#impl-AsHandle-for-Arc%3CT%3E) - [`windows::io::AsSocket for Box<T>`](https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsSocket.html#impl-AsSocket-for-Box%3CT%3E) - [`windows::io::AsSocket for Rc<T>`](https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsSocket.html#impl-AsSocket-for-Rc%3CT%3E) - [`windows::io::AsSocket for Arc<T>`](https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsSocket.html#impl-AsSocket-for-Arc%3CT%3E) These APIs are now stable in const contexts: - [`<*const T>::read`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.read) - [`<*const T>::read_unaligned`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.read_unaligned) - [`<*mut T>::read`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.read-1) - [`<*mut T>::read_unaligned`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.read_unaligned-1) - [`ptr::read`](https://doc.rust-lang.org/stable/std/ptr/fn.read.html) - [`ptr::read_unaligned`](https://doc.rust-lang.org/stable/std/ptr/fn.read_unaligned.html) - [`<[T]>::split_at`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_at) <a id="1.71.0-Cargo"></a> Cargo ----- - [Allow named debuginfo options in `Cargo.toml`.](https://github.com/rust-lang/cargo/pull/11958/) - [Add `workspace_default_members` to the output of `cargo metadata`.](https://github.com/rust-lang/cargo/pull/11978/) - [Automatically inherit workspace fields when running `cargo new`/`cargo init`.](https://github.com/rust-lang/cargo/pull/12069/) <a id="1.71.0-Rustdoc"></a> Rustdoc ------- - [Add a new `rustdoc::unescaped_backticks` lint for broken inline code.](https://github.com/rust-lang/rust/pull/105848/) - [Support strikethrough with single tildes.](https://github.com/rust-lang/rust/pull/111152/) (`~~old~~` vs. `~new~`) <a id="1.71.0-Misc"></a> Misc ---- <a id="1.71.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Remove structural match from `TypeId`.](https://github.com/rust-lang/rust/pull/103291/) Code that uses a constant `TypeId` in a pattern will potentially be broken. Known cases have already been fixed -- in particular, users of the `log` crate's `kv_unstable` feature should update to `log v0.4.18` or later. - [Add a `sysroot` crate to represent the standard library crates.](https://github.com/rust-lang/rust/pull/108865/) This does not affect stable users, but may require adjustment in tools that build their own standard library. - [Cargo optimizes its usage under `rustup`.](https://github.com/rust-lang/cargo/pull/11917/) When Cargo detects it will run `rustc` pointing to a rustup proxy, it'll try bypassing the proxy and use the underlying binary directly. There are assumptions around the interaction with rustup and `RUSTUP_TOOLCHAIN`. However, it's not expected to affect normal users. - [When querying a package, Cargo tries only the original name, all hyphens, and all underscores to handle misspellings.](https://github.com/rust-lang/cargo/pull/12083/) Previously, Cargo tried each combination of hyphens and underscores, causing excessive requests to crates.io. - Cargo now [disallows `RUSTUP_HOME`](https://github.com/rust-lang/cargo/pull/12101/) and [`RUSTUP_TOOLCHAIN`](https://github.com/rust-lang/cargo/pull/12107/) in the `[env]` configuration table. This is considered to be not a use case Cargo would like to support, since it will likely cause problems or lead to confusion. <a id="1.71.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. Version 1.70.0 (2023-06-01) ========================== <a id="1.70.0-Language"></a> Language -------- - [Relax ordering rules for `asm!` operands](https://github.com/rust-lang/rust/pull/105798/) - [Properly allow macro expanded `format_args` invocations to uses captures](https://github.com/rust-lang/rust/pull/106505/) - [Lint ambiguous glob re-exports](https://github.com/rust-lang/rust/pull/107880/) - [Perform const and unsafe checking for expressions in `let _ = expr` position.](https://github.com/rust-lang/rust/pull/102256/) <a id="1.70.0-Compiler"></a> Compiler -------- - [Extend -Cdebuginfo with new options and named aliases](https://github.com/rust-lang/rust/pull/109808/) This provides a smaller version of debuginfo for cases that only need line number information (`-Cdebuginfo=line-tables-only`), which may eventually become the default for `-Cdebuginfo=1`. - [Make `unused_allocation` lint against `Box::new` too](https://github.com/rust-lang/rust/pull/104363/) - [Detect uninhabited types early in const eval](https://github.com/rust-lang/rust/pull/109435/) - [Switch to LLD as default linker for {arm,thumb}v4t-none-eabi](https://github.com/rust-lang/rust/pull/109721/) - [Add tier 3 target `loongarch64-unknown-linux-gnu`](https://github.com/rust-lang/rust/pull/96971) - [Add tier 3 target for `i586-pc-nto-qnx700` (QNX Neutrino RTOS, version 7.0)](https://github.com/rust-lang/rust/pull/109173/), - [Insert alignment checks for pointer dereferences as debug assertions](https://github.com/rust-lang/rust/pull/98112) This catches undefined behavior at runtime, and may cause existing code to fail. Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. <a id="1.70.0-Libraries"></a> Libraries --------- - [Document NonZeroXxx layout guarantees](https://github.com/rust-lang/rust/pull/94786/) - [Windows: make `Command` prefer non-verbatim paths](https://github.com/rust-lang/rust/pull/96391/) - [Implement Default for some alloc/core iterators](https://github.com/rust-lang/rust/pull/99929/) - [Fix handling of trailing bare CR in str::lines](https://github.com/rust-lang/rust/pull/100311/) - [allow negative numeric literals in `concat!`](https://github.com/rust-lang/rust/pull/106844/) - [Add documentation about the memory layout of `Cell`](https://github.com/rust-lang/rust/pull/106921/) - [Use `partial_cmp` to implement tuple `lt`/`le`/`ge`/`gt`](https://github.com/rust-lang/rust/pull/108157/) - [Stabilize `atomic_as_ptr`](https://github.com/rust-lang/rust/pull/108419/) - [Stabilize `nonnull_slice_from_raw_parts`](https://github.com/rust-lang/rust/pull/97506/) - [Partial stabilization of `once_cell`](https://github.com/rust-lang/rust/pull/105587/) - [Stabilize `nonzero_min_max`](https://github.com/rust-lang/rust/pull/106633/) - [Flatten/inline format_args!() and (string and int) literal arguments into format_args!()](https://github.com/rust-lang/rust/pull/106824/) - [Stabilize movbe target feature](https://github.com/rust-lang/rust/pull/107711/) - [don't splice from files into pipes in io::copy](https://github.com/rust-lang/rust/pull/108283/) - [Add a builtin unstable `FnPtr` trait that is implemented for all function pointers](https://github.com/rust-lang/rust/pull/108080/) This extends `Debug`, `Pointer`, `Hash`, `PartialEq`, `Eq`, `PartialOrd`, and `Ord` implementations for function pointers with all ABIs. <a id="1.70.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`NonZero*::MIN/MAX`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI8.html#associatedconstant.MIN) - [`BinaryHeap::retain`](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.retain) - [`Default for std::collections::binary_heap::IntoIter`](https://doc.rust-lang.org/stable/std/collections/binary_heap/struct.IntoIter.html) - [`Default for std::collections::btree_map::{IntoIter, Iter, IterMut}`](https://doc.rust-lang.org/stable/std/collections/btree_map/struct.IntoIter.html) - [`Default for std::collections::btree_map::{IntoKeys, Keys}`](https://doc.rust-lang.org/stable/std/collections/btree_map/struct.IntoKeys.html) - [`Default for std::collections::btree_map::{IntoValues, Values}`](https://doc.rust-lang.org/stable/std/collections/btree_map/struct.IntoValues.html) - [`Default for std::collections::btree_map::Range`](https://doc.rust-lang.org/stable/std/collections/btree_map/struct.Range.html) - [`Default for std::collections::btree_set::{IntoIter, Iter}`](https://doc.rust-lang.org/stable/std/collections/btree_set/struct.IntoIter.html) - [`Default for std::collections::btree_set::Range`](https://doc.rust-lang.org/stable/std/collections/btree_set/struct.Range.html) - [`Default for std::collections::linked_list::{IntoIter, Iter, IterMut}`](https://doc.rust-lang.org/stable/alloc/collections/linked_list/struct.IntoIter.html) - [`Default for std::vec::IntoIter`](https://doc.rust-lang.org/stable/alloc/vec/struct.IntoIter.html#impl-Default-for-IntoIter%3CT,+A%3E) - [`Default for std::iter::Chain`](https://doc.rust-lang.org/stable/std/iter/struct.Chain.html) - [`Default for std::iter::Cloned`](https://doc.rust-lang.org/stable/std/iter/struct.Cloned.html) - [`Default for std::iter::Copied`](https://doc.rust-lang.org/stable/std/iter/struct.Copied.html) - [`Default for std::iter::Enumerate`](https://doc.rust-lang.org/stable/std/iter/struct.Enumerate.html) - [`Default for std::iter::Flatten`](https://doc.rust-lang.org/stable/std/iter/struct.Flatten.html) - [`Default for std::iter::Fuse`](https://doc.rust-lang.org/stable/std/iter/struct.Fuse.html) - [`Default for std::iter::Rev`](https://doc.rust-lang.org/stable/std/iter/struct.Rev.html) - [`Default for std::slice::Iter`](https://doc.rust-lang.org/stable/std/slice/struct.Iter.html) - [`Default for std::slice::IterMut`](https://doc.rust-lang.org/stable/std/slice/struct.IterMut.html) - [`Rc::into_inner`](https://doc.rust-lang.org/stable/alloc/rc/struct.Rc.html#method.into_inner) - [`Arc::into_inner`](https://doc.rust-lang.org/stable/alloc/sync/struct.Arc.html#method.into_inner) - [`std::cell::OnceCell`](https://doc.rust-lang.org/stable/std/cell/struct.OnceCell.html) - [`Option::is_some_and`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.is_some_and) - [`NonNull::slice_from_raw_parts`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.slice_from_raw_parts) - [`Result::is_ok_and`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.is_ok_and) - [`Result::is_err_and`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.is_err_and) - [`std::sync::atomic::Atomic*::as_ptr`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicU8.html#method.as_ptr) - [`std::io::IsTerminal`](https://doc.rust-lang.org/stable/std/io/trait.IsTerminal.html) - [`std::os::linux::net::SocketAddrExt`](https://doc.rust-lang.org/stable/std/os/linux/net/trait.SocketAddrExt.html) - [`std::os::unix::net::UnixDatagram::bind_addr`](https://doc.rust-lang.org/stable/std/os/unix/net/struct.UnixDatagram.html#method.bind_addr) - [`std::os::unix::net::UnixDatagram::connect_addr`](https://doc.rust-lang.org/stable/std/os/unix/net/struct.UnixDatagram.html#method.connect_addr) - [`std::os::unix::net::UnixDatagram::send_to_addr`](https://doc.rust-lang.org/stable/std/os/unix/net/struct.UnixDatagram.html#method.send_to_addr) - [`std::os::unix::net::UnixListener::bind_addr`](https://doc.rust-lang.org/stable/std/os/unix/net/struct.UnixListener.html#method.bind_addr) - [`std::path::Path::as_mut_os_str`](https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.as_mut_os_str) - [`std::sync::OnceLock`](https://doc.rust-lang.org/stable/std/sync/struct.OnceLock.html) <a id="1.70.0-Cargo"></a> Cargo ----- - [Add `CARGO_PKG_README`](https://github.com/rust-lang/cargo/pull/11645/) - [Make `sparse` the default protocol for crates.io](https://github.com/rust-lang/cargo/pull/11791/) - [Accurately show status when downgrading dependencies](https://github.com/rust-lang/cargo/pull/11839/) - [Use registry.default for login/logout](https://github.com/rust-lang/cargo/pull/11949/) - [Stabilize `cargo logout`](https://github.com/rust-lang/cargo/pull/11950/) <a id="1.70.0-Misc"></a> Misc ---- - [Stabilize rustdoc `--test-run-directory`](https://github.com/rust-lang/rust/pull/103682/) <a id="1.70.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Prevent stable `libtest` from supporting `-Zunstable-options`](https://github.com/rust-lang/rust/pull/109044/) - [Perform const and unsafe checking for expressions in `let _ = expr` position.](https://github.com/rust-lang/rust/pull/102256/) - [WebAssembly targets enable `sign-ext` and `mutable-globals` features in codegen](https://github.com/rust-lang/rust/issues/109807) This may cause incompatibility with older execution environments. - [Insert alignment checks for pointer dereferences as debug assertions](https://github.com/rust-lang/rust/pull/98112) This catches undefined behavior at runtime, and may cause existing code to fail. <a id="1.70.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Upgrade to LLVM 16](https://github.com/rust-lang/rust/pull/109474/) - [Use SipHash-1-3 instead of SipHash-2-4 for StableHasher](https://github.com/rust-lang/rust/pull/107925/) Version 1.69.0 (2023-04-20) ========================== <a id="1.69.0-Language"></a> Language -------- - [Deriving built-in traits on packed structs works with `Copy` fields.](https://github.com/rust-lang/rust/pull/104429/) - [Stabilize the `cmpxchg16b` target feature on x86 and x86_64.](https://github.com/rust-lang/rust/pull/106774/) - [Improve analysis of trait bounds for associated types.](https://github.com/rust-lang/rust/pull/103695/) - [Allow associated types to be used as union fields.](https://github.com/rust-lang/rust/pull/106938/) - [Allow `Self: Autotrait` bounds on dyn-safe trait methods.](https://github.com/rust-lang/rust/pull/107082/) - [Treat `str` as containing `[u8]` for auto trait purposes.](https://github.com/rust-lang/rust/pull/107941/) <a id="1.69.0-Compiler"></a> Compiler -------- - [Upgrade `*-pc-windows-gnu` on CI to mingw-w64 v10 and GCC 12.2.](https://github.com/rust-lang/rust/pull/100178/) - [Rework min_choice algorithm of member constraints.](https://github.com/rust-lang/rust/pull/105300/) - [Support `true` and `false` as boolean flags in compiler arguments.](https://github.com/rust-lang/rust/pull/107043/) - [Default `repr(C)` enums to `c_int` size.](https://github.com/rust-lang/rust/pull/107592/) <a id="1.69.0-Libraries"></a> Libraries --------- - [Implement the unstable `DispatchFromDyn` for cell types, allowing downstream experimentation with custom method receivers.](https://github.com/rust-lang/rust/pull/97373/) - [Document that `fmt::Arguments::as_str()` may return `Some(_)` in more cases after optimization, subject to change.](https://github.com/rust-lang/rust/pull/106823/) - [Implement `AsFd` and `AsRawFd` for `Rc`.](https://github.com/rust-lang/rust/pull/107317/) <a id="1.69.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`CStr::from_bytes_until_nul`](https://doc.rust-lang.org/stable/core/ffi/struct.CStr.html#method.from_bytes_until_nul) - [`core::ffi::FromBytesUntilNulError`](https://doc.rust-lang.org/stable/core/ffi/struct.FromBytesUntilNulError.html) These APIs are now stable in const contexts: - [`SocketAddr::new`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.new) - [`SocketAddr::ip`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.ip) - [`SocketAddr::port`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.port) - [`SocketAddr::is_ipv4`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.is_ipv4) - [`SocketAddr::is_ipv6`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.is_ipv6) - [`SocketAddrV4::new`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.new) - [`SocketAddrV4::ip`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.ip) - [`SocketAddrV4::port`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.port) - [`SocketAddrV6::new`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.new) - [`SocketAddrV6::ip`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.ip) - [`SocketAddrV6::port`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.port) - [`SocketAddrV6::flowinfo`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.flowinfo) - [`SocketAddrV6::scope_id`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.scope_id) <a id="1.69.0-Cargo"></a> Cargo ----- - [Cargo now suggests `cargo fix` or `cargo clippy --fix` when compilation warnings are auto-fixable.](https://github.com/rust-lang/cargo/pull/11558/) - [Cargo now suggests `cargo add` if you try to install a library crate.](https://github.com/rust-lang/cargo/pull/11410/) - [Cargo now sets the `CARGO_BIN_NAME` environment variable also for binary examples.](https://github.com/rust-lang/cargo/pull/11705/) <a id="1.69.0-Rustdoc"></a> Rustdoc ----- - [Vertically compact trait bound formatting.](https://github.com/rust-lang/rust/pull/102842/) - [Only include stable lints in `rustdoc::all` group.](https://github.com/rust-lang/rust/pull/106316/) - [Compute maximum Levenshtein distance based on the query.](https://github.com/rust-lang/rust/pull/107141/) - [Remove inconsistently-present sidebar tooltips.](https://github.com/rust-lang/rust/pull/107490/) - [Search by macro when query ends with `!`.](https://github.com/rust-lang/rust/pull/108143/) <a id="1.69.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [The `rust-analysis` component from `rustup` now only contains a warning placeholder.](https://github.com/rust-lang/rust/pull/101841/) This was primarily intended for RLS, and the corresponding `-Zsave-analysis` flag has been removed from the compiler as well. - [Unaligned references to packed fields are now a hard error.](https://github.com/rust-lang/rust/pull/102513/) This has been a warning since 1.53, and denied by default with a future-compatibility warning since 1.62. - [Update the minimum external LLVM to 14.](https://github.com/rust-lang/rust/pull/107573/) - [Cargo now emits errors on invalid characters in a registry token.](https://github.com/rust-lang/cargo/pull/11600/) - [When `default-features` is set to false of a workspace dependency, and an inherited dependency of a member has `default-features = true`, Cargo will enable default features of that dependency.](https://github.com/rust-lang/cargo/pull/11409/) - [Cargo denies `CARGO_HOME` in the `[env]` configuration table. Cargo itself doesn't pick up this value, but recursive calls to cargo would, which was not intended.](https://github.com/rust-lang/cargo/pull/11644/) - [Debuginfo for build dependencies is now off if not explicitly set. This is expected to improve the overall build time.](https://github.com/rust-lang/cargo/pull/11252/) - [The Rust distribution no longer always includes rustdoc](https://github.com/rust-lang/rust/pull/106886) If `tools = [...]` is set in bootstrap.toml, we will respect a missing rustdoc in that list. By default rustdoc remains included. To retain the prior behavior explicitly add `"rustdoc"` to the list. <a id="1.69.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Move `format_args!()` into AST (and expand it during AST lowering)](https://github.com/rust-lang/rust/pull/106745/) Version 1.68.2 (2023-03-28) =========================== - [Update the GitHub RSA host key bundled within Cargo](https://github.com/rust-lang/cargo/pull/11883). The key was [rotated by GitHub](https://github.blog/2023-03-23-we-updated-our-rsa-ssh-host-key/) on 2023-03-24 after the old one leaked. - [Mark the old GitHub RSA host key as revoked](https://github.com/rust-lang/cargo/pull/11889). This will prevent Cargo from accepting the leaked key even when trusted by the system. - [Add support for `@revoked` and a better error message for `@cert-authority` in Cargo's SSH host key verification](https://github.com/rust-lang/cargo/pull/11635) Version 1.68.1 (2023-03-23) =========================== - [Fix miscompilation in produced Windows MSVC artifacts](https://github.com/rust-lang/rust/pull/109094) This was introduced by enabling ThinLTO for the distributed rustc which led to miscompilations in the resulting binary. Currently this is believed to be limited to the -Zdylib-lto flag used for rustc compilation, rather than a general bug in ThinLTO, so only rustc artifacts should be affected. - [Fix --enable-local-rust builds](https://github.com/rust-lang/rust/pull/109111/) - [Treat `$prefix-clang` as `clang` in linker detection code](https://github.com/rust-lang/rust/pull/109156) - [Fix panic in compiler code](https://github.com/rust-lang/rust/pull/108162) Version 1.68.0 (2023-03-09) ========================== <a id="1.68.0-Language"></a> Language -------- - [Stabilize default_alloc_error_handler](https://github.com/rust-lang/rust/pull/102318/) This allows usage of `alloc` on stable without requiring the definition of a handler for allocation failure. Defining custom handlers is still unstable. - [Stabilize `efiapi` calling convention.](https://github.com/rust-lang/rust/pull/105795/) - [Remove implicit promotion for types with drop glue](https://github.com/rust-lang/rust/pull/105085/) <a id="1.68.0-Compiler"></a> Compiler -------- - [Change `bindings_with_variant_name` to deny-by-default](https://github.com/rust-lang/rust/pull/104154/) - [Allow .. to be parsed as let initializer](https://github.com/rust-lang/rust/pull/105701/) - [Add `armv7-sony-vita-newlibeabihf` as a tier 3 target](https://github.com/rust-lang/rust/pull/105712/) - [Always check alignment during compile-time const evaluation](https://github.com/rust-lang/rust/pull/104616/) - [Disable "split dwarf inlining" by default.](https://github.com/rust-lang/rust/pull/106709/) - [Add vendor to Fuchsia's target triple](https://github.com/rust-lang/rust/pull/106429/) - [Enable sanitizers for s390x-linux](https://github.com/rust-lang/rust/pull/107127/) <a id="1.68.0-Libraries"></a> Libraries --------- - [Loosen the bound on the Debug implementation of Weak.](https://github.com/rust-lang/rust/pull/90291/) - [Make `std::task::Context` !Send and !Sync](https://github.com/rust-lang/rust/pull/95985/) - [PhantomData layout guarantees](https://github.com/rust-lang/rust/pull/104081/) - [Don't derive Debug for `OnceWith` & `RepeatWith`](https://github.com/rust-lang/rust/pull/104163/) - [Implement DerefMut for PathBuf](https://github.com/rust-lang/rust/pull/105018/) - [Add O(1) `Vec -> VecDeque` conversion guarantee](https://github.com/rust-lang/rust/pull/105128/) - [Leak amplification for peek_mut() to ensure BinaryHeap's invariant is always met](https://github.com/rust-lang/rust/pull/105851/) <a id="1.68.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`{core,std}::pin::pin!`](https://doc.rust-lang.org/stable/std/pin/macro.pin.html) - [`impl From<bool> for {f32,f64}`](https://doc.rust-lang.org/stable/std/primitive.f32.html#impl-From%3Cbool%3E-for-f32) - [`std::path::MAIN_SEPARATOR_STR`](https://doc.rust-lang.org/stable/std/path/constant.MAIN_SEPARATOR_STR.html) - [`impl DerefMut for PathBuf`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#impl-DerefMut-for-PathBuf) These APIs are now stable in const contexts: - [`VecDeque::new`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html#method.new) <a id="1.68.0-Cargo"></a> Cargo ----- - [Stabilize sparse registry support for crates.io](https://github.com/rust-lang/cargo/pull/11224/) - [`cargo build --verbose` tells you more about why it recompiles.](https://github.com/rust-lang/cargo/pull/11407/) - [Show progress of crates.io index update even `net.git-fetch-with-cli` option enabled](https://github.com/rust-lang/cargo/pull/11579/) <a id="1.68.0-Misc"></a> Misc ---- <a id="1.68.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [Only support Android NDK 25 or newer](https://blog.rust-lang.org/2023/01/09/android-ndk-update-r25.html) - [Add `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` to future-incompat report](https://github.com/rust-lang/rust/pull/103418/) - [Only specify `--target` by default for `-Zgcc-ld=lld` on wasm](https://github.com/rust-lang/rust/pull/101792/) - [Bump `IMPLIED_BOUNDS_ENTAILMENT` to Deny + ReportNow](https://github.com/rust-lang/rust/pull/106465/) - [`std::task::Context` no longer implements Send and Sync](https://github.com/rust-lang/rust/pull/95985) <a id="1.68.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Encode spans relative to the enclosing item](https://github.com/rust-lang/rust/pull/84762/) - [Don't normalize in AstConv](https://github.com/rust-lang/rust/pull/101947/) - [Find the right lower bound region in the scenario of partial order relations](https://github.com/rust-lang/rust/pull/104765/) - [Fix impl block in const expr](https://github.com/rust-lang/rust/pull/104889/) - [Check ADT fields for copy implementations considering regions](https://github.com/rust-lang/rust/pull/105102/) - [rustdoc: simplify JS search routine by not messing with lev distance](https://github.com/rust-lang/rust/pull/105796/) - [Enable ThinLTO for rustc on `x86_64-pc-windows-msvc`](https://github.com/rust-lang/rust/pull/103591/) - [Enable ThinLTO for rustc on `x86_64-apple-darwin`](https://github.com/rust-lang/rust/pull/103647/) Version 1.67.1 (2023-02-09) =========================== - [Fix interoperability with thin archives.](https://github.com/rust-lang/rust/pull/107360) - [Fix an internal error in the compiler build process.](https://github.com/rust-lang/rust/pull/105624) - [Downgrade `clippy::uninlined_format_args` to pedantic.](https://github.com/rust-lang/rust-clippy/pull/10265) Version 1.67.0 (2023-01-26) ========================== <a id="1.67.0-Language"></a> Language -------- - [Make `Sized` predicates coinductive, allowing cycles.](https://github.com/rust-lang/rust/pull/100386/) - [`#[must_use]` annotations on `async fn` also affect the `Future::Output`.](https://github.com/rust-lang/rust/pull/100633/) - [Elaborate supertrait obligations when deducing closure signatures.](https://github.com/rust-lang/rust/pull/101834/) - [Invalid literals are no longer an error under `cfg(FALSE)`.](https://github.com/rust-lang/rust/pull/102944/) - [Unreserve braced enum variants in value namespace.](https://github.com/rust-lang/rust/pull/103578/) <a id="1.67.0-Compiler"></a> Compiler -------- - [Enable varargs support for calling conventions other than `C` or `cdecl`.](https://github.com/rust-lang/rust/pull/97971/) - [Add new MIR constant propagation based on dataflow analysis.](https://github.com/rust-lang/rust/pull/101168/) - [Optimize field ordering by grouping m\*2^n-sized fields with equivalently aligned ones.](https://github.com/rust-lang/rust/pull/102750/) - [Stabilize native library modifier `verbatim`.](https://github.com/rust-lang/rust/pull/104360/) Added, updated, and removed targets: - [Add a tier 3 target for PowerPC on AIX](https://github.com/rust-lang/rust/pull/102293/), `powerpc64-ibm-aix`. - [Add a tier 3 target for the Sony PlayStation 1](https://github.com/rust-lang/rust/pull/102689/), `mipsel-sony-psx`. - [Add tier 3 `no_std` targets for the QNX Neutrino RTOS](https://github.com/rust-lang/rust/pull/102701/), `aarch64-unknown-nto-qnx710` and `x86_64-pc-nto-qnx710`. - [Promote UEFI targets to tier 2](https://github.com/rust-lang/rust/pull/103933/), `aarch64-unknown-uefi`, `i686-unknown-uefi`, and `x86_64-unknown-uefi`. - [Remove tier 3 `linuxkernel` targets](https://github.com/rust-lang/rust/pull/104015/) (not used by the actual kernel). Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. <a id="1.67.0-Libraries"></a> Libraries --------- - [Merge `crossbeam-channel` into `std::sync::mpsc`.](https://github.com/rust-lang/rust/pull/93563/) - [Fix inconsistent rounding of 0.5 when formatted to 0 decimal places.](https://github.com/rust-lang/rust/pull/102935/) - [Derive `Eq` and `Hash` for `ControlFlow`.](https://github.com/rust-lang/rust/pull/103084/) - [Don't build `compiler_builtins` with `-C panic=abort`.](https://github.com/rust-lang/rust/pull/103786/) <a id="1.67.0-Stabilized-APIs"></a> Stabilized APIs --------------- - [`{integer}::checked_ilog`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.checked_ilog) - [`{integer}::checked_ilog2`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.checked_ilog2) - [`{integer}::checked_ilog10`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.checked_ilog10) - [`{integer}::ilog`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.ilog) - [`{integer}::ilog2`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.ilog2) - [`{integer}::ilog10`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.ilog10) - [`NonZeroU*::ilog2`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroU32.html#method.ilog2) - [`NonZeroU*::ilog10`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroU32.html#method.ilog10) - [`NonZero*::BITS`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroU32.html#associatedconstant.BITS) These APIs are now stable in const contexts: - [`char::from_u32`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.from_u32) - [`char::from_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.from_digit) - [`char::to_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.to_digit) - [`core::char::from_u32`](https://doc.rust-lang.org/stable/core/char/fn.from_u32.html) - [`core::char::from_digit`](https://doc.rust-lang.org/stable/core/char/fn.from_digit.html) <a id="1.67.0-Compatibility-Notes"></a> Compatibility Notes ------------------- - [The layout of `repr(Rust)` types now groups m\*2^n-sized fields with equivalently aligned ones.](https://github.com/rust-lang/rust/pull/102750/) This is intended to be an optimization, but it is also known to increase type sizes in a few cases for the placement of enum tags. As a reminder, the layout of `repr(Rust)` types is an implementation detail, subject to change. - [0.5 now rounds to 0 when formatted to 0 decimal places.](https://github.com/rust-lang/rust/pull/102935/) This makes it consistent with the rest of floating point formatting that rounds ties toward even digits. - [Chains of `&&` and `||` will now drop temporaries from their sub-expressions in evaluation order, left-to-right.](https://github.com/rust-lang/rust/pull/103293/) Previously, it was "twisted" such that the _first_ expression dropped its temporaries _last_, after all of the other expressions dropped in order. - [Underscore suffixes on string literals are now a hard error.](https://github.com/rust-lang/rust/pull/103914/) This has been a future-compatibility warning since 1.20.0. - [Stop passing `-export-dynamic` to `wasm-ld`.](https://github.com/rust-lang/rust/pull/105405/) - [`main` is now mangled as `__main_void` on `wasm32-wasi`.](https://github.com/rust-lang/rust/pull/105468/) - [Cargo now emits an error if there are multiple registries in the configuration with the same index URL.](https://github.com/rust-lang/cargo/pull/10592) <a id="1.67.0-Internal-Changes"></a> Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Rewrite LLVM's archive writer in Rust.](https://github.com/rust-lang/rust/pull/97485/) Version 1.66.1 (2023-01-10) =========================== - Added validation of SSH host keys for git URLs in Cargo ([CVE-2022-46176](https://www.cve.org/CVERecord?id=CVE-2022-46176)) Version 1.66.0 (2022-12-15) ========================== Language -------- - [Permit specifying explicit discriminants on all `repr(Int)` enums](https://github.com/rust-lang/rust/pull/95710/) ```rust #[repr(u8)] enum Foo { A(u8) = 0, B(i8) = 1, C(bool) = 42, } ``` - [Allow transmutes between the same type differing only in lifetimes](https://github.com/rust-lang/rust/pull/101520/) - [Change constant evaluation errors from a deny-by-default lint to a hard error](https://github.com/rust-lang/rust/pull/102091/) - [Trigger `must_use` on `impl Trait` for supertraits](https://github.com/rust-lang/rust/pull/102287/) This makes `impl ExactSizeIterator` respect the existing `#[must_use]` annotation on `Iterator`. - [Allow `..=X` in patterns](https://github.com/rust-lang/rust/pull/102275/) - [Uplift `clippy::for_loops_over_fallibles` lint into rustc](https://github.com/rust-lang/rust/pull/99696/) - [Stabilize `sym` operands in inline assembly](https://github.com/rust-lang/rust/pull/103168/) - [Update to Unicode 15](https://github.com/rust-lang/rust/pull/101912/) - [Opaque types no longer imply lifetime bounds](https://github.com/rust-lang/rust/pull/95474/) This is a soundness fix which may break code that was erroneously relying on this behavior. Compiler -------- - [Add armv5te-none-eabi and thumbv5te-none-eabi tier 3 targets](https://github.com/rust-lang/rust/pull/101329/) - Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. - [Add support for linking against macOS universal libraries](https://github.com/rust-lang/rust/pull/98736) Libraries --------- - [Fix `#[derive(Default)]` on a generic `#[default]` enum adding unnecessary `Default` bounds](https://github.com/rust-lang/rust/pull/101040/) - [Update to Unicode 15](https://github.com/rust-lang/rust/pull/101821/) Stabilized APIs --------------- - [`proc_macro::Span::source_text`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.source_text) - [`uX::{checked_add_signed, overflowing_add_signed, saturating_add_signed, wrapping_add_signed}`](https://doc.rust-lang.org/stable/std/primitive.u8.html#method.checked_add_signed) - [`iX::{checked_add_unsigned, overflowing_add_unsigned, saturating_add_unsigned, wrapping_add_unsigned}`](https://doc.rust-lang.org/stable/std/primitive.i8.html#method.checked_add_unsigned) - [`iX::{checked_sub_unsigned, overflowing_sub_unsigned, saturating_sub_unsigned, wrapping_sub_unsigned}`](https://doc.rust-lang.org/stable/std/primitive.i8.html#method.checked_sub_unsigned) - [`BTreeSet::{first, last, pop_first, pop_last}`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeSet.html#method.first) - [`BTreeMap::{first_key_value, last_key_value, first_entry, last_entry, pop_first, pop_last}`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html#method.first_key_value) - [Add `AsFd` implementations for stdio lock types on WASI.](https://github.com/rust-lang/rust/pull/101768/) - [`impl TryFrom<Vec<T>> for Box<[T; N]>`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#impl-TryFrom%3CVec%3CT%2C%20Global%3E%3E-for-Box%3C%5BT%3B%20N%5D%2C%20Global%3E) - [`core::hint::black_box`](https://doc.rust-lang.org/stable/std/hint/fn.black_box.html) - [`Duration::try_from_secs_{f32,f64}`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.try_from_secs_f32) - [`Option::unzip`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.unzip) - [`std::os::fd`](https://doc.rust-lang.org/stable/std/os/fd/index.html) Rustdoc ------- - [Add Rustdoc warning for invalid HTML tags in the documentation](https://github.com/rust-lang/rust/pull/101720/) Cargo ----- - [Added `cargo remove` to remove dependencies from Cargo.toml](https://doc.rust-lang.org/nightly/cargo/commands/cargo-remove.html) - [`cargo publish` now waits for the new version to be downloadable before exiting](https://github.com/rust-lang/cargo/pull/11062) See [detailed release notes](https://github.com/rust-lang/cargo/blob/master/CHANGELOG.md#cargo-166-2022-12-15) for more. Compatibility Notes ------------------- - [Only apply `ProceduralMasquerade` hack to older versions of `rental`](https://github.com/rust-lang/rust/pull/94063/) - [Don't export `__heap_base` and `__data_end` on wasm32-wasi.](https://github.com/rust-lang/rust/pull/102385/) - [Don't export `__wasm_init_memory` on WebAssembly.](https://github.com/rust-lang/rust/pull/102426/) - [Only export `__tls_*` on wasm32-unknown-unknown.](https://github.com/rust-lang/rust/pull/102440/) - [Don't link to `libresolv` in libstd on Darwin](https://github.com/rust-lang/rust/pull/102766/) - [Update libstd's libc to 0.2.135 (to make `libstd` no longer pull in `libiconv.dylib` on Darwin)](https://github.com/rust-lang/rust/pull/103277/) - [Opaque types no longer imply lifetime bounds](https://github.com/rust-lang/rust/pull/95474/) This is a soundness fix which may break code that was erroneously relying on this behavior. - [Make `order_dependent_trait_objects` show up in future-breakage reports](https://github.com/rust-lang/rust/pull/102635/) - [Change std::process::Command spawning to default to inheriting the parent's signal mask](https://github.com/rust-lang/rust/pull/101077/) Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Enable BOLT for LLVM compilation](https://github.com/rust-lang/rust/pull/94381/) - [Enable LTO for rustc_driver.so](https://github.com/rust-lang/rust/pull/101403/) Version 1.65.0 (2022-11-03) ========================== Language -------- - [Error on `as` casts of enums with `#[non_exhaustive]` variants](https://github.com/rust-lang/rust/pull/92744/) - [Stabilize `let else`](https://github.com/rust-lang/rust/pull/93628/) - [Stabilize generic associated types (GATs)](https://github.com/rust-lang/rust/pull/96709/) - [Add lints `let_underscore_drop` and `let_underscore_lock` from Clippy](https://github.com/rust-lang/rust/pull/97739/) - [Stabilize `break`ing from arbitrary labeled blocks ("label-break-value")](https://github.com/rust-lang/rust/pull/99332/) - [Uninitialized integers, floats, and raw pointers are now considered immediate UB](https://github.com/rust-lang/rust/pull/98919/). Usage of `MaybeUninit` is the correct way to work with uninitialized memory. - [Stabilize raw-dylib for Windows x86_64, aarch64, and thumbv7a](https://github.com/rust-lang/rust/pull/99916/) - [Do not allow `Drop` impl on foreign ADTs](https://github.com/rust-lang/rust/pull/99576/) Compiler -------- - [Stabilize -Csplit-debuginfo on Linux](https://github.com/rust-lang/rust/pull/98051/) - [Use niche-filling optimization even when multiple variants have data](https://github.com/rust-lang/rust/pull/94075/) - [Associated type projections are now verified to be well-formed prior to resolving the underlying type](https://github.com/rust-lang/rust/pull/99217/#issuecomment-1209365630) - [Stringify non-shorthand visibility correctly](https://github.com/rust-lang/rust/pull/100350/) - [Normalize struct field types when unsizing](https://github.com/rust-lang/rust/pull/101831/) - [Update to LLVM 15](https://github.com/rust-lang/rust/pull/99464/) - [Fix aarch64 call abi to correctly zeroext when needed](https://github.com/rust-lang/rust/pull/97800/) - [debuginfo: Generalize C++-like encoding for enums](https://github.com/rust-lang/rust/pull/98393/) - [Add `special_module_name` lint](https://github.com/rust-lang/rust/pull/94467/) - [Add support for generating unique profraw files by default when using `-C instrument-coverage`](https://github.com/rust-lang/rust/pull/100384/) - [Allow dynamic linking for iOS/tvOS targets](https://github.com/rust-lang/rust/pull/100636/) New targets: - [Add armv4t-none-eabi as a tier 3 target](https://github.com/rust-lang/rust/pull/100244/) - [Add powerpc64-unknown-openbsd and riscv64-unknown-openbsd as tier 3 targets](https://github.com/rust-lang/rust/pull/101025/) - Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [Don't generate `PartialEq::ne` in derive(PartialEq)](https://github.com/rust-lang/rust/pull/98655/) - [Windows RNG: Use `BCRYPT_RNG_ALG_HANDLE` by default](https://github.com/rust-lang/rust/pull/101325/) - [Forbid mixing `System` with direct system allocator calls](https://github.com/rust-lang/rust/pull/101394/) - [Document no support for writing to non-blocking stdio/stderr](https://github.com/rust-lang/rust/pull/101416/) - [`std::layout::Layout` size must not overflow `isize::MAX` when rounded up to `align`](https://github.com/rust-lang/rust/pull/95295) This also changes the safety conditions on `Layout::from_size_align_unchecked`. Stabilized APIs --------------- - [`std::backtrace::Backtrace`](https://doc.rust-lang.org/stable/std/backtrace/struct.Backtrace.html) - [`Bound::as_ref`](https://doc.rust-lang.org/stable/std/ops/enum.Bound.html#method.as_ref) - [`std::io::read_to_string`](https://doc.rust-lang.org/stable/std/io/fn.read_to_string.html) - [`<*const T>::cast_mut`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.cast_mut) - [`<*mut T>::cast_const`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.cast_const) These APIs are now stable in const contexts: - [`<*const T>::offset_from`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.offset_from) - [`<*mut T>::offset_from`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.offset_from) Cargo ----- - [Apply GitHub fast path even for partial hashes](https://github.com/rust-lang/cargo/pull/10807/) - [Do not add home bin path to PATH if it's already there](https://github.com/rust-lang/cargo/pull/11023/) - [Take priority into account within the pending queue](https://github.com/rust-lang/cargo/pull/11032/). This slightly optimizes job scheduling by Cargo, with typically small improvements on larger crate graph builds. Compatibility Notes ------------------- - [`std::layout::Layout` size must not overflow `isize::MAX` when rounded up to `align`](https://github.com/rust-lang/rust/pull/95295). This also changes the safety conditions on `Layout::from_size_align_unchecked`. - [`PollFn` now only implements `Unpin` if the closure is `Unpin`](https://github.com/rust-lang/rust/pull/102737). This is a possible breaking change if users were relying on the blanket unpin implementation. See discussion on the PR for details of why this change was made. - [Drop ExactSizeIterator impl from std::char::EscapeAscii](https://github.com/rust-lang/rust/pull/99880) This is a backwards-incompatible change to the standard library's surface area, but is unlikely to affect real world usage. - [Do not consider a single repeated lifetime eligible for elision in the return type](https://github.com/rust-lang/rust/pull/103450) This behavior was unintentionally changed in 1.64.0, and this release reverts that change by making this an error again. - [Reenable disabled early syntax gates as future-incompatibility lints](https://github.com/rust-lang/rust/pull/99935/) - [Update the minimum external LLVM to 13](https://github.com/rust-lang/rust/pull/100460/) - [Don't duplicate file descriptors into stdio fds](https://github.com/rust-lang/rust/pull/101426/) - [Sunset RLS](https://github.com/rust-lang/rust/pull/100863/) - [Deny usage of `#![cfg_attr(..., crate_type = ...)]` to set the crate type](https://github.com/rust-lang/rust/pull/99784/) This strengthens the forward compatibility lint deprecated_cfg_attr_crate_type_name to deny. - [`llvm-has-rust-patches` allows setting the build system to treat the LLVM as having Rust-specific patches](https://github.com/rust-lang/rust/pull/101072) This option may need to be set for distributions that are building Rust with a patched LLVM via `llvm-config`, not the built-in LLVM. - Combining three or more languages (e.g. Objective C, C++ and Rust) into one binary may hit linker limitations when using `lld`. For more information, see [issue 102754][102754]. [102754]: https://github.com/rust-lang/rust/issues/102754 Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - [Add `x.sh` and `x.ps1` shell scripts](https://github.com/rust-lang/rust/pull/99992/) - [compiletest: use target cfg instead of hard-coded tables](https://github.com/rust-lang/rust/pull/100260/) - [Use object instead of LLVM for reading bitcode from rlibs](https://github.com/rust-lang/rust/pull/98100/) - [Enable MIR inlining for optimized compilations](https://github.com/rust-lang/rust/pull/91743) This provides a 3-10% improvement in compiletimes for real world crates. See [perf results](https://perf.rust-lang.org/compare.html?start=aedf78e56b2279cc869962feac5153b6ba7001ed&end=0075bb4fad68e64b6d1be06bf2db366c30bc75e1&stat=instructions:u). Version 1.64.0 (2022-09-22) =========================== Language -------- - [Unions with mutable references or tuples of allowed types are now allowed](https://github.com/rust-lang/rust/pull/97995/) - It is now considered valid to deallocate memory pointed to by a shared reference `&T` [if every byte in `T` is inside an `UnsafeCell`](https://github.com/rust-lang/rust/pull/98017/) - Unused tuple struct fields are now warned against in an allow-by-default lint, [`unused_tuple_struct_fields`](https://github.com/rust-lang/rust/pull/95977/), similar to the existing warning for unused struct fields. This lint will become warn-by-default in the future. Compiler -------- - [Add Nintendo Switch as tier 3 target](https://github.com/rust-lang/rust/pull/88991/) - Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. - [Only compile `#[used]` as llvm.compiler.used for ELF targets](https://github.com/rust-lang/rust/pull/93718/) - [Add the `--diagnostic-width` compiler flag to define the terminal width.](https://github.com/rust-lang/rust/pull/95635/) - [Add support for link-flavor `rust-lld` for iOS, tvOS and watchOS](https://github.com/rust-lang/rust/pull/98771/) Libraries --------- - [Remove restrictions on compare-exchange memory ordering.](https://github.com/rust-lang/rust/pull/98383/) - You can now `write!` or `writeln!` into an `OsString`: [Implement `fmt::Write` for `OsString`](https://github.com/rust-lang/rust/pull/97915/) - [Make RwLockReadGuard covariant](https://github.com/rust-lang/rust/pull/96820/) - [Implement `FusedIterator` for `std::net::[Into]Incoming`](https://github.com/rust-lang/rust/pull/97300/) - [`impl<T: AsRawFd> AsRawFd for {Arc,Box}<T>`](https://github.com/rust-lang/rust/pull/97437/) - [`ptr::copy` and `ptr::swap` are doing untyped copies](https://github.com/rust-lang/rust/pull/97712/) - [Add cgroupv1 support to `available_parallelism`](https://github.com/rust-lang/rust/pull/97925/) - [Mitigate many incorrect uses of `mem::uninitialized`](https://github.com/rust-lang/rust/pull/99182/) Stabilized APIs --------------- - [`future::IntoFuture`](https://doc.rust-lang.org/stable/std/future/trait.IntoFuture.html) - [`future::poll_fn`](https://doc.rust-lang.org/stable/std/future/fn.poll_fn.html) - [`task::ready!`](https://doc.rust-lang.org/stable/std/task/macro.ready.html) - [`num::NonZero*::checked_mul`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroUsize.html#method.checked_mul) - [`num::NonZero*::checked_pow`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroUsize.html#method.checked_pow) - [`num::NonZero*::saturating_mul`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroUsize.html#method.saturating_mul) - [`num::NonZero*::saturating_pow`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroUsize.html#method.saturating_pow) - [`num::NonZeroI*::abs`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroIsize.html#method.abs) - [`num::NonZeroI*::checked_abs`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroIsize.html#method.checked_abs) - [`num::NonZeroI*::overflowing_abs`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroIsize.html#method.overflowing_abs) - [`num::NonZeroI*::saturating_abs`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroIsize.html#method.saturating_abs) - [`num::NonZeroI*::unsigned_abs`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroIsize.html#method.unsigned_abs) - [`num::NonZeroI*::wrapping_abs`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroIsize.html#method.wrapping_abs) - [`num::NonZeroU*::checked_add`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroUsize.html#method.checked_add) - [`num::NonZeroU*::checked_next_power_of_two`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroUsize.html#method.checked_next_power_of_two) - [`num::NonZeroU*::saturating_add`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroUsize.html#method.saturating_add) - [`os::unix::process::CommandExt::process_group`](https://doc.rust-lang.org/stable/std/os/unix/process/trait.CommandExt.html#tymethod.process_group) - [`os::windows::fs::FileTypeExt::is_symlink_dir`](https://doc.rust-lang.org/stable/std/os/windows/fs/trait.FileTypeExt.html#tymethod.is_symlink_dir) - [`os::windows::fs::FileTypeExt::is_symlink_file`](https://doc.rust-lang.org/stable/std/os/windows/fs/trait.FileTypeExt.html#tymethod.is_symlink_file) These types were previously stable in `std::ffi`, but are now also available in `core` and `alloc`: - [`core::ffi::CStr`](https://doc.rust-lang.org/stable/core/ffi/struct.CStr.html) - [`core::ffi::FromBytesWithNulError`](https://doc.rust-lang.org/stable/core/ffi/struct.FromBytesWithNulError.html) - [`alloc::ffi::CString`](https://doc.rust-lang.org/stable/alloc/ffi/struct.CString.html) - [`alloc::ffi::FromVecWithNulError`](https://doc.rust-lang.org/stable/alloc/ffi/struct.FromVecWithNulError.html) - [`alloc::ffi::IntoStringError`](https://doc.rust-lang.org/stable/alloc/ffi/struct.IntoStringError.html) - [`alloc::ffi::NulError`](https://doc.rust-lang.org/stable/alloc/ffi/struct.NulError.html) These types were previously stable in `std::os::raw`, but are now also available in `core::ffi` and `std::ffi`: - [`ffi::c_char`](https://doc.rust-lang.org/stable/std/ffi/type.c_char.html) - [`ffi::c_double`](https://doc.rust-lang.org/stable/std/ffi/type.c_double.html) - [`ffi::c_float`](https://doc.rust-lang.org/stable/std/ffi/type.c_float.html) - [`ffi::c_int`](https://doc.rust-lang.org/stable/std/ffi/type.c_int.html) - [`ffi::c_long`](https://doc.rust-lang.org/stable/std/ffi/type.c_long.html) - [`ffi::c_longlong`](https://doc.rust-lang.org/stable/std/ffi/type.c_longlong.html) - [`ffi::c_schar`](https://doc.rust-lang.org/stable/std/ffi/type.c_schar.html) - [`ffi::c_short`](https://doc.rust-lang.org/stable/std/ffi/type.c_short.html) - [`ffi::c_uchar`](https://doc.rust-lang.org/stable/std/ffi/type.c_uchar.html) - [`ffi::c_uint`](https://doc.rust-lang.org/stable/std/ffi/type.c_uint.html) - [`ffi::c_ulong`](https://doc.rust-lang.org/stable/std/ffi/type.c_ulong.html) - [`ffi::c_ulonglong`](https://doc.rust-lang.org/stable/std/ffi/type.c_ulonglong.html) - [`ffi::c_ushort`](https://doc.rust-lang.org/stable/std/ffi/type.c_ushort.html) These APIs are now usable in const contexts: - [`slice::from_raw_parts`](https://doc.rust-lang.org/stable/core/slice/fn.from_raw_parts.html) Cargo ----- - [Packages can now inherit settings from the workspace so that the settings can be centralized in one place.](https://github.com/rust-lang/cargo/pull/10859) See [`workspace.package`](https://doc.rust-lang.org/nightly/cargo/reference/workspaces.html#the-workspacepackage-table) and [`workspace.dependencies`](https://doc.rust-lang.org/nightly/cargo/reference/workspaces.html#the-workspacedependencies-table) for more details on how to define these common settings. - [Cargo commands can now accept multiple `--target` flags to build for multiple targets at once](https://github.com/rust-lang/cargo/pull/10766), and the [`build.target`](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildtarget) config option may now take an array of multiple targets. - [The `--jobs` argument can now take a negative number to count backwards from the max CPUs.](https://github.com/rust-lang/cargo/pull/10844) - [`cargo add` will now update `Cargo.lock`.](https://github.com/rust-lang/cargo/pull/10902) - [Added](https://github.com/rust-lang/cargo/pull/10838) the [`--crate-type`](https://doc.rust-lang.org/nightly/cargo/commands/cargo-rustc.html#option-cargo-rustc---crate-type) flag to `cargo rustc` to override the crate type. - [Significantly improved the performance fetching git dependencies from GitHub when using a hash in the `rev` field.](https://github.com/rust-lang/cargo/pull/10079) Misc ---- - [The `rust-analyzer` rustup component is now available on the stable channel.](https://github.com/rust-lang/rust/pull/98640/) Compatibility Notes ------------------- - The minimum required versions for all `-linux-gnu` targets are now at least kernel 3.2 and glibc 2.17, for targets that previously supported older versions: [Increase the minimum linux-gnu versions](https://github.com/rust-lang/rust/pull/95026/) - [Network primitives are now implemented with the ideal Rust layout, not the C system layout](https://github.com/rust-lang/rust/pull/78802/). This can cause problems when transmuting the types. - [Add assertion that `transmute_copy`'s `U` is not larger than `T`](https://github.com/rust-lang/rust/pull/98839/) - [A soundness bug in `BTreeMap` was fixed](https://github.com/rust-lang/rust/pull/99413/) that allowed data it was borrowing to be dropped before the container. - [The Drop behavior of C-like enums cast to ints has changed](https://github.com/rust-lang/rust/pull/96862/). These are already discouraged by a compiler warning. - [Relate late-bound closure lifetimes to parent fn in NLL](https://github.com/rust-lang/rust/pull/98835/) - [Errors at const-eval time are now in future incompatibility reports](https://github.com/rust-lang/rust/pull/97743/) - On the `thumbv6m-none-eabi` target, some incorrect `asm!` statements were erroneously accepted if they used the high registers (r8 to r14) as an input/output operand. [This is no longer accepted](https://github.com/rust-lang/rust/pull/99155/). - [`impl Trait` was accidentally accepted as the associated type value of return-position `impl Trait`](https://github.com/rust-lang/rust/pull/97346/), without fulfilling all the trait bounds of that associated type, as long as the hidden type satisfies said bounds. This has been fixed. Internal Changes ---------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. - Windows builds now use profile-guided optimization, providing 10-20% improvements to compiler performance: [Utilize PGO for windows x64 rustc dist builds](https://github.com/rust-lang/rust/pull/96978/) - [Stop keeping metadata in memory before writing it to disk](https://github.com/rust-lang/rust/pull/96544/) - [compiletest: strip debuginfo by default for mode=ui](https://github.com/rust-lang/rust/pull/98140/) - Many improvements to generated code for derives, including performance improvements: - [Don't use match-destructuring for derived ops on structs.](https://github.com/rust-lang/rust/pull/98446/) - [Many small deriving cleanups](https://github.com/rust-lang/rust/pull/98741/) - [More derive output improvements](https://github.com/rust-lang/rust/pull/98758/) - [Clarify deriving code](https://github.com/rust-lang/rust/pull/98915/) - [Final derive output improvements](https://github.com/rust-lang/rust/pull/99046/) - [Stop injecting `#[allow(unused_qualifications)]` in generated `derive` implementations](https://github.com/rust-lang/rust/pull/99485/) - [Improve `derive(Debug)`](https://github.com/rust-lang/rust/pull/98190/) - [Bump to clap 3](https://github.com/rust-lang/rust/pull/98213/) - [fully move dropck to mir](https://github.com/rust-lang/rust/pull/98641/) - [Optimize `Vec::insert` for the case where `index == len`.](https://github.com/rust-lang/rust/pull/98755/) - [Convert rust-analyzer to an in-tree tool](https://github.com/rust-lang/rust/pull/99603/) Version 1.63.0 (2022-08-11) ========================== Language -------- - [Remove migrate borrowck mode for pre-NLL errors.][95565] - [Modify MIR building to drop repeat expressions with length zero.][95953] - [Remove label/lifetime shadowing warnings.][96296] - [Allow explicit generic arguments in the presence of `impl Trait` args.][96868] - [Make `cenum_impl_drop_cast` warnings deny-by-default.][97652] - [Prevent unwinding when `-C panic=abort` is used regardless of declared ABI.][96959] - [lub: don't bail out due to empty binders.][97867] Compiler -------- - [Stabilize the `bundle` native library modifier,][95818] also removing the deprecated `static-nobundle` linking kind. - [Add Apple WatchOS compile targets\*.][95243] - [Add a Windows application manifest to rustc-main.][96737] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [Implement `Copy`, `Clone`, `PartialEq` and `Eq` for `core::fmt::Alignment`.][94530] - [Extend `ptr::null` and `null_mut` to all thin (including extern) types.][94954] - [`impl Read and Write for VecDeque<u8>`.][95632] - [STD support for the Nintendo 3DS.][95897] - [Use rounding in float to Duration conversion methods.][96051] - [Make write/print macros eagerly drop temporaries.][96455] - [Implement internal traits that enable `[OsStr]::join`.][96881] - [Implement `Hash` for `core::alloc::Layout`.][97034] - [Add capacity documentation for `OsString`.][97202] - [Put a bound on collection misbehavior.][97316] - [Make `std::mem::needs_drop` accept `?Sized`.][97675] - [`impl Termination for Infallible` and then make the `Result` impls of `Termination` more generic.][97803] - [Document Rust's stance on `/proc/self/mem`.][97837] Stabilized APIs --------------- - [`array::from_fn`] - [`Box::into_pin`] - [`BinaryHeap::try_reserve`] - [`BinaryHeap::try_reserve_exact`] - [`OsString::try_reserve`] - [`OsString::try_reserve_exact`] - [`PathBuf::try_reserve`] - [`PathBuf::try_reserve_exact`] - [`Path::try_exists`] - [`Ref::filter_map`] - [`RefMut::filter_map`] - [`NonNull::<[T]>::len`][`NonNull::<slice>::len`] - [`ToOwned::clone_into`] - [`Ipv6Addr::to_ipv4_mapped`] - [`unix::io::AsFd`] - [`unix::io::BorrowedFd<'fd>`] - [`unix::io::OwnedFd`] - [`windows::io::AsHandle`] - [`windows::io::BorrowedHandle<'handle>`] - [`windows::io::OwnedHandle`] - [`windows::io::HandleOrInvalid`] - [`windows::io::HandleOrNull`] - [`windows::io::InvalidHandleError`] - [`windows::io::NullHandleError`] - [`windows::io::AsSocket`] - [`windows::io::BorrowedSocket<'handle>`] - [`windows::io::OwnedSocket`] - [`thread::scope`] - [`thread::Scope`] - [`thread::ScopedJoinHandle`] These APIs are now usable in const contexts: - [`array::from_ref`] - [`slice::from_ref`] - [`intrinsics::copy`] - [`intrinsics::copy_nonoverlapping`] - [`<*const T>::copy_to`] - [`<*const T>::copy_to_nonoverlapping`] - [`<*mut T>::copy_to`] - [`<*mut T>::copy_to_nonoverlapping`] - [`<*mut T>::copy_from`] - [`<*mut T>::copy_from_nonoverlapping`] - [`str::from_utf8`] - [`Utf8Error::error_len`] - [`Utf8Error::valid_up_to`] - [`Condvar::new`] - [`Mutex::new`] - [`RwLock::new`] Cargo ----- - [Stabilize the `--config path` command-line argument.][cargo/10755] - [Expose rust-version in the environment as `CARGO_PKG_RUST_VERSION`.][cargo/10713] Compatibility Notes ------------------- - [`#[link]` attributes are now checked more strictly,][96885] which may introduce errors for invalid attribute arguments that were previously ignored. - [Rounding is now used when converting a float to a `Duration`.][96051] The converted duration can differ slightly from what it was. Internal Changes ---------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. - [Prepare Rust for LLVM opaque pointers.][94214] [94214]: https://github.com/rust-lang/rust/pull/94214/ [94530]: https://github.com/rust-lang/rust/pull/94530/ [94954]: https://github.com/rust-lang/rust/pull/94954/ [95243]: https://github.com/rust-lang/rust/pull/95243/ [95565]: https://github.com/rust-lang/rust/pull/95565/ [95632]: https://github.com/rust-lang/rust/pull/95632/ [95818]: https://github.com/rust-lang/rust/pull/95818/ [95897]: https://github.com/rust-lang/rust/pull/95897/ [95953]: https://github.com/rust-lang/rust/pull/95953/ [96051]: https://github.com/rust-lang/rust/pull/96051/ [96296]: https://github.com/rust-lang/rust/pull/96296/ [96455]: https://github.com/rust-lang/rust/pull/96455/ [96737]: https://github.com/rust-lang/rust/pull/96737/ [96868]: https://github.com/rust-lang/rust/pull/96868/ [96881]: https://github.com/rust-lang/rust/pull/96881/ [96885]: https://github.com/rust-lang/rust/pull/96885/ [96959]: https://github.com/rust-lang/rust/pull/96959/ [97034]: https://github.com/rust-lang/rust/pull/97034/ [97202]: https://github.com/rust-lang/rust/pull/97202/ [97316]: https://github.com/rust-lang/rust/pull/97316/ [97652]: https://github.com/rust-lang/rust/pull/97652/ [97675]: https://github.com/rust-lang/rust/pull/97675/ [97803]: https://github.com/rust-lang/rust/pull/97803/ [97837]: https://github.com/rust-lang/rust/pull/97837/ [97867]: https://github.com/rust-lang/rust/pull/97867/ [cargo/10713]: https://github.com/rust-lang/cargo/pull/10713/ [cargo/10755]: https://github.com/rust-lang/cargo/pull/10755/ [`array::from_fn`]: https://doc.rust-lang.org/stable/std/array/fn.from_fn.html [`Box::into_pin`]: https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.into_pin [`BinaryHeap::try_reserve_exact`]: https://doc.rust-lang.org/stable/alloc/collections/binary_heap/struct.BinaryHeap.html#method.try_reserve_exact [`BinaryHeap::try_reserve`]: https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.try_reserve [`OsString::try_reserve`]: https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.try_reserve [`OsString::try_reserve_exact`]: https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.try_reserve_exact [`PathBuf::try_reserve`]: https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.try_reserve [`PathBuf::try_reserve_exact`]: https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.try_reserve_exact [`Path::try_exists`]: https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.try_exists [`Ref::filter_map`]: https://doc.rust-lang.org/stable/std/cell/struct.Ref.html#method.filter_map [`RefMut::filter_map`]: https://doc.rust-lang.org/stable/std/cell/struct.RefMut.html#method.filter_map [`NonNull::<slice>::len`]: https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.len [`ToOwned::clone_into`]: https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into [`Ipv6Addr::to_ipv4_mapped`]: https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.to_ipv4_mapped [`unix::io::AsFd`]: https://doc.rust-lang.org/stable/std/os/unix/io/trait.AsFd.html [`unix::io::BorrowedFd<'fd>`]: https://doc.rust-lang.org/stable/std/os/unix/io/struct.BorrowedFd.html [`unix::io::OwnedFd`]: https://doc.rust-lang.org/stable/std/os/unix/io/struct.OwnedFd.html [`windows::io::AsHandle`]: https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsHandle.html [`windows::io::BorrowedHandle<'handle>`]: https://doc.rust-lang.org/stable/std/os/windows/io/struct.BorrowedHandle.html [`windows::io::OwnedHandle`]: https://doc.rust-lang.org/stable/std/os/windows/io/struct.OwnedHandle.html [`windows::io::HandleOrInvalid`]: https://doc.rust-lang.org/stable/std/os/windows/io/struct.HandleOrInvalid.html [`windows::io::HandleOrNull`]: https://doc.rust-lang.org/stable/std/os/windows/io/struct.HandleOrNull.html [`windows::io::InvalidHandleError`]: https://doc.rust-lang.org/stable/std/os/windows/io/struct.InvalidHandleError.html [`windows::io::NullHandleError`]: https://doc.rust-lang.org/stable/std/os/windows/io/struct.NullHandleError.html [`windows::io::AsSocket`]: https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsSocket.html [`windows::io::BorrowedSocket<'handle>`]: https://doc.rust-lang.org/stable/std/os/windows/io/struct.BorrowedSocket.html [`windows::io::OwnedSocket`]: https://doc.rust-lang.org/stable/std/os/windows/io/struct.OwnedSocket.html [`thread::scope`]: https://doc.rust-lang.org/stable/std/thread/fn.scope.html [`thread::Scope`]: https://doc.rust-lang.org/stable/std/thread/struct.Scope.html [`thread::ScopedJoinHandle`]: https://doc.rust-lang.org/stable/std/thread/struct.ScopedJoinHandle.html [`array::from_ref`]: https://doc.rust-lang.org/stable/std/array/fn.from_ref.html [`slice::from_ref`]: https://doc.rust-lang.org/stable/std/slice/fn.from_ref.html [`intrinsics::copy`]: https://doc.rust-lang.org/stable/std/intrinsics/fn.copy.html [`intrinsics::copy_nonoverlapping`]: https://doc.rust-lang.org/stable/std/intrinsics/fn.copy_nonoverlapping.html [`<*const T>::copy_to`]: https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.copy_to [`<*const T>::copy_to_nonoverlapping`]: https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.copy_to_nonoverlapping [`<*mut T>::copy_to`]: https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.copy_to-1 [`<*mut T>::copy_to_nonoverlapping`]: https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.copy_to_nonoverlapping-1 [`<*mut T>::copy_from`]: https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.copy_from [`<*mut T>::copy_from_nonoverlapping`]: https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.copy_from_nonoverlapping [`str::from_utf8`]: https://doc.rust-lang.org/stable/std/str/fn.from_utf8.html [`Utf8Error::error_len`]: https://doc.rust-lang.org/stable/std/str/struct.Utf8Error.html#method.error_len [`Utf8Error::valid_up_to`]: https://doc.rust-lang.org/stable/std/str/struct.Utf8Error.html#method.valid_up_to [`Condvar::new`]: https://doc.rust-lang.org/stable/std/sync/struct.Condvar.html#method.new [`Mutex::new`]: https://doc.rust-lang.org/stable/std/sync/struct.Mutex.html#method.new [`RwLock::new`]: https://doc.rust-lang.org/stable/std/sync/struct.RwLock.html#method.new Version 1.62.1 (2022-07-19) ========================== Rust 1.62.1 addresses a few recent regressions in the compiler and standard library, and also mitigates a CPU vulnerability on Intel SGX. * [The compiler fixed unsound function coercions involving `impl Trait` return types.][98608] * [The compiler fixed an incremental compilation bug with `async fn` lifetimes.][98890] * [Windows added a fallback for overlapped I/O in synchronous reads and writes.][98950] * [The `x86_64-fortanix-unknown-sgx` target added a mitigation for the MMIO stale data vulnerability][98126], advisory [INTEL-SA-00615]. [98608]: https://github.com/rust-lang/rust/issues/98608 [98890]: https://github.com/rust-lang/rust/issues/98890 [98950]: https://github.com/rust-lang/rust/pull/98950 [98126]: https://github.com/rust-lang/rust/pull/98126 [INTEL-SA-00615]: https://www.intel.com/content/www/us/en/security-center/advisory/intel-sa-00615.html Version 1.62.0 (2022-06-30) ========================== Language -------- - [Stabilize `#[derive(Default)]` on enums with a `#[default]` variant][94457] - [Teach flow sensitive checks that visibly uninhabited call expressions never return][93313] - [Fix constants not getting dropped if part of a diverging expression][94775] - [Support unit struct/enum variant in destructuring assignment][95380] - [Remove mutable_borrow_reservation_conflict lint and allow the code pattern][96268] - [`const` functions may now specify `extern "C"` or `extern "Rust"`][95346] Compiler -------- - [linker: Stop using whole-archive on dependencies of dylibs][96436] - [Make `unaligned_references` lint deny-by-default][95372] This lint is also a future compatibility lint, and is expected to eventually become a hard error. - [Only add codegen backend to dep info if -Zbinary-dep-depinfo is used][93969] - [Reject `#[thread_local]` attribute on non-static items][95006] - [Add tier 3 `aarch64-pc-windows-gnullvm` and `x86_64-pc-windows-gnullvm` targets\*][94872] - [Implement a lint to warn about unused macro rules][96150] - [Promote `x86_64-unknown-none` target to Tier 2\*][95705] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [Windows: Use a pipe relay for chaining pipes][95841] - [Replace Linux Mutex and Condvar with futex based ones.][95035] - [Replace RwLock by a futex based one on Linux][95801] - [std: directly use pthread in UNIX parker implementation][96393] Stabilized APIs --------------- - [`bool::then_some`] - [`f32::total_cmp`] - [`f64::total_cmp`] - [`Stdin::lines`] - [`windows::CommandExt::raw_arg`] - [`impl<T: Default> Default for AssertUnwindSafe<T>`] - [`From<Rc<str>> for Rc<[u8]>`][rc-u8-from-str] - [`From<Arc<str>> for Arc<[u8]>`][arc-u8-from-str] - [`FusedIterator for EncodeWide`] - [RDM intrinsics on aarch64][stdarch/1285] Clippy ------ - [Create clippy lint against unexpectedly late drop for temporaries in match scrutinee expressions][94206] Cargo ----- - Added the `cargo add` command for adding dependencies to `Cargo.toml` from the command-line. [docs](https://doc.rust-lang.org/nightly/cargo/commands/cargo-add.html) - Package ID specs now support `name@version` syntax in addition to the previous `name:version` to align with the behavior in `cargo add` and other tools. `cargo install` and `cargo yank` also now support this syntax so the version does not need to passed as a separate flag. - The `git` and `registry` directories in Cargo's home directory (usually `~/.cargo`) are now marked as cache directories so that they are not included in backups or content indexing (on Windows). - Added automatic `@` argfile support, which will use "response files" if the command-line to `rustc` exceeds the operating system's limit. Compatibility Notes ------------------- - `cargo test` now passes `--target` to `rustdoc` if the specified target is the same as the host target. [#10594](https://github.com/rust-lang/cargo/pull/10594) - [rustdoc: doctests are now run on unexported `macro_rules!` macros, matching other private items][96630] - [rustdoc: Remove .woff font files][96279] - [Enforce Copy bounds for repeat elements while considering lifetimes][95819] - [Windows: Fix potential unsoundness by aborting if `File` reads or writes cannot complete synchronously][95469]. Internal Changes ---------------- - [Unify ReentrantMutex implementations across all platforms][96042] These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. [93313]: https://github.com/rust-lang/rust/pull/93313/ [93969]: https://github.com/rust-lang/rust/pull/93969/ [94206]: https://github.com/rust-lang/rust/pull/94206/ [94457]: https://github.com/rust-lang/rust/pull/94457/ [94775]: https://github.com/rust-lang/rust/pull/94775/ [94872]: https://github.com/rust-lang/rust/pull/94872/ [95006]: https://github.com/rust-lang/rust/pull/95006/ [95035]: https://github.com/rust-lang/rust/pull/95035/ [95346]: https://github.com/rust-lang/rust/pull/95346/ [95372]: https://github.com/rust-lang/rust/pull/95372/ [95380]: https://github.com/rust-lang/rust/pull/95380/ [95431]: https://github.com/rust-lang/rust/pull/95431/ [95469]: https://github.com/rust-lang/rust/pull/95469/ [95705]: https://github.com/rust-lang/rust/pull/95705/ [95801]: https://github.com/rust-lang/rust/pull/95801/ [95819]: https://github.com/rust-lang/rust/pull/95819/ [95841]: https://github.com/rust-lang/rust/pull/95841/ [96042]: https://github.com/rust-lang/rust/pull/96042/ [96150]: https://github.com/rust-lang/rust/pull/96150/ [96268]: https://github.com/rust-lang/rust/pull/96268/ [96279]: https://github.com/rust-lang/rust/pull/96279/ [96393]: https://github.com/rust-lang/rust/pull/96393/ [96436]: https://github.com/rust-lang/rust/pull/96436/ [96557]: https://github.com/rust-lang/rust/pull/96557/ [96630]: https://github.com/rust-lang/rust/pull/96630/ [`bool::then_some`]: https://doc.rust-lang.org/stable/std/primitive.bool.html#method.then_some [`f32::total_cmp`]: https://doc.rust-lang.org/stable/std/primitive.f32.html#method.total_cmp [`f64::total_cmp`]: https://doc.rust-lang.org/stable/std/primitive.f64.html#method.total_cmp [`Stdin::lines`]: https://doc.rust-lang.org/stable/std/io/struct.Stdin.html#method.lines [`impl<T: Default> Default for AssertUnwindSafe<T>`]: https://doc.rust-lang.org/stable/std/panic/struct.AssertUnwindSafe.html#impl-Default [rc-u8-from-str]: https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#impl-From%3CRc%3Cstr%3E%3E [arc-u8-from-str]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#impl-From%3CArc%3Cstr%3E%3E [stdarch/1285]: https://github.com/rust-lang/stdarch/pull/1285 [`windows::CommandExt::raw_arg`]: https://doc.rust-lang.org/stable/std/os/windows/process/trait.CommandExt.html#tymethod.raw_arg [`FusedIterator for EncodeWide`]: https://doc.rust-lang.org/stable/std/os/windows/ffi/struct.EncodeWide.html#impl-FusedIterator Version 1.61.0 (2022-05-19) ========================== Language -------- - [`const fn` signatures can now include generic trait bounds][93827] - [`const fn` signatures can now use `impl Trait` in argument and return position][93827] - [Function pointers can now be created, cast, and passed around in a `const fn`][93827] - [Recursive calls can now set the value of a function's opaque `impl Trait` return type][94081] Compiler -------- - [Linking modifier syntax in `#[link]` attributes and on the command line, as well as the `whole-archive` modifier specifically, are now supported][93901] - [The `char` type is now described as UTF-32 in debuginfo][89887] - The [`#[target_feature]`][target_feature] attribute [can now be used with aarch64 features][90621] - X86 [`#[target_feature = "adx"]` is now stable][93745] Libraries --------- - [`ManuallyDrop<T>` is now documented to have the same layout as `T`][88375] - [`#[ignore = "…"]` messages are printed when running tests][92714] - [Consistently show absent stdio handles on Windows as NULL handles][93263] - [Make `std::io::stdio::lock()` return `'static` handles.][93965] Previously, the creation of locked handles to stdin/stdout/stderr would borrow the handles being locked, which prevented writing `let out = std::io::stdout().lock();` because `out` would outlive the return value of `stdout()`. Such code now works, eliminating a common pitfall that affected many Rust users. - [`Vec::from_raw_parts` is now less restrictive about its inputs][95016] - [`std::thread::available_parallelism` now takes cgroup quotas into account.][92697] Since `available_parallelism` is often used to create a thread pool for parallel computation, which may be CPU-bound for performance, `available_parallelism` will return a value consistent with the ability to use that many threads continuously, if possible. For instance, in a container with 8 virtual CPUs but quotas only allowing for 50% usage, `available_parallelism` will return 4. Stabilized APIs --------------- - [`Pin::static_mut`] - [`Pin::static_ref`] - [`Vec::retain_mut`] - [`VecDeque::retain_mut`] - [`Write` for `Cursor<[u8; N]>`][cursor-write-array] - [`std::os::unix::net::SocketAddr::from_pathname`] - [`std::process::ExitCode`] and [`std::process::Termination`]. The stabilization of these two APIs now makes it possible for programs to return errors from `main` with custom exit codes. - [`std::thread::JoinHandle::is_finished`] These APIs are now usable in const contexts: - [`<*const T>::offset` and `<*mut T>::offset`][ptr-offset] - [`<*const T>::wrapping_offset` and `<*mut T>::wrapping_offset`][ptr-wrapping_offset] - [`<*const T>::add` and `<*mut T>::add`][ptr-add] - [`<*const T>::sub` and `<*mut T>::sub`][ptr-sub] - [`<*const T>::wrapping_add` and `<*mut T>::wrapping_add`][ptr-wrapping_add] - [`<*const T>::wrapping_sub` and `<*mut T>::wrapping_sub`][ptr-wrapping_sub] - [`<[T]>::as_mut_ptr`][slice-as_mut_ptr] - [`<[T]>::as_ptr_range`][slice-as_ptr_range] - [`<[T]>::as_mut_ptr_range`][slice-as_mut_ptr_range] Cargo ----- No feature changes, but see compatibility notes. Compatibility Notes ------------------- - Previously native static libraries were linked as `whole-archive` in some cases, but now rustc tries not to use `whole-archive` unless explicitly requested. This [change][93901] may result in linking errors in some cases. To fix such errors, native libraries linked from the command line, build scripts, or [`#[link]` attributes][link-attr] need to - (more common) either be reordered to respect dependencies between them (if `a` depends on `b` then `a` should go first and `b` second) - (less common) or be updated to use the [`+whole-archive`] modifier. - [Catching a second unwind from FFI code while cleaning up from a Rust panic now causes the process to abort][92911] - [Proc macros no longer see `ident` matchers wrapped in groups][92472] - [The number of `#` in `r#` raw string literals is now required to be less than 256][95251] - [When checking that a dyn type satisfies a trait bound, supertrait bounds are now enforced][92285] - [`cargo vendor` now only accepts one value for each `--sync` flag][cargo/10448] - [`cfg` predicates in `all()` and `any()` are always evaluated to detect errors, instead of short-circuiting.][94295] The compatibility considerations here arise in nightly-only code that used the short-circuiting behavior of `all` to write something like `cfg(all(feature = "nightly", syntax-requiring-nightly))`, which will now fail to compile. Instead, use either `cfg_attr(feature = "nightly", ...)` or nested uses of `cfg`. - [bootstrap: static-libstdcpp is now enabled by default, and can now be disabled when llvm-tools is enabled][94832] Internal Changes ---------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. - [debuginfo: Refactor debuginfo generation for types][94261] - [Remove the everybody loops pass][93913] [88375]: https://github.com/rust-lang/rust/pull/88375/ [89887]: https://github.com/rust-lang/rust/pull/89887/ [90621]: https://github.com/rust-lang/rust/pull/90621/ [92285]: https://github.com/rust-lang/rust/pull/92285/ [92472]: https://github.com/rust-lang/rust/pull/92472/ [92697]: https://github.com/rust-lang/rust/pull/92697/ [92714]: https://github.com/rust-lang/rust/pull/92714/ [92911]: https://github.com/rust-lang/rust/pull/92911/ [93263]: https://github.com/rust-lang/rust/pull/93263/ [93745]: https://github.com/rust-lang/rust/pull/93745/ [93827]: https://github.com/rust-lang/rust/pull/93827/ [93901]: https://github.com/rust-lang/rust/pull/93901/ [93913]: https://github.com/rust-lang/rust/pull/93913/ [93965]: https://github.com/rust-lang/rust/pull/93965/ [94081]: https://github.com/rust-lang/rust/pull/94081/ [94261]: https://github.com/rust-lang/rust/pull/94261/ [94295]: https://github.com/rust-lang/rust/pull/94295/ [94832]: https://github.com/rust-lang/rust/pull/94832/ [95016]: https://github.com/rust-lang/rust/pull/95016/ [95251]: https://github.com/rust-lang/rust/pull/95251/ [`+whole-archive`]: https://doc.rust-lang.org/stable/rustc/command-line-arguments.html#linking-modifiers-whole-archive [`Pin::static_mut`]: https://doc.rust-lang.org/stable/std/pin/struct.Pin.html#method.static_mut [`Pin::static_ref`]: https://doc.rust-lang.org/stable/std/pin/struct.Pin.html#method.static_ref [`Vec::retain_mut`]: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.retain_mut [`VecDeque::retain_mut`]: https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html#method.retain_mut [`std::os::unix::net::SocketAddr::from_pathname`]: https://doc.rust-lang.org/stable/std/os/unix/net/struct.SocketAddr.html#method.from_pathname [`std::process::ExitCode`]: https://doc.rust-lang.org/stable/std/process/struct.ExitCode.html [`std::process::Termination`]: https://doc.rust-lang.org/stable/std/process/trait.Termination.html [`std::thread::JoinHandle::is_finished`]: https://doc.rust-lang.org/stable/std/thread/struct.JoinHandle.html#method.is_finished [cargo/10448]: https://github.com/rust-lang/cargo/pull/10448/ [cursor-write-array]: https://doc.rust-lang.org/stable/std/io/struct.Cursor.html#impl-Write-4 [link-attr]: https://doc.rust-lang.org/stable/reference/items/external-blocks.html#the-link-attribute [ptr-add]: https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.add [ptr-offset]: https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.offset [ptr-sub]: https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.sub [ptr-wrapping_add]: https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.wrapping_add [ptr-wrapping_offset]: https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.wrapping_offset [ptr-wrapping_sub]: https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.wrapping_sub [slice-as_mut_ptr]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_mut_ptr [slice-as_mut_ptr_range]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_mut_ptr_range [slice-as_ptr_range]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_ptr_range [target_feature]: https://doc.rust-lang.org/reference/attributes/codegen.html#the-target_feature-attribute Version 1.60.0 (2022-04-07) ========================== Language -------- - [Stabilize `#[cfg(panic = "...")]` for either `"unwind"` or `"abort"`.][93658] - [Stabilize `#[cfg(target_has_atomic = "...")]` for each integer size and `"ptr"`.][93824] Compiler -------- - [Enable combining `+crt-static` and `relocation-model=pic` on `x86_64-unknown-linux-gnu`][86374] - [Fixes wrong `unreachable_pub` lints on nested and glob public reexport][87487] - [Stabilize `-Z instrument-coverage` as `-C instrument-coverage`][90132] - [Stabilize `-Z print-link-args` as `--print link-args`][91606] - [Add new Tier 3 target `mips64-openwrt-linux-musl`\*][92300] - [Add new Tier 3 target `armv7-unknown-linux-uclibceabi` (softfloat)\*][92383] - [Fix invalid removal of newlines from doc comments][92357] - [Add kernel target for RustyHermit][92670] - [Deny mixing bin crate type with lib crate types][92933] - [Make rustc use `RUST_BACKTRACE=full` by default][93566] - [Upgrade to LLVM 14][93577] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [Guarantee call order for `sort_by_cached_key`][89621] - [Improve `Duration::try_from_secs_f32`/`f64` accuracy by directly processing exponent and mantissa][90247] - [Make `Instant::{duration_since, elapsed, sub}` saturating][89926] - [Remove non-monotonic clocks workarounds in `Instant::now`][89926] - [Make `BuildHasherDefault`, `iter::Empty` and `future::Pending` covariant][92630] Stabilized APIs --------------- - [`Arc::new_cyclic`][arc_new_cyclic] - [`Rc::new_cyclic`][rc_new_cyclic] - [`slice::EscapeAscii`][slice_escape_ascii] - [`<[u8]>::escape_ascii`][slice_u8_escape_ascii] - [`u8::escape_ascii`][u8_escape_ascii] - [`Vec::spare_capacity_mut`][vec_spare_capacity_mut] - [`MaybeUninit::assume_init_drop`][assume_init_drop] - [`MaybeUninit::assume_init_read`][assume_init_read] - [`i8::abs_diff`][i8_abs_diff] - [`i16::abs_diff`][i16_abs_diff] - [`i32::abs_diff`][i32_abs_diff] - [`i64::abs_diff`][i64_abs_diff] - [`i128::abs_diff`][i128_abs_diff] - [`isize::abs_diff`][isize_abs_diff] - [`u8::abs_diff`][u8_abs_diff] - [`u16::abs_diff`][u16_abs_diff] - [`u32::abs_diff`][u32_abs_diff] - [`u64::abs_diff`][u64_abs_diff] - [`u128::abs_diff`][u128_abs_diff] - [`usize::abs_diff`][usize_abs_diff] - [`Display for io::ErrorKind`][display_error_kind] - [`From<u8> for ExitCode`][from_u8_exit_code] - [`Not for !` (the "never" type)][not_never] - [_Op_`Assign<$t> for Wrapping<$t>`][wrapping_assign_ops] - [`arch::is_aarch64_feature_detected!`][is_aarch64_feature_detected] Cargo ----- - [Port cargo from `toml-rs` to `toml_edit`][cargo/10086] - [Stabilize `-Ztimings` as `--timings`][cargo/10245] - [Stabilize namespaced and weak dependency features.][cargo/10269] - [Accept more `cargo:rustc-link-arg-*` types from build script output.][cargo/10274] - [cargo-new should not add ignore rule on Cargo.lock inside subdirs][cargo/10379] Misc ---- - [Ship docs on Tier 2 platforms by reusing the closest Tier 1 platform docs][92800] - [Drop rustc-docs from complete profile][93742] - [bootstrap: tidy up flag handling for llvm build][93918] Compatibility Notes ------------------- - [Remove compiler-rt linking hack on Android][83822] - [Mitigations for platforms with non-monotonic clocks have been removed from `Instant::now`][89926]. On platforms that don't provide monotonic clocks, an instant is not guaranteed to be greater than an earlier instant anymore. - [`Instant::{duration_since, elapsed, sub}` do not panic anymore on underflow, saturating to `0` instead][89926]. In the real world the panic happened mostly on platforms with buggy monotonic clock implementations rather than catching programming errors like reversing the start and end times. Such programming errors will now result in `0` rather than a panic. - In a future release we're planning to increase the baseline requirements for the Linux kernel to version 3.2, and for glibc to version 2.17. We'd love your feedback in [PR #95026][95026]. Internal Changes ---------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. - [Switch all libraries to the 2021 edition][92068] [83822]: https://github.com/rust-lang/rust/pull/83822 [86374]: https://github.com/rust-lang/rust/pull/86374 [87487]: https://github.com/rust-lang/rust/pull/87487 [89621]: https://github.com/rust-lang/rust/pull/89621 [89926]: https://github.com/rust-lang/rust/pull/89926 [90132]: https://github.com/rust-lang/rust/pull/90132 [90247]: https://github.com/rust-lang/rust/pull/90247 [91606]: https://github.com/rust-lang/rust/pull/91606 [92068]: https://github.com/rust-lang/rust/pull/92068 [92300]: https://github.com/rust-lang/rust/pull/92300 [92357]: https://github.com/rust-lang/rust/pull/92357 [92383]: https://github.com/rust-lang/rust/pull/92383 [92630]: https://github.com/rust-lang/rust/pull/92630 [92670]: https://github.com/rust-lang/rust/pull/92670 [92800]: https://github.com/rust-lang/rust/pull/92800 [92933]: https://github.com/rust-lang/rust/pull/92933 [93566]: https://github.com/rust-lang/rust/pull/93566 [93577]: https://github.com/rust-lang/rust/pull/93577 [93658]: https://github.com/rust-lang/rust/pull/93658 [93742]: https://github.com/rust-lang/rust/pull/93742 [93824]: https://github.com/rust-lang/rust/pull/93824 [93918]: https://github.com/rust-lang/rust/pull/93918 [95026]: https://github.com/rust-lang/rust/pull/95026 [cargo/10086]: https://github.com/rust-lang/cargo/pull/10086 [cargo/10245]: https://github.com/rust-lang/cargo/pull/10245 [cargo/10269]: https://github.com/rust-lang/cargo/pull/10269 [cargo/10274]: https://github.com/rust-lang/cargo/pull/10274 [cargo/10379]: https://github.com/rust-lang/cargo/pull/10379 [arc_new_cyclic]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#method.new_cyclic [rc_new_cyclic]: https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#method.new_cyclic [slice_escape_ascii]: https://doc.rust-lang.org/stable/std/slice/struct.EscapeAscii.html [slice_u8_escape_ascii]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.escape_ascii [u8_escape_ascii]: https://doc.rust-lang.org/stable/std/primitive.u8.html#method.escape_ascii [vec_spare_capacity_mut]: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.spare_capacity_mut [assume_init_drop]: https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.assume_init_drop [assume_init_read]: https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.assume_init_read [i8_abs_diff]: https://doc.rust-lang.org/stable/std/primitive.i8.html#method.abs_diff [i16_abs_diff]: https://doc.rust-lang.org/stable/std/primitive.i16.html#method.abs_diff [i32_abs_diff]: https://doc.rust-lang.org/stable/std/primitive.i32.html#method.abs_diff [i64_abs_diff]: https://doc.rust-lang.org/stable/std/primitive.i64.html#method.abs_diff [i128_abs_diff]: https://doc.rust-lang.org/stable/std/primitive.i128.html#method.abs_diff [isize_abs_diff]: https://doc.rust-lang.org/stable/std/primitive.isize.html#method.abs_diff [u8_abs_diff]: https://doc.rust-lang.org/stable/std/primitive.u8.html#method.abs_diff [u16_abs_diff]: https://doc.rust-lang.org/stable/std/primitive.u16.html#method.abs_diff [u32_abs_diff]: https://doc.rust-lang.org/stable/std/primitive.u32.html#method.abs_diff [u64_abs_diff]: https://doc.rust-lang.org/stable/std/primitive.u64.html#method.abs_diff [u128_abs_diff]: https://doc.rust-lang.org/stable/std/primitive.u128.html#method.abs_diff [usize_abs_diff]: https://doc.rust-lang.org/stable/std/primitive.usize.html#method.abs_diff [display_error_kind]: https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-Display [from_u8_exit_code]: https://doc.rust-lang.org/stable/std/process/struct.ExitCode.html#impl-From%3Cu8%3E [not_never]: https://doc.rust-lang.org/stable/std/primitive.never.html#impl-Not [wrapping_assign_ops]: https://doc.rust-lang.org/stable/std/num/struct.Wrapping.html#trait-implementations [is_aarch64_feature_detected]: https://doc.rust-lang.org/stable/std/arch/macro.is_aarch64_feature_detected.html Version 1.59.0 (2022-02-24) ========================== Language -------- - [Stabilize default arguments for const parameters and remove the ordering restriction for type and const parameters][90207] - [Stabilize destructuring assignment][90521] - [Relax private in public lint on generic bounds and where clauses of trait impls][90586] - [Stabilize asm! and global_asm! for x86, x86_64, ARM, Aarch64, and RISC-V][91728] Compiler -------- - [Stabilize new symbol mangling format, leaving it opt-in (-Csymbol-mangling-version=v0)][90128] - [Emit LLVM optimization remarks when enabled with `-Cremark`][90833] - [Fix sparc64 ABI for aggregates with floating point members][91003] - [Warn when a `#[test]`-like built-in attribute macro is present multiple times.][91172] - [Add support for riscv64gc-unknown-freebsd][91284] - [Stabilize `-Z emit-future-incompat` as `--json future-incompat`][91535] - [Soft disable incremental compilation][94124] This release disables incremental compilation, unless the user has explicitly opted in via the newly added RUSTC_FORCE_INCREMENTAL=1 environment variable. This is due to a known and relatively frequently occurring bug in incremental compilation, which causes builds to issue internal compiler errors. This particular bug is already fixed on nightly, but that fix has not yet rolled out to stable and is deemed too risky for a direct stable backport. As always, we encourage users to test with nightly and report bugs so that we can track failures and fix issues earlier. See [94124] for more details. [94124]: https://github.com/rust-lang/rust/issues/94124 Libraries --------- - [Remove unnecessary bounds for some Hash{Map,Set} methods][91593] Stabilized APIs --------------- - [`std::thread::available_parallelism`][available_parallelism] - [`Result::copied`][result-copied] - [`Result::cloned`][result-cloned] - [`arch::asm!`][asm] - [`arch::global_asm!`][global_asm] - [`ops::ControlFlow::is_break`][is_break] - [`ops::ControlFlow::is_continue`][is_continue] - [`TryFrom<char> for u8`][try_from_char_u8] - [`char::TryFromCharError`][try_from_char_err] implementing `Clone`, `Debug`, `Display`, `PartialEq`, `Copy`, `Eq`, `Error` - [`iter::zip`][zip] - [`NonZeroU8::is_power_of_two`][is_power_of_two8] - [`NonZeroU16::is_power_of_two`][is_power_of_two16] - [`NonZeroU32::is_power_of_two`][is_power_of_two32] - [`NonZeroU64::is_power_of_two`][is_power_of_two64] - [`NonZeroU128::is_power_of_two`][is_power_of_two128] - [`NonZeroUsize::is_power_of_two`][is_power_of_two_usize] - [`DoubleEndedIterator for ToLowercase`][lowercase] - [`DoubleEndedIterator for ToUppercase`][uppercase] - [`TryFrom<&mut [T]> for [T; N]`][tryfrom_ref_arr] - [`UnwindSafe for Once`][unwindsafe_once] - [`RefUnwindSafe for Once`][refunwindsafe_once] - [armv8 neon intrinsics for aarch64][stdarch/1266] Const-stable: - [`mem::MaybeUninit::as_ptr`][muninit_ptr] - [`mem::MaybeUninit::assume_init`][muninit_init] - [`mem::MaybeUninit::assume_init_ref`][muninit_init_ref] - [`ffi::CStr::from_bytes_with_nul_unchecked`][cstr_from_bytes] Cargo ----- - [Stabilize the `strip` profile option][cargo/10088] - [Stabilize future-incompat-report][cargo/10165] - [Support abbreviating `--release` as `-r`][cargo/10133] - [Support `term.quiet` configuration][cargo/10152] - [Remove `--host` from cargo {publish,search,login}][cargo/10145] Compatibility Notes ------------------- - [Refactor weak symbols in std::sys::unix][90846] This may add new, versioned, symbols when building with a newer glibc, as the standard library uses weak linkage rather than dynamically attempting to load certain symbols at runtime. - [Deprecate crate_type and crate_name nested inside `#![cfg_attr]`][83744] This adds a future compatibility lint to supporting the use of cfg_attr wrapping either crate_type or crate_name specification within Rust files; it is recommended that users migrate to setting the equivalent command line flags. - [Remove effect of `#[no_link]` attribute on name resolution][92034] This may expose new names, leading to conflicts with preexisting names in a given namespace and a compilation failure. - [Cargo will document libraries before binaries.][cargo/10172] - [Respect doc=false in dependencies, not just the root crate][cargo/10201] - [Weaken guarantee around advancing underlying iterators in zip][83791] - [Make split_inclusive() on an empty slice yield an empty output][89825] - [Update std::env::temp_dir to use GetTempPath2 on Windows when available.][89999] - [unreachable! was updated to match other formatting macro behavior on Rust 2021][92137] Internal Changes ---------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. - [Fix many cases of normalization-related ICEs][91255] - [Replace dominators algorithm with simple Lengauer-Tarjan][85013] - [Store liveness in interval sets for region inference][90637] - [Remove `in_band_lifetimes` from the compiler and standard library, in preparation for removing this unstable feature.][91867] [91867]: https://github.com/rust-lang/rust/issues/91867 [83744]: https://github.com/rust-lang/rust/pull/83744/ [83791]: https://github.com/rust-lang/rust/pull/83791/ [85013]: https://github.com/rust-lang/rust/pull/85013/ [89825]: https://github.com/rust-lang/rust/pull/89825/ [89999]: https://github.com/rust-lang/rust/pull/89999/ [90128]: https://github.com/rust-lang/rust/pull/90128/ [90207]: https://github.com/rust-lang/rust/pull/90207/ [90521]: https://github.com/rust-lang/rust/pull/90521/ [90586]: https://github.com/rust-lang/rust/pull/90586/ [90637]: https://github.com/rust-lang/rust/pull/90637/ [90833]: https://github.com/rust-lang/rust/pull/90833/ [90846]: https://github.com/rust-lang/rust/pull/90846/ [91003]: https://github.com/rust-lang/rust/pull/91003/ [91172]: https://github.com/rust-lang/rust/pull/91172/ [91255]: https://github.com/rust-lang/rust/pull/91255/ [91284]: https://github.com/rust-lang/rust/pull/91284/ [91535]: https://github.com/rust-lang/rust/pull/91535/ [91593]: https://github.com/rust-lang/rust/pull/91593/ [91728]: https://github.com/rust-lang/rust/pull/91728/ [91878]: https://github.com/rust-lang/rust/pull/91878/ [91896]: https://github.com/rust-lang/rust/pull/91896/ [91926]: https://github.com/rust-lang/rust/pull/91926/ [91984]: https://github.com/rust-lang/rust/pull/91984/ [92020]: https://github.com/rust-lang/rust/pull/92020/ [92034]: https://github.com/rust-lang/rust/pull/92034/ [92137]: https://github.com/rust-lang/rust/pull/92137/ [92483]: https://github.com/rust-lang/rust/pull/92483/ [cargo/10088]: https://github.com/rust-lang/cargo/pull/10088/ [cargo/10133]: https://github.com/rust-lang/cargo/pull/10133/ [cargo/10145]: https://github.com/rust-lang/cargo/pull/10145/ [cargo/10152]: https://github.com/rust-lang/cargo/pull/10152/ [cargo/10165]: https://github.com/rust-lang/cargo/pull/10165/ [cargo/10172]: https://github.com/rust-lang/cargo/pull/10172/ [cargo/10201]: https://github.com/rust-lang/cargo/pull/10201/ [cargo/10269]: https://github.com/rust-lang/cargo/pull/10269/ [cstr_from_bytes]: https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#method.from_bytes_with_nul_unchecked [muninit_ptr]: https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.as_ptr [muninit_init]: https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.assume_init [muninit_init_ref]: https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.assume_init_ref [unwindsafe_once]: https://doc.rust-lang.org/stable/std/sync/struct.Once.html#impl-UnwindSafe [refunwindsafe_once]: https://doc.rust-lang.org/stable/std/sync/struct.Once.html#impl-RefUnwindSafe [tryfrom_ref_arr]: https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#impl-TryFrom%3C%26%27_%20mut%20%5BT%5D%3E [lowercase]: https://doc.rust-lang.org/stable/std/char/struct.ToLowercase.html#impl-DoubleEndedIterator [uppercase]: https://doc.rust-lang.org/stable/std/char/struct.ToUppercase.html#impl-DoubleEndedIterator [try_from_char_err]: https://doc.rust-lang.org/stable/std/char/struct.TryFromCharError.html [available_parallelism]: https://doc.rust-lang.org/stable/std/thread/fn.available_parallelism.html [result-copied]: https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.copied [result-cloned]: https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.cloned [asm]: https://doc.rust-lang.org/stable/core/arch/macro.asm.html [global_asm]: https://doc.rust-lang.org/stable/core/arch/macro.global_asm.html [is_break]: https://doc.rust-lang.org/stable/std/ops/enum.ControlFlow.html#method.is_break [is_continue]: https://doc.rust-lang.org/stable/std/ops/enum.ControlFlow.html#method.is_continue [try_from_char_u8]: https://doc.rust-lang.org/stable/std/primitive.char.html#impl-TryFrom%3Cchar%3E [zip]: https://doc.rust-lang.org/stable/std/iter/fn.zip.html [is_power_of_two8]: https://doc.rust-lang.org/stable/core/num/struct.NonZeroU8.html#method.is_power_of_two [is_power_of_two16]: https://doc.rust-lang.org/stable/core/num/struct.NonZeroU16.html#method.is_power_of_two [is_power_of_two32]: https://doc.rust-lang.org/stable/core/num/struct.NonZeroU32.html#method.is_power_of_two [is_power_of_two64]: https://doc.rust-lang.org/stable/core/num/struct.NonZeroU64.html#method.is_power_of_two [is_power_of_two128]: https://doc.rust-lang.org/stable/core/num/struct.NonZeroU128.html#method.is_power_of_two [is_power_of_two_usize]: https://doc.rust-lang.org/stable/core/num/struct.NonZeroUsize.html#method.is_power_of_two [stdarch/1266]: https://github.com/rust-lang/stdarch/pull/1266 Version 1.58.1 (2022-01-20) =========================== * Fix race condition in `std::fs::remove_dir_all` ([CVE-2022-21658]) * [Handle captured arguments in the `useless_format` Clippy lint][clippy/8295] * [Move `non_send_fields_in_send_ty` Clippy lint to nursery][clippy/8075] * [Fix wrong error message displayed when some imports are missing][91254] * [Fix rustfmt not formatting generated files from stdin][92912] [CVE-2022-21658]: https://www.cve.org/CVERecord?id=CVE-2022-21658 [91254]: https://github.com/rust-lang/rust/pull/91254 [92912]: https://github.com/rust-lang/rust/pull/92912 [clippy/8075]: https://github.com/rust-lang/rust-clippy/pull/8075 [clippy/8295]: https://github.com/rust-lang/rust-clippy/pull/8295 Version 1.58.0 (2022-01-13) ========================== Language -------- - [Format strings can now capture arguments simply by writing `{ident}` in the string.][90473] This works in all macros accepting format strings. Support for this in `panic!` (`panic!("{ident}")`) requires the 2021 edition; panic invocations in previous editions that appear to be trying to use this will result in a warning lint about not having the intended effect. - [`*const T` pointers can now be dereferenced in const contexts.][89551] - [The rules for when a generic struct implements `Unsize` have been relaxed.][90417] Compiler -------- - [Add LLVM CFI support to the Rust compiler][89652] - [Stabilize -Z strip as -C strip][90058]. Note that while release builds already don't add debug symbols for the code you compile, the compiled standard library that ships with Rust includes debug symbols, so you may want to use the `strip` option to remove these symbols to produce smaller release binaries. Note that this release only includes support in rustc, not directly in cargo. - [Add support for LLVM coverage mapping format versions 5 and 6][91207] - [Emit LLVM optimization remarks when enabled with `-Cremark`][90833] - [Update the minimum external LLVM to 12][90175] - [Add `x86_64-unknown-none` at Tier 3*][89062] - [Build musl dist artifacts with debuginfo enabled][90733]. When building release binaries using musl, you may want to use the newly stabilized strip option to remove these debug symbols, reducing the size of your binaries. - [Don't abort compilation after giving a lint error][87337] - [Error messages point at the source of trait bound obligations in more places][89580] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [All remaining functions in the standard library have `#[must_use]` annotations where appropriate][89692], producing a warning when ignoring their return value. This helps catch mistakes such as expecting a function to mutate a value in place rather than return a new value. - [Paths are automatically canonicalized on Windows for operations that support it][89174] - [Re-enable debug checks for `copy` and `copy_nonoverlapping`][90041] - [Implement `RefUnwindSafe` for `Rc<T>`][87467] - [Make RSplit<T, P>: Clone not require T: Clone][90117] - [Implement `Termination` for `Result<Infallible, E>`][88601]. This allows writing `fn main() -> Result<Infallible, ErrorType>`, for a program whose successful exits never involve returning from `main` (for instance, a program that calls `exit`, or that uses `exec` to run another program). Stabilized APIs --------------- - [`Metadata::is_symlink`] - [`Path::is_symlink`] - [`{integer}::saturating_div`] - [`Option::unwrap_unchecked`] - [`Result::unwrap_unchecked`] - [`Result::unwrap_err_unchecked`] - [`File::options`] These APIs are now usable in const contexts: - [`Duration::new`] - [`Duration::checked_add`] - [`Duration::saturating_add`] - [`Duration::checked_sub`] - [`Duration::saturating_sub`] - [`Duration::checked_mul`] - [`Duration::saturating_mul`] - [`Duration::checked_div`] Cargo ----- - [Add --message-format for install command][cargo/10107] - [Warn when alias shadows external subcommand][cargo/10082] Rustdoc ------- - [Show all Deref implementations recursively in rustdoc][90183] - [Use computed visibility in rustdoc][88447] Compatibility Notes ------------------- - [Try all stable method candidates first before trying unstable ones][90329]. This change ensures that adding new nightly-only methods to the Rust standard library will not break code invoking methods of the same name from traits outside the standard library. - Windows: [`std::process::Command` will no longer search the current directory for executables.][87704] - [All proc-macro backward-compatibility lints are now deny-by-default.][88041] - [proc_macro: Append .0 to unsuffixed float if it would otherwise become int token][90297] - [Refactor weak symbols in std::sys::unix][90846]. This optimizes accesses to glibc functions, by avoiding the use of dlopen. This does not increase the [minimum expected version of glibc](https://doc.rust-lang.org/nightly/rustc/platform-support.html). However, software distributions that use symbol versions to detect library dependencies, and which take weak symbols into account in that analysis, may detect rust binaries as requiring newer versions of glibc. - [rustdoc now rejects some unexpected semicolons in doctests][91026] Internal Changes ---------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. - [Implement coherence checks for negative trait impls][90104] - [Add rustc lint, warning when iterating over hashmaps][89558] - [Optimize live point computation][90491] - [Enable verification for 1/32nd of queries loaded from disk][90361] - [Implement version of normalize_erasing_regions that allows for normalization failure][91255] [87337]: https://github.com/rust-lang/rust/pull/87337/ [87467]: https://github.com/rust-lang/rust/pull/87467/ [87704]: https://github.com/rust-lang/rust/pull/87704/ [88041]: https://github.com/rust-lang/rust/pull/88041/ [88447]: https://github.com/rust-lang/rust/pull/88447/ [88601]: https://github.com/rust-lang/rust/pull/88601/ [89062]: https://github.com/rust-lang/rust/pull/89062/ [89174]: https://github.com/rust-lang/rust/pull/89174/ [89551]: https://github.com/rust-lang/rust/pull/89551/ [89558]: https://github.com/rust-lang/rust/pull/89558/ [89580]: https://github.com/rust-lang/rust/pull/89580/ [89652]: https://github.com/rust-lang/rust/pull/89652/ [90041]: https://github.com/rust-lang/rust/pull/90041/ [90058]: https://github.com/rust-lang/rust/pull/90058/ [90104]: https://github.com/rust-lang/rust/pull/90104/ [90117]: https://github.com/rust-lang/rust/pull/90117/ [90175]: https://github.com/rust-lang/rust/pull/90175/ [90183]: https://github.com/rust-lang/rust/pull/90183/ [90297]: https://github.com/rust-lang/rust/pull/90297/ [90329]: https://github.com/rust-lang/rust/pull/90329/ [90361]: https://github.com/rust-lang/rust/pull/90361/ [90417]: https://github.com/rust-lang/rust/pull/90417/ [90473]: https://github.com/rust-lang/rust/pull/90473/ [90491]: https://github.com/rust-lang/rust/pull/90491/ [90733]: https://github.com/rust-lang/rust/pull/90733/ [90833]: https://github.com/rust-lang/rust/pull/90833/ [90846]: https://github.com/rust-lang/rust/pull/90846/ [91026]: https://github.com/rust-lang/rust/pull/91026/ [91207]: https://github.com/rust-lang/rust/pull/91207/ [91255]: https://github.com/rust-lang/rust/pull/91255/ [cargo/10082]: https://github.com/rust-lang/cargo/pull/10082/ [cargo/10107]: https://github.com/rust-lang/cargo/pull/10107/ [`Metadata::is_symlink`]: https://doc.rust-lang.org/stable/std/fs/struct.Metadata.html#method.is_symlink [`Path::is_symlink`]: https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.is_symlink [`{integer}::saturating_div`]: https://doc.rust-lang.org/stable/std/primitive.i8.html#method.saturating_div [`Option::unwrap_unchecked`]: https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.unwrap_unchecked [`Result::unwrap_unchecked`]: https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap_unchecked [`Result::unwrap_err_unchecked`]: https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap_err_unchecked [`File::options`]: https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.options [`Duration::new`]: https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.new Version 1.57.0 (2021-12-02) ========================== Language -------- - [Macro attributes may follow `#[derive]` and will see the original (pre-`cfg`) input.][87220] - [Accept curly-brace macros in expressions, like `m!{ .. }.method()` and `m!{ .. }?`.][88690] - [Allow panicking in constant evaluation.][89508] - [Ignore derived `Clone` and `Debug` implementations during dead code analysis.][85200] Compiler -------- - [Create more accurate debuginfo for vtables.][89597] - [Add `armv6k-nintendo-3ds` at Tier 3\*.][88529] - [Add `armv7-unknown-linux-uclibceabihf` at Tier 3\*.][88952] - [Add `m68k-unknown-linux-gnu` at Tier 3\*.][88321] - [Add SOLID targets at Tier 3\*:][86191] `aarch64-kmc-solid_asp3`, `armv7a-kmc-solid_asp3-eabi`, `armv7a-kmc-solid_asp3-eabihf` \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [Avoid allocations and copying in `Vec::leak`][89337] - [Add `#[repr(i8)]` to `Ordering`][89507] - [Optimize `File::read_to_end` and `read_to_string`][89582] - [Update to Unicode 14.0][89614] - [Many more functions are marked `#[must_use]`][89692], producing a warning when ignoring their return value. This helps catch mistakes such as expecting a function to mutate a value in place rather than return a new value. Stabilised APIs --------------- - [`[T; N]::as_mut_slice`][`array::as_mut_slice`] - [`[T; N]::as_slice`][`array::as_slice`] - [`collections::TryReserveError`] - [`HashMap::try_reserve`] - [`HashSet::try_reserve`] - [`String::try_reserve`] - [`String::try_reserve_exact`] - [`Vec::try_reserve`] - [`Vec::try_reserve_exact`] - [`VecDeque::try_reserve`] - [`VecDeque::try_reserve_exact`] - [`Iterator::map_while`] - [`iter::MapWhile`] - [`proc_macro::is_available`] - [`Command::get_program`] - [`Command::get_args`] - [`Command::get_envs`] - [`Command::get_current_dir`] - [`CommandArgs`] - [`CommandEnvs`] These APIs are now usable in const contexts: - [`hint::unreachable_unchecked`] Cargo ----- - [Stabilize custom profiles][cargo/9943] Compatibility notes ------------------- - [Ignore derived `Clone` and `Debug` implementations during dead code analysis.][85200] This will break some builds that set `#![deny(dead_code)]`. Internal changes ---------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. - [Added an experimental backend for codegen with `libgccjit`.][87260] [85200]: https://github.com/rust-lang/rust/pull/85200/ [86191]: https://github.com/rust-lang/rust/pull/86191/ [87220]: https://github.com/rust-lang/rust/pull/87220/ [87260]: https://github.com/rust-lang/rust/pull/87260/ [88321]: https://github.com/rust-lang/rust/pull/88321/ [88529]: https://github.com/rust-lang/rust/pull/88529/ [88690]: https://github.com/rust-lang/rust/pull/88690/ [88952]: https://github.com/rust-lang/rust/pull/88952/ [89337]: https://github.com/rust-lang/rust/pull/89337/ [89507]: https://github.com/rust-lang/rust/pull/89507/ [89508]: https://github.com/rust-lang/rust/pull/89508/ [89582]: https://github.com/rust-lang/rust/pull/89582/ [89597]: https://github.com/rust-lang/rust/pull/89597/ [89614]: https://github.com/rust-lang/rust/pull/89614/ [89692]: https://github.com/rust-lang/rust/issues/89692/ [cargo/9943]: https://github.com/rust-lang/cargo/pull/9943/ [`array::as_mut_slice`]: https://doc.rust-lang.org/std/primitive.array.html#method.as_mut_slice [`array::as_slice`]: https://doc.rust-lang.org/std/primitive.array.html#method.as_slice [`collections::TryReserveError`]: https://doc.rust-lang.org/std/collections/struct.TryReserveError.html [`HashMap::try_reserve`]: https://doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#method.try_reserve [`HashSet::try_reserve`]: https://doc.rust-lang.org/std/collections/hash_set/struct.HashSet.html#method.try_reserve [`String::try_reserve`]: https://doc.rust-lang.org/alloc/string/struct.String.html#method.try_reserve [`String::try_reserve_exact`]: https://doc.rust-lang.org/alloc/string/struct.String.html#method.try_reserve_exact [`Vec::try_reserve`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.try_reserve [`Vec::try_reserve_exact`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.try_reserve_exact [`VecDeque::try_reserve`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.try_reserve [`VecDeque::try_reserve_exact`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.try_reserve_exact [`Iterator::map_while`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map_while [`iter::MapWhile`]: https://doc.rust-lang.org/std/iter/struct.MapWhile.html [`proc_macro::is_available`]: https://doc.rust-lang.org/proc_macro/fn.is_available.html [`Command::get_program`]: https://doc.rust-lang.org/std/process/struct.Command.html#method.get_program [`Command::get_args`]: https://doc.rust-lang.org/std/process/struct.Command.html#method.get_args [`Command::get_envs`]: https://doc.rust-lang.org/std/process/struct.Command.html#method.get_envs [`Command::get_current_dir`]: https://doc.rust-lang.org/std/process/struct.Command.html#method.get_current_dir [`CommandArgs`]: https://doc.rust-lang.org/std/process/struct.CommandArgs.html [`CommandEnvs`]: https://doc.rust-lang.org/std/process/struct.CommandEnvs.html Version 1.56.1 (2021-11-01) =========================== - New lints to detect the presence of bidirectional-override Unicode codepoints in the compiled source code ([CVE-2021-42574]) [CVE-2021-42574]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-42574 Version 1.56.0 (2021-10-21) ======================== Language -------- - [The 2021 Edition is now stable.][rust#88100] See [the edition guide][rust-2021-edition-guide] for more details. - [The pattern in `binding @ pattern` can now also introduce new bindings.][rust#85305] - [Union field access is permitted in `const fn`.][rust#85769] [rust-2021-edition-guide]: https://doc.rust-lang.org/nightly/edition-guide/rust-2021/index.html Compiler -------- - [Upgrade to LLVM 13.][rust#87570] - [Support memory, address, and thread sanitizers on aarch64-unknown-freebsd.][rust#88023] - [Allow specifying a deployment target version for all iOS targets][rust#87699] - [Warnings can be forced on with `--force-warn`.][rust#87472] This feature is primarily intended for usage by `cargo fix`, rather than end users. - [Promote `aarch64-apple-ios-sim` to Tier 2\*.][rust#87760] - [Add `powerpc-unknown-freebsd` at Tier 3\*.][rust#87370] - [Add `riscv32imc-esp-espidf` at Tier 3\*.][rust#87666] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [Allow writing of incomplete UTF-8 sequences via stdout/stderr on Windows.][rust#83342] The Windows console still requires valid Unicode, but this change allows splitting a UTF-8 character across multiple write calls. This allows, for instance, programs that just read and write data buffers (e.g. copying a file to stdout) without regard for Unicode or character boundaries. - [Prefer `AtomicU{64,128}` over Mutex for Instant backsliding protection.][rust#83093] For this use case, atomics scale much better under contention. - [Implement `Extend<(A, B)>` for `(Extend<A>, Extend<B>)`][rust#85835] - [impl Default, Copy, Clone for std::io::Sink and std::io::Empty][rust#86744] - [`impl From<[(K, V); N]>` for all collections.][rust#84111] - [Remove `P: Unpin` bound on impl Future for Pin.][rust#81363] - [Treat invalid environment variable names as nonexistent.][rust#86183] Previously, the environment functions would panic if given a variable name with an internal null character or equal sign (`=`). Now, these functions will just treat such names as nonexistent variables, since the OS cannot represent the existence of a variable with such a name. Stabilised APIs --------------- - [`std::os::unix::fs::chroot`] - [`UnsafeCell::raw_get`] - [`BufWriter::into_parts`] - [`core::panic::{UnwindSafe, RefUnwindSafe, AssertUnwindSafe}`] These APIs were previously stable in `std`, but are now also available in `core`. - [`Vec::shrink_to`] - [`String::shrink_to`] - [`OsString::shrink_to`] - [`PathBuf::shrink_to`] - [`BinaryHeap::shrink_to`] - [`VecDeque::shrink_to`] - [`HashMap::shrink_to`] - [`HashSet::shrink_to`] These APIs are now usable in const contexts: - [`std::mem::transmute`] - [`[T]::first`][`slice::first`] - [`[T]::split_first`][`slice::split_first`] - [`[T]::last`][`slice::last`] - [`[T]::split_last`][`slice::split_last`] Cargo ----- - [Cargo supports specifying a minimum supported Rust version in Cargo.toml.][`rust-version`] This has no effect at present on dependency version selection. We encourage crates to specify their minimum supported Rust version, and we encourage CI systems that support Rust code to include a crate's specified minimum version in the test matrix for that crate by default. Compatibility notes ------------------- - [Update to new argument parsing rules on Windows.][rust#87580] This adjusts Rust's standard library to match the behavior of the standard libraries for C/C++. The rules have changed slightly over time, and this PR brings us to the latest set of rules (changed in 2008). - [Disallow the aapcs calling convention on aarch64][rust#88399] This was already not supported by LLVM; this change surfaces this lack of support with a better error message. - [Make `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` warn by default][rust#87385] - [Warn when an escaped newline skips multiple lines.][rust#87671] - [Calls to `libc::getpid` / `std::process::id` from `Command::pre_exec` may return different values on glibc <= 2.24.][rust#81825] Rust now invokes the `clone3` system call directly, when available, to use new functionality available via that system call. Older versions of glibc cache the result of `getpid`, and only update that cache when calling glibc's clone/fork functions, so a direct system call bypasses that cache update. glibc 2.25 and newer no longer cache `getpid` for exactly this reason. Internal changes ---------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. - [LLVM is compiled with PGO in published x86_64-unknown-linux-gnu artifacts.][rust#88069] This improves the performance of most Rust builds. - [Unify representation of macros in internal data structures.][rust#88019] This change fixes a host of bugs with the handling of macros by the compiler, as well as rustdoc. [`std::os::unix::fs::chroot`]: https://doc.rust-lang.org/stable/std/os/unix/fs/fn.chroot.html [`UnsafeCell::raw_get`]: https://doc.rust-lang.org/stable/std/cell/struct.UnsafeCell.html#method.raw_get [`BufWriter::into_parts`]: https://doc.rust-lang.org/stable/std/io/struct.BufWriter.html#method.into_parts [`core::panic::{UnwindSafe, RefUnwindSafe, AssertUnwindSafe}`]: https://github.com/rust-lang/rust/pull/84662 [`Vec::shrink_to`]: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.shrink_to [`String::shrink_to`]: https://doc.rust-lang.org/stable/std/string/struct.String.html#method.shrink_to [`OsString::shrink_to`]: https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.shrink_to [`PathBuf::shrink_to`]: https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.shrink_to [`BinaryHeap::shrink_to`]: https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.shrink_to [`VecDeque::shrink_to`]: https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html#method.shrink_to [`HashMap::shrink_to`]: https://doc.rust-lang.org/stable/std/collections/hash_map/struct.HashMap.html#method.shrink_to [`HashSet::shrink_to`]: https://doc.rust-lang.org/stable/std/collections/hash_set/struct.HashSet.html#method.shrink_to [`std::mem::transmute`]: https://doc.rust-lang.org/stable/std/mem/fn.transmute.html [`slice::first`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.first [`slice::split_first`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_first [`slice::last`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.last [`slice::split_last`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_last [`rust-version`]: https://doc.rust-lang.org/nightly/cargo/reference/manifest.html#the-rust-version-field [rust#87671]: https://github.com/rust-lang/rust/pull/87671 [rust#86183]: https://github.com/rust-lang/rust/pull/86183 [rust#87385]: https://github.com/rust-lang/rust/pull/87385 [rust#88100]: https://github.com/rust-lang/rust/pull/88100 [rust#85305]: https://github.com/rust-lang/rust/pull/85305 [rust#88069]: https://github.com/rust-lang/rust/pull/88069 [rust#87472]: https://github.com/rust-lang/rust/pull/87472 [rust#87699]: https://github.com/rust-lang/rust/pull/87699 [rust#87570]: https://github.com/rust-lang/rust/pull/87570 [rust#88023]: https://github.com/rust-lang/rust/pull/88023 [rust#87760]: https://github.com/rust-lang/rust/pull/87760 [rust#87370]: https://github.com/rust-lang/rust/pull/87370 [rust#87580]: https://github.com/rust-lang/rust/pull/87580 [rust#83342]: https://github.com/rust-lang/rust/pull/83342 [rust#83093]: https://github.com/rust-lang/rust/pull/83093 [rust#85835]: https://github.com/rust-lang/rust/pull/85835 [rust#86744]: https://github.com/rust-lang/rust/pull/86744 [rust#81363]: https://github.com/rust-lang/rust/pull/81363 [rust#84111]: https://github.com/rust-lang/rust/pull/84111 [rust#85769]: https://github.com/rust-lang/rust/pull/85769#issuecomment-854363720 [rust#88399]: https://github.com/rust-lang/rust/pull/88399 [rust#81825]: https://github.com/rust-lang/rust/pull/81825#issuecomment-808406918 [rust#88019]: https://github.com/rust-lang/rust/pull/88019 [rust#87666]: https://github.com/rust-lang/rust/pull/87666 Version 1.55.0 (2021-09-09) ============================ Language -------- - [You can now write open "from" range patterns (`X..`), which will start at `X` and will end at the maximum value of the integer.][83918] - [You can now explicitly import the prelude of different editions through `std::prelude` (e.g. `use std::prelude::rust_2021::*;`).][86294] Compiler -------- - [Added tier 3\* support for `powerpc64le-unknown-freebsd`.][83572] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [Updated std's float parsing to use the Eisel-Lemire algorithm.][86761] These improvements should in general provide faster string parsing of floats, no longer reject certain valid floating point values, and reduce the produced code size for non-stripped artifacts. - [`string::Drain` now implements `AsRef<str>` and `AsRef<[u8]>`.][86858] Stabilised APIs --------------- - [`Bound::cloned`] - [`Drain::as_str`] - [`IntoInnerError::into_error`] - [`IntoInnerError::into_parts`] - [`MaybeUninit::assume_init_mut`] - [`MaybeUninit::assume_init_ref`] - [`MaybeUninit::write`] - [`array::map`] - [`ops::ControlFlow`] - [`x86::_bittest`] - [`x86::_bittestandcomplement`] - [`x86::_bittestandreset`] - [`x86::_bittestandset`] - [`x86_64::_bittest64`] - [`x86_64::_bittestandcomplement64`] - [`x86_64::_bittestandreset64`] - [`x86_64::_bittestandset64`] The following previously stable functions are now `const`. - [`str::from_utf8_unchecked`] Cargo ----- - [Cargo will now deduplicate compiler diagnostics to the terminal when invoking rustc in parallel such as when using `cargo test`.][cargo/9675] - [The package definition in `cargo metadata` now includes the `"default_run"` field from the manifest.][cargo/9550] - [Added `cargo d` as an alias for `cargo doc`.][cargo/9680] - [Added `{lib}` as formatting option for `cargo tree` to print the `"lib_name"` of packages.][cargo/9663] Rustdoc ------- - [Added "Go to item on exact match" search option.][85876] - [The "Implementors" section on traits no longer shows redundant method definitions.][85970] - [Trait implementations are toggled open by default.][86260] This should make the implementations more searchable by tools like `CTRL+F` in your browser. - [Intra-doc links should now correctly resolve associated items (e.g. methods) through type aliases.][86334] - [Traits which are marked with `#[doc(hidden)]` will no longer appear in the "Trait Implementations" section.][86513] Compatibility Notes ------------------- - [std functions that return an `io::Error` will no longer use the `ErrorKind::Other` variant.][85746] This is to better reflect that these kinds of errors could be categorised [into newer more specific `ErrorKind` variants][79965], and that they do not represent a user error. - [Using environment variable names with `process::Command` on Windows now behaves as expected.][85270] Previously using environment variables with `Command` would cause them to be ASCII-uppercased. - [Rustdoc will now warn on using rustdoc lints that aren't prefixed with `rustdoc::`][86849] - `RUSTFLAGS` is no longer set for build scripts. Build scripts should use `CARGO_ENCODED_RUSTFLAGS` instead. See the [documentation](https://doc.rust-lang.org/nightly/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts) for more details. [86849]: https://github.com/rust-lang/rust/pull/86849 [86513]: https://github.com/rust-lang/rust/pull/86513 [86334]: https://github.com/rust-lang/rust/pull/86334 [86260]: https://github.com/rust-lang/rust/pull/86260 [85970]: https://github.com/rust-lang/rust/pull/85970 [85876]: https://github.com/rust-lang/rust/pull/85876 [83572]: https://github.com/rust-lang/rust/pull/83572 [86294]: https://github.com/rust-lang/rust/pull/86294 [86858]: https://github.com/rust-lang/rust/pull/86858 [86761]: https://github.com/rust-lang/rust/pull/86761 [85746]: https://github.com/rust-lang/rust/pull/85746 [85270]: https://github.com/rust-lang/rust/pull/85270 [83918]: https://github.com/rust-lang/rust/pull/83918 [79965]: https://github.com/rust-lang/rust/pull/79965 [cargo/9663]: https://github.com/rust-lang/cargo/pull/9663 [cargo/9675]: https://github.com/rust-lang/cargo/pull/9675 [cargo/9550]: https://github.com/rust-lang/cargo/pull/9550 [cargo/9680]: https://github.com/rust-lang/cargo/pull/9680 [`array::map`]: https://doc.rust-lang.org/stable/std/primitive.array.html#method.map [`Bound::cloned`]: https://doc.rust-lang.org/stable/std/ops/enum.Bound.html#method.cloned [`Drain::as_str`]: https://doc.rust-lang.org/stable/std/string/struct.Drain.html#method.as_str [`IntoInnerError::into_error`]: https://doc.rust-lang.org/stable/std/io/struct.IntoInnerError.html#method.into_error [`IntoInnerError::into_parts`]: https://doc.rust-lang.org/stable/std/io/struct.IntoInnerError.html#method.into_parts [`MaybeUninit::assume_init_mut`]: https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.assume_init_mut [`MaybeUninit::assume_init_ref`]: https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.assume_init_ref [`MaybeUninit::write`]: https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.write [`ops::ControlFlow`]: https://doc.rust-lang.org/stable/std/ops/enum.ControlFlow.html [`str::from_utf8_unchecked`]: https://doc.rust-lang.org/stable/std/str/fn.from_utf8_unchecked.html [`x86::_bittest`]: https://doc.rust-lang.org/stable/core/arch/x86/fn._bittest.html [`x86::_bittestandcomplement`]: https://doc.rust-lang.org/stable/core/arch/x86/fn._bittestandcomplement.html [`x86::_bittestandreset`]: https://doc.rust-lang.org/stable/core/arch/x86/fn._bittestandreset.html [`x86::_bittestandset`]: https://doc.rust-lang.org/stable/core/arch/x86/fn._bittestandset.html [`x86_64::_bittest64`]: https://doc.rust-lang.org/stable/core/arch/x86_64/fn._bittest64.html [`x86_64::_bittestandcomplement64`]: https://doc.rust-lang.org/stable/core/arch/x86_64/fn._bittestandcomplement64.html [`x86_64::_bittestandreset64`]: https://doc.rust-lang.org/stable/core/arch/x86_64/fn._bittestandreset64.html [`x86_64::_bittestandset64`]: https://doc.rust-lang.org/stable/core/arch/x86_64/fn._bittestandset64.html Version 1.54.0 (2021-07-29) ============================ Language ----------------------- - [You can now use macros for values in some built-in attributes.][83366] This primarily allows you to call macros within the `#[doc]` attribute. For example, to include external documentation in your crate, you can now write the following: ```rust #![doc = include_str!("README.md")] ``` - [You can now cast between unsized slice types (and types which contain unsized slices) in `const fn`.][85078] - [You can now use multiple generic lifetimes with `impl Trait` where the lifetimes don't explicitly outlive another.][84701] In code this means that you can now have `impl Trait<'a, 'b>` where as before you could only have `impl Trait<'a, 'b> where 'b: 'a`. Compiler ----------------------- - [Rustc will now search for custom JSON targets in `/lib/rustlib/<target-triple>/target.json` where `/` is the "sysroot" directory.][83800] You can find your sysroot directory by running `rustc --print sysroot`. - [Added `wasm` as a `target_family` for WebAssembly platforms.][84072] - [You can now use `#[target_feature]` on safe functions when targeting WebAssembly platforms.][84988] - [Improved debugger output for enums on Windows MSVC platforms.][85292] - [Added tier 3\* support for `bpfel-unknown-none` and `bpfeb-unknown-none`.][79608] - [`-Zmutable-noalias=yes`][82834] is enabled by default when using LLVM 12 or above. \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries ----------------------- - [`panic::panic_any` will now `#[track_caller]`.][85745] - [Added `OutOfMemory` as a variant of `io::ErrorKind`.][84744] - [ `proc_macro::Literal` now implements `FromStr`.][84717] - [The implementations of vendor intrinsics in core::arch have been significantly refactored.][83278] The main user-visible changes are a 50% reduction in the size of libcore.rlib and stricter validation of constant operands passed to intrinsics. The latter is technically a breaking change, but allows Rust to more closely match the C vendor intrinsics API. Stabilized APIs --------------- - [`BTreeMap::into_keys`] - [`BTreeMap::into_values`] - [`HashMap::into_keys`] - [`HashMap::into_values`] - [`arch::wasm32`] - [`VecDeque::binary_search`] - [`VecDeque::binary_search_by`] - [`VecDeque::binary_search_by_key`] - [`VecDeque::partition_point`] Cargo ----- - [Added the `--prune <spec>` option to `cargo-tree` to remove a package from the dependency graph.][cargo/9520] - [Added the `--depth` option to `cargo-tree` to print only to a certain depth in the tree ][cargo/9499] - [Added the `no-proc-macro` value to `cargo-tree --edges` to hide procedural macro dependencies.][cargo/9488] - [A new environment variable named `CARGO_TARGET_TMPDIR` is available.][cargo/9375] This variable points to a directory that integration tests and benches can use as a "scratchpad" for testing filesystem operations. Compatibility Notes ------------------- - [Mixing Option and Result via `?` is no longer permitted in closures for inferred types.][86831] - [Previously unsound code is no longer permitted where different constructors in branches could require different lifetimes.][85574] - As previously mentioned the [`std::arch` intrinsics now uses stricter const checking][83278] than before and may reject some previously accepted code. - [`i128` multiplication on Cortex M0+ platforms currently unconditionally causes overflow when compiled with `codegen-units = 1`.][86063] [85574]: https://github.com/rust-lang/rust/issues/85574 [86831]: https://github.com/rust-lang/rust/issues/86831 [86063]: https://github.com/rust-lang/rust/issues/86063 [79608]: https://github.com/rust-lang/rust/pull/79608 [84988]: https://github.com/rust-lang/rust/pull/84988 [84701]: https://github.com/rust-lang/rust/pull/84701 [84072]: https://github.com/rust-lang/rust/pull/84072 [85745]: https://github.com/rust-lang/rust/pull/85745 [84744]: https://github.com/rust-lang/rust/pull/84744 [85078]: https://github.com/rust-lang/rust/pull/85078 [84717]: https://github.com/rust-lang/rust/pull/84717 [83800]: https://github.com/rust-lang/rust/pull/83800 [83366]: https://github.com/rust-lang/rust/pull/83366 [83278]: https://github.com/rust-lang/rust/pull/83278 [85292]: https://github.com/rust-lang/rust/pull/85292 [82834]: https://github.com/rust-lang/rust/pull/82834 [cargo/9520]: https://github.com/rust-lang/cargo/pull/9520 [cargo/9499]: https://github.com/rust-lang/cargo/pull/9499 [cargo/9488]: https://github.com/rust-lang/cargo/pull/9488 [cargo/9375]: https://github.com/rust-lang/cargo/pull/9375 [`BTreeMap::into_keys`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.into_keys [`BTreeMap::into_values`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.into_values [`HashMap::into_keys`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.into_keys [`HashMap::into_values`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.into_values [`arch::wasm32`]: https://doc.rust-lang.org/core/arch/wasm32/index.html [`VecDeque::binary_search`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.binary_search [`VecDeque::binary_search_by`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.binary_search_by [`VecDeque::binary_search_by_key`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.binary_search_by_key [`VecDeque::partition_point`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.partition_point Version 1.53.0 (2021-06-17) ============================ Language ----------------------- - [You can now use unicode for identifiers.][83799] This allows multilingual identifiers but still doesn't allow glyphs that are not considered characters such as `◆` or `🦀`. More specifically you can now use any identifier that matches the UAX #31 "Unicode Identifier and Pattern Syntax" standard. This is the same standard as languages like Python, however Rust uses NFC normalization which may be different from other languages. - [You can now specify "or patterns" inside pattern matches.][79278] Previously you could only use `|` (OR) on complete patterns. E.g. ```rust let x = Some(2u8); // Before matches!(x, Some(1) | Some(2)); // Now matches!(x, Some(1 | 2)); ``` - [Added the `:pat_param` `macro_rules!` matcher.][83386] This matcher has the same semantics as the `:pat` matcher. This is to allow `:pat` to change semantics to being a pattern fragment in a future edition. Compiler ----------------------- - [Updated the minimum external LLVM version to LLVM 10.][83387] - [Added Tier 3\* support for the `wasm64-unknown-unknown` target.][80525] - [Improved debuginfo for closures and async functions on Windows MSVC.][83941] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries ----------------------- - [Abort messages will now forward to `android_set_abort_message` on Android platforms when available.][81469] - [`slice::IterMut<'_, T>` now implements `AsRef<[T]>`][82771] - [Arrays of any length now implement `IntoIterator`.][84147] Currently calling `.into_iter()` as a method on an array will return `impl Iterator<Item=&T>`, but this may change in a future edition to change `Item` to `T`. Calling `IntoIterator::into_iter` directly on arrays will provide `impl Iterator<Item=T>` as expected. - [`leading_zeros`, and `trailing_zeros` are now available on all `NonZero` integer types.][84082] - [`{f32, f64}::from_str` now parse and print special values (`NaN`, `-0`) according to IEEE 754.][78618] - [You can now index into slices using `(Bound<usize>, Bound<usize>)`.][77704] - [Add the `BITS` associated constant to all numeric types.][82565] Stabilised APIs --------------- - [`AtomicBool::fetch_update`] - [`AtomicPtr::fetch_update`] - [`BTreeMap::retain`] - [`BTreeSet::retain`] - [`BufReader::seek_relative`] - [`DebugStruct::non_exhaustive`] - [`Duration::MAX`] - [`Duration::ZERO`] - [`Duration::is_zero`] - [`Duration::saturating_add`] - [`Duration::saturating_mul`] - [`Duration::saturating_sub`] - [`ErrorKind::Unsupported`] - [`Option::insert`] - [`Ordering::is_eq`] - [`Ordering::is_ge`] - [`Ordering::is_gt`] - [`Ordering::is_le`] - [`Ordering::is_lt`] - [`Ordering::is_ne`] - [`OsStr::is_ascii`] - [`OsStr::make_ascii_lowercase`] - [`OsStr::make_ascii_uppercase`] - [`OsStr::to_ascii_lowercase`] - [`OsStr::to_ascii_uppercase`] - [`Peekable::peek_mut`] - [`Rc::decrement_strong_count`] - [`Rc::increment_strong_count`] - [`Vec::extend_from_within`] - [`array::from_mut`] - [`array::from_ref`] - [`cmp::max_by_key`] - [`cmp::max_by`] - [`cmp::min_by_key`] - [`cmp::min_by`] - [`f32::is_subnormal`] - [`f64::is_subnormal`] Cargo ----------------------- - [Cargo now supports git repositories where the default `HEAD` branch is not "master".][cargo/9392] This also includes a switch to the version 3 `Cargo.lock` format which can handle default branches correctly. - [macOS targets now default to `unpacked` split-debuginfo.][cargo/9298] - [The `authors` field is no longer included in `Cargo.toml` for new projects.][cargo/9282] Rustdoc ----------------------- - [Added the `rustdoc::bare_urls` lint that warns when you have URLs without hyperlinks.][81764] Compatibility Notes ------------------- - [Implement token-based handling of attributes during expansion][82608] - [`Ipv4::from_str` will now reject octal format IP addresses in addition to rejecting hexadecimal IP addresses.][83652] The octal format can lead to confusion and potential security vulnerabilities and [is no longer recommended][ietf6943]. - [The added `BITS` constant may conflict with external definitions.][85667] In particular, this was known to be a problem in the `lexical-core` crate, but they have published fixes for semantic versions 0.4 through 0.7. To update this dependency alone, use `cargo update -p lexical-core`. - Incremental compilation remains off by default, unless one uses the `RUSTC_FORCE_INCREMENTAL=1` environment variable added in 1.52.1. Internal Only ------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. - [Rework the `std::sys::windows::alloc` implementation.][83065] - [rustdoc: Don't enter an infer_ctxt in get_blanket_impls for impls that aren't blanket impls.][82864] - [rustdoc: Only look at blanket impls in `get_blanket_impls`][83681] - [Rework rustdoc const type][82873] [85667]: https://github.com/rust-lang/rust/pull/85667 [83386]: https://github.com/rust-lang/rust/pull/83386 [82771]: https://github.com/rust-lang/rust/pull/82771 [84147]: https://github.com/rust-lang/rust/pull/84147 [84082]: https://github.com/rust-lang/rust/pull/84082 [83799]: https://github.com/rust-lang/rust/pull/83799 [83681]: https://github.com/rust-lang/rust/pull/83681 [83652]: https://github.com/rust-lang/rust/pull/83652 [83387]: https://github.com/rust-lang/rust/pull/83387 [82873]: https://github.com/rust-lang/rust/pull/82873 [82864]: https://github.com/rust-lang/rust/pull/82864 [82608]: https://github.com/rust-lang/rust/pull/82608 [82565]: https://github.com/rust-lang/rust/pull/82565 [80525]: https://github.com/rust-lang/rust/pull/80525 [79278]: https://github.com/rust-lang/rust/pull/79278 [78618]: https://github.com/rust-lang/rust/pull/78618 [77704]: https://github.com/rust-lang/rust/pull/77704 [83941]: https://github.com/rust-lang/rust/pull/83941 [83065]: https://github.com/rust-lang/rust/pull/83065 [81764]: https://github.com/rust-lang/rust/pull/81764 [81469]: https://github.com/rust-lang/rust/pull/81469 [cargo/9298]: https://github.com/rust-lang/cargo/pull/9298 [cargo/9282]: https://github.com/rust-lang/cargo/pull/9282 [cargo/9392]: https://github.com/rust-lang/cargo/pull/9392 [`AtomicBool::fetch_update`]: https://doc.rust-lang.org/std/sync/atomic/struct.AtomicBool.html#method.fetch_update [`AtomicPtr::fetch_update`]: https://doc.rust-lang.org/std/sync/atomic/struct.AtomicPtr.html#method.fetch_update [`BTreeMap::retain`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.retain [`BTreeSet::retain`]: https://doc.rust-lang.org/std/collections/struct.BTreeSet.html#method.retain [`BufReader::seek_relative`]: https://doc.rust-lang.org/std/io/struct.BufReader.html#method.seek_relative [`DebugStruct::non_exhaustive`]: https://doc.rust-lang.org/std/fmt/struct.DebugStruct.html#method.finish_non_exhaustive [`Duration::MAX`]: https://doc.rust-lang.org/std/time/struct.Duration.html#associatedconstant.MAX [`Duration::ZERO`]: https://doc.rust-lang.org/std/time/struct.Duration.html#associatedconstant.ZERO [`Duration::is_zero`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.is_zero [`Duration::saturating_add`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.saturating_add [`Duration::saturating_mul`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.saturating_mul [`Duration::saturating_sub`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.saturating_sub [`ErrorKind::Unsupported`]: https://doc.rust-lang.org/std/io/enum.ErrorKind.html#variant.Unsupported [`Option::insert`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.insert [`Ordering::is_eq`]: https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.is_eq [`Ordering::is_ge`]: https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.is_ge [`Ordering::is_gt`]: https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.is_gt [`Ordering::is_le`]: https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.is_le [`Ordering::is_lt`]: https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.is_lt [`Ordering::is_ne`]: https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.is_ne [`OsStr::is_ascii`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.is_ascii [`OsStr::make_ascii_lowercase`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.make_ascii_lowercase [`OsStr::make_ascii_uppercase`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.make_ascii_uppercase [`OsStr::to_ascii_lowercase`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.to_ascii_lowercase [`OsStr::to_ascii_uppercase`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.to_ascii_uppercase [`Peekable::peek_mut`]: https://doc.rust-lang.org/std/iter/struct.Peekable.html#method.peek_mut [`Rc::decrement_strong_count`]: https://doc.rust-lang.org/std/rc/struct.Rc.html#method.decrement_strong_count [`Rc::increment_strong_count`]: https://doc.rust-lang.org/std/rc/struct.Rc.html#method.increment_strong_count [`Vec::extend_from_within`]: https://doc.rust-lang.org/beta/std/vec/struct.Vec.html#method.extend_from_within [`array::from_mut`]: https://doc.rust-lang.org/beta/std/array/fn.from_mut.html [`array::from_ref`]: https://doc.rust-lang.org/beta/std/array/fn.from_ref.html [`cmp::max_by_key`]: https://doc.rust-lang.org/beta/std/cmp/fn.max_by_key.html [`cmp::max_by`]: https://doc.rust-lang.org/beta/std/cmp/fn.max_by.html [`cmp::min_by_key`]: https://doc.rust-lang.org/beta/std/cmp/fn.min_by_key.html [`cmp::min_by`]: https://doc.rust-lang.org/beta/std/cmp/fn.min_by.html [`f32::is_subnormal`]: https://doc.rust-lang.org/std/primitive.f32.html#method.is_subnormal [`f64::is_subnormal`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_subnormal [ietf6943]: https://datatracker.ietf.org/doc/html/rfc6943#section-3.1.1 Version 1.52.1 (2021-05-10) ============================ This release disables incremental compilation, unless the user has explicitly opted in via the newly added RUSTC_FORCE_INCREMENTAL=1 environment variable. This is due to the widespread, and frequently occurring, breakage encountered by Rust users due to newly enabled incremental verification in 1.52.0. Notably, Rust users **should** upgrade to 1.52.0 or 1.52.1: the bugs that are detected by newly added incremental verification are still present in past stable versions, and are not yet fixed on any channel. These bugs can lead to miscompilation of Rust binaries. These problems only affect incremental builds, so release builds with Cargo should not be affected unless the user has explicitly opted into incremental. Debug and check builds are affected. See [84970] for more details. [84970]: https://github.com/rust-lang/rust/issues/84970 Version 1.52.0 (2021-05-06) ============================ Language -------- - [Added the `unsafe_op_in_unsafe_fn` lint, which checks whether the unsafe code in an `unsafe fn` is wrapped in a `unsafe` block.][79208] This lint is allowed by default, and may become a warning or hard error in a future edition. - [You can now cast mutable references to arrays to a pointer of the same type as the element.][81479] Compiler -------- - [Upgraded the default LLVM to LLVM 12.][81451] Added tier 3\* support for the following targets. - [`s390x-unknown-linux-musl`][82166] - [`riscv32gc-unknown-linux-musl` & `riscv64gc-unknown-linux-musl`][82202] - [`powerpc-unknown-openbsd`][82733] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [`OsString` now implements `Extend` and `FromIterator`.][82121] - [`cmp::Reverse` now has `#[repr(transparent)]` representation.][81879] - [`Arc<impl Error>` now implements `error::Error`.][80553] - [All integer division and remainder operations are now `const`.][80962] Stabilised APIs ------------- - [`Arguments::as_str`] - [`char::MAX`] - [`char::REPLACEMENT_CHARACTER`] - [`char::UNICODE_VERSION`] - [`char::decode_utf16`] - [`char::from_digit`] - [`char::from_u32_unchecked`] - [`char::from_u32`] - [`slice::partition_point`] - [`str::rsplit_once`] - [`str::split_once`] The following previously stable APIs are now `const`. - [`char::len_utf8`] - [`char::len_utf16`] - [`char::to_ascii_uppercase`] - [`char::to_ascii_lowercase`] - [`char::eq_ignore_ascii_case`] - [`u8::to_ascii_uppercase`] - [`u8::to_ascii_lowercase`] - [`u8::eq_ignore_ascii_case`] Rustdoc ------- - [Rustdoc lints are now treated as a tool lint, meaning that lints are now prefixed with `rustdoc::` (e.g. `#[warn(rustdoc::broken_intra_doc_links)]`).][80527] Using the old style is still allowed, and will become a warning in a future release. - [Rustdoc now supports argument files.][82261] - [Rustdoc now generates smart punctuation for documentation.][79423] - [You can now use "task lists" in Rustdoc Markdown.][81766] E.g. ```markdown - [x] Complete - [ ] Todo ``` Misc ---- - [You can now pass multiple filters to tests.][81356] E.g. `cargo test -- foo bar` will run all tests that match `foo` and `bar`. - [Rustup now distributes PDB symbols for the `std` library on Windows, allowing you to see `std` symbols when debugging.][82218] Internal Only ------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. - [Check the result cache before the DepGraph when ensuring queries][81855] - [Try fast_reject::simplify_type in coherence before doing full check][81744] - [Only store a LocalDefId in some HIR nodes][81611] - [Store HIR attributes in a side table][79519] Compatibility Notes ------------------- - [Cargo build scripts are now forbidden from setting `RUSTC_BOOTSTRAP`.][cargo/9181] - [Removed support for the `x86_64-rumprun-netbsd` target.][82594] - [Deprecated the `x86_64-sun-solaris` target in favor of `x86_64-pc-solaris`.][82216] - [Rustdoc now only accepts `,`, ` `, and `\t` as delimiters for specifying languages in code blocks.][78429] - [Rustc now catches more cases of `pub_use_of_private_extern_crate`][80763] - [Changes in how proc macros handle whitespace may lead to panics when used with older `proc-macro-hack` versions. A `cargo update` should be sufficient to fix this in all cases.][84136] - [Turn `#[derive]` into a regular macro attribute][79078] [84136]: https://github.com/rust-lang/rust/issues/84136 [80763]: https://github.com/rust-lang/rust/pull/80763 [82166]: https://github.com/rust-lang/rust/pull/82166 [82121]: https://github.com/rust-lang/rust/pull/82121 [81879]: https://github.com/rust-lang/rust/pull/81879 [82261]: https://github.com/rust-lang/rust/pull/82261 [82218]: https://github.com/rust-lang/rust/pull/82218 [82216]: https://github.com/rust-lang/rust/pull/82216 [82202]: https://github.com/rust-lang/rust/pull/82202 [81855]: https://github.com/rust-lang/rust/pull/81855 [81766]: https://github.com/rust-lang/rust/pull/81766 [81744]: https://github.com/rust-lang/rust/pull/81744 [81611]: https://github.com/rust-lang/rust/pull/81611 [81479]: https://github.com/rust-lang/rust/pull/81479 [81451]: https://github.com/rust-lang/rust/pull/81451 [81356]: https://github.com/rust-lang/rust/pull/81356 [80962]: https://github.com/rust-lang/rust/pull/80962 [80553]: https://github.com/rust-lang/rust/pull/80553 [80527]: https://github.com/rust-lang/rust/pull/80527 [79519]: https://github.com/rust-lang/rust/pull/79519 [79423]: https://github.com/rust-lang/rust/pull/79423 [79208]: https://github.com/rust-lang/rust/pull/79208 [78429]: https://github.com/rust-lang/rust/pull/78429 [82733]: https://github.com/rust-lang/rust/pull/82733 [82594]: https://github.com/rust-lang/rust/pull/82594 [79078]: https://github.com/rust-lang/rust/pull/79078 [cargo/9181]: https://github.com/rust-lang/cargo/pull/9181 [`char::MAX`]: https://doc.rust-lang.org/std/primitive.char.html#associatedconstant.MAX [`char::REPLACEMENT_CHARACTER`]: https://doc.rust-lang.org/std/primitive.char.html#associatedconstant.REPLACEMENT_CHARACTER [`char::UNICODE_VERSION`]: https://doc.rust-lang.org/std/primitive.char.html#associatedconstant.UNICODE_VERSION [`char::decode_utf16`]: https://doc.rust-lang.org/std/primitive.char.html#method.decode_utf16 [`char::from_u32`]: https://doc.rust-lang.org/std/primitive.char.html#method.from_u32 [`char::from_u32_unchecked`]: https://doc.rust-lang.org/std/primitive.char.html#method.from_u32_unchecked [`char::from_digit`]: https://doc.rust-lang.org/std/primitive.char.html#method.from_digit [`Peekable::next_if`]: https://doc.rust-lang.org/stable/std/iter/struct.Peekable.html#method.next_if [`Peekable::next_if_eq`]: https://doc.rust-lang.org/stable/std/iter/struct.Peekable.html#method.next_if_eq [`Arguments::as_str`]: https://doc.rust-lang.org/stable/std/fmt/struct.Arguments.html#method.as_str [`str::split_once`]: https://doc.rust-lang.org/stable/std/primitive.str.html#method.split_once [`str::rsplit_once`]: https://doc.rust-lang.org/stable/std/primitive.str.html#method.rsplit_once [`slice::partition_point`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.partition_point [`char::len_utf8`]: https://doc.rust-lang.org/stable/std/primitive.char.html#method.len_utf8 [`char::len_utf16`]: https://doc.rust-lang.org/stable/std/primitive.char.html#method.len_utf16 [`char::to_ascii_uppercase`]: https://doc.rust-lang.org/stable/std/primitive.char.html#method.to_ascii_uppercase [`char::to_ascii_lowercase`]: https://doc.rust-lang.org/stable/std/primitive.char.html#method.to_ascii_lowercase [`char::eq_ignore_ascii_case`]: https://doc.rust-lang.org/stable/std/primitive.char.html#method.eq_ignore_ascii_case [`u8::to_ascii_uppercase`]: https://doc.rust-lang.org/stable/std/primitive.u8.html#method.to_ascii_uppercase [`u8::to_ascii_lowercase`]: https://doc.rust-lang.org/stable/std/primitive.u8.html#method.to_ascii_lowercase [`u8::eq_ignore_ascii_case`]: https://doc.rust-lang.org/stable/std/primitive.u8.html#method.eq_ignore_ascii_case Version 1.51.0 (2021-03-25) ============================ Language -------- - [You can now parameterize items such as functions, traits, and `struct`s by constant values in addition to by types and lifetimes.][79135] Also known as "const generics" E.g. you can now write the following. Note: Only values of primitive integers, `bool`, or `char` types are currently permitted. ```rust struct GenericArray<T, const LENGTH: usize> { inner: [T; LENGTH] } impl<T, const LENGTH: usize> GenericArray<T, LENGTH> { const fn last(&self) -> Option<&T> { if LENGTH == 0 { None } else { Some(&self.inner[LENGTH - 1]) } } } ``` Compiler -------- - [Added the `-Csplit-debuginfo` codegen option for macOS platforms.][79570] This option controls whether debug information is split across multiple files or packed into a single file. **Note** This option is unstable on other platforms. - [Added tier 3\* support for `aarch64_be-unknown-linux-gnu`, `aarch64-unknown-linux-gnu_ilp32`, and `aarch64_be-unknown-linux-gnu_ilp32` targets.][81455] - [Added tier 3 support for `i386-unknown-linux-gnu` and `i486-unknown-linux-gnu` targets.][80662] - [The `target-cpu=native` option will now detect individual features of CPUs.][80749] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [`Box::downcast` is now also implemented for any `dyn Any + Send + Sync` object.][80945] - [`str` now implements `AsMut<str>`.][80279] - [`u64` and `u128` now implement `From<char>`.][79502] - [`Error` is now implemented for `&T` where `T` implements `Error`.][75180] - [`Poll::{map_ok, map_err}` are now implemented for `Poll<Option<Result<T, E>>>`.][80968] - [`unsigned_abs` is now implemented for all signed integer types.][80959] - [`io::Empty` now implements `io::Seek`.][78044] - [`rc::Weak<T>` and `sync::Weak<T>`'s methods such as `as_ptr` are now implemented for `T: ?Sized` types.][80764] - [`Div` and `Rem` by their `NonZero` variant is now implemented for all unsigned integers.][79134] Stabilized APIs --------------- - [`Arc::decrement_strong_count`] - [`Arc::increment_strong_count`] - [`Once::call_once_force`] - [`Peekable::next_if_eq`] - [`Peekable::next_if`] - [`Seek::stream_position`] - [`array::IntoIter`] - [`panic::panic_any`] - [`ptr::addr_of!`] - [`ptr::addr_of_mut!`] - [`slice::fill_with`] - [`slice::split_inclusive_mut`] - [`slice::split_inclusive`] - [`slice::strip_prefix`] - [`slice::strip_suffix`] - [`str::split_inclusive`] - [`sync::OnceState`] - [`task::Wake`] - [`VecDeque::range`] - [`VecDeque::range_mut`] Cargo ----- - [Added the `split-debuginfo` profile option to control the -Csplit-debuginfo codegen option.][cargo/9112] - [Added the `resolver` field to `Cargo.toml` to enable the new feature resolver and CLI option behavior.][cargo/8997] Version 2 of the feature resolver will try to avoid unifying features of dependencies where that unification could be unwanted. Such as using the same dependency with a `std` feature in a build scripts and proc-macros, while using the `no-std` feature in the final binary. See the [Cargo book documentation][feature-resolver@2.0] for more information on the feature. Rustdoc ------- - [Rustdoc will now include documentation for methods available from _nested_ `Deref` traits.][80653] - [You can now provide a `--default-theme` flag which sets the default theme to use for documentation.][79642] Various improvements to intra-doc links: - [You can link to non-path primitives such as `slice`.][80181] - [You can link to associated items.][74489] - [You can now include generic parameters when linking to items, like `Vec<T>`.][76934] Misc ---- - [You can now pass `--include-ignored` to tests (e.g. with `cargo test -- --include-ignored`) to include testing tests marked `#[ignore]`.][80053] Compatibility Notes ------------------- - [WASI platforms no longer use the `wasm-bindgen` ABI, and instead use the wasm32 ABI.][79998] - [`rustc` no longer promotes division, modulo and indexing operations to `const` that could fail.][80579] - [The minimum version of glibc for the following platforms has been bumped to version 2.31 for the distributed artifacts.][81521] - `armv5te-unknown-linux-gnueabi` - `sparc64-unknown-linux-gnu` - `thumbv7neon-unknown-linux-gnueabihf` - `armv7-unknown-linux-gnueabi` - `x86_64-unknown-linux-gnux32` - [`atomic::spin_loop_hint` has been deprecated.][80966] It's recommended to use `hint::spin_loop` instead. Internal Only ------------- - [Consistently avoid constructing optimized MIR when not doing codegen][80718] [79135]: https://github.com/rust-lang/rust/pull/79135 [74489]: https://github.com/rust-lang/rust/pull/74489 [76934]: https://github.com/rust-lang/rust/pull/76934 [79570]: https://github.com/rust-lang/rust/pull/79570 [80181]: https://github.com/rust-lang/rust/pull/80181 [79642]: https://github.com/rust-lang/rust/pull/79642 [80945]: https://github.com/rust-lang/rust/pull/80945 [80279]: https://github.com/rust-lang/rust/pull/80279 [80053]: https://github.com/rust-lang/rust/pull/80053 [79502]: https://github.com/rust-lang/rust/pull/79502 [75180]: https://github.com/rust-lang/rust/pull/75180 [81521]: https://github.com/rust-lang/rust/pull/81521 [80968]: https://github.com/rust-lang/rust/pull/80968 [80959]: https://github.com/rust-lang/rust/pull/80959 [80718]: https://github.com/rust-lang/rust/pull/80718 [80653]: https://github.com/rust-lang/rust/pull/80653 [80579]: https://github.com/rust-lang/rust/pull/80579 [79998]: https://github.com/rust-lang/rust/pull/79998 [78044]: https://github.com/rust-lang/rust/pull/78044 [81455]: https://github.com/rust-lang/rust/pull/81455 [80764]: https://github.com/rust-lang/rust/pull/80764 [80749]: https://github.com/rust-lang/rust/pull/80749 [80662]: https://github.com/rust-lang/rust/pull/80662 [79134]: https://github.com/rust-lang/rust/pull/79134 [80966]: https://github.com/rust-lang/rust/pull/80966 [cargo/8997]: https://github.com/rust-lang/cargo/pull/8997 [cargo/9112]: https://github.com/rust-lang/cargo/pull/9112 [feature-resolver@2.0]: https://doc.rust-lang.org/nightly/cargo/reference/features.html#feature-resolver-version-2 [`Once::call_once_force`]: https://doc.rust-lang.org/stable/std/sync/struct.Once.html#method.call_once_force [`sync::OnceState`]: https://doc.rust-lang.org/stable/std/sync/struct.OnceState.html [`panic::panic_any`]: https://doc.rust-lang.org/stable/std/panic/fn.panic_any.html [`slice::strip_prefix`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.strip_prefix [`slice::strip_suffix`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.strip_suffix [`Arc::increment_strong_count`]: https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.increment_strong_count [`Arc::decrement_strong_count`]: https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.decrement_strong_count [`slice::fill_with`]: https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.fill_with [`ptr::addr_of!`]: https://doc.rust-lang.org/nightly/std/ptr/macro.addr_of.html [`ptr::addr_of_mut!`]: https://doc.rust-lang.org/nightly/std/ptr/macro.addr_of_mut.html [`array::IntoIter`]: https://doc.rust-lang.org/nightly/std/array/struct.IntoIter.html [`slice::split_inclusive`]: https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.split_inclusive [`slice::split_inclusive_mut`]: https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.split_inclusive_mut [`str::split_inclusive`]: https://doc.rust-lang.org/nightly/std/primitive.str.html#method.split_inclusive [`task::Wake`]: https://doc.rust-lang.org/nightly/std/task/trait.Wake.html [`Seek::stream_position`]: https://doc.rust-lang.org/nightly/std/io/trait.Seek.html#method.stream_position [`Peekable::next_if`]: https://doc.rust-lang.org/nightly/std/iter/struct.Peekable.html#method.next_if [`Peekable::next_if_eq`]: https://doc.rust-lang.org/nightly/std/iter/struct.Peekable.html#method.next_if_eq [`VecDeque::range`]: https://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.range [`VecDeque::range_mut`]: https://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.range_mut Version 1.50.0 (2021-02-11) ============================ Language ----------------------- - [You can now use `const` values for `x` in `[x; N]` array expressions.][79270] This has been technically possible since 1.38.0, as it was unintentionally stabilized. - [Assignments to `ManuallyDrop<T>` union fields are now considered safe.][78068] Compiler ----------------------- - [Added tier 3\* support for the `armv5te-unknown-linux-uclibceabi` target.][78142] - [Added tier 3 support for the `aarch64-apple-ios-macabi` target.][77484] - [The `x86_64-unknown-freebsd` is now built with the full toolset.][79484] - [Dropped support for all cloudabi targets.][78439] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries ----------------------- - [`proc_macro::Punct` now implements `PartialEq<char>`.][78636] - [`ops::{Index, IndexMut}` are now implemented for fixed sized arrays of any length.][74989] - [On Unix platforms, the `std::fs::File` type now has a "niche" of `-1`.][74699] This value cannot be a valid file descriptor, and now means `Option<File>` takes up the same amount of space as `File`. Stabilized APIs --------------- - [`bool::then`] - [`btree_map::Entry::or_insert_with_key`] - [`f32::clamp`] - [`f64::clamp`] - [`hash_map::Entry::or_insert_with_key`] - [`Ord::clamp`] - [`RefCell::take`] - [`slice::fill`] - [`UnsafeCell::get_mut`] The following previously stable methods are now `const`. - [`IpAddr::is_ipv4`] - [`IpAddr::is_ipv6`] - [`IpAddr::is_unspecified`] - [`IpAddr::is_loopback`] - [`IpAddr::is_multicast`] - [`Ipv4Addr::octets`] - [`Ipv4Addr::is_loopback`] - [`Ipv4Addr::is_private`] - [`Ipv4Addr::is_link_local`] - [`Ipv4Addr::is_multicast`] - [`Ipv4Addr::is_broadcast`] - [`Ipv4Addr::is_documentation`] - [`Ipv4Addr::to_ipv6_compatible`] - [`Ipv4Addr::to_ipv6_mapped`] - [`Ipv6Addr::segments`] - [`Ipv6Addr::is_unspecified`] - [`Ipv6Addr::is_loopback`] - [`Ipv6Addr::is_multicast`] - [`Ipv6Addr::to_ipv4`] - [`Layout::size`] - [`Layout::align`] - [`Layout::from_size_align`] - `pow` for all integer types. - `checked_pow` for all integer types. - `saturating_pow` for all integer types. - `wrapping_pow` for all integer types. - `next_power_of_two` for all unsigned integer types. - `checked_next_power_of_two` for all unsigned integer types. Cargo ----------------------- - [Added the `[build.rustc-workspace-wrapper]` option.][cargo/8976] This option sets a wrapper to execute instead of `rustc`, for workspace members only. - [`cargo:rerun-if-changed` will now, if provided a directory, scan the entire contents of that directory for changes.][cargo/8973] - [Added the `--workspace` flag to the `cargo update` command.][cargo/8725] Misc ---- - [The search results tab and the help button are focusable with keyboard in rustdoc.][79896] - [Running tests will now print the total time taken to execute.][75752] Compatibility Notes ------------------- - [The `compare_and_swap` method on atomics has been deprecated.][79261] It's recommended to use the `compare_exchange` and `compare_exchange_weak` methods instead. - [Changes in how `TokenStream`s are checked have fixed some cases where you could write unhygenic `macro_rules!` macros.][79472] - [`#![test]` as an inner attribute is now considered unstable like other inner macro attributes, and reports an error by default through the `soft_unstable` lint.][79003] - [Overriding a `forbid` lint at the same level that it was set is now a hard error.][78864] - [You can no longer intercept `panic!` calls by supplying your own macro.][78343] It's recommended to use the `#[panic_handler]` attribute to provide your own implementation. - [Semi-colons after item statements (e.g. `struct Foo {};`) now produce a warning.][78296] [74989]: https://github.com/rust-lang/rust/pull/74989 [79261]: https://github.com/rust-lang/rust/pull/79261 [79896]: https://github.com/rust-lang/rust/pull/79896 [79484]: https://github.com/rust-lang/rust/pull/79484 [79472]: https://github.com/rust-lang/rust/pull/79472 [79270]: https://github.com/rust-lang/rust/pull/79270 [79003]: https://github.com/rust-lang/rust/pull/79003 [78864]: https://github.com/rust-lang/rust/pull/78864 [78636]: https://github.com/rust-lang/rust/pull/78636 [78439]: https://github.com/rust-lang/rust/pull/78439 [78343]: https://github.com/rust-lang/rust/pull/78343 [78296]: https://github.com/rust-lang/rust/pull/78296 [78068]: https://github.com/rust-lang/rust/pull/78068 [75752]: https://github.com/rust-lang/rust/pull/75752 [74699]: https://github.com/rust-lang/rust/pull/74699 [78142]: https://github.com/rust-lang/rust/pull/78142 [77484]: https://github.com/rust-lang/rust/pull/77484 [cargo/8976]: https://github.com/rust-lang/cargo/pull/8976 [cargo/8973]: https://github.com/rust-lang/cargo/pull/8973 [cargo/8725]: https://github.com/rust-lang/cargo/pull/8725 [`IpAddr::is_ipv4`]: https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_ipv4 [`IpAddr::is_ipv6`]: https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_ipv6 [`IpAddr::is_unspecified`]: https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_unspecified [`IpAddr::is_loopback`]: https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_loopback [`IpAddr::is_multicast`]: https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_multicast [`Ipv4Addr::octets`]: https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.octets [`Ipv4Addr::is_loopback`]: https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_loopback [`Ipv4Addr::is_private`]: https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_private [`Ipv4Addr::is_link_local`]: https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_link_local [`Ipv4Addr::is_multicast`]: https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_multicast [`Ipv4Addr::is_broadcast`]: https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_broadcast [`Ipv4Addr::is_documentation`]: https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_documentation [`Ipv4Addr::to_ipv6_compatible`]: https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.to_ipv6_compatible [`Ipv4Addr::to_ipv6_mapped`]: https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.to_ipv6_mapped [`Ipv6Addr::segments`]: https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.segments [`Ipv6Addr::is_unspecified`]: https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.is_unspecified [`Ipv6Addr::is_loopback`]: https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.is_loopback [`Ipv6Addr::is_multicast`]: https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.is_multicast [`Ipv6Addr::to_ipv4`]: https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.to_ipv4 [`Layout::align`]: https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.align [`Layout::from_size_align`]: https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.from_size_align [`Layout::size`]: https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.size [`Ord::clamp`]: https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.clamp [`RefCell::take`]: https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html#method.take [`UnsafeCell::get_mut`]: https://doc.rust-lang.org/stable/std/cell/struct.UnsafeCell.html#method.get_mut [`bool::then`]: https://doc.rust-lang.org/stable/std/primitive.bool.html#method.then [`btree_map::Entry::or_insert_with_key`]: https://doc.rust-lang.org/stable/std/collections/btree_map/enum.Entry.html#method.or_insert_with_key [`f32::clamp`]: https://doc.rust-lang.org/stable/std/primitive.f32.html#method.clamp [`f64::clamp`]: https://doc.rust-lang.org/stable/std/primitive.f64.html#method.clamp [`hash_map::Entry::or_insert_with_key`]: https://doc.rust-lang.org/stable/std/collections/hash_map/enum.Entry.html#method.or_insert_with_key [`slice::fill`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.fill Version 1.49.0 (2020-12-31) ============================ Language ----------------------- - [Unions can now implement `Drop`, and you can now have a field in a union with `ManuallyDrop<T>`.][77547] - [You can now cast uninhabited enums to integers.][76199] - [You can now bind by reference and by move in patterns.][76119] This allows you to selectively borrow individual components of a type. E.g. ```rust #[derive(Debug)] struct Person { name: String, age: u8, } let person = Person { name: String::from("Alice"), age: 20, }; // `name` is moved out of person, but `age` is referenced. let Person { name, ref age } = person; println!("{} {}", name, age); ``` Compiler ----------------------- - [Added tier 1\* support for `aarch64-unknown-linux-gnu`.][78228] - [Added tier 2 support for `aarch64-apple-darwin`.][75991] - [Added tier 2 support for `aarch64-pc-windows-msvc`.][75914] - [Added tier 3 support for `mipsel-unknown-none`.][78676] - [Raised the minimum supported LLVM version to LLVM 9.][78848] - [Output from threads spawned in tests is now captured.][78227] - [Change os and vendor values to "none" and "unknown" for some targets][78951] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries ----------------------- - [`RangeInclusive` now checks for exhaustion when calling `contains` and indexing.][78109] - [`ToString::to_string` now no longer shrinks the internal buffer in the default implementation.][77997] Stabilized APIs --------------- - [`slice::select_nth_unstable`] - [`slice::select_nth_unstable_by`] - [`slice::select_nth_unstable_by_key`] The following previously stable methods are now `const`. - [`Poll::is_ready`] - [`Poll::is_pending`] Cargo ----------------------- - [Building a crate with `cargo-package` should now be independently reproducible.][cargo/8864] - [`cargo-tree` now marks proc-macro crates.][cargo/8765] - [Added `CARGO_PRIMARY_PACKAGE` build-time environment variable.][cargo/8758] This variable will be set if the crate being built is one the user selected to build, either with `-p` or through defaults. - [You can now use glob patterns when specifying packages & targets.][cargo/8752] Compatibility Notes ------------------- - [Demoted `i686-unknown-freebsd` from host tier 2 to target tier 2 support.][78746] - [Macros that end with a semi-colon are now treated as statements even if they expand to nothing.][78376] - [Rustc will now check for the validity of some built-in attributes on enum variants.][77015] Previously such invalid or unused attributes could be ignored. - Leading whitespace is stripped more uniformly in documentation comments, which may change behavior. You read [this post about the changes][rustdoc-ws-post] for more details. - [Trait bounds are no longer inferred for associated types.][79904] Internal Only ------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. - [rustc's internal crates are now compiled using the `initial-exec` Thread Local Storage model.][78201] - [Calculate visibilities once in resolve.][78077] - [Added `system` to the `llvm-libunwind` bootstrap config option.][77703] - [Added `--color` for configuring terminal color support to bootstrap.][79004] [75991]: https://github.com/rust-lang/rust/pull/75991 [78951]: https://github.com/rust-lang/rust/pull/78951 [78848]: https://github.com/rust-lang/rust/pull/78848 [78746]: https://github.com/rust-lang/rust/pull/78746 [78376]: https://github.com/rust-lang/rust/pull/78376 [78228]: https://github.com/rust-lang/rust/pull/78228 [78227]: https://github.com/rust-lang/rust/pull/78227 [78201]: https://github.com/rust-lang/rust/pull/78201 [78109]: https://github.com/rust-lang/rust/pull/78109 [78077]: https://github.com/rust-lang/rust/pull/78077 [77997]: https://github.com/rust-lang/rust/pull/77997 [77703]: https://github.com/rust-lang/rust/pull/77703 [77547]: https://github.com/rust-lang/rust/pull/77547 [77015]: https://github.com/rust-lang/rust/pull/77015 [76199]: https://github.com/rust-lang/rust/pull/76199 [76119]: https://github.com/rust-lang/rust/pull/76119 [75914]: https://github.com/rust-lang/rust/pull/75914 [79004]: https://github.com/rust-lang/rust/pull/79004 [78676]: https://github.com/rust-lang/rust/pull/78676 [79904]: https://github.com/rust-lang/rust/issues/79904 [cargo/8864]: https://github.com/rust-lang/cargo/pull/8864 [cargo/8765]: https://github.com/rust-lang/cargo/pull/8765 [cargo/8758]: https://github.com/rust-lang/cargo/pull/8758 [cargo/8752]: https://github.com/rust-lang/cargo/pull/8752 [`slice::select_nth_unstable`]: https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.select_nth_unstable [`slice::select_nth_unstable_by`]: https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.select_nth_unstable_by [`slice::select_nth_unstable_by_key`]: https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.select_nth_unstable_by_key [`Poll::is_ready`]: https://doc.rust-lang.org/stable/std/task/enum.Poll.html#method.is_ready [`Poll::is_pending`]: https://doc.rust-lang.org/stable/std/task/enum.Poll.html#method.is_pending [rustdoc-ws-post]: https://blog.guillaume-gomez.fr/articles/2020-11-11+New+doc+comment+handling+in+rustdoc Version 1.48.0 (2020-11-19) ========================== Language -------- - [The `unsafe` keyword is now syntactically permitted on modules.][75857] This is still rejected *semantically*, but can now be parsed by procedural macros. Compiler -------- - [Stabilised the `-C link-self-contained=<yes|no>` compiler flag.][76158] This tells `rustc` whether to link its own C runtime and libraries or to rely on a external linker to find them. (Supported only on `windows-gnu`, `linux-musl`, and `wasi` platforms.) - [You can now use `-C target-feature=+crt-static` on `linux-gnu` targets.][77386] Note: If you're using cargo you must explicitly pass the `--target` flag. - [Added tier 2\* support for `aarch64-unknown-linux-musl`.][76420] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [`io::Write` is now implemented for `&ChildStdin` `&Sink`, `&Stdout`, and `&Stderr`.][76275] - [All arrays of any length now implement `TryFrom<Vec<T>>`.][76310] - [The `matches!` macro now supports having a trailing comma.][74880] - [`Vec<A>` now implements `PartialEq<[B]>` where `A: PartialEq<B>`.][74194] - [The `RefCell::{replace, replace_with, clone}` methods now all use `#[track_caller]`.][77055] Stabilized APIs --------------- - [`slice::as_ptr_range`] - [`slice::as_mut_ptr_range`] - [`VecDeque::make_contiguous`] - [`future::pending`] - [`future::ready`] The following previously stable methods are now `const fn`'s: - [`Option::is_some`] - [`Option::is_none`] - [`Option::as_ref`] - [`Result::is_ok`] - [`Result::is_err`] - [`Result::as_ref`] - [`Ordering::reverse`] - [`Ordering::then`] Cargo ----- Rustdoc ------- - [You can now link to items in `rustdoc` using the intra-doc link syntax.][74430] E.g. ``/// Uses [`std::future`]`` will automatically generate a link to `std::future`'s documentation. See ["Linking to items by name"][intradoc-links] for more information. - [You can now specify `#[doc(alias = "<alias>")]` on items to add search aliases when searching through `rustdoc`'s UI.][75740] Compatibility Notes ------------------- - [Promotion of references to `'static` lifetime inside `const fn` now follows the same rules as inside a `fn` body.][75502] In particular, `&foo()` will not be promoted to `'static` lifetime any more inside `const fn`s. - [Associated type bindings on trait objects are now verified to meet the bounds declared on the trait when checking that they implement the trait.][27675] - [When trait bounds on associated types or opaque types are ambiguous, the compiler no longer makes an arbitrary choice on which bound to use.][54121] - [Fixed recursive nonterminals not being expanded in macros during pretty-print/reparse check.][77153] This may cause errors if your macro wasn't correctly handling recursive nonterminal tokens. - [`&mut` references to non zero-sized types are no longer promoted.][75585] - [`rustc` will now warn if you use attributes like `#[link_name]` or `#[cold]` in places where they have no effect.][73461] - [Updated `_mm256_extract_epi8` and `_mm256_extract_epi16` signatures in `arch::{x86, x86_64}` to return `i32` to match the vendor signatures.][73166] - [`mem::uninitialized` will now panic if any inner types inside a struct or enum disallow zero-initialization.][71274] - [`#[target_feature]` will now error if used in a place where it has no effect.][78143] - [Foreign exceptions are now caught by `catch_unwind` and will cause an abort.][70212] Note: This behaviour is not guaranteed and is still considered undefined behaviour, see the [`catch_unwind`] documentation for further information. Internal Only ------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. - [Building `rustc` from source now uses `ninja` by default over `make`.][74922] You can continue building with `make` by setting `ninja=false` in your `bootstrap.toml`. - [cg_llvm: `fewer_names` in `uncached_llvm_type`][76030] - [Made `ensure_sufficient_stack()` non-generic][76680] [78143]: https://github.com/rust-lang/rust/issues/78143 [76680]: https://github.com/rust-lang/rust/pull/76680/ [76030]: https://github.com/rust-lang/rust/pull/76030/ [70212]: https://github.com/rust-lang/rust/pull/70212/ [27675]: https://github.com/rust-lang/rust/issues/27675/ [54121]: https://github.com/rust-lang/rust/issues/54121/ [71274]: https://github.com/rust-lang/rust/pull/71274/ [77386]: https://github.com/rust-lang/rust/pull/77386/ [77153]: https://github.com/rust-lang/rust/pull/77153/ [77055]: https://github.com/rust-lang/rust/pull/77055/ [76275]: https://github.com/rust-lang/rust/pull/76275/ [76310]: https://github.com/rust-lang/rust/pull/76310/ [76420]: https://github.com/rust-lang/rust/pull/76420/ [76158]: https://github.com/rust-lang/rust/pull/76158/ [75857]: https://github.com/rust-lang/rust/pull/75857/ [75585]: https://github.com/rust-lang/rust/pull/75585/ [75740]: https://github.com/rust-lang/rust/pull/75740/ [75502]: https://github.com/rust-lang/rust/pull/75502/ [74880]: https://github.com/rust-lang/rust/pull/74880/ [74922]: https://github.com/rust-lang/rust/pull/74922/ [74430]: https://github.com/rust-lang/rust/pull/74430/ [74194]: https://github.com/rust-lang/rust/pull/74194/ [73461]: https://github.com/rust-lang/rust/pull/73461/ [73166]: https://github.com/rust-lang/rust/pull/73166/ [intradoc-links]: https://doc.rust-lang.org/rustdoc/linking-to-items-by-name.html [`catch_unwind`]: https://doc.rust-lang.org/std/panic/fn.catch_unwind.html [`Option::is_some`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.is_some [`Option::is_none`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.is_none [`Option::as_ref`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.as_ref [`Result::is_ok`]: https://doc.rust-lang.org/std/result/enum.Result.html#method.is_ok [`Result::is_err`]: https://doc.rust-lang.org/std/result/enum.Result.html#method.is_err [`Result::as_ref`]: https://doc.rust-lang.org/std/result/enum.Result.html#method.as_ref [`Ordering::reverse`]: https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.reverse [`Ordering::then`]: https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.then [`slice::as_ptr_range`]: https://doc.rust-lang.org/std/primitive.slice.html#method.as_ptr_range [`slice::as_mut_ptr_range`]: https://doc.rust-lang.org/std/primitive.slice.html#method.as_mut_ptr_range [`VecDeque::make_contiguous`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.make_contiguous [`future::pending`]: https://doc.rust-lang.org/std/future/fn.pending.html [`future::ready`]: https://doc.rust-lang.org/std/future/fn.ready.html Version 1.47.0 (2020-10-08) ========================== Language -------- - [Closures will now warn when not used.][74869] Compiler -------- - [Stabilized the `-C control-flow-guard` codegen option][73893], which enables [Control Flow Guard][1.47.0-cfg] for Windows platforms, and is ignored on other platforms. - [Upgraded to LLVM 11.][73526] - [Added tier 3\* support for the `thumbv4t-none-eabi` target.][74419] - [Upgrade the FreeBSD toolchain to version 11.4][75204] - [`RUST_BACKTRACE`'s output is now more compact.][75048] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [`CStr` now implements `Index<RangeFrom<usize>>`.][74021] - [Traits in `std`/`core` are now implemented for arrays of any length, not just those of length less than 33.][74060] - [`ops::RangeFull` and `ops::Range` now implement Default.][73197] - [`panic::Location` now implements `Copy`, `Clone`, `Eq`, `Hash`, `Ord`, `PartialEq`, and `PartialOrd`.][73583] Stabilized APIs --------------- - [`Ident::new_raw`] - [`Range::is_empty`] - [`RangeInclusive::is_empty`] - [`Result::as_deref`] - [`Result::as_deref_mut`] - [`Vec::leak`] - [`pointer::offset_from`] - [`f32::TAU`] - [`f64::TAU`] The following previously stable APIs have now been made const. - [The `new` method for all `NonZero` integers.][73858] - [The `checked_add`,`checked_sub`,`checked_mul`,`checked_neg`, `checked_shl`, `checked_shr`, `saturating_add`, `saturating_sub`, and `saturating_mul` methods for all integers.][73858] - [The `checked_abs`, `saturating_abs`, `saturating_neg`, and `signum` for all signed integers.][73858] - [The `is_ascii_alphabetic`, `is_ascii_uppercase`, `is_ascii_lowercase`, `is_ascii_alphanumeric`, `is_ascii_digit`, `is_ascii_hexdigit`, `is_ascii_punctuation`, `is_ascii_graphic`, `is_ascii_whitespace`, and `is_ascii_control` methods for `char` and `u8`.][73858] Cargo ----- - [`build-dependencies` are now built with opt-level 0 by default.][cargo/8500] You can override this by setting the following in your `Cargo.toml`. ```toml [profile.release.build-override] opt-level = 3 ``` - [`cargo-help` will now display man pages for commands rather just the `--help` text.][cargo/8456] - [`cargo-metadata` now emits a `test` field indicating if a target has tests enabled.][cargo/8478] - [`workspace.default-members` now respects `workspace.exclude`.][cargo/8485] - [`cargo-publish` will now use an alternative registry by default if it's the only registry specified in `package.publish`.][cargo/8571] Misc ---- - [Added a help button beside Rustdoc's searchbar that explains rustdoc's type based search.][75366] - [Added the Ayu theme to rustdoc.][71237] Compatibility Notes ------------------- - [Bumped the minimum supported Emscripten version to 1.39.20.][75716] - [Fixed a regression parsing `{} && false` in tail expressions.][74650] - [Added changes to how proc-macros are expanded in `macro_rules!` that should help to preserve more span information.][73084] These changes may cause compilation errors if your macro was unhygenic or didn't correctly handle `Delimiter::None`. - [Moved support for the CloudABI target to tier 3.][75568] - [`linux-gnu` targets now require minimum kernel 2.6.32 and glibc 2.11.][74163] - [Added the `rustc-docs` component.][75560] This allows you to install and read the documentation for the compiler internal APIs. (Currently only available for `x86_64-unknown-linux-gnu`.) Internal Only -------- - [Improved default settings for bootstrapping in `x.py`.][73964] You can read details about this change in the ["Changes to `x.py` defaults"](https://blog.rust-lang.org/inside-rust/2020/08/30/changes-to-x-py-defaults.html) post on the Inside Rust blog. [1.47.0-cfg]: https://docs.microsoft.com/en-us/windows/win32/secbp/control-flow-guard [75048]: https://github.com/rust-lang/rust/pull/75048/ [74163]: https://github.com/rust-lang/rust/pull/74163/ [71237]: https://github.com/rust-lang/rust/pull/71237/ [74869]: https://github.com/rust-lang/rust/pull/74869/ [73858]: https://github.com/rust-lang/rust/pull/73858/ [75716]: https://github.com/rust-lang/rust/pull/75716/ [75560]: https://github.com/rust-lang/rust/pull/75560/ [75568]: https://github.com/rust-lang/rust/pull/75568/ [75366]: https://github.com/rust-lang/rust/pull/75366/ [75204]: https://github.com/rust-lang/rust/pull/75204/ [74650]: https://github.com/rust-lang/rust/pull/74650/ [74419]: https://github.com/rust-lang/rust/pull/74419/ [73964]: https://github.com/rust-lang/rust/pull/73964/ [74021]: https://github.com/rust-lang/rust/pull/74021/ [74060]: https://github.com/rust-lang/rust/pull/74060/ [73893]: https://github.com/rust-lang/rust/pull/73893/ [73526]: https://github.com/rust-lang/rust/pull/73526/ [73583]: https://github.com/rust-lang/rust/pull/73583/ [73084]: https://github.com/rust-lang/rust/pull/73084/ [73197]: https://github.com/rust-lang/rust/pull/73197/ [cargo/8456]: https://github.com/rust-lang/cargo/pull/8456/ [cargo/8478]: https://github.com/rust-lang/cargo/pull/8478/ [cargo/8485]: https://github.com/rust-lang/cargo/pull/8485/ [cargo/8500]: https://github.com/rust-lang/cargo/pull/8500/ [cargo/8571]: https://github.com/rust-lang/cargo/pull/8571/ [`Ident::new_raw`]: https://doc.rust-lang.org/nightly/proc_macro/struct.Ident.html#method.new_raw [`Range::is_empty`]: https://doc.rust-lang.org/nightly/std/ops/struct.Range.html#method.is_empty [`RangeInclusive::is_empty`]: https://doc.rust-lang.org/nightly/std/ops/struct.RangeInclusive.html#method.is_empty [`Result::as_deref_mut`]: https://doc.rust-lang.org/nightly/std/result/enum.Result.html#method.as_deref_mut [`Result::as_deref`]: https://doc.rust-lang.org/nightly/std/result/enum.Result.html#method.as_deref [`Vec::leak`]: https://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#method.leak [`f32::TAU`]: https://doc.rust-lang.org/nightly/std/f32/consts/constant.TAU.html [`f64::TAU`]: https://doc.rust-lang.org/nightly/std/f64/consts/constant.TAU.html [`pointer::offset_from`]: https://doc.rust-lang.org/nightly/std/primitive.pointer.html#method.offset_from Version 1.46.0 (2020-08-27) ========================== Language -------- - [`if`, `match`, and `loop` expressions can now be used in const functions.][72437] - [Additionally you are now also able to coerce and cast to slices (`&[T]`) in const functions.][73862] - [The `#[track_caller]` attribute can now be added to functions to use the function's caller's location information for panic messages.][72445] - [Recursively indexing into tuples no longer needs parentheses.][71322] E.g. `x.0.0` over `(x.0).0`. - [`mem::transmute` can now be used in statics and constants.][72920] **Note** You currently can't use `mem::transmute` in constant functions. Compiler -------- - [You can now use the `cdylib` target on Apple iOS and tvOS platforms.][73516] - [Enabled static "Position Independent Executables" by default for `x86_64-unknown-linux-musl`.][70740] Libraries --------- - [`mem::forget` is now a `const fn`.][73887] - [`String` now implements `From<char>`.][73466] - [The `leading_ones`, and `trailing_ones` methods have been stabilised for all integer types.][73032] - [`vec::IntoIter<T>` now implements `AsRef<[T]>`.][72583] - [All non-zero integer types (`NonZeroU8`) now implement `TryFrom` for their zero-able equivalent (e.g. `TryFrom<u8>`).][72717] - [`&[T]` and `&mut [T]` now implement `PartialEq<Vec<T>>`.][71660] - [`(String, u16)` now implements `ToSocketAddrs`.][73007] - [`vec::Drain<'_, T>` now implements `AsRef<[T]>`.][72584] Stabilized APIs --------------- - [`Option::zip`] - [`vec::Drain::as_slice`] Cargo ----- Added a number of new environment variables that are now available when compiling your crate. - [`CARGO_BIN_NAME` and `CARGO_CRATE_NAME`][cargo/8270] Providing the name of the specific binary being compiled and the name of the crate. - [`CARGO_PKG_LICENSE`][cargo/8325] The license from the manifest of the package. - [`CARGO_PKG_LICENSE_FILE`][cargo/8387] The path to the license file. Compatibility Notes ------------------- - [The target configuration option `abi_blacklist` has been renamed to `unsupported_abis`.][74150] The old name will still continue to work. - [Rustc will now warn if you cast a C-like enum that implements `Drop`.][72331] This was previously accepted but will become a hard error in a future release. - [Rustc will fail to compile if you have a struct with `#[repr(i128)]` or `#[repr(u128)]`.][74109] This representation is currently only allowed on `enum`s. - [Tokens passed to `macro_rules!` are now always captured.][73293] This helps ensure that spans have the correct information, and may cause breakage if you were relying on receiving spans with dummy information. - [The InnoSetup installer for Windows is no longer available.][72569] This was a legacy installer that was replaced by a MSI installer a few years ago but was still being built. - [`{f32, f64}::asinh` now returns the correct values for negative numbers.][72486] - [Rustc will no longer accept overlapping trait implementations that only differ in how the lifetime was bound.][72493] - [Rustc now correctly relates the lifetime of an existential associated type.][71896] This fixes some edge cases where `rustc` would erroneously allow you to pass a shorter lifetime than expected. - [Rustc now dynamically links to `libz` (also called `zlib`) on Linux.][74420] The library will need to be installed for `rustc` to work, even though we expect it to be already available on most systems. - [Tests annotated with `#[should_panic]` are broken on ARMv7 while running under QEMU.][74820] - [Pretty printing of some tokens in procedural macros changed.][75453] The exact output returned by rustc's pretty printing is an unstable implementation detail: we recommend any macro relying on it to switch to a more robust parsing system. [75453]: https://github.com/rust-lang/rust/issues/75453/ [74820]: https://github.com/rust-lang/rust/issues/74820/ [74420]: https://github.com/rust-lang/rust/issues/74420/ [74109]: https://github.com/rust-lang/rust/pull/74109/ [74150]: https://github.com/rust-lang/rust/pull/74150/ [73862]: https://github.com/rust-lang/rust/pull/73862/ [73887]: https://github.com/rust-lang/rust/pull/73887/ [73466]: https://github.com/rust-lang/rust/pull/73466/ [73516]: https://github.com/rust-lang/rust/pull/73516/ [73293]: https://github.com/rust-lang/rust/pull/73293/ [73007]: https://github.com/rust-lang/rust/pull/73007/ [73032]: https://github.com/rust-lang/rust/pull/73032/ [72920]: https://github.com/rust-lang/rust/pull/72920/ [72569]: https://github.com/rust-lang/rust/pull/72569/ [72583]: https://github.com/rust-lang/rust/pull/72583/ [72584]: https://github.com/rust-lang/rust/pull/72584/ [72717]: https://github.com/rust-lang/rust/pull/72717/ [72437]: https://github.com/rust-lang/rust/pull/72437/ [72445]: https://github.com/rust-lang/rust/pull/72445/ [72486]: https://github.com/rust-lang/rust/pull/72486/ [72493]: https://github.com/rust-lang/rust/pull/72493/ [72331]: https://github.com/rust-lang/rust/pull/72331/ [71896]: https://github.com/rust-lang/rust/pull/71896/ [71660]: https://github.com/rust-lang/rust/pull/71660/ [71322]: https://github.com/rust-lang/rust/pull/71322/ [70740]: https://github.com/rust-lang/rust/pull/70740/ [cargo/8270]: https://github.com/rust-lang/cargo/pull/8270/ [cargo/8325]: https://github.com/rust-lang/cargo/pull/8325/ [cargo/8387]: https://github.com/rust-lang/cargo/pull/8387/ [`Option::zip`]: https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.zip [`vec::Drain::as_slice`]: https://doc.rust-lang.org/stable/std/vec/struct.Drain.html#method.as_slice Version 1.45.2 (2020-08-03) ========================== * [Fix bindings in tuple struct patterns][74954] * [Fix track_caller integration with trait objects][74784] [74954]: https://github.com/rust-lang/rust/issues/74954 [74784]: https://github.com/rust-lang/rust/issues/74784 Version 1.45.1 (2020-07-30) ========================== * [Fix const propagation with references.][73613] * [rustfmt accepts rustfmt_skip in cfg_attr again.][73078] * [Avoid spurious implicit region bound.][74509] * [Install clippy on x.py install][74457] [73613]: https://github.com/rust-lang/rust/pull/73613 [73078]: https://github.com/rust-lang/rust/issues/73078 [74509]: https://github.com/rust-lang/rust/pull/74509 [74457]: https://github.com/rust-lang/rust/pull/74457 Version 1.45.0 (2020-07-16) ========================== Language -------- - [Out of range float to int conversions using `as` has been defined as a saturating conversion.][71269] This was previously undefined behaviour, but you can use the `{f64, f32}::to_int_unchecked` methods to continue using the current behaviour, which may be desirable in rare performance sensitive situations. - [`mem::Discriminant<T>` now uses `T`'s discriminant type instead of always using `u64`.][70705] - [Function like procedural macros can now be used in expression, pattern, and statement positions.][68717] This means you can now use a function-like procedural macro anywhere you can use a declarative (`macro_rules!`) macro. Compiler -------- - [You can now override individual target features through the `target-feature` flag.][72094] E.g. `-C target-feature=+avx2 -C target-feature=+fma` is now equivalent to `-C target-feature=+avx2,+fma`. - [Added the `force-unwind-tables` flag.][69984] This option allows rustc to always generate unwind tables regardless of panic strategy. - [Added the `embed-bitcode` flag.][71716] This codegen flag allows rustc to include LLVM bitcode into generated `rlib`s (this is on by default). - [Added the `tiny` value to the `code-model` codegen flag.][72397] - [Added tier 3 support\* for the `mipsel-sony-psp` target.][72062] - [Added tier 3 support for the `thumbv7a-uwp-windows-msvc` target.][72133] - [Upgraded to LLVM 10.][67759] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [`net::{SocketAddr, SocketAddrV4, SocketAddrV6}` now implements `PartialOrd` and `Ord`.][72239] - [`proc_macro::TokenStream` now implements `Default`.][72234] - [You can now use `char` with `ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo}` to iterate over a range of codepoints.][72413] E.g. you can now write the following; ```rust for ch in 'a'..='z' { print!("{}", ch); } println!(); // Prints "abcdefghijklmnopqrstuvwxyz" ``` - [`OsString` now implements `FromStr`.][71662] - [The `saturating_neg` method has been added to all signed integer primitive types, and the `saturating_abs` method has been added for all integer primitive types.][71886] - [`Arc<T>`, `Rc<T>` now implement `From<Cow<'_, T>>`, and `Box` now implements `From<Cow>` when `T` is `[T: Copy]`, `str`, `CStr`, `OsStr`, or `Path`.][71447] - [`Box<[T]>` now implements `From<[T; N]>`.][71095] - [`BitOr` and `BitOrAssign` are implemented for all `NonZero` integer types.][69813] - [The `fetch_min`, and `fetch_max` methods have been added to all atomic integer types.][72324] - [The `fetch_update` method has been added to all atomic integer types.][71843] Stabilized APIs --------------- - [`Arc::as_ptr`] - [`BTreeMap::remove_entry`] - [`Rc::as_ptr`] - [`rc::Weak::as_ptr`] - [`rc::Weak::from_raw`] - [`rc::Weak::into_raw`] - [`str::strip_prefix`] - [`str::strip_suffix`] - [`sync::Weak::as_ptr`] - [`sync::Weak::from_raw`] - [`sync::Weak::into_raw`] - [`char::UNICODE_VERSION`] - [`Span::resolved_at`] - [`Span::located_at`] - [`Span::mixed_site`] - [`unix::process::CommandExt::arg0`] Cargo ----- - [Cargo uses the `embed-bitcode` flag to optimize disk usage and build time.][cargo/8066] Misc ---- - [Rustdoc now supports strikethrough text in Markdown.][71928] E.g. `~~outdated information~~` becomes "~~outdated information~~". - [Added an emoji to Rustdoc's deprecated API message.][72014] Compatibility Notes ------------------- - [Trying to self initialize a static value (that is creating a value using itself) is unsound and now causes a compile error.][71140] - [`{f32, f64}::powi` now returns a slightly different value on Windows.][73420] This is due to changes in LLVM's intrinsics which `{f32, f64}::powi` uses. - [Rustdoc's CLI's extra error exit codes have been removed.][71900] These were previously undocumented and not intended for public use. Rustdoc still provides a non-zero exit code on errors. - [Rustc's `lto` flag is incompatible with the new `embed-bitcode=no`.][71848] This may cause issues if LTO is enabled through `RUSTFLAGS` or `cargo rustc` flags while cargo is adding `embed-bitcode` itself. The recommended way to control LTO is with Cargo profiles, either in `Cargo.toml` or `.cargo/config`, or by setting `CARGO_PROFILE_<name>_LTO` in the environment. Internals Only -------------- - [Make clippy a git subtree instead of a git submodule][70655] - [Unify the undo log of all snapshot types][69464] [71848]: https://github.com/rust-lang/rust/issues/71848/ [73420]: https://github.com/rust-lang/rust/issues/73420/ [72324]: https://github.com/rust-lang/rust/pull/72324/ [71843]: https://github.com/rust-lang/rust/pull/71843/ [71886]: https://github.com/rust-lang/rust/pull/71886/ [72234]: https://github.com/rust-lang/rust/pull/72234/ [72239]: https://github.com/rust-lang/rust/pull/72239/ [72397]: https://github.com/rust-lang/rust/pull/72397/ [72413]: https://github.com/rust-lang/rust/pull/72413/ [72014]: https://github.com/rust-lang/rust/pull/72014/ [72062]: https://github.com/rust-lang/rust/pull/72062/ [72094]: https://github.com/rust-lang/rust/pull/72094/ [72133]: https://github.com/rust-lang/rust/pull/72133/ [67759]: https://github.com/rust-lang/rust/pull/67759/ [71900]: https://github.com/rust-lang/rust/pull/71900/ [71928]: https://github.com/rust-lang/rust/pull/71928/ [71662]: https://github.com/rust-lang/rust/pull/71662/ [71716]: https://github.com/rust-lang/rust/pull/71716/ [71447]: https://github.com/rust-lang/rust/pull/71447/ [71269]: https://github.com/rust-lang/rust/pull/71269/ [71095]: https://github.com/rust-lang/rust/pull/71095/ [71140]: https://github.com/rust-lang/rust/pull/71140/ [70655]: https://github.com/rust-lang/rust/pull/70655/ [70705]: https://github.com/rust-lang/rust/pull/70705/ [69984]: https://github.com/rust-lang/rust/pull/69984/ [69813]: https://github.com/rust-lang/rust/pull/69813/ [69464]: https://github.com/rust-lang/rust/pull/69464/ [68717]: https://github.com/rust-lang/rust/pull/68717/ [cargo/8066]: https://github.com/rust-lang/cargo/pull/8066 [`Arc::as_ptr`]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#method.as_ptr [`BTreeMap::remove_entry`]: https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html#method.remove_entry [`Rc::as_ptr`]: https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#method.as_ptr [`rc::Weak::as_ptr`]: https://doc.rust-lang.org/stable/std/rc/struct.Weak.html#method.as_ptr [`rc::Weak::from_raw`]: https://doc.rust-lang.org/stable/std/rc/struct.Weak.html#method.from_raw [`rc::Weak::into_raw`]: https://doc.rust-lang.org/stable/std/rc/struct.Weak.html#method.into_raw [`sync::Weak::as_ptr`]: https://doc.rust-lang.org/stable/std/sync/struct.Weak.html#method.as_ptr [`sync::Weak::from_raw`]: https://doc.rust-lang.org/stable/std/sync/struct.Weak.html#method.from_raw [`sync::Weak::into_raw`]: https://doc.rust-lang.org/stable/std/sync/struct.Weak.html#method.into_raw [`str::strip_prefix`]: https://doc.rust-lang.org/stable/std/primitive.str.html#method.strip_prefix [`str::strip_suffix`]: https://doc.rust-lang.org/stable/std/primitive.str.html#method.strip_suffix [`char::UNICODE_VERSION`]: https://doc.rust-lang.org/stable/std/char/constant.UNICODE_VERSION.html [`Span::resolved_at`]: https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.resolved_at [`Span::located_at`]: https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.located_at [`Span::mixed_site`]: https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.mixed_site [`unix::process::CommandExt::arg0`]: https://doc.rust-lang.org/std/os/unix/process/trait.CommandExt.html#tymethod.arg0 Version 1.44.1 (2020-06-18) =========================== * [rustfmt accepts rustfmt_skip in cfg_attr again.][73078] * [Don't hash executable filenames on apple platforms, fixing backtraces.][cargo/8329] * [Fix crashes when finding backtrace on macOS.][71397] * [Clippy applies lint levels into different files.][clippy/5356] [71397]: https://github.com/rust-lang/rust/issues/71397 [73078]: https://github.com/rust-lang/rust/issues/73078 [cargo/8329]: https://github.com/rust-lang/cargo/pull/8329 [clippy/5356]: https://github.com/rust-lang/rust-clippy/issues/5356 Version 1.44.0 (2020-06-04) ========================== Language -------- - [You can now use `async/.await` with `#[no_std]` enabled.][69033] - [Added the `unused_braces` lint.][70081] **Syntax-only changes** - [Expansion-driven outline module parsing][69838] ```rust #[cfg(FALSE)] mod foo { mod bar { mod baz; // `foo/bar/baz.rs` doesn't exist, but no error! } } ``` These are still rejected semantically, so you will likely receive an error but these changes can be seen and parsed by macros and conditional compilation. Compiler -------- - [Rustc now respects the `-C codegen-units` flag in incremental mode.][70156] Additionally when in incremental mode rustc defaults to 256 codegen units. - [Refactored `catch_unwind` to have zero-cost, unless unwinding is enabled and a panic is thrown.][67502] - [Added tier 3\* support for the `aarch64-unknown-none` and `aarch64-unknown-none-softfloat` targets.][68334] - [Added tier 3 support for `arm64-apple-tvos` and `x86_64-apple-tvos` targets.][68191] Libraries --------- - [Special cased `vec![]` to map directly to `Vec::new()`.][70632] This allows `vec![]` to be able to be used in `const` contexts. - [`convert::Infallible` now implements `Hash`.][70281] - [`OsString` now implements `DerefMut` and `IndexMut` returning a `&mut OsStr`.][70048] - [Unicode 13 is now supported.][69929] - [`String` now implements `From<&mut str>`.][69661] - [`IoSlice` now implements `Copy`.][69403] - [`Vec<T>` now implements `From<[T; N]>`.][68692] Where `N` is at most 32. - [`proc_macro::LexError` now implements `fmt::Display` and `Error`.][68899] - [`from_le_bytes`, `to_le_bytes`, `from_be_bytes`, `to_be_bytes`, `from_ne_bytes`, and `to_ne_bytes` methods are now `const` for all integer types.][69373] Stabilized APIs --------------- - [`PathBuf::with_capacity`] - [`PathBuf::capacity`] - [`PathBuf::clear`] - [`PathBuf::reserve`] - [`PathBuf::reserve_exact`] - [`PathBuf::shrink_to_fit`] - [`f32::to_int_unchecked`] - [`f64::to_int_unchecked`] - [`Layout::align_to`] - [`Layout::pad_to_align`] - [`Layout::array`] - [`Layout::extend`] Cargo ----- - [Added the `cargo tree` command which will print a tree graph of your dependencies.][cargo/8062] E.g. ``` mdbook v0.3.2 (/Users/src/rust/mdbook) ├── ammonia v3.0.0 │ ├── html5ever v0.24.0 │ │ ├── log v0.4.8 │ │ │ └── cfg-if v0.1.9 │ │ ├── mac v0.1.1 │ │ └── markup5ever v0.9.0 │ │ ├── log v0.4.8 (*) │ │ ├── phf v0.7.24 │ │ │ └── phf_shared v0.7.24 │ │ │ ├── siphasher v0.2.3 │ │ │ └── unicase v1.4.2 │ │ │ [build-dependencies] │ │ │ └── version_check v0.1.5 ... ``` You can also display dependencies on multiple versions of the same crate with `cargo tree -d` (short for `cargo tree --duplicates`). Misc ---- - [Rustdoc now allows you to specify `--crate-version` to have rustdoc include the version in the sidebar.][69494] Compatibility Notes ------------------- - [Rustc now correctly generates static libraries on Windows GNU targets with the `.a` extension, rather than the previous `.lib`.][70937] - [Removed the `-C no_integrated_as` flag from rustc.][70345] - [The `file_name` property in JSON output of macro errors now points the actual source file rather than the previous format of `<NAME macros>`.][70969] **Note:** this may not point to a file that actually exists on the user's system. - [The minimum required external LLVM version has been bumped to LLVM 8.][71147] - [`mem::{zeroed, uninitialised}` will now panic when used with types that do not allow zero initialization such as `NonZeroU8`.][66059] This was previously a warning. - [In 1.45.0 (the next release) converting a `f64` to `u32` using the `as` operator has been defined as a saturating operation.][71269] This was previously undefined behaviour, but you can use the `{f64, f32}::to_int_unchecked` methods to continue using the current behaviour, which may be desirable in rare performance sensitive situations. Internal Only ------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. - [dep_graph Avoid allocating a set on when the number reads are small.][69778] - [Replace big JS dict with JSON parsing.][71250] [69373]: https://github.com/rust-lang/rust/pull/69373/ [66059]: https://github.com/rust-lang/rust/pull/66059/ [68191]: https://github.com/rust-lang/rust/pull/68191/ [68899]: https://github.com/rust-lang/rust/pull/68899/ [71147]: https://github.com/rust-lang/rust/pull/71147/ [71250]: https://github.com/rust-lang/rust/pull/71250/ [70937]: https://github.com/rust-lang/rust/pull/70937/ [70969]: https://github.com/rust-lang/rust/pull/70969/ [70632]: https://github.com/rust-lang/rust/pull/70632/ [70281]: https://github.com/rust-lang/rust/pull/70281/ [70345]: https://github.com/rust-lang/rust/pull/70345/ [70048]: https://github.com/rust-lang/rust/pull/70048/ [70081]: https://github.com/rust-lang/rust/pull/70081/ [70156]: https://github.com/rust-lang/rust/pull/70156/ [71269]: https://github.com/rust-lang/rust/pull/71269/ [69838]: https://github.com/rust-lang/rust/pull/69838/ [69929]: https://github.com/rust-lang/rust/pull/69929/ [69661]: https://github.com/rust-lang/rust/pull/69661/ [69778]: https://github.com/rust-lang/rust/pull/69778/ [69494]: https://github.com/rust-lang/rust/pull/69494/ [69403]: https://github.com/rust-lang/rust/pull/69403/ [69033]: https://github.com/rust-lang/rust/pull/69033/ [68692]: https://github.com/rust-lang/rust/pull/68692/ [68334]: https://github.com/rust-lang/rust/pull/68334/ [67502]: https://github.com/rust-lang/rust/pull/67502/ [cargo/8062]: https://github.com/rust-lang/cargo/pull/8062/ [`PathBuf::with_capacity`]: https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.with_capacity [`PathBuf::capacity`]: https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.capacity [`PathBuf::clear`]: https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.clear [`PathBuf::reserve`]: https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.reserve [`PathBuf::reserve_exact`]: https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.reserve_exact [`PathBuf::shrink_to_fit`]: https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.shrink_to_fit [`f32::to_int_unchecked`]: https://doc.rust-lang.org/std/primitive.f32.html#method.to_int_unchecked [`f64::to_int_unchecked`]: https://doc.rust-lang.org/std/primitive.f64.html#method.to_int_unchecked [`Layout::align_to`]: https://doc.rust-lang.org/std/alloc/struct.Layout.html#method.align_to [`Layout::pad_to_align`]: https://doc.rust-lang.org/std/alloc/struct.Layout.html#method.pad_to_align [`Layout::array`]: https://doc.rust-lang.org/std/alloc/struct.Layout.html#method.array [`Layout::extend`]: https://doc.rust-lang.org/std/alloc/struct.Layout.html#method.extend Version 1.43.1 (2020-05-07) =========================== * [Updated openssl-src to 1.1.1g for CVE-2020-1967.][71430] * [Fixed the stabilization of AVX-512 features.][71473] * [Fixed `cargo package --list` not working with unpublished dependencies.][cargo/8151] [71430]: https://github.com/rust-lang/rust/pull/71430 [71473]: https://github.com/rust-lang/rust/issues/71473 [cargo/8151]: https://github.com/rust-lang/cargo/issues/8151 Version 1.43.0 (2020-04-23) ========================== Language -------- - [Fixed using binary operations with `&{number}` (e.g. `&1.0`) not having the type inferred correctly.][68129] - [Attributes such as `#[cfg()]` can now be used on `if` expressions.][69201] **Syntax only changes** - [Allow `type Foo: Ord` syntactically.][69361] - [Fuse associated and extern items up to defaultness.][69194] - [Syntactically allow `self` in all `fn` contexts.][68764] - [Merge `fn` syntax + cleanup item parsing.][68728] - [`item` macro fragments can be interpolated into `trait`s, `impl`s, and `extern` blocks.][69366] For example, you may now write: ```rust macro_rules! mac_trait { ($i:item) => { trait T { $i } } } mac_trait! { fn foo() {} } ``` These are still rejected *semantically*, so you will likely receive an error but these changes can be seen and parsed by macros and conditional compilation. Compiler -------- - [You can now pass multiple lint flags to rustc to override the previous flags.][67885] For example; `rustc -D unused -A unused-variables` denies everything in the `unused` lint group except `unused-variables` which is explicitly allowed. However, passing `rustc -A unused-variables -D unused` denies everything in the `unused` lint group **including** `unused-variables` since the allow flag is specified before the deny flag (and therefore overridden). - [rustc will now prefer your system MinGW libraries over its bundled libraries if they are available on `windows-gnu`.][67429] - [rustc now buffers errors/warnings printed in JSON.][69227] Libraries --------- - [`Arc<[T; N]>`, `Box<[T; N]>`, and `Rc<[T; N]>`, now implement `TryFrom<Arc<[T]>>`,`TryFrom<Box<[T]>>`, and `TryFrom<Rc<[T]>>` respectively.][69538] **Note** These conversions are only available when `N` is `0..=32`. - [You can now use associated constants on floats and integers directly, rather than having to import the module.][68952] e.g. You can now write `u32::MAX` or `f32::NAN` with no imports. - [`u8::is_ascii` is now `const`.][68984] - [`String` now implements `AsMut<str>`.][68742] - [Added the `primitive` module to `std` and `core`.][67637] This module reexports Rust's primitive types. This is mainly useful in macros where you want avoid these types being shadowed. - [Relaxed some of the trait bounds on `HashMap` and `HashSet`.][67642] - [`string::FromUtf8Error` now implements `Clone + Eq`.][68738] Stabilized APIs --------------- - [`Once::is_completed`] - [`f32::LOG10_2`] - [`f32::LOG2_10`] - [`f64::LOG10_2`] - [`f64::LOG2_10`] - [`iter::once_with`] Cargo ----- - [You can now set config `[profile]`s in your `.cargo/config`, or through your environment.][cargo/7823] - [Cargo will now set `CARGO_BIN_EXE_<name>` pointing to a binary's executable path when running integration tests or benchmarks.][cargo/7697] `<name>` is the name of your binary as-is e.g. If you wanted the executable path for a binary named `my-program`you would use `env!("CARGO_BIN_EXE_my-program")`. Misc ---- - [Certain checks in the `const_err` lint were deemed unrelated to const evaluation][69185], and have been moved to the `unconditional_panic` and `arithmetic_overflow` lints. Compatibility Notes ------------------- - [Having trailing syntax in the `assert!` macro is now a hard error.][69548] This has been a warning since 1.36.0. - [Fixed `Self` not having the correctly inferred type.][69340] This incorrectly led to some instances being accepted, and now correctly emits a hard error. [69340]: https://github.com/rust-lang/rust/pull/69340 Internal Only ------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of `rustc` and related tools. - [All components are now built with `opt-level=3` instead of `2`.][67878] - [Improved how rustc generates drop code.][67332] - [Improved performance from `#[inline]`-ing certain hot functions.][69256] - [traits: preallocate 2 Vecs of known initial size][69022] - [Avoid exponential behaviour when relating types][68772] - [Skip `Drop` terminators for enum variants without drop glue][68943] - [Improve performance of coherence checks][68966] - [Deduplicate types in the generator witness][68672] - [Invert control in struct_lint_level.][68725] [67332]: https://github.com/rust-lang/rust/pull/67332/ [67429]: https://github.com/rust-lang/rust/pull/67429/ [67637]: https://github.com/rust-lang/rust/pull/67637/ [67642]: https://github.com/rust-lang/rust/pull/67642/ [67878]: https://github.com/rust-lang/rust/pull/67878/ [67885]: https://github.com/rust-lang/rust/pull/67885/ [68129]: https://github.com/rust-lang/rust/pull/68129/ [68672]: https://github.com/rust-lang/rust/pull/68672/ [68725]: https://github.com/rust-lang/rust/pull/68725/ [68728]: https://github.com/rust-lang/rust/pull/68728/ [68738]: https://github.com/rust-lang/rust/pull/68738/ [68742]: https://github.com/rust-lang/rust/pull/68742/ [68764]: https://github.com/rust-lang/rust/pull/68764/ [68772]: https://github.com/rust-lang/rust/pull/68772/ [68943]: https://github.com/rust-lang/rust/pull/68943/ [68952]: https://github.com/rust-lang/rust/pull/68952/ [68966]: https://github.com/rust-lang/rust/pull/68966/ [68984]: https://github.com/rust-lang/rust/pull/68984/ [69022]: https://github.com/rust-lang/rust/pull/69022/ [69185]: https://github.com/rust-lang/rust/pull/69185/ [69194]: https://github.com/rust-lang/rust/pull/69194/ [69201]: https://github.com/rust-lang/rust/pull/69201/ [69227]: https://github.com/rust-lang/rust/pull/69227/ [69548]: https://github.com/rust-lang/rust/pull/69548/ [69256]: https://github.com/rust-lang/rust/pull/69256/ [69361]: https://github.com/rust-lang/rust/pull/69361/ [69366]: https://github.com/rust-lang/rust/pull/69366/ [69538]: https://github.com/rust-lang/rust/pull/69538/ [cargo/7823]: https://github.com/rust-lang/cargo/pull/7823 [cargo/7697]: https://github.com/rust-lang/cargo/pull/7697 [`Once::is_completed`]: https://doc.rust-lang.org/std/sync/struct.Once.html#method.is_completed [`f32::LOG10_2`]: https://doc.rust-lang.org/std/f32/consts/constant.LOG10_2.html [`f32::LOG2_10`]: https://doc.rust-lang.org/std/f32/consts/constant.LOG2_10.html [`f64::LOG10_2`]: https://doc.rust-lang.org/std/f64/consts/constant.LOG10_2.html [`f64::LOG2_10`]: https://doc.rust-lang.org/std/f64/consts/constant.LOG2_10.html [`iter::once_with`]: https://doc.rust-lang.org/std/iter/fn.once_with.html Version 1.42.0 (2020-03-12) ========================== Language -------- - [You can now use the slice pattern syntax with subslices.][67712] e.g. ```rust fn foo(words: &[&str]) { match words { ["Hello", "World", "!", ..] => println!("Hello World!"), ["Foo", "Bar", ..] => println!("Baz"), rest => println!("{:?}", rest), } } ``` - [You can now use `#[repr(transparent)]` on univariant `enum`s.][68122] Meaning that you can create an enum that has the exact layout and ABI of the type it contains. - [You can now use outer attribute procedural macros on inline modules.][64273] - [There are some *syntax-only* changes:][67131] - `default` is syntactically allowed before items in `trait` definitions. - Items in `impl`s (i.e. `const`s, `type`s, and `fn`s) may syntactically leave out their bodies in favor of `;`. - Bounds on associated types in `impl`s are now syntactically allowed (e.g. `type Foo: Ord;`). - `...` (the C-variadic type) may occur syntactically directly as the type of any function parameter. These are still rejected *semantically*, so you will likely receive an error but these changes can be seen and parsed by procedural macros and conditional compilation. Compiler -------- - [Added tier 2\* support for `armv7a-none-eabi`.][68253] - [Added tier 2 support for `riscv64gc-unknown-linux-gnu`.][68339] - [`Option::{expect,unwrap}` and `Result::{expect, expect_err, unwrap, unwrap_err}` now produce panic messages pointing to the location where they were called, rather than `core`'s internals. ][67887] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [`iter::Empty<T>` now implements `Send` and `Sync` for any `T`.][68348] - [`Pin::{map_unchecked, map_unchecked_mut}` no longer require the return type to implement `Sized`.][67935] - [`io::Cursor` now derives `PartialEq` and `Eq`.][67233] - [`Layout::new` is now `const`.][66254] - [Added Standard Library support for `riscv64gc-unknown-linux-gnu`.][66899] Stabilized APIs --------------- - [`CondVar::wait_while`] - [`CondVar::wait_timeout_while`] - [`DebugMap::key`] - [`DebugMap::value`] - [`ManuallyDrop::take`] - [`matches!`] - [`ptr::slice_from_raw_parts_mut`] - [`ptr::slice_from_raw_parts`] Cargo ----- - [You no longer need to include `extern crate proc_macro;` to be able to `use proc_macro;` in the `2018` edition.][cargo/7700] Compatibility Notes ------------------- - [`Error::description` has been deprecated, and its use will now produce a warning.][66919] It's recommended to use `Display`/`to_string` instead. [68253]: https://github.com/rust-lang/rust/pull/68253/ [68348]: https://github.com/rust-lang/rust/pull/68348/ [67935]: https://github.com/rust-lang/rust/pull/67935/ [68339]: https://github.com/rust-lang/rust/pull/68339/ [68122]: https://github.com/rust-lang/rust/pull/68122/ [64273]: https://github.com/rust-lang/rust/pull/64273/ [67712]: https://github.com/rust-lang/rust/pull/67712/ [67887]: https://github.com/rust-lang/rust/pull/67887/ [67131]: https://github.com/rust-lang/rust/pull/67131/ [67233]: https://github.com/rust-lang/rust/pull/67233/ [66899]: https://github.com/rust-lang/rust/pull/66899/ [66919]: https://github.com/rust-lang/rust/pull/66919/ [66254]: https://github.com/rust-lang/rust/pull/66254/ [cargo/7700]: https://github.com/rust-lang/cargo/pull/7700 [`DebugMap::key`]: https://doc.rust-lang.org/stable/std/fmt/struct.DebugMap.html#method.key [`DebugMap::value`]: https://doc.rust-lang.org/stable/std/fmt/struct.DebugMap.html#method.value [`ManuallyDrop::take`]: https://doc.rust-lang.org/stable/std/mem/struct.ManuallyDrop.html#method.take [`matches!`]: https://doc.rust-lang.org/stable/std/macro.matches.html [`ptr::slice_from_raw_parts_mut`]: https://doc.rust-lang.org/stable/std/ptr/fn.slice_from_raw_parts_mut.html [`ptr::slice_from_raw_parts`]: https://doc.rust-lang.org/stable/std/ptr/fn.slice_from_raw_parts.html [`CondVar::wait_while`]: https://doc.rust-lang.org/stable/std/sync/struct.Condvar.html#method.wait_while [`CondVar::wait_timeout_while`]: https://doc.rust-lang.org/stable/std/sync/struct.Condvar.html#method.wait_timeout_while Version 1.41.1 (2020-02-27) =========================== * [Always check types of static items][69145] * [Always check lifetime bounds of `Copy` impls][69145] * [Fix miscompilation in callers of `Layout::repeat`][69225] * [Rust 1.41.0 was announced as the last Rust release with tier 1 or tier 2 support for 32-bit Apple targets][apple-32bit-drop]. That announcement did not expect a patch release. 1.41.1 also includes release binaries for these targets. [69225]: https://github.com/rust-lang/rust/issues/69225 [69145]: https://github.com/rust-lang/rust/pull/69145 Version 1.41.0 (2020-01-30) =========================== Language -------- - [You can now pass type parameters to foreign items when implementing traits.][65879] E.g. You can now write `impl<T> From<Foo> for Vec<T> {}`. - [You can now arbitrarily nest receiver types in the `self` position.][64325] E.g. you can now write `fn foo(self: Box<Box<Self>>) {}`. Previously only `Self`, `&Self`, `&mut Self`, `Arc<Self>`, `Rc<Self>`, and `Box<Self>` were allowed. - [You can now use any valid identifier in a `format_args` macro.][66847] Previously identifiers starting with an underscore were not allowed. - [Visibility modifiers (e.g. `pub`) are now syntactically allowed on trait items and enum variants.][66183] These are still rejected semantically, but can be seen and parsed by procedural macros and conditional compilation. - [You can now define a Rust `extern "C"` function with `Box<T>` and use `T*` as the corresponding type on the C side.][62514] Please see [the documentation][box-memory-layout] for more information, including the important caveat about preferring to avoid `Box<T>` in Rust signatures for functions defined in C. [box-memory-layout]: https://doc.rust-lang.org/std/boxed/index.html#memory-layout Compiler -------- - [Rustc will now warn if you have unused loop `'label`s.][66325] - [Removed support for the `i686-unknown-dragonfly` target.][67255] - [Added tier 3 support\* for the `riscv64gc-unknown-linux-gnu` target.][66661] - [You can now pass an arguments file passing the `@path` syntax to rustc.][66172] Note that the format differs somewhat from what is found in other tooling; please see [the documentation][argfile-docs] for more information. - [You can now provide `--extern` flag without a path, indicating that it is available from the search path or specified with an `-L` flag.][64882] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. [argfile-docs]: https://doc.rust-lang.org/nightly/rustc/command-line-arguments.html#path-load-command-line-flags-from-a-path Libraries --------- - [The `core::panic` module is now stable.][66771] It was already stable through `std`. - [`NonZero*` numerics now implement `From<NonZero*>` if it's a smaller integer width.][66277] E.g. `NonZeroU16` now implements `From<NonZeroU8>`. - [`MaybeUninit<T>` now implements `fmt::Debug`.][65013] Stabilized APIs --------------- - [`Result::map_or`] - [`Result::map_or_else`] - [`std::rc::Weak::weak_count`] - [`std::rc::Weak::strong_count`] - [`std::sync::Weak::weak_count`] - [`std::sync::Weak::strong_count`] Cargo ----- - [Cargo will now document all the private items for binary crates by default.][cargo/7593] - [`cargo-install` will now reinstall the package if it detects that it is out of date.][cargo/7560] - [Cargo.lock now uses a more git friendly format that should help to reduce merge conflicts.][cargo/7579] - [You can now override specific dependencies's build settings][cargo/7591] E.g. `[profile.dev.package.image] opt-level = 2` sets the `image` crate's optimisation level to `2` for debug builds. You can also use `[profile.<profile>.build-override]` to override build scripts and their dependencies. Misc ---- - [You can now specify `edition` in documentation code blocks to compile the block for that edition.][66238] E.g. `edition2018` tells rustdoc that the code sample should be compiled the 2018 edition of Rust. - [You can now provide custom themes to rustdoc with `--theme`, and check the current theme with `--check-theme`.][54733] - [You can use `#[cfg(doc)]` to compile an item when building documentation.][61351] Compatibility Notes ------------------- - [As previously announced 1.41 will be the last tier 1 release for 32-bit Apple targets.][apple-32bit-drop] This means that the source code is still available to build, but the targets are no longer being tested and release binaries for those platforms will no longer be distributed by the Rust project. Please refer to the linked blog post for more information. [54733]: https://github.com/rust-lang/rust/pull/54733/ [61351]: https://github.com/rust-lang/rust/pull/61351/ [62514]: https://github.com/rust-lang/rust/pull/62514/ [67255]: https://github.com/rust-lang/rust/pull/67255/ [66661]: https://github.com/rust-lang/rust/pull/66661/ [66771]: https://github.com/rust-lang/rust/pull/66771/ [66847]: https://github.com/rust-lang/rust/pull/66847/ [66238]: https://github.com/rust-lang/rust/pull/66238/ [66277]: https://github.com/rust-lang/rust/pull/66277/ [66325]: https://github.com/rust-lang/rust/pull/66325/ [66172]: https://github.com/rust-lang/rust/pull/66172/ [66183]: https://github.com/rust-lang/rust/pull/66183/ [65879]: https://github.com/rust-lang/rust/pull/65879/ [65013]: https://github.com/rust-lang/rust/pull/65013/ [64882]: https://github.com/rust-lang/rust/pull/64882/ [64325]: https://github.com/rust-lang/rust/pull/64325/ [cargo/7560]: https://github.com/rust-lang/cargo/pull/7560/ [cargo/7579]: https://github.com/rust-lang/cargo/pull/7579/ [cargo/7591]: https://github.com/rust-lang/cargo/pull/7591/ [cargo/7593]: https://github.com/rust-lang/cargo/pull/7593/ [`Result::map_or_else`]: https://doc.rust-lang.org/std/result/enum.Result.html#method.map_or_else [`Result::map_or`]: https://doc.rust-lang.org/std/result/enum.Result.html#method.map_or [`std::rc::Weak::weak_count`]: https://doc.rust-lang.org/std/rc/struct.Weak.html#method.weak_count [`std::rc::Weak::strong_count`]: https://doc.rust-lang.org/std/rc/struct.Weak.html#method.strong_count [`std::sync::Weak::weak_count`]: https://doc.rust-lang.org/std/sync/struct.Weak.html#method.weak_count [`std::sync::Weak::strong_count`]: https://doc.rust-lang.org/std/sync/struct.Weak.html#method.strong_count [apple-32bit-drop]: https://blog.rust-lang.org/2020/01/03/reducing-support-for-32-bit-apple-targets.html Version 1.40.0 (2019-12-19) =========================== Language -------- - [You can now use tuple `struct`s and tuple `enum` variant's constructors in `const` contexts.][65188] e.g. ```rust pub struct Point(i32, i32); const ORIGIN: Point = { let constructor = Point; constructor(0, 0) }; ``` - [You can now mark `struct`s, `enum`s, and `enum` variants with the `#[non_exhaustive]` attribute to indicate that there may be variants or fields added in the future.][64639] For example this requires adding a wild-card branch (`_ => {}`) to any match statements on a non-exhaustive `enum`. [(RFC 2008)] - [You can now use function-like procedural macros in `extern` blocks and in type positions.][63931] e.g. `type Generated = macro!();` - [Function-like and attribute procedural macros can now emit `macro_rules!` items, so you can now have your macros generate macros.][64035] - [The `meta` pattern matcher in `macro_rules!` now correctly matches the modern attribute syntax.][63674] For example `(#[$m:meta])` now matches `#[attr]`, `#[attr{tokens}]`, `#[attr[tokens]]`, and `#[attr(tokens)]`. Compiler -------- - [Added tier 3 support\* for the `thumbv7neon-unknown-linux-musleabihf` target.][66103] - [Added tier 3 support for the `aarch64-unknown-none-softfloat` target.][64589] - [Added tier 3 support for the `mips64-unknown-linux-muslabi64`, and `mips64el-unknown-linux-muslabi64` targets.][65843] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [The `is_power_of_two` method on unsigned numeric types is now a `const` function.][65092] Stabilized APIs --------------- - [`BTreeMap::get_key_value`] - [`HashMap::get_key_value`] - [`Option::as_deref_mut`] - [`Option::as_deref`] - [`Option::flatten`] - [`UdpSocket::peer_addr`] - [`f32::to_be_bytes`] - [`f32::to_le_bytes`] - [`f32::to_ne_bytes`] - [`f64::to_be_bytes`] - [`f64::to_le_bytes`] - [`f64::to_ne_bytes`] - [`f32::from_be_bytes`] - [`f32::from_le_bytes`] - [`f32::from_ne_bytes`] - [`f64::from_be_bytes`] - [`f64::from_le_bytes`] - [`f64::from_ne_bytes`] - [`mem::take`] - [`slice::repeat`] - [`todo!`] Cargo ----- - [Cargo will now always display warnings, rather than only on fresh builds.][cargo/7450] - [Feature flags (except `--all-features`) passed to a virtual workspace will now produce an error.][cargo/7507] Previously these flags were ignored. - [You can now publish `dev-dependencies` without including a `version`.][cargo/7333] Misc ---- - [You can now specify the `#[cfg(doctest)]` attribute to include an item only when running documentation tests with `rustdoc`.][63803] Compatibility Notes ------------------- - [As previously announced, any previous NLL warnings in the 2015 edition are now hard errors.][64221] - [The `include!` macro will now warn if it failed to include the entire file.][64284] The `include!` macro unintentionally only includes the first _expression_ in a file, and this can be unintuitive. This will become either a hard error in a future release, or the behavior may be fixed to include all expressions as expected. - [Using `#[inline]` on function prototypes and consts now emits a warning under `unused_attribute` lint.][65294] Using `#[inline]` anywhere else inside traits or `extern` blocks now correctly emits a hard error. [65294]: https://github.com/rust-lang/rust/pull/65294/ [66103]: https://github.com/rust-lang/rust/pull/66103/ [65843]: https://github.com/rust-lang/rust/pull/65843/ [65188]: https://github.com/rust-lang/rust/pull/65188/ [65092]: https://github.com/rust-lang/rust/pull/65092/ [64589]: https://github.com/rust-lang/rust/pull/64589/ [64639]: https://github.com/rust-lang/rust/pull/64639/ [64221]: https://github.com/rust-lang/rust/pull/64221/ [64284]: https://github.com/rust-lang/rust/pull/64284/ [63931]: https://github.com/rust-lang/rust/pull/63931/ [64035]: https://github.com/rust-lang/rust/pull/64035/ [63674]: https://github.com/rust-lang/rust/pull/63674/ [63803]: https://github.com/rust-lang/rust/pull/63803/ [cargo/7450]: https://github.com/rust-lang/cargo/pull/7450/ [cargo/7507]: https://github.com/rust-lang/cargo/pull/7507/ [cargo/7333]: https://github.com/rust-lang/cargo/pull/7333/ [(rfc 2008)]: https://rust-lang.github.io/rfcs/2008-non-exhaustive.html [`f32::to_be_bytes`]: https://doc.rust-lang.org/std/primitive.f32.html#method.to_be_bytes [`f32::to_le_bytes`]: https://doc.rust-lang.org/std/primitive.f32.html#method.to_le_bytes [`f32::to_ne_bytes`]: https://doc.rust-lang.org/std/primitive.f32.html#method.to_ne_bytes [`f64::to_be_bytes`]: https://doc.rust-lang.org/std/primitive.f64.html#method.to_be_bytes [`f64::to_le_bytes`]: https://doc.rust-lang.org/std/primitive.f64.html#method.to_le_bytes [`f64::to_ne_bytes`]: https://doc.rust-lang.org/std/primitive.f64.html#method.to_ne_bytes [`f32::from_be_bytes`]: https://doc.rust-lang.org/std/primitive.f32.html#method.from_be_bytes [`f32::from_le_bytes`]: https://doc.rust-lang.org/std/primitive.f32.html#method.from_le_bytes [`f32::from_ne_bytes`]: https://doc.rust-lang.org/std/primitive.f32.html#method.from_ne_bytes [`f64::from_be_bytes`]: https://doc.rust-lang.org/std/primitive.f64.html#method.from_be_bytes [`f64::from_le_bytes`]: https://doc.rust-lang.org/std/primitive.f64.html#method.from_le_bytes [`f64::from_ne_bytes`]: https://doc.rust-lang.org/std/primitive.f64.html#method.from_ne_bytes [`option::flatten`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.flatten [`option::as_deref`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.as_deref [`option::as_deref_mut`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.as_deref_mut [`hashmap::get_key_value`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.get_key_value [`btreemap::get_key_value`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.get_key_value [`slice::repeat`]: https://doc.rust-lang.org/std/primitive.slice.html#method.repeat [`mem::take`]: https://doc.rust-lang.org/std/mem/fn.take.html [`udpsocket::peer_addr`]: https://doc.rust-lang.org/std/net/struct.UdpSocket.html#method.peer_addr [`todo!`]: https://doc.rust-lang.org/std/macro.todo.html Version 1.39.0 (2019-11-07) =========================== Language -------- - [You can now create `async` functions and blocks with `async fn`, `async move {}`, and `async {}` respectively, and you can now call `.await` on async expressions.][63209] - [You can now use certain attributes on function, closure, and function pointer parameters.][64010] These attributes include `cfg`, `cfg_attr`, `allow`, `warn`, `deny`, `forbid` as well as inert helper attributes used by procedural macro attributes applied to items. e.g. ```rust fn len( #[cfg(windows)] slice: &[u16], #[cfg(not(windows))] slice: &[u8], ) -> usize { slice.len() } ``` - [You can now take shared references to bind-by-move patterns in the `if` guards of `match` arms.][63118] e.g. ```rust fn main() { let array: Box<[u8; 4]> = Box::new([1, 2, 3, 4]); match array { nums // ---- `nums` is bound by move. if nums.iter().sum::<u8>() == 10 // ^------ `.iter()` implicitly takes a reference to `nums`. => { drop(nums); // ----------- Legal as `nums` was bound by move and so we have ownership. } _ => unreachable!(), } } ``` Compiler -------- - [Added tier 3\* support for the `i686-unknown-uefi` target.][64334] - [Added tier 3 support for the `sparc64-unknown-openbsd` target.][63595] - [rustc will now trim code snippets in diagnostics to fit in your terminal.][63402] **Note** Cargo currently doesn't use this feature. Refer to [cargo#7315][cargo/7315] to track this feature's progress. - [You can now pass `--show-output` argument to test binaries to print the output of successful tests.][62600] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [`Vec::new` and `String::new` are now `const` functions.][64028] - [`LinkedList::new` is now a `const` function.][63684] - [`str::len`, `[T]::len` and `str::as_bytes` are now `const` functions.][63770] - [The `abs`, `wrapping_abs`, and `overflowing_abs` numeric functions are now `const`.][63786] Stabilized APIs --------------- - [`Pin::into_inner`] - [`Instant::checked_duration_since`] - [`Instant::saturating_duration_since`] Cargo ----- - [You can now publish git dependencies if supplied with a `version`.][cargo/7237] - [The `--all` flag has been renamed to `--workspace`.][cargo/7241] Using `--all` is now deprecated. Misc ---- - [You can now pass `-Clinker` to rustdoc to control the linker used for compiling doctests.][63834] Compatibility Notes ------------------- - [Code that was previously accepted by the old borrow checker, but rejected by the NLL borrow checker is now a hard error in Rust 2018.][63565] This was previously a warning, and will also become a hard error in the Rust 2015 edition in the 1.40.0 release. - [`rustdoc` now requires `rustc` to be installed and in the same directory to run tests.][63827] This should improve performance when running a large amount of doctests. - [The `try!` macro will now issue a deprecation warning.][62672] It is recommended to use the `?` operator instead. - [`asinh(-0.0)` now correctly returns `-0.0`.][63698] Previously this returned `0.0`. [62600]: https://github.com/rust-lang/rust/pull/62600/ [62672]: https://github.com/rust-lang/rust/pull/62672/ [63118]: https://github.com/rust-lang/rust/pull/63118/ [63209]: https://github.com/rust-lang/rust/pull/63209/ [63402]: https://github.com/rust-lang/rust/pull/63402/ [63565]: https://github.com/rust-lang/rust/pull/63565/ [63595]: https://github.com/rust-lang/rust/pull/63595/ [63684]: https://github.com/rust-lang/rust/pull/63684/ [63698]: https://github.com/rust-lang/rust/pull/63698/ [63770]: https://github.com/rust-lang/rust/pull/63770/ [63786]: https://github.com/rust-lang/rust/pull/63786/ [63827]: https://github.com/rust-lang/rust/pull/63827/ [63834]: https://github.com/rust-lang/rust/pull/63834/ [64010]: https://github.com/rust-lang/rust/pull/64010/ [64028]: https://github.com/rust-lang/rust/pull/64028/ [64334]: https://github.com/rust-lang/rust/pull/64334/ [cargo/7237]: https://github.com/rust-lang/cargo/pull/7237/ [cargo/7241]: https://github.com/rust-lang/cargo/pull/7241/ [cargo/7315]: https://github.com/rust-lang/cargo/pull/7315/ [`Pin::into_inner`]: https://doc.rust-lang.org/std/pin/struct.Pin.html#method.into_inner [`Instant::checked_duration_since`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.checked_duration_since [`Instant::saturating_duration_since`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.saturating_duration_since Version 1.38.0 (2019-09-26) ========================== Language -------- - [The `#[global_allocator]` attribute can now be used in submodules.][62735] - [The `#[deprecated]` attribute can now be used on macros.][62042] Compiler -------- - [Added pipelined compilation support to `rustc`.][62766] This will improve compilation times in some cases. For further information please refer to the [_"Evaluating pipelined rustc compilation"_][pipeline-internals] thread. - [Added tier 3\* support for the `aarch64-uwp-windows-msvc`, `i686-uwp-windows-gnu`, `i686-uwp-windows-msvc`, `x86_64-uwp-windows-gnu`, and `x86_64-uwp-windows-msvc` targets.][60260] - [Added tier 3 support for the `armv7-unknown-linux-gnueabi` and `armv7-unknown-linux-musleabi` targets.][63107] - [Added tier 3 support for the `hexagon-unknown-linux-musl` target.][62814] - [Added tier 3 support for the `riscv32i-unknown-none-elf` target.][62784] - [Upgraded to LLVM 9.][62592] \* Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries --------- - [`ascii::EscapeDefault` now implements `Clone` and `Display`.][63421] - [Derive macros for prelude traits (e.g. `Clone`, `Debug`, `Hash`) are now available at the same path as the trait.][63056] (e.g. The `Clone` derive macro is available at `std::clone::Clone`). This also makes all built-in macros available in `std`/`core` root. e.g. `std::include_bytes!`. - [`str::Chars` now implements `Debug`.][63000] - [`slice::{concat, connect, join}` now accepts `&[T]` in addition to `&T`.][62528] - [`*const T` and `*mut T` now implement `marker::Unpin`.][62583] - [`Arc<[T]>` and `Rc<[T]>` now implement `FromIterator<T>`.][61953] - [Added euclidean remainder and division operations (`div_euclid`, `rem_euclid`) to all numeric primitives.][61884] Additionally `checked`, `overflowing`, and `wrapping` versions are available for all integer primitives. - [`thread::AccessError` now implements `Clone`, `Copy`, `Eq`, `Error`, and `PartialEq`.][61491] - [`iter::{StepBy, Peekable, Take}` now implement `DoubleEndedIterator`.][61457] Stabilized APIs --------------- - [`<*const T>::cast`] - [`<*mut T>::cast`] - [`Duration::as_secs_f32`] - [`Duration::as_secs_f64`] - [`Duration::div_f32`] - [`Duration::div_f64`] - [`Duration::from_secs_f32`] - [`Duration::from_secs_f64`] - [`Duration::mul_f32`] - [`Duration::mul_f64`] - [`any::type_name`] Cargo ----- - [Added pipelined compilation support to `cargo`.][cargo/7143] - [You can now pass the `--features` option multiple times to enable multiple features.][cargo/7084] Rustdoc ------- - [Documentation on `pub use` statements is prepended to the documentation of the re-exported item][63048] Misc ---- - [`rustc` will now warn about some incorrect uses of `mem::{uninitialized, zeroed}` that are known to cause undefined behaviour.][63346] Compatibility Notes ------------------- - The [`x86_64-unknown-uefi` platform can not be built][62785] with rustc 1.38.0. - The [`armv7-unknown-linux-gnueabihf` platform is known to have issues][62896] with certain crates such as libc. [60260]: https://github.com/rust-lang/rust/pull/60260/ [61457]: https://github.com/rust-lang/rust/pull/61457/ [61491]: https://github.com/rust-lang/rust/pull/61491/ [61884]: https://github.com/rust-lang/rust/pull/61884/ [61953]: https://github.com/rust-lang/rust/pull/61953/ [62042]: https://github.com/rust-lang/rust/pull/62042/ [62528]: https://github.com/rust-lang/rust/pull/62528/ [62583]: https://github.com/rust-lang/rust/pull/62583/ [62735]: https://github.com/rust-lang/rust/pull/62735/ [62766]: https://github.com/rust-lang/rust/pull/62766/ [62784]: https://github.com/rust-lang/rust/pull/62784/ [62592]: https://github.com/rust-lang/rust/pull/62592/ [62785]: https://github.com/rust-lang/rust/issues/62785/ [62814]: https://github.com/rust-lang/rust/pull/62814/ [62896]: https://github.com/rust-lang/rust/issues/62896/ [63000]: https://github.com/rust-lang/rust/pull/63000/ [63056]: https://github.com/rust-lang/rust/pull/63056/ [63107]: https://github.com/rust-lang/rust/pull/63107/ [63346]: https://github.com/rust-lang/rust/pull/63346/ [63421]: https://github.com/rust-lang/rust/pull/63421/ [cargo/7084]: https://github.com/rust-lang/cargo/pull/7084/ [cargo/7143]: https://github.com/rust-lang/cargo/pull/7143/ [63048]: https://github.com/rust-lang/rust/pull/63048 [`<*const T>::cast`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.cast [`<*mut T>::cast`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.cast [`Duration::as_secs_f32`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.as_secs_f32 [`Duration::as_secs_f64`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.as_secs_f64 [`Duration::div_f32`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.div_f32 [`Duration::div_f64`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.div_f64 [`Duration::from_secs_f32`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.from_secs_f32 [`Duration::from_secs_f64`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.from_secs_f64 [`Duration::mul_f32`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.mul_f32 [`Duration::mul_f64`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.mul_f64 [`any::type_name`]: https://doc.rust-lang.org/std/any/fn.type_name.html [platform-support-doc]: https://doc.rust-lang.org/nightly/rustc/platform-support.html [pipeline-internals]: https://internals.rust-lang.org/t/evaluating-pipelined-rustc-compilation/10199 Version 1.37.0 (2019-08-15) ========================== Language -------- - `#[must_use]` will now warn if the type is contained in a [tuple][61100], [`Box`][62228], or an [array][62235] and unused. - [You can now use the `cfg` and `cfg_attr` attributes on generic parameters.][61547] - [You can now use enum variants through type alias.][61682] e.g. You can write the following: ```rust type MyOption = Option<u8>; fn increment_or_zero(x: MyOption) -> u8 { match x { MyOption::Some(y) => y + 1, MyOption::None => 0, } } ``` - [You can now use `_` as an identifier for consts.][61347] e.g. You can write `const _: u32 = 5;`. - [You can now use `#[repr(align(X)]` on enums.][61229] - [The `?` Kleene macro operator is now available in the 2015 edition.][60932] Compiler -------- - [You can now enable Profile-Guided Optimization with the `-C profile-generate` and `-C profile-use` flags.][61268] For more information on how to use profile guided optimization, please refer to the [rustc book][rustc-book-pgo]. - [The `rust-lldb` wrapper script should now work again.][61827] Libraries --------- - [`mem::MaybeUninit<T>` is now ABI-compatible with `T`.][61802] Stabilized APIs --------------- - [`BufReader::buffer`] - [`BufWriter::buffer`] - [`Cell::from_mut`] - [`Cell<[T]>::as_slice_of_cells`][`Cell<slice>::as_slice_of_cells`] - [`DoubleEndedIterator::nth_back`] - [`Option::xor`] - [`Wrapping::reverse_bits`] - [`i128::reverse_bits`] - [`i16::reverse_bits`] - [`i32::reverse_bits`] - [`i64::reverse_bits`] - [`i8::reverse_bits`] - [`isize::reverse_bits`] - [`slice::copy_within`] - [`u128::reverse_bits`] - [`u16::reverse_bits`] - [`u32::reverse_bits`] - [`u64::reverse_bits`] - [`u8::reverse_bits`] - [`usize::reverse_bits`] Cargo ----- - [`Cargo.lock` files are now included by default when publishing executable crates with executables.][cargo/7026] - [You can now specify `default-run="foo"` in `[package]` to specify the default executable to use for `cargo run`.][cargo/7056] Misc ---- Compatibility Notes ------------------- - [Using `...` for inclusive range patterns will now warn by default.][61342] Please transition your code to using the `..=` syntax for inclusive ranges instead. - [Using a trait object without the `dyn` will now warn by default.][61203] Please transition your code to use `dyn Trait` for trait objects instead. [62228]: https://github.com/rust-lang/rust/pull/62228/ [62235]: https://github.com/rust-lang/rust/pull/62235/ [61802]: https://github.com/rust-lang/rust/pull/61802/ [61827]: https://github.com/rust-lang/rust/pull/61827/ [61547]: https://github.com/rust-lang/rust/pull/61547/ [61682]: https://github.com/rust-lang/rust/pull/61682/ [61268]: https://github.com/rust-lang/rust/pull/61268/ [61342]: https://github.com/rust-lang/rust/pull/61342/ [61347]: https://github.com/rust-lang/rust/pull/61347/ [61100]: https://github.com/rust-lang/rust/pull/61100/ [61203]: https://github.com/rust-lang/rust/pull/61203/ [61229]: https://github.com/rust-lang/rust/pull/61229/ [60932]: https://github.com/rust-lang/rust/pull/60932/ [cargo/7026]: https://github.com/rust-lang/cargo/pull/7026/ [cargo/7056]: https://github.com/rust-lang/cargo/pull/7056/ [`BufReader::buffer`]: https://doc.rust-lang.org/std/io/struct.BufReader.html#method.buffer [`BufWriter::buffer`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html#method.buffer [`Cell::from_mut`]: https://doc.rust-lang.org/std/cell/struct.Cell.html#method.from_mut [`Cell<slice>::as_slice_of_cells`]: https://doc.rust-lang.org/std/cell/struct.Cell.html#method.as_slice_of_cells [`DoubleEndedIterator::nth_back`]: https://doc.rust-lang.org/std/iter/trait.DoubleEndedIterator.html#method.nth_back [`Option::xor`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.xor [`Wrapping::reverse_bits`]: https://doc.rust-lang.org/std/num/struct.Wrapping.html#method.reverse_bits [`i128::reverse_bits`]: https://doc.rust-lang.org/std/primitive.i128.html#method.reverse_bits [`i16::reverse_bits`]: https://doc.rust-lang.org/std/primitive.i16.html#method.reverse_bits [`i32::reverse_bits`]: https://doc.rust-lang.org/std/primitive.i32.html#method.reverse_bits [`i64::reverse_bits`]: https://doc.rust-lang.org/std/primitive.i64.html#method.reverse_bits [`i8::reverse_bits`]: https://doc.rust-lang.org/std/primitive.i8.html#method.reverse_bits [`isize::reverse_bits`]: https://doc.rust-lang.org/std/primitive.isize.html#method.reverse_bits [`slice::copy_within`]: https://doc.rust-lang.org/std/primitive.slice.html#method.copy_within [`u128::reverse_bits`]: https://doc.rust-lang.org/std/primitive.u128.html#method.reverse_bits [`u16::reverse_bits`]: https://doc.rust-lang.org/std/primitive.u16.html#method.reverse_bits [`u32::reverse_bits`]: https://doc.rust-lang.org/std/primitive.u32.html#method.reverse_bits [`u64::reverse_bits`]: https://doc.rust-lang.org/std/primitive.u64.html#method.reverse_bits [`u8::reverse_bits`]: https://doc.rust-lang.org/std/primitive.u8.html#method.reverse_bits [`usize::reverse_bits`]: https://doc.rust-lang.org/std/primitive.usize.html#method.reverse_bits [rustc-book-pgo]: https://doc.rust-lang.org/rustc/profile-guided-optimization.html Version 1.36.0 (2019-07-04) ========================== Language -------- - [Non-Lexical Lifetimes are now enabled on the 2015 edition.][59114] - [The order of traits in trait objects no longer affects the semantics of that object.][59445] e.g. `dyn Send + fmt::Debug` is now equivalent to `dyn fmt::Debug + Send`, where this was previously not the case. Libraries --------- - [`HashMap`'s implementation has been replaced with `hashbrown::HashMap` implementation.][58623] - [`TryFromSliceError` now implements `From<Infallible>`.][60318] - [`mem::needs_drop` is now available as a const fn.][60364] - [`alloc::Layout::from_size_align_unchecked` is now available as a const fn.][60370] - [`String` now implements `BorrowMut<str>`.][60404] - [`io::Cursor` now implements `Default`.][60234] - [Both `NonNull::{dangling, cast}` are now const fns.][60244] - [The `alloc` crate is now stable.][59675] `alloc` allows you to use a subset of `std` (e.g. `Vec`, `Box`, `Arc`) in `#![no_std]` environments if the environment has access to heap memory allocation. - [`String` now implements `From<&String>`.][59825] - [You can now pass multiple arguments to the `dbg!` macro.][59826] `dbg!` will return a tuple of each argument when there is multiple arguments. - [`Result::{is_err, is_ok}` are now `#[must_use]` and will produce a warning if not used.][59648] Stabilized APIs --------------- - [`VecDeque::rotate_left`] - [`VecDeque::rotate_right`] - [`Iterator::copied`] - [`io::IoSlice`] - [`io::IoSliceMut`] - [`Read::read_vectored`] - [`Write::write_vectored`] - [`str::as_mut_ptr`] - [`mem::MaybeUninit`] - [`pointer::align_offset`] - [`future::Future`] - [`task::Context`] - [`task::RawWaker`] - [`task::RawWakerVTable`] - [`task::Waker`] - [`task::Poll`] Cargo ----- - [Cargo will now produce an error if you attempt to use the name of a required dependency as a feature.][cargo/6860] - [You can now pass the `--offline` flag to run cargo without accessing the network.][cargo/6934] You can find further change's in [Cargo's 1.36.0 release notes][cargo-1-36-0]. Clippy ------ There have been numerous additions and fixes to clippy, see [Clippy's 1.36.0 release notes][clippy-1-36-0] for more details. Misc ---- Compatibility Notes ------------------- - With the stabilisation of `mem::MaybeUninit`, `mem::uninitialized` use is no longer recommended, and will be deprecated in 1.39.0. [60318]: https://github.com/rust-lang/rust/pull/60318/ [60364]: https://github.com/rust-lang/rust/pull/60364/ [60370]: https://github.com/rust-lang/rust/pull/60370/ [60404]: https://github.com/rust-lang/rust/pull/60404/ [60234]: https://github.com/rust-lang/rust/pull/60234/ [60244]: https://github.com/rust-lang/rust/pull/60244/ [58623]: https://github.com/rust-lang/rust/pull/58623/ [59648]: https://github.com/rust-lang/rust/pull/59648/ [59675]: https://github.com/rust-lang/rust/pull/59675/ [59825]: https://github.com/rust-lang/rust/pull/59825/ [59826]: https://github.com/rust-lang/rust/pull/59826/ [59445]: https://github.com/rust-lang/rust/pull/59445/ [59114]: https://github.com/rust-lang/rust/pull/59114/ [cargo/6860]: https://github.com/rust-lang/cargo/pull/6860/ [cargo/6934]: https://github.com/rust-lang/cargo/pull/6934/ [`VecDeque::rotate_left`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.rotate_left [`VecDeque::rotate_right`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.rotate_right [`Iterator::copied`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.copied [`io::IoSlice`]: https://doc.rust-lang.org/std/io/struct.IoSlice.html [`io::IoSliceMut`]: https://doc.rust-lang.org/std/io/struct.IoSliceMut.html [`Read::read_vectored`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_vectored [`Write::write_vectored`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_vectored [`str::as_mut_ptr`]: https://doc.rust-lang.org/std/primitive.str.html#method.as_mut_ptr [`mem::MaybeUninit`]: https://doc.rust-lang.org/std/mem/union.MaybeUninit.html [`pointer::align_offset`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.align_offset [`future::Future`]: https://doc.rust-lang.org/std/future/trait.Future.html [`task::Context`]: https://doc.rust-lang.org/beta/std/task/struct.Context.html [`task::RawWaker`]: https://doc.rust-lang.org/beta/std/task/struct.RawWaker.html [`task::RawWakerVTable`]: https://doc.rust-lang.org/beta/std/task/struct.RawWakerVTable.html [`task::Waker`]: https://doc.rust-lang.org/beta/std/task/struct.Waker.html [`task::Poll`]: https://doc.rust-lang.org/beta/std/task/enum.Poll.html [clippy-1-36-0]: https://github.com/rust-lang/rust-clippy/blob/master/CHANGELOG.md#rust-136 [cargo-1-36-0]: https://github.com/rust-lang/cargo/blob/master/CHANGELOG.md#cargo-136-2019-07-04 Version 1.35.0 (2019-05-23) ========================== Language -------- - [`FnOnce`, `FnMut`, and the `Fn` traits are now implemented for `Box<FnOnce>`, `Box<FnMut>`, and `Box<Fn>` respectively.][59500] - [You can now coerce closures into unsafe function pointers.][59580] e.g. ```rust unsafe fn call_unsafe(func: unsafe fn()) { func() } pub fn main() { unsafe { call_unsafe(|| {}); } } ``` Compiler -------- - [Added the `armv6-unknown-freebsd-gnueabihf` and `armv7-unknown-freebsd-gnueabihf` targets.][58080] - [Added the `wasm32-unknown-wasi` target.][59464] Libraries --------- - [`Thread` will now show its ID in `Debug` output.][59460] - [`StdinLock`, `StdoutLock`, and `StderrLock` now implement `AsRawFd`.][59512] - [`alloc::System` now implements `Default`.][59451] - [Expanded `Debug` output (`{:#?}`) for structs now has a trailing comma on the last field.][59076] - [`char::{ToLowercase, ToUppercase}` now implement `ExactSizeIterator`.][58778] - [All `NonZero` numeric types now implement `FromStr`.][58717] - [Removed the `Read` trait bounds on the `BufReader::{get_ref, get_mut, into_inner}` methods.][58423] - [You can now call the `dbg!` macro without any parameters to print the file and line where it is called.][57847] - [In place ASCII case conversions are now up to 4× faster.][59283] e.g. `str::make_ascii_lowercase` - [`hash_map::{OccupiedEntry, VacantEntry}` now implement `Sync` and `Send`.][58369] Stabilized APIs --------------- - [`f32::copysign`] - [`f64::copysign`] - [`RefCell::replace_with`] - [`RefCell::map_split`] - [`ptr::hash`] - [`Range::contains`] - [`RangeFrom::contains`] - [`RangeTo::contains`] - [`RangeInclusive::contains`] - [`RangeToInclusive::contains`] - [`Option::copied`] Cargo ----- - [You can now set `cargo:rustc-cdylib-link-arg` at build time to pass custom linker arguments when building a `cdylib`.][cargo/6298] Its usage is highly platform specific. Misc ---- - [The Rust toolchain is now available natively for musl based distros.][58575] [59460]: https://github.com/rust-lang/rust/pull/59460/ [59464]: https://github.com/rust-lang/rust/pull/59464/ [59500]: https://github.com/rust-lang/rust/pull/59500/ [59512]: https://github.com/rust-lang/rust/pull/59512/ [59580]: https://github.com/rust-lang/rust/pull/59580/ [59283]: https://github.com/rust-lang/rust/pull/59283/ [59451]: https://github.com/rust-lang/rust/pull/59451/ [59076]: https://github.com/rust-lang/rust/pull/59076/ [58778]: https://github.com/rust-lang/rust/pull/58778/ [58717]: https://github.com/rust-lang/rust/pull/58717/ [58369]: https://github.com/rust-lang/rust/pull/58369/ [58423]: https://github.com/rust-lang/rust/pull/58423/ [58080]: https://github.com/rust-lang/rust/pull/58080/ [57847]: https://github.com/rust-lang/rust/pull/57847/ [58575]: https://github.com/rust-lang/rust/pull/58575 [cargo/6298]: https://github.com/rust-lang/cargo/pull/6298/ [`f32::copysign`]: https://doc.rust-lang.org/stable/std/primitive.f32.html#method.copysign [`f64::copysign`]: https://doc.rust-lang.org/stable/std/primitive.f64.html#method.copysign [`RefCell::replace_with`]: https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html#method.replace_with [`RefCell::map_split`]: https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html#method.map_split [`ptr::hash`]: https://doc.rust-lang.org/stable/std/ptr/fn.hash.html [`Range::contains`]: https://doc.rust-lang.org/std/ops/struct.Range.html#method.contains [`RangeFrom::contains`]: https://doc.rust-lang.org/std/ops/struct.RangeFrom.html#method.contains [`RangeTo::contains`]: https://doc.rust-lang.org/std/ops/struct.RangeTo.html#method.contains [`RangeInclusive::contains`]: https://doc.rust-lang.org/std/ops/struct.RangeInclusive.html#method.contains [`RangeToInclusive::contains`]: https://doc.rust-lang.org/std/ops/struct.RangeToInclusive.html#method.contains [`Option::copied`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.copied Version 1.34.2 (2019-05-14) =========================== * [Destabilize the `Error::type_id` function due to a security vulnerability][60785] ([CVE-2019-12083]) [60785]: https://github.com/rust-lang/rust/pull/60785 [CVE-2019-12083]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-12083 Version 1.34.1 (2019-04-25) =========================== * [Fix false positives for the `redundant_closure` Clippy lint][clippy/3821] * [Fix false positives for the `missing_const_for_fn` Clippy lint][clippy/3844] * [Fix Clippy panic when checking some macros][clippy/3805] [clippy/3821]: https://github.com/rust-lang/rust-clippy/pull/3821 [clippy/3844]: https://github.com/rust-lang/rust-clippy/pull/3844 [clippy/3805]: https://github.com/rust-lang/rust-clippy/pull/3805 Version 1.34.0 (2019-04-11) ========================== Language -------- - [You can now use `#[deprecated = "reason"]`][58166] as a shorthand for `#[deprecated(note = "reason")]`. This was previously allowed by mistake but had no effect. - [You can now accept token streams in `#[attr()]`,`#[attr[]]`, and `#[attr{}]` procedural macros.][57367] - [You can now write `extern crate self as foo;`][57407] to import your crate's root into the extern prelude. Compiler -------- - [You can now target `riscv64imac-unknown-none-elf` and `riscv64gc-unknown-none-elf`.][58406] - [You can now enable linker plugin LTO optimisations with `-C linker-plugin-lto`.][58057] This allows rustc to compile your Rust code into LLVM bitcode allowing LLVM to perform LTO optimisations across C/C++ FFI boundaries. - [You can now target `powerpc64-unknown-freebsd`.][57809] Libraries --------- - [The trait bounds have been removed on some of `HashMap<K, V, S>`'s and `HashSet<T, S>`'s basic methods.][58370] Most notably you no longer require the `Hash` trait to create an iterator. - [The `Ord` trait bounds have been removed on some of `BinaryHeap<T>`'s basic methods.][58421] Most notably you no longer require the `Ord` trait to create an iterator. - [The methods `overflowing_neg` and `wrapping_neg` are now `const` functions for all numeric types.][58044] - [Indexing a `str` is now generic over all types that implement `SliceIndex<str>`.][57604] - [`str::trim`, `str::trim_matches`, `str::trim_{start, end}`, and `str::trim_{start, end}_matches` are now `#[must_use]`][57106] and will produce a warning if their returning type is unused. - [The methods `checked_pow`, `saturating_pow`, `wrapping_pow`, and `overflowing_pow` are now available for all numeric types.][57873] These are equivalent to methods such as `wrapping_add` for the `pow` operation. Stabilized APIs --------------- #### std & core * [`Any::type_id`] * [`Error::type_id`] * [`atomic::AtomicI16`] * [`atomic::AtomicI32`] * [`atomic::AtomicI64`] * [`atomic::AtomicI8`] * [`atomic::AtomicU16`] * [`atomic::AtomicU32`] * [`atomic::AtomicU64`] * [`atomic::AtomicU8`] * [`convert::Infallible`] * [`convert::TryFrom`] * [`convert::TryInto`] * [`iter::from_fn`] * [`iter::successors`] * [`num::NonZeroI128`] * [`num::NonZeroI16`] * [`num::NonZeroI32`] * [`num::NonZeroI64`] * [`num::NonZeroI8`] * [`num::NonZeroIsize`] * [`slice::sort_by_cached_key`] * [`str::escape_debug`] * [`str::escape_default`] * [`str::escape_unicode`] * [`str::split_ascii_whitespace`] #### std * [`Instant::checked_add`] * [`Instant::checked_sub`] * [`SystemTime::checked_add`] * [`SystemTime::checked_sub`] Cargo ----- - [You can now use alternative registries to crates.io.][cargo/6654] Misc ---- - [You can now use the `?` operator in your documentation tests without manually adding `fn main() -> Result<(), _> {}`.][56470] Compatibility Notes ------------------- - [`Command::before_exec` is being replaced by the unsafe method `Command::pre_exec`][58059] and will be deprecated with Rust 1.37.0. - [Use of `ATOMIC_{BOOL, ISIZE, USIZE}_INIT` is now deprecated][57425] as you can now use `const` functions in `static` variables. [58370]: https://github.com/rust-lang/rust/pull/58370/ [58406]: https://github.com/rust-lang/rust/pull/58406/ [58421]: https://github.com/rust-lang/rust/pull/58421/ [58166]: https://github.com/rust-lang/rust/pull/58166/ [58044]: https://github.com/rust-lang/rust/pull/58044/ [58057]: https://github.com/rust-lang/rust/pull/58057/ [58059]: https://github.com/rust-lang/rust/pull/58059/ [57809]: https://github.com/rust-lang/rust/pull/57809/ [57873]: https://github.com/rust-lang/rust/pull/57873/ [57604]: https://github.com/rust-lang/rust/pull/57604/ [57367]: https://github.com/rust-lang/rust/pull/57367/ [57407]: https://github.com/rust-lang/rust/pull/57407/ [57425]: https://github.com/rust-lang/rust/pull/57425/ [57106]: https://github.com/rust-lang/rust/pull/57106/ [56470]: https://github.com/rust-lang/rust/pull/56470/ [cargo/6654]: https://github.com/rust-lang/cargo/pull/6654/ [`Any::type_id`]: https://doc.rust-lang.org/std/any/trait.Any.html#tymethod.type_id [`Error::type_id`]: https://doc.rust-lang.org/std/error/trait.Error.html#method.type_id [`atomic::AtomicI16`]: https://doc.rust-lang.org/std/sync/atomic/struct.AtomicI16.html [`atomic::AtomicI32`]: https://doc.rust-lang.org/std/sync/atomic/struct.AtomicI32.html [`atomic::AtomicI64`]: https://doc.rust-lang.org/std/sync/atomic/struct.AtomicI64.html [`atomic::AtomicI8`]: https://doc.rust-lang.org/std/sync/atomic/struct.AtomicI8.html [`atomic::AtomicU16`]: https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU16.html [`atomic::AtomicU32`]: https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU32.html [`atomic::AtomicU64`]: https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU64.html [`atomic::AtomicU8`]: https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU8.html [`convert::Infallible`]: https://doc.rust-lang.org/std/convert/enum.Infallible.html [`convert::TryFrom`]: https://doc.rust-lang.org/std/convert/trait.TryFrom.html [`convert::TryInto`]: https://doc.rust-lang.org/std/convert/trait.TryInto.html [`iter::from_fn`]: https://doc.rust-lang.org/std/iter/fn.from_fn.html [`iter::successors`]: https://doc.rust-lang.org/std/iter/fn.successors.html [`num::NonZeroI128`]: https://doc.rust-lang.org/std/num/struct.NonZeroI128.html [`num::NonZeroI16`]: https://doc.rust-lang.org/std/num/struct.NonZeroI16.html [`num::NonZeroI32`]: https://doc.rust-lang.org/std/num/struct.NonZeroI32.html [`num::NonZeroI64`]: https://doc.rust-lang.org/std/num/struct.NonZeroI64.html [`num::NonZeroI8`]: https://doc.rust-lang.org/std/num/struct.NonZeroI8.html [`num::NonZeroIsize`]: https://doc.rust-lang.org/std/num/struct.NonZeroIsize.html [`slice::sort_by_cached_key`]: https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by_cached_key [`str::escape_debug`]: https://doc.rust-lang.org/std/primitive.str.html#method.escape_debug [`str::escape_default`]: https://doc.rust-lang.org/std/primitive.str.html#method.escape_default [`str::escape_unicode`]: https://doc.rust-lang.org/std/primitive.str.html#method.escape_unicode [`str::split_ascii_whitespace`]: https://doc.rust-lang.org/std/primitive.str.html#method.split_ascii_whitespace [`Instant::checked_add`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.checked_add [`Instant::checked_sub`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.checked_sub [`SystemTime::checked_add`]: https://doc.rust-lang.org/std/time/struct.SystemTime.html#method.checked_add [`SystemTime::checked_sub`]: https://doc.rust-lang.org/std/time/struct.SystemTime.html#method.checked_sub Version 1.33.0 (2019-02-28) ========================== Language -------- - [You can now use the `cfg(target_vendor)` attribute.][57465] E.g. `#[cfg(target_vendor="apple")] fn main() { println!("Hello Apple!"); }` - [Integer patterns such as in a match expression can now be exhaustive.][56362] E.g. You can have match statement on a `u8` that covers `0..=255` and you would no longer be required to have a `_ => unreachable!()` case. - [You can now have multiple patterns in `if let` and `while let` expressions.][57532] You can do this with the same syntax as a `match` expression. E.g. ```rust enum Creature { Crab(String), Lobster(String), Person(String), } fn main() { let state = Creature::Crab("Ferris"); if let Creature::Crab(name) | Creature::Person(name) = state { println!("This creature's name is: {}", name); } } ``` - [You can now have irrefutable `if let` and `while let` patterns.][57535] Using this feature will by default produce a warning as this behaviour can be unintuitive. E.g. `if let _ = 5 {}` - [You can now use `let` bindings, assignments, expression statements, and irrefutable pattern destructuring in const functions.][57175] - [You can now call unsafe const functions.][57067] E.g. ```rust const unsafe fn foo() -> i32 { 5 } const fn bar() -> i32 { unsafe { foo() } } ``` - [You can now specify multiple attributes in a `cfg_attr` attribute.][57332] E.g. `#[cfg_attr(all(), must_use, optimize)]` - [You can now specify a specific alignment with the `#[repr(packed)]` attribute.][57049] E.g. `#[repr(packed(2))] struct Foo(i16, i32);` is a struct with an alignment of 2 bytes and a size of 6 bytes. - [You can now import an item from a module as an `_`.][56303] This allows you to import a trait's impls, and not have the name in the namespace. E.g. ```rust use std::io::Read as _; // Allowed as there is only one `Read` in the module. pub trait Read {} ``` - [You may now use `Rc`, `Arc`, and `Pin` as method receivers][56805]. Compiler -------- - [You can now set a linker flavor for `rustc` with the `-Clinker-flavor` command line argument.][56351] - [The minimum required LLVM version has been bumped to 6.0.][56642] - [Added support for the PowerPC64 architecture on FreeBSD.][57615] - [The `x86_64-fortanix-unknown-sgx` target support has been upgraded to tier 2 support.][57130] Visit the [platform support][platform-support] page for information on Rust's platform support. - [Added support for the `thumbv7neon-linux-androideabi` and `thumbv7neon-unknown-linux-gnueabihf` targets.][56947] - [Added support for the `x86_64-unknown-uefi` target.][56769] Libraries --------- - [The methods `overflowing_{add, sub, mul, shl, shr}` are now `const` functions for all numeric types.][57566] - [The methods `rotate_left`, `rotate_right`, and `wrapping_{add, sub, mul, shl, shr}` are now `const` functions for all numeric types.][57105] - [The methods `is_positive` and `is_negative` are now `const` functions for all signed numeric types.][57105] - [The `get` method for all `NonZero` types is now `const`.][57167] - [The methods `count_ones`, `count_zeros`, `leading_zeros`, `trailing_zeros`, `swap_bytes`, `from_be`, `from_le`, `to_be`, `to_le` are now `const` for all numeric types.][57234] - [`Ipv4Addr::new` is now a `const` function][57234] Stabilized APIs --------------- - [`unix::FileExt::read_exact_at`] - [`unix::FileExt::write_all_at`] - [`Option::transpose`] - [`Result::transpose`] - [`convert::identity`] - [`pin::Pin`] - [`marker::Unpin`] - [`marker::PhantomPinned`] - [`Vec::resize_with`] - [`VecDeque::resize_with`] - [`Duration::as_millis`] - [`Duration::as_micros`] - [`Duration::as_nanos`] Cargo ----- - [You can now publish crates that require a feature flag to compile with `cargo publish --features` or `cargo publish --all-features`.][cargo/6453] - [Cargo should now rebuild a crate if a file was modified during the initial build.][cargo/6484] Compatibility Notes ------------------- - The methods `str::{trim_left, trim_right, trim_left_matches, trim_right_matches}` are now deprecated in the standard library, and their usage will now produce a warning. Please use the `str::{trim_start, trim_end, trim_start_matches, trim_end_matches}` methods instead. - The `Error::cause` method has been deprecated in favor of `Error::source` which supports downcasting. - [Libtest no longer creates a new thread for each test when `--test-threads=1`. It also runs the tests in deterministic order][56243] [56243]: https://github.com/rust-lang/rust/pull/56243 [56303]: https://github.com/rust-lang/rust/pull/56303/ [56351]: https://github.com/rust-lang/rust/pull/56351/ [56362]: https://github.com/rust-lang/rust/pull/56362 [56642]: https://github.com/rust-lang/rust/pull/56642/ [56769]: https://github.com/rust-lang/rust/pull/56769/ [56805]: https://github.com/rust-lang/rust/pull/56805 [56947]: https://github.com/rust-lang/rust/pull/56947/ [57049]: https://github.com/rust-lang/rust/pull/57049/ [57067]: https://github.com/rust-lang/rust/pull/57067/ [57105]: https://github.com/rust-lang/rust/pull/57105 [57130]: https://github.com/rust-lang/rust/pull/57130/ [57167]: https://github.com/rust-lang/rust/pull/57167/ [57175]: https://github.com/rust-lang/rust/pull/57175/ [57234]: https://github.com/rust-lang/rust/pull/57234/ [57332]: https://github.com/rust-lang/rust/pull/57332/ [57465]: https://github.com/rust-lang/rust/pull/57465/ [57532]: https://github.com/rust-lang/rust/pull/57532/ [57535]: https://github.com/rust-lang/rust/pull/57535/ [57566]: https://github.com/rust-lang/rust/pull/57566/ [57615]: https://github.com/rust-lang/rust/pull/57615/ [cargo/6453]: https://github.com/rust-lang/cargo/pull/6453/ [cargo/6484]: https://github.com/rust-lang/cargo/pull/6484/ [`unix::FileExt::read_exact_at`]: https://doc.rust-lang.org/std/os/unix/fs/trait.FileExt.html#method.read_exact_at [`unix::FileExt::write_all_at`]: https://doc.rust-lang.org/std/os/unix/fs/trait.FileExt.html#method.write_all_at [`Option::transpose`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.transpose [`Result::transpose`]: https://doc.rust-lang.org/std/result/enum.Result.html#method.transpose [`convert::identity`]: https://doc.rust-lang.org/std/convert/fn.identity.html [`pin::Pin`]: https://doc.rust-lang.org/std/pin/struct.Pin.html [`marker::Unpin`]: https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html [`marker::PhantomPinned`]: https://doc.rust-lang.org/nightly/std/marker/struct.PhantomPinned.html [`Vec::resize_with`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.resize_with [`VecDeque::resize_with`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.resize_with [`Duration::as_millis`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.as_millis [`Duration::as_micros`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.as_micros [`Duration::as_nanos`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.as_nanos [platform-support]: https://forge.rust-lang.org/platform-support.html Version 1.32.0 (2019-01-17) ========================== Language -------- #### 2018 edition - [You can now use the `?` operator in macro definitions.][56245] The `?` operator allows you to specify zero or one repetitions similar to the `*` and `+` operators. - [Module paths with no leading keyword like `super`, `self`, or `crate`, will now always resolve to the item (`enum`, `struct`, etc.) available in the module if present, before resolving to a external crate or an item the prelude.][56759] E.g. ```rust enum Color { Red, Green, Blue } use Color::*; ``` #### All editions - [You can now match against `PhantomData<T>` types.][55837] - [You can now match against literals in macros with the `literal` specifier.][56072] This will match against a literal of any type. E.g. `1`, `'A'`, `"Hello World"` - [Self can now be used as a constructor and pattern for unit and tuple structs.][56365] E.g. ```rust struct Point(i32, i32); impl Point { pub fn new(x: i32, y: i32) -> Self { Self(x, y) } pub fn is_origin(&self) -> bool { match self { Self(0, 0) => true, _ => false, } } } ``` - [Self can also now be used in type definitions.][56366] E.g. ```rust enum List<T> where Self: PartialOrd<Self> // can write `Self` instead of `List<T>` { Nil, Cons(T, Box<Self>) // likewise here } ``` - [You can now mark traits with `#[must_use]`.][55663] This provides a warning if a `impl Trait` or `dyn Trait` is returned and unused in the program. Compiler -------- - [The default allocator has changed from jemalloc to the default allocator on your system.][55238] The compiler itself on Linux & macOS will still use jemalloc, but programs compiled with it will use the system allocator. - [Added the `aarch64-pc-windows-msvc` target.][55702] Libraries --------- - [`PathBuf` now implements `FromStr`.][55148] - [`Box<[T]>` now implements `FromIterator<T>`.][55843] - [The `dbg!` macro has been stabilized.][56395] This macro enables you to easily debug expressions in your rust program. E.g. ```rust let a = 2; let b = dbg!(a * 2) + 1; // ^-- prints: [src/main.rs:4] a * 2 = 4 assert_eq!(b, 5); ``` The following APIs are now `const` functions and can be used in a `const` context. - [`Cell::as_ptr`] - [`UnsafeCell::get`] - [`char::is_ascii`] - [`iter::empty`] - [`ManuallyDrop::new`] - [`ManuallyDrop::into_inner`] - [`RangeInclusive::start`] - [`RangeInclusive::end`] - [`NonNull::as_ptr`] - [`slice::as_ptr`] - [`str::as_ptr`] - [`Duration::as_secs`] - [`Duration::subsec_millis`] - [`Duration::subsec_micros`] - [`Duration::subsec_nanos`] - [`CStr::as_ptr`] - [`Ipv4Addr::is_unspecified`] - [`Ipv6Addr::new`] - [`Ipv6Addr::octets`] Stabilized APIs --------------- - [`i8::to_be_bytes`] - [`i8::to_le_bytes`] - [`i8::to_ne_bytes`] - [`i8::from_be_bytes`] - [`i8::from_le_bytes`] - [`i8::from_ne_bytes`] - [`i16::to_be_bytes`] - [`i16::to_le_bytes`] - [`i16::to_ne_bytes`] - [`i16::from_be_bytes`] - [`i16::from_le_bytes`] - [`i16::from_ne_bytes`] - [`i32::to_be_bytes`] - [`i32::to_le_bytes`] - [`i32::to_ne_bytes`] - [`i32::from_be_bytes`] - [`i32::from_le_bytes`] - [`i32::from_ne_bytes`] - [`i64::to_be_bytes`] - [`i64::to_le_bytes`] - [`i64::to_ne_bytes`] - [`i64::from_be_bytes`] - [`i64::from_le_bytes`] - [`i64::from_ne_bytes`] - [`i128::to_be_bytes`] - [`i128::to_le_bytes`] - [`i128::to_ne_bytes`] - [`i128::from_be_bytes`] - [`i128::from_le_bytes`] - [`i128::from_ne_bytes`] - [`isize::to_be_bytes`] - [`isize::to_le_bytes`] - [`isize::to_ne_bytes`] - [`isize::from_be_bytes`] - [`isize::from_le_bytes`] - [`isize::from_ne_bytes`] - [`u8::to_be_bytes`] - [`u8::to_le_bytes`] - [`u8::to_ne_bytes`] - [`u8::from_be_bytes`] - [`u8::from_le_bytes`] - [`u8::from_ne_bytes`] - [`u16::to_be_bytes`] - [`u16::to_le_bytes`] - [`u16::to_ne_bytes`] - [`u16::from_be_bytes`] - [`u16::from_le_bytes`] - [`u16::from_ne_bytes`] - [`u32::to_be_bytes`] - [`u32::to_le_bytes`] - [`u32::to_ne_bytes`] - [`u32::from_be_bytes`] - [`u32::from_le_bytes`] - [`u32::from_ne_bytes`] - [`u64::to_be_bytes`] - [`u64::to_le_bytes`] - [`u64::to_ne_bytes`] - [`u64::from_be_bytes`] - [`u64::from_le_bytes`] - [`u64::from_ne_bytes`] - [`u128::to_be_bytes`] - [`u128::to_le_bytes`] - [`u128::to_ne_bytes`] - [`u128::from_be_bytes`] - [`u128::from_le_bytes`] - [`u128::from_ne_bytes`] - [`usize::to_be_bytes`] - [`usize::to_le_bytes`] - [`usize::to_ne_bytes`] - [`usize::from_be_bytes`] - [`usize::from_le_bytes`] - [`usize::from_ne_bytes`] Cargo ----- - [You can now run `cargo c` as an alias for `cargo check`.][cargo/6218] - [Usernames are now allowed in alt registry URLs.][cargo/6242] Misc ---- - [`libproc_macro` has been added to the `rust-src` distribution.][55280] Compatibility Notes ------------------- - [The argument types for AVX's `_mm256_stream_si256`, `_mm256_stream_pd`, `_mm256_stream_ps`][55610] have been changed from `*const` to `*mut` as the previous implementation was unsound. [55148]: https://github.com/rust-lang/rust/pull/55148/ [55238]: https://github.com/rust-lang/rust/pull/55238/ [55280]: https://github.com/rust-lang/rust/pull/55280/ [55610]: https://github.com/rust-lang/rust/pull/55610/ [55663]: https://github.com/rust-lang/rust/pull/55663/ [55702]: https://github.com/rust-lang/rust/pull/55702/ [55837]: https://github.com/rust-lang/rust/pull/55837/ [55843]: https://github.com/rust-lang/rust/pull/55843/ [56072]: https://github.com/rust-lang/rust/pull/56072/ [56245]: https://github.com/rust-lang/rust/pull/56245/ [56365]: https://github.com/rust-lang/rust/pull/56365/ [56366]: https://github.com/rust-lang/rust/pull/56366/ [56395]: https://github.com/rust-lang/rust/pull/56395/ [56759]: https://github.com/rust-lang/rust/pull/56759/ [cargo/6218]: https://github.com/rust-lang/cargo/pull/6218/ [cargo/6242]: https://github.com/rust-lang/cargo/pull/6242/ [`CStr::as_ptr`]: https://doc.rust-lang.org/std/ffi/struct.CStr.html#method.as_ptr [`Cell::as_ptr`]: https://doc.rust-lang.org/std/cell/struct.Cell.html#method.as_ptr [`Duration::as_secs`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.as_secs [`Duration::subsec_micros`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.subsec_micros [`Duration::subsec_millis`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.subsec_millis [`Duration::subsec_nanos`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.subsec_nanos [`Ipv4Addr::is_unspecified`]: https://doc.rust-lang.org/std/net/struct.Ipv4Addr.html#method.is_unspecified [`Ipv6Addr::new`]: https://doc.rust-lang.org/std/net/struct.Ipv6Addr.html#method.new [`Ipv6Addr::octets`]: https://doc.rust-lang.org/std/net/struct.Ipv6Addr.html#method.octets [`ManuallyDrop::into_inner`]: https://doc.rust-lang.org/std/mem/struct.ManuallyDrop.html#method.into_inner [`ManuallyDrop::new`]: https://doc.rust-lang.org/std/mem/struct.ManuallyDrop.html#method.new [`NonNull::as_ptr`]: https://doc.rust-lang.org/std/ptr/struct.NonNull.html#method.as_ptr [`RangeInclusive::end`]: https://doc.rust-lang.org/std/ops/struct.RangeInclusive.html#method.end [`RangeInclusive::start`]: https://doc.rust-lang.org/std/ops/struct.RangeInclusive.html#method.start [`UnsafeCell::get`]: https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html#method.get [`slice::as_ptr`]: https://doc.rust-lang.org/std/primitive.slice.html#method.as_ptr [`char::is_ascii`]: https://doc.rust-lang.org/std/primitive.char.html#method.is_ascii [`i128::from_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i128.html#method.from_be_bytes [`i128::from_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i128.html#method.from_le_bytes [`i128::from_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i128.html#method.from_ne_bytes [`i128::to_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i128.html#method.to_be_bytes [`i128::to_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i128.html#method.to_le_bytes [`i128::to_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i128.html#method.to_ne_bytes [`i16::from_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i16.html#method.from_be_bytes [`i16::from_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i16.html#method.from_le_bytes [`i16::from_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i16.html#method.from_ne_bytes [`i16::to_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i16.html#method.to_be_bytes [`i16::to_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i16.html#method.to_le_bytes [`i16::to_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i16.html#method.to_ne_bytes [`i32::from_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i32.html#method.from_be_bytes [`i32::from_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i32.html#method.from_le_bytes [`i32::from_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i32.html#method.from_ne_bytes [`i32::to_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i32.html#method.to_be_bytes [`i32::to_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i32.html#method.to_le_bytes [`i32::to_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i32.html#method.to_ne_bytes [`i64::from_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i64.html#method.from_be_bytes [`i64::from_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i64.html#method.from_le_bytes [`i64::from_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i64.html#method.from_ne_bytes [`i64::to_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i64.html#method.to_be_bytes [`i64::to_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i64.html#method.to_le_bytes [`i64::to_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i64.html#method.to_ne_bytes [`i8::from_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i8.html#method.from_be_bytes [`i8::from_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i8.html#method.from_le_bytes [`i8::from_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i8.html#method.from_ne_bytes [`i8::to_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i8.html#method.to_be_bytes [`i8::to_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i8.html#method.to_le_bytes [`i8::to_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.i8.html#method.to_ne_bytes [`isize::from_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.isize.html#method.from_be_bytes [`isize::from_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.isize.html#method.from_le_bytes [`isize::from_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.isize.html#method.from_ne_bytes [`isize::to_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.isize.html#method.to_be_bytes [`isize::to_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.isize.html#method.to_le_bytes [`isize::to_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.isize.html#method.to_ne_bytes [`iter::empty`]: https://doc.rust-lang.org/std/iter/fn.empty.html [`str::as_ptr`]: https://doc.rust-lang.org/std/primitive.str.html#method.as_ptr [`u128::from_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u128.html#method.from_be_bytes [`u128::from_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u128.html#method.from_le_bytes [`u128::from_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u128.html#method.from_ne_bytes [`u128::to_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u128.html#method.to_be_bytes [`u128::to_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u128.html#method.to_le_bytes [`u128::to_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u128.html#method.to_ne_bytes [`u16::from_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u16.html#method.from_be_bytes [`u16::from_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u16.html#method.from_le_bytes [`u16::from_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u16.html#method.from_ne_bytes [`u16::to_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u16.html#method.to_be_bytes [`u16::to_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u16.html#method.to_le_bytes [`u16::to_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u16.html#method.to_ne_bytes [`u32::from_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u32.html#method.from_be_bytes [`u32::from_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u32.html#method.from_le_bytes [`u32::from_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u32.html#method.from_ne_bytes [`u32::to_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u32.html#method.to_be_bytes [`u32::to_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u32.html#method.to_le_bytes [`u32::to_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u32.html#method.to_ne_bytes [`u64::from_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u64.html#method.from_be_bytes [`u64::from_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u64.html#method.from_le_bytes [`u64::from_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u64.html#method.from_ne_bytes [`u64::to_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u64.html#method.to_be_bytes [`u64::to_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u64.html#method.to_le_bytes [`u64::to_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u64.html#method.to_ne_bytes [`u8::from_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u8.html#method.from_be_bytes [`u8::from_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u8.html#method.from_le_bytes [`u8::from_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u8.html#method.from_ne_bytes [`u8::to_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u8.html#method.to_be_bytes [`u8::to_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u8.html#method.to_le_bytes [`u8::to_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.u8.html#method.to_ne_bytes [`usize::from_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.usize.html#method.from_be_bytes [`usize::from_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.usize.html#method.from_le_bytes [`usize::from_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.usize.html#method.from_ne_bytes [`usize::to_be_bytes`]: https://doc.rust-lang.org/stable/std/primitive.usize.html#method.to_be_bytes [`usize::to_le_bytes`]: https://doc.rust-lang.org/stable/std/primitive.usize.html#method.to_le_bytes [`usize::to_ne_bytes`]: https://doc.rust-lang.org/stable/std/primitive.usize.html#method.to_ne_bytes Version 1.31.1 (2018-12-20) =========================== - [Fix Rust failing to build on `powerpc-unknown-netbsd`][56562] - [Fix broken go-to-definition in RLS][rls/1171] - [Fix infinite loop on hover in RLS][rls/1170] [56562]: https://github.com/rust-lang/rust/pull/56562 [rls/1171]: https://github.com/rust-lang/rls/issues/1171 [rls/1170]: https://github.com/rust-lang/rls/pull/1170 Version 1.31.0 (2018-12-06) ========================== Language -------- - 🎉 [This version marks the release of the 2018 edition of Rust.][54057] 🎉 - [New lifetime elision rules now allow for eliding lifetimes in functions and impl headers.][54778] E.g. `impl<'a> Reader for BufReader<'a> {}` can now be `impl Reader for BufReader<'_> {}`. Lifetimes are still required to be defined in structs. - [You can now define and use `const` functions.][54835] These are currently a strict minimal subset of the [const fn RFC][RFC-911]. Refer to the [language reference][const-reference] for what exactly is available. - [You can now use tool lints, which allow you to scope lints from external tools using attributes.][54870] E.g. `#[allow(clippy::filter_map)]`. - [`#[no_mangle]` and `#[export_name]` attributes can now be located anywhere in a crate, not just in exported functions.][54451] - [You can now use parentheses in pattern matches.][54497] Compiler -------- - [Updated musl to 1.1.20][54430] Libraries --------- - [You can now convert `num::NonZero*` types to their raw equivalents using the `From` trait.][54240] E.g. `u8` now implements `From<NonZeroU8>`. - [You can now convert a `&Option<T>` into `Option<&T>` and `&mut Option<T>` into `Option<&mut T>` using the `From` trait.][53218] - [You can now multiply (`*`) a `time::Duration` by a `u32`.][52813] Stabilized APIs --------------- - [`slice::align_to`] - [`slice::align_to_mut`] - [`slice::chunks_exact`] - [`slice::chunks_exact_mut`] - [`slice::rchunks`] - [`slice::rchunks_mut`] - [`slice::rchunks_exact`] - [`slice::rchunks_exact_mut`] - [`Option::replace`] Cargo ----- - [Cargo will now download crates in parallel using HTTP/2.][cargo/6005] - [You can now rename packages in your Cargo.toml][cargo/6319] We have a guide on [how to use the `package` key in your dependencies.][cargo-rename-reference] [52813]: https://github.com/rust-lang/rust/pull/52813/ [53218]: https://github.com/rust-lang/rust/pull/53218/ [54057]: https://github.com/rust-lang/rust/pull/54057/ [54240]: https://github.com/rust-lang/rust/pull/54240/ [54430]: https://github.com/rust-lang/rust/pull/54430/ [54451]: https://github.com/rust-lang/rust/pull/54451/ [54497]: https://github.com/rust-lang/rust/pull/54497/ [54778]: https://github.com/rust-lang/rust/pull/54778/ [54835]: https://github.com/rust-lang/rust/pull/54835/ [54870]: https://github.com/rust-lang/rust/pull/54870/ [RFC-911]: https://github.com/rust-lang/rfcs/pull/911 [`Option::replace`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.replace [`slice::align_to_mut`]: https://doc.rust-lang.org/std/primitive.slice.html#method.align_to_mut [`slice::align_to`]: https://doc.rust-lang.org/std/primitive.slice.html#method.align_to [`slice::chunks_exact_mut`]: https://doc.rust-lang.org/std/primitive.slice.html#method.chunks_exact_mut [`slice::chunks_exact`]: https://doc.rust-lang.org/std/primitive.slice.html#method.chunks_exact [`slice::rchunks_exact_mut`]: https://doc.rust-lang.org/std/primitive.slice.html#method.rchunks_mut [`slice::rchunks_exact`]: https://doc.rust-lang.org/std/primitive.slice.html#method.rchunks_exact [`slice::rchunks_mut`]: https://doc.rust-lang.org/std/primitive.slice.html#method.rchunks_mut [`slice::rchunks`]: https://doc.rust-lang.org/std/primitive.slice.html#method.rchunks [cargo/6005]: https://github.com/rust-lang/cargo/pull/6005/ [cargo/6319]: https://github.com/rust-lang/cargo/pull/6319/ [cargo-rename-reference]: https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#renaming-dependencies-in-cargotoml [const-reference]: https://doc.rust-lang.org/reference/items/functions.html#const-functions Version 1.30.1 (2018-11-08) =========================== - [Fixed overflow ICE in rustdoc][54199] - [Cap Cargo progress bar width at 60 in MSYS terminals][cargo/6122] [54199]: https://github.com/rust-lang/rust/pull/54199 [cargo/6122]: https://github.com/rust-lang/cargo/pull/6122 Version 1.30.0 (2018-10-25) ========================== Language -------- - [Procedural macros are now available.][52081] These kinds of macros allow for more powerful code generation. There is a [new chapter available][proc-macros] in the Rust Programming Language book that goes further in depth. - [You can now use keywords as identifiers using the raw identifiers syntax (`r#`),][53236] e.g. `let r#for = true;` - [Using anonymous parameters in traits is now deprecated with a warning and will be a hard error in the 2018 edition.][53272] - [You can now use `crate` in paths.][54404] This allows you to refer to the crate root in the path, e.g. `use crate::foo;` refers to `foo` in `src/lib.rs`. - [Using a external crate no longer requires being prefixed with `::`.][54404] Previously, using a external crate in a module without a use statement required `let json = ::serde_json::from_str(foo);` but can now be written as `let json = serde_json::from_str(foo);`. - [You can now apply the `#[used]` attribute to static items to prevent the compiler from optimising them away, even if they appear to be unused,][51363] e.g. `#[used] static FOO: u32 = 1;` - [You can now import and reexport macros from other crates with the `use` syntax.][50911] Macros exported with `#[macro_export]` are now placed into the root module of the crate. If your macro relies on calling other local macros, it is recommended to export with the `#[macro_export(local_inner_macros)]` attribute so users won't have to import those macros. - [You can now catch visibility keywords (e.g. `pub`, `pub(crate)`) in macros using the `vis` specifier.][53370] - [Non-macro attributes now allow all forms of literals, not just strings.][53044] Previously, you would write `#[attr("true")]`, and you can now write `#[attr(true)]`. - [You can now specify a function to handle a panic in the Rust runtime with the `#[panic_handler]` attribute.][51366] Compiler -------- - [Added the `riscv32imc-unknown-none-elf` target.][53822] - [Added the `aarch64-unknown-netbsd` target][53165] - [Upgraded to LLVM 8.][53611] Libraries --------- - [`ManuallyDrop` now allows the inner type to be unsized.][53033] Stabilized APIs --------------- - [`Ipv4Addr::BROADCAST`] - [`Ipv4Addr::LOCALHOST`] - [`Ipv4Addr::UNSPECIFIED`] - [`Ipv6Addr::LOCALHOST`] - [`Ipv6Addr::UNSPECIFIED`] - [`Iterator::find_map`] The following methods are replacement methods for `trim_left`, `trim_right`, `trim_left_matches`, and `trim_right_matches`, which will be deprecated in 1.33.0: - [`str::trim_end_matches`] - [`str::trim_end`] - [`str::trim_start_matches`] - [`str::trim_start`] Cargo ---- - [`cargo run` doesn't require specifying a package in workspaces.][cargo/5877] - [`cargo doc` now supports `--message-format=json`.][cargo/5878] This is equivalent to calling `rustdoc --error-format=json`. - [Cargo will now provide a progress bar for builds.][cargo/5995] Misc ---- - [`rustdoc` allows you to specify what edition to treat your code as with the `--edition` option.][54057] - [`rustdoc` now has the `--color` (specify whether to output color) and `--error-format` (specify error format, e.g. `json`) options.][53003] - [We now distribute a `rust-gdbgui` script that invokes `gdbgui` with Rust debug symbols.][53774] - [Attributes from Rust tools such as `rustfmt` or `clippy` are now available,][53459] e.g. `#[rustfmt::skip]` will skip formatting the next item. [50911]: https://github.com/rust-lang/rust/pull/50911/ [51363]: https://github.com/rust-lang/rust/pull/51363/ [51366]: https://github.com/rust-lang/rust/pull/51366/ [52081]: https://github.com/rust-lang/rust/pull/52081/ [53003]: https://github.com/rust-lang/rust/pull/53003/ [53033]: https://github.com/rust-lang/rust/pull/53033/ [53044]: https://github.com/rust-lang/rust/pull/53044/ [53165]: https://github.com/rust-lang/rust/pull/53165/ [53611]: https://github.com/rust-lang/rust/pull/53611/ [53236]: https://github.com/rust-lang/rust/pull/53236/ [53272]: https://github.com/rust-lang/rust/pull/53272/ [53370]: https://github.com/rust-lang/rust/pull/53370/ [53459]: https://github.com/rust-lang/rust/pull/53459/ [53774]: https://github.com/rust-lang/rust/pull/53774/ [53822]: https://github.com/rust-lang/rust/pull/53822/ [54057]: https://github.com/rust-lang/rust/pull/54057/ [54404]: https://github.com/rust-lang/rust/pull/54404/ [cargo/5877]: https://github.com/rust-lang/cargo/pull/5877/ [cargo/5878]: https://github.com/rust-lang/cargo/pull/5878/ [cargo/5995]: https://github.com/rust-lang/cargo/pull/5995/ [proc-macros]: https://doc.rust-lang.org/nightly/book/2018-edition/ch19-06-macros.html [`Ipv4Addr::BROADCAST`]: https://doc.rust-lang.org/nightly/std/net/struct.Ipv4Addr.html#associatedconstant.BROADCAST [`Ipv4Addr::LOCALHOST`]: https://doc.rust-lang.org/nightly/std/net/struct.Ipv4Addr.html#associatedconstant.LOCALHOST [`Ipv4Addr::UNSPECIFIED`]: https://doc.rust-lang.org/nightly/std/net/struct.Ipv4Addr.html#associatedconstant.UNSPECIFIED [`Ipv6Addr::LOCALHOST`]: https://doc.rust-lang.org/nightly/std/net/struct.Ipv6Addr.html#associatedconstant.LOCALHOST [`Ipv6Addr::UNSPECIFIED`]: https://doc.rust-lang.org/nightly/std/net/struct.Ipv6Addr.html#associatedconstant.UNSPECIFIED [`Iterator::find_map`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.find_map [`str::trim_end_matches`]: https://doc.rust-lang.org/nightly/std/primitive.str.html#method.trim_end_matches [`str::trim_end`]: https://doc.rust-lang.org/nightly/std/primitive.str.html#method.trim_end [`str::trim_start_matches`]: https://doc.rust-lang.org/nightly/std/primitive.str.html#method.trim_start_matches [`str::trim_start`]: https://doc.rust-lang.org/nightly/std/primitive.str.html#method.trim_start Version 1.29.2 (2018-10-11) =========================== - [Workaround for an aliasing-related LLVM bug, which caused miscompilation.][54639] - The `rls-preview` component on the windows-gnu targets has been restored. [54639]: https://github.com/rust-lang/rust/pull/54639 Version 1.29.1 (2018-09-25) =========================== Security Notes -------------- - The standard library's `str::repeat` function contained an out of bounds write caused by an integer overflow. This has been fixed by deterministically panicking when an overflow happens. Thank you to Scott McMurray for responsibly disclosing this vulnerability to us. Version 1.29.0 (2018-09-13) ========================== Compiler -------- - [Bumped minimum LLVM version to 5.0.][51899] - [Added `powerpc64le-unknown-linux-musl` target.][51619] - [Added `aarch64-unknown-hermit` and `x86_64-unknown-hermit` targets.][52861] - [Upgraded to LLVM 7.][51966] Libraries --------- - [`Once::call_once` no longer requires `Once` to be `'static`.][52239] - [`BuildHasherDefault` now implements `PartialEq` and `Eq`.][52402] - [`Box<CStr>`, `Box<OsStr>`, and `Box<Path>` now implement `Clone`.][51912] - [Implemented `PartialEq<&str>` for `OsString` and `PartialEq<OsString>` for `&str`.][51178] - [`Cell<T>` now allows `T` to be unsized.][50494] - [`SocketAddr` is now stable on Redox.][52656] Stabilized APIs --------------- - [`Arc::downcast`] - [`Iterator::flatten`] - [`Rc::downcast`] Cargo ----- - [Cargo can silently fix some bad lockfiles.][cargo/5831] You can use `--locked` to disable this behavior. - [`cargo-install` will now allow you to cross compile an install using `--target`.][cargo/5614] - [Added the `cargo-fix` subcommand to automatically move project code from 2015 edition to 2018.][cargo/5723] - [`cargo doc` can now optionally document private types using the `--document-private-items` flag.][cargo/5543] Misc ---- - [`rustdoc` now has the `--cap-lints` option which demotes all lints above the specified level to that level.][52354] For example `--cap-lints warn` will demote `deny` and `forbid` lints to `warn`. - [`rustc` and `rustdoc` will now have the exit code of `1` if compilation fails and `101` if there is a panic.][52197] - [A preview of clippy has been made available through rustup.][51122] You can install the preview with `rustup component add clippy-preview`. Compatibility Notes ------------------- - [`str::{slice_unchecked, slice_unchecked_mut}` are now deprecated.][51807] Use `str::get_unchecked(begin..end)` instead. - [`std::env::home_dir` is now deprecated for its unintuitive behavior.][51656] Consider using the `home_dir` function from https://crates.io/crates/dirs instead. - [`rustc` will no longer silently ignore invalid data in target spec.][52330] - [`cfg` attributes and `--cfg` command line flags are now more strictly validated.][53893] [53893]: https://github.com/rust-lang/rust/pull/53893/ [52861]: https://github.com/rust-lang/rust/pull/52861/ [51966]: https://github.com/rust-lang/rust/pull/51966/ [52656]: https://github.com/rust-lang/rust/pull/52656/ [52239]: https://github.com/rust-lang/rust/pull/52239/ [52330]: https://github.com/rust-lang/rust/pull/52330/ [52354]: https://github.com/rust-lang/rust/pull/52354/ [52402]: https://github.com/rust-lang/rust/pull/52402/ [52197]: https://github.com/rust-lang/rust/pull/52197/ [51807]: https://github.com/rust-lang/rust/pull/51807/ [51899]: https://github.com/rust-lang/rust/pull/51899/ [51912]: https://github.com/rust-lang/rust/pull/51912/ [51619]: https://github.com/rust-lang/rust/pull/51619/ [51656]: https://github.com/rust-lang/rust/pull/51656/ [51178]: https://github.com/rust-lang/rust/pull/51178/ [51122]: https://github.com/rust-lang/rust/pull/51122 [50494]: https://github.com/rust-lang/rust/pull/50494/ [cargo/5543]: https://github.com/rust-lang/cargo/pull/5543 [cargo/5614]: https://github.com/rust-lang/cargo/pull/5614/ [cargo/5723]: https://github.com/rust-lang/cargo/pull/5723/ [cargo/5831]: https://github.com/rust-lang/cargo/pull/5831/ [`Arc::downcast`]: https://doc.rust-lang.org/std/sync/struct.Arc.html#method.downcast [`Iterator::flatten`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.flatten [`Rc::downcast`]: https://doc.rust-lang.org/std/rc/struct.Rc.html#method.downcast Version 1.28.0 (2018-08-02) =========================== Language -------- - [The `#[repr(transparent)]` attribute is now stable.][51562] This attribute allows a Rust newtype wrapper (`struct NewType<T>(T);`) to be represented as the inner type across Foreign Function Interface (FFI) boundaries. - [The keywords `pure`, `sizeof`, `alignof`, and `offsetof` have been unreserved and can now be used as identifiers.][51196] - [The `GlobalAlloc` trait and `#[global_allocator]` attribute are now stable.][51241] This will allow users to specify a global allocator for their program. - [Unit test functions marked with the `#[test]` attribute can now return `Result<(), E: Debug>` in addition to `()`.][51298] - [The `lifetime` specifier for `macro_rules!` is now stable.][50385] This allows macros to easily target lifetimes. Compiler -------- - [The `s` and `z` optimisation levels are now stable.][50265] These optimisations prioritise making smaller binary sizes. `z` is the same as `s` with the exception that it does not vectorise loops, which typically results in an even smaller binary. - [The short error format is now stable.][49546] Specified with `--error-format=short` this option will provide a more compressed output of rust error messages. - [Added a lint warning when you have duplicated `macro_export`s.][50143] - [Reduced the number of allocations in the macro parser.][50855] This can improve compile times of macro heavy crates on average by 5%. Libraries --------- - [Implemented `Default` for `&mut str`.][51306] - [Implemented `From<bool>` for all integer and unsigned number types.][50554] - [Implemented `Extend` for `()`.][50234] - [The `Debug` implementation of `time::Duration` should now be more easily human readable.][50364] Previously a `Duration` of one second would printed as `Duration { secs: 1, nanos: 0 }` and will now be printed as `1s`. - [Implemented `From<&String>` for `Cow<str>`, `From<&Vec<T>>` for `Cow<[T]>`, `From<Cow<CStr>>` for `CString`, `From<CString>, From<CStr>, From<&CString>` for `Cow<CStr>`, `From<OsString>, From<OsStr>, From<&OsString>` for `Cow<OsStr>`, `From<&PathBuf>` for `Cow<Path>`, and `From<Cow<Path>>` for `PathBuf`.][50170] - [Implemented `Shl` and `Shr` for `Wrapping<u128>` and `Wrapping<i128>`.][50465] - [`DirEntry::metadata` now uses `fstatat` instead of `lstat` when possible.][51050] This can provide up to a 40% speed increase. - [Improved error messages when using `format!`.][50610] Stabilized APIs --------------- - [`Iterator::step_by`] - [`Path::ancestors`] - [`SystemTime::UNIX_EPOCH`] - [`alloc::GlobalAlloc`] - [`alloc::Layout`] - [`alloc::LayoutErr`] - [`alloc::System`] - [`alloc::alloc`] - [`alloc::alloc_zeroed`] - [`alloc::dealloc`] - [`alloc::realloc`] - [`alloc::handle_alloc_error`] - [`btree_map::Entry::or_default`] - [`fmt::Alignment`] - [`hash_map::Entry::or_default`] - [`iter::repeat_with`] - [`num::NonZeroUsize`] - [`num::NonZeroU128`] - [`num::NonZeroU16`] - [`num::NonZeroU32`] - [`num::NonZeroU64`] - [`num::NonZeroU8`] - [`ops::RangeBounds`] - [`slice::SliceIndex`] - [`slice::from_mut`] - [`slice::from_ref`] - [`{Any + Send + Sync}::downcast_mut`] - [`{Any + Send + Sync}::downcast_ref`] - [`{Any + Send + Sync}::is`] Cargo ----- - [Cargo will now no longer allow you to publish crates with build scripts that modify the `src` directory.][cargo/5584] The `src` directory in a crate should be considered to be immutable. Misc ---- - [The `suggestion_applicability` field in `rustc`'s json output is now stable.][50486] This will allow dev tools to check whether a code suggestion would apply to them. Compatibility Notes ------------------- - [Rust will consider trait objects with duplicated constraints to be the same type as without the duplicated constraint.][51276] For example the below code will now fail to compile. ```rust trait Trait {} impl Trait + Send { fn test(&self) { println!("one"); } //~ ERROR duplicate definitions with name `test` } impl Trait + Send + Send { fn test(&self) { println!("two"); } } ``` [49546]: https://github.com/rust-lang/rust/pull/49546/ [50143]: https://github.com/rust-lang/rust/pull/50143/ [50170]: https://github.com/rust-lang/rust/pull/50170/ [50234]: https://github.com/rust-lang/rust/pull/50234/ [50265]: https://github.com/rust-lang/rust/pull/50265/ [50364]: https://github.com/rust-lang/rust/pull/50364/ [50385]: https://github.com/rust-lang/rust/pull/50385/ [50465]: https://github.com/rust-lang/rust/pull/50465/ [50486]: https://github.com/rust-lang/rust/pull/50486/ [50554]: https://github.com/rust-lang/rust/pull/50554/ [50610]: https://github.com/rust-lang/rust/pull/50610/ [50855]: https://github.com/rust-lang/rust/pull/50855/ [51050]: https://github.com/rust-lang/rust/pull/51050/ [51196]: https://github.com/rust-lang/rust/pull/51196/ [51241]: https://github.com/rust-lang/rust/pull/51241/ [51276]: https://github.com/rust-lang/rust/pull/51276/ [51298]: https://github.com/rust-lang/rust/pull/51298/ [51306]: https://github.com/rust-lang/rust/pull/51306/ [51562]: https://github.com/rust-lang/rust/pull/51562/ [cargo/5584]: https://github.com/rust-lang/cargo/pull/5584/ [`Iterator::step_by`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.step_by [`Path::ancestors`]: https://doc.rust-lang.org/std/path/struct.Path.html#method.ancestors [`SystemTime::UNIX_EPOCH`]: https://doc.rust-lang.org/std/time/struct.SystemTime.html#associatedconstant.UNIX_EPOCH [`alloc::GlobalAlloc`]: https://doc.rust-lang.org/std/alloc/trait.GlobalAlloc.html [`alloc::Layout`]: https://doc.rust-lang.org/std/alloc/struct.Layout.html [`alloc::LayoutErr`]: https://doc.rust-lang.org/std/alloc/struct.LayoutErr.html [`alloc::System`]: https://doc.rust-lang.org/std/alloc/struct.System.html [`alloc::alloc`]: https://doc.rust-lang.org/std/alloc/fn.alloc.html [`alloc::alloc_zeroed`]: https://doc.rust-lang.org/std/alloc/fn.alloc_zeroed.html [`alloc::dealloc`]: https://doc.rust-lang.org/std/alloc/fn.dealloc.html [`alloc::realloc`]: https://doc.rust-lang.org/std/alloc/fn.realloc.html [`alloc::handle_alloc_error`]: https://doc.rust-lang.org/std/alloc/fn.handle_alloc_error.html [`btree_map::Entry::or_default`]: https://doc.rust-lang.org/std/collections/btree_map/enum.Entry.html#method.or_default [`fmt::Alignment`]: https://doc.rust-lang.org/std/fmt/enum.Alignment.html [`hash_map::Entry::or_default`]: https://doc.rust-lang.org/std/collections/hash_map/enum.Entry.html#method.or_default [`iter::repeat_with`]: https://doc.rust-lang.org/std/iter/fn.repeat_with.html [`num::NonZeroUsize`]: https://doc.rust-lang.org/std/num/struct.NonZeroUsize.html [`num::NonZeroU128`]: https://doc.rust-lang.org/std/num/struct.NonZeroU128.html [`num::NonZeroU16`]: https://doc.rust-lang.org/std/num/struct.NonZeroU16.html [`num::NonZeroU32`]: https://doc.rust-lang.org/std/num/struct.NonZeroU32.html [`num::NonZeroU64`]: https://doc.rust-lang.org/std/num/struct.NonZeroU64.html [`num::NonZeroU8`]: https://doc.rust-lang.org/std/num/struct.NonZeroU8.html [`ops::RangeBounds`]: https://doc.rust-lang.org/std/ops/trait.RangeBounds.html [`slice::SliceIndex`]: https://doc.rust-lang.org/std/slice/trait.SliceIndex.html [`slice::from_mut`]: https://doc.rust-lang.org/std/slice/fn.from_mut.html [`slice::from_ref`]: https://doc.rust-lang.org/std/slice/fn.from_ref.html [`{Any + Send + Sync}::downcast_mut`]: https://doc.rust-lang.org/std/any/trait.Any.html#method.downcast_mut-2 [`{Any + Send + Sync}::downcast_ref`]: https://doc.rust-lang.org/std/any/trait.Any.html#method.downcast_ref-2 [`{Any + Send + Sync}::is`]: https://doc.rust-lang.org/std/any/trait.Any.html#method.is-2 Version 1.27.2 (2018-07-20) =========================== Compatibility Notes ------------------- - The borrow checker was fixed to avoid potential unsoundness when using match ergonomics: [#52213][52213]. [52213]: https://github.com/rust-lang/rust/issues/52213 Version 1.27.1 (2018-07-10) =========================== Security Notes -------------- - rustdoc would execute plugins in the /tmp/rustdoc/plugins directory when running, which enabled executing code as some other user on a given machine. This release fixes that vulnerability; you can read more about this on the [blog][rustdoc-sec]. The associated CVE is [CVE-2018-1000622]. Thank you to Red Hat for responsibly disclosing this vulnerability to us. Compatibility Notes ------------------- - The borrow checker was fixed to avoid an additional potential unsoundness when using match ergonomics: [#51415][51415], [#49534][49534]. [51415]: https://github.com/rust-lang/rust/issues/51415 [49534]: https://github.com/rust-lang/rust/issues/49534 [rustdoc-sec]: https://blog.rust-lang.org/2018/07/06/security-advisory-for-rustdoc.html [CVE-2018-1000622]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=%20CVE-2018-1000622 Version 1.27.0 (2018-06-21) ========================== Language -------- - [Removed 'proc' from the reserved keywords list.][49699] This allows `proc` to be used as an identifier. - [The dyn syntax is now available.][49968] This syntax is equivalent to the bare `Trait` syntax, and should make it clearer when being used in tandem with `impl Trait` because it is equivalent to the following syntax: `&Trait == &dyn Trait`, `&mut Trait == &mut dyn Trait`, and `Box<Trait> == Box<dyn Trait>`. - [Attributes on generic parameters such as types and lifetimes are now stable.][48851] e.g. `fn foo<#[lifetime_attr] 'a, #[type_attr] T: 'a>() {}` - [The `#[must_use]` attribute can now also be used on functions as well as types.][48925] It provides a lint that by default warns users when the value returned by a function has not been used. Compiler -------- - [Added the `armv5te-unknown-linux-musleabi` target.][50423] Libraries --------- - [SIMD (Single Instruction Multiple Data) on x86/x86_64 is now stable.][49664] This includes [`arch::x86`] & [`arch::x86_64`] modules which contain SIMD intrinsics, a new macro called `is_x86_feature_detected!`, the `#[target_feature(enable="")]` attribute, and adding `target_feature = ""` to the `cfg` attribute. - [A lot of methods for `[u8]`, `f32`, and `f64` previously only available in std are now available in core.][49896] - [The generic `Rhs` type parameter on `ops::{Shl, ShlAssign, Shr}` now defaults to `Self`.][49630] - [`std::str::replace` now has the `#[must_use]` attribute][50177] to clarify that the operation isn't done in place. - [`Clone::clone`, `Iterator::collect`, and `ToOwned::to_owned` now have the `#[must_use]` attribute][49533] to warn about unused potentially expensive allocations. Stabilized APIs --------------- - [`DoubleEndedIterator::rfind`] - [`DoubleEndedIterator::rfold`] - [`DoubleEndedIterator::try_rfold`] - [`Duration::from_micros`] - [`Duration::from_nanos`] - [`Duration::subsec_micros`] - [`Duration::subsec_millis`] - [`HashMap::remove_entry`] - [`Iterator::try_fold`] - [`Iterator::try_for_each`] - [`NonNull::cast`] - [`Option::filter`] - [`String::replace_range`] - [`Take::set_limit`] - [`hint::unreachable_unchecked`] - [`os::unix::process::parent_id`] - [`ptr::swap_nonoverlapping`] - [`slice::rsplit_mut`] - [`slice::rsplit`] - [`slice::swap_with_slice`] Cargo ----- - [`cargo-metadata` now includes `authors`, `categories`, `keywords`, `readme`, and `repository` fields.][cargo/5386] - [`cargo-metadata` now includes a package's `metadata` table.][cargo/5360] - [Added the `--target-dir` optional argument.][cargo/5393] This allows you to specify a different directory than `target` for placing compilation artifacts. - [Cargo will be adding automatic target inference for binaries, benchmarks, examples, and tests in the Rust 2018 edition.][cargo/5335] If your project specifies specific targets, e.g. using `[[bin]]`, and have other binaries in locations where cargo would infer a binary, Cargo will produce a warning. You can disable this feature ahead of time by setting any of the following to false: `autobins`, `autobenches`, `autoexamples`, `autotests`. - [Cargo will now cache compiler information.][cargo/5359] This can be disabled by setting `CARGO_CACHE_RUSTC_INFO=0` in your environment. Misc ---- - [Added “The Rustc book” into the official documentation.][49707] [“The Rustc book”] documents and teaches how to use the rustc compiler. - [All books available on `doc.rust-lang.org` are now searchable.][49623] Compatibility Notes ------------------- - [Calling a `CharExt` or `StrExt` method directly on core will no longer work.][49896] e.g. `::core::prelude::v1::StrExt::is_empty("")` will not compile, `"".is_empty()` will still compile. - [`Debug` output on `atomic::{AtomicBool, AtomicIsize, AtomicPtr, AtomicUsize}` will only print the inner type.][48553] E.g. `print!("{:?}", AtomicBool::new(true))` will print `true`, not `AtomicBool(true)`. - [The maximum number for `repr(align(N))` is now 2²⁹.][50378] Previously you could enter higher numbers but they were not supported by LLVM. Up to 512MB alignment should cover all use cases. - The `.description()` method on the `std::error::Error` trait [has been soft-deprecated][50163]. It is no longer required to implement it. [48553]: https://github.com/rust-lang/rust/pull/48553/ [48851]: https://github.com/rust-lang/rust/pull/48851/ [48925]: https://github.com/rust-lang/rust/pull/48925/ [49533]: https://github.com/rust-lang/rust/pull/49533/ [49623]: https://github.com/rust-lang/rust/pull/49623/ [49630]: https://github.com/rust-lang/rust/pull/49630/ [49664]: https://github.com/rust-lang/rust/pull/49664/ [49699]: https://github.com/rust-lang/rust/pull/49699/ [49707]: https://github.com/rust-lang/rust/pull/49707/ [49896]: https://github.com/rust-lang/rust/pull/49896/ [49968]: https://github.com/rust-lang/rust/pull/49968/ [50163]: https://github.com/rust-lang/rust/pull/50163 [50177]: https://github.com/rust-lang/rust/pull/50177/ [50378]: https://github.com/rust-lang/rust/pull/50378/ [50423]: https://github.com/rust-lang/rust/pull/50423/ [cargo/5335]: https://github.com/rust-lang/cargo/pull/5335/ [cargo/5359]: https://github.com/rust-lang/cargo/pull/5359/ [cargo/5360]: https://github.com/rust-lang/cargo/pull/5360/ [cargo/5386]: https://github.com/rust-lang/cargo/pull/5386/ [cargo/5393]: https://github.com/rust-lang/cargo/pull/5393/ [`DoubleEndedIterator::rfind`]: https://doc.rust-lang.org/std/iter/trait.DoubleEndedIterator.html#method.rfind [`DoubleEndedIterator::rfold`]: https://doc.rust-lang.org/std/iter/trait.DoubleEndedIterator.html#method.rfold [`DoubleEndedIterator::try_rfold`]: https://doc.rust-lang.org/std/iter/trait.DoubleEndedIterator.html#method.try_rfold [`Duration::from_micros`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.from_micros [`Duration::from_nanos`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.from_nanos [`Duration::subsec_micros`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.subsec_micros [`Duration::subsec_millis`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.subsec_millis [`HashMap::remove_entry`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.remove_entry [`Iterator::try_fold`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.try_fold [`Iterator::try_for_each`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.try_for_each [`NonNull::cast`]: https://doc.rust-lang.org/std/ptr/struct.NonNull.html#method.cast [`Option::filter`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.filter [`String::replace_range`]: https://doc.rust-lang.org/std/string/struct.String.html#method.replace_range [`Take::set_limit`]: https://doc.rust-lang.org/std/io/struct.Take.html#method.set_limit [`hint::unreachable_unchecked`]: https://doc.rust-lang.org/std/hint/fn.unreachable_unchecked.html [`os::unix::process::parent_id`]: https://doc.rust-lang.org/std/os/unix/process/fn.parent_id.html [`process::id`]: https://doc.rust-lang.org/std/process/fn.id.html [`ptr::swap_nonoverlapping`]: https://doc.rust-lang.org/std/ptr/fn.swap_nonoverlapping.html [`slice::rsplit_mut`]: https://doc.rust-lang.org/std/primitive.slice.html#method.rsplit_mut [`slice::rsplit`]: https://doc.rust-lang.org/std/primitive.slice.html#method.rsplit [`slice::swap_with_slice`]: https://doc.rust-lang.org/std/primitive.slice.html#method.swap_with_slice [`arch::x86_64`]: https://doc.rust-lang.org/std/arch/x86_64/index.html [`arch::x86`]: https://doc.rust-lang.org/std/arch/x86/index.html [“The Rustc book”]: https://doc.rust-lang.org/rustc Version 1.26.2 (2018-06-05) ========================== Compatibility Notes ------------------- - [The borrow checker was fixed to avoid unsoundness when using match ergonomics.][51117] [51117]: https://github.com/rust-lang/rust/issues/51117 Version 1.26.1 (2018-05-29) ========================== Tools ----- - [RLS now works on Windows.][50646] - [Rustfmt stopped badly formatting text in some cases.][rustfmt/2695] Compatibility Notes -------- - [`fn main() -> impl Trait` no longer works for non-Termination trait.][50656] This reverts an accidental stabilization. - [`NaN > NaN` no longer returns true in const-fn contexts.][50812] - [Prohibit using turbofish for `impl Trait` in method arguments.][50950] [50646]: https://github.com/rust-lang/rust/issues/50646 [50656]: https://github.com/rust-lang/rust/pull/50656 [50812]: https://github.com/rust-lang/rust/pull/50812 [50950]: https://github.com/rust-lang/rust/issues/50950 [rustfmt/2695]: https://github.com/rust-lang-nursery/rustfmt/issues/2695 Version 1.26.0 (2018-05-10) ========================== Language -------- - [Closures now implement `Copy` and/or `Clone` if all captured variables implement either or both traits.][49299] - [The inclusive range syntax e.g. `for x in 0..=10` is now stable.][47813] - [The `'_` lifetime is now stable. The underscore lifetime can be used anywhere a lifetime can be elided.][49458] - [`impl Trait` is now stable allowing you to have abstract types in returns or in function parameters.][49255] E.g. `fn foo() -> impl Iterator<Item=u8>` or `fn open(path: impl AsRef<Path>)`. - [Pattern matching will now automatically apply dereferences.][49394] - [128-bit integers in the form of `u128` and `i128` are now stable.][49101] - [`main` can now return `Result<(), E: Debug>`][49162] in addition to `()`. - [A lot of operations are now available in a const context.][46882] E.g. You can now index into constant arrays, reference and dereference into constants, and use tuple struct constructors. - [Fixed entry slice patterns are now stable.][48516] E.g. ```rust let points = [1, 2, 3, 4]; match points { [1, 2, 3, 4] => println!("All points were sequential."), _ => println!("Not all points were sequential."), } ``` Compiler -------- - [LLD is now used as the default linker for `wasm32-unknown-unknown`.][48125] - [Fixed exponential projection complexity on nested types.][48296] This can provide up to a ~12% reduction in compile times for certain crates. - [Added the `--remap-path-prefix` option to rustc.][48359] Allowing you to remap path prefixes outputted by the compiler. - [Added `powerpc-unknown-netbsd` target.][48281] Libraries --------- - [Implemented `From<u16> for usize` & `From<{u8, i16}> for isize`.][49305] - [Added hexadecimal formatting for integers with fmt::Debug][48978] e.g. `assert!(format!("{:02x?}", b"Foo\0") == "[46, 6f, 6f, 00]")` - [Implemented `Default, Hash` for `cmp::Reverse`.][48628] - [Optimized `str::repeat` being 8x faster in large cases.][48657] - [`ascii::escape_default` is now available in libcore.][48735] - [Trailing commas are now supported in std and core macros.][48056] - [Implemented `Copy, Clone` for `cmp::Reverse`][47379] - [Implemented `Clone` for `char::{ToLowercase, ToUppercase}`.][48629] Stabilized APIs --------------- - [`*const T::add`] - [`*const T::copy_to_nonoverlapping`] - [`*const T::copy_to`] - [`*const T::read_unaligned`] - [`*const T::read_volatile`] - [`*const T::read`] - [`*const T::sub`] - [`*const T::wrapping_add`] - [`*const T::wrapping_sub`] - [`*mut T::add`] - [`*mut T::copy_to_nonoverlapping`] - [`*mut T::copy_to`] - [`*mut T::read_unaligned`] - [`*mut T::read_volatile`] - [`*mut T::read`] - [`*mut T::replace`] - [`*mut T::sub`] - [`*mut T::swap`] - [`*mut T::wrapping_add`] - [`*mut T::wrapping_sub`] - [`*mut T::write_bytes`] - [`*mut T::write_unaligned`] - [`*mut T::write_volatile`] - [`*mut T::write`] - [`Box::leak`] - [`FromUtf8Error::as_bytes`] - [`LocalKey::try_with`] - [`Option::cloned`] - [`btree_map::Entry::and_modify`] - [`fs::read_to_string`] - [`fs::read`] - [`fs::write`] - [`hash_map::Entry::and_modify`] - [`iter::FusedIterator`] - [`ops::RangeInclusive`] - [`ops::RangeToInclusive`] - [`process::id`] - [`slice::rotate_left`] - [`slice::rotate_right`] - [`String::retain`] Cargo ----- - [Cargo will now output path to custom commands when `-v` is passed with `--list`][cargo/5041] - [The Cargo binary version is now the same as the Rust version][cargo/5083] Misc ---- - [The second edition of "The Rust Programming Language" book is now recommended over the first.][48404] Compatibility Notes ------------------- - [aliasing a `Fn` trait as `dyn` no longer works.][48481] E.g. the following syntax is now invalid. ``` use std::ops::Fn as dyn; fn g(_: Box<dyn(std::fmt::Debug)>) {} ``` - [The result of dereferences are no longer promoted to `'static`.][47408] e.g. ```rust fn main() { const PAIR: &(i32, i32) = &(0, 1); let _reversed_pair: &'static _ = &(PAIR.1, PAIR.0); // Doesn't work } ``` - [Deprecate `AsciiExt` trait in favor of inherent methods.][49109] - [`".e0"` will now no longer parse as `0.0` and will instead cause an error.][48235] - [Removed hoedown from rustdoc.][48274] - [Bounds on higher-kinded lifetimes a hard error.][48326] [46882]: https://github.com/rust-lang/rust/pull/46882 [47379]: https://github.com/rust-lang/rust/pull/47379 [47408]: https://github.com/rust-lang/rust/pull/47408 [47813]: https://github.com/rust-lang/rust/pull/47813 [48056]: https://github.com/rust-lang/rust/pull/48056 [48125]: https://github.com/rust-lang/rust/pull/48125 [48235]: https://github.com/rust-lang/rust/pull/48235 [48274]: https://github.com/rust-lang/rust/pull/48274 [48281]: https://github.com/rust-lang/rust/pull/48281 [48296]: https://github.com/rust-lang/rust/pull/48296 [48326]: https://github.com/rust-lang/rust/pull/48326 [48359]: https://github.com/rust-lang/rust/pull/48359 [48404]: https://github.com/rust-lang/rust/pull/48404 [48481]: https://github.com/rust-lang/rust/pull/48481 [48516]: https://github.com/rust-lang/rust/pull/48516 [48628]: https://github.com/rust-lang/rust/pull/48628 [48629]: https://github.com/rust-lang/rust/pull/48629 [48657]: https://github.com/rust-lang/rust/pull/48657 [48735]: https://github.com/rust-lang/rust/pull/48735 [48978]: https://github.com/rust-lang/rust/pull/48978 [49101]: https://github.com/rust-lang/rust/pull/49101 [49109]: https://github.com/rust-lang/rust/pull/49109 [49162]: https://github.com/rust-lang/rust/pull/49162 [49255]: https://github.com/rust-lang/rust/pull/49255 [49299]: https://github.com/rust-lang/rust/pull/49299 [49305]: https://github.com/rust-lang/rust/pull/49305 [49394]: https://github.com/rust-lang/rust/pull/49394 [49458]: https://github.com/rust-lang/rust/pull/49458 [`*const T::add`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.add [`*const T::copy_to_nonoverlapping`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.copy_to_nonoverlapping [`*const T::copy_to`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.copy_to [`*const T::read_unaligned`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.read_unaligned [`*const T::read_volatile`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.read_volatile [`*const T::read`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.read [`*const T::sub`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.sub [`*const T::wrapping_add`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_add [`*const T::wrapping_sub`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_sub [`*mut T::add`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.add-1 [`*mut T::copy_to_nonoverlapping`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.copy_to_nonoverlapping-1 [`*mut T::copy_to`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.copy_to-1 [`*mut T::read_unaligned`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.read_unaligned-1 [`*mut T::read_volatile`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.read_volatile-1 [`*mut T::read`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.read-1 [`*mut T::replace`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.replace [`*mut T::sub`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.sub-1 [`*mut T::swap`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.swap [`*mut T::wrapping_add`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_add-1 [`*mut T::wrapping_sub`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_sub-1 [`*mut T::write_bytes`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.write_bytes [`*mut T::write_unaligned`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.write_unaligned [`*mut T::write_volatile`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.write_volatile [`*mut T::write`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.write [`Box::leak`]: https://doc.rust-lang.org/std/boxed/struct.Box.html#method.leak [`FromUtf8Error::as_bytes`]: https://doc.rust-lang.org/std/string/struct.FromUtf8Error.html#method.as_bytes [`LocalKey::try_with`]: https://doc.rust-lang.org/std/thread/struct.LocalKey.html#method.try_with [`Option::cloned`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.cloned [`btree_map::Entry::and_modify`]: https://doc.rust-lang.org/std/collections/btree_map/enum.Entry.html#method.and_modify [`fs::read_to_string`]: https://doc.rust-lang.org/std/fs/fn.read_to_string.html [`fs::read`]: https://doc.rust-lang.org/std/fs/fn.read.html [`fs::write`]: https://doc.rust-lang.org/std/fs/fn.write.html [`hash_map::Entry::and_modify`]: https://doc.rust-lang.org/std/collections/hash_map/enum.Entry.html#method.and_modify [`iter::FusedIterator`]: https://doc.rust-lang.org/std/iter/trait.FusedIterator.html [`ops::RangeInclusive`]: https://doc.rust-lang.org/std/ops/struct.RangeInclusive.html [`ops::RangeToInclusive`]: https://doc.rust-lang.org/std/ops/struct.RangeToInclusive.html [`process::id`]: https://doc.rust-lang.org/std/process/fn.id.html [`slice::rotate_left`]: https://doc.rust-lang.org/std/primitive.slice.html#method.rotate_left [`slice::rotate_right`]: https://doc.rust-lang.org/std/primitive.slice.html#method.rotate_right [`String::retain`]: https://doc.rust-lang.org/std/string/struct.String.html#method.retain [cargo/5041]: https://github.com/rust-lang/cargo/pull/5041 [cargo/5083]: https://github.com/rust-lang/cargo/pull/5083 Version 1.25.0 (2018-03-29) ========================== Language -------- - [The `#[repr(align(x))]` attribute is now stable.][47006] [RFC 1358] - [You can now use nested groups of imports.][47948] e.g. `use std::{fs::File, io::Read, path::{Path, PathBuf}};` - [You can now have `|` at the start of a match arm.][47947] e.g. ```rust enum Foo { A, B, C } fn main() { let x = Foo::A; match x { | Foo::A | Foo::B => println!("AB"), | Foo::C => println!("C"), } } ``` Compiler -------- - [Upgraded to LLVM 6.][47828] - [Added `-C lto=val` option.][47521] - [Added `i586-unknown-linux-musl` target][47282] Libraries --------- - [Impl Send for `process::Command` on Unix.][47760] - [Impl PartialEq and Eq for `ParseCharError`.][47790] - [`UnsafeCell::into_inner` is now safe.][47204] - [Implement libstd for CloudABI.][47268] - [`Float::{from_bits, to_bits}` is now available in libcore.][46931] - [Implement `AsRef<Path>` for Component][46985] - [Implemented `Write` for `Cursor<&mut Vec<u8>>`][46830] - [Moved `Duration` to libcore.][46666] Stabilized APIs --------------- - [`Location::column`] - [`ptr::NonNull`] The following functions can now be used in a constant expression. eg. `static MINUTE: Duration = Duration::from_secs(60);` - [`Duration::new`][47300] - [`Duration::from_secs`][47300] - [`Duration::from_millis`][47300] Cargo ----- - [`cargo new` no longer removes `rust` or `rs` prefixes/suffixes.][cargo/5013] - [`cargo new` now defaults to creating a binary crate, instead of a library crate.][cargo/5029] Misc ---- - [Rust by example is now shipped with new releases][46196] Compatibility Notes ------------------- - [Deprecated `net::lookup_host`.][47510] - [`rustdoc` has switched to pulldown as the default markdown renderer.][47398] - The borrow checker was sometimes incorrectly permitting overlapping borrows around indexing operations (see [#47349][47349]). This has been fixed (which also enabled some correct code that used to cause errors (e.g. [#33903][33903] and [#46095][46095]). - [Removed deprecated unstable attribute `#[simd]`.][47251] [33903]: https://github.com/rust-lang/rust/pull/33903 [47947]: https://github.com/rust-lang/rust/pull/47947 [47948]: https://github.com/rust-lang/rust/pull/47948 [47760]: https://github.com/rust-lang/rust/pull/47760 [47790]: https://github.com/rust-lang/rust/pull/47790 [47828]: https://github.com/rust-lang/rust/pull/47828 [47398]: https://github.com/rust-lang/rust/pull/47398 [47510]: https://github.com/rust-lang/rust/pull/47510 [47521]: https://github.com/rust-lang/rust/pull/47521 [47204]: https://github.com/rust-lang/rust/pull/47204 [47251]: https://github.com/rust-lang/rust/pull/47251 [47268]: https://github.com/rust-lang/rust/pull/47268 [47282]: https://github.com/rust-lang/rust/pull/47282 [47300]: https://github.com/rust-lang/rust/pull/47300 [47349]: https://github.com/rust-lang/rust/pull/47349 [46931]: https://github.com/rust-lang/rust/pull/46931 [46985]: https://github.com/rust-lang/rust/pull/46985 [47006]: https://github.com/rust-lang/rust/pull/47006 [46830]: https://github.com/rust-lang/rust/pull/46830 [46095]: https://github.com/rust-lang/rust/pull/46095 [46666]: https://github.com/rust-lang/rust/pull/46666 [46196]: https://github.com/rust-lang/rust/pull/46196 [cargo/5013]: https://github.com/rust-lang/cargo/pull/5013 [cargo/5029]: https://github.com/rust-lang/cargo/pull/5029 [RFC 1358]: https://github.com/rust-lang/rfcs/pull/1358 [`Location::column`]: https://doc.rust-lang.org/std/panic/struct.Location.html#method.column [`ptr::NonNull`]: https://doc.rust-lang.org/std/ptr/struct.NonNull.html Version 1.24.1 (2018-03-01) ========================== - [Do not abort when unwinding through FFI][48251] - [Emit UTF-16 files for linker arguments on Windows][48318] - [Make the error index generator work again][48308] - [Cargo will warn on Windows 7 if an update is needed][cargo/5069]. [48251]: https://github.com/rust-lang/rust/issues/48251 [48308]: https://github.com/rust-lang/rust/issues/48308 [48318]: https://github.com/rust-lang/rust/issues/48318 [cargo/5069]: https://github.com/rust-lang/cargo/pull/5069 Version 1.24.0 (2018-02-15) ========================== Language -------- - [External `sysv64` ffi is now available.][46528] eg. `extern "sysv64" fn foo () {}` Compiler -------- - [rustc now uses 16 codegen units by default for release builds.][46910] For the fastest builds, utilize `codegen-units=1`. - [Added `armv4t-unknown-linux-gnueabi` target.][47018] - [Add `aarch64-unknown-openbsd` support][46760] Libraries --------- - [`str::find::<char>` now uses memchr.][46735] This should lead to a 10x improvement in performance in the majority of cases. - [`OsStr`'s `Debug` implementation is now lossless and consistent with Windows.][46798] - [`time::{SystemTime, Instant}` now implement `Hash`.][46828] - [impl `From<bool>` for `AtomicBool`][46293] - [impl `From<{CString, &CStr}>` for `{Arc<CStr>, Rc<CStr>}`][45990] - [impl `From<{OsString, &OsStr}>` for `{Arc<OsStr>, Rc<OsStr>}`][45990] - [impl `From<{PathBuf, &Path}>` for `{Arc<Path>, Rc<Path>}`][45990] - [float::from_bits now just uses transmute.][46012] This provides some optimisations from LLVM. - [Copied `AsciiExt` methods onto `char`][46077] - [Remove `T: Sized` requirement on `ptr::is_null()`][46094] - [impl `From<RecvError>` for `{TryRecvError, RecvTimeoutError}`][45506] - [Optimised `f32::{min, max}` to generate more efficient x86 assembly][47080] - [`[u8]::contains` now uses memchr which provides a 3x speed improvement][46713] Stabilized APIs --------------- - [`RefCell::replace`] - [`RefCell::swap`] - [`atomic::spin_loop_hint`] The following functions can now be used in a constant expression. eg. `let buffer: [u8; size_of::<usize>()];`, `static COUNTER: AtomicUsize = AtomicUsize::new(1);` - [`AtomicBool::new`][46287] - [`AtomicUsize::new`][46287] - [`AtomicIsize::new`][46287] - [`AtomicPtr::new`][46287] - [`Cell::new`][46287] - [`{integer}::min_value`][46287] - [`{integer}::max_value`][46287] - [`mem::size_of`][46287] - [`mem::align_of`][46287] - [`ptr::null`][46287] - [`ptr::null_mut`][46287] - [`RefCell::new`][46287] - [`UnsafeCell::new`][46287] Cargo ----- - [Added a `workspace.default-members` config that overrides implied `--all` in virtual workspaces.][cargo/4743] - [Enable incremental by default on development builds.][cargo/4817] Also added configuration keys to `Cargo.toml` and `.cargo/config` to disable on a per-project or global basis respectively. Misc ---- Compatibility Notes ------------------- - [Floating point types `Debug` impl now always prints a decimal point.][46831] - [`Ipv6Addr` now rejects superfluous `::`'s in IPv6 addresses][46671] This is in accordance with IETF RFC 4291 §2.2. - [Unwinding will no longer go past FFI boundaries, and will instead abort.][46833] - [`Formatter::flags` method is now deprecated.][46284] The `sign_plus`, `sign_minus`, `alternate`, and `sign_aware_zero_pad` should be used instead. - [Leading zeros in tuple struct members is now an error][47084] - [`column!()` macro is one-based instead of zero-based][46977] - [`fmt::Arguments` can no longer be shared across threads][45198] - [Access to `#[repr(packed)]` struct fields is now unsafe][44884] - [Cargo sets a different working directory for the compiler][cargo/4788] [44884]: https://github.com/rust-lang/rust/pull/44884 [45198]: https://github.com/rust-lang/rust/pull/45198 [45506]: https://github.com/rust-lang/rust/pull/45506 [45990]: https://github.com/rust-lang/rust/pull/45990 [46012]: https://github.com/rust-lang/rust/pull/46012 [46077]: https://github.com/rust-lang/rust/pull/46077 [46094]: https://github.com/rust-lang/rust/pull/46094 [46284]: https://github.com/rust-lang/rust/pull/46284 [46287]: https://github.com/rust-lang/rust/pull/46287 [46293]: https://github.com/rust-lang/rust/pull/46293 [46528]: https://github.com/rust-lang/rust/pull/46528 [46671]: https://github.com/rust-lang/rust/pull/46671 [46713]: https://github.com/rust-lang/rust/pull/46713 [46735]: https://github.com/rust-lang/rust/pull/46735 [46760]: https://github.com/rust-lang/rust/pull/46760 [46798]: https://github.com/rust-lang/rust/pull/46798 [46828]: https://github.com/rust-lang/rust/pull/46828 [46831]: https://github.com/rust-lang/rust/pull/46831 [46833]: https://github.com/rust-lang/rust/pull/46833 [46910]: https://github.com/rust-lang/rust/pull/46910 [46977]: https://github.com/rust-lang/rust/pull/46977 [47018]: https://github.com/rust-lang/rust/pull/47018 [47080]: https://github.com/rust-lang/rust/pull/47080 [47084]: https://github.com/rust-lang/rust/pull/47084 [cargo/4743]: https://github.com/rust-lang/cargo/pull/4743 [cargo/4788]: https://github.com/rust-lang/cargo/pull/4788 [cargo/4817]: https://github.com/rust-lang/cargo/pull/4817 [`RefCell::replace`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.replace [`RefCell::swap`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.swap [`atomic::spin_loop_hint`]: https://doc.rust-lang.org/std/sync/atomic/fn.spin_loop_hint.html Version 1.23.0 (2018-01-04) ========================== Language -------- - [Arbitrary `auto` traits are now permitted in trait objects.][45772] - [rustc now uses subtyping on the left hand side of binary operations.][45435] Which should fix some confusing errors in some operations. Compiler -------- - [Enabled `TrapUnreachable` in LLVM which should mitigate the impact of undefined behavior.][45920] - [rustc now suggests renaming import if names clash.][45660] - [Display errors/warnings correctly when there are zero-width or wide characters.][45711] - [rustc now avoids unnecessary copies of arguments that are simple bindings][45380] This should improve memory usage on average by 5-10%. - [Updated musl used to build musl rustc to 1.1.17][45393] Libraries --------- - [Allow a trailing comma in `assert_eq/ne` macro][45887] - [Implement Hash for raw pointers to unsized types][45483] - [impl `From<*mut T>` for `AtomicPtr<T>`][45610] - [impl `From<usize/isize>` for `AtomicUsize/AtomicIsize`.][45610] - [Removed the `T: Sync` requirement for `RwLock<T>: Send`][45267] - [Removed `T: Sized` requirement for `{<*const T>, <*mut T>}::as_ref` and `<*mut T>::as_mut`][44932] - [Optimized `Thread::{park, unpark}` implementation][45524] - [Improved `SliceExt::binary_search` performance.][45333] - [impl `FromIterator<()>` for `()`][45379] - [Copied `AsciiExt` trait methods to primitive types.][44042] Use of `AsciiExt` is now deprecated. Stabilized APIs --------------- Cargo ----- - [Cargo now supports uninstallation of multiple packages][cargo/4561] eg. `cargo uninstall foo bar` uninstalls `foo` and `bar`. - [Added unit test checking to `cargo check`][cargo/4592] - [Cargo now lets you install a specific version using `cargo install --version`][cargo/4637] Misc ---- - [Releases now ship with the Cargo book documentation.][45692] - [rustdoc now prints rendering warnings on every run.][45324] Compatibility Notes ------------------- - [Changes have been made to type equality to make it more correct, in rare cases this could break some code.][45853] [Tracking issue for further information][45852] - [`char::escape_debug` now uses Unicode 10 over 9.][45571] - [Upgraded Android SDK to 27, and NDK to r15c.][45580] This drops support for Android 9, the minimum supported version is Android 14. - [Bumped the minimum LLVM to 3.9][45326] [44042]: https://github.com/rust-lang/rust/pull/44042 [44932]: https://github.com/rust-lang/rust/pull/44932 [45267]: https://github.com/rust-lang/rust/pull/45267 [45324]: https://github.com/rust-lang/rust/pull/45324 [45326]: https://github.com/rust-lang/rust/pull/45326 [45333]: https://github.com/rust-lang/rust/pull/45333 [45379]: https://github.com/rust-lang/rust/pull/45379 [45380]: https://github.com/rust-lang/rust/pull/45380 [45393]: https://github.com/rust-lang/rust/pull/45393 [45435]: https://github.com/rust-lang/rust/pull/45435 [45483]: https://github.com/rust-lang/rust/pull/45483 [45524]: https://github.com/rust-lang/rust/pull/45524 [45571]: https://github.com/rust-lang/rust/pull/45571 [45580]: https://github.com/rust-lang/rust/pull/45580 [45610]: https://github.com/rust-lang/rust/pull/45610 [45660]: https://github.com/rust-lang/rust/pull/45660 [45692]: https://github.com/rust-lang/rust/pull/45692 [45711]: https://github.com/rust-lang/rust/pull/45711 [45772]: https://github.com/rust-lang/rust/pull/45772 [45852]: https://github.com/rust-lang/rust/issues/45852 [45853]: https://github.com/rust-lang/rust/pull/45853 [45887]: https://github.com/rust-lang/rust/pull/45887 [45920]: https://github.com/rust-lang/rust/pull/45920 [cargo/4561]: https://github.com/rust-lang/cargo/pull/4561 [cargo/4592]: https://github.com/rust-lang/cargo/pull/4592 [cargo/4637]: https://github.com/rust-lang/cargo/pull/4637 Version 1.22.1 (2017-11-22) ========================== - [Update Cargo to fix an issue with macOS 10.13 "High Sierra"][46183] [46183]: https://github.com/rust-lang/rust/pull/46183 Version 1.22.0 (2017-11-22) ========================== Language -------- - [`non_snake_case` lint now allows extern no-mangle functions][44966] - [Now accepts underscores in unicode escapes][43716] - [`T op= &T` now works for numeric types.][44287] eg. `let mut x = 2; x += &8;` - [types that impl `Drop` are now allowed in `const` and `static` types][44456] Compiler -------- - [rustc now defaults to having 16 codegen units at debug on supported platforms.][45064] - [rustc will no longer inline in codegen units when compiling for debug][45075] This should decrease compile times for debug builds. - [strict memory alignment now enabled on ARMv6][45094] - [Remove support for the PNaCl target `le32-unknown-nacl`][45041] Libraries --------- - [Allow atomic operations up to 32 bits on `armv5te_unknown_linux_gnueabi`][44978] - [`Box<Error>` now impls `From<Cow<str>>`][44466] - [`std::mem::Discriminant` is now guaranteed to be `Send + Sync`][45095] - [`fs::copy` now returns the length of the main stream on NTFS.][44895] - [Properly detect overflow in `Instant += Duration`.][44220] - [impl `Hasher` for `{&mut Hasher, Box<Hasher>}`][44015] - [impl `fmt::Debug` for `SplitWhitespace`.][44303] - [`Option<T>` now impls `Try`][42526] This allows for using `?` with `Option` types. Stabilized APIs --------------- Cargo ----- - [Cargo will now build multi file examples in subdirectories of the `examples` folder that have a `main.rs` file.][cargo/4496] - [Changed `[root]` to `[package]` in `Cargo.lock`][cargo/4571] Packages with the old format will continue to work and can be updated with `cargo update`. - [Now supports vendoring git repositories][cargo/3992] Misc ---- - [`libbacktrace` is now available on Apple platforms.][44251] - [Stabilised the `compile_fail` attribute for code fences in doc-comments.][43949] This now lets you specify that a given code example will fail to compile. Compatibility Notes ------------------- - [The minimum Android version that rustc can build for has been bumped to `4.0` from `2.3`][45656] - [Allowing `T op= &T` for numeric types has broken some type inference cases][45480] [42526]: https://github.com/rust-lang/rust/pull/42526 [43716]: https://github.com/rust-lang/rust/pull/43716 [43949]: https://github.com/rust-lang/rust/pull/43949 [44015]: https://github.com/rust-lang/rust/pull/44015 [44220]: https://github.com/rust-lang/rust/pull/44220 [44251]: https://github.com/rust-lang/rust/pull/44251 [44287]: https://github.com/rust-lang/rust/pull/44287 [44303]: https://github.com/rust-lang/rust/pull/44303 [44456]: https://github.com/rust-lang/rust/pull/44456 [44466]: https://github.com/rust-lang/rust/pull/44466 [44895]: https://github.com/rust-lang/rust/pull/44895 [44966]: https://github.com/rust-lang/rust/pull/44966 [44978]: https://github.com/rust-lang/rust/pull/44978 [45041]: https://github.com/rust-lang/rust/pull/45041 [45064]: https://github.com/rust-lang/rust/pull/45064 [45075]: https://github.com/rust-lang/rust/pull/45075 [45094]: https://github.com/rust-lang/rust/pull/45094 [45095]: https://github.com/rust-lang/rust/pull/45095 [45480]: https://github.com/rust-lang/rust/issues/45480 [45656]: https://github.com/rust-lang/rust/pull/45656 [cargo/3992]: https://github.com/rust-lang/cargo/pull/3992 [cargo/4496]: https://github.com/rust-lang/cargo/pull/4496 [cargo/4571]: https://github.com/rust-lang/cargo/pull/4571 Version 1.21.0 (2017-10-12) ========================== Language -------- - [You can now use static references for literals.][43838] Example: ```rust fn main() { let x: &'static u32 = &0; } ``` - [Relaxed path syntax. Optional `::` before `<` is now allowed in all contexts.][43540] Example: ```rust my_macro!(Vec<i32>::new); // Always worked my_macro!(Vec::<i32>::new); // Now works ``` Compiler -------- - [Upgraded jemalloc to 4.5.0][43911] - [Enabled unwinding panics on Redox][43917] - [Now runs LLVM in parallel during translation phase.][43506] This should reduce peak memory usage. Libraries --------- - [Generate builtin impls for `Clone` for all arrays and tuples that are `T: Clone`][43690] - [`Stdin`, `Stdout`, and `Stderr` now implement `AsRawFd`.][43459] - [`Rc` and `Arc` now implement `From<&[T]> where T: Clone`, `From<str>`, `From<String>`, `From<Box<T>> where T: ?Sized`, and `From<Vec<T>>`.][42565] Stabilized APIs --------------- [`std::mem::discriminant`] Cargo ----- - [You can now call `cargo install` with multiple package names][cargo/4216] - [Cargo commands inside a virtual workspace will now implicitly pass `--all`][cargo/4335] - [Added a `[patch]` section to `Cargo.toml` to handle prepublication dependencies][cargo/4123] [RFC 1969] - [`include` & `exclude` fields in `Cargo.toml` now accept gitignore like patterns][cargo/4270] - [Added the `--all-targets` option][cargo/4400] - [Using required dependencies as a feature is now deprecated and emits a warning][cargo/4364] Misc ---- - [Cargo docs are moving][43916] to [doc.rust-lang.org/cargo](https://doc.rust-lang.org/cargo) - [The rustdoc book is now available][43863] at [doc.rust-lang.org/rustdoc](https://doc.rust-lang.org/rustdoc) - [Added a preview of RLS has been made available through rustup][44204] Install with `rustup component add rls-preview` - [`std::os` documentation for Unix, Linux, and Windows now appears on doc.rust-lang.org][43348] Previously only showed `std::os::unix`. Compatibility Notes ------------------- - [Changes in method matching against higher-ranked types][43880] This may cause breakage in subtyping corner cases. [A more in-depth explanation is available.][info/43880] - [rustc's JSON error output's byte position start at top of file.][42973] Was previously relative to the rustc's internal `CodeMap` struct which required the unstable library `libsyntax` to correctly use. - [`unused_results` lint no longer ignores booleans][43728] [42565]: https://github.com/rust-lang/rust/pull/42565 [42973]: https://github.com/rust-lang/rust/pull/42973 [43348]: https://github.com/rust-lang/rust/pull/43348 [43459]: https://github.com/rust-lang/rust/pull/43459 [43506]: https://github.com/rust-lang/rust/pull/43506 [43540]: https://github.com/rust-lang/rust/pull/43540 [43690]: https://github.com/rust-lang/rust/pull/43690 [43728]: https://github.com/rust-lang/rust/pull/43728 [43838]: https://github.com/rust-lang/rust/pull/43838 [43863]: https://github.com/rust-lang/rust/pull/43863 [43880]: https://github.com/rust-lang/rust/pull/43880 [43911]: https://github.com/rust-lang/rust/pull/43911 [43916]: https://github.com/rust-lang/rust/pull/43916 [43917]: https://github.com/rust-lang/rust/pull/43917 [44204]: https://github.com/rust-lang/rust/pull/44204 [cargo/4123]: https://github.com/rust-lang/cargo/pull/4123 [cargo/4216]: https://github.com/rust-lang/cargo/pull/4216 [cargo/4270]: https://github.com/rust-lang/cargo/pull/4270 [cargo/4335]: https://github.com/rust-lang/cargo/pull/4335 [cargo/4364]: https://github.com/rust-lang/cargo/pull/4364 [cargo/4400]: https://github.com/rust-lang/cargo/pull/4400 [RFC 1969]: https://github.com/rust-lang/rfcs/pull/1969 [info/43880]: https://github.com/rust-lang/rust/issues/44224#issuecomment-330058902 [`std::mem::discriminant`]: https://doc.rust-lang.org/std/mem/fn.discriminant.html Version 1.20.0 (2017-08-31) =========================== Language -------- - [Associated constants are now stabilised.][42809] - [A lot of macro bugs are now fixed.][42913] Compiler -------- - [Struct fields are now properly coerced to the expected field type.][42807] - [Enabled wasm LLVM backend][42571] WASM can now be built with the `wasm32-experimental-emscripten` target. - [Changed some of the error messages to be more helpful.][42033] - [Add support for RELRO(RELocation Read-Only) for platforms that support it.][43170] - [rustc now reports the total number of errors on compilation failure][43015] previously this was only the number of errors in the pass that failed. - [Expansion in rustc has been sped up 29x.][42533] - [added `msp430-none-elf` target.][43099] - [rustc will now suggest one-argument enum variant to fix type mismatch when applicable][43178] - [Fixes backtraces on Redox][43228] - [rustc now identifies different versions of same crate when absolute paths of different types match in an error message.][42826] Libraries --------- - [Relaxed Debug constraints on `{HashMap,BTreeMap}::{Keys,Values}`.][42854] - [Impl `PartialEq`, `Eq`, `PartialOrd`, `Ord`, `Debug`, `Hash` for unsized tuples.][43011] - [Impl `fmt::{Display, Debug}` for `Ref`, `RefMut`, `MutexGuard`, `RwLockReadGuard`, `RwLockWriteGuard`][42822] - [Impl `Clone` for `DefaultHasher`.][42799] - [Impl `Sync` for `SyncSender`.][42397] - [Impl `FromStr` for `char`][42271] - [Fixed how `{f32, f64}::{is_sign_negative, is_sign_positive}` handles NaN.][42431] - [allow messages in the `unimplemented!()` macro.][42155] ie. `unimplemented!("Waiting for 1.21 to be stable")` - [`pub(restricted)` is now supported in the `thread_local!` macro.][43185] - [Upgrade to Unicode 10.0.0][42999] - [Reimplemented `{f32, f64}::{min, max}` in Rust instead of using CMath.][42430] - [Skip the main thread's manual stack guard on Linux][43072] - [Iterator::nth for `ops::{Range, RangeFrom}` is now done in *O*(1) time][43077] - [`#[repr(align(N))]` attribute max number is now 2^31 - 1.][43097] This was previously 2^15. - [`{OsStr, Path}::Display` now avoids allocations where possible][42613] Stabilized APIs --------------- - [`CStr::into_c_string`] - [`CString::as_c_str`] - [`CString::into_boxed_c_str`] - [`Chain::get_mut`] - [`Chain::get_ref`] - [`Chain::into_inner`] - [`Option::get_or_insert_with`] - [`Option::get_or_insert`] - [`OsStr::into_os_string`] - [`OsString::into_boxed_os_str`] - [`Take::get_mut`] - [`Take::get_ref`] - [`Utf8Error::error_len`] - [`char::EscapeDebug`] - [`char::escape_debug`] - [`compile_error!`] - [`f32::from_bits`] - [`f32::to_bits`] - [`f64::from_bits`] - [`f64::to_bits`] - [`mem::ManuallyDrop`] - [`slice::sort_unstable_by_key`] - [`slice::sort_unstable_by`] - [`slice::sort_unstable`] - [`str::from_boxed_utf8_unchecked`] - [`str::as_bytes_mut`] - [`str::as_bytes_mut`] - [`str::from_utf8_mut`] - [`str::from_utf8_unchecked_mut`] - [`str::get_mut`] - [`str::get_unchecked_mut`] - [`str::get_unchecked`] - [`str::get`] - [`str::into_boxed_bytes`] Cargo ----- - [Cargo API token location moved from `~/.cargo/config` to `~/.cargo/credentials`.][cargo/3978] - [Cargo will now build `main.rs` binaries that are in sub-directories of `src/bin`.][cargo/4214] ie. Having `src/bin/server/main.rs` and `src/bin/client/main.rs` generates `target/debug/server` and `target/debug/client` - [You can now specify version of a binary when installed through `cargo install` using `--vers`.][cargo/4229] - [Added `--no-fail-fast` flag to cargo to run all benchmarks regardless of failure.][cargo/4248] - [Changed the convention around which file is the crate root.][cargo/4259] Compatibility Notes ------------------- - [Functions with `'static` in their return types will now not be as usable as if they were using lifetime parameters instead.][42417] - [The reimplementation of `{f32, f64}::is_sign_{negative, positive}` now takes the sign of NaN into account where previously didn't.][42430] [42033]: https://github.com/rust-lang/rust/pull/42033 [42155]: https://github.com/rust-lang/rust/pull/42155 [42271]: https://github.com/rust-lang/rust/pull/42271 [42397]: https://github.com/rust-lang/rust/pull/42397 [42417]: https://github.com/rust-lang/rust/pull/42417 [42430]: https://github.com/rust-lang/rust/pull/42430 [42431]: https://github.com/rust-lang/rust/pull/42431 [42533]: https://github.com/rust-lang/rust/pull/42533 [42571]: https://github.com/rust-lang/rust/pull/42571 [42613]: https://github.com/rust-lang/rust/pull/42613 [42799]: https://github.com/rust-lang/rust/pull/42799 [42807]: https://github.com/rust-lang/rust/pull/42807 [42809]: https://github.com/rust-lang/rust/pull/42809 [42822]: https://github.com/rust-lang/rust/pull/42822 [42826]: https://github.com/rust-lang/rust/pull/42826 [42854]: https://github.com/rust-lang/rust/pull/42854 [42913]: https://github.com/rust-lang/rust/pull/42913 [42999]: https://github.com/rust-lang/rust/pull/42999 [43011]: https://github.com/rust-lang/rust/pull/43011 [43015]: https://github.com/rust-lang/rust/pull/43015 [43072]: https://github.com/rust-lang/rust/pull/43072 [43077]: https://github.com/rust-lang/rust/pull/43077 [43097]: https://github.com/rust-lang/rust/pull/43097 [43099]: https://github.com/rust-lang/rust/pull/43099 [43170]: https://github.com/rust-lang/rust/pull/43170 [43178]: https://github.com/rust-lang/rust/pull/43178 [43185]: https://github.com/rust-lang/rust/pull/43185 [43228]: https://github.com/rust-lang/rust/pull/43228 [cargo/3978]: https://github.com/rust-lang/cargo/pull/3978 [cargo/4214]: https://github.com/rust-lang/cargo/pull/4214 [cargo/4229]: https://github.com/rust-lang/cargo/pull/4229 [cargo/4248]: https://github.com/rust-lang/cargo/pull/4248 [cargo/4259]: https://github.com/rust-lang/cargo/pull/4259 [`CStr::into_c_string`]: https://doc.rust-lang.org/std/ffi/struct.CStr.html#method.into_c_string [`CString::as_c_str`]: https://doc.rust-lang.org/std/ffi/struct.CString.html#method.as_c_str [`CString::into_boxed_c_str`]: https://doc.rust-lang.org/std/ffi/struct.CString.html#method.into_boxed_c_str [`Chain::get_mut`]: https://doc.rust-lang.org/std/io/struct.Chain.html#method.get_mut [`Chain::get_ref`]: https://doc.rust-lang.org/std/io/struct.Chain.html#method.get_ref [`Chain::into_inner`]: https://doc.rust-lang.org/std/io/struct.Chain.html#method.into_inner [`Option::get_or_insert_with`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.get_or_insert_with [`Option::get_or_insert`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.get_or_insert [`OsStr::into_os_string`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.into_os_string [`OsString::into_boxed_os_str`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html#method.into_boxed_os_str [`Take::get_mut`]: https://doc.rust-lang.org/std/io/struct.Take.html#method.get_mut [`Take::get_ref`]: https://doc.rust-lang.org/std/io/struct.Take.html#method.get_ref [`Utf8Error::error_len`]: https://doc.rust-lang.org/std/str/struct.Utf8Error.html#method.error_len [`char::EscapeDebug`]: https://doc.rust-lang.org/std/char/struct.EscapeDebug.html [`char::escape_debug`]: https://doc.rust-lang.org/std/primitive.char.html#method.escape_debug [`compile_error!`]: https://doc.rust-lang.org/std/macro.compile_error.html [`f32::from_bits`]: https://doc.rust-lang.org/std/primitive.f32.html#method.from_bits [`f32::to_bits`]: https://doc.rust-lang.org/std/primitive.f32.html#method.to_bits [`f64::from_bits`]: https://doc.rust-lang.org/std/primitive.f64.html#method.from_bits [`f64::to_bits`]: https://doc.rust-lang.org/std/primitive.f64.html#method.to_bits [`mem::ManuallyDrop`]: https://doc.rust-lang.org/std/mem/union.ManuallyDrop.html [`slice::sort_unstable_by_key`]: https://doc.rust-lang.org/std/primitive.slice.html#method.sort_unstable_by_key [`slice::sort_unstable_by`]: https://doc.rust-lang.org/std/primitive.slice.html#method.sort_unstable_by [`slice::sort_unstable`]: https://doc.rust-lang.org/std/primitive.slice.html#method.sort_unstable [`str::from_boxed_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_boxed_utf8_unchecked.html [`str::as_bytes_mut`]: https://doc.rust-lang.org/std/primitive.str.html#method.as_bytes_mut [`str::from_utf8_mut`]: https://doc.rust-lang.org/std/str/fn.from_utf8_mut.html [`str::from_utf8_unchecked_mut`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked_mut.html [`str::get_mut`]: https://doc.rust-lang.org/std/primitive.str.html#method.get_mut [`str::get_unchecked_mut`]: https://doc.rust-lang.org/std/primitive.str.html#method.get_unchecked_mut [`str::get_unchecked`]: https://doc.rust-lang.org/std/primitive.str.html#method.get_unchecked [`str::get`]: https://doc.rust-lang.org/std/primitive.str.html#method.get [`str::into_boxed_bytes`]: https://doc.rust-lang.org/std/primitive.str.html#method.into_boxed_bytes Version 1.19.0 (2017-07-20) =========================== Language -------- - [Numeric fields can now be used for creating tuple structs.][41145] [RFC 1506] For example `struct Point(u32, u32); let x = Point { 0: 7, 1: 0 };`. - [Macro recursion limit increased to 1024 from 64.][41676] - [Added lint for detecting unused macros.][41907] - [`loop` can now return a value with `break`.][42016] [RFC 1624] For example: `let x = loop { break 7; };` - [C compatible `union`s are now available.][42068] [RFC 1444] They can only contain `Copy` types and cannot have a `Drop` implementation. Example: `union Foo { bar: u8, baz: usize }` - [Non capturing closures can now be coerced into `fn`s,][42162] [RFC 1558] Example: `let foo: fn(u8) -> u8 = |v: u8| { v };` Compiler -------- - [Add support for bootstrapping the Rust compiler toolchain on Android.][41370] - [Change `arm-linux-androideabi` to correspond to the `armeabi` official ABI.][41656] If you wish to continue targeting the `armeabi-v7a` ABI you should use `--target armv7-linux-androideabi`. - [Fixed ICE when removing a source file between compilation sessions.][41873] - [Minor optimisation of string operations.][42037] - [Compiler error message is now `aborting due to previous error(s)` instead of `aborting due to N previous errors`][42150] This was previously inaccurate and would only count certain kinds of errors. - [The compiler now supports Visual Studio 2017][42225] - [The compiler is now built against LLVM 4.0.1 by default][42948] - [Added a lot][42264] of [new error codes][42302] - [Added `target-feature=+crt-static` option][37406] [RFC 1721] Which allows libraries with C Run-time Libraries(CRT) to be statically linked. - [Fixed various ARM codegen bugs][42740] Libraries --------- - [`String` now implements `FromIterator<Cow<'a, str>>` and `Extend<Cow<'a, str>>`][41449] - [`Vec` now implements `From<&mut [T]>`][41530] - [`Box<[u8]>` now implements `From<Box<str>>`][41258] - [`SplitWhitespace` now implements `Clone`][41659] - [`[u8]::reverse` is now 5x faster and `[u16]::reverse` is now 1.5x faster][41764] - [`eprint!` and `eprintln!` macros added to prelude.][41192] Same as the `print!` macros, but for printing to stderr. Stabilized APIs --------------- - [`OsString::shrink_to_fit`] - [`cmp::Reverse`] - [`Command::envs`] - [`thread::ThreadId`] Cargo ----- - [Build scripts can now add environment variables to the environment the crate is being compiled in. Example: `println!("cargo:rustc-env=FOO=bar");`][cargo/3929] - [Subcommands now replace the current process rather than spawning a new child process][cargo/3970] - [Workspace members can now accept glob file patterns][cargo/3979] - [Added `--all` flag to the `cargo bench` subcommand to run benchmarks of all the members in a given workspace.][cargo/3988] - [Updated `libssh2-sys` to 0.2.6][cargo/4008] - [Target directory path is now in the cargo metadata][cargo/4022] - [Cargo no longer checks out a local working directory for the crates.io index][cargo/4026] This should provide smaller file size for the registry, and improve cloning times, especially on Windows machines. - [Added an `--exclude` option for excluding certain packages when using the `--all` option][cargo/4031] - [Cargo will now automatically retry when receiving a 5xx error from crates.io][cargo/4032] - [The `--features` option now accepts multiple comma or space delimited values.][cargo/4084] - [Added support for custom target specific runners][cargo/3954] Misc ---- - [Added `rust-windbg.cmd`][39983] for loading rust `.natvis` files in the Windows Debugger. - [Rust will now release XZ compressed packages][rust-installer/57] - [rustup will now prefer to download rust packages with XZ compression][rustup/1100] over GZip packages. - [Added the ability to escape `#` in rust documentation][41785] By adding additional `#`'s ie. `##` is now `#` Compatibility Notes ------------------- - [`MutexGuard<T>` may only be `Sync` if `T` is `Sync`.][41624] - [`-Z` flags are now no longer allowed to be used on the stable compiler.][41751] This has been a warning for a year previous to this. - [As a result of the `-Z` flag change, the `cargo-check` plugin no longer works][42844]. Users should migrate to the built-in `check` command, which has been available since 1.16. - [Ending a float literal with `._` is now a hard error. Example: `42._` .][41946] - [Any use of a private `extern crate` outside of its module is now a hard error.][36886] This was previously a warning. - [`use ::self::foo;` is now a hard error.][36888] `self` paths are always relative while the `::` prefix makes a path absolute, but was ignored and the path was relative regardless. - [Floating point constants in match patterns is now a hard error][36890] This was previously a warning. - [Struct or enum constants that don't derive `PartialEq` & `Eq` used match patterns is now a hard error][36891] This was previously a warning. - [Lifetimes named `'_` are no longer allowed.][36892] This was previously a warning. - [From the pound escape, lines consisting of multiple `#`s are now visible][41785] - [It is an error to re-export private enum variants][42460]. This is known to break a number of crates that depend on an older version of mustache. - [On Windows, if `VCINSTALLDIR` is set incorrectly, `rustc` will try to use it to find the linker, and the build will fail where it did not previously][42607] [36886]: https://github.com/rust-lang/rust/issues/36886 [36888]: https://github.com/rust-lang/rust/issues/36888 [36890]: https://github.com/rust-lang/rust/issues/36890 [36891]: https://github.com/rust-lang/rust/issues/36891 [36892]: https://github.com/rust-lang/rust/issues/36892 [37406]: https://github.com/rust-lang/rust/issues/37406 [39983]: https://github.com/rust-lang/rust/pull/39983 [41145]: https://github.com/rust-lang/rust/pull/41145 [41192]: https://github.com/rust-lang/rust/pull/41192 [41258]: https://github.com/rust-lang/rust/pull/41258 [41370]: https://github.com/rust-lang/rust/pull/41370 [41449]: https://github.com/rust-lang/rust/pull/41449 [41530]: https://github.com/rust-lang/rust/pull/41530 [41624]: https://github.com/rust-lang/rust/pull/41624 [41656]: https://github.com/rust-lang/rust/pull/41656 [41659]: https://github.com/rust-lang/rust/pull/41659 [41676]: https://github.com/rust-lang/rust/pull/41676 [41751]: https://github.com/rust-lang/rust/pull/41751 [41764]: https://github.com/rust-lang/rust/pull/41764 [41785]: https://github.com/rust-lang/rust/pull/41785 [41873]: https://github.com/rust-lang/rust/pull/41873 [41907]: https://github.com/rust-lang/rust/pull/41907 [41946]: https://github.com/rust-lang/rust/pull/41946 [42016]: https://github.com/rust-lang/rust/pull/42016 [42037]: https://github.com/rust-lang/rust/pull/42037 [42068]: https://github.com/rust-lang/rust/pull/42068 [42150]: https://github.com/rust-lang/rust/pull/42150 [42162]: https://github.com/rust-lang/rust/pull/42162 [42225]: https://github.com/rust-lang/rust/pull/42225 [42264]: https://github.com/rust-lang/rust/pull/42264 [42302]: https://github.com/rust-lang/rust/pull/42302 [42460]: https://github.com/rust-lang/rust/issues/42460 [42607]: https://github.com/rust-lang/rust/issues/42607 [42740]: https://github.com/rust-lang/rust/pull/42740 [42844]: https://github.com/rust-lang/rust/issues/42844 [42948]: https://github.com/rust-lang/rust/pull/42948 [RFC 1444]: https://github.com/rust-lang/rfcs/pull/1444 [RFC 1506]: https://github.com/rust-lang/rfcs/pull/1506 [RFC 1558]: https://github.com/rust-lang/rfcs/pull/1558 [RFC 1624]: https://github.com/rust-lang/rfcs/pull/1624 [RFC 1721]: https://github.com/rust-lang/rfcs/pull/1721 [`Command::envs`]: https://doc.rust-lang.org/std/process/struct.Command.html#method.envs [`OsString::shrink_to_fit`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html#method.shrink_to_fit [`cmp::Reverse`]: https://doc.rust-lang.org/std/cmp/struct.Reverse.html [`thread::ThreadId`]: https://doc.rust-lang.org/std/thread/struct.ThreadId.html [cargo/3929]: https://github.com/rust-lang/cargo/pull/3929 [cargo/3954]: https://github.com/rust-lang/cargo/pull/3954 [cargo/3970]: https://github.com/rust-lang/cargo/pull/3970 [cargo/3979]: https://github.com/rust-lang/cargo/pull/3979 [cargo/3988]: https://github.com/rust-lang/cargo/pull/3988 [cargo/4008]: https://github.com/rust-lang/cargo/pull/4008 [cargo/4022]: https://github.com/rust-lang/cargo/pull/4022 [cargo/4026]: https://github.com/rust-lang/cargo/pull/4026 [cargo/4031]: https://github.com/rust-lang/cargo/pull/4031 [cargo/4032]: https://github.com/rust-lang/cargo/pull/4032 [cargo/4084]: https://github.com/rust-lang/cargo/pull/4084 [rust-installer/57]: https://github.com/rust-lang/rust-installer/pull/57 [rustup/1100]: https://github.com/rust-lang-nursery/rustup.rs/pull/1100 Version 1.18.0 (2017-06-08) =========================== Language -------- - [Stabilize pub(restricted)][40556] `pub` can now accept a module path to make the item visible to just that module tree. Also accepts the keyword `crate` to make something public to the whole crate but not users of the library. Example: `pub(crate) mod utils;`. [RFC 1422]. - [Stabilize `#![windows_subsystem]` attribute][40870] conservative exposure of the `/SUBSYSTEM` linker flag on Windows platforms. [RFC 1665]. - [Refactor of trait object type parsing][40043] Now `ty` in macros can accept types like `Write + Send`, trailing `+` are now supported in trait objects, and better error reporting for trait objects starting with `?Sized`. - [0e+10 is now a valid floating point literal][40589] - [Now warns if you bind a lifetime parameter to 'static][40734] - [Tuples, Enum variant fields, and structs with no `repr` attribute or with `#[repr(Rust)]` are reordered to minimize padding and produce a smaller representation in some cases.][40377] Compiler -------- - [rustc can now emit mir with `--emit mir`][39891] - [Improved LLVM IR for trivial functions][40367] - [Added explanation for E0090(Wrong number of lifetimes are supplied)][40723] - [rustc compilation is now 15%-20% faster][41469] Thanks to optimisation opportunities found through profiling - [Improved backtrace formatting when panicking][38165] Libraries --------- - [Specialized `Vec::from_iter` being passed `vec::IntoIter`][40731] if the iterator hasn't been advanced the original `Vec` is reassembled with no actual iteration or reallocation. - [Simplified HashMap Bucket interface][40561] provides performance improvements for iterating and cloning. - [Specialize Vec::from_elem to use calloc][40409] - [Fixed Race condition in fs::create_dir_all][39799] - [No longer caching stdio on Windows][40516] - [Optimized insertion sort in slice][40807] insertion sort in some cases 2.50%~ faster and in one case now 12.50% faster. - [Optimized `AtomicBool::fetch_nand`][41143] Stabilized APIs --------------- - [`Child::try_wait`] - [`HashMap::retain`] - [`HashSet::retain`] - [`PeekMut::pop`] - [`TcpStream::peek`] - [`UdpSocket::peek`] - [`UdpSocket::peek_from`] Cargo ----- - [Added partial Pijul support][cargo/3842] Pijul is a version control system in Rust. You can now create new cargo projects with Pijul using `cargo new --vcs pijul` - [Now always emits build script warnings for crates that fail to build][cargo/3847] - [Added Android build support][cargo/3885] - [Added `--bins` and `--tests` flags][cargo/3901] now you can build all programs of a certain type, for example `cargo build --bins` will build all binaries. - [Added support for haiku][cargo/3952] Misc ---- - [rustdoc can now use pulldown-cmark with the `--enable-commonmark` flag][40338] - [Rust now uses the official cross compiler for NetBSD][40612] - [rustdoc now accepts `#` at the start of files][40828] - [Fixed jemalloc support for musl][41168] Compatibility Notes ------------------- - [Changes to how the `0` flag works in format!][40241] Padding zeroes are now always placed after the sign if it exists and before the digits. With the `#` flag the zeroes are placed after the prefix and before the digits. - [Due to the struct field optimisation][40377], using `transmute` on structs that have no `repr` attribute or `#[repr(Rust)]` will no longer work. This has always been undefined behavior, but is now more likely to break in practice. - [The refactor of trait object type parsing][40043] fixed a bug where `+` was receiving the wrong priority parsing things like `&for<'a> Tr<'a> + Send` as `&(for<'a> Tr<'a> + Send)` instead of `(&for<'a> Tr<'a>) + Send` - [Overlapping inherent `impl`s are now a hard error][40728] - [`PartialOrd` and `Ord` must agree on the ordering.][41270] - [`rustc main.rs -o out --emit=asm,llvm-ir`][41085] Now will output `out.asm` and `out.ll` instead of only one of the filetypes. - [ calling a function that returns `Self` will no longer work][41805] when the size of `Self` cannot be statically determined. - [rustc now builds with a "pthreads" flavour of MinGW for Windows GNU][40805] this has caused a few regressions namely: - Changed the link order of local static/dynamic libraries (respecting the order on given rather than having the compiler reorder). - Changed how MinGW is linked, native code linked to dynamic libraries may require manually linking to the gcc support library (for the native code itself) [38165]: https://github.com/rust-lang/rust/pull/38165 [39799]: https://github.com/rust-lang/rust/pull/39799 [39891]: https://github.com/rust-lang/rust/pull/39891 [40043]: https://github.com/rust-lang/rust/pull/40043 [40241]: https://github.com/rust-lang/rust/pull/40241 [40338]: https://github.com/rust-lang/rust/pull/40338 [40367]: https://github.com/rust-lang/rust/pull/40367 [40377]: https://github.com/rust-lang/rust/pull/40377 [40409]: https://github.com/rust-lang/rust/pull/40409 [40516]: https://github.com/rust-lang/rust/pull/40516 [40556]: https://github.com/rust-lang/rust/pull/40556 [40561]: https://github.com/rust-lang/rust/pull/40561 [40589]: https://github.com/rust-lang/rust/pull/40589 [40612]: https://github.com/rust-lang/rust/pull/40612 [40723]: https://github.com/rust-lang/rust/pull/40723 [40728]: https://github.com/rust-lang/rust/pull/40728 [40731]: https://github.com/rust-lang/rust/pull/40731 [40734]: https://github.com/rust-lang/rust/pull/40734 [40805]: https://github.com/rust-lang/rust/pull/40805 [40807]: https://github.com/rust-lang/rust/pull/40807 [40828]: https://github.com/rust-lang/rust/pull/40828 [40870]: https://github.com/rust-lang/rust/pull/40870 [41085]: https://github.com/rust-lang/rust/pull/41085 [41143]: https://github.com/rust-lang/rust/pull/41143 [41168]: https://github.com/rust-lang/rust/pull/41168 [41270]: https://github.com/rust-lang/rust/issues/41270 [41469]: https://github.com/rust-lang/rust/pull/41469 [41805]: https://github.com/rust-lang/rust/issues/41805 [RFC 1422]: https://github.com/rust-lang/rfcs/blob/master/text/1422-pub-restricted.md [RFC 1665]: https://github.com/rust-lang/rfcs/blob/master/text/1665-windows-subsystem.md [`Child::try_wait`]: https://doc.rust-lang.org/std/process/struct.Child.html#method.try_wait [`HashMap::retain`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.retain [`HashSet::retain`]: https://doc.rust-lang.org/std/collections/struct.HashSet.html#method.retain [`PeekMut::pop`]: https://doc.rust-lang.org/std/collections/binary_heap/struct.PeekMut.html#method.pop [`TcpStream::peek`]: https://doc.rust-lang.org/std/net/struct.TcpStream.html#method.peek [`UdpSocket::peek_from`]: https://doc.rust-lang.org/std/net/struct.UdpSocket.html#method.peek_from [`UdpSocket::peek`]: https://doc.rust-lang.org/std/net/struct.UdpSocket.html#method.peek [cargo/3842]: https://github.com/rust-lang/cargo/pull/3842 [cargo/3847]: https://github.com/rust-lang/cargo/pull/3847 [cargo/3885]: https://github.com/rust-lang/cargo/pull/3885 [cargo/3901]: https://github.com/rust-lang/cargo/pull/3901 [cargo/3952]: https://github.com/rust-lang/cargo/pull/3952 Version 1.17.0 (2017-04-27) =========================== Language -------- * [The lifetime of statics and consts defaults to `'static`][39265]. [RFC 1623] * [Fields of structs may be initialized without duplicating the field/variable names][39761]. [RFC 1682] * [`Self` may be included in the `where` clause of `impls`][38864]. [RFC 1647] * [When coercing to an unsized type lifetimes must be equal][40319]. That is, there is no subtyping between `T` and `U` when `T: Unsize<U>`. For example, coercing `&mut [&'a X; N]` to `&mut [&'b X]` requires `'a` be equal to `'b`. Soundness fix. * [Values passed to the indexing operator, `[]`, automatically coerce][40166] * [Static variables may contain references to other statics][40027] Compiler -------- * [Exit quickly on only `--emit dep-info`][40336] * [Make `-C relocation-model` more correctly determine whether the linker creates a position-independent executable][40245] * [Add `-C overflow-checks` to directly control whether integer overflow panics][40037] * [The rustc type checker now checks items on demand instead of in a single in-order pass][40008]. This is mostly an internal refactoring in support of future work, including incremental type checking, but also resolves [RFC 1647], allowing `Self` to appear in `impl` `where` clauses. * [Optimize vtable loads][39995] * [Turn off vectorization for Emscripten targets][39990] * [Provide suggestions for unknown macros imported with `use`][39953] * [Fix ICEs in path resolution][39939] * [Strip exception handling code on Emscripten when `panic=abort`][39193] * [Add clearer error message using `&str + &str`][39116] Stabilized APIs --------------- * [`Arc::into_raw`] * [`Arc::from_raw`] * [`Arc::ptr_eq`] * [`Rc::into_raw`] * [`Rc::from_raw`] * [`Rc::ptr_eq`] * [`Ordering::then`] * [`Ordering::then_with`] * [`BTreeMap::range`] * [`BTreeMap::range_mut`] * [`collections::Bound`] * [`process::abort`] * [`ptr::read_unaligned`] * [`ptr::write_unaligned`] * [`Result::expect_err`] * [`Cell::swap`] * [`Cell::replace`] * [`Cell::into_inner`] * [`Cell::take`] Libraries --------- * [`BTreeMap` and `BTreeSet` can iterate over ranges][27787] * [`Cell` can store non-`Copy` types][39793]. [RFC 1651] * [`String` implements `FromIterator<&char>`][40028] * `Box` [implements][40009] a number of new conversions: `From<Box<str>> for String`, `From<Box<[T]>> for Vec<T>`, `From<Box<CStr>> for CString`, `From<Box<OsStr>> for OsString`, `From<Box<Path>> for PathBuf`, `Into<Box<str>> for String`, `Into<Box<[T]>> for Vec<T>`, `Into<Box<CStr>> for CString`, `Into<Box<OsStr>> for OsString`, `Into<Box<Path>> for PathBuf`, `Default for Box<str>`, `Default for Box<CStr>`, `Default for Box<OsStr>`, `From<&CStr> for Box<CStr>`, `From<&OsStr> for Box<OsStr>`, `From<&Path> for Box<Path>` * [`ffi::FromBytesWithNulError` implements `Error` and `Display`][39960] * [Specialize `PartialOrd<A> for [A] where A: Ord`][39642] * [Slightly optimize `slice::sort`][39538] * [Add `ToString` trait specialization for `Cow<'a, str>` and `String`][39440] * [`Box<[T]>` implements `From<&[T]> where T: Copy`, `Box<str>` implements `From<&str>`][39438] * [`IpAddr` implements `From` for various arrays. `SocketAddr` implements `From<(I, u16)> where I: Into<IpAddr>`][39372] * [`format!` estimates the needed capacity before writing a string][39356] * [Support unprivileged symlink creation in Windows][38921] * [`PathBuf` implements `Default`][38764] * [Implement `PartialEq<[A]>` for `VecDeque<A>`][38661] * [`HashMap` resizes adaptively][38368] to guard against DOS attacks and poor hash functions. Cargo ----- * [Add `cargo check --all`][cargo/3731] * [Add an option to ignore SSL revocation checking][cargo/3699] * [Add `cargo run --package`][cargo/3691] * [Add `required_features`][cargo/3667] * [Assume `build.rs` is a build script][cargo/3664] * [Find workspace via `workspace_root` link in containing member][cargo/3562] Misc ---- * [Documentation is rendered with mdbook instead of the obsolete, in-tree `rustbook`][39633] * [The "Unstable Book" documents nightly-only features][ubook] * [Improve the style of the sidebar in rustdoc output][40265] * [Configure build correctly on 64-bit CPU's with the armhf ABI][40261] * [Fix MSP430 breakage due to `i128`][40257] * [Preliminary Solaris/SPARCv9 support][39903] * [`rustc` is linked statically on Windows MSVC targets][39837], allowing it to run without installing the MSVC runtime. * [`rustdoc --test` includes file names in test names][39788] * This release includes builds of `std` for `sparc64-unknown-linux-gnu`, `aarch64-unknown-linux-fuchsia`, and `x86_64-unknown-linux-fuchsia`. * [Initial support for `aarch64-unknown-freebsd`][39491] * [Initial support for `i686-unknown-netbsd`][39426] * [This release no longer includes the old makefile build system][39431]. Rust is built with a custom build system, written in Rust, and with Cargo. * [Add Debug implementations for libcollection structs][39002] * [`TypeId` implements `PartialOrd` and `Ord`][38981] * [`--test-threads=0` produces an error][38945] * [`rustup` installs documentation by default][40526] * [The Rust source includes NatVis visualizations][39843]. These can be used by WinDbg and Visual Studio to improve the debugging experience. Compatibility Notes ------------------- * [Rust 1.17 does not correctly detect the MSVC 2017 linker][38584]. As a workaround, either use MSVC 2015 or run vcvars.bat. * [When coercing to an unsized type lifetimes must be equal][40319]. That is, disallow subtyping between `T` and `U` when `T: Unsize<U>`, e.g. coercing `&mut [&'a X; N]` to `&mut [&'b X]` requires `'a` be equal to `'b`. Soundness fix. * [`format!` and `Display::to_string` panic if an underlying formatting implementation returns an error][40117]. Previously the error was silently ignored. It is incorrect for `write_fmt` to return an error when writing to a string. * [In-tree crates are verified to be unstable][39851]. Previously, some minor crates were marked stable and could be accessed from the stable toolchain. * [Rust git source no longer includes vendored crates][39728]. Those that need to build with vendored crates should build from release tarballs. * [Fix inert attributes from `proc_macro_derives`][39572] * [During crate resolution, rustc prefers a crate in the sysroot if two crates are otherwise identical][39518]. Unlikely to be encountered outside the Rust build system. * [Fixed bugs around how type inference interacts with dead-code][39485]. The existing code generally ignores the type of dead-code unless a type-hint is provided; this can cause surprising inference interactions particularly around defaulting. The new code uniformly ignores the result type of dead-code. * [Tuple-struct constructors with private fields are no longer visible][38932] * [Lifetime parameters that do not appear in the arguments are now considered early-bound][38897], resolving a soundness bug (#[32330]). The `hr_lifetime_in_assoc_type` future-compatibility lint has been in effect since April of 2016. * [rustdoc: fix doctests with non-feature crate attributes][38161] * [Make transmuting from fn item types to pointer-sized types a hard error][34198] [27787]: https://github.com/rust-lang/rust/issues/27787 [32330]: https://github.com/rust-lang/rust/issues/32330 [34198]: https://github.com/rust-lang/rust/pull/34198 [38161]: https://github.com/rust-lang/rust/pull/38161 [38368]: https://github.com/rust-lang/rust/pull/38368 [38584]: https://github.com/rust-lang/rust/issues/38584 [38661]: https://github.com/rust-lang/rust/pull/38661 [38764]: https://github.com/rust-lang/rust/pull/38764 [38864]: https://github.com/rust-lang/rust/issues/38864 [38897]: https://github.com/rust-lang/rust/pull/38897 [38921]: https://github.com/rust-lang/rust/pull/38921 [38932]: https://github.com/rust-lang/rust/pull/38932 [38945]: https://github.com/rust-lang/rust/pull/38945 [38981]: https://github.com/rust-lang/rust/pull/38981 [39002]: https://github.com/rust-lang/rust/pull/39002 [39116]: https://github.com/rust-lang/rust/pull/39116 [39193]: https://github.com/rust-lang/rust/pull/39193 [39265]: https://github.com/rust-lang/rust/pull/39265 [39356]: https://github.com/rust-lang/rust/pull/39356 [39372]: https://github.com/rust-lang/rust/pull/39372 [39426]: https://github.com/rust-lang/rust/pull/39426 [39431]: https://github.com/rust-lang/rust/pull/39431 [39438]: https://github.com/rust-lang/rust/pull/39438 [39440]: https://github.com/rust-lang/rust/pull/39440 [39485]: https://github.com/rust-lang/rust/pull/39485 [39491]: https://github.com/rust-lang/rust/pull/39491 [39518]: https://github.com/rust-lang/rust/pull/39518 [39538]: https://github.com/rust-lang/rust/pull/39538 [39572]: https://github.com/rust-lang/rust/pull/39572 [39633]: https://github.com/rust-lang/rust/pull/39633 [39642]: https://github.com/rust-lang/rust/pull/39642 [39728]: https://github.com/rust-lang/rust/pull/39728 [39761]: https://github.com/rust-lang/rust/pull/39761 [39788]: https://github.com/rust-lang/rust/pull/39788 [39793]: https://github.com/rust-lang/rust/pull/39793 [39837]: https://github.com/rust-lang/rust/pull/39837 [39843]: https://github.com/rust-lang/rust/pull/39843 [39851]: https://github.com/rust-lang/rust/pull/39851 [39903]: https://github.com/rust-lang/rust/pull/39903 [39939]: https://github.com/rust-lang/rust/pull/39939 [39953]: https://github.com/rust-lang/rust/pull/39953 [39960]: https://github.com/rust-lang/rust/pull/39960 [39990]: https://github.com/rust-lang/rust/pull/39990 [39995]: https://github.com/rust-lang/rust/pull/39995 [40008]: https://github.com/rust-lang/rust/pull/40008 [40009]: https://github.com/rust-lang/rust/pull/40009 [40027]: https://github.com/rust-lang/rust/pull/40027 [40028]: https://github.com/rust-lang/rust/pull/40028 [40037]: https://github.com/rust-lang/rust/pull/40037 [40117]: https://github.com/rust-lang/rust/pull/40117 [40166]: https://github.com/rust-lang/rust/pull/40166 [40245]: https://github.com/rust-lang/rust/pull/40245 [40257]: https://github.com/rust-lang/rust/pull/40257 [40261]: https://github.com/rust-lang/rust/pull/40261 [40265]: https://github.com/rust-lang/rust/pull/40265 [40319]: https://github.com/rust-lang/rust/pull/40319 [40336]: https://github.com/rust-lang/rust/pull/40336 [40526]: https://github.com/rust-lang/rust/pull/40526 [RFC 1623]: https://github.com/rust-lang/rfcs/blob/master/text/1623-static.md [RFC 1647]: https://github.com/rust-lang/rfcs/blob/master/text/1647-allow-self-in-where-clauses.md [RFC 1651]: https://github.com/rust-lang/rfcs/blob/master/text/1651-movecell.md [RFC 1682]: https://github.com/rust-lang/rfcs/blob/master/text/1682-field-init-shorthand.md [`Arc::from_raw`]: https://doc.rust-lang.org/std/sync/struct.Arc.html#method.from_raw [`Arc::into_raw`]: https://doc.rust-lang.org/std/sync/struct.Arc.html#method.into_raw [`Arc::ptr_eq`]: https://doc.rust-lang.org/std/sync/struct.Arc.html#method.ptr_eq [`BTreeMap::range_mut`]: https://doc.rust-lang.org/std/collections/btree_map/struct.BTreeMap.html#method.range_mut [`BTreeMap::range`]: https://doc.rust-lang.org/std/collections/btree_map/struct.BTreeMap.html#method.range [`Cell::into_inner`]: https://doc.rust-lang.org/std/cell/struct.Cell.html#method.into_inner [`Cell::replace`]: https://doc.rust-lang.org/std/cell/struct.Cell.html#method.replace [`Cell::swap`]: https://doc.rust-lang.org/std/cell/struct.Cell.html#method.swap [`Cell::take`]: https://doc.rust-lang.org/std/cell/struct.Cell.html#method.take [`Ordering::then_with`]: https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.then_with [`Ordering::then`]: https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.then [`Rc::from_raw`]: https://doc.rust-lang.org/std/rc/struct.Rc.html#method.from_raw [`Rc::into_raw`]: https://doc.rust-lang.org/std/rc/struct.Rc.html#method.into_raw [`Rc::ptr_eq`]: https://doc.rust-lang.org/std/rc/struct.Rc.html#method.ptr_eq [`Result::expect_err`]: https://doc.rust-lang.org/std/result/enum.Result.html#method.expect_err [`collections::Bound`]: https://doc.rust-lang.org/std/collections/enum.Bound.html [`process::abort`]: https://doc.rust-lang.org/std/process/fn.abort.html [`ptr::read_unaligned`]: https://doc.rust-lang.org/std/ptr/fn.read_unaligned.html [`ptr::write_unaligned`]: https://doc.rust-lang.org/std/ptr/fn.write_unaligned.html [cargo/3562]: https://github.com/rust-lang/cargo/pull/3562 [cargo/3664]: https://github.com/rust-lang/cargo/pull/3664 [cargo/3667]: https://github.com/rust-lang/cargo/pull/3667 [cargo/3691]: https://github.com/rust-lang/cargo/pull/3691 [cargo/3699]: https://github.com/rust-lang/cargo/pull/3699 [cargo/3731]: https://github.com/rust-lang/cargo/pull/3731 [ubook]: https://doc.rust-lang.org/unstable-book/ Version 1.16.0 (2017-03-16) =========================== Language -------- * [The compiler's `dead_code` lint now accounts for type aliases][38051]. * [Uninhabitable enums (those without any variants) no longer permit wildcard match patterns][38069] * [Clean up semantics of `self` in an import list][38313] * [`Self` may appear in `impl` headers][38920] * [`Self` may appear in struct expressions][39282] Compiler -------- * [`rustc` now supports `--emit=metadata`, which causes rustc to emit a `.rmeta` file containing only crate metadata][38571]. This can be used by tools like the Rust Language Service to perform metadata-only builds. * [Levenshtein based typo suggestions now work in most places, while previously they worked only for fields and sometimes for local variables][38927]. Together with the overhaul of "no resolution"/"unexpected resolution" errors (#[38154]) they result in large and systematic improvement in resolution diagnostics. * [Fix `transmute::<T, U>` where `T` requires a bigger alignment than `U`][38670] * [rustc: use -Xlinker when specifying an rpath with ',' in it][38798] * [`rustc` no longer attempts to provide "consider using an explicit lifetime" suggestions][37057]. They were inaccurate. Stabilized APIs --------------- * [`VecDeque::truncate`] * [`VecDeque::resize`] * [`String::insert_str`] * [`Duration::checked_add`] * [`Duration::checked_sub`] * [`Duration::checked_div`] * [`Duration::checked_mul`] * [`str::replacen`] * [`str::repeat`] * [`SocketAddr::is_ipv4`] * [`SocketAddr::is_ipv6`] * [`IpAddr::is_ipv4`] * [`IpAddr::is_ipv6`] * [`Vec::dedup_by`] * [`Vec::dedup_by_key`] * [`Result::unwrap_or_default`] * [`<*const T>::wrapping_offset`] * [`<*mut T>::wrapping_offset`] * `CommandExt::creation_flags` * [`File::set_permissions`] * [`String::split_off`] Libraries --------- * [`[T]::binary_search` and `[T]::binary_search_by_key` now take their argument by `Borrow` parameter][37761] * [All public types in std implement `Debug`][38006] * [`IpAddr` implements `From<Ipv4Addr>` and `From<Ipv6Addr>`][38327] * [`Ipv6Addr` implements `From<[u16; 8]>`][38131] * [Ctrl-Z returns from `Stdin.read()` when reading from the console on Windows][38274] * [std: Fix partial writes in `LineWriter`][38062] * [std: Clamp max read/write sizes on Unix][38622] * [Use more specific panic message for `&str` slicing errors][38066] * [`TcpListener::set_only_v6` is deprecated][38304]. This functionality cannot be achieved in std currently. * [`writeln!`, like `println!`, now accepts a form with no string or formatting arguments, to just print a newline][38469] * [Implement `iter::Sum` and `iter::Product` for `Result`][38580] * [Reduce the size of static data in `std_unicode::tables`][38781] * [`char::EscapeDebug`, `EscapeDefault`, `EscapeUnicode`, `CaseMappingIter`, `ToLowercase`, `ToUppercase`, implement `Display`][38909] * [`Duration` implements `Sum`][38712] * [`String` implements `ToSocketAddrs`][39048] Cargo ----- * [The `cargo check` command does a type check of a project without building it][cargo/3296] * [crates.io will display CI badges from Travis and AppVeyor, if specified in Cargo.toml][cargo/3546] * [crates.io will display categories listed in Cargo.toml][cargo/3301] * [Compilation profiles accept integer values for `debug`, in addition to `true` and `false`. These are passed to `rustc` as the value to `-C debuginfo`][cargo/3534] * [Implement `cargo --version --verbose`][cargo/3604] * [All builds now output 'dep-info' build dependencies compatible with make and ninja][cargo/3557] * [Build all workspace members with `build --all`][cargo/3511] * [Document all workspace members with `doc --all`][cargo/3515] * [Path deps outside workspace are not members][cargo/3443] Misc ---- * [`rustdoc` has a `--sysroot` argument that, like `rustc`, specifies the path to the Rust implementation][38589] * [The `armv7-linux-androideabi` target no longer enables NEON extensions, per Google's ABI guide][38413] * [The stock standard library can be compiled for Redox OS][38401] * [Rust has initial SPARC support][38726]. Tier 3. No builds available. * [Rust has experimental support for Nvidia PTX][38559]. Tier 3. No builds available. * [Fix backtraces on i686-pc-windows-gnu by disabling FPO][39379] Compatibility Notes ------------------- * [Uninhabitable enums (those without any variants) no longer permit wildcard match patterns][38069] * In this release, references to uninhabited types can not be pattern-matched. This was accidentally allowed in 1.15. * [The compiler's `dead_code` lint now accounts for type aliases][38051]. * [Ctrl-Z returns from `Stdin.read()` when reading from the console on Windows][38274] * [Clean up semantics of `self` in an import list][38313] * Reimplemented lifetime elision. This change was almost entirely compatible with existing code, but it did close a number of small bugs and loopholes, as well as being more accepting in some other [cases][41105]. [37057]: https://github.com/rust-lang/rust/pull/37057 [37761]: https://github.com/rust-lang/rust/pull/37761 [38006]: https://github.com/rust-lang/rust/pull/38006 [38051]: https://github.com/rust-lang/rust/pull/38051 [38062]: https://github.com/rust-lang/rust/pull/38062 [38622]: https://github.com/rust-lang/rust/pull/38622 [38066]: https://github.com/rust-lang/rust/pull/38066 [38069]: https://github.com/rust-lang/rust/pull/38069 [38131]: https://github.com/rust-lang/rust/pull/38131 [38154]: https://github.com/rust-lang/rust/pull/38154 [38274]: https://github.com/rust-lang/rust/pull/38274 [38304]: https://github.com/rust-lang/rust/pull/38304 [38313]: https://github.com/rust-lang/rust/pull/38313 [38327]: https://github.com/rust-lang/rust/pull/38327 [38401]: https://github.com/rust-lang/rust/pull/38401 [38413]: https://github.com/rust-lang/rust/pull/38413 [38469]: https://github.com/rust-lang/rust/pull/38469 [38559]: https://github.com/rust-lang/rust/pull/38559 [38571]: https://github.com/rust-lang/rust/pull/38571 [38580]: https://github.com/rust-lang/rust/pull/38580 [38589]: https://github.com/rust-lang/rust/pull/38589 [38670]: https://github.com/rust-lang/rust/pull/38670 [38712]: https://github.com/rust-lang/rust/pull/38712 [38726]: https://github.com/rust-lang/rust/pull/38726 [38781]: https://github.com/rust-lang/rust/pull/38781 [38798]: https://github.com/rust-lang/rust/pull/38798 [38909]: https://github.com/rust-lang/rust/pull/38909 [38920]: https://github.com/rust-lang/rust/pull/38920 [38927]: https://github.com/rust-lang/rust/pull/38927 [39048]: https://github.com/rust-lang/rust/pull/39048 [39282]: https://github.com/rust-lang/rust/pull/39282 [39379]: https://github.com/rust-lang/rust/pull/39379 [41105]: https://github.com/rust-lang/rust/issues/41105 [`<*const T>::wrapping_offset`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_offset [`<*mut T>::wrapping_offset`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_offset-1 [`Duration::checked_add`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.checked_add [`Duration::checked_div`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.checked_div [`Duration::checked_mul`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.checked_mul [`Duration::checked_sub`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.checked_sub [`File::set_permissions`]: https://doc.rust-lang.org/std/fs/struct.File.html#method.set_permissions [`IpAddr::is_ipv4`]: https://doc.rust-lang.org/std/net/enum.IpAddr.html#method.is_ipv4 [`IpAddr::is_ipv6`]: https://doc.rust-lang.org/std/net/enum.IpAddr.html#method.is_ipv6 [`Result::unwrap_or_default`]: https://doc.rust-lang.org/std/result/enum.Result.html#method.unwrap_or_default [`SocketAddr::is_ipv4`]: https://doc.rust-lang.org/std/net/enum.SocketAddr.html#method.is_ipv4 [`SocketAddr::is_ipv6`]: https://doc.rust-lang.org/std/net/enum.SocketAddr.html#method.is_ipv6 [`String::insert_str`]: https://doc.rust-lang.org/std/string/struct.String.html#method.insert_str [`String::split_off`]: https://doc.rust-lang.org/std/string/struct.String.html#method.split_off [`Vec::dedup_by_key`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.dedup_by_key [`Vec::dedup_by`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.dedup_by [`VecDeque::resize`]: https://doc.rust-lang.org/std/collections/vec_deque/struct.VecDeque.html#method.resize [`VecDeque::truncate`]: https://doc.rust-lang.org/std/collections/vec_deque/struct.VecDeque.html#method.truncate [`str::repeat`]: https://doc.rust-lang.org/std/primitive.str.html#method.repeat [`str::replacen`]: https://doc.rust-lang.org/std/primitive.str.html#method.replacen [cargo/3296]: https://github.com/rust-lang/cargo/pull/3296 [cargo/3301]: https://github.com/rust-lang/cargo/pull/3301 [cargo/3443]: https://github.com/rust-lang/cargo/pull/3443 [cargo/3511]: https://github.com/rust-lang/cargo/pull/3511 [cargo/3515]: https://github.com/rust-lang/cargo/pull/3515 [cargo/3534]: https://github.com/rust-lang/cargo/pull/3534 [cargo/3546]: https://github.com/rust-lang/cargo/pull/3546 [cargo/3557]: https://github.com/rust-lang/cargo/pull/3557 [cargo/3604]: https://github.com/rust-lang/cargo/pull/3604 Version 1.15.1 (2017-02-09) =========================== * [Fix IntoIter::as_mut_slice's signature][39466] * [Compile compiler builtins with `-fPIC` on 32-bit platforms][39523] [39466]: https://github.com/rust-lang/rust/pull/39466 [39523]: https://github.com/rust-lang/rust/pull/39523 Version 1.15.0 (2017-02-02) =========================== Language -------- * Basic procedural macros allowing custom `#[derive]`, aka "macros 1.1", are stable. This allows popular code-generating crates like Serde and Diesel to work ergonomically. [RFC 1681]. * [Tuple structs may be empty. Unary and empty tuple structs may be instantiated with curly braces][36868]. Part of [RFC 1506]. * [A number of minor changes to name resolution have been activated][37127]. They add up to more consistent semantics, allowing for future evolution of Rust macros. Specified in [RFC 1560], see its section on ["changes"] for details of what is different. The breaking changes here have been transitioned through the [`legacy_imports`] lint since 1.14, with no known regressions. * [In `macro_rules`, `path` fragments can now be parsed as type parameter bounds][38279] * [`?Sized` can be used in `where` clauses][37791] * [There is now a limit on the size of monomorphized types and it can be modified with the `#![type_size_limit]` crate attribute, similarly to the `#![recursion_limit]` attribute][37789] Compiler -------- * [On Windows, the compiler will apply dllimport attributes when linking to extern functions][37973]. Additional attributes and flags can control which library kind is linked and its name. [RFC 1717]. * [Rust-ABI symbols are no longer exported from cdylibs][38117] * [The `--test` flag works with procedural macro crates][38107] * [Fix `extern "aapcs" fn` ABI][37814] * [The `-C no-stack-check` flag is deprecated][37636]. It does nothing. * [The `format!` expander recognizes incorrect `printf` and shell-style formatting directives and suggests the correct format][37613]. * [Only report one error for all unused imports in an import list][37456] Compiler Performance -------------------- * [Avoid unnecessary `mk_ty` calls in `Ty::super_fold_with`][37705] * [Avoid more unnecessary `mk_ty` calls in `Ty::super_fold_with`][37979] * [Don't clone in `UnificationTable::probe`][37848] * [Remove `scope_auxiliary` to cut RSS by 10%][37764] * [Use small vectors in type walker][37760] * [Macro expansion performance was improved][37701] * [Change `HirVec<P<T>>` to `HirVec<T>` in `hir::Expr`][37642] * [Replace FNV with a faster hash function][37229] Stabilized APIs --------------- * [`std::iter::Iterator::min_by`] * [`std::iter::Iterator::max_by`] * [`std::os::*::fs::FileExt`] * [`std::sync::atomic::Atomic*::get_mut`] * [`std::sync::atomic::Atomic*::into_inner`] * [`std::vec::IntoIter::as_slice`] * [`std::vec::IntoIter::as_mut_slice`] * [`std::sync::mpsc::Receiver::try_iter`] * [`std::os::unix::process::CommandExt::before_exec`] * [`std::rc::Rc::strong_count`] * [`std::rc::Rc::weak_count`] * [`std::sync::Arc::strong_count`] * [`std::sync::Arc::weak_count`] * [`std::char::encode_utf8`] * [`std::char::encode_utf16`] * [`std::cell::Ref::clone`] * [`std::io::Take::into_inner`] Libraries --------- * [The standard sorting algorithm has been rewritten for dramatic performance improvements][38192]. It is a hybrid merge sort, drawing influences from Timsort. Previously it was a naive merge sort. * [`Iterator::nth` no longer has a `Sized` bound][38134] * [`Extend<&T>` is specialized for `Vec` where `T: Copy`][38182] to improve performance. * [`chars().count()` is much faster][37888] and so are [`chars().last()` and `char_indices().last()`][37882] * [Fix ARM Objective-C ABI in `std::env::args`][38146] * [Chinese characters display correctly in `fmt::Debug`][37855] * [Derive `Default` for `Duration`][37699] * [Support creation of anonymous pipes on WinXP/2k][37677] * [`mpsc::RecvTimeoutError` implements `Error`][37527] * [Don't pass overlapped handles to processes][38835] Cargo ----- * [In this release, Cargo build scripts no longer have access to the `OUT_DIR` environment variable at build time via `env!("OUT_DIR")`][cargo/3368]. They should instead check the variable at runtime with `std::env`. That the value was set at build time was a bug, and incorrect when cross-compiling. This change is known to cause breakage. * [Add `--all` flag to `cargo test`][cargo/3221] * [Compile statically against the MSVC CRT][cargo/3363] * [Mix feature flags into fingerprint/metadata shorthash][cargo/3102] * [Link OpenSSL statically on OSX][cargo/3311] * [Apply new fingerprinting to build dir outputs][cargo/3310] * [Test for bad path overrides with summaries][cargo/3336] * [Require `cargo install --vers` to take a semver version][cargo/3338] * [Fix retrying crate downloads for network errors][cargo/3348] * [Implement string lookup for `build.rustflags` config key][cargo/3356] * [Emit more info on --message-format=json][cargo/3319] * [Assume `build.rs` in the same directory as `Cargo.toml` is a build script][cargo/3361] * [Don't ignore errors in workspace manifest][cargo/3409] * [Fix `--message-format JSON` when rustc emits non-JSON warnings][cargo/3410] Tooling ------- * [Test runners (binaries built with `--test`) now support a `--list` argument that lists the tests it contains][38185] * [Test runners now support a `--exact` argument that makes the test filter match exactly, instead of matching only a substring of the test name][38181] * [rustdoc supports a `--playground-url` flag][37763] * [rustdoc provides more details about `#[should_panic]` errors][37749] Misc ---- * [The Rust build system is now written in Rust][37817]. The Makefiles may continue to be used in this release by passing `--disable-rustbuild` to the configure script, but they will be deleted soon. Note that the new build system uses a different on-disk layout that will likely affect any scripts building Rust. * [Rust supports i686-unknown-openbsd][38086]. Tier 3 support. No testing or releases. * [Rust supports the MSP430][37627]. Tier 3 support. No testing or releases. * [Rust supports the ARMv5TE architecture][37615]. Tier 3 support. No testing or releases. Compatibility Notes ------------------- * [A number of minor changes to name resolution have been activated][37127]. They add up to more consistent semantics, allowing for future evolution of Rust macros. Specified in [RFC 1560], see its section on ["changes"] for details of what is different. The breaking changes here have been transitioned through the [`legacy_imports`] lint since 1.14, with no known regressions. * [In this release, Cargo build scripts no longer have access to the `OUT_DIR` environment variable at build time via `env!("OUT_DIR")`][cargo/3368]. They should instead check the variable at runtime with `std::env`. That the value was set at build time was a bug, and incorrect when cross-compiling. This change is known to cause breakage. * [Higher-ranked lifetimes are no longer allowed to appear _only_ in associated types][33685]. The [`hr_lifetime_in_assoc_type` lint] has been a warning since 1.10 and is now an error by default. It will become a hard error in the near future. * [The semantics relating modules to file system directories are changing in minor ways][37602]. This is captured in the new `legacy_directory_ownership` lint, which is a warning in this release, and will become a hard error in the future. * [Rust-ABI symbols are no longer exported from cdylibs][38117] * [Once `Peekable` peeks a `None` it will return that `None` without re-querying the underlying iterator][37834] ["changes"]: https://github.com/rust-lang/rfcs/blob/master/text/1560-name-resolution.md#changes-to-name-resolution-rules [33685]: https://github.com/rust-lang/rust/issues/33685 [36868]: https://github.com/rust-lang/rust/pull/36868 [37127]: https://github.com/rust-lang/rust/pull/37127 [37229]: https://github.com/rust-lang/rust/pull/37229 [37456]: https://github.com/rust-lang/rust/pull/37456 [37527]: https://github.com/rust-lang/rust/pull/37527 [37602]: https://github.com/rust-lang/rust/pull/37602 [37613]: https://github.com/rust-lang/rust/pull/37613 [37615]: https://github.com/rust-lang/rust/pull/37615 [37636]: https://github.com/rust-lang/rust/pull/37636 [37627]: https://github.com/rust-lang/rust/pull/37627 [37642]: https://github.com/rust-lang/rust/pull/37642 [37677]: https://github.com/rust-lang/rust/pull/37677 [37699]: https://github.com/rust-lang/rust/pull/37699 [37701]: https://github.com/rust-lang/rust/pull/37701 [37705]: https://github.com/rust-lang/rust/pull/37705 [37749]: https://github.com/rust-lang/rust/pull/37749 [37760]: https://github.com/rust-lang/rust/pull/37760 [37763]: https://github.com/rust-lang/rust/pull/37763 [37764]: https://github.com/rust-lang/rust/pull/37764 [37789]: https://github.com/rust-lang/rust/pull/37789 [37791]: https://github.com/rust-lang/rust/pull/37791 [37814]: https://github.com/rust-lang/rust/pull/37814 [37817]: https://github.com/rust-lang/rust/pull/37817 [37834]: https://github.com/rust-lang/rust/pull/37834 [37848]: https://github.com/rust-lang/rust/pull/37848 [37855]: https://github.com/rust-lang/rust/pull/37855 [37882]: https://github.com/rust-lang/rust/pull/37882 [37888]: https://github.com/rust-lang/rust/pull/37888 [37973]: https://github.com/rust-lang/rust/pull/37973 [37979]: https://github.com/rust-lang/rust/pull/37979 [38086]: https://github.com/rust-lang/rust/pull/38086 [38107]: https://github.com/rust-lang/rust/pull/38107 [38117]: https://github.com/rust-lang/rust/pull/38117 [38134]: https://github.com/rust-lang/rust/pull/38134 [38146]: https://github.com/rust-lang/rust/pull/38146 [38181]: https://github.com/rust-lang/rust/pull/38181 [38182]: https://github.com/rust-lang/rust/pull/38182 [38185]: https://github.com/rust-lang/rust/pull/38185 [38192]: https://github.com/rust-lang/rust/pull/38192 [38279]: https://github.com/rust-lang/rust/pull/38279 [38835]: https://github.com/rust-lang/rust/pull/38835 [RFC 1506]: https://github.com/rust-lang/rfcs/blob/master/text/1506-adt-kinds.md [RFC 1560]: https://github.com/rust-lang/rfcs/blob/master/text/1560-name-resolution.md [RFC 1681]: https://github.com/rust-lang/rfcs/blob/master/text/1681-macros-1.1.md [RFC 1717]: https://github.com/rust-lang/rfcs/blob/master/text/1717-dllimport.md [`hr_lifetime_in_assoc_type` lint]: https://github.com/rust-lang/rust/issues/33685 [`legacy_imports`]: https://github.com/rust-lang/rust/pull/38271 [cargo/3102]: https://github.com/rust-lang/cargo/pull/3102 [cargo/3221]: https://github.com/rust-lang/cargo/pull/3221 [cargo/3310]: https://github.com/rust-lang/cargo/pull/3310 [cargo/3311]: https://github.com/rust-lang/cargo/pull/3311 [cargo/3319]: https://github.com/rust-lang/cargo/pull/3319 [cargo/3336]: https://github.com/rust-lang/cargo/pull/3336 [cargo/3338]: https://github.com/rust-lang/cargo/pull/3338 [cargo/3348]: https://github.com/rust-lang/cargo/pull/3348 [cargo/3356]: https://github.com/rust-lang/cargo/pull/3356 [cargo/3361]: https://github.com/rust-lang/cargo/pull/3361 [cargo/3363]: https://github.com/rust-lang/cargo/pull/3363 [cargo/3368]: https://github.com/rust-lang/cargo/issues/3368 [cargo/3409]: https://github.com/rust-lang/cargo/pull/3409 [cargo/3410]: https://github.com/rust-lang/cargo/pull/3410 [`std::iter::Iterator::min_by`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.min_by [`std::iter::Iterator::max_by`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.max_by [`std::os::*::fs::FileExt`]: https://doc.rust-lang.org/std/os/unix/fs/trait.FileExt.html [`std::sync::atomic::Atomic*::get_mut`]: https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU8.html#method.get_mut [`std::sync::atomic::Atomic*::into_inner`]: https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU8.html#method.into_inner [`std::vec::IntoIter::as_slice`]: https://doc.rust-lang.org/std/vec/struct.IntoIter.html#method.as_slice [`std::vec::IntoIter::as_mut_slice`]: https://doc.rust-lang.org/std/vec/struct.IntoIter.html#method.as_mut_slice [`std::sync::mpsc::Receiver::try_iter`]: https://doc.rust-lang.org/std/sync/mpsc/struct.Receiver.html#method.try_iter [`std::os::unix::process::CommandExt::before_exec`]: https://doc.rust-lang.org/std/os/unix/process/trait.CommandExt.html#tymethod.before_exec [`std::rc::Rc::strong_count`]: https://doc.rust-lang.org/std/rc/struct.Rc.html#method.strong_count [`std::rc::Rc::weak_count`]: https://doc.rust-lang.org/std/rc/struct.Rc.html#method.weak_count [`std::sync::Arc::strong_count`]: https://doc.rust-lang.org/std/sync/struct.Arc.html#method.strong_count [`std::sync::Arc::weak_count`]: https://doc.rust-lang.org/std/sync/struct.Arc.html#method.weak_count [`std::char::encode_utf8`]: https://doc.rust-lang.org/std/primitive.char.html#method.encode_utf8 [`std::char::encode_utf16`]: https://doc.rust-lang.org/std/primitive.char.html#method.encode_utf16 [`std::cell::Ref::clone`]: https://doc.rust-lang.org/std/cell/struct.Ref.html#method.clone [`std::io::Take::into_inner`]: https://doc.rust-lang.org/std/io/struct.Take.html#method.into_inner Version 1.14.0 (2016-12-22) =========================== Language -------- * [`..` matches multiple tuple fields in enum variants, structs and tuples][36843]. [RFC 1492]. * [Safe `fn` items can be coerced to `unsafe fn` pointers][37389] * [`use *` and `use ::*` both glob-import from the crate root][37367] * [It's now possible to call a `Vec<Box<Fn()>>` without explicit dereferencing][36822] Compiler -------- * [Mark enums with non-zero discriminant as non-zero][37224] * [Lower-case `static mut` names are linted like other statics and consts][37162] * [Fix ICE on some macros in const integer positions (e.g. `[u8; m!()]`)][36819] * [Improve error message and snippet for "did you mean `x`"][36798] * [Add a panic-strategy field to the target specification][36794] * [Include LLVM version in `--version --verbose`][37200] Compile-time Optimizations -------------------------- * [Improve macro expansion performance][37569] * [Shrink `Expr_::ExprInlineAsm`][37445] * [Replace all uses of SHA-256 with BLAKE2b][37439] * [Reduce the number of bytes hashed by `IchHasher`][37427] * [Avoid more allocations when compiling html5ever][37373] * [Use `SmallVector` in `CombineFields::instantiate`][37322] * [Avoid some allocations in the macro parser][37318] * [Use a faster deflate setting][37298] * [Add `ArrayVec` and `AccumulateVec` to reduce heap allocations during interning of slices][37270] * [Optimize `write_metadata`][37267] * [Don't process obligation forest cycles when stalled][37231] * [Avoid many `CrateConfig` clones][37161] * [Optimize `Substs::super_fold_with`][37108] * [Optimize `ObligationForest`'s `NodeState` handling][36993] * [Speed up `plug_leaks`][36917] Libraries --------- * [`println!()`, with no arguments, prints newline][36825]. Previously, an empty string was required to achieve the same. * [`Wrapping` impls standard binary and unary operators, as well as the `Sum` and `Product` iterators][37356] * [Implement `From<Cow<str>> for String` and `From<Cow<[T]>> for Vec<T>`][37326] * [Improve `fold` performance for `chain`, `cloned`, `map`, and `VecDeque` iterators][37315] * [Improve `SipHasher` performance on small values][37312] * [Add Iterator trait TrustedLen to enable better FromIterator / Extend][37306] * [Expand `.zip()` specialization to `.map()` and `.cloned()`][37230] * [`ReadDir` implements `Debug`][37221] * [Implement `RefUnwindSafe` for atomic types][37178] * [Specialize `Vec::extend` to `Vec::extend_from_slice`][37094] * [Avoid allocations in `Decoder::read_str`][37064] * [`io::Error` implements `From<io::ErrorKind>`][37037] * [Impl `Debug` for raw pointers to unsized data][36880] * [Don't reuse `HashMap` random seeds][37470] * [The internal memory layout of `HashMap` is more cache-friendly, for significant improvements in some operations][36692] * [`HashMap` uses less memory on 32-bit architectures][36595] * [Impl `Add<{str, Cow<str>}>` for `Cow<str>`][36430] Cargo ----- * [Expose rustc cfg values to build scripts][cargo/3243] * [Allow cargo to work with read-only `CARGO_HOME`][cargo/3259] * [Fix passing --features when testing multiple packages][cargo/3280] * [Use a single profile set per workspace][cargo/3249] * [Load `replace` sections from lock files][cargo/3220] * [Ignore `panic` configuration for test/bench profiles][cargo/3175] Tooling ------- * [rustup is the recommended Rust installation method][1.14rustup] * This release includes host (rustc) builds for Linux on MIPS, PowerPC, and S390x. These are [tier 2] platforms and may have major defects. Follow the instructions on the website to install, or add the targets to an existing installation with `rustup target add`. The new target triples are: - `mips-unknown-linux-gnu` - `mipsel-unknown-linux-gnu` - `mips64-unknown-linux-gnuabi64` - `mips64el-unknown-linux-gnuabi64 ` - `powerpc-unknown-linux-gnu` - `powerpc64-unknown-linux-gnu` - `powerpc64le-unknown-linux-gnu` - `s390x-unknown-linux-gnu ` * This release includes target (std) builds for ARM Linux running MUSL libc. These are [tier 2] platforms and may have major defects. Add the following triples to an existing rustup installation with `rustup target add`: - `arm-unknown-linux-musleabi` - `arm-unknown-linux-musleabihf` - `armv7-unknown-linux-musleabihf` * This release includes [experimental support for WebAssembly][1.14wasm], via the `wasm32-unknown-emscripten` target. This target is known to have major defects. Please test, report, and fix. * rustup no longer installs documentation by default. Run `rustup component add rust-docs` to install. * [Fix line stepping in debugger][37310] * [Enable line number debuginfo in releases][37280] Misc ---- * [Disable jemalloc on aarch64/powerpc/mips][37392] * [Add support for Fuchsia OS][37313] * [Detect local-rebuild by only MAJOR.MINOR version][37273] Compatibility Notes ------------------- * [A number of forward-compatibility lints used by the compiler to gradually introduce language changes have been converted to deny by default][36894]: - ["use of inaccessible extern crate erroneously allowed"][36886] - ["type parameter default erroneously allowed in invalid location"][36887] - ["detects super or self keywords at the beginning of global path"][36888] - ["two overlapping inherent impls define an item with the same name were erroneously allowed"][36889] - ["floating-point constants cannot be used in patterns"][36890] - ["constants of struct or enum type can only be used in a pattern if the struct or enum has `#[derive(PartialEq, Eq)]`"][36891] - ["lifetimes or labels named `'_` were erroneously allowed"][36892] * [Prohibit patterns in trait methods without bodies][37378] * [The atomic `Ordering` enum may not be matched exhaustively][37351] * [Future-proofing `#[no_link]` breaks some obscure cases][37247] * [The `$crate` macro variable is accepted in fewer locations][37213] * [Impls specifying extra region requirements beyond the trait they implement are rejected][37167] * [Enums may not be unsized][37111]. Unsized enums are intended to work but never have. For now they are forbidden. * [Enforce the shadowing restrictions from RFC 1560 for today's macros][36767] [tier 2]: https://forge.rust-lang.org/platform-support.html [1.14rustup]: https://internals.rust-lang.org/t/beta-testing-rustup-rs/3316/204 [1.14wasm]: https://users.rust-lang.org/t/compiling-to-the-web-with-rust-and-emscripten/7627 [36430]: https://github.com/rust-lang/rust/pull/36430 [36595]: https://github.com/rust-lang/rust/pull/36595 [36692]: https://github.com/rust-lang/rust/pull/36692 [36767]: https://github.com/rust-lang/rust/pull/36767 [36794]: https://github.com/rust-lang/rust/pull/36794 [36798]: https://github.com/rust-lang/rust/pull/36798 [36819]: https://github.com/rust-lang/rust/pull/36819 [36822]: https://github.com/rust-lang/rust/pull/36822 [36825]: https://github.com/rust-lang/rust/pull/36825 [36843]: https://github.com/rust-lang/rust/pull/36843 [36880]: https://github.com/rust-lang/rust/pull/36880 [36886]: https://github.com/rust-lang/rust/issues/36886 [36887]: https://github.com/rust-lang/rust/issues/36887 [36888]: https://github.com/rust-lang/rust/issues/36888 [36889]: https://github.com/rust-lang/rust/issues/36889 [36890]: https://github.com/rust-lang/rust/issues/36890 [36891]: https://github.com/rust-lang/rust/issues/36891 [36892]: https://github.com/rust-lang/rust/issues/36892 [36894]: https://github.com/rust-lang/rust/pull/36894 [36917]: https://github.com/rust-lang/rust/pull/36917 [36993]: https://github.com/rust-lang/rust/pull/36993 [37037]: https://github.com/rust-lang/rust/pull/37037 [37064]: https://github.com/rust-lang/rust/pull/37064 [37094]: https://github.com/rust-lang/rust/pull/37094 [37108]: https://github.com/rust-lang/rust/pull/37108 [37111]: https://github.com/rust-lang/rust/pull/37111 [37161]: https://github.com/rust-lang/rust/pull/37161 [37162]: https://github.com/rust-lang/rust/pull/37162 [37167]: https://github.com/rust-lang/rust/pull/37167 [37178]: https://github.com/rust-lang/rust/pull/37178 [37200]: https://github.com/rust-lang/rust/pull/37200 [37213]: https://github.com/rust-lang/rust/pull/37213 [37221]: https://github.com/rust-lang/rust/pull/37221 [37224]: https://github.com/rust-lang/rust/pull/37224 [37230]: https://github.com/rust-lang/rust/pull/37230 [37231]: https://github.com/rust-lang/rust/pull/37231 [37247]: https://github.com/rust-lang/rust/pull/37247 [37267]: https://github.com/rust-lang/rust/pull/37267 [37270]: https://github.com/rust-lang/rust/pull/37270 [37273]: https://github.com/rust-lang/rust/pull/37273 [37280]: https://github.com/rust-lang/rust/pull/37280 [37298]: https://github.com/rust-lang/rust/pull/37298 [37306]: https://github.com/rust-lang/rust/pull/37306 [37310]: https://github.com/rust-lang/rust/pull/37310 [37312]: https://github.com/rust-lang/rust/pull/37312 [37313]: https://github.com/rust-lang/rust/pull/37313 [37315]: https://github.com/rust-lang/rust/pull/37315 [37318]: https://github.com/rust-lang/rust/pull/37318 [37322]: https://github.com/rust-lang/rust/pull/37322 [37326]: https://github.com/rust-lang/rust/pull/37326 [37351]: https://github.com/rust-lang/rust/pull/37351 [37356]: https://github.com/rust-lang/rust/pull/37356 [37367]: https://github.com/rust-lang/rust/pull/37367 [37373]: https://github.com/rust-lang/rust/pull/37373 [37378]: https://github.com/rust-lang/rust/pull/37378 [37389]: https://github.com/rust-lang/rust/pull/37389 [37392]: https://github.com/rust-lang/rust/pull/37392 [37427]: https://github.com/rust-lang/rust/pull/37427 [37439]: https://github.com/rust-lang/rust/pull/37439 [37445]: https://github.com/rust-lang/rust/pull/37445 [37470]: https://github.com/rust-lang/rust/pull/37470 [37569]: https://github.com/rust-lang/rust/pull/37569 [RFC 1492]: https://github.com/rust-lang/rfcs/blob/master/text/1492-dotdot-in-patterns.md [cargo/3175]: https://github.com/rust-lang/cargo/pull/3175 [cargo/3220]: https://github.com/rust-lang/cargo/pull/3220 [cargo/3243]: https://github.com/rust-lang/cargo/pull/3243 [cargo/3249]: https://github.com/rust-lang/cargo/pull/3249 [cargo/3259]: https://github.com/rust-lang/cargo/pull/3259 [cargo/3280]: https://github.com/rust-lang/cargo/pull/3280 Version 1.13.0 (2016-11-10) =========================== Language -------- * [Stabilize the `?` operator][36995]. `?` is a simple way to propagate errors, like the `try!` macro, described in [RFC 0243]. * [Stabilize macros in type position][36014]. Described in [RFC 873]. * [Stabilize attributes on statements][36995]. Described in [RFC 0016]. * [Fix `#[derive]` for empty tuple structs/variants][35728] * [Fix lifetime rules for 'if' conditions][36029] * [Avoid loading and parsing unconfigured non-inline modules][36482] Compiler -------- * [Add the `-C link-arg` argument][36574] * [Remove the old AST-based backend from rustc_trans][35764] * [Don't enable NEON by default on armv7 Linux][35814] * [Fix debug line number info for macro expansions][35238] * [Do not emit "class method" debuginfo for types that are not DICompositeType][36008] * [Warn about multiple conflicting #[repr] hints][34623] * [When sizing DST, don't double-count nested struct prefixes][36351] * [Default RUST_MIN_STACK to 16MiB for now][36505] * [Improve rlib metadata format][36551]. Reduces rlib size significantly. * [Reject macros with empty repetitions to avoid infinite loop][36721] * [Expand macros without recursing to avoid stack overflows][36214] Diagnostics ----------- * [Replace macro backtraces with labeled local uses][35702] * [Improve error message for misplaced doc comments][33922] * [Buffer unix and lock windows to prevent message interleaving][35975] * [Update lifetime errors to specifically note temporaries][36171] * [Special case a few colors for Windows][36178] * [Suggest `use self` when such an import resolves][36289] * [Be more specific when type parameter shadows primitive type][36338] * Many minor improvements Compile-time Optimizations -------------------------- * [Compute and cache HIR hashes at beginning][35854] * [Don't hash types in loan paths][36004] * [Cache projections in trans][35761] * [Optimize the parser's last token handling][36527] * [Only instantiate #[inline] functions in codegen units referencing them][36524]. This leads to big improvements in cases where crates export define many inline functions without using them directly. * [Lazily allocate TypedArena's first chunk][36592] * [Don't allocate during default HashSet creation][36734] Stabilized APIs --------------- * [`checked_abs`] * [`wrapping_abs`] * [`overflowing_abs`] * [`RefCell::try_borrow`] * [`RefCell::try_borrow_mut`] Libraries --------- * [Add `assert_ne!` and `debug_assert_ne!`][35074] * [Make `vec_deque::Drain`, `hash_map::Drain`, and `hash_set::Drain` covariant][35354] * [Implement `AsRef<[T]>` for `std::slice::Iter`][35559] * [Implement `Debug` for `std::vec::IntoIter`][35707] * [`CString`: avoid excessive growth just to 0-terminate][35871] * [Implement `CoerceUnsized` for `{Cell, RefCell, UnsafeCell}`][35627] * [Use arc4rand on FreeBSD][35884] * [memrchr: Correct aligned offset computation][35969] * [Improve Demangling of Rust Symbols][36059] * [Use monotonic time in condition variables][35048] * [Implement `Debug` for `std::path::{Components,Iter}`][36101] * [Implement conversion traits for `char`][35755] * [Fix illegal instruction caused by overflow in channel cloning][36104] * [Zero first byte of CString on drop][36264] * [Inherit overflow checks for sum and product][36372] * [Add missing Eq implementations][36423] * [Implement `Debug` for `DirEntry`][36631] * [When `getaddrinfo` returns `EAI_SYSTEM` retrieve actual error from `errno`][36754] * [`SipHasher`] is deprecated. Use [`DefaultHasher`]. * [Implement more traits for `std::io::ErrorKind`][35911] * [Optimize BinaryHeap bounds checking][36072] * [Work around pointer aliasing issue in `Vec::extend_from_slice`, `extend_with_element`][36355] * [Fix overflow checking in unsigned pow()][34942] Cargo ----- * This release includes security fixes to both curl and OpenSSL. * [Fix transitive doctests when panic=abort][cargo/3021] * [Add --all-features flag to cargo][cargo/3038] * [Reject path-based dependencies in `cargo package`][cargo/3060] * [Don't parse the home directory more than once][cargo/3078] * [Don't try to generate Cargo.lock on empty workspaces][cargo/3092] * [Update OpenSSL to 1.0.2j][cargo/3121] * [Add license and license_file to cargo metadata output][cargo/3110] * [Make crates-io registry URL optional in config; ignore all changes to source.crates-io][cargo/3089] * [Don't download dependencies from other platforms][cargo/3123] * [Build transitive dev-dependencies when needed][cargo/3125] * [Add support for per-target rustflags in .cargo/config][cargo/3157] * [Avoid updating registry when adding existing deps][cargo/3144] * [Warn about path overrides that won't work][cargo/3136] * [Use workspaces during `cargo install`][cargo/3146] * [Leak mspdbsrv.exe processes on Windows][cargo/3162] * [Add --message-format flag][cargo/3000] * [Pass target environment for rustdoc][cargo/3205] * [Use `CommandExt::exec` for `cargo run` on Unix][cargo/2818] * [Update curl and curl-sys][cargo/3241] * [Call rustdoc test with the correct cfg flags of a package][cargo/3242] Tooling ------- * [rustdoc: Add the `--sysroot` argument][36586] * [rustdoc: Fix a couple of issues with the search results][35655] * [rustdoc: remove the `!` from macro URLs and titles][35234] * [gdb: Fix pretty-printing special-cased Rust types][35585] * [rustdoc: Filter more incorrect methods inherited through Deref][36266] Misc ---- * [Remove unmaintained style guide][35124] * [Add s390x support][36369] * [Initial work at Haiku OS support][36727] * [Add mips-uclibc targets][35734] * [Crate-ify compiler-rt into compiler-builtins][35021] * [Add rustc version info (git hash + date) to dist tarball][36213] * Many documentation improvements Compatibility Notes ------------------- * [`SipHasher`] is deprecated. Use [`DefaultHasher`]. * [Deny (by default) transmuting from fn item types to pointer-sized types][34923]. Continuing the long transition to zero-sized fn items, per [RFC 401]. * [Fix `#[derive]` for empty tuple structs/variants][35728]. Part of [RFC 1506]. * [Issue deprecation warnings for safe accesses to extern statics][36173] * [Fix lifetime rules for 'if' conditions][36029]. * [Inherit overflow checks for sum and product][36372]. * [Forbid user-defined macros named "macro_rules"][36730]. [33922]: https://github.com/rust-lang/rust/pull/33922 [34623]: https://github.com/rust-lang/rust/pull/34623 [34923]: https://github.com/rust-lang/rust/pull/34923 [34942]: https://github.com/rust-lang/rust/pull/34942 [35021]: https://github.com/rust-lang/rust/pull/35021 [35048]: https://github.com/rust-lang/rust/pull/35048 [35074]: https://github.com/rust-lang/rust/pull/35074 [35124]: https://github.com/rust-lang/rust/pull/35124 [35234]: https://github.com/rust-lang/rust/pull/35234 [35238]: https://github.com/rust-lang/rust/pull/35238 [35354]: https://github.com/rust-lang/rust/pull/35354 [35559]: https://github.com/rust-lang/rust/pull/35559 [35585]: https://github.com/rust-lang/rust/pull/35585 [35627]: https://github.com/rust-lang/rust/pull/35627 [35655]: https://github.com/rust-lang/rust/pull/35655 [35702]: https://github.com/rust-lang/rust/pull/35702 [35707]: https://github.com/rust-lang/rust/pull/35707 [35728]: https://github.com/rust-lang/rust/pull/35728 [35734]: https://github.com/rust-lang/rust/pull/35734 [35755]: https://github.com/rust-lang/rust/pull/35755 [35761]: https://github.com/rust-lang/rust/pull/35761 [35764]: https://github.com/rust-lang/rust/pull/35764 [35814]: https://github.com/rust-lang/rust/pull/35814 [35854]: https://github.com/rust-lang/rust/pull/35854 [35871]: https://github.com/rust-lang/rust/pull/35871 [35884]: https://github.com/rust-lang/rust/pull/35884 [35911]: https://github.com/rust-lang/rust/pull/35911 [35969]: https://github.com/rust-lang/rust/pull/35969 [35975]: https://github.com/rust-lang/rust/pull/35975 [36004]: https://github.com/rust-lang/rust/pull/36004 [36008]: https://github.com/rust-lang/rust/pull/36008 [36014]: https://github.com/rust-lang/rust/pull/36014 [36029]: https://github.com/rust-lang/rust/pull/36029 [36059]: https://github.com/rust-lang/rust/pull/36059 [36072]: https://github.com/rust-lang/rust/pull/36072 [36101]: https://github.com/rust-lang/rust/pull/36101 [36104]: https://github.com/rust-lang/rust/pull/36104 [36171]: https://github.com/rust-lang/rust/pull/36171 [36173]: https://github.com/rust-lang/rust/pull/36173 [36178]: https://github.com/rust-lang/rust/pull/36178 [36213]: https://github.com/rust-lang/rust/pull/36213 [36214]: https://github.com/rust-lang/rust/pull/36214 [36264]: https://github.com/rust-lang/rust/pull/36264 [36266]: https://github.com/rust-lang/rust/pull/36266 [36289]: https://github.com/rust-lang/rust/pull/36289 [36338]: https://github.com/rust-lang/rust/pull/36338 [36351]: https://github.com/rust-lang/rust/pull/36351 [36355]: https://github.com/rust-lang/rust/pull/36355 [36369]: https://github.com/rust-lang/rust/pull/36369 [36372]: https://github.com/rust-lang/rust/pull/36372 [36423]: https://github.com/rust-lang/rust/pull/36423 [36482]: https://github.com/rust-lang/rust/pull/36482 [36505]: https://github.com/rust-lang/rust/pull/36505 [36524]: https://github.com/rust-lang/rust/pull/36524 [36527]: https://github.com/rust-lang/rust/pull/36527 [36551]: https://github.com/rust-lang/rust/pull/36551 [36574]: https://github.com/rust-lang/rust/pull/36574 [36586]: https://github.com/rust-lang/rust/pull/36586 [36592]: https://github.com/rust-lang/rust/pull/36592 [36631]: https://github.com/rust-lang/rust/pull/36631 [36721]: https://github.com/rust-lang/rust/pull/36721 [36727]: https://github.com/rust-lang/rust/pull/36727 [36730]: https://github.com/rust-lang/rust/pull/36730 [36734]: https://github.com/rust-lang/rust/pull/36734 [36754]: https://github.com/rust-lang/rust/pull/36754 [36995]: https://github.com/rust-lang/rust/pull/36995 [RFC 0016]: https://github.com/rust-lang/rfcs/blob/master/text/0016-more-attributes.md [RFC 0243]: https://github.com/rust-lang/rfcs/blob/master/text/0243-trait-based-exception-handling.md [RFC 1506]: https://github.com/rust-lang/rfcs/blob/master/text/1506-adt-kinds.md [RFC 401]: https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md [RFC 873]: https://github.com/rust-lang/rfcs/blob/master/text/0873-type-macros.md [cargo/2818]: https://github.com/rust-lang/cargo/pull/2818 [cargo/3000]: https://github.com/rust-lang/cargo/pull/3000 [cargo/3021]: https://github.com/rust-lang/cargo/pull/3021 [cargo/3038]: https://github.com/rust-lang/cargo/pull/3038 [cargo/3060]: https://github.com/rust-lang/cargo/pull/3060 [cargo/3078]: https://github.com/rust-lang/cargo/pull/3078 [cargo/3089]: https://github.com/rust-lang/cargo/pull/3089 [cargo/3092]: https://github.com/rust-lang/cargo/pull/3092 [cargo/3110]: https://github.com/rust-lang/cargo/pull/3110 [cargo/3121]: https://github.com/rust-lang/cargo/pull/3121 [cargo/3123]: https://github.com/rust-lang/cargo/pull/3123 [cargo/3125]: https://github.com/rust-lang/cargo/pull/3125 [cargo/3136]: https://github.com/rust-lang/cargo/pull/3136 [cargo/3144]: https://github.com/rust-lang/cargo/pull/3144 [cargo/3146]: https://github.com/rust-lang/cargo/pull/3146 [cargo/3157]: https://github.com/rust-lang/cargo/pull/3157 [cargo/3162]: https://github.com/rust-lang/cargo/pull/3162 [cargo/3205]: https://github.com/rust-lang/cargo/pull/3205 [cargo/3241]: https://github.com/rust-lang/cargo/pull/3241 [cargo/3242]: https://github.com/rust-lang/cargo/pull/3242 [`checked_abs`]: https://doc.rust-lang.org/std/primitive.i32.html#method.checked_abs [`wrapping_abs`]: https://doc.rust-lang.org/std/primitive.i32.html#method.wrapping_abs [`overflowing_abs`]: https://doc.rust-lang.org/std/primitive.i32.html#method.overflowing_abs [`RefCell::try_borrow`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.try_borrow [`RefCell::try_borrow_mut`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.try_borrow_mut [`SipHasher`]: https://doc.rust-lang.org/std/hash/struct.SipHasher.html [`DefaultHasher`]: https://doc.rust-lang.org/std/collections/hash_map/struct.DefaultHasher.html Version 1.12.1 (2016-10-20) =========================== Regression Fixes ---------------- * [ICE: 'rustc' panicked at 'assertion failed: concrete_substs.is_normalized_for_trans()' #36381][36381] * [Confusion with double negation and booleans][36856] * [rustc 1.12.0 fails with SIGSEGV in release mode (syn crate 0.8.0)][36875] * [Rustc 1.12.0 Windows build of `ethcore` crate fails with LLVM error][36924] * [1.12.0: High memory usage when linking in release mode with debug info][36926] * [Corrupted memory after updated to 1.12][36936] * ["Let NullaryConstructor = something;" causes internal compiler error: "tried to overwrite interned AdtDef"][37026] * [Fix ICE: inject bitcast if types mismatch for invokes/calls/stores][37112] * [debuginfo: Handle spread_arg case in MIR-trans in a more stable way.][37153] [36381]: https://github.com/rust-lang/rust/issues/36381 [36856]: https://github.com/rust-lang/rust/issues/36856 [36875]: https://github.com/rust-lang/rust/issues/36875 [36924]: https://github.com/rust-lang/rust/issues/36924 [36926]: https://github.com/rust-lang/rust/issues/36926 [36936]: https://github.com/rust-lang/rust/issues/36936 [37026]: https://github.com/rust-lang/rust/issues/37026 [37112]: https://github.com/rust-lang/rust/issues/37112 [37153]: https://github.com/rust-lang/rust/issues/37153 Version 1.12.0 (2016-09-29) =========================== Highlights ---------- * [`rustc` translates code to LLVM IR via its own "middle" IR (MIR)](https://github.com/rust-lang/rust/pull/34096). This translation pass is far simpler than the previous AST->LLVM pass, and creates opportunities to perform new optimizations directly on the MIR. It was previously described [on the Rust blog](https://blog.rust-lang.org/2016/04/19/MIR.html). * [`rustc` presents a new, more readable error format, along with machine-readable JSON error output for use by IDEs](https://github.com/rust-lang/rust/pull/35401). Most common editors supporting Rust have been updated to work with it. It was previously described [on the Rust blog](https://blog.rust-lang.org/2016/08/10/Shape-of-errors-to-come.html). Compiler -------- * [`rustc` translates code to LLVM IR via its own "middle" IR (MIR)](https://github.com/rust-lang/rust/pull/34096). This translation pass is far simpler than the previous AST->LLVM pass, and creates opportunities to perform new optimizations directly on the MIR. It was previously described [on the Rust blog](https://blog.rust-lang.org/2016/04/19/MIR.html). * [Print the Rust target name, not the LLVM target name, with `--print target-list`](https://github.com/rust-lang/rust/pull/35489) * [The computation of `TypeId` is correct in some cases where it was previously producing inconsistent results](https://github.com/rust-lang/rust/pull/35267) * [The `mips-unknown-linux-gnu` target uses hardware floating point by default](https://github.com/rust-lang/rust/pull/34910) * [The `rustc` arguments, `--print target-cpus`, `--print target-features`, `--print relocation-models`, and `--print code-models` print the available options to the `-C target-cpu`, `-C target-feature`, `-C relocation-model` and `-C code-model` code generation arguments](https://github.com/rust-lang/rust/pull/34845) * [`rustc` supports three new MUSL targets on ARM: `arm-unknown-linux-musleabi`, `arm-unknown-linux-musleabihf`, and `armv7-unknown-linux-musleabihf`](https://github.com/rust-lang/rust/pull/35060). These targets produce statically-linked binaries. There are no binary release builds yet though. Diagnostics ----------- * [`rustc` presents a new, more readable error format, along with machine-readable JSON error output for use by IDEs](https://github.com/rust-lang/rust/pull/35401). Most common editors supporting Rust have been updated to work with it. It was previously described [on the Rust blog](https://blog.rust-lang.org/2016/08/10/Shape-of-errors-to-come.html). * [In error descriptions, references are now described in plain English, instead of as "&-ptr"](https://github.com/rust-lang/rust/pull/35611) * [In error type descriptions, unknown numeric types are named `{integer}` or `{float}` instead of `_`](https://github.com/rust-lang/rust/pull/35080) * [`rustc` emits a clearer error when inner attributes follow a doc comment](https://github.com/rust-lang/rust/pull/34676) Language -------- * [`macro_rules!` invocations can be made within `macro_rules!` invocations](https://github.com/rust-lang/rust/pull/34925) * [`macro_rules!` meta-variables are hygienic](https://github.com/rust-lang/rust/pull/35453) * [`macro_rules!` `tt` matchers can be reparsed correctly, making them much more useful](https://github.com/rust-lang/rust/pull/34908) * [`macro_rules!` `stmt` matchers correctly consume the entire contents when inside non-braces invocations](https://github.com/rust-lang/rust/pull/34886) * [Semicolons are properly required as statement delimiters inside `macro_rules!` invocations](https://github.com/rust-lang/rust/pull/34660) * [`cfg_attr` works on `path` attributes](https://github.com/rust-lang/rust/pull/34546) Stabilized APIs --------------- * [`Cell::as_ptr`](https://doc.rust-lang.org/std/cell/struct.Cell.html#method.as_ptr) * [`RefCell::as_ptr`](https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.as_ptr) * [`IpAddr::is_unspecified`](https://doc.rust-lang.org/std/net/enum.IpAddr.html#method.is_unspecified) * [`IpAddr::is_loopback`](https://doc.rust-lang.org/std/net/enum.IpAddr.html#method.is_loopback) * [`IpAddr::is_multicast`](https://doc.rust-lang.org/std/net/enum.IpAddr.html#method.is_multicast) * [`Ipv4Addr::is_unspecified`](https://doc.rust-lang.org/std/net/struct.Ipv4Addr.html#method.is_unspecified) * [`Ipv6Addr::octets`](https://doc.rust-lang.org/std/net/struct.Ipv6Addr.html#method.octets) * [`LinkedList::contains`](https://doc.rust-lang.org/std/collections/linked_list/struct.LinkedList.html#method.contains) * [`VecDeque::contains`](https://doc.rust-lang.org/std/collections/vec_deque/struct.VecDeque.html#method.contains) * [`ExitStatusExt::from_raw`](https://doc.rust-lang.org/std/os/unix/process/trait.ExitStatusExt.html#tymethod.from_raw). Both on Unix and Windows. * [`Receiver::recv_timeout`](https://doc.rust-lang.org/std/sync/mpsc/struct.Receiver.html#method.recv_timeout) * [`RecvTimeoutError`](https://doc.rust-lang.org/std/sync/mpsc/enum.RecvTimeoutError.html) * [`BinaryHeap::peek_mut`](https://doc.rust-lang.org/std/collections/binary_heap/struct.BinaryHeap.html#method.peek_mut) * [`PeekMut`](https://doc.rust-lang.org/std/collections/binary_heap/struct.PeekMut.html) * [`iter::Product`](https://doc.rust-lang.org/std/iter/trait.Product.html) * [`iter::Sum`](https://doc.rust-lang.org/std/iter/trait.Sum.html) * [`OccupiedEntry::remove_entry`](https://doc.rust-lang.org/std/collections/btree_map/struct.OccupiedEntry.html#method.remove_entry) * [`VacantEntry::into_key`](https://doc.rust-lang.org/std/collections/btree_map/struct.VacantEntry.html#method.into_key) Libraries --------- * [The `format!` macro and friends now allow a single argument to be formatted in multiple styles](https://github.com/rust-lang/rust/pull/33642) * [The lifetime bounds on `[T]::binary_search_by` and `[T]::binary_search_by_key` have been adjusted to be more flexible](https://github.com/rust-lang/rust/pull/34762) * [`Option` implements `From` for its contained type](https://github.com/rust-lang/rust/pull/34828) * [`Cell`, `RefCell` and `UnsafeCell` implement `From` for their contained type](https://github.com/rust-lang/rust/pull/35392) * [`RwLock` panics if the reader count overflows](https://github.com/rust-lang/rust/pull/35378) * [`vec_deque::Drain`, `hash_map::Drain` and `hash_set::Drain` are covariant](https://github.com/rust-lang/rust/pull/35354) * [`vec::Drain` and `binary_heap::Drain` are covariant](https://github.com/rust-lang/rust/pull/34951) * [`Cow<str>` implements `FromIterator` for `char`, `&str` and `String`](https://github.com/rust-lang/rust/pull/35064) * [Sockets on Linux are correctly closed in subprocesses via `SOCK_CLOEXEC`](https://github.com/rust-lang/rust/pull/34946) * [`hash_map::Entry`, `hash_map::VacantEntry` and `hash_map::OccupiedEntry` implement `Debug`](https://github.com/rust-lang/rust/pull/34937) * [`btree_map::Entry`, `btree_map::VacantEntry` and `btree_map::OccupiedEntry` implement `Debug`](https://github.com/rust-lang/rust/pull/34885) * [`String` implements `AddAssign`](https://github.com/rust-lang/rust/pull/34890) * [Variadic `extern fn` pointers implement the `Clone`, `PartialEq`, `Eq`, `PartialOrd`, `Ord`, `Hash`, `fmt::Pointer`, and `fmt::Debug` traits](https://github.com/rust-lang/rust/pull/34879) * [`FileType` implements `Debug`](https://github.com/rust-lang/rust/pull/34757) * [References to `Mutex` and `RwLock` are unwind-safe](https://github.com/rust-lang/rust/pull/34756) * [`mpsc::sync_channel` `Receiver`s return any available message before reporting a disconnect](https://github.com/rust-lang/rust/pull/34731) * [Unicode definitions have been updated to 9.0](https://github.com/rust-lang/rust/pull/34599) * [`env` iterators implement `DoubleEndedIterator`](https://github.com/rust-lang/rust/pull/33312) Cargo ----- * [Support local mirrors of registries](https://github.com/rust-lang/cargo/pull/2857) * [Add support for command aliases](https://github.com/rust-lang/cargo/pull/2679) * [Allow `opt-level="s"` / `opt-level="z"` in profile overrides](https://github.com/rust-lang/cargo/pull/3007) * [Make `cargo doc --open --target` work as expected](https://github.com/rust-lang/cargo/pull/2988) * [Speed up noop registry updates](https://github.com/rust-lang/cargo/pull/2974) * [Update OpenSSL](https://github.com/rust-lang/cargo/pull/2971) * [Fix `--panic=abort` with plugins](https://github.com/rust-lang/cargo/pull/2954) * [Always pass `-C metadata` to the compiler](https://github.com/rust-lang/cargo/pull/2946) * [Fix depending on git repos with workspaces](https://github.com/rust-lang/cargo/pull/2938) * [Add a `--lib` flag to `cargo new`](https://github.com/rust-lang/cargo/pull/2921) * [Add `http.cainfo` for custom certs](https://github.com/rust-lang/cargo/pull/2917) * [Indicate the compilation profile after compiling](https://github.com/rust-lang/cargo/pull/2909) * [Allow enabling features for dependencies with `--features`](https://github.com/rust-lang/cargo/pull/2876) * [Add `--jobs` flag to `cargo package`](https://github.com/rust-lang/cargo/pull/2867) * [Add `--dry-run` to `cargo publish`](https://github.com/rust-lang/cargo/pull/2849) * [Add support for `RUSTDOCFLAGS`](https://github.com/rust-lang/cargo/pull/2794) Performance ----------- * [`panic::catch_unwind` is more optimized](https://github.com/rust-lang/rust/pull/35444) * [`panic::catch_unwind` no longer accesses thread-local storage on entry](https://github.com/rust-lang/rust/pull/34866) Tooling ------- * [Test binaries now support a `--test-threads` argument to specify the number of threads used to run tests, and which acts the same as the `RUST_TEST_THREADS` environment variable](https://github.com/rust-lang/rust/pull/35414) * [The test runner now emits a warning when tests run over 60 seconds](https://github.com/rust-lang/rust/pull/35405) * [rustdoc: Fix methods in search results](https://github.com/rust-lang/rust/pull/34752) * [`rust-lldb` warns about unsupported versions of LLDB](https://github.com/rust-lang/rust/pull/34646) * [Rust releases now come with source packages that can be installed by rustup via `rustup component add rust-src`](https://github.com/rust-lang/rust/pull/34366). The resulting source code can be used by tools and IDES, located in the sysroot under `lib/rustlib/src`. Misc ---- * [The compiler can now be built against LLVM 3.9](https://github.com/rust-lang/rust/pull/35594) * Many minor improvements to the documentation. * [The Rust exception handling "personality" routine is now written in Rust](https://github.com/rust-lang/rust/pull/34832) Compatibility Notes ------------------- * [When printing Windows `OsStr`s, unpaired surrogate codepoints are escaped with the lowercase format instead of the uppercase](https://github.com/rust-lang/rust/pull/35084) * [When formatting strings, if "precision" is specified, the "fill", "align" and "width" specifiers are no longer ignored](https://github.com/rust-lang/rust/pull/34544) * [The `Debug` impl for strings no longer escapes all non-ASCII characters](https://github.com/rust-lang/rust/pull/34485) Version 1.11.0 (2016-08-18) =========================== Language -------- * [Support nested `cfg_attr` attributes](https://github.com/rust-lang/rust/pull/34216) * [Allow statement-generating braced macro invocations at the end of blocks](https://github.com/rust-lang/rust/pull/34436) * [Macros can be expanded inside of trait definitions](https://github.com/rust-lang/rust/pull/34213) * [`#[macro_use]` works properly when it is itself expanded from a macro](https://github.com/rust-lang/rust/pull/34032) Stabilized APIs --------------- * [`BinaryHeap::append`](https://doc.rust-lang.org/std/collections/binary_heap/struct.BinaryHeap.html#method.append) * [`BTreeMap::append`](https://doc.rust-lang.org/std/collections/btree_map/struct.BTreeMap.html#method.append) * [`BTreeMap::split_off`](https://doc.rust-lang.org/std/collections/btree_map/struct.BTreeMap.html#method.split_off) * [`BTreeSet::append`](https://doc.rust-lang.org/std/collections/btree_set/struct.BTreeSet.html#method.append) * [`BTreeSet::split_off`](https://doc.rust-lang.org/std/collections/btree_set/struct.BTreeSet.html#method.split_off) * [`f32::to_degrees`](https://doc.rust-lang.org/std/primitive.f32.html#method.to_degrees) (in libcore - previously stabilized in libstd) * [`f32::to_radians`](https://doc.rust-lang.org/std/primitive.f32.html#method.to_radians) (in libcore - previously stabilized in libstd) * [`f64::to_degrees`](https://doc.rust-lang.org/std/primitive.f64.html#method.to_degrees) (in libcore - previously stabilized in libstd) * [`f64::to_radians`](https://doc.rust-lang.org/std/primitive.f64.html#method.to_radians) (in libcore - previously stabilized in libstd) * [`Iterator::sum`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.sum) * [`Iterator::product`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.product) * [`Cell::get_mut`](https://doc.rust-lang.org/std/cell/struct.Cell.html#method.get_mut) * [`RefCell::get_mut`](https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.get_mut) Libraries --------- * [The `thread_local!` macro supports multiple definitions in a single invocation, and can apply attributes](https://github.com/rust-lang/rust/pull/34077) * [`Cow` implements `Default`](https://github.com/rust-lang/rust/pull/34305) * [`Wrapping` implements binary, octal, lower-hex and upper-hex `Display` formatting](https://github.com/rust-lang/rust/pull/34190) * [The range types implement `Hash`](https://github.com/rust-lang/rust/pull/34180) * [`lookup_host` ignores unknown address types](https://github.com/rust-lang/rust/pull/34067) * [`assert_eq!` accepts a custom error message, like `assert!` does](https://github.com/rust-lang/rust/pull/33976) * [The main thread is now called "main" instead of "&lt;main&gt;"](https://github.com/rust-lang/rust/pull/33803) Cargo ----- * [Disallow specifying features of transitive deps](https://github.com/rust-lang/cargo/pull/2821) * [Add color support for Windows consoles](https://github.com/rust-lang/cargo/pull/2804) * [Fix `harness = false` on `[lib]` sections](https://github.com/rust-lang/cargo/pull/2795) * [Don't panic when `links` contains a '.'](https://github.com/rust-lang/cargo/pull/2787) * [Build scripts can emit warnings](https://github.com/rust-lang/cargo/pull/2630), and `-vv` prints warnings for all crates. * [Ignore file locks on OS X NFS mounts](https://github.com/rust-lang/cargo/pull/2720) * [Don't warn about `package.metadata` keys](https://github.com/rust-lang/cargo/pull/2668). This provides room for expansion by arbitrary tools. * [Add support for cdylib crate types](https://github.com/rust-lang/cargo/pull/2741) * [Prevent publishing crates when files are dirty](https://github.com/rust-lang/cargo/pull/2781) * [Don't fetch all crates on clean](https://github.com/rust-lang/cargo/pull/2704) * [Propagate --color option to rustc](https://github.com/rust-lang/cargo/pull/2779) * [Fix `cargo doc --open` on Windows](https://github.com/rust-lang/cargo/pull/2780) * [Improve autocompletion](https://github.com/rust-lang/cargo/pull/2772) * [Configure colors of stderr as well as stdout](https://github.com/rust-lang/cargo/pull/2739) Performance ----------- * [Caching projections speeds up type check dramatically for some workloads](https://github.com/rust-lang/rust/pull/33816) * [The default `HashMap` hasher is SipHash 1-3 instead of SipHash 2-4](https://github.com/rust-lang/rust/pull/33940) This hasher is faster, but is believed to provide sufficient protection from collision attacks. * [Comparison of `Ipv4Addr` is 10x faster](https://github.com/rust-lang/rust/pull/33891) Rustdoc ------- * [Fix empty implementation section on some module pages](https://github.com/rust-lang/rust/pull/34536) * [Fix inlined renamed re-exports in import lists](https://github.com/rust-lang/rust/pull/34479) * [Fix search result layout for enum variants and struct fields](https://github.com/rust-lang/rust/pull/34477) * [Fix issues with source links to external crates](https://github.com/rust-lang/rust/pull/34387) * [Fix redirect pages for renamed re-exports](https://github.com/rust-lang/rust/pull/34245) Tooling ------- * [rustc is better at finding the MSVC toolchain](https://github.com/rust-lang/rust/pull/34492) * [When emitting debug info, rustc emits frame pointers for closures, shims and glue, as it does for all other functions](https://github.com/rust-lang/rust/pull/33909) * [rust-lldb warns about unsupported versions of LLDB](https://github.com/rust-lang/rust/pull/34646) * Many more errors have been given error codes and extended explanations * API documentation continues to be improved, with many new examples Misc ---- * [rustc no longer hangs when dependencies recursively re-export submodules](https://github.com/rust-lang/rust/pull/34542) * [rustc requires LLVM 3.7+](https://github.com/rust-lang/rust/pull/34104) * [The 'How Safe and Unsafe Interact' chapter of The Rustonomicon was rewritten](https://github.com/rust-lang/rust/pull/33895) * [rustc support 16-bit pointer sizes](https://github.com/rust-lang/rust/pull/33460). No targets use this yet, but it works toward AVR support. Compatibility Notes ------------------- * [`const`s and `static`s may not have unsized types](https://github.com/rust-lang/rust/pull/34443) * [The new follow-set rules that place restrictions on `macro_rules!` in order to ensure syntax forward-compatibility have been enabled](https://github.com/rust-lang/rust/pull/33982) This was an [amendment to RFC 550](https://github.com/rust-lang/rfcs/pull/1384), and has been a warning since 1.10. * [`cfg` attribute process has been refactored to fix various bugs](https://github.com/rust-lang/rust/pull/33706). This causes breakage in some corner cases. Version 1.10.0 (2016-07-07) =========================== Language -------- * [`Copy` types are required to have a trivial implementation of `Clone`](https://github.com/rust-lang/rust/pull/33420). [RFC 1521](https://github.com/rust-lang/rfcs/blob/master/text/1521-copy-clone-semantics.md). * [Single-variant enums support the `#[repr(..)]` attribute](https://github.com/rust-lang/rust/pull/33355). * [Fix `#[derive(RustcEncodable)]` in the presence of other `encode` methods](https://github.com/rust-lang/rust/pull/32908). * [`panic!` can be converted to a runtime abort with the `-C panic=abort` flag](https://github.com/rust-lang/rust/pull/32900). [RFC 1513](https://github.com/rust-lang/rfcs/blob/master/text/1513-less-unwinding.md). * [Add a new crate type, 'cdylib'](https://github.com/rust-lang/rust/pull/33553). cdylibs are dynamic libraries suitable for loading by non-Rust hosts. [RFC 1510](https://github.com/rust-lang/rfcs/blob/master/text/1510-cdylib.md). Note that Cargo does not yet directly support cdylibs. Stabilized APIs --------------- * `os::windows::fs::OpenOptionsExt::access_mode` * `os::windows::fs::OpenOptionsExt::share_mode` * `os::windows::fs::OpenOptionsExt::custom_flags` * `os::windows::fs::OpenOptionsExt::attributes` * `os::windows::fs::OpenOptionsExt::security_qos_flags` * `os::unix::fs::OpenOptionsExt::custom_flags` * [`sync::Weak::new`](http://doc.rust-lang.org/alloc/arc/struct.Weak.html#method.new) * `Default for sync::Weak` * [`panic::set_hook`](http://doc.rust-lang.org/std/panic/fn.set_hook.html) * [`panic::take_hook`](http://doc.rust-lang.org/std/panic/fn.take_hook.html) * [`panic::PanicInfo`](http://doc.rust-lang.org/std/panic/struct.PanicInfo.html) * [`panic::PanicInfo::payload`](http://doc.rust-lang.org/std/panic/struct.PanicInfo.html#method.payload) * [`panic::PanicInfo::location`](http://doc.rust-lang.org/std/panic/struct.PanicInfo.html#method.location) * [`panic::Location`](http://doc.rust-lang.org/std/panic/struct.Location.html) * [`panic::Location::file`](http://doc.rust-lang.org/std/panic/struct.Location.html#method.file) * [`panic::Location::line`](http://doc.rust-lang.org/std/panic/struct.Location.html#method.line) * [`ffi::CStr::from_bytes_with_nul`](http://doc.rust-lang.org/std/ffi/struct.CStr.html#method.from_bytes_with_nul) * [`ffi::CStr::from_bytes_with_nul_unchecked`](http://doc.rust-lang.org/std/ffi/struct.CStr.html#method.from_bytes_with_nul_unchecked) * [`ffi::FromBytesWithNulError`](http://doc.rust-lang.org/std/ffi/struct.FromBytesWithNulError.html) * [`fs::Metadata::modified`](http://doc.rust-lang.org/std/fs/struct.Metadata.html#method.modified) * [`fs::Metadata::accessed`](http://doc.rust-lang.org/std/fs/struct.Metadata.html#method.accessed) * [`fs::Metadata::created`](http://doc.rust-lang.org/std/fs/struct.Metadata.html#method.created) * `sync::atomic::Atomic{Usize,Isize,Bool,Ptr}::compare_exchange` * `sync::atomic::Atomic{Usize,Isize,Bool,Ptr}::compare_exchange_weak` * `collections::{btree,hash}_map::{Occupied,Vacant,}Entry::key` * `os::unix::net::{UnixStream, UnixListener, UnixDatagram, SocketAddr}` * [`SocketAddr::is_unnamed`](http://doc.rust-lang.org/std/os/unix/net/struct.SocketAddr.html#method.is_unnamed) * [`SocketAddr::as_pathname`](http://doc.rust-lang.org/std/os/unix/net/struct.SocketAddr.html#method.as_pathname) * [`UnixStream::connect`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.connect) * [`UnixStream::pair`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.pair) * [`UnixStream::try_clone`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.try_clone) * [`UnixStream::local_addr`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.local_addr) * [`UnixStream::peer_addr`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.peer_addr) * [`UnixStream::set_read_timeout`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.read_timeout) * [`UnixStream::set_write_timeout`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.write_timeout) * [`UnixStream::read_timeout`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.read_timeout) * [`UnixStream::write_timeout`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.write_timeout) * [`UnixStream::set_nonblocking`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.set_nonblocking) * [`UnixStream::take_error`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.take_error) * [`UnixStream::shutdown`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.shutdown) * Read/Write/RawFd impls for `UnixStream` * [`UnixListener::bind`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixListener.html#method.bind) * [`UnixListener::accept`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixListener.html#method.accept) * [`UnixListener::try_clone`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixListener.html#method.try_clone) * [`UnixListener::local_addr`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixListener.html#method.local_addr) * [`UnixListener::set_nonblocking`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixListener.html#method.set_nonblocking) * [`UnixListener::take_error`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixListener.html#method.take_error) * [`UnixListener::incoming`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixListener.html#method.incoming) * RawFd impls for `UnixListener` * [`UnixDatagram::bind`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.bind) * [`UnixDatagram::unbound`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.unbound) * [`UnixDatagram::pair`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.pair) * [`UnixDatagram::connect`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.connect) * [`UnixDatagram::try_clone`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.try_clone) * [`UnixDatagram::local_addr`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.local_addr) * [`UnixDatagram::peer_addr`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.peer_addr) * [`UnixDatagram::recv_from`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.recv_from) * [`UnixDatagram::recv`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.recv) * [`UnixDatagram::send_to`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.send_to) * [`UnixDatagram::send`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.send) * [`UnixDatagram::set_read_timeout`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.set_read_timeout) * [`UnixDatagram::set_write_timeout`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.set_write_timeout) * [`UnixDatagram::read_timeout`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.read_timeout) * [`UnixDatagram::write_timeout`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.write_timeout) * [`UnixDatagram::set_nonblocking`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.set_nonblocking) * [`UnixDatagram::take_error`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.take_error) * [`UnixDatagram::shutdown`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.shutdown) * RawFd impls for `UnixDatagram` * `{BTree,Hash}Map::values_mut` * [`<[_]>::binary_search_by_key`](http://doc.rust-lang.org/std/primitive.slice.html#method.binary_search_by_key) Libraries --------- * [The `abs_sub` method of floats is deprecated](https://github.com/rust-lang/rust/pull/33664). The semantics of this minor method are subtle and probably not what most people want. * [Add implementation of Ord for Cell<T> and RefCell<T> where T: Ord](https://github.com/rust-lang/rust/pull/33306). * [On Linux, if `HashMap`s can't be initialized with `getrandom` they will fall back to `/dev/urandom` temporarily to avoid blocking during early boot](https://github.com/rust-lang/rust/pull/33086). * [Implemented negation for wrapping numerals](https://github.com/rust-lang/rust/pull/33067). * [Implement `Clone` for `binary_heap::IntoIter`](https://github.com/rust-lang/rust/pull/33050). * [Implement `Display` and `Hash` for `std::num::Wrapping`](https://github.com/rust-lang/rust/pull/33023). * [Add `Default` implementation for `&CStr`, `CString`](https://github.com/rust-lang/rust/pull/32990). * [Implement `From<Vec<T>>` and `Into<Vec<T>>` for `VecDeque<T>`](https://github.com/rust-lang/rust/pull/32866). * [Implement `Default` for `UnsafeCell`, `fmt::Error`, `Condvar`, `Mutex`, `RwLock`](https://github.com/rust-lang/rust/pull/32785). Cargo ----- * [Cargo.toml supports the `profile.*.panic` option](https://github.com/rust-lang/cargo/pull/2687). This controls the runtime behavior of the `panic!` macro and can be either "unwind" (the default), or "abort". [RFC 1513](https://github.com/rust-lang/rfcs/blob/master/text/1513-less-unwinding.md). * [Don't throw away errors with `-p` arguments](https://github.com/rust-lang/cargo/pull/2723). * [Report status to stderr instead of stdout](https://github.com/rust-lang/cargo/pull/2693). * [Build scripts are passed a `CARGO_MANIFEST_LINKS` environment variable that corresponds to the `links` field of the manifest](https://github.com/rust-lang/cargo/pull/2710). * [Ban keywords from crate names](https://github.com/rust-lang/cargo/pull/2707). * [Canonicalize `CARGO_HOME` on Windows](https://github.com/rust-lang/cargo/pull/2604). * [Retry network requests](https://github.com/rust-lang/cargo/pull/2396). By default they are retried twice, which can be customized with the `net.retry` value in `.cargo/config`. * [Don't print extra error info for failing subcommands](https://github.com/rust-lang/cargo/pull/2674). * [Add `--force` flag to `cargo install`](https://github.com/rust-lang/cargo/pull/2405). * [Don't use `flock` on NFS mounts](https://github.com/rust-lang/cargo/pull/2623). * [Prefer building `cargo install` artifacts in temporary directories](https://github.com/rust-lang/cargo/pull/2610). Makes it possible to install multiple crates in parallel. * [Add `cargo test --doc`](https://github.com/rust-lang/cargo/pull/2578). * [Add `cargo --explain`](https://github.com/rust-lang/cargo/pull/2551). * [Don't print warnings when `-q` is passed](https://github.com/rust-lang/cargo/pull/2576). * [Add `cargo doc --lib` and `--bin`](https://github.com/rust-lang/cargo/pull/2577). * [Don't require build script output to be UTF-8](https://github.com/rust-lang/cargo/pull/2560). * [Correctly attempt multiple git usernames](https://github.com/rust-lang/cargo/pull/2584). Performance ----------- * [rustc memory usage was reduced by refactoring the context used for type checking](https://github.com/rust-lang/rust/pull/33425). * [Speed up creation of `HashMap`s by caching the random keys used to initialize the hash state](https://github.com/rust-lang/rust/pull/33318). * [The `find` implementation for `Chain` iterators is 2x faster](https://github.com/rust-lang/rust/pull/33289). * [Trait selection optimizations speed up type checking by 15%](https://github.com/rust-lang/rust/pull/33138). * [Efficient trie lookup for boolean Unicode properties](https://github.com/rust-lang/rust/pull/33098). 10x faster than the previous lookup tables. * [Special case `#[derive(Copy, Clone)]` to avoid bloat](https://github.com/rust-lang/rust/pull/31414). Usability --------- * Many incremental improvements to documentation and rustdoc. * [rustdoc: List blanket trait impls](https://github.com/rust-lang/rust/pull/33514). * [rustdoc: Clean up ABI rendering](https://github.com/rust-lang/rust/pull/33151). * [Indexing with the wrong type produces a more informative error](https://github.com/rust-lang/rust/pull/33401). * [Improve diagnostics for constants being used in irrefutable patterns](https://github.com/rust-lang/rust/pull/33406). * [When many method candidates are in scope limit the suggestions to 10](https://github.com/rust-lang/rust/pull/33338). * [Remove confusing suggestion when calling a `fn` type](https://github.com/rust-lang/rust/pull/33325). * [Do not suggest changing `&mut self` to `&mut mut self`](https://github.com/rust-lang/rust/pull/33319). Misc ---- * [Update i686-linux-android features to match Android ABI](https://github.com/rust-lang/rust/pull/33651). * [Update aarch64-linux-android features to match Android ABI](https://github.com/rust-lang/rust/pull/33500). * [`std` no longer prints backtraces on platforms where the running module must be loaded with `env::current_exe`, which can't be relied on](https://github.com/rust-lang/rust/pull/33554). * This release includes std binaries for the i586-unknown-linux-gnu, i686-unknown-linux-musl, and armv7-linux-androideabi targets. The i586 target is for old x86 hardware without SSE2, and the armv7 target is for Android running on modern ARM architectures. * [The `rust-gdb` and `rust-lldb` scripts are distributed on all Unix platforms](https://github.com/rust-lang/rust/pull/32835). * [On Unix the runtime aborts by calling `libc::abort` instead of generating an illegal instruction](https://github.com/rust-lang/rust/pull/31457). * [Rust is now bootstrapped from the previous release of Rust, instead of a snapshot from an arbitrary commit](https://github.com/rust-lang/rust/pull/32942). Compatibility Notes ------------------- * [`AtomicBool` is now bool-sized, not word-sized](https://github.com/rust-lang/rust/pull/33579). * [`target_env` for Linux ARM targets is just `gnu`, not `gnueabihf`, `gnueabi`, etc](https://github.com/rust-lang/rust/pull/33403). * [Consistently panic on overflow in `Duration::new`](https://github.com/rust-lang/rust/pull/33072). * [Change `String::truncate` to panic less](https://github.com/rust-lang/rust/pull/32977). * [Add `:block` to the follow set for `:ty` and `:path`](https://github.com/rust-lang/rust/pull/32945). Affects how macros are parsed. * [Fix macro hygiene bug](https://github.com/rust-lang/rust/pull/32923). * [Feature-gated attributes on macro-generated macro invocations are now rejected](https://github.com/rust-lang/rust/pull/32791). * [Suppress fallback and ambiguity errors during type inference](https://github.com/rust-lang/rust/pull/32258). This caused some minor changes to type inference. Version 1.9.0 (2016-05-26) ========================== Language -------- * The `#[deprecated]` attribute when applied to an API will generate warnings when used. The warnings may be suppressed with `#[allow(deprecated)]`. [RFC 1270]. * [`fn` item types are zero sized, and each `fn` names a unique type][1.9fn]. This will break code that transmutes `fn`s, so calling `transmute` on a `fn` type will generate a warning for a few cycles, then will be converted to an error. * [Field and method resolution understand visibility, so private fields and methods cannot prevent the proper use of public fields and methods][1.9fv]. * [The parser considers unicode codepoints in the `PATTERN_WHITE_SPACE` category to be whitespace][1.9ws]. Stabilized APIs --------------- * [`std::panic`] * [`std::panic::catch_unwind`] (renamed from `recover`) * [`std::panic::resume_unwind`] (renamed from `propagate`) * [`std::panic::AssertUnwindSafe`] (renamed from `AssertRecoverSafe`) * [`std::panic::UnwindSafe`] (renamed from `RecoverSafe`) * [`str::is_char_boundary`] * [`<*const T>::as_ref`] * [`<*mut T>::as_ref`] * [`<*mut T>::as_mut`] * [`AsciiExt::make_ascii_uppercase`] * [`AsciiExt::make_ascii_lowercase`] * [`char::decode_utf16`] * [`char::DecodeUtf16`] * [`char::DecodeUtf16Error`] * [`char::DecodeUtf16Error::unpaired_surrogate`] * [`BTreeSet::take`] * [`BTreeSet::replace`] * [`BTreeSet::get`] * [`HashSet::take`] * [`HashSet::replace`] * [`HashSet::get`] * [`OsString::with_capacity`] * [`OsString::clear`] * [`OsString::capacity`] * [`OsString::reserve`] * [`OsString::reserve_exact`] * [`OsStr::is_empty`] * [`OsStr::len`] * [`std::os::unix::thread`] * [`RawPthread`] * [`JoinHandleExt`] * [`JoinHandleExt::as_pthread_t`] * [`JoinHandleExt::into_pthread_t`] * [`HashSet::hasher`] * [`HashMap::hasher`] * [`CommandExt::exec`] * [`File::try_clone`] * [`SocketAddr::set_ip`] * [`SocketAddr::set_port`] * [`SocketAddrV4::set_ip`] * [`SocketAddrV4::set_port`] * [`SocketAddrV6::set_ip`] * [`SocketAddrV6::set_port`] * [`SocketAddrV6::set_flowinfo`] * [`SocketAddrV6::set_scope_id`] * [`slice::copy_from_slice`] * [`ptr::read_volatile`] * [`ptr::write_volatile`] * [`OpenOptions::create_new`] * [`TcpStream::set_nodelay`] * [`TcpStream::nodelay`] * [`TcpStream::set_ttl`] * [`TcpStream::ttl`] * [`TcpStream::set_only_v6`] * [`TcpStream::only_v6`] * [`TcpStream::take_error`] * [`TcpStream::set_nonblocking`] * [`TcpListener::set_ttl`] * [`TcpListener::ttl`] * [`TcpListener::set_only_v6`] * [`TcpListener::only_v6`] * [`TcpListener::take_error`] * [`TcpListener::set_nonblocking`] * [`UdpSocket::set_broadcast`] * [`UdpSocket::broadcast`] * [`UdpSocket::set_multicast_loop_v4`] * [`UdpSocket::multicast_loop_v4`] * [`UdpSocket::set_multicast_ttl_v4`] * [`UdpSocket::multicast_ttl_v4`] * [`UdpSocket::set_multicast_loop_v6`] * [`UdpSocket::multicast_loop_v6`] * [`UdpSocket::set_multicast_ttl_v6`] * [`UdpSocket::multicast_ttl_v6`] * [`UdpSocket::set_ttl`] * [`UdpSocket::ttl`] * [`UdpSocket::set_only_v6`] * [`UdpSocket::only_v6`] * [`UdpSocket::join_multicast_v4`] * [`UdpSocket::join_multicast_v6`] * [`UdpSocket::leave_multicast_v4`] * [`UdpSocket::leave_multicast_v6`] * [`UdpSocket::take_error`] * [`UdpSocket::connect`] * [`UdpSocket::send`] * [`UdpSocket::recv`] * [`UdpSocket::set_nonblocking`] Libraries --------- * [`std::sync::Once` is poisoned if its initialization function fails][1.9o]. * [`cell::Ref` and `cell::RefMut` can contain unsized types][1.9cu]. * [Most types implement `fmt::Debug`][1.9db]. * [The default buffer size used by `BufReader` and `BufWriter` was reduced to 8K, from 64K][1.9bf]. This is in line with the buffer size used by other languages. * [`Instant`, `SystemTime` and `Duration` implement `+=` and `-=`. `Duration` additionally implements `*=` and `/=`][1.9ta]. * [`Skip` is a `DoubleEndedIterator`][1.9sk]. * [`From<[u8; 4]>` is implemented for `Ipv4Addr`][1.9fi]. * [`Chain` implements `BufRead`][1.9ch]. * [`HashMap`, `HashSet` and iterators are covariant][1.9hc]. Cargo ----- * [Cargo can now run concurrently][1.9cc]. * [Top-level overrides allow specific revisions of crates to be overridden through the entire crate graph][1.9ct]. This is intended to make upgrades easier for large projects, by allowing crates to be forked temporarily until they've been upgraded and republished. * [Cargo exports a `CARGO_PKG_AUTHORS` environment variable][1.9cp]. * [Cargo will pass the contents of the `RUSTFLAGS` variable to `rustc` on the commandline][1.9cf]. `rustc` arguments can also be specified in the `build.rustflags` configuration key. Performance ----------- * [The time complexity of comparing variables for equivalence during type unification is reduced from _O_(_n_!) to _O_(_n_)][1.9tu]. This leads to major compilation time improvement in some scenarios. * [`ToString` is specialized for `str`, giving it the same performance as `to_owned`][1.9ts]. * [Spawning processes with `Command::output` no longer creates extra threads][1.9sp]. * [`#[derive(PartialEq)]` and `#[derive(PartialOrd)]` emit less code for C-like enums][1.9cl]. Misc ---- * [Passing the `--quiet` flag to a test runner will produce much-abbreviated output][1.9q]. * The Rust Project now publishes std binaries for the `mips-unknown-linux-musl`, `mipsel-unknown-linux-musl`, and `i586-pc-windows-msvc` targets. Compatibility Notes ------------------- * [`std::sync::Once` is poisoned if its initialization function fails][1.9o]. * [It is illegal to define methods with the same name in overlapping inherent `impl` blocks][1.9sn]. * [`fn` item types are zero sized, and each `fn` names a unique type][1.9fn]. This will break code that transmutes `fn`s, so calling `transmute` on a `fn` type will generate a warning for a few cycles, then will be converted to an error. * [Improvements to const evaluation may trigger new errors when integer literals are out of range][1.9ce]. [1.9bf]: https://github.com/rust-lang/rust/pull/32695 [1.9cc]: https://github.com/rust-lang/cargo/pull/2486 [1.9ce]: https://github.com/rust-lang/rust/pull/30587 [1.9cf]: https://github.com/rust-lang/cargo/pull/2241 [1.9ch]: https://github.com/rust-lang/rust/pull/32541 [1.9cl]: https://github.com/rust-lang/rust/pull/31977 [1.9cp]: https://github.com/rust-lang/cargo/pull/2465 [1.9ct]: https://github.com/rust-lang/cargo/pull/2385 [1.9cu]: https://github.com/rust-lang/rust/pull/32652 [1.9db]: https://github.com/rust-lang/rust/pull/32054 [1.9fi]: https://github.com/rust-lang/rust/pull/32050 [1.9fn]: https://github.com/rust-lang/rust/pull/31710 [1.9fv]: https://github.com/rust-lang/rust/pull/31938 [1.9hc]: https://github.com/rust-lang/rust/pull/32635 [1.9o]: https://github.com/rust-lang/rust/pull/32325 [1.9q]: https://github.com/rust-lang/rust/pull/31887 [1.9sk]: https://github.com/rust-lang/rust/pull/31700 [1.9sn]: https://github.com/rust-lang/rust/pull/31925 [1.9sp]: https://github.com/rust-lang/rust/pull/31618 [1.9ta]: https://github.com/rust-lang/rust/pull/32448 [1.9ts]: https://github.com/rust-lang/rust/pull/32586 [1.9tu]: https://github.com/rust-lang/rust/pull/32062 [1.9ws]: https://github.com/rust-lang/rust/pull/29734 [RFC 1270]: https://github.com/rust-lang/rfcs/blob/master/text/1270-deprecation.md [`<*const T>::as_ref`]: http://doc.rust-lang.org/nightly/std/primitive.pointer.html#method.as_ref [`<*mut T>::as_mut`]: http://doc.rust-lang.org/nightly/std/primitive.pointer.html#method.as_mut [`<*mut T>::as_ref`]: http://doc.rust-lang.org/nightly/std/primitive.pointer.html#method.as_ref [`slice::copy_from_slice`]: http://doc.rust-lang.org/nightly/std/primitive.slice.html#method.copy_from_slice [`AsciiExt::make_ascii_lowercase`]: http://doc.rust-lang.org/nightly/std/ascii/trait.AsciiExt.html#tymethod.make_ascii_lowercase [`AsciiExt::make_ascii_uppercase`]: http://doc.rust-lang.org/nightly/std/ascii/trait.AsciiExt.html#tymethod.make_ascii_uppercase [`BTreeSet::get`]: http://doc.rust-lang.org/nightly/collections/btree/set/struct.BTreeSet.html#method.get [`BTreeSet::replace`]: http://doc.rust-lang.org/nightly/collections/btree/set/struct.BTreeSet.html#method.replace [`BTreeSet::take`]: http://doc.rust-lang.org/nightly/collections/btree/set/struct.BTreeSet.html#method.take [`CommandExt::exec`]: http://doc.rust-lang.org/nightly/std/os/unix/process/trait.CommandExt.html#tymethod.exec [`File::try_clone`]: http://doc.rust-lang.org/nightly/std/fs/struct.File.html#method.try_clone [`HashMap::hasher`]: http://doc.rust-lang.org/nightly/std/collections/struct.HashMap.html#method.hasher [`HashSet::get`]: http://doc.rust-lang.org/nightly/std/collections/struct.HashSet.html#method.get [`HashSet::hasher`]: http://doc.rust-lang.org/nightly/std/collections/struct.HashSet.html#method.hasher [`HashSet::replace`]: http://doc.rust-lang.org/nightly/std/collections/struct.HashSet.html#method.replace [`HashSet::take`]: http://doc.rust-lang.org/nightly/std/collections/struct.HashSet.html#method.take [`JoinHandleExt::as_pthread_t`]: http://doc.rust-lang.org/nightly/std/os/unix/thread/trait.JoinHandleExt.html#tymethod.as_pthread_t [`JoinHandleExt::into_pthread_t`]: http://doc.rust-lang.org/nightly/std/os/unix/thread/trait.JoinHandleExt.html#tymethod.into_pthread_t [`JoinHandleExt`]: http://doc.rust-lang.org/nightly/std/os/unix/thread/trait.JoinHandleExt.html [`OpenOptions::create_new`]: http://doc.rust-lang.org/nightly/std/fs/struct.OpenOptions.html#method.create_new [`OsStr::is_empty`]: http://doc.rust-lang.org/nightly/std/ffi/struct.OsStr.html#method.is_empty [`OsStr::len`]: http://doc.rust-lang.org/nightly/std/ffi/struct.OsStr.html#method.len [`OsString::capacity`]: http://doc.rust-lang.org/nightly/std/ffi/struct.OsString.html#method.capacity [`OsString::clear`]: http://doc.rust-lang.org/nightly/std/ffi/struct.OsString.html#method.clear [`OsString::reserve_exact`]: http://doc.rust-lang.org/nightly/std/ffi/struct.OsString.html#method.reserve_exact [`OsString::reserve`]: http://doc.rust-lang.org/nightly/std/ffi/struct.OsString.html#method.reserve [`OsString::with_capacity`]: http://doc.rust-lang.org/nightly/std/ffi/struct.OsString.html#method.with_capacity [`RawPthread`]: http://doc.rust-lang.org/nightly/std/os/unix/thread/type.RawPthread.html [`SocketAddr::set_ip`]: http://doc.rust-lang.org/nightly/std/net/enum.SocketAddr.html#method.set_ip [`SocketAddr::set_port`]: http://doc.rust-lang.org/nightly/std/net/enum.SocketAddr.html#method.set_port [`SocketAddrV4::set_ip`]: http://doc.rust-lang.org/nightly/std/net/struct.SocketAddrV4.html#method.set_ip [`SocketAddrV4::set_port`]: http://doc.rust-lang.org/nightly/std/net/struct.SocketAddrV4.html#method.set_port [`SocketAddrV6::set_flowinfo`]: http://doc.rust-lang.org/nightly/std/net/struct.SocketAddrV6.html#method.set_flowinfo [`SocketAddrV6::set_ip`]: http://doc.rust-lang.org/nightly/std/net/struct.SocketAddrV6.html#method.set_ip [`SocketAddrV6::set_port`]: http://doc.rust-lang.org/nightly/std/net/struct.SocketAddrV6.html#method.set_port [`SocketAddrV6::set_scope_id`]: http://doc.rust-lang.org/nightly/std/net/struct.SocketAddrV6.html#method.set_scope_id [`TcpListener::only_v6`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.only_v6 [`TcpListener::set_nonblocking`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_nonblocking [`TcpListener::set_only_v6`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_only_v6 [`TcpListener::set_ttl`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_ttl [`TcpListener::take_error`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.take_error [`TcpListener::ttl`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.ttl [`TcpStream::nodelay`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.nodelay [`TcpStream::only_v6`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.only_v6 [`TcpStream::set_nodelay`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_nodelay [`TcpStream::set_nonblocking`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_nonblocking [`TcpStream::set_only_v6`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_only_v6 [`TcpStream::set_ttl`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_ttl [`TcpStream::take_error`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.take_error [`TcpStream::ttl`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.ttl [`UdpSocket::broadcast`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.broadcast [`UdpSocket::connect`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.connect [`UdpSocket::join_multicast_v4`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.join_multicast_v4 [`UdpSocket::join_multicast_v6`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.join_multicast_v6 [`UdpSocket::leave_multicast_v4`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.leave_multicast_v4 [`UdpSocket::leave_multicast_v6`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.leave_multicast_v6 [`UdpSocket::multicast_loop_v4`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.multicast_loop_v4 [`UdpSocket::multicast_loop_v6`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.multicast_loop_v6 [`UdpSocket::multicast_ttl_v4`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.multicast_ttl_v4 [`UdpSocket::multicast_ttl_v6`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.multicast_ttl_v6 [`UdpSocket::only_v6`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.only_v6 [`UdpSocket::recv`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.recv [`UdpSocket::send`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.send [`UdpSocket::set_broadcast`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.set_broadcast [`UdpSocket::set_multicast_loop_v4`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.set_multicast_loop_v4 [`UdpSocket::set_multicast_loop_v6`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.set_multicast_loop_v6 [`UdpSocket::set_multicast_ttl_v4`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.set_multicast_ttl_v4 [`UdpSocket::set_multicast_ttl_v6`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.set_multicast_ttl_v6 [`UdpSocket::set_nonblocking`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.set_nonblocking [`UdpSocket::set_only_v6`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.set_only_v6 [`UdpSocket::set_ttl`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.set_ttl [`UdpSocket::take_error`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.take_error [`UdpSocket::ttl`]: http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.ttl [`char::DecodeUtf16Error::unpaired_surrogate`]: http://doc.rust-lang.org/nightly/std/char/struct.DecodeUtf16Error.html#method.unpaired_surrogate [`char::DecodeUtf16Error`]: http://doc.rust-lang.org/nightly/std/char/struct.DecodeUtf16Error.html [`char::DecodeUtf16`]: http://doc.rust-lang.org/nightly/std/char/struct.DecodeUtf16.html [`char::decode_utf16`]: http://doc.rust-lang.org/nightly/std/char/fn.decode_utf16.html [`ptr::read_volatile`]: http://doc.rust-lang.org/nightly/std/ptr/fn.read_volatile.html [`ptr::write_volatile`]: http://doc.rust-lang.org/nightly/std/ptr/fn.write_volatile.html [`std::os::unix::thread`]: http://doc.rust-lang.org/nightly/std/os/unix/thread/index.html [`std::panic::AssertUnwindSafe`]: http://doc.rust-lang.org/nightly/std/panic/struct.AssertUnwindSafe.html [`std::panic::UnwindSafe`]: http://doc.rust-lang.org/nightly/std/panic/trait.UnwindSafe.html [`std::panic::catch_unwind`]: http://doc.rust-lang.org/nightly/std/panic/fn.catch_unwind.html [`std::panic::resume_unwind`]: http://doc.rust-lang.org/nightly/std/panic/fn.resume_unwind.html [`std::panic`]: http://doc.rust-lang.org/nightly/std/panic/index.html [`str::is_char_boundary`]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.is_char_boundary Version 1.8.0 (2016-04-14) ========================== Language -------- * Rust supports overloading of compound assignment statements like `+=` by implementing the [`AddAssign`], [`SubAssign`], [`MulAssign`], [`DivAssign`], [`RemAssign`], [`BitAndAssign`], [`BitOrAssign`], [`BitXorAssign`], [`ShlAssign`], or [`ShrAssign`] traits. [RFC 953]. * Empty structs can be defined with braces, as in `struct Foo { }`, in addition to the non-braced form, `struct Foo;`. [RFC 218]. Libraries --------- * Stabilized APIs: * [`str::encode_utf16`] (renamed from `utf16_units`) * [`str::EncodeUtf16`] (renamed from `Utf16Units`) * [`Ref::map`] * [`RefMut::map`] * [`ptr::drop_in_place`] * [`time::Instant`] * [`time::SystemTime`] * [`Instant::now`] * [`Instant::duration_since`] (renamed from `duration_from_earlier`) * [`Instant::elapsed`] * [`SystemTime::now`] * [`SystemTime::duration_since`] (renamed from `duration_from_earlier`) * [`SystemTime::elapsed`] * Various `Add`/`Sub` impls for `Time` and `SystemTime` * [`SystemTimeError`] * [`SystemTimeError::duration`] * Various impls for `SystemTimeError` * [`UNIX_EPOCH`] * [`AddAssign`], [`SubAssign`], [`MulAssign`], [`DivAssign`], [`RemAssign`], [`BitAndAssign`], [`BitOrAssign`], [`BitXorAssign`], [`ShlAssign`], [`ShrAssign`]. * [The `write!` and `writeln!` macros correctly emit errors if any of their arguments can't be formatted][1.8w]. * [Various I/O functions support large files on 32-bit Linux][1.8l]. * [The Unix-specific `raw` modules, which contain a number of redefined C types are deprecated][1.8r], including `os::raw::unix`, `os::raw::macos`, and `os::raw::linux`. These modules defined types such as `ino_t` and `dev_t`. The inconsistency of these definitions across platforms was making it difficult to implement `std` correctly. Those that need these definitions should use the `libc` crate. [RFC 1415]. * The Unix-specific `MetadataExt` traits, including `os::unix::fs::MetadataExt`, which expose values such as inode numbers [no longer return platform-specific types][1.8r], but instead return widened integers. [RFC 1415]. * [`btree_set::{IntoIter, Iter, Range}` are covariant][1.8cv]. * [Atomic loads and stores are not volatile][1.8a]. * [All types in `sync::mpsc` implement `fmt::Debug`][1.8mp]. Performance ----------- * [Inlining hash functions lead to a 3% compile-time improvement in some workloads][1.8h]. * When using jemalloc, its symbols are [unprefixed so that it overrides the libc malloc implementation][1.8h]. This means that for rustc, LLVM is now using jemalloc, which results in a 6% compile-time improvement on a specific workload. * [Avoid quadratic growth in function size due to cleanups][1.8cu]. Misc ---- * [32-bit MSVC builds finally implement unwinding][1.8ms]. i686-pc-windows-msvc is now considered a tier-1 platform. * [The `--print targets` flag prints a list of supported targets][1.8t]. * [The `--print cfg` flag prints the `cfg`s defined for the current target][1.8cf]. * [`rustc` can be built with an new Cargo-based build system, written in Rust][1.8b]. It will eventually replace Rust's Makefile-based build system. To enable it configure with `configure --rustbuild`. * [Errors for non-exhaustive `match` patterns now list up to 3 missing variants while also indicating the total number of missing variants if more than 3][1.8m]. * [Executable stacks are disabled on Linux and BSD][1.8nx]. * The Rust Project now publishes binary releases of the standard library for a number of tier-2 targets: `armv7-unknown-linux-gnueabihf`, `powerpc-unknown-linux-gnu`, `powerpc64-unknown-linux-gnu`, `powerpc64le-unknown-linux-gnu` `x86_64-rumprun-netbsd`. These can be installed with tools such as [multirust][1.8mr]. Cargo ----- * [`cargo init` creates a new Cargo project in the current directory][1.8ci]. It is otherwise like `cargo new`. * [Cargo has configuration keys for `-v` and `--color`][1.8cc]. `verbose` and `color`, respectively, go in the `[term]` section of `.cargo/config`. * [Configuration keys that evaluate to strings or integers can be set via environment variables][1.8ce]. For example the `build.jobs` key can be set via `CARGO_BUILD_JOBS`. Environment variables take precedence over config files. * [Target-specific dependencies support Rust `cfg` syntax for describing targets][1.8cfg] so that dependencies for multiple targets can be specified together. [RFC 1361]. * [The environment variables `CARGO_TARGET_ROOT`, `RUSTC`, and `RUSTDOC` take precedence over the `build.target-dir`, `build.rustc`, and `build.rustdoc` configuration values][1.8cfv]. * [The child process tree is killed on Windows when Cargo is killed][1.8ck]. * [The `build.target` configuration value sets the target platform, like `--target`][1.8ct]. Compatibility Notes ------------------- * [Unstable compiler flags have been further restricted][1.8u]. Since 1.0 `-Z` flags have been considered unstable, and other flags that were considered unstable additionally required passing `-Z unstable-options` to access. Unlike unstable language and library features though, these options have been accessible on the stable release channel. Going forward, *new unstable flags will not be available on the stable release channel*, and old unstable flags will warn about their usage. In the future, all unstable flags will be unavailable on the stable release channel. * [It is no longer possible to `match` on empty enum variants using the `Variant(..)` syntax][1.8v]. This has been a warning since 1.6. * The Unix-specific `MetadataExt` traits, including `os::unix::fs::MetadataExt`, which expose values such as inode numbers [no longer return platform-specific types][1.8r], but instead return widened integers. [RFC 1415]. * [Modules sourced from the filesystem cannot appear within arbitrary blocks, but only within other modules][1.8mf]. * [`--cfg` compiler flags are parsed strictly as identifiers][1.8c]. * On Unix, [stack overflow triggers a runtime abort instead of a SIGSEGV][1.8so]. * [`Command::spawn` and its equivalents return an error if any of its command-line arguments contain interior `NUL`s][1.8n]. * [Tuple and unit enum variants from other crates are in the type namespace][1.8tn]. * [On Windows `rustc` emits `.lib` files for the `staticlib` library type instead of `.a` files][1.8st]. Additionally, for the MSVC toolchain, `rustc` emits import libraries named `foo.dll.lib` instead of `foo.lib`. [1.8a]: https://github.com/rust-lang/rust/pull/30962 [1.8b]: https://github.com/rust-lang/rust/pull/31123 [1.8c]: https://github.com/rust-lang/rust/pull/31530 [1.8cc]: https://github.com/rust-lang/cargo/pull/2397 [1.8ce]: https://github.com/rust-lang/cargo/pull/2398 [1.8cf]: https://github.com/rust-lang/rust/pull/31278 [1.8cfg]: https://github.com/rust-lang/cargo/pull/2328 [1.8ci]: https://github.com/rust-lang/cargo/pull/2081 [1.8ck]: https://github.com/rust-lang/cargo/pull/2370 [1.8ct]: https://github.com/rust-lang/cargo/pull/2335 [1.8cu]: https://github.com/rust-lang/rust/pull/31390 [1.8cfv]: https://github.com/rust-lang/cargo/issues/2365 [1.8cv]: https://github.com/rust-lang/rust/pull/30998 [1.8h]: https://github.com/rust-lang/rust/pull/31460 [1.8l]: https://github.com/rust-lang/rust/pull/31668 [1.8m]: https://github.com/rust-lang/rust/pull/31020 [1.8mf]: https://github.com/rust-lang/rust/pull/31534 [1.8mp]: https://github.com/rust-lang/rust/pull/30894 [1.8mr]: https://users.rust-lang.org/t/multirust-0-8-with-cross-std-installation/4901 [1.8ms]: https://github.com/rust-lang/rust/pull/30448 [1.8n]: https://github.com/rust-lang/rust/pull/31056 [1.8nx]: https://github.com/rust-lang/rust/pull/30859 [1.8r]: https://github.com/rust-lang/rust/pull/31551 [1.8so]: https://github.com/rust-lang/rust/pull/31333 [1.8st]: https://github.com/rust-lang/rust/pull/29520 [1.8t]: https://github.com/rust-lang/rust/pull/31358 [1.8tn]: https://github.com/rust-lang/rust/pull/30882 [1.8u]: https://github.com/rust-lang/rust/pull/31793 [1.8v]: https://github.com/rust-lang/rust/pull/31757 [1.8w]: https://github.com/rust-lang/rust/pull/31904 [RFC 1361]: https://github.com/rust-lang/rfcs/blob/master/text/1361-cargo-cfg-dependencies.md [RFC 1415]: https://github.com/rust-lang/rfcs/blob/master/text/1415-trim-std-os.md [RFC 218]: https://github.com/rust-lang/rfcs/blob/master/text/0218-empty-struct-with-braces.md [RFC 953]: https://github.com/rust-lang/rfcs/blob/master/text/0953-op-assign.md [`AddAssign`]: http://doc.rust-lang.org/nightly/std/ops/trait.AddAssign.html [`BitAndAssign`]: http://doc.rust-lang.org/nightly/std/ops/trait.BitAndAssign.html [`BitOrAssign`]: http://doc.rust-lang.org/nightly/std/ops/trait.BitOrAssign.html [`BitXorAssign`]: http://doc.rust-lang.org/nightly/std/ops/trait.BitXorAssign.html [`DivAssign`]: http://doc.rust-lang.org/nightly/std/ops/trait.DivAssign.html [`Instant::duration_since`]: http://doc.rust-lang.org/nightly/std/time/struct.Instant.html#method.duration_since [`Instant::elapsed`]: http://doc.rust-lang.org/nightly/std/time/struct.Instant.html#method.elapsed [`Instant::now`]: http://doc.rust-lang.org/nightly/std/time/struct.Instant.html#method.now [`MulAssign`]: http://doc.rust-lang.org/nightly/std/ops/trait.MulAssign.html [`Ref::map`]: http://doc.rust-lang.org/nightly/std/cell/struct.Ref.html#method.map [`RefMut::map`]: http://doc.rust-lang.org/nightly/std/cell/struct.RefMut.html#method.map [`RemAssign`]: http://doc.rust-lang.org/nightly/std/ops/trait.RemAssign.html [`ShlAssign`]: http://doc.rust-lang.org/nightly/std/ops/trait.ShlAssign.html [`ShrAssign`]: http://doc.rust-lang.org/nightly/std/ops/trait.ShrAssign.html [`SubAssign`]: http://doc.rust-lang.org/nightly/std/ops/trait.SubAssign.html [`SystemTime::duration_since`]: http://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#method.duration_since [`SystemTime::elapsed`]: http://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#method.elapsed [`SystemTime::now`]: http://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#method.now [`SystemTimeError::duration`]: http://doc.rust-lang.org/nightly/std/time/struct.SystemTimeError.html#method.duration [`SystemTimeError`]: http://doc.rust-lang.org/nightly/std/time/struct.SystemTimeError.html [`UNIX_EPOCH`]: http://doc.rust-lang.org/nightly/std/time/constant.UNIX_EPOCH.html [`ptr::drop_in_place`]: http://doc.rust-lang.org/nightly/std/ptr/fn.drop_in_place.html [`str::EncodeUtf16`]: http://doc.rust-lang.org/nightly/std/str/struct.EncodeUtf16.html [`str::encode_utf16`]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.encode_utf16 [`time::Instant`]: http://doc.rust-lang.org/nightly/std/time/struct.Instant.html [`time::SystemTime`]: http://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html Version 1.7.0 (2016-03-03) ========================== Libraries --------- * Stabilized APIs * `Path` * [`Path::strip_prefix`] (renamed from relative_from) * [`path::StripPrefixError`] (new error type returned from strip_prefix) * `Ipv4Addr` * [`Ipv4Addr::is_loopback`] * [`Ipv4Addr::is_private`] * [`Ipv4Addr::is_link_local`] * [`Ipv4Addr::is_multicast`] * [`Ipv4Addr::is_broadcast`] * [`Ipv4Addr::is_documentation`] * `Ipv6Addr` * [`Ipv6Addr::is_unspecified`] * [`Ipv6Addr::is_loopback`] * [`Ipv6Addr::is_multicast`] * `Vec` * [`Vec::as_slice`] * [`Vec::as_mut_slice`] * `String` * [`String::as_str`] * [`String::as_mut_str`] * Slices * `<[T]>::`[`clone_from_slice`], which now requires the two slices to be the same length * `<[T]>::`[`sort_by_key`] * checked, saturated, and overflowing operations * [`i32::checked_rem`], [`i32::checked_neg`], [`i32::checked_shl`], [`i32::checked_shr`] * [`i32::saturating_mul`] * [`i32::overflowing_add`], [`i32::overflowing_sub`], [`i32::overflowing_mul`], [`i32::overflowing_div`] * [`i32::overflowing_rem`], [`i32::overflowing_neg`], [`i32::overflowing_shl`], [`i32::overflowing_shr`] * [`u32::checked_rem`], [`u32::checked_neg`], [`u32::checked_shl`], [`u32::checked_shl`] * [`u32::saturating_mul`] * [`u32::overflowing_add`], [`u32::overflowing_sub`], [`u32::overflowing_mul`], [`u32::overflowing_div`] * [`u32::overflowing_rem`], [`u32::overflowing_neg`], [`u32::overflowing_shl`], [`u32::overflowing_shr`] * and checked, saturated, and overflowing operations for other primitive types * FFI * [`ffi::IntoStringError`] * [`CString::into_string`] * [`CString::into_bytes`] * [`CString::into_bytes_with_nul`] * `From<CString> for Vec<u8>` * `IntoStringError` * [`IntoStringError::into_cstring`] * [`IntoStringError::utf8_error`] * `Error for IntoStringError` * Hashing * [`std::hash::BuildHasher`] * [`BuildHasher::Hasher`] * [`BuildHasher::build_hasher`] * [`std::hash::BuildHasherDefault`] * [`HashMap::with_hasher`] * [`HashMap::with_capacity_and_hasher`] * [`HashSet::with_hasher`] * [`HashSet::with_capacity_and_hasher`] * [`std::collections::hash_map::RandomState`] * [`RandomState::new`] * [Validating UTF-8 is faster by a factor of between 7 and 14x for ASCII input][1.7utf8]. This means that creating `String`s and `str`s from bytes is faster. * [The performance of `LineWriter` (and thus `io::stdout`) was improved by using `memchr` to search for newlines][1.7m]. * [`f32::to_degrees` and `f32::to_radians` are stable][1.7f]. The `f64` variants were stabilized previously. * [`BTreeMap` was rewritten to use less memory and improve the performance of insertion and iteration, the latter by as much as 5x][1.7bm]. * [`BTreeSet` and its iterators, `Iter`, `IntoIter`, and `Range` are covariant over their contained type][1.7bt]. * [`LinkedList` and its iterators, `Iter` and `IntoIter` are covariant over their contained type][1.7ll]. * [`str::replace` now accepts a `Pattern`][1.7rp], like other string searching methods. * [`Any` is implemented for unsized types][1.7a]. * [`Hash` is implemented for `Duration`][1.7h]. Misc ---- * [When running tests with `--test`, rustdoc will pass `--cfg` arguments to the compiler][1.7dt]. * [The compiler is built with RPATH information by default][1.7rpa]. This means that it will be possible to run `rustc` when installed in unusual configurations without configuring the dynamic linker search path explicitly. * [`rustc` passes `--enable-new-dtags` to GNU ld][1.7dta]. This makes any RPATH entries (emitted with `-C rpath`) *not* take precedence over `LD_LIBRARY_PATH`. Cargo ----- * [`cargo rustc` accepts a `--profile` flag that runs `rustc` under any of the compilation profiles, 'dev', 'bench', or 'test'][1.7cp]. * [The `rerun-if-changed` build script directive no longer causes the build script to incorrectly run twice in certain scenarios][1.7rr]. Compatibility Notes ------------------- * Soundness fixes to the interactions between associated types and lifetimes, specified in [RFC 1214], [now generate errors][1.7sf] for code that violates the new rules. This is a significant change that is known to break existing code, so it has emitted warnings for the new error cases since 1.4 to give crate authors time to adapt. The details of what is changing are subtle; read the RFC for more. * [Several bugs in the compiler's visibility calculations were fixed][1.7v]. Since this was found to break significant amounts of code, the new errors will be emitted as warnings for several release cycles, under the `private_in_public` lint. * Defaulted type parameters were accidentally accepted in positions that were not intended. In this release, [defaulted type parameters appearing outside of type definitions will generate a warning][1.7d], which will become an error in future releases. * [Parsing "." as a float results in an error instead of 0][1.7p]. That is, `".".parse::<f32>()` returns `Err`, not `Ok(0.0)`. * [Borrows of closure parameters may not outlive the closure][1.7bc]. [1.7a]: https://github.com/rust-lang/rust/pull/30928 [1.7bc]: https://github.com/rust-lang/rust/pull/30341 [1.7bm]: https://github.com/rust-lang/rust/pull/30426 [1.7bt]: https://github.com/rust-lang/rust/pull/30998 [1.7cp]: https://github.com/rust-lang/cargo/pull/2224 [1.7d]: https://github.com/rust-lang/rust/pull/30724 [1.7dt]: https://github.com/rust-lang/rust/pull/30372 [1.7dta]: https://github.com/rust-lang/rust/pull/30394 [1.7f]: https://github.com/rust-lang/rust/pull/30672 [1.7h]: https://github.com/rust-lang/rust/pull/30818 [1.7ll]: https://github.com/rust-lang/rust/pull/30663 [1.7m]: https://github.com/rust-lang/rust/pull/30381 [1.7p]: https://github.com/rust-lang/rust/pull/30681 [1.7rp]: https://github.com/rust-lang/rust/pull/29498 [1.7rpa]: https://github.com/rust-lang/rust/pull/30353 [1.7rr]: https://github.com/rust-lang/cargo/pull/2279 [1.7sf]: https://github.com/rust-lang/rust/pull/30389 [1.7utf8]: https://github.com/rust-lang/rust/pull/30740 [1.7v]: https://github.com/rust-lang/rust/pull/29973 [RFC 1214]: https://github.com/rust-lang/rfcs/blob/master/text/1214-projections-lifetimes-and-wf.md [`BuildHasher::Hasher`]: http://doc.rust-lang.org/nightly/std/hash/trait.Hasher.html [`BuildHasher::build_hasher`]: http://doc.rust-lang.org/nightly/std/hash/trait.BuildHasher.html#tymethod.build_hasher [`CString::into_bytes_with_nul`]: http://doc.rust-lang.org/nightly/std/ffi/struct.CString.html#method.into_bytes_with_nul [`CString::into_bytes`]: http://doc.rust-lang.org/nightly/std/ffi/struct.CString.html#method.into_bytes [`CString::into_string`]: http://doc.rust-lang.org/nightly/std/ffi/struct.CString.html#method.into_string [`HashMap::with_capacity_and_hasher`]: http://doc.rust-lang.org/nightly/std/collections/struct.HashMap.html#method.with_capacity_and_hasher [`HashMap::with_hasher`]: http://doc.rust-lang.org/nightly/std/collections/struct.HashMap.html#method.with_hasher [`HashSet::with_capacity_and_hasher`]: http://doc.rust-lang.org/nightly/std/collections/struct.HashSet.html#method.with_capacity_and_hasher [`HashSet::with_hasher`]: http://doc.rust-lang.org/nightly/std/collections/struct.HashSet.html#method.with_hasher [`IntoStringError::into_cstring`]: http://doc.rust-lang.org/nightly/std/ffi/struct.IntoStringError.html#method.into_cstring [`IntoStringError::utf8_error`]: http://doc.rust-lang.org/nightly/std/ffi/struct.IntoStringError.html#method.utf8_error [`Ipv4Addr::is_broadcast`]: http://doc.rust-lang.org/nightly/std/net/struct.Ipv4Addr.html#method.is_broadcast [`Ipv4Addr::is_documentation`]: http://doc.rust-lang.org/nightly/std/net/struct.Ipv4Addr.html#method.is_documentation [`Ipv4Addr::is_link_local`]: http://doc.rust-lang.org/nightly/std/net/struct.Ipv4Addr.html#method.is_link_local [`Ipv4Addr::is_loopback`]: http://doc.rust-lang.org/nightly/std/net/struct.Ipv4Addr.html#method.is_loopback [`Ipv4Addr::is_multicast`]: http://doc.rust-lang.org/nightly/std/net/struct.Ipv4Addr.html#method.is_multicast [`Ipv4Addr::is_private`]: http://doc.rust-lang.org/nightly/std/net/struct.Ipv4Addr.html#method.is_private [`Ipv6Addr::is_loopback`]: http://doc.rust-lang.org/nightly/std/net/struct.Ipv6Addr.html#method.is_loopback [`Ipv6Addr::is_multicast`]: http://doc.rust-lang.org/nightly/std/net/struct.Ipv6Addr.html#method.is_multicast [`Ipv6Addr::is_unspecified`]: http://doc.rust-lang.org/nightly/std/net/struct.Ipv6Addr.html#method.is_unspecified [`Path::strip_prefix`]: http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.strip_prefix [`RandomState::new`]: http://doc.rust-lang.org/nightly/std/collections/hash_map/struct.RandomState.html#method.new [`String::as_mut_str`]: http://doc.rust-lang.org/nightly/std/string/struct.String.html#method.as_mut_str [`String::as_str`]: http://doc.rust-lang.org/nightly/std/string/struct.String.html#method.as_str [`Vec::as_mut_slice`]: http://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#method.as_mut_slice [`Vec::as_slice`]: http://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#method.as_slice [`clone_from_slice`]: http://doc.rust-lang.org/nightly/std/primitive.slice.html#method.clone_from_slice [`ffi::IntoStringError`]: http://doc.rust-lang.org/nightly/std/ffi/struct.IntoStringError.html [`i32::checked_neg`]: http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.checked_neg [`i32::checked_rem`]: http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.checked_rem [`i32::checked_shl`]: http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.checked_shl [`i32::checked_shr`]: http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.checked_shr [`i32::overflowing_add`]: http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.overflowing_add [`i32::overflowing_div`]: http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.overflowing_div [`i32::overflowing_mul`]: http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.overflowing_mul [`i32::overflowing_neg`]: http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.overflowing_neg [`i32::overflowing_rem`]: http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.overflowing_rem [`i32::overflowing_shl`]: http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.overflowing_shl [`i32::overflowing_shr`]: http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.overflowing_shr [`i32::overflowing_sub`]: http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.overflowing_sub [`i32::saturating_mul`]: http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.saturating_mul [`path::StripPrefixError`]: http://doc.rust-lang.org/nightly/std/path/struct.StripPrefixError.html [`sort_by_key`]: http://doc.rust-lang.org/nightly/std/primitive.slice.html#method.sort_by_key [`std::collections::hash_map::RandomState`]: http://doc.rust-lang.org/nightly/std/collections/hash_map/struct.RandomState.html [`std::hash::BuildHasherDefault`]: http://doc.rust-lang.org/nightly/std/hash/struct.BuildHasherDefault.html [`std::hash::BuildHasher`]: http://doc.rust-lang.org/nightly/std/hash/trait.BuildHasher.html [`u32::checked_neg`]: http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.checked_neg [`u32::checked_rem`]: http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.checked_rem [`u32::checked_neg`]: http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.checked_neg [`u32::checked_shl`]: http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.checked_shl [`u32::overflowing_add`]: http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.overflowing_add [`u32::overflowing_div`]: http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.overflowing_div [`u32::overflowing_mul`]: http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.overflowing_mul [`u32::overflowing_neg`]: http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.overflowing_neg [`u32::overflowing_rem`]: http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.overflowing_rem [`u32::overflowing_shl`]: http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.overflowing_shl [`u32::overflowing_shr`]: http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.overflowing_shr [`u32::overflowing_sub`]: http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.overflowing_sub [`u32::saturating_mul`]: http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.saturating_mul Version 1.6.0 (2016-01-21) ========================== Language -------- * The `#![no_std]` attribute causes a crate to not be linked to the standard library, but only the [core library][1.6co], as described in [RFC 1184]. The core library defines common types and traits but has no platform dependencies whatsoever, and is the basis for Rust software in environments that cannot support a full port of the standard library, such as operating systems. Most of the core library is now stable. Libraries --------- * Stabilized APIs: [`Read::read_exact`], [`ErrorKind::UnexpectedEof`] (renamed from `UnexpectedEOF`), [`fs::DirBuilder`], [`fs::DirBuilder::new`], [`fs::DirBuilder::recursive`], [`fs::DirBuilder::create`], [`os::unix::fs::DirBuilderExt`], [`os::unix::fs::DirBuilderExt::mode`], [`vec::Drain`], [`vec::Vec::drain`], [`string::Drain`], [`string::String::drain`], [`vec_deque::Drain`], [`vec_deque::VecDeque::drain`], [`collections::hash_map::Drain`], [`collections::hash_map::HashMap::drain`], [`collections::hash_set::Drain`], [`collections::hash_set::HashSet::drain`], [`collections::binary_heap::Drain`], [`collections::binary_heap::BinaryHeap::drain`], [`Vec::extend_from_slice`] (renamed from `push_all`), [`Mutex::get_mut`], [`Mutex::into_inner`], [`RwLock::get_mut`], [`RwLock::into_inner`], [`Iterator::min_by_key`] (renamed from `min_by`), [`Iterator::max_by_key`] (renamed from `max_by`). * The [core library][1.6co] is stable, as are most of its APIs. * [The `assert_eq!` macro supports arguments that don't implement `Sized`][1.6ae], such as arrays. In this way it behaves more like `assert!`. * Several timer functions that take duration in milliseconds [are deprecated in favor of those that take `Duration`][1.6ms]. These include `Condvar::wait_timeout_ms`, `thread::sleep_ms`, and `thread::park_timeout_ms`. * The algorithm by which `Vec` reserves additional elements was [tweaked to not allocate excessive space][1.6a] while still growing exponentially. * `From` conversions are [implemented from integers to floats][1.6f] in cases where the conversion is lossless. Thus they are not implemented for 32-bit ints to `f32`, nor for 64-bit ints to `f32` or `f64`. They are also not implemented for `isize` and `usize` because the implementations would be platform-specific. `From` is also implemented from `f32` to `f64`. * `From<&Path>` and `From<PathBuf>` are implemented for `Cow<Path>`. * `From<T>` is implemented for `Box<T>`, `Rc<T>` and `Arc<T>`. * `IntoIterator` is implemented for `&PathBuf` and `&Path`. * [`BinaryHeap` was refactored][1.6bh] for modest performance improvements. * Sorting slices that are already sorted [is 50% faster in some cases][1.6s]. Cargo ----- * Cargo will look in `$CARGO_HOME/bin` for subcommands [by default][1.6c]. * Cargo build scripts can specify their dependencies by emitting the [`rerun-if-changed`][1.6rr] key. * crates.io will reject publication of crates with dependencies that have a wildcard version constraint. Crates with wildcard dependencies were seen to cause a variety of problems, as described in [RFC 1241]. Since 1.5 publication of such crates has emitted a warning. * `cargo clean` [accepts a `--release` flag][1.6cc] to clean the release folder. A variety of artifacts that Cargo failed to clean are now correctly deleted. Misc ---- * The `unreachable_code` lint [warns when a function call's argument diverges][1.6dv]. * The parser indicates [failures that may be caused by confusingly-similar Unicode characters][1.6uc] * Certain macro errors [are reported at definition time][1.6m], not expansion. Compatibility Notes ------------------- * The compiler no longer makes use of the [`RUST_PATH`][1.6rp] environment variable when locating crates. This was a pre-cargo feature for integrating with the package manager that was accidentally never removed. * [A number of bugs were fixed in the privacy checker][1.6p] that could cause previously-accepted code to break. * [Modules and unit/tuple structs may not share the same name][1.6ts]. * [Bugs in pattern matching unit structs were fixed][1.6us]. The tuple struct pattern syntax (`Foo(..)`) can no longer be used to match unit structs. This is a warning now, but will become an error in future releases. Patterns that share the same name as a const are now an error. * A bug was fixed that causes [rustc not to apply default type parameters][1.6xc] when resolving certain method implementations of traits defined in other crates. [1.6a]: https://github.com/rust-lang/rust/pull/29454 [1.6ae]: https://github.com/rust-lang/rust/pull/29770 [1.6bh]: https://github.com/rust-lang/rust/pull/29811 [1.6c]: https://github.com/rust-lang/cargo/pull/2192 [1.6cc]: https://github.com/rust-lang/cargo/pull/2131 [1.6co]: http://doc.rust-lang.org/core/index.html [1.6dv]: https://github.com/rust-lang/rust/pull/30000 [1.6f]: https://github.com/rust-lang/rust/pull/29129 [1.6m]: https://github.com/rust-lang/rust/pull/29828 [1.6ms]: https://github.com/rust-lang/rust/pull/29604 [1.6p]: https://github.com/rust-lang/rust/pull/29726 [1.6rp]: https://github.com/rust-lang/rust/pull/30034 [1.6rr]: https://github.com/rust-lang/cargo/pull/2134 [1.6s]: https://github.com/rust-lang/rust/pull/29675 [1.6ts]: https://github.com/rust-lang/rust/issues/21546 [1.6uc]: https://github.com/rust-lang/rust/pull/29837 [1.6us]: https://github.com/rust-lang/rust/pull/29383 [1.6xc]: https://github.com/rust-lang/rust/issues/30123 [RFC 1184]: https://github.com/rust-lang/rfcs/blob/master/text/1184-stabilize-no_std.md [RFC 1241]: https://github.com/rust-lang/rfcs/blob/master/text/1241-no-wildcard-deps.md [`ErrorKind::UnexpectedEof`]: http://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html#variant.UnexpectedEof [`Iterator::max_by_key`]: http://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#method.max_by_key [`Iterator::min_by_key`]: http://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#method.min_by_key [`Mutex::get_mut`]: http://doc.rust-lang.org/nightly/std/sync/struct.Mutex.html#method.get_mut [`Mutex::into_inner`]: http://doc.rust-lang.org/nightly/std/sync/struct.Mutex.html#method.into_inner [`Read::read_exact`]: http://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.read_exact [`RwLock::get_mut`]: http://doc.rust-lang.org/nightly/std/sync/struct.RwLock.html#method.get_mut [`RwLock::into_inner`]: http://doc.rust-lang.org/nightly/std/sync/struct.RwLock.html#method.into_inner [`Vec::extend_from_slice`]: http://doc.rust-lang.org/nightly/collections/vec/struct.Vec.html#method.extend_from_slice [`collections::binary_heap::BinaryHeap::drain`]: http://doc.rust-lang.org/nightly/std/collections/binary_heap/struct.BinaryHeap.html#method.drain [`collections::binary_heap::Drain`]: http://doc.rust-lang.org/nightly/std/collections/binary_heap/struct.Drain.html [`collections::hash_map::Drain`]: http://doc.rust-lang.org/nightly/std/collections/hash_map/struct.Drain.html [`collections::hash_map::HashMap::drain`]: http://doc.rust-lang.org/nightly/std/collections/hash_map/struct.HashMap.html#method.drain [`collections::hash_set::Drain`]: http://doc.rust-lang.org/nightly/std/collections/hash_set/struct.Drain.html [`collections::hash_set::HashSet::drain`]: http://doc.rust-lang.org/nightly/std/collections/hash_set/struct.HashSet.html#method.drain [`fs::DirBuilder::create`]: http://doc.rust-lang.org/nightly/std/fs/struct.DirBuilder.html#method.create [`fs::DirBuilder::new`]: http://doc.rust-lang.org/nightly/std/fs/struct.DirBuilder.html#method.new [`fs::DirBuilder::recursive`]: http://doc.rust-lang.org/nightly/std/fs/struct.DirBuilder.html#method.recursive [`fs::DirBuilder`]: http://doc.rust-lang.org/nightly/std/fs/struct.DirBuilder.html [`os::unix::fs::DirBuilderExt::mode`]: http://doc.rust-lang.org/nightly/std/os/unix/fs/trait.DirBuilderExt.html#tymethod.mode [`os::unix::fs::DirBuilderExt`]: http://doc.rust-lang.org/nightly/std/os/unix/fs/trait.DirBuilderExt.html [`string::Drain`]: http://doc.rust-lang.org/nightly/std/string/struct.Drain.html [`string::String::drain`]: http://doc.rust-lang.org/nightly/std/string/struct.String.html#method.drain [`vec::Drain`]: http://doc.rust-lang.org/nightly/std/vec/struct.Drain.html [`vec::Vec::drain`]: http://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#method.drain [`vec_deque::Drain`]: http://doc.rust-lang.org/nightly/std/collections/vec_deque/struct.Drain.html [`vec_deque::VecDeque::drain`]: http://doc.rust-lang.org/nightly/std/collections/vec_deque/struct.VecDeque.html#method.drain Version 1.5.0 (2015-12-10) ========================== * ~700 changes, numerous bugfixes Highlights ---------- * Stabilized APIs: [`BinaryHeap::from`], [`BinaryHeap::into_sorted_vec`], [`BinaryHeap::into_vec`], [`Condvar::wait_timeout`], [`FileTypeExt::is_block_device`], [`FileTypeExt::is_char_device`], [`FileTypeExt::is_fifo`], [`FileTypeExt::is_socket`], [`FileTypeExt`], [`Formatter::alternate`], [`Formatter::fill`], [`Formatter::precision`], [`Formatter::sign_aware_zero_pad`], [`Formatter::sign_minus`], [`Formatter::sign_plus`], [`Formatter::width`], [`Iterator::cmp`], [`Iterator::eq`], [`Iterator::ge`], [`Iterator::gt`], [`Iterator::le`], [`Iterator::lt`], [`Iterator::ne`], [`Iterator::partial_cmp`], [`Path::canonicalize`], [`Path::exists`], [`Path::is_dir`], [`Path::is_file`], [`Path::metadata`], [`Path::read_dir`], [`Path::read_link`], [`Path::symlink_metadata`], [`Utf8Error::valid_up_to`], [`Vec::resize`], [`VecDeque::as_mut_slices`], [`VecDeque::as_slices`], [`VecDeque::insert`], [`VecDeque::shrink_to_fit`], [`VecDeque::swap_remove_back`], [`VecDeque::swap_remove_front`], [`slice::split_first_mut`], [`slice::split_first`], [`slice::split_last_mut`], [`slice::split_last`], [`char::from_u32_unchecked`], [`fs::canonicalize`], [`str::MatchIndices`], [`str::RMatchIndices`], [`str::match_indices`], [`str::rmatch_indices`], [`str::slice_mut_unchecked`], [`string::ParseError`]. * Rust applications hosted on crates.io can be installed locally to `~/.cargo/bin` with the [`cargo install`] command. Among other things this makes it easier to augment Cargo with new subcommands: when a binary named e.g. `cargo-foo` is found in `$PATH` it can be invoked as `cargo foo`. * Crates with wildcard (`*`) dependencies will [emit warnings when published][1.5w]. In 1.6 it will no longer be possible to publish crates with wildcard dependencies. Breaking Changes ---------------- * The rules determining when a particular lifetime must outlive a particular value (known as '[dropck]') have been [modified to not rely on parametricity][1.5p]. * [Implementations of `AsRef` and `AsMut` were added to `Box`, `Rc`, and `Arc`][1.5a]. Because these smart pointer types implement `Deref`, this causes breakage in cases where the interior type contains methods of the same name. * [Correct a bug in Rc/Arc][1.5c] that caused [dropck] to be unaware that they could drop their content. Soundness fix. * All method invocations are [properly checked][1.5wf1] for [well-formedness][1.5wf2]. Soundness fix. * Traits whose supertraits contain `Self` are [not object safe][1.5o]. Soundness fix. * Target specifications support a [`no_default_libraries`][1.5nd] setting that controls whether `-nodefaultlibs` is passed to the linker, and in turn the `is_like_windows` setting no longer affects the `-nodefaultlibs` flag. * `#[derive(Show)]`, long-deprecated, [has been removed][1.5ds]. * The `#[inline]` and `#[repr]` attributes [can only appear in valid locations][1.5at]. * Native libraries linked from the local crate are [passed to the linker before native libraries from upstream crates][1.5nl]. * Two rarely-used attributes, `#[no_debug]` and `#[omit_gdb_pretty_printer_section]` [are feature gated][1.5fg]. * Negation of unsigned integers, which has been a warning for several releases, [is now behind a feature gate and will generate errors][1.5nu]. * The parser accidentally accepted visibility modifiers on enum variants, a bug [which has been fixed][1.5ev]. * [A bug was fixed that allowed `use` statements to import unstable features][1.5use]. Language -------- * When evaluating expressions at compile-time that are not compile-time constants (const-evaluating expressions in non-const contexts), incorrect code such as overlong bitshifts and arithmetic overflow will [generate a warning instead of an error][1.5ce], delaying the error until runtime. This will allow the const-evaluator to be expanded in the future backwards-compatibly. * The `improper_ctypes` lint [no longer warns about using `isize` and `usize` in FFI][1.5ict]. Libraries --------- * `Arc<T>` and `Rc<T>` are [covariant with respect to `T` instead of invariant][1.5c]. * `Default` is [implemented for mutable slices][1.5d]. * `FromStr` is [implemented for `SockAddrV4` and `SockAddrV6`][1.5s]. * There are now `From` conversions [between floating point types][1.5f] where the conversions are lossless. * There are now `From` conversions [between integer types][1.5i] where the conversions are lossless. * [`fs::Metadata` implements `Clone`][1.5fs]. * The `parse` method [accepts a leading "+" when parsing integers][1.5pi]. * [`AsMut` is implemented for `Vec`][1.5am]. * The `clone_from` implementations for `String` and `BinaryHeap` [have been optimized][1.5cf] and no longer rely on the default impl. * The `extern "Rust"`, `extern "C"`, `unsafe extern "Rust"` and `unsafe extern "C"` function types now [implement `Clone`, `PartialEq`, `Eq`, `PartialOrd`, `Ord`, `Hash`, `fmt::Pointer`, and `fmt::Debug` for up to 12 arguments][1.5fp]. * [Dropping `Vec`s is much faster in unoptimized builds when the element types don't implement `Drop`][1.5dv]. * A bug that caused in incorrect behavior when [combining `VecDeque` with zero-sized types][1.5vdz] was resolved. * [`PartialOrd` for slices is faster][1.5po]. Miscellaneous ------------- * [Crate metadata size was reduced by 20%][1.5md]. * [Improvements to code generation reduced the size of libcore by 3.3 MB and rustc's memory usage by 18MB][1.5m]. * [Improvements to deref translation increased performance in unoptimized builds][1.5dr]. * Various errors in trait resolution [are deduplicated to only be reported once][1.5te]. * Rust has preliminary [support for rumprun kernels][1.5rr]. * Rust has preliminary [support for NetBSD on amd64][1.5na]. [1.5use]: https://github.com/rust-lang/rust/pull/28364 [1.5po]: https://github.com/rust-lang/rust/pull/28436 [1.5ev]: https://github.com/rust-lang/rust/pull/28442 [1.5nu]: https://github.com/rust-lang/rust/pull/28468 [1.5dr]: https://github.com/rust-lang/rust/pull/28491 [1.5vdz]: https://github.com/rust-lang/rust/pull/28494 [1.5md]: https://github.com/rust-lang/rust/pull/28521 [1.5fg]: https://github.com/rust-lang/rust/pull/28522 [1.5dv]: https://github.com/rust-lang/rust/pull/28531 [1.5na]: https://github.com/rust-lang/rust/pull/28543 [1.5fp]: https://github.com/rust-lang/rust/pull/28560 [1.5rr]: https://github.com/rust-lang/rust/pull/28593 [1.5cf]: https://github.com/rust-lang/rust/pull/28602 [1.5nl]: https://github.com/rust-lang/rust/pull/28605 [1.5te]: https://github.com/rust-lang/rust/pull/28645 [1.5at]: https://github.com/rust-lang/rust/pull/28650 [1.5am]: https://github.com/rust-lang/rust/pull/28663 [1.5m]: https://github.com/rust-lang/rust/pull/28778 [1.5ict]: https://github.com/rust-lang/rust/pull/28779 [1.5a]: https://github.com/rust-lang/rust/pull/28811 [1.5pi]: https://github.com/rust-lang/rust/pull/28826 [1.5ce]: https://github.com/rust-lang/rfcs/blob/master/text/1229-compile-time-asserts.md [1.5p]: https://github.com/rust-lang/rfcs/blob/master/text/1238-nonparametric-dropck.md [1.5i]: https://github.com/rust-lang/rust/pull/28921 [1.5fs]: https://github.com/rust-lang/rust/pull/29021 [1.5f]: https://github.com/rust-lang/rust/pull/29129 [1.5ds]: https://github.com/rust-lang/rust/pull/29148 [1.5s]: https://github.com/rust-lang/rust/pull/29190 [1.5d]: https://github.com/rust-lang/rust/pull/29245 [1.5o]: https://github.com/rust-lang/rust/pull/29259 [1.5nd]: https://github.com/rust-lang/rust/pull/28578 [1.5wf2]: https://github.com/rust-lang/rfcs/blob/master/text/1214-projections-lifetimes-and-wf.md [1.5wf1]: https://github.com/rust-lang/rust/pull/28669 [dropck]: https://doc.rust-lang.org/nightly/nomicon/dropck.html [1.5c]: https://github.com/rust-lang/rust/pull/29110 [1.5w]: https://github.com/rust-lang/rfcs/blob/master/text/1241-no-wildcard-deps.md [`cargo install`]: https://github.com/rust-lang/rfcs/blob/master/text/1200-cargo-install.md [`BinaryHeap::from`]: http://doc.rust-lang.org/nightly/std/convert/trait.From.html#method.from [`BinaryHeap::into_sorted_vec`]: http://doc.rust-lang.org/nightly/std/collections/struct.BinaryHeap.html#method.into_sorted_vec [`BinaryHeap::into_vec`]: http://doc.rust-lang.org/nightly/std/collections/struct.BinaryHeap.html#method.into_vec [`Condvar::wait_timeout`]: http://doc.rust-lang.org/nightly/std/sync/struct.Condvar.html#method.wait_timeout [`FileTypeExt::is_block_device`]: http://doc.rust-lang.org/nightly/std/os/unix/fs/trait.FileTypeExt.html#tymethod.is_block_device [`FileTypeExt::is_char_device`]: http://doc.rust-lang.org/nightly/std/os/unix/fs/trait.FileTypeExt.html#tymethod.is_char_device [`FileTypeExt::is_fifo`]: http://doc.rust-lang.org/nightly/std/os/unix/fs/trait.FileTypeExt.html#tymethod.is_fifo [`FileTypeExt::is_socket`]: http://doc.rust-lang.org/nightly/std/os/unix/fs/trait.FileTypeExt.html#tymethod.is_socket [`FileTypeExt`]: http://doc.rust-lang.org/nightly/std/os/unix/fs/trait.FileTypeExt.html [`Formatter::alternate`]: http://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.alternate [`Formatter::fill`]: http://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.fill [`Formatter::precision`]: http://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.precision [`Formatter::sign_aware_zero_pad`]: http://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.sign_aware_zero_pad [`Formatter::sign_minus`]: http://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.sign_minus [`Formatter::sign_plus`]: http://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.sign_plus [`Formatter::width`]: http://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.width [`Iterator::cmp`]: http://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.cmp [`Iterator::eq`]: http://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.eq [`Iterator::ge`]: http://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.ge [`Iterator::gt`]: http://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.gt [`Iterator::le`]: http://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.le [`Iterator::lt`]: http://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.lt [`Iterator::ne`]: http://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.ne [`Iterator::partial_cmp`]: http://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.partial_cmp [`Path::canonicalize`]: http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.canonicalize [`Path::exists`]: http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.exists [`Path::is_dir`]: http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.is_dir [`Path::is_file`]: http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.is_file [`Path::metadata`]: http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.metadata [`Path::read_dir`]: http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.read_dir [`Path::read_link`]: http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.read_link [`Path::symlink_metadata`]: http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.symlink_metadata [`Utf8Error::valid_up_to`]: http://doc.rust-lang.org/nightly/core/str/struct.Utf8Error.html#method.valid_up_to [`Vec::resize`]: http://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#method.resize [`VecDeque::as_mut_slices`]: http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.as_mut_slices [`VecDeque::as_slices`]: http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.as_slices [`VecDeque::insert`]: http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.insert [`VecDeque::shrink_to_fit`]: http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.shrink_to_fit [`VecDeque::swap_remove_back`]: http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.swap_remove_back [`VecDeque::swap_remove_front`]: http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.swap_remove_front [`slice::split_first_mut`]: http://doc.rust-lang.org/nightly/std/primitive.slice.html#method.split_first_mut [`slice::split_first`]: http://doc.rust-lang.org/nightly/std/primitive.slice.html#method.split_first [`slice::split_last_mut`]: http://doc.rust-lang.org/nightly/std/primitive.slice.html#method.split_last_mut [`slice::split_last`]: http://doc.rust-lang.org/nightly/std/primitive.slice.html#method.split_last [`char::from_u32_unchecked`]: http://doc.rust-lang.org/nightly/std/char/fn.from_u32_unchecked.html [`fs::canonicalize`]: http://doc.rust-lang.org/nightly/std/fs/fn.canonicalize.html [`str::MatchIndices`]: http://doc.rust-lang.org/nightly/std/str/struct.MatchIndices.html [`str::RMatchIndices`]: http://doc.rust-lang.org/nightly/std/str/struct.RMatchIndices.html [`str::match_indices`]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.match_indices [`str::rmatch_indices`]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.rmatch_indices [`str::slice_mut_unchecked`]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.slice_mut_unchecked [`string::ParseError`]: http://doc.rust-lang.org/nightly/std/string/enum.ParseError.html Version 1.4.0 (2015-10-29) ========================== * ~1200 changes, numerous bugfixes Highlights ---------- * Windows builds targeting the 64-bit MSVC ABI and linker (instead of GNU) are now supported and recommended for use. Breaking Changes ---------------- * [Several changes have been made to fix type soundness and improve the behavior of associated types][sound]. See [RFC 1214]. Although we have mostly introduced these changes as warnings this release, to become errors next release, there are still some scenarios that will see immediate breakage. * [The `str::lines` and `BufRead::lines` iterators treat `\r\n` as line breaks in addition to `\n`][crlf]. * [Loans of `'static` lifetime extend to the end of a function][stat]. * [`str::parse` no longer introduces avoidable rounding error when parsing floating point numbers. Together with earlier changes to float formatting/output, "round trips" like f.to_string().parse() now preserve the value of f exactly. Additionally, leading plus signs are now accepted][fp3]. Language -------- * `use` statements that import multiple items [can now rename them][i], as in `use foo::{bar as kitten, baz as puppy}`. * [Binops work correctly on fat pointers][binfat]. * `pub extern crate`, which does not behave as expected, [issues a warning][pec] until a better solution is found. Libraries --------- * [Many APIs were stabilized][stab]: `<Box<str>>::into_string`, [`Arc::downgrade`], [`Arc::get_mut`], [`Arc::make_mut`], [`Arc::try_unwrap`], [`Box::from_raw`], [`Box::into_raw`], [`CStr::to_str`], [`CStr::to_string_lossy`], [`CString::from_raw`], [`CString::into_raw`], [`IntoRawFd::into_raw_fd`], [`IntoRawFd`], `IntoRawHandle::into_raw_handle`, `IntoRawHandle`, `IntoRawSocket::into_raw_socket`, `IntoRawSocket`, [`Rc::downgrade`], [`Rc::get_mut`], [`Rc::make_mut`], [`Rc::try_unwrap`], [`Result::expect`], [`String::into_boxed_str`], [`TcpStream::read_timeout`], [`TcpStream::set_read_timeout`], [`TcpStream::set_write_timeout`], [`TcpStream::write_timeout`], [`UdpSocket::read_timeout`], [`UdpSocket::set_read_timeout`], [`UdpSocket::set_write_timeout`], [`UdpSocket::write_timeout`], `Vec::append`, `Vec::split_off`, [`VecDeque::append`], [`VecDeque::retain`], [`VecDeque::split_off`], [`rc::Weak::upgrade`], [`rc::Weak`], [`slice::Iter::as_slice`], [`slice::IterMut::into_slice`], [`str::CharIndices::as_str`], [`str::Chars::as_str`], [`str::split_at_mut`], [`str::split_at`], [`sync::Weak::upgrade`], [`sync::Weak`], [`thread::park_timeout`], [`thread::sleep`]. * [Some APIs were deprecated][dep]: `BTreeMap::with_b`, `BTreeSet::with_b`, `Option::as_mut_slice`, `Option::as_slice`, `Result::as_mut_slice`, `Result::as_slice`, `f32::from_str_radix`, `f64::from_str_radix`. * [Reverse-searching strings is faster with the 'two-way' algorithm][s]. * [`std::io::copy` allows `?Sized` arguments][cc]. * The `Windows`, `Chunks`, and `ChunksMut` iterators over slices all [override `count`, `nth` and `last` with an *O*(1) implementation][it]. * [`Default` is implemented for arrays up to `[T; 32]`][d]. * [`IntoRawFd` has been added to the Unix-specific prelude, `IntoRawSocket` and `IntoRawHandle` to the Windows-specific prelude][pr]. * [`Extend<String>` and `FromIterator<String` are both implemented for `String`][es]. * [`IntoIterator` is implemented for references to `Option` and `Result`][into2]. * [`HashMap` and `HashSet` implement `Extend<&T>` where `T: Copy`][ext] as part of [RFC 839]. This will cause type inference breakage in rare situations. * [`BinaryHeap` implements `Debug`][bh2]. * [`Borrow` and `BorrowMut` are implemented for fixed-size arrays][bm]. * [`extern fn`s with the "Rust" and "C" ABIs implement common traits including `Eq`, `Ord`, `Debug`, `Hash`][fp]. * [String comparison is faster][faststr]. * `&mut T` where `T: std::fmt::Write` [also implements `std::fmt::Write`][mutw]. * [A stable regression in `VecDeque::push_back` and other capacity-altering methods that caused panics for zero-sized types was fixed][vd]. * [Function pointers implement traits for up to 12 parameters][fp2]. Miscellaneous ------------- * The compiler [no longer uses the 'morestack' feature to prevent stack overflow][mm]. Instead it uses guard pages and stack probes (though stack probes are not yet implemented on any platform but Windows). * [The compiler matches traits faster when projections are involved][p]. * The 'improper_ctypes' lint [no longer warns about use of `isize` and `usize`][ffi]. * [Cargo now displays useful information about what its doing during `cargo update`][cu]. [`Arc::downgrade`]: http://doc.rust-lang.org/nightly/alloc/arc/struct.Arc.html#method.downgrade [`Arc::make_mut`]: http://doc.rust-lang.org/nightly/alloc/arc/struct.Arc.html#method.make_mut [`Arc::get_mut`]: http://doc.rust-lang.org/nightly/alloc/arc/struct.Arc.html#method.get_mut [`Arc::try_unwrap`]: http://doc.rust-lang.org/nightly/alloc/arc/struct.Arc.html#method.try_unwrap [`Box::from_raw`]: http://doc.rust-lang.org/nightly/alloc/boxed/struct.Box.html#method.from_raw [`Box::into_raw`]: http://doc.rust-lang.org/nightly/alloc/boxed/struct.Box.html#method.into_raw [`CStr::to_str`]: http://doc.rust-lang.org/nightly/std/ffi/struct.CStr.html#method.to_str [`CStr::to_string_lossy`]: http://doc.rust-lang.org/nightly/std/ffi/struct.CStr.html#method.to_string_lossy [`CString::from_raw`]: http://doc.rust-lang.org/nightly/std/ffi/struct.CString.html#method.from_raw [`CString::into_raw`]: http://doc.rust-lang.org/nightly/std/ffi/struct.CString.html#method.into_raw [`IntoRawFd::into_raw_fd`]: http://doc.rust-lang.org/nightly/std/os/unix/io/trait.IntoRawFd.html#tymethod.into_raw_fd [`IntoRawFd`]: http://doc.rust-lang.org/nightly/std/os/unix/io/trait.IntoRawFd.html [`Rc::downgrade`]: http://doc.rust-lang.org/nightly/alloc/rc/struct.Rc.html#method.downgrade [`Rc::get_mut`]: http://doc.rust-lang.org/nightly/alloc/rc/struct.Rc.html#method.get_mut [`Rc::make_mut`]: http://doc.rust-lang.org/nightly/alloc/rc/struct.Rc.html#method.make_mut [`Rc::try_unwrap`]: http://doc.rust-lang.org/nightly/alloc/rc/struct.Rc.html#method.try_unwrap [`Result::expect`]: http://doc.rust-lang.org/nightly/core/result/enum.Result.html#method.expect [`String::into_boxed_str`]: http://doc.rust-lang.org/nightly/collections/string/struct.String.html#method.into_boxed_str [`TcpStream::read_timeout`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.read_timeout [`TcpStream::set_read_timeout`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_read_timeout [`TcpStream::write_timeout`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.write_timeout [`TcpStream::set_write_timeout`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_write_timeout [`UdpSocket::read_timeout`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.read_timeout [`UdpSocket::set_read_timeout`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_read_timeout [`UdpSocket::write_timeout`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.write_timeout [`UdpSocket::set_write_timeout`]: http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_write_timeout [`VecDeque::append`]: http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.append [`VecDeque::retain`]: http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.retain [`VecDeque::split_off`]: http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.split_off [`rc::Weak::upgrade`]: http://doc.rust-lang.org/nightly/std/rc/struct.Weak.html#method.upgrade [`rc::Weak`]: http://doc.rust-lang.org/nightly/std/rc/struct.Weak.html [`slice::Iter::as_slice`]: http://doc.rust-lang.org/nightly/std/slice/struct.Iter.html#method.as_slice [`slice::IterMut::into_slice`]: http://doc.rust-lang.org/nightly/std/slice/struct.IterMut.html#method.into_slice [`str::CharIndices::as_str`]: http://doc.rust-lang.org/nightly/std/str/struct.CharIndices.html#method.as_str [`str::Chars::as_str`]: http://doc.rust-lang.org/nightly/std/str/struct.Chars.html#method.as_str [`str::split_at_mut`]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.split_at_mut [`str::split_at`]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.split_at [`sync::Weak::upgrade`]: http://doc.rust-lang.org/nightly/std/sync/struct.Weak.html#method.upgrade [`sync::Weak`]: http://doc.rust-lang.org/nightly/std/sync/struct.Weak.html [`thread::park_timeout`]: http://doc.rust-lang.org/nightly/std/thread/fn.park_timeout.html [`thread::sleep`]: http://doc.rust-lang.org/nightly/std/thread/fn.sleep.html [bh2]: https://github.com/rust-lang/rust/pull/28156 [binfat]: https://github.com/rust-lang/rust/pull/28270 [bm]: https://github.com/rust-lang/rust/pull/28197 [cc]: https://github.com/rust-lang/rust/pull/27531 [crlf]: https://github.com/rust-lang/rust/pull/28034 [cu]: https://github.com/rust-lang/cargo/pull/1931 [d]: https://github.com/rust-lang/rust/pull/27825 [dep]: https://github.com/rust-lang/rust/pull/28339 [es]: https://github.com/rust-lang/rust/pull/27956 [ext]: https://github.com/rust-lang/rust/pull/28094 [faststr]: https://github.com/rust-lang/rust/pull/28338 [ffi]: https://github.com/rust-lang/rust/pull/28779 [fp]: https://github.com/rust-lang/rust/pull/28268 [fp2]: https://github.com/rust-lang/rust/pull/28560 [fp3]: https://github.com/rust-lang/rust/pull/27307 [i]: https://github.com/rust-lang/rust/pull/27451 [into2]: https://github.com/rust-lang/rust/pull/28039 [it]: https://github.com/rust-lang/rust/pull/27652 [mm]: https://github.com/rust-lang/rust/pull/27338 [mutw]: https://github.com/rust-lang/rust/pull/28368 [sound]: https://github.com/rust-lang/rust/pull/27641 [p]: https://github.com/rust-lang/rust/pull/27866 [pec]: https://github.com/rust-lang/rust/pull/28486 [pr]: https://github.com/rust-lang/rust/pull/27896 [RFC 839]: https://github.com/rust-lang/rfcs/blob/master/text/0839-embrace-extend-extinguish.md [RFC 1214]: https://github.com/rust-lang/rfcs/blob/master/text/1214-projections-lifetimes-and-wf.md [s]: https://github.com/rust-lang/rust/pull/27474 [stab]: https://github.com/rust-lang/rust/pull/28339 [stat]: https://github.com/rust-lang/rust/pull/28321 [vd]: https://github.com/rust-lang/rust/pull/28494 Version 1.3.0 (2015-09-17) ============================== * ~900 changes, numerous bugfixes Highlights ---------- * The [new object lifetime defaults][nold] have been [turned on][nold2] after a cycle of warnings about the change. Now types like `&'a Box<Trait>` (or `&'a Rc<Trait>`, etc) will change from being interpreted as `&'a Box<Trait+'a>` to `&'a Box<Trait+'static>`. * [The Rustonomicon][nom] is a new book in the official documentation that dives into writing unsafe Rust. * The [`Duration`] API, [has been stabilized][ds]. This basic unit of timekeeping is employed by other std APIs, as well as out-of-tree time crates. Breaking Changes ---------------- * The [new object lifetime defaults][nold] have been [turned on][nold2] after a cycle of warnings about the change. * There is a known [regression][lr] in how object lifetime elision is interpreted, the proper solution for which is undetermined. * The `#[prelude_import]` attribute, an internal implementation detail, was accidentally stabilized previously. [It has been put behind the `prelude_import` feature gate][pi]. This change is believed to break no existing code. * The behavior of [`size_of_val`][dst1] and [`align_of_val`][dst2] is [more sane for dynamically sized types][dst3]. Code that relied on the previous behavior is thought to be broken. * The `dropck` rules, which checks that destructors can't access destroyed values, [have been updated][dropck] to match the [RFC][dropckrfc]. This fixes some soundness holes, and as such will cause some previously-compiling code to no longer build. Language -------- * The [new object lifetime defaults][nold] have been [turned on][nold2] after a cycle of warnings about the change. * Semicolons may [now follow types and paths in macros](https://github.com/rust-lang/rust/pull/27000). * The behavior of [`size_of_val`][dst1] and [`align_of_val`][dst2] is [more sane for dynamically sized types][dst3]. Code that relied on the previous behavior is not known to exist, and suspected to be broken. * `'static` variables [may now be recursive][st]. * `ref` bindings choose between [`Deref`] and [`DerefMut`] implementations correctly. * The `dropck` rules, which checks that destructors can't access destroyed values, [have been updated][dropck] to match the [RFC][dropckrfc]. Libraries --------- * The [`Duration`] API, [has been stabilized][ds], as well as the `std::time` module, which presently contains only `Duration`. * `Box<str>` and `Box<[T]>` both implement `Clone`. * The owned C string, [`CString`], implements [`Borrow`] and the borrowed C string, [`CStr`], implements [`ToOwned`]. The two of these allow C strings to be borrowed and cloned in generic code. * [`CStr`] implements [`Debug`]. * [`AtomicPtr`] implements [`Debug`]. * [`Error`] trait objects [can be downcast to their concrete types][e] in many common configurations, using the [`is`], [`downcast`], [`downcast_ref`] and [`downcast_mut`] methods, similarly to the [`Any`] trait. * Searching for substrings now [employs the two-way algorithm][search] instead of doing a naive search. This gives major speedups to a number of methods, including [`contains`][sc], [`find`][sf], [`rfind`][srf], [`split`][ss]. [`starts_with`][ssw] and [`ends_with`][sew] are also faster. * The performance of `PartialEq` for slices is [much faster][ps]. * The [`Hash`] trait offers the default method, [`hash_slice`], which is overridden and optimized by the implementations for scalars. * The [`Hasher`] trait now has a number of specialized `write_*` methods for primitive types, for efficiency. * The I/O-specific error type, [`std::io::Error`][ie], gained a set of methods for accessing the 'inner error', if any: [`get_ref`][iegr], [`get_mut`][iegm], [`into_inner`][ieii]. As well, the implementation of [`std::error::Error::cause`][iec] also delegates to the inner error. * [`process::Child`][pc] gained the [`id`] method, which returns a `u32` representing the platform-specific process identifier. * The [`connect`] method on slices is deprecated, replaced by the new [`join`] method (note that both of these are on the *unstable* [`SliceConcatExt`] trait, but through the magic of the prelude are available to stable code anyway). * The [`Div`] operator is implemented for [`Wrapping`] types. * [`DerefMut` is implemented for `String`][dms]. * Performance of SipHash (the default hasher for `HashMap`) is [better for long data][sh]. * [`AtomicPtr`] implements [`Send`]. * The [`read_to_end`] implementations for [`Stdin`] and [`File`] are now [specialized to use uninitialized buffers for increased performance][rte]. * Lifetime parameters of foreign functions [are now resolved properly][f]. Misc ---- * Rust can now, with some coercion, [produce programs that run on Windows XP][xp], though XP is not considered a supported platform. * Porting Rust on Windows from the GNU toolchain to MSVC continues ([1][win1], [2][win2], [3][win3], [4][win4]). It is still not recommended for use in 1.3, though should be fully-functional in the [64-bit 1.4 beta][b14]. * On Fedora-based systems installation will [properly configure the dynamic linker][fl]. * The compiler gained many new extended error descriptions, which can be accessed with the `--explain` flag. * The `dropck` pass, which checks that destructors can't access destroyed values, [has been rewritten][27261]. This fixes some soundness holes, and as such will cause some previously-compiling code to no longer build. * `rustc` now uses [LLVM to write archive files where possible][ar]. Eventually this will eliminate the compiler's dependency on the ar utility. * Rust has [preliminary support for i686 FreeBSD][26959] (it has long supported FreeBSD on x86_64). * The [`unused_mut`][lum], [`unconditional_recursion`][lur], [`improper_ctypes`][lic], and [`negate_unsigned`][lnu] lints are more strict. * If landing pads are disabled (with `-Z no-landing-pads`), [`panic!` will kill the process instead of leaking][nlp]. [`Any`]: http://doc.rust-lang.org/nightly/std/any/trait.Any.html [`AtomicPtr`]: http://doc.rust-lang.org/nightly/std/sync/atomic/struct.AtomicPtr.html [`Borrow`]: http://doc.rust-lang.org/nightly/std/borrow/trait.Borrow.html [`CStr`]: http://doc.rust-lang.org/nightly/std/ffi/struct.CStr.html [`CString`]: http://doc.rust-lang.org/nightly/std/ffi/struct.CString.html [`Debug`]: http://doc.rust-lang.org/nightly/std/fmt/trait.Debug.html [`DerefMut`]: http://doc.rust-lang.org/nightly/std/ops/trait.DerefMut.html [`Deref`]: http://doc.rust-lang.org/nightly/std/ops/trait.Deref.html [`Div`]: http://doc.rust-lang.org/nightly/std/ops/trait.Div.html [`Duration`]: http://doc.rust-lang.org/nightly/std/time/struct.Duration.html [`Error`]: http://doc.rust-lang.org/nightly/std/error/trait.Error.html [`File`]: http://doc.rust-lang.org/nightly/std/fs/struct.File.html [`Hash`]: http://doc.rust-lang.org/nightly/std/hash/trait.Hash.html [`Hasher`]: http://doc.rust-lang.org/nightly/std/hash/trait.Hasher.html [`Send`]: http://doc.rust-lang.org/nightly/std/marker/trait.Send.html [`SliceConcatExt`]: http://doc.rust-lang.org/nightly/std/slice/trait.SliceConcatExt.html [`Stdin`]: http://doc.rust-lang.org/nightly/std/io/struct.Stdin.html [`ToOwned`]: http://doc.rust-lang.org/nightly/std/borrow/trait.ToOwned.html [`Wrapping`]: http://doc.rust-lang.org/nightly/std/num/struct.Wrapping.html [`connect`]: http://doc.rust-lang.org/nightly/std/slice/trait.SliceConcatExt.html#method.connect [`downcast_mut`]: http://doc.rust-lang.org/nightly/std/error/trait.Error.html#method.downcast_mut [`downcast_ref`]: http://doc.rust-lang.org/nightly/std/error/trait.Error.html#method.downcast_ref [`downcast`]: http://doc.rust-lang.org/nightly/std/error/trait.Error.html#method.downcast [`hash_slice`]: http://doc.rust-lang.org/nightly/std/hash/trait.Hash.html#method.hash_slice [`id`]: http://doc.rust-lang.org/nightly/std/process/struct.Child.html#method.id [`is`]: http://doc.rust-lang.org/nightly/std/error/trait.Error.html#method.is [`join`]: http://doc.rust-lang.org/nightly/std/slice/trait.SliceConcatExt.html#method.join [`read_to_end`]: http://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.read_to_end [ar]: https://github.com/rust-lang/rust/pull/26926 [b14]: https://static.rust-lang.org/dist/rust-beta-x86_64-pc-windows-msvc.msi [dms]: https://github.com/rust-lang/rust/pull/26241 [27261]: https://github.com/rust-lang/rust/pull/27261 [dropckrfc]: https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md [ds]: https://github.com/rust-lang/rust/pull/26818 [dst1]: http://doc.rust-lang.org/nightly/std/mem/fn.size_of_val.html [dst2]: http://doc.rust-lang.org/nightly/std/mem/fn.align_of_val.html [dst3]: https://github.com/rust-lang/rust/pull/27351 [e]: https://github.com/rust-lang/rust/pull/24793 [f]: https://github.com/rust-lang/rust/pull/26588 [26959]: https://github.com/rust-lang/rust/pull/26959 [fl]: https://github.com/rust-lang/rust-installer/pull/41 [ie]: http://doc.rust-lang.org/nightly/std/io/struct.Error.html [iec]: http://doc.rust-lang.org/nightly/std/io/struct.Error.html#method.cause [iegm]: http://doc.rust-lang.org/nightly/std/io/struct.Error.html#method.get_mut [iegr]: http://doc.rust-lang.org/nightly/std/io/struct.Error.html#method.get_ref [ieii]: http://doc.rust-lang.org/nightly/std/io/struct.Error.html#method.into_inner [lic]: https://github.com/rust-lang/rust/pull/26583 [lnu]: https://github.com/rust-lang/rust/pull/27026 [lr]: https://github.com/rust-lang/rust/issues/27248 [lum]: https://github.com/rust-lang/rust/pull/26378 [lur]: https://github.com/rust-lang/rust/pull/26783 [nlp]: https://github.com/rust-lang/rust/pull/27176 [nold2]: https://github.com/rust-lang/rust/pull/27045 [nold]: https://github.com/rust-lang/rfcs/blob/master/text/1156-adjust-default-object-bounds.md [nom]: http://doc.rust-lang.org/nightly/nomicon/ [pc]: http://doc.rust-lang.org/nightly/std/process/struct.Child.html [pi]: https://github.com/rust-lang/rust/pull/26699 [ps]: https://github.com/rust-lang/rust/pull/26884 [rte]: https://github.com/rust-lang/rust/pull/26950 [sc]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.contains [search]: https://github.com/rust-lang/rust/pull/26327 [sew]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.ends_with [sf]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.find [sh]: https://github.com/rust-lang/rust/pull/27280 [srf]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.rfind [ss]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.split [ssw]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.starts_with [st]: https://github.com/rust-lang/rust/pull/26630 [win1]: https://github.com/rust-lang/rust/pull/26569 [win2]: https://github.com/rust-lang/rust/pull/26741 [win3]: https://github.com/rust-lang/rust/pull/26741 [win4]: https://github.com/rust-lang/rust/pull/27210 [xp]: https://github.com/rust-lang/rust/pull/26569 Version 1.2.0 (2015-08-07) ========================== * ~1200 changes, numerous bugfixes Highlights ---------- * [Dynamically-sized-type coercions][dst] allow smart pointer types like `Rc` to contain types without a fixed size, arrays and trait objects, finally enabling use of `Rc<[T]>` and completing the implementation of DST. * [Parallel codegen][parcodegen] is now working again, which can substantially speed up large builds in debug mode; It also gets another ~33% speedup when bootstrapping on a 4 core machine (using 8 jobs). It's not enabled by default, but will be "in the near future". It can be activated with the `-C codegen-units=N` flag to `rustc`. * This is the first release with [experimental support for linking with the MSVC linker and lib C on Windows (instead of using the GNU variants via MinGW)][win]. It is yet recommended only for the most intrepid Rustaceans. * Benchmark compilations are showing a 30% improvement in bootstrapping over 1.1. Breaking Changes ---------------- * The [`to_uppercase`] and [`to_lowercase`] methods on `char` now do unicode case mapping, which is a previously-planned change in behavior and considered a bugfix. * [`mem::align_of`] now specifies [the *minimum alignment* for T][align], which is usually the alignment programs are interested in, and the same value reported by clang's `alignof`. [`mem::min_align_of`] is deprecated. This is not known to break real code. * [The `#[packed]` attribute is no longer silently accepted by the compiler][packed]. This attribute did nothing and code that mentioned it likely did not work as intended. * Associated type defaults are [now behind the `associated_type_defaults` feature gate][ad]. In 1.1 associated type defaults *did not work*, but could be mentioned syntactically. As such this breakage has minimal impact. Language -------- * Patterns with `ref mut` now correctly invoke [`DerefMut`] when matching against dereferenceable values. Libraries --------- * The [`Extend`] trait, which grows a collection from an iterator, is implemented over iterators of references, for `String`, `Vec`, `LinkedList`, `VecDeque`, `EnumSet`, `BinaryHeap`, `VecMap`, `BTreeSet` and `BTreeMap`. [RFC][extend-rfc]. * The [`iter::once`] function returns an iterator that yields a single element, and [`iter::empty`] returns an iterator that yields no elements. * The [`matches`] and [`rmatches`] methods on `str` return iterators over substring matches. * [`Cell`] and [`RefCell`] both implement `Eq`. * A number of methods for wrapping arithmetic are added to the integral types, [`wrapping_div`], [`wrapping_rem`], [`wrapping_neg`], [`wrapping_shl`], [`wrapping_shr`]. These are in addition to the existing [`wrapping_add`], [`wrapping_sub`], and [`wrapping_mul`] methods, and alternatives to the [`Wrapping`] type.. It is illegal for the default arithmetic operations in Rust to overflow; the desire to wrap must be explicit. * The `{:#?}` formatting specifier [displays the alternate, pretty-printed][debugfmt] form of the `Debug` formatter. This feature was actually introduced prior to 1.0 with little fanfare. * [`fmt::Formatter`] implements [`fmt::Write`], a `fmt`-specific trait for writing data to formatted strings, similar to [`io::Write`]. * [`fmt::Formatter`] adds 'debug builder' methods, [`debug_struct`], [`debug_tuple`], [`debug_list`], [`debug_set`], [`debug_map`]. These are used by code generators to emit implementations of [`Debug`]. * `str` has new [`to_uppercase`][strup] and [`to_lowercase`][strlow] methods that convert case, following Unicode case mapping. * It is now easier to handle poisoned locks. The [`PoisonError`] type, returned by failing lock operations, exposes `into_inner`, `get_ref`, and `get_mut`, which all give access to the inner lock guard, and allow the poisoned lock to continue to operate. The `is_poisoned` method of [`RwLock`] and [`Mutex`] can poll for a poisoned lock without attempting to take the lock. * On Unix the [`FromRawFd`] trait is implemented for [`Stdio`], and [`AsRawFd`] for [`ChildStdin`], [`ChildStdout`], [`ChildStderr`]. On Windows the `FromRawHandle` trait is implemented for `Stdio`, and `AsRawHandle` for `ChildStdin`, `ChildStdout`, `ChildStderr`. * [`io::ErrorKind`] has a new variant, `InvalidData`, which indicates malformed input. Misc ---- * `rustc` employs smarter heuristics for guessing at [typos]. * `rustc` emits more efficient code for [no-op conversions between unsafe pointers][nop]. * Fat pointers are now [passed in pairs of immediate arguments][fat], resulting in faster compile times and smaller code. [`Extend`]: https://doc.rust-lang.org/nightly/std/iter/trait.Extend.html [extend-rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0839-embrace-extend-extinguish.md [`iter::once`]: https://doc.rust-lang.org/nightly/std/iter/fn.once.html [`iter::empty`]: https://doc.rust-lang.org/nightly/std/iter/fn.empty.html [`matches`]: https://doc.rust-lang.org/nightly/std/primitive.str.html#method.matches [`rmatches`]: https://doc.rust-lang.org/nightly/std/primitive.str.html#method.rmatches [`Cell`]: https://doc.rust-lang.org/nightly/std/cell/struct.Cell.html [`RefCell`]: https://doc.rust-lang.org/nightly/std/cell/struct.RefCell.html [`wrapping_add`]: https://doc.rust-lang.org/nightly/std/primitive.i8.html#method.wrapping_add [`wrapping_sub`]: https://doc.rust-lang.org/nightly/std/primitive.i8.html#method.wrapping_sub [`wrapping_mul`]: https://doc.rust-lang.org/nightly/std/primitive.i8.html#method.wrapping_mul [`wrapping_div`]: https://doc.rust-lang.org/nightly/std/primitive.i8.html#method.wrapping_div [`wrapping_rem`]: https://doc.rust-lang.org/nightly/std/primitive.i8.html#method.wrapping_rem [`wrapping_neg`]: https://doc.rust-lang.org/nightly/std/primitive.i8.html#method.wrapping_neg [`wrapping_shl`]: https://doc.rust-lang.org/nightly/std/primitive.i8.html#method.wrapping_shl [`wrapping_shr`]: https://doc.rust-lang.org/nightly/std/primitive.i8.html#method.wrapping_shr [`Wrapping`]: https://doc.rust-lang.org/nightly/std/num/struct.Wrapping.html [`fmt::Formatter`]: https://doc.rust-lang.org/nightly/std/fmt/struct.Formatter.html [`fmt::Write`]: https://doc.rust-lang.org/nightly/std/fmt/trait.Write.html [`io::Write`]: https://doc.rust-lang.org/nightly/std/io/trait.Write.html [`debug_struct`]: https://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.debug_struct [`debug_tuple`]: https://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.debug_tuple [`debug_list`]: https://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.debug_list [`debug_set`]: https://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.debug_set [`debug_map`]: https://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.debug_map [`Debug`]: https://doc.rust-lang.org/nightly/std/fmt/trait.Debug.html [strup]: https://doc.rust-lang.org/nightly/std/primitive.str.html#method.to_uppercase [strlow]: https://doc.rust-lang.org/nightly/std/primitive.str.html#method.to_lowercase [`to_uppercase`]: https://doc.rust-lang.org/nightly/std/primitive.char.html#method.to_uppercase [`to_lowercase`]: https://doc.rust-lang.org/nightly/std/primitive.char.html#method.to_lowercase [`PoisonError`]: https://doc.rust-lang.org/nightly/std/sync/struct.PoisonError.html [`RwLock`]: https://doc.rust-lang.org/nightly/std/sync/struct.RwLock.html [`Mutex`]: https://doc.rust-lang.org/nightly/std/sync/struct.Mutex.html [`FromRawFd`]: https://doc.rust-lang.org/nightly/std/os/unix/io/trait.FromRawFd.html [`AsRawFd`]: https://doc.rust-lang.org/nightly/std/os/unix/io/trait.AsRawFd.html [`Stdio`]: https://doc.rust-lang.org/nightly/std/process/struct.Stdio.html [`ChildStdin`]: https://doc.rust-lang.org/nightly/std/process/struct.ChildStdin.html [`ChildStdout`]: https://doc.rust-lang.org/nightly/std/process/struct.ChildStdout.html [`ChildStderr`]: https://doc.rust-lang.org/nightly/std/process/struct.ChildStderr.html [`io::ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html [debugfmt]: https://www.reddit.com/r/rust/comments/3ceaui/psa_produces_prettyprinted_debug_output/ [`DerefMut`]: https://doc.rust-lang.org/nightly/std/ops/trait.DerefMut.html [`mem::align_of`]: https://doc.rust-lang.org/nightly/std/mem/fn.align_of.html [align]: https://github.com/rust-lang/rust/pull/25646 [`mem::min_align_of`]: https://doc.rust-lang.org/nightly/std/mem/fn.min_align_of.html [typos]: https://github.com/rust-lang/rust/pull/26087 [nop]: https://github.com/rust-lang/rust/pull/26336 [fat]: https://github.com/rust-lang/rust/pull/26411 [dst]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md [parcodegen]: https://github.com/rust-lang/rust/pull/26018 [packed]: https://github.com/rust-lang/rust/pull/25541 [ad]: https://github.com/rust-lang/rust/pull/27382 [win]: https://github.com/rust-lang/rust/pull/25350 Version 1.1.0 (2015-06-25) ========================= * ~850 changes, numerous bugfixes Highlights ---------- * The [`std::fs` module has been expanded][fs] to expand the set of functionality exposed: * `DirEntry` now supports optimizations like `file_type` and `metadata` which don't incur a syscall on some platforms. * A `symlink_metadata` function has been added. * The `fs::Metadata` structure now lowers to its OS counterpart, providing access to all underlying information. * The compiler now contains extended explanations of many errors. When an error with an explanation occurs the compiler suggests using the `--explain` flag to read the explanation. Error explanations are also [available online][err-index]. * Thanks to multiple [improvements][sk] to [type checking][pre], as well as other work, the time to bootstrap the compiler decreased by 32%. Libraries --------- * The [`str::split_whitespace`] method splits a string on unicode whitespace boundaries. * On both Windows and Unix, new extension traits provide conversion of I/O types to and from the underlying system handles. On Unix, these traits are [`FromRawFd`] and [`AsRawFd`], on Windows `FromRawHandle` and `AsRawHandle`. These are implemented for `File`, `TcpStream`, `TcpListener`, and `UpdSocket`. Further implementations for `std::process` will be stabilized later. * On Unix, [`std::os::unix::symlink`] creates symlinks. On Windows, symlinks can be created with `std::os::windows::symlink_dir` and `std::os::windows::symlink_file`. * The `mpsc::Receiver` type can now be converted into an iterator with `into_iter` on the [`IntoIterator`] trait. * `Ipv4Addr` can be created from `u32` with the `From<u32>` implementation of the [`From`] trait. * The `Debug` implementation for `RangeFull` [creates output that is more consistent with other implementations][rf]. * [`Debug` is implemented for `File`][file]. * The `Default` implementation for `Arc` [no longer requires `Sync + Send`][arc]. * [The `Iterator` methods `count`, `nth`, and `last` have been overridden for slices to have *O*(1) performance instead of *O*(*n*)][si]. * Incorrect handling of paths on Windows has been improved in both the compiler and the standard library. * [`AtomicPtr` gained a `Default` implementation][ap]. * In accordance with Rust's policy on arithmetic overflow `abs` now [panics on overflow when debug assertions are enabled][abs]. * The [`Cloned`] iterator, which was accidentally left unstable for 1.0 [has been stabilized][c]. * The [`Incoming`] iterator, which iterates over incoming TCP connections, and which was accidentally unnamable in 1.0, [is now properly exported][inc]. * [`BinaryHeap`] no longer corrupts itself [when functions called by `sift_up` or `sift_down` panic][bh]. * The [`split_off`] method of `LinkedList` [no longer corrupts the list in certain scenarios][ll]. Misc ---- * Type checking performance [has improved notably][sk] with [multiple improvements][pre]. * The compiler [suggests code changes][ch] for more errors. * rustc and it's build system have experimental support for [building toolchains against MUSL][m] instead of glibc on Linux. * The compiler defines the `target_env` cfg value, which is used for distinguishing toolchains that are otherwise for the same platform. Presently this is set to `gnu` for common GNU Linux targets and for MinGW targets, and `musl` for MUSL Linux targets. * The [`cargo rustc`][crc] command invokes a build with custom flags to rustc. * [Android executables are always position independent][pie]. * [The `drop_with_repr_extern` lint warns about mixing `repr(C)` with `Drop`][24935]. [`str::split_whitespace`]: https://doc.rust-lang.org/nightly/std/primitive.str.html#method.split_whitespace [`FromRawFd`]: https://doc.rust-lang.org/nightly/std/os/unix/io/trait.FromRawFd.html [`AsRawFd`]: https://doc.rust-lang.org/nightly/std/os/unix/io/trait.AsRawFd.html [`std::os::unix::symlink`]: https://doc.rust-lang.org/nightly/std/os/unix/fs/fn.symlink.html [`IntoIterator`]: https://doc.rust-lang.org/nightly/std/iter/trait.IntoIterator.html [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html [rf]: https://github.com/rust-lang/rust/pull/24491 [err-index]: https://doc.rust-lang.org/error-index.html [sk]: https://github.com/rust-lang/rust/pull/24615 [pre]: https://github.com/rust-lang/rust/pull/25323 [file]: https://github.com/rust-lang/rust/pull/24598 [ch]: https://github.com/rust-lang/rust/pull/24683 [arc]: https://github.com/rust-lang/rust/pull/24695 [si]: https://github.com/rust-lang/rust/pull/24701 [ap]: https://github.com/rust-lang/rust/pull/24834 [m]: https://github.com/rust-lang/rust/pull/24777 [fs]: https://github.com/rust-lang/rfcs/blob/master/text/1044-io-fs-2.1.md [crc]: https://github.com/rust-lang/cargo/pull/1568 [pie]: https://github.com/rust-lang/rust/pull/24953 [abs]: https://github.com/rust-lang/rust/pull/25441 [c]: https://github.com/rust-lang/rust/pull/25496 [`Cloned`]: https://doc.rust-lang.org/nightly/std/iter/struct.Cloned.html [`Incoming`]: https://doc.rust-lang.org/nightly/std/net/struct.Incoming.html [inc]: https://github.com/rust-lang/rust/pull/25522 [bh]: https://github.com/rust-lang/rust/pull/25856 [`BinaryHeap`]: https://doc.rust-lang.org/nightly/std/collections/struct.BinaryHeap.html [ll]: https://github.com/rust-lang/rust/pull/26022 [`split_off`]: https://doc.rust-lang.org/nightly/collections/linked_list/struct.LinkedList.html#method.split_off [24935]: https://github.com/rust-lang/rust/pull/24935 Version 1.0.0 (2015-05-15) ======================== * ~1500 changes, numerous bugfixes Highlights ---------- * The vast majority of the standard library is now `#[stable]`. It is no longer possible to use unstable features with a stable build of the compiler. * Many popular crates on [crates.io] now work on the stable release channel. * Arithmetic on basic integer types now [checks for overflow in debug builds][overflow]. Language -------- * Several [restrictions have been added to trait coherence][coh] in order to make it easier for upstream authors to change traits without breaking downstream code. * Digits of binary and octal literals are [lexed more eagerly][lex] to improve error messages and macro behavior. For example, `0b1234` is now lexed as `0b1234` instead of two tokens, `0b1` and `234`. * Trait bounds [are always invariant][inv], eliminating the need for the `PhantomFn` and `MarkerTrait` lang items, which have been removed. * ["-" is no longer a valid character in crate names][cr], the `extern crate "foo" as bar` syntax has been replaced with `extern crate foo as bar`, and Cargo now automatically translates "-" in *package* names to underscore for the crate name. * [Lifetime shadowing is an error][lt]. * [`Send` no longer implies `'static`][send-rfc]. * [UFCS now supports trait-less associated paths][moar-ufcs] like `MyType::default()`. * Primitive types [now have inherent methods][prim-inherent], obviating the need for extension traits like `SliceExt`. * Methods with `Self: Sized` in their `where` clause are [considered object-safe][self-sized], allowing many extension traits like `IteratorExt` to be merged into the traits they extended. * You can now [refer to associated types][assoc-where] whose corresponding trait bounds appear only in a `where` clause. * The final bits of [OIBIT landed][oibit-final], meaning that traits like `Send` and `Sync` are now library-defined. * A [Reflect trait][reflect] was introduced, which means that downcasting via the `Any` trait is effectively limited to concrete types. This helps retain the potentially-important "parametricity" property: generic code cannot behave differently for different type arguments except in minor ways. * The `unsafe_destructor` feature is now deprecated in favor of the [new `dropck`][rfc769]. This change is a major reduction in unsafe code. Libraries --------- * The `thread_local` module [has been renamed to `std::thread`][th]. * The methods of `IteratorExt` [have been moved to the `Iterator` trait itself][23300]. * Several traits that implement Rust's conventions for type conversions, `AsMut`, `AsRef`, `From`, and `Into` have been [centralized in the `std::convert` module][con]. * The `FromError` trait [was removed in favor of `From`][fe]. * The basic sleep function [has moved to `std::thread::sleep_ms`][slp]. * The `splitn` function now takes an `n` parameter that represents the number of items yielded by the returned iterator [instead of the number of 'splits'][spl]. * [On Unix, all file descriptors are `CLOEXEC` by default][clo]. * [Derived implementations of `PartialOrd` now order enums according to their explicitly-assigned discriminants][po]. * [Methods for searching strings are generic over `Pattern`s][pat], implemented presently by `&char`, `&str`, `FnMut(char) -> bool` and some others. * [In method resolution, object methods are resolved before inherent methods][meth]. * [`String::from_str` has been deprecated in favor of the `From` impl, `String::from`][24517]. * [`io::Error` implements `Sync`][ios]. * [The `words` method on `&str` has been replaced with `split_whitespace`][sw], to avoid answering the tricky question, 'what is a word?' * The new path and IO modules are complete and `#[stable]`. This was the major library focus for this cycle. * The path API was [revised][path-normalize] to normalize `.`, adjusting the tradeoffs in favor of the most common usage. * A large number of remaining APIs in `std` were also stabilized during this cycle; about 75% of the non-deprecated API surface is now stable. * The new [string pattern API][string-pattern] landed, which makes the string slice API much more internally consistent and flexible. * A new set of [generic conversion traits][conversion] replaced many existing ad hoc traits. * Generic numeric traits were [completely removed][num-traits]. This was made possible thanks to inherent methods for primitive types, and the removal gives maximal flexibility for designing a numeric hierarchy in the future. * The `Fn` traits are now related via [inheritance][fn-inherit] and provide ergonomic [blanket implementations][fn-blanket]. * The `Index` and `IndexMut` traits were changed to [take the index by value][index-value], enabling code like `hash_map["string"]` to work. * `Copy` now [inherits][copy-clone] from `Clone`, meaning that all `Copy` data is known to be `Clone` as well. Misc ---- * Many errors now have extended explanations that can be accessed with the `--explain` flag to `rustc`. * Many new examples have been added to the standard library documentation. * rustdoc has received a number of improvements focused on completion and polish. * Metadata was tuned, shrinking binaries [by 27%][metadata-shrink]. * Much headway was made on ecosystem-wide CI, making it possible to [compare builds for breakage][ci-compare]. [crates.io]: http://crates.io [clo]: https://github.com/rust-lang/rust/pull/24034 [coh]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md [con]: https://github.com/rust-lang/rust/pull/23875 [cr]: https://github.com/rust-lang/rust/pull/23419 [fe]: https://github.com/rust-lang/rust/pull/23879 [23300]: https://github.com/rust-lang/rust/pull/23300 [inv]: https://github.com/rust-lang/rust/pull/23938 [ios]: https://github.com/rust-lang/rust/pull/24133 [lex]: https://github.com/rust-lang/rfcs/blob/master/text/0879-small-base-lexing.md [lt]: https://github.com/rust-lang/rust/pull/24057 [meth]: https://github.com/rust-lang/rust/pull/24056 [pat]: https://github.com/rust-lang/rfcs/blob/master/text/0528-string-patterns.md [po]: https://github.com/rust-lang/rust/pull/24270 [24517]: https://github.com/rust-lang/rust/pull/24517 [slp]: https://github.com/rust-lang/rust/pull/23949 [spl]: https://github.com/rust-lang/rfcs/blob/master/text/0979-align-splitn-with-other-languages.md [sw]: https://github.com/rust-lang/rfcs/blob/master/text/1054-str-words.md [th]: https://github.com/rust-lang/rfcs/blob/master/text/0909-move-thread-local-to-std-thread.md [send-rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0458-send-improvements.md [moar-ufcs]: https://github.com/rust-lang/rust/pull/22172 [prim-inherent]: https://github.com/rust-lang/rust/pull/23104 [overflow]: https://github.com/rust-lang/rfcs/blob/master/text/0560-integer-overflow.md [metadata-shrink]: https://github.com/rust-lang/rust/pull/22971 [self-sized]: https://github.com/rust-lang/rust/pull/22301 [assoc-where]: https://github.com/rust-lang/rust/pull/22512 [string-pattern]: https://github.com/rust-lang/rust/pull/22466 [oibit-final]: https://github.com/rust-lang/rust/pull/21689 [reflect]: https://github.com/rust-lang/rust/pull/23712 [conversion]: https://github.com/rust-lang/rfcs/pull/529 [num-traits]: https://github.com/rust-lang/rust/pull/23549 [index-value]: https://github.com/rust-lang/rust/pull/23601 [rfc769]: https://github.com/rust-lang/rfcs/pull/769 [ci-compare]: https://gist.github.com/brson/a30a77836fbec057cbee [fn-inherit]: https://github.com/rust-lang/rust/pull/23282 [fn-blanket]: https://github.com/rust-lang/rust/pull/23895 [copy-clone]: https://github.com/rust-lang/rust/pull/23860 [path-normalize]: https://github.com/rust-lang/rust/pull/23229 Version 1.0.0-alpha.2 (2015-02-20) ===================================== * ~1300 changes, numerous bugfixes * Highlights * The various I/O modules were [overhauled][io-rfc] to reduce unnecessary abstractions and provide better interoperation with the underlying platform. The old `io` module remains temporarily at `std::old_io`. * The standard library now [participates in feature gating][feat], so use of unstable libraries now requires a `#![feature(...)]` attribute. The impact of this change is [described on the forum][feat-forum]. [RFC][feat-rfc]. * Language * `for` loops [now operate on the `IntoIterator` trait][into], which eliminates the need to call `.iter()`, etc. to iterate over collections. There are some new subtleties to remember though regarding what sort of iterators various types yield, in particular that `for foo in bar { }` yields values from a move iterator, destroying the original collection. [RFC][into-rfc]. * Objects now have [default lifetime bounds][obj], so you don't have to write `Box<Trait+'static>` when you don't care about storing references. [RFC][obj-rfc]. * In types that implement `Drop`, [lifetimes must outlive the value][drop]. This will soon make it possible to safely implement `Drop` for types where `#[unsafe_destructor]` is now required. Read the [gorgeous RFC][drop-rfc] for details. * The fully qualified <T as Trait>::X syntax lets you set the Self type for a trait method or associated type. [RFC][ufcs-rfc]. * References to types that implement `Deref<U>` now [automatically coerce to references][deref] to the dereferenced type `U`, e.g. `&T where T: Deref<U>` automatically coerces to `&U`. This should eliminate many unsightly uses of `&*`, as when converting from references to vectors into references to slices. [RFC][deref-rfc]. * The explicit [closure kind syntax][close] (`|&:|`, `|&mut:|`, `|:|`) is obsolete and closure kind is inferred from context. * [`Self` is a keyword][Self]. * Libraries * The `Show` and `String` formatting traits [have been renamed][fmt] to `Debug` and `Display` to more clearly reflect their related purposes. Automatically getting a string conversion to use with `format!("{:?}", something_to_debug)` is now written `#[derive(Debug)]`. * Abstract [OS-specific string types][osstr], `std::ff::{OsString, OsStr}`, provide strings in platform-specific encodings for easier interop with system APIs. [RFC][osstr-rfc]. * The `boxed::into_raw` and `Box::from_raw` functions [convert between `Box<T>` and `*mut T`][boxraw], a common pattern for creating raw pointers. * Tooling * Certain long error messages of the form 'expected foo found bar' are now [split neatly across multiple lines][multiline]. Examples in the PR. * On Unix Rust can be [uninstalled][un] by running `/usr/local/lib/rustlib/uninstall.sh`. * The `#[rustc_on_unimplemented]` attribute, requiring the 'on_unimplemented' feature, lets rustc [display custom error messages when a trait is expected to be implemented for a type but is not][onun]. * Misc * Rust is tested against a [LALR grammar][lalr], which parses almost all the Rust files that rustc does. [boxraw]: https://github.com/rust-lang/rust/pull/21318 [close]: https://github.com/rust-lang/rust/pull/21843 [deref]: https://github.com/rust-lang/rust/pull/21351 [deref-rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0241-deref-conversions.md [drop]: https://github.com/rust-lang/rust/pull/21972 [drop-rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md [feat]: https://github.com/rust-lang/rust/pull/21248 [feat-forum]: https://users.rust-lang.org/t/psa-important-info-about-rustcs-new-feature-staging/82/5 [feat-rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0507-release-channels.md [fmt]: https://github.com/rust-lang/rust/pull/21457 [into]: https://github.com/rust-lang/rust/pull/20790 [into-rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0235-collections-conventions.md#intoiterator-and-iterable [io-rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0517-io-os-reform.md [lalr]: https://github.com/rust-lang/rust/pull/21452 [multiline]: https://github.com/rust-lang/rust/pull/19870 [obj]: https://github.com/rust-lang/rust/pull/22230 [obj-rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0599-default-object-bound.md [onun]: https://github.com/rust-lang/rust/pull/20889 [osstr]: https://github.com/rust-lang/rust/pull/21488 [osstr-rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0517-io-os-reform.md [Self]: https://github.com/rust-lang/rust/pull/22158 [ufcs-rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0132-ufcs.md [un]: https://github.com/rust-lang/rust/pull/22256 Version 1.0.0-alpha (2015-01-09) ================================== * ~2400 changes, numerous bugfixes * Highlights * The language itself is considered feature complete for 1.0, though there will be many usability improvements and bugfixes before the final release. * Nearly 50% of the public API surface of the standard library has been declared 'stable'. Those interfaces are unlikely to change before 1.0. * The long-running debate over integer types has been [settled][ints]: Rust will ship with types named `isize` and `usize`, rather than `int` and `uint`, for pointer-sized integers. Guidelines will be rolled out during the alpha cycle. * Most crates that are not `std` have been moved out of the Rust distribution into the Cargo ecosystem so they can evolve separately and don't need to be stabilized as quickly, including 'time', 'getopts', 'num', 'regex', and 'term'. * Documentation continues to be expanded with more API coverage, more examples, and more in-depth explanations. The guides have been consolidated into [The Rust Programming Language][trpl]. * "[Rust By Example][rbe]" is now maintained by the Rust team. * All official Rust binary installers now come with [Cargo], the Rust package manager. * Language * Closures have been [completely redesigned][unboxed] to be implemented in terms of traits, can now be used as generic type bounds and thus monomorphized and inlined, or via an opaque pointer (boxed) as in the old system. The new system is often referred to as 'unboxed' closures. * Traits now support [associated types][assoc], allowing families of related types to be defined together and used generically in powerful ways. * Enum variants are [namespaced by their type names][enum]. * [`where` clauses][where] provide a more versatile and attractive syntax for specifying generic bounds, though the previous syntax remains valid. * Rust again picks a [fallback][fb] (either i32 or f64) for uninferred numeric types. * Rust [no longer has a runtime][rt] of any description, and only supports OS threads, not green threads. * At long last, Rust has been overhauled for 'dynamically-sized types' ([DST]), which integrates 'fat pointers' (object types, arrays, and `str`) more deeply into the type system, making it more consistent. * Rust now has a general [range syntax][range], `i..j`, `i..`, and `..j` that produce range types and which, when combined with the `Index` operator and multidispatch, leads to a convenient slice notation, `[i..j]`. * The new range syntax revealed an ambiguity in the fixed-length array syntax, so now fixed length arrays [are written `[T; N]`][arrays]. * The `Copy` trait is no longer implemented automatically. Unsafe pointers no longer implement `Sync` and `Send` so types containing them don't automatically either. `Sync` and `Send` are now 'unsafe traits' so one can "forcibly" implement them via `unsafe impl` if a type confirms to the requirements for them even though the internals do not (e.g. structs containing unsafe pointers like `Arc`). These changes are intended to prevent some footguns and are collectively known as [opt-in built-in traits][oibit] (though `Sync` and `Send` will soon become pure library types unknown to the compiler). * Operator traits now take their operands [by value][ops], and comparison traits can use multidispatch to compare one type against multiple other types, allowing e.g. `String` to be compared with `&str`. * `if let` and `while let` are no longer feature-gated. * Rust has adopted a more [uniform syntax for escaping unicode characters][unicode]. * `macro_rules!` [has been declared stable][mac]. Though it is a flawed system it is sufficiently popular that it must be usable for 1.0. Effort has gone into [future-proofing][mac-future] it in ways that will allow other macro systems to be developed in parallel, and won't otherwise impact the evolution of the language. * The prelude has been [pared back significantly][prelude] such that it is the minimum necessary to support the most pervasive code patterns, and through [generalized where clauses][where] many of the prelude extension traits have been consolidated. * Rust's rudimentary reflection [has been removed][refl], as it incurred too much code generation for little benefit. * [Struct variants][structvars] are no longer feature-gated. * Trait bounds can be [polymorphic over lifetimes][hrtb]. Also known as 'higher-ranked trait bounds', this crucially allows unboxed closures to work. * Macros invocations surrounded by parens or square brackets and not terminated by a semicolon are [parsed as expressions][macros], which makes expressions like `vec![1i32, 2, 3].len()` work as expected. * Trait objects now implement their traits automatically, and traits that can be coerced to objects now must be [object safe][objsafe]. * Automatically deriving traits is now done with `#[derive(...)]` not `#[deriving(...)]` for [consistency with other naming conventions][derive]. * Importing the containing module or enum at the same time as items or variants they contain is [now done with `self` instead of `mod`][self], as in use `foo::{self, bar}` * Glob imports are no longer feature-gated. * The `box` operator and `box` patterns have been feature-gated pending a redesign. For now unique boxes should be allocated like other containers, with `Box::new`. * Libraries * A [series][coll1] of [efforts][coll2] to establish [conventions][coll3] for collections types has resulted in API improvements throughout the standard library. * New [APIs for error handling][err] provide ergonomic interop between error types, and [new conventions][err-conv] describe more clearly the recommended error handling strategies in Rust. * The `fail!` macro has been renamed to [`panic!`][panic] so that it is easier to discuss failure in the context of error handling without making clarifications as to whether you are referring to the 'fail' macro or failure more generally. * On Linux, `OsRng` prefers the new, more reliable `getrandom` syscall when available. * The 'serialize' crate has been renamed 'rustc-serialize' and moved out of the distribution to Cargo. Although it is widely used now, it is expected to be superseded in the near future. * The `Show` formatter, typically implemented with `#[derive(Show)]` is [now requested with the `{:?}` specifier][show] and is intended for use by all types, for uses such as `println!` debugging. The new `String` formatter must be implemented by hand, uses the `{}` specifier, and is intended for full-fidelity conversions of things that can logically be represented as strings. * Tooling * [Flexible target specification][flex] allows rustc's code generation to be configured to support otherwise-unsupported platforms. * Rust comes with rust-gdb and rust-lldb scripts that launch their respective debuggers with Rust-appropriate pretty-printing. * The Windows installation of Rust is distributed with the MinGW components currently required to link binaries on that platform. * Misc * Nullable enum optimizations have been extended to more types so that e.g. `Option<Vec<T>>` and `Option<String>` take up no more space than the inner types themselves. * Work has begun on supporting AArch64. [Cargo]: https://crates.io [unboxed]: http://smallcultfollowing.com/babysteps/blog/2014/11/26/purging-proc/ [enum]: https://github.com/rust-lang/rfcs/blob/master/text/0390-enum-namespacing.md [flex]: https://github.com/rust-lang/rfcs/blob/master/text/0131-target-specification.md [err]: https://github.com/rust-lang/rfcs/blob/master/text/0201-error-chaining.md [err-conv]: https://github.com/rust-lang/rfcs/blob/master/text/0236-error-conventions.md [rt]: https://github.com/rust-lang/rfcs/blob/master/text/0230-remove-runtime.md [mac]: https://github.com/rust-lang/rfcs/blob/master/text/0453-macro-reform.md [mac-future]: https://github.com/rust-lang/rfcs/pull/550 [DST]: http://smallcultfollowing.com/babysteps/blog/2014/01/05/dst-take-5/ [coll1]: https://github.com/rust-lang/rfcs/blob/master/text/0235-collections-conventions.md [coll2]: https://github.com/rust-lang/rfcs/blob/master/text/0509-collections-reform-part-2.md [coll3]: https://github.com/rust-lang/rfcs/blob/master/text/0216-collection-views.md [ops]: https://github.com/rust-lang/rfcs/blob/master/text/0439-cmp-ops-reform.md [prelude]: https://github.com/rust-lang/rfcs/blob/master/text/0503-prelude-stabilization.md [where]: https://github.com/rust-lang/rfcs/blob/master/text/0135-where.md [refl]: https://github.com/rust-lang/rfcs/blob/master/text/0379-remove-reflection.md [panic]: https://github.com/rust-lang/rfcs/blob/master/text/0221-panic.md [structvars]: https://github.com/rust-lang/rfcs/blob/master/text/0418-struct-variants.md [hrtb]: https://github.com/rust-lang/rfcs/blob/master/text/0387-higher-ranked-trait-bounds.md [unicode]: https://github.com/rust-lang/rfcs/blob/master/text/0446-es6-unicode-escapes.md [oibit]: https://github.com/rust-lang/rfcs/blob/master/text/0019-opt-in-builtin-traits.md [macros]: https://github.com/rust-lang/rfcs/blob/master/text/0378-expr-macros.md [range]: https://github.com/rust-lang/rfcs/blob/master/text/0439-cmp-ops-reform.md#indexing-and-slicing [arrays]: https://github.com/rust-lang/rfcs/blob/master/text/0520-new-array-repeat-syntax.md [show]: https://github.com/rust-lang/rfcs/blob/master/text/0504-show-stabilization.md [derive]: https://github.com/rust-lang/rfcs/blob/master/text/0534-deriving2derive.md [self]: https://github.com/rust-lang/rfcs/blob/master/text/0532-self-in-use.md [fb]: https://github.com/rust-lang/rfcs/blob/master/text/0212-restore-int-fallback.md [objsafe]: https://github.com/rust-lang/rfcs/blob/master/text/0255-object-safety.md [assoc]: https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md [ints]: https://github.com/rust-lang/rfcs/pull/544#issuecomment-68760871 [trpl]: https://doc.rust-lang.org/book/index.html [rbe]: http://rustbyexample.com/ Version 0.12.0 (2014-10-09) ============================= * ~1900 changes, numerous bugfixes * Highlights * The introductory documentation (now called The Rust Guide) has been completely rewritten, as have a number of supplementary guides. * Rust's package manager, Cargo, continues to improve and is sometimes considered to be quite awesome. * Many API's in `std` have been reviewed and updated for consistency with the in-development Rust coding guidelines. The standard library documentation tracks stabilization progress. * Minor libraries have been moved out-of-tree to the rust-lang org on GitHub: uuid, semver, glob, num, hexfloat, fourcc. They can be installed with Cargo. * Lifetime elision allows lifetime annotations to be left off of function declarations in many common scenarios. * Rust now works on 64-bit Windows. * Language * Indexing can be overloaded with the `Index` and `IndexMut` traits. * The `if let` construct takes a branch only if the `let` pattern matches, currently behind the 'if_let' feature gate. * 'where clauses', a more flexible syntax for specifying trait bounds that is more aesthetic, have been added for traits and free functions. Where clauses will in the future make it possible to constrain associated types, which would be impossible with the existing syntax. * A new slicing syntax (e.g. `[0..4]`) has been introduced behind the 'slicing_syntax' feature gate, and can be overloaded with the `Slice` or `SliceMut` traits. * The syntax for matching of sub-slices has been changed to use a postfix `..` instead of prefix (.e.g. `[a, b, c..]`), for consistency with other uses of `..` and to future-proof potential additional uses of the syntax. * The syntax for matching inclusive ranges in patterns has changed from `0..3` to `0...4` to be consistent with the exclusive range syntax for slicing. * Matching of sub-slices in non-tail positions (e.g. `[a.., b, c]`) has been put behind the 'advanced_slice_patterns' feature gate and may be removed in the future. * Components of tuples and tuple structs can be extracted using the `value.0` syntax, currently behind the `tuple_indexing` feature gate. * The `#[crate_id]` attribute is no longer supported; versioning is handled by the package manager. * Renaming crate imports are now written `extern crate foo as bar` instead of `extern crate bar = foo`. * Renaming use statements are now written `use foo as bar` instead of `use bar = foo`. * `let` and `match` bindings and argument names in macros are now hygienic. * The new, more efficient, closure types ('unboxed closures') have been added under a feature gate, 'unboxed_closures'. These will soon replace the existing closure types, once higher-ranked trait lifetimes are added to the language. * `move` has been added as a keyword, for indicating closures that capture by value. * Mutation and assignment is no longer allowed in pattern guards. * Generic structs and enums can now have trait bounds. * The `Share` trait is now called `Sync` to free up the term 'shared' to refer to 'shared reference' (the default reference type. * Dynamically-sized types have been mostly implemented, unifying the behavior of fat-pointer types with the rest of the type system. * As part of dynamically-sized types, the `Sized` trait has been introduced, which qualifying types implement by default, and which type parameters expect by default. To specify that a type parameter does not need to be sized, write `<Sized? T>`. Most types are `Sized`, notable exceptions being unsized arrays (`[T]`) and trait types. * Closures can return `!`, as in `|| -> !` or `proc() -> !`. * Lifetime bounds can now be applied to type parameters and object types. * The old, reference counted GC type, `Gc<T>` which was once denoted by the `@` sigil, has finally been removed. GC will be revisited in the future. * Libraries * Library documentation has been improved for a number of modules. * Bit-vectors, collections::bitv has been modernized. * The url crate is deprecated in favor of http://github.com/servo/rust-url, which can be installed with Cargo. * Most I/O stream types can be cloned and subsequently closed from a different thread. * A `std::time::Duration` type has been added for use in I/O methods that rely on timers, as well as in the 'time' crate's `Timespec` arithmetic. * The runtime I/O abstraction layer that enabled the green thread scheduler to do non-thread-blocking I/O has been removed, along with the libuv-based implementation employed by the green thread scheduler. This will greatly simplify the future I/O work. * `collections::btree` has been rewritten to have a more idiomatic and efficient design. * Tooling * rustdoc output now indicates the stability levels of API's. * The `--crate-name` flag can specify the name of the crate being compiled, like `#[crate_name]`. * The `-C metadata` specifies additional metadata to hash into symbol names, and `-C extra-filename` specifies additional information to put into the output filename, for use by the package manager for versioning. * debug info generation has continued to improve and should be more reliable under both gdb and lldb. * rustc has experimental support for compiling in parallel using the `-C codegen-units` flag. * rustc no longer encodes rpath information into binaries by default. * Misc * Stack usage has been optimized with LLVM lifetime annotations. * Official Rust binaries on Linux are more compatible with older kernels and distributions, built on CentOS 5.10. Version 0.11.0 (2014-07-02) ========================== * ~1700 changes, numerous bugfixes * Language * ~[T] has been removed from the language. This type is superseded by the Vec<T> type. * ~str has been removed from the language. This type is superseded by the String type. * ~T has been removed from the language. This type is superseded by the Box<T> type. * @T has been removed from the language. This type is superseded by the standard library's std::gc::Gc<T> type. * Struct fields are now all private by default. * Vector indices and shift amounts are both required to be a `uint` instead of any integral type. * Byte character, byte string, and raw byte string literals are now all supported by prefixing the normal literal with a `b`. * Multiple ABIs are no longer allowed in an ABI string * The syntax for lifetimes on closures/procedures has been tweaked slightly: `<'a>|A, B|: 'b + K -> T` * Floating point modulus has been removed from the language; however it is still provided by a library implementation. * Private enum variants are now disallowed. * The `priv` keyword has been removed from the language. * A closure can no longer be invoked through a &-pointer. * The `use foo, bar, baz;` syntax has been removed from the language. * The transmute intrinsic no longer works on type parameters. * Statics now allow blocks/items in their definition. * Trait bounds are separated from objects with + instead of : now. * Objects can no longer be read while they are mutably borrowed. * The address of a static is now marked as insignificant unless the #[inline(never)] attribute is placed it. * The #[unsafe_destructor] attribute is now behind a feature gate. * Struct literals are no longer allowed in ambiguous positions such as if, while, match, and for..in. * Declaration of lang items and intrinsics are now feature-gated by default. * Integral literals no longer default to `int`, and floating point literals no longer default to `f64`. Literals must be suffixed with an appropriate type if inference cannot determine the type of the literal. * The Box<T> type is no longer implicitly borrowed to &mut T. * Procedures are now required to not capture borrowed references. * Libraries * The standard library is now a "facade" over a number of underlying libraries. This means that development on the standard library should be speedier due to smaller crates, as well as a clearer line between all dependencies. * A new library, libcore, lives under the standard library's facade which is Rust's "0-assumption" library, suitable for embedded and kernel development for example. * A regex crate has been added to the standard distribution. This crate includes statically compiled regular expressions. * The unwrap/unwrap_err methods on Result require a Show bound for better error messages. * The return types of the std::comm primitives have been centralized around the Result type. * A number of I/O primitives have gained the ability to time out their operations. * A number of I/O primitives have gained the ability to close their reading/writing halves to cancel pending operations. * Reverse iterator methods have been removed in favor of `rev()` on their forward-iteration counterparts. * A bitflags! macro has been added to enable easy interop with C and management of bit flags. * A debug_assert! macro is now provided which is disabled when `--cfg ndebug` is passed to the compiler. * A graphviz crate has been added for creating .dot files. * The std::cast module has been migrated into std::mem. * The std::local_data api has been migrated from freestanding functions to being based on methods. * The Pod trait has been renamed to Copy. * jemalloc has been added as the default allocator for types. * The API for allocating memory has been changed to use proper alignment and sized deallocation * Connecting a TcpStream or binding a TcpListener is now based on a string address and a u16 port. This allows connecting to a hostname as opposed to an IP. * The Reader trait now contains a core method, read_at_least(), which correctly handles many repeated 0-length reads. * The process-spawning API is now centered around a builder-style Command struct. * The :? printing qualifier has been moved from the standard library to an external libdebug crate. * Eq/Ord have been renamed to PartialEq/PartialOrd. TotalEq/TotalOrd have been renamed to Eq/Ord. * The select/plural methods have been removed from format!. The escapes for { and } have also changed from \{ and \} to {{ and }}, respectively. * The TaskBuilder API has been re-worked to be a true builder, and extension traits for spawning native/green tasks have been added. * Tooling * All breaking changes to the language or libraries now have their commit message annotated with `[breaking-change]` to allow for easy discovery of breaking changes. * The compiler will now try to suggest how to annotate lifetimes if a lifetime-related error occurs. * Debug info continues to be improved greatly with general bug fixes and better support for situations like link time optimization (LTO). * Usage of syntax extensions when cross-compiling has been fixed. * Functionality equivalent to GCC & Clang's -ffunction-sections, -fdata-sections and --gc-sections has been enabled by default * The compiler is now stricter about where it will load module files from when a module is declared via `mod foo;`. * The #[phase(syntax)] attribute has been renamed to #[phase(plugin)]. Syntax extensions are now discovered via a "plugin registrar" type which will be extended in the future to other various plugins. * Lints have been restructured to allow for dynamically loadable lints. * A number of rustdoc improvements: * The HTML output has been visually redesigned. * Markdown is now powered by hoedown instead of sundown. * Searching heuristics have been greatly improved. * The search index has been reduced in size by a great amount. * Cross-crate documentation via `pub use` has been greatly improved. * Primitive types are now hyperlinked and documented. * Documentation has been moved from static.rust-lang.org/doc to doc.rust-lang.org * A new sandbox, play.rust-lang.org, is available for running and sharing rust code examples on-line. * Unused attributes are now more robustly warned about. * The dead_code lint now warns about unused struct fields. * Cross-compiling to iOS is now supported. * Cross-compiling to mipsel is now supported. * Stability attributes are now inherited by default and no longer apply to intra-crate usage, only inter-crate usage. * Error message related to non-exhaustive match expressions have been greatly improved. Version 0.10 (2014-04-03) ========================= * ~1500 changes, numerous bugfixes * Language * A new RFC process is now in place for modifying the language. * Patterns with `@`-pointers have been removed from the language. * Patterns with unique vectors (`~[T]`) have been removed from the language. * Patterns with unique strings (`~str`) have been removed from the language. * `@str` has been removed from the language. * `@[T]` has been removed from the language. * `@self` has been removed from the language. * `@Trait` has been removed from the language. * Headers on `~` allocations which contain `@` boxes inside the type for reference counting have been removed. * The semantics around the lifetimes of temporary expressions have changed, see #3511 and #11585 for more information. * Cross-crate syntax extensions are now possible, but feature gated. See #11151 for more information. This includes both `macro_rules!` macros as well as syntax extensions such as `format!`. * New lint modes have been added, and older ones have been turned on to be warn-by-default. * Unnecessary parentheses * Uppercase statics * Camel Case types * Uppercase variables * Publicly visible private types * `#[deriving]` with raw pointers * Unsafe functions can no longer be coerced to closures. * Various obscure macros such as `log_syntax!` are now behind feature gates. * The `#[simd]` attribute is now behind a feature gate. * Visibility is no longer allowed on `extern crate` statements, and unnecessary visibility (`priv`) is no longer allowed on `use` statements. * Trailing commas are now allowed in argument lists and tuple patterns. * The `do` keyword has been removed, it is now a reserved keyword. * Default type parameters have been implemented, but are feature gated. * Borrowed variables through captures in closures are now considered soundly. * `extern mod` is now `extern crate` * The `Freeze` trait has been removed. * The `Share` trait has been added for types that can be shared among threads. * Labels in macros are now hygienic. * Expression/statement macro invocations can be delimited with `{}` now. * Treatment of types allowed in `static mut` locations has been tweaked. * The `*` and `.` operators are now overloadable through the `Deref` and `DerefMut` traits. * `~Trait` and `proc` no longer have `Send` bounds by default. * Partial type hints are now supported with the `_` type marker. * An `Unsafe` type was introduced for interior mutability. It is now considered undefined to transmute from `&T` to `&mut T` without using the `Unsafe` type. * The #[linkage] attribute was implemented for extern statics/functions. * The inner attribute syntax has changed from `#[foo];` to `#![foo]`. * `Pod` was renamed to `Copy`. * Libraries * The `libextra` library has been removed. It has now been decomposed into component libraries with smaller and more focused nuggets of functionality. The full list of libraries can be found on the documentation index page. * std: `std::condition` has been removed. All I/O errors are now propagated through the `Result` type. In order to assist with error handling, a `try!` macro for unwrapping errors with an early return and a lint for unused results has been added. See #12039 for more information. * std: The `vec` module has been renamed to `slice`. * std: A new vector type, `Vec<T>`, has been added in preparation for DST. This will become the only growable vector in the future. * std: `std::io` now has more public re-exports. Types such as `BufferedReader` are now found at `std::io::BufferedReader` instead of `std::io::buffered::BufferedReader`. * std: `print` and `println` are no longer in the prelude, the `print!` and `println!` macros are intended to be used instead. * std: `Rc` now has a `Weak` pointer for breaking cycles, and it no longer attempts to statically prevent cycles. * std: The standard distribution is adopting the policy of pushing failure to the user rather than failing in libraries. Many functions (such as `slice::last()`) now return `Option<T>` instead of `T` + failing. * std: `fmt::Default` has been renamed to `fmt::Show`, and it now has a new deriving mode: `#[deriving(Show)]`. * std: `ToStr` is now implemented for all types implementing `Show`. * std: The formatting trait methods now take `&self` instead of `&T` * std: The `invert()` method on iterators has been renamed to `rev()` * std: `std::num` has seen a reduction in the genericity of its traits, consolidating functionality into a few core traits. * std: Backtraces are now printed on task failure if the environment variable `RUST_BACKTRACE` is present. * std: Naming conventions for iterators have been standardized. More details can be found on the wiki's style guide. * std: `eof()` has been removed from the `Reader` trait. Specific types may still implement the function. * std: Networking types are now cloneable to allow simultaneous reads/writes. * std: `assert_approx_eq!` has been removed * std: The `e` and `E` formatting specifiers for floats have been added to print them in exponential notation. * std: The `Times` trait has been removed * std: Indications of variance and opting out of builtin bounds is done through marker types in `std::kinds::marker` now * std: `hash` has been rewritten, `IterBytes` has been removed, and `#[deriving(Hash)]` is now possible. * std: `SharedChan` has been removed, `Sender` is now cloneable. * std: `Chan` and `Port` were renamed to `Sender` and `Receiver`. * std: `Chan::new` is now `channel()`. * std: A new synchronous channel type has been implemented. * std: A `select!` macro is now provided for selecting over `Receiver`s. * std: `hashmap` and `trie` have been moved to `libcollections` * std: `run` has been rolled into `io::process` * std: `assert_eq!` now uses `{}` instead of `{:?}` * std: The equality and comparison traits have seen some reorganization. * std: `rand` has moved to `librand`. * std: `to_{lower,upper}case` has been implemented for `char`. * std: Logging has been moved to `liblog`. * collections: `HashMap` has been rewritten for higher performance and less memory usage. * native: The default runtime is now `libnative`. If `libgreen` is desired, it can be booted manually. The runtime guide has more information and examples. * native: All I/O functionality except signals has been implemented. * green: Task spawning with `libgreen` has been optimized with stack caching and various trimming of code. * green: Tasks spawned by `libgreen` now have an unmapped guard page. * sync: The `extra::sync` module has been updated to modern rust (and moved to the `sync` library), tweaking and improving various interfaces while dropping redundant functionality. * sync: A new `Barrier` type has been added to the `sync` library. * sync: An efficient mutex for native and green tasks has been implemented. * serialize: The `base64` module has seen some improvement. It treats newlines better, has non-string error values, and has seen general cleanup. * fourcc: A `fourcc!` macro was introduced * hexfloat: A `hexfloat!` macro was implemented for specifying floats via a hexadecimal literal. * Tooling * `rustpkg` has been deprecated and removed from the main repository. Its replacement, `cargo`, is under development. * Nightly builds of rust are now available * The memory usage of rustc has been improved many times throughout this release cycle. * The build process supports disabling rpath support for the rustc binary itself. * Code generation has improved in some cases, giving more information to the LLVM optimization passes to enable more extensive optimizations. * Debuginfo compatibility with lldb on OSX has been restored. * The master branch is now gated on an android bot, making building for android much more reliable. * Output flags have been centralized into one `--emit` flag. * Crate type flags have been centralized into one `--crate-type` flag. * Codegen flags have been consolidated behind a `-C` flag. * Linking against outdated crates now has improved error messages. * Error messages with lifetimes will often suggest how to annotate the function to fix the error. * Many more types are documented in the standard library, and new guides were written. * Many `rustdoc` improvements: * code blocks are syntax highlighted. * render standalone markdown files. * the --test flag tests all code blocks by default. * exported macros are displayed. * re-exported types have their documentation inlined at the location of the first re-export. * search works across crates that have been rendered to the same output directory. Version 0.9 (2014-01-09) ========================== * ~1800 changes, numerous bugfixes * Language * The `float` type has been removed. Use `f32` or `f64` instead. * A new facility for enabling experimental features (feature gating) has been added, using the crate-level `#[feature(foo)]` attribute. * Managed boxes (@) are now behind a feature gate (`#[feature(managed_boxes)]`) in preparation for future removal. Use the standard library's `Gc` or `Rc` types instead. * `@mut` has been removed. Use `std::cell::{Cell, RefCell}` instead. * Jumping back to the top of a loop is now done with `continue` instead of `loop`. * Strings can no longer be mutated through index assignment. * Raw strings can be created via the basic `r"foo"` syntax or with matched hash delimiters, as in `r###"foo"###`. * `~fn` is now written `proc (args) -> retval { ... }` and may only be called once. * The `&fn` type is now written `|args| -> ret` to match the literal form. * `@fn`s have been removed. * `do` only works with procs in order to make it obvious what the cost of `do` is. * Single-element tuple-like structs can no longer be dereferenced to obtain the inner value. A more comprehensive solution for overloading the dereference operator will be provided in the future. * The `#[link(...)]` attribute has been replaced with `#[crate_id = "name#vers"]`. * Empty `impl`s must be terminated with empty braces and may not be terminated with a semicolon. * Keywords are no longer allowed as lifetime names; the `self` lifetime no longer has any special meaning. * The old `fmt!` string formatting macro has been removed. * `printf!` and `printfln!` (old-style formatting) removed in favor of `print!` and `println!`. * `mut` works in patterns now, as in `let (mut x, y) = (1, 2);`. * The `extern mod foo (name = "bar")` syntax has been removed. Use `extern mod foo = "bar"` instead. * New reserved keywords: `alignof`, `offsetof`, `sizeof`. * Macros can have attributes. * Macros can expand to items with attributes. * Macros can expand to multiple items. * The `asm!` macro is feature-gated (`#[feature(asm)]`). * Comments may be nested. * Values automatically coerce to trait objects they implement, without an explicit `as`. * Enum discriminants are no longer an entire word but as small as needed to contain all the variants. The `repr` attribute can be used to override the discriminant size, as in `#[repr(int)]` for integer-sized, and `#[repr(C)]` to match C enums. * Non-string literals are not allowed in attributes (they never worked). * The FFI now supports variadic functions. * Octal numeric literals, as in `0o7777`. * The `concat!` syntax extension performs compile-time string concatenation. * The `#[fixed_stack_segment]` and `#[rust_stack]` attributes have been removed as Rust no longer uses segmented stacks. * Non-ascii identifiers are feature-gated (`#[feature(non_ascii_idents)]`). * Ignoring all fields of an enum variant or tuple-struct is done with `..`, not `*`; ignoring remaining fields of a struct is also done with `..`, not `_`; ignoring a slice of a vector is done with `..`, not `.._`. * `rustc` supports the "win64" calling convention via `extern "win64"`. * `rustc` supports the "system" calling convention, which defaults to the preferred convention for the target platform, "stdcall" on 32-bit Windows, "C" elsewhere. * The `type_overflow` lint (default: warn) checks literals for overflow. * The `unsafe_block` lint (default: allow) checks for usage of `unsafe`. * The `attribute_usage` lint (default: warn) warns about unknown attributes. * The `unknown_features` lint (default: warn) warns about unknown feature gates. * The `dead_code` lint (default: warn) checks for dead code. * Rust libraries can be linked statically to one another * `#[link_args]` is behind the `link_args` feature gate. * Native libraries are now linked with `#[link(name = "foo")]` * Native libraries can be statically linked to a rust crate (`#[link(name = "foo", kind = "static")]`). * Native OS X frameworks are now officially supported (`#[link(name = "foo", kind = "framework")]`). * The `#[thread_local]` attribute creates thread-local (not task-local) variables. Currently behind the `thread_local` feature gate. * The `return` keyword may be used in closures. * Types that can be copied via a memcpy implement the `Pod` kind. * The `cfg` attribute can now be used on struct fields and enum variants. * Libraries * std: The `option` and `result` API's have been overhauled to make them simpler, more consistent, and more composable. * std: The entire `std::io` module has been replaced with one that is more comprehensive and that properly interfaces with the underlying scheduler. File, TCP, UDP, Unix sockets, pipes, and timers are all implemented. * std: `io::util` contains a number of useful implementations of `Reader` and `Writer`, including `NullReader`, `NullWriter`, `ZeroReader`, `TeeReader`. * std: The reference counted pointer type `extra::rc` moved into std. * std: The `Gc` type in the `gc` module will replace `@` (it is currently just a wrapper around it). * std: The `Either` type has been removed. * std: `fmt::Default` can be implemented for any type to provide default formatting to the `format!` macro, as in `format!("{}", myfoo)`. * std: The `rand` API continues to be tweaked. * std: The `rust_begin_unwind` function, useful for inserting breakpoints on failure in gdb, is now named `rust_fail`. * std: The `each_key` and `each_value` methods on `HashMap` have been replaced by the `keys` and `values` iterators. * std: Functions dealing with type size and alignment have moved from the `sys` module to the `mem` module. * std: The `path` module was written and API changed. * std: `str::from_utf8` has been changed to cast instead of allocate. * std: `starts_with` and `ends_with` methods added to vectors via the `ImmutableEqVector` trait, which is in the prelude. * std: Vectors can be indexed with the `get_opt` method, which returns `None` if the index is out of bounds. * std: Task failure no longer propagates between tasks, as the model was complex, expensive, and incompatible with thread-based tasks. * std: The `Any` type can be used for dynamic typing. * std: `~Any` can be passed to the `fail!` macro and retrieved via `task::try`. * std: Methods that produce iterators generally do not have an `_iter` suffix now. * std: `cell::Cell` and `cell::RefCell` can be used to introduce mutability roots (mutable fields, etc.). Use instead of e.g. `@mut`. * std: `util::ignore` renamed to `prelude::drop`. * std: Slices have `sort` and `sort_by` methods via the `MutableVector` trait. * std: `vec::raw` has seen a lot of cleanup and API changes. * std: The standard library no longer includes any C++ code, and very minimal C, eliminating the dependency on libstdc++. * std: Runtime scheduling and I/O functionality has been factored out into extensible interfaces and is now implemented by two different crates: libnative, for native threading and I/O; and libgreen, for green threading and I/O. This paves the way for using the standard library in more limited embedded environments. * std: The `comm` module has been rewritten to be much faster, have a simpler, more consistent API, and to work for both native and green threading. * std: All libuv dependencies have been moved into the rustuv crate. * native: New implementations of runtime scheduling on top of OS threads. * native: New native implementations of TCP, UDP, file I/O, process spawning, and other I/O. * green: The green thread scheduler and message passing types are almost entirely lock-free. * extra: The `flatpipes` module had bitrotted and was removed. * extra: All crypto functions have been removed and Rust now has a policy of not reimplementing crypto in the standard library. In the future crypto will be provided by external crates with bindings to established libraries. * extra: `c_vec` has been modernized. * extra: The `sort` module has been removed. Use the `sort` method on mutable slices. * Tooling * The `rust` and `rusti` commands have been removed, due to lack of maintenance. * `rustdoc` was completely rewritten. * `rustdoc` can test code examples in documentation. * `rustpkg` can test packages with the argument, 'test'. * `rustpkg` supports arbitrary dependencies, including C libraries. * `rustc`'s support for generating debug info is improved again. * `rustc` has better error reporting for unbalanced delimiters. * `rustc`'s JIT support was removed due to bitrot. * Executables and static libraries can be built with LTO (-Z lto) * `rustc` adds a `--dep-info` flag for communicating dependencies to build tools. Version 0.8 (2013-09-26) ============================ * ~2200 changes, numerous bugfixes * Language * The `for` loop syntax has changed to work with the `Iterator` trait. * At long last, unwinding works on Windows. * Default methods are ready for use. * Many trait inheritance bugs fixed. * Owned and borrowed trait objects work more reliably. * `copy` is no longer a keyword. It has been replaced by the `Clone` trait. * rustc can omit emission of code for the `debug!` macro if it is passed `--cfg ndebug` * mod.rs is now "blessed". When loading `mod foo;`, rustc will now look for foo.rs, then foo/mod.rs, and will generate an error when both are present. * Strings no longer contain trailing nulls. The new `std::c_str` module provides new mechanisms for converting to C strings. * The type of foreign functions is now `extern "C" fn` instead of `*u8'. * The FFI has been overhauled such that foreign functions are called directly, instead of through a stack-switching wrapper. * Calling a foreign function must be done through a Rust function with the `#[fixed_stack_segment]` attribute. * The `externfn!` macro can be used to declare both a foreign function and a `#[fixed_stack_segment]` wrapper at once. * `pub` and `priv` modifiers on `extern` blocks are no longer parsed. * `unsafe` is no longer allowed on extern fns - they are all unsafe. * `priv` is disallowed everywhere except for struct fields and enum variants. * `&T` (besides `&'static T`) is no longer allowed in `@T`. * `ref` bindings in irrefutable patterns work correctly now. * `char` is now prevented from containing invalid code points. * Casting to `bool` is no longer allowed. * `\0` is now accepted as an escape in chars and strings. * `yield` is a reserved keyword. * `typeof` is a reserved keyword. * Crates may be imported by URL with `extern mod foo = "url";`. * Explicit enum discriminants may be given as uints as in `enum E { V = 0u }` * Static vectors can be initialized with repeating elements, e.g. `static foo: [u8, .. 100]: [0, .. 100];`. * Static structs can be initialized with functional record update, e.g. `static foo: Foo = Foo { a: 5, .. bar };`. * `cfg!` can be used to conditionally execute code based on the crate configuration, similarly to `#[cfg(...)]`. * The `unnecessary_qualification` lint detects unneeded module prefixes (default: allow). * Arithmetic operations have been implemented on the SIMD types in `std::unstable::simd`. * Exchange allocation headers were removed, reducing memory usage. * `format!` implements a completely new, extensible, and higher-performance string formatting system. It will replace `fmt!`. * `print!` and `println!` write formatted strings (using the `format!` extension) to stdout. * `write!` and `writeln!` write formatted strings (using the `format!` extension) to the new Writers in `std::rt::io`. * The library section in which a function or static is placed may be specified with `#[link_section = "..."]`. * The `proto!` syntax extension for defining bounded message protocols was removed. * `macro_rules!` is hygienic for `let` declarations. * The `#[export_name]` attribute specifies the name of a symbol. * `unreachable!` can be used to indicate unreachable code, and fails if executed. * Libraries * std: Transitioned to the new runtime, written in Rust. * std: Added an experimental I/O library, `rt::io`, based on the new runtime. * std: A new generic `range` function was added to the prelude, replacing `uint::range` and friends. * std: `range_rev` no longer exists. Since range is an iterator it can be reversed with `range(lo, hi).invert()`. * std: The `chain` method on option renamed to `and_then`; `unwrap_or_default` renamed to `unwrap_or`. * std: The `iterator` module was renamed to `iter`. * std: Integral types now support the `checked_add`, `checked_sub`, and `checked_mul` operations for detecting overflow. * std: Many methods in `str`, `vec`, `option, `result` were renamed for consistency. * std: Methods are standardizing on conventions for casting methods: `to_foo` for copying, `into_foo` for moving, `as_foo` for temporary and cheap casts. * std: The `CString` type in `c_str` provides new ways to convert to and from C strings. * std: `DoubleEndedIterator` can yield elements in two directions. * std: The `mut_split` method on vectors partitions an `&mut [T]` into two splices. * std: `str::from_bytes` renamed to `str::from_utf8`. * std: `pop_opt` and `shift_opt` methods added to vectors. * std: The task-local data interface no longer uses @, and keys are no longer function pointers. * std: The `swap_unwrap` method of `Option` renamed to `take_unwrap`. * std: Added `SharedPort` to `comm`. * std: `Eq` has a default method for `ne`; only `eq` is required in implementations. * std: `Ord` has default methods for `le`, `gt` and `ge`; only `lt` is required in implementations. * std: `is_utf8` performance is improved, impacting many string functions. * std: `os::MemoryMap` provides cross-platform mmap. * std: `ptr::offset` is now unsafe, but also more optimized. Offsets that are not 'in-bounds' are considered undefined. * std: Many freestanding functions in `vec` removed in favor of methods. * std: Many freestanding functions on scalar types removed in favor of methods. * std: Many options to task builders were removed since they don't make sense in the new scheduler design. * std: More containers implement `FromIterator` so can be created by the `collect` method. * std: More complete atomic types in `unstable::atomics`. * std: `comm::PortSet` removed. * std: Mutating methods in the `Set` and `Map` traits have been moved into the `MutableSet` and `MutableMap` traits. `Container::is_empty`, `Map::contains_key`, `MutableMap::insert`, and `MutableMap::remove` have default implementations. * std: Various `from_str` functions were removed in favor of a generic `from_str` which is available in the prelude. * std: `util::unreachable` removed in favor of the `unreachable!` macro. * extra: `dlist`, the doubly-linked list was modernized. * extra: Added a `hex` module with `ToHex` and `FromHex` traits. * extra: Added `glob` module, replacing `std::os::glob`. * extra: `rope` was removed. * extra: `deque` was renamed to `ringbuf`. `RingBuf` implements `Deque`. * extra: `net`, and `timer` were removed. The experimental replacements are `std::rt::io::net` and `std::rt::io::timer`. * extra: Iterators implemented for `SmallIntMap`. * extra: Iterators implemented for `Bitv` and `BitvSet`. * extra: `SmallIntSet` removed. Use `BitvSet`. * extra: Performance of JSON parsing greatly improved. * extra: `semver` updated to SemVer 2.0.0. * extra: `term` handles more terminals correctly. * extra: `dbg` module removed. * extra: `par` module removed. * extra: `future` was cleaned up, with some method renames. * extra: Most free functions in `getopts` were converted to methods. * Other * rustc's debug info generation (`-Z debug-info`) is greatly improved. * rustc accepts `--target-cpu` to compile to a specific CPU architecture, similarly to gcc's `--march` flag. * rustc's performance compiling small crates is much better. * rustpkg has received many improvements. * rustpkg supports git tags as package IDs. * rustpkg builds into target-specific directories so it can be used for cross-compiling. * The number of concurrent test tasks is controlled by the environment variable RUST_TEST_TASKS. * The test harness can now report metrics for benchmarks. * All tools have man pages. * Programs compiled with `--test` now support the `-h` and `--help` flags. * The runtime uses jemalloc for allocations. * Segmented stacks are temporarily disabled as part of the transition to the new runtime. Stack overflows are possible! * A new documentation backend, rustdoc_ng, is available for use. It is still invoked through the normal `rustdoc` command. Version 0.7 (2013-07-03) ======================= * ~2000 changes, numerous bugfixes * Language * `impl`s no longer accept a visibility qualifier. Put them on methods instead. * The borrow checker has been rewritten with flow-sensitivity, fixing many bugs and inconveniences. * The `self` parameter no longer implicitly means `&'self self`, and can be explicitly marked with a lifetime. * Overloadable compound operators (`+=`, etc.) have been temporarily removed due to bugs. * The `for` loop protocol now requires `for`-iterators to return `bool` so they compose better. * The `Durable` trait is replaced with the `'static` bounds. * Trait default methods work more often. * Structs with the `#[packed]` attribute have byte alignment and no padding between fields. * Type parameters bound by `Copy` must now be copied explicitly with the `copy` keyword. * It is now illegal to move out of a dereferenced unsafe pointer. * `Option<~T>` is now represented as a nullable pointer. * `@mut` does dynamic borrow checks correctly. * The `main` function is only detected at the topmost level of the crate. The `#[main]` attribute is still valid anywhere. * Struct fields may no longer be mutable. Use inherited mutability. * The `#[no_send]` attribute makes a type that would otherwise be `Send`, not. * The `#[no_freeze]` attribute makes a type that would otherwise be `Freeze`, not. * Unbounded recursion will abort the process after reaching the limit specified by the `RUST_MAX_STACK` environment variable (default: 1GB). * The `vecs_implicitly_copyable` lint mode has been removed. Vectors are never implicitly copyable. * `#[static_assert]` makes compile-time assertions about static bools. * At long last, 'argument modes' no longer exist. * The rarely used `use mod` statement no longer exists. * Syntax extensions * `fail!` and `assert!` accept `~str`, `&'static str` or `fmt!`-style argument list. * `Encodable`, `Decodable`, `Ord`, `TotalOrd`, `TotalEq`, `DeepClone`, `Rand`, `Zero` and `ToStr` can all be automatically derived with `#[deriving(...)]`. * The `bytes!` macro returns a vector of bytes for string, u8, char, and unsuffixed integer literals. * Libraries * The `core` crate was renamed to `std`. * The `std` crate was renamed to `extra`. * More and improved documentation. * std: `iterator` module for external iterator objects. * Many old-style (internal, higher-order function) iterators replaced by implementations of `Iterator`. * std: Many old internal vector and string iterators, incl. `any`, `all`. removed. * std: The `finalize` method of `Drop` renamed to `drop`. * std: The `drop` method now takes `&mut self` instead of `&self`. * std: The prelude no longer re-exports any modules, only types and traits. * std: Prelude additions: `print`, `println`, `FromStr`, `ApproxEq`, `Equiv`, `Iterator`, `IteratorUtil`, many numeric traits, many tuple traits. * std: New numeric traits: `Fractional`, `Real`, `RealExt`, `Integer`, `Ratio`, `Algebraic`, `Trigonometric`, `Exponential`, `Primitive`. * std: Tuple traits and accessors defined for up to 12-tuples, e.g. `(0, 1, 2).n2()` or `(0, 1, 2).n2_ref()`. * std: Many types implement `Clone`. * std: `path` type renamed to `Path`. * std: `mut` module and `Mut` type removed. * std: Many standalone functions removed in favor of methods and iterators in `vec`, `str`. In the future methods will also work as functions. * std: `reinterpret_cast` removed. Use `transmute`. * std: ascii string handling in `std::ascii`. * std: `Rand` is implemented for ~/@. * std: `run` module for spawning processes overhauled. * std: Various atomic types added to `unstable::atomic`. * std: Various types implement `Zero`. * std: `LinearMap` and `LinearSet` renamed to `HashMap` and `HashSet`. * std: Borrowed pointer functions moved from `ptr` to `borrow`. * std: Added `os::mkdir_recursive`. * std: Added `os::glob` function performs filesystems globs. * std: `FuzzyEq` renamed to `ApproxEq`. * std: `Map` now defines `pop` and `swap` methods. * std: `Cell` constructors converted to static methods. * extra: `rc` module adds the reference counted pointers, `Rc` and `RcMut`. * extra: `flate` module moved from `std` to `extra`. * extra: `fileinput` module for iterating over a series of files. * extra: `Complex` number type and `complex` module. * extra: `Rational` number type and `rational` module. * extra: `BigInt`, `BigUint` implement numeric and comparison traits. * extra: `term` uses terminfo now, is more correct. * extra: `arc` functions converted to methods. * extra: Implementation of fixed output size variations of SHA-2. * Tooling * `unused_variables` lint mode for unused variables (default: warn). * `unused_unsafe` lint mode for detecting unnecessary `unsafe` blocks (default: warn). * `unused_mut` lint mode for identifying unused `mut` qualifiers (default: warn). * `dead_assignment` lint mode for unread variables (default: warn). * `unnecessary_allocation` lint mode detects some heap allocations that are immediately borrowed so could be written without allocating (default: warn). * `missing_doc` lint mode (default: allow). * `unreachable_code` lint mode (default: warn). * The `rusti` command has been rewritten and a number of bugs addressed. * rustc outputs in color on more terminals. * rustc accepts a `--link-args` flag to pass arguments to the linker. * rustc accepts a `-Z print-link-args` flag for debugging linkage. * Compiling with `-g` will make the binary record information about dynamic borrowcheck failures for debugging. * rustdoc has a nicer stylesheet. * Various improvements to rustdoc. * Improvements to rustpkg (see the detailed release notes). Version 0.6 (2013-04-03) ======================== * ~2100 changes, numerous bugfixes * Syntax changes * The self type parameter in traits is now spelled `Self` * The `self` parameter in trait and impl methods must now be explicitly named (for example: `fn f(&self) { }`). Implicit self is deprecated. * Static methods no longer require the `static` keyword and instead are distinguished by the lack of a `self` parameter * Replaced the `Durable` trait with the `'static` lifetime * The old closure type syntax with the trailing sigil has been removed in favor of the more consistent leading sigil * `super` is a keyword, and may be prefixed to paths * Trait bounds are separated with `+` instead of whitespace * Traits are implemented with `impl Trait for Type` instead of `impl Type: Trait` * Lifetime syntax is now `&'l foo` instead of `&l/foo` * The `export` keyword has finally been removed * The `move` keyword has been removed (see "Semantic changes") * The interior mutability qualifier on vectors, `[mut T]`, has been removed. Use `&mut [T]`, etc. * `mut` is no longer valid in `~mut T`. Use inherited mutability * `fail` is no longer a keyword. Use `fail!()` * `assert` is no longer a keyword. Use `assert!()` * `log` is no longer a keyword. use `debug!`, etc. * 1-tuples may be represented as `(T,)` * Struct fields may no longer be `mut`. Use inherited mutability, `@mut T`, `core::mut` or `core::cell` * `extern mod { ... }` is no longer valid syntax for foreign function modules. Use extern blocks: `extern { ... }` * Newtype enums removed. Use tuple-structs. * Trait implementations no longer support visibility modifiers * Pattern matching over vectors improved and expanded * `const` renamed to `static` to correspond to lifetime name, and make room for future `static mut` unsafe mutable globals. * Replaced `#[deriving_eq]` with `#[deriving(Eq)]`, etc. * `Clone` implementations can be automatically generated with `#[deriving(Clone)]` * Casts to traits must use a pointer sigil, e.g. `@foo as @Bar` instead of `foo as Bar`. * Fixed length vector types are now written as `[int, .. 3]` instead of `[int * 3]`. * Fixed length vector types can express the length as a constant expression. (ex: `[int, .. GL_BUFFER_SIZE - 2]`) * Semantic changes * Types with owned pointers or custom destructors move by default, eliminating the `move` keyword * All foreign functions are considered unsafe * &mut is now unaliasable * Writes to borrowed @mut pointers are prevented dynamically * () has size 0 * The name of the main function can be customized using #[main] * The default type of an inferred closure is &fn instead of @fn * `use` statements may no longer be "chained" - they cannot import identifiers imported by previous `use` statements * `use` statements are crate relative, importing from the "top" of the crate by default. Paths may be prefixed with `super::` or `self::` to change the search behavior. * Method visibility is inherited from the implementation declaration * Structural records have been removed * Many more types can be used in static items, including enums 'static-lifetime pointers and vectors * Pattern matching over vectors improved and expanded * Typechecking of closure types has been overhauled to improve inference and eliminate unsoundness * Macros leave scope at the end of modules, unless that module is tagged with #[macro_escape] * Libraries * Added big integers to `std::bigint` * Removed `core::oldcomm` module * Added pipe-based `core::comm` module * Numeric traits have been reorganized under `core::num` * `vec::slice` finally returns a slice * `debug!` and friends don't require a format string, e.g. `debug!(Foo)` * Containers reorganized around traits in `core::container` * `core::dvec` removed, `~[T]` is a drop-in replacement * `core::send_map` renamed to `core::hashmap` * `std::map` removed; replaced with `core::hashmap` * `std::treemap` reimplemented as an owned balanced tree * `std::deque` and `std::smallintmap` reimplemented as owned containers * `core::trie` added as a fast ordered map for integer keys * Set types added to `core::hashmap`, `core::trie` and `std::treemap` * `Ord` split into `Ord` and `TotalOrd`. `Ord` is still used to overload the comparison operators, whereas `TotalOrd` is used by certain container types * Other * Replaced the 'cargo' package manager with 'rustpkg' * Added all-purpose 'rust' tool * `rustc --test` now supports benchmarks with the `#[bench]` attribute * rustc now *attempts* to offer spelling suggestions * Improved support for ARM and Android * Preliminary MIPS backend * Improved foreign function ABI implementation for x86, x86_64 * Various memory usage improvements * Rust code may be embedded in foreign code under limited circumstances * Inline assembler supported by new asm!() syntax extension. Version 0.5 (2012-12-21) =========================== * ~900 changes, numerous bugfixes * Syntax changes * Removed `<-` move operator * Completed the transition from the `#fmt` extension syntax to `fmt!` * Removed old fixed length vector syntax - `[T]/N` * New token-based quasi-quoters, `quote_tokens!`, `quote_expr!`, etc. * Macros may now expand to items and statements * `a.b()` is always parsed as a method call, never as a field projection * `Eq` and `IterBytes` implementations can be automatically generated with `#[deriving_eq]` and `#[deriving_iter_bytes]` respectively * Removed the special crate language for `.rc` files * Function arguments may consist of any irrefutable pattern * Semantic changes * `&` and `~` pointers may point to objects * Tuple structs - `struct Foo(Bar, Baz)`. Will replace newtype enums. * Enum variants may be structs * Destructors can be added to all nominal types with the Drop trait * Structs and nullary enum variants may be constants * Values that cannot be implicitly copied are now automatically moved without writing `move` explicitly * `&T` may now be coerced to `*T` * Coercions happen in `let` statements as well as function calls * `use` statements now take crate-relative paths * The module and type namespaces have been merged so that static method names can be resolved under the trait in which they are declared * Improved support for language features * Trait inheritance works in many scenarios * More support for explicit self arguments in methods - `self`, `&self` `@self`, and `~self` all generally work as expected * Static methods work in more situations * Experimental: Traits may declare default methods for the implementations to use * Libraries * New condition handling system in `core::condition` * Timsort added to `std::sort` * New priority queue, `std::priority_queue` * Pipes for serializable types, `std::flatpipes' * Serialization overhauled to be trait-based * Expanded `getopts` definitions * Moved futures to `std` * More functions are pure now * `core::comm` renamed to `oldcomm`. Still deprecated * `rustdoc` and `cargo` are libraries now * Misc * Added a preliminary REPL, `rusti` * License changed from MIT to dual MIT/APL2 Version 0.4 (2012-10-15) ========================== * ~2000 changes, numerous bugfixes * Syntax * All keywords are now strict and may not be used as identifiers anywhere * Keyword removal: 'again', 'import', 'check', 'new', 'owned', 'send', 'of', 'with', 'to', 'class'. * Classes are replaced with simpler structs * Explicit method self types * `ret` became `return` and `alt` became `match` * `import` is now `use`; `use is now `extern mod` * `extern mod { ... }` is now `extern { ... }` * `use mod` is the recommended way to import modules * `pub` and `priv` replace deprecated export lists * The syntax of `match` pattern arms now uses fat arrow (=>) * `main` no longer accepts an args vector; use `os::args` instead * Semantics * Trait implementations are now coherent, ala Haskell typeclasses * Trait methods may be static * Argument modes are deprecated * Borrowed pointers are much more mature and recommended for use * Strings and vectors in the static region are stored in constant memory * Typestate was removed * Resolution rewritten to be more reliable * Support for 'dual-mode' data structures (freezing and thawing) * Libraries * Most binary operators can now be overloaded via the traits in `core::ops' * `std::net::url` for representing URLs * Sendable hash maps in `core::send_map` * `core::task' gained a (currently unsafe) task-local storage API * Concurrency * An efficient new intertask communication primitive called the pipe, along with a number of higher-level channel types, in `core::pipes` * `std::arc`, an atomically reference counted, immutable, shared memory type * `std::sync`, various exotic synchronization tools based on arcs and pipes * Futures are now based on pipes and sendable * More robust linked task failure * Improved task builder API * Other * Improved error reporting * Preliminary JIT support * Preliminary work on precise GC * Extensive architectural improvements to rustc * Begun a transition away from buggy C++-based reflection (shape) code to Rust-based (visitor) code * All hash functions and tables converted to secure, randomized SipHash Version 0.3 (2012-07-12) ======================== * ~1900 changes, numerous bugfixes * New coding conveniences * Integer-literal suffix inference * Per-item control over warnings, errors * #[cfg(windows)] and #[cfg(unix)] attributes * Documentation comments * More compact closure syntax * 'do' expressions for treating higher-order functions as control structures * *-patterns (wildcard extended to all constructor fields) * Semantic cleanup * Name resolution pass and exhaustiveness checker rewritten * Region pointers and borrow checking supersede alias analysis * Init-ness checking is now provided by a region-based liveness pass instead of the typestate pass; same for last-use analysis * Extensive work on region pointers * Experimental new language features * Slices and fixed-size, interior-allocated vectors * #!-comments for lang versioning, shell execution * Destructors and iface implementation for classes; type-parameterized classes and class methods * 'const' type kind for types that can be used to implement shared-memory concurrency patterns * Type reflection * Removal of various obsolete features * Keywords: 'be', 'prove', 'syntax', 'note', 'mutable', 'bind', 'crust', 'native' (now 'extern'), 'cont' (now 'again') * Constructs: do-while loops ('do' repurposed), fn binding, resources (replaced by destructors) * Compiler reorganization * Syntax-layer of compiler split into separate crate * Clang (from LLVM project) integrated into build * Typechecker split into sub-modules * New library code * New time functions * Extension methods for many built-in types * Arc: atomic-refcount read-only / exclusive-use shared cells * Par: parallel map and search routines * Extensive work on libuv interface * Much vector code moved to libraries * Syntax extensions: #line, #col, #file, #mod, #stringify, #include, #include_str, #include_bin * Tool improvements * Cargo automatically resolves dependencies Version 0.2 (2012-03-29) ========================= * >1500 changes, numerous bugfixes * New docs and doc tooling * New port: FreeBSD x86_64 * Compilation model enhancements * Generics now specialized, multiply instantiated * Functions now inlined across separate crates * Scheduling, stack and threading fixes * Noticeably improved message-passing performance * Explicit schedulers * Callbacks from C * Helgrind clean * Experimental new language features * Operator overloading * Region pointers * Classes * Various language extensions * C-callback function types: 'crust fn ...' * Infinite-loop construct: 'loop { ... }' * Shorten 'mutable' to 'mut' * Required mutable-local qualifier: 'let mut ...' * Basic glob-exporting: 'export foo::*;' * Alt now exhaustive, 'alt check' for runtime-checked * Block-function form of 'for' loop, with 'break' and 'ret'. * New library code * AST quasi-quote syntax extension * Revived libuv interface * New modules: core::{future, iter}, std::arena * Merged per-platform std::{os*, fs*} to core::{libc, os} * Extensive cleanup, regularization in libstd, libcore Version 0.1 (2012-01-20) =============================== * Most language features work, including: * Unique pointers, unique closures, move semantics * Interface-constrained generics * Static interface dispatch * Stack growth * Multithread task scheduling * Typestate predicates * Failure unwinding, destructors * Pattern matching and destructuring assignment * Lightweight block-lambda syntax * Preliminary macro-by-example * Compiler works with the following configurations: * Linux: x86 and x86_64 hosts and targets * macOS: x86 and x86_64 hosts and targets * Windows: x86 hosts and targets * Cross compilation / multi-target configuration supported. * Preliminary API-documentation and package-management tools included. Known issues: * Documentation is incomplete. * Performance is below intended target. * Standard library APIs are subject to extensive change, reorganization. * Language-level versioning is not yet operational - future code will break unexpectedly.
unknown
github
https://github.com/rust-lang/rust
RELEASES.md
# Copyright (C) 2010-2014 GRNET S.A. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from django.conf.urls import patterns, include from snf_django.lib.api.utils import prefix_pattern from snf_django.lib.api import api_endpoint_not_found from synnefo_stats.stats_settings import BASE_PATH from synnefo_stats.grapher import grapher graph_types_re = '((cpu|net)-(bar|(ts(-w)?)))' stats_v1_patterns = patterns( '', (r'^(?P<graph_type>%s)/(?P<hostname>[^ /]+)$' % graph_types_re, grapher), ) stats_patterns = patterns( '', (r'^v1.0/', include(stats_v1_patterns)), (r'^.*', api_endpoint_not_found), ) urlpatterns = patterns( '', (prefix_pattern(BASE_PATH), include(stats_patterns)), )
unknown
codeparrot/codeparrot-clean
{ "html": { "type": "Fragment", "start": 0, "end": 41, "children": [ { "type": "EachBlock", "start": 0, "end": 41, "children": [ { "type": "Element", "start": 22, "end": 33, "name": "p", "attributes": [], "children": [ { "type": "MustacheTag", "start": 25, "end": 29, "expression": { "type": "Identifier", "start": 26, "end": 28, "loc": { "start": { "line": 2, "column": 5 }, "end": { "line": 2, "column": 7 } }, "name": "𐊧" } } ] } ], "context": { "type": "Identifier", "name": "𐊧", "start": 17, "end": 19, "loc": { "start": { "line": 1, "column": 17, "character": 17 }, "end": { "line": 1, "column": 19, "character": 19 } } }, "expression": { "type": "Identifier", "start": 7, "end": 13, "loc": { "start": { "line": 1, "column": 7 }, "end": { "line": 1, "column": 13 } }, "name": "things" } } ] } }
json
github
https://github.com/sveltejs/svelte
packages/svelte/tests/parser-legacy/samples/unusual-identifier/output.json
<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>columns.name</th> <th>0</th> <th>1</th> </tr> </thead> <tbody> <tr> <th rowspan="2" valign="top">a</th> <th>b</th> <td>0</td> <td>0</td> </tr> <tr> <th>c</th> <td>0</td> <td>0</td> </tr> </tbody> </table>
html
github
https://github.com/pandas-dev/pandas
pandas/tests/io/formats/data/html/index_unnamed_multi_columns_named_standard.html
// run // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Test methods on slices. package main type T []int func (t T) Len() int { return len(t) } type I interface { Len() int } func main() { var t T = T{0, 1, 2, 3, 4} var i I i = t if i.Len() != 5 { println("i.Len", i.Len()) panic("fail") } if T.Len(t) != 5 { println("T.Len", T.Len(t)) panic("fail") } if (*T).Len(&t) != 5 { println("(*T).Len", (*T).Len(&t)) panic("fail") } }
go
github
https://github.com/golang/go
test/method3.go
import os import sys import tempfile import operator import functools import itertools import re import contextlib import pickle import textwrap from setuptools.extern import six from setuptools.extern.six.moves import builtins, map import pkg_resources.py31compat if sys.platform.startswith('java'): import org.python.modules.posix.PosixModule as _os else: _os = sys.modules[os.name] try: _file = file except NameError: _file = None _open = open from distutils.errors import DistutilsError from pkg_resources import working_set __all__ = [ "AbstractSandbox", "DirectorySandbox", "SandboxViolation", "run_setup", ] def _execfile(filename, globals, locals=None): """ Python 3 implementation of execfile. """ mode = 'rb' with open(filename, mode) as stream: script = stream.read() # compile() function in Python 2.6 and 3.1 requires LF line endings. if sys.version_info[:2] < (2, 7) or sys.version_info[:2] >= (3, 0) and sys.version_info[:2] < (3, 2): script = script.replace(b'\r\n', b'\n') script = script.replace(b'\r', b'\n') if locals is None: locals = globals code = compile(script, filename, 'exec') exec(code, globals, locals) @contextlib.contextmanager def save_argv(repl=None): saved = sys.argv[:] if repl is not None: sys.argv[:] = repl try: yield saved finally: sys.argv[:] = saved @contextlib.contextmanager def save_path(): saved = sys.path[:] try: yield saved finally: sys.path[:] = saved @contextlib.contextmanager def override_temp(replacement): """ Monkey-patch tempfile.tempdir with replacement, ensuring it exists """ pkg_resources.py31compat.makedirs(replacement, exist_ok=True) saved = tempfile.tempdir tempfile.tempdir = replacement try: yield finally: tempfile.tempdir = saved @contextlib.contextmanager def pushd(target): saved = os.getcwd() os.chdir(target) try: yield saved finally: os.chdir(saved) class UnpickleableException(Exception): """ An exception representing another Exception that could not be pickled. """ @staticmethod def dump(type, exc): """ Always return a dumped (pickled) type and exc. If exc can't be pickled, wrap it in UnpickleableException first. """ try: return pickle.dumps(type), pickle.dumps(exc) except Exception: # get UnpickleableException inside the sandbox from setuptools.sandbox import UnpickleableException as cls return cls.dump(cls, cls(repr(exc))) class ExceptionSaver: """ A Context Manager that will save an exception, serialized, and restore it later. """ def __enter__(self): return self def __exit__(self, type, exc, tb): if not exc: return # dump the exception self._saved = UnpickleableException.dump(type, exc) self._tb = tb # suppress the exception return True def resume(self): "restore and re-raise any exception" if '_saved' not in vars(self): return type, exc = map(pickle.loads, self._saved) six.reraise(type, exc, self._tb) @contextlib.contextmanager def save_modules(): """ Context in which imported modules are saved. Translates exceptions internal to the context into the equivalent exception outside the context. """ saved = sys.modules.copy() with ExceptionSaver() as saved_exc: yield saved sys.modules.update(saved) # remove any modules imported since del_modules = ( mod_name for mod_name in sys.modules if mod_name not in saved # exclude any encodings modules. See #285 and not mod_name.startswith('encodings.') ) _clear_modules(del_modules) saved_exc.resume() def _clear_modules(module_names): for mod_name in list(module_names): del sys.modules[mod_name] @contextlib.contextmanager def save_pkg_resources_state(): saved = pkg_resources.__getstate__() try: yield saved finally: pkg_resources.__setstate__(saved) @contextlib.contextmanager def setup_context(setup_dir): temp_dir = os.path.join(setup_dir, 'temp') with save_pkg_resources_state(): with save_modules(): hide_setuptools() with save_path(): with save_argv(): with override_temp(temp_dir): with pushd(setup_dir): # ensure setuptools commands are available __import__('setuptools') yield def _needs_hiding(mod_name): """ >>> _needs_hiding('setuptools') True >>> _needs_hiding('pkg_resources') True >>> _needs_hiding('setuptools_plugin') False >>> _needs_hiding('setuptools.__init__') True >>> _needs_hiding('distutils') True >>> _needs_hiding('os') False >>> _needs_hiding('Cython') True """ pattern = re.compile(r'(setuptools|pkg_resources|distutils|Cython)(\.|$)') return bool(pattern.match(mod_name)) def hide_setuptools(): """ Remove references to setuptools' modules from sys.modules to allow the invocation to import the most appropriate setuptools. This technique is necessary to avoid issues such as #315 where setuptools upgrading itself would fail to find a function declared in the metadata. """ modules = filter(_needs_hiding, sys.modules) _clear_modules(modules) def run_setup(setup_script, args): """Run a distutils setup script, sandboxed in its directory""" setup_dir = os.path.abspath(os.path.dirname(setup_script)) with setup_context(setup_dir): try: sys.argv[:] = [setup_script] + list(args) sys.path.insert(0, setup_dir) # reset to include setup dir, w/clean callback list working_set.__init__() working_set.callbacks.append(lambda dist: dist.activate()) # __file__ should be a byte string on Python 2 (#712) dunder_file = ( setup_script if isinstance(setup_script, str) else setup_script.encode(sys.getfilesystemencoding()) ) with DirectorySandbox(setup_dir): ns = dict(__file__=dunder_file, __name__='__main__') _execfile(setup_script, ns) except SystemExit as v: if v.args and v.args[0]: raise # Normal exit, just return class AbstractSandbox: """Wrap 'os' module and 'open()' builtin for virtualizing setup scripts""" _active = False def __init__(self): self._attrs = [ name for name in dir(_os) if not name.startswith('_') and hasattr(self, name) ] def _copy(self, source): for name in self._attrs: setattr(os, name, getattr(source, name)) def __enter__(self): self._copy(self) if _file: builtins.file = self._file builtins.open = self._open self._active = True def __exit__(self, exc_type, exc_value, traceback): self._active = False if _file: builtins.file = _file builtins.open = _open self._copy(_os) def run(self, func): """Run 'func' under os sandboxing""" with self: return func() def _mk_dual_path_wrapper(name): original = getattr(_os, name) def wrap(self, src, dst, *args, **kw): if self._active: src, dst = self._remap_pair(name, src, dst, *args, **kw) return original(src, dst, *args, **kw) return wrap for name in ["rename", "link", "symlink"]: if hasattr(_os, name): locals()[name] = _mk_dual_path_wrapper(name) def _mk_single_path_wrapper(name, original=None): original = original or getattr(_os, name) def wrap(self, path, *args, **kw): if self._active: path = self._remap_input(name, path, *args, **kw) return original(path, *args, **kw) return wrap if _file: _file = _mk_single_path_wrapper('file', _file) _open = _mk_single_path_wrapper('open', _open) for name in [ "stat", "listdir", "chdir", "open", "chmod", "chown", "mkdir", "remove", "unlink", "rmdir", "utime", "lchown", "chroot", "lstat", "startfile", "mkfifo", "mknod", "pathconf", "access" ]: if hasattr(_os, name): locals()[name] = _mk_single_path_wrapper(name) def _mk_single_with_return(name): original = getattr(_os, name) def wrap(self, path, *args, **kw): if self._active: path = self._remap_input(name, path, *args, **kw) return self._remap_output(name, original(path, *args, **kw)) return original(path, *args, **kw) return wrap for name in ['readlink', 'tempnam']: if hasattr(_os, name): locals()[name] = _mk_single_with_return(name) def _mk_query(name): original = getattr(_os, name) def wrap(self, *args, **kw): retval = original(*args, **kw) if self._active: return self._remap_output(name, retval) return retval return wrap for name in ['getcwd', 'tmpnam']: if hasattr(_os, name): locals()[name] = _mk_query(name) def _validate_path(self, path): """Called to remap or validate any path, whether input or output""" return path def _remap_input(self, operation, path, *args, **kw): """Called for path inputs""" return self._validate_path(path) def _remap_output(self, operation, path): """Called for path outputs""" return self._validate_path(path) def _remap_pair(self, operation, src, dst, *args, **kw): """Called for path pairs like rename, link, and symlink operations""" return ( self._remap_input(operation + '-from', src, *args, **kw), self._remap_input(operation + '-to', dst, *args, **kw) ) if hasattr(os, 'devnull'): _EXCEPTIONS = [os.devnull,] else: _EXCEPTIONS = [] class DirectorySandbox(AbstractSandbox): """Restrict operations to a single subdirectory - pseudo-chroot""" write_ops = dict.fromkeys([ "open", "chmod", "chown", "mkdir", "remove", "unlink", "rmdir", "utime", "lchown", "chroot", "mkfifo", "mknod", "tempnam", ]) _exception_patterns = [ # Allow lib2to3 to attempt to save a pickled grammar object (#121) r'.*lib2to3.*\.pickle$', ] "exempt writing to paths that match the pattern" def __init__(self, sandbox, exceptions=_EXCEPTIONS): self._sandbox = os.path.normcase(os.path.realpath(sandbox)) self._prefix = os.path.join(self._sandbox, '') self._exceptions = [ os.path.normcase(os.path.realpath(path)) for path in exceptions ] AbstractSandbox.__init__(self) def _violation(self, operation, *args, **kw): from setuptools.sandbox import SandboxViolation raise SandboxViolation(operation, args, kw) if _file: def _file(self, path, mode='r', *args, **kw): if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path): self._violation("file", path, mode, *args, **kw) return _file(path, mode, *args, **kw) def _open(self, path, mode='r', *args, **kw): if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path): self._violation("open", path, mode, *args, **kw) return _open(path, mode, *args, **kw) def tmpnam(self): self._violation("tmpnam") def _ok(self, path): active = self._active try: self._active = False realpath = os.path.normcase(os.path.realpath(path)) return ( self._exempted(realpath) or realpath == self._sandbox or realpath.startswith(self._prefix) ) finally: self._active = active def _exempted(self, filepath): start_matches = ( filepath.startswith(exception) for exception in self._exceptions ) pattern_matches = ( re.match(pattern, filepath) for pattern in self._exception_patterns ) candidates = itertools.chain(start_matches, pattern_matches) return any(candidates) def _remap_input(self, operation, path, *args, **kw): """Called for path inputs""" if operation in self.write_ops and not self._ok(path): self._violation(operation, os.path.realpath(path), *args, **kw) return path def _remap_pair(self, operation, src, dst, *args, **kw): """Called for path pairs like rename, link, and symlink operations""" if not self._ok(src) or not self._ok(dst): self._violation(operation, src, dst, *args, **kw) return (src, dst) def open(self, file, flags, mode=0o777, *args, **kw): """Called for low-level os.open()""" if flags & WRITE_FLAGS and not self._ok(file): self._violation("os.open", file, flags, mode, *args, **kw) return _os.open(file, flags, mode, *args, **kw) WRITE_FLAGS = functools.reduce( operator.or_, [getattr(_os, a, 0) for a in "O_WRONLY O_RDWR O_APPEND O_CREAT O_TRUNC O_TEMPORARY".split()] ) class SandboxViolation(DistutilsError): """A setup script attempted to modify the filesystem outside the sandbox""" tmpl = textwrap.dedent(""" SandboxViolation: {cmd}{args!r} {kwargs} The package setup script has attempted to modify files on your system that are not within the EasyInstall build area, and has been aborted. This package cannot be safely installed by EasyInstall, and may not support alternate installation locations even if you run its setup script by hand. Please inform the package's author and the EasyInstall maintainers to find out if a fix or workaround is available. """).lstrip() def __str__(self): cmd, args, kwargs = self.args return self.tmpl.format(**locals())
unknown
codeparrot/codeparrot-clean
doctests = """ Unpack tuple >>> t = (1, 2, 3) >>> a, b, c = t >>> a == 1 and b == 2 and c == 3 True Unpack list >>> l = [4, 5, 6] >>> a, b, c = l >>> a == 4 and b == 5 and c == 6 True Unpack implied tuple >>> a, b, c = 7, 8, 9 >>> a == 7 and b == 8 and c == 9 True Unpack string... fun! >>> a, b, c = 'one' >>> a == 'o' and b == 'n' and c == 'e' True Unpack generic sequence >>> class Seq: ... def __getitem__(self, i): ... if i >= 0 and i < 3: return i ... raise IndexError ... >>> a, b, c = Seq() >>> a == 0 and b == 1 and c == 2 True Single element unpacking, with extra syntax >>> st = (99,) >>> sl = [100] >>> a, = st >>> a 99 >>> b, = sl >>> b 100 Now for some failures Unpacking non-sequence >>> a, b, c = 7 Traceback (most recent call last): ... TypeError: 'int' object is not iterable Unpacking tuple of wrong size >>> a, b = t Traceback (most recent call last): ... ValueError: too many values to unpack Unpacking tuple of wrong size >>> a, b = l Traceback (most recent call last): ... ValueError: too many values to unpack Unpacking sequence too short >>> a, b, c, d = Seq() Traceback (most recent call last): ... ValueError: need more than 3 values to unpack Unpacking sequence too long >>> a, b = Seq() Traceback (most recent call last): ... ValueError: too many values to unpack Unpacking a sequence where the test for too long raises a different kind of error >>> class BozoError(Exception): ... pass ... >>> class BadSeq: ... def __getitem__(self, i): ... if i >= 0 and i < 3: ... return i ... elif i == 3: ... raise BozoError ... else: ... raise IndexError ... Trigger code while not expecting an IndexError (unpack sequence too long, wrong error) >>> a, b, c, d, e = BadSeq() Traceback (most recent call last): ... BozoError Trigger code while expecting an IndexError (unpack sequence too short, wrong error) >>> a, b, c = BadSeq() Traceback (most recent call last): ... BozoError """ __test__ = {'doctests' : doctests} def test_main(verbose=False): import sys from test import test_support from test import test_unpack test_support.run_doctest(test_unpack, verbose) if __name__ == "__main__": test_main(verbose=True)
unknown
codeparrot/codeparrot-clean
# # (c) 2016 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.compat.tests.mock import patch from ansible.modules.network.onyx import onyx_config from units.modules.utils import set_module_args from .onyx_module import TestOnyxModule, load_fixture class TestOnyxConfigModule(TestOnyxModule): module = onyx_config def setUp(self): super(TestOnyxConfigModule, self).setUp() self.mock_get_config = patch('ansible.modules.network.onyx.onyx_config.get_config') self.get_config = self.mock_get_config.start() self.mock_load_config = patch('ansible.modules.network.onyx.onyx_config.load_config') self.load_config = self.mock_load_config.start() self.mock_run_commands = patch('ansible.modules.network.onyx.onyx_config.run_commands') self.run_commands = self.mock_run_commands.start() def tearDown(self): super(TestOnyxConfigModule, self).tearDown() self.mock_get_config.stop() self.mock_load_config.stop() self.mock_run_commands.stop() def load_fixtures(self, commands=None, transport='cli'): config_file = 'onyx_config_config.cfg' self.get_config.return_value = load_fixture(config_file) self.load_config.return_value = None def test_onyx_config_unchanged(self): src = load_fixture('onyx_config_config.cfg') set_module_args(dict(src=src)) self.execute_module() def test_onyx_config_src(self): src = load_fixture('onyx_config_src.cfg') set_module_args(dict(src=src)) commands = [ 'interface mlag-port-channel 2'] self.execute_module(changed=True, commands=commands, is_updates=True) def test_onyx_config_backup(self): set_module_args(dict(backup=True)) result = self.execute_module() self.assertIn('__backup__', result) def test_onyx_config_save(self): set_module_args(dict(save='yes')) self.execute_module(changed=True) self.assertEqual(self.run_commands.call_count, 1) self.assertEqual(self.get_config.call_count, 1) self.assertEqual(self.load_config.call_count, 0) args = self.run_commands.call_args[0][1] self.assertIn('configuration write', args) def test_onyx_config_lines_wo_parents(self): set_module_args(dict(lines=['hostname foo'])) commands = ['hostname foo'] self.execute_module(changed=True, commands=commands, is_updates=True) def test_onyx_config_before(self): set_module_args(dict(lines=['hostname foo'], before=['test1', 'test2'])) commands = ['test1', 'test2', 'hostname foo'] self.execute_module(changed=True, commands=commands, sort=False, is_updates=True) def test_onyx_config_after(self): set_module_args(dict(lines=['hostname foo'], after=['test1', 'test2'])) commands = ['hostname foo', 'test1', 'test2'] self.execute_module(changed=True, commands=commands, sort=False, is_updates=True) def test_onyx_config_before_after(self): set_module_args(dict(lines=['hostname foo'], before=['test1', 'test2'], after=['test3', 'test4'])) commands = ['test1', 'test2', 'hostname foo', 'test3', 'test4'] self.execute_module(changed=True, commands=commands, sort=False, is_updates=True) def test_onyx_config_config(self): config = 'hostname localhost' set_module_args(dict(lines=['hostname router'], config=config)) commands = ['hostname router'] self.execute_module(changed=True, commands=commands, is_updates=True) def test_onyx_config_match_none(self): lines = ['hostname router'] set_module_args(dict(lines=lines, match='none')) self.execute_module(changed=True, commands=lines, is_updates=True)
unknown
codeparrot/codeparrot-clean
/* * X.509 internal, common functions for writing * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #include "common.h" #if defined(MBEDTLS_X509_CSR_WRITE_C) || defined(MBEDTLS_X509_CRT_WRITE_C) #include "mbedtls/x509_crt.h" #include "x509_internal.h" #include "mbedtls/asn1write.h" #include "mbedtls/error.h" #include "mbedtls/oid.h" #include "mbedtls/platform.h" #include "mbedtls/platform_util.h" #include <string.h> #include <stdint.h> #if defined(MBEDTLS_PEM_WRITE_C) #include "mbedtls/pem.h" #endif /* MBEDTLS_PEM_WRITE_C */ #if defined(MBEDTLS_USE_PSA_CRYPTO) #include "psa/crypto.h" #include "mbedtls/psa_util.h" #include "md_psa.h" #endif /* MBEDTLS_USE_PSA_CRYPTO */ #define CHECK_OVERFLOW_ADD(a, b) \ do \ { \ if (a > SIZE_MAX - (b)) \ { \ return MBEDTLS_ERR_X509_BAD_INPUT_DATA; \ } \ a += b; \ } while (0) int mbedtls_x509_write_set_san_common(mbedtls_asn1_named_data **extensions, const mbedtls_x509_san_list *san_list) { int ret = 0; const mbedtls_x509_san_list *cur; unsigned char *buf; unsigned char *p; size_t len; size_t buflen = 0; /* Determine the maximum size of the SubjectAltName list */ for (cur = san_list; cur != NULL; cur = cur->next) { /* Calculate size of the required buffer */ switch (cur->node.type) { case MBEDTLS_X509_SAN_DNS_NAME: case MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER: case MBEDTLS_X509_SAN_IP_ADDRESS: case MBEDTLS_X509_SAN_RFC822_NAME: /* length of value for each name entry, * maximum 4 bytes for the length field, * 1 byte for the tag/type. */ CHECK_OVERFLOW_ADD(buflen, cur->node.san.unstructured_name.len); CHECK_OVERFLOW_ADD(buflen, 4 + 1); break; case MBEDTLS_X509_SAN_DIRECTORY_NAME: { const mbedtls_asn1_named_data *chunk = &cur->node.san.directory_name; while (chunk != NULL) { // Max 4 bytes for length, +1 for tag, // additional 4 max for length, +1 for tag. // See x509_write_name for more information. CHECK_OVERFLOW_ADD(buflen, 4 + 1 + 4 + 1); CHECK_OVERFLOW_ADD(buflen, chunk->oid.len); CHECK_OVERFLOW_ADD(buflen, chunk->val.len); chunk = chunk->next; } CHECK_OVERFLOW_ADD(buflen, 4 + 1); break; } default: /* Not supported - return. */ return MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE; } } /* Add the extra length field and tag */ CHECK_OVERFLOW_ADD(buflen, 4 + 1); /* Allocate buffer */ buf = mbedtls_calloc(1, buflen); if (buf == NULL) { return MBEDTLS_ERR_ASN1_ALLOC_FAILED; } p = buf + buflen; /* Write ASN.1-based structure */ cur = san_list; len = 0; while (cur != NULL) { size_t single_san_len = 0; switch (cur->node.type) { case MBEDTLS_X509_SAN_DNS_NAME: case MBEDTLS_X509_SAN_RFC822_NAME: case MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER: case MBEDTLS_X509_SAN_IP_ADDRESS: { const unsigned char *unstructured_name = (const unsigned char *) cur->node.san.unstructured_name.p; size_t unstructured_name_len = cur->node.san.unstructured_name.len; MBEDTLS_ASN1_CHK_CLEANUP_ADD(single_san_len, mbedtls_asn1_write_raw_buffer( &p, buf, unstructured_name, unstructured_name_len)); MBEDTLS_ASN1_CHK_CLEANUP_ADD(single_san_len, mbedtls_asn1_write_len( &p, buf, unstructured_name_len)); MBEDTLS_ASN1_CHK_CLEANUP_ADD(single_san_len, mbedtls_asn1_write_tag( &p, buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | cur->node.type)); } break; case MBEDTLS_X509_SAN_DIRECTORY_NAME: MBEDTLS_ASN1_CHK_CLEANUP_ADD(single_san_len, mbedtls_x509_write_names(&p, buf, (mbedtls_asn1_named_data *) & cur->node .san.directory_name)); MBEDTLS_ASN1_CHK_CLEANUP_ADD(single_san_len, mbedtls_asn1_write_len(&p, buf, single_san_len)); MBEDTLS_ASN1_CHK_CLEANUP_ADD(single_san_len, mbedtls_asn1_write_tag(&p, buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_X509_SAN_DIRECTORY_NAME)); break; default: /* Error out on an unsupported SAN */ ret = MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE; goto cleanup; } cur = cur->next; /* check for overflow */ if (len > SIZE_MAX - single_san_len) { ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA; goto cleanup; } len += single_san_len; } MBEDTLS_ASN1_CHK_CLEANUP_ADD(len, mbedtls_asn1_write_len(&p, buf, len)); MBEDTLS_ASN1_CHK_CLEANUP_ADD(len, mbedtls_asn1_write_tag(&p, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)); ret = mbedtls_x509_set_extension(extensions, MBEDTLS_OID_SUBJECT_ALT_NAME, MBEDTLS_OID_SIZE(MBEDTLS_OID_SUBJECT_ALT_NAME), 0, buf + buflen - len, len); /* If we exceeded the allocated buffer it means that maximum size of the SubjectAltName list * was incorrectly calculated and memory is corrupted. */ if (p < buf) { ret = MBEDTLS_ERR_ASN1_LENGTH_MISMATCH; } cleanup: mbedtls_free(buf); return ret; } #endif /* MBEDTLS_X509_CSR_WRITE_C || MBEDTLS_X509_CRT_WRITE_C */
c
github
https://github.com/nodejs/node
deps/LIEF/third-party/mbedtls/library/x509write.c
from twilio.twiml import Response from django_twilio.decorators import twilio_view from django.template.defaultfilters import striptags from django.views.decorators.http import require_http_methods from django.views.decorators.cache import never_cache from django.utils import timezone from dateutil.parser import parse as dateparse from sked.models import Event, Session import base62 @never_cache @twilio_view @require_http_methods(['POST', ]) def coming_up(request): sessions = Session.objects.filter(is_public=True, event=Event.objects.current()) r = Response() inmsg = request.POST.get('Body').strip() or 'next' if inmsg.lower() == 'next': messages = _as_sms(Session.objects.next()) elif inmsg.lower() == 'now': messages = _as_sms(Session.objects.current()) elif inmsg.lower() == 'lunch': try: now = timezone.now() messages = _as_sms(Session.objects.filter(start_time__day=now.day, start_time__month=now.month, start_time__year=now.year, title__icontains='lunch')[0]) except IndexError: messages = ["No lunch on the schedule for today, sorry.\n"] else: # First try to base62 decode the message try: session = _get_session_from_base62(inmsg) messages = _as_sms(session) except Session.DoesNotExist: messages = ["Couldn't find that session.\n\nText 'next' to get the upcoming block of sessions."] except ValueError: # Not b62-encoded, check to see if it's a time. try: ts = dateparse(inmsg) if ts.hour is 0 and ts.minute is 0: messages = ["A lot of stuff can happen in a whole day! Try specifying a time.\n"] else: messages = _as_sms(sessions.filter(start_time__lte=ts, end_time__gte=ts)) except: messages = ["Welcome to TCamp!\n\nOptions:\nnow: Current sessions\nnext: Next timeslot\nlunch: When's lunch?\n<time>, eg. 4:30pm: What's happening at 4:30?\n"] l = len(messages) for i, message in enumerate(messages): r.sms(message + '\n(%d/%d)' % (i+1, l)) return r def _get_session_from_base62(id): session_id = base62.decode(id) session = Session.objects.published().filter(pk=session_id) return session def _as_sms(qset): msgs = ['No events.\n'] if qset.count() > 1: return _format_multiple(qset) elif qset.count() is 1: return _format_single(qset) return msgs def _format_multiple(qset): msgs = ['No events.\n'] now = timezone.now() tm = _convert_time(qset[0].start_time) if tm.date() == now.date(): msgs[0] = u'At %s\n' % tm.strftime('%-I:%M') else: msgs[0] = u'%s at %s\n' % (tm.strftime('%A'), tm.strftime('%-I:%M')) msgs[0] += u' (text shortcode for more info):' for s in qset: line = u'\n%s: \n%s (%s)\n' % (base62.encode(s.id), s.title, s.location.name) if len(msgs[-1] + line) <= 150: msgs[-1] += line else: msgs.append(line) return msgs def _format_single(qset): sess = qset[0] tm = _convert_time(qset[0].start_time) msgs = [] detail = u'''{title} {time}, in {room} {speaker_names} {description} '''.format(title=sess.title, time=u'%s at %s' % (tm.strftime('%A'), tm.strftime('%-I:%M')), room=sess.location.name, description=striptags(sess.description).replace('&amp;', '&'), speaker_names=sess.speaker_names, ) if sess.tags.count(): detail += u"\n\nTagged: %s" % sess.tag_string lines = detail.split('\n') msgs.append(lines[0]) def build_line(tokens, **kwargs): maxlen = kwargs.get('maxlen', 146) i = kwargs.get('offset', 0) curline = [] while len(u' '.join(curline) + u' %s' % tokens[i]) <= maxlen: curline.append(tokens[i]) i += 1 if i >= len(tokens): break return (u' '.join(curline), i) for line in lines[1:]: if len(msgs[-1] + line) <= 146: msgs[-1] += "\n%s" % line else: if len(line) > 146: tokens = line.split() offset = 0 while offset < len(tokens): newline, offset = build_line(tokens, offset=offset) msgs.append(newline) else: msgs.append(line) return msgs def _convert_time(tm): return tm.astimezone(timezone.get_current_timezone())
unknown
codeparrot/codeparrot-clean
import operator_benchmark as op_bench import torch tensor_conversion_short_configs = op_bench.cross_product_configs( M=[32], N=[128], device=["cpu", "cuda"], dtype_one=[ torch.bool, torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64, torch.half, torch.bfloat16, torch.float, torch.double, ], dtype_two=[ torch.bool, torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64, torch.half, torch.bfloat16, torch.float, torch.double, ], tags=["short"], ) tensor_conversion_long_configs = op_bench.cross_product_configs( M=[1024], N=[1024], device=["cpu", "cuda"], dtype_one=[ torch.bool, torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64, torch.half, torch.bfloat16, torch.float, torch.double, ], dtype_two=[ torch.bool, torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64, torch.half, torch.bfloat16, torch.float, torch.double, ], tags=["long"], ) class TensorConversionBenchmark(op_bench.TorchBenchmarkBase): def init(self, M, N, dtype_one, dtype_two, device): self.inputs = { "input": torch.rand( M, N, device=device, requires_grad=False, dtype=torch.float ).to(dtype=dtype_one) } self.dtype_one = dtype_one self.dtype_two = dtype_two def forward(self, input): return input.to(dtype=self.dtype_two) op_bench.generate_pt_test(tensor_conversion_short_configs, TensorConversionBenchmark) op_bench.generate_pt_test(tensor_conversion_long_configs, TensorConversionBenchmark) if __name__ == "__main__": op_bench.benchmark_runner.main()
python
github
https://github.com/pytorch/pytorch
benchmarks/operator_benchmark/pt/tensor_to_test.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from osv import osv class wiki_wiki_page_open(osv.osv_memory): """ wizard Open Page """ _name = "wiki.wiki.page.open" _description = "wiz open page" def open_wiki_page(self, cr, uid, ids, context=None): """ Opens Wiki Page of Group @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: List of open wiki page’s IDs @return: dictionay of open wiki window on give group id """ if context is None: context = {} group_ids = context.get('active_ids', []) for group in self.pool.get('wiki.groups').browse(cr, uid, group_ids, context=context): value = { 'domain': "[('group_id','=',%d)]" % (group.id), 'name': 'Wiki Page', 'view_type': 'form', 'view_mode': 'form,tree', 'res_model': 'wiki.wiki', 'view_id': False, 'type': 'ir.actions.act_window', } if group.method == 'page': value['res_id'] = group.home.id elif group.method == 'list': value['view_type'] = 'form' value['view_mode'] = 'tree,form' elif group.method == 'tree': view_id = self.pool.get('ir.ui.view').search(cr, uid, [('name', '=', 'wiki.wiki.tree.children')]) value['view_id'] = view_id value['domain'] = [('group_id', '=', group.id), ('parent_id', '=', False)] value['view_type'] = 'tree' return value wiki_wiki_page_open() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
unknown
codeparrot/codeparrot-clean
''' This is a file which stores various statistics for AI metrics: ''' import random, sys, time, math, dictionarywords class AIStats(): FILENAME = "wordsmithed/media/aistats.txt" #'media/heuristic/heuristic_tilequantile_5_5.txt' COLLECT_WORD_DATA = False #if True, this will collect data on timing/letterPlays COLLECT_GAME_DATA = False #if True, this will record data for entire games def __init__(self): self.timingInfo = [] self.letterPlays = {} for code in range(ord('A'), ord('Z')+1): char = chr(code) self.letterPlays[char] = [] #also add a count for blanks self.letterPlays["_"] = [] self.scores = [] self.seedRatio = [] self.load() ''' Loads all stats from last time to update ''' def load(self): try: statsFile = open(AIStats.FILENAME, 'r') MODE = "none" for line in statsFile: if line != "\n": line = line.rstrip() if MODE == "TIMING:": tokens = line.split() #TIMING DATA should be [totalTime] [timeAtMaxWord] assert len(tokens) == 2 self.timingInfo.append((float(tokens[0]) , float(tokens[1]))) elif MODE == "LETTERS:": tokens = line.split() #LETTER PLAY should be [letter] [score] assert len(tokens) == 2 self.letterPlays[tokens[0]].append(float(tokens[1])) elif MODE == "SEED:": tokens = line.split() #SEEDS should be [numSeeds] [numTiles] [points] assert len(tokens) == 3 self.seedRatio.append((int(tokens[0]), int(tokens[1]), float(tokens[2]))) elif MODE == "GAME:": tokens = line.split() self.scores.append([int(token) for token in tokens]) else: MODE = "none" if line == "TIMING:": MODE = "TIMING:" elif line == "LETTERS:": MODE = "LETTERS:" elif line == "SEED:": MODE = "SEED:" elif line == "GAME:": MODE = "GAME:" except IOError as e: pass ''' Saves all stats ''' def save(self): statsFile = open(AIStats.FILENAME, 'w') statsFile.write("TIMING:\n") for timeStamp in self.timingInfo: statsFile.write(str(timeStamp[0])+" "+str(timeStamp[1])+"\n") statsFile.write("\n") statsFile.write("LETTERS:\n") for code in range(ord('A'), ord('Z')+1): char = chr(code) if len(self.letterPlays[char]) > 0: for play in self.letterPlays[char]: statsFile.write(char+" "+str(play)+"\n") if len(self.letterPlays["_"]) > 0: for play in self.letterPlays["_"]: statsFile.write("_ "+str(play)+"\n") statsFile.write("\n") statsFile.write("SEED:\n") for seeds in self.seedRatio: statsFile.write(str(seeds[0])+" "+str(seeds[1])+" "+str(seeds[2])+"\n") statsFile.write("\n") statsFile.write("GAME:\n") for game in self.scores: for score in game: statsFile.write(str(score)+" ") statsFile.write("\n") statsFile.write("\n") def updateTiming(self, totalTime, timeAtMaxWord): if AIStats.COLLECT_WORD_DATA: self.timingInfo.append((totalTime, timeAtMaxWord)) def updateLetterPlays(self, lettersUsed, points): if AIStats.COLLECT_WORD_DATA: for letter in lettersUsed: self.letterPlays[letter].append(points) def updateSeedRatio(self, (numSeeds, numTiles), points): if AIStats.COLLECT_WORD_DATA: self.seedRatio.append((numSeeds, numTiles, points)) def saveGame(self, gameScores): if AIStats.COLLECT_GAME_DATA: self.scores.append(gameScores) ''' Displays a histogram of the ratio of timeAtMaxWord over totalTime ''' def visualizeTiming(self, DISPLAYSURF): values = [] for timeStamp in self.timingInfo: values.append(timeStamp[1]/(timeStamp[0]+0.00001)) self.drawHistogram(DISPLAYSURF, values, 400, 400, 100) ''' Gets the CDF of the timingInfo data, given a certain cutoff time, to see what percentage of turns would be executed properly ''' def timingCDF(self, cutoffTime): i = 0 for totalTime, maxWordTime in self.timingInfo: if maxWordTime < cutoffTime: i += 1 return i / (len(self.timingInfo) + 0.00001) ''' Gets the inverse CDF of letterPlay info for one play, to determine what score and less accounts for percentMass of the data ''' def letterPlaysInvCDF(self, letter, mass): assert mass >= 0.0 and mass <= 1.0 if letter != None: plays = self.letterPlays[letter] else: plays = [] for code in range(ord('A'), ord('Z')+1): char = chr(code) for play in self.letterPlays[char]: plays.append(play) score = -1 if len(plays) > 0: plays = sorted(plays) score = plays[int(mass*len(plays))] return score ''' Gets the average of a letterPlay ''' def letterPlaysMean(self, letter): total = 0 if letter != None: plays = self.letterPlays[letter] else: plays = [] for code in range(ord('A'), ord('Z')+1): char = chr(code) for play in self.letterPlays[char]: plays.append(play) for play in plays: total += play mean = total/(len(plays)+0.0001) return mean ''' Gets the standard deviation of a letterPlay ''' def letterPlaysStdDev(self, letter): total = 0 mean = self.letterPlaysMean(letter) if letter != None: plays = self.letterPlays[letter] else: plays = [] for code in range(ord('A'), ord('Z')+1): char = chr(code) for play in self.letterPlays[char]: plays.append(play) for play in plays: total += math.pow(play-mean, 2) variance = total/(len(plays)+0.0001) stddev = math.sqrt(variance) return stddev ''' Gets the games won from the 1st player, to see the relative win % ''' def getGamesWon(self): totalWon = 0 for scores in self.scores: assert len(scores) == 2, "Error, function only works for 2-player games." if scores[0] > scores[1]: totalWon += 1 elif scores[0] == scores[1]: totalWon += 0.5 return totalWon ''' Gets the mean of the difference Player 1 - Player 2 in game scores (assumes Heurstic v. Control) ''' def getGameDiffMean(self): totalDifference = 0 for scores in self.scores: assert len(scores) == 2, "Error: function only works for 2-player games." difference = scores[0] - scores[1] totalDifference += difference return (totalDifference / len(self.scores)) ''' Gets the standard deviation of the difference Player 1 - Player 2 in game scores (assumes Heurstic v. Control) ''' def getGameDiffStdDev(self): totalDifference = 0 mean = self.getGameDiffMean() for scores in self.scores: assert len(scores) == 2, "Error: function only works for 2-player games." difference = scores[0] - scores[1] totalDifference += math.pow(difference-mean, 2) totalDifference = math.sqrt(totalDifference) return (totalDifference / len(self.scores)) ''' Gets the highest word score ''' def getHighestWord(self, letter = None): if letter != None: plays = self.letterPlays[letter] else: plays = [] for code in range(ord('A'), ord('Z')+1): char = chr(code) for play in self.letterPlays[char]: plays.append(play) return(max(plays)) ''' Normalizes all seedRatio data and draws the heat map ''' def visualizeSeedRatio(self, DISPLAYSURF, clamp=50): maxSeeds = 0 maxTiles = 0 maxScore = 0 for seeds, tiles, score in self.seedRatio: if seeds > maxSeeds: maxSeeds = seeds if tiles > maxTiles: maxTiles = tiles if score > maxScore: maxScore = score values = [] for seeds, tiles, score in self.seedRatio: normSeeds = seeds / (maxSeeds + 0.00001) normTiles = tiles / (maxTiles + 0.00001) normScore = score / (clamp + 0.00001) assert (normSeeds >= 0.0 and normSeeds <= 1.0 and normTiles >= 0.0 and normTiles <= 1.0) values.append((normSeeds, normTiles, normScore)) self.drawHeatMap(DISPLAYSURF, values, 30) ''' Draws a heatmap of a 3D data-set where x, y are ranged between 0.0 and 1.0, plotted values must range between 0.0 and 1.0, everything above and below is clamped. ''' def drawHeatMap(self, DISPLAYSURF, values, size, blockSize = 10): #create a grid buckets = [] for i in range(size): buckets.append([]) for j in range(size): buckets[i].append([]) for value in values: x = int(value[0] / (1.0/(size))) y = int(value[1] / (1.0/(size))) assert x >= 0 and x < len(buckets) and y >= 0 and y < len(buckets) buckets[x][y].append(value[2]) LEFT_X = 10 TOP_Y = 50 for x in range(size): for y in range(size): total = 0.0 num = 0.0001 #Add a small amount to the number so we don't get div by 0 errors for value in buckets[x][y]: #Clamp values if value > 1.0: value = 1.0 elif value < 0.0: value = 0.0 total += value num += 1 avg = (total/num) assert avg >= 0.0 and avg <= 1.0 color = (255*avg, 255*avg, 255*avg) if num < 1.0: color = (0, 0, 0) left = LEFT_X + blockSize * x top = TOP_Y + blockSize * y pygame.draw.rect(DISPLAYSURF, color, (left, top, blockSize, blockSize)) ''' Shows a histogram of words by their Google n-gram usage value ''' def visualizeWordUsage(self, DISPLAYSURF): dictionary = dictionarywords.DictionaryWords("media/scrabblewords_usage.txt") values = dictionary.words.values() maxUsage = math.log(max(values)) print "Most used word appeared "+str(maxUsage)+" times in Google's ngram corpus." normalizedValues = [] for val in values: if val < 0: normalizedValues.append(math.log(1)/(maxUsage+1)) else: normalizedValues.append(math.log(val)/(maxUsage+1)) self.drawHistogram(DISPLAYSURF, normalizedValues, 400, 400, 10) ''' Gives the quantiles of word usages ''' def wordUsageQuantiles(self, quantiles): dictionary = dictionarywords.DictionaryWords("media/scrabblewords_usage.txt") values = dictionary.words.values() values.sort(reverse=True) for quantile in quantiles: massCutoff = int(quantile * len(values)) assert massCutoff < len(values) point = values[massCutoff] if point <= 1: point = 1 print str(quantile)+" = "+str(math.log(point)) ''' Draws a histogram given a set of values ranging from 0.0 -> 1.0 and a width, height and number of buckets ''' def drawHistogram(self, DISPLAYSURF, values, width, height, numBuckets): buckets = [] for i in range(numBuckets): buckets.append(0) for value in values: assert value >= 0.0 and value <= 1.0, "Histogram only works on values between 0.0 and 1.0" bucketNumber = int(value / (1.0/(numBuckets))) assert bucketNumber >= 0 and bucketNumber < len(buckets) buckets[bucketNumber] += 1 maxBucket = max(buckets) LEFT_X = 10 TOP_Y = 50 COLOR = (0, 100, 255) pygame.draw.rect(DISPLAYSURF, (255, 255, 255), (LEFT_X, TOP_Y, width, height)) i = 0 barWidth = width/numBuckets for bucket in buckets: barLeft = LEFT_X + i * barWidth barHeight = float(bucket)/maxBucket * height barTop = TOP_Y + (height - barHeight) pygame.draw.rect(DISPLAYSURF, COLOR, (barLeft, barTop, barWidth, barHeight)) i += 1 #RUNNING WORD FREQUENCY ON ITS OWN PROVIDES STATISTICS if __name__ == '__main__': aiStats = AIStats() print str(len(aiStats.timingInfo)) + " data points collected." #DISPLAYSURF = pygame.display.set_mode((800, 600)) #pygame.display.set_caption('Wordsmith Statistics') #aiStats.visualizeTiming(DISPLAYSURF) #aiStats.visualizeSeedRatio(DISPLAYSURF) #aiStats.visualizeWordUsage(DISPLAYSURF) aiStats.wordUsageQuantiles([(i+1)/100.0 for i in range(99)]) groupMedian = aiStats.letterPlaysInvCDF(None, .5) groupMean = aiStats.letterPlaysMean(None) group25p = aiStats.letterPlaysInvCDF(None, .25) group75p = aiStats.letterPlaysInvCDF(None, .75) groupStdDev = aiStats.letterPlaysStdDev(None) for code in range(ord('A'), ord('Z')+1): char = chr(code) print char+": \tmedian = "+str(aiStats.letterPlaysInvCDF(char, .5)-groupMedian) print "\tmean = "+str(aiStats.letterPlaysMean(char)-groupMean) print "\t25th percentile: "+str(aiStats.letterPlaysInvCDF(char, .25)-group25p) print "\t75th percentile: "+str(aiStats.letterPlaysInvCDF(char, .75)-group75p) print "\tStd dev: "+str(aiStats.letterPlaysStdDev(char)/groupStdDev) print "\tBest play ever: "+str(aiStats.getHighestWord(char)) char = '_' print char+": \tmedian = "+str(aiStats.letterPlaysInvCDF(char, .5)-groupMedian) print "\tmean = "+str(aiStats.letterPlaysMean(char)-groupMean) print "\t25th percentile: "+str(aiStats.letterPlaysInvCDF(char, .25)-group25p) print "\t75th percentile: "+str(aiStats.letterPlaysInvCDF(char, .75)-group75p) print "\tStd dev: "+str(aiStats.letterPlaysStdDev(char)/groupStdDev) print "\tBest play ever: "+str(aiStats.getHighestWord(char)) print "\nHighest-ever word score: "+str(aiStats.getHighestWord()) print str(len(aiStats.letterPlays['Q']))+" games played counting letter statistics.\n" print "Latest Heuristic Game Analysis:" print "Test won "+str(100.0*aiStats.getGamesWon() / (len(aiStats.scores) + 0.00001))+"% of games." print "Mean performance improvement: "+str(aiStats.getGameDiffMean()) print "Performance difference stddev: "+str(aiStats.getGameDiffStdDev()) print str(len(aiStats.scores))+" games played in this round of testing.\n" #for i in range(0, 20, 1): # print str(100*aiStats.timingCDF(i)) + '% would be completed successfully in '+ str(i) +' seconds' '''while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update() '''
unknown
codeparrot/codeparrot-clean
"""unit tests for sparse utility functions""" from __future__ import division, print_function, absolute_import import numpy as np from numpy.testing import assert_equal from pytest import raises as assert_raises from scipy.sparse import sputils from scipy.sparse.sputils import matrix from scipy._lib._numpy_compat import suppress_warnings class TestSparseUtils(object): def test_upcast(self): assert_equal(sputils.upcast('intc'), np.intc) assert_equal(sputils.upcast('int32', 'float32'), np.float64) assert_equal(sputils.upcast('bool', complex, float), np.complex128) assert_equal(sputils.upcast('i', 'd'), np.float64) def test_getdtype(self): A = np.array([1], dtype='int8') assert_equal(sputils.getdtype(None, default=float), float) assert_equal(sputils.getdtype(None, a=A), np.int8) def test_isscalarlike(self): assert_equal(sputils.isscalarlike(3.0), True) assert_equal(sputils.isscalarlike(-4), True) assert_equal(sputils.isscalarlike(2.5), True) assert_equal(sputils.isscalarlike(1 + 3j), True) assert_equal(sputils.isscalarlike(np.array(3)), True) assert_equal(sputils.isscalarlike("16"), True) assert_equal(sputils.isscalarlike(np.array([3])), False) assert_equal(sputils.isscalarlike([[3]]), False) assert_equal(sputils.isscalarlike((1,)), False) assert_equal(sputils.isscalarlike((1, 2)), False) def test_isintlike(self): assert_equal(sputils.isintlike(-4), True) assert_equal(sputils.isintlike(np.array(3)), True) assert_equal(sputils.isintlike(np.array([3])), False) with suppress_warnings() as sup: sup.filter(DeprecationWarning, "Inexact indices into sparse matrices are deprecated") assert_equal(sputils.isintlike(3.0), True) assert_equal(sputils.isintlike(2.5), False) assert_equal(sputils.isintlike(1 + 3j), False) assert_equal(sputils.isintlike((1,)), False) assert_equal(sputils.isintlike((1, 2)), False) def test_isshape(self): assert_equal(sputils.isshape((1, 2)), True) assert_equal(sputils.isshape((5, 2)), True) assert_equal(sputils.isshape((1.5, 2)), False) assert_equal(sputils.isshape((2, 2, 2)), False) assert_equal(sputils.isshape(([2], 2)), False) assert_equal(sputils.isshape((-1, 2), nonneg=False),True) assert_equal(sputils.isshape((2, -1), nonneg=False),True) assert_equal(sputils.isshape((-1, 2), nonneg=True),False) assert_equal(sputils.isshape((2, -1), nonneg=True),False) def test_issequence(self): assert_equal(sputils.issequence((1,)), True) assert_equal(sputils.issequence((1, 2, 3)), True) assert_equal(sputils.issequence([1]), True) assert_equal(sputils.issequence([1, 2, 3]), True) assert_equal(sputils.issequence(np.array([1, 2, 3])), True) assert_equal(sputils.issequence(np.array([[1], [2], [3]])), False) assert_equal(sputils.issequence(3), False) def test_ismatrix(self): assert_equal(sputils.ismatrix(((),)), True) assert_equal(sputils.ismatrix([[1], [2]]), True) assert_equal(sputils.ismatrix(np.arange(3)[None]), True) assert_equal(sputils.ismatrix([1, 2]), False) assert_equal(sputils.ismatrix(np.arange(3)), False) assert_equal(sputils.ismatrix([[[1]]]), False) assert_equal(sputils.ismatrix(3), False) def test_isdense(self): assert_equal(sputils.isdense(np.array([1])), True) assert_equal(sputils.isdense(matrix([1])), True) def test_validateaxis(self): assert_raises(TypeError, sputils.validateaxis, (0, 1)) assert_raises(TypeError, sputils.validateaxis, 1.5) assert_raises(ValueError, sputils.validateaxis, 3) # These function calls should not raise errors for axis in (-2, -1, 0, 1, None): sputils.validateaxis(axis) def test_get_index_dtype(self): imax = np.iinfo(np.int32).max too_big = imax + 1 # Check that uint32's with no values too large doesn't return # int64 a1 = np.ones(90, dtype='uint32') a2 = np.ones(90, dtype='uint32') assert_equal( np.dtype(sputils.get_index_dtype((a1, a2), check_contents=True)), np.dtype('int32') ) # Check that if we can not convert but all values are less than or # equal to max that we can just convert to int32 a1[-1] = imax assert_equal( np.dtype(sputils.get_index_dtype((a1, a2), check_contents=True)), np.dtype('int32') ) # Check that if it can not convert directly and the contents are # too large that we return int64 a1[-1] = too_big assert_equal( np.dtype(sputils.get_index_dtype((a1, a2), check_contents=True)), np.dtype('int64') ) # test that if can not convert and didn't specify to check_contents # we return int64 a1 = np.ones(89, dtype='uint32') a2 = np.ones(89, dtype='uint32') assert_equal( np.dtype(sputils.get_index_dtype((a1, a2))), np.dtype('int64') ) # Check that even if we have arrays that can be converted directly # that if we specify a maxval directly it takes precedence a1 = np.ones(12, dtype='uint32') a2 = np.ones(12, dtype='uint32') assert_equal( np.dtype(sputils.get_index_dtype( (a1, a2), maxval=too_big, check_contents=True )), np.dtype('int64') ) # Check that an array with a too max size and maxval set # still returns int64 a1[-1] = too_big assert_equal( np.dtype(sputils.get_index_dtype((a1, a2), maxval=too_big)), np.dtype('int64') )
unknown
codeparrot/codeparrot-clean
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build unix package runtime import _ "unsafe" // used in internal/syscall/unix //go:linkname fcntl
go
github
https://github.com/golang/go
src/runtime/linkname_unix.go
<!--Copyright 2020 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # DeepSpeed集成 [DeepSpeed](https://github.com/deepspeedai/DeepSpeed)实现了[ZeRO论文](https://huggingface.co/papers/1910.02054)中描述的所有内容。目前,它提供对以下功能的全面支持: 1. 优化器状态分区(ZeRO stage 1) 2. 梯度分区(ZeRO stage 2) 3. 参数分区(ZeRO stage 3) 4. 自定义混合精度训练处理 5. 一系列基于CUDA扩展的快速优化器 6. ZeRO-Offload 到 CPU 和 NVMe ZeRO-Offload有其自己的专门论文:[ZeRO-Offload: Democratizing Billion-Scale Model Training](https://huggingface.co/papers/2101.06840)。而NVMe支持在论文[ZeRO-Infinity: Breaking the GPU Memory Wall for Extreme Scale Deep Learning](https://huggingface.co/papers/2104.07857)中进行了描述。 DeepSpeed ZeRO-2主要用于训练,因为它的特性对推理没有用处。 DeepSpeed ZeRO-3也可以用于推理,因为它允许将单个GPU无法加载的大模型加载到多个GPU上。 🤗 Transformers通过以下两种方式集成了[DeepSpeed](https://github.com/deepspeedai/DeepSpeed): 1. 通过[`Trainer`]集成核心的DeepSpeed功能。这是一种“为您完成一切”式的集成 - 您只需提供自定义配置文件或使用我们的模板配置文件。本文档的大部分内容都集中在这个功能上。 2. 如果您不使用[`Trainer`]并希望在自己的Trainer中集成DeepSpeed,那么像`from_pretrained`和`from_config`这样的核心功能函数将包括ZeRO stage 3及以上的DeepSpeed的基础部分,如`zero.Init`。要利用此功能,请阅读有关[非Trainer DeepSpeed集成](#nontrainer-deepspeed-integration)的文档。 集成的内容: 训练: 1. DeepSpeed ZeRO训练支持完整的ZeRO stages 1、2和3,以及ZeRO-Infinity(CPU和NVMe offload)。 推理: 1. DeepSpeed ZeRO推理支持ZeRO stage 3和ZeRO-Infinity。它使用与训练相同的ZeRO协议,但不使用优化器和学习率调度器,只有stage 3与推理相关。更多详细信息请参阅:[zero-inference](#zero-inference)。 此外还有DeepSpeed推理 - 这是一种完全不同的技术,它使用张量并行而不是ZeRO(即将推出)。 <a id='deepspeed-trainer-integration'></a> ## Trainer DeepSpeed 集成 <a id='deepspeed-installation'></a> ### 安装 通过pypi安装库: ```bash pip install deepspeed ``` 或通过 `transformers` 的 `extras`安装: ```bash pip install transformers[deepspeed] ``` 或在 [DeepSpeed 的 GitHub 页面](https://github.com/deepspeedai/DeepSpeed#installation) 和 [高级安装](https://www.deepspeed.ai/tutorials/advanced-install/) 中查找更多详细信息。 如果构建过程中仍然遇到问题,请首先确保阅读 [CUDA 扩展安装注意事项](trainer#cuda-extension-installation-notes)。 如果您没有预先构建扩展而是在运行时构建它们,而且您尝试了以上所有解决方案都无效,下一步可以尝试在安装之前预先构建扩展。 进行 DeepSpeed 的本地构建: ```bash git clone https://github.com/deepspeedai/DeepSpeed/ cd DeepSpeed rm -rf build TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 pip install . \ --global-option="build_ext" --global-option="-j8" --no-cache -v \ --disable-pip-version-check 2>&1 | tee build.log ``` 如果您打算使用 NVMe offload,您还需要在上述说明中添加 `DS_BUILD_AIO=1`(并且还需要在系统范围内安装 *libaio-dev*)。 编辑 `TORCH_CUDA_ARCH_LIST` 以插入您打算使用的 GPU 卡的架构代码。假设您的所有卡都是相同的,您可以通过以下方式获取架构: ```bash CUDA_VISIBLE_DEVICES=0 python -c "import torch; print(torch.cuda.get_device_capability())" ``` 因此,如果您得到 `8, 6`,则使用 `TORCH_CUDA_ARCH_LIST="8.6"`。如果您有多个不同的卡,您可以像这样列出所有卡 `TORCH_CUDA_ARCH_LIST="6.1;8.6"`。 如果您需要在多台机器上使用相同的设置,请创建一个二进制 wheel: ```bash git clone https://github.com/deepspeedai/DeepSpeed/ cd DeepSpeed rm -rf build TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 \ python setup.py build_ext -j8 bdist_wheel ``` 它将生成类似于 `dist/deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl` 的文件,现在您可以在本地或任何其他机器上安装它,如 `pip install deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl`。 再次提醒确保调整 `TORCH_CUDA_ARCH_LIST` 以匹配目标架构。 您可以在[这里](https://developer.nvidia.com/cuda-gpus)找到完整的 NVIDIA GPU 列表及其对应的 **计算能力**(与此上下文中的架构相同)。 您可以使用以下命令检查 PyTorch 构建时使用的架构: ```bash python -c "import torch; print(torch.cuda.get_arch_list())" ``` 以下是如何查找已安装 GPU 中的一张卡的架构。例如,对于 GPU 0: ```bash CUDA_VISIBLE_DEVICES=0 python -c "import torch; \ print(torch.cuda.get_device_properties(torch.device('cuda')))" ``` 如果输出结果如下: ```bash _CudaDeviceProperties(name='GeForce RTX 3090', major=8, minor=6, total_memory=24268MB, multi_processor_count=82) ``` 然后您就知道这张卡的架构是 `8.6`。 您也可以完全省略 `TORCH_CUDA_ARCH_LIST`,然后构建程序将自动查询构建所在的 GPU 的架构。这可能与目标机器上的 GPU 不匹配,因此最好明确指定所需的架构。 如果尝试了所有建议的方法仍然遇到构建问题,请继续在 [Deepspeed](https://github.com/deepspeedai/DeepSpeed/issues)的 GitHub Issue 上提交问题。 <a id='deepspeed-multi-gpu'></a> ### 多GPU启用 为了启用DeepSpeed 集成,调整 [`Trainer`] 的命令行参数,添加一个新的参数 `--deepspeed ds_config.json`,其中 `ds_config.json` 是 DeepSpeed 配置文件,如文档 [这里](https://www.deepspeed.ai/docs/config-json/) 所述。文件命名由您决定。 建议使用 DeepSpeed 的 `add_config_arguments` 程序将必要的命令行参数添加到您的代码中。 有关更多信息,请参阅 [DeepSpeed 的参数解析](https://deepspeed.readthedocs.io/en/latest/initialize.html#argument-parsing) 文档。 在这里,您可以使用您喜欢的启动器。您可以继续使用 PyTorch 启动器: ```bash torch.distributed.run --nproc_per_node=2 your_program.py <normal cl args> --deepspeed ds_config.json ``` 或使用由 `deepspeed` 提供的启动器: ```bash deepspeed --num_gpus=2 your_program.py <normal cl args> --deepspeed ds_config.json ``` 正如您所见,这两个启动器的参数不同,但对于大多数需求,任何一个都可以满足工作需求。有关如何配置各个节点和 GPU 的完整详细信息,请查看 [此处](https://www.deepspeed.ai/getting-started/#resource-configuration-multi-node)。 当您使用 `deepspeed` 启动器并且希望使用所有可用的 GPU 时,您可以简单地省略 `--num_gpus` 标志。 以下是在 DeepSpeed 中启用使用所有可用 GPU情况下, 运行 `run_translation.py` 的示例: ```bash deepspeed examples/pytorch/translation/run_translation.py \ --deepspeed tests/deepspeed/ds_config_zero3.json \ --model_name_or_path google-t5/t5-small --per_device_train_batch_size 1 \ --output_dir output_dir --fp16 \ --do_train --max_train_samples 500 --num_train_epochs 1 \ --dataset_name wmt16 --dataset_config "ro-en" \ --source_lang en --target_lang ro ``` 请注意,在 DeepSpeed 文档中,您可能会看到 `--deepspeed --deepspeed_config ds_config.json` - 即两个与 DeepSpeed 相关的参数,但为简单起见,并且因为已经有很多参数要处理,我们将两者合并为一个单一参数。 有关一些实际使用示例,请参阅 [此帖](https://github.com/huggingface/transformers/issues/8771#issuecomment-759248400)。 <a id='deepspeed-one-gpu'></a> ### 单GPU启用 要使用一张 GPU 启用 DeepSpeed,调整 [`Trainer`] 的命令行参数如下: ```bash deepspeed --num_gpus=1 examples/pytorch/translation/run_translation.py \ --deepspeed tests/deepspeed/ds_config_zero2.json \ --model_name_or_path google-t5/t5-small --per_device_train_batch_size 1 \ --output_dir output_dir --fp16 \ --do_train --max_train_samples 500 --num_train_epochs 1 \ --dataset_name wmt16 --dataset_config "ro-en" \ --source_lang en --target_lang ro ``` 这与多 GPU 的情况几乎相同,但在这里我们通过 `--num_gpus=1` 明确告诉 DeepSpeed 仅使用一张 GPU。默认情况下,DeepSpeed 启用给定节点上可以看到的所有 GPU。如果您一开始只有一张 GPU,那么您不需要这个参数。以下 [文档](https://www.deepspeed.ai/getting-started/#resource-configuration-multi-node) 讨论了启动器的选项。 为什么要在仅使用一张 GPU 的情况下使用 DeepSpeed 呢? 1. 它具有 ZeRO-offload 功能,可以将一些计算和内存委托给主机的 CPU 和 内存,从而为模型的需求保留更多 GPU 资源 - 例如更大的批处理大小,或启用正常情况下无法容纳的非常大模型。 2. 它提供了智能的 GPU 内存管理系统,最小化内存碎片,这再次允许您容纳更大的模型和数据批次。 虽然接下来我们将详细讨论配置,但在单个 GPU 上通过 DeepSpeed 实现巨大性能提升的关键是在配置文件中至少有以下配置: ```json { "zero_optimization": { "stage": 2, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "allgather_partitions": true, "allgather_bucket_size": 2e8, "reduce_scatter": true, "reduce_bucket_size": 2e8, "overlap_comm": true, "contiguous_gradients": true } } ``` 这会启用`optimizer offload`和一些其他重要功能。您可以尝试不同的buffer大小,有关详细信息,请参见下面的讨论。 关于这种启用类型的实际使用示例,请参阅 [此帖](https://github.com/huggingface/transformers/issues/8771#issuecomment-759176685)。 您还可以尝试使用本文后面进一步解释的支持`CPU 和 NVMe offload`功能的ZeRO-3 。 <!--- TODO: Benchmark whether we can get better performance out of ZeRO-3 vs. ZeRO-2 on a single GPU, and then recommend ZeRO-3 config as starting one. --> 注意: - 如果您需要在特定的 GPU 上运行,而不是 GPU 0,则无法使用 `CUDA_VISIBLE_DEVICES` 来限制可用 GPU 的可见范围。相反,您必须使用以下语法: ```bash deepspeed --include localhost:1 examples/pytorch/translation/run_translation.py ... ``` 在这个例子中,我们告诉 DeepSpeed 使用 GPU 1(第二个 GPU)。 <a id='deepspeed-multi-node'></a> ### 多节点启用 这一部分的信息不仅适用于 DeepSpeed 集成,也适用于任何多节点程序。但 DeepSpeed 提供了一个比其他启动器更易于使用的 `deepspeed` 启动器,除非您在 SLURM 环境中。 在本节,让我们假设您有两个节点,每个节点有 8 张 GPU。您可以通过 `ssh hostname1` 访问第一个节点,通过 `ssh hostname2` 访问第二个节点,两者必须能够在本地通过 ssh 无密码方式相互访问。当然,您需要将这些主机(节点)名称重命名为您实际使用的主机名称。 #### torch.distributed.run启动器 例如,要使用 `torch.distributed.run`,您可以执行以下操作: ```bash python -m torch.distributed.run --nproc_per_node=8 --nnode=2 --node_rank=0 --master_addr=hostname1 \ --master_port=9901 your_program.py <normal cl args> --deepspeed ds_config.json ``` 您必须 ssh 到每个节点,并在每个节点上运行相同的命令!不用担心,启动器会等待两个节点同步完成。 有关更多信息,请参阅 [torchrun](https://pytorch.org/docs/stable/elastic/run.html)。顺便说一下,这也是替代了几个 PyTorch 版本前的 `torch.distributed.launch` 的启动器。 #### deepspeed启动器 要改用 `deepspeed` 启动器,首先需要创建一个 `hostfile` 文件: ``` hostname1 slots=8 hostname2 slots=8 ``` 然后,您可以这样启动: ```bash deepspeed --num_gpus 8 --num_nodes 2 --hostfile hostfile --master_addr hostname1 --master_port=9901 \ your_program.py <normal cl args> --deepspeed ds_config.json ``` 与 `torch.distributed.run` 启动器不同,`deepspeed` 将自动在两个节点上启动此命令! 更多信息,请参阅[资源配置(多节点)](https://www.deepspeed.ai/getting-started/#resource-configuration-multi-node)。 #### 在 SLURM 环境中启动 在 SLURM 环境中,可以采用以下方法。以下是一个 SLURM 脚本 `launch.slurm`,您需要根据您的具体 SLURM 环境进行调整。 ```bash #SBATCH --job-name=test-nodes # name #SBATCH --nodes=2 # nodes #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! #SBATCH --cpus-per-task=10 # number of cores per tasks #SBATCH --gres=gpu:8 # number of gpus #SBATCH --time 20:00:00 # maximum execution time (HH:MM:SS) #SBATCH --output=%x-%j.out # output file name export GPUS_PER_NODE=8 export MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) export MASTER_PORT=9901 srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ your_program.py <normal cl args> --deepspeed ds_config.json' ``` 剩下的就是运行它: ```bash sbatch launch.slurm ``` `srun` 将负责在所有节点上同时启动程序。 #### 使用非共享文件系统 默认情况下,DeepSpeed 假定多节点环境使用共享存储。如果不是这种情况,每个节点只能看到本地文件系统,你需要调整配置文件,包含一个 [`checkpoint` 部分](https://www.deepspeed.ai/docs/config-json/#checkpoint-options)并设置如下选项: ```json { "checkpoint": { "use_node_local_storage": true } } ``` 或者,你还可以使用 [`Trainer`] 的 `--save_on_each_node` 参数,上述配置将自动添加。 <a id='deepspeed-notebook'></a> ### 在Notebooks启用 在将`notebook cells`作为脚本运行的情况下,问题在于没有正常的 `deepspeed` 启动器可依赖,因此在某些设置下,我们必须仿真运行它。 如果您只使用一个 GPU,以下是如何调整notebook中的训练代码以使用 DeepSpeed。 ```python # DeepSpeed requires a distributed environment even when only one process is used. # This emulates a launcher in the notebook import os os.environ["MASTER_ADDR"] = "localhost" os.environ["MASTER_PORT"] = "9994" # modify if RuntimeError: Address already in use os.environ["RANK"] = "0" os.environ["LOCAL_RANK"] = "0" os.environ["WORLD_SIZE"] = "1" # Now proceed as normal, plus pass the deepspeed config file training_args = TrainingArguments(..., deepspeed="ds_config_zero3.json") trainer = Trainer(...) trainer.train() ``` 注意:`...` 代表您传递给函数的正常参数。 如果要使用多于一个 GPU,您必须在 DeepSpeed 中使用多进程环境。也就是说,您必须使用专门的启动器来实现这一目的,而不能通过仿真本节开头呈现的分布式环境来完成。 如果想要在notebook中动态创建配置文件并保存在当前目录,您可以在一个专用的cell中使用: ```python no-style %%bash cat <<'EOT' > ds_config_zero3.json { "fp16": { "enabled": "auto", "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 }, "optimizer": { "type": "AdamW", "params": { "lr": "auto", "betas": "auto", "eps": "auto", "weight_decay": "auto" } }, "scheduler": { "type": "WarmupLR", "params": { "warmup_min_lr": "auto", "warmup_max_lr": "auto", "warmup_num_steps": "auto" } }, "zero_optimization": { "stage": 3, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "offload_param": { "device": "cpu", "pin_memory": true }, "overlap_comm": true, "contiguous_gradients": true, "sub_group_size": 1e9, "reduce_bucket_size": "auto", "stage3_prefetch_bucket_size": "auto", "stage3_param_persistence_threshold": "auto", "stage3_max_live_parameters": 1e9, "stage3_max_reuse_distance": 1e9, "stage3_gather_16bit_weights_on_model_save": true }, "gradient_accumulation_steps": "auto", "gradient_clipping": "auto", "steps_per_print": 2000, "train_batch_size": "auto", "train_micro_batch_size_per_gpu": "auto", "wall_clock_breakdown": false } EOT ``` 如果训练脚本在一个普通文件中而不是在notebook cells中,您可以通过笔记本中的 shell 正常启动 `deepspeed`。例如,要使用 `run_translation.py`,您可以这样启动: ```python no-style !git clone https://github.com/huggingface/transformers !cd transformers; deepspeed examples/pytorch/translation/run_translation.py ... ``` 或者使用 `%%bash` 魔术命令,您可以编写多行代码,用于运行 shell 程序: ```python no-style %%bash git clone https://github.com/huggingface/transformers cd transformers deepspeed examples/pytorch/translation/run_translation.py ... ``` 在这种情况下,您不需要本节开头呈现的任何代码。 注意:虽然 `%%bash` 魔术命令很方便,但目前它会缓冲输出,因此在进程完成之前您看不到日志。 <a id='deepspeed-config'></a> ### 配置 有关可以在 DeepSpeed 配置文件中使用的完整配置选项的详细指南,请参阅[以下文档](https://www.deepspeed.ai/docs/config-json/)。 您可以在 [DeepSpeedExamples 仓库](https://github.com/deepspeedai/DeepSpeedExamples)中找到解决各种实际需求的数十个 DeepSpeed 配置示例。 ```bash git clone https://github.com/deepspeedai/DeepSpeedExamples cd DeepSpeedExamples find . -name '*json' ``` 延续上面的代码,假设您要配置 Lamb 优化器。那么您可以通过以下方式在示例的 `.json` 文件中进行搜索: ```bash grep -i Lamb $(find . -name '*json') ``` 还可以在[主仓](https://github.com/deepspeedai/DeepSpeed)中找到更多示例。 在使用 DeepSpeed 时,您总是需要提供一个 DeepSpeed 配置文件,但是一些配置参数必须通过命令行进行配置。您将在本指南的剩余章节找到这些细微差别。 为了了解 DeepSpeed 配置文件,这里有一个激活 ZeRO stage 2 功能的示例,包括优化器状态的 CPU offload,使用 `AdamW` 优化器和 `WarmupLR` 调度器,并且如果传递了 `--fp16` 参数将启用混合精度训练: ```json { "fp16": { "enabled": "auto", "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 }, "optimizer": { "type": "AdamW", "params": { "lr": "auto", "betas": "auto", "eps": "auto", "weight_decay": "auto" } }, "scheduler": { "type": "WarmupLR", "params": { "warmup_min_lr": "auto", "warmup_max_lr": "auto", "warmup_num_steps": "auto" } }, "zero_optimization": { "stage": 2, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "allgather_partitions": true, "allgather_bucket_size": 2e8, "overlap_comm": true, "reduce_scatter": true, "reduce_bucket_size": 2e8, "contiguous_gradients": true }, "gradient_accumulation_steps": "auto", "gradient_clipping": "auto", "train_batch_size": "auto", "train_micro_batch_size_per_gpu": "auto", } ``` 当您执行程序时,DeepSpeed 将把它从 [`Trainer`] 收到的配置日志输出到console,因此您可以看到传递给它的最终配置。 <a id='deepspeed-config-passing'></a> ### 传递配置 正如本文档讨论的那样,通常将 DeepSpeed 配置作为指向 JSON 文件的路径传递,但如果您没有使用命令行界面配置训练,而是通过 [`TrainingArguments`] 实例化 [`Trainer`],那么对于 `deepspeed` 参数,你可以传递一个嵌套的 `dict`。这使您能够即时创建配置,而无需在将其传递给 [`TrainingArguments`] 之前将其写入文件系统。 总结起来,您可以这样做: ```python TrainingArguments(..., deepspeed="/path/to/ds_config.json") ``` 或者: ```python ds_config_dict = dict(scheduler=scheduler_params, optimizer=optimizer_params) TrainingArguments(..., deepspeed=ds_config_dict) ``` <a id='deepspeed-config-shared'></a> ### 共享配置 <Tip warning={true}> 这一部分是必读的。 </Tip> 一些配置值对于 [`Trainer`] 和 DeepSpeed 正常运行都是必需的,因此,为了防止定义冲突及导致的难以检测的错误,我们选择通过 [`Trainer`] 命令行参数配置这些值。 此外,一些配置值是基于模型的配置自动派生的,因此,与其记住手动调整多个值,最好让 [`Trainer`] 为您做大部分配置。 因此,在本指南的其余部分,您将找到一个特殊的配置值:`auto`,当设置时将自动将参数替换为正确或最有效的值。请随意选择忽略此建议或显式设置该值,在这种情况下,请务必确保 [`Trainer`] 参数和 DeepSpeed 配置保持一致。例如,您是否使用相同的学习率、批量大小或梯度累积设置?如果这些不匹配,训练可能以非常难以检测的方式失败。请重视该警告。 还有一些参数是仅适用于 DeepSpeed 的,并且这些参数必须手动设置以适应您的需求。 在您自己的程序中,如果您想要作为主动修改 DeepSpeed 配置并以此配置 [`TrainingArguments`],您还可以使用以下方法。步骤如下: 1. 创建或加载要用作主配置的 DeepSpeed 配置 2. 根据这些参数值创建 [`TrainingArguments`] 对象 请注意,一些值,比如 `scheduler.params.total_num_steps`,是在 [`Trainer`] 的 `train` 过程中计算的,但当然您也可以自己计算这些值。 <a id='deepspeed-zero'></a> ### ZeRO [Zero Redundancy Optimizer (ZeRO)](https://www.deepspeed.ai/tutorials/zero/) 是 DeepSpeed 的工作核心。它支持3个不同级别(stages)的优化。Stage 1 对于扩展性来说不是很有趣,因此本文档重点关注Stage 2和Stage 3。Stage 3通过最新的 ZeRO-Infinity 进一步改进。你可以在 DeepSpeed 文档中找到更详细的信息。 配置文件的 `zero_optimization` 部分是最重要的部分([文档](https://www.deepspeed.ai/docs/config-json/#zero-optimizations-for-fp16-training)),因为在这里您定义了要启用哪些 ZeRO stages 以及如何配置它们。您可以在 DeepSpeed 文档中找到每个参数的解释。 这一部分必须通过 DeepSpeed 配置文件单独配置 - [`Trainer`] 不提供相应的命令行参数。 注意:目前 DeepSpeed 不验证参数名称,因此如果您拼错了任何参数,它将使用拼写错误的参数的默认设置。您可以观察 DeepSpeed 引擎启动日志消息,看看它将使用哪些值。 <a id='deepspeed-zero2-config'></a> #### ZeRO-2 配置 以下是 ZeRO stage 2 的配置示例: ```json { "zero_optimization": { "stage": 2, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "allgather_partitions": true, "allgather_bucket_size": 5e8, "overlap_comm": true, "reduce_scatter": true, "reduce_bucket_size": 5e8, "contiguous_gradients": true } } ``` **性能调优:** - 启用 `offload_optimizer` 应该减少 GPU 内存使用(需要 `"stage": 2`)。 - `"overlap_comm": true` 通过增加 GPU 内存使用来降低all-reduce 的延迟。 `overlap_comm` 使用了 `allgather_bucket_size` 和 `reduce_bucket_size` 值的4.5倍。因此,如果它们设置为 `5e8`,这将需要一个9GB的内存占用(`5e8 x 2Bytes x 2 x 4.5`)。因此,如果您的 GPU 内存为8GB或更小,为了避免出现OOM错误,您需要将这些参数减小到约 `2e8`,这将需要3.6GB。如果您的 GPU 容量更大,当您开始遇到OOM时,你可能也需要这样做。 - 当减小这些buffers时,您以更慢的通信速度来换取更多的 GPU 内存。buffers大小越小,通信速度越慢,GPU 可用于其他任务的内存就越多。因此,如果更大的批处理大小很重要,那么稍微减慢训练时间可能是一个很好的权衡。 此外,`deepspeed==0.4.4` 添加了一个新选项 `round_robin_gradients`,您可以通过以下方式启用: ```json { "zero_optimization": { "round_robin_gradients": true } } ``` 这是一个用于 CPU offloading 的stage 2优化,通过细粒度梯度分区在 ranks 之间并行复制到 CPU 内存,从而实现了性能的提升。性能优势随着梯度累积步骤(在优化器步骤之间进行更多复制)或 GPU 数量(增加并行性)增加而增加。 <a id='deepspeed-zero3-config'></a> #### ZeRO-3 配置 以下是 ZeRO stage 3的配置示例: ```json { "zero_optimization": { "stage": 3, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "offload_param": { "device": "cpu", "pin_memory": true }, "overlap_comm": true, "contiguous_gradients": true, "sub_group_size": 1e9, "reduce_bucket_size": "auto", "stage3_prefetch_bucket_size": "auto", "stage3_param_persistence_threshold": "auto", "stage3_max_live_parameters": 1e9, "stage3_max_reuse_distance": 1e9, "stage3_gather_16bit_weights_on_model_save": true } } ``` 如果您因为你的模型或激活值超过 GPU 内存而遇到OOM问题,并且您有未使用的 CPU 内存,可以通股票使用 `"device": "cpu"` 将优化器状态和参数卸载到 CPU 内存中,来解决这个限制。如果您不想卸载到 CPU 内存,可以在 `device` 条目中使用 `none` 代替 `cpu`。将优化器状态卸载到 NVMe 上会在后面进一步讨论。 通过将 `pin_memory` 设置为 `true` 启用固定内存。此功能会以减少可用于其他进程的内存为代价来提高吞吐量。固定内存被分配给特定请求它的进程,通常比普通 CPU 内存访问速度更快。 **性能调优:** - `stage3_max_live_parameters`: `1e9` - `stage3_max_reuse_distance`: `1e9` 如果遇到OOM问题,请减小 `stage3_max_live_parameters` 和 `stage3_max_reuse_distance`。它们对性能的影响应该很小,除非您正在进行激活值checkpointing。`1e9` 大约会消耗 ~2GB。内存由 `stage3_max_live_parameters` 和 `stage3_max_reuse_distance` 共享,所以它不是叠加的,而是总共2GB。 `stage3_max_live_parameters` 是在任何给定时间要在 GPU 上保留多少个完整参数的上限。"reuse distance" 是我们用来确定参数在将来何时会再次使用的度量标准,我们使用 `stage3_max_reuse_distance` 来决定是丢弃参数还是保留参数。如果一个参数在不久的将来(小于 `stage3_max_reuse_distance`)将被再次使用,那么我们将其保留以减少通信开销。这在启用激活值checkpoing时非常有用,其中我们以单层粒度进行前向重计算和反向传播,并希望在反向传播期间保留前向重计算中的参数。 以下配置值取决于模型的隐藏大小: - `reduce_bucket_size`: `hidden_size*hidden_size` - `stage3_prefetch_bucket_size`: `0.9 * hidden_size * hidden_size` - `stage3_param_persistence_threshold`: `10 * hidden_size` 因此,将这些值设置为 `auto`,[`Trainer`] 将自动分配推荐的参数值。当然,如果您愿意,也可以显式设置这些值。 `stage3_gather_16bit_weights_on_model_save` 在模型保存时启用模型的 fp16 权重整合。对于大模型和多个 GPU,无论是在内存还是速度方面,这都是一项昂贵的操作。目前如果计划恢复训练,这是必需的。请注意未来的更新可能会删除此限制并让使用更加灵活。 如果您从 ZeRO-2 配置迁移,请注意 `allgather_partitions`、`allgather_bucket_size` 和 `reduce_scatter` 配置参数在 ZeRO-3 中不被使用。如果保留这些配置文件,它们将被忽略。 - `sub_group_size`: `1e9` `sub_group_size` 控制在优化器步骤期间更新参数的粒度。参数被分组到大小为 `sub_group_size` 的桶中,每个桶逐个更新。在 ZeRO-Infinity 中与 NVMe offload一起使用时,`sub_group_size` 控制了在优化器步骤期间在 NVMe 和 CPU 内存之间移动模型状态的粒度。这可以防止非常大的模型耗尽 CPU 内存。 当不使用 NVMe offload时,可以将 `sub_group_size` 保留为其默认值 *1e9*。在以下情况下,您可能需要更改其默认值: 1. 在优化器步骤中遇到OOM:减小 `sub_group_size` 以减少临时buffers的内存利用 2. 优化器步骤花费很长时间:增加 `sub_group_size` 以提高由于增加的数据buffers而导致的带宽利用率。 #### ZeRO-0 配置 请注意,我们将 Stage 0 和 1 放在最后,因为它们很少使用。 Stage 0 禁用了所有类型的分片,只是将 DeepSpeed 作为 DDP 使用。您可以通过以下方式启用: ```json { "zero_optimization": { "stage": 0 } } ``` 这将实质上禁用 ZeRO,而无需更改其他任何内容。 #### ZeRO-1 配置 Stage 1 等同于 Stage 2 减去梯度分片。您可以尝试使用以下配置,仅对优化器状态进行分片,以稍微加速: ```json { "zero_optimization": { "stage": 1 } } ``` <a id='deepspeed-nvme'></a> ### NVMe 支持 ZeRO-Infinity 通过使用 NVMe 内存扩展 GPU 和 CPU 内存,从而允许训练非常大的模型。由于智能分区和平铺算法,在offload期间每个 GPU 需要发送和接收非常小量的数据,因此 NVMe 被证明适用于训练过程中提供更大的总内存池。ZeRO-Infinity 需要启用 ZeRO-3。 以下配置示例启用 NVMe 来offload优化器状态和参数: ```json { "zero_optimization": { "stage": 3, "offload_optimizer": { "device": "nvme", "nvme_path": "/local_nvme", "pin_memory": true, "buffer_count": 4, "fast_init": false }, "offload_param": { "device": "nvme", "nvme_path": "/local_nvme", "pin_memory": true, "buffer_count": 5, "buffer_size": 1e8, "max_in_cpu": 1e9 }, "aio": { "block_size": 262144, "queue_depth": 32, "thread_count": 1, "single_submit": false, "overlap_events": true }, "overlap_comm": true, "contiguous_gradients": true, "sub_group_size": 1e9, "reduce_bucket_size": "auto", "stage3_prefetch_bucket_size": "auto", "stage3_param_persistence_threshold": "auto", "stage3_max_live_parameters": 1e9, "stage3_max_reuse_distance": 1e9, "stage3_gather_16bit_weights_on_model_save": true }, } ``` 您可以选择将优化器状态和参数都卸载到 NVMe,也可以只选择其中一个,或者都不选择。例如,如果您有大量的 CPU 内存可用,只卸载到 CPU 内存训练速度会更快(提示:"device": "cpu")。 这是有关卸载 [优化器状态](https://www.deepspeed.ai/docs/config-json/#optimizer-offloading) 和 [参数](https://www.deepspeed.ai/docs/config-json/#parameter-offloading) 的完整文档。 确保您的 `nvme_path` 实际上是一个 NVMe,因为它与普通硬盘或 SSD 一起工作,但速度会慢得多。快速可扩展的训练是根据现代 NVMe 传输速度设计的(截至本文撰写时,可以达到 ~3.5GB/s 读取,~3GB/s 写入的峰值速度)。 为了找出最佳的 `aio` 配置块,您必须在目标设置上运行一个基准测试,具体操作请参见[说明](https://github.com/deepspeedai/DeepSpeed/issues/998)。 <a id='deepspeed-zero2-zero3-performance'></a> #### ZeRO-2 和 ZeRO-3 性能对比 如果其他一切都配置相同,ZeRO-3 可能比 ZeRO-2 慢,因为前者除了 ZeRO-2 的操作外,还必须收集模型权重。如果 ZeRO-2 满足您的需求,而且您不需要扩展到几个 GPU 以上,那么您可以选择继续使用它。重要的是要理解,ZeRO-3 以速度为代价实现了更高的可扩展性。 可以调整 ZeRO-3 配置使其性能接近 ZeRO-2: - 将 `stage3_param_persistence_threshold` 设置为一个非常大的数字 - 大于最大的参数,例如 `6 * hidden_size * hidden_size`。这将保留参数在 GPU 上。 - 关闭 `offload_params`,因为 ZeRO-2 没有这个选项。 即使不更改 `stage3_param_persistence_threshold`,仅将 `offload_params` 关闭,性能可能会显著提高。当然,这些更改将影响您可以训练的模型的大小。因此,这些更改可根据需求帮助您在可扩展性和速度之间进行权衡。 <a id='deepspeed-zero2-example'></a> #### ZeRO-2 示例 这是一个完整的 ZeRO-2 自动配置文件 `ds_config_zero2.json`: ```json { "fp16": { "enabled": "auto", "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 }, "optimizer": { "type": "AdamW", "params": { "lr": "auto", "betas": "auto", "eps": "auto", "weight_decay": "auto" } }, "scheduler": { "type": "WarmupLR", "params": { "warmup_min_lr": "auto", "warmup_max_lr": "auto", "warmup_num_steps": "auto" } }, "zero_optimization": { "stage": 2, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "allgather_partitions": true, "allgather_bucket_size": 2e8, "overlap_comm": true, "reduce_scatter": true, "reduce_bucket_size": 2e8, "contiguous_gradients": true }, "gradient_accumulation_steps": "auto", "gradient_clipping": "auto", "steps_per_print": 2000, "train_batch_size": "auto", "train_micro_batch_size_per_gpu": "auto", "wall_clock_breakdown": false } ``` 这是一个完整的手动设置的启用所有功能的 ZeRO-2 配置文件。主要是为了让您看到典型的参数值是什么样的,但我们强烈建议使用其中包含多个 `auto` 设置的配置文件。 ```json { "fp16": { "enabled": true, "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 }, "optimizer": { "type": "AdamW", "params": { "lr": 3e-5, "betas": [0.8, 0.999], "eps": 1e-8, "weight_decay": 3e-7 } }, "scheduler": { "type": "WarmupLR", "params": { "warmup_min_lr": 0, "warmup_max_lr": 3e-5, "warmup_num_steps": 500 } }, "zero_optimization": { "stage": 2, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "allgather_partitions": true, "allgather_bucket_size": 2e8, "overlap_comm": true, "reduce_scatter": true, "reduce_bucket_size": 2e8, "contiguous_gradients": true }, "steps_per_print": 2000, "wall_clock_breakdown": false } ``` <a id='deepspeed-zero3-example'></a> #### ZeRO-3 示例 这是一个完整的 ZeRO-3 自动配置文件 `ds_config_zero3.json`: ```json { "fp16": { "enabled": "auto", "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 }, "optimizer": { "type": "AdamW", "params": { "lr": "auto", "betas": "auto", "eps": "auto", "weight_decay": "auto" } }, "scheduler": { "type": "WarmupLR", "params": { "warmup_min_lr": "auto", "warmup_max_lr": "auto", "warmup_num_steps": "auto" } }, "zero_optimization": { "stage": 3, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "offload_param": { "device": "cpu", "pin_memory": true }, "overlap_comm": true, "contiguous_gradients": true, "sub_group_size": 1e9, "reduce_bucket_size": "auto", "stage3_prefetch_bucket_size": "auto", "stage3_param_persistence_threshold": "auto", "stage3_max_live_parameters": 1e9, "stage3_max_reuse_distance": 1e9, "stage3_gather_16bit_weights_on_model_save": true }, "gradient_accumulation_steps": "auto", "gradient_clipping": "auto", "steps_per_print": 2000, "train_batch_size": "auto", "train_micro_batch_size_per_gpu": "auto", "wall_clock_breakdown": false } ``` 这是一个完整的 手动设置的启用所有功能的ZeRO-3 配置文件。主要是为了让您看到典型的参数值是什么样的,但我们强烈建议使用其中包含多个 `auto` 设置的配置文件。 ```json { "fp16": { "enabled": true, "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 }, "optimizer": { "type": "AdamW", "params": { "lr": 3e-5, "betas": [0.8, 0.999], "eps": 1e-8, "weight_decay": 3e-7 } }, "scheduler": { "type": "WarmupLR", "params": { "warmup_min_lr": 0, "warmup_max_lr": 3e-5, "warmup_num_steps": 500 } }, "zero_optimization": { "stage": 3, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "offload_param": { "device": "cpu", "pin_memory": true }, "overlap_comm": true, "contiguous_gradients": true, "sub_group_size": 1e9, "reduce_bucket_size": 1e6, "stage3_prefetch_bucket_size": 0.94e6, "stage3_param_persistence_threshold": 1e4, "stage3_max_live_parameters": 1e9, "stage3_max_reuse_distance": 1e9, "stage3_gather_16bit_weights_on_model_save": true }, "steps_per_print": 2000, "wall_clock_breakdown": false } ``` #### 如何选择最佳性能的ZeRO Stage和 offloads 了解了这些不同stages后,现在您需要决定使用哪个stage。本节将尝试回答这个问题。 通常,以下规则适用: - 速度方面(左边比右边快) stage 0(DDP) > stage 1 > stage 2 > stage 2 + offload > stage 3 > stage3 + offload - GPU内存使用方面(右边比左边更节省GPU内存) stage 0(DDP) < stage 1 < stage 2 < stage 2 + offload < stage 3 < stage 3 + offload 所以,当您希望在尽量使用较少数量的GPU的同时获得最快的执行速度时,可以按照以下步骤进行。我们从最快的方法开始,如果遇到GPU内存溢出,然后切换到下一个速度较慢但使用的GPU内存更少的方法。以此类推。 首先,将批量大小设置为1(您始终可以使用梯度累积来获得任何所需的有效批量大小)。 1. 启用 `--gradient_checkpointing 1`(HF Trainer)或直接 `model.gradient_checkpointing_enable()` - 如果发生OOM(Out of Memory),则执行以下步骤。 2. 首先尝试 ZeRO stage 2。如果发生OOM,则执行以下步骤。 3. 尝试 ZeRO stage 2 + `offload_optimizer` - 如果发生OOM,则执行以下步骤。 4. 切换到 ZeRO stage 3 - 如果发生OOM,则执行以下步骤。 5. 启用 `offload_param` 到 `cpu` - 如果发生OOM,则执行以下步骤。 6. 启用 `offload_optimizer` 到 `cpu` - 如果发生OOM,则执行以下步骤。 7. 如果仍然无法适应批量大小为1,请首先检查各种默认值并尽可能降低它们。例如,如果使用 `generate` 并且不使用宽搜索束,将其缩小,因为它会占用大量内存。 8. 绝对要使用混合半精度而非fp32 - 在Ampere及更高的GPU上使用bf16,在旧的GPU体系结构上使用fp16。 9. 如果仍然发生OOM,可以添加更多硬件或启用ZeRO-Infinity - 即切换 `offload_param` 和 `offload_optimizer` 到 `nvme`。您需要确保它是非常快的NVMe。作为趣闻,我曾经能够在一个小型GPU上使用BLOOM-176B进行推理,使用了ZeRO-Infinity,尽管速度非常慢。但它奏效了! 当然,您也可以按相反的顺序进行这些步骤,从最节省GPU内存的配置开始,然后逐步反向进行,或者尝试进行二分法。 一旦您的批量大小为1不会导致OOM,就测量您的有效吞吐量。 接下来尝试将批量大小增加到尽可能大,因为批量大小越大,GPU的效率越高,特别是在它们乘法运算的矩阵很大时。 现在性能优化游戏开始了。您可以关闭一些offload特性,或者降低ZeRO stage,并增加/减少批量大小,再次测量有效吞吐量。反复尝试,直到满意为止。 不要花费太多时间,但如果您即将开始一个为期3个月的训练 - 请花几天时间找到吞吐量方面最有效的设置。这样您的训练成本将最低,而且您会更快地完成训练。在当前快节奏的机器学习世界中,如果您花费一个额外的月份来训练某样东西,你很可能会错过一个黄金机会。当然,这只是我分享的一种观察,我并不是在催促你。在开始训练BLOOM-176B之前,我花了2天时间进行这个过程,成功将吞吐量从90 TFLOPs提高到150 TFLOPs!这一努力为我们节省了一个多月的训练时间。 这些注释主要是为训练模式编写的,但它们在推理中也应该大部分适用。例如,在推理中,Gradient Checkpointing 是无用的,因为它只在训练过程中有用。此外,我们发现,如果你正在进行多GPU推理并且不使用 [DeepSpeed-Inference](https://www.deepspeed.ai/tutorials/inference-tutorial/),[Accelerate](https://huggingface.co/blog/bloom-inference-pytorch-scripts) 应该提供更优越的性能。 其他与性能相关的快速注释: - 如果您从头开始训练某个模型,请尽量确保张量的形状可以被16整除(例如隐藏层大小)。对于批量大小,至少尝试可被2整除。如果您想从GPU中挤取更高性能,还有一些硬件特定的[wave和tile量化](https://developer.nvidia.com/blog/optimizing-gpu-performance-tensor-cores/)的可整除性。 ### Activation Checkpointing 或 Gradient Checkpointing Activation Checkpointing和Gradient Checkpointing是指相同方法的两个不同术语。这确实让人感到困惑,但事实就是这样。 Gradient Checkpointing允许通过牺牲速度来换取GPU内存,这要么使您能够克服GPU内存溢出,要么增加批量大小来获得更好的性能。 HF Transformers 模型对DeepSpeed的Activation Checkpointing一无所知,因此如果尝试在DeepSpeed配置文件中启用该功能,什么都不会发生。 因此,您有两种方法可以利用这个非常有益的功能: 1. 如果您想使用 HF Transformers 模型,你可以使用 `model.gradient_checkpointing_enable()` 或在 HF Trainer 中使用 `--gradient_checkpointing`,它会自动为您启用这个功能。在这里使用了 `torch.utils.checkpoint`。 2. 如果您编写自己的模型并希望使用DeepSpeed的Activation Checkpointing,可以使用[规定的API](https://deepspeed.readthedocs.io/en/latest/activation-checkpointing.html)。您还可以使用 HF Transformers 的模型代码,将 `torch.utils.checkpoint` 替换为 DeepSpeed 的API。后者更灵活,因为它允许您将前向激活值卸载到CPU内存,而不是重新计算它们。 ### Optimizer 和 Scheduler 只要你不启用 `offload_optimizer`,您可以混合使用DeepSpeed和HuggingFace的调度器和优化器,但有一个例外,即不要使用HuggingFace调度器和DeepSpeed优化器的组合: | Combos | HF Scheduler | DS Scheduler | |:-------------|:-------------|:-------------| | HF Optimizer | Yes | Yes | | DS Optimizer | No | Yes | 在启用 `offload_optimizer` 的情况下,可以使用非DeepSpeed优化器,只要该优化器具有CPU和GPU的实现(除了LAMB)。 <a id='deepspeed-optimizer'></a> #### Optimizer DeepSpeed的主要优化器包括Adam、AdamW、OneBitAdam和Lamb。这些优化器已经与ZeRO进行了彻底的测试,因此建议使用它们。然而,也可以导入`torch`中的其他优化器。完整的文档在[这里](https://www.deepspeed.ai/docs/config-json/#optimizer-parameters)。 如果在配置文件中不配置`optimizer`条目,[`Trainer`] 将自动将其设置为 `AdamW`,并使用提供的值或以下命令行参数的默认值:`--learning_rate`、`--adam_beta1`、`--adam_beta2`、`--adam_epsilon` 和 `--weight_decay`。 以下是`AdamW` 的自动配置示例: ```json { "optimizer": { "type": "AdamW", "params": { "lr": "auto", "betas": "auto", "eps": "auto", "weight_decay": "auto" } } } ``` 请注意,命令行参数将设置配置文件中的值。这是为了有一个明确的值来源,并避免在不同地方设置学习率等值时难以找到的错误。命令行参数配置高于其他。被覆盖的值包括: - `lr` 的值为 `--learning_rate` - `betas` 的值为 `--adam_beta1 --adam_beta2` - `eps` 的值为 `--adam_epsilon` - `weight_decay` 的值为 `--weight_decay` 因此,请记住在命令行上调整共享的超参数。 您也可以显式地设置这些值: ```json { "optimizer": { "type": "AdamW", "params": { "lr": 0.001, "betas": [0.8, 0.999], "eps": 1e-8, "weight_decay": 3e-7 } } } ``` 但在这种情况下,您需要自己同步[`Trainer`]命令行参数和DeepSpeed配置。 如果您想使用上面未列出的其他优化器,您将不得不将其添加到顶层配置中。 ```json { "zero_allow_untested_optimizer": true } ``` 类似于 `AdamW`,您可以配置其他官方支持的优化器。只是记住这些可能有不同的配置值。例如,对于Adam,您可能需要将 `weight_decay` 设置在 `0.01` 左右。 此外,当与DeepSpeed的CPU Adam优化器一起使用时,offload的效果最好。如果您想在offload时使用不同的优化器,自 `deepspeed==0.8.3` 起,您还需要添加: ```json { "zero_force_ds_cpu_optimizer": false } ``` 到顶层配置中。 <a id='deepspeed-scheduler'></a> #### Scheduler DeepSpeed支持`LRRangeTest`、`OneCycle`、`WarmupLR`和`WarmupDecayLR`学习率调度器。完整文档在[这里](https://www.deepspeed.ai/docs/config-json/#scheduler-parameters)。 以下是🤗 Transformers 和 DeepSpeed 之间的调度器重叠部分: - 通过 `--lr_scheduler_type constant_with_warmup` 实现 `WarmupLR` - 通过 `--lr_scheduler_type linear` 实现 `WarmupDecayLR`。这也是 `--lr_scheduler_type` 的默认值,因此,如果不配置调度器,这将是默认配置的调度器。 如果在配置文件中不配置 `scheduler` 条目,[`Trainer`] 将使用 `--lr_scheduler_type`、`--learning_rate` 和 `--warmup_steps` 的值来配置其🤗 Transformers 版本。 以下是 `WarmupLR` 的自动配置示例: ```json { "scheduler": { "type": "WarmupLR", "params": { "warmup_min_lr": "auto", "warmup_max_lr": "auto", "warmup_num_steps": "auto" } } } ``` 由于使用了 *"auto"*,[`Trainer`] 的参数将在配置文件中设置正确的值。这是为了有一个明确的值来源,并避免在不同地方设置学习率等值时难以找到的错误。命令行配置高于其他。被设置的值包括: - `warmup_min_lr` 的值为 `0`。 - `warmup_max_lr` 的值为 `--learning_rate`。 - `warmup_num_steps` 的值为 `--warmup_steps`(如果提供)。 - `total_num_steps` 的值为 `--max_steps` 或者如果没有提供,将在运行时根据环境、数据集的大小和其他命令行参数(对于 `WarmupDecayLR` 来说需要)自动推导。 当然,您可以接管任何或所有的配置值,并自行设置这些值: ```json { "scheduler": { "type": "WarmupLR", "params": { "warmup_min_lr": 0, "warmup_max_lr": 0.001, "warmup_num_steps": 1000 } } } ``` 但在这种情况下,您需要自己同步[`Trainer`]命令行参数和DeepSpeed配置。 例如,对于 `WarmupDecayLR`,您可以使用以下条目: ```json { "scheduler": { "type": "WarmupDecayLR", "params": { "last_batch_iteration": -1, "total_num_steps": "auto", "warmup_min_lr": "auto", "warmup_max_lr": "auto", "warmup_num_steps": "auto" } } } ``` 然后,`total_num_steps`、`warmup_max_lr`、`warmup_num_steps` 和 `total_num_steps` 将在加载时设置。 <a id='deepspeed-fp32'></a> ### fp32精度 DeepSpeed支持完整的fp32和fp16混合精度。 由于fp16混合精度具有更小的内存需求和更快的速度,唯一不使用它的时候是当您使用的模型在这种训练模式下表现不佳时。通常,当模型没有在fp16混合精度下进行预训练时(例如,bf16预训练模型经常出现这种情况),会出现这种情况。这样的模型可能会发生溢出或下溢,导致 `NaN` 损失。如果是这种情况,那么您将希望使用完整的fp32模式,通过显式禁用默认启用的fp16混合精度模式: ```json { "fp16": { "enabled": false, } } ``` 如果您使用基于Ampere架构的GPU,PyTorch版本1.7及更高版本将自动切换到使用更高效的tf32格式进行一些操作,但结果仍将以fp32格式呈现。有关详细信息和基准测试,请参见[TensorFloat-32(TF32) on Ampere devices](https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices)。如果出于某种原因您不希望使用它,该文档包括有关如何禁用此自动转换的说明。 在🤗 Trainer中,你可以使用 `--tf32` 来启用它,或使用 `--tf32 0` 或 `--no_tf32` 来禁用它。默认情况下,使用PyTorch的默认设置。 <a id='deepspeed-amp'></a> ### 自动混合精度 ### fp16 要配置PyTorch AMP-like 的 fp16(float16) 模式,请设置: ```json { "fp16": { "enabled": "auto", "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 } } ``` [`Trainer`]将根据`fp16`或`fp16_full_eval`的值自动启用或禁用它。其余的配置值由您决定。 当传递`--fp16`或`--fp16_full_eval`命令行参数时,此模式将被启用。 您也可以显式地启用/禁用此模式: ```json { "fp16": { "enabled": true, "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 } } ``` 但是之后您需要自己同步[`Trainer`]命令行参数和DeepSpeed配置。 以下是[相关文档](https://www.deepspeed.ai/docs/config-json/#fp16-training-options) ### bf16 如果需要使用bfloat16而不是fp16,那么可以使用以下配置部分: ```json { "bf16": { "enabled": "auto" } } ``` bf16具有与fp32相同的动态范围,因此不需要损失缩放。 当传递`--bf16`或`--bf16_full_eval`命令行参数时,启用此模式。 您还可以显式地启用/禁用此模式: ```json { "bf16": { "enabled": true } } ``` <Tip> 在`deepspeed==0.6.0`版本中,bf16支持是新的实验性功能。 如果您启用了bf16来进行[梯度累积](#gradient-accumulation),您需要意识到它会以bf16累积梯度,这可能不是您想要的,因为这种格式的低精度可能会导致lossy accumulation。 修复这个问题的工作正在努力进行,同时提供了使用更高精度的`dtype`(fp16或fp32)的选项。 </Tip> ### NCCL集合 在训练过程中,有两种数据类型:`dtype`和用于通信收集操作的`dtype`,如各种归约和收集/分散操作。 所有的gather/scatter操作都是在数据相同的`dtype`中执行的,所以如果您正在使用bf16的训练模式,那么它将在bf16中进行gather操作 - gather操作是非损失性的。 各种reduce操作可能会是非常损失性的,例如当梯度在多个gpu上平均时,如果通信是在fp16或bf16中进行的,那么结果可能是有损失性的 - 因为当在一个低精度中添加多个数字时,结果可能不是精确的。更糟糕的是,bf16比fp16具有更低的精度。通常,当平均梯度时,损失最小,这些梯度通常非常小。因此,对于半精度训练,默认情况下,fp16被用作reduction操作的默认值。但是,您可以完全控制这个功能,如果你选择的话,您可以添加一个小的开销,并确保reductions将使用fp32作为累积数据类型,只有当结果准备好时,它才会降级到您在训练中使用的半精度`dtype`。 要覆盖默认设置,您只需添加一个新的配置条目: ```json { "communication_data_type": "fp32" } ``` 根据这个信息,有效的值包括"fp16"、"bfp16"和"fp32"。 注意:在stage zero 3中,bf16通信数据类型存在一个bug,该问题已在`deepspeed==0.8.1`版本中得到修复。 <a id='deepspeed-bs'></a> ### Batch Size 配置batch size可以使用如下参数: ```json { "train_batch_size": "auto", "train_micro_batch_size_per_gpu": "auto" } ``` 并且,[`Trainer`]将自动将`train_micro_batch_size_per_gpu`设置为`args.per_device_train_batch_size`的值,并将`train_batch_size`设置为`args.world_size * args.per_device_train_batch_size * args.gradient_accumulation_steps`。 您也可以显式设置这些值: ```json { "train_batch_size": 12, "train_micro_batch_size_per_gpu": 4 } ``` 但是,您需要自己同步[`Trainer`]命令行参数和DeepSpeed配置。 <a id='deepspeed-grad-acc'></a> ### Gradient Accumulation 配置gradient accumulation设置如下: ```json { "gradient_accumulation_steps": "auto" } ``` 并且,[`Trainer`]将自动将其设置为`args.gradient_accumulation_steps`的值。 您也可以显式设置这个值: ```json { "gradient_accumulation_steps": 3 } ``` 但是,您需要自己同步[`Trainer`]命令行参数和DeepSpeed配置。 <a id='deepspeed-grad-clip'></a> ### Gradient Clipping 配置gradient clipping如下: ```json { "gradient_clipping": "auto" } ``` 并且,[`Trainer`]将自动将其设置为`args.max_grad_norm`的值。 您也可以显式设置这个值: ```json { "gradient_clipping": 1.0 } ``` 但是,您需要自己同步[`Trainer`]命令行参数和DeepSpeed配置。 <a id='deepspeed-weight-extraction'></a> ### 获取模型权重 只要您继续使用DeepSpeed进行训练和恢复,您就不需要担心任何事情。DeepSpeed在其自定义检查点优化器文件中存储fp32主权重,这些文件是`global_step*/*optim_states.pt`(这是glob模式),并保存在正常的checkpoint下。 **FP16权重:** 当模型保存在ZeRO-2下时,您最终会得到一个包含模型权重的普通`pytorch_model.bin`文件,但它们只是权重的fp16版本。 在ZeRO-3下,事情要复杂得多,因为模型权重分布在多个GPU上,因此需要`"stage3_gather_16bit_weights_on_model_save": true`才能让`Trainer`保存fp16版本的权重。如果这个设置是`False`,`pytorch_model.bin`将不会被创建。这是因为默认情况下,DeepSpeed的`state_dict`包含一个占位符而不是实际的权重。如果我们保存这个`state_dict`,就无法再加载它了。 ```json { "zero_optimization": { "stage3_gather_16bit_weights_on_model_save": true } } ``` **FP32权重:** 虽然fp16权重适合恢复训练,但如果您完成了模型的微调并希望将其上传到[models hub](https://huggingface.co/models)或传递给其他人,您很可能想要获取fp32权重。这最好不要在训练期间完成,因为这需要大量内存,因此最好在训练完成后离线进行。但是,如果需要并且有充足的空闲CPU内存,可以在相同的训练脚本中完成。以下部分将讨论这两种方法。 **实时FP32权重恢复:** 如果您的模型很大,并且在训练结束时几乎没有剩余的空闲CPU内存,这种方法可能不起作用。 如果您至少保存了一个检查点,并且想要使用最新的一个,可以按照以下步骤操作: ```python from transformers.trainer_utils import get_last_checkpoint from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint checkpoint_dir = get_last_checkpoint(trainer.args.output_dir) fp32_model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) ``` 如果您在使用`--load_best_model_at_end`类:*~transformers.TrainingArguments*参数(用于跟踪最佳 检查点),那么你可以首先显式地保存最终模型,然后再执行相同的操作: ```python from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint checkpoint_dir = os.path.join(trainer.args.output_dir, "checkpoint-final") trainer.deepspeed.save_checkpoint(checkpoint_dir) fp32_model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) ``` <Tip> 注意,一旦运行了`load_state_dict_from_zero_checkpoint`,该模型将不再可以在相同的应用程序的DeepSpeed上下文中使用。也就是说,您需要重新初始化deepspeed引擎,因为`model.load_state_dict(state_dict)`会从其中移除所有的DeepSpeed相关点。所以您只能训练结束时这样做。 </Tip> 当然,您不必使用类:*~transformers.Trainer*,您可以根据你的需求调整上面的示例。 如果您出于某种原因想要更多的优化,您也可以提取权重的fp32 `state_dict`并按照以下示例进行操作: ```python from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu model = model.cpu() model.load_state_dict(state_dict) ``` **离线FP32权重恢复:** DeepSpeed会创建一个特殊的转换脚本`zero_to_fp32.py`,并将其放置在checkpoint文件夹的顶层。使用此脚本,您可以在任何时候提取权重。该脚本是独立的,您不再需要配置文件或`Trainer`来执行提取操作。 假设您的checkpoint文件夹如下所示: ```bash $ ls -l output_dir/checkpoint-1/ -rw-rw-r-- 1 stas stas 1.4K Mar 27 20:42 config.json drwxrwxr-x 2 stas stas 4.0K Mar 25 19:52 global_step1/ -rw-rw-r-- 1 stas stas 12 Mar 27 13:16 latest -rw-rw-r-- 1 stas stas 827K Mar 27 20:42 optimizer.pt -rw-rw-r-- 1 stas stas 231M Mar 27 20:42 pytorch_model.bin -rw-rw-r-- 1 stas stas 623 Mar 27 20:42 scheduler.pt -rw-rw-r-- 1 stas stas 1.8K Mar 27 20:42 special_tokens_map.json -rw-rw-r-- 1 stas stas 774K Mar 27 20:42 spiece.model -rw-rw-r-- 1 stas stas 1.9K Mar 27 20:42 tokenizer_config.json -rw-rw-r-- 1 stas stas 339 Mar 27 20:42 trainer_state.json -rw-rw-r-- 1 stas stas 2.3K Mar 27 20:42 training_args.bin -rwxrw-r-- 1 stas stas 5.5K Mar 27 13:16 zero_to_fp32.py* ``` 在这个例子中,只有一个DeepSpeed检查点子文件夹*global_step1*。因此,要重构fp32权重,只需运行: ```bash python zero_to_fp32.py . pytorch_model.bin ``` 这就是它。`pytorch_model.bin`现在将包含从多个GPUs合并的完整的fp32模型权重。 该脚本将自动能够处理ZeRO-2或ZeRO-3 checkpoint。 `python zero_to_fp32.py -h`将为您提供使用细节。 该脚本将通过文件`latest`的内容自动发现deepspeed子文件夹,在当前示例中,它将包含`global_step1`。 注意:目前该脚本需要2倍于最终fp32模型权重的通用内存。 ### ZeRO-3 和 Infinity Nuances ZeRO-3与ZeRO-2有很大的不同,主要是因为它的参数分片功能。 ZeRO-Infinity进一步扩展了ZeRO-3,以支持NVMe内存和其他速度和可扩展性改进。 尽管所有努力都是为了在不需要对模型进行任何特殊更改的情况下就能正常运行,但在某些情况下,您可能需要以下信息。 #### 构建大模型 DeepSpeed/ZeRO-3可以处理参数量达到数万亿的模型,这些模型可能无法适应现有的内存。在这种情况下,如果您还是希望初始化更快地发生,可以使用*deepspeed.zero.Init()*上下文管理器(也是一个函数装饰器)来初始化模型,如下所示: ```python from transformers import T5ForConditionalGeneration, T5Config import deepspeed with deepspeed.zero.Init(): config = T5Config.from_pretrained("google-t5/t5-small") model = T5ForConditionalGeneration(config) ``` 如您所见,这会为您随机初始化一个模型。 如果您想使用预训练模型,`model_class.from_pretrained`将在`is_deepspeed_zero3_enabled()`返回`True`的情况下激活此功能,目前这是通过传递的DeepSpeed配置文件中的ZeRO-3配置部分设置的。因此,在调用`from_pretrained`之前,您必须创建**TrainingArguments**对象。以下是可能的顺序示例: ```python from transformers import AutoModel, Trainer, TrainingArguments training_args = TrainingArguments(..., deepspeed=ds_config) model = AutoModel.from_pretrained("google-t5/t5-small") trainer = Trainer(model=model, args=training_args, ...) ``` 如果您使用的是官方示例脚本,并且命令行参数中包含`--deepspeed ds_config.json`且启用了ZeRO-3配置,那么一切都已经为您准备好了,因为这是示例脚本的编写方式。 注意:如果模型的fp16权重无法适应单个GPU的内存,则必须使用此功能。 有关此方法和其他相关功能的完整详细信息,请参阅[构建大模型](https://deepspeed.readthedocs.io/en/latest/zero3.html#constructing-massive-models)。 此外,在加载fp16预训练模型时,您希望`from_pretrained`使用`dtype=torch.float16`。详情请参见[from_pretrained-torch-dtype](#from_pretrained-torch-dtype)。 #### 参数收集 在多个GPU上使用ZeRO-3时,没有一个GPU拥有所有参数,除非它是当前执行层的参数。因此,如果您需要一次访问所有层的所有参数,有一个特定的方法可以实现。 您可能不需要它,但如果您需要,请参考[参数收集](https://deepspeed.readthedocs.io/en/latest/zero3.html#manual-parameter-coordination)。 然而,我们在多个地方确实使用了它,其中一个例子是在`from_pretrained`中加载预训练模型权重。我们一次加载一层,然后立即将其分区到所有参与的GPU上,因为对于非常大的模型,无法在一个GPU上一次性加载并将其分布到多个GPU上,因为内存限制。 此外,在ZeRO-3下,如果您编写自己的代码并遇到看起来像这样的模型参数权重: ```python tensor([1.0], device="cuda:0", dtype=torch.float16, requires_grad=True) ``` 强调`tensor([1.])`,或者如果您遇到一个错误,它说参数的大小是`1`,而不是某个更大的多维形状,这意味着参数被划分了,你看到的是一个ZeRO-3占位符。 <a id='deepspeed-zero-inference'></a> ### ZeRO 推理 "ZeRO 推断" 使用与 "ZeRO-3 训练" 相同的配置。您只需要去掉优化器和调度器部分。实际上,如果您希望与训练共享相同的配置文件,您可以将它们保留在配置文件中,它们只会被忽略。 您只需要传递通常的[`TrainingArguments`]参数。例如: ```bash deepspeed --num_gpus=2 your_program.py <normal cl args> --do_eval --deepspeed ds_config.json ``` 唯一的重要事情是您需要使用ZeRO-3配置,因为ZeRO-2对于推理没有任何优势,因为只有ZeRO-3才对参数进行分片,而ZeRO-1则对梯度和优化器状态进行分片。 以下是在DeepSpeed下运行`run_translation.py`启用所有可用GPU的示例: ```bash deepspeed examples/pytorch/translation/run_translation.py \ --deepspeed tests/deepspeed/ds_config_zero3.json \ --model_name_or_path google-t5/t5-small --output_dir output_dir \ --do_eval --max_eval_samples 50 --warmup_steps 50 \ --max_source_length 128 --val_max_target_length 128 \ --per_device_eval_batch_size 4 \ --predict_with_generate --dataset_config "ro-en" --fp16 \ --source_lang en --target_lang ro --dataset_name wmt16 \ --source_prefix "translate English to Romanian: " ``` 由于在推理阶段,优化器状态和梯度不需要额外的大量内存,您应该能够将更大的批次和/或序列长度放到相同的硬件上。 此外,DeepSpeed目前正在开发一个名为Deepspeed-Inference的相关产品,它与ZeRO技术无关,而是使用张量并行来扩展无法适应单个GPU的模型。这是一个正在进行的工作,一旦该产品完成,我们将提供集成。 ### 内存要求 由于 DeepSpeed ZeRO 可以将内存卸载到 CPU(和 NVMe),该框架提供了一些工具,允许根据使用的 GPU 数量告知将需要多少 CPU 和 GPU 内存。 让我们估计在单个GPU上微调"bigscience/T0_3B"所需的内存: ```bash $ python -c 'from transformers import AutoModel; \ from deepspeed.runtime.zero.stage3 import estimate_zero3_model_states_mem_needs_all_live; \ model = AutoModel.from_pretrained("bigscience/T0_3B"); \ estimate_zero3_model_states_mem_needs_all_live(model, num_gpus_per_node=1, num_nodes=1)' [...] Estimated memory needed for params, optim states and gradients for a: HW: Setup with 1 node, 1 GPU per node. SW: Model with 2783M total params, 65M largest layer params. per CPU | per GPU | Options 70.00GB | 0.25GB | offload_param=cpu , offload_optimizer=cpu , zero_init=1 70.00GB | 0.25GB | offload_param=cpu , offload_optimizer=cpu , zero_init=0 62.23GB | 5.43GB | offload_param=none, offload_optimizer=cpu , zero_init=1 62.23GB | 5.43GB | offload_param=none, offload_optimizer=cpu , zero_init=0 0.37GB | 46.91GB | offload_param=none, offload_optimizer=none, zero_init=1 15.56GB | 46.91GB | offload_param=none, offload_optimizer=none, zero_init=0 ``` 因此,您可以将模型拟合在单个80GB的GPU上,不进行CPU offload,或者使用微小的8GB GPU,但需要约60GB的CPU内存。(请注意,这仅是参数、优化器状态和梯度所需的内存 - 您还需要为CUDA内核、激活值和临时变量分配更多的内存。) 然后,这是成本与速度的权衡。购买/租用较小的 GPU(或较少的 GPU,因为您可以使用多个 GPU 进行 Deepspeed ZeRO)。但这样会更慢,因此即使您不关心完成某项任务的速度,减速也直接影响 GPU 使用的持续时间,从而导致更大的成本。因此,请进行实验并比较哪种方法效果最好。 如果您有足够的GPU内存,请确保禁用CPU/NVMe卸载,因为这会使所有操作更快。 例如,让我们重复相同的操作,使用2个GPU: ```bash $ python -c 'from transformers import AutoModel; \ from deepspeed.runtime.zero.stage3 import estimate_zero3_model_states_mem_needs_all_live; \ model = AutoModel.from_pretrained("bigscience/T0_3B"); \ estimate_zero3_model_states_mem_needs_all_live(model, num_gpus_per_node=2, num_nodes=1)' [...] Estimated memory needed for params, optim states and gradients for a: HW: Setup with 1 node, 2 GPUs per node. SW: Model with 2783M total params, 65M largest layer params. per CPU | per GPU | Options 70.00GB | 0.25GB | offload_param=cpu , offload_optimizer=cpu , zero_init=1 70.00GB | 0.25GB | offload_param=cpu , offload_optimizer=cpu , zero_init=0 62.23GB | 2.84GB | offload_param=none, offload_optimizer=cpu , zero_init=1 62.23GB | 2.84GB | offload_param=none, offload_optimizer=cpu , zero_init=0 0.74GB | 23.58GB | offload_param=none, offload_optimizer=none, zero_init=1 31.11GB | 23.58GB | offload_param=none, offload_optimizer=none, zero_init=0 ``` 所以,您需要2个32GB或更高的GPU,且不进行CPU卸载。 如需了解更多信息,请参阅[内存估算器](https://deepspeed.readthedocs.io/en/latest/memory.html)。 ### 归档Issues 请按照以下步骤提交问题,以便我们能够迅速找到问题并帮助您解除工作阻塞。 在您的报告中,请始终包括以下内容: 1. 完整的Deepspeed配置文件 2. 如果使用了[`Trainer`],则包括命令行参数;如果自己编写了Trainer设置,则包括[`TrainingArguments`]参数。请不要导出[`TrainingArguments`],因为它有几十个与问题无关的条目。 3. 输出: ```bash python -c 'import torch; print(f"torch: {torch.__version__}")' python -c 'import transformers; print(f"transformers: {transformers.__version__}")' python -c 'import deepspeed; print(f"deepspeed: {deepspeed.__version__}")' ``` 4. 如果可能,请包含一个Google Colab notebook链接,我们可以使用它来重现问题。您可以使用这个[notebook](https://github.com/stas00/porting/blob/master/transformers/deepspeed/DeepSpeed_on_colab_CLI.ipynb)作为起点。 5. 除非不可能,否则请始终使用标准数据集,而不是自定义数据集。 6. 如果可能,尝试使用现有[示例](https://github.com/huggingface/transformers/tree/main/examples/pytorch)之一来重现问题。 需要考虑的因素: - Deepspeed通常不是问题的原因。 一些已提交的问题被证明与Deepspeed无关。也就是说,一旦将Deepspeed从设置中移除,问题仍然存在。 因此,如果问题明显与DeepSpeed相关,例如您可以看到有一个异常并且可以看到DeepSpeed模块涉及其中,请先重新测试没有DeepSpeed的设置。只有当问题仍然存在时,才向Deepspeed提供所有必需的细节。 - 如果您明确问题是在Deepspeed核心中而不是集成部分,请直接向[Deepspeed](https://github.com/deepspeedai/DeepSpeed/)提交问题。如果您不确定,请不要担心,无论使用哪个issue跟踪问题都可以,一旦您发布问题,我们会弄清楚并将其重定向到另一个issue跟踪(如果需要的话)。 ### Troubleshooting #### 启动时`deepspeed`进程被终止,没有回溯 如果启动时`deepspeed`进程被终止,没有回溯,这通常意味着程序尝试分配的CPU内存超过了系统的限制或进程被允许分配的内存,操作系统内核杀死了该进程。这是因为您的配置文件很可能将`offload_optimizer`或`offload_param`或两者都配置为卸载到`cpu`。如果您有NVMe,可以尝试在ZeRO-3下卸载到NVMe。这里是如何[估计特定模型所需的内存](https://deepspeed.readthedocs.io/en/latest/memory.html)。 #### 训练和/或评估/预测loss为`NaN` 这种情况通常发生在使用bf16混合精度模式预训练的模型试图在fp16(带或不带混合精度)下使用时。大多数在TPU上训练的模型以及由谷歌发布的模型都属于这个类别(例如,几乎所有基于t5的模型)。在这种情况下,解决方案是要么使用fp32,要么在支持的情况下使用bf16(如TPU、Ampere GPU或更新的版本)。 另一个问题可能与使用fp16有关。当您配置此部分时: ```json { "fp16": { "enabled": "auto", "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 } } ``` 并且您在日志中看到Deepspeed报告`OVERFLOW`如下 ``` 0%| | 0/189 [00:00<?, ?it/s] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 262144, reducing to 262144 1%|▌ | 1/189 [00:00<01:26, 2.17it/s] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 262144, reducing to 131072.0 1%|█▏ [...] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1 14%|████████████████▌ | 27/189 [00:14<01:13, 2.21it/s] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1 15%|█████████████████▏ | 28/189 [00:14<01:13, 2.18it/s] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1 15%|█████████████████▊ | 29/189 [00:15<01:13, 2.18it/s] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1 [...] ``` 这意味着Deepspeed损失缩放器无法找到一个克服损失溢出的缩放系数。 在这种情况下,通常需要提高`initial_scale_power`的值。将其设置为`"initial_scale_power": 32`通常会解决问题。 ### 注意事项 - 尽管 DeepSpeed 有一个可安装的 PyPI 包,但强烈建议从源代码安装它,以最好地匹配您的硬件,如果您需要启用某些功能,如 1-bit Adam,这些功能在 pypi 发行版中不可用。 - 您不必使用🤗 Transformers的 [`Trainer`] 来使用 DeepSpeed - 您可以使用任何模型与自己的训练器,您还需要根据 [DeepSpeed 集成说明](https://www.deepspeed.ai/getting-started/#writing-deepspeed-models) 调整后者。 ## Non-Trainer Deepspeed集成 当`Trainer`没有被使用时,`~integrations.HfDeepSpeedConfig`被用来将Deepspeed集成到huggingface的Transformers核心功能中。它唯一做的事情就是在`from_pretrained`调用期间处理Deepspeed ZeRO-3参数收集和将模型自动分割到多个GPU上。除此之外,您需要自己完成其他所有工作。 当使用`Trainer`时,所有事情都自动得到了处理。 当不使用`Trainer`时,为了高效地部署Deepspeed ZeRO-3,您必须在实例化模型之前实例化`~integrations.HfDeepSpeedConfig`对象并保持该对象活跃。 如果您正在使用Deepspeed ZeRO-1或ZeRO-2,您根本不需要使用`HfDeepSpeedConfig`。 以预训练模型为例: ```python from transformers.integrations import HfDeepSpeedConfig from transformers import AutoModel import deepspeed ds_config = {...} # deepspeed config object or path to the file # must run before instantiating the model to detect zero 3 dschf = HfDeepSpeedConfig(ds_config) # keep this object alive model = AutoModel.from_pretrained("openai-community/gpt2") engine = deepspeed.initialize(model=model, config_params=ds_config, ...) ``` 或者以非预训练模型为例: ```python from transformers.integrations import HfDeepSpeedConfig from transformers import AutoModel, AutoConfig import deepspeed ds_config = {...} # deepspeed config object or path to the file # must run before instantiating the model to detect zero 3 dschf = HfDeepSpeedConfig(ds_config) # keep this object alive config = AutoConfig.from_pretrained("openai-community/gpt2") model = AutoModel.from_config(config) engine = deepspeed.initialize(model=model, config_params=ds_config, ...) ``` 请注意,如果您没有使用[`Trainer`]集成,您完全需要自己动手。基本上遵循[Deepspeed](https://www.deepspeed.ai/)网站上的文档。同时,您必须显式配置配置文件 - 不能使用`"auto"`值,而必须放入实际值。 ## HfDeepSpeedConfig [[autodoc]] integrations.HfDeepSpeedConfig - all ### 自定义DeepSpeed ZeRO推理 以下是一个示例,演示了在无法将模型放入单个 GPU 时如果不使用[Trainer]进行 DeepSpeed ZeRO 推理 。该解决方案包括使用额外的 GPU 或/和将 GPU 内存卸载到 CPU 内存。 这里要理解的重要细微差别是,ZeRO的设计方式可以让您在不同的GPU上并行处理不同的输入。 这个例子有很多注释,并且是自文档化的。 请确保: 1. 如果您有足够的GPU内存(因为这会减慢速度),禁用CPU offload。 2. 如果您拥有Ampere架构或更新的GPU,启用bf16以加快速度。如果您没有这种硬件,只要不使用任何在bf16混合精度下预训练的模型(如大多数t5模型),就可以启用fp16。否则这些模型通常在fp16中溢出,您会看到输出无效结果。 ```python #!/usr/bin/env python # This script demonstrates how to use Deepspeed ZeRO in an inference mode when one can't fit a model # into a single GPU # # 1. Use 1 GPU with CPU offload # 2. Or use multiple GPUs instead # # First you need to install deepspeed: pip install deepspeed # # Here we use a 3B "bigscience/T0_3B" model which needs about 15GB GPU RAM - so 1 largish or 2 # small GPUs can handle it. or 1 small GPU and a lot of CPU memory. # # To use a larger model like "bigscience/T0" which needs about 50GB, unless you have an 80GB GPU - # you will need 2-4 gpus. And then you can adapt the script to handle more gpus if you want to # process multiple inputs at once. # # The provided deepspeed config also activates CPU memory offloading, so chances are that if you # have a lot of available CPU memory and you don't mind a slowdown you should be able to load a # model that doesn't normally fit into a single GPU. If you have enough GPU memory the program will # run faster if you don't want offload to CPU - so disable that section then. # # To deploy on 1 gpu: # # deepspeed --num_gpus 1 t0.py # or: # python -m torch.distributed.run --nproc_per_node=1 t0.py # # To deploy on 2 gpus: # # deepspeed --num_gpus 2 t0.py # or: # python -m torch.distributed.run --nproc_per_node=2 t0.py from transformers import AutoTokenizer, AutoConfig, AutoModelForSeq2SeqLM from transformers.integrations import HfDeepSpeedConfig import deepspeed import os import torch os.environ["TOKENIZERS_PARALLELISM"] = "false" # To avoid warnings about parallelism in tokenizers # distributed setup local_rank = int(os.getenv("LOCAL_RANK", "0")) world_size = int(os.getenv("WORLD_SIZE", "1")) torch.cuda.set_device(local_rank) deepspeed.init_distributed() model_name = "bigscience/T0_3B" config = AutoConfig.from_pretrained(model_name) model_hidden_size = config.d_model # batch size has to be divisible by world_size, but can be bigger than world_size train_batch_size = 1 * world_size # ds_config notes # # - enable bf16 if you use Ampere or higher GPU - this will run in mixed precision and will be # faster. # # - for older GPUs you can enable fp16, but it'll only work for non-bf16 pretrained models - e.g. # all official t5 models are bf16-pretrained # # - set offload_param.device to "none" or completely remove the `offload_param` section if you don't # - want CPU offload # # - if using `offload_param` you can manually finetune stage3_param_persistence_threshold to control # - which params should remain on gpus - the larger the value the smaller the offload size # # For in-depth info on Deepspeed config see # https://huggingface.co/docs/transformers/main/main_classes/deepspeed # keeping the same format as json for consistency, except it uses lower case for true/false # fmt: off ds_config = { "fp16": { "enabled": False }, "bf16": { "enabled": False }, "zero_optimization": { "stage": 3, "offload_param": { "device": "cpu", "pin_memory": True }, "overlap_comm": True, "contiguous_gradients": True, "reduce_bucket_size": model_hidden_size * model_hidden_size, "stage3_prefetch_bucket_size": 0.9 * model_hidden_size * model_hidden_size, "stage3_param_persistence_threshold": 10 * model_hidden_size }, "steps_per_print": 2000, "train_batch_size": train_batch_size, "train_micro_batch_size_per_gpu": 1, "wall_clock_breakdown": False } # fmt: on # next line instructs transformers to partition the model directly over multiple gpus using # deepspeed.zero.Init when model's `from_pretrained` method is called. # # **it has to be run before loading the model AutoModelForSeq2SeqLM.from_pretrained(model_name)** # # otherwise the model will first be loaded normally and only partitioned at forward time which is # less efficient and when there is little CPU RAM may fail dschf = HfDeepSpeedConfig(ds_config) # keep this object alive # now a model can be loaded. model = AutoModelForSeq2SeqLM.from_pretrained(model_name) # initialise Deepspeed ZeRO and store only the engine object ds_engine = deepspeed.initialize(model=model, config_params=ds_config)[0] ds_engine.module.eval() # inference # Deepspeed ZeRO can process unrelated inputs on each GPU. So for 2 gpus you process 2 inputs at once. # If you use more GPUs adjust for more. # And of course if you have just one input to process you then need to pass the same string to both gpus # If you use only one GPU, then you will have only rank 0. rank = torch.distributed.get_rank() if rank == 0: text_in = "Is this review positive or negative? Review: this is the best cast iron skillet you will ever buy" elif rank == 1: text_in = "Is this review positive or negative? Review: this is the worst restaurant ever" tokenizer = AutoTokenizer.from_pretrained(model_name) inputs = tokenizer.encode(text_in, return_tensors="pt").to(device=local_rank) with torch.no_grad(): outputs = ds_engine.module.generate(inputs, synced_gpus=True) text_out = tokenizer.decode(outputs[0], skip_special_tokens=True) print(f"rank{rank}:\n in={text_in}\n out={text_out}") ``` 让我们保存它为 `t0.py`并运行: ```bash $ deepspeed --num_gpus 2 t0.py rank0: in=Is this review positive or negative? Review: this is the best cast iron skillet you will ever buy out=Positive rank1: in=Is this review positive or negative? Review: this is the worst restaurant ever out=negative ``` 这是一个非常基本的例子,您需要根据自己的需求进行修改。 ### `generate` 的差异 在使用ZeRO stage 3的多GPU时,需要通过调用`generate(..., synced_gpus=True)`来同步GPU。如果一个GPU在其它GPU之前完成生成,整个系统将挂起,因为其他GPU无法从停止生成的GPU接收权重分片。 从`transformers>=4.28`开始,如果没有明确指定`synced_gpus`,检测到这些条件后它将自动设置为`True`。但如果您需要覆盖`synced_gpus`的值,仍然可以这样做。 ## 测试 DeepSpeed 集成 如果您提交了一个涉及DeepSpeed集成的PR,请注意我们的CircleCI PR CI设置没有GPU,因此我们只在另一个CI夜间运行需要GPU的测试。因此,如果您在PR中获得绿色的CI报告,并不意味着DeepSpeed测试通过。 要运行DeepSpeed测试,请至少运行以下命令: ```bash RUN_SLOW=1 pytest tests/deepspeed/test_deepspeed.py ``` 如果你更改了任何模型或PyTorch示例代码,请同时运行多模型测试。以下将运行所有DeepSpeed测试: ```bash RUN_SLOW=1 pytest tests/deepspeed ``` ## 主要的DeepSpeed资源 - [项目GitHub](https://github.com/deepspeedai/DeepSpeed) - [使用文档](https://www.deepspeed.ai/getting-started/) - [API文档](https://deepspeed.readthedocs.io/en/latest/index.html) - [博客文章](https://www.microsoft.com/en-us/research/search/?q=deepspeed) 论文: - [ZeRO: Memory Optimizations Toward Training Trillion Parameter Models](https://huggingface.co/papers/1910.02054) - [ZeRO-Offload: Democratizing Billion-Scale Model Training](https://huggingface.co/papers/2101.06840) - [ZeRO-Infinity: Breaking the GPU Memory Wall for Extreme Scale Deep Learning](https://huggingface.co/papers/2104.07857) 最后,请记住,HuggingFace [`Trainer`]仅集成了DeepSpeed,因此如果您在使用DeepSpeed时遇到任何问题或疑问,请在[DeepSpeed GitHub](https://github.com/deepspeedai/DeepSpeed/issues)上提交一个issue。
unknown
github
https://github.com/huggingface/transformers
docs/source/zh/main_classes/deepspeed.md
/* * Copyright 2010-2025 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.api.renderer.declarations.renderers.callables import org.jetbrains.kotlin.analysis.api.KaExperimentalApi import org.jetbrains.kotlin.analysis.api.KaSession import org.jetbrains.kotlin.analysis.api.KaSpi import org.jetbrains.kotlin.analysis.api.renderer.declarations.KaDeclarationRenderer import org.jetbrains.kotlin.analysis.api.symbols.KaAnonymousFunctionSymbol import org.jetbrains.kotlin.analysis.utils.printer.PrettyPrinter import org.jetbrains.kotlin.lexer.KtTokens @KaSpi @KaExperimentalApi public interface KaAnonymousFunctionSymbolRenderer { public fun renderSymbol( analysisSession: KaSession, symbol: KaAnonymousFunctionSymbol, declarationRenderer: KaDeclarationRenderer, printer: PrettyPrinter, ) @KaExperimentalApi public object AS_SOURCE : KaAnonymousFunctionSymbolRenderer { override fun renderSymbol( analysisSession: KaSession, symbol: KaAnonymousFunctionSymbol, declarationRenderer: KaDeclarationRenderer, printer: PrettyPrinter, ) { printer { declarationRenderer.callableSignatureRenderer .renderCallableSignature(analysisSession, symbol, KtTokens.FUN_KEYWORD, declarationRenderer, printer) } } } }
kotlin
github
https://github.com/JetBrains/kotlin
analysis/analysis-api/src/org/jetbrains/kotlin/analysis/api/renderer/declarations/renderers/callables/KaAnonymousFunctionSymbolRenderer.kt
# -*- coding: utf-8 -*- """Test forms.""" from webapp.public.forms import LoginForm from webapp.user.forms import RegisterForm class TestRegisterForm: """Register form.""" def test_validate_user_already_registered(self, user): """Enter username that is already registered.""" form = RegisterForm(username=user.username, email='foo@bar.com', password='example', confirm='example') assert form.validate() is False assert 'Username already registered' in form.username.errors def test_validate_email_already_registered(self, user): """Enter email that is already registered.""" form = RegisterForm(username='unique', email=user.email, password='example', confirm='example') assert form.validate() is False assert 'Email already registered' in form.email.errors def test_validate_success(self, db): """Register with success.""" form = RegisterForm(username='newusername', email='new@test.test', password='example', confirm='example') assert form.validate() is True class TestLoginForm: """Login form.""" def test_validate_success(self, user): """Login successful.""" user.set_password('example') user.save() form = LoginForm(username=user.username, password='example') assert form.validate() is True assert form.user == user def test_validate_unknown_username(self, db): """Unknown username.""" form = LoginForm(username='unknown', password='example') assert form.validate() is False assert 'Unknown username' in form.username.errors assert form.user is None def test_validate_invalid_password(self, user): """Invalid password.""" user.set_password('example') user.save() form = LoginForm(username=user.username, password='wrongpassword') assert form.validate() is False assert 'Invalid password' in form.password.errors def test_validate_inactive_user(self, user): """Inactive user.""" user.active = False user.set_password('example') user.save() # Correct username and password, but user is not activated form = LoginForm(username=user.username, password='example') assert form.validate() is False assert 'User not activated' in form.username.errors
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- # Copyright 2007-2021 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # HyperSpy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with HyperSpy. If not, see <http://www.gnu.org/licenses/>. import inspect def _connect_events(event, to_connect): try: for ev in event: # Iterable of events, connect all of them ev.connect(to_connect, []) except TypeError: # It was not an iterable, connect the single event event.connect(to_connect, []) class Interactive: """Chainable operations on Signals that update on events. """ def __init__(self, f, event="auto", recompute_out_event="auto", *args, **kwargs): """Update operation result when a given event is triggered. Parameters ---------- f : function or method A function that returns an object and that optionally can place the result in an object given through the `out` keyword. event : {Event, "auto", None, iterable of events} Update the result of the operation when the event is triggered. If "auto" and `f` is a method of a Signal class instance its `data_changed` event is selected if the function takes an `out` argument. If None, `update` is not connected to any event. The default is "auto". It is also possible to pass an iterable of events, in which case all the events are connected. recompute_out_event : {Event, "auto", None, iterable of events} Optional argument. If supplied, this event causes a full recomputation of a new object. Both the data and axes of the new object are then copied over to the existing `out` object. Only useful for `Signal` or other objects that have an attribute `axes_manager`. If "auto" and `f` is a method of a Signal class instance its `AxesManager` `any_axis_changed` event is selected. Otherwise the `Signal` `data_changed` event is selected. If None, `recompute_out` is not connected to any event. The default is "auto". It is also possible to pass an iterable of events, in which case all the events are connected. *args Arguments to be passed to `f`. **kwargs Keyword arguments to be passed to `f`. """ from hyperspy.signal import BaseSignal self.f = f self.args = args self.kwargs = kwargs _plot_kwargs = self.kwargs.pop('_plot_kwargs', None) if 'out' in self.kwargs: self.f(*self.args, **self.kwargs) self.out = self.kwargs.pop('out') else: self.out = self.f(*self.args, **self.kwargs) # Reuse the `_plot_kwargs` for the roi if available if _plot_kwargs and 'signal' in self.kwargs: self.out._plot_kwargs = self.kwargs['signal']._plot_kwargs try: fargs = list(inspect.signature(self.f).parameters.keys()) except TypeError: # This is probably a Cython function that is not supported by # inspect. fargs = [] has_out = "out" in fargs # If it is a BaseSignal method if hasattr(f, "__self__") and isinstance(f.__self__, BaseSignal): if event == "auto": event = self.f.__self__.events.data_changed if recompute_out_event == "auto": recompute_out_event = \ self.f.__self__.axes_manager.events.any_axis_changed else: event = None if event == "auto" else event recompute_out_event = (None if recompute_out_event == "auto" else recompute_out_event) if recompute_out_event: _connect_events(recompute_out_event, self.recompute_out) if event: if has_out: _connect_events(event, self.update) else: # We "simulate" out by triggering `recompute_out` instead. _connect_events(event, self.recompute_out) def recompute_out(self): out = self.f(*self.args, **self.kwargs) if out is None: return if out.data.shape == self.out.data.shape: # Keep the same array if possible. self.out.data[:] = out.data[:] else: self.out.data = out.data self.out.axes_manager.update_axes_attributes_from( out.axes_manager._axes) self.out.events.data_changed.trigger(self.out) def update(self): self.f(*self.args, out=self.out, **self.kwargs) def interactive(f, event="auto", recompute_out_event="auto", *args, **kwargs): cls = Interactive(f, event, recompute_out_event, *args, **kwargs) return cls.out interactive.__doc__ = Interactive.__init__.__doc__
unknown
codeparrot/codeparrot-clean
mod queue; mod shutdown; mod yield_now; /// Full runtime loom tests. These are heavy tests and take significant time to /// run on CI. /// /// Use `LOOM_MAX_PREEMPTIONS=1` to do a "quick" run as a smoke test. /// /// In order to speed up the C use crate::runtime::tests::loom_oneshot as oneshot; use crate::runtime::{self, Runtime}; use crate::{spawn, task}; use tokio_test::assert_ok; use loom::sync::atomic::{AtomicBool, AtomicUsize}; use loom::sync::Arc; use pin_project_lite::pin_project; use std::future::{poll_fn, Future}; use std::pin::Pin; use std::sync::atomic::Ordering::{Relaxed, SeqCst}; use std::task::{ready, Context, Poll}; mod atomic_take { use loom::sync::atomic::AtomicBool; use std::mem::MaybeUninit; use std::sync::atomic::Ordering::SeqCst; pub(super) struct AtomicTake<T> { inner: MaybeUninit<T>, taken: AtomicBool, } impl<T> AtomicTake<T> { pub(super) fn new(value: T) -> Self { Self { inner: MaybeUninit::new(value), taken: AtomicBool::new(false), } } pub(super) fn take(&self) -> Option<T> { // safety: Only one thread will see the boolean change from false // to true, so that thread is able to take the value. match self.taken.fetch_or(true, SeqCst) { false => unsafe { Some(std::ptr::read(self.inner.as_ptr())) }, true => None, } } } impl<T> Drop for AtomicTake<T> { fn drop(&mut self) { drop(self.take()); } } } #[derive(Clone)] struct AtomicOneshot<T> { value: std::sync::Arc<atomic_take::AtomicTake<oneshot::Sender<T>>>, } impl<T> AtomicOneshot<T> { fn new(sender: oneshot::Sender<T>) -> Self { Self { value: std::sync::Arc::new(atomic_take::AtomicTake::new(sender)), } } fn assert_send(&self, value: T) { self.value.take().unwrap().send(value); } } /// Tests are divided into groups to make the runs faster on CI. mod group_a { use super::*; #[test] fn racy_shutdown() { loom::model(|| { let pool = mk_pool(1); // here's the case we want to exercise: // // a worker that still has tasks in its local queue gets sent to the blocking pool (due to // block_in_place). the blocking pool is shut down, so drops the worker. the worker's // shutdown method never gets run. // // we do this by spawning two tasks on one worker, the first of which does block_in_place, // and then immediately drop the pool. pool.spawn(track(async { crate::task::block_in_place(|| {}); })); pool.spawn(track(async {})); drop(pool); }); } #[test] fn pool_multi_spawn() { loom::model(|| { let pool = mk_pool(2); let c1 = Arc::new(AtomicUsize::new(0)); let (tx, rx) = oneshot::channel(); let tx1 = AtomicOneshot::new(tx); // Spawn a task let c2 = c1.clone(); let tx2 = tx1.clone(); pool.spawn(track(async move { spawn(track(async move { if 1 == c1.fetch_add(1, Relaxed) { tx1.assert_send(()); } })); })); // Spawn a second task pool.spawn(track(async move { spawn(track(async move { if 1 == c2.fetch_add(1, Relaxed) { tx2.assert_send(()); } })); })); rx.recv(); }); } fn only_blocking_inner(first_pending: bool) { loom::model(move || { let pool = mk_pool(1); let (block_tx, block_rx) = oneshot::channel(); pool.spawn(track(async move { crate::task::block_in_place(move || { block_tx.send(()); }); if first_pending { task::yield_now().await } })); block_rx.recv(); drop(pool); }); } #[test] fn only_blocking_without_pending() { only_blocking_inner(false) } #[test] fn only_blocking_with_pending() { only_blocking_inner(true) } } mod group_b { use super::*; fn blocking_and_regular_inner(first_pending: bool) { const NUM: usize = 3; loom::model(move || { let pool = mk_pool(1); let cnt = Arc::new(AtomicUsize::new(0)); let (block_tx, block_rx) = oneshot::channel(); let (done_tx, done_rx) = oneshot::channel(); let done_tx = AtomicOneshot::new(done_tx); pool.spawn(track(async move { crate::task::block_in_place(move || { block_tx.send(()); }); if first_pending { task::yield_now().await } })); for _ in 0..NUM { let cnt = cnt.clone(); let done_tx = done_tx.clone(); pool.spawn(track(async move { if NUM == cnt.fetch_add(1, Relaxed) + 1 { done_tx.assert_send(()); } })); } done_rx.recv(); block_rx.recv(); drop(pool); }); } #[test] fn blocking_and_regular() { blocking_and_regular_inner(false); } #[test] fn blocking_and_regular_with_pending() { blocking_and_regular_inner(true); } #[test] fn join_output() { loom::model(|| { let rt = mk_pool(1); rt.block_on(async { let t = crate::spawn(track(async { "hello" })); let out = assert_ok!(t.await); assert_eq!("hello", out.into_inner()); }); }); } #[test] fn poll_drop_handle_then_drop() { loom::model(|| { let rt = mk_pool(1); rt.block_on(async move { let mut t = crate::spawn(track(async { "hello" })); poll_fn(|cx| { let _ = Pin::new(&mut t).poll(cx); Poll::Ready(()) }) .await; }); }) } #[test] fn complete_block_on_under_load() { loom::model(|| { let pool = mk_pool(1); pool.block_on(async { // Trigger a re-schedule crate::spawn(track(async { for _ in 0..2 { task::yield_now().await; } })); gated2(true).await }); }); } #[test] fn shutdown_with_notification() { use crate::sync::oneshot; loom::model(|| { let rt = mk_pool(2); let (done_tx, done_rx) = oneshot::channel::<()>(); rt.spawn(track(async move { let (tx, rx) = oneshot::channel::<()>(); crate::spawn(async move { crate::task::spawn_blocking(move || { let _ = tx.send(()); }); let _ = done_rx.await; }); let _ = rx.await; let _ = done_tx.send(()); })); }); } } mod group_c { use super::*; #[test] fn pool_shutdown() { loom::model(|| { let pool = mk_pool(2); pool.spawn(track(async move { gated2(true).await; })); pool.spawn(track(async move { gated2(false).await; })); drop(pool); }); } } mod group_d { use super::*; #[test] fn pool_multi_notify() { loom::model(|| { let pool = mk_pool(2); let c1 = Arc::new(AtomicUsize::new(0)); let (done_tx, done_rx) = oneshot::channel(); let done_tx1 = AtomicOneshot::new(done_tx); let done_tx2 = done_tx1.clone(); // Spawn a task let c2 = c1.clone(); pool.spawn(track(async move { multi_gated().await; if 1 == c1.fetch_add(1, Relaxed) { done_tx1.assert_send(()); } })); // Spawn a second task pool.spawn(track(async move { multi_gated().await; if 1 == c2.fetch_add(1, Relaxed) { done_tx2.assert_send(()); } })); done_rx.recv(); }); } } fn mk_pool(num_threads: usize) -> Runtime { runtime::Builder::new_multi_thread() .worker_threads(num_threads) // Set the intervals to avoid tuning logic .event_interval(2) .build() .unwrap() } fn gated2(thread: bool) -> impl Future<Output = &'static str> { use loom::thread; use std::sync::Arc; let gate = Arc::new(AtomicBool::new(false)); let mut fired = false; poll_fn(move |cx| { if !fired { let gate = gate.clone(); let waker = cx.waker().clone(); if thread { thread::spawn(move || { gate.store(true, SeqCst); waker.wake_by_ref(); }); } else { spawn(track(async move { gate.store(true, SeqCst); waker.wake_by_ref(); })); } fired = true; return Poll::Pending; } if gate.load(SeqCst) { Poll::Ready("hello world") } else { Poll::Pending } }) } async fn multi_gated() { struct Gate { waker: loom::future::AtomicWaker, count: AtomicUsize, } let gate = Arc::new(Gate { waker: loom::future::AtomicWaker::new(), count: AtomicUsize::new(0), }); { let gate = gate.clone(); spawn(track(async move { for i in 1..3 { gate.count.store(i, SeqCst); gate.waker.wake(); } })); } poll_fn(move |cx| { gate.waker.register_by_ref(cx.waker()); if gate.count.load(SeqCst) < 2 { Poll::Pending } else { Poll::Ready(()) } }) .await; } fn track<T: Future>(f: T) -> Track<T> { Track { inner: f, arc: Arc::new(()), } } pin_project! { struct Track<T> { #[pin] inner: T, // Arc is used to hook into loom's leak tracking. arc: Arc<()>, } } impl<T> Track<T> { fn into_inner(self) -> T { self.inner } } impl<T: Future> Future for Track<T> { type Output = Track<T::Output>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let me = self.project(); Poll::Ready(Track { inner: ready!(me.inner.poll(cx)), arc: me.arc.clone(), }) } }
rust
github
https://github.com/tokio-rs/tokio
tokio/src/runtime/tests/loom_multi_thread.rs
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Self-test for skimage. import filecmp import os import subprocess import sys import tempfile class BinaryNotFoundException(Exception): def __str__ (self): return ("Could not find binary!\n" "Did you forget to build the tools project?\n" "Self tests failed") # Find a path to the binary to use. Iterates through a list of possible # locations the binary may be. def PickBinaryPath(base_dir): POSSIBLE_BINARY_PATHS = [ 'out/Debug/skimage', 'out/Release/skimage', 'xcodebuild/Debug/skimage', 'xcodebuild/Release/skimage', ] for binary in POSSIBLE_BINARY_PATHS: binary_full_path = os.path.join(base_dir, binary) if (os.path.exists(binary_full_path)): return binary_full_path raise BinaryNotFoundException # Quit early if two files have different content. def DieIfFilesMismatch(expected, actual): if not filecmp.cmp(expected, actual): raise Exception("Error: file mismatch! expected=%s , actual=%s" % ( expected, actual)) def test_invalid_file(file_dir, skimage_binary): """ Test the return value of skimage when an invalid file is decoded. If there is no expectation file, or the file expects a particular result, skimage should return nonzero indicating failure. If the file has no expectation, or ignore-failure is set to true, skimage should return zero indicating success. """ invalid_file = os.path.join(file_dir, "skimage", "input", "bad-images", "invalid.png") # No expectations file: args = [skimage_binary, "--readPath", invalid_file] result = subprocess.call(args) if 0 == result: raise Exception("'%s' should have reported failure!" % " ".join(args)) # Directory holding all expectations files expectations_dir = os.path.join(file_dir, "skimage", "input", "bad-images") # Expectations file expecting a valid decode: incorrect_expectations = os.path.join(expectations_dir, "incorrect-results.json") args = [skimage_binary, "--readPath", invalid_file, "--readExpectationsPath", incorrect_expectations] result = subprocess.call(args) if 0 == result: raise Exception("'%s' should have reported failure!" % " ".join(args)) # Empty expectations: empty_expectations = os.path.join(expectations_dir, "empty-results.json") output = subprocess.check_output([skimage_binary, "--readPath", invalid_file, "--readExpectationsPath", empty_expectations], stderr=subprocess.STDOUT) if not "Missing" in output: # Another test (in main()) tests to ensure that "Missing" does not appear # in the output. That test could be passed if the output changed so # "Missing" never appears. This ensures that an error is not missed if # that happens. raise Exception( "skimage output changed! This may cause other self tests to fail!") # Ignore failure: ignore_expectations = os.path.join(expectations_dir, "ignore-results.json") output = subprocess.check_output([skimage_binary, "--readPath", invalid_file, "--readExpectationsPath", ignore_expectations], stderr=subprocess.STDOUT) if not "failures" in output: # Another test (in main()) tests to ensure that "failures" does not # appear in the output. That test could be passed if the output changed # so "failures" never appears. This ensures that an error is not missed # if that happens. raise Exception( "skimage output changed! This may cause other self tests to fail!") def test_incorrect_expectations(file_dir, skimage_binary): """ Test that comparing to incorrect expectations fails, unless ignore-failures is set to true. """ valid_file = os.path.join(file_dir, "skimage", "input", "images-with-known-hashes", "1209453360120438698.png") expectations_dir = os.path.join(file_dir, "skimage", "input", "images-with-known-hashes") incorrect_results = os.path.join(expectations_dir, "incorrect-results.json") args = [skimage_binary, "--readPath", valid_file, "--readExpectationsPath", incorrect_results] result = subprocess.call(args) if 0 == result: raise Exception("'%s' should have reported failure!" % " ".join(args)) ignore_results = os.path.join(expectations_dir, "ignore-failures.json") subprocess.check_call([skimage_binary, "--readPath", valid_file, "--readExpectationsPath", ignore_results]) def main(): # Use the directory of this file as the out directory file_dir = os.path.abspath(os.path.dirname(__file__)) trunk_dir = os.path.normpath(os.path.join(file_dir, os.pardir, os.pardir)) # Find the binary skimage_binary = PickBinaryPath(trunk_dir) print "Running " + skimage_binary # Generate an expectations file from known images. images_dir = os.path.join(file_dir, "skimage", "input", "images-with-known-hashes") expectations_path = os.path.join(file_dir, "skimage", "output-actual", "create-expectations", "expectations.json") subprocess.check_call([skimage_binary, "--readPath", images_dir, "--createExpectationsPath", expectations_path]) # Make sure the expectations file was generated correctly. golden_expectations = os.path.join(file_dir, "skimage", "output-expected", "create-expectations", "expectations.json") DieIfFilesMismatch(expected=golden_expectations, actual=expectations_path) # Tell skimage to read back the expectations file it just wrote, and # confirm that the images in images_dir match it. output = subprocess.check_output([skimage_binary, "--readPath", images_dir, "--readExpectationsPath", expectations_path], stderr=subprocess.STDOUT) # Although skimage succeeded, it would have reported success if the file # was missing from the expectations file. Consider this a failure, since # the expectations file was created from this same image. (It will print # "Missing" in this case before listing the missing expectations). if "Missing" in output: raise Exception("Expectations file was missing expectations: %s" % output) # Again, skimage would succeed if there were known failures (and print # "failures"), but there should be no failures, since the file just # created did not include failures to ignore. if "failures" in output: raise Exception("Image failed: %s" % output) test_incorrect_expectations(file_dir=file_dir, skimage_binary=skimage_binary) # Generate an expectations file from an empty directory. empty_dir = tempfile.mkdtemp() expectations_path = os.path.join(file_dir, "skimage", "output-actual", "empty-dir", "expectations.json") subprocess.check_call([skimage_binary, "--readPath", empty_dir, "--createExpectationsPath", expectations_path]) golden_expectations = os.path.join(file_dir, "skimage", "output-expected", "empty-dir", "expectations.json") DieIfFilesMismatch(expected=golden_expectations, actual=expectations_path) os.rmdir(empty_dir) # Generate an expectations file from a nonexistent directory. expectations_path = os.path.join(file_dir, "skimage", "output-actual", "nonexistent-dir", "expectations.json") subprocess.check_call([skimage_binary, "--readPath", "/nonexistent/dir", "--createExpectationsPath", expectations_path]) golden_expectations = os.path.join(file_dir, "skimage", "output-expected", "nonexistent-dir", "expectations.json") DieIfFilesMismatch(expected=golden_expectations, actual=expectations_path) test_invalid_file(file_dir=file_dir, skimage_binary=skimage_binary) # Done with all tests. print "Self tests succeeded!" if __name__ == "__main__": main()
unknown
codeparrot/codeparrot-clean
from django.contrib import admin from labourwages.models import * # Register your models here. class AgoperationAdmin(admin.ModelAdmin): fields=('name',) admin.site.register(Agoperation,AgoperationAdmin) class WagetypeAdmin(admin.ModelAdmin): fields=('name',) admin.site.register(Wagetype,WagetypeAdmin) class WorkprogrammeAdmin(admin.ModelAdmin): fields=('name',) admin.site.register(Workprogramme,WorkprogrammeAdmin) class ObligationtypeAdmin(admin.ModelAdmin): fields=('name',) admin.site.register(Obligationtype,ObligationtypeAdmin) class TaskdescriptionAdmin(admin.ModelAdmin): fields=('name',) admin.site.register(Taskdescription,TaskdescriptionAdmin) class CollecteditemsAdmin(admin.ModelAdmin): fields=('name',) admin.site.register(Collecteditems,CollecteditemsAdmin) class MagencyAdmin(admin.ModelAdmin): fields=('name',) admin.site.register(Magency,MagencyAdmin) class CheatingfacedAdmin(admin.ModelAdmin): fields=('name',) admin.site.register(Cheatingfaced,CheatingfacedAdmin) class WorkdescriptionAdmin(admin.ModelAdmin): fields=('name',) admin.site.register(Workdescription,WorkdescriptionAdmin) class AnimaltypeAdmin(admin.ModelAdmin): fields=('name',) admin.site.register(Animaltype,AnimaltypeAdmin) class AnimalproductionAdmin(admin.ModelAdmin): fields=('name',) admin.site.register(Animalproduction,AnimalproductionAdmin) class LabourdaysAdmin(admin.ModelAdmin): fields=('household','household_number','labour_deployed','s_no','crop','extent','agricultural_operation','family_labour_days_m','family_labour_days_w','family_labour_days_c','family_labour_hours_m','family_labour_hours_w','family_labour_hours_c','daily_labour_days_m','daily_labour_days_w','daily_labour_days_c','daily_labour_hours_m','daily_labour_hours_w','daily_labour_hours_c','daily_labour_wages_m','daily_labour_wages_w','daily_labour_wages_c','exchange_labour_days_m','exchange_labour_days_w','exchange_labour_days_c','exchange_labour_hours_m','exchange_labour_hours_w','exchange_labour_hours_c','piece_rated_cash','piece_rated_kind','machine_labour_workhours','machine_labourpayment','comments',) admin.site.register(Labourdays,LabourdaysAdmin) class WagesAdmin(admin.ModelAdmin): fields=('household','household_number','is_agricultural_labour','worker_name','crop','operation','type_wage','place_work','labour_days','work_hours','earnings_cash','income','piece_rate_kind','contract_number_acres','contract_remuniration','contract_howmany_workers','contract_total_wage','wagerates_increased','migrations_declined','isthere_change_peasants','has_baragaining_power_increased','comments',) admin.site.register(Wages,WagesAdmin) class NonaglabourAdmin(admin.ModelAdmin): fields=('household','household_number','workedin_nonag_operation','worker_name','description_specify_programme', 'type_wage_contract','place_work','number_days','work_hours','wage_rate' ,'totalearnings_cash','comments') admin.site.register(Nonaglabour,NonaglabourAdmin) class EmpfreedomAdmin(admin.ModelAdmin): fields=('household' , 'household_number', 'comments',) admin.site.register(Empfreedom,EmpfreedomAdmin) class IncomeotherAdmin(admin.ModelAdmin): fields=('household','household_number','worker_name','work_description','work_place','totalnet_earnings','earlier_income_kind','comments',) admin.site.register(Incomeother,IncomeotherAdmin) class AnimalsourceAdmin(admin.ModelAdmin): fields=('household','household_number','animal_owned','type','s_no','nu','age','feed_home_grown','feed_purchased','total_present_value','veternary_charges','maintanence_buildings','insurance','interest_loans_livestock','labour_charges','others','income_production_one','production_work_qty_one','production_work_price_one','income_production_two','production_work_qty_two','production_work_price_two','comments') admin.site.register(Animalsource,AnimalsourceAdmin)
unknown
codeparrot/codeparrot-clean
# $HeadURL$ """ PlottingClient is a client of the Plotting Service """ __RCSID__ = "$Id$" import types, tempfile from DIRAC import S_OK, S_ERROR from DIRAC.Core.DISET.RPCClient import RPCClient from DIRAC.Core.DISET.TransferClient import TransferClient class PlottingClient: def __init__( self, rpcClient = None, transferClient = None ): self.serviceName = "Framework/Plotting" self.rpcClient = rpcClient self.transferClient = transferClient def __getRPCClient( self ): if self.rpcClient: return self.rpcClient return RPCClient( self.serviceName ) def __getTransferClient( self ): if self.transferClient: return self.transferClient return TransferClient( self.serviceName ) def getPlotToMemory( self, plotName ): """ Get the prefabricated plot from the service and return it as a string """ transferClient = self.__getTransferClient() tmpFile = tempfile.TemporaryFile() retVal = transferClient.receiveFile( tmpFile, plotName ) if not retVal[ 'OK' ]: return retVal tmpFile.seek( 0 ) data = tmpFile.read() tmpFile.close() return S_OK( data ) def getPlotToFile( self, plotName, fileName ): """ Get the prefabricated plot from the service and store it in a file """ transferClient = self.__getTransferClient() try: destFile = file( fileName, "wb" ) except Exception as e: return S_ERROR( "Can't open file %s for writing: %s" % ( fileName, str( e ) ) ) retVal = transferClient.receiveFile( destFile, plotName ) if not retVal[ 'OK' ]: return retVal destFile.close() return S_OK( fileName ) def graph( self, data, fname = False, *args, **kw ): """ Generic method to obtain graphs from the Plotting service. The requested graphs are completely described by their data and metadata """ client = self.__getRPCClient() plotMetadata = {} for arg in args: if type( arg ) == types.DictType: plotMetadata.update( arg ) else: return S_ERROR( 'Non-dictionary non-keyed argument' ) plotMetadata.update( kw ) result = client.generatePlot( data, plotMetadata ) if not result['OK']: return result plotName = result['Value'] if fname and fname != 'Memory': result = self.getPlotToFile( plotName, fname ) else: result = self.getPlotToMemory( plotName ) return result def barGraph( self, data, fileName, *args, **kw ): return self.graph( data, fileName, plot_type = 'BarGraph', statistics_line = True, *args, **kw ) def lineGraph( self, data, fileName, *args, **kw ): return self.graph( data, fileName, plot_type = 'LineGraph', statistics_line = True, *args, **kw ) def curveGraph( self, data, fileName, *args, **kw ): return self.graph( data, fileName, plot_type = 'CurveGraph', statistics_line = True, *args, **kw ) def cumulativeGraph( self, data, fileName, *args, **kw ): return self.graph( data, fileName, plot_type = 'LineGraph', cumulate_data = True, *args, **kw ) def pieGraph( self, data, fileName, *args, **kw ): prefs = {'xticks':False, 'yticks':False, 'legend_position':'right'} return self.graph( data, fileName, prefs, plot_type = 'PieGraph', *args, **kw ) def qualityGraph( self, data, fileName, *args, **kw ): prefs = {'plot_axis_grid':False} return self.graph( data, fileName, prefs, plot_type = 'QualityMapGraph', *args, **kw ) def textGraph( self, text, fileName, *args, **kw ): prefs = {'text_image':text} return self.graph( {}, fileName, prefs, *args, **kw ) def histogram( self, data, fileName, bins, *args, **kw ): try: from pylab import hist except: return S_ERROR( "No pylab module available" ) values, vbins, patches = hist( data, bins ) histo = dict( zip( vbins, values ) ) span = ( max( data ) - min( data ) ) / float( bins ) * 0.98 return self.graph( histo, fileName, plot_type = 'BarGraph', span = span, statistics_line = True, *args, **kw )
unknown
codeparrot/codeparrot-clean
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Background Subtraction Example</title> <link href="js_example_style.css" rel="stylesheet" type="text/css" /> </head> <body> <h2>Background Subtraction Example</h2> <p> Click <b>Start/Stop</b> button to start or stop the camera capture.<br> The <b>videoInput</b> is a &lt;video&gt; element used as input. The <b>canvasOutput</b> is a &lt;canvas&gt; element used as output.<br> The code of &lt;textarea&gt; will be executed when video is started. You can modify the code to investigate more. </p> <div> <div class="control"><button id="startAndStop" disabled>Start</button></div> <textarea class="code" rows="29" cols="80" id="codeEditor" spellcheck="false"> </textarea> </div> <p class="err" id="errorMessage"></p> <div> <table cellpadding="0" cellspacing="0" width="0" border="0"> <tr> <td> <video id="videoInput" width="320" height="240" muted loop></video> </td> <td> <canvas id="canvasOutput" width="320" height="240"></canvas> </td> <td></td> <td></td> </tr> <tr> <td> <div class="caption">videoInput</div> </td> <td> <div class="caption">canvasOutput</div> </td> <td></td> <td></td> </tr> </table> </div> <script src="https://webrtc.github.io/adapter/adapter-5.0.4.js" type="text/javascript"></script> <script src="utils.js" type="text/javascript"></script> <script id="codeSnippet" type="text/code-snippet"> let video = document.getElementById('videoInput'); let cap = new cv.VideoCapture(video); let frame = new cv.Mat(video.height, video.width, cv.CV_8UC4); let fgmask = new cv.Mat(video.height, video.width, cv.CV_8UC1); let fgbg = new cv.BackgroundSubtractorMOG2(500, 16, true); const FPS = 30; function processVideo() { try { if (!streaming) { // clean and stop. frame.delete(); fgmask.delete(); fgbg.delete(); return; } let begin = Date.now(); // start processing. cap.read(frame); fgbg.apply(frame, fgmask); cv.imshow('canvasOutput', fgmask); // schedule the next one. let delay = 1000/FPS - (Date.now() - begin); setTimeout(processVideo, delay); } catch (err) { utils.printError(err); } }; // schedule the first one. setTimeout(processVideo, 0); </script> <script type="text/javascript"> let utils = new Utils('errorMessage'); utils.loadCode('codeSnippet', 'codeEditor'); let streaming = false; let videoInput = document.getElementById('videoInput'); let startAndStop = document.getElementById('startAndStop'); let canvasOutput = document.getElementById('canvasOutput'); let canvasContext = canvasOutput.getContext('2d'); startAndStop.addEventListener('click', () => { if (!streaming) { utils.clearError(); videoInput.play().then(() => { onVideoStarted(); }); } else { videoInput.pause(); videoInput.currentTime = 0; onVideoStopped(); } }); function onVideoStarted() { streaming = true; startAndStop.innerText = 'Stop'; videoInput.height = videoInput.width * (videoInput.videoHeight / videoInput.videoWidth); utils.executeCode('codeEditor'); } function onVideoStopped() { streaming = false; canvasContext.clearRect(0, 0, canvasOutput.width, canvasOutput.height); startAndStop.innerText = 'Start'; } utils.loadOpenCv(() => { videoInput.addEventListener('canplay', () => { startAndStop.removeAttribute('disabled'); }); videoInput.src = 'box.mp4'; }); </script> </body> </html>
html
github
https://github.com/opencv/opencv
doc/js_tutorials/js_assets/js_bg_subtraction.html
# Owner(s): ["module: tests"] # ruff: noqa: F841 import itertools import math import operator import random import sys import warnings from functools import partial from itertools import chain, product from numbers import Number import numpy as np import torch import torch.autograd.forward_ad as fwAD from torch import inf, nan from torch.testing import make_tensor from torch.testing._internal.common_device_type import ( deviceCountAtLeast, dtypes, dtypesIfCPU, dtypesIfCUDA, dtypesIfXPU, expectedFailureMeta, instantiate_device_type_tests, onlyCPU, onlyCUDA, onlyNativeDeviceTypes, onlyOn, OpDTypes, ops, precisionOverride, skipIf, skipMeta, skipXPU, ) from torch.testing._internal.common_dtype import ( all_types, all_types_and, all_types_and_complex_and, complex_types, floating_and_complex_types, floating_types_and, get_all_int_dtypes, get_all_math_dtypes, integral_types, integral_types_and, ) from torch.testing._internal.common_methods_invocations import ( binary_ufuncs, binary_ufuncs_and_refs, generate_elementwise_binary_broadcasting_tensors, generate_elementwise_binary_extremal_value_tensors, generate_elementwise_binary_large_value_tensors, generate_elementwise_binary_small_value_tensors, generate_elementwise_binary_tensors, generate_elementwise_binary_with_scalar_and_type_promotion_samples, generate_elementwise_binary_with_scalar_samples, ) from torch.testing._internal.common_utils import ( gradcheck, iter_indices, numpy_to_torch_dtype_dict, run_tests, set_default_dtype, skipIfTorchDynamo, slowTest, TEST_SCIPY, TestCase, torch_to_numpy_dtype_dict, xfailIfTorchDynamo, ) if TEST_SCIPY: import scipy.integrate import scipy.special device_type = ( acc.type if (acc := torch.accelerator.current_accelerator(True)) else "cpu" ) # TODO: update to use opinfos consistently class TestBinaryUfuncs(TestCase): # Generic tests for elementwise binary (AKA binary universal (u) functions (funcs)) # TODO: below contiguous tensor results are compared with a variety of noncontiguous results. # It would be interesting to have the lhs and rhs have different discontinuities. # Helper for comparing torch tensors and NumPy arrays # TODO: should this or assertEqual also validate that strides are equal? def assertEqualHelper( self, actual, expected, msg, *, dtype, exact_dtype=True, **kwargs ): if not isinstance(actual, torch.Tensor): raise AssertionError( f"expected actual to be torch.Tensor, got {type(actual)}" ) # Some NumPy functions return scalars, not arrays if isinstance(expected, Number): self.assertEqual(actual.item(), expected, msg=msg, **kwargs) elif isinstance(expected, np.ndarray): # Handles exact dtype comparisons between arrays and tensors if exact_dtype: # Allows array dtype to be float32 when comparing with bfloat16 tensors # since NumPy doesn't support the bfloat16 dtype # Also ops like scipy.special.erf, scipy.special.erfc, etc, promote float16 # to float32 if expected.dtype == np.float32: if actual.dtype not in ( torch.float16, torch.bfloat16, torch.float32, ): raise AssertionError( f"actual.dtype {actual.dtype} not in expected dtypes" ) else: if expected.dtype != torch_to_numpy_dtype_dict[actual.dtype]: raise AssertionError( f"dtype mismatch: {expected.dtype} != {torch_to_numpy_dtype_dict[actual.dtype]}" ) self.assertEqual( actual, torch.from_numpy(expected).to(actual.dtype), msg, exact_device=False, **kwargs, ) else: self.assertEqual(actual, expected, msg, exact_device=False, **kwargs) # Tests that the function and its (array-accepting) reference produce the same # values on given tensors def _test_reference_numerics(self, dtype, op, gen, equal_nan=True): def _helper_reference_numerics( expected, actual, msg, exact_dtype, equal_nan=True ): if not torch.can_cast( numpy_to_torch_dtype_dict[expected.dtype.type], dtype ): exact_dtype = False if dtype is torch.bfloat16 and expected.dtype == np.float32: # Ref: https://github.com/pytorch/pytorch/blob/master/torch/testing/_internal/common_utils.py#L1149 self.assertEqualHelper( actual, expected, msg, dtype=dtype, exact_dtype=exact_dtype, rtol=16e-3, atol=1e-5, ) else: self.assertEqualHelper( actual, expected, msg, dtype=dtype, equal_nan=equal_nan, exact_dtype=exact_dtype, ) for sample in gen: # Each sample input acquired from the generator is just one lhs tensor # and one rhs tensor l = sample.input r = sample.args[0] numpy_sample = sample.numpy() l_numpy = numpy_sample.input r_numpy = numpy_sample.args[0] actual = op(l, r) expected = op.ref(l_numpy, r_numpy) # Dtype promo rules have changed since NumPy 2. # Specialize the backward-incompatible cases. if ( np.__version__ > "2" and op.name in ("sub", "_refs.sub") and isinstance(l_numpy, np.ndarray) ): expected = expected.astype(l_numpy.dtype) # Crafts a custom error message for smaller, printable tensors def _numel(x): if isinstance(x, torch.Tensor): return x.numel() # Assumes x is a scalar return 1 if _numel(l) <= 100 and _numel(r) <= 100: msg = ( "Failed to produce expected results! Input lhs tensor was" f" {l}, rhs tensor was {r}, torch result is {actual}, and reference result is" f" {expected}." ) else: msg = None exact_dtype = True if isinstance(actual, torch.Tensor): _helper_reference_numerics( expected, actual, msg, exact_dtype, equal_nan ) else: for x, y in zip(expected, actual): # testing multi-outputs results _helper_reference_numerics(x, y, msg, exact_dtype, equal_nan) # The following tests only apply to elementwise binary operators with references binary_ufuncs_with_references = list( filter(lambda op: op.ref is not None, binary_ufuncs) ) @ops(binary_ufuncs_with_references) def test_reference_numerics(self, device, dtype, op): gen = generate_elementwise_binary_tensors(op, device=device, dtype=dtype) self._test_reference_numerics(dtype, op, gen, equal_nan=True) @ops(binary_ufuncs_with_references) def test_reference_numerics_small_values(self, device, dtype, op): if dtype is torch.bool: self.skipTest("Doesn't support bool!") gen = generate_elementwise_binary_small_value_tensors( op, device=device, dtype=dtype ) self._test_reference_numerics(dtype, op, gen, equal_nan=True) @ops( binary_ufuncs_with_references, allowed_dtypes=( torch.int16, torch.int32, torch.int64, torch.float16, torch.bfloat16, torch.float32, torch.float64, torch.complex64, torch.complex128, ), ) def test_reference_numerics_large_values(self, device, dtype, op): gen = generate_elementwise_binary_large_value_tensors( op, device=device, dtype=dtype ) self._test_reference_numerics(dtype, op, gen, equal_nan=True) @ops( binary_ufuncs_with_references, allowed_dtypes=( torch.float16, torch.bfloat16, torch.float32, torch.float64, torch.complex64, torch.complex128, ), ) def test_reference_numerics_extremal_values(self, device, dtype, op): gen = generate_elementwise_binary_extremal_value_tensors( op, device=device, dtype=dtype ) self._test_reference_numerics(dtype, op, gen, equal_nan=True) # tests broadcasting and noncontiguous broadcasting behavior @ops( binary_ufuncs_with_references, allowed_dtypes=( torch.long, torch.float32, ), ) def test_broadcasting(self, device, dtype, op): gen = generate_elementwise_binary_broadcasting_tensors( op, device=device, dtype=dtype ) self._test_reference_numerics(dtype, op, gen, equal_nan=True) @ops( binary_ufuncs_with_references, allowed_dtypes=(torch.long, torch.float32, torch.complex64), ) def test_scalar_support(self, device, dtype, op): gen = generate_elementwise_binary_with_scalar_samples( op, device=device, dtype=dtype ) self._test_reference_numerics(dtype, op, gen, equal_nan=True) gen = generate_elementwise_binary_with_scalar_and_type_promotion_samples( op, device=device, dtype=dtype ) self._test_reference_numerics(dtype, op, gen, equal_nan=True) @ops(binary_ufuncs) def test_contig_vs_every_other(self, device, dtype, op): lhs = make_tensor( (1026,), device=device, dtype=dtype, **op.lhs_make_tensor_kwargs ) rhs = make_tensor( (1026,), device=device, dtype=dtype, **op.rhs_make_tensor_kwargs ) lhs_non_contig = lhs[::2] rhs_non_contig = rhs[::2] self.assertTrue(lhs.is_contiguous()) self.assertTrue(rhs.is_contiguous()) self.assertFalse(lhs_non_contig.is_contiguous()) self.assertFalse(rhs_non_contig.is_contiguous()) expected = op(lhs, rhs)[::2] actual = op(lhs_non_contig, rhs_non_contig) self.assertEqual(expected, actual) @ops(binary_ufuncs) def test_contig_vs_transposed(self, device, dtype, op): lhs = make_tensor( (789, 357), device=device, dtype=dtype, **op.lhs_make_tensor_kwargs ) rhs = make_tensor( (789, 357), device=device, dtype=dtype, **op.rhs_make_tensor_kwargs ) lhs_non_contig = lhs.T rhs_non_contig = rhs.T self.assertTrue(lhs.is_contiguous()) self.assertTrue(rhs.is_contiguous()) self.assertFalse(lhs_non_contig.is_contiguous()) self.assertFalse(rhs_non_contig.is_contiguous()) expected = op(lhs, rhs).T actual = op(lhs_non_contig, rhs_non_contig) self.assertEqual(expected, actual) @ops(binary_ufuncs) def test_non_contig(self, device, dtype, op): shapes = ((5, 7), (1024,)) for shape in shapes: lhs = make_tensor( shape, dtype=dtype, device=device, **op.lhs_make_tensor_kwargs ) rhs = make_tensor( shape, dtype=dtype, device=device, **op.rhs_make_tensor_kwargs ) lhs_non_contig = torch.empty(shape + (2,), device=device, dtype=dtype)[ ..., 0 ] lhs_non_contig.copy_(lhs) rhs_non_contig = torch.empty(shape + (2,), device=device, dtype=dtype)[ ..., 0 ] rhs_non_contig.copy_(rhs) self.assertTrue(lhs.is_contiguous()) self.assertTrue(rhs.is_contiguous()) self.assertFalse(lhs_non_contig.is_contiguous()) self.assertFalse(rhs_non_contig.is_contiguous()) expected = op(lhs, rhs) actual = op(lhs_non_contig, rhs_non_contig) self.assertEqual(expected, actual) @ops(binary_ufuncs) def test_non_contig_index(self, device, dtype, op): shape = (2, 2, 1, 2) lhs = make_tensor( shape, dtype=dtype, device=device, **op.lhs_make_tensor_kwargs ) rhs = make_tensor( shape, dtype=dtype, device=device, **op.rhs_make_tensor_kwargs ) lhs_non_contig = lhs[:, 1, ...] lhs = lhs_non_contig.contiguous() rhs_non_contig = rhs[:, 1, ...] rhs = rhs_non_contig.contiguous() self.assertTrue(lhs.is_contiguous()) self.assertTrue(rhs.is_contiguous()) self.assertFalse(lhs_non_contig.is_contiguous()) self.assertFalse(rhs_non_contig.is_contiguous()) expected = op(lhs, rhs) actual = op(lhs_non_contig, rhs_non_contig) self.assertEqual(expected, actual) @ops(binary_ufuncs) def test_non_contig_expand(self, device, dtype, op): shapes = [(1, 3), (1, 7), (5, 7)] for shape in shapes: lhs = make_tensor( shape, dtype=dtype, device=device, **op.lhs_make_tensor_kwargs ) rhs = make_tensor( shape, dtype=dtype, device=device, **op.rhs_make_tensor_kwargs ) lhs_non_contig = lhs.clone().expand(3, -1, -1) rhs_non_contig = rhs.clone().expand(3, -1, -1) self.assertTrue(lhs.is_contiguous()) self.assertTrue(rhs.is_contiguous()) self.assertFalse(lhs_non_contig.is_contiguous()) self.assertFalse(rhs_non_contig.is_contiguous()) expected = op(lhs, rhs) actual = op(lhs_non_contig, rhs_non_contig) for i in range(3): self.assertEqual(expected, actual[i]) @ops(binary_ufuncs) def test_contig_size1(self, device, dtype, op): shape = (5, 100) lhs = make_tensor( shape, dtype=dtype, device=device, **op.lhs_make_tensor_kwargs ) rhs = make_tensor( shape, dtype=dtype, device=device, **op.rhs_make_tensor_kwargs ) lhs = lhs[:1, :50] lhs_alt = torch.empty(lhs.size(), device=device, dtype=dtype) lhs_alt.copy_(lhs) rhs = rhs[:1, :50] rhs_alt = torch.empty(rhs.size(), device=device, dtype=dtype) rhs_alt.copy_(rhs) self.assertTrue(lhs.is_contiguous()) self.assertTrue(rhs.is_contiguous()) self.assertTrue(lhs_alt.is_contiguous()) self.assertTrue(rhs_alt.is_contiguous()) expected = op(lhs, rhs) actual = op(lhs_alt, rhs_alt) self.assertEqual(expected, actual) @ops(binary_ufuncs) def test_contig_size1_large_dim(self, device, dtype, op): shape = (5, 2, 3, 1, 4, 5, 3, 2, 1, 2, 3, 4) lhs = make_tensor( shape, dtype=dtype, device=device, **op.lhs_make_tensor_kwargs ) rhs = make_tensor( shape, dtype=dtype, device=device, **op.rhs_make_tensor_kwargs ) lhs = lhs[:1, :, :, :, :, :, :, :, :, :, :, :] lhs_alt = torch.empty(lhs.size(), device=device, dtype=dtype) lhs_alt.copy_(lhs) rhs = rhs[:1, :, :, :, :, :, :, :, :, :, :, :] rhs_alt = torch.empty(rhs.size(), device=device, dtype=dtype) rhs_alt.copy_(rhs) self.assertTrue(lhs.is_contiguous()) self.assertTrue(rhs.is_contiguous()) self.assertTrue(lhs_alt.is_contiguous()) self.assertTrue(rhs_alt.is_contiguous()) expected = op(lhs, rhs) actual = op(lhs_alt, rhs_alt) self.assertEqual(expected, actual) @ops(binary_ufuncs) def test_batch_vs_slicing(self, device, dtype, op): shape = (32, 512) lhs = make_tensor( shape, dtype=dtype, device=device, **op.lhs_make_tensor_kwargs ) rhs = make_tensor( shape, dtype=dtype, device=device, **op.rhs_make_tensor_kwargs ) expected = op(lhs, rhs) actual = [] for idx in range(32): actual.append(op(lhs[idx], rhs[idx])) actual = torch.stack(actual) self.assertEqual(expected, actual) # Tests that elementwise binary operators participate in type promotion properly # NOTE: because the cross-product of all possible type promotion tests is huge, this # just spot checks some handwritten cases. # NOTE: It may be possible to refactor this test into something simpler @ops(binary_ufuncs_and_refs, dtypes=OpDTypes.none) def test_type_promotion(self, device, op): supported_dtypes = op.supported_dtypes(torch.device(device).type) make_lhs = partial( make_tensor, (5,), device=device, **op.lhs_make_tensor_kwargs ) make_rhs = partial( make_tensor, (5,), device=device, **op.rhs_make_tensor_kwargs ) make_rhs_scalar_tensor = partial( make_tensor, (), device="cpu", **op.rhs_make_tensor_kwargs ) def _supported(dtypes): return all(x in supported_dtypes for x in dtypes) # int x int type promotion if _supported((torch.int16, torch.int32, torch.int64)): lhs_i16 = make_lhs(dtype=torch.int16) lhs_i32 = make_lhs(dtype=torch.int32) lhs_i64 = make_lhs(dtype=torch.int64) rhs_i16 = make_rhs(dtype=torch.int16) rhs_i32 = make_rhs(dtype=torch.int32) rhs_i64 = make_rhs(dtype=torch.int64) if op.promotes_int_to_float: default_dtype = torch.get_default_dtype() self.assertEqual(op(lhs_i16, rhs_i32).dtype, default_dtype) self.assertEqual( op(lhs_i16, rhs_i32), op(lhs_i16.to(default_dtype), rhs_i32.to(default_dtype)), ) self.assertEqual(op(lhs_i32, rhs_i64).dtype, default_dtype) self.assertEqual( op(lhs_i32, rhs_i64), op(lhs_i32.to(default_dtype), rhs_i64.to(default_dtype)), ) elif op.always_returns_bool: self.assertEqual(op(lhs_i16, rhs_i32).dtype, torch.bool) self.assertEqual(op(lhs_i32, rhs_i64).dtype, torch.bool) else: # standard type promotion self.assertEqual(op(lhs_i16, rhs_i32).dtype, torch.int32) self.assertEqual( op(lhs_i16, rhs_i32), op(lhs_i16.to(torch.int32), rhs_i32) ) self.assertEqual(op(lhs_i32, rhs_i64).dtype, torch.int64) self.assertEqual( op(lhs_i32, rhs_i64), op(lhs_i32.to(torch.int64), rhs_i64) ) if op.supports_out: if not op.promotes_int_to_float: # Integers can be safely cast to other integer types out = torch.empty_like(lhs_i64) self.assertEqual(op(lhs_i16, rhs_i32, out=out).dtype, torch.int64) self.assertEqual(op(lhs_i16, rhs_i32), out, exact_dtype=False) out = torch.empty_like(lhs_i16) self.assertEqual(op(lhs_i32, rhs_i64, out=out).dtype, torch.int16) else: # Float outs cannot be safely cast to integer types with self.assertRaisesRegex(RuntimeError, "can't be cast"): op(lhs_i16, rhs_i32, out=torch.empty_like(lhs_i64)) if not op.always_returns_bool: # Neither integer nor float outs can be cast to bool with self.assertRaisesRegex(RuntimeError, "can't be cast"): op( lhs_i16, rhs_i32, out=torch.empty_like(lhs_i64, dtype=torch.bool), ) # All these output types can be cast to any float or complex type out = torch.empty_like(lhs_i64, dtype=torch.float16) self.assertEqual(op(lhs_i16, rhs_i32, out=out).dtype, torch.float16) out = torch.empty_like(lhs_i64, dtype=torch.bfloat16) self.assertEqual(op(lhs_i16, rhs_i32, out=out).dtype, torch.bfloat16) out = torch.empty_like(lhs_i64, dtype=torch.float32) self.assertEqual(op(lhs_i16, rhs_i32, out=out).dtype, torch.float32) self.assertEqual(op(lhs_i16, rhs_i32), out, exact_dtype=False) out = torch.empty_like(lhs_i64, dtype=torch.complex64) self.assertEqual(op(lhs_i16, rhs_i32, out=out).dtype, torch.complex64) self.assertEqual(op(lhs_i16, rhs_i32), out, exact_dtype=False) # float x float type promotion if _supported((torch.float32, torch.float64)): lhs_f32 = make_lhs(dtype=torch.float32) lhs_f64 = make_lhs(dtype=torch.float64) rhs_f32 = make_rhs(dtype=torch.float32) rhs_f64 = make_rhs(dtype=torch.float64) if op.always_returns_bool: self.assertEqual(op(lhs_f32, rhs_f64).dtype, torch.bool) else: # normal float type promotion self.assertEqual(op(lhs_f32, rhs_f64).dtype, torch.float64) self.assertEqual( op(lhs_f32, rhs_f64), op(lhs_f32.to(torch.float64), rhs_f64) ) if op.supports_out: # All these output types can be cast to any float or complex type out = torch.empty_like(lhs_f64, dtype=torch.float16) self.assertEqual(op(lhs_f32, rhs_f64, out=out).dtype, torch.float16) out = torch.empty_like(lhs_f64, dtype=torch.bfloat16) self.assertEqual(op(lhs_f32, rhs_f64, out=out).dtype, torch.bfloat16) self.assertEqual(op(lhs_f32, rhs_f64), out, exact_dtype=False) out = torch.empty_like(lhs_f64, dtype=torch.float32) self.assertEqual(op(lhs_f32, rhs_f64, out=out).dtype, torch.float32) self.assertEqual(op(lhs_f32, rhs_f64), out, exact_dtype=False) out = torch.empty_like(lhs_f64, dtype=torch.complex64) self.assertEqual(op(lhs_f32, rhs_f64, out=out).dtype, torch.complex64) self.assertEqual(op(lhs_f32, rhs_f64), out, exact_dtype=False) if not op.always_returns_bool: # float outs can't be cast to an integer dtype with self.assertRaisesRegex(RuntimeError, "can't be cast"): op( lhs_f32, rhs_f64, out=torch.empty_like(lhs_f64, dtype=torch.int64), ) else: # bool outs can be cast to an integer dtype out = torch.empty_like(lhs_f64, dtype=torch.int64) self.assertEqual(op(lhs_f32, rhs_f64, out=out).dtype, torch.int64) self.assertEqual(op(lhs_f32, rhs_f64), out, exact_dtype=False) # complex x complex type promotion if _supported((torch.complex64, torch.complex128)): lhs_c64 = make_lhs(dtype=torch.complex64) lhs_c128 = make_lhs(dtype=torch.complex128) rhs_c64 = make_rhs(dtype=torch.complex64) rhs_c128 = make_rhs(dtype=torch.complex128) if op.always_returns_bool: self.assertEqual(op(lhs_c64, lhs_c128).dtype, torch.bool) else: # normal complex type promotion self.assertEqual(op(lhs_c64, rhs_c128).dtype, torch.complex128) self.assertEqual( op(lhs_c64, rhs_c128), op(lhs_c64.to(torch.complex128), rhs_c128) ) if op.supports_out: # All these output types can be cast to any or complex type out = torch.empty_like(lhs_c64, dtype=torch.complex64) self.assertEqual(op(lhs_c64, rhs_c128, out=out).dtype, torch.complex64) result = op(lhs_c64, rhs_c128) self.assertEqual(result, out.to(result.dtype)) if not op.always_returns_bool: # complex outs can't be cast to float types with self.assertRaisesRegex(RuntimeError, "can't be cast"): op( lhs_c64, rhs_c128, out=torch.empty_like(lhs_c64, dtype=torch.float64), ) # complex outs can't be cast to an integer dtype with self.assertRaisesRegex(RuntimeError, "can't be cast"): op( lhs_c64, rhs_c128, out=torch.empty_like(lhs_c64, dtype=torch.int64), ) else: # bool outs can be cast to a float type out = torch.empty_like(lhs_c64, dtype=torch.float64) self.assertEqual( op(lhs_c64, rhs_c128, out=out).dtype, torch.float64 ) self.assertEqual(op(lhs_c64, rhs_c128), out, exact_dtype=False) # bool outs can be cast to an integer dtype out = torch.empty_like(lhs_f64, dtype=torch.int64) self.assertEqual(op(lhs_f32, rhs_f64, out=out).dtype, torch.int64) self.assertEqual(op(lhs_f32, rhs_f64), out, exact_dtype=False) # int x float type promotion # Note: float type is the result dtype if _supported((torch.long, torch.float32)): lhs_i64 = make_lhs(dtype=torch.int64) rhs_f32 = make_rhs(dtype=torch.float32) result = op(lhs_i64, rhs_f32) expected_dtype = torch.float32 if not op.always_returns_bool else torch.bool self.assertEqual(result.dtype, expected_dtype) # float x complex type promotion # Note: complex type with highest "value type" is the result dtype if _supported((torch.float64, torch.complex64)): lhs_f64 = make_lhs(dtype=torch.float64) rhs_c64 = make_rhs(dtype=torch.complex64) result = op(lhs_f64, rhs_c64) expected_dtype = ( torch.complex128 if not op.always_returns_bool else torch.bool ) self.assertEqual(result.dtype, expected_dtype) # int x float scalar type promotion # Note: default float dtype is the result dtype if _supported((torch.int64, torch.float32)) and op.supports_rhs_python_scalar: lhs_i64 = make_lhs(dtype=torch.int64) rhs_f_scalar = 1.0 result = op(lhs_i64, rhs_f_scalar) expected_dtype = ( torch.get_default_dtype() if not op.always_returns_bool else torch.bool ) self.assertEqual(result.dtype, expected_dtype) # repeats with a scalar float tensor, which should set the dtype rhs_f32_scalar_tensor = make_rhs_scalar_tensor(dtype=torch.float32) result = op(lhs_i64, rhs_f32_scalar_tensor) expected_dtype = torch.float32 if not op.always_returns_bool else torch.bool self.assertEqual(result.dtype, expected_dtype) # Additional test with double if _supported((torch.float64,)): rhs_f64_scalar_tensor = make_rhs_scalar_tensor(dtype=torch.float64) result = op(lhs_i64, rhs_f64_scalar_tensor) expected_dtype = ( torch.float64 if not op.always_returns_bool else torch.bool ) self.assertEqual(result.dtype, expected_dtype) # float x complex scalar type promotion # Note: result dtype is complex with highest "value type" among all tensors if ( _supported((torch.float32, torch.complex64)) and op.supports_rhs_python_scalar ): lhs_f32 = make_lhs(dtype=torch.float32) rhs_c_scalar = complex(1, 1) result = op(lhs_f32, rhs_c_scalar) expected_dtype = ( torch.complex64 if not op.always_returns_bool else torch.bool ) self.assertEqual(result.dtype, expected_dtype) # repeats with a scalar complex tensor rhs_c64_scalar_tensor = make_rhs_scalar_tensor(dtype=torch.complex64) result = op(lhs_f32, rhs_c64_scalar_tensor) expected_dtype = ( torch.complex64 if not op.always_returns_bool else torch.bool ) self.assertEqual(result.dtype, expected_dtype) # Additional test with complexdouble if _supported((torch.complex128,)): rhs_c128_scalar_tensor = make_rhs_scalar_tensor(dtype=torch.complex128) result = op(lhs_f32, rhs_c128_scalar_tensor) # Value type of 1D+ Tensor (lhs_f32) takes priority over scalar tensor (rhs_c128). expected_dtype = ( torch.complex64 if not op.always_returns_bool else torch.bool ) self.assertEqual(result.dtype, expected_dtype) # float x float scalar tensor # Note: result dtype is the type of the float tensor if _supported((torch.float32, torch.float64)) and op.supports_rhs_python_scalar: lhs_f32 = make_lhs(dtype=torch.float32) rhs_f64_scalar_tensor = make_rhs_scalar_tensor(dtype=torch.float64) result = op(lhs_f32, rhs_f64_scalar_tensor) expected_dtype = torch.float32 if not op.always_returns_bool else torch.bool self.assertEqual(result.dtype, expected_dtype) # complex x complex scalar tensor # Note: result dtype is the type of the complex tensor if ( _supported((torch.complex64, torch.complex128)) and op.supports_rhs_python_scalar ): lhs_c64 = make_lhs(dtype=torch.complex64) rhs_c128_scalar_tensor = make_rhs_scalar_tensor(dtype=torch.complex128) result = op(lhs_c64, rhs_c128_scalar_tensor) expected_dtype = ( torch.complex64 if not op.always_returns_bool else torch.bool ) self.assertEqual(result.dtype, expected_dtype) # scalar x scalar # Note: result dtype is default float type if op.supports_two_python_scalars and _supported((torch.long, torch.float32)): rhs_f_scalar = 2.0 for lhs in (1, 1.0): result = op(lhs, rhs_f_scalar) expected_dtype = ( torch.get_default_dtype() if not op.always_returns_bool else torch.bool ) self.assertEqual(result.dtype, expected_dtype) # TODO: move to error input test @ops(binary_ufuncs, allowed_dtypes=(torch.float32,)) def test_not_broadcastable(self, device, dtype, op): for shape_lhs, shape_rhs in ( ((2,), (3,)), ((3, 1), (2, 1)), ((1, 3, 2), (3,)), ((3, 1, 2), (2, 1, 2)), ): lhs = make_tensor( shape_lhs, device=device, dtype=dtype, **op.lhs_make_tensor_kwargs ) rhs = make_tensor( shape_rhs, device=device, dtype=dtype, **op.rhs_make_tensor_kwargs ) try: broadcasted_shape = op(lhs, rhs).shape except RuntimeError: continue msg = ( f"On {device}, torch.{op.name} broadcasts inputs shapes {shape_lhs} and {shape_rhs} into " f"{broadcasted_shape}, although they are not broadcastable." ) raise AssertionError(msg) def test_add_broadcast_empty(self, device): # empty + empty self.assertRaises( RuntimeError, lambda: torch.randn(5, 0, device=device) + torch.randn(0, 5, device=device), ) self.assertEqual( torch.randn(5, 0, device=device), torch.randn(0, device=device) + torch.randn(5, 0, device=device), ) self.assertEqual( torch.randn(5, 0, 0, device=device), torch.randn(0, device=device) + torch.randn(5, 0, 1, device=device), ) # scalar + empty self.assertEqual( torch.randn(5, 0, 6, device=device), torch.randn((), device=device) + torch.randn(5, 0, 6, device=device), ) # non-empty, empty self.assertEqual( torch.randn(0, device=device), torch.randn(0, device=device) + torch.randn(1, device=device), ) self.assertEqual( torch.randn(0, 7, 0, 6, 5, 0, 7, device=device), torch.randn(0, 7, 0, 6, 5, 0, 1, device=device) + torch.randn(1, 1, 5, 1, 7, device=device), ) self.assertRaises( RuntimeError, lambda: torch.randn(7, 0, device=device) + torch.randn(2, 1, device=device), ) def test_addcmul_scalars_as_floats(self, device): # zero-dim variables that don't require grad should bind to scalar arguments x = torch.tensor(2.0) y = torch.tensor(3.0, device=device) # 3 + (3 * 3) * 2 self.assertEqual(y.addcmul(y, y, value=x), 21) x = torch.tensor(2.0, requires_grad=True) self.assertRaises(Exception, lambda: y.addcmul(y, y, value=x)) # Tests that the binary operators and, or, and xor (as well as their reflected and inplace versions) # work properly (AKA &, ||, ^ and &=, |=, ^=) @dtypes(*integral_types_and(torch.bool)) def test_bitwise_ops(self, device, dtype): # Tensor x Tensor and Tensor x Scalar ops ops = ( operator.and_, operator.iand, operator.or_, operator.ior, operator.xor, operator.ixor, ) inplace_ops = (operator.iand, operator.ior, operator.ixor) shapes = ((5,), (15, 15), (500, 500)) for op, shape in itertools.product(ops, shapes): # Tests tensor x tensor case a = make_tensor(shape, device=device, dtype=dtype) b = make_tensor(shape, device=device, dtype=dtype) a_np = a.cpu().clone().numpy() b_np = b.cpu().clone().numpy() self.assertEqual(op(a, b), op(a_np, b_np)) # Tests tensor x scalar case a = make_tensor(shape, device=device, dtype=dtype) b_scalar = make_tensor((), device="cpu", dtype=dtype).item() a_np = a.cpu().clone().numpy() self.assertEqual(op(a, b_scalar), op(a_np, b_scalar)) # Tests scalar x tensor case a_scalar = make_tensor((), device="cpu", dtype=dtype).item() b = make_tensor(shape, device=device, dtype=dtype) b_np = b.cpu().clone().numpy() self.assertEqual(op(a_scalar, b), op(a_scalar, b_np)) # Tests scalar x tensor case (for ops which aren't inplace) if op in inplace_ops: # Tests tensor x tensor case a = make_tensor(shape, device=device, dtype=dtype) b = make_tensor(shape, device=device, dtype=dtype) a_np = a.cpu().clone().numpy() b_np = b.cpu().clone().numpy() op(a, b) op(a_np, b_np) self.assertEqual(a, a_np) # Tests tensor x scalar case a = make_tensor(shape, device=device, dtype=dtype) b_scalar = make_tensor((), device="cpu", dtype=dtype).item() a_np = a.cpu().clone().numpy() op(a, b_scalar) op(a_np, b_scalar) self.assertEqual(a, a_np) def test_inplace_division(self, device): t = torch.rand(5, 5, device=device) id_before = id(t) t /= 2 id_after = id(t) self.assertEqual(id_before, id_after) @dtypes(*all_types_and(torch.half, torch.bfloat16)) def test_div_rounding_modes(self, device, dtype): if dtype.is_floating_point: low, high = -10.0, 10.0 else: info = torch.iinfo(dtype) low, high = info.min, info.max a = make_tensor((100,), dtype=dtype, device=device, low=low, high=high) b = make_tensor((100,), dtype=dtype, device=device, low=low, high=high) # Avoid division by zero so we can test (a / b) * b == a if dtype.is_floating_point: eps = 0.1 b[(-eps < b) & (b < eps)] = eps else: b[b == 0] = 1 if not dtype.is_floating_point: # floor(a / b) * b can be < a, so fixup slightly to avoid underflow a = torch.where(a < 0, a + b, a) d_true = torch.divide(a, b, rounding_mode=None) self.assertTrue(d_true.is_floating_point()) self.assertEqual(d_true * b, a.to(d_true.dtype)) d_floor = torch.divide(a, b, rounding_mode="floor") if dtype not in (torch.bfloat16, torch.half): self.assertEqual(d_floor * b + torch.remainder(a, b), a) else: self.assertEqual( d_floor * b + torch.remainder(a.float(), b.float()), a, exact_dtype=False, ) d_trunc = torch.divide(a, b, rounding_mode="trunc") rounding_unsupported = ( dtype == torch.half and torch.device(device).type not in ["cuda", "xpu"] or dtype == torch.bfloat16 and device != "cpu" ) d_ref = d_true.float() if rounding_unsupported else d_true self.assertEqual(d_trunc, d_ref.trunc().to(dtype)) @dtypes(*floating_types_and(torch.bfloat16, torch.float16)) def test_floor_div_extremal(self, device, dtype): for num, denom, shape in itertools.product( [torch.finfo(dtype).max * 0.7], [0.5, -0.5, 0.0], [(), (32,)], # Scalar and vectorized ): a = torch.full(shape, num, dtype=dtype, device=device) b = torch.full(shape, denom, dtype=dtype, device=device) ref = np.floor_divide(num, denom).item() if ref > torch.finfo(dtype).max: ref = np.inf elif ref < torch.finfo(dtype).min: ref = -np.inf expect = torch.full(shape, ref, dtype=dtype, device=device) actual = torch.div(a, b, rounding_mode="floor") self.assertEqual(expect, actual) @dtypes(torch.bfloat16, torch.half, torch.float32, torch.float64) def test_div_rounding_nonfinite(self, device, dtype): # Compare division of special floating point values against NumPy num = torch.tensor( [1.0, -1.0, 0, 0.1, -0.1, np.pi, -np.pi, np.inf, -np.inf, np.nan], dtype=dtype, device=device, ) # Divide by zero is tested separately denom = num[num != 0] a, b = num[None, :].clone(), denom[:, None].clone() # Compare bfloat16 against NumPy float exact_dtype = dtype != torch.bfloat16 if exact_dtype: an, bn = a.cpu().numpy(), b.cpu().numpy() else: an, bn = a.float().cpu().numpy(), b.float().cpu().numpy() for mode, np_ref in ((None, np.true_divide), ("floor", np.floor_divide)): expect = np_ref(an, bn) kwargs = dict(rounding_mode=mode) if mode is not None else {} with set_default_dtype(torch.double): actual = torch.divide(a, b, **kwargs) self.assertEqual( actual, torch.from_numpy(expect), exact_device=False, exact_dtype=exact_dtype, ) # Compare contiguous (likely vectorized) against non-contiguous (not vectorized) a_noncontig = torch.empty([2 * i for i in a.shape], dtype=dtype, device=device)[ ::2, ::2 ] a_noncontig[:] = a b_noncontig = torch.empty([2 * i for i in b.shape], dtype=dtype, device=device)[ ::2, ::2 ] b_noncontig[:] = b for rounding_mode in (None, "trunc", "floor"): expect = torch.divide(a_noncontig, b_noncontig, rounding_mode=rounding_mode) actual = torch.divide(a, b, rounding_mode=rounding_mode) self.assertEqual(actual, expect) @dtypes(torch.bfloat16, torch.half, torch.float32, torch.float64) def test_divide_by_zero_rounding(self, device, dtype): a = torch.tensor( [1.0, -1.0, 0, 0.1, -0.1, np.pi, -np.pi, np.inf, -np.inf, np.nan], dtype=dtype, ) exact_dtype = dtype != torch.bfloat16 if exact_dtype: an = a.cpu().numpy() else: an = a.float().cpu().numpy() zero = torch.zeros_like(a) # NOTE: NumPy's floor_divide rounding changed in 1.20.0 to be consistent with divide expect = np.divide(an, 0) for rounding_mode in (None, "floor"): # CPU scalar actual = torch.divide(a, 0, rounding_mode=rounding_mode) self.assertEqual(actual, expect, exact_dtype=exact_dtype) # Device tensor actual = torch.divide(a, zero, rounding_mode=rounding_mode) self.assertEqual(actual, expect, exact_dtype=exact_dtype) @dtypes(*all_types_and(torch.half)) @dtypesIfXPU(*all_types()) def test_div_rounding_numpy(self, device, dtype): info = torch.finfo(dtype) if dtype.is_floating_point else torch.iinfo(dtype) low, high = info.min, info.max # Compare division of random values against NumPy a = make_tensor((4096,), dtype=dtype, device=device, low=low, high=high) b = make_tensor((4096,), dtype=dtype, device=device, low=low, high=high) # Avoid division by zero which raises for integers and, for floats, # NumPy 1.20 changed floor_divide to follow IEEE rules for inf/nan # after dividing by zero. b[b == 0] = 1 # Compare bfloat16 against NumPy float exact_dtype = dtype != torch.bfloat16 if exact_dtype: an, bn = a.cpu().numpy(), b.cpu().numpy() else: an, bn = a.float().cpu().numpy(), b.float().cpu().numpy() for mode, np_ref in ( (None, np.true_divide), ("floor", np.floor_divide), ("trunc", lambda a, b: np.trunc(np.true_divide(a, b)).astype(a.dtype)), ): expect = torch.from_numpy(np_ref(an, bn)) kwargs = dict(rounding_mode=mode) if mode is not None else {} # Contiguous (likely vectorized) with set_default_dtype(torch.double): actual = torch.divide(a, b, **kwargs) self.assertEqual( actual, expect, exact_device=False, exact_dtype=exact_dtype ) # Non-contiguous (not vectorized) expect = expect[::2] with set_default_dtype(torch.double): actual = torch.divide(a[::2], b[::2], **kwargs) self.assertEqual( actual, expect, exact_device=False, exact_dtype=exact_dtype ) @dtypes(*complex_types()) def test_complex_div_underflow_overflow(self, device, dtype): # test to make sure the complex division does not produce underflow or overflow # in the intermediate of its calculations # NOTE: the calculation still produces an error if the number is greater than # finfo.max / 2, but hopefully people realized that it's a dangerous region to work with finfo = torch.finfo(dtype) nom_lst = [ complex(finfo.min / 2, finfo.min / 2), complex(finfo.max / 2, finfo.max / 2), complex(finfo.tiny, finfo.tiny), complex(finfo.tiny, 0.0), complex(0.0, 0.0), ] denom_lst = [ complex(finfo.min / 2, finfo.min / 2), complex(finfo.max / 2, finfo.max / 2), complex(finfo.tiny, finfo.tiny), complex(0.0, finfo.tiny), complex(finfo.tiny, finfo.tiny), ] expected_lst = [ complex(1.0, 0.0), complex(1.0, 0.0), complex(1.0, 0.0), complex(0.0, -1.0), complex(0.0, 0.0), ] nom = torch.tensor(nom_lst, dtype=dtype, device=device) denom = torch.tensor(denom_lst, dtype=dtype, device=device) expected = torch.tensor(expected_lst, dtype=dtype, device=device) res = nom / denom self.assertEqual(res, expected) @onlyCUDA @dtypes(torch.float, torch.bfloat16) def test_division_by_scalar(self, device, dtype): num = torch.rand(1024, device=device, dtype=dtype) denom = torch.logspace(-4, 4, steps=20) denom = [d.item() for d in denom] res = [num / d for d in denom] ref = [num * (1 / d) for d in denom] self.assertEqual(res, ref, atol=0, rtol=0) # Tests that trying to add, inplace, a CUDA tensor to a CPU tensor # throws the correct error message @onlyCUDA def test_cross_device_inplace_error_msg(self, device): a = torch.tensor(2.0) b = torch.tensor(2.0, device=device) with self.assertRaisesRegex( RuntimeError, "Expected all tensors to be on the same device" ): a += b # TODO: refactor this test into a more generic one, it's parked here currently @onlyNativeDeviceTypes def test_out_resize_warning(self, device): a = torch.tensor((1, 2, 3), device=device, dtype=torch.float32) b = torch.tensor((4, 5, 6), device=device, dtype=torch.float32) unary_inputs = (a,) binary_inputs = (a, b) unary_ops = (torch.ceil, torch.exp) binary_ops = (torch.add, torch.sub) for op in unary_ops + binary_ops: with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") inputs = unary_inputs if op in unary_ops else binary_inputs # No warnings op(*inputs, out=torch.empty(3, device=device)) op(*inputs, out=torch.empty(0, device=device)) self.assertEqual(len(w), 0) # Cases that throw warnings op(*inputs, out=torch.empty(2, device=device)) self.assertEqual(len(w), 1) # test that multi-d out doesn't trigger segfault arg1 = (torch.ones(2, 1, device=device), torch.ones(1, device=device)) arg2 = (torch.ones(2, device=device), torch.ones(1, 1, device=device)) outs = ( torch.ones(2, 1, 1, 1, device=device), torch.ones(2, 2, 2, 2, device=device), ) for a1, a2, o in zip(arg1, arg2, outs): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") torch.mul(a1, a2, out=o) self.assertEqual(len(w), 1) # Verifies that the inplace dunders (like idiv) actually are in place @expectedFailureMeta # UserWarning not triggered @onlyNativeDeviceTypes def test_inplace_dunders(self, device): t = torch.randn((1,), device=device) expected = t.data_ptr() t += 1 t -= 1 t *= 1 t /= 1 t **= 1 t //= 1 t %= 1 self.assertEqual(expected, t.data_ptr()) def check_internal_mem_overlap( self, inplace_op, num_inputs, dtype, device, expected_failure=False ): if isinstance(inplace_op, str): inplace_op = getattr(torch.Tensor, inplace_op) input = torch.randn(1, dtype=dtype, device=device).expand(3, 3) inputs = [input] + [torch.randn_like(input) for i in range(num_inputs - 1)] if not expected_failure: with self.assertRaisesRegex(RuntimeError, "single memory location"): inplace_op(*inputs) else: with self.assertRaises(AssertionError): with self.assertRaisesRegex(RuntimeError, "single memory location"): inplace_op(*inputs) def unary_check_input_output_mem_overlap( self, data, sz, op, expected_failure=False ): def _test(op, output, input): output_exp = torch.empty_like(output) op(input, out=output_exp) self.assertEqual(op(input, out=output), output_exp, msg=op.__name__) # output is identical to input: _test(op, output=data[0:sz], input=data[0:sz]) # output and input are independent: _test(op, output=data[0:sz], input=data[sz : 2 * sz]) # output partially overlaps with input: if not expected_failure: with self.assertRaisesRegex(RuntimeError, "unsupported operation"): _test(op, data[0:sz], data[1 : sz + 1]) else: with self.assertRaises(AssertionError): with self.assertRaisesRegex(RuntimeError, "unsupported operation"): _test(op, data[0:sz], data[1 : sz + 1]) def binary_check_input_output_mem_overlap(self, op, device, expected_failure=False): sz = 3 data = torch.randn(2 * sz, device=device) other = torch.randn(sz, device=device) self.unary_check_input_output_mem_overlap( data, sz, lambda input, out: op(other, input, out=out), expected_failure=expected_failure, ) self.unary_check_input_output_mem_overlap( data, sz, lambda input, out: op(input, other, out=out), expected_failure=expected_failure, ) # https://github.com/pytorch/pytorch/issues/126474 @xfailIfTorchDynamo @dtypes(torch.double) def test_binary_op_mem_overlap(self, device, dtype): ops = [ ("add", True, True, ["cpu", "cuda", "xpu"]), ("mul", True, True, ["cpu", "cuda", "xpu"]), ("sub", True, True, ["cpu", "cuda", "xpu"]), ("div", True, True, ["cpu", "cuda", "xpu"]), ("pow", True, True, ["cpu", "cuda", "xpu"]), ("fmod", True, True, ["cpu", "cuda", "xpu"]), ("atan2", True, True, ["cpu", "cuda", "xpu"]), ("hypot", True, True, ["cpu", "cuda", "xpu"]), ("igamma", True, True, ["cpu", "cuda", "xpu"]), ("igammac", True, True, ["cpu", "cuda", "xpu"]), ("nextafter", True, True, ["cpu", "cuda", "xpu"]), ("le", True, True, ["cpu", "cuda", "xpu"]), ("lt", True, True, ["cpu", "cuda", "xpu"]), ("ge", True, True, ["cpu", "cuda", "xpu"]), ("gt", True, True, ["cpu", "cuda", "xpu"]), ("eq", True, True, ["cpu", "cuda", "xpu"]), ("ne", True, True, ["cpu", "cuda", "xpu"]), ("logical_and", True, True, ["cpu", "cuda", "xpu"]), ("logical_or", True, True, ["cpu", "cuda", "xpu"]), ("logical_xor", True, True, ["cpu", "cuda", "xpu"]), ] for ( fn, has_input_output_mem_overlap_check, has_internal_mem_overlap_check, devs, ) in ops: if torch.device(device).type not in devs: continue out_op = getattr(torch, fn) inplace_op = getattr(torch.Tensor, fn + "_") self.check_internal_mem_overlap( inplace_op, 2, dtype, device, expected_failure=not has_internal_mem_overlap_check, ) self.binary_check_input_output_mem_overlap( out_op, device, expected_failure=not has_input_output_mem_overlap_check ) def _do_pow_for_exponents(self, m1, exponents, pow_fn, atol): for num in exponents: if ( isinstance(num, int) and num < 0 and not m1.is_floating_point() and not m1.is_complex() ): with self.assertRaisesRegex( RuntimeError, r"Integers to negative integer powers are not allowed\.", ): torch.pow(m1[4], num) else: # base - tensor, exponent - number # contiguous res1 = torch.pow(m1[4], num) res2 = res1.clone().zero_() # `math.pow` has issues with complex exponentiation so we need to resort to normal `pow`. for i in range(res2.size(0)): res2[i] = pow_fn(m1[4][i], num) rtol = 0 if atol is not None else None self.assertEqual(res1, res2, atol=atol, rtol=rtol) # non-contiguous res1 = torch.pow(m1[:, 4], num) res2 = res1.clone().zero_() for i in range(res2.size(0)): res2[i] = pow_fn(m1[i, 4], num) self.assertEqual(res1, res2, atol=atol, rtol=rtol) # scalar ** tensor to enforce correct handling of dtypes for __rpow__(). expected_dtype = torch.result_type(num, m1) res1 = num ** m1[4] res2 = ( torch.tensor(num, dtype=expected_dtype, device=m1.device) ** m1[4] ) self.assertEqual(res1, res2) self.assertEqual(res1.dtype, expected_dtype) @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_pow(self, device, dtype): m1 = torch.empty(0, dtype=dtype, device=device) if m1.is_floating_point() or m1.is_complex(): m1 = ( make_tensor((100, 100), low=0, high=1, dtype=dtype, device=device) + 0.5 ) else: # math.pow will overflow and throw exceptions for large integers range_high = 4 if dtype in (torch.int8, torch.uint8) else 10 m1 = make_tensor( (100, 100), low=1, high=range_high, dtype=dtype, device=device ) exponents = [-2.8, -2, -1, -0.5, 0, 0.5, 1, 2, 3, 4, 3.3, True, False] complex_exponents = [ -2.5j, -1.0j, 0j, 1.0j, 2.5j, 1.0 + 1.0j, -1.0 - 1.5j, 3.3j, ] if m1.is_complex(): self._do_pow_for_exponents(m1, exponents + complex_exponents, pow, 10e-4) else: self._do_pow_for_exponents(m1, exponents, math.pow, None) will_raise_error = ( dtype is torch.half and torch.device(device).type == "cpu" ) if will_raise_error: # On CPU, # Half Tensor with complex exponents leads to computation dtype # of ComplexHalf for which this ops is not supported yet with self.assertRaisesRegex( RuntimeError, "not implemented for 'ComplexHalf'" ): self._do_pow_for_exponents(m1, complex_exponents, pow, 10e-4) else: self._do_pow_for_exponents(m1, complex_exponents, pow, 10e-4) # base - number, exponent - tensor # contiguous res1 = torch.pow(3, m1[4]) res2 = res1.clone().zero_() for i in range(res2.size(0)): res2[i] = pow(3, m1[4, i]) self.assertEqual(res1, res2) # non-contiguous res1 = torch.pow(3, m1[:, 4]) res2 = res1.clone().zero_() for i in range(res2.size(0)): res2[i] = pow(3, m1[i][4]) self.assertEqual(res1, res2) # TODO: refactor all these tests using opinfos properly def _test_pow(self, base, exponent, np_exponent=None): if np_exponent is None: np_exponent = exponent def to_np(value): if isinstance(value, torch.Tensor): return value.cpu().numpy() return value try: np_res = np.power(to_np(base), to_np(np_exponent)) expected = ( torch.from_numpy(np_res) if isinstance(np_res, np.ndarray) else torch.tensor(np_res, dtype=base.dtype) ) except ValueError as e: err_msg = "Integers to negative integer powers are not allowed." self.assertEqual(str(e), err_msg) out = torch.empty_like(base) test_cases = [ lambda: base.pow(exponent), lambda: base.pow_(exponent), lambda: torch.pow(base, exponent), lambda: torch.pow(base, exponent, out=out), ] for test_case in test_cases: self.assertRaisesRegex(RuntimeError, err_msg, test_case) else: if isinstance(base, torch.Tensor): actual = base.pow(exponent) self.assertEqual(actual, expected.to(actual)) actual = base.clone() # When base is a 0-dim cpu tensor and exp is a cuda tensor, we exp `pow` to work but `pow_` to fail, since # `pow` will try to create the output tensor on a cuda device, but `pow_` needs to use the cpu tensor as the output if ( isinstance(exponent, torch.Tensor) and base.dim() == 0 and base.device.type == "cpu" and exponent.device.type in ["cuda", "xpu"] ): regex = ( f"Expected all tensors to be on the same device, " f"but found at least two devices, {device_type}.* and cpu!" ) self.assertRaisesRegex(RuntimeError, regex, base.pow_, exponent) elif torch.can_cast(torch.result_type(base, exponent), base.dtype): actual2 = actual.pow_(exponent) self.assertEqual(actual, expected.to(actual)) self.assertEqual(actual2, expected.to(actual2)) else: self.assertRaisesRegex( RuntimeError, r"result type \w+ can't be cast to the desired output type \w+", lambda: actual.pow_(exponent), ) actual = torch.pow(base, exponent) self.assertEqual(actual, expected.to(actual)) actual2 = torch.pow(base, exponent, out=actual) self.assertEqual(actual, expected.to(actual)) self.assertEqual(actual2, expected.to(actual)) # We can potentially merge this into OpInfo, but one blocker is that the # first input must be a scalar. It is not as simple as just wrapping this in # a lambada that switches the inputs, because we also want to test samples inputs # where the second input is a scalar. The wrapper would need some more logic. def test_pow_scalar_base(self, device): a = ( torch.arange(1, 13, dtype=torch.double, device=device) .view(3, 4) .requires_grad_() ) gradcheck(lambda a: torch.pow(2, a), (a,)) # Tests pow() for integral, floating-type tensors, with integral, floating-type # exponents (tensor or scalar), respectively. noncontiguous tensors are also tested. def test_int_and_float_pow(self, device): def _test_int_and_float_pow(dt, low, high, dev): test_cases = ( ((4, 4), 0, (4, 1)), ((3, 1), 4, (3, 1)), ((2,), 4, (1,)), ((1,), 2, ()), ((513, 513), 4, (513,)), ((5, 5, 5), 5, (5,)), ((), 2, ()), ) for base_shape, exp_scalar, exp_shape in test_cases: base_tensor = make_tensor( base_shape, dtype=dt, device=dev, low=low, high=high ) # int tensors don't take negative exponents if dt in [ torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64, ]: exp_tensor = make_tensor( exp_shape, dtype=dt, device=dev, low=0, high=high ) else: exp_tensor = make_tensor( exp_shape, dtype=dt, device=dev, low=low, high=high ) self._test_pow(base_tensor, exp_scalar) self._test_pow(base_tensor, exp_tensor) # test non-contiguous tensors as well base_tensor = make_tensor( base_shape, dtype=dt, device=dev, low=low, high=high, noncontiguous=True, ) if dt in [ torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64, ]: exp_tensor = make_tensor( exp_shape, dtype=dt, device=dev, low=0, high=high, noncontiguous=True, ) else: exp_tensor = make_tensor( exp_shape, dtype=dt, device=dev, low=low, high=high, noncontiguous=True, ) self._test_pow(base_tensor, exp_scalar) self._test_pow(base_tensor, exp_tensor) _test_int_and_float_pow(torch.int8, -2, 2, device) _test_int_and_float_pow(torch.uint8, 0, 3, device) _test_int_and_float_pow(torch.int16, -5, 5, device) _test_int_and_float_pow(torch.int64, -10, 10, device) _test_int_and_float_pow(torch.int32, -10, 10, device) _test_int_and_float_pow(torch.float16, 0.0, 5.0, device) _test_int_and_float_pow(torch.float32, 0.0, 10.0, device) _test_int_and_float_pow(torch.float64, 0.0, 10.0, device) # pow's output would have some NaNs as well _test_int_and_float_pow(torch.float32, -10.0, 10.0, device) _test_int_and_float_pow(torch.float64, -10.0, 10.0, device) # Tests that a Runtime error occurs when a base tensor cannot be resized # by pow's inplace variant due to PyTorch's broadcasting semantics. def test_pow_inplace_resizing_exception(self, device): test_cases = ( ((), (3,)), ((2,), (2, 1)), ((2, 1), (2, 2)), ((2, 2), (2, 1, 1)), ) test_inputs = [ ( make_tensor( base_size, dtype=torch.float64, device=device, high=10.0, low=0.0 ), make_tensor( exp_size, dtype=torch.float64, device=device, high=10.0, low=0.0 ), ) for base_size, exp_size in test_cases ] for base, exponent in test_inputs: regex = "doesn't match the broadcast shape" self.assertRaisesRegex(RuntimeError, regex, base.pow_, exponent) def test_int_tensor_pow_neg_ints(self, device): ints = [ torch.iinfo(torch.int32).min, -3, -2, -1, 0, 1, 2, 3, torch.iinfo(torch.int32).max, ] neg_ints = [torch.iinfo(torch.int32).min, -3, -2, -1] tensor = torch.tensor(ints, dtype=torch.int32, device=device) for pow in neg_ints: self._test_pow(tensor, pow) def test_long_tensor_pow_floats(self, device): ints = [0, 1, 23, 4567] floats = [0.0, 1 / 3, 1 / 2, 1.0, 3 / 2, 2.0] tensor = torch.tensor(ints, dtype=torch.int64, device=device) for pow in floats: self._test_pow(tensor, pow) @dtypes(*[torch.float32, torch.float64]) def test_float_scalar_pow_float_tensor(self, device, dtype): floats = [2.0, -3 / 2, -1.0, -1 / 2, -1 / 3, 0.0, 1 / 3, 1 / 2, 1.0, 3 / 2, 2.0] exponent_shapes = ( (1,), (2, 2), (2, 1), (2, 2, 2), ) tensors = [ make_tensor(shape, dtype=dtype, device=device, low=0) for shape in exponent_shapes ] floats_tensor = torch.tensor(floats, dtype=dtype, device=device) for base in floats: self._test_pow(base, floats_tensor) for tensor in tensors: self._test_pow(base, tensor) @onlyOn(["cuda", "xpu"]) def test_cuda_tensor_pow_scalar_tensor(self, device): cuda_tensors = [ torch.randn((3, 3), device=device), torch.tensor(3.0, device=device), ] scalar_tensors = [ torch.tensor(5.0, device="cpu"), torch.tensor(-3), torch.tensor(1), ] for base, exp in product(cuda_tensors, scalar_tensors): self._test_pow(base, exp) @onlyOn(["cuda", "xpu"]) def test_cpu_tensor_pow_cuda_scalar_tensor(self, device): cuda_tensors = [ torch.tensor(5.0, device=device_type), torch.tensor(-3, device=device_type), ] for exp in cuda_tensors: base = torch.randn((3, 3), device="cpu") regex = f"Expected all tensors to be on the same device, but found at least two devices, {device_type}.* and cpu!" self.assertRaisesRegex(RuntimeError, regex, torch.pow, base, exp) for exp in cuda_tensors: # Binary ops with a cpu + cuda tensor are allowed if the cpu tensor has 0 dimension base = torch.tensor(3.0, device="cpu") self._test_pow(base, exp) @onlyCUDA @dtypes(torch.complex64, torch.complex128) def test_pow_cuda_complex_extremal_passing(self, device, dtype): t = torch.tensor(complex(-1.0, float("inf")), dtype=dtype, device=device) cuda_out = t.pow(2) cpu_out = t.cpu().pow(2) self.assertEqual(cpu_out, cuda_out) @skipIfTorchDynamo() @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half)) def test_complex_scalar_pow_tensor(self, device, dtype): complexes = [0.5j, 1.0 + 1.0j, -1.5j, 2.2 - 1.6j, 1 + 0j] first_exp = make_tensor((100,), dtype=dtype, device=device, low=-2, high=2) second_exp = make_tensor( (100,), dtype=dtype, device=device, low=-2, high=2, noncontiguous=True ) first_exp[0] = first_exp[10] = first_exp[20] = 0 second_exp[0] = second_exp[10] = second_exp[20] = 0 for base in complexes: # On CPU, # Half Tensor with complex base leads to computation dtype # of ComplexHalf for which this ops is not supported yet # NOTE: pow has fast-path when base is 1 which supports # ComplexHalf will_raise_error = ( torch.device(device).type == "cpu" and dtype is torch.half and base != (1 + 0j) ) if will_raise_error: with self.assertRaisesRegex( RuntimeError, "not implemented for 'ComplexHalf'" ): self._test_pow(base, first_exp) self._test_pow(base, second_exp) else: self._test_pow(base, first_exp) self._test_pow(base, second_exp) @onlyNativeDeviceTypes @skipMeta def test_pow_scalar_type_promotion(self, device): # Test against a scalar and non-scalar input inputs = [17, [17]] for input in inputs: # We expect the computation to be performed in uint8 (overflowing to 0), and then cast to int64 input_tensor_uint8 = torch.tensor(input, dtype=torch.uint8, device=device) out_uint8_computation = torch.pow( 2, input_tensor_uint8, out=torch.tensor(0, dtype=torch.int64, device=device), ) # Computation should run in int64, and not overflow input_tensor_int64 = torch.tensor(input, dtype=torch.int64, device=device) out_int64_computation = torch.pow( 2, input_tensor_int64, out=torch.tensor(0, dtype=torch.int64, device=device), ) self.assertNotEqual(out_uint8_computation, out_int64_computation) self.assertEqual( out_uint8_computation.to(dtype=torch.uint8), out_int64_computation.to(dtype=torch.uint8), ) def test_tensor_pow_tensor(self, device): def rotate(l, n): return l[-n:] + l[:-n] def test_tensor_pow_tensor(values, torch_type, numpy_type): vals_tensor = torch.tensor(values, dtype=torch_type, device=device) for i in range(len(values)): pows = rotate(values, i) pows_tensor = torch.tensor(pows, dtype=torch_type, device=device) self._test_pow(vals_tensor, pows_tensor) ints = [0, 1, 2, 3] test_tensor_pow_tensor(ints, torch.uint8, np.uint8) test_tensor_pow_tensor(ints, torch.int8, np.int8) test_tensor_pow_tensor(ints, torch.int16, np.int16) test_tensor_pow_tensor(ints, torch.int32, np.int32) test_tensor_pow_tensor(ints, torch.int64, np.int64) floats = [-3.0, -2.0, -1.0, -1 / 2, -1 / 3, 0.0, 1 / 3, 1 / 2, 1.0, 2.0, 3.0] test_tensor_pow_tensor(floats, torch.float16, np.float16) test_tensor_pow_tensor(floats, torch.float32, np.float32) test_tensor_pow_tensor(floats, torch.float64, np.float64) def test_logical_xor_with_nontrivial_alignment(self, device): # test tensor that is not aligned to multiple of 16 bytes size = 128 a = torch.randn(size, device=device) > 0 b = torch.randn(size, device=device) > 0 c = torch.randn(size, device=device) > 0 non_trivial_alignment = [1, 2, 4, 8, 15] for i in non_trivial_alignment: for j in non_trivial_alignment: for k in non_trivial_alignment: a_ = a[i : 100 + i] b_ = b[j : 100 + j] c_ = c[k : 100 + k] torch.logical_xor(a_, b_, out=c_) for x, y, z in zip(a_.tolist(), b_.tolist(), c_.tolist()): self.assertEqual(x ^ y, z) @dtypes(torch.float) def test_add_with_tail(self, device, dtype): # test tensor where there is a tail which is not a multiple # of GPU warp size for tail_size in [1, 63, 67, 130]: size = 4096 + tail_size a = torch.randn(size, device=device, dtype=dtype) b = torch.randn(size, device=device, dtype=dtype) c = a + b for x, y, z in zip(a.tolist(), b.tolist(), c.tolist()): self.assertEqual(x + y, z) # Tests that CUDA tensors on different devices cannot be used in the same # binary operation, and that CUDA "scalars" cannot be used in the same # binary operation as non-scalar CPU tensors. @deviceCountAtLeast(2) @onlyOn(["cuda", "xpu"]) def test_cross_device_binary_ops(self, devices): vals = (1.0, (2.0,)) cpu_tensor = torch.randn(2, 2) def do_test(op, a, b): with self.assertRaisesRegex(RuntimeError, "Expected all tensors.+"): op(a, b) with self.assertRaisesRegex(RuntimeError, "Expected all tensors.+"): op(b, a) with self.assertRaisesRegex(RuntimeError, "Expected all tensors.+"): op(a, cpu_tensor) with self.assertRaisesRegex(RuntimeError, "Expected all tensors.+"): op(cpu_tensor, a) for op in ( operator.add, torch.add, operator.sub, torch.sub, operator.mul, torch.mul, operator.truediv, torch.true_divide, operator.floordiv, torch.floor_divide, ): for a, b in product(vals, vals): a = torch.tensor(a, device=devices[0]) b = torch.tensor(b, device=devices[1]) do_test(op, a, b) # This test ensures that a scalar Tensor can be safely used # in a binary operation in conjunction with a Tensor on all # available CUDA devices @deviceCountAtLeast(2) @onlyOn(["cuda", "xpu"]) def test_binary_op_scalar_device_unspecified(self, devices): scalar_val = torch.tensor(1.0) for default_device in devices: with torch.accelerator.device_index(torch.device(default_device).index): for device in devices: device_obj = torch.device(device) x = torch.rand(3, device=device) y0 = x * scalar_val self.assertEqual(y0.device, device_obj) y1 = scalar_val * x self.assertEqual(y1.device, device_obj) self.assertEqual(y0, y1) def test_div_and_floordiv_vs_python(self, device): # Tests torch division ops which can handle both arguments being # scalars. def _scalar_helper(python_op, torch_op): for a, b in product(range(-10, 10), range(-10, 10)): for op in (lambda x: x * 0.5, lambda x: math.floor(x)): a = op(a) b = op(b) # Skips zero divisors if b == 0: continue expected = python_op(a, b) actual_scalar = torch_op(a, b) a_t = torch.tensor(a, device=device) b_t = torch.tensor(b, device=device) actual_tensor = torch_op(a_t, b_t) actual_first_tensor = torch_op(a_t, b) actual_second_tensor = torch_op(a, b_t) self.assertEqual(actual_scalar, expected) self.assertEqual(actual_tensor.item(), expected) self.assertEqual(actual_first_tensor, actual_tensor) self.assertEqual(actual_second_tensor, actual_tensor) _scalar_helper(operator.truediv, operator.truediv) _scalar_helper(operator.truediv, torch.true_divide) _scalar_helper(lambda a, b: math.floor(a / b), operator.floordiv) _scalar_helper(lambda a, b: math.floor(a / b), torch.floor_divide) @onlyNativeDeviceTypes @skipIfTorchDynamo("Not a suitable test for TorchDynamo") def test_div_and_floordiv_script_vs_python(self, device): # Creates jitted functions of two tensors def _wrapped_div(a, b): return a / b def _wrapped_floordiv(a, b): return a // b scripted_div = torch.jit.script(_wrapped_div) scripted_floordiv = torch.jit.script(_wrapped_floordiv) for a, b in product(range(-10, 10), range(-10, 10)): for op in (lambda x: x * 0.5, lambda x: math.floor(x)): a = op(a) b = op(b) # Skips zero divisors if b == 0: continue expected_div = a / b expected_floordiv = math.floor(a / b) a_t = torch.tensor(a, device=device) b_t = torch.tensor(b, device=device) self.assertEqual(scripted_div(a_t, b_t), expected_div) self.assertEqual(scripted_floordiv(a_t, b_t), expected_floordiv) # Creates jitted functions of one tensor def _wrapped_div_scalar(a): return a / 5 # NOTE: the JIT implements division as torch.reciprocal(a) * 5 def _wrapped_rdiv_scalar(a): return 5 / a def _wrapped_floordiv_scalar(a): return a // 5 # NOTE: this fails if the input is not an integer tensor # See https://github.com/pytorch/pytorch/issues/45199 def _wrapped_rfloordiv_scalar(a): return 5 // a scripted_div_scalar = torch.jit.script(_wrapped_div_scalar) scripted_rdiv_scalar = torch.jit.script(_wrapped_rdiv_scalar) scripted_floordiv_scalar = torch.jit.script(_wrapped_floordiv_scalar) scripted_rfloordiv_scalar = torch.jit.script(_wrapped_rfloordiv_scalar) for a in range(-10, 10): for op in (lambda x: x * 0.5, lambda x: math.floor(x)): a = op(a) a_t = torch.tensor(a, device=device) self.assertEqual(a / 5, scripted_div_scalar(a_t)) # Skips zero divisors if a == 0: continue self.assertEqual(5 / a, scripted_rdiv_scalar(a_t)) # Handles Issue 45199 (see comment above) if a_t.is_floating_point(): with self.assertRaises(RuntimeError): scripted_rfloordiv_scalar(a_t) else: # This should emit a UserWarning, why doesn't it? # See issue gh-52387 self.assertEqual(5 // a, scripted_rfloordiv_scalar(a_t)) @onlyNativeDeviceTypes @skipIfTorchDynamo("Not a suitable test for TorchDynamo") def test_idiv_and_ifloordiv_vs_python(self, device): def _wrapped_idiv_tensor(a, b): a /= b return a def _wrapped_idiv_scalar(a): a /= 5 return a def _wrapped_true_divide__tensor(a, b): a.true_divide_(b) return a def _wrapped_true_divide__scalar(a): a.true_divide_(5) return a def _wrapped_floor_divide__tensor(a, b): a.floor_divide_(b) return a def _wrapped_floor_divide__scalar(a): a.floor_divide_(5) return a # The following functions are unsupported by the JIT def _wrapped_ifloordiv_tensor(a, b): a //= b return a def _wrapped_ifloordiv_scalar(a): a //= 5 return a with self.assertRaises(torch.jit.frontend.NotSupportedError): scripted_ifloordiv_tensor = torch.jit.script(_wrapped_ifloordiv_tensor) with self.assertRaises(torch.jit.frontend.NotSupportedError): scripted_ifloordiv_scalar = torch.jit.script(_wrapped_ifloordiv_scalar) scripted_idiv_tensor = torch.jit.script(_wrapped_idiv_tensor) scripted_idiv_scalar = torch.jit.script(_wrapped_idiv_scalar) scripted_true_divide__tensor = torch.jit.script(_wrapped_true_divide__tensor) scripted_true_divide__scalar = torch.jit.script(_wrapped_true_divide__scalar) scripted_floor_divide__tensor = torch.jit.script(_wrapped_floor_divide__tensor) scripted_floor_divide__scalar = torch.jit.script(_wrapped_floor_divide__scalar) for a, b in product(range(-10, 10), range(-10, 10)): for op in (lambda x: x * 0.5, lambda x: math.floor(x)): a = op(a) b = op(b) # Skips zero divisors if b == 0: continue expected_idiv = a / b expected_ifloordiv = a // b a_t = torch.tensor(a, device=device) b_t = torch.tensor(b, device=device) if a_t.is_floating_point(): tmp0 = a_t.clone() tmp0 /= b tmp1 = a_t.clone() tmp1 /= b_t self.assertEqual(tmp0.item(), expected_idiv) self.assertEqual(tmp1.item(), expected_idiv) self.assertEqual( scripted_true_divide__tensor(a_t.clone(), b_t).item(), expected_idiv, ) self.assertEqual( scripted_true_divide__scalar(a_t.clone()).item(), a / 5 ) else: tmp = a_t.clone() with self.assertRaises(RuntimeError): tmp /= b with self.assertRaises(RuntimeError): tmp /= b_t with self.assertRaises(RuntimeError): scripted_true_divide__tensor(tmp, b_t) with self.assertRaises(RuntimeError): scripted_true_divide__scalar(tmp) if not a_t.is_floating_point() and b_t.is_floating_point(): # Inplace modification fails because a float tensor is required # if the divisor is a float tensor a_t.clone().floor_divide_(b_t) scripted_floor_divide__tensor(a_t.clone(), b_t) tmp = a_t.clone() tmp //= b_t else: # Inplace modification is OK when both or neither tensor is # a float tensor self.assertEqual( a_t.clone().floor_divide_(b_t).item(), expected_ifloordiv ) self.assertEqual( scripted_floor_divide__tensor(a_t.clone(), b_t).item(), expected_ifloordiv, ) tmp = a_t.clone() tmp //= b_t self.assertEqual(tmp.item(), expected_ifloordiv) self.assertEqual(scripted_floor_divide__scalar(a_t), math.floor(a / 5)) # Tests binary op equivalence with Python builtin ops # Also tests that reverse operations are equivalent to forward ops # NOTE: division ops are tested separately above def test_binary_ops_with_scalars(self, device): for python_op, torch_op in ( (operator.add, torch.add), (operator.sub, torch.sub), (operator.mul, torch.mul), (operator.truediv, torch.div), ): for a, b in product(range(-10, 10), range(-10, 10)): for op in (lambda x: x * 0.5, lambda x: math.floor(x)): a = op(a) b = op(b) # Skips zero divisors if b == 0 or a == 0: continue a_tensor = torch.tensor(a, device=device) b_tensor = torch.tensor(b, device=device) a_tensor_cpu = a_tensor.cpu() b_tensor_cpu = b_tensor.cpu() vals = (a, b, a_tensor, b_tensor, a_tensor_cpu, b_tensor_cpu) for args in product(vals, vals): first, second = args first_scalar = ( first if not isinstance(first, torch.Tensor) else first.item() ) second_scalar = ( second if not isinstance(second, torch.Tensor) else second.item() ) expected = python_op(first_scalar, second_scalar) self.assertEqual(expected, python_op(first, second)) self.assertEqual(expected, torch_op(first, second)) @dtypes( *product( all_types_and(torch.half, torch.bfloat16, torch.bool), all_types_and(torch.half, torch.bfloat16, torch.bool), ) ) def test_maximum_minimum_type_promotion(self, device, dtypes): a = torch.tensor((0, 1), device=device, dtype=dtypes[0]) b = torch.tensor((1, 0), device=device, dtype=dtypes[1]) for op in ( torch.maximum, torch.max, torch.fmax, torch.minimum, torch.min, torch.fmin, ): result = op(a, b) self.assertEqual(result.dtype, torch.result_type(a, b)) @dtypes(*integral_types_and(torch.bool)) def test_maximum_minimum_int_and_bool(self, device, dtype): ops = ( (torch.maximum, torch.max, np.maximum), (torch.minimum, torch.min, np.minimum), (torch.fmax, None, np.fmax), (torch.fmin, None, np.fmin), ) rng = np.random.default_rng() a_np = np.array( rng.integers(-100, 100, size=10), dtype=torch_to_numpy_dtype_dict[dtype] ) b_np = np.array( rng.integers(-100, 100, size=10), dtype=torch_to_numpy_dtype_dict[dtype] ) for torch_op, alias, numpy_op in ops: a_tensor = torch.from_numpy(a_np).to(device=device, dtype=dtype) b_tensor = torch.from_numpy(b_np).to(device=device, dtype=dtype) tensor_result = torch_op(a_tensor, b_tensor) out = torch.empty_like(a_tensor) torch_op(a_tensor, b_tensor, out=out) numpy_result = numpy_op(a_np, b_np) if alias is not None: alias_result = alias(a_tensor, b_tensor) self.assertEqual(alias_result, tensor_result) self.assertEqual(tensor_result, numpy_result) self.assertEqual(out, numpy_result) @precisionOverride({torch.bfloat16: 1e-2}) @dtypes(*(floating_types_and(torch.half, torch.bfloat16))) def test_maximum_minimum_float(self, device, dtype): ops = ( (torch.maximum, torch.max, np.maximum), (torch.minimum, torch.min, np.minimum), (torch.fmax, None, np.fmax), (torch.fmin, None, np.fmin), ) if dtype == torch.bfloat16: a_np = np.random.randn(10).astype(np.float64) b_np = np.random.randn(10).astype(np.float64) else: a_np = np.random.randn(10).astype(torch_to_numpy_dtype_dict[dtype]) b_np = np.random.randn(10).astype(torch_to_numpy_dtype_dict[dtype]) for torch_op, alias, numpy_op in ops: numpy_result = numpy_op(a_np, b_np) a_tensor = torch.from_numpy(a_np).to(device=device, dtype=dtype) b_tensor = torch.from_numpy(b_np).to(device=device, dtype=dtype) tensor_result = torch_op(a_tensor, b_tensor) out = torch.empty_like(a_tensor) torch_op(a_tensor, b_tensor, out=out) if alias is not None: alias_result = alias(a_tensor, b_tensor) self.assertEqual(alias_result, tensor_result, exact_dtype=False) self.assertEqual(tensor_result, numpy_result, exact_dtype=False) self.assertEqual(out, numpy_result, exact_dtype=False) @dtypes(*(floating_types_and(torch.half, torch.bfloat16))) def test_maximum_minimum_float_nan_and_inf(self, device, dtype): # np.maximum and np.minimum functions compare input arrays element-wisely. # if one of the elements being compared is a NaN, then that element is returned. ops = ( (torch.maximum, torch.max, np.maximum), (torch.minimum, torch.min, np.minimum), (torch.fmax, None, np.fmax), (torch.fmin, None, np.fmin), ) a_vals = ( float("inf"), -float("inf"), float("nan"), float("inf"), float("nan"), float("nan"), 1, float("nan"), ) b_vals = ( -float("inf"), float("inf"), float("inf"), float("nan"), float("nan"), 0, float("nan"), -5, ) if dtype == torch.bfloat16: a_np = np.array(a_vals, dtype=np.float64) b_np = np.array(b_vals, dtype=np.float64) else: a_np = np.array(a_vals, dtype=torch_to_numpy_dtype_dict[dtype]) b_np = np.array(b_vals, dtype=torch_to_numpy_dtype_dict[dtype]) for torch_op, alias, numpy_op in ops: numpy_result = numpy_op(a_np, b_np) a_tensor = torch.from_numpy(a_np).to(device=device, dtype=dtype) b_tensor = torch.from_numpy(b_np).to(device=device, dtype=dtype) tensor_result = torch_op(a_tensor, b_tensor) out = torch.empty_like(a_tensor) torch_op(a_tensor, b_tensor, out=out) if alias is not None: alias_result = alias(a_tensor, b_tensor) self.assertEqual(alias_result, tensor_result) if dtype == torch.bfloat16: self.assertEqual(tensor_result, numpy_result, exact_dtype=False) self.assertEqual(out, numpy_result, exact_dtype=False) else: self.assertEqual(tensor_result, numpy_result) self.assertEqual(out, numpy_result) @dtypes( *product( complex_types(), all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool), ) ) def test_maximum_minimum_complex(self, device, dtypes): for torch_op in ( torch.maximum, torch.minimum, torch.max, torch.min, torch.fmax, torch.fmin, ): with self.assertRaisesRegex(RuntimeError, ".+not implemented for.+"): torch_op( torch.ones(1, device=device, dtype=dtypes[0]), torch.ones(1, device=device, dtype=dtypes[1]), ) with self.assertRaisesRegex(RuntimeError, ".+not implemented for.+"): torch_op( torch.ones(1, device=device, dtype=dtypes[1]), torch.ones(1, device=device, dtype=dtypes[0]), ) @onlyOn(["cuda", "xpu"]) def test_maximum_minimum_cross_device(self, device): a = torch.tensor((1, 2, -1)) b = torch.tensor((3, 0, 4), device=device) ops = (torch.maximum, torch.minimum) for torch_op in ops: with self.assertRaisesRegex( RuntimeError, "Expected all tensors to be on the same device" ): torch_op(a, b) with self.assertRaisesRegex( RuntimeError, "Expected all tensors to be on the same device" ): torch_op(b, a) # test cuda tensor and cpu scalar ops = ((torch.maximum, np.maximum), (torch.minimum, np.minimum)) a_np = np.array(1) b_np = np.array([3, 0, 4]) for torch_op, numpy_op in ops: a_tensor = torch.from_numpy(a_np) b_tensor = torch.from_numpy(b_np).to(device=device) tensor_result_1 = torch_op(a_tensor, b_tensor) numpy_result_1 = numpy_op(a_np, b_np) tensor_result_2 = torch_op(b_tensor, a_tensor) numpy_result_2 = numpy_op(b_np, a_np) self.assertEqual(tensor_result_1, numpy_result_1) self.assertEqual(tensor_result_2, numpy_result_2) @dtypes( *product( floating_types_and(torch.half, torch.bfloat16), floating_types_and(torch.half, torch.bfloat16), ) ) def test_maximum_and_minimum_subgradient(self, device, dtypes): def run_test(f, a, b, expected_a_grad, expected_b_grad): a = torch.tensor(a, requires_grad=True, device=device, dtype=dtypes[0]) b = torch.tensor(b, requires_grad=True, device=device, dtype=dtypes[1]) z = f(a, b) z.sum().backward() self.assertEqual(a.grad, expected_a_grad) self.assertEqual(b.grad, expected_b_grad) run_test( torch.maximum, [0.0, 1.0, 2.0], [1.0, 1.0, 1.0], [0.0, 0.5, 1.0], [1.0, 0.5, 0.0], ) run_test( torch.minimum, [0.0, 1.0, 2.0], [1.0, 1.0, 1.0], [1.0, 0.5, 0.0], [0.0, 0.5, 1.0], ) def test_maximum_minimum_forward_ad_float32(self, device): # TODO: This should really be covered by OpInfo but it isn't. The problem # is that our gradient tests test using float64 but it should also test # float32 x = torch.randn(3, device=device, dtype=torch.float32) y = torch.randn(3, device=device, dtype=torch.float32) tx = torch.randn(3, device=device, dtype=torch.float32) ty = torch.randn(3, device=device, dtype=torch.float32) with fwAD.dual_level(): x_dual = fwAD.make_dual(x, tx) y_dual = fwAD.make_dual(y, ty) result = torch.maximum(x_dual, y_dual) _, result_tangent = fwAD.unpack_dual(result) expected = torch.where(x > y, tx, ty) self.assertEqual(result_tangent, expected) with fwAD.dual_level(): x_dual = fwAD.make_dual(x, tx) y_dual = fwAD.make_dual(y, ty) result = torch.minimum(x_dual, y_dual) _, result_tangent = fwAD.unpack_dual(result) expected = torch.where(x < y, tx, ty) self.assertEqual(result_tangent, expected) # TODO: tests like this should be generic @dtypesIfCUDA(torch.half, torch.float, torch.double) @dtypesIfXPU(torch.half, torch.float, torch.double) @dtypes(torch.float, torch.double) def test_mul_intertype_scalar(self, device, dtype): x = torch.tensor(1.5, dtype=dtype, device=device) y = torch.tensor(3, dtype=torch.int32, device=device) self.assertEqual(x * y, 4.5) self.assertEqual(y * x, 4.5) with self.assertRaisesRegex( RuntimeError, "can't be cast to the desired output type" ): y *= x x *= y self.assertEqual(x, 4.5) @onlyCPU @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool)) def test_sub(self, device, dtype): if dtype in integral_types(): # Before Python 3.10, floats were implicitly converted to ints, but with # DeprecationWarning: an integer is required (got type float). # Implicit conversion to integers using __int__ is deprecated, # and may be removed in a future version of Python. # Since Python 3.10, that attempt gives an error. m1 = torch.tensor([2, 4], dtype=dtype, device=device) m2 = torch.tensor([1, 2], dtype=dtype, device=device) diff = torch.tensor([1, 2], dtype=dtype) else: m1 = torch.tensor([2.34, 4.44], dtype=dtype, device=device) m2 = torch.tensor([1.23, 2.33], dtype=dtype, device=device) diff = torch.tensor([1.11, 2.11], dtype=dtype) if dtype == torch.bool: self.assertRaises(RuntimeError, lambda: m1 - m2) elif dtype == torch.bfloat16 or dtype == torch.half: # bfloat16 has a lower precision so we have to have a separate check for it self.assertEqual(m1 - m2, diff, atol=0.01, rtol=0) else: self.assertEqual(m1 - m2, diff) # TODO: what is this test testing? @onlyCPU @dtypes(torch.float) def test_csub(self, device, dtype): # with a tensor a = torch.randn(100, 90, dtype=dtype, device=device) b = a.clone().normal_() res_add = torch.add(a, b, alpha=-1) res_csub = a.clone() res_csub.sub_(b) self.assertEqual(res_add, res_csub) # with a scalar a = torch.randn(100, 100, dtype=dtype, device=device) scalar = 123.5 res_add = torch.add(a, -scalar) res_csub = a.clone() res_csub.sub_(scalar) self.assertEqual(res_add, res_csub) # TODO: reconcile with minimum/maximum tests @dtypesIfCUDA(torch.half, torch.float, torch.double) @dtypesIfXPU(torch.half, torch.float, torch.double) @dtypes(torch.float, torch.double) def test_min_max_binary_op_nan(self, device, dtype): a = torch.rand(1000, dtype=dtype, device=device) b = torch.rand(1000, dtype=dtype, device=device) # 0:250: a -- nan, b -- not nan a[:250] = float("nan") # 250:500: a -- not nan, b -- nan b[250:500] = float("nan") # 500:750: a and b both nan a[500:750] = float("nan") b[500:750] = float("nan") # 750:1000: neither nan ma = torch.max(a, b) mi = torch.min(a, b) for i in range(750): self.assertTrue( torch.isnan(ma[i]), f"max(a, b): {ma[i]}, a: {a[i]}, b: {b[i]}", ) self.assertTrue( torch.isnan(mi[i]), f"min(a, b): {mi[i]}, a: {a[i]}, b: {b[i]}", ) for i in range(750, 1000): self.assertFalse( torch.isnan(ma[i]), f"max(a, b): {ma[i]}, a: {a[i]}, b: {b[i]}", ) self.assertFalse( torch.isnan(mi[i]), f"min(a, b): {mi[i]}, a: {a[i]}, b: {b[i]}", ) @dtypes( *product( all_types_and(torch.half, torch.bfloat16, torch.bool), all_types_and(torch.half, torch.bfloat16, torch.bool), ) ) def test_copysign(self, device, dtypes): def _test_copysign_numpy(a, b): torch_result = torch.copysign(a, b) if a.dtype == torch.bfloat16: np_a = a.to(torch.float).cpu().numpy() else: np_a = a.cpu().numpy() if b.dtype == torch.bfloat16: np_b = b.to(torch.float).cpu().numpy() else: np_b = b.cpu().numpy() expected = torch.from_numpy(np.copysign(np_a, np_b)) # To handle inconsistencies of type promotion between PyTorch and Numpy # Applied for both arguments having integral precision and bfloat16 types = integral_types_and(torch.bool, torch.bfloat16) if a.dtype in types or b.dtype in types: promoted_type = torch.promote_types(torch_result.dtype, expected.dtype) torch_result = torch_result.to(promoted_type) expected = expected.to(promoted_type) # Verify Value self.assertEqual(torch_result, expected) # Verify Sign # Use double copysign to verify the correctness of 0.0 and -0.0, since # it always True for self.assertEqual(0.0 == -0.0). So, we use 1 as the # magnitude to verify the sign between torch and numpy results, elementwise. # Special case: NaN conversions between FP32 and FP16 is not bitwise # equivalent to pass this assertion. if a.dtype != torch.float16 and b.dtype != torch.float16: self.assertEqual( torch.copysign(torch.tensor(1.0), torch_result), torch.copysign(torch.tensor(1.0), expected), ) # Compare Result with NumPy # Type promotion a = make_tensor((10, 10), device=device, dtype=dtypes[0], low=-9, high=9) b = make_tensor((10, 10), device=device, dtype=dtypes[1], low=-9, high=9) _test_copysign_numpy(a, b) # Broadcast a = make_tensor((10, 1, 10), device=device, dtype=dtypes[0], low=-9, high=9) b = make_tensor((10, 10), device=device, dtype=dtypes[1], low=-9, high=9) _test_copysign_numpy(a, b) a = make_tensor((10, 10), device=device, dtype=dtypes[0], low=-9, high=9) b = make_tensor((10, 1, 10), device=device, dtype=dtypes[1], low=-9, high=9) _test_copysign_numpy(a, b) # 0.0/-0.0/inf/-inf/nan cases = [0.0, -0.0, float("inf"), float("-inf"), float("nan")] # torch.bfloat16 can not hold '-nan' # torch.half can not hold '-nan' on CUDA types = [torch.float32, torch.float64] if device == "cpu": types.append(torch.float16) if dtypes[0] in types: b = make_tensor((10, 10), device=device, dtype=dtypes[1], low=-9, high=9) for case in cases: _test_copysign_numpy( torch.tensor([case], device=device, dtype=dtypes[0]), b ) if dtypes[1] in floating_types_and(torch.half, torch.bfloat16): a = make_tensor((10, 10), device=device, dtype=dtypes[0], low=-9, high=9) for case in cases: _test_copysign_numpy( a, torch.tensor([case], device=device, dtype=dtypes[1]) ) @dtypes( *product( floating_types_and(torch.half, torch.bfloat16), floating_types_and(torch.half, torch.bfloat16), ) ) def test_copysign_subgradient(self, device, dtypes): # Input is 0.0 x = torch.tensor( [0.0, 0.0, 0.0], dtype=dtypes[0], device=device, requires_grad=True ) y = torch.tensor( [-1.0, 0.0, 1.0], dtype=dtypes[1], device=device, requires_grad=True ) out = torch.copysign(x, y) out.sum().backward() self.assertEqual(x.grad.tolist(), [0.0, 0.0, 0.0]) self.assertEqual(y.grad.tolist(), [0.0] * 3) # Input is -0.0 x = torch.tensor( [-0.0, -0.0, -0.0], dtype=dtypes[0], device=device, requires_grad=True ) y = torch.tensor( [-1.0, 0.0, 1.0], dtype=dtypes[1], device=device, requires_grad=True ) out = torch.copysign(x, y) out.sum().backward() self.assertEqual(x.grad.tolist(), [0.0, 0.0, 0.0]) self.assertEqual(y.grad.tolist(), [0.0] * 3) # Other is 0.0 x = torch.tensor( [-1.0, 0.0, 1.0], dtype=dtypes[0], device=device, requires_grad=True ) y = torch.tensor( [0.0, 0.0, 0.0], dtype=dtypes[1], device=device, requires_grad=True ) out = torch.copysign(x, y) out.sum().backward() self.assertEqual(x.grad.tolist(), [-1.0, 0.0, 1.0]) self.assertEqual(y.grad.tolist(), [0.0] * 3) # Other is -0.0 x = torch.tensor( [-1.0, 0.0, 1.0], dtype=dtypes[0], device=device, requires_grad=True ) y = torch.tensor( [-0.0, -0.0, -0.0], dtype=dtypes[1], device=device, requires_grad=True ) out = torch.copysign(x, y) out.sum().backward() self.assertEqual(x.grad.tolist(), [1.0, 0.0, -1.0]) self.assertEqual(y.grad.tolist(), [0.0] * 3) @dtypes(torch.bfloat16, torch.float) def test_div(self, device, dtype): for op, method, inplace in ( (torch.div, torch.Tensor.div, torch.Tensor.div_), (torch.true_divide, torch.Tensor.true_divide, torch.Tensor.true_divide_), ): m1 = torch.randn(10, 10, dtype=torch.float, device=device).to(dtype=dtype) res1 = m1.clone() inplace(res1[:, 3], 2) res2 = m1.clone() for i in range(m1.size(0)): res2[i, 3] = res2[i, 3] / 2 self.assertEqual(res1, res2) if dtype == torch.bfloat16: a1 = torch.tensor([4.2, 6.2], dtype=dtype, device=device) a2 = torch.tensor([2.0, 2.0], dtype=dtype, device=device) self.assertEqual( op(a1, a2), torch.tensor([2.1, 3.1], dtype=dtype, device=device), atol=0.01, rtol=0, ) self.assertEqual(method(a1, a2), op(a1, a2)) @dtypes(torch.bfloat16, torch.float) def test_true_divide_out(self, device, dtype): a1 = torch.tensor([4.2, 6.2], dtype=dtype, device=device) a2 = torch.tensor([2.0, 2.0], dtype=dtype, device=device) res = torch.empty_like(a1) self.assertEqual( torch.true_divide(a1, a2, out=res), torch.tensor([2.1, 3.1], dtype=dtype, device=device), atol=0.01, rtol=0, ) @dtypes(torch.half) def test_divmul_scalar(self, device, dtype): x = torch.tensor(100.0, device=device, dtype=dtype) x_ref = x.float() scale = 1e5 res = x.div(scale) expected = x_ref.div(scale) self.assertEqual(res, expected.to(dtype), atol=0.0, rtol=0.0) x = torch.tensor(1e-5, device=device, dtype=dtype) x_ref = x.float() res = x.mul(scale) expected = x_ref.mul(scale) self.assertEqual(res, expected.to(dtype), atol=0.0, rtol=0.0) res = scale * x self.assertEqual(res, expected.to(dtype), atol=0.0, rtol=0.0) @dtypesIfCUDA( *set(get_all_math_dtypes("cuda")) - {torch.complex64, torch.complex128} ) @dtypesIfXPU(*set(get_all_math_dtypes("xpu")) - {torch.complex64, torch.complex128}) @dtypes(*set(get_all_math_dtypes("cpu")) - {torch.complex64, torch.complex128}) def test_floor_divide_tensor(self, device, dtype): x = torch.randn(10, device=device).mul(30).to(dtype) y = torch.arange(1, 11, dtype=dtype, device=device) z = x // y z_alt = torch.floor(x.double() / y.double()).to(dtype) self.assertEqual(z.dtype, x.dtype) self.assertEqual(z, z_alt) @dtypesIfCUDA( *set(get_all_math_dtypes("cuda")) - {torch.complex64, torch.complex128} ) @dtypesIfXPU(*set(get_all_math_dtypes("xpu")) - {torch.complex64, torch.complex128}) @dtypes(*set(get_all_math_dtypes("cpu")) - {torch.complex64, torch.complex128}) def test_floor_divide_scalar(self, device, dtype): x = torch.randn(100, device=device).mul(10).to(dtype) z = x // 3 z_alt = torch.tensor( [math.floor(v.item() / 3.0) for v in x], dtype=x.dtype, device=device ) self.assertEqual(z.dtype, x.dtype) self.assertEqual(z, z_alt) @onlyCPU @dtypes(*get_all_math_dtypes("cpu")) def test_rdiv(self, device, dtype): if dtype is torch.float16: return elif dtype.is_complex: x = torch.rand(100, dtype=dtype, device=device).add(1).mul(4) else: x = torch.rand(100, device=device).add(1).mul(4).to(dtype) y = 30 / x z = torch.tensor([30 / v.item() for v in x], device=device) self.assertEqual(y, z, exact_dtype=False) @dtypes(*floating_types_and(torch.half)) def test_fmod_remainder_by_zero_float(self, device, dtype): fn_list = (torch.fmod, torch.remainder) for fn in fn_list: # check floating-point tensor fmod/remainder to zero is nan on both CPU and GPU x = make_tensor((10, 10), device=device, dtype=dtype, low=-9, high=9) zero = torch.zeros_like(x) self.assertTrue(torch.all(fn(x, 0.0).isnan())) self.assertTrue(torch.all(fn(x, zero).isnan())) @onlyNativeDeviceTypes # Check Issue https://github.com/pytorch/pytorch/issues/48130 @dtypes(*integral_types()) @dtypesIfXPU(*set(integral_types()) - {torch.int64}) def test_fmod_remainder_by_zero_integral(self, device, dtype): fn_list = (torch.fmod, torch.remainder) for fn in fn_list: # check integral tensor fmod/remainder to zero x = make_tensor((10, 10), device=device, dtype=dtype, low=-9, high=9) zero = torch.zeros_like(x) # RuntimeError on CPU if self.device_type == "cpu": with self.assertRaisesRegex(RuntimeError, "ZeroDivisionError"): fn(x, zero) elif torch.version.hip is not None: # ROCm behavior: x % 0 is a no-op; x is returned self.assertEqual(fn(x, zero), x) else: # CUDA behavior: Different value for different dtype # Due to it's an undefined behavior, CUDA returns a pattern of all 1s # for integral dividend (other than int64) divided by zero. For int64, # CUDA returns all 1s for negative dividend, half 1s for positive dividend. # uint8: 0xff -> 255 # int32: 0xffffffff -> -1 if dtype == torch.int64: self.assertEqual(fn(x, zero) == 4294967295, x >= 0) self.assertEqual(fn(x, zero) == -1, x < 0) else: value = 255 if dtype == torch.uint8 else -1 self.assertTrue(torch.all(fn(x, zero) == value)) @onlyNativeDeviceTypes @dtypes(*integral_types()) def test_fmod_remainder_overflow(self, device, dtype): fn_list = (torch.fmod, torch.remainder) for fn in fn_list: if dtype in [torch.uint8, torch.uint16, torch.uint32, torch.uint64]: continue min_val = torch.iinfo(dtype).min dividend = torch.full((2, 3), min_val, dtype=dtype, device=device) divisor = torch.full((3,), -1, dtype=dtype, device=device) result = fn(dividend, divisor) expected = torch.zeros_like(dividend) self.assertEqual(result, expected) result_scalar = fn(dividend, -1) self.assertEqual(result_scalar, expected) @dtypes(*all_types_and(torch.half)) def test_fmod_remainder(self, device, dtype): # Use numpy as reference def _helper(x, mod, fns_list): for fn, inplace_fn, ref_fn in fns_list: np_x = x.cpu().numpy() if torch.is_tensor(x) else x np_mod = mod.cpu().numpy() if torch.is_tensor(mod) else mod exp = ref_fn(np_x, np_mod) exp = torch.from_numpy(exp) res = fn(x, mod) self.assertEqual(res, exp, exact_dtype=False) if torch.is_tensor(x): # out out = torch.empty(0, device=device, dtype=res.dtype) fn(x, mod, out=out) self.assertEqual(out, exp, exact_dtype=False) self.assertEqual(out.size(), torch.Size([10, 10])) # in-place (Type cast runtime error) try: inplace_fn(x, mod) self.assertEqual(x, exp, exact_dtype=False) except RuntimeError as e: self.assertRegex( str(e), "result type (Half|Float|Double) " "can't be cast to the desired output " "type (Byte|Char|Short|Int|Long)", ) x = make_tensor((10, 10), device=device, dtype=dtype, low=-9, high=9) # mod with same dtype as x mod = make_tensor((10, 10), device=device, dtype=dtype, low=-9, high=9) # Exclude 0 mod[mod == 0] = 1 # Mods: Integer, Float, Tensor, Non-contiguous Tensor mods = [3, 2.3, mod, mod.t()] # mod with floating-point dtype if dtype in integral_types(): mod_float = make_tensor( (10, 10), device=device, dtype=torch.float, low=-9, high=9 ) mod[mod == 0] = 1 mods.append(mod_float) for dividend, mod in product([x, x.t()], mods): _helper( dividend, mod, ( (torch.fmod, torch.Tensor.fmod_, np.fmod), (torch.remainder, torch.Tensor.remainder_, np.remainder), ), ) # Tests for torch.remainder(scalar, tensor) for dividend, mod in product([5, 3.14], mods): if torch.is_tensor(mod): _helper( dividend, mod, ((torch.remainder, torch.Tensor.remainder_, np.remainder),), ) @dtypes(torch.float, torch.double) def test_remainder_fmod_large_dividend(self, device, dtype): alarge = 1e9 pi = 3.14159265358979 for avalue in [alarge, -alarge]: for bvalue in [pi, -pi]: a = torch.tensor([avalue], dtype=dtype, device=device) b = torch.tensor([bvalue], dtype=dtype, device=device) c = torch.remainder(a, b) d = torch.fmod(a, b) self.assertTrue( (b[0] > 0) == (c[0] > 0) ) # remainder has same sign as divisor self.assertTrue( (a[0] > 0) == (d[0] > 0) ) # fmod has same sign as dividend self.assertTrue( abs(c[0]) < abs(b[0]) ) # remainder is within range of divisor self.assertTrue( abs(d[0]) < abs(b[0]) ) # fmod is within range of divisor if (a[0] > 0) == (b[0] > 0): self.assertTrue(c[0] == d[0]) # remainder is same as fmod else: self.assertTrue( abs(c[0] - d[0]) == abs(b[0]) ) # differ by one divisor @dtypesIfCPU(torch.bfloat16, torch.half, torch.float32, torch.float64) @dtypes(torch.float32, torch.float64) @skipXPU def test_hypot(self, device, dtype): inputs = [ ( torch.randn(10, device=device).to(dtype), torch.randn(10, device=device).to(dtype), ), ( torch.randn((3, 3, 3), device=device).to(dtype), torch.randn((3, 3, 3), device=device).to(dtype), ), ( torch.randn((10, 1), device=device).to(dtype), torch.randn((10, 1), device=device).to(dtype).transpose(0, 1), ), ( torch.randint(100, (10,), device=device, dtype=torch.long), torch.randn(10, device=device).to(dtype), ), ] for input in inputs: actual = torch.hypot(input[0], input[1]) if dtype in [torch.bfloat16, torch.half]: expected = torch.sqrt(input[0] * input[0] + input[1] * input[1]) else: expected = np.hypot(input[0].cpu().numpy(), input[1].cpu().numpy()) self.assertEqual(actual, expected, exact_dtype=False) if torch.device(device).type in ["cuda", "xpu"]: # test using cpu scalar with cuda. x = torch.randn(10, device=device).to(dtype) y = torch.tensor(2.0).to(dtype) actual1 = torch.hypot(x, y) actual2 = torch.hypot(y, x) expected = np.hypot(x.cpu().numpy(), 2.0) self.assertTrue(actual1.device.type == device_type) self.assertTrue(actual2.device.type == device_type) self.assertEqual(actual1, expected, exact_dtype=False) self.assertEqual(actual2, expected, exact_dtype=False) @onlyNativeDeviceTypes @dtypes(torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64) def test_gcd(self, device, dtype): # Tests gcd(0, 0), gcd(0, a) cases t1 = torch.tensor([0, 10, 0], dtype=dtype, device=device) t2 = torch.tensor([0, 0, 10], dtype=dtype, device=device) actual = torch.gcd(t1, t2) expected = np.gcd([0, 10, 0], [0, 0, 10]) self.assertEqual(actual, expected, exact_dtype=False) if dtype == torch.uint8: # Test unsigned integers with potential sign issues (i.e., uint8 with value >= 128) a = torch.tensor([190, 210], device=device, dtype=dtype) b = torch.tensor([190, 220], device=device, dtype=dtype) actual = torch.gcd(a, b) expected = torch.tensor([190, 10], device=device, dtype=dtype) self.assertEqual(actual, expected) else: # Compares with NumPy a = torch.randint(-20, 20, (1024,), device=device, dtype=dtype) b = torch.randint(-20, 20, (1024,), device=device, dtype=dtype) actual = torch.gcd(a, b) expected = np.gcd(a.cpu().numpy(), b.cpu().numpy()) self.assertEqual(actual, expected) @onlyNativeDeviceTypes @dtypes(torch.int16, torch.int32, torch.int64) def test_lcm(self, device, dtype): # Tests lcm(0, 0), lcm(0, a) cases t1 = torch.tensor([0, 10, 0], dtype=dtype, device=device) t2 = torch.tensor([0, 0, 10], dtype=dtype, device=device) actual = torch.lcm(t1, t2) expected = np.lcm([0, 10, 0], [0, 0, 10]) self.assertEqual(actual, expected, exact_dtype=False) # Compares with NumPy a = torch.randint(-20, 20, (1024,), device=device, dtype=dtype) b = torch.randint(-20, 20, (1024,), device=device, dtype=dtype) actual = torch.lcm(a, b) expected = np.lcm(a.cpu().numpy(), b.cpu().numpy()) self.assertEqual(actual, expected, exact_dtype=False) @onlyNativeDeviceTypes @dtypesIfCPU(torch.float32, torch.float64, torch.float16) @dtypes(torch.float32, torch.float64) def test_nextafter(self, device, dtype): # Test special cases t1 = torch.tensor([0, 0, 10], device=device, dtype=dtype) t2 = torch.tensor([inf, -inf, 10], device=device, dtype=dtype) actual = torch.nextafter(t1, t2) expected = np.nextafter(t1.cpu().numpy(), t2.cpu().numpy()) self.assertEqual(actual, expected, atol=0, rtol=0) actual = torch.nextafter(t2, t1) expected = np.nextafter(t2.cpu().numpy(), t1.cpu().numpy()) self.assertEqual(actual, expected, atol=0, rtol=0) t1 = torch.tensor([0, nan], device=device, dtype=dtype) t2 = torch.tensor([nan, 0], device=device, dtype=dtype) self.assertTrue(torch.nextafter(t1, t2).isnan().all()) a = torch.randn(100, device=device, dtype=dtype) b = torch.randn(100, device=device, dtype=dtype) actual = torch.nextafter(a, b) expected = np.nextafter(a.cpu().numpy(), b.cpu().numpy()) self.assertEqual(actual, expected, atol=0, rtol=0) @onlyNativeDeviceTypes @dtypes(torch.bfloat16) def test_nextafter_bfloat16(self, device, dtype): nan = float("nan") inf = float("inf") cases = ( # (from, to, expected) (0, 1, 9.183549615799121e-41), (0, -1, -9.183549615799121e-41), (1, -2, 0.99609375), (1, 0, 0.99609375), (1, 2, 1.0078125), (-1, -2, -1.0078125), (-1, 0, -0.99609375), (2, -1, 1.9921875), (2, 1, 1.9921875), (20, 3000, 20.125), (20, -3000, 19.875), (3000, -20, 2992.0), (-3000, 20, -2992.0), (65536, 0, 65280.0), (65536, inf, 66048.0), (-65536, 0, -65280.0), (-65536, -inf, -66048.0), (nan, 0, nan), (0, nan, nan), (nan, nan, nan), (nan, inf, nan), (inf, nan, nan), (inf, -inf, 3.3895313892515355e38), (-inf, inf, -3.3895313892515355e38), (inf, 0, 3.3895313892515355e38), (0, inf, 9.183549615799121e-41), (-inf, 0, -3.3895313892515355e38), (0, -inf, -9.183549615799121e-41), ) for from_v, to_v, expected in cases: from_t = torch.tensor([from_v], device=device, dtype=dtype) to_t = torch.tensor([to_v], device=device, dtype=dtype) actual = torch.nextafter(from_t, to_t).item() self.assertEqual(actual, expected, atol=0, rtol=0) def _test_cop(self, torchfn, mathfn, dtype, device): def reference_implementation(res2): for i, j in iter_indices(sm1): idx1d = i * sm1.size(0) + j res2[i, j] = mathfn(sm1[i, j], sm2[idx1d]) return res2 # contiguous m1 = torch.randn(10, 10, 10, dtype=dtype, device=device) m2 = torch.randn(10, 10 * 10, dtype=dtype, device=device) sm1 = m1[4] sm2 = m2[4] res1 = torchfn(sm1, sm2.view(10, 10)) res2 = reference_implementation(res1.clone()) self.assertEqual(res1, res2) # non-contiguous m1 = torch.randn(10, 10, 10, dtype=dtype, device=device) m2 = torch.randn(10 * 10, 10 * 10, dtype=dtype, device=device) sm1 = m1[:, 4] sm2 = m2[:, 4] # view as sm1.size() sm2.set_( sm2.storage(), sm2.storage_offset(), sm1.size(), (sm2.stride()[0] * 10, sm2.stride()[0]), ) res1 = torchfn(sm1, sm2) # reference_implementation assumes 1-d sm2 sm2.set_( sm2.storage(), sm2.storage_offset(), m2[:, 4].size(), m2[:, 4].stride() ) res2 = reference_implementation(res1.clone()) self.assertEqual(res1, res2) @onlyCPU @dtypes(torch.float) def test_cdiv(self, device, dtype): self._test_cop(torch.div, operator.truediv, dtype, device) @onlyCPU @dtypes(torch.float) def test_cremainder(self, device, dtype): self._test_cop(torch.remainder, operator.mod, dtype, device) @onlyCPU @dtypes(torch.float) def test_cmul(self, device, dtype): self._test_cop(torch.mul, operator.mul, dtype, device) @onlyCPU @dtypes(torch.float) def test_cpow(self, device, dtype): self._test_cop( torch.pow, lambda x, y: nan if x < 0 else math.pow(x, y), dtype, device ) @onlyCPU @dtypes(torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64) def test_floor_divide_zero(self, device, dtype): a = torch.tensor([0, 1], dtype=dtype, device=device) b = torch.tensor([0, 1], dtype=dtype, device=device) with self.assertRaisesRegex(RuntimeError, "ZeroDivisionError"): with self.assertWarnsOnceRegex(UserWarning, "floor_divide"): a // b @dtypes(torch.int8, torch.int16, torch.int32, torch.int64) def test_floor_divide_int_min(self, device, dtype): int_min = torch.iinfo(dtype).min a = torch.tensor([int_min], dtype=dtype, device=device) b = torch.tensor([-1], dtype=dtype, device=device) result = torch.floor_divide(a, b) result_ = a // b self.assertEqual(result, a) self.assertEqual(result_, a) @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool)) def test_muldiv_scalar(self, device, dtype): x = make_tensor((10, 3), dtype=dtype, device=device, low=None, high=None) s = make_tensor((1,), dtype=dtype, device="cpu", low=None, high=None).item() y = torch.full_like(x, s) self.assertEqual(x * s, x * y) self.assertEqual(s * x, y * x) self.assertEqual(x / s, x / y) self.assertEqual(s / x, y / x) # TODO: update make_tensor to support extremal additions and remove this in favor of make_tensor def _generate_input(self, shape, dtype, device, with_extremal): if shape == (): x = torch.tensor((), dtype=dtype, device=device) else: if dtype.is_floating_point or dtype.is_complex: # work around torch.randn not being implemented for bfloat16 if dtype == torch.bfloat16: x = torch.randn(*shape, device=device) * random.randint(30, 100) x = x.to(torch.bfloat16) else: x = torch.randn( *shape, dtype=dtype, device=device ) * random.randint(30, 100) x[torch.randn(*shape) > 0.5] = 0 if with_extremal and dtype.is_floating_point: # Use extremal values x[torch.randn(*shape) > 0.5] = float("nan") x[torch.randn(*shape) > 0.5] = float("inf") x[torch.randn(*shape) > 0.5] = float("-inf") elif with_extremal and dtype.is_complex: x[torch.randn(*shape) > 0.5] = complex("nan") x[torch.randn(*shape) > 0.5] = complex("inf") x[torch.randn(*shape) > 0.5] = complex("-inf") elif dtype == torch.bool: x = torch.zeros(shape, dtype=dtype, device=device) x[torch.randn(*shape) > 0.5] = True else: x = torch.randint(15, 100, shape, dtype=dtype, device=device) return x @dtypes( *tuple( itertools.combinations_with_replacement( all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool), 2 ) ) ) def test_comparison_ops_type_promotion_and_broadcasting(self, device, dtypes): # issue #42660 # testing all combinations of broadcasting and type promotion # with a range of dtypes and input shapes, and with extremal values def compare_with_numpy_bin_op(torch_fn, np_fn, x, y, out=None): # working around the fact that numpy doesn't support bfloat16 # by letting numpy treat them as float32's x_np = x if x.dtype != torch.bfloat16 else x.to(torch.float32) y_np = ( y.cpu().numpy() if y.dtype != torch.bfloat16 else y.to(torch.float32).cpu().numpy() ) self.compare_with_numpy( lambda inp: torch_fn(inp, y, out=out) if out else torch_fn(inp, y), lambda inp: np_fn(inp, y_np, out=out) if out else np_fn(inp, y_np), x_np, ) complex_op_denylist = [ torch.lt, torch.le, torch.gt, torch.ge, ] # complex not supported input_sizes = [(1,), (10,), (10, 1), (1, 10), (4, 10), (64, 10), (12, 3)] op_pairs = [ (torch.lt, np.less), (torch.le, np.less_equal), (torch.gt, np.greater), (torch.ge, np.greater_equal), (torch.eq, np.equal), (torch.ne, np.not_equal), (torch.logical_and, np.logical_and), (torch.logical_or, np.logical_or), (torch.logical_xor, np.logical_xor), ] for size1 in input_sizes: size2 = (2,) + size1 # perform broadcasting for with_extremal in [False, True]: a = self._generate_input(size1, dtypes[0], device, with_extremal) b = self._generate_input(size2, dtypes[1], device, with_extremal) for torch_op, numpy_op in op_pairs: if ( dtypes[0].is_complex or dtypes[1].is_complex ) and torch_op in complex_op_denylist: continue # functional version of op compare_with_numpy_bin_op(torch_op, numpy_op, a, b) # functional comparison ops always return bool tensors self.assertEqual(torch_op(a, b).dtype, torch.bool) # out version of op out = torch.zeros( 1, dtype=torch.complex128 ) # all casts to complex128 are safe compare_with_numpy_bin_op(torch_op, numpy_op, a, b, out=out) @onlyNativeDeviceTypes @dtypes(torch.int8, torch.int16, torch.int32, torch.int64) def test_signed_shift(self, device, dtype): "Ensure that signed integer bit shifting works as expected." a = torch.tensor([-10, 10], device=device, dtype=dtype) # [11...1110110, 1010] expected_l = torch.tensor( [-40, 40], device=device, dtype=dtype ) # [11...11011000, 101000] self.assertEqual(a << 2, expected_l) self.compare_with_numpy(lambda x: x << 2, lambda x: np.left_shift(x, 2), a) expected_r = torch.tensor( [-5, 5], device=device, dtype=dtype ) # [1111...111011, 101] self.assertEqual(a >> 1, expected_r) self.compare_with_numpy(lambda x: x >> 1, lambda x: np.right_shift(x, 1), a) @onlyNativeDeviceTypes @dtypes(*get_all_int_dtypes()) def test_shift_limits(self, device, dtype): "Ensure that integer bit shifting works as expected with out-of-limits shift values." # Issue #70904 iinfo = torch.iinfo(dtype) bits = iinfo.bits low = iinfo.min high = iinfo.max exact_dtype = ( dtype != torch.uint8 ) # numpy changes dtype from uint8 to int16 for some out-of-limits shift values for input in ( torch.tensor( [-1, 0, 1], device=device, dtype=dtype ), # small for non-vectorized operation torch.tensor( [low, high], device=device, dtype=dtype ), # small for non-vectorized operation make_tensor( (64, 64, 64), low=low, high=high, device=device, dtype=dtype ), # large for vectorized operation ): shift_left_expected = torch.zeros_like(input) shift_right_expected = torch.clamp(input, -1, 0) # NumPy 2 does not support negative shift values. if np.__version__ > "2": iterator = range(bits, 100) else: iterator = chain(range(-100, -1), range(bits, 100)) for shift in iterator: shift_left = input << shift self.assertEqual(shift_left, shift_left_expected, msg=f"<< {shift}") self.compare_with_numpy( lambda x: x << shift, lambda x: np.left_shift(x, shift), input, exact_dtype=exact_dtype, msg=f"<< {shift}", ) shift_right = input >> shift self.assertEqual(shift_right, shift_right_expected, msg=f">> {shift}") self.compare_with_numpy( lambda x: x >> shift, lambda x: np.right_shift(x, shift), input, exact_dtype=exact_dtype, msg=f">> {shift}", ) @onlyNativeDeviceTypes @dtypes( *list( product( all_types_and(torch.half, torch.bfloat16, torch.bool), all_types_and(torch.half, torch.bfloat16, torch.bool), ) ) ) def test_heaviside(self, device, dtypes): input_dtype = dtypes[0] values_dtype = dtypes[1] rng = np.random.default_rng() input = np.array( rng.integers(-10, 10, size=10), dtype=torch_to_numpy_dtype_dict[ input_dtype if (input_dtype != torch.bfloat16) else torch.float64 ], ) input[0] = input[3] = input[7] = 0 values = np.array( rng.integers(-10, 10, size=10), dtype=torch_to_numpy_dtype_dict[ values_dtype if (values_dtype != torch.bfloat16) else torch.float64 ], ) np_result = torch.from_numpy(np.heaviside(input, values)).to( device=device, dtype=input_dtype ) input = torch.from_numpy(input).to(device=device, dtype=input_dtype) values = torch.from_numpy(values).to(device=device, dtype=values_dtype) out = torch.empty_like(input) if input_dtype == values_dtype: torch_result = torch.heaviside(input, values) self.assertEqual(np_result, torch_result) torch_result = input.heaviside(values) self.assertEqual(np_result, torch_result) torch.heaviside(input, values, out=out) self.assertEqual(np_result, out) input.heaviside_(values) self.assertEqual(np_result, input) else: with self.assertRaisesRegex( RuntimeError, "heaviside is not yet implemented for tensors with different dtypes.", ): torch.heaviside(input, values) with self.assertRaisesRegex( RuntimeError, "heaviside is not yet implemented for tensors with different dtypes.", ): input.heaviside(values) with self.assertRaisesRegex( RuntimeError, "heaviside is not yet implemented for tensors with different dtypes.", ): torch.heaviside(input, values, out=out) with self.assertRaisesRegex( RuntimeError, "heaviside is not yet implemented for tensors with different dtypes.", ): input.heaviside_(values) @onlyOn(["cuda", "xpu"]) def test_heaviside_cross_device(self, device): x = torch.tensor([-9, 5, 0, 6, -2, 2], device=device) y = torch.tensor(0) result = torch.heaviside(x, y) expect = torch.tensor([0, 1, 0, 1, 0, 1], device=device) self.assertEqual(result, expect) result = torch.heaviside(y, x) expect = torch.tensor([-9, 5, 0, 6, -2, 2], device=device) self.assertEqual(result, expect) x = torch.tensor([-9, 5, 0, 6, -2, 2]) y = torch.tensor(0, device=device) with self.assertRaisesRegex( RuntimeError, "Expected all tensors to be on the same device" ): torch.heaviside(x, y) with self.assertRaisesRegex( RuntimeError, "Expected all tensors to be on the same device" ): torch.heaviside(y, x) @dtypes(*list(product(complex_types(), complex_types()))) def test_heaviside_complex(self, device, dtypes): input_dtype = dtypes[0] values_dtype = dtypes[1] data = (complex(0, -6), complex(-1, 3), complex(1, 1)) input = torch.tensor(data, device=device, dtype=input_dtype) values = torch.tensor(data, device=device, dtype=values_dtype) out = torch.empty_like(input) real = input.real with self.assertRaisesRegex( RuntimeError, "heaviside is not yet implemented for complex tensors." ): torch.heaviside(input, real) with self.assertRaisesRegex( RuntimeError, "heaviside is not yet implemented for complex tensors." ): real.heaviside(values) with self.assertRaisesRegex( RuntimeError, "heaviside is not yet implemented for complex tensors." ): input.heaviside_(values) with self.assertRaisesRegex( RuntimeError, "heaviside is not yet implemented for complex tensors." ): torch.heaviside(real, real, out=out) def _test_logical(self, device, dtypes, op, a_, b_, expected_res_): expected_res = torch.tensor(expected_res_, dtype=dtypes[0], device=device) a = torch.tensor(a_, dtype=dtypes[0], device=device) b = torch.tensor(b_, dtype=dtypes[1], device=device) # new tensor self.assertEqual(expected_res.bool(), getattr(a, op)(b)) # out c = torch.empty(0, dtype=torch.bool, device=device) getattr(torch, op)(a, b, out=c) self.assertEqual(expected_res.bool(), c) getattr(a, op + "_")(b) self.assertEqual(expected_res, a) @dtypes( *product( all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool), all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool), ) ) def test_logical_xor(self, device, dtypes): self._test_logical( device, dtypes, "logical_xor", [10, 0, 1, 0], [1, 0, 0, 10], [0, 0, 1, 1] ) @dtypes( *product( all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool), all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool), ) ) def test_logical_and(self, device, dtypes): self._test_logical( device, dtypes, "logical_and", [10, 0, 1, 0], [1, 0, 0, 10], [1, 0, 0, 0] ) @dtypes( *product( all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool), all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool), ) ) def test_logical_or(self, device, dtypes): self._test_logical( device, dtypes, "logical_or", [10, 0, 1, 0], [1, 0, 0, 10], [1, 0, 1, 1] ) def test_remainder_overflow(self, device): # Check Integer Overflows x = torch.tensor(23500, dtype=torch.int64, device=device) q = 392486996410368 self.assertEqual(x % q, x) self.assertEqual(-x % q, q - x) self.assertEqual(x % -q, x - q) self.assertEqual(-x % -q, -x) def test_rpow(self, device): m = torch.randn(10, 10, device=device) self.assertEqual(torch.pow(2, m), 2**m) # test with scalar m = torch.randn(1, device=device).squeeze() if m.dim() != 0: raise AssertionError("m is intentionally a scalar") self.assertEqual(torch.pow(2, m), 2**m) @skipXPU def test_ldexp(self, device): # random values mantissas = torch.randn(64, device=device) exponents = torch.randint(-31, 31, (64,), device=device, dtype=torch.int32) # basic test np_outcome = np.ldexp(mantissas.cpu().numpy(), exponents.cpu().numpy()) pt_outcome_1 = torch.ldexp(mantissas, exponents) pt_outcome_2 = mantissas.ldexp(exponents) self.assertEqual(np_outcome, pt_outcome_1.cpu()) self.assertEqual(np_outcome, pt_outcome_2.cpu()) mantissas.ldexp_(exponents) self.assertEqual(np_outcome, mantissas.cpu()) # test bounds mantissas = torch.tensor( [float("inf"), float("-inf"), float("inf"), float("nan")], device=device ) exponents = torch.randint(0, 31, (4,), device=device, dtype=torch.int32) np_outcome = np.ldexp(mantissas.cpu().numpy(), exponents.cpu().numpy()) pt_outcome = torch.ldexp(mantissas, exponents) self.assertEqual(np_outcome, pt_outcome.cpu()) # test half dtype behavior mantissas = torch.randn(64, device=device, dtype=torch.half) exponents = torch.randint(-5, 5, (64,), device=device) self.assertEqual(torch.ldexp(mantissas, exponents).dtype, torch.half) # test half dtype bound ends (very small and very large exponents) mantissas = torch.tensor([-2, 2**-10], device=device, dtype=torch.half) exponents = torch.tensor([-25, 20], device=device) self.assertEqual( torch.ldexp(mantissas, exponents), torch.tensor([-(2**-24), 2**10], dtype=torch.half), ) # test float64 computation mantissas = torch.tensor([1], dtype=torch.float64, device=device) exponents = torch.tensor([128], dtype=torch.int64, device=device) expected = torch.pow( torch.full((1,), 2, device=device, dtype=torch.float64), 128 ) self.assertEqual(torch.ldexp(mantissas, exponents), expected) @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble) def test_lerp(self, device, dtype): start_end_weight_shapes = [(), (5,), (5, 5)] for shapes in product( start_end_weight_shapes, start_end_weight_shapes, start_end_weight_shapes ): start = torch.randn(shapes[0], device=device, dtype=dtype) end = torch.randn(shapes[1], device=device, dtype=dtype) # Tensor weights weights = [ torch.randn(shapes[2], device=device, dtype=dtype), random.random(), torch.randn([], device="cpu", dtype=dtype), ] if dtype.is_complex: weights += [complex(0, 1), complex(0.4, 1.2)] for weight in weights: actual = torch.lerp(start, end, weight) actual_method = start.lerp(end, weight) self.assertEqual(actual, actual_method) actual_out = torch.tensor(1.0, dtype=dtype, device=device) torch.lerp(start, end, weight, out=actual_out) self.assertEqual(actual, actual_out) expected = start + weight * (end - start) self.assertEqual(expected, actual) @onlyOn(["cuda", "xpu"]) @dtypes(torch.half, torch.bfloat16) def test_lerp_lowp(self, device, dtype): xvals = (0.0, -30000.0) yvals = (0.1, -20000.0) xs = [torch.full((4,), xval, device=device, dtype=dtype) for xval in xvals] ys = [torch.full((4,), yval, device=device, dtype=dtype) for yval in yvals] weights = [70000, torch.full((4,), 8, device=device, dtype=dtype)] for x, y, w in zip(xs, ys, weights): xref = x.float() yref = y.float() wref = w.float() if isinstance(w, torch.Tensor) else w actual = torch.lerp(x, y, w) expected = torch.lerp(xref, yref, wref).to(dtype) self.assertEqual(actual, expected, atol=0.0, rtol=0.0) @onlyCPU @dtypes(torch.half, torch.bfloat16) def test_lerp_lowp_cpu(self, device, dtype): xvals = (0.0, -30000.0) yvals = (0.1, -20000.0) for shape in [(4,), (20,), (3, 10, 10)]: xs = [torch.full(shape, xval, device=device, dtype=dtype) for xval in xvals] ys = [torch.full(shape, yval, device=device, dtype=dtype) for yval in yvals] weights = [70000, torch.full(shape, 8, device=device, dtype=dtype)] for x, y, w in zip(xs, ys, weights): xref = x.float() yref = y.float() wref = w.float() if isinstance(w, torch.Tensor) else w actual = torch.lerp(x, y, w) expected = torch.lerp(xref, yref, wref).to(dtype) self.assertEqual(actual, expected, atol=0.0, rtol=0.0) @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble) def test_lerp_weight_scalar_tensor_promotion(self, device, dtype): start = make_tensor((5, 5), dtype=dtype, device=device, low=1, high=100) end = make_tensor((5, 5), dtype=dtype, device=device, low=1, high=100) weight = torch.rand((), dtype=torch.float, device=device) actual = torch.lerp(start, end, weight) expected = start + weight.to(dtype) * (end - start) self.assertEqual(expected, actual) @dtypes(torch.double, torch.cfloat, torch.cdouble) def test_lerp_weight_tensor_promotion_error(self, device, dtype): start = make_tensor((5, 5), dtype=dtype, device=device, low=1, high=100) end = make_tensor((5, 5), dtype=dtype, device=device, low=1, high=100) weight = torch.rand((5, 5), dtype=torch.float, device=device) with self.assertRaisesRegex(RuntimeError, "expected dtype"): torch.lerp(start, end, weight) def _test_logaddexp(self, device, dtype, base2): if base2: ref_func = np.logaddexp2 our_func = torch.logaddexp2 elif dtype in (torch.complex32, torch.complex64, torch.complex128): # numpy has not implemented logaddexp for complex def complex_logaddexp(x1, x2): x = np.stack((x1, x2)) amax = np.amax(x, axis=0) amax[~np.isfinite(amax)] = 0 return np.log(np.sum(np.exp(x - amax), axis=0)) + np.squeeze(amax) ref_func = complex_logaddexp our_func = torch.logaddexp else: ref_func = np.logaddexp our_func = torch.logaddexp def _test_helper(a, b): if dtype == torch.bfloat16: ref = ref_func(a.cpu().float().numpy(), b.cpu().float().numpy()) v = our_func(a, b) self.assertEqual(ref, v.float(), atol=0.01, rtol=0.01) elif dtype == torch.complex32: ref = ref_func( a.cpu().to(torch.complex64).numpy(), b.cpu().to(torch.complex64).numpy(), ) v = our_func(a, b) self.assertEqual(ref, v.to(torch.complex64), atol=0.01, rtol=0.01) else: ref = ref_func(a.cpu().numpy(), b.cpu().numpy()) v = our_func(a, b) self.assertEqual(ref, v) # simple test a = torch.randn(64, 2, dtype=dtype, device=device) - 0.5 b = torch.randn(64, 2, dtype=dtype, device=device) - 0.5 _test_helper(a, b) _test_helper(a[:3], b[:3]) # large value test for numerical stability a *= 10000 b *= 10000 _test_helper(a, b) _test_helper(a[:3], b[:3]) a = torch.tensor( [float("inf"), float("-inf"), float("inf"), float("nan")], dtype=dtype, device=device, ) b = torch.tensor( [float("inf"), float("-inf"), float("-inf"), float("nan")], dtype=dtype, device=device, ) _test_helper(a, b) @skipIfTorchDynamo() # complex infs/nans differ under Dynamo/Inductor @dtypesIfCUDA( torch.float32, torch.float64, torch.bfloat16, torch.complex32, torch.complex64, torch.complex128, ) @dtypesIfXPU( torch.float32, torch.float64, torch.bfloat16, ) @dtypes( torch.float32, torch.float64, torch.bfloat16, torch.complex64, torch.complex128 ) def test_logaddexp(self, device, dtype): if sys.version_info >= (3, 12) and dtype in ( torch.complex32, torch.complex64, torch.complex128, ): return self.skipTest("complex flaky in 3.12") self._test_logaddexp(device, dtype, base2=False) @dtypes(torch.float32, torch.float64, torch.bfloat16) def test_logaddexp2(self, device, dtype): self._test_logaddexp(device, dtype, base2=True) def test_add(self, device): dtypes = floating_and_complex_types() for dtype in dtypes: # [res] torch.add([res,] tensor1, tensor2) m1 = torch.randn(100, 100, dtype=dtype, device=device) v1 = torch.randn(100, dtype=dtype, device=device) # contiguous res1 = torch.add(m1[4], v1) res2 = res1.clone().zero_() for i in range(m1.size(1)): res2[i] = m1[4, i] + v1[i] self.assertEqual(res1, res2) m1 = torch.randn(100, 100, device=device) v1 = torch.randn(100, device=device) # non-contiguous res1 = torch.add(m1[:, 4], v1) res2 = res1.clone().zero_() for i in range(m1.size(0)): res2[i] = m1[i, 4] + v1[i] self.assertEqual(res1, res2) # [res] torch.add([res,] tensor, value) m1 = torch.randn(10, 10, device=device) # contiguous res1 = m1.clone() res1[3].add_(2) res2 = m1.clone() for i in range(m1.size(1)): res2[3, i] = res2[3, i] + 2 self.assertEqual(res1, res2) # non-contiguous m1 = torch.randn(10, 10, device=device) res1 = m1.clone() res1[:, 3].add_(2) res2 = m1.clone() for i in range(m1.size(0)): res2[i, 3] = res2[i, 3] + 2 self.assertEqual(res1, res2) # inter-type m1 = torch.randn(10, 10, dtype=dtype, device=device) self.assertEqual(m1 + 3, m1 + torch.tensor(3)) self.assertEqual(3 + m1, torch.tensor(3) + m1) # contiguous + non-contiguous m1 = torch.randn(10, 10, dtype=dtype, device=device) m2 = torch.randn(10, 10, dtype=dtype, device=device).t() res = m1 + m2 self.assertTrue(res.is_contiguous()) self.assertEqual(res, m1 + m2.contiguous()) # 1d + empty m1 = torch.tensor([1.0], dtype=dtype, device=device) m2 = torch.tensor([], dtype=dtype, device=device) self.assertEqual(m1 + m2, []) # inter-type unint8 one = torch.tensor(1, dtype=torch.uint8, device=device) self.assertEqual(torch.add(one, 1), 2) self.assertEqual(torch.add(one, 1).dtype, torch.uint8) # bool m1 = torch.tensor( [True, False, False, True, False, False], dtype=torch.bool, device=device ) m2 = torch.tensor( [True, True, False, False, False, True], dtype=torch.bool, device=device ) expected = torch.tensor( [True, True, False, True, False, True], dtype=torch.bool, device=device ) self.assertEqual(m1 + m2, expected) # fused multiply add a = torch.zeros(2, 3, dtype=torch.bool, device=device) res = torch.add(a, a, alpha=0) expected = torch.zeros(2, 3, device=device).bool() self.assertEqual(res, expected) # bfloat16 m1 = torch.tensor([1.0, 2.0], dtype=torch.bfloat16) m2 = torch.tensor([3.0, 4.0], dtype=torch.bfloat16) self.assertEqual(m1 + m2, torch.tensor([4.0, 6.0], dtype=torch.bfloat16)) # different alpha types m1 = torch.tensor([2 + 3j, 4 + 5j], dtype=torch.complex64, device=device) m2 = torch.tensor([4 + 5j, 2 + 3j], dtype=torch.complex64, device=device) # add complex numbers with float alpha res = torch.add(m1, m2, alpha=0.1) expected = torch.tensor( [2.4000 + 3.5000j, 4.2000 + 5.3000j], dtype=torch.complex64, device=device ) self.assertEqual(res, expected) # add complex numbers with complex alpha res = torch.add(m1, m2, alpha=complex(0.1, 0.2)) expected = torch.tensor( [1.4000 + 4.3000j, 3.6000 + 5.7000j], dtype=torch.complex64, device=device ) self.assertEqual(res, expected) # add complex numbers with integer alpha res = torch.add(m1, m2, alpha=2) expected = torch.tensor( [10.0 + 13.0j, 8.0 + 11.0j], dtype=torch.complex64, device=device ) self.assertEqual(res, expected) # mismatched alpha m1 = torch.tensor([1], dtype=torch.int8, device=device) m2 = torch.tensor([2], dtype=torch.int8, device=device) self.assertRaisesRegex( RuntimeError, r"Boolean alpha only supported for Boolean results\.", lambda: torch.add(m1, m2, alpha=True), ) self.assertRaisesRegex( RuntimeError, r"For integral input tensors, argument alpha must not be a floating point number\.", lambda: torch.add(m1, m2, alpha=1.0), ) # mismatched alpha, float / double tensor and complex alpha msg = r"For non-complex input tensors, argument alpha must not be a complex number\." m1 = torch.tensor([3.0, 4.0], device=device) m2 = torch.tensor([4.0, 3.0], device=device) self.assertRaisesRegex( RuntimeError, msg, lambda: torch.add(m1, m2, alpha=complex(0.1, 0.2)) ) m1 = torch.tensor([3.0, 4.0], dtype=torch.double, device=device) m2 = torch.tensor([4.0, 3.0], dtype=torch.double, device=device) self.assertRaisesRegex( RuntimeError, msg, lambda: torch.add(m1, m2, alpha=complex(0.1, 0.2)) ) # complex m1 = torch.tensor((4.0000 + 4.0000j), dtype=torch.complex64) m2 = torch.tensor(4.0, dtype=torch.float64) self.assertRaisesRegex( RuntimeError, r"result type ComplexFloat can't be cast to the desired output type Double", lambda: torch.add(m1, m1, out=m2), ) @onlyOn(["cuda", "xpu"]) def test_addsub_half_tensor(self, device): x = torch.tensor([60000.0], dtype=torch.half, device=device) for op, y, alpha in ( (torch.add, torch.tensor([-60000.0], dtype=torch.half, device=device), 2), (torch.sub, torch.tensor([60000.0], dtype=torch.half, device=device), 2), (torch.add, -70000.0, 1), (torch.sub, 70000.0, 1), ): actual = op(x, y, alpha=alpha) self.assertTrue(not (actual.isnan() or actual.isinf())) def test_sub_typing(self, device): m1 = torch.tensor( [True, False, False, True, False, False], dtype=torch.bool, device=device ) m2 = torch.tensor( [True, True, False, False, False, True], dtype=torch.bool, device=device ) self.assertRaisesRegex( RuntimeError, r"Subtraction, the `\-` operator, with two bool tensors is not supported. " r"Use the `\^` or `logical_xor\(\)` operator instead.", lambda: m1 - m2, ) self.assertRaisesRegex( RuntimeError, r"Subtraction, the `\-` operator, with a bool tensor is not supported. " r"If you are trying to invert a mask, use the `\~` or `logical_not\(\)` operator instead.", lambda: 1 - m1, ) self.assertRaisesRegex( RuntimeError, r"Subtraction, the `\-` operator, with a bool tensor is not supported. " r"If you are trying to invert a mask, use the `\~` or `logical_not\(\)` operator instead.", lambda: m2 - 1, ) # mismatched alpha m1 = torch.tensor([1], dtype=torch.int8, device=device) m2 = torch.tensor([2], dtype=torch.int8, device=device) self.assertRaisesRegex( RuntimeError, r"Boolean alpha only supported for Boolean results\.", lambda: torch.sub(m1, m2, alpha=True), ) self.assertRaisesRegex( RuntimeError, r"For integral input tensors, argument alpha must not be a floating point number\.", lambda: torch.sub(m1, m2, alpha=1.0), ) def test_mul(self, device): m1 = torch.randn(10, 10, device=device) res1 = m1.clone() res1[:, 3].mul_(2) res2 = m1.clone() for i in range(res1.size(0)): res2[i, 3] = res2[i, 3] * 2 self.assertEqual(res1, res2) a1 = torch.tensor([True, False, False, True], dtype=torch.bool, device=device) a2 = torch.tensor([True, False, True, False], dtype=torch.bool, device=device) self.assertEqual( a1 * a2, torch.tensor([True, False, False, False], dtype=torch.bool, device=device), ) if device == "cpu": a1 = torch.tensor([0.1, 0.1], dtype=torch.bfloat16, device=device) a2 = torch.tensor([1.1, 0.1], dtype=torch.bfloat16, device=device) self.assertEqual( a1 * a2, torch.tensor([0.11, 0.01], dtype=torch.bfloat16, device=device), atol=0.01, rtol=0, ) self.assertEqual(a1.mul(a2), a1 * a2) def test_bool_tensor_comparison_ops(self, device): a = torch.tensor( [True, False, True, False, True, False], dtype=torch.bool, device=device ) b = torch.tensor( [True, False, True, True, True, True], dtype=torch.bool, device=device ) self.assertEqual( a == b, torch.tensor([1, 1, 1, 0, 1, 0], dtype=torch.bool, device=device) ) self.assertEqual( a != b, torch.tensor([0, 0, 0, 1, 0, 1], dtype=torch.bool, device=device) ) self.assertEqual( a < b, torch.tensor([0, 0, 0, 1, 0, 1], dtype=torch.bool, device=device) ) self.assertEqual( a > b, torch.tensor([0, 0, 0, 0, 0, 0], dtype=torch.bool, device=device) ) self.assertEqual( a >= b, torch.tensor([1, 1, 1, 0, 1, 0], dtype=torch.bool, device=device) ) self.assertEqual( a <= b, torch.tensor([1, 1, 1, 1, 1, 1], dtype=torch.bool, device=device) ) self.assertEqual( a > False, torch.tensor([1, 0, 1, 0, 1, 0], dtype=torch.bool, device=device) ) self.assertEqual( a == torch.tensor(True, dtype=torch.bool, device=device), torch.tensor([1, 0, 1, 0, 1, 0], dtype=torch.bool, device=device), ) self.assertEqual( a == torch.tensor(0, dtype=torch.bool, device=device), torch.tensor([0, 1, 0, 1, 0, 1], dtype=torch.bool, device=device), ) self.assertFalse(a.equal(b)) @dtypes(*all_types_and(torch.half, torch.bfloat16, torch.bool)) def test_logical(self, device, dtype): if dtype != torch.bool: x = torch.tensor([1, 2, 3, 4], device=device, dtype=dtype) b = torch.tensor([2], device=device, dtype=dtype) self.assertEqual(x.lt(2), torch.tensor([True, False, False, False])) self.assertEqual(x.le(2), torch.tensor([True, True, False, False])) self.assertEqual(x.ge(2), torch.tensor([False, True, True, True])) self.assertEqual(x.gt(2), torch.tensor([False, False, True, True])) self.assertEqual(x.eq(2), torch.tensor([False, True, False, False])) self.assertEqual(x.ne(2), torch.tensor([True, False, True, True])) self.assertEqual(x.lt(b), torch.tensor([True, False, False, False])) self.assertEqual(x.le(b), torch.tensor([True, True, False, False])) self.assertEqual(x.ge(b), torch.tensor([False, True, True, True])) self.assertEqual(x.gt(b), torch.tensor([False, False, True, True])) self.assertEqual(x.eq(b), torch.tensor([False, True, False, False])) self.assertEqual(x.ne(b), torch.tensor([True, False, True, True])) else: x = torch.tensor([True, False, True, False], device=device) self.assertEqual(x.lt(True), torch.tensor([False, True, False, True])) self.assertEqual(x.le(True), torch.tensor([True, True, True, True])) self.assertEqual(x.ge(True), torch.tensor([True, False, True, False])) self.assertEqual(x.gt(True), torch.tensor([False, False, False, False])) self.assertEqual(x.eq(True), torch.tensor([True, False, True, False])) self.assertEqual(x.ne(True), torch.tensor([False, True, False, True])) def test_atan2(self, device): def _test_atan2_with_size(size, device): a = torch.rand(size=size, device=device, dtype=torch.double) b = torch.rand(size=size, device=device, dtype=torch.double) actual = a.atan2(b) x = a.view(-1) y = b.view(-1) expected = torch.tensor( [math.atan2(x[i].item(), y[i].item()) for i in range(x.numel())], device=device, dtype=torch.double, ) self.assertEqual(expected, actual.view(-1), rtol=0, atol=0.02) # bfloat16/float16 for lowp_dtype in [torch.bfloat16, torch.float16]: if lowp_dtype == torch.bfloat16: rtol = 0 atol = 0.02 else: rtol = 0 atol = 0.001 a_16 = a.to(dtype=lowp_dtype) b_16 = b.to(dtype=lowp_dtype) actual_16 = a_16.atan2(b_16) self.assertEqual(actual_16, actual.to(dtype=lowp_dtype)) self.assertEqual( expected, actual_16.view(-1), exact_dtype=False, rtol=rtol, atol=atol, ) _test_atan2_with_size((2, 2), device) _test_atan2_with_size((3, 3), device) _test_atan2_with_size((5, 5), device) def test_atan2_edgecases(self, device): def _test_atan2(x, y, expected, device, dtype): expected_tensor = torch.tensor([expected], dtype=dtype, device=device) x_tensor = torch.tensor([x], dtype=dtype, device=device) y_tensor = torch.tensor([y], dtype=dtype, device=device) actual = torch.atan2(y_tensor, x_tensor) self.assertEqual(expected_tensor, actual, rtol=0, atol=0.02) for dtype in [torch.float, torch.double]: _test_atan2(0, 0, 0, device, dtype) _test_atan2(0, 1, math.pi / 2, device, dtype) _test_atan2(0, -1, math.pi / -2, device, dtype) _test_atan2(-1, 0, math.pi, device, dtype) _test_atan2(1, 0, 0, device, dtype) _test_atan2(-1, -1, math.pi * -3 / 4, device, dtype) _test_atan2(1, 1, math.pi / 4, device, dtype) _test_atan2(1, -1, math.pi / -4, device, dtype) _test_atan2(-1, 1, math.pi * 3 / 4, device, dtype) def test_trapezoid(self, device): def test_dx(sizes, dim, dx, device): t = torch.randn(sizes, device=device) actual = torch.trapezoid(t, dx=dx, dim=dim) if int(np.__version__.split(".")[0]) >= 2: expected = np.trapezoid(t.cpu().numpy(), dx=dx, axis=dim) # noqa: NPY201 else: expected = np.trapz(t.cpu().numpy(), dx=dx, axis=dim) # noqa: NPY201 self.assertEqual(expected.shape, actual.shape) self.assertEqual(expected, actual, exact_dtype=False) def test_x(sizes, dim, x, device): t = torch.randn(sizes, device=device) actual = torch.trapezoid(t, x=torch.tensor(x, device=device), dim=dim) if int(np.__version__.split(".")[0]) >= 2: expected = np.trapezoid(t.cpu().numpy(), x=x, axis=dim) # noqa: NPY201 else: expected = np.trapz(t.cpu().numpy(), x=x, axis=dim) # noqa: NPY201 self.assertEqual(expected.shape, actual.shape) self.assertEqual(expected, actual.cpu(), exact_dtype=False) test_dx((2, 3, 4), 1, 1, device) test_dx((10, 2), 0, 0.1, device) test_dx((1, 10), 0, 2.3, device) test_dx((0, 2), 0, 1.0, device) test_dx((0, 2), 1, 1.0, device) test_x((2, 3, 4), 1, [1.0, 2.0, 3.0], device) test_x( (10, 2), 0, [2.0, 3.0, 4.0, 7.0, 11.0, 14.0, 22.0, 26.0, 26.1, 30.3], device ) test_x((1, 10), 0, [1.0], device) test_x((0, 2), 0, [], device) test_x((0, 2), 1, [1.0, 2.0], device) test_x((2, 3, 4), -1, [1.0, 2.0, 3.0, 4.0], device) test_x((2, 3, 4), 0, [1.0, 2.0], device) test_x((2, 3, 4), 1, [1.0, 2.0, 3.0], device) test_x((2, 3, 4), 2, [1.0, 2.0, 3.0, 4.0], device) test_x((2, 2, 4), -1, [[1.0, 2.0, 3.0, 4.0], [1.0, 2.0, 3.0, 4.0]], device) with self.assertRaisesRegex(IndexError, "Dimension out of range"): test_x((2, 3), 2, [], device) test_dx((2, 3), 2, 1.0, device) with self.assertRaisesRegex( RuntimeError, "There must be one `x` value for each sample point" ): test_x((2, 3), 1, [1.0, 2.0], device) test_x((2, 3), 1, [1.0, 2.0, 3.0, 4.0], device) @skipIf(not TEST_SCIPY, "Scipy required for the test.") def test_cumulative_trapezoid(self, device): import scipy.integrate if hasattr(scipy.integrate, "cumulative_trapezoid"): _scipy_cumulative_trapezoid = scipy.integrate.cumulative_trapezoid else: # Older version of SciPy uses a different name _scipy_cumulative_trapezoid = scipy.integrate.cumtrapz def scipy_cumulative_trapezoid(y, x=None, dx=1.0, axis=-1, initial=None): if y.shape[axis] == 0: return np.empty_like(y) else: return _scipy_cumulative_trapezoid(y, x, dx, axis, initial) def test_dx(sizes, dim, dx, device): t = torch.randn(sizes, device=device) y = t.cpu().numpy() actual = torch.cumulative_trapezoid(t, dx=dx, dim=dim) expected = scipy_cumulative_trapezoid(t.cpu().numpy(), dx=dx, axis=dim) self.assertEqual(expected.shape, actual.shape) self.assertEqual(expected, actual, exact_dtype=False, atol=1e-4, rtol=1e-4) def test_x(sizes, dim, x, device): t = torch.randn(sizes, device=device) actual = torch.cumulative_trapezoid( t, x=torch.tensor(x, device=device), dim=dim ) expected = scipy_cumulative_trapezoid(t.cpu().numpy(), x=x, axis=dim) self.assertEqual(expected.shape, actual.shape) self.assertEqual( expected, actual.cpu(), exact_dtype=False, atol=1e-4, rtol=1e-4 ) def test_empty_x(sizes, dim, x, device): t = torch.randn(sizes, device=device) actual = torch.cumulative_trapezoid( t, x=torch.tensor(x, device=device), dim=dim ) self.assertEqual(torch.empty(actual.shape), actual) test_dx((2,), -1, 1, device) test_dx((3, 3), -1, 1, device) test_dx((4, 2), 0, 1, device) test_dx((2, 3, 4), 1, 1, device) test_dx((10, 2), 0, 0.1, device) test_dx((1, 10), 0, 2.3, device) test_dx((0, 2), 0, 1.0, device) test_dx((0, 2), 1, 1.0, device) test_dx((512, 512), 1, 1.0, device) test_dx((100, 100, 100), 1, 1.0, device) test_x((2,), -1, [100, 50], device) test_x((4, 2), 0, [2, 3, 4, 5], device) test_x((2, 3, 4), 1, [1.0, 2.0, 3.0], device) test_x( (10, 2), 0, [2.0, 3.0, 4.0, 7.0, 11.0, 14.0, 22.0, 26.0, 26.1, 30.3], device ) test_x((1, 10), 0, [1.0], device) test_x((0, 2), 1, [1, 2], device) test_x((2, 3, 4), -1, [1.0, 2.0, 3.0, 4.0], device) test_x((2, 3, 4), 0, [1.0, 2.0], device) test_x((2, 3, 4), 1, [1.0, 2.0, 3.0], device) test_x((2, 3, 4), 2, [1.0, 2.0, 3.0, 4.0], device) test_empty_x( (0, 2), 0, [], device ) # SciPy failing when x == [], but our version returns empty with self.assertRaisesRegex(IndexError, "Dimension out of range"): test_x((2, 3), 2, [], device) test_dx((2, 3), 2, 1.0, device) with self.assertRaisesRegex( RuntimeError, "There must be one `x` value for each sample point" ): test_x((2, 3), 1, [1.0, 2.0], device) test_x((0, 2), 0, [1.0, 2.0], device) test_x((2, 3), 1, [1.0, 2.0, 3.0, 4.0], device) with self.assertRaisesRegex( RuntimeError, "Currently, we only support dx as a real number" ): test_dx((2, 2), -1, complex(1, 1), device) with self.assertRaisesRegex( TypeError, "received an invalid combination of arguments" ): actual = torch.cumulative_trapezoid( torch.randn((3, 3)), x=torch.randn((3, 3)), dx=3 ) @skipMeta @dtypes(torch.double) def test_pow_scalar_overloads_mem_overlap(self, device, dtype): sz = 3 doubles = torch.randn(2 * sz, dtype=dtype, device=device) self.check_internal_mem_overlap(lambda t: t.pow_(42), 1, dtype, device) self.unary_check_input_output_mem_overlap( doubles, sz, lambda input, out: torch.pow(input, 42, out=out) ) self.unary_check_input_output_mem_overlap( doubles, sz, lambda input, out: torch.pow(42, input, out=out) ) @dtypes( *list( product( all_types_and_complex_and(torch.half, torch.bfloat16), all_types_and_complex_and(torch.half, torch.bfloat16), ) ) ) def test_float_power(self, device, dtypes): def to_np(value): if isinstance(value, torch.Tensor) and value.dtype == torch.bfloat16: return value.to(torch.float).cpu().numpy() return value.cpu().numpy() if isinstance(value, torch.Tensor) else value base_dtype = dtypes[0] exp_dtype = dtypes[1] out_dtype = ( torch.complex128 if base_dtype.is_complex or exp_dtype.is_complex else torch.float64 ) base = make_tensor((30,), dtype=base_dtype, device=device, low=1, high=100) # Complex and real results do not agree between PyTorch and NumPy when computing negative and zero power of 0 # Related: https://github.com/pytorch/pytorch/issues/48000 # base[0] = base[3] = base[7] = 0 exp = make_tensor((30,), dtype=exp_dtype, device=device, low=-2, high=2) exp[0] = exp[4] = exp[6] = 0 expected = torch.from_numpy(np.float_power(to_np(base), to_np(exp))) exponents = [-2.8, -2, -1, -0.5, 0.5, 1, 2] complex_exponents = exponents + [ -2.5j, -1.0j, 1.0j, 2.5j, 1.0 + 1.0j, -1.0 - 1.5j, 3.3j, ] for op in ( torch.float_power, torch.Tensor.float_power, torch.Tensor.float_power_, ): # Case of Tensor x Tensor if op is torch.Tensor.float_power_ and base_dtype != out_dtype: with self.assertRaisesRegex( RuntimeError, "operation's result requires dtype" ): op(base.clone(), exp) else: result = op(base.clone(), exp) self.assertEqual(expected, result) if op is torch.float_power: out = torch.empty_like(base).to(device=device, dtype=out_dtype) op(base, exp, out=out) self.assertEqual(expected, out) # Case of Tensor x Scalar for i in complex_exponents if exp_dtype.is_complex else exponents: out_dtype_scalar_exp = ( torch.complex128 if base_dtype.is_complex or type(i) is complex else torch.float64 ) expected_scalar_exp = torch.from_numpy(np.float_power(to_np(base), i)) if ( op is torch.Tensor.float_power_ and base_dtype != out_dtype_scalar_exp ): with self.assertRaisesRegex( RuntimeError, "operation's result requires dtype" ): op(base.clone(), i) else: result = op(base.clone(), i) self.assertEqual(expected_scalar_exp, result) if op is torch.float_power: out = torch.empty_like(base).to( device=device, dtype=out_dtype_scalar_exp ) op(base, i, out=out) self.assertEqual(expected_scalar_exp, out) # Case of Scalar x Tensor for i in complex_exponents if base_dtype.is_complex else exponents: out_dtype_scalar_base = ( torch.complex128 if exp_dtype.is_complex or type(i) is complex else torch.float64 ) expected_scalar_base = torch.from_numpy(np.float_power(i, to_np(exp))) result = torch.float_power(i, exp) self.assertEqual(expected_scalar_base, result) out = torch.empty_like(exp).to(device=device, dtype=out_dtype_scalar_base) torch.float_power(i, exp, out=out) self.assertEqual(expected_scalar_base, out) def test_float_power_exceptions(self, device): def _promo_helper(x, y): for i in (x, y): if type(i) is complex: return torch.complex128 elif type(i) is torch.Tensor and i.is_complex(): return torch.complex128 return torch.double test_cases = ( (torch.tensor([-2, -1, 0, 1, 2], device=device), -0.25), ( torch.tensor([-1.0j, 0j, 1.0j, 1.0 + 1.0j, -1.0 - 1.5j], device=device), 2.0, ), ) for base, exp in test_cases: for out_dtype in (torch.long, torch.float, torch.double, torch.cdouble): out = torch.empty(1, device=device, dtype=out_dtype) required_dtype = _promo_helper(base, exp) if out.dtype == required_dtype: torch.float_power(base, exp, out=out) else: with self.assertRaisesRegex( RuntimeError, "operation's result requires dtype" ): torch.float_power(base, exp, out=out) if base.dtype == required_dtype: torch.Tensor.float_power_(base.clone(), exp) else: with self.assertRaisesRegex( RuntimeError, "operation's result requires dtype" ): torch.Tensor.float_power_(base.clone(), exp) @skipIf(not TEST_SCIPY, "Scipy required for the test.") @dtypes( *product( all_types_and(torch.half, torch.bool), all_types_and(torch.half, torch.bool) ) ) def test_xlogy_xlog1py(self, device, dtypes): x_dtype, y_dtype = dtypes def out_variant_helper(torch_fn, x, y): expected = torch_fn(x, y) out = torch.empty_like(expected) torch_fn(x, y, out=out) self.assertEqual(expected, out) def xlogy_inplace_variant_helper(x, y): if x.dtype in integral_types_and(torch.bool): with self.assertRaisesRegex( RuntimeError, "can't be cast to the desired output type" ): x.clone().xlogy_(y) else: expected = torch.empty_like(x) torch.xlogy(x, y, out=expected) inplace_out = x.clone().xlogy_(y) self.assertEqual(expected, inplace_out) def test_helper(torch_fn, reference_fn, inputs, scalar=None): x, y, z = inputs torch_fn_partial = partial(torch_fn, x) reference_fn_partial = partial(reference_fn, x.cpu().numpy()) self.compare_with_numpy( torch_fn_partial, reference_fn_partial, x, exact_dtype=False ) self.compare_with_numpy( torch_fn_partial, reference_fn_partial, y, exact_dtype=False ) self.compare_with_numpy( torch_fn_partial, reference_fn_partial, z, exact_dtype=False ) val = scalar if scalar is not None else x out_variant_helper(torch_fn, val, x) out_variant_helper(torch_fn, val, y) out_variant_helper(torch_fn, val, z) # Tensor-Tensor Test (tensor of same and different shape) x = make_tensor((3, 2, 4, 5), dtype=x_dtype, device=device, low=0.5, high=1000) y = make_tensor((3, 2, 4, 5), dtype=y_dtype, device=device, low=0.5, high=1000) z = make_tensor((4, 5), dtype=y_dtype, device=device, low=0.5, high=1000) x_1p = make_tensor( (3, 2, 4, 5), dtype=x_dtype, device=device, low=-0.5, high=1000 ) y_1p = make_tensor( (3, 2, 4, 5), dtype=y_dtype, device=device, low=-0.5, high=1000 ) z_1p = make_tensor((4, 5), dtype=y_dtype, device=device, low=-0.5, high=1000) xlogy_fns = torch.xlogy, scipy.special.xlogy xlog1py_fns = torch.special.xlog1py, scipy.special.xlog1py test_helper(*xlogy_fns, (x, y, z)) xlogy_inplace_variant_helper(x, x) xlogy_inplace_variant_helper(x, y) xlogy_inplace_variant_helper(x, z) test_helper(*xlog1py_fns, (x_1p, y_1p, z_1p)) # Scalar-Tensor Test test_helper(*xlogy_fns, (x, y, z), 3.14) test_helper(*xlog1py_fns, (x_1p, y_1p, z_1p), 3.14) # Special Values Tensor-Tensor t = torch.tensor( [-1.0, 0.0, 1.0, 2.0, float("inf"), -float("inf"), float("nan")], device=device, ) zeros = torch.zeros(7, dtype=y_dtype, device=device) def test_zeros_special_helper(torch_fn, reference_fn, scalar=False): zeros_t = 0 if scalar else zeros zeros_np = 0 if scalar else zeros.cpu().numpy() torch_fn_partial = partial(torch_fn, zeros_t) reference_fn_partial = partial(reference_fn, zeros_np) self.compare_with_numpy( torch_fn_partial, reference_fn_partial, t, exact_dtype=False ) out_variant_helper(torch_fn, zeros_t, t) test_zeros_special_helper(*xlogy_fns) xlogy_inplace_variant_helper(zeros, t) test_zeros_special_helper(*xlog1py_fns) # Special Values Scalar-Tensor test_zeros_special_helper(*xlogy_fns, scalar=True) test_zeros_special_helper(*xlog1py_fns, scalar=True) @dtypes(torch.float64) def test_xlogy_xlog1py_gradients(self, device, dtype): make_arg = partial(torch.tensor, dtype=dtype, device=device, requires_grad=True) zeros = torch.zeros((2,), dtype=dtype, device=device) x = make_arg([0.0, 0.0]) y = make_arg([-1.5, 0.0]) torch.special.xlogy(x, y).sum().backward() self.assertEqual(x.grad, zeros) x = make_arg([0.0, 0.0]) y = make_arg([-2.5, -1.0]) torch.special.xlog1py(x, y).sum().backward() self.assertEqual(x.grad, zeros) def test_xlogy_xlog1py_scalar_type_promotion(self, device): # Test that python numbers don't participate in type promotion at the same # priority level as 0-dim tensors t = torch.randn((), dtype=torch.float32, device=device) self.assertEqual(t.dtype, torch.xlogy(t, 5).dtype) self.assertEqual(t.dtype, torch.xlogy(t, 5.0).dtype) self.assertEqual(t.dtype, torch.special.xlog1py(t, 5).dtype) self.assertEqual(t.dtype, torch.special.xlog1py(t, 5.0).dtype) self.assertEqual(t.dtype, torch.xlogy(5, t).dtype) self.assertEqual(t.dtype, torch.xlogy(5.0, t).dtype) self.assertEqual(t.dtype, torch.special.xlog1py(5, t).dtype) self.assertEqual(t.dtype, torch.special.xlog1py(5.0, t).dtype) @skipIf(not TEST_SCIPY, "Scipy required for the test.") def test_xlogy_xlog1py_bfloat16(self, device): def _compare_helper(x, y, torch_fn, reference_fn): x_np = x if isinstance(x, float) else x.cpu().to(torch.float).numpy() y_np = y if isinstance(y, float) else y.cpu().to(torch.float).numpy() expected = torch.from_numpy(reference_fn(x_np, y_np)) actual = torch_fn(x, y) self.assertEqual(expected, actual, exact_dtype=False) x_dtype, y_dtype = torch.bfloat16, torch.bfloat16 # Tensor-Tensor Test (tensor of same and different shape) x = make_tensor((3, 2, 4, 5), dtype=x_dtype, device=device, low=0.5, high=1000) y = make_tensor((3, 2, 4, 5), dtype=y_dtype, device=device, low=0.5, high=1000) z = make_tensor((4, 5), dtype=y_dtype, device=device, low=0.5, high=1000) x_1p = make_tensor( (3, 2, 4, 5), dtype=x_dtype, device=device, low=-0.8, high=1000 ) y_1p = make_tensor( (3, 2, 4, 5), dtype=y_dtype, device=device, low=-0.8, high=1000 ) z_1p = make_tensor((4, 5), dtype=y_dtype, device=device, low=-0.8, high=1000) xlogy_fns = torch.xlogy, scipy.special.xlogy xlog1py_fns = torch.special.xlog1py, scipy.special.xlog1py _compare_helper(x, x, *xlogy_fns) _compare_helper(x, y, *xlogy_fns) _compare_helper(x, z, *xlogy_fns) _compare_helper(x, 3.14, *xlogy_fns) _compare_helper(y, 3.14, *xlogy_fns) _compare_helper(z, 3.14, *xlogy_fns) _compare_helper(x_1p, x_1p, *xlog1py_fns) _compare_helper(x_1p, y_1p, *xlog1py_fns) _compare_helper(x_1p, z_1p, *xlog1py_fns) _compare_helper(x_1p, 3.14, *xlog1py_fns) _compare_helper(y_1p, 3.14, *xlog1py_fns) _compare_helper(z_1p, 3.14, *xlog1py_fns) # Special Values Tensor-Tensor t = torch.tensor( [-1.0, 0.0, 1.0, 2.0, float("inf"), -float("inf"), float("nan")], device=device, ) zeros = torch.tensor(7, dtype=y_dtype, device=device) _compare_helper(t, zeros, *xlogy_fns) _compare_helper(t, 0.0, *xlogy_fns) _compare_helper(t, zeros, *xlog1py_fns) _compare_helper(t, 0.0, *xlog1py_fns) @dtypes(*product(all_types_and(torch.bool), all_types_and(torch.bool))) @skipIf(not TEST_SCIPY, "Scipy required for the test.") @slowTest def test_zeta(self, device, dtypes): x_dtype, q_dtype = dtypes def test_helper(x, q): x_np = x if isinstance(x, float) else x.cpu().numpy() q_np = q if isinstance(q, float) else q.cpu().numpy() expected = torch.from_numpy(scipy.special.zeta(x_np, q_np)) actual = torch.special.zeta(x, q) rtol, atol = None, None if self.device_type == "cpu": rtol, atol = 1e-6, 1e-6 self.assertEqual(expected, actual, rtol=rtol, atol=atol, exact_dtype=False) # x tensor - q tensor same size x = make_tensor((2, 3, 4), dtype=x_dtype, device=device) q = make_tensor((2, 3, 4), dtype=q_dtype, device=device) test_helper(x, q) # x tensor - q tensor broadcast lhs x = make_tensor((2, 1, 4), dtype=x_dtype, device=device) q = make_tensor((2, 3, 4), dtype=q_dtype, device=device) test_helper(x, q) # x tensor - q tensor broadcast rhs x = make_tensor((2, 3, 4), dtype=x_dtype, device=device) q = make_tensor((2, 1, 4), dtype=q_dtype, device=device) test_helper(x, q) # x tensor - q tensor broadcast all x = make_tensor((2, 3, 1), dtype=x_dtype, device=device) q = make_tensor((2, 1, 4), dtype=q_dtype, device=device) test_helper(x, q) # x scalar - q tensor for x in np.linspace(-5, 5, num=10).tolist(): if not q_dtype.is_floating_point: q_dtype = torch.get_default_dtype() q = make_tensor((2, 3, 4), dtype=q_dtype, device=device) test_helper(x, q) # x tensor - q scalar for q in np.linspace(-5, 5, num=10).tolist(): if not x_dtype.is_floating_point: x_dtype = torch.get_default_dtype() x = make_tensor((2, 3, 4), dtype=x_dtype, device=device) test_helper(x, q) @onlyOn(["cuda", "xpu"]) @dtypes(torch.chalf) def test_mul_chalf_tensor_and_cpu_scalar(self, device, dtype): # Tests that Tensor and CPU Scalar work for `mul` for chalf. # Ideally, this should be covered by `test_complex_half_reference_testing` # from test_ops.py by checking reference_samples from the OpInfo. # But currently that doesn't work as sample generation requires support of # `index_select` which is not implemented for `complex32` at the # time of writing this test. # TODO: Remove this test once above issue is fixed. # Ref: https://github.com/pytorch/pytorch/pull/76364 x = make_tensor((2, 2), device=device, dtype=dtype) self.assertEqual(x * 2.5, x * torch.tensor(2.5, device=device, dtype=dtype)) tensor_binary_ops = [ "__lt__", "__le__", "__gt__", "__ge__", "__eq__", "__ne__", "__add__", "__radd__", "__iadd__", "__sub__", "__rsub__", "__isub__", "__mul__", "__rmul__", "__imul__", "__matmul__", "__rmatmul__", "__truediv__", "__rtruediv__", "__itruediv__", "__floordiv__", "__rfloordiv__", "__ifloordiv__", "__mod__", "__rmod__", "__imod__", "__pow__", "__rpow__", "__ipow__", "__lshift__", "__rlshift__", "__ilshift__", "__rshift__", "__rrshift__", "__irshift__", "__and__", "__rand__", "__iand__", "__xor__", "__rxor__", "__ixor__", "__or__", "__ror__", "__ior__", # Unsupported operators # '__imatmul__', # '__divmod__', '__rdivmod__', '__idivmod__', ] # Test that binary math operations return NotImplemented for unknown types. def generate_not_implemented_tests(cls): class UnknownType: pass # TODO: refactor to inline these _types = [ torch.half, torch.float, torch.double, torch.int8, torch.short, torch.int, torch.long, torch.uint8, ] def create_test_func(op): @dtypes(*_types) def test(self, device, dtype): # Generate the inputs tensor = torch.empty((), device=device, dtype=dtype) # Runs the tensor op on the device result = getattr(tensor, op)(UnknownType()) self.assertEqual(result, NotImplemented) return test for op in tensor_binary_ops: test_name = f"test_{op}_not_implemented" if hasattr(cls, test_name): raise AssertionError(f"{test_name} already in {cls.__name__}") setattr(cls, test_name, create_test_func(op)) generate_not_implemented_tests(TestBinaryUfuncs) instantiate_device_type_tests(TestBinaryUfuncs, globals(), allow_xpu=True) if __name__ == "__main__": run_tests()
python
github
https://github.com/pytorch/pytorch
test/test_binary_ufuncs.py
__author__ = 'srodgers' from .Dialog import * """ This file is part of chargectrl-python-buspirate. chargectrl-python-buspirate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. chargectrl-python-buspirate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with chargectrl-python-buspirate. If not, see <http://www.gnu.org/licenses/>. """ class LoadEnableDialog(Dialog): def __init__(self, parent, cc, title = None, xoffset=50, yoffset=50): self.cc = cc self.state = "NO" Dialog.__init__(self, parent=parent, title=title, xoffset=xoffset, yoffset=yoffset) # # Dialog body def body(self, master): self.legend = Label(master, text="Load Enabled", width=20) if self.cc.get_load_enable_state(): self.state = 'YES' else: self.state = 'NO' self.field = Label(master, text = self.state, relief=SUNKEN, width=3, background= 'white', foreground='black') self.legend.grid(row=0, column=0, sticky=W) self.field.grid(row=0, column=1, sticky=W) # # Buttons def buttonbox(self): box = Frame(self) self.enabutton = Button(box, text="ENABLE", width=10, command=self.enable) self.enabutton.pack(side=LEFT) self.disabutton = Button(box, text="DISABLE", width=10, command=self.disable, default=ACTIVE) self.disabutton.pack(side=LEFT) self.disabutton = Button(box, text="CLOSE", width=10, command=self.cancel) self.disabutton.pack(side=LEFT) self.bind("<Escape>", self.cancel) box.pack() # # Enable load def enable(self): self.cc.enable_load() self.state = 'YES' self.field.configure(text=self.state) # # Disable load def disable(self): self.cc.disable_load() self.state = 'NO' self.field.configure(text=self.state)
unknown
codeparrot/codeparrot-clean
//===--- OptimizerBridging.h - header for the OptimizerBridging module ----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #ifndef SWIFT_SILOPTIMIZER_OPTIMIZERBRIDGING_H #define SWIFT_SILOPTIMIZER_OPTIMIZERBRIDGING_H /// `OptimizerBridging.h` is imported into Swift. Be *very* careful with what /// you include here and keep these includes minimal! /// /// See include guidelines and caveats in `BasicBridging.h`. #include "swift/AST/ASTBridging.h" #include "swift/SIL/SILBridging.h" #include "swift/SILOptimizer/Analysis/ArrayCallKind.h" #ifndef NOT_COMPILED_WITH_SWIFT_PURE_BRIDGING_MODE // Pure bridging mode does not permit including any C++/llvm/swift headers. // See also the comments for `BRIDGING_MODE` in the top-level CMakeLists.txt file. #ifdef SWIFT_SIL_SILVALUE_H #error "should not include swift headers into bridging header" #endif #ifdef LLVM_SUPPORT_COMPILER_H #error "should not include llvm headers into bridging header" #endif #endif // #ifndef NOT_COMPILED_WITH_SWIFT_PURE_BRIDGING_MODE SWIFT_BEGIN_NULLABILITY_ANNOTATIONS namespace swift { class AliasAnalysis; class ArraySemanticsCall; class BasicCalleeAnalysis; class CalleeList; class DeadEndBlocks; class DominanceInfo; class PostDominanceInfo; class SILLoopInfo; class SILLoop; class SwiftPassInvocation; class SILVTable; } struct BridgedPassContext; struct BridgedAliasAnalysis { swift::AliasAnalysis * _Nonnull aa; // Workaround for a compiler bug. // When this unused function is removed, the compiler gives an error. BRIDGED_INLINE bool unused(BridgedValue address1, BridgedValue address2) const; typedef void (* _Nonnull InitFn)(BridgedAliasAnalysis aliasAnalysis, SwiftInt size); typedef void (* _Nonnull DestroyFn)(BridgedAliasAnalysis aliasAnalysis); typedef BridgedMemoryBehavior (* _Nonnull GetMemEffectFn)( BridgedContext context, BridgedAliasAnalysis aliasAnalysis, BridgedValue, BridgedInstruction); typedef bool (* _Nonnull Escaping2InstFn)( BridgedContext context, BridgedAliasAnalysis aliasAnalysis, BridgedValue, BridgedInstruction); typedef bool (* _Nonnull Escaping2ValIntFn)( BridgedContext context, BridgedAliasAnalysis aliasAnalysis, BridgedValue, BridgedValue); typedef bool (* _Nonnull MayAliasFn)( BridgedContext context, BridgedAliasAnalysis aliasAnalysis, BridgedValue, BridgedValue); static void registerAnalysis(InitFn initFn, DestroyFn destroyFn, GetMemEffectFn getMemEffectsFn, Escaping2InstFn isObjReleasedFn, Escaping2ValIntFn isAddrVisibleFromObjFn, MayAliasFn mayAliasFn); }; struct BridgedCalleeAnalysis { swift::BasicCalleeAnalysis * _Nonnull ca; struct CalleeList { uint64_t storage[3]; BRIDGED_INLINE CalleeList(swift::CalleeList list); BRIDGED_INLINE swift::CalleeList unbridged() const; BRIDGED_INLINE bool isIncomplete() const; BRIDGED_INLINE SwiftInt getCount() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getCallee(SwiftInt index) const; }; SWIFT_IMPORT_UNSAFE CalleeList getCallees(BridgedValue callee) const; SWIFT_IMPORT_UNSAFE CalleeList getDestructors(BridgedType type, bool isExactType) const; typedef bool (* _Nonnull IsDeinitBarrierFn)(BridgedInstruction, BridgedCalleeAnalysis bca); typedef BridgedMemoryBehavior (* _Nonnull GetMemBehvaiorFn)( BridgedInstruction apply, bool observeRetains, BridgedCalleeAnalysis bca); static void registerAnalysis(IsDeinitBarrierFn isDeinitBarrierFn, GetMemBehvaiorFn getEffectsFn); }; struct BridgedDeadEndBlocksAnalysis { swift::DeadEndBlocks * _Nonnull deb; BRIDGED_INLINE bool isDeadEnd(BridgedBasicBlock block) const; }; struct BridgedDomTree { swift::DominanceInfo * _Nonnull di; BRIDGED_INLINE bool dominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const; BRIDGED_INLINE SwiftInt getNumberOfChildren(BridgedBasicBlock bb) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock getChildAt(BridgedBasicBlock bb, SwiftInt index) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedBasicBlock getImmediateDominator(BridgedBasicBlock block) const; }; struct BridgedPostDomTree { swift::PostDominanceInfo * _Nonnull pdi; BRIDGED_INLINE bool postDominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const; }; struct BridgedOptimizerUtilities { typedef void (* _Nonnull UpdateFunctionFn)(BridgedContext, BridgedFunction); typedef void (* _Nonnull UpdateLifetimeFunctionFn)(BridgedContext, BridgedFunction, bool); typedef void (* _Nonnull UpdateLifetimeValuesFn)(BridgedContext, BridgedArrayRef, BridgedArrayRef); static void registerLifetimeCompletion(UpdateLifetimeFunctionFn completeAllLifetimesFn, UpdateLifetimeValuesFn completeLifetimeFn); static void registerControlFlowUtils(UpdateFunctionFn breakInfiniteLoopsFn); }; struct BridgedLoopTree { swift::SILLoopInfo * _Nonnull li; BRIDGED_INLINE SwiftInt getTopLevelLoopCount() const; BRIDGED_INLINE BridgedLoop getLoop(SwiftInt index) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock splitEdge(BridgedBasicBlock bb, SwiftInt edgeIndex, BridgedDomTree domTree) const; }; struct BridgedPassContext { swift::SwiftPassInvocation * _Nonnull invocation; BridgedPassContext(swift::SwiftPassInvocation * _Nonnull invocation) : invocation(invocation) {} BRIDGED_INLINE BridgedPassContext(BridgedContext ctxt); BRIDGED_INLINE bool hadError() const; BRIDGED_INLINE void notifyDependencyOnBodyOf(BridgedFunction otherFunction) const; BRIDGED_INLINE void updateAnalysis() const; // Analysis SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedAliasAnalysis getAliasAnalysis() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedCalleeAnalysis getCalleeAnalysis() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeadEndBlocksAnalysis getDeadEndBlocksAnalysis() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDomTree getDomTree() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedPostDomTree getPostDomTree() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclObj getSwiftArrayDecl() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclObj getSwiftMutableSpanDecl() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedLoopTree getLoopTree() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedLoop getLoop() const; // Array semantics call static BRIDGED_INLINE ArrayCallKind getArraySemanticsCallKind(BridgedInstruction inst); BRIDGED_INLINE bool canHoistArraySemanticsCall(BridgedInstruction inst, BridgedInstruction toInst) const; BRIDGED_INLINE void hoistArraySemanticsCall(BridgedInstruction inst, BridgedInstruction beforeInst) const; // AST SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDiagnosticEngine getDiagnosticEngine() const; // SIL modifications struct DevirtResult { OptionalBridgedInstruction newApply; bool cfgChanged; }; bool tryOptimizeApplyOfPartialApply(BridgedInstruction closure) const; bool tryDeleteDeadClosure(BridgedInstruction closure, bool needKeepArgsAlive) const; SWIFT_IMPORT_UNSAFE DevirtResult tryDevirtualizeApply(BridgedInstruction apply, bool isMandatory) const; bool tryOptimizeKeypath(BridgedInstruction apply) const; SWIFT_IMPORT_UNSAFE OptionalBridgedValue constantFoldBuiltin(BridgedInstruction builtin) const; SWIFT_IMPORT_UNSAFE OptionalBridgedFunction specializeFunction(BridgedFunction function, BridgedSubstitutionMap substitutions, bool convertIndirectToDirect, bool isMandatory) const; void deserializeAllCallees(BridgedFunction function, bool deserializeAll) const; bool specializeClassMethodInst(BridgedInstruction cm) const; bool specializeWitnessMethodInst(BridgedInstruction wm) const; bool specializeAppliesInFunction(BridgedFunction function, bool isMandatory) const; BridgedOwnedString mangleOutlinedVariable(BridgedFunction function) const; BridgedOwnedString mangleAsyncRemoved(BridgedFunction function) const; struct ClosureArgMangling { SwiftInt argIdx; OptionalBridgedInstruction inst; SwiftInt otherArgIdx; }; BridgedOwnedString mangleWithDeadArgs(BridgedArrayRef bridgedDeadArgIndices, BridgedFunction function) const; BridgedOwnedString mangleWithClosureArgs(BridgedArrayRef closureArgManglings, BridgedFunction applySiteCallee) const; BridgedOwnedString mangleWithConstCaptureArgs(BridgedArrayRef bridgedConstArgs, BridgedFunction applySiteCallee) const; BridgedOwnedString mangleWithBoxToStackPromotedArgs(BridgedArrayRef bridgedPromotedArgIndices, BridgedFunction bridgedOriginalFunction) const; BridgedOwnedString mangleWithExplodedPackArgs(BridgedArrayRef bridgedPackArgs, BridgedFunction applySiteCallee) const; BridgedOwnedString mangleWithChangedRepresentation(BridgedFunction applySiteCallee) const; void inlineFunction(BridgedInstruction apply, bool mandatoryInline) const; BRIDGED_INLINE bool eliminateDeadAllocations(BridgedFunction f) const; void eraseFunction(BridgedFunction function) const; BRIDGED_INLINE bool shouldExpand(BridgedType type) const; // IRGen SwiftInt getStaticSize(BridgedType type) const; SwiftInt getStaticAlignment(BridgedType type) const; SwiftInt getStaticStride(BridgedType type) const; bool canMakeStaticObjectReadOnly(BridgedType type) const; // Stack nesting and other notifications BRIDGED_INLINE void notifyInvalidatedStackNesting() const; BRIDGED_INLINE bool getNeedFixStackNesting() const; void fixStackNesting(BridgedFunction function) const; BRIDGED_INLINE bool getNeedBreakInfiniteLoops() const; BRIDGED_INLINE void setNeedBreakInfiniteLoops(bool value) const; BRIDGED_INLINE bool getNeedCompleteLifetimes() const; BRIDGED_INLINE void setNeedCompleteLifetimes(bool value) const; // Access SIL module data structures SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedFunction getFirstFunctionInModule() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE static OptionalBridgedFunction getNextFunctionInModule(BridgedFunction function); SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedGlobalVar getFirstGlobalInModule() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE static OptionalBridgedGlobalVar getNextGlobalInModule(BridgedGlobalVar global); BRIDGED_INLINE SwiftInt getNumVTables() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedVTable getVTable(SwiftInt index) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedWitnessTable getFirstWitnessTableInModule() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE static OptionalBridgedWitnessTable getNextWitnessTableInModule( BridgedWitnessTable table); SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedDefaultWitnessTable getFirstDefaultWitnessTableInModule() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE static OptionalBridgedDefaultWitnessTable getNextDefaultWitnessTableInModule( BridgedDefaultWitnessTable table); // Passmanager housekeeping BRIDGED_INLINE bool continueWithNextSubpassRun(OptionalBridgedInstruction inst) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedContext initializeNestedPassContext(BridgedFunction newFunction) const; BRIDGED_INLINE void deinitializedNestedPassContext() const; BRIDGED_INLINE void addFunctionToPassManagerWorklist(BridgedFunction newFunction, BridgedFunction oldFunction) const; // Options enum class AssertConfiguration { Debug = 0, Release = 1, Unchecked = 2 }; BRIDGED_INLINE bool useAggressiveReg2MemForCodeSize() const; BRIDGED_INLINE bool enableStackProtection() const; BRIDGED_INLINE bool enableMergeableTraps() const; BRIDGED_INLINE bool hasFeature(BridgedFeature feature) const; BRIDGED_INLINE bool shouldRemoveCondFail(BridgedStringRef message, BridgedStringRef function) const; BRIDGED_INLINE bool enableMoveInoutStackProtection() const; BRIDGED_INLINE AssertConfiguration getAssertConfiguration() const; bool enableSimplificationFor(BridgedInstruction inst) const; BRIDGED_INLINE bool enableWMORequiredDiagnostics() const; BRIDGED_INLINE bool noAllocations() const; // Temporary for AddressableParameters Bootstrapping. BRIDGED_INLINE bool enableAddressDependencies() const; // Closure specializer SWIFT_IMPORT_UNSAFE BridgedFunction createSpecializedFunctionDeclaration(BridgedStringRef specializedName, const BridgedParameterInfo * _Nullable specializedBridgedParams, SwiftInt paramCount, const BridgedResultInfo *_Nullable specializedBridgedResults, SwiftInt resultCount, BridgedFunction bridgedOriginal, BridgedASTType::FunctionTypeRepresentation representation, bool makeBare, bool preserveGenericSignature) const; bool completeLifetime(BridgedValue value) const; }; bool BeginApply_canInline(BridgedInstruction beginApply); enum class BridgedDynamicCastResult { willSucceed, maySucceed, willFail }; BridgedDynamicCastResult classifyDynamicCastBridged(BridgedCanType sourceTy, BridgedCanType destTy, BridgedFunction function, bool sourceTypeIsExact); BridgedDynamicCastResult classifyDynamicCastBridged(BridgedInstruction inst); //===----------------------------------------------------------------------===// // Pass registration //===----------------------------------------------------------------------===// struct BridgedFunctionPassCtxt { BridgedFunction function; BridgedContext passContext; } ; struct BridgedInstructionPassCtxt { BridgedInstruction instruction; BridgedContext passContext; }; typedef void (* _Nonnull BridgedModulePassRunFn)(BridgedContext); typedef void (* _Nonnull BridgedFunctionPassRunFn)(BridgedFunctionPassCtxt); typedef void (* _Nonnull BridgedInstructionPassRunFn)(BridgedInstructionPassCtxt); void SILPassManager_registerModulePass(BridgedStringRef name, BridgedModulePassRunFn runFn); void SILPassManager_registerFunctionPass(BridgedStringRef name, BridgedFunctionPassRunFn runFn); void SILCombine_registerInstructionPass(BridgedStringRef instClassName, BridgedInstructionPassRunFn runFn); void registerFunctionTestThunk(SwiftNativeFunctionTestThunk); void registerFunctionTest(BridgedStringRef, void *_Nonnull nativeSwiftContext); #ifndef PURE_BRIDGING_MODE // In _not_ PURE_BRIDGING_MODE, briding functions are inlined and therefore inluded in the header file. #include "OptimizerBridgingImpl.h" #else // For fflush and stdout #include <stdio.h> #endif SWIFT_END_NULLABILITY_ANNOTATIONS #endif
c
github
https://github.com/apple/swift
include/swift/SILOptimizer/OptimizerBridging.h
#!/usr/bin/python import re import sys def remove_rtti(text): return re.sub(r'dynamic_cast<(.* \*)>', r'(\1)', text) def make_dalvik_compat(text): init_text = """/* Utility class for managing the JNI environment */ class JNIEnvWrapper { const Director *director_; JNIEnv *jenv_; public: JNIEnvWrapper(const Director *director) : director_(director), jenv_(0) { #if defined(SWIG_JAVA_ATTACH_CURRENT_THREAD_AS_DAEMON) // Attach a daemon thread to the JVM. Useful when the JVM should not wait for // the thread to exit upon shutdown. Only for jdk-1.4 and later. director_->swig_jvm_->AttachCurrentThreadAsDaemon((void **) &jenv_, NULL); #else director_->swig_jvm_->AttachCurrentThread((void **) &jenv_, NULL); #endif } ~JNIEnvWrapper() { #if !defined(SWIG_JAVA_NO_DETACH_CURRENT_THREAD) // Some JVMs, eg jdk-1.4.2 and lower on Solaris have a bug and crash with the DetachCurrentThread call. // However, without this call, the JVM hangs on exit when the thread was not created by the JVM and creates a memory leak. director_->swig_jvm_->DetachCurrentThread(); #endif } JNIEnv *getJNIEnv() const { return jenv_; } };""" final_text = """/* Utility class for managing the JNI environment */ class JNIEnvWrapper { const Director *director_; JNIEnv *jenv_; int env_status; JNIEnv *g_env; public: JNIEnvWrapper(const Director *director) : director_(director), jenv_(0) { env_status = director_->swig_jvm_->GetEnv( (void **) &g_env, JNI_VERSION_1_6); #if defined(SWIG_JAVA_ATTACH_CURRENT_THREAD_AS_DAEMON) // Attach a daemon thread to the JVM. Useful when the JVM should not wait for // the thread to exit upon shutdown. Only for jdk-1.4 and later. director_->swig_jvm_->AttachCurrentThreadAsDaemon( &jenv_, NULL); #else director_->swig_jvm_->AttachCurrentThread( &jenv_, NULL); #endif } ~JNIEnvWrapper() { #if !defined(SWIG_JAVA_NO_DETACH_CURRENT_THREAD) // Some JVMs, eg jdk-1.4.2 and lower on Solaris have a bug and crash with the DetachCurrentThread call. // However, without this call, the JVM hangs on exit when the thread was not created by the JVM and creates a memory leak. if( env_status == JNI_EDETACHED ){ director_->swig_jvm_->DetachCurrentThread(); } #endif } JNIEnv *getJNIEnv() const { return jenv_; } };""" return text.replace(init_text, final_text) if __name__ == '__main__': filename = sys.argv[1] brut_code = open(filename).read() code_wo_rtti = remove_rtti(brut_code) code_dalvik_compat = make_dalvik_compat(code_wo_rtti) print code_dalvik_compat
unknown
codeparrot/codeparrot-clean
<!--Copyright 2020 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> *This model was released on 2018-06-11 and added to Hugging Face Transformers on 2023-06-20.* <div style="float: right;"> <div class="flex flex-wrap space-x-1"> <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> <img alt="SDPA" src="https://img.shields.io/badge/SDPA-DE3412?style=flat&logo=pytorch&logoColor=white"> <img alt="FlashAttention" src="https://img.shields.io/badge/%E2%9A%A1%EF%B8%8E%20FlashAttention-eae0c8?style=flat"> </div> </div> # GPT [GPT (Generative Pre-trained Transformer)](https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf) ([blog post](https://openai.com/index/language-unsupervised/)) focuses on effectively learning text representations and transferring them to tasks. This model trains the Transformer decoder to predict the next word, and then fine-tuned on labeled data. GPT can generate high-quality text, making it well-suited for a variety of natural language understanding tasks such as textual entailment, question answering, semantic similarity, and document classification. You can find all the original GPT checkpoints under the [OpenAI community](https://huggingface.co/openai-community/openai-gpt) organization. > [!TIP] > Click on the GPT models in the right sidebar for more examples of how to apply GPT to different language tasks. The example below demonstrates how to generate text with [`Pipeline`], [`AutoModel`], and from the command line. <hfoptions id="usage"> <hfoption id="Pipeline"> ```python import torch from transformers import pipeline generator = pipeline(task="text-generation", model="openai-community/openai-gpt", device=0) output = generator("The future of AI is", max_length=50, do_sample=True) print(output[0]["generated_text"]) ``` </hfoption> <hfoption id="AutoModel"> ```python from transformers import AutoModelForCausalLM, AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("openai-community/openai-gpt") model = AutoModelForCausalLM.from_pretrained("openai-community/openai-gpt") inputs = tokenizer("The future of AI is", return_tensors="pt") outputs = model.generate(**inputs, max_length=50) print(tokenizer.decode(outputs[0], skip_special_tokens=True)) ``` </hfoption> <hfoption id="transformers CLI"> ```bash echo -e "The future of AI is" | transformers run --task text-generation --model openai-community/openai-gpt --device 0 ``` </hfoption> </hfoptions> ## Notes - Inputs should be padded on the right because GPT uses absolute position embeddings. ## OpenAIGPTConfig [[autodoc]] OpenAIGPTConfig ## OpenAIGPTModel [[autodoc]] OpenAIGPTModel - forward ## OpenAIGPTLMHeadModel [[autodoc]] OpenAIGPTLMHeadModel - forward ## OpenAIGPTDoubleHeadsModel [[autodoc]] OpenAIGPTDoubleHeadsModel - forward ## OpenAIGPTForSequenceClassification [[autodoc]] OpenAIGPTForSequenceClassification - forward ## OpenAIGPTTokenizer [[autodoc]] OpenAIGPTTokenizer ## OpenAIGPTTokenizerFast [[autodoc]] OpenAIGPTTokenizerFast
unknown
github
https://github.com/huggingface/transformers
docs/source/en/model_doc/openai-gpt.md
from __future__ import unicode_literals from django.contrib import admin from django.contrib.admin.options import ModelAdmin from django.contrib.auth.models import User from django.test import RequestFactory, TestCase from .models import ( Band, DynOrderingBandAdmin, Song, SongInlineDefaultOrdering, SongInlineNewOrdering, ) class MockRequest(object): pass class MockSuperUser(object): def has_perm(self, perm): return True def has_module_perms(self, module): return True request = MockRequest() request.user = MockSuperUser() site = admin.AdminSite() class TestAdminOrdering(TestCase): """ Let's make sure that ModelAdmin.get_queryset uses the ordering we define in ModelAdmin rather that ordering defined in the model's inner Meta class. """ def setUp(self): self.request_factory = RequestFactory() Band.objects.bulk_create([ Band(name='Aerosmith', bio='', rank=3), Band(name='Radiohead', bio='', rank=1), Band(name='Van Halen', bio='', rank=2), ]) def test_default_ordering(self): """ The default ordering should be by name, as specified in the inner Meta class. """ ma = ModelAdmin(Band, site) names = [b.name for b in ma.get_queryset(request)] self.assertListEqual(['Aerosmith', 'Radiohead', 'Van Halen'], names) def test_specified_ordering(self): """ Let's use a custom ModelAdmin that changes the ordering, and make sure it actually changes. """ class BandAdmin(ModelAdmin): ordering = ('rank',) # default ordering is ('name',) ma = BandAdmin(Band, site) names = [b.name for b in ma.get_queryset(request)] self.assertListEqual(['Radiohead', 'Van Halen', 'Aerosmith'], names) def test_dynamic_ordering(self): """ Let's use a custom ModelAdmin that changes the ordering dynamically. """ super_user = User.objects.create(username='admin', is_superuser=True) other_user = User.objects.create(username='other') request = self.request_factory.get('/') request.user = super_user ma = DynOrderingBandAdmin(Band, site) names = [b.name for b in ma.get_queryset(request)] self.assertListEqual(['Radiohead', 'Van Halen', 'Aerosmith'], names) request.user = other_user names = [b.name for b in ma.get_queryset(request)] self.assertListEqual(['Aerosmith', 'Radiohead', 'Van Halen'], names) class TestInlineModelAdminOrdering(TestCase): """ Let's make sure that InlineModelAdmin.get_queryset uses the ordering we define in InlineModelAdmin. """ def setUp(self): self.band = Band.objects.create(name='Aerosmith', bio='', rank=3) Song.objects.bulk_create([ Song(band=self.band, name='Pink', duration=235), Song(band=self.band, name='Dude (Looks Like a Lady)', duration=264), Song(band=self.band, name='Jaded', duration=214), ]) def test_default_ordering(self): """ The default ordering should be by name, as specified in the inner Meta class. """ inline = SongInlineDefaultOrdering(self.band, site) names = [s.name for s in inline.get_queryset(request)] self.assertListEqual(['Dude (Looks Like a Lady)', 'Jaded', 'Pink'], names) def test_specified_ordering(self): """ Let's check with ordering set to something different than the default. """ inline = SongInlineNewOrdering(self.band, site) names = [s.name for s in inline.get_queryset(request)] self.assertListEqual(['Jaded', 'Pink', 'Dude (Looks Like a Lady)'], names) class TestRelatedFieldsAdminOrdering(TestCase): def setUp(self): self.b1 = Band.objects.create(name='Pink Floyd', bio='', rank=1) self.b2 = Band.objects.create(name='Foo Fighters', bio='', rank=5) # we need to register a custom ModelAdmin (instead of just using # ModelAdmin) because the field creator tries to find the ModelAdmin # for the related model class SongAdmin(admin.ModelAdmin): pass site.register(Song, SongAdmin) def tearDown(self): site.unregister(Song) if Band in site._registry: site.unregister(Band) def check_ordering_of_field_choices(self, correct_ordering): fk_field = site._registry[Song].formfield_for_foreignkey(Song.band.field) m2m_field = site._registry[Song].formfield_for_manytomany(Song.other_interpreters.field) self.assertListEqual(list(fk_field.queryset), correct_ordering) self.assertListEqual(list(m2m_field.queryset), correct_ordering) def test_no_admin_fallback_to_model_ordering(self): # should be ordered by name (as defined by the model) self.check_ordering_of_field_choices([self.b2, self.b1]) def test_admin_with_no_ordering_fallback_to_model_ordering(self): class NoOrderingBandAdmin(admin.ModelAdmin): pass site.register(Band, NoOrderingBandAdmin) # should be ordered by name (as defined by the model) self.check_ordering_of_field_choices([self.b2, self.b1]) def test_admin_ordering_beats_model_ordering(self): class StaticOrderingBandAdmin(admin.ModelAdmin): ordering = ('rank',) site.register(Band, StaticOrderingBandAdmin) # should be ordered by rank (defined by the ModelAdmin) self.check_ordering_of_field_choices([self.b1, self.b2]) def test_custom_queryset_still_wins(self): """Test that custom queryset has still precedence (#21405)""" class SongAdmin(admin.ModelAdmin): # Exclude one of the two Bands from the querysets def formfield_for_foreignkey(self, db_field, **kwargs): if db_field.name == 'band': kwargs["queryset"] = Band.objects.filter(rank__gt=2) return super(SongAdmin, self).formfield_for_foreignkey(db_field, **kwargs) def formfield_for_manytomany(self, db_field, **kwargs): if db_field.name == 'other_interpreters': kwargs["queryset"] = Band.objects.filter(rank__gt=2) return super(SongAdmin, self).formfield_for_foreignkey(db_field, **kwargs) class StaticOrderingBandAdmin(admin.ModelAdmin): ordering = ('rank',) site.unregister(Song) site.register(Song, SongAdmin) site.register(Band, StaticOrderingBandAdmin) self.check_ordering_of_field_choices([self.b2])
unknown
codeparrot/codeparrot-clean
// This file is part of ICU4X. For terms of use, please see the file // called LICENSE at the top level of the ICU4X source tree // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). //! This module contains types and implementations for the Julian calendar. //! //! ```rust //! use icu::calendar::{cal::Julian, Date}; //! //! let date_iso = Date::try_new_iso(1970, 1, 2) //! .expect("Failed to initialize ISO Date instance."); //! let date_julian = Date::new_from_iso(date_iso, Julian); //! //! assert_eq!(date_julian.era_year().year, 1969); //! assert_eq!(date_julian.month().ordinal, 12); //! assert_eq!(date_julian.day_of_month().0, 20); //! ``` use crate::cal::iso::{Iso, IsoDateInner}; use crate::calendar_arithmetic::{ArithmeticDate, CalendarArithmetic}; use crate::error::{year_check, DateError}; use crate::{types, Calendar, Date, DateDuration, DateDurationUnit, RangeError}; use calendrical_calculations::helpers::I32CastError; use calendrical_calculations::rata_die::RataDie; use tinystr::tinystr; /// The [Julian Calendar] /// /// The [Julian calendar] is a solar calendar that was used commonly historically, with twelve months. /// /// This type can be used with [`Date`] to represent dates in this calendar. /// /// [Julian calendar]: https://en.wikipedia.org/wiki/Julian_calendar /// /// # Era codes /// /// This calendar uses two era codes: `bce` (alias `bc`), and `ce` (alias `ad`), corresponding to the BCE and CE eras. /// /// # Month codes /// /// This calendar supports 12 solar month codes (`"M01" - "M12"`) #[derive(Copy, Clone, Debug, Hash, Default, Eq, PartialEq, PartialOrd, Ord)] #[allow(clippy::exhaustive_structs)] // this type is stable pub struct Julian; /// The inner date type used for representing [`Date`]s of [`Julian`]. See [`Date`] and [`Julian`] for more details. #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] // The inner date type used for representing Date<Julian> pub struct JulianDateInner(pub(crate) ArithmeticDate<Julian>); impl CalendarArithmetic for Julian { type YearInfo = i32; fn days_in_provided_month(year: i32, month: u8) -> u8 { match month { 4 | 6 | 9 | 11 => 30, 2 if Self::provided_year_is_leap(year) => 29, 2 => 28, 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, _ => 0, } } fn months_in_provided_year(_: i32) -> u8 { 12 } fn provided_year_is_leap(year: i32) -> bool { calendrical_calculations::julian::is_leap_year(year) } fn last_month_day_in_provided_year(_year: i32) -> (u8, u8) { (12, 31) } fn days_in_provided_year(year: i32) -> u16 { if Self::provided_year_is_leap(year) { 366 } else { 365 } } } impl crate::cal::scaffold::UnstableSealed for Julian {} impl Calendar for Julian { type DateInner = JulianDateInner; type Year = types::EraYear; fn from_codes( &self, era: Option<&str>, year: i32, month_code: types::MonthCode, day: u8, ) -> Result<Self::DateInner, DateError> { let year = match era { Some("ce" | "ad") | None => year_check(year, 1..)?, Some("bce" | "bc") => 1 - year_check(year, 1..)?, Some(_) => return Err(DateError::UnknownEra), }; ArithmeticDate::new_from_codes(self, year, month_code, day).map(JulianDateInner) } fn from_rata_die(&self, rd: RataDie) -> Self::DateInner { JulianDateInner( match calendrical_calculations::julian::julian_from_fixed(rd) { Err(I32CastError::BelowMin) => ArithmeticDate::min_date(), Err(I32CastError::AboveMax) => ArithmeticDate::max_date(), Ok((year, month, day)) => ArithmeticDate::new_unchecked(year, month, day), }, ) } fn to_rata_die(&self, date: &Self::DateInner) -> RataDie { calendrical_calculations::julian::fixed_from_julian(date.0.year, date.0.month, date.0.day) } fn from_iso(&self, iso: IsoDateInner) -> JulianDateInner { self.from_rata_die(Iso.to_rata_die(&iso)) } fn to_iso(&self, date: &Self::DateInner) -> IsoDateInner { Iso.from_rata_die(self.to_rata_die(date)) } fn months_in_year(&self, date: &Self::DateInner) -> u8 { date.0.months_in_year() } fn days_in_year(&self, date: &Self::DateInner) -> u16 { date.0.days_in_year() } fn days_in_month(&self, date: &Self::DateInner) -> u8 { date.0.days_in_month() } fn offset_date(&self, date: &mut Self::DateInner, offset: DateDuration<Self>) { date.0.offset_date(offset, &()); } #[allow(clippy::field_reassign_with_default)] fn until( &self, date1: &Self::DateInner, date2: &Self::DateInner, _calendar2: &Self, _largest_unit: DateDurationUnit, _smallest_unit: DateDurationUnit, ) -> DateDuration<Self> { date1.0.until(date2.0, _largest_unit, _smallest_unit) } /// The calendar-specific year represented by `date` /// Julian has the same era scheme as Gregorian fn year_info(&self, date: &Self::DateInner) -> Self::Year { let extended_year = self.extended_year(date); if extended_year > 0 { types::EraYear { era: tinystr!(16, "ce"), era_index: Some(1), year: extended_year, ambiguity: types::YearAmbiguity::CenturyRequired, } } else { types::EraYear { era: tinystr!(16, "bce"), era_index: Some(0), year: 1_i32.saturating_sub(extended_year), ambiguity: types::YearAmbiguity::EraAndCenturyRequired, } } } fn extended_year(&self, date: &Self::DateInner) -> i32 { date.0.extended_year() } fn is_in_leap_year(&self, date: &Self::DateInner) -> bool { Self::provided_year_is_leap(date.0.year) } /// The calendar-specific month represented by `date` fn month(&self, date: &Self::DateInner) -> types::MonthInfo { date.0.month() } /// The calendar-specific day-of-month represented by `date` fn day_of_month(&self, date: &Self::DateInner) -> types::DayOfMonth { date.0.day_of_month() } fn day_of_year(&self, date: &Self::DateInner) -> types::DayOfYear { date.0.day_of_year() } fn debug_name(&self) -> &'static str { "Julian" } fn calendar_algorithm(&self) -> Option<crate::preferences::CalendarAlgorithm> { None } } impl Julian { /// Construct a new Julian Calendar pub fn new() -> Self { Self } } impl Date<Julian> { /// Construct new Julian Date. /// /// Years are arithmetic, meaning there is a year 0. Zero and negative years are in BC, with year 0 = 1 BC /// /// ```rust /// use icu::calendar::Date; /// /// let date_julian = Date::try_new_julian(1969, 12, 20) /// .expect("Failed to initialize Julian Date instance."); /// /// assert_eq!(date_julian.era_year().year, 1969); /// assert_eq!(date_julian.month().ordinal, 12); /// assert_eq!(date_julian.day_of_month().0, 20); /// ``` pub fn try_new_julian(year: i32, month: u8, day: u8) -> Result<Date<Julian>, RangeError> { ArithmeticDate::new_from_ordinals(year, month, day) .map(JulianDateInner) .map(|inner| Date::from_raw(inner, Julian)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_day_iso_to_julian() { // March 1st 200 is same on both calendars let iso_date = Date::try_new_iso(200, 3, 1).unwrap(); let julian_date = Date::new_from_iso(iso_date, Julian).inner; assert_eq!(julian_date.0.year, 200); assert_eq!(julian_date.0.month, 3); assert_eq!(julian_date.0.day, 1); // Feb 28th, 200 (iso) = Feb 29th, 200 (julian) let iso_date = Date::try_new_iso(200, 2, 28).unwrap(); let julian_date = Date::new_from_iso(iso_date, Julian).inner; assert_eq!(julian_date.0.year, 200); assert_eq!(julian_date.0.month, 2); assert_eq!(julian_date.0.day, 29); // March 1st 400 (iso) = Feb 29th, 400 (julian) let iso_date = Date::try_new_iso(400, 3, 1).unwrap(); let julian_date = Date::new_from_iso(iso_date, Julian).inner; assert_eq!(julian_date.0.year, 400); assert_eq!(julian_date.0.month, 2); assert_eq!(julian_date.0.day, 29); // Jan 1st, 2022 (iso) = Dec 19, 2021 (julian) let iso_date = Date::try_new_iso(2022, 1, 1).unwrap(); let julian_date = Date::new_from_iso(iso_date, Julian).inner; assert_eq!(julian_date.0.year, 2021); assert_eq!(julian_date.0.month, 12); assert_eq!(julian_date.0.day, 19); } #[test] fn test_day_julian_to_iso() { // March 1st 200 is same on both calendars let julian_date = Date::try_new_julian(200, 3, 1).unwrap(); let iso_date = julian_date.to_iso(); let iso_expected_date = Date::try_new_iso(200, 3, 1).unwrap(); assert_eq!(iso_date, iso_expected_date); // Feb 28th, 200 (iso) = Feb 29th, 200 (julian) let julian_date = Date::try_new_julian(200, 2, 29).unwrap(); let iso_date = julian_date.to_iso(); let iso_expected_date = Date::try_new_iso(200, 2, 28).unwrap(); assert_eq!(iso_date, iso_expected_date); // March 1st 400 (iso) = Feb 29th, 400 (julian) let julian_date = Date::try_new_julian(400, 2, 29).unwrap(); let iso_date = julian_date.to_iso(); let iso_expected_date = Date::try_new_iso(400, 3, 1).unwrap(); assert_eq!(iso_date, iso_expected_date); // Jan 1st, 2022 (iso) = Dec 19, 2021 (julian) let julian_date = Date::try_new_julian(2021, 12, 19).unwrap(); let iso_date = julian_date.to_iso(); let iso_expected_date = Date::try_new_iso(2022, 1, 1).unwrap(); assert_eq!(iso_date, iso_expected_date); // March 1st, 2022 (iso) = Feb 16, 2022 (julian) let julian_date = Date::try_new_julian(2022, 2, 16).unwrap(); let iso_date = julian_date.to_iso(); let iso_expected_date = Date::try_new_iso(2022, 3, 1).unwrap(); assert_eq!(iso_date, iso_expected_date); } #[test] fn test_roundtrip_negative() { // https://github.com/unicode-org/icu4x/issues/2254 let iso_date = Date::try_new_iso(-1000, 3, 3).unwrap(); let julian = iso_date.to_calendar(Julian::new()); let recovered_iso = julian.to_iso(); assert_eq!(iso_date, recovered_iso); } #[test] fn test_julian_near_era_change() { // Tests that the Julian calendar gives the correct expected // day, month, and year for positive years (CE) #[derive(Debug)] struct TestCase { rd: i64, iso_year: i32, iso_month: u8, iso_day: u8, expected_year: i32, expected_era: &'static str, expected_month: u8, expected_day: u8, } let cases = [ TestCase { rd: 1, iso_year: 1, iso_month: 1, iso_day: 1, expected_year: 1, expected_era: "ce", expected_month: 1, expected_day: 3, }, TestCase { rd: 0, iso_year: 0, iso_month: 12, iso_day: 31, expected_year: 1, expected_era: "ce", expected_month: 1, expected_day: 2, }, TestCase { rd: -1, iso_year: 0, iso_month: 12, iso_day: 30, expected_year: 1, expected_era: "ce", expected_month: 1, expected_day: 1, }, TestCase { rd: -2, iso_year: 0, iso_month: 12, iso_day: 29, expected_year: 1, expected_era: "bce", expected_month: 12, expected_day: 31, }, TestCase { rd: -3, iso_year: 0, iso_month: 12, iso_day: 28, expected_year: 1, expected_era: "bce", expected_month: 12, expected_day: 30, }, TestCase { rd: -367, iso_year: -1, iso_month: 12, iso_day: 30, expected_year: 1, expected_era: "bce", expected_month: 1, expected_day: 1, }, TestCase { rd: -368, iso_year: -1, iso_month: 12, iso_day: 29, expected_year: 2, expected_era: "bce", expected_month: 12, expected_day: 31, }, TestCase { rd: -1462, iso_year: -4, iso_month: 12, iso_day: 30, expected_year: 4, expected_era: "bce", expected_month: 1, expected_day: 1, }, TestCase { rd: -1463, iso_year: -4, iso_month: 12, iso_day: 29, expected_year: 5, expected_era: "bce", expected_month: 12, expected_day: 31, }, ]; for case in cases { let iso_from_rd = Date::from_rata_die(RataDie::new(case.rd), crate::Iso); let julian_from_rd = Date::from_rata_die(RataDie::new(case.rd), Julian); assert_eq!(julian_from_rd.era_year().year, case.expected_year, "Failed year check from RD: {case:?}\nISO: {iso_from_rd:?}\nJulian: {julian_from_rd:?}"); assert_eq!(julian_from_rd.era_year().era, case.expected_era, "Failed era check from RD: {case:?}\nISO: {iso_from_rd:?}\nJulian: {julian_from_rd:?}"); assert_eq!(julian_from_rd.month().ordinal, case.expected_month, "Failed month check from RD: {case:?}\nISO: {iso_from_rd:?}\nJulian: {julian_from_rd:?}"); assert_eq!(julian_from_rd.day_of_month().0, case.expected_day, "Failed day check from RD: {case:?}\nISO: {iso_from_rd:?}\nJulian: {julian_from_rd:?}"); let iso_date_man = Date::try_new_iso(case.iso_year, case.iso_month, case.iso_day) .expect("Failed to initialize ISO date for {case:?}"); let julian_date_man = Date::new_from_iso(iso_date_man, Julian); assert_eq!(iso_from_rd, iso_date_man, "ISO from RD not equal to ISO generated from manually-input ymd\nCase: {case:?}\nRD: {iso_from_rd:?}\nMan: {iso_date_man:?}"); assert_eq!(julian_from_rd, julian_date_man, "Julian from RD not equal to Julian generated from manually-input ymd\nCase: {case:?}\nRD: {julian_from_rd:?}\nMan: {julian_date_man:?}"); } } #[test] fn test_julian_rd_date_conversion() { // Tests that converting from RD to Julian then // back to RD yields the same RD for i in -10000..=10000 { let rd = RataDie::new(i); let julian = Date::from_rata_die(rd, Julian); let new_rd = julian.to_rata_die(); assert_eq!(rd, new_rd); } } #[test] fn test_julian_directionality() { // Tests that for a large range of RDs, if a RD // is less than another, the corresponding YMD should also be less // than the other, without exception. for i in -100..=100 { for j in -100..=100 { let julian_i = Date::from_rata_die(RataDie::new(i), Julian); let julian_j = Date::from_rata_die(RataDie::new(j), Julian); assert_eq!( i.cmp(&j), julian_i.inner.0.cmp(&julian_j.inner.0), "Julian directionality inconsistent with directionality for i: {i}, j: {j}" ); } } } #[test] fn test_hebrew_epoch() { assert_eq!( calendrical_calculations::julian::fixed_from_julian_book_version(-3761, 10, 7), RataDie::new(-1373427) ); } #[test] fn test_julian_leap_years() { assert!(Julian::provided_year_is_leap(4)); assert!(Julian::provided_year_is_leap(0)); assert!(Julian::provided_year_is_leap(-4)); Date::try_new_julian(2020, 2, 29).unwrap(); } }
rust
github
https://github.com/nodejs/node
deps/crates/vendor/icu_calendar/src/cal/julian.rs
# XXX TO DO: # - popup menu # - support partial or total redisplay # - key bindings (instead of quick-n-dirty bindings on Canvas): # - up/down arrow keys to move focus around # - ditto for page up/down, home/end # - left/right arrows to expand/collapse & move out/in # - more doc strings # - add icons for "file", "module", "class", "method"; better "python" icon # - callback for selection??? # - multiple-item selection # - tooltips # - redo geometry without magic numbers # - keep track of object ids to allow more careful cleaning # - optimize tree redraw after expand of subnode import os from Tkinter import * import imp from idlelib import ZoomHeight from idlelib.configHandler import idleConf ICONDIR = "Icons" # Look for Icons subdirectory in the same directory as this module try: _icondir = os.path.join(os.path.dirname(__file__), ICONDIR) except NameError: _icondir = ICONDIR if os.path.isdir(_icondir): ICONDIR = _icondir elif not os.path.isdir(ICONDIR): raise RuntimeError, "can't find icon directory (%r)" % (ICONDIR,) def listicons(icondir=ICONDIR): """Utility to display the available icons.""" root = Tk() import glob list = glob.glob(os.path.join(icondir, "*.gif")) list.sort() images = [] row = column = 0 for file in list: name = os.path.splitext(os.path.basename(file))[0] image = PhotoImage(file=file, master=root) images.append(image) label = Label(root, image=image, bd=1, relief="raised") label.grid(row=row, column=column) label = Label(root, text=name) label.grid(row=row+1, column=column) column = column + 1 if column >= 10: row = row+2 column = 0 root.images = images class TreeNode: def __init__(self, canvas, parent, item): self.canvas = canvas self.parent = parent self.item = item self.state = 'collapsed' self.selected = False self.children = [] self.x = self.y = None self.iconimages = {} # cache of PhotoImage instances for icons def destroy(self): for c in self.children[:]: self.children.remove(c) c.destroy() self.parent = None def geticonimage(self, name): try: return self.iconimages[name] except KeyError: pass file, ext = os.path.splitext(name) ext = ext or ".gif" fullname = os.path.join(ICONDIR, file + ext) image = PhotoImage(master=self.canvas, file=fullname) self.iconimages[name] = image return image def select(self, event=None): if self.selected: return self.deselectall() self.selected = True self.canvas.delete(self.image_id) self.drawicon() self.drawtext() def deselect(self, event=None): if not self.selected: return self.selected = False self.canvas.delete(self.image_id) self.drawicon() self.drawtext() def deselectall(self): if self.parent: self.parent.deselectall() else: self.deselecttree() def deselecttree(self): if self.selected: self.deselect() for child in self.children: child.deselecttree() def flip(self, event=None): if self.state == 'expanded': self.collapse() else: self.expand() self.item.OnDoubleClick() return "break" def expand(self, event=None): if not self.item._IsExpandable(): return if self.state != 'expanded': self.state = 'expanded' self.update() self.view() def collapse(self, event=None): if self.state != 'collapsed': self.state = 'collapsed' self.update() def view(self): top = self.y - 2 bottom = self.lastvisiblechild().y + 17 height = bottom - top visible_top = self.canvas.canvasy(0) visible_height = self.canvas.winfo_height() visible_bottom = self.canvas.canvasy(visible_height) if visible_top <= top and bottom <= visible_bottom: return x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion']) if top >= visible_top and height <= visible_height: fraction = top + height - visible_height else: fraction = top fraction = float(fraction) / y1 self.canvas.yview_moveto(fraction) def lastvisiblechild(self): if self.children and self.state == 'expanded': return self.children[-1].lastvisiblechild() else: return self def update(self): if self.parent: self.parent.update() else: oldcursor = self.canvas['cursor'] self.canvas['cursor'] = "watch" self.canvas.update() self.canvas.delete(ALL) # XXX could be more subtle self.draw(7, 2) x0, y0, x1, y1 = self.canvas.bbox(ALL) self.canvas.configure(scrollregion=(0, 0, x1, y1)) self.canvas['cursor'] = oldcursor def draw(self, x, y): # XXX This hard-codes too many geometry constants! self.x, self.y = x, y self.drawicon() self.drawtext() if self.state != 'expanded': return y+17 # draw children if not self.children: sublist = self.item._GetSubList() if not sublist: # _IsExpandable() was mistaken; that's allowed return y+17 for item in sublist: child = self.__class__(self.canvas, self, item) self.children.append(child) cx = x+20 cy = y+17 cylast = 0 for child in self.children: cylast = cy self.canvas.create_line(x+9, cy+7, cx, cy+7, fill="gray50") cy = child.draw(cx, cy) if child.item._IsExpandable(): if child.state == 'expanded': iconname = "minusnode" callback = child.collapse else: iconname = "plusnode" callback = child.expand image = self.geticonimage(iconname) id = self.canvas.create_image(x+9, cylast+7, image=image) # XXX This leaks bindings until canvas is deleted: self.canvas.tag_bind(id, "<1>", callback) self.canvas.tag_bind(id, "<Double-1>", lambda x: None) id = self.canvas.create_line(x+9, y+10, x+9, cylast+7, ##stipple="gray50", # XXX Seems broken in Tk 8.0.x fill="gray50") self.canvas.tag_lower(id) # XXX .lower(id) before Python 1.5.2 return cy def drawicon(self): if self.selected: imagename = (self.item.GetSelectedIconName() or self.item.GetIconName() or "openfolder") else: imagename = self.item.GetIconName() or "folder" image = self.geticonimage(imagename) id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image) self.image_id = id self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "<Double-1>", self.flip) def drawtext(self): textx = self.x+20-1 texty = self.y-1 labeltext = self.item.GetLabelText() if labeltext: id = self.canvas.create_text(textx, texty, anchor="nw", text=labeltext) self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "<Double-1>", self.flip) x0, y0, x1, y1 = self.canvas.bbox(id) textx = max(x1, 200) + 10 text = self.item.GetText() or "<no text>" try: self.entry except AttributeError: pass else: self.edit_finish() try: label = self.label except AttributeError: # padding carefully selected (on Windows) to match Entry widget: self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2) theme = idleConf.GetOption('main','Theme','name') if self.selected: self.label.configure(idleConf.GetHighlight(theme, 'hilite')) else: self.label.configure(idleConf.GetHighlight(theme, 'normal')) id = self.canvas.create_window(textx, texty, anchor="nw", window=self.label) self.label.bind("<1>", self.select_or_edit) self.label.bind("<Double-1>", self.flip) self.text_id = id def select_or_edit(self, event=None): if self.selected and self.item.IsEditable(): self.edit(event) else: self.select(event) def edit(self, event=None): self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0) self.entry.insert(0, self.label['text']) self.entry.selection_range(0, END) self.entry.pack(ipadx=5) self.entry.focus_set() self.entry.bind("<Return>", self.edit_finish) self.entry.bind("<Escape>", self.edit_cancel) def edit_finish(self, event=None): try: entry = self.entry del self.entry except AttributeError: return text = entry.get() entry.destroy() if text and text != self.item.GetText(): self.item.SetText(text) text = self.item.GetText() self.label['text'] = text self.drawtext() self.canvas.focus_set() def edit_cancel(self, event=None): try: entry = self.entry del self.entry except AttributeError: return entry.destroy() self.drawtext() self.canvas.focus_set() class TreeItem: """Abstract class representing tree items. Methods should typically be overridden, otherwise a default action is used. """ def __init__(self): """Constructor. Do whatever you need to do.""" def GetText(self): """Return text string to display.""" def GetLabelText(self): """Return label text string to display in front of text (if any).""" expandable = None def _IsExpandable(self): """Do not override! Called by TreeNode.""" if self.expandable is None: self.expandable = self.IsExpandable() return self.expandable def IsExpandable(self): """Return whether there are subitems.""" return 1 def _GetSubList(self): """Do not override! Called by TreeNode.""" if not self.IsExpandable(): return [] sublist = self.GetSubList() if not sublist: self.expandable = 0 return sublist def IsEditable(self): """Return whether the item's text may be edited.""" def SetText(self, text): """Change the item's text (if it is editable).""" def GetIconName(self): """Return name of icon to be displayed normally.""" def GetSelectedIconName(self): """Return name of icon to be displayed when selected.""" def GetSubList(self): """Return list of items forming sublist.""" def OnDoubleClick(self): """Called on a double-click on the item.""" # Example application class FileTreeItem(TreeItem): """Example TreeItem subclass -- browse the file system.""" def __init__(self, path): self.path = path def GetText(self): return os.path.basename(self.path) or self.path def IsEditable(self): return os.path.basename(self.path) != "" def SetText(self, text): newpath = os.path.dirname(self.path) newpath = os.path.join(newpath, text) if os.path.dirname(newpath) != os.path.dirname(self.path): return try: os.rename(self.path, newpath) self.path = newpath except os.error: pass def GetIconName(self): if not self.IsExpandable(): return "python" # XXX wish there was a "file" icon def IsExpandable(self): return os.path.isdir(self.path) def GetSubList(self): try: names = os.listdir(self.path) except os.error: return [] names.sort(key = os.path.normcase) sublist = [] for name in names: item = FileTreeItem(os.path.join(self.path, name)) sublist.append(item) return sublist # A canvas widget with scroll bars and some useful bindings class ScrolledCanvas: def __init__(self, master, **opts): if 'yscrollincrement' not in opts: opts['yscrollincrement'] = 17 self.master = master self.frame = Frame(master) self.frame.rowconfigure(0, weight=1) self.frame.columnconfigure(0, weight=1) self.canvas = Canvas(self.frame, **opts) self.canvas.grid(row=0, column=0, sticky="nsew") self.vbar = Scrollbar(self.frame, name="vbar") self.vbar.grid(row=0, column=1, sticky="nse") self.hbar = Scrollbar(self.frame, name="hbar", orient="horizontal") self.hbar.grid(row=1, column=0, sticky="ews") self.canvas['yscrollcommand'] = self.vbar.set self.vbar['command'] = self.canvas.yview self.canvas['xscrollcommand'] = self.hbar.set self.hbar['command'] = self.canvas.xview self.canvas.bind("<Key-Prior>", self.page_up) self.canvas.bind("<Key-Next>", self.page_down) self.canvas.bind("<Key-Up>", self.unit_up) self.canvas.bind("<Key-Down>", self.unit_down) #if isinstance(master, Toplevel) or isinstance(master, Tk): self.canvas.bind("<Alt-Key-2>", self.zoom_height) self.canvas.focus_set() def page_up(self, event): self.canvas.yview_scroll(-1, "page") return "break" def page_down(self, event): self.canvas.yview_scroll(1, "page") return "break" def unit_up(self, event): self.canvas.yview_scroll(-1, "unit") return "break" def unit_down(self, event): self.canvas.yview_scroll(1, "unit") return "break" def zoom_height(self, event): ZoomHeight.zoom_height(self.master) return "break" # Testing functions def test(): from idlelib import PyShell root = Toplevel(PyShell.root) root.configure(bd=0, bg="yellow") root.focus_set() sc = ScrolledCanvas(root, bg="white", highlightthickness=0, takefocus=1) sc.frame.pack(expand=1, fill="both") item = FileTreeItem("C:/windows/desktop") node = TreeNode(sc.canvas, None, item) node.expand() def test2(): # test w/o scrolling canvas root = Tk() root.configure(bd=0) canvas = Canvas(root, bg="white", highlightthickness=0) canvas.pack(expand=1, fill="both") item = FileTreeItem(os.curdir) node = TreeNode(canvas, None, item) node.update() canvas.focus_set() if __name__ == '__main__': test()
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import io import pickle import os.path import tempfile import atom.http_core class Error(Exception): pass class NoRecordingFound(Error): pass class MockHttpClient(object): debug = False real_client = None last_request_was_live = False # The following members are used to construct the session cache temp file # name. # These are combined to form the file name # /tmp/cache_prefix.cache_case_name.cache_test_name cache_name_prefix = 'gdata_live_test' cache_case_name = '' cache_test_name = '' def __init__(self, recordings=None, real_client=None): self._recordings = recordings or [] if real_client is not None: self.real_client = real_client def add_response(self, http_request, status, reason, headers=None, body=None): response = MockHttpResponse(status, reason, headers, body) # TODO Scrub the request and the response. self._recordings.append((http_request._copy(), response)) AddResponse = add_response def request(self, http_request): """Provide a recorded response, or record a response for replay. If the real_client is set, the request will be made using the real_client, and the response from the server will be recorded. If the real_client is None (the default), this method will examine the recordings and find the first which matches. """ request = http_request._copy() _scrub_request(request) if self.real_client is None: self.last_request_was_live = False for recording in self._recordings: if _match_request(recording[0], request): return recording[1] else: # Pass along the debug settings to the real client. self.real_client.debug = self.debug # Make an actual request since we can use the real HTTP client. self.last_request_was_live = True response = self.real_client.request(http_request) scrubbed_response = _scrub_response(response) self.add_response(request, scrubbed_response.status, scrubbed_response.reason, dict(atom.http_core.get_headers(scrubbed_response)), scrubbed_response.read()) # Return the recording which we just added. return self._recordings[-1][1] raise NoRecordingFound('No recoding was found for request: %s %s' % ( request.method, str(request.uri))) Request = request def _save_recordings(self, filename): recording_file = open(os.path.join(tempfile.gettempdir(), filename), 'wb') pickle.dump(self._recordings, recording_file) recording_file.close() def _load_recordings(self, filename): recording_file = open(os.path.join(tempfile.gettempdir(), filename), 'rb') self._recordings = pickle.load(recording_file) recording_file.close() def _delete_recordings(self, filename): full_path = os.path.join(tempfile.gettempdir(), filename) if os.path.exists(full_path): os.remove(full_path) def _load_or_use_client(self, filename, http_client): if os.path.exists(os.path.join(tempfile.gettempdir(), filename)): self._load_recordings(filename) else: self.real_client = http_client def use_cached_session(self, name=None, real_http_client=None): """Attempts to load recordings from a previous live request. If a temp file with the recordings exists, then it is used to fulfill requests. If the file does not exist, then a real client is used to actually make the desired HTTP requests. Requests and responses are recorded and will be written to the desired temprary cache file when close_session is called. Args: name: str (optional) The file name of session file to be used. The file is loaded from the temporary directory of this machine. If no name is passed in, a default name will be constructed using the cache_name_prefix, cache_case_name, and cache_test_name of this object. real_http_client: atom.http_core.HttpClient the real client to be used if the cached recordings are not found. If the default value is used, this will be an atom.http_core.HttpClient. """ if real_http_client is None: real_http_client = atom.http_core.HttpClient() if name is None: self._recordings_cache_name = self.get_cache_file_name() else: self._recordings_cache_name = name self._load_or_use_client(self._recordings_cache_name, real_http_client) def close_session(self): """Saves recordings in the temporary file named in use_cached_session.""" if self.real_client is not None: self._save_recordings(self._recordings_cache_name) def delete_session(self, name=None): """Removes recordings from a previous live request.""" if name is None: self._delete_recordings(self._recordings_cache_name) else: self._delete_recordings(name) def get_cache_file_name(self): return '%s.%s.%s' % (self.cache_name_prefix, self.cache_case_name, self.cache_test_name) def _dump(self): """Provides debug information in a string.""" output = 'MockHttpClient\n real_client: %s\n cache file name: %s\n' % ( self.real_client, self.get_cache_file_name()) output += ' recordings:\n' i = 0 for recording in self._recordings: output += ' recording %i is for: %s %s\n' % ( i, recording[0].method, str(recording[0].uri)) i += 1 return output def _match_request(http_request, stored_request): """Determines whether a request is similar enough to a stored request to cause the stored response to be returned.""" # Check to see if the host names match. if (http_request.uri.host is not None and http_request.uri.host != stored_request.uri.host): return False # Check the request path in the URL (/feeds/private/full/x) elif http_request.uri.path != stored_request.uri.path: return False # Check the method used in the request (GET, POST, etc.) elif http_request.method != stored_request.method: return False # If there is a gsession ID in either request, make sure that it is matched # exactly. elif ('gsessionid' in http_request.uri.query or 'gsessionid' in stored_request.uri.query): if 'gsessionid' not in stored_request.uri.query: return False elif 'gsessionid' not in http_request.uri.query: return False elif (http_request.uri.query['gsessionid'] != stored_request.uri.query['gsessionid']): return False # Ignores differences in the query params (?start-index=5&max-results=20), # the body of the request, the port number, HTTP headers, just to name a # few. return True def _scrub_request(http_request): """ Removes email address and password from a client login request. Since the mock server saves the request and response in plantext, sensitive information like the password should be removed before saving the recordings. At the moment only requests sent to a ClientLogin url are scrubbed. """ if (http_request and http_request.uri and http_request.uri.path and http_request.uri.path.endswith('ClientLogin')): # Remove the email and password from a ClientLogin request. http_request._body_parts = [] http_request.add_form_inputs( {'form_data': 'client login request has been scrubbed'}) else: # We can remove the body of the post from the recorded request, since # the request body is not used when finding a matching recording. http_request._body_parts = [] return http_request def _scrub_response(http_response): return http_response class EchoHttpClient(object): """Sends the request data back in the response. Used to check the formatting of the request as it was sent. Always responds with a 200 OK, and some information from the HTTP request is returned in special Echo-X headers in the response. The following headers are added in the response: 'Echo-Host': The host name and port number to which the HTTP connection is made. If no port was passed in, the header will contain host:None. 'Echo-Uri': The path portion of the URL being requested. /example?x=1&y=2 'Echo-Scheme': The beginning of the URL, usually 'http' or 'https' 'Echo-Method': The HTTP method being used, 'GET', 'POST', 'PUT', etc. """ def request(self, http_request): return self._http_request(http_request.uri, http_request.method, http_request.headers, http_request._body_parts) def _http_request(self, uri, method, headers=None, body_parts=None): body = io.StringIO() response = atom.http_core.HttpResponse(status=200, reason='OK', body=body) if headers is None: response._headers = {} else: # Copy headers from the request to the response but convert values to # strings. Server response headers always come in as strings, so an int # should be converted to a corresponding string when echoing. for header, value in headers.items(): response._headers[header] = str(value) response._headers['Echo-Host'] = '%s:%s' % (uri.host, str(uri.port)) response._headers['Echo-Uri'] = uri._get_relative_path() response._headers['Echo-Scheme'] = uri.scheme response._headers['Echo-Method'] = method for part in body_parts: if isinstance(part, str): body.write(part) elif hasattr(part, 'read'): body.write(part.read()) body.seek(0) return response class SettableHttpClient(object): """An HTTP Client which responds with the data given in set_response.""" def __init__(self, status, reason, body, headers): """Configures the response for the server. See set_response for details on the arguments to the constructor. """ self.set_response(status, reason, body, headers) self.last_request = None def set_response(self, status, reason, body, headers): """Determines the response which will be sent for each request. Args: status: An int for the HTTP status code, example: 200, 404, etc. reason: String for the HTTP reason, example: OK, NOT FOUND, etc. body: The body of the HTTP response as a string or a file-like object (something with a read method). headers: dict of strings containing the HTTP headers in the response. """ self.response = atom.http_core.HttpResponse(status=status, reason=reason, body=body) self.response._headers = headers.copy() def request(self, http_request): self.last_request = http_request return self.response class MockHttpResponse(atom.http_core.HttpResponse): def __init__(self, status=None, reason=None, headers=None, body=None): self._headers = headers or {} if status is not None: self.status = status if reason is not None: self.reason = reason if body is not None: # Instead of using a file-like object for the body, store as a string # so that reads can be repeated. if hasattr(body, 'read'): self._body = body.read() else: self._body = body def read(self): return self._body
unknown
codeparrot/codeparrot-clean
import tempfile import unittest from boto.compat import StringIO, six, json from textwrap import dedent from boto.cloudfront.distribution import Distribution class CloudfrontSignedUrlsTest(unittest.TestCase): cloudfront = True notdefault = True def setUp(self): self.pk_str = dedent(""" -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDA7ki9gI/lRygIoOjV1yymgx6FYFlzJ+z1ATMaLo57nL57AavW hb68HYY8EA0GJU9xQdMVaHBogF3eiCWYXSUZCWM/+M5+ZcdQraRRScucmn6g4EvY 2K4W2pxbqH8vmUikPxir41EeBPLjMOzKvbzzQy9e/zzIQVREKSp/7y1mywIDAQAB AoGABc7mp7XYHynuPZxChjWNJZIq+A73gm0ASDv6At7F8Vi9r0xUlQe/v0AQS3yc N8QlyR4XMbzMLYk3yjxFDXo4ZKQtOGzLGteCU2srANiLv26/imXA8FVidZftTAtL viWQZBVPTeYIA69ATUYPEq0a5u5wjGyUOij9OWyuy01mbPkCQQDluYoNpPOekQ0Z WrPgJ5rxc8f6zG37ZVoDBiexqtVShIF5W3xYuWhW5kYb0hliYfkq15cS7t9m95h3 1QJf/xI/AkEA1v9l/WN1a1N3rOK4VGoCokx7kR2SyTMSbZgF9IWJNOugR/WZw7HT njipO3c9dy1Ms9pUKwUF46d7049ck8HwdQJARgrSKuLWXMyBH+/l1Dx/I4tXuAJI rlPyo+VmiOc7b5NzHptkSHEPfR9s1OK0VqjknclqCJ3Ig86OMEtEFBzjZQJBAKYz 470hcPkaGk7tKYAgP48FvxRsnzeooptURW5E+M+PQ2W9iDPPOX9739+Xi02hGEWF B0IGbQoTRFdE4VVcPK0CQQCeS84lODlC0Y2BZv2JxW3Osv/WkUQ4dslfAQl1T303 7uwwr7XTroMv8dIFQIPreoPhRKmd/SbJzbiKfS/4QDhU -----END RSA PRIVATE KEY----- """) self.pk_id = "PK123456789754" self.dist = Distribution() self.canned_policy = ( '{"Statement":[{"Resource":' '"http://d604721fxaaqy9.cloudfront.net/horizon.jpg' '?large=yes&license=yes",' '"Condition":{"DateLessThan":{"AWS:EpochTime":1258237200}}}]}') self.custom_policy_1 = ( '{ \n' ' "Statement": [{ \n' ' "Resource":"http://d604721fxaaqy9.cloudfront.net/training/*", \n' ' "Condition":{ \n' ' "IpAddress":{"AWS:SourceIp":"145.168.143.0/24"}, \n' ' "DateLessThan":{"AWS:EpochTime":1258237200} \n' ' } \n' ' }] \n' '}\n') self.custom_policy_2 = ( '{ \n' ' "Statement": [{ \n' ' "Resource":"http://*", \n' ' "Condition":{ \n' ' "IpAddress":{"AWS:SourceIp":"216.98.35.1/32"},\n' ' "DateGreaterThan":{"AWS:EpochTime":1241073790},\n' ' "DateLessThan":{"AWS:EpochTime":1255674716}\n' ' } \n' ' }] \n' '}\n') def test_encode_custom_policy_1(self): """ Test base64 encoding custom policy 1 from Amazon's documentation. """ expected = ("eyAKICAgIlN0YXRlbWVudCI6IFt7IAogICAgICAiUmVzb3VyY2Ui" "OiJodHRwOi8vZDYwNDcyMWZ4YWFxeTkuY2xvdWRmcm9udC5uZXQv" "dHJhaW5pbmcvKiIsIAogICAgICAiQ29uZGl0aW9uIjp7IAogICAg" "ICAgICAiSXBBZGRyZXNzIjp7IkFXUzpTb3VyY2VJcCI6IjE0NS4x" "NjguMTQzLjAvMjQifSwgCiAgICAgICAgICJEYXRlTGVzc1RoYW4i" "OnsiQVdTOkVwb2NoVGltZSI6MTI1ODIzNzIwMH0gICAgICAKICAg" "ICAgfSAKICAgfV0gCn0K") encoded = self.dist._url_base64_encode(self.custom_policy_1) self.assertEqual(expected, encoded) def test_encode_custom_policy_2(self): """ Test base64 encoding custom policy 2 from Amazon's documentation. """ expected = ("eyAKICAgIlN0YXRlbWVudCI6IFt7IAogICAgICAiUmVzb3VyY2Ui" "OiJodHRwOi8vKiIsIAogICAgICAiQ29uZGl0aW9uIjp7IAogICAg" "ICAgICAiSXBBZGRyZXNzIjp7IkFXUzpTb3VyY2VJcCI6IjIxNi45" "OC4zNS4xLzMyIn0sCiAgICAgICAgICJEYXRlR3JlYXRlclRoYW4i" "OnsiQVdTOkVwb2NoVGltZSI6MTI0MTA3Mzc5MH0sCiAgICAgICAg" "ICJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTI1NTY3" "NDcxNn0KICAgICAgfSAKICAgfV0gCn0K") encoded = self.dist._url_base64_encode(self.custom_policy_2) self.assertEqual(expected, encoded) def test_sign_canned_policy(self): """ Test signing the canned policy from amazon's cloudfront documentation. """ expected = ("Nql641NHEUkUaXQHZINK1FZ~SYeUSoBJMxjdgqrzIdzV2gyEXPDN" "v0pYdWJkflDKJ3xIu7lbwRpSkG98NBlgPi4ZJpRRnVX4kXAJK6td" "Nx6FucDB7OVqzcxkxHsGFd8VCG1BkC-Afh9~lOCMIYHIaiOB6~5j" "t9w2EOwi6sIIqrg_") sig = self.dist._sign_string(self.canned_policy, private_key_string=self.pk_str) encoded_sig = self.dist._url_base64_encode(sig) self.assertEqual(expected, encoded_sig) def test_sign_canned_policy_pk_file(self): """ Test signing the canned policy from amazon's cloudfront documentation with a file object. """ expected = ("Nql641NHEUkUaXQHZINK1FZ~SYeUSoBJMxjdgqrzIdzV2gyEXPDN" "v0pYdWJkflDKJ3xIu7lbwRpSkG98NBlgPi4ZJpRRnVX4kXAJK6td" "Nx6FucDB7OVqzcxkxHsGFd8VCG1BkC-Afh9~lOCMIYHIaiOB6~5j" "t9w2EOwi6sIIqrg_") pk_file = tempfile.TemporaryFile() pk_file.write(self.pk_str) pk_file.seek(0) sig = self.dist._sign_string(self.canned_policy, private_key_file=pk_file) encoded_sig = self.dist._url_base64_encode(sig) self.assertEqual(expected, encoded_sig) def test_sign_canned_policy_pk_file_name(self): """ Test signing the canned policy from amazon's cloudfront documentation with a file name. """ expected = ("Nql641NHEUkUaXQHZINK1FZ~SYeUSoBJMxjdgqrzIdzV2gyEXPDN" "v0pYdWJkflDKJ3xIu7lbwRpSkG98NBlgPi4ZJpRRnVX4kXAJK6td" "Nx6FucDB7OVqzcxkxHsGFd8VCG1BkC-Afh9~lOCMIYHIaiOB6~5j" "t9w2EOwi6sIIqrg_") pk_file = tempfile.NamedTemporaryFile() pk_file.write(self.pk_str) pk_file.flush() sig = self.dist._sign_string(self.canned_policy, private_key_file=pk_file.name) encoded_sig = self.dist._url_base64_encode(sig) self.assertEqual(expected, encoded_sig) def test_sign_canned_policy_pk_file_like(self): """ Test signing the canned policy from amazon's cloudfront documentation with a file-like object (not a subclass of 'file' type) """ expected = ("Nql641NHEUkUaXQHZINK1FZ~SYeUSoBJMxjdgqrzIdzV2gyEXPDN" "v0pYdWJkflDKJ3xIu7lbwRpSkG98NBlgPi4ZJpRRnVX4kXAJK6td" "Nx6FucDB7OVqzcxkxHsGFd8VCG1BkC-Afh9~lOCMIYHIaiOB6~5j" "t9w2EOwi6sIIqrg_") pk_file = StringIO() pk_file.write(self.pk_str) pk_file.seek(0) sig = self.dist._sign_string(self.canned_policy, private_key_file=pk_file) encoded_sig = self.dist._url_base64_encode(sig) self.assertEqual(expected, encoded_sig) def test_sign_canned_policy_unicode(self): """ Test signing the canned policy from amazon's cloudfront documentation. """ expected = ("Nql641NHEUkUaXQHZINK1FZ~SYeUSoBJMxjdgqrzIdzV2gyEXPDN" "v0pYdWJkflDKJ3xIu7lbwRpSkG98NBlgPi4ZJpRRnVX4kXAJK6td" "Nx6FucDB7OVqzcxkxHsGFd8VCG1BkC-Afh9~lOCMIYHIaiOB6~5j" "t9w2EOwi6sIIqrg_") unicode_policy = six.text_type(self.canned_policy) sig = self.dist._sign_string(unicode_policy, private_key_string=self.pk_str) encoded_sig = self.dist._url_base64_encode(sig) self.assertEqual(expected, encoded_sig) def test_sign_custom_policy_1(self): """ Test signing custom policy 1 from amazon's cloudfront documentation. """ expected = ("cPFtRKvUfYNYmxek6ZNs6vgKEZP6G3Cb4cyVt~FjqbHOnMdxdT7e" "T6pYmhHYzuDsFH4Jpsctke2Ux6PCXcKxUcTIm8SO4b29~1QvhMl-" "CIojki3Hd3~Unxjw7Cpo1qRjtvrimW0DPZBZYHFZtiZXsaPt87yB" "P9GWnTQoaVysMxQ_") sig = self.dist._sign_string(self.custom_policy_1, private_key_string=self.pk_str) encoded_sig = self.dist._url_base64_encode(sig) self.assertEqual(expected, encoded_sig) def test_sign_custom_policy_2(self): """ Test signing custom policy 2 from amazon's cloudfront documentation. """ expected = ("rc~5Qbbm8EJXjUTQ6Cn0LAxR72g1DOPrTmdtfbWVVgQNw0q~KHUA" "mBa2Zv1Wjj8dDET4XSL~Myh44CLQdu4dOH~N9huH7QfPSR~O4tIO" "S1WWcP~2JmtVPoQyLlEc8YHRCuN3nVNZJ0m4EZcXXNAS-0x6Zco2" "SYx~hywTRxWR~5Q_") sig = self.dist._sign_string(self.custom_policy_2, private_key_string=self.pk_str) encoded_sig = self.dist._url_base64_encode(sig) self.assertEqual(expected, encoded_sig) def test_create_canned_policy(self): """ Test that a canned policy is generated correctly. """ url = "http://1234567.cloudfront.com/test_resource.mp3?dog=true" expires = 999999 policy = self.dist._canned_policy(url, expires) policy = json.loads(policy) self.assertEqual(1, len(policy.keys())) statements = policy["Statement"] self.assertEqual(1, len(statements)) statement = statements[0] resource = statement["Resource"] self.assertEqual(url, resource) condition = statement["Condition"] self.assertEqual(1, len(condition.keys())) date_less_than = condition["DateLessThan"] self.assertEqual(1, len(date_less_than.keys())) aws_epoch_time = date_less_than["AWS:EpochTime"] self.assertEqual(expires, aws_epoch_time) def test_custom_policy_expires_and_policy_url(self): """ Test that a custom policy can be created with an expire time and an arbitrary URL. """ url = "http://1234567.cloudfront.com/*" expires = 999999 policy = self.dist._custom_policy(url, expires=expires) policy = json.loads(policy) self.assertEqual(1, len(policy.keys())) statements = policy["Statement"] self.assertEqual(1, len(statements)) statement = statements[0] resource = statement["Resource"] self.assertEqual(url, resource) condition = statement["Condition"] self.assertEqual(1, len(condition.keys())) date_less_than = condition["DateLessThan"] self.assertEqual(1, len(date_less_than.keys())) aws_epoch_time = date_less_than["AWS:EpochTime"] self.assertEqual(expires, aws_epoch_time) def test_custom_policy_valid_after(self): """ Test that a custom policy can be created with a valid-after time and an arbitrary URL. """ url = "http://1234567.cloudfront.com/*" valid_after = 999999 policy = self.dist._custom_policy(url, valid_after=valid_after) policy = json.loads(policy) self.assertEqual(1, len(policy.keys())) statements = policy["Statement"] self.assertEqual(1, len(statements)) statement = statements[0] resource = statement["Resource"] self.assertEqual(url, resource) condition = statement["Condition"] self.assertEqual(2, len(condition.keys())) date_less_than = condition["DateLessThan"] date_greater_than = condition["DateGreaterThan"] self.assertEqual(1, len(date_greater_than.keys())) aws_epoch_time = date_greater_than["AWS:EpochTime"] self.assertEqual(valid_after, aws_epoch_time) def test_custom_policy_ip_address(self): """ Test that a custom policy can be created with an IP address and an arbitrary URL. """ url = "http://1234567.cloudfront.com/*" ip_range = "192.168.0.1" policy = self.dist._custom_policy(url, ip_address=ip_range) policy = json.loads(policy) self.assertEqual(1, len(policy.keys())) statements = policy["Statement"] self.assertEqual(1, len(statements)) statement = statements[0] resource = statement["Resource"] self.assertEqual(url, resource) condition = statement["Condition"] self.assertEqual(2, len(condition.keys())) ip_address = condition["IpAddress"] self.assertTrue("DateLessThan" in condition) self.assertEqual(1, len(ip_address.keys())) source_ip = ip_address["AWS:SourceIp"] self.assertEqual("%s/32" % ip_range, source_ip) def test_custom_policy_ip_range(self): """ Test that a custom policy can be created with an IP address and an arbitrary URL. """ url = "http://1234567.cloudfront.com/*" ip_range = "192.168.0.0/24" policy = self.dist._custom_policy(url, ip_address=ip_range) policy = json.loads(policy) self.assertEqual(1, len(policy.keys())) statements = policy["Statement"] self.assertEqual(1, len(statements)) statement = statements[0] resource = statement["Resource"] self.assertEqual(url, resource) condition = statement["Condition"] self.assertEqual(2, len(condition.keys())) self.assertTrue("DateLessThan" in condition) ip_address = condition["IpAddress"] self.assertEqual(1, len(ip_address.keys())) source_ip = ip_address["AWS:SourceIp"] self.assertEqual(ip_range, source_ip) def test_custom_policy_all(self): """ Test that a custom policy can be created with an IP address and an arbitrary URL. """ url = "http://1234567.cloudfront.com/test.txt" expires = 999999 valid_after = 111111 ip_range = "192.168.0.0/24" policy = self.dist._custom_policy(url, expires=expires, valid_after=valid_after, ip_address=ip_range) policy = json.loads(policy) self.assertEqual(1, len(policy.keys())) statements = policy["Statement"] self.assertEqual(1, len(statements)) statement = statements[0] resource = statement["Resource"] self.assertEqual(url, resource) condition = statement["Condition"] self.assertEqual(3, len(condition.keys())) #check expires condition date_less_than = condition["DateLessThan"] self.assertEqual(1, len(date_less_than.keys())) aws_epoch_time = date_less_than["AWS:EpochTime"] self.assertEqual(expires, aws_epoch_time) #check valid_after condition date_greater_than = condition["DateGreaterThan"] self.assertEqual(1, len(date_greater_than.keys())) aws_epoch_time = date_greater_than["AWS:EpochTime"] self.assertEqual(valid_after, aws_epoch_time) #check source ip address condition ip_address = condition["IpAddress"] self.assertEqual(1, len(ip_address.keys())) source_ip = ip_address["AWS:SourceIp"] self.assertEqual(ip_range, source_ip) def test_params_canned_policy(self): """ Test the correct params are generated for a canned policy. """ url = "http://d604721fxaaqy9.cloudfront.net/horizon.jpg?large=yes&license=yes" expire_time = 1258237200 expected_sig = ("Nql641NHEUkUaXQHZINK1FZ~SYeUSoBJMxjdgqrzIdzV2gyE" "XPDNv0pYdWJkflDKJ3xIu7lbwRpSkG98NBlgPi4ZJpRRnVX4" "kXAJK6tdNx6FucDB7OVqzcxkxHsGFd8VCG1BkC-Afh9~lOCM" "IYHIaiOB6~5jt9w2EOwi6sIIqrg_") signed_url_params = self.dist._create_signing_params(url, self.pk_id, expire_time, private_key_string=self.pk_str) self.assertEqual(3, len(signed_url_params)) self.assertEqual(signed_url_params["Expires"], "1258237200") self.assertEqual(signed_url_params["Signature"], expected_sig) self.assertEqual(signed_url_params["Key-Pair-Id"], "PK123456789754") def test_canned_policy(self): """ Generate signed url from the Example Canned Policy in Amazon's documentation. """ url = "http://d604721fxaaqy9.cloudfront.net/horizon.jpg?large=yes&license=yes" expire_time = 1258237200 expected_url = "http://d604721fxaaqy9.cloudfront.net/horizon.jpg?large=yes&license=yes&Expires=1258237200&Signature=Nql641NHEUkUaXQHZINK1FZ~SYeUSoBJMxjdgqrzIdzV2gyEXPDNv0pYdWJkflDKJ3xIu7lbwRpSkG98NBlgPi4ZJpRRnVX4kXAJK6tdNx6FucDB7OVqzcxkxHsGFd8VCG1BkC-Afh9~lOCMIYHIaiOB6~5jt9w2EOwi6sIIqrg_&Key-Pair-Id=PK123456789754" signed_url = self.dist.create_signed_url( url, self.pk_id, expire_time, private_key_string=self.pk_str) self.assertEqual(expected_url, signed_url)
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- import sys import logging from framework.transactions.context import TokuTransaction from website.app import init_app from website.models import NodeLog, Node from scripts import utils as script_utils from modularodm import Q logger = logging.getLogger(__name__) # Use a system to mark migrated nodes SYSTEM_TAG = 'migrated_logs' def get_all_parents(node): # return a list contains all possible forked_from and registered_from of the node to the very origin parent_list = [] while True: parent = get_parent(node) if parent is None: break parent_list.append(parent) node = parent return parent_list def get_parent(node): # detemine the latest action of the node that generate this node and return its parent if node.forked_from and node.registered_from: if node.forked_date > node.registered_date: return node.forked_from else: return node.registered_from elif node.forked_from and not node.registered_from: return node.forked_from elif node.registered_from and not node.forked_from: return node.registered_from else: return None def do_migration(records, dry=False): for node in records: logs = list(NodeLog.find(Q('was_connected_to', 'eq', node))) existing_logs = node.logs for log in logs: if not log.node__logged: continue log_node = log.node__logged[0] # if the log_node is not contained in the node parent list then it doesn't belong to this node if log_node not in get_all_parents(node): logger.info('Excluding log {} from list because it is not associated with node {}'.format(log, node)) logs.remove(log) with TokuTransaction(): node.logs = logs + existing_logs node.system_tags.append(SYSTEM_TAG) node_type = 'registration' if node.is_registration else 'fork' logger.info('Adding {} logs to {} {}'.format(len(logs), node_type, node)) if not dry: try: node.save() except Exception as err: logger.error('Could not update logs for node {} due to error'.format(node._id)) logger.exception(err) logger.error('Skipping...') def get_targets(): return Node.find( ( (Q('registered_from', 'ne', None) & Q('logs', 'eq', [])) | Q('forked_from', 'ne', None) ) & Q('is_deleted', 'ne', True) & Q('system_tags', 'ne', SYSTEM_TAG) ) def main(): init_app(routes=False) # Sets the storage backends on all models dry = 'dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) do_migration(get_targets(), dry) if __name__ == '__main__': main()
unknown
codeparrot/codeparrot-clean
# Copyright 2017, Google, Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TODO: Import the storage module from quiz.gcp import datastore # END TODO """ uploads file into google cloud storage - upload file - return public_url """ def upload_file(image_file, public): if not image_file: return None # TODO: Use the storage client to Upload the file # The second argument is a boolean # END TODO # TODO: Return the public URL # for the object return u'' # END TODO """ uploads file into google cloud storage - call method to upload file (public=true) - call datastore helper method to save question """ def save_question(data, image_file): # TODO: If there is an image file, then upload it # And assign the result to a new Datastore property imageUrl # If there isn't, assign an empty string # END TODO data['correctAnswer'] = int(data['correctAnswer']) datastore.save_question(data) return
unknown
codeparrot/codeparrot-clean
# Owner(s): ["module: PrivateUse1"] import sys import torch from torch.testing._internal.common_utils import run_tests, skipIfTorchDynamo, TestCase class DummyPrivateUse1Module: @staticmethod def is_available(): return True @staticmethod def is_autocast_enabled(): return True @staticmethod def get_autocast_dtype(): return torch.float16 @staticmethod def set_autocast_enabled(enable): pass @staticmethod def set_autocast_dtype(dtype): pass @staticmethod def get_amp_supported_dtype(): return [torch.float16] class TestExtensionUtils(TestCase): def tearDown(self): # Clean up backend_name = torch._C._get_privateuse1_backend_name() if hasattr(torch, backend_name): delattr(torch, backend_name) if f"torch.{backend_name}" in sys.modules: del sys.modules[f"torch.{backend_name}"] def test_external_module_register(self): # Built-in module with self.assertRaisesRegex(RuntimeError, "The runtime module of"): torch._register_device_module("cuda", torch.cuda) # Wrong device type with self.assertRaisesRegex(RuntimeError, "Expected one of cpu"): torch._register_device_module("dummmy", DummyPrivateUse1Module) with self.assertRaises(AttributeError): torch.privateuseone.is_available() # type: ignore[attr-defined] torch._register_device_module("privateuseone", DummyPrivateUse1Module) torch.privateuseone.is_available() # type: ignore[attr-defined] # No supporting for override with self.assertRaisesRegex(RuntimeError, "The runtime module of"): torch._register_device_module("privateuseone", DummyPrivateUse1Module) @skipIfTorchDynamo( "accelerator doesn't compose with privateuse1 : https://github.com/pytorch/pytorch/issues/166696" ) def test_external_module_register_with_renamed_backend(self): torch.utils.rename_privateuse1_backend("foo") with self.assertRaisesRegex(RuntimeError, "has already been set"): torch.utils.rename_privateuse1_backend("dummmy") custom_backend_name = torch._C._get_privateuse1_backend_name() self.assertEqual(custom_backend_name, "foo") with self.assertRaises(AttributeError): torch.foo.is_available() # type: ignore[attr-defined] with self.assertRaisesRegex(AssertionError, "Tried to use AMP with the"): with torch.autocast(device_type=custom_backend_name): pass torch._register_device_module("foo", DummyPrivateUse1Module) torch.foo.is_available() # type: ignore[attr-defined] with torch.autocast(device_type=custom_backend_name): pass self.assertEqual(torch._utils._get_device_index("foo:1"), 1) self.assertEqual(torch._utils._get_device_index(torch.device("foo:2")), 2) if __name__ == "__main__": run_tests()
python
github
https://github.com/pytorch/pytorch
test/test_extension_utils.py
from __future__ import absolute_import from __future__ import print_function from typing import Any from argparse import ArgumentParser from optparse import make_option from django.core.management.base import BaseCommand from zerver.lib.actions import do_remove_subscription from zerver.models import Realm, UserProfile, get_realm, get_stream, \ get_user_profile_by_email class Command(BaseCommand): help = """Remove some or all users in a realm from a stream.""" option_list = BaseCommand.option_list + ( make_option('-d', '--domain', dest='domain', type='str', help='The name of the realm in which you are removing people.'), make_option('-s', '--stream', dest='stream', type='str', help='A stream name.'), make_option('-u', '--users', dest='users', type='str', help='A comma-separated list of email addresses.'), make_option('-a', '--all-users', dest='all_users', action="store_true", default=False, help='Remove all users in this realm from this stream.'), ) def handle(self, **options): # type: (*Any, **Any) -> None if options["domain"] is None or options["stream"] is None or \ (options["users"] is None and options["all_users"] is None): self.print_help("python manage.py", "remove_users_from_stream") exit(1) realm = get_realm(options["domain"]) stream_name = options["stream"].strip() stream = get_stream(stream_name, realm) if options["all_users"]: user_profiles = UserProfile.objects.filter(realm=realm) else: emails = set([email.strip() for email in options["users"].split(",")]) user_profiles = [] for email in emails: user_profiles.append(get_user_profile_by_email(email)) for user_profile in user_profiles: did_remove = do_remove_subscription(user_profile, stream) print("%s %s from %s" % ( "Removed" if did_remove else "Couldn't remove", user_profile.email, stream_name))
unknown
codeparrot/codeparrot-clean
"""Support for reading data from a serial port.""" import asyncio import json import logging from serial import SerialException import serial_asyncio import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME, CONF_VALUE_TEMPLATE, EVENT_HOMEASSISTANT_STOP from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) CONF_SERIAL_PORT = "serial_port" CONF_BAUDRATE = "baudrate" CONF_BYTESIZE = "bytesize" CONF_PARITY = "parity" CONF_STOPBITS = "stopbits" CONF_XONXOFF = "xonxoff" CONF_RTSCTS = "rtscts" CONF_DSRDTR = "dsrdtr" DEFAULT_NAME = "Serial Sensor" DEFAULT_BAUDRATE = 9600 DEFAULT_BYTESIZE = serial_asyncio.serial.EIGHTBITS DEFAULT_PARITY = serial_asyncio.serial.PARITY_NONE DEFAULT_STOPBITS = serial_asyncio.serial.STOPBITS_ONE DEFAULT_XONXOFF = False DEFAULT_RTSCTS = False DEFAULT_DSRDTR = False PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_SERIAL_PORT): cv.string, vol.Optional(CONF_BAUDRATE, default=DEFAULT_BAUDRATE): cv.positive_int, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_BYTESIZE, default=DEFAULT_BYTESIZE): vol.In( [ serial_asyncio.serial.FIVEBITS, serial_asyncio.serial.SIXBITS, serial_asyncio.serial.SEVENBITS, serial_asyncio.serial.EIGHTBITS, ] ), vol.Optional(CONF_PARITY, default=DEFAULT_PARITY): vol.In( [ serial_asyncio.serial.PARITY_NONE, serial_asyncio.serial.PARITY_EVEN, serial_asyncio.serial.PARITY_ODD, serial_asyncio.serial.PARITY_MARK, serial_asyncio.serial.PARITY_SPACE, ] ), vol.Optional(CONF_STOPBITS, default=DEFAULT_STOPBITS): vol.In( [ serial_asyncio.serial.STOPBITS_ONE, serial_asyncio.serial.STOPBITS_ONE_POINT_FIVE, serial_asyncio.serial.STOPBITS_TWO, ] ), vol.Optional(CONF_XONXOFF, default=DEFAULT_XONXOFF): cv.boolean, vol.Optional(CONF_RTSCTS, default=DEFAULT_RTSCTS): cv.boolean, vol.Optional(CONF_DSRDTR, default=DEFAULT_DSRDTR): cv.boolean, } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Serial sensor platform.""" name = config.get(CONF_NAME) port = config.get(CONF_SERIAL_PORT) baudrate = config.get(CONF_BAUDRATE) bytesize = config.get(CONF_BYTESIZE) parity = config.get(CONF_PARITY) stopbits = config.get(CONF_STOPBITS) xonxoff = config.get(CONF_XONXOFF) rtscts = config.get(CONF_RTSCTS) dsrdtr = config.get(CONF_DSRDTR) value_template = config.get(CONF_VALUE_TEMPLATE) if value_template is not None: value_template.hass = hass sensor = SerialSensor( name, port, baudrate, bytesize, parity, stopbits, xonxoff, rtscts, dsrdtr, value_template, ) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, sensor.stop_serial_read) async_add_entities([sensor], True) class SerialSensor(Entity): """Representation of a Serial sensor.""" def __init__( self, name, port, baudrate, bytesize, parity, stopbits, xonxoff, rtscts, dsrdtr, value_template, ): """Initialize the Serial sensor.""" self._name = name self._state = None self._port = port self._baudrate = baudrate self._bytesize = bytesize self._parity = parity self._stopbits = stopbits self._xonxoff = xonxoff self._rtscts = rtscts self._dsrdtr = dsrdtr self._serial_loop_task = None self._template = value_template self._attributes = None async def async_added_to_hass(self): """Handle when an entity is about to be added to Home Assistant.""" self._serial_loop_task = self.hass.loop.create_task( self.serial_read( self._port, self._baudrate, self._bytesize, self._parity, self._stopbits, self._xonxoff, self._rtscts, self._dsrdtr, ) ) async def serial_read( self, device, baudrate, bytesize, parity, stopbits, xonxoff, rtscts, dsrdtr, **kwargs, ): """Read the data from the port.""" logged_error = False while True: try: reader, _ = await serial_asyncio.open_serial_connection( url=device, baudrate=baudrate, bytesize=bytesize, parity=parity, stopbits=stopbits, xonxoff=xonxoff, rtscts=rtscts, dsrdtr=dsrdtr, **kwargs, ) except SerialException as exc: if not logged_error: _LOGGER.exception( "Unable to connect to the serial device %s: %s. Will retry", device, exc, ) logged_error = True await self._handle_error() else: _LOGGER.info("Serial device %s connected", device) while True: try: line = await reader.readline() except SerialException as exc: _LOGGER.exception( "Error while reading serial device %s: %s", device, exc ) await self._handle_error() break else: line = line.decode("utf-8").strip() try: data = json.loads(line) except ValueError: pass else: if isinstance(data, dict): self._attributes = data if self._template is not None: line = self._template.async_render_with_possible_json_value( line ) _LOGGER.debug("Received: %s", line) self._state = line self.async_write_ha_state() async def _handle_error(self): """Handle error for serial connection.""" self._state = None self._attributes = None self.async_write_ha_state() await asyncio.sleep(5) @callback def stop_serial_read(self, event): """Close resources.""" if self._serial_loop_task: self._serial_loop_task.cancel() @property def name(self): """Return the name of the sensor.""" return self._name @property def should_poll(self): """No polling needed.""" return False @property def device_state_attributes(self): """Return the attributes of the entity (if any JSON present).""" return self._attributes @property def state(self): """Return the state of the sensor.""" return self._state
unknown
codeparrot/codeparrot-clean
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This file lives in the runtime package // so we can get access to the runtime guts. // The rest of the implementation of this test is in align_test.go. package runtime import "unsafe" // AtomicFields is the set of fields on which we perform 64-bit atomic // operations (all the *64 operations in internal/runtime/atomic). var AtomicFields = []uintptr{ unsafe.Offsetof(m{}.procid), unsafe.Offsetof(profBuf{}.overflow), unsafe.Offsetof(profBuf{}.overflowTime), unsafe.Offsetof(heapStatsDelta{}.tinyAllocCount), unsafe.Offsetof(heapStatsDelta{}.smallAllocCount), unsafe.Offsetof(heapStatsDelta{}.smallFreeCount), unsafe.Offsetof(heapStatsDelta{}.largeAlloc), unsafe.Offsetof(heapStatsDelta{}.largeAllocCount), unsafe.Offsetof(heapStatsDelta{}.largeFree), unsafe.Offsetof(heapStatsDelta{}.largeFreeCount), unsafe.Offsetof(heapStatsDelta{}.committed), unsafe.Offsetof(heapStatsDelta{}.released), unsafe.Offsetof(heapStatsDelta{}.inHeap), unsafe.Offsetof(heapStatsDelta{}.inStacks), unsafe.Offsetof(heapStatsDelta{}.inWorkBufs), unsafe.Offsetof(lfnode{}.next), unsafe.Offsetof(mstats{}.last_gc_nanotime), unsafe.Offsetof(mstats{}.last_gc_unix), unsafe.Offsetof(workType{}.bytesMarked), } // AtomicVariables is the set of global variables on which we perform // 64-bit atomic operations. var AtomicVariables = []unsafe.Pointer{ unsafe.Pointer(&ncgocall), unsafe.Pointer(&test_z64), unsafe.Pointer(&blockprofilerate), unsafe.Pointer(&mutexprofilerate), unsafe.Pointer(&gcController), unsafe.Pointer(&memstats), unsafe.Pointer(&sched), unsafe.Pointer(&ticks), unsafe.Pointer(&work), }
go
github
https://github.com/golang/go
src/runtime/align_runtime_test.go
# The original Tempita implements all of its templating code here. # Moved it to _tempita.py to make the compilation portable. from ._tempita import *
python
github
https://github.com/numpy/numpy
numpy/_build_utils/tempita/__init__.py
/* contrib/amcheck/amcheck--1.3--1.4.sql */ -- complain if script is sourced in psql, rather than via CREATE EXTENSION \echo Use "ALTER EXTENSION amcheck UPDATE TO '1.4'" to load this file. \quit -- In order to avoid issues with dependencies when updating amcheck to 1.4, -- create new, overloaded versions of the 1.2 bt_index_parent_check signature, -- and 1.1 bt_index_check signature. -- -- bt_index_parent_check() -- CREATE FUNCTION bt_index_parent_check(index regclass, heapallindexed boolean, rootdescend boolean, checkunique boolean) RETURNS VOID AS 'MODULE_PATHNAME', 'bt_index_parent_check' LANGUAGE C STRICT PARALLEL RESTRICTED; -- -- bt_index_check() -- CREATE FUNCTION bt_index_check(index regclass, heapallindexed boolean, checkunique boolean) RETURNS VOID AS 'MODULE_PATHNAME', 'bt_index_check' LANGUAGE C STRICT PARALLEL RESTRICTED; -- We don't want this to be available to public REVOKE ALL ON FUNCTION bt_index_parent_check(regclass, boolean, boolean, boolean) FROM PUBLIC; REVOKE ALL ON FUNCTION bt_index_check(regclass, boolean, boolean) FROM PUBLIC;
sql
github
https://github.com/postgres/postgres
contrib/amcheck/amcheck--1.3--1.4.sql
% This is generated by ESQL's AbstractFunctionTestCase. Do not edit it. See ../README.md for how to regenerate it. **Description** Converts a multivalued expression into a single valued column containing the first value. This is most useful when reading from a function that emits multivalued columns in a known order like [`SPLIT`](/reference/query-languages/esql/functions-operators/string-functions.md#esql-split). The order that [multivalued fields](/reference/query-languages/esql/esql-multivalued-fields.md) are read from underlying storage is not guaranteed. It is **frequently** ascending, but don’t rely on that. If you need the minimum value use [`MV_MIN`](/reference/query-languages/esql/functions-operators/mv-functions.md#esql-mv_min) instead of `MV_FIRST`. `MV_MIN` has optimizations for sorted values so there isn’t a performance benefit to `MV_FIRST`.
unknown
github
https://github.com/elastic/elasticsearch
docs/reference/query-languages/esql/_snippets/functions/description/mv_first.md
function useSomething() { useLayoutEffect({ "useSomething.useLayoutEffect": ()=>{} }["useSomething.useLayoutEffect"]); useEffect({ "useSomething.useEffect": ()=>{} }["useSomething.useEffect"]); const onClick = useCallback({ "useSomething.useCallback[onClick]": ()=>[] }["useSomething.useCallback[onClick]"]); const computed = useMemo({ "useSomething.useMemo[computed]": ()=>{} }["useSomething.useMemo[computed]"]); }
javascript
github
https://github.com/vercel/next.js
crates/next-custom-transforms/tests/fixture/debug-fn-name/composite-hook/output.js
#!/bin/bash set -ex # MKL MKL_VERSION=2024.2.0 MKLROOT=/opt/intel mkdir -p ${MKLROOT} pushd /tmp python3 -mpip install wheel python3 -mpip download -d . mkl-static==${MKL_VERSION} python3 -m wheel unpack mkl_static-${MKL_VERSION}-py2.py3-none-manylinux1_x86_64.whl python3 -m wheel unpack mkl_include-${MKL_VERSION}-py2.py3-none-manylinux1_x86_64.whl mv mkl_static-${MKL_VERSION}/mkl_static-${MKL_VERSION}.data/data/lib ${MKLROOT} mv mkl_include-${MKL_VERSION}/mkl_include-${MKL_VERSION}.data/data/include ${MKLROOT}
unknown
github
https://github.com/pytorch/pytorch
.ci/docker/common/install_mkl.sh
/* * Low level 3-way in-core file merge. */ #ifndef LL_MERGE_H #define LL_MERGE_H #include "xdiff/xdiff.h" /** * * Calling sequence: * ---------------- * * - Prepare a `struct ll_merge_options` to record options. * If you have no special requests, skip this and pass `NULL` * as the `opts` parameter to use the default options. * * - Allocate an mmbuffer_t variable for the result. * * - Allocate and fill variables with the file's original content * and two modified versions (using `read_mmfile`, for example). * * - Call `ll_merge()`. * * - Read the merged content from `result_buf.ptr` and `result_buf.size`. * * - Release buffers when finished. A simple * `free(ancestor.ptr); free(ours.ptr); free(theirs.ptr); * free(result_buf.ptr);` will do. * * If the modifications do not merge cleanly, `ll_merge` will return a * nonzero value and `result_buf` will generally include a description of * the conflict bracketed by markers such as the traditional `<<<<<<<` * and `>>>>>>>`. * * The `ancestor_label`, `our_label`, and `their_label` parameters are * used to label the different sides of a conflict if the merge driver * supports this. */ struct index_state; /** * This describes the set of options the calling program wants to affect * the operation of a low-level (single file) merge. */ struct ll_merge_options { /** * Behave as though this were part of a merge between common ancestors in * a recursive merge (merges of binary files may need to be handled * differently in such cases, for example). If a helper program is * specified by the `[merge "<driver>"] recursive` configuration, it will * be used. */ unsigned virtual_ancestor : 1; /** * Resolve local conflicts automatically in favor of one side or the other * (as in 'git merge-file' `--ours`/`--theirs`/`--union`). Can be `0`, * `XDL_MERGE_FAVOR_OURS`, `XDL_MERGE_FAVOR_THEIRS`, * or `XDL_MERGE_FAVOR_UNION`. */ unsigned variant : 2; /** * Resmudge and clean the "base", "theirs" and "ours" files before merging. * Use this when the merge is likely to have overlapped with a change in * smudge/clean or end-of-line normalization rules. */ unsigned renormalize : 1; /** * Increase the length of conflict markers so that nested conflicts  * can be differentiated. */ unsigned extra_marker_size; /* Override the global conflict style. */ int conflict_style; /* Extra xpparam_t flags as defined in xdiff/xdiff.h. */ long xdl_opts; }; #define LL_MERGE_OPTIONS_INIT { .conflict_style = -1 } enum ll_merge_result { LL_MERGE_ERROR = -1, LL_MERGE_OK = 0, LL_MERGE_CONFLICT, LL_MERGE_BINARY_CONFLICT, }; /** * Perform a three-way single-file merge in core. This is a thin wrapper * around `xdl_merge` that takes the path and any merge backend specified in * `.gitattributes` or `.git/info/attributes` into account. * Returns 0 for a clean merge. */ enum ll_merge_result ll_merge(mmbuffer_t *result_buf, const char *path, mmfile_t *ancestor, const char *ancestor_label, mmfile_t *ours, const char *our_label, mmfile_t *theirs, const char *their_label, struct index_state *istate, const struct ll_merge_options *opts); int ll_merge_marker_size(struct index_state *istate, const char *path); void reset_merge_attributes(void); #endif
c
github
https://github.com/git/git
merge-ll.h
import ddapp.visualization as vis from ddapp import filterUtils import ddapp.vtkAll as vtk import ddapp.vtkNumpy as vnp from ddapp.shallowCopy import shallowCopy from ddapp import ioUtils import numpy as np def createTexturedPlane(): source = vtk.vtkPlaneSource() textureMap = vtk.vtkTextureMapToPlane() textureMap.SetInput(source.GetOutput()) textureMap.Update() return shallowCopy(textureMap.GetOutput()) def getSkyboxSides(): return ['top', 'bottom', 'front', 'back', 'left', 'right'] def createSkyboxPlane(side): pd = createTexturedPlane() t = vtk.vtkTransform() t.PostMultiply() if side == 'top': t.Translate(0,0,0.5) t.RotateZ(180) elif side == 'bottom': t.RotateX(180) t.RotateY(180) t.RotateZ(-270) t.Translate(0,0,-0.5) elif side == 'front': t.RotateY(90) t.RotateX(90) t.RotateZ(180) t.Translate(0.5,0.0,0.0) elif side == 'back': t.RotateY(90) t.RotateX(90) t.RotateZ(0) t.Translate(-0.5,0.0,0.0) elif side == 'left': t.RotateY(90) t.RotateX(90) t.RotateZ(-90) t.Translate(0.0,0.5,0.0) elif side == 'right': t.RotateY(90) t.RotateX(90) t.RotateZ(90) t.Translate(0.0,-0.5,0.0) pd = filterUtils.transformPolyData(pd, t) return pd def createSkyboxPlanes(): planes = {} for side in getSkyboxSides(): planes[side] = createSkyboxPlane(side) return planes def createTexture(imageFilename): image = ioUtils.readImage(imageFilename) tex = vtk.vtkTexture() tex.SetInput(image) tex.EdgeClampOn() tex.RepeatOff() return tex def createSkybox(imageMap, view): objs = {} planes = createSkyboxPlanes() for side, imageFilename in imageMap.iteritems(): texture = createTexture(imageFilename) obj = vis.PolyDataItem('skybox %s' % side, planes[side], view=None) obj.actor.SetTexture(texture) obj.actor.GetProperty().LightingOff() view.backgroundRenderer().AddActor(obj.actor) objs[side] = obj return objs def getSkyboxImages(baseDir): imageMap = dict( top = baseDir + '/topmars1.jpg', bottom = baseDir + '/botmars1.jpg', front = baseDir + '/frontmars1.jpg', back = baseDir + '/backmars1.jpg', left = baseDir + '/leftmars1.jpg', right = baseDir + '/rightmars1.jpg') return imageMap def createTextureGround(imageFilename, view): pd = createTexturedPlane() texture = createTexture(imageFilename) texture.RepeatOn() tcoords = vnp.getNumpyFromVtk(pd, 'Texture Coordinates') tcoords *= 60 t = vtk.vtkTransform() t.PostMultiply() t.Scale(200,200,200) t.Translate(0,0,-0.005) pd = filterUtils.transformPolyData(pd, t) obj = vis.showPolyData(pd, 'ground', view=view, alpha=1.0, parent='skybox') obj.actor.SetTexture(texture) obj.actor.GetProperty().LightingOff() def connectSkyboxCamera(view, debug=False): baseRen = view.backgroundRenderer() def updateSkyboxCamera(o, e): c = baseRen.GetActiveCamera() c2 = view.camera() viewDirection = np.array(c2.GetFocalPoint()) - np.array(c2.GetPosition()) viewDirection /= np.linalg.norm(viewDirection) if debug: c.SetPosition(c2.GetPosition()) c.SetFocalPoint(c2.GetFocalPoint()) else: c.SetPosition(0,0,0) c.SetFocalPoint(viewDirection) c.SetViewUp(c2.GetViewUp()) c.SetViewAngle(c2.GetViewAngle()) view.renderWindow().AddObserver('StartEvent', updateSkyboxCamera)
unknown
codeparrot/codeparrot-clean
'''Handling HBNL files ''' import os import shutil import subprocess from collections import OrderedDict from datetime import datetime import h5py import numpy as np import pandas as pd import db.database as D from .utils.compilation import join_allcols, extract_session_fromuID, join_ufields, column_split from .utils.filename_parsing import parse_filename, system_shorthands from .utils.records import unflatten_dict def next_file_with_base(directory, base, ext): ''' given directory, base filename, and extension, return the next file of its type ''' files = [f for f in os.listdir(directory) if base in f and '.' + ext in f] if files: numbers = [int(os.path.splitext(f)[0].split('_')[-1]) for f in files] next_num = max(numbers) + 1 else: next_num = 1 next_file = base + '_' + str(next_num) + '.' + ext return next_file ############################## ## # EEG ## ############################## class RestingDAT: ''' represents David's files containing estimates of resting state power for various frequency bands and bipolar derived channels ''' bands = ['3-5', '5-7', '7-9', '9-12', '12-16', '16-20', '20-28'] channels = ['FP1-F3', 'FP2-F4', 'FP1-F7', 'FP2-F8', 'F7-F3', 'F8-F4', 'F7-T7', 'F8-T8', 'F3-C3', 'F4-C4', 'FZ-CZ', 'CZ-PZ', 'T7-C3', 'T8-C4', 'T7-P7', 'T8-P8', 'C3-P3', 'C4-P4', 'P7-P3', 'P8-P4', 'P7-O1', 'P8-O2', 'P3-O1', 'P4-O2', 'PZ-O1', 'PZ-O2', 'O1-O2', 'CZ-C3', 'CZ-C4', 'PZ-P3', 'PZ-P4', 'F7-C3', 'F8-C4', 'FP1-FP2', 'F3-FZ', 'FZ-F4', ] columns = ['uID', 'age'] for band in bands: for chan in channels: columns.append('_'.join((chan, band))) def __init__(s, path): s.path = path def ns_to_dataframe(s): file_df = pd.read_csv(s.path, delim_whitespace=True, header=None) file_df.columns = s.columns file_df['session'] = file_df['uID'].apply(extract_session_fromuID) file_df['ID'] = file_df['uID'].apply(column_split, args=[1, '_']) file_df.set_index(['ID', 'session'], drop=False, inplace=True) file_df['uID_hbnl'] = file_df['uID'] file_df['uID'] = file_df[['ID', 'session']].apply(join_allcols, axis=1) s.file_df = file_df def mc_to_dataframe(s, session): s.columns[0] = 'ID' file_df = pd.read_csv(s.path, delim_whitespace=True, header=None) file_df.columns = s.columns file_df['ID'] = file_df['ID'].apply(int).apply(str) file_df['session'] = session file_df.set_index(['ID', 'session'], drop=False, inplace=True) file_df['uID'] = file_df[['ID', 'session']].apply(join_allcols, axis=1) s.file_df = file_df class CNTH1_File: def __init__(s, filepath): s.filepath = filepath s.filename = os.path.split(filepath)[1] s.file_info = parse_filename(s.filename) def parse_fileDB(s): ''' prepare the data field for the database object ''' s.data = {} s.data.update(s.file_info) s.data.update({'filepath': s.filepath}) s.data['ID'] = s.data['id'] def read_trial_info(s, nlines=-1): h5header = subprocess.check_output( ['/opt/bin/print_h5_header', s.filepath]) head_lines = h5header.decode().split('\n') hD = {} for L in head_lines[:nlines]: if L[:8] == 'category': cat = L[9:].split('"')[1] hD[cat] = {} curD = hD[cat] elif L[:len(cat)] == cat: subcat = L.split(cat)[1].strip() hD[cat][subcat] = {} curD = hD[cat][subcat] else: parts = L.split(';') var = parts[0].split('"')[1] val = parse_maybe_numeric(parts[1].split(',')[0].strip()) curD[var] = val s.trial_info = hD def parse_maybe_numeric(st): proc = st.replace('-', '') dec = False if '.' in st: dec = True proc = st.replace('.', '') if proc.isnumeric(): if dec: return float(st) else: return int(st) return st def extract_case_tuple(path): ''' given a path to an .avg.h1 file, extract a case tuple for comparison ''' f = h5py.File(path, 'r') case_info = f['file']['run']['case']['case'][:] case_lst = [] for case in case_info: index = case[0][0] type_letter = case[-3][0].decode() type_word = case[-2][0].decode() case_lst.append((index, type_letter, type_word)) case_tup = tuple(case_lst) return case_tup class AVGH1_File(CNTH1_File): ''' represents *.avg.h1 files, mostly for the behavioral info inside ''' min_resptime = 100 trial_columns = ['Trial', 'Case Index', 'Response Code', 'Stimulus', 'Correct', 'Omitted', 'Artifact Present', 'Accepted', 'Max Amp in Threshold Window', 'Threshold', 'Reaction Time (ms)', 'Time (s)'] def __init__(s, filepath): s.filepath = filepath CNTH1_File.__init__(s, filepath) path_parts = filepath.split(os.path.sep) system_letters = path_parts[-2][:2] s.file_info['system'] = system_shorthands[system_letters] s.data = {'uID': s.file_info['id'] + '_' + s.file_info['session']} def fix_ant(s): case_tup = extract_case_tuple(s.filepath) try: ind = MT_File.ant_cases_types_lk.index(case_tup) except IndexError: print('case info unexpected') return if ind > 0: for type_ind in range(4): s.case_dict[type_ind]['code'] = 'JPAW'[type_ind] def parse_behav_forDB(s, general_info=False): ''' wrapper for main function that also prepares for DB insert ''' # s.data = {} # experiment specific stuff if s.file_info['system'] == 'masscomp': s.load_data_mc() if s.file_info['experiment'] == 'ant': s.fix_ant() s.calc_results_mc() elif s.file_info['system'] == 'neuroscan': s.load_data() s.parse_seq() s.calc_results() # puts behavioral results in s.results else: print('system not recognized') return s.data[s.exp] = unflatten_dict(s.results) s.data[s.exp]['filepath'] = s.filepath s.data[s.exp]['run'] = s.file_info.pop('run') s.data[s.exp]['version'] = s.file_info.pop('version') # ID-session specific stuff s.data.update(s.file_info) s.data['ID'] = s.data['id'] # s.data['uID'] = s.data['ID']+'_'+s.data['session'] del s.data['experiment'] if not general_info: s.data = {s.exp: s.data[s.exp], 'uID': s.data['uID']} def calc_results(s): ''' calculates accuracy and reaction time from the event table ''' results = {} for t, t_attrs in s.case_dict.items(): nm = t_attrs['code'] stmevs = s.ev_df['type_seq'] == t if t_attrs['corr_resp'] == 0: # no response required correct = s.ev_df.loc[stmevs, 'correct'] results[nm + '_acc'] = np.sum(correct) / np.sum(stmevs) continue # response required rspevs = (np.roll(stmevs, 1)) & (s.ev_df['resp_seq'] != 0) correct_late = rspevs & (s.ev_df['correct']) correct = correct_late & ~(s.ev_df['late']) results[nm + '_acc'] = np.sum(correct) / np.sum(stmevs) results[nm + '_accwithlate'] = np.sum(correct_late) / np.sum(stmevs) results[nm + '_medianrt'] = s.ev_df.loc[correct, 'rt'].median() results[nm + '_medianrtwithlate'] = \ s.ev_df.loc[correct_late, 'rt'].median() # for certain experiments, keep track of noresp info if s.file_info['experiment'] in ['ant', 'ern', 'stp']: noresp = s.ev_df.loc[stmevs, 'noresp'] results[nm + '_noresp'] = np.sum(noresp) / np.sum(stmevs) results[nm + '_accwithresp'] = np.sum(correct) / \ (np.sum(stmevs) - np.sum(noresp)) results[nm + '_accwithrespwithlate'] = np.sum(correct_late) / \ (np.sum(stmevs) - np.sum(noresp)) # this part logs the median reaction time for each type of response # (i.e. both for correct and incorrect responses) for rc in s.acceptable_resps: tmp_df = s.ev_df[(s.ev_df['resp_seq'] == rc) & ~(s.ev_df['early']) & ~(s.ev_df['errant'])] results[nm + str(rc) + '_medianrtwithlate'] = \ tmp_df['rt'].median() tmp_df2 = tmp_df[~tmp_df['late']] results[nm + str(rc) + '_medianrt'] = tmp_df2['rt'].median() s.results = results def calc_results_mc(s): results = {} for t, t_attrs in s.case_dict.items(): nm = t_attrs['code'] case_trials = s.trial_df[s.trial_df['Stimulus'] == t] try: results[nm + '_acc'] = sum(case_trials['Correct']) / case_trials.shape[0] except ZeroDivisionError: results[nm + '_acc'] = np.nan if t_attrs['corr_resp'] != 0: # response required case_trials.drop(case_trials[~case_trials['Correct']].index, inplace=True) results[nm + '_medianrt'] = case_trials['Reaction Time (ms)'].median() s.results = results def load_data(s): ''' prepare needed data from the h5py pointer ''' f = h5py.File(s.filepath) s.exp = f['file/experiment/experiment'][0][-3][0].decode() s.case_dict = {} for column in f['file/run/case/case']: s.case_dict.update({column[3][0]: {'code': column[-3][0].decode(), 'descriptor': column[-2][0].decode(), 'corr_resp': column[4][0], 'resp_win': column[9][0]}}) s.acceptable_resps = set(v['corr_resp'] for v in s.case_dict.values()) s.type_seq = np.array([col[1][0] for col in f['file/run/event/event']]) s.resp_seq = np.array([col[2][0] for col in f['file/run/event/event']]) s.time_seq = np.array([col[-1][0] for col in f['file/run/event/event']]) def load_data_mc(s): ''' prepare needed data from the h5py pointer for a masscomp file ''' f = h5py.File(s.filepath) s.exp = f['file/experiment/experiment'][0][-3][0].decode() s.case_dict = {} for column in f['file/run/case/case']: s.case_dict.update({column[3][0]: {'code': column[-3][0].decode(), 'descriptor': column[-2][0].decode(), 'corr_resp': column[4][0], 'resp_win': column[9][0]}}) base_trialarray = f['file/run/trial/trial'][:] np_array = np.array([[elem[0] for elem in row] for row in base_trialarray]) s.trial_df = pd.DataFrame(np_array) s.trial_df.iloc[:, :4] = s.trial_df.iloc[:, :4].applymap(int) s.trial_df.iloc[:, 4:8] = s.trial_df.iloc[:, 4:8].applymap(bool) s.trial_df.iloc[:, 8:12] = s.trial_df.iloc[:, 8:12].applymap(float) s.trial_df.columns = s.trial_columns s.trial_df.set_index('Trial', inplace=True) def parse_seq(s): ''' parse the behavioral sequence and create a dataframe containing the event table ''' bad_respcodes = ~np.in1d(s.resp_seq, list(range(0, 9))) # bad_respcodes = ~np.in1d(s.resp_seq, [0, 1, 8]) # if strict about acceptable responses if np.any(bad_respcodes): s.resp_seq[bad_respcodes] = 0 nonresp_respcodes = (s.resp_seq != 0) & (s.type_seq != 0) if np.any(nonresp_respcodes): s.resp_seq[nonresp_respcodes] = 0 s.ev_len = len(s.type_seq) s.errant = np.zeros(s.ev_len, dtype=bool) s.early = np.zeros(s.ev_len, dtype=bool) s.late = np.zeros(s.ev_len, dtype=bool) s.correct = np.zeros(s.ev_len, dtype=bool) s.noresp = np.zeros(s.ev_len, dtype=bool) s.type_descriptor = [] # this is the main algorithm applied to the event sequence s.parse_alg() event_interval_ms = np.concatenate([[0], np.diff(s.time_seq) * 1000]) rt = np.empty_like(event_interval_ms) * np.nan rt[(s.resp_seq != 0) & ~s.errant] = \ event_interval_ms[(s.resp_seq != 0) & ~s.errant] s.type_descriptor = np.array(s.type_descriptor, dtype=np.object_) dd = {'type_seq': s.type_seq, 'type_descriptor': s.type_descriptor, 'correct': s.correct, 'rt': rt, 'resp_seq': s.resp_seq, 'noresp': s.noresp, 'errant': s.errant, 'early': s.early, 'late': s.late, 'time_seq': s.time_seq, 'event_intrvl_ms': event_interval_ms} ev_df = pd.DataFrame(dd) # reorder columns col_order = ['type_seq', 'type_descriptor', 'correct', 'rt', 'resp_seq', 'noresp', 'errant', 'early', 'late', 'time_seq', 'event_intrvl_ms'] ev_df = ev_df[col_order] s.ev_df = ev_df def parse_alg(s): ''' algorithm applied to event structure. the underlying philosophy is: each descriptive of an event is false unless proven true ''' for ev, t in enumerate(s.type_seq): if t == 0: # some kind of response prev_t = s.type_seq[ev - 1] if ev == 0 or prev_t not in s.case_dict: # first code is response, previous event is also response, # or previous event is unrecognized s.type_descriptor.append('rsp_err') s.errant[ev] = True continue else: # early / late responses # early is considered incorrect, while late can be correct tmp_rt = (s.time_seq[ev] - s.time_seq[ev - 1]) * 1000 if tmp_rt > s.case_dict[prev_t]['resp_win']: s.late[ev] = True elif tmp_rt < s.min_resptime: s.early[ev] = True s.type_descriptor.append('rsp_early') continue # interpret correctness (could have been late) if s.resp_seq[ev] == s.case_dict[prev_t]['corr_resp']: s.type_descriptor.append('rsp_correct') s.correct[ev] = True continue else: s.type_descriptor.append('rsp_incorrect') continue else: # some kind of stimulus if t in s.case_dict: s.type_descriptor.append(s.exp + '_' + s.case_dict[t]['code']) # interpret correctness if ev + 1 == s.ev_len: # if the last event # only correct if correct resp is no response if s.case_dict[t]['corr_resp'] == 0: s.correct[ev] = True else: # if not the last event # only considered correct if following resp was correct if s.resp_seq[ev + 1] == s.case_dict[t]['corr_resp']: s.correct[ev] = True # if incorrect, note if due to response omission elif s.case_dict[t]['corr_resp'] != 0 and \ s.resp_seq[ev + 1] == 0: s.noresp[ev] = True else: s.type_descriptor.append('stm_unknown') class MT_File: ''' manually picked files from eeg experiments initialization only parses the filename, call parse_file to load data ''' columns = ['subject_id', 'experiment', 'version', 'gender', 'age', 'case_num', 'electrode', 'peak', 'amplitude', 'latency', 'reaction_time'] cases_peaks_by_experiment = {'aod': {(1, 'tt'): ['N1', 'P3'], (2, 'nt'): ['N1', 'P2'] }, 'vp3': {(1, 'tt'): ['N1', 'P3'], (2, 'nt'): ['N1', 'P3'], (3, 'nv'): ['N1', 'P3'] }, 'ant': {(1, 'a'): ['N4', 'P3'], (2, 'j'): ['N4', 'P3'], (3, 'w'): ['N4', 'P3'], # (4, 'p'): ['P3', 'N4'] } } # string for reference data_structure = '{(case#,peak):{electrodes:(amplitude,latency),reaction_time:time} }' ant_cases_types_lk = [((1, 'A', 'Antonym'), (2, 'J', 'Jumble'), (3, 'W', 'Word'), (4, 'P', 'Prime')), ((1, 'T', 'jumble'), (2, 'T', 'prime'), (3, 'T', 'antonym'), (4, 'T', 'other')), ((1, 'T', 'jumble'), (2, 'T', ' prime'), (3, 'T', ' antonym'), (4, 'T', ' other')), ((1, 'T', 'jumble'), (2, 'T', 'prime'), (3, 'T', 'antonym'), (4, 'T', 'word'))] case_fields = ['case_num', 'case_type', 'descriptor'] ant_case_convD = {0: {1: 1, 2: 2, 3: 3, 4: 4}, # Translates case0 to each case 1: {1: 3, 2: 1, 3: 4, 4: 2}, 2: {1: 3, 2: 1, 3: 4, 4: 2}, 3: {1: 3, 2: 1, 3: 4, 4: 2}} # 4:{1:1,2:2,3:3,4:4} } case_nums2names = {'aod': {1: 't', 2: 'nt'}, 'vp3': {1: 't', 2: 'nt', 3: 'nv'}, 'ant': {1: 'a', 2: 'j', 3: 'w', 4: 'p'}, 'cpt': {1: 'g', 2: 'c', 3: 'cng', 4: 'db4ng', 5: 'ng', 6: 'dad'}, 'stp': {1: 'c', 2: 'i'}, } query_fields = ['id', 'session', 'experiment'] def normAntCase(s): case_nums = tuple( sorted([ k for k in s.header['cases_peaks'].keys() ]) ) if case_nums == (1,3,4): # Inconsistent ordering with open('/active_projects/db/logs/134_cases_HBNL4.log','a') as logf: logf.write(s.fullpath+'\n') return {1:2,2:4,3:1,4:3} else: query = {k: v for k, v in s.file_info.items() if k in s.query_fields} doc = D.Mdb['avgh1s'].find_one(query) avgh1_path = doc['filepath'] case_tup = extract_case_tuple(avgh1_path) case_type = MT_File.ant_cases_types_lk.index(case_tup) return MT_File.ant_case_convD[case_type] def __init__(s, filepath): s.fullpath = filepath s.filename = os.path.split(filepath)[1] s.header = {'cases_peaks': {}} s.parse_fileinfo() s.data = dict() s.data['uID'] = s.file_info['id'] + '_' + s.file_info['session'] if s.file_info['experiment'] == 'ant': s.normed_cases_calc() s.parse_header() def parse_fileinfo(s): s.file_info = parse_filename(s.filename) def __repr__(s): return '<mt-file object ' + str(s.file_info) + ' >' def parse_header(s): of = open(s.fullpath, 'r') reading_header = True s.header_lines = 0 cases = [] while reading_header: file_line = of.readline() if len(file_line) < 2 or file_line[0] != '#': reading_header = False continue s.header_lines += 1 line_parts = [pt.strip() for pt in file_line[1:-1].split(';')] if 'nchans' in line_parts[0]: s.header['nchans'] = int(line_parts[0].split(' ')[1]) elif 'case' in line_parts[0]: cs_pks = [lp.split(' ') for lp in line_parts] if cs_pks[1][0] != 'npeaks': s.header['problems'] = True else: case = int(cs_pks[0][1]) peak = int(cs_pks[1][1]) # if 'normed_cases' in dir(s): # case = s.normed_cases[case] s.header['cases_peaks'][case] = peak cases.append( case ) s.header['case_tup'] = tuple(sorted(list(set(cases)))) s.normed_cases_calc() of.close() def normed_cases_calc(s): try: norm_dict = s.normAntCase() s.normed_cases = norm_dict except: s.normed_cases = MT_File.ant_case_convD[0] s.norm_fail = True def parse_fileDB(s, general_info=False): s.parse_file() exp = s.file_info['experiment'] ddict = {} for k in s.mt_data: # for case_convdict = s.case_nums2names[exp] case = case_convdict[int(k[0])] peak = k[1] inner_ddict = {} for chan, amp_lat in s.mt_data[k].items(): # chans - reaction time in parallel if type(amp_lat) is tuple: # if amp / lat tuple inner_ddict.update( {chan: {'amp': float(amp_lat[0]), 'lat': float(amp_lat[1])}} ) elif chan == 'reaction_time': inner_ddict['rt'] = float(amp_lat) ddict[case + '_' + peak] = inner_ddict ddict['filepath'] = s.fullpath ddict['run'] = s.file_info['run'] ddict['version'] = s.file_info['version'] if general_info: s.data.update(s.file_info) del s.data['experiment'] del s.data['run'] del s.data['version'] s.data['ID'] = s.data['id'] s.data[exp] = ddict def parse_file(s): of = open(s.fullpath, 'r') data_lines = of.readlines()[s.header_lines:] of.close() s.mt_data = OrderedDict() for L in data_lines: Ld = {c: v for c, v in zip(s.columns, L.split())} if 'normed_cases' in dir(s): Ld['case_num'] = s.normed_cases[int(Ld['case_num'])] key = (int(Ld['case_num']), Ld['peak']) if key not in s.mt_data: s.mt_data[key] = OrderedDict() s.mt_data[key][Ld['electrode'].upper()] = ( Ld['amplitude'], Ld['latency']) if 'reaction_time' not in s.mt_data[key]: s.mt_data[key]['reaction_time'] = Ld['reaction_time'] return def parse_fileDF(s): s.dataDF = pd.read_csv(s.fullpath, delim_whitespace=True, comment='#', names=s.columns) def check_peak_order(s): ''' Pandas Dataframe based ''' if 'dataDF' not in dir(s): s.parse_fileDF() if 'normed_cases' in dir(s): case_lk = {v: k for k, v in s.normed_cases.items()} probs = {} # peaks by case number case_peaks = {k[0]: v for k, v in s.cases_peaks_by_experiment[s.file_info['experiment']].items()} cols_use = ['electrode', 'latency'] for case in s.dataDF['case_num'].unique(): cDF = s.dataDF[s.dataDF['case_num'] == case] if 'normed_cases' in dir(s): case_norm = case_lk[case] else: case_norm = case if case_norm in case_peaks: pk = case_peaks[case_norm][0] ordDF = cDF[cDF['peak'] == pk][cols_use] ordDF.rename(columns={'latency': 'latency_' + pk}, inplace=True) peak_track = [pk] delta_cols = [] if case in case_peaks: for pk in case_peaks[case][1:]: pkDF = cDF[cDF['peak'] == pk][cols_use] pkDF.rename(columns={'latency': 'latency_' + pk}, inplace=True) # return (ordDF, pkDF) ordDF = ordDF.join(pkDF, on='electrode', rsuffix=pk) delta_col = pk + '_' + peak_track[-1] + '_delta' ordDF[delta_col] = \ ordDF['latency_' + pk] - ordDF['latency_' + peak_track[-1]] peak_track.append(pk) delta_cols.append(delta_col) for dc in delta_cols: wrong_order = ordDF[ordDF[dc] < 0] if len(wrong_order) > 0: case_name = s.case_nums2names[s.file_info['experiment']][case_norm] probs[case_name + '_' + dc] = list(wrong_order['electrode']) if len(probs) == 0: return True else: return probs def check_max_latency(s, latency_thresh=1000): ''' Pandas Dataframe based ''' if 'dataDF' not in dir(s): s.parse_fileDF() high_lat = s.dataDF[s.dataDF['latency'] > latency_thresh] if len(high_lat) == 0: return True else: return high_lat[['case_num', 'electorde', 'peak', 'amplitude', 'latency']] def build_header(s): if 'mt_data' not in dir(s): s.parse_file() cases_peaks = list(s.mt_data.keys()) cases_peaks.sort() header_data = OrderedDict() for cp in cases_peaks: if cp[0] not in header_data: header_data[cp[0]] = 0 header_data[cp[0]] += 1 # one less for reaction_time s.header_text = '#nchans ' + \ str(len(s.mt_data[cases_peaks[0]]) - 1) + '\n' for cs, ch_count in header_data.items(): s.header_text += '#case ' + \ str(cs) + '; npeaks ' + str(ch_count) + ';\n' print(s.header_text) def build_file(s): pass def check_header_for_experiment(s): expected = s.cases_peaks_by_experiment[s.file_info['experiment']] if len(expected) != len(s.header['cases_peaks']): return 'Wrong number of cases' case_problems = [] for pknum_name, pk_list in expected.items(): if s.header['cases_peaks'][pknum_name[0]] != len(pk_list): case_problems.append( 'Wrong number of peaks for case ' + str(pknum_name)) if case_problems: return str(case_problems) return True def check_peak_identities(s): if 'mt_data' not in dir(s): s.parse_file() for case, peaks in s.cases_peaks_by_experiment[s.file_info['experiment']].items(): if (case[0], peaks[0]) not in s.mt_data: return False, 'case ' + str(case) + ' missing ' + peaks[0] + ' peak' if (case[0], peaks[1]) not in s.mt_data: return False, 'case ' + str(case) + ' missing ' + peaks[1] + ' peak' return True def check_peak_orderNmax_latency(s, latency_thresh=1000): if 'mt_data' not in dir(s): s.parse_file() for case, peaks in s.cases_peaks_by_experiment[s.file_info['experiment']].items(): try: latency1 = float(s.mt_data[(case[0], peaks[0])]['FZ'][1]) latency2 = float(s.mt_data[(case[0], peaks[1])]['FZ'][1]) except: print(s.fullpath + ': ' + str(s.mt_data[(case[0], peaks[0])].keys())) if latency1 > latency_thresh: return ( False, str(case) + ' ' + peaks[0] + ' ' + 'exceeds latency threshold (' + str(latency_thresh) + 'ms)') if latency2 > latency_thresh: return ( False, str(case) + ' ' + peaks[1] + ' ' + 'exceeds latency threshold (' + str(latency_thresh) + 'ms)') if latency1 > latency2: return False, 'Wrong order for case ' + str(case) return True def move_picked_files_to_processed(from_base, from_folders, working_directory, filter_list=[], do_now=False): ''' utility for moving processed files - places files in appropriate folders based on filenames inputs: from_base - folder containing all from_folders from_folders - list of subfolders working_directory - folder to store delete list (/active_projects can only be modified by exp) filter_list - a list by which to limit the files do_now - must be set to true to execute - by default, just a list of proposed copies is returned ''' to_base = '/processed_data/mt-files/' to_copy = [] counts = {'non coga': 0, 'total': 0, 'to move': 0, 'masscomp': 0, 'neuroscan': 0} if do_now: delete_file = open(os.path.join(working_directory, next_file_with_base(working_directory, 'picked_files_copied_to_processed', 'lst')), 'w') for folder in from_folders: for reject in [False, True]: from_folder = os.path.join(from_base, folder) if reject: from_folder += os.path.sep + 'reject' if not os.path.exists(from_folder): print(from_folder + ' Does Not Exist') continue print('checking: ' + from_folder) files = [f for f in os.listdir(from_folder) if not os.path.isdir( os.path.join(from_folder, f))] if filter_list: print(len(files)) files = [f for f in files if any( [s in f for s in filter_list])] print(len(files)) for file in files: counts['total'] += 1 if not ('.lst' in file or '.txt' in file or '_list' in file): try: file_info = parse_filename(file) if 'subjects' in file_info['site']: counts['non coga'] += 1 if file_info['system'] == 'masscomp': counts['masscomp'] += 1 type_short = 'mc' session_path = None else: counts['neuroscan'] += 1 type_short = 'ns' session_path = file_info['session'] + '-session' to_path = to_base + file_info['experiment'] + os.path.sep + file_info[ 'site'] + os.path.sep + type_short + os.path.sep if session_path: to_path += session_path + os.path.sep if reject: to_path += 'reject' + os.path.sep to_copy.append( (from_folder + os.path.sep + file, to_path)) counts['to move'] += 1 except: print('uninterpretable file: ' + file) print(str(counts['total']) + ' total (' + str(counts['masscomp']) + ' masscomp, ' + str( counts['neuroscan']) + ' neuroscan) ' + str(counts['to move']) + ' to move') print('total non coga: ' + str(counts['non coga'])) if do_now: for cf_dest in to_copy: delete_file.write(cf_dest[0] + '\n') if not os.path.exists(cf_dest[1]): os.makedirs(cf_dest[1]) shutil.copy2(cf_dest[0], cf_dest[1]) delete_file.close() return to_copy class ERO_CSV: ''' Compilations in processed data ''' columns = ['ID', 'session', 'trial', 'F3', 'FZ', 'F4', 'C3', 'CZ', 'C4', 'P3', 'PZ', 'P4'] parameterD = {'e': {'name': 'electrodes', 'values': {'1': 'all', '4': 'center 9'} }, 'b': {'name': 'baseline type', 'values': {'0': 'none', '1': 'mean'}}, # 'm':{}, 'hi': {'name': 'hi-pass', 'values': 'numeric'}, 'lo': {'name': 'lo-pass', 'values': 'numeric'}, 'n': {'name': 'minimum trials', 'values': 'numeric'}, 's': {'name': 'threshold electrodes', 'values': 'numeric'}, 't': {'name': 'threshold level', 'values': 'numeric'}, 'u': {'name': 'threshold min time', 'values': 'numeric'}, 'v': {'name': 'threshold max time', 'values': 'numeric'}, } defaults_by_exp = {} @staticmethod def parse_parameters(param_string, unknown=set()): pD = {'unknown': unknown} for p in param_string.split('-'): pFlag = p[0] if pFlag in ERO_CSV.parameterD: pLookup = ERO_CSV.parameterD[pFlag] pval = p[1:] pOpts = pLookup['values'] if pOpts == 'numeric': pval = int(pval) else: pval = pOpts[pval] pD[pLookup['name']] = pval else: pD['unknown'].update(p) return pD def __init__(s, filepath): s.filepath = filepath s.filename = os.path.split(filepath)[1] s.parameters = ERO_CSV.defaults_by_exp.copy() s.parse_fileinfo() def parse_fileinfo(s): path_parts = s.filepath.split(os.path.sep) calc_version = path_parts[2][-3:] path_parameters = path_parts[-3] site = path_parts[-2] s.parameters.update(ERO_CSV.parse_parameters(path_parameters)) file_parts = s.filename.split('_') exp, case = file_parts[0].split('-') freq_min, freq_max = [float(v) for v in file_parts[1].split('-')] time_min, time_max = [int(v) for v in file_parts[2].split('-')] for param in file_parts[3:-4]: s.parameters.update(ERO_CSV.parse_parameters(param, unknown=s.parameters['unknown'])) s.parameters['unknown'] = list(s.parameters['unknown']) s.parameters['version'] = calc_version pwr_type = file_parts[-4].split('-')[0] date = file_parts[-1].split('.')[0] mod_date = datetime.fromtimestamp(os.path.getmtime(s.filepath)) s.exp_info = {'experiment': exp, 'case': case, 'site': site} s.dates = {'file date': date, 'mod date': mod_date} s.phenotype = {'power type': pwr_type, 'frequency min': freq_min, 'frequency max': freq_max, 'time min': time_min, 'time max': time_max} def read_data(s): ''' prepare the data field for the database object ''' s.data = pd.read_csv(s.filepath, converters={'ID': str}, na_values=['.'], error_bad_lines=False, warn_bad_lines=True) dup_cols = [col for col in s.data.columns if '.' in col] s.data.drop(dup_cols, axis=1, inplace=True) def data_for_file(s): fileD = s.phenotype.copy() fileD.update(s.exp_info) fileD.update(s.parameters) fileD.update(s.dates) return fileD def data_by_sub_ses(s): ''' returns an iterator over rows of data by subject and session including file and phenotype info ''' s.read_data() for row in s.data.to_dict(orient='records'): row.update(s.exp_info) row.update(s.phenotype) yield row def data_forjoin(s): ''' creates unique doc identifying field and renames columns in preparation for joining with other CSVs ''' s.read_data() if s.data.shape[1] <= 3: s.data = pd.DataFrame() if s.data.empty: return s.data['uID'] = s.data.apply(join_ufields, axis=1, args=[s.exp_info['experiment']]) s.data.drop(['ID', 'session'], axis=1, inplace=True) s.data.set_index('uID', inplace=True) bad_list = ['50338099_a_vp3', '50700072_a_vp3', '50174138_e_vp3', '50164139_c_vp3', '50126477_a_vp3'] drop_rows = [uID for uID in s.data.index.values if uID in bad_list] s.data.drop(drop_rows, inplace=True) param_str = '' if 'version' in s.parameters: param_str += s.parameters['version'] if 'electrodes' in s.parameters: param_str += '-' + str(s.parameters['electrodes']) if 'threshold min time' in s.parameters: param_str += '-' + str(s.parameters['threshold min time']) rename_dict = {col: '_'.join(['data', param_str, s.phenotype['power type'], s.exp_info['case'], str(s.phenotype['frequency min']).replace('.', 'p'), str(s.phenotype['frequency max']).replace('.', 'p'), str(s.phenotype['time min']), str(s.phenotype['time max']), col]) for col in s.data.columns} s.data.rename(columns=rename_dict, inplace=True) class ERO_Summary_CSV(ERO_CSV): ''' Compilations in processed data/csv-files-*/ERO-results ''' rem_columns = ['sex', 'EROage', 'POP', 'wave12-race', '4500-race', 'ccGWAS-race', 'COGA11k-race', 'alc_dep_dx', 'alc_dep_ons'] def parse_fileinfo(s): path_parts = s.filepath.split(os.path.sep) calc_version = path_parts[2][-3:] file_parts = s.filename.split('_') end_parts = file_parts[-1].split('.') calc_parameters = end_parts[0] s.parameters.update(ERO_Summary_CSV.parse_parameters(calc_parameters)) exp, case = file_parts[0].split('-') freq_min, freq_max = [float(v) for v in file_parts[1].split('-')] time_min, time_max = [int(v) for v in file_parts[2].split('-')] pwr_type = file_parts[3].split('-')[0] date = end_parts[1] mod_date = datetime.fromtimestamp(os.path.getmtime(s.filepath)) s.exp_info = {'experiment': exp, 'case': case} s.dates = {'file date': date, 'mod date': mod_date} s.phenotype = {'calc version': calc_version, 'power type': pwr_type, 'frequency min': freq_min, 'frequency max': freq_max, 'time min': time_min, 'time max': time_max} def read_data(s): s.data = pd.read_csv(s.filepath, converters={ 'ID': str}, na_values=['.']) s.data.drop(s.rem_columns, axis=1, inplace=True) # drop extra cols dup_cols = [col for col in s.data.columns if '.' in col] s.data.drop(dup_cols, axis=1, inplace=True) def data_3tuple_bulklist(s): s.read_data() if s.data.empty: return s.data['uID'] = s.data.apply(join_ufields, axis=1, args=[s.exp_info['experiment']]) for k, v in s.exp_info.items(): s.data[k] = v for k, v in s.phenotype.items(): s.data[k] = str(v).replace('.', 'p') s.data = list(s.data.to_dict(orient='records')) class ERN_extract: ex_funs = ['extract_ern_react','extract_ern_val'] def __init__(s, filepath): s.filepath = filepath s.path = os.path.dirname(s.filepath) s.path_parts = filepath.split(os.path.sep) s.filename = os.path.splitext(s.path_parts[-1])[0] s.file_info = parse_filename(filepath) data = s.extract_data def extract_data(s): pass ############################## ## # Neuropsych ## ############################## class Neuropsych_XML: ''' given filepath to .xml file in /raw_data/neuropsych/, represent it ''' # labels for fields output by david's awk script cols = ['id', 'dob', 'gender', 'hand', 'testdate', 'sessioncode', 'motiv_avg', 'motiv_cbst', 'motiv_tolt', 'age', 'tolt_3b_mim', 'tolt_3b_mom', 'tolt_3b_em', 'tolt_3b_ao', 'tolt_3b_apt', 'tolt_3b_atoti', 'tolt_3b_ttrti', 'tolt_3b_atrti', 'tolt_4b_mim', 'tolt_4b_mom', 'tolt_4b_em', 'tolt_4b_ao', 'tolt_4b_apt', 'tolt_4b_atoti', 'tolt_4b_ttrti', 'tolt_4b_atrti', 'tolt_5b_mim', 'tolt_5b_mom', 'tolt_5b_em', 'tolt_5b_ao', 'tolt_5b_apt', 'tolt_5b_atoti', 'tolt_5b_ttrti', 'tolt_5b_atrti', 'tolt_tt_mim', 'tolt_tt_mom', 'tolt_tt_em', 'tolt_tt_ao', 'tolt_tt_apt', 'tolt_tt_atoti', 'tolt_tt_ttrti', 'tolt_tt_atrti', 'tolt_3b_otr', 'tolt_4b_otr', 'tolt_5b_otr', 'tolt_tt_otr', 'vst_f_tc', 'vst_f_span', 'vst_f_tcat', 'vst_f_tat', 'vst_b_tc', 'vst_b_span', 'vst_b_tcat', 'vst_b_tat'] # this function needs to be in /usr/bin of the invoking system func_name = '/opt/bin/do_np_processC' session_letters = 'abcdefghijklmnop' npsession_npfollowup = {letter: number for letter, number in zip(session_letters, range(len(session_letters)))} def __init__(s, filepath): s.filepath = filepath s.path = os.path.dirname(s.filepath) s.path_parts = filepath.split(os.path.sep) s.filename = os.path.splitext(s.path_parts[-1])[0] s.fileparts = s.filename.split('_') s.site = s.path_parts[-3] s.subject_id = s.fileparts[0] s.session = s.fileparts[1] s.data = {'ID': s.subject_id, 'site': s.site, 'np_session': s.session, 'np_followup': s.npsession_npfollowup[s.session], 'filepath': s.filepath, } s.read_file() def read_file(s): ''' use program s.func_name to extract results and put in s.data ''' raw_line = subprocess.check_output([s.func_name, s.filepath]) data_dict = s.parse_csvline(raw_line) data_dict.pop('id', None) data_dict.pop('sessioncode', None) s.data.update(data_dict) def parse_csvline(s, raw_line): ''' given a string which is a comma-delimited list of results (the raw output of s.func_name) parse into a list and parse its items ''' # [:-1] excludes the \n at line end lst = raw_line[:-1].decode('utf-8').split(',') # convert to dict in anticipation of storing as record d = dict(zip(s.cols, lst)) # convert dict items to appropriate types for k, v in d.items(): d[k] = s.parse_csvitem(k, d.pop(k)) # pop passes the val to parser return d @staticmethod def parse_csvitem(k, v): ''' given a string item from the results, parse it appropriately ''' if v == ' ' or v == ' ': return None # these will get safely coerced to NaN by pandas df else: v = v.lstrip() # remove leading whitespace if k in ['dob', 'testdate']: v = datetime.strptime(v, '%m/%d/%Y') # dates elif k in ['id', 'gender', 'hand', 'sessioncode']: pass # leave these as strings elif '_ao' in k: v = float(v[:-1]) # percentages converted to proportions else: v = float(v) # all other data becomes float return v def assure_quality(s): ''' after results have been extracted, perform quality assurance checks on them ''' try: # check if TOLT or CBST data is missing - if so, set motivation to none if 'tolt_5b_mim' not in s.data or s.data['tolt_5b_mim'] is None: s.data['motiv_tolt'] = None if 'vst_f_tat' not in s.data or s.data['vst_f_tat'] is None: s.data['motiv_cbst'] = None # then re-calculate mean motivs = [motiv for motiv in (s.data['motiv_tolt'], s.data['motiv_cbst']) if motiv] if motivs: s.data['motiv_avg'] = np.mean(motivs) else: s.data['motiv_avg'] = None # set CBST fields of 0 to be None # if any forward field is 0, set all forward to None # if any backward field is 0, set all backward to None if s.data['vst_f_span'] == 0: for field in ['vst_f_tc', 'vst_f_span', 'vst_f_tcat', 'vst_f_tat']: s.data[field] = None if s.data['vst_b_span'] == 0: for field in ['vst_b_tc', 'vst_b_span', 'vst_b_tcat', 'vst_b_tat']: s.data[field] = None except KeyError: print('Missing key in ',s.data['filepath']) return None class Neuropsych_Summary: def __init__(s, filepath): s.filepath = filepath s.path = os.path.dirname(s.filepath) s.path_parts = filepath.split(os.path.sep) s.filename = os.path.splitext(s.path_parts[-1])[0] s.fileparts = s.filename.split('_') s.site = s.path_parts[-3] s.subject_id = s.fileparts[0] s.session = s.fileparts[3][0] s.motivation = int(s.fileparts[3][1]) s.xmlname = '_'.join([s.subject_id, s.session, 'sub.xml']) s.xmlpath = os.path.join(s.path, s.xmlname) s.data = {'ID': s.subject_id, 'site': s.site, 'session': s.session, 'motivation': s.motivation, } def read_file(s): of = open(s.filepath) lines = [l.strip() for l in of.readlines()] of.close() # find section line numbers section_beginnings = [lines.index( k) for k in s.section_header_funs_names] + [-1] ind = -1 for sec, fun_nm in s.section_header_funs_names.items(): ind += 1 sec_cols = lines[section_beginnings[ind] + 1].split('\t') sec_lines = [L.split('\t') for L in lines[section_beginnings[ ind] + 2:section_beginnings[ind + 1]]] s.data[fun_nm[1]] = eval('s.' + fun_nm[0])(sec_cols, sec_lines) class TOLT_Summary_File(Neuropsych_Summary): integer_columns = ['PegCount', 'MinimumMoves', 'MovesMade', 'ExcessMoves'] float_columns = ['AvgPickupTime', 'AvgTotalTime', 'AvgTrialTime', '%AboveOptimal', 'TotalTrialsTime', 'AvgTrialsTime'] # boolean_columns = {} section_header_funs_names = OrderedDict([ ('Trial Summary', ('parse_trial_summary', 'trials')), ('Test Summary', ('parse_test_summary', 'tests'))]) def parse_trial_summary(s, trial_cols, trial_lines): trials = {} for trial_line in trial_lines: trialD = {} for col, val in zip(trial_cols, trial_line): val = parse_value_with_info( val, col, s.integer_columns, s.float_columns) if col == 'TrialNumber': trial_num = val else: trialD[col] = val trials[trial_num] = trialD return trials def parse_test_summary(s, test_cols, test_lines): # summary data is transposed for lnum, tl in enumerate(test_lines): if tl[0][0] == '%': test_lines[lnum] = [tl[0]] + \ [st[:-1] if '%' in st else st for st in tl[1:]] # print(type(tl),tl) # print([ st[:-1] if '%' in st else st for st in tl[1:] ]) # tlinesP.append( tl[0] + [ st[:-1] if '%' in st else st for st in tl[1:] ] ) test_data = {line[0]: [parse_value_with_info(val, line[0], s.integer_columns, s.float_columns) for val in line[1:]] for line in test_lines} caseD = {} # case:{} for case in test_cols[1:] } for cnum, case in enumerate(test_cols[1:]): caseD[case] = {stat: data[cnum] for stat, data in test_data.items()} return caseD def __init__(s, filepath): Neuropsych_Summary.__init__(s, filepath) s.read_file() class CBST_Summary_File(Neuropsych_Summary): integer_columns = ['Trials', 'TrialsCorrect'] float_columns = ['TrialTime', 'AverageTime'] boolean_columns = {'Direction': [ 'Backward', 'Forward'], 'Correct': ['-', '+']} # False, True section_header_funs_names = {'Trial Summary': ('parse_trial_summary', 'trials'), 'Test Summary': ('parse_test_summary', 'tests')} def parse_trial_summary(s, trial_cols, trial_lines): trials = {} for trial_line in trial_lines: trialD = {} for col, val in zip(trial_cols, trial_line): val = parse_value_with_info( val, col, s.integer_columns, s.float_columns, s.boolean_columns) if col == 'TrialNum': trial_num = val else: trialD[col] = val trials[trial_num] = trialD return trials def parse_test_summary(s, test_cols, test_lines): tests = {'Forward': {}, 'Backward': {}} for test_line in test_lines: testD = {} for col, val in zip(test_cols, test_line): if col == 'Direction': dirD = tests[val] else: val = parse_value_with_info( val, col, s.integer_columns, s.float_columns, s.boolean_columns) if col == 'Length': test_len = val else: testD[col] = val dirD[test_len] = testD return tests def __init__(s, filepath): Neuropsych_Summary.__init__(s, filepath) s.read_file() def parse_value_with_info(val, column, integer_columns, float_columns, boolean_columns={}): if column in integer_columns: val = int(val) elif column in float_columns: val = float(val) elif column in boolean_columns: val = bool(boolean_columns[column].index(val)) return val
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python3 """ Parsování dokladů z pirátské wiki do csv 1. Dataplugin v Docuwiki ukladá data do sqlite2, tu si stáhneme: scp <path>/data.sqlite ucto2.db 2. Nejdřívě je třeba převést sqlite2 do sqlite3: sqlite ucto2.db .dump | sqlite3 ucto3.db # konverze sqlite 2 do sqlite 3 3. Potom spustit tento skript Parsování přímo z webu: https://github.com/pirati-byro/fo-vydaje2017 (zbytečně vytěžující a zdlouhavé) """ import csv import sqlite3 year = '2017' dbfile = 'ucto3.db' csvfile = 'ucto' + year + '.csv' vydaje = [] def parsePolozka(pol): """ input format: fo:hospodareni2017:rozpocty:strana:212800001 return (stredisko, polozka_num) """ try: ns = pol.split(':') pair = (ns[-2], ns[-1]) return pair except: return ('stana', '') def processVydaj(records, results): """ Procces multiple records with key, vals into one object, for example: sqlite> select * from data where pid = 482; eid pid key value ---------- ---------- ---------- ---------- 14848162 482 značka FO 20/2014 14848163 482 číslo 20 14848164 482 složka regiony:pl 14848165 482 hospodář lide:lukas 14848166 482 položka fo:hospoda 14848167 482 záměr Proplacen� 14848168 482 účel volné pen 14848169 482 příjemce Lukáš V� 14848170 482 účet 1204210039 14848171 482 vs 123456789 14848172 482 ks 14848173 482 částka -1167.50 14848174 482 doklad není pot� 14848175 482 podáno 2014-02-16 14848176 482 proplaceno 2014-02-17 14848177 482 souhlas https://ww """ vydaj = {} for item in records: key = item[2] val = item[3] if key == 'položka': if val == '': return # nejedná se o vydaj vydaj['středisko'], vydaj['položka'] = parsePolozka(val) continue vydaj[item[2]] = item[3] results.append(vydaj) with sqlite3.connect(dbfile) as conn: c = conn.cursor() namespace = 'fo:vydaje:fo_%_' + year args = (namespace,) pids = c.execute("select pid from pages where page like ?;", args).fetchall() for row in pids: pid = row[0] records = c.execute("select * from data where pid = '%d'" % pid).fetchall() processVydaj(records, vydaje) with open(csvfile, 'w') as csvw: fieldnames = ['značka', 'středisko', 'položka', 'částka', 'podáno', 'proplaceno', 'redmine', 'popis'] # jakub fieldnames = ['značka', 'středisko', 'položka', 'částka', 'podáno', 'proplaceno', 'souhlas', 'usnesení', 'název', 'vs', 'příjemce', 'záměr', 'doklad', 'ks', 'rok', 'druh', 'ss', 'účet', 'číslo', 'účtováno', 'hospodář', 'rest', 'zdroj', 'složka', 'účel'] # full writer = csv.DictWriter(csvw, fieldnames=fieldnames) writer.writeheader() for vydaj in vydaje: try: writer.writerow(vydaj) except ValueError as e: print(vydaj) print(e)
unknown
codeparrot/codeparrot-clean
# Copyright (c) 2007 The Hewlett-Packard Development Company # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Gabe Black microcode = ''' def macroop CVTSI2SS_XMM_R { mov2fp ufp1, regm, destSize=dsz, srcSize=dsz cvti2f xmml, ufp1, srcSize=dsz, destSize=4, ext=Scalar }; def macroop CVTSI2SS_XMM_M { ldfp ufp1, seg, sib, disp, dataSize=8 cvti2f xmml, ufp1, srcSize=dsz, destSize=4, ext=Scalar }; def macroop CVTSI2SS_XMM_P { rdip t7 ldfp ufp1, seg, riprel, disp, dataSize=8 cvti2f xmml, ufp1, srcSize=dsz, destSize=4, ext=Scalar }; def macroop CVTSI2SD_XMM_R { mov2fp ufp1, regm, destSize=dsz, srcSize=dsz cvti2f xmml, ufp1, srcSize=dsz, destSize=8, ext=Scalar }; def macroop CVTSI2SD_XMM_M { ldfp ufp1, seg, sib, disp, dataSize=8 cvti2f xmml, ufp1, srcSize=dsz, destSize=8, ext=Scalar }; def macroop CVTSI2SD_XMM_P { rdip t7 ldfp ufp1, seg, riprel, disp, dataSize=8 cvti2f xmml, ufp1, srcSize=dsz, destSize=8, ext=Scalar }; '''
unknown
codeparrot/codeparrot-clean
<?php namespace Illuminate\Contracts\Auth; interface Authenticatable { /** * Get the name of the unique identifier for the user. * * @return string */ public function getAuthIdentifierName(); /** * Get the unique identifier for the user. * * @return mixed */ public function getAuthIdentifier(); /** * Get the name of the password attribute for the user. * * @return string */ public function getAuthPasswordName(); /** * Get the password for the user. * * @return string */ public function getAuthPassword(); /** * Get the token value for the "remember me" session. * * @return string */ public function getRememberToken(); /** * Set the token value for the "remember me" session. * * @param string $value * @return void */ public function setRememberToken($value); /** * Get the column name for the "remember me" token. * * @return string */ public function getRememberTokenName(); }
php
github
https://github.com/laravel/framework
src/Illuminate/Contracts/Auth/Authenticatable.php
import numpy as np from ase.optimize.optimize import Dynamics from ase.optimize.fire import FIRE from ase.units import kB from ase.parallel import world from ase.io.trajectory import PickleTrajectory class BasinHopping(Dynamics): """Basin hopping algorythm. After Wales and Doye, J. Phys. Chem. A, vol 101 (1997) 5111-5116 and David J. Wales and Harold A. Scheraga, Science, Vol. 285, 1368 (1999) """ def __init__(self, atoms, temperature=100 * kB, optimizer=FIRE, fmax=0.1, dr=0.1, logfile='-', trajectory='lowest.traj', optimizer_logfile='-', local_minima_trajectory='local_minima.traj', adjust_cm=True): Dynamics.__init__(self, atoms, logfile, trajectory) self.kT = temperature self.optimizer = optimizer self.fmax = fmax self.dr = dr if adjust_cm: self.cm = atoms.get_center_of_mass() else: self.cm = None self.optimizer_logfile = optimizer_logfile self.lm_trajectory = local_minima_trajectory if isinstance(local_minima_trajectory, str): self.lm_trajectory = PickleTrajectory(local_minima_trajectory, 'w', atoms) self.initialize() def initialize(self): self.positions = 0.0 * self.atoms.get_positions() self.Emin = self.get_energy(self.atoms.get_positions()) or 1.e32 self.rmin = self.atoms.get_positions() self.positions = self.atoms.get_positions() self.call_observers() self.log(-1, self.Emin, self.Emin) def run(self, steps): """Hop the basins for defined number of steps.""" ro = self.positions Eo = self.get_energy(ro) for step in range(steps): En = None while En is None: rn = self.move(ro) En = self.get_energy(rn) if En < self.Emin: # new minimum found self.Emin = En self.rmin = self.atoms.get_positions() self.call_observers() self.log(step, En, self.Emin) accept = np.exp((Eo - En) / self.kT) > np.random.uniform() if accept: ro = rn.copy() Eo = En def log(self, step, En, Emin): if self.logfile is None: return name = self.__class__.__name__ self.logfile.write('%s: step %d, energy %15.6f, emin %15.6f\n' % (name, step, En, Emin)) self.logfile.flush() def move(self, ro): """Move atoms by a random step.""" atoms = self.atoms # displace coordinates disp = np.random.uniform(-1., 1., (len(atoms), 3)) rn = ro + self.dr * disp atoms.set_positions(rn) if self.cm is not None: cm = atoms.get_center_of_mass() atoms.translate(self.cm - cm) rn = atoms.get_positions() world.broadcast(rn, 0) atoms.set_positions(rn) return atoms.get_positions() def get_minimum(self): """Return minimal energy and configuration.""" atoms = self.atoms.copy() atoms.set_positions(self.rmin) return self.Emin, atoms def get_energy(self, positions): """Return the energy of the nearest local minimum.""" if np.sometrue(self.positions != positions): self.positions = positions self.atoms.set_positions(positions) try: opt = self.optimizer(self.atoms, logfile=self.optimizer_logfile) opt.run(fmax=self.fmax) if self.lm_trajectory is not None: self.lm_trajectory.write(self.atoms) self.energy = self.atoms.get_potential_energy() except: # Something went wrong. # In GPAW the atoms are probably to near to each other. return None return self.energy
unknown
codeparrot/codeparrot-clean
from __future__ import absolute_import, print_function, division # Run using # mpiexec -np 2 python _test_mpi_roundtrip.py from mpi4py import MPI import theano from theano.tensor.io import send, recv, mpi_cmps from theano.gof.sched import sort_schedule_fn import numpy as np from sys import stdout, stderr, exit comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() if size != 2: stderr.write("mpiexec failed to create a world with two nodes.\n" "Closing with success message.") stdout.write("True") exit(0) shape = (2, 2) dtype = 'float32' scheduler = sort_schedule_fn(*mpi_cmps) mode = theano.Mode(optimizer=None, linker=theano.OpWiseCLinker(schedule=scheduler)) if rank == 0: x = theano.tensor.matrix('x', dtype=dtype) y = x + 1 send_request = send(y, 1, 11) z = recv(shape, dtype, 1, 12) f = theano.function([x], [send_request, z], mode=mode) xx = np.random.rand(*shape).astype(dtype) expected = (xx + 1) * 2 _, zz = f(xx) same = np.linalg.norm(zz - expected) < .001 stdout.write(str(same)) if rank == 1: y = recv(shape, dtype, 0, 11) z = y * 2 send_request = send(z, 0, 12) f = theano.function([], send_request, mode=mode) f()
unknown
codeparrot/codeparrot-clean
# Copyright 2012 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from glance.common import exception from glance import domain import glance.tests.utils as test_utils UUID1 = 'c80a1a6c-bd1f-41c5-90ee-81afedb1d58d' TENANT1 = '6838eb7b-6ded-434a-882c-b344c77fe8df' class TestImageFactory(test_utils.BaseTestCase): def setUp(self): super(TestImageFactory, self).setUp() self.image_factory = domain.ImageFactory() def test_minimal_new_image(self): image = self.image_factory.new_image() self.assertTrue(image.image_id is not None) self.assertTrue(image.created_at is not None) self.assertEqual(image.created_at, image.updated_at) self.assertEqual(image.status, 'queued') self.assertEqual(image.visibility, 'private') self.assertEqual(image.owner, None) self.assertEqual(image.name, None) self.assertEqual(image.size, None) self.assertEqual(image.min_disk, 0) self.assertEqual(image.min_ram, 0) self.assertEqual(image.protected, False) self.assertEqual(image.disk_format, None) self.assertEqual(image.container_format, None) self.assertEqual(image.extra_properties, {}) self.assertEqual(image.tags, set([])) def test_new_image(self): image = self.image_factory.new_image( image_id=UUID1, name='image-1', min_disk=256, owner=TENANT1) self.assertEqual(image.image_id, UUID1) self.assertTrue(image.created_at is not None) self.assertEqual(image.created_at, image.updated_at) self.assertEqual(image.status, 'queued') self.assertEqual(image.visibility, 'private') self.assertEqual(image.owner, TENANT1) self.assertEqual(image.name, 'image-1') self.assertEqual(image.size, None) self.assertEqual(image.min_disk, 256) self.assertEqual(image.min_ram, 0) self.assertEqual(image.protected, False) self.assertEqual(image.disk_format, None) self.assertEqual(image.container_format, None) self.assertEqual(image.extra_properties, {}) self.assertEqual(image.tags, set([])) def test_new_image_with_extra_properties_and_tags(self): extra_properties = {'foo': 'bar'} tags = ['one', 'two'] image = self.image_factory.new_image( image_id=UUID1, name='image-1', extra_properties=extra_properties, tags=tags) self.assertEqual(image.image_id, UUID1) self.assertTrue(image.created_at is not None) self.assertEqual(image.created_at, image.updated_at) self.assertEqual(image.status, 'queued') self.assertEqual(image.visibility, 'private') self.assertEqual(image.owner, None) self.assertEqual(image.name, 'image-1') self.assertEqual(image.size, None) self.assertEqual(image.min_disk, 0) self.assertEqual(image.min_ram, 0) self.assertEqual(image.protected, False) self.assertEqual(image.disk_format, None) self.assertEqual(image.container_format, None) self.assertEqual(image.extra_properties, {'foo': 'bar'}) self.assertEqual(image.tags, set(['one', 'two'])) def test_new_image_read_only_property(self): self.assertRaises(exception.ReadonlyProperty, self.image_factory.new_image, image_id=UUID1, name='image-1', size=256) def test_new_image_unexpected_property(self): self.assertRaises(TypeError, self.image_factory.new_image, image_id=UUID1, image_name='name-1') def test_new_image_reserved_property(self): extra_properties = {'deleted': True} self.assertRaises(exception.ReservedProperty, self.image_factory.new_image, image_id=UUID1, extra_properties=extra_properties) class TestImage(test_utils.BaseTestCase): def setUp(self): super(TestImage, self).setUp() self.image_factory = domain.ImageFactory() self.image = self.image_factory.new_image( container_format='bear', disk_format='rawr') def test_extra_properties(self): self.image.extra_properties = {'foo': 'bar'} self.assertEqual(self.image.extra_properties, {'foo': 'bar'}) def test_extra_properties_assign(self): self.image.extra_properties['foo'] = 'bar' self.assertEqual(self.image.extra_properties, {'foo': 'bar'}) def test_delete_extra_properties(self): self.image.extra_properties = {'foo': 'bar'} self.assertEqual(self.image.extra_properties, {'foo': 'bar'}) del self.image.extra_properties['foo'] self.assertEqual(self.image.extra_properties, {}) def test_visibility_enumerated(self): self.image.visibility = 'public' self.image.visibility = 'private' self.assertRaises(ValueError, setattr, self.image, 'visibility', 'ellison') def test_tags_always_a_set(self): self.image.tags = ['a', 'b', 'c'] self.assertEqual(self.image.tags, set(['a', 'b', 'c'])) def test_delete_protected_image(self): self.image.protected = True self.assertRaises(exception.ProtectedImageDelete, self.image.delete) def test_status_saving(self): self.image.status = 'saving' self.assertEqual(self.image.status, 'saving') def test_status_saving_without_disk_format(self): self.image.disk_format = None self.assertRaises(ValueError, setattr, self.image, 'status', 'saving') def test_status_saving_without_container_format(self): self.image.container_format = None self.assertRaises(ValueError, setattr, self.image, 'status', 'saving') def test_status_active_without_disk_format(self): self.image.disk_format = None self.assertRaises(ValueError, setattr, self.image, 'status', 'active') def test_status_active_without_container_format(self): self.image.container_format = None self.assertRaises(ValueError, setattr, self.image, 'status', 'active') class TestImageMember(test_utils.BaseTestCase): def setUp(self): super(TestImageMember, self).setUp() self.image_member_factory = domain.ImageMemberFactory() self.image_factory = domain.ImageFactory() self.image = self.image_factory.new_image() self.image_member = self.image_member_factory\ .new_image_member(image=self.image, member_id=TENANT1) def test_status_enumerated(self): self.image_member.status = 'pending' self.image_member.status = 'accepted' self.image_member.status = 'rejected' self.assertRaises(ValueError, setattr, self.image_member, 'status', 'ellison') class TestImageMemberFactory(test_utils.BaseTestCase): def setUp(self): super(TestImageMemberFactory, self).setUp() self.image_member_factory = domain.ImageMemberFactory() self.image_factory = domain.ImageFactory() def test_minimal_new_image_member(self): member_id = 'fake-member-id' image = self.image_factory.new_image( image_id=UUID1, name='image-1', min_disk=256, owner=TENANT1) image_member = self.image_member_factory.new_image_member(image, member_id) self.assertEqual(image_member.image_id, image.image_id) self.assertTrue(image_member.created_at is not None) self.assertEqual(image_member.created_at, image_member.updated_at) self.assertEqual(image_member.status, 'pending') self.assertTrue(image_member.member_id is not None) class TestExtraProperties(test_utils.BaseTestCase): def test_getitem(self): a_dict = {'foo': 'bar', 'snitch': 'golden'} extra_properties = domain.ExtraProperties(a_dict) self.assertEqual(extra_properties['foo'], 'bar') self.assertEqual(extra_properties['snitch'], 'golden') def test_getitem_with_no_items(self): extra_properties = domain.ExtraProperties() self.assertRaises(KeyError, extra_properties.__getitem__, 'foo') def test_setitem(self): a_dict = {'foo': 'bar', 'snitch': 'golden'} extra_properties = domain.ExtraProperties(a_dict) extra_properties['foo'] = 'baz' self.assertEqual(extra_properties['foo'], 'baz') def test_delitem(self): a_dict = {'foo': 'bar', 'snitch': 'golden'} extra_properties = domain.ExtraProperties(a_dict) del extra_properties['foo'] self.assertRaises(KeyError, extra_properties.__getitem__, 'foo') self.assertEqual(extra_properties['snitch'], 'golden') def test_len_with_zero_items(self): extra_properties = domain.ExtraProperties() self.assertEqual(len(extra_properties), 0) def test_len_with_non_zero_items(self): extra_properties = domain.ExtraProperties() extra_properties['foo'] = 'bar' extra_properties['snitch'] = 'golden' self.assertEqual(len(extra_properties), 2) def test_eq_with_a_dict(self): a_dict = {'foo': 'bar', 'snitch': 'golden'} extra_properties = domain.ExtraProperties(a_dict) ref_extra_properties = {'foo': 'bar', 'snitch': 'golden'} self.assertEqual(extra_properties, ref_extra_properties) def test_eq_with_an_object_of_ExtraProperties(self): a_dict = {'foo': 'bar', 'snitch': 'golden'} extra_properties = domain.ExtraProperties(a_dict) ref_extra_properties = domain.ExtraProperties() ref_extra_properties['snitch'] = 'golden' ref_extra_properties['foo'] = 'bar' self.assertEqual(extra_properties, ref_extra_properties) def test_eq_with_uneqal_dict(self): a_dict = {'foo': 'bar', 'snitch': 'golden'} extra_properties = domain.ExtraProperties(a_dict) ref_extra_properties = {'boo': 'far', 'gnitch': 'solden'} self.assertFalse(extra_properties.__eq__(ref_extra_properties)) def test_eq_with_unequal_ExtraProperties_object(self): a_dict = {'foo': 'bar', 'snitch': 'golden'} extra_properties = domain.ExtraProperties(a_dict) ref_extra_properties = domain.ExtraProperties() ref_extra_properties['gnitch'] = 'solden' ref_extra_properties['boo'] = 'far' self.assertFalse(extra_properties.__eq__(ref_extra_properties)) def test_eq_with_incompatible_object(self): a_dict = {'foo': 'bar', 'snitch': 'golden'} extra_properties = domain.ExtraProperties(a_dict) random_list = ['foo', 'bar'] self.assertFalse(extra_properties.__eq__(random_list))
unknown
codeparrot/codeparrot-clean
from __future__ import division from random import shuffle, choice, randint, seed from os.path import expanduser from numpy import log10 from scipy import stats import numpy as np import time import math import copy import sys import os from pprint import pprint as pp mydir = expanduser("~/") sys.path.append(mydir + "GitHub/Emergence-Senescence/model") GenPath = mydir + "GitHub/Emergence-Senescence/results/simulated_data/" col_headers = 'sim,r,gr,mt,q,rls_min,rls_max,grcv,mtcv,rlscv,ct,rlsmean,rlsvar,total.abundance,species.richness' OUT = open("/gpfs/home/r/z/rzmogerr/Carbonate/SSTOSIMPLE.csv", 'w+') print>>OUT, col_headers OUT.close() senesce_simple = lambda age, rls: (1-(age/(rls+0.01))) #senesce_simple = lambda age, rls: 1 tradeoff_reverse_logistic = lambda rls: 2 / (2 + math.exp((0.2*rls)-8))#in the full implementation, don't enforce these parameters #tradeoff_reverse_logistic = lambda rls: 2 / (2 + math.exp((0.2*rls)-4)) #tradeoff_reverse_logistic = lambda rls: rls/rls g0delay = lambda rls: 1 / (1 + (rls/100)) #competitive_growth = lambda age: def output(iD, sD, rD, sim, ct, r): IndIDs, SpIDs = [], [] for k, v in iD.items(): IndIDs.append(k) SpIDs.append(v['sp']) #pp(IndIDs) #pp(SpIDs) N = len(IndIDs) R = len(rD.items()) S = len(list(set(SpIDs))) #RLSL=[] #for i in IndIDs: # RLSL.append(iD[i]['rls']) RLSL=[iD[i]['rls'] for i in IndIDs] rlsmean = np.mean(RLSL) rlsvar = np.var(RLSL) if N > 0: #OUT = open(GenPath + 'SimData.csv', 'a') OUT=open("/gpfs/home/r/z/rzmogerr/Carbonate/SSTOSIMPLE.csv","a") outlist = [sim, r, gr, mt, q, rls_min, rls_max, grcv, mtcv, rlscv, ct, rlsmean, rlsvar, N, S] outlist = str(outlist).strip('[]') outlist = outlist.replace(" ", "") print>>OUT, outlist OUT.close() try: print 'sim:', '%3s' % sim, 'ct:', '%3s' % ct,' N:', '%4s' % N, ' S:', '%4s' % S, ' R:', '%4s' % R, 'LSm:' '%1s' % rlsmean, 'LSv:' '%2s' % rlsvar except UnboundLocalError: print 'ERROR: N=0' return def immigration(sD, iD, ps, sd=1): r, u, gr, mt, q, rls_min, rls_max, grcv, mtcv, rlscv, efcv, a = ps for j in range(sd): if sd == 1 and np.random.binomial(1, u) == 0: continue p = np.random.randint(1, 1000) if p not in sD: sD[p] = {'gr' : 10**np.random.uniform(gr, 0)} sD[p]['mt'] = 10**np.random.uniform(mt, 0) sD[p]['rls'] = 50#randint(rls_min,rls_max) sD[p]['grcv']=10**np.random.uniform(-6.01,grcv) sD[p]['mtcv']=10**np.random.uniform(-6.01,mtcv) sD[p]['rlscv']=.15#10**np.random.uniform(-6.01,rlscv) sD[p]['efcv']=10**np.random.uniform(-6.01,efcv) es = np.random.uniform(1, 100, 3) sD[p]['ef'] = es/sum(es) sD[p]['a']=a ID = time.time() iD[ID] = copy.copy(sD[p]) iD[ID]['sp'] = p iD[ID]['age']=np.random.geometric(.5)-1 #iD[ID]['age']=0#doesn't need to start with age==0... iD[ID]['x'] = 0 iD[ID]['y'] = 0 iD[ID]['rls']=sD[p]['rls']; iD[ID]['mt']=sD[p]['mt']; iD[ID]['ef']=sD[p]['ef'];iD[ID]['gr']=sD[p]['gr'];iD[ID]['a']=sD[p]['a'] iD[ID]['q'] = 10**np.random.uniform(0, q) return [sD, iD] def consume(iD, rD, ps): r, u, gr, mt, q, rls_min, rls_max, grcv, mtcv, rlscv, efcv, a = ps keys = list(iD) shuffle(keys) for k in keys: if len(list(rD)) == 0: return [iD, rD] c = choice(list(rD)) e = iD[k]['ef'][rD[c]['t']] * iD[k]['q']#why does this dep on the indiv's q? #pp(iD[k]['ef'][rD[c]['t']]) #pp(e) #To account for the Frenk et al. 2017, one idea that you had was to make the indiv a generalist by taking a max of #iD[k]['ef'][rD[c]['t']] and another number (e.g., (1/3)) #but it would be better to do some distrn that has age as a param, so that it is generalizable and can be randomized. iD[k]['q'] += min([rD[c]['v'], e]) rD[c]['v'] -= min([rD[c]['v'], e]) if rD[c]['v'] <= 0: del rD[c] return [iD, rD] def grow(iD): for k, v in iD.items(): m = v['mt'] iD[k]['q'] -= v['gr'] * (v['q']) if v['age']==0 and v['q'] < m/(0.5+v['a'])*(0.5-v['a']):#daughters are born in G0 phase,we know that #theyre smaller in G0. We don't want to kill them all because of it, though del iD[k] elif v['q'] < m: del iD[k] return iD def maintenance(iD):#mt is less for juveniles for k, v in iD.items(): if v['age']==0: iD[k]['q'] -= v['mt']/(0.5+v['a'])*(0.5-v['a']) if v['q'] < v['mt']/(0.5+v['a'])*(0.5-v['a']): del iD[k] else: iD[k]['q'] -= v['mt'] if v['q'] < v['mt']: del iD[k] return iD def reproduce(sD, iD, ps, p = 0): for k, v in iD.items(): if v['gr'] > 1 or v['gr'] < 0: del iD[k] elif v['q'] > v['mt']/(0.5+v['a']) and np.random.binomial(1, v['gr']) == 1: if v['age'] >= v['rls'] or v['mt']<0: del iD[k] else: iD[k]['q'] = v['q']*(0.5+v['a']) grorig=(v['gr'])/(senesce_simple(v['age'],v['rls'])) iD[k]['gr']=v['gr']/(senesce_simple((v['age']-1),v['rls']))*(senesce_simple(v['age'],v['rls'])) #modifier based on the newly incremented age value, after removing the gr reduction due to previous age #in full implementation the sscnc model will be chosen at random from a list of choices i = time.time() iD[i] = copy.deepcopy(iD[k]) iD[k]['age']+=1 #in addition to copying physiology, need to copy the rlsmax--- #rlsmax is determined genetically so there should be a chance of mutation, here with normally distributed #effect sizes iD[i]['rls']=np.random.normal((v['rls']),sD[v['sp']]['rlscv']*v['rls'],None) #pp(iD[k]['age']);pp(iD[k]['rls']) try: iD[i]['gr']=np.random.normal(grorig,(sD[v['sp']]['grcv']*grorig),None)#these should not be normal distrns, should be negv-biased iD[i]['mt']=np.random.normal(v['mt'],sD[v['sp']]['mtcv']*v['mt'],None) #is total ef allowed to != 1 except ValueError: del iD[i]; continue if iD[i]['gr'] > 1 or iD[i]['gr'] < 0: del iD[i]; continue iD[i]['q']=(v['q'])/(0.5+v['a'])*(0.5-v['a']) iD[i]['age']=0 return [sD, iD] def iter_procs(iD, sD, rD, ps, ct): procs = range(6) shuffle(procs) for p in procs: if p == 0: rD = ResIn(rD, ps) elif p == 1: pass#sD, iD = immigration(sD, iD, ps) elif p == 2: iD, rD = consume(iD, rD, ps) elif p == 3: iD = grow(iD) elif p == 4: iD = maintenance(iD) elif p == 5: sD, iD = reproduce(sD, iD, ps) N = len(list(iD)) return [iD, sD, rD, N, ct+1] def ResIn(rD, ps): r, u, gr, mt, q, rls_min, rls_max, grcv, mtcv, rlscv, efcv, a = ps for i in range(r): p = np.random.binomial(1, u) if p == 1: ID = time.time() rD[ID] = {'t' : randint(0, 2)} rD[ID]['v'] = 10**np.random.uniform(0, 2) return rD def run_model(sim, gr, mt, q, rls_min, rls_max, grcv, mtcv, rlscv, efcv, a=0, rD = {}, sD = {}, iD = {}, ct = 0, splist2 = []): print '\n' rD={};iD={};sD={} if iD=={} and sD=={} and rD=={}: pass else: sys.exit() r = choice([10,100])#10**randint(0, 2) u = 10**np.random.uniform(-2, 0) ps = r, u, gr, mt, q, rls_min, rls_max, grcv, mtcv, rlscv, efcv, a sD, iD = immigration(sD, iD, ps, 1000)#this is the initial number of indivs while ct < 2000:#this is the number of timesteps if ct < 1: print str(rls_min) + ' ' + str(rls_max) + " " + str(r) iD, sD, rD, N, ct = iter_procs(iD, sD, rD, ps, ct) if (ct > 1400 and ct%100 == 0) or (ct == 1): output(iD, sD, rD, sim, ct, r) for sim in range(500):#number of different models run (had been set at 10**6) seed(time.time()) gr = np.random.uniform(-2,-1) mt = np.random.uniform(-2,-1) rls_min = randint(1,10) rls_max = randint(rls_min,100) grcv = np.random.uniform(-6,-0.3) mtcv = np.random.uniform(-6,-0.3) rlscv = np.random.uniform(-6,-0.3) efcv = np.random.uniform(-6,-0.3) q = choice([1, 2]) a=.35#a can take values [0,0.5) run_model(sim, gr, mt, q, rls_min, rls_max, grcv, mtcv, rlscv, efcv, a)
unknown
codeparrot/codeparrot-clean
package libnetwork import ( "context" "fmt" "sync" "time" "github.com/containerd/log" "github.com/moby/moby/api/types/system" "github.com/moby/moby/v2/daemon/libnetwork/internal/nftables" "github.com/moby/moby/v2/daemon/libnetwork/iptables" "github.com/moby/moby/v2/daemon/libnetwork/osl" ) // FirewallBackend returns the name of the firewall backend for "docker info". func (c *Controller) FirewallBackend() *system.FirewallInfo { var info system.FirewallInfo info.Driver = "iptables" if nftables.Enabled() { info.Driver = "nftables" } if iptables.UsingFirewalld() { info.Driver += "+firewalld" if reloadedAt := iptables.FirewalldReloadedAt(); !reloadedAt.IsZero() { info.Info = [][2]string{{"ReloadedAt", reloadedAt.Format(time.RFC3339)}} } } return &info } // enabledIptablesVersions returns the iptables versions that are enabled // for the controller. func (c *Controller) enabledIptablesVersions() []iptables.IPVersion { var versions []iptables.IPVersion if c.cfg.BridgeConfig.EnableIPTables { versions = append(versions, iptables.IPv4) } if c.cfg.BridgeConfig.EnableIP6Tables { versions = append(versions, iptables.IPv6) } return versions } // getDefaultOSLSandbox returns the controller's default [osl.Sandbox]. It // creates the sandbox if it does not yet exist. func (c *Controller) getDefaultOSLSandbox(key string) (*osl.Namespace, error) { var err error c.defOsSboxOnce.Do(func() { c.defOsSbox, err = osl.NewSandbox(key, false, false) }) if err != nil { c.defOsSboxOnce = sync.Once{} return nil, fmt.Errorf("failed to create default sandbox: %v", err) } return c.defOsSbox, nil } // setupOSLSandbox sets the sandbox [osl.Sandbox], and applies operating- // specific configuration. // // Depending on the Sandbox settings, it may either use the Controller's // default sandbox, or configure a new one. func (c *Controller) setupOSLSandbox(sb *Sandbox) error { if sb.config.useDefaultSandBox { defSB, err := c.getDefaultOSLSandbox(sb.Key()) if err != nil { return err } sb.osSbox = defSB } if sb.osSbox == nil && !sb.config.useExternalKey { newSB, err := osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox, false) if err != nil { return fmt.Errorf("failed to create new osl sandbox: %v", err) } sb.osSbox = newSB } if sb.osSbox != nil { // Apply operating specific knobs on the load balancer sandbox err := sb.osSbox.InvokeFunc(func() { sb.osSbox.ApplyOSTweaks(sb.oslTypes) }) if err != nil { log.G(context.TODO()).Errorf("Failed to apply performance tuning sysctls to the sandbox: %v", err) } // Keep this just so performance is not changed sb.osSbox.ApplyOSTweaks(sb.oslTypes) } return nil }
go
github
https://github.com/moby/moby
daemon/libnetwork/controller_linux.go
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver\Operation; use Composer\Package\AliasPackage; /** * Solver install operation. * * @author Nils Adermann <naderman@naderman.de> */ class MarkAliasInstalledOperation extends SolverOperation implements OperationInterface { protected const TYPE = 'markAliasInstalled'; /** * @var AliasPackage */ protected $package; public function __construct(AliasPackage $package) { $this->package = $package; } /** * Returns package instance. */ public function getPackage(): AliasPackage { return $this->package; } /** * @inheritDoc */ public function show($lock): string { return 'Marking <info>'.$this->package->getPrettyName().'</info> (<comment>'.$this->package->getFullPrettyVersion().'</comment>) as installed, alias of <info>'.$this->package->getAliasOf()->getPrettyName().'</info> (<comment>'.$this->package->getAliasOf()->getFullPrettyVersion().'</comment>)'; } }
php
github
https://github.com/composer/composer
src/Composer/DependencyResolver/Operation/MarkAliasInstalledOperation.php
# -*- coding: utf-8 -*- # vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4 ############################################################################### # OpenLP - Open Source Lyrics Projection # # --------------------------------------------------------------------------- # # Copyright (c) 2008-2015 OpenLP Developers # # --------------------------------------------------------------------------- # # This program is free software; you can redistribute it and/or modify it # # under the terms of the GNU General Public License as published by the Free # # Software Foundation; version 2 of the License. # # # # This program is distributed in the hope that it will be useful, but WITHOUT # # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # # more details. # # # # You should have received a copy of the GNU General Public License along # # with this program; if not, write to the Free Software Foundation, Inc., 59 # # Temple Place, Suite 330, Boston, MA 02111-1307 USA # ###############################################################################
unknown
codeparrot/codeparrot-clean
from typing import TYPE_CHECKING, Any from langchain_classic._api import create_importer if TYPE_CHECKING: from langchain_community.vectorstores import PGVector from langchain_community.vectorstores.pgvector import DistanceStrategy # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling optional imports. DEPRECATED_LOOKUP = { "DistanceStrategy": "langchain_community.vectorstores.pgvector", "PGVector": "langchain_community.vectorstores", } _import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP) def __getattr__(name: str) -> Any: """Look up attributes dynamically.""" return _import_attribute(name) __all__ = [ "DistanceStrategy", "PGVector", ]
python
github
https://github.com/langchain-ai/langchain
libs/langchain/langchain_classic/vectorstores/pgvector.py
# Copyright (C) 2009 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import logging from webkitpy.tool import steps from webkitpy.common.checkout.scm import CheckoutNeedsUpdate from webkitpy.common.system.executive import ScriptError from webkitpy.tool.bot.queueengine import QueueEngine _log = logging.getLogger(__name__) class StepSequenceErrorHandler(): @classmethod def handle_script_error(cls, tool, patch, script_error): raise NotImplementedError, "subclasses must implement" @classmethod def handle_checkout_needs_update(cls, tool, state, options, error): raise NotImplementedError, "subclasses must implement" class StepSequence(object): def __init__(self, steps): self._steps = steps or [] def options(self): collected_options = [ steps.Options.parent_command, steps.Options.quiet, ] for step in self._steps: collected_options = collected_options + step.options() # Remove duplicates. collected_options = sorted(set(collected_options)) return collected_options def _run(self, tool, options, state): for step in self._steps: step(tool, options).run(state) def run_and_handle_errors(self, tool, options, state=None): if not state: state = {} try: self._run(tool, options, state) except CheckoutNeedsUpdate, e: _log.info("Commit failed because the checkout is out of date. Please update and try again.") if options.parent_command: command = tool.command_by_name(options.parent_command) command.handle_checkout_needs_update(tool, state, options, e) QueueEngine.exit_after_handled_error(e) except ScriptError, e: if not options.quiet: _log.error(e.message_with_output()) if options.parent_command: command = tool.command_by_name(options.parent_command) command.handle_script_error(tool, state, e) QueueEngine.exit_after_handled_error(e)
unknown
codeparrot/codeparrot-clean
import { type ComponentInternalInstance, type ComponentOptions, warn, } from 'vue' import { compile } from '@vue/compiler-ssr' import { NO, extend, generateCodeFrame, isFunction } from '@vue/shared' import type { CompilerError, CompilerOptions } from '@vue/compiler-core' import type { PushFn } from '../render' import * as Vue from 'vue' import * as helpers from '../internal' type SSRRenderFunction = ( context: any, push: PushFn, parentInstance: ComponentInternalInstance, ) => void const compileCache: Record<string, SSRRenderFunction> = Object.create(null) export function ssrCompile( template: string, instance: ComponentInternalInstance, ): SSRRenderFunction { // TODO: this branch should now work in ESM builds, enable it in a minor if (!__CJS__) { throw new Error( `On-the-fly template compilation is not supported in the ESM build of ` + `@vue/server-renderer. All templates must be pre-compiled into ` + `render functions.`, ) } // TODO: This is copied from runtime-core/src/component.ts and should probably be refactored const Component = instance.type as ComponentOptions const { isCustomElement, compilerOptions } = instance.appContext.config const { delimiters, compilerOptions: componentCompilerOptions } = Component const finalCompilerOptions: CompilerOptions = extend( extend( { isCustomElement, delimiters, }, compilerOptions, ), componentCompilerOptions, ) finalCompilerOptions.isCustomElement = finalCompilerOptions.isCustomElement || NO finalCompilerOptions.isNativeTag = finalCompilerOptions.isNativeTag || NO const cacheKey = JSON.stringify( { template, compilerOptions: finalCompilerOptions, }, (key, value) => { return isFunction(value) ? value.toString() : value }, ) const cached = compileCache[cacheKey] if (cached) { return cached } finalCompilerOptions.onError = (err: CompilerError) => { if (__DEV__) { const message = `[@vue/server-renderer] Template compilation error: ${err.message}` const codeFrame = err.loc && generateCodeFrame( template as string, err.loc.start.offset, err.loc.end.offset, ) warn(codeFrame ? `${message}\n${codeFrame}` : message) } else { throw err } } const { code } = compile(template, finalCompilerOptions) const requireMap = { vue: Vue, 'vue/server-renderer': helpers, } const fakeRequire = (id: 'vue' | 'vue/server-renderer') => requireMap[id] return (compileCache[cacheKey] = Function('require', code)(fakeRequire)) }
typescript
github
https://github.com/vuejs/core
packages/server-renderer/src/helpers/ssrCompile.ts
#!/usr/bin/env python # -*- coding: utf-8 -*- # Call Web2py scheduler in app models context and run a specified task using # its scheduled arguments. Two options for running this script: # # cd web2py # python applications/<app>/static/scripts/tools/run_scheduler_tasks.py --app=<app> --task=<task> # -- or -- # export WEB2PY_PATH=/path/to/web2py # cd $WEB2PY_PATH/applications/<app>/static/scripts/tools # python run_scheduler_tasks.py --app=<app> --task=<task> # # If task is omitted this will run all scheduled tasks sequentially. If both # args are omitted, the app will default to eden. # # Purpose of this is to allow executing tasks with the Eclipse debugger -- the # usual ways of starting a scheduler worker launchs it in a separate thread or # via exec, which the debugger doesn't step into. # # To set up an Eclipse run config, duplicate your Web2py run config, replace # the file to run with this script, and add at least the --app argument. # The WEB2PY_PATH is not needed in this case since the working directory will # be set to the web2py directory. # # The statement that executes the task function is marked with a comment: # SET BREAKPOINT HERE # Find that, set a breakpoint on that line, then step into the function. import os, sys, argparse if not "WEB2PY_PATH" in os.environ: os.environ["WEB2PY_PATH"] = os.getcwd() else: os.chdir(os.environ["WEB2PY_PATH"]) sys.path.append(os.environ["WEB2PY_PATH"]) if __name__ == "__main__": parser = argparse.ArgumentParser( description = """ Run Web2py scheduler tasks in Web2py application context, without the scheduler. Useful for executing the task in a debugger. Tasks must be scheduled in order to provide their arguments -- they won't be run if not scheduled. If task is specified, the first scheduled instance will be run. If task is not specified, the first scheduled instance for each task will be run sequentially. """, usage = """ export WEB2PY_PATH = /path/to/web2py; python run_scheduler_tasks.py --app=<app> [--task=<task>] [--allargs=<True|False>] """) parser.add_argument( "--app", dest="app", default="eden", help="Application directory name") parser.add_argument( "--task", dest="task", default=None, help="Task name") parser.add_argument( "--allargs", dest="allargs", default=True, help="If True (the default), run task with all scheduled arg sets. If False, run with first set encountered only.") args = vars(parser.parse_args()) app = args["app"] task = args["task"] allargs = args["allargs"] adir = os.path.join("applications", app) if not os.path.exists(adir): print >> sys.stderr, "Application not found: %s" % adir sys.exit(1) from gluon.custom_import import custom_import_install custom_import_install() from gluon.shell import env _env = env(app, c=None, import_models=True) globals().update(**_env) # This is present in case this is a first run of the models. db.commit() from gluon import current # Get tasks from the scheduler_task table. if task: query = (db.scheduler_task.task_name == task) else: query = (db.scheduler_task.id > 0) scheduled_tasks = db(query).select(orderby=db.scheduler_task.task_name) # Pick up the associated function objects from the scheduler's task list. # These are also stored in the S3Task instance -- both lists should be the # same. posted_tasks = current._scheduler.tasks #posted_tasks = current.response.s3.tasks task_name = None for task_row in scheduled_tasks: if not allargs and task_row.task_name == task_name: continue task_name = task_row.task_name task_function = posted_tasks.get(task_name, None) if not task_function: print >> sys.stderr, "Skipping task %s as no function in task list" % task_name continue # That args list and vars dict are stored as strings. if task_row.args: task_args = eval(task_row.args) else: task_args = [] if task_row.vars: task_vars = eval(task_row.vars) else: task_vars = {} try: # To examine each task function in the debugger, set a breakpoint # here, then step into the function. task_function(*task_args, **task_vars) # SET BREAKPOINT HERE except Exception: print >> sys.stderr, "Task %s threw:\n" % task_name import traceback exc_type, exc_value, exc_trace = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_trace, file=sys.stderr) try: # Python docs for sys.exc_info() warn that one must clean up the # extracted trace object. del exc_trace except: pass
unknown
codeparrot/codeparrot-clean
/*------------------------------------------------------------------------- * * file_ops.h * Helper functions for operating on files * * Copyright (c) 2013-2026, PostgreSQL Global Development Group * *------------------------------------------------------------------------- */ #ifndef FILE_OPS_H #define FILE_OPS_H #include "filemap.h" extern void open_target_file(const char *path, bool trunc); extern void write_target_range(char *buf, off_t begin, size_t size); extern void close_target_file(void); extern void remove_target_file(const char *path, bool missing_ok); extern void truncate_target_file(const char *path, off_t newsize); extern void create_target(file_entry_t *entry); extern void remove_target(file_entry_t *entry); extern void sync_target_dir(void); extern char *slurpFile(const char *datadir, const char *path, size_t *filesize); typedef void (*process_file_callback_t) (const char *path, file_type_t type, size_t size, const char *link_target); extern void traverse_datadir(const char *datadir, process_file_callback_t callback); #endif /* FILE_OPS_H */
c
github
https://github.com/postgres/postgres
src/bin/pg_rewind/file_ops.h
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Helper file to manipulate entity keys and names.""" def EntityKind(key): """Given entity primary key as Reference Proto, returns entity kind. Args: key: primary key of entity in ReferenceProto form. Returns: Kind of entity in string format. Returns '' if kind cannot be determined in some unexpected scenario. """ if key.path().element_list(): return key.path().element_list()[-1].type() else: return '' def EntityGroupKind(key): """Given entity primary key as Reference Proto, returns kind of entity group. Args: key: primary key of entity in ReferenceProto form. Returns: Kind of entity group that entity belongs to in string format. """ return key.path().element(0).type() def EntityListKind(keylist): """Given list of entity keys, return entity kind. Args: keylist: list of primary keys of entities in ReferenceProto form. Returns: Kind of entity. Returns 'None' if list is empty and 'Multi' if entities in the list are of different kinds. """ kinds = map(EntityKind, keylist) unique_kinds = set(kinds) numkinds = len(unique_kinds) if numkinds > 1: return 'Multi' elif numkinds == 1: return unique_kinds.pop() else: return 'None' def EntityGroupName(entity): """Given entity primary key as Reference Proto, returns entity group. Args: entity: primary key of entity in ReferenceProto form Returns: Name of entitygroup in string format. """ element = entity.path().element(0) if element.has_id(): return str(element.id()) elif element.has_name(): return element.name() else: return 'None' def EntityFullName(entity): """Given entity primary key as a Reference Proto, returns full name. This is a concatenation of entity information along the entire path, and includes entity kind and entity name (or id) at each level. Args: entity: primary key of entity in ReferenceProto form Returns: Full name of entity in string format with dots delimiting each element in the path. Each element is represented as 'entity_kind:entity_id' or 'entity_kind:entity_name' as applicable. """ names = [] for element in entity.path().element_list(): if element.has_id(): name = '%s:%s' %(element.type(), str(element.id())) elif element.has_name(): name = '%s:%s' %(element.type(), str(element.name())) else: name = '%s:None' %(element.type()) names.append(name) fullname = '.'.join(names) return fullname
unknown
codeparrot/codeparrot-clean
"""Module that defines indexed objects The classes IndexedBase, Indexed and Idx would represent a matrix element M[i, j] as in the following graph:: 1) The Indexed class represents the entire indexed object. | ___|___ ' ' M[i, j] / \__\______ | | | | | 2) The Idx class represent indices and each Idx can | optionally contain information about its range. | 3) IndexedBase represents the `stem' of an indexed object, here `M'. The stem used by itself is usually taken to represent the entire array. There can be any number of indices on an Indexed object. No transformation properties are implemented in these Base objects, but implicit contraction of repeated indices is supported. Note that the support for complicated (i.e. non-atomic) integer expressions as indices is limited. (This should be improved in future releases.) Examples ======== To express the above matrix element example you would write: >>> from sympy.tensor import IndexedBase, Idx >>> from sympy import symbols >>> M = IndexedBase('M') >>> i, j = symbols('i j', cls=Idx) >>> M[i, j] M[i, j] Repeated indices in a product implies a summation, so to express a matrix-vector product in terms of Indexed objects: >>> x = IndexedBase('x') >>> M[i, j]*x[j] x[j]*M[i, j] If the indexed objects will be converted to component based arrays, e.g. with the code printers or the autowrap framework, you also need to provide (symbolic or numerical) dimensions. This can be done by passing an optional shape parameter to IndexedBase upon construction: >>> dim1, dim2 = symbols('dim1 dim2', integer=True) >>> A = IndexedBase('A', shape=(dim1, 2*dim1, dim2)) >>> A.shape (dim1, 2*dim1, dim2) >>> A[i, j, 3].shape (dim1, 2*dim1, dim2) If an IndexedBase object has no shape information, it is assumed that the array is as large as the ranges of its indices: >>> n, m = symbols('n m', integer=True) >>> i = Idx('i', m) >>> j = Idx('j', n) >>> M[i, j].shape (m, n) >>> M[i, j].ranges [(0, m - 1), (0, n - 1)] The above can be compared with the following: >>> A[i, 2, j].shape (dim1, 2*dim1, dim2) >>> A[i, 2, j].ranges [(0, m - 1), None, (0, n - 1)] To analyze the structure of indexed expressions, you can use the methods get_indices() and get_contraction_structure(): >>> from sympy.tensor import get_indices, get_contraction_structure >>> get_indices(A[i, j, j]) (set([i]), {}) >>> get_contraction_structure(A[i, j, j]) {(j,): set([A[i, j, j]])} See the appropriate docstrings for a detailed explanation of the output. """ # TODO: (some ideas for improvement) # # o test and guarantee numpy compatibility # - implement full support for broadcasting # - strided arrays # # o more functions to analyze indexed expressions # - identify standard constructs, e.g matrix-vector product in a subexpression # # o functions to generate component based arrays (numpy and sympy.Matrix) # - generate a single array directly from Indexed # - convert simple sub-expressions # # o sophisticated indexing (possibly in subclasses to preserve simplicity) # - Idx with range smaller than dimension of Indexed # - Idx with stepsize != 1 # - Idx with step determined by function call from __future__ import print_function, division from sympy.core import Expr, Tuple, Symbol, sympify, S from sympy.core.compatibility import is_sequence, string_types, NotIterable, range class IndexException(Exception): pass class Indexed(Expr): """Represents a mathematical object with indices. >>> from sympy.tensor import Indexed, IndexedBase, Idx >>> from sympy import symbols >>> i, j = symbols('i j', cls=Idx) >>> Indexed('A', i, j) A[i, j] It is recommended that Indexed objects are created via IndexedBase: >>> A = IndexedBase('A') >>> Indexed('A', i, j) == A[i, j] True """ is_commutative = True def __new__(cls, base, *args): from sympy.utilities.misc import filldedent if not args: raise IndexException("Indexed needs at least one index.") if isinstance(base, (string_types, Symbol)): base = IndexedBase(base) elif not hasattr(base, '__getitem__') and not isinstance(base, IndexedBase): raise TypeError(filldedent(""" Indexed expects string, Symbol or IndexedBase as base.""")) args = list(map(sympify, args)) return Expr.__new__(cls, base, *args) @property def base(self): """Returns the IndexedBase of the Indexed object. Examples ======== >>> from sympy.tensor import Indexed, IndexedBase, Idx >>> from sympy import symbols >>> i, j = symbols('i j', cls=Idx) >>> Indexed('A', i, j).base A >>> B = IndexedBase('B') >>> B == B[i, j].base True """ return self.args[0] @property def indices(self): """ Returns the indices of the Indexed object. Examples ======== >>> from sympy.tensor import Indexed, Idx >>> from sympy import symbols >>> i, j = symbols('i j', cls=Idx) >>> Indexed('A', i, j).indices (i, j) """ return self.args[1:] @property def rank(self): """ Returns the rank of the Indexed object. Examples ======== >>> from sympy.tensor import Indexed, Idx >>> from sympy import symbols >>> i, j, k, l, m = symbols('i:m', cls=Idx) >>> Indexed('A', i, j).rank 2 >>> q = Indexed('A', i, j, k, l, m) >>> q.rank 5 >>> q.rank == len(q.indices) True """ return len(self.args) - 1 @property def shape(self): """Returns a list with dimensions of each index. Dimensions is a property of the array, not of the indices. Still, if the IndexedBase does not define a shape attribute, it is assumed that the ranges of the indices correspond to the shape of the array. >>> from sympy.tensor.indexed import IndexedBase, Idx >>> from sympy import symbols >>> n, m = symbols('n m', integer=True) >>> i = Idx('i', m) >>> j = Idx('j', m) >>> A = IndexedBase('A', shape=(n, n)) >>> B = IndexedBase('B') >>> A[i, j].shape (n, n) >>> B[i, j].shape (m, m) """ from sympy.utilities.misc import filldedent if self.base.shape: return self.base.shape try: return Tuple(*[i.upper - i.lower + 1 for i in self.indices]) except AttributeError: raise IndexException(filldedent(""" Range is not defined for all indices in: %s""" % self)) except TypeError: raise IndexException(filldedent(""" Shape cannot be inferred from Idx with undefined range: %s""" % self)) @property def ranges(self): """Returns a list of tuples with lower and upper range of each index. If an index does not define the data members upper and lower, the corresponding slot in the list contains ``None`` instead of a tuple. Examples ======== >>> from sympy import Indexed,Idx, symbols >>> Indexed('A', Idx('i', 2), Idx('j', 4), Idx('k', 8)).ranges [(0, 1), (0, 3), (0, 7)] >>> Indexed('A', Idx('i', 3), Idx('j', 3), Idx('k', 3)).ranges [(0, 2), (0, 2), (0, 2)] >>> x, y, z = symbols('x y z', integer=True) >>> Indexed('A', x, y, z).ranges [None, None, None] """ ranges = [] for i in self.indices: try: ranges.append(Tuple(i.lower, i.upper)) except AttributeError: ranges.append(None) return ranges def _sympystr(self, p): indices = list(map(p.doprint, self.indices)) return "%s[%s]" % (p.doprint(self.base), ", ".join(indices)) class IndexedBase(Expr, NotIterable): """Represent the base or stem of an indexed object The IndexedBase class represent an array that contains elements. The main purpose of this class is to allow the convenient creation of objects of the Indexed class. The __getitem__ method of IndexedBase returns an instance of Indexed. Alone, without indices, the IndexedBase class can be used as a notation for e.g. matrix equations, resembling what you could do with the Symbol class. But, the IndexedBase class adds functionality that is not available for Symbol instances: - An IndexedBase object can optionally store shape information. This can be used in to check array conformance and conditions for numpy broadcasting. (TODO) - An IndexedBase object implements syntactic sugar that allows easy symbolic representation of array operations, using implicit summation of repeated indices. - The IndexedBase object symbolizes a mathematical structure equivalent to arrays, and is recognized as such for code generation and automatic compilation and wrapping. >>> from sympy.tensor import IndexedBase, Idx >>> from sympy import symbols >>> A = IndexedBase('A'); A A >>> type(A) <class 'sympy.tensor.indexed.IndexedBase'> When an IndexedBase object receives indices, it returns an array with named axes, represented by an Indexed object: >>> i, j = symbols('i j', integer=True) >>> A[i, j, 2] A[i, j, 2] >>> type(A[i, j, 2]) <class 'sympy.tensor.indexed.Indexed'> The IndexedBase constructor takes an optional shape argument. If given, it overrides any shape information in the indices. (But not the index ranges!) >>> m, n, o, p = symbols('m n o p', integer=True) >>> i = Idx('i', m) >>> j = Idx('j', n) >>> A[i, j].shape (m, n) >>> B = IndexedBase('B', shape=(o, p)) >>> B[i, j].shape (o, p) """ is_commutative = True def __new__(cls, label, shape=None, **kw_args): if isinstance(label, string_types): label = Symbol(label) elif isinstance(label, Symbol): pass else: raise TypeError("Base label should be a string or Symbol.") if is_sequence(shape): shape = Tuple(*shape) else: shape = sympify(shape) if shape is not None: obj = Expr.__new__(cls, label, shape, **kw_args) else: obj = Expr.__new__(cls, label, **kw_args) obj._shape = shape return obj def __getitem__(self, indices, **kw_args): if is_sequence(indices): # Special case needed because M[*my_tuple] is a syntax error. if self.shape and len(self.shape) != len(indices): raise IndexException("Rank mismatch.") return Indexed(self, *indices, **kw_args) else: if self.shape and len(self.shape) != 1: raise IndexException("Rank mismatch.") return Indexed(self, indices, **kw_args) @property def shape(self): """Returns the shape of the IndexedBase object. Examples ======== >>> from sympy import IndexedBase, Idx, Symbol >>> from sympy.abc import x, y >>> IndexedBase('A', shape=(x, y)).shape (x, y) Note: If the shape of the IndexedBase is specified, it will override any shape information given by the indices. >>> A = IndexedBase('A', shape=(x, y)) >>> B = IndexedBase('B') >>> i = Idx('i', 2) >>> j = Idx('j', 1) >>> A[i, j].shape (x, y) >>> B[i, j].shape (2, 1) """ return self._shape @property def label(self): """Returns the label of the IndexedBase object. Examples ======== >>> from sympy import IndexedBase >>> from sympy.abc import x, y >>> IndexedBase('A', shape=(x, y)).label A """ return self.args[0] def _sympystr(self, p): return p.doprint(self.label) class Idx(Expr): """Represents an integer index as an Integer or integer expression. There are a number of ways to create an Idx object. The constructor takes two arguments: ``label`` An integer or a symbol that labels the index. ``range`` Optionally you can specify a range as either - Symbol or integer: This is interpreted as a dimension. Lower and upper bounds are set to 0 and range - 1, respectively. - tuple: The two elements are interpreted as the lower and upper bounds of the range, respectively. Note: the Idx constructor is rather pedantic in that it only accepts integer arguments. The only exception is that you can use oo and -oo to specify an unbounded range. For all other cases, both label and bounds must be declared as integers, e.g. if n is given as an argument then n.is_integer must return True. For convenience, if the label is given as a string it is automatically converted to an integer symbol. (Note: this conversion is not done for range or dimension arguments.) Examples ======== >>> from sympy.tensor import Idx >>> from sympy import symbols, oo >>> n, i, L, U = symbols('n i L U', integer=True) If a string is given for the label an integer Symbol is created and the bounds are both None: >>> idx = Idx('qwerty'); idx qwerty >>> idx.lower, idx.upper (None, None) Both upper and lower bounds can be specified: >>> idx = Idx(i, (L, U)); idx i >>> idx.lower, idx.upper (L, U) When only a single bound is given it is interpreted as the dimension and the lower bound defaults to 0: >>> idx = Idx(i, n); idx.lower, idx.upper (0, n - 1) >>> idx = Idx(i, 4); idx.lower, idx.upper (0, 3) >>> idx = Idx(i, oo); idx.lower, idx.upper (0, oo) """ is_integer = True def __new__(cls, label, range=None, **kw_args): from sympy.utilities.misc import filldedent if isinstance(label, string_types): label = Symbol(label, integer=True) label, range = list(map(sympify, (label, range))) if label.is_Number: if not label.is_integer: raise TypeError("Index is not an integer number.") return label if not label.is_integer: raise TypeError("Idx object requires an integer label.") elif is_sequence(range): if len(range) != 2: raise ValueError(filldedent(""" Idx range tuple must have length 2, but got %s""" % len(range))) for bound in range: if not (bound.is_integer or abs(bound) is S.Infinity): raise TypeError("Idx object requires integer bounds.") args = label, Tuple(*range) elif isinstance(range, Expr): if not (range.is_integer or range is S.Infinity): raise TypeError("Idx object requires an integer dimension.") args = label, Tuple(0, range - 1) elif range: raise TypeError(filldedent(""" The range must be an ordered iterable or integer SymPy expression.""")) else: args = label, obj = Expr.__new__(cls, *args, **kw_args) return obj @property def label(self): """Returns the label (Integer or integer expression) of the Idx object. Examples ======== >>> from sympy import Idx, Symbol >>> x = Symbol('x', integer=True) >>> Idx(x).label x >>> j = Symbol('j', integer=True) >>> Idx(j).label j >>> Idx(j + 1).label j + 1 """ return self.args[0] @property def lower(self): """Returns the lower bound of the Index. Examples ======== >>> from sympy import Idx >>> Idx('j', 2).lower 0 >>> Idx('j', 5).lower 0 >>> Idx('j').lower is None True """ try: return self.args[1][0] except IndexError: return @property def upper(self): """Returns the upper bound of the Index. Examples ======== >>> from sympy import Idx >>> Idx('j', 2).upper 1 >>> Idx('j', 5).upper 4 >>> Idx('j').upper is None True """ try: return self.args[1][1] except IndexError: return def _sympystr(self, p): return p.doprint(self.label)
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- # # Doctrine 2 ORM documentation build configuration file, created by # sphinx-quickstart on Fri Dec 3 18:10:24 2010. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.append(os.path.abspath('_exts')) # -- General configuration ----------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['configurationblock'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Doctrine 2 ORM' copyright = u'2010-12, Doctrine Project Team' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '2' # The full version, including alpha/beta/rc tags. release = '2' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. language = 'en' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. show_authors = True # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. html_theme = 'doctrine' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['_theme'] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'Doctrine2ORMdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Doctrine2ORM.tex', u'Doctrine 2 ORM Documentation', u'Doctrine Project Team', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True primary_domain = "dcorm" def linkcode_resolve(domain, info): if domain == 'dcorm': return 'http://' return None
unknown
codeparrot/codeparrot-clean
# -*- encoding: utf-8 -*- ############################################################################## # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see http://www.gnu.org/licenses/. # ############################################################################## { "name": "Purchase Stock Quant Shortcut", "version": "1.0", "depends": [ "purchase", "stock_quants_shortcuts", ], "author": "OdooMRP team," "AvanzOSC," "Serv. Tecnol. Avanzados - Pedro M. Baeza", "contributors": [ "Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>", ], "category": "Hidden/Dependency", "website": "http://www.odoomrp.com", "summary": "", "data": [ "views/purchase_order_view.xml", ], "installable": True, "auto_install": True, }
unknown
codeparrot/codeparrot-clean
# Copyright (c) 2011-2012, 30loops.net # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of 30loops.net nor the names of its contributors may # be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL 30loops.net BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Environment dictionary - support structures""" class _AttributeDict(dict): """ Dictionary subclass enabling attribute lookup/assignment of keys/values. For example:: >>> m = _AttributeDict({'foo': 'bar'}) >>> m.foo 'bar' >>> m.foo = 'not bar' >>> m['foo'] 'not bar' ``_AttributeDict`` objects also provide ``.first()`` which acts like ``.get()`` but accepts multiple keys as arguments, and returns the value of the first hit, e.g.:: >>> m = _AttributeDict({'foo': 'bar', 'biz': 'baz'}) >>> m.first('wrong', 'incorrect', 'foo', 'biz') 'bar' """ def __getattr__(self, key): try: return self[key] except KeyError: # to conform with __getattr__ spec raise AttributeError(key) def __setattr__(self, key, value): self[key] = value def first(self, *names): for name in names: value = self.get(name) if value: return value # Global config dictionary. Stores the global state. env = _AttributeDict({ 'base_uri': 'https://api.30loops.net', 'api_version': '0.9', 'account': None, 'service': None, 'appname': None, 'username': None, 'password': None }) def uri( base_uri=None, api_version=None, account=None): """Compose the base uri.""" if not base_uri: base_uri = env.base_uri if not api_version: api_version = env.api_version if not account: account = env.account path = [] path.append(api_version.strip('/')) if not isinstance(account, type(None)): path.append(account.strip('/')) return "%s/%s" % (base_uri.strip('/'), '/'.join(path)) def app_uri( base_uri=None, api_version=None, account=None, appname=None): """Compose the app uri.""" if not appname: appname = env.appname return "%s/apps/%s" % (uri(base_uri, api_version, account), appname) def service_uri( base_uri=None, api_version=None, account=None, appname=None, service=None): """Compose as service uri.""" if not service: service = env.service return "%s/services/%s" % (app_uri(base_uri, api_version, account, appname), service) def resource_collection_uri( base_uri=None, api_version=None, account=None, label=None): """Return the URI of a resource as a string.""" if not base_uri: base_uri = env.base_uri if not api_version: api_version = env.api_version if not account: account = env.account if not label: label = env.label path = [] path.append(api_version.strip('/')) path.append(account.strip('/')) path.append(label.strip('/')) return "%s/%s" % (base_uri.strip('/'), '/'.join(path))
unknown
codeparrot/codeparrot-clean