#prog #rust хайлайты
Пару недель назад из лексера убрали зависимость от парсера. Почему эта зависимость была? Один из методов для восстановления от незакрытого разделителя полагался на создание временного парсера для того, чтобы давать диагностику получше. Как следствие, после этого изменения для парочки крайних случаев качество диагностик несколько снизилось.
Пару недель назад из лексера убрали зависимость от парсера. Почему эта зависимость была? Один из методов для восстановления от незакрытого разделителя полагался на создание временного парсера для того, чтобы давать диагностику получше. Как следствие, после этого изменения для парочки крайних случаев качество диагностик несколько снизилось.
GitHub
Remove `Lexer`'s dependency on `Parser`. by nnethercote · Pull Request #134192 · rust-lang/rust
Lexing precedes parsing, as you'd expect: Lexer creates a TokenStream and Parser then parses that TokenStream.
But, in a horrendous violation of layering abstractions and common sense, Lexe...
But, in a horrendous violation of layering abstractions and common sense, Lexe...
#prog #article
Storing currency values: data types, caveats, best practices
This article is not the final source of the truth, but it contains useful information that you should take into consideration when designing software.
(thanks @badassorange)
Storing currency values: data types, caveats, best practices
This article is not the final source of the truth, but it contains useful information that you should take into consideration when designing software.
(thanks @badassorange)
cardinalby.github.io
Storing currency values: data types, caveats, best practices
Intro Repeatedly facing questions, debates, and mistakes related to storing and representing currency amounts, I decided to collect all facts and advice regarding this topic in one place. This article is not the final source of the truth, but it contains…
#prog #rust #article
Thoughts on Rust hashing
Или о том, как дизайн API для хеширования в Rust напрямую ведёт к неэффективностям.
Thoughts on Rust hashing
Или о том, как дизайн API для хеширования в Rust напрямую ведёт к неэффективностям.
purplesyringa's blog
Thoughts on Rust hashing
In languages like Python, Java, or C++, values are hashed by calling a “hash me” method on them, implemented by the type author. This fixed-hash size is then immediately used by the hash table or what have you. This design suffers from some obvious problems…
Forwarded from Таксики и лытдыбр σποραδικος
Короче.
У нас по соседству с кладбищем находится цирк.
И если это не объясняет всю нашу жизнь, то что тогда.
У нас по соседству с кладбищем находится цирк.
И если это не объясняет всю нашу жизнь, то что тогда.
#prog #rust #article
Four limitations of Rust's borrow checker
In this post, I’ll cover four surprising limitations of the borrow checker that I ran into in the course of my work.
Also note that when I say something can’t be done, I mean that it can’t be done in a way that leverages Rust’s type system, i.e. with static type checking. <...>. It’s never the case that you literally can’t solve a problem at all, since there are always those escape hatches (and I’ll even show examples of an escape hatch I used below), but it is impossible to solve the problem in a way that makes Rust Rust.
Four limitations of Rust's borrow checker
In this post, I’ll cover four surprising limitations of the borrow checker that I ran into in the course of my work.
Also note that when I say something can’t be done, I mean that it can’t be done in a way that leverages Rust’s type system, i.e. with static type checking. <...>. It’s never the case that you literally can’t solve a problem at all, since there are always those escape hatches (and I’ll even show examples of an escape hatch I used below), but it is impossible to solve the problem in a way that makes Rust Rust.
Considerations on Codecrafting
Four limitations of Rust’s borrow checker
I’ve been using Rust for hobby projects since 2016 and have been working professionally in Rust since 2021, so I tend to consider myself pretty knowledgeable about Rust. I’m already familiar with all the common limitations of Rust’s type system and how to…
Куплю на Новый год много шоколадных яиц
Съем их все
И буду говорить, что полон сюрпризов
Съем их все
И буду говорить, что полон сюрпризов
Блог*
Юрист (муж. р., ед. число) — поклонник жанра юри
Тотализатор (муж. р., ед. ч.) — человек, устанавливающий тоталитаризм
#prog #rust #article
Compiling C to Safe Rust, Formalized (PDF)
<...> We instead explore a different path, and explore what it would take to translate C to safe Rust; that is, to produce code that is trivially memory safe, because it abides by Rust's type system without caveats. Our work sports several original contributions: a type-directed translation from (a subset of) C to safe Rust; a novel static analysis based on "split trees" that allows expressing C's pointer arithmetic using Rust's slices and splitting operations; an analysis that infers exactly which borrows need to be mutable; and a compilation strategy for C's struct types that is compatible with Rust's distinction between non-owned and owned allocations.
We apply our methodology to existing formally verified C codebases: the HACL* cryptographic library, and binary parsers and serializers from EverParse, and show that the subset of C we support is sufficient to translate both applications to safe Rust. Our evaluation shows that for the few places that do violate Rust's aliasing discipline, automated, surgical rewrites suffice; and that the few strategic copies we insert have a negligible performance impact.
По понятным причинам подход авторов покрывает лишь некоторое подмножество C, но вроде достаточно обширное для написания реалистичных программ.
Парочка претензий:
1. Написанный авторами инструмент пока что отсутствует в публичном доступе, поскольку "will be made public after the review process" (который, судя по всему, ещё не пройден).
2. Два примера кодовых баз, на которых автора проверяли свой инструмент, не были написаны изначально на C, а были написаны, как DSL в F* (для верификации одновременно с трансляцией в C) — на более реалистичных программах подход может показать себя менее эффективно.
Compiling C to Safe Rust, Formalized (PDF)
<...> We instead explore a different path, and explore what it would take to translate C to safe Rust; that is, to produce code that is trivially memory safe, because it abides by Rust's type system without caveats. Our work sports several original contributions: a type-directed translation from (a subset of) C to safe Rust; a novel static analysis based on "split trees" that allows expressing C's pointer arithmetic using Rust's slices and splitting operations; an analysis that infers exactly which borrows need to be mutable; and a compilation strategy for C's struct types that is compatible with Rust's distinction between non-owned and owned allocations.
We apply our methodology to existing formally verified C codebases: the HACL* cryptographic library, and binary parsers and serializers from EverParse, and show that the subset of C we support is sufficient to translate both applications to safe Rust. Our evaluation shows that for the few places that do violate Rust's aliasing discipline, automated, surgical rewrites suffice; and that the few strategic copies we insert have a negligible performance impact.
По понятным причинам подход авторов покрывает лишь некоторое подмножество C, но вроде достаточно обширное для написания реалистичных программ.
Парочка претензий:
1. Написанный авторами инструмент пока что отсутствует в публичном доступе, поскольку "will be made public after the review process" (который, судя по всему, ещё не пройден).
2. Два примера кодовых баз, на которых автора проверяли свой инструмент, не были написаны изначально на C, а были написаны, как DSL в F* (для верификации одновременно с трансляцией в C) — на более реалистичных программах подход может показать себя менее эффективно.
arXiv.org
Compiling C to Safe Rust, Formalized
The popularity of the Rust language continues to explode; yet, many critical codebases remain authored in C, and cannot be realistically rewritten by hand. Automatically translating C to Rust is...
#prog #rust #article
Fish 4.0: The Fish Of Theseus
Довольно подробно описывают различные моменты, возникшие во время переписывания. Советую к прочтению — возможно, портирование далеко не так сложно для вашего проекта, как кажется.
The port wasn’t without challenges, and it did not all go entirely as planned. But overall, it went pretty dang well. We’re now left with a codebase that we like a lot more, that has already gained some features that would have been much more annoying to add with C++, with more on the way, and we did it while creating a separate 3.7 release that also included some cool stuff.
(thanks @teamerlin)
Fish 4.0: The Fish Of Theseus
Довольно подробно описывают различные моменты, возникшие во время переписывания. Советую к прочтению — возможно, портирование далеко не так сложно для вашего проекта, как кажется.
The port wasn’t without challenges, and it did not all go entirely as planned. But overall, it went pretty dang well. We’re now left with a codebase that we like a lot more, that has already gained some features that would have been much more annoying to add with C++, with more on the way, and we did it while creating a separate 3.7 release that also included some cool stuff.
(thanks @teamerlin)
Forwarded from Awful Rust snippets for fun and profit
parsing sequences (like dates or version strings) by matching on part index
playground
original example
thanks to @kanashimia for suggesting this one!
playground
original example
thanks to @kanashimia for suggesting this one!