Skip to content

Handling of BOM (byte order mark) in source files #4353

Closed

Description

@squiddy

Feature

PEP 263 specifies that

To aid with platforms such as Windows, which add Unicode BOM marks to the beginning of Unicode files, the UTF-8 signature \xef\xbb\xbf will be interpreted as ‘utf-8’ encoding as well (even if no magic encoding comment is given).

However, RustPython currently fails on files that include a BOM.

$ printf '\xEF\xBB\xBF' > f.py
$ cargo run f.py
SyntaxError: Got unexpected token  at line 1 column 1

^

Python Documentation

Not familiar with CPython source code, but some pointers:

https://github.com/python/cpython/blob/3.11/Lib/tokenize.py#L299 (detect_encoding)
https://github.com/python/cpython/blob/3.11/Lib/test/test_importlib/source/test_source_encoding.py

Activity

  1. fanninpm commented on Dec 24, 2022

    @fanninpm
    Contributor

    I remember encountering something like this before, in #3919 (comment).

  2. yt2b commented on Dec 24, 2022

    @yt2b
    Contributor

    Checking whether BOM exists is needed.

    But in Rust, UTF-8 BOM(EF BB BF) is recognized as FE FF when converted from bytes to String.

    let utf8_bom = vec![0xef, 0xbb, 0xbf];
    println!("{:?}", String::from_utf8(utf8_bom)); // Ok("\u{feff}")
  3. DimitrisJim commented on Dec 26, 2022

    @DimitrisJim
    Member

    Thanks for reporting this @squiddy! #4359 fixed the erroneous SyntaxError, handling of the mismatch between it and an encoding declaration that differs is not handled (and silently ignored atm) so keep that in mind.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions