Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
f2cba0d
Generate the unicode tables from the Unicode Character Database
kddnewton Nov 16, 2026
27c85c9
Match Unicode version per Ruby parsing version
kddnewton Nov 16, 2026
4c48d63
Create pm_options_version_supported_p
kddnewton Nov 16, 2026
19dbae9
Accept version keyword for string queries
kddnewton Nov 16, 2026
93906ec
Read a ? before a non-ASCII identifier as a ternary operator
kddnewton Nov 16, 2026
e9a997f
Allow attributes with non-ASCII names as multiple assignment targets
kddnewton Nov 16, 2026
56af0b9
Add pm_encoding_ascii_alnum_p for the % literal checks
kddnewton Nov 16, 2026
e77b29d
Check the ASCII characters of names in string queries as ASCII
kddnewton Nov 17, 2026
5128866
Read the coding magic comment value as ASCII
kddnewton Nov 17, 2026
2a5372c
Remove the unreachable Unicode branches of pm_encoding_property_char
kddnewton Nov 17, 2026
6752575
Keep only the uppercase bits in the Unicode tables
kddnewton Nov 17, 2026
ba126a3
Begin constant names the way Ruby does in encodings that are not Unicode
kddnewton Nov 17, 2026
50f11ec
Replace the single-byte tables with bitmaps of the constant-starting …
kddnewton Nov 17, 2026
89ab616
Check only uppercase in the multibyte encodings
kddnewton Nov 17, 2026
fc1c886
Use pm_encoding_ascii_alpha_p and pm_encoding_ascii_alnum_p for ident…
kddnewton Nov 17, 2026
ab06144
Update encoding documentation
kddnewton Nov 17, 2026
d5eaf0b
Cover every four-byte Emacs-Mule character that starts with 0x9C
kddnewton Nov 17, 2026
5916a52
Resolve string query versions in FFI the way the extension does
kddnewton Nov 17, 2026
80b45e3
Read non-ASCII Emacs-Mule characters as the start of a local name
kddnewton Nov 17, 2026
1613c44
Skip the non-ASCII name snapshots on TruffleRuby
kddnewton Nov 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) a
### Added

- `pm_options_stack_budget_set` was added to the C API. It sets the number of bytes of C stack the parser may use before reporting a `stack_exhausted` error, instead of overflowing the stack. `SIZE_MAX` means no budget, which is the default. The nesting depth limit alone assumes a stack of roughly 8MB, so embedders that parse on a smaller stack, such as a thread's or a fiber's, should pass a budget.
- `Prism::StringQuery` methods accept a `version:` keyword, just like the parse methods. It defaults to the nearest version to the running Ruby. This matters for `constant?`, because Ruby 4.0 recognizes more uppercase letters than Ruby 3.4.
- `StringQuery::version` was added to the Rust bindings. It picks the Ruby version that a query checks against. The default is the latest version.
- A new `stack` error level, for errors that should raise `SystemStackError`. Its only error is `stack_exhausted`, reported once per parse when the stack budget is used up. It is separate from `nesting_too_deep`, which stays a syntax error, because the same source may parse with more stack. When errors are formatted, a `stack_exhausted` error takes precedence over the syntax errors around it, as argument and load errors do. The level is `:stack` in Ruby, `"stack"` in JavaScript, `ERROR_STACK` in Java, and `PM_ERROR_LEVEL_STACK` in C and Rust.

### Changed
Expand All @@ -17,6 +19,11 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) a
- `PRISM_BUILD_MINIMAL` now excludes the full set of encodings, as `PRISM_ENCODING_EXCLUDE_FULL` does.
- In CESU-8, a surrogate is a valid character only as half of a surrogate pair.
- A `\M-`, `\C-`, or `\c` escape may wrap an escape of any ASCII character, such as `"\M-\<0x01>"`, as CRuby allows.
- The `pm_string_query_*` functions take a Ruby version as their last argument, written like the strings that `pm_options_version_set` accepts. Pass `NULL` for the latest version. An unknown version returns the new `PM_STRING_QUERY_ERROR_VERSION`.
- Whether a name is a constant follows the version of Unicode of the Ruby that is targeted: Unicode 15.0.0 for Ruby 3.3 and 3.4, and Unicode 17.0.0 for Ruby 4.0 and 4.1. A name that starts with a letter that became uppercase in Unicode 16.0.0 or 17.0.0, such as the Garay capital letters, is now a local variable name when targeting Ruby 3.3 or 3.4.
- A `?` followed by two identifier characters is a ternary operator, even when the first one is not ASCII. For example, `a ?☃b : c` used to read `?☃` as a character literal.
- A multiple assignment can write to an attribute whose name starts with a character that is not ASCII, as in `foo.☃, bar = 1, 2`.
- A name that starts with `€` (0xA4) in ISO-8859-16, or with `¯` (0xAF) in Windows-1252, is a constant name. In encodings that are not Unicode, a character that is neither uppercase nor lowercase begins a constant if case folding changes it.

## [2.1.0] - 2026-10-28

Expand Down
216 changes: 175 additions & 41 deletions bin/prism
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,13 @@ module Prism
exit(1)
end

lookup_table(found)
unicode_lists(found) if found == Encoding::UTF_8 || found == Encoding::UTF8_MAC
if found == Encoding::UTF_8 || found == Encoding::UTF8_MAC
unicode_lists
elsif found == Encoding::ASCII_8BIT
lookup_table(found)
else
uppercase_bitmap(found)
end
end

# bin/prism error [source]
Expand Down Expand Up @@ -398,8 +403,19 @@ module Prism
pp parser_tokens
end

# Generate the list of values that will be used in a lookup table for a
# given encoding.
# Return true if a name that starts with the given character is a constant
# name. Object.const_defined? raises a NameError for a name that is not.
# This is more than [[:upper:]]: in an encoding that is not Unicode, a
# character that is neither uppercase nor lowercase begins a constant if
# case folding changes it, as Windows-1252 does to the multiplication sign.
def constant_start?(character)
Object.const_defined?(character)
true
rescue NameError
false
end

# Generate the list of values that will be used in the ASCII table.
def lookup_table_values(encoding)
(0...256).each_slice(16).map.with_index do |slice, row_index|
slice.map do |codepoint|
Expand All @@ -408,52 +424,154 @@ module Prism
values = 0
values |= (1 << 0) if character.match?(/[[:alpha:]]/)
values |= (1 << 1) if character.match?(/[[:alnum:]]/)
values |= (1 << 2) if character.match?(/[[:upper:]]/)
values |= (1 << 2) if constant_start?(character)
values
rescue RangeError
0
end
end
end

# Generate a lookup table for a given encoding.
# Generate the lookup table of the ASCII characters.
def lookup_table(encoding)
encoding_values = lookup_table_values(encoding)
if encoding_values == lookup_table_values(Encoding::US_ASCII)
puts "static const uint8_t pm_encoding_ascii_table[256] = {"
else
puts "static const uint8_t pm_encoding_#{encoding.name.downcase}_table[256] = {"
puts "const uint8_t pm_encoding_ascii_table[256] = {"
puts "/* #{(0...16).map { |value| value.to_s(16).upcase }.join(" ")} */"
lookup_table_values(encoding).each_with_index do |row, row_index|
puts " #{row.join(", ")}, /* #{row_index.to_s(16).upcase}x */"
end
puts "};"
end

puts "// #{(0...16).map { |value| value.to_s(16).upcase }.join(" ")}"
encoding_values.each_with_index do |row, row_index|
puts " #{row.join(", ")}, // #{row_index.to_s(16).upcase}x"
# Generate the bitmap of the bytes from 0x80 to 0xFF that begin a constant
# name in a single-byte encoding. The bit for a byte is bit (byte & 7) of
# element ((byte - 0x80) >> 3). The bytes below 0x80 are ASCII in every
# encoding that prism supports, so they need no bits.
def uppercase_bitmap(encoding)
bitmap = Array.new(16, 0)

(0x80...0x100).each do |byte|
next unless constant_start?(byte.chr(encoding))
bitmap[(byte - 0x80) >> 3] |= 1 << (byte & 7)
rescue RangeError
warn("Encoding `#{encoding.name}' is not a single-byte encoding. The forms of the multibyte encodings are written by hand in src/encoding.c.")
exit(1)
end

if bitmap.all?(0)
puts "/* No byte from 0x80 up begins a constant name in #{encoding.name}, so it needs no bitmap. */"
return
end

puts "/**"
puts " * The bytes from 0x80 up that begin a constant name in #{encoding.name}."
puts " */"
puts "static const uint8_t pm_encoding_#{encoding.name.downcase.tr("-", "_")}_uppercase[16] = {"
bitmap.each_slice(8).with_index do |row, row_index|
puts " #{row.map { |value| "0x%02X" % value }.join(", ")}, /* 0x#{(0x80 + row_index * 64).to_s(16).upcase} */"
end
puts "};"
end

# The version of Unicode that each version of Ruby that prism supports
# uses, from oldest to newest. The functions in src/encoding.c that take a
# version of Ruby answer for its version of Unicode from what this
# generates.
RUBY_UNICODE_VERSIONS = {
"3.3" => "15.0.0",
"3.4" => "15.0.0",
"4.0" => "17.0.0",
"4.1" => "17.0.0"
}

# The version of the Unicode Character Database that the unicode tables
# are generated from. It is the newest version that any version of Ruby
# that prism supports uses.
UNICODE_VERSION = RUBY_UNICODE_VERSIONS.values.max_by { |version| Gem::Version.new(version) }

# The older versions of Unicode that versions of Ruby that prism supports
# use, from oldest to newest. The functions that answer for those versions
# of Ruby check lists of the characters whose properties differ from the
# tables.
UNICODE_OLDER_VERSIONS =(RUBY_UNICODE_VERSIONS.values.uniq - [UNICODE_VERSION]).sort_by { |version| Gem::Version.new(version) }

# Read a file of the Unicode Character Database at the given version. Each
# file is downloaded once from unicode.org and kept in tmp/unicode.
def unicode_data(path, version = UNICODE_VERSION)
cache = File.expand_path("../tmp/unicode/#{version}/#{path}", __dir__)

unless File.exist?(cache)
require "fileutils"
require "net/http"

uri = URI("https://www.unicode.org/Public/#{version}/ucd/#{path}")
response = Net::HTTP.get_response(uri)
raise "could not download #{uri}: #{response.code} #{response.message}" unless response.is_a?(Net::HTTPSuccess)

FileUtils.mkdir_p(File.dirname(cache))
File.write(cache, response.body)
end

File.read(cache)
end

# Return the codepoints that have the given property in the given file of
# the Unicode Character Database at the given version. Each line of the
# file gives a codepoint or a range of codepoints and a property, as in
# "0041..005A ; Uppercase".
def unicode_property(path, property, version = UNICODE_VERSION)
codepoints = []

unicode_data(path, version).each_line do |line|
fields = line.sub(/#.*/, "").split(";").map(&:strip)
next unless fields.length == 2 && fields[1] == property

low, high = fields[0].split("..").map { |value| Integer(value, 16) }
codepoints.concat((low..(high || low)).to_a)
end

raise "no codepoints have #{property} in #{path} at #{version}" if codepoints.empty?
codepoints
end

# Return the codepoints that can begin a constant name in the given version
# of Unicode: those with the Uppercase property, as in [[:upper:]], and the
# titlecase letters (Lt).
def unicode_uppercase(version = UNICODE_VERSION)
unicode_property("DerivedCoreProperties.txt", "Uppercase", version) |
unicode_property("extracted/DerivedGeneralCategory.txt", "Lt", version)
end

# Generate the multistage lookup tables of unicode codepoint properties
# for a given encoding. A codepoint's properties live in the leaf table,
# reached by indexing the root table with its high bits and the middle
# table with its next five bits. Identical middle and leaf blocks are
# shared, which is what keeps the tables small. Titlecase letters count as
# uppercase because they can begin a constant name.
def unicode_lists(encoding)
encoding = Encoding::UTF_8

values =
(0...0x110000).map do |codepoint|
next 0 if (0xD800..0xDFFF).cover?(codepoint)
character = codepoint.chr(encoding)

value = 0
value |= (1 << 0) if character.match?(/[[:alpha:]]/)
value |= (1 << 1) if character.match?(/[[:alnum:]]/)
value |= (1 << 2) if character.match?(/[[:upper:]\p{Lt}]/)
value
end

names = { 0 => "N", 2 => "D", 3 => "A", 7 => "U" }
# shared, which is what keeps the tables small.
#
# The tables mark the codepoints that are uppercase in the Unicode
# Character Database at UNICODE_VERSION: those with the Uppercase property,
# as in [[:upper:]], and the titlecase letters (Lt), since either can begin
# a constant name. Every other character that is not ASCII is an identifier
# character, so the tables need no other properties.
#
# Older versions of Ruby use an older version of Unicode, in which some
# of the uppercase letters of the tables are not uppercase. Another bit
# marks those letters, so that the tables answer for every version of
# Ruby that prism supports.
def unicode_lists
raise "one bit marks the letters of one older version of Unicode, but there are #{UNICODE_OLDER_VERSIONS.length}" unless UNICODE_OLDER_VERSIONS.length == 1

older = UNICODE_OLDER_VERSIONS.first
older_bit = "PM_UNICODE_#{older.split(".").first}_NOT_UPPERCASE_BIT"
latest_uppercase = unicode_uppercase
older_uppercase = unicode_uppercase(older)
raise "uppercase in Unicode #{older} but not #{UNICODE_VERSION}: #{(older_uppercase - latest_uppercase).inspect}" unless (older_uppercase - latest_uppercase).empty?

values = Array.new(0x110000, 0)

latest_uppercase.each { |codepoint| values[codepoint] |= (1 << 2) }
(latest_uppercase - older_uppercase).each { |codepoint| values[codepoint] |= (1 << 3) }

names = { 0 => "N", 4 => "U", 12 => "V" }
unknown = values.uniq - names.keys
raise "unnamed property values: #{unknown.inspect}" if unknown.any?

Expand All @@ -479,19 +597,35 @@ module Prism
end
puts "};"

tables_ruby = RUBY_UNICODE_VERSIONS.find { |_, version| version == UNICODE_VERSION }.first
tables_update = "PM_UNICODE_TABLES_#{UNICODE_VERSION.split(".").first}_UPDATE"
versions = RUBY_UNICODE_VERSIONS.group_by(&:last).map { |version, rubies| " * * Ruby #{rubies.map(&:first).join(" and ")} use Unicode #{version}." }

puts <<~C

/* No properties. */
/**
* The version of Ruby that updated its version of Unicode to #{UNICODE_VERSION}.
*
#{versions.join("\n")}
*/
#define #{tables_update} PM_OPTIONS_VERSION_CRUBY_#{tables_ruby.tr(".", "_")}

/**
* The unicode tables use the fourth bit of each property byte to mark the
* letters that are uppercase or titlecase in the tables but not in Unicode
* #{older}, which the versions of Ruby before #{tables_update}
* use.
*/
#define #{older_bit} (1 << 3)

/* Not uppercase. */
#define N 0

/* A digit: alphanumeric but not alphabetic. */
#define D (PRISM_ENCODING_ALPHANUMERIC_BIT)

/* A letter that is not uppercase: alphabetic and alphanumeric. */
#define A (PRISM_ENCODING_ALPHABETIC_BIT | PRISM_ENCODING_ALPHANUMERIC_BIT)
/* An uppercase or titlecase letter. */
#define U (PRISM_ENCODING_UPPERCASE_BIT)

/* An uppercase or titlecase letter: alphabetic, alphanumeric, and uppercase. */
#define U (PRISM_ENCODING_ALPHABETIC_BIT | PRISM_ENCODING_ALPHANUMERIC_BIT | PRISM_ENCODING_UPPERCASE_BIT)
/* An uppercase or titlecase letter that is not one in Unicode #{older}. */
#define V (PRISM_ENCODING_UPPERCASE_BIT | #{older_bit})
C

puts "\nstatic const uint8_t pm_unicode_leaf[#{leaf_blocks.length}][8] = {"
Expand All @@ -500,7 +634,7 @@ module Prism
end
puts "};"

puts "\n#undef N\n#undef D\n#undef A\n#undef U"
puts "\n#undef N\n#undef U\n#undef V"
end

# Deduplicate the given blocks. The block made entirely of the given empty
Expand Down
6 changes: 3 additions & 3 deletions docs/encoding.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Encoding

When parsing a Ruby file, there are times when the parser must parse identifiers. Identifiers are names of variables, methods, classes, etc. To determine the start of an identifier, the parser must be able to tell if the subsequent bytes form an alphabetic character. To determine the rest of the identifier, the parser must look forward through all alphanumeric characters.
When parsing a Ruby file, there are times when the parser must parse identifiers. Identifiers are names of variables, methods, classes, etc. An identifier starts with an ASCII letter, an underscore, or any character that is not ASCII. The rest of it is ASCII letters, digits, and underscores, and any characters that are not ASCII. An identifier is a constant name if its first character is uppercase.

Determining if a set of bytes comprise an alphabetic or alphanumeric character is encoding-dependent. By default, the parser assumes that all source files are encoded UTF-8. If the file is not encoded in UTF-8, it must be encoded using an encoding that is "ASCII compatible" (i.e., all of the codepoints below 128 match the corresponding codepoints in ASCII and the minimum number of bytes required to represent a codepoint is 1 byte).
Which bytes form a character, and which characters begin a constant name, depends on the encoding. By default, the parser assumes that all source files are encoded UTF-8. If the file is not encoded in UTF-8, it must be encoded using an encoding that is "ASCII compatible" (i.e., all of the codepoints below 128 match the corresponding codepoints in ASCII and the minimum number of bytes required to represent a codepoint is 1 byte).

If the file is not encoded in UTF-8, the user must specify the encoding in a "magic" comment at the top of the file. The comment looks like:

Expand Down Expand Up @@ -103,7 +103,7 @@ The key of the comment can be either "encoding" or "coding". The value of the co
* `Windows-31J`
* `Windows-874`

For each of these encodings, prism provides functions for checking if the subsequent bytes can be interpreted as a character, and then if that character is alphabetic, alphanumeric, or uppercase.
For each of these encodings, prism provides functions for checking if the subsequent bytes can be interpreted as a character, and then if that character begins a constant name. In the encodings whose characters are Unicode code points, such as UTF-8 and CESU-8, that depends on the version of Unicode that the targeted version of Ruby uses.

## Getting notified when the encoding changes

Expand Down
Loading
Loading