repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/features.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/features.rb | require 'set'
module Sass
# Provides `Sass.has_feature?` which allows for simple feature detection
# by providing a feature name.
module Features
# This is the set of features that can be detected.
#
# When this is updated, the documentation of `feature-exists()` should be
# updated as well.
KNOWN_FEATURES = Set[*%w(
global-variable-shadowing
extend-selector-pseudoclass
units-level-3
at-error
custom-property
)]
# Check if a feature exists by name. This is used to implement
# the Sass function `feature-exists($feature)`
#
# @param feature_name [String] The case sensitive name of the feature to
# check if it exists in this version of Sass.
# @return [Boolean] whether the feature of that name exists.
def has_feature?(feature_name)
KNOWN_FEATURES.include?(feature_name)
end
# Add a feature to Sass. Plugins can use this to easily expose their
# availability to end users. Plugins must prefix their feature
# names with a dash to distinguish them from official features.
#
# @example
# Sass.add_feature("-import-globbing")
# Sass.add_feature("-math-cos")
#
#
# @param feature_name [String] The case sensitive name of the feature to
# to add to Sass. Must begin with a dash.
def add_feature(feature_name)
unless feature_name[0] == ?-
raise ArgumentError.new("Plugin feature names must begin with a dash")
end
KNOWN_FEATURES << feature_name
end
end
extend Features
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/error.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/error.rb | module Sass
# An exception class that keeps track of
# the line of the Sass template it was raised on
# and the Sass file that was being parsed (if applicable).
#
# All Sass errors are raised as {Sass::SyntaxError}s.
#
# When dealing with SyntaxErrors,
# it's important to provide filename and line number information.
# This will be used in various error reports to users, including backtraces;
# see \{#sass\_backtrace} for details.
#
# Some of this information is usually provided as part of the constructor.
# New backtrace entries can be added with \{#add\_backtrace},
# which is called when an exception is raised between files (e.g. with `@import`).
#
# Often, a chunk of code will all have similar backtrace information -
# the same filename or even line.
# It may also be useful to have a default line number set.
# In those situations, the default values can be used
# by omitting the information on the original exception,
# and then calling \{#modify\_backtrace} in a wrapper `rescue`.
# When doing this, be sure that all exceptions ultimately end up
# with the information filled in.
class SyntaxError < StandardError
# The backtrace of the error within Sass files.
# This is an array of hashes containing information for a single entry.
# The hashes have the following keys:
#
# `:filename`
# : The name of the file in which the exception was raised,
# or `nil` if no filename is available.
#
# `:mixin`
# : The name of the mixin in which the exception was raised,
# or `nil` if it wasn't raised in a mixin.
#
# `:line`
# : The line of the file on which the error occurred. Never nil.
#
# This information is also included in standard backtrace format
# in the output of \{#backtrace}.
#
# @return [Aray<{Symbol => Object>}]
attr_accessor :sass_backtrace
# The text of the template where this error was raised.
#
# @return [String]
attr_accessor :sass_template
# @param msg [String] The error message
# @param attrs [{Symbol => Object}] The information in the backtrace entry.
# See \{#sass\_backtrace}
def initialize(msg, attrs = {})
@message = msg
@sass_backtrace = []
add_backtrace(attrs)
end
# The name of the file in which the exception was raised.
# This could be `nil` if no filename is available.
#
# @return [String, nil]
def sass_filename
sass_backtrace.first[:filename]
end
# The name of the mixin in which the error occurred.
# This could be `nil` if the error occurred outside a mixin.
#
# @return [String]
def sass_mixin
sass_backtrace.first[:mixin]
end
# The line of the Sass template on which the error occurred.
#
# @return [Integer]
def sass_line
sass_backtrace.first[:line]
end
# Adds an entry to the exception's Sass backtrace.
#
# @param attrs [{Symbol => Object}] The information in the backtrace entry.
# See \{#sass\_backtrace}
def add_backtrace(attrs)
sass_backtrace << attrs.reject {|_k, v| v.nil?}
end
# Modify the top Sass backtrace entries
# (that is, the most deeply nested ones)
# to have the given attributes.
#
# Specifically, this goes through the backtrace entries
# from most deeply nested to least,
# setting the given attributes for each entry.
# If an entry already has one of the given attributes set,
# the pre-existing attribute takes precedence
# and is not used for less deeply-nested entries
# (even if they don't have that attribute set).
#
# @param attrs [{Symbol => Object}] The information to add to the backtrace entry.
# See \{#sass\_backtrace}
def modify_backtrace(attrs)
attrs = attrs.reject {|_k, v| v.nil?}
# Move backwards through the backtrace
(0...sass_backtrace.size).to_a.reverse_each do |i|
entry = sass_backtrace[i]
sass_backtrace[i] = attrs.merge(entry)
attrs.reject! {|k, _v| entry.include?(k)}
break if attrs.empty?
end
end
# @return [String] The error message
def to_s
@message
end
# Returns the standard exception backtrace,
# including the Sass backtrace.
#
# @return [Array<String>]
def backtrace
return nil if super.nil?
return super if sass_backtrace.all? {|h| h.empty?}
sass_backtrace.map do |h|
"#{h[:filename] || '(sass)'}:#{h[:line]}" +
(h[:mixin] ? ":in `#{h[:mixin]}'" : "")
end + super
end
# Returns a string representation of the Sass backtrace.
#
# @param default_filename [String] The filename to use for unknown files
# @see #sass_backtrace
# @return [String]
def sass_backtrace_str(default_filename = "an unknown file")
lines = message.split("\n")
msg = lines[0] + lines[1..-1].
map {|l| "\n" + (" " * "Error: ".size) + l}.join
"Error: #{msg}" +
sass_backtrace.each_with_index.map do |entry, i|
"\n #{i == 0 ? 'on' : 'from'} line #{entry[:line]}" +
" of #{entry[:filename] || default_filename}" +
(entry[:mixin] ? ", in `#{entry[:mixin]}'" : "")
end.join
end
class << self
# Returns an error report for an exception in CSS format.
#
# @param e [Exception]
# @param line_offset [Integer] The number of the first line of the Sass template.
# @return [String] The error report
# @raise [Exception] `e`, if the
# {file:SASS_REFERENCE.md#full_exception-option `:full_exception`} option
# is set to false.
def exception_to_css(e, line_offset = 1)
header = header_string(e, line_offset)
<<END
/*
#{header.gsub('*/', '*\\/')}
Backtrace:\n#{e.backtrace.join("\n").gsub('*/', '*\\/')}
*/
body:before {
white-space: pre;
font-family: monospace;
content: "#{header.gsub('"', '\"').gsub("\n", '\\A ')}"; }
END
end
private
def header_string(e, line_offset)
unless e.is_a?(Sass::SyntaxError) && e.sass_line && e.sass_template
return "#{e.class}: #{e.message}"
end
line_num = e.sass_line + 1 - line_offset
min = [line_num - 6, 0].max
section = e.sass_template.rstrip.split("\n")[min...line_num + 5]
return e.sass_backtrace_str if section.nil? || section.empty?
e.sass_backtrace_str + "\n\n" + section.each_with_index.
map {|line, i| "#{line_offset + min + i}: #{line}"}.join("\n")
end
end
end
# The class for Sass errors that are raised due to invalid unit conversions
# in SassScript.
class UnitConversionError < SyntaxError; end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/cache_stores.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/cache_stores.rb | require 'stringio'
module Sass
# Sass cache stores are in charge of storing cached information,
# especially parse trees for Sass documents.
#
# User-created importers must inherit from {CacheStores::Base}.
module CacheStores
end
end
require 'sass/cache_stores/base'
require 'sass/cache_stores/filesystem'
require 'sass/cache_stores/memory'
require 'sass/cache_stores/chain'
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/shared.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/shared.rb | module Sass
# This module contains functionality that's shared between Haml and Sass.
module Shared
extend self
# Scans through a string looking for the interoplation-opening `#{`
# and, when it's found, yields the scanner to the calling code
# so it can handle it properly.
#
# The scanner will have any backslashes immediately in front of the `#{`
# as the second capture group (`scan[2]`),
# and the text prior to that as the first (`scan[1]`).
#
# @yieldparam scan [StringScanner] The scanner scanning through the string
# @return [String] The text remaining in the scanner after all `#{`s have been processed
def handle_interpolation(str)
scan = Sass::Util::MultibyteStringScanner.new(str)
yield scan while scan.scan(/(.*?)(\\*)\#\{/m)
scan.rest
end
# Moves a scanner through a balanced pair of characters.
# For example:
#
# Foo (Bar (Baz bang) bop) (Bang (bop bip))
# ^ ^
# from to
#
# @param scanner [StringScanner] The string scanner to move
# @param start [Character] The character opening the balanced pair.
# A `Fixnum` in 1.8, a `String` in 1.9
# @param finish [Character] The character closing the balanced pair.
# A `Fixnum` in 1.8, a `String` in 1.9
# @param count [Integer] The number of opening characters matched
# before calling this method
# @return [(String, String)] The string matched within the balanced pair
# and the rest of the string.
# `["Foo (Bar (Baz bang) bop)", " (Bang (bop bip))"]` in the example above.
def balance(scanner, start, finish, count = 0)
str = ''
scanner = Sass::Util::MultibyteStringScanner.new(scanner) unless scanner.is_a? StringScanner
regexp = Regexp.new("(.*?)[\\#{start.chr}\\#{finish.chr}]", Regexp::MULTILINE)
while scanner.scan(regexp)
str << scanner.matched
count += 1 if scanner.matched[-1] == start
count -= 1 if scanner.matched[-1] == finish
return [str, scanner.rest] if count == 0
end
end
# Formats a string for use in error messages about indentation.
#
# @param indentation [String] The string used for indentation
# @param was [Boolean] Whether or not to add `"was"` or `"were"`
# (depending on how many characters were in `indentation`)
# @return [String] The name of the indentation (e.g. `"12 spaces"`, `"1 tab"`)
def human_indentation(indentation, was = false)
if !indentation.include?(?\t)
noun = 'space'
elsif !indentation.include?(?\s)
noun = 'tab'
else
return indentation.inspect + (was ? ' was' : '')
end
singular = indentation.length == 1
if was
was = singular ? ' was' : ' were'
else
was = ''
end
"#{indentation.length} #{noun}#{'s' unless singular}#{was}"
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/util.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/util.rb | # -*- coding: utf-8 -*-
require 'erb'
require 'set'
require 'enumerator'
require 'stringio'
require 'rbconfig'
require 'uri'
require 'thread'
require 'pathname'
require 'sass/root'
require 'sass/util/subset_map'
module Sass
# A module containing various useful functions.
module Util
extend self
# An array of ints representing the Ruby version number.
# @api public
RUBY_VERSION_COMPONENTS = RUBY_VERSION.split(".").map {|s| s.to_i}
# The Ruby engine we're running under. Defaults to `"ruby"`
# if the top-level constant is undefined.
# @api public
RUBY_ENGINE = defined?(::RUBY_ENGINE) ? ::RUBY_ENGINE : "ruby"
# Returns the path of a file relative to the Sass root directory.
#
# @param file [String] The filename relative to the Sass root
# @return [String] The filename relative to the the working directory
def scope(file)
File.join(Sass::ROOT_DIR, file)
end
# Maps the keys in a hash according to a block.
#
# @example
# map_keys({:foo => "bar", :baz => "bang"}) {|k| k.to_s}
# #=> {"foo" => "bar", "baz" => "bang"}
# @param hash [Hash] The hash to map
# @yield [key] A block in which the keys are transformed
# @yieldparam key [Object] The key that should be mapped
# @yieldreturn [Object] The new value for the key
# @return [Hash] The mapped hash
# @see #map_vals
# @see #map_hash
def map_keys(hash)
map_hash(hash) {|k, v| [yield(k), v]}
end
# Maps the values in a hash according to a block.
#
# @example
# map_values({:foo => "bar", :baz => "bang"}) {|v| v.to_sym}
# #=> {:foo => :bar, :baz => :bang}
# @param hash [Hash] The hash to map
# @yield [value] A block in which the values are transformed
# @yieldparam value [Object] The value that should be mapped
# @yieldreturn [Object] The new value for the value
# @return [Hash] The mapped hash
# @see #map_keys
# @see #map_hash
def map_vals(hash)
# We don't delegate to map_hash for performance here
# because map_hash does more than is necessary.
rv = hash.class.new
hash = hash.as_stored if hash.is_a?(NormalizedMap)
hash.each do |k, v|
rv[k] = yield(v)
end
rv
end
# Maps the key-value pairs of a hash according to a block.
#
# @example
# map_hash({:foo => "bar", :baz => "bang"}) {|k, v| [k.to_s, v.to_sym]}
# #=> {"foo" => :bar, "baz" => :bang}
# @param hash [Hash] The hash to map
# @yield [key, value] A block in which the key-value pairs are transformed
# @yieldparam [key] The hash key
# @yieldparam [value] The hash value
# @yieldreturn [(Object, Object)] The new value for the `[key, value]` pair
# @return [Hash] The mapped hash
# @see #map_keys
# @see #map_vals
def map_hash(hash)
# Copy and modify is more performant than mapping to an array and using
# to_hash on the result.
rv = hash.class.new
hash.each do |k, v|
new_key, new_value = yield(k, v)
new_key = hash.denormalize(new_key) if hash.is_a?(NormalizedMap) && new_key == k
rv[new_key] = new_value
end
rv
end
# Computes the powerset of the given array.
# This is the set of all subsets of the array.
#
# @example
# powerset([1, 2, 3]) #=>
# Set[Set[], Set[1], Set[2], Set[3], Set[1, 2], Set[2, 3], Set[1, 3], Set[1, 2, 3]]
# @param arr [Enumerable]
# @return [Set<Set>] The subsets of `arr`
def powerset(arr)
arr.inject([Set.new].to_set) do |powerset, el|
new_powerset = Set.new
powerset.each do |subset|
new_powerset << subset
new_powerset << subset + [el]
end
new_powerset
end
end
# Restricts a number to falling within a given range.
# Returns the number if it falls within the range,
# or the closest value in the range if it doesn't.
#
# @param value [Numeric]
# @param range [Range<Numeric>]
# @return [Numeric]
def restrict(value, range)
[[value, range.first].max, range.last].min
end
# Like [Fixnum.round], but leaves rooms for slight floating-point
# differences.
#
# @param value [Numeric]
# @return [Numeric]
def round(value)
# If the number is within epsilon of X.5, round up (or down for negative
# numbers).
mod = value % 1
mod_is_half = (mod - 0.5).abs < Script::Value::Number.epsilon
if value > 0
!mod_is_half && mod < 0.5 ? value.floor : value.ceil
else
mod_is_half || mod < 0.5 ? value.floor : value.ceil
end
end
# Concatenates all strings that are adjacent in an array,
# while leaving other elements as they are.
#
# @example
# merge_adjacent_strings([1, "foo", "bar", 2, "baz"])
# #=> [1, "foobar", 2, "baz"]
# @param arr [Array]
# @return [Array] The enumerable with strings merged
def merge_adjacent_strings(arr)
# Optimize for the common case of one element
return arr if arr.size < 2
arr.inject([]) do |a, e|
if e.is_a?(String)
if a.last.is_a?(String)
a.last << e
else
a << e.dup
end
else
a << e
end
a
end
end
# Non-destructively replaces all occurrences of a subsequence in an array
# with another subsequence.
#
# @example
# replace_subseq([1, 2, 3, 4, 5], [2, 3], [:a, :b])
# #=> [1, :a, :b, 4, 5]
#
# @param arr [Array] The array whose subsequences will be replaced.
# @param subseq [Array] The subsequence to find and replace.
# @param replacement [Array] The sequence that `subseq` will be replaced with.
# @return [Array] `arr` with `subseq` replaced with `replacement`.
def replace_subseq(arr, subseq, replacement)
new = []
matched = []
i = 0
arr.each do |elem|
if elem != subseq[i]
new.push(*matched)
matched = []
i = 0
new << elem
next
end
if i == subseq.length - 1
matched = []
i = 0
new.push(*replacement)
else
matched << elem
i += 1
end
end
new.push(*matched)
new
end
# Intersperses a value in an enumerable, as would be done with `Array#join`
# but without concatenating the array together afterwards.
#
# @param enum [Enumerable]
# @param val
# @return [Array]
def intersperse(enum, val)
enum.inject([]) {|a, e| a << e << val}[0...-1]
end
def slice_by(enum)
results = []
enum.each do |value|
key = yield(value)
if !results.empty? && results.last.first == key
results.last.last << value
else
results << [key, [value]]
end
end
results
end
# Substitutes a sub-array of one array with another sub-array.
#
# @param ary [Array] The array in which to make the substitution
# @param from [Array] The sequence of elements to replace with `to`
# @param to [Array] The sequence of elements to replace `from` with
def substitute(ary, from, to)
res = ary.dup
i = 0
while i < res.size
if res[i...i + from.size] == from
res[i...i + from.size] = to
end
i += 1
end
res
end
# Destructively strips whitespace from the beginning and end
# of the first and last elements, respectively,
# in the array (if those elements are strings).
#
# @param arr [Array]
# @return [Array] `arr`
def strip_string_array(arr)
arr.first.lstrip! if arr.first.is_a?(String)
arr.last.rstrip! if arr.last.is_a?(String)
arr
end
# Return an array of all possible paths through the given arrays.
#
# @param arrs [Array<Array>]
# @return [Array<Arrays>]
#
# @example
# paths([[1, 2], [3, 4], [5]]) #=>
# # [[1, 3, 5],
# # [2, 3, 5],
# # [1, 4, 5],
# # [2, 4, 5]]
def paths(arrs)
arrs.inject([[]]) do |paths, arr|
arr.map {|e| paths.map {|path| path + [e]}}.flatten(1)
end
end
# Computes a single longest common subsequence for `x` and `y`.
# If there are more than one longest common subsequences,
# the one returned is that which starts first in `x`.
#
# @param x [Array]
# @param y [Array]
# @yield [a, b] An optional block to use in place of a check for equality
# between elements of `x` and `y`.
# @yieldreturn [Object, nil] If the two values register as equal,
# this will return the value to use in the LCS array.
# @return [Array] The LCS
def lcs(x, y, &block)
x = [nil, *x]
y = [nil, *y]
block ||= proc {|a, b| a == b && a}
lcs_backtrace(lcs_table(x, y, &block), x, y, x.size - 1, y.size - 1, &block)
end
# Like `String.upcase`, but only ever upcases ASCII letters.
def upcase(string)
return string.upcase unless ruby2_4?
string.upcase(:ascii)
end
# Like `String.downcase`, but only ever downcases ASCII letters.
def downcase(string)
return string.downcase unless ruby2_4?
string.downcase(:ascii)
end
# Returns a sub-array of `minuend` containing only elements that are also in
# `subtrahend`. Ensures that the return value has the same order as
# `minuend`, even on Rubinius where that's not guaranteed by `Array#-`.
#
# @param minuend [Array]
# @param subtrahend [Array]
# @return [Array]
def array_minus(minuend, subtrahend)
return minuend - subtrahend unless rbx?
set = Set.new(minuend) - subtrahend
minuend.select {|e| set.include?(e)}
end
# Returns the maximum of `val1` and `val2`. We use this over \{Array.max} to
# avoid unnecessary garbage collection.
def max(val1, val2)
val1 > val2 ? val1 : val2
end
# Returns the minimum of `val1` and `val2`. We use this over \{Array.min} to
# avoid unnecessary garbage collection.
def min(val1, val2)
val1 <= val2 ? val1 : val2
end
# Returns a string description of the character that caused an
# `Encoding::UndefinedConversionError`.
#
# @param e [Encoding::UndefinedConversionError]
# @return [String]
def undefined_conversion_error_char(e)
# Rubinius (as of 2.0.0.rc1) pre-quotes the error character.
return e.error_char if rbx?
# JRuby (as of 1.7.2) doesn't have an error_char field on
# Encoding::UndefinedConversionError.
return e.error_char.dump unless jruby?
e.message[/^"[^"]+"/] # "
end
# Asserts that `value` falls within `range` (inclusive), leaving
# room for slight floating-point errors.
#
# @param name [String] The name of the value. Used in the error message.
# @param range [Range] The allowed range of values.
# @param value [Numeric, Sass::Script::Value::Number] The value to check.
# @param unit [String] The unit of the value. Used in error reporting.
# @return [Numeric] `value` adjusted to fall within range, if it
# was outside by a floating-point margin.
def check_range(name, range, value, unit = '')
grace = (-0.00001..0.00001)
str = value.to_s
value = value.value if value.is_a?(Sass::Script::Value::Number)
return value if range.include?(value)
return range.first if grace.include?(value - range.first)
return range.last if grace.include?(value - range.last)
raise ArgumentError.new(
"#{name} #{str} must be between #{range.first}#{unit} and #{range.last}#{unit}")
end
# Returns whether or not `seq1` is a subsequence of `seq2`. That is, whether
# or not `seq2` contains every element in `seq1` in the same order (and
# possibly more elements besides).
#
# @param seq1 [Array]
# @param seq2 [Array]
# @return [Boolean]
def subsequence?(seq1, seq2)
i = j = 0
loop do
return true if i == seq1.size
return false if j == seq2.size
i += 1 if seq1[i] == seq2[j]
j += 1
end
end
# Returns information about the caller of the previous method.
#
# @param entry [String] An entry in the `#caller` list, or a similarly formatted string
# @return [[String, Integer, (String, nil)]]
# An array containing the filename, line, and method name of the caller.
# The method name may be nil
def caller_info(entry = nil)
# JRuby evaluates `caller` incorrectly when it's in an actual default argument.
entry ||= caller[1]
info = entry.scan(/^((?:[A-Za-z]:)?.*?):(-?.*?)(?::.*`(.+)')?$/).first
info[1] = info[1].to_i
# This is added by Rubinius to designate a block, but we don't care about it.
info[2].sub!(/ \{\}\Z/, '') if info[2]
info
end
# Returns whether one version string represents a more recent version than another.
#
# @param v1 [String] A version string.
# @param v2 [String] Another version string.
# @return [Boolean]
def version_gt(v1, v2)
# Construct an array to make sure the shorter version is padded with nil
Array.new([v1.length, v2.length].max).zip(v1.split("."), v2.split(".")) do |_, p1, p2|
p1 ||= "0"
p2 ||= "0"
release1 = p1 =~ /^[0-9]+$/
release2 = p2 =~ /^[0-9]+$/
if release1 && release2
# Integer comparison if both are full releases
p1, p2 = p1.to_i, p2.to_i
next if p1 == p2
return p1 > p2
elsif !release1 && !release2
# String comparison if both are prereleases
next if p1 == p2
return p1 > p2
else
# If only one is a release, that one is newer
return release1
end
end
end
# Returns whether one version string represents the same or a more
# recent version than another.
#
# @param v1 [String] A version string.
# @param v2 [String] Another version string.
# @return [Boolean]
def version_geq(v1, v2)
version_gt(v1, v2) || !version_gt(v2, v1)
end
# Throws a NotImplementedError for an abstract method.
#
# @param obj [Object] `self`
# @raise [NotImplementedError]
def abstract(obj)
raise NotImplementedError.new("#{obj.class} must implement ##{caller_info[2]}")
end
# Prints a deprecation warning for the caller method.
#
# @param obj [Object] `self`
# @param message [String] A message describing what to do instead.
def deprecated(obj, message = nil)
obj_class = obj.is_a?(Class) ? "#{obj}." : "#{obj.class}#"
full_message = "DEPRECATION WARNING: #{obj_class}#{caller_info[2]} " +
"will be removed in a future version of Sass.#{("\n" + message) if message}"
Sass::Util.sass_warn full_message
end
# Silences all Sass warnings within a block.
#
# @yield A block in which no Sass warnings will be printed
def silence_sass_warnings
old_level, Sass.logger.log_level = Sass.logger.log_level, :error
yield
ensure
Sass.logger.log_level = old_level
end
# The same as `Kernel#warn`, but is silenced by \{#silence\_sass\_warnings}.
#
# @param msg [String]
def sass_warn(msg)
Sass.logger.warn("#{msg}\n")
end
## Cross Rails Version Compatibility
# Returns the root of the Rails application,
# if this is running in a Rails context.
# Returns `nil` if no such root is defined.
#
# @return [String, nil]
def rails_root
if defined?(::Rails.root)
return ::Rails.root.to_s if ::Rails.root
raise "ERROR: Rails.root is nil!"
end
return RAILS_ROOT.to_s if defined?(RAILS_ROOT)
nil
end
# Returns the environment of the Rails application,
# if this is running in a Rails context.
# Returns `nil` if no such environment is defined.
#
# @return [String, nil]
def rails_env
return ::Rails.env.to_s if defined?(::Rails.env)
return RAILS_ENV.to_s if defined?(RAILS_ENV)
nil
end
# Returns whether this environment is using ActionPack
# version 3.0.0 or greater.
#
# @return [Boolean]
def ap_geq_3?
ap_geq?("3.0.0.beta1")
end
# Returns whether this environment is using ActionPack
# of a version greater than or equal to that specified.
#
# @param version [String] The string version number to check against.
# Should be greater than or equal to Rails 3,
# because otherwise ActionPack::VERSION isn't autoloaded
# @return [Boolean]
def ap_geq?(version)
# The ActionPack module is always loaded automatically in Rails >= 3
return false unless defined?(ActionPack) && defined?(ActionPack::VERSION) &&
defined?(ActionPack::VERSION::STRING)
version_geq(ActionPack::VERSION::STRING, version)
end
# Returns an ActionView::Template* class.
# In pre-3.0 versions of Rails, most of these classes
# were of the form `ActionView::TemplateFoo`,
# while afterwards they were of the form `ActionView;:Template::Foo`.
#
# @param name [#to_s] The name of the class to get.
# For example, `:Error` will return `ActionView::TemplateError`
# or `ActionView::Template::Error`.
def av_template_class(name)
return ActionView.const_get("Template#{name}") if ActionView.const_defined?("Template#{name}")
ActionView::Template.const_get(name.to_s)
end
## Cross-OS Compatibility
#
# These methods are cached because some of them are called quite frequently
# and even basic checks like String#== are too costly to be called repeatedly.
# Whether or not this is running on Windows.
#
# @return [Boolean]
def windows?
return @windows if defined?(@windows)
@windows = (RbConfig::CONFIG['host_os'] =~ /mswin|windows|mingw/i)
end
# Whether or not this is running on IronRuby.
#
# @return [Boolean]
def ironruby?
return @ironruby if defined?(@ironruby)
@ironruby = RUBY_ENGINE == "ironruby"
end
# Whether or not this is running on Rubinius.
#
# @return [Boolean]
def rbx?
return @rbx if defined?(@rbx)
@rbx = RUBY_ENGINE == "rbx"
end
# Whether or not this is running on JRuby.
#
# @return [Boolean]
def jruby?
return @jruby if defined?(@jruby)
@jruby = RUBY_PLATFORM =~ /java/
end
# Returns an array of ints representing the JRuby version number.
#
# @return [Array<Integer>]
def jruby_version
@jruby_version ||= ::JRUBY_VERSION.split(".").map {|s| s.to_i}
end
# Like `Dir.glob`, but works with backslash-separated paths on Windows.
#
# @param path [String]
def glob(path)
path = path.tr('\\', '/') if windows?
if block_given?
Dir.glob(path) {|f| yield(f)}
else
Dir.glob(path)
end
end
# Like `Pathname.new`, but normalizes Windows paths to always use backslash
# separators.
#
# `Pathname#relative_path_from` can break if the two pathnames aren't
# consistent in their slash style.
#
# @param path [String]
# @return [Pathname]
def pathname(path)
path = path.tr("/", "\\") if windows?
Pathname.new(path)
end
# Like `Pathname#cleanpath`, but normalizes Windows paths to always use
# backslash separators. Normally, `Pathname#cleanpath` actually does the
# reverse -- it will convert backslashes to forward slashes, which can break
# `Pathname#relative_path_from`.
#
# @param path [String, Pathname]
# @return [Pathname]
def cleanpath(path)
path = Pathname.new(path) unless path.is_a?(Pathname)
pathname(path.cleanpath.to_s)
end
# Returns `path` with all symlinks resolved.
#
# @param path [String, Pathname]
# @return [Pathname]
def realpath(path)
path = Pathname.new(path) unless path.is_a?(Pathname)
# Explicitly DON'T run #pathname here. We don't want to convert
# to Windows directory separators because we're comparing these
# against the paths returned by Listen, which use forward
# slashes everywhere.
begin
path.realpath
rescue SystemCallError
# If [path] doesn't actually exist, don't bail, just
# return the original.
path
end
end
# Returns `path` relative to `from`.
#
# This is like `Pathname#relative_path_from` except it accepts both strings
# and pathnames, it handles Windows path separators correctly, and it throws
# an error rather than crashing if the paths use different encodings
# (https://github.com/ruby/ruby/pull/713).
#
# @param path [String, Pathname]
# @param from [String, Pathname]
# @return [Pathname?]
def relative_path_from(path, from)
pathname(path.to_s).relative_path_from(pathname(from.to_s))
rescue NoMethodError => e
raise e unless e.name == :zero?
# Work around https://github.com/ruby/ruby/pull/713.
path = path.to_s
from = from.to_s
raise ArgumentError("Incompatible path encodings: #{path.inspect} is #{path.encoding}, " +
"#{from.inspect} is #{from.encoding}")
end
# Converts `path` to a "file:" URI. This handles Windows paths correctly.
#
# @param path [String, Pathname]
# @return [String]
def file_uri_from_path(path)
path = path.to_s if path.is_a?(Pathname)
path = path.tr('\\', '/') if windows?
path = URI::DEFAULT_PARSER.escape(path)
return path.start_with?('/') ? "file://" + path : path unless windows?
return "file:///" + path.tr("\\", "/") if path =~ %r{^[a-zA-Z]:[/\\]}
return "file:" + path.tr("\\", "/") if path =~ %r{\\\\[^\\]+\\[^\\/]+}
path.tr("\\", "/")
end
# Retries a filesystem operation if it fails on Windows. Windows
# has weird and flaky locking rules that can cause operations to fail.
#
# @yield [] The filesystem operation.
def retry_on_windows
return yield unless windows?
begin
yield
rescue SystemCallError
sleep 0.1
yield
end
end
# Prepare a value for a destructuring assignment (e.g. `a, b =
# val`). This works around a performance bug when using
# ActiveSupport, and only needs to be called when `val` is likely
# to be `nil` reasonably often.
#
# See [this bug report](http://redmine.ruby-lang.org/issues/4917).
#
# @param val [Object]
# @return [Object]
def destructure(val)
val || []
end
CHARSET_REGEXP = /\A@charset "([^"]+)"/
bom = "\uFEFF"
UTF_8_BOM = bom.encode("UTF-8").force_encoding('BINARY')
UTF_16BE_BOM = bom.encode("UTF-16BE").force_encoding('BINARY')
UTF_16LE_BOM = bom.encode("UTF-16LE").force_encoding('BINARY')
## Cross-Ruby-Version Compatibility
# Whether or not this is running under Ruby 2.4 or higher.
#
# @return [Boolean]
def ruby2_4?
return @ruby2_4 if defined?(@ruby2_4)
@ruby2_4 =
if RUBY_VERSION_COMPONENTS[0] == 2
RUBY_VERSION_COMPONENTS[1] >= 4
else
RUBY_VERSION_COMPONENTS[0] > 2
end
end
# Like {\#check\_encoding}, but also checks for a `@charset` declaration
# at the beginning of the file and uses that encoding if it exists.
#
# Sass follows CSS's decoding rules.
#
# @param str [String] The string of which to check the encoding
# @return [(String, Encoding)] The original string encoded as UTF-8,
# and the source encoding of the string
# @raise [Encoding::UndefinedConversionError] if the source encoding
# cannot be converted to UTF-8
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
# @raise [Sass::SyntaxError] If the document declares an encoding that
# doesn't match its contents, or it doesn't declare an encoding and its
# contents are invalid in the native encoding.
def check_sass_encoding(str)
# Determine the fallback encoding following section 3.2 of CSS Syntax Level 3 and Encodings:
# http://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#determine-the-fallback-encoding
# http://encoding.spec.whatwg.org/#decode
binary = str.dup.force_encoding("BINARY")
if binary.start_with?(UTF_8_BOM)
binary.slice! 0, UTF_8_BOM.length
str = binary.force_encoding('UTF-8')
elsif binary.start_with?(UTF_16BE_BOM)
binary.slice! 0, UTF_16BE_BOM.length
str = binary.force_encoding('UTF-16BE')
elsif binary.start_with?(UTF_16LE_BOM)
binary.slice! 0, UTF_16LE_BOM.length
str = binary.force_encoding('UTF-16LE')
elsif binary =~ CHARSET_REGEXP
charset = $1.force_encoding('US-ASCII')
encoding = Encoding.find(charset)
if encoding.name == 'UTF-16' || encoding.name == 'UTF-16BE'
encoding = Encoding.find('UTF-8')
end
str = binary.force_encoding(encoding)
elsif str.encoding.name == "ASCII-8BIT"
# Normally we want to fall back on believing the Ruby string
# encoding, but if that's just binary we want to make sure
# it's valid UTF-8.
str = str.force_encoding('utf-8')
end
find_encoding_error(str) unless str.valid_encoding?
begin
# If the string is valid, preprocess it according to section 3.3 of CSS Syntax Level 3.
return str.encode("UTF-8").gsub(/\r\n?|\f/, "\n").tr("\u0000", "�"), str.encoding
rescue EncodingError
find_encoding_error(str)
end
end
# Destructively removes all elements from an array that match a block, and
# returns the removed elements.
#
# @param array [Array] The array from which to remove elements.
# @yield [el] Called for each element.
# @yieldparam el [*] The element to test.
# @yieldreturn [Boolean] Whether or not to extract the element.
# @return [Array] The extracted elements.
def extract!(array)
out = []
array.reject! do |e|
next false unless yield e
out << e
true
end
out
end
# Flattens the first level of nested arrays in `arrs`. Unlike
# `Array#flatten`, this orders the result by taking the first
# values from each array in order, then the second, and so on.
#
# @param arrs [Array] The array to flatten.
# @return [Array] The flattened array.
def flatten_vertically(arrs)
result = []
arrs = arrs.map {|sub| sub.is_a?(Array) ? sub.dup : Array(sub)}
until arrs.empty?
arrs.reject! do |arr|
result << arr.shift
arr.empty?
end
end
result
end
# Like `Object#inspect`, but preserves non-ASCII characters rather than
# escaping them under Ruby 1.9.2. This is necessary so that the
# precompiled Haml template can be `#encode`d into `@options[:encoding]`
# before being evaluated.
#
# @param obj {Object}
# @return {String}
def inspect_obj(obj)
return obj.inspect unless version_geq(RUBY_VERSION, "1.9.2")
return ':' + inspect_obj(obj.to_s) if obj.is_a?(Symbol)
return obj.inspect unless obj.is_a?(String)
'"' + obj.gsub(/[\x00-\x7F]+/) {|s| s.inspect[1...-1]} + '"'
end
# Extracts the non-string vlaues from an array containing both strings and non-strings.
# These values are replaced with escape sequences.
# This can be undone using \{#inject\_values}.
#
# This is useful e.g. when we want to do string manipulation
# on an interpolated string.
#
# The precise format of the resulting string is not guaranteed.
# However, it is guaranteed that newlines and whitespace won't be affected.
#
# @param arr [Array] The array from which values are extracted.
# @return [(String, Array)] The resulting string, and an array of extracted values.
def extract_values(arr)
values = []
mapped = arr.map do |e|
next e.gsub('{', '{{') if e.is_a?(String)
values << e
next "{#{values.count - 1}}"
end
return mapped.join, values
end
# Undoes \{#extract\_values} by transforming a string with escape sequences
# into an array of strings and non-string values.
#
# @param str [String] The string with escape sequences.
# @param values [Array] The array of values to inject.
# @return [Array] The array of strings and values.
def inject_values(str, values)
return [str.gsub('{{', '{')] if values.empty?
# Add an extra { so that we process the tail end of the string
result = (str + '{{').scan(/(.*?)(?:(\{\{)|\{(\d+)\})/m).map do |(pre, esc, n)|
[pre, esc ? '{' : '', n ? values[n.to_i] : '']
end.flatten(1)
result[-2] = '' # Get rid of the extra {
merge_adjacent_strings(result).reject {|s| s == ''}
end
# Allows modifications to be performed on the string form
# of an array containing both strings and non-strings.
#
# @param arr [Array] The array from which values are extracted.
# @yield [str] A block in which string manipulation can be done to the array.
# @yieldparam str [String] The string form of `arr`.
# @yieldreturn [String] The modified string.
# @return [Array] The modified, interpolated array.
def with_extracted_values(arr)
str, vals = extract_values(arr)
str = yield str
inject_values(str, vals)
end
# Builds a sourcemap file name given the generated CSS file name.
#
# @param css [String] The generated CSS file name.
# @return [String] The source map file name.
def sourcemap_name(css)
css + ".map"
end
# Escapes certain characters so that the result can be used
# as the JSON string value. Returns the original string if
# no escaping is necessary.
#
# @param s [String] The string to be escaped
# @return [String] The escaped string
def json_escape_string(s)
return s if s !~ /["\\\b\f\n\r\t]/
result = ""
s.split("").each do |c|
case c
when '"', "\\"
result << "\\" << c
when "\n" then result << "\\n"
when "\t" then result << "\\t"
when "\r" then result << "\\r"
when "\f" then result << "\\f"
when "\b" then result << "\\b"
else
result << c
end
end
result
end
# Converts the argument into a valid JSON value.
#
# @param v [Integer, String, Array, Boolean, nil]
# @return [String]
def json_value_of(v)
case v
when Integer
v.to_s
when String
"\"" + json_escape_string(v) + "\""
when Array
"[" + v.map {|x| json_value_of(x)}.join(",") + "]"
when NilClass
"null"
when TrueClass
"true"
when FalseClass
"false"
else
raise ArgumentError.new("Unknown type: #{v.class.name}")
end
end
VLQ_BASE_SHIFT = 5
VLQ_BASE = 1 << VLQ_BASE_SHIFT
VLQ_BASE_MASK = VLQ_BASE - 1
VLQ_CONTINUATION_BIT = VLQ_BASE
BASE64_DIGITS = ('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a + ['+', '/']
BASE64_DIGIT_MAP = begin
map = {}
BASE64_DIGITS.each_with_index.map do |digit, i|
map[digit] = i
end
map
end
# Encodes `value` as VLQ (http://en.wikipedia.org/wiki/VLQ).
#
# @param value [Integer]
# @return [String] The encoded value
def encode_vlq(value)
if value < 0
value = ((-value) << 1) | 1
else
value <<= 1
end
result = ''
begin
digit = value & VLQ_BASE_MASK
value >>= VLQ_BASE_SHIFT
if value > 0
digit |= VLQ_CONTINUATION_BIT
end
result << BASE64_DIGITS[digit]
end while value > 0
result
end
## Static Method Stuff
# The context in which the ERB for \{#def\_static\_method} will be run.
class StaticConditionalContext
# @param set [#include?] The set of variables that are defined for this context.
def initialize(set)
@set = set
end
# Checks whether or not a variable is defined for this context.
#
# @param name [Symbol] The name of the variable
# @return [Boolean]
def method_missing(name, *args)
super unless args.empty? && !block_given?
@set.include?(name)
end
end
# @private
ATOMIC_WRITE_MUTEX = Mutex.new
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | true |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/util/test.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/util/test.rb | module Sass
module Util
module Test
def skip(msg = nil, bt = caller)
super if defined?(super)
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/util/subset_map.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/util/subset_map.rb | require 'set'
module Sass
module Util
# A map from sets to values.
# A value is \{#\[]= set} by providing a set (the "set-set") and a value,
# which is then recorded as corresponding to that set.
# Values are \{#\[] accessed} by providing a set (the "get-set")
# and returning all values that correspond to set-sets
# that are subsets of the get-set.
#
# SubsetMap preserves the order of values as they're inserted.
#
# @example
# ssm = SubsetMap.new
# ssm[Set[1, 2]] = "Foo"
# ssm[Set[2, 3]] = "Bar"
# ssm[Set[1, 2, 3]] = "Baz"
#
# ssm[Set[1, 2, 3]] #=> ["Foo", "Bar", "Baz"]
class SubsetMap
# Creates a new, empty SubsetMap.
def initialize
@hash = {}
@vals = []
end
# Whether or not this SubsetMap has any key-value pairs.
#
# @return [Boolean]
def empty?
@hash.empty?
end
# Associates a value with a set.
# When `set` or any of its supersets is accessed,
# `value` will be among the values returned.
#
# Note that if the same `set` is passed to this method multiple times,
# all given `value`s will be associated with that `set`.
#
# This runs in `O(n)` time, where `n` is the size of `set`.
#
# @param set [#to_set] The set to use as the map key. May not be empty.
# @param value [Object] The value to associate with `set`.
# @raise [ArgumentError] If `set` is empty.
def []=(set, value)
raise ArgumentError.new("SubsetMap keys may not be empty.") if set.empty?
index = @vals.size
@vals << value
set.each do |k|
@hash[k] ||= []
@hash[k] << [set, set.to_set, index]
end
end
# Returns all values associated with subsets of `set`.
#
# In the worst case, this runs in `O(m*max(n, log m))` time,
# where `n` is the size of `set`
# and `m` is the number of associations in the map.
# However, unless many keys in the map overlap with `set`,
# `m` will typically be much smaller.
#
# @param set [Set] The set to use as the map key.
# @return [Array<(Object, #to_set)>] An array of pairs,
# where the first value is the value associated with a subset of `set`,
# and the second value is that subset of `set`
# (or whatever `#to_set` object was used to set the value)
# This array is in insertion order.
# @see #[]
def get(set)
res = set.map do |k|
subsets = @hash[k]
next unless subsets
subsets.map do |subenum, subset, index|
next unless subset.subset?(set)
[index, subenum]
end
end.flatten(1)
res.compact!
res.uniq!
res.sort!
res.map! {|i, s| [@vals[i], s]}
res
end
# Same as \{#get}, but doesn't return the subsets of the argument
# for which values were found.
#
# @param set [Set] The set to use as the map key.
# @return [Array] The array of all values
# associated with subsets of `set`, in insertion order.
# @see #get
def [](set)
get(set).map {|v, _| v}
end
# Iterates over each value in the subset map. Ignores keys completely. If
# multiple keys have the same value, this will return them multiple times.
#
# @yield [Object] Each value in the map.
def each_value
@vals.each {|v| yield v}
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/util/multibyte_string_scanner.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/util/multibyte_string_scanner.rb | require 'strscan'
if Sass::Util.rbx?
# Rubinius's StringScanner class implements some of its methods in terms of
# others, which causes us to double-count bytes in some cases if we do
# straightforward inheritance. To work around this, we use a delegate class.
require 'delegate'
class Sass::Util::MultibyteStringScanner < DelegateClass(StringScanner)
def initialize(str)
super(StringScanner.new(str))
@mb_pos = 0
@mb_matched_size = nil
@mb_last_pos = nil
end
def is_a?(klass)
__getobj__.is_a?(klass) || super
end
end
else
class Sass::Util::MultibyteStringScanner < StringScanner
def initialize(str)
super
@mb_pos = 0
@mb_matched_size = nil
@mb_last_pos = nil
end
end
end
# A wrapper of the native StringScanner class that works correctly with
# multibyte character encodings. The native class deals only in bytes, not
# characters, for methods like [#pos] and [#matched_size]. This class deals
# only in characters, instead.
class Sass::Util::MultibyteStringScanner
def self.new(str)
return StringScanner.new(str) if str.ascii_only?
super
end
alias_method :byte_pos, :pos
alias_method :byte_matched_size, :matched_size
def check(pattern); _match super; end
def check_until(pattern); _matched super; end
def getch; _forward _match super; end
def match?(pattern); _size check(pattern); end
def matched_size; @mb_matched_size; end
def peek(len); string[@mb_pos, len]; end
alias_method :peep, :peek
def pos; @mb_pos; end
alias_method :pointer, :pos
def rest_size; rest.size; end
def scan(pattern); _forward _match super; end
def scan_until(pattern); _forward _matched super; end
def skip(pattern); _size scan(pattern); end
def skip_until(pattern); _matched _size scan_until(pattern); end
def get_byte
raise "MultibyteStringScanner doesn't support #get_byte."
end
def getbyte
raise "MultibyteStringScanner doesn't support #getbyte."
end
def pos=(n)
@mb_last_pos = nil
# We set position kind of a lot during parsing, so we want it to be as
# efficient as possible. This is complicated by the fact that UTF-8 is a
# variable-length encoding, so it's difficult to find the byte length that
# corresponds to a given character length.
#
# Our heuristic here is to try to count the fewest possible characters. So
# if the new position is close to the current one, just count the
# characters between the two; if the new position is closer to the
# beginning of the string, just count the characters from there.
if @mb_pos - n < @mb_pos / 2
# New position is close to old position
byte_delta = @mb_pos > n ? -string[n...@mb_pos].bytesize : string[@mb_pos...n].bytesize
super(byte_pos + byte_delta)
else
# New position is close to BOS
super(string[0...n].bytesize)
end
@mb_pos = n
end
def reset
@mb_pos = 0
@mb_matched_size = nil
@mb_last_pos = nil
super
end
def scan_full(pattern, advance_pointer_p, return_string_p)
res = _match super(pattern, advance_pointer_p, true)
_forward res if advance_pointer_p
return res if return_string_p
end
def search_full(pattern, advance_pointer_p, return_string_p)
res = super(pattern, advance_pointer_p, true)
_forward res if advance_pointer_p
_matched((res if return_string_p))
end
def string=(str)
@mb_pos = 0
@mb_matched_size = nil
@mb_last_pos = nil
super
end
def terminate
@mb_pos = string.size
@mb_matched_size = nil
@mb_last_pos = nil
super
end
alias_method :clear, :terminate
def unscan
super
@mb_pos = @mb_last_pos
@mb_last_pos = @mb_matched_size = nil
end
private
def _size(str)
str && str.size
end
def _match(str)
@mb_matched_size = str && str.size
str
end
def _matched(res)
_match matched
res
end
def _forward(str)
@mb_last_pos = @mb_pos
@mb_pos += str.size if str
str
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/util/normalized_map.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/util/normalized_map.rb | require 'delegate'
module Sass
module Util
# A hash that normalizes its string keys while still allowing you to get back
# to the original keys that were stored. If several different values normalize
# to the same value, whichever is stored last wins.
class NormalizedMap
# Create a normalized map
def initialize(map = nil)
@key_strings = {}
@map = {}
map.each {|key, value| self[key] = value} if map
end
# Specifies how to transform the key.
#
# This can be overridden to create other normalization behaviors.
def normalize(key)
key.tr("-", "_")
end
# Returns the version of `key` as it was stored before
# normalization. If `key` isn't in the map, returns it as it was
# passed in.
#
# @return [String]
def denormalize(key)
@key_strings[normalize(key)] || key
end
# @private
def []=(k, v)
normalized = normalize(k)
@map[normalized] = v
@key_strings[normalized] = k
v
end
# @private
def [](k)
@map[normalize(k)]
end
# @private
def has_key?(k)
@map.has_key?(normalize(k))
end
# @private
def delete(k)
normalized = normalize(k)
@key_strings.delete(normalized)
@map.delete(normalized)
end
# @return [Hash] Hash with the keys as they were stored (before normalization).
def as_stored
Sass::Util.map_keys(@map) {|k| @key_strings[k]}
end
def empty?
@map.empty?
end
def values
@map.values
end
def keys
@map.keys
end
def each
@map.each {|k, v| yield(k, v)}
end
def size
@map.size
end
def to_hash
@map.dup
end
def to_a
@map.to_a
end
def map
@map.map {|k, v| yield(k, v)}
end
def dup
d = super
d.send(:instance_variable_set, "@map", @map.dup)
d
end
def sort_by
@map.sort_by {|k, v| yield k, v}
end
def update(map)
map = map.as_stored if map.is_a?(NormalizedMap)
map.each {|k, v| self[k] = v}
end
def method_missing(method, *args, &block)
if Sass.tests_running
raise ArgumentError.new("The method #{method} must be implemented explicitly")
end
@map.send(method, *args, &block)
end
def respond_to_missing?(method, include_private = false)
@map.respond_to?(method, include_private)
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/plugin/generic.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/plugin/generic.rb | # The reason some options are declared here rather than in sass/plugin/configuration.rb
# is that otherwise they'd clobber the Rails-specific options.
# Since Rails' options are lazy-loaded in Rails 3,
# they're reverse-merged with the default options
# so that user configuration is preserved.
# This means that defaults that differ from Rails'
# must be declared here.
unless defined?(Sass::GENERIC_LOADED)
Sass::GENERIC_LOADED = true
Sass::Plugin.options.merge!(:css_location => './public/stylesheets',
:always_update => false,
:always_check => true)
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/plugin/rails.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/plugin/rails.rb | unless defined?(Sass::RAILS_LOADED)
Sass::RAILS_LOADED = true
module Sass::Plugin::Configuration
# Different default options in a rails environment.
def default_options
return @default_options if @default_options
opts = {
:quiet => Sass::Util.rails_env != "production",
:full_exception => Sass::Util.rails_env != "production",
:cache_location => Sass::Util.rails_root + '/tmp/sass-cache'
}
opts.merge!(
:always_update => false,
:template_location => Sass::Util.rails_root + '/public/stylesheets/sass',
:css_location => Sass::Util.rails_root + '/public/stylesheets',
:always_check => Sass::Util.rails_env == "development")
@default_options = opts.freeze
end
end
Sass::Plugin.options.reverse_merge!(Sass::Plugin.default_options)
# Rails 3.1 loads and handles Sass all on its own
if defined?(ActionController::Metal)
# 3.1 > Rails >= 3.0
require 'sass/plugin/rack'
Rails.configuration.middleware.use(Sass::Plugin::Rack)
elsif defined?(ActionController::Dispatcher) &&
defined?(ActionController::Dispatcher.middleware)
# Rails >= 2.3
require 'sass/plugin/rack'
ActionController::Dispatcher.middleware.use(Sass::Plugin::Rack)
else
module ActionController
class Base
alias_method :sass_old_process, :process
def process(*args)
Sass::Plugin.check_for_updates
sass_old_process(*args)
end
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/plugin/compiler.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/plugin/compiler.rb | require 'fileutils'
require 'sass'
# XXX CE: is this still necessary now that we have the compiler class?
require 'sass/callbacks'
require 'sass/plugin/configuration'
require 'sass/plugin/staleness_checker'
module Sass::Plugin
# The Compiler class handles compilation of multiple files and/or directories,
# including checking which CSS files are out-of-date and need to be updated
# and calling Sass to perform the compilation on those files.
#
# {Sass::Plugin} uses this class to update stylesheets for a single application.
# Unlike {Sass::Plugin}, though, the Compiler class has no global state,
# and so multiple instances may be created and used independently.
#
# If you need to compile a Sass string into CSS,
# please see the {Sass::Engine} class.
#
# Unlike {Sass::Plugin}, this class doesn't keep track of
# whether or how many times a stylesheet should be updated.
# Therefore, the following `Sass::Plugin` options are ignored by the Compiler:
#
# * `:never_update`
# * `:always_check`
class Compiler
include Configuration
extend Sass::Callbacks
# Creates a new compiler.
#
# @param opts [{Symbol => Object}]
# See {file:SASS_REFERENCE.md#Options the Sass options documentation}.
def initialize(opts = {})
@watched_files = Set.new
options.merge!(opts)
end
# Register a callback to be run before stylesheets are mass-updated.
# This is run whenever \{#update\_stylesheets} is called,
# unless the \{file:SASS_REFERENCE.md#never_update-option `:never_update` option}
# is enabled.
#
# @yield [files]
# @yieldparam files [<(String, String, String)>]
# Individual files to be updated. Files in directories specified are included in this list.
# The first element of each pair is the source file,
# the second is the target CSS file,
# the third is the target sourcemap file.
define_callback :updating_stylesheets
# Register a callback to be run after stylesheets are mass-updated.
# This is run whenever \{#update\_stylesheets} is called,
# unless the \{file:SASS_REFERENCE.md#never_update-option `:never_update` option}
# is enabled.
#
# @yield [updated_files]
# @yieldparam updated_files [<(String, String)>]
# Individual files that were updated.
# The first element of each pair is the source file, the second is the target CSS file.
define_callback :updated_stylesheets
# Register a callback to be run after a single stylesheet is updated.
# The callback is only run if the stylesheet is really updated;
# if the CSS file is fresh, this won't be run.
#
# Even if the \{file:SASS_REFERENCE.md#full_exception-option `:full_exception` option}
# is enabled, this callback won't be run
# when an exception CSS file is being written.
# To run an action for those files, use \{#on\_compilation\_error}.
#
# @yield [template, css, sourcemap]
# @yieldparam template [String]
# The location of the Sass/SCSS file being updated.
# @yieldparam css [String]
# The location of the CSS file being generated.
# @yieldparam sourcemap [String]
# The location of the sourcemap being generated, if any.
define_callback :updated_stylesheet
# Register a callback to be run when compilation starts.
#
# In combination with on_updated_stylesheet, this could be used
# to collect compilation statistics like timing or to take a
# diff of the changes to the output file.
#
# @yield [template, css, sourcemap]
# @yieldparam template [String]
# The location of the Sass/SCSS file being updated.
# @yieldparam css [String]
# The location of the CSS file being generated.
# @yieldparam sourcemap [String]
# The location of the sourcemap being generated, if any.
define_callback :compilation_starting
# Register a callback to be run when Sass decides not to update a stylesheet.
# In particular, the callback is run when Sass finds that
# the template file and none of its dependencies
# have been modified since the last compilation.
#
# Note that this is **not** run when the
# \{file:SASS_REFERENCE.md#never-update_option `:never_update` option} is set,
# nor when Sass decides not to compile a partial.
#
# @yield [template, css]
# @yieldparam template [String]
# The location of the Sass/SCSS file not being updated.
# @yieldparam css [String]
# The location of the CSS file not being generated.
define_callback :not_updating_stylesheet
# Register a callback to be run when there's an error
# compiling a Sass file.
# This could include not only errors in the Sass document,
# but also errors accessing the file at all.
#
# @yield [error, template, css]
# @yieldparam error [Exception] The exception that was raised.
# @yieldparam template [String]
# The location of the Sass/SCSS file being updated.
# @yieldparam css [String]
# The location of the CSS file being generated.
define_callback :compilation_error
# Register a callback to be run when Sass creates a directory
# into which to put CSS files.
#
# Note that even if multiple levels of directories need to be created,
# the callback may only be run once.
# For example, if "foo/" exists and "foo/bar/baz/" needs to be created,
# this may only be run for "foo/bar/baz/".
# This is not a guarantee, however;
# it may also be run for "foo/bar/".
#
# @yield [dirname]
# @yieldparam dirname [String]
# The location of the directory that was created.
define_callback :creating_directory
# Register a callback to be run when Sass detects
# that a template has been modified.
# This is only run when using \{#watch}.
#
# @yield [template]
# @yieldparam template [String]
# The location of the template that was modified.
define_callback :template_modified
# Register a callback to be run when Sass detects
# that a new template has been created.
# This is only run when using \{#watch}.
#
# @yield [template]
# @yieldparam template [String]
# The location of the template that was created.
define_callback :template_created
# Register a callback to be run when Sass detects
# that a template has been deleted.
# This is only run when using \{#watch}.
#
# @yield [template]
# @yieldparam template [String]
# The location of the template that was deleted.
define_callback :template_deleted
# Register a callback to be run when Sass deletes a CSS file.
# This happens when the corresponding Sass/SCSS file has been deleted
# and when the compiler cleans the output files.
#
# @yield [filename]
# @yieldparam filename [String]
# The location of the CSS file that was deleted.
define_callback :deleting_css
# Register a callback to be run when Sass deletes a sourcemap file.
# This happens when the corresponding Sass/SCSS file has been deleted
# and when the compiler cleans the output files.
#
# @yield [filename]
# @yieldparam filename [String]
# The location of the sourcemap file that was deleted.
define_callback :deleting_sourcemap
# Updates out-of-date stylesheets.
#
# Checks each Sass/SCSS file in
# {file:SASS_REFERENCE.md#template_location-option `:template_location`}
# to see if it's been modified more recently than the corresponding CSS file
# in {file:SASS_REFERENCE.md#css_location-option `:css_location`}.
# If it has, it updates the CSS file.
#
# @param individual_files [Array<(String, String[, String])>]
# A list of files to check for updates
# **in addition to those specified by the
# {file:SASS_REFERENCE.md#template_location-option `:template_location` option}.**
# The first string in each pair is the location of the Sass/SCSS file,
# the second is the location of the CSS file that it should be compiled to.
# The third string, if provided, is the location of the Sourcemap file.
def update_stylesheets(individual_files = [])
Sass::Plugin.checked_for_updates = true
staleness_checker = StalenessChecker.new(engine_options)
files = file_list(individual_files)
run_updating_stylesheets(files)
updated_stylesheets = []
files.each do |file, css, sourcemap|
# TODO: Does staleness_checker need to check the sourcemap file as well?
if options[:always_update] || staleness_checker.stylesheet_needs_update?(css, file)
# XXX For consistency, this should return the sourcemap too, but it would
# XXX be an API change.
updated_stylesheets << [file, css]
update_stylesheet(file, css, sourcemap)
else
run_not_updating_stylesheet(file, css, sourcemap)
end
end
run_updated_stylesheets(updated_stylesheets)
end
# Construct a list of files that might need to be compiled
# from the provided individual_files and the template_locations.
#
# Note: this method does not cache the results as they can change
# across invocations when sass files are added or removed.
#
# @param individual_files [Array<(String, String[, String])>]
# A list of files to check for updates
# **in addition to those specified by the
# {file:SASS_REFERENCE.md#template_location-option `:template_location` option}.**
# The first string in each pair is the location of the Sass/SCSS file,
# the second is the location of the CSS file that it should be compiled to.
# The third string, if provided, is the location of the Sourcemap file.
# @return [Array<(String, String, String)>]
# A list of [sass_file, css_file, sourcemap_file] tuples similar
# to what was passed in, but expanded to include the current state
# of the directories being updated.
def file_list(individual_files = [])
files = individual_files.map do |tuple|
if engine_options[:sourcemap] == :none
tuple[0..1]
elsif tuple.size < 3
[tuple[0], tuple[1], Sass::Util.sourcemap_name(tuple[1])]
else
tuple.dup
end
end
template_location_array.each do |template_location, css_location|
Sass::Util.glob(File.join(template_location, "**", "[^_]*.s[ca]ss")).sort.each do |file|
# Get the relative path to the file
name = Sass::Util.relative_path_from(file, template_location).to_s
css = css_filename(name, css_location)
sourcemap = Sass::Util.sourcemap_name(css) unless engine_options[:sourcemap] == :none
files << [file, css, sourcemap]
end
end
files
end
# Watches the template directory (or directories)
# and updates the CSS files whenever the related Sass/SCSS files change.
# `watch` never returns.
#
# Whenever a change is detected to a Sass/SCSS file in
# {file:SASS_REFERENCE.md#template_location-option `:template_location`},
# the corresponding CSS file in {file:SASS_REFERENCE.md#css_location-option `:css_location`}
# will be recompiled.
# The CSS files of any Sass/SCSS files that import the changed file will also be recompiled.
#
# Before the watching starts in earnest, `watch` calls \{#update\_stylesheets}.
#
# Note that `watch` uses the [Listen](http://github.com/guard/listen) library
# to monitor the filesystem for changes.
# Listen isn't loaded until `watch` is run.
# The version of Listen distributed with Sass is loaded by default,
# but if another version has already been loaded that will be used instead.
#
# @param individual_files [Array<(String, String[, String])>]
# A list of files to check for updates
# **in addition to those specified by the
# {file:SASS_REFERENCE.md#template_location-option `:template_location` option}.**
# The first string in each pair is the location of the Sass/SCSS file,
# the second is the location of the CSS file that it should be compiled to.
# The third string, if provided, is the location of the Sourcemap file.
# @param options [Hash] The options that control how watching works.
# @option options [Boolean] :skip_initial_update
# Don't do an initial update when starting the watcher when true
def watch(individual_files = [], options = {})
@inferred_directories = []
options, individual_files = individual_files, [] if individual_files.is_a?(Hash)
update_stylesheets(individual_files) unless options[:skip_initial_update]
directories = watched_paths
individual_files.each do |(source, _, _)|
source = File.expand_path(source)
@watched_files << Sass::Util.realpath(source).to_s
@inferred_directories << File.dirname(source)
end
directories += @inferred_directories
directories = remove_redundant_directories(directories)
# TODO: Keep better track of what depends on what
# so we don't have to run a global update every time anything changes.
# XXX The :additional_watch_paths option exists for Compass to use until
# a deprecated feature is removed. It may be removed without warning.
directories += Array(options[:additional_watch_paths])
options = {
:relative_paths => false,
# The native windows listener is much slower than the polling option, according to
# https://github.com/nex3/sass/commit/a3031856b22bc834a5417dedecb038b7be9b9e3e
:force_polling => @options[:poll] || Sass::Util.windows?
}
listener = create_listener(*directories, options) do |modified, added, removed|
on_file_changed(individual_files, modified, added, removed)
yield(modified, added, removed) if block_given?
end
begin
listener.start
sleep
rescue Interrupt
# Squelch Interrupt for clean exit from Listen::Listener
end
end
# Non-destructively modifies \{#options} so that default values are properly set,
# and returns the result.
#
# @param additional_options [{Symbol => Object}] An options hash with which to merge \{#options}
# @return [{Symbol => Object}] The modified options hash
def engine_options(additional_options = {})
opts = options.merge(additional_options)
opts[:load_paths] = load_paths(opts)
options[:sourcemap] = :auto if options[:sourcemap] == true
options[:sourcemap] = :none if options[:sourcemap] == false
opts
end
# Compass expects this to exist
def stylesheet_needs_update?(css_file, template_file)
StalenessChecker.stylesheet_needs_update?(css_file, template_file)
end
# Remove all output files that would be created by calling update_stylesheets, if they exist.
#
# This method runs the deleting_css and deleting_sourcemap callbacks for
# the files that are deleted.
#
# @param individual_files [Array<(String, String[, String])>]
# A list of files to check for updates
# **in addition to those specified by the
# {file:SASS_REFERENCE.md#template_location-option `:template_location` option}.**
# The first string in each pair is the location of the Sass/SCSS file,
# the second is the location of the CSS file that it should be compiled to.
# The third string, if provided, is the location of the Sourcemap file.
def clean(individual_files = [])
file_list(individual_files).each do |(_, css_file, sourcemap_file)|
if File.exist?(css_file)
run_deleting_css css_file
File.delete(css_file)
end
if sourcemap_file && File.exist?(sourcemap_file)
run_deleting_sourcemap sourcemap_file
File.delete(sourcemap_file)
end
end
nil
end
private
# This is mocked out in compiler_test.rb.
def create_listener(*args, &block)
require 'sass-listen'
SassListen.to(*args, &block)
end
def remove_redundant_directories(directories)
dedupped = []
directories.each do |new_directory|
# no need to add a directory that is already watched.
next if dedupped.any? do |existing_directory|
child_of_directory?(existing_directory, new_directory)
end
# get rid of any sub directories of this new directory
dedupped.reject! do |existing_directory|
child_of_directory?(new_directory, existing_directory)
end
dedupped << new_directory
end
dedupped
end
def on_file_changed(individual_files, modified, added, removed)
recompile_required = false
modified.uniq.each do |f|
next unless watched_file?(f)
recompile_required = true
run_template_modified(relative_to_pwd(f))
end
added.uniq.each do |f|
next unless watched_file?(f)
recompile_required = true
run_template_created(relative_to_pwd(f))
end
removed.uniq.each do |f|
next unless watched_file?(f)
run_template_deleted(relative_to_pwd(f))
if (files = individual_files.find {|(source, _, _)| File.expand_path(source) == f})
recompile_required = true
# This was a file we were watching explicitly and compiling to a particular location.
# Delete the corresponding file.
try_delete_css files[1]
else
next unless watched_file?(f)
recompile_required = true
# Look for the sass directory that contained the sass file
# And try to remove the css file that corresponds to it
template_location_array.each do |(sass_dir, css_dir)|
sass_dir = File.expand_path(sass_dir)
next unless child_of_directory?(sass_dir, f)
remainder = f[(sass_dir.size + 1)..-1]
try_delete_css(css_filename(remainder, css_dir))
break
end
end
end
return unless recompile_required
# In case a file we're watching is removed and then recreated we
# prune out the non-existant files here.
watched_files_remaining = individual_files.select {|(source, _, _)| File.exist?(source)}
update_stylesheets(watched_files_remaining)
end
def update_stylesheet(filename, css, sourcemap)
dir = File.dirname(css)
unless File.exist?(dir)
run_creating_directory dir
FileUtils.mkdir_p dir
end
begin
File.read(filename) unless File.readable?(filename) # triggers an error for handling
engine_opts = engine_options(:css_filename => css,
:filename => filename,
:sourcemap_filename => sourcemap)
mapping = nil
run_compilation_starting(filename, css, sourcemap)
engine = Sass::Engine.for_file(filename, engine_opts)
if sourcemap
rendered, mapping = engine.render_with_sourcemap(File.basename(sourcemap))
else
rendered = engine.render
end
rescue StandardError => e
compilation_error_occurred = true
run_compilation_error e, filename, css, sourcemap
raise e unless options[:full_exception]
rendered = Sass::SyntaxError.exception_to_css(e, options[:line] || 1)
end
write_file(css, rendered)
if mapping
write_file(
sourcemap,
mapping.to_json(
:css_path => css, :sourcemap_path => sourcemap, :type => options[:sourcemap]))
end
run_updated_stylesheet(filename, css, sourcemap) unless compilation_error_occurred
end
def write_file(fileName, content)
flag = 'w'
flag = 'wb' if Sass::Util.windows? && options[:unix_newlines]
File.open(fileName, flag) do |file|
file.set_encoding(content.encoding)
file.print(content)
end
end
def try_delete_css(css)
if File.exist?(css)
run_deleting_css css
File.delete css
end
map = Sass::Util.sourcemap_name(css)
return unless File.exist?(map)
run_deleting_sourcemap map
File.delete map
end
def watched_file?(file)
@watched_files.include?(file) ||
normalized_load_paths.any? {|lp| lp.watched_file?(file)} ||
@inferred_directories.any? {|d| sass_file_in_directory?(d, file)}
end
def sass_file_in_directory?(directory, filename)
filename =~ /\.s[ac]ss$/ && filename.start_with?(directory + File::SEPARATOR)
end
def watched_paths
@watched_paths ||= normalized_load_paths.map {|lp| lp.directories_to_watch}.compact.flatten
end
def normalized_load_paths
@normalized_load_paths ||=
Sass::Engine.normalize_options(:load_paths => load_paths)[:load_paths]
end
def load_paths(opts = options)
(opts[:load_paths] || []) + template_locations
end
def template_locations
template_location_array.to_a.map {|l| l.first}
end
def css_locations
template_location_array.to_a.map {|l| l.last}
end
def css_filename(name, path)
"#{path}#{File::SEPARATOR unless path.end_with?(File::SEPARATOR)}#{name}".
gsub(/\.s[ac]ss$/, '.css')
end
def relative_to_pwd(f)
Sass::Util.relative_path_from(f, Dir.pwd).to_s
rescue ArgumentError # when a relative path cannot be computed
f
end
def child_of_directory?(parent, child)
parent_dir = parent.end_with?(File::SEPARATOR) ? parent : (parent + File::SEPARATOR)
child.start_with?(parent_dir) || parent == child
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/plugin/staleness_checker.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/plugin/staleness_checker.rb | require 'thread'
module Sass
module Plugin
# The class handles `.s[ca]ss` file staleness checks via their mtime timestamps.
#
# To speed things up two level of caches are employed:
#
# * A class-level dependency cache which stores @import paths for each file.
# This is a long-lived cache that is reused by every StalenessChecker instance.
# * Three short-lived instance-level caches, one for file mtimes,
# one for whether a file is stale during this particular run.
# and one for the parse tree for a file.
# These are only used by a single StalenessChecker instance.
#
# Usage:
#
# * For a one-off staleness check of a single `.s[ca]ss` file,
# the class-level {stylesheet_needs_update?} method
# should be used.
# * For a series of staleness checks (e.g. checking all files for staleness)
# a StalenessChecker instance should be created,
# and the instance-level \{#stylesheet\_needs\_update?} method should be used.
# the caches should make the whole process significantly faster.
# *WARNING*: It is important not to retain the instance for too long,
# as its instance-level caches are never explicitly expired.
class StalenessChecker
@dependencies_cache = {}
@dependency_cache_mutex = Mutex.new
class << self
# TODO: attach this to a compiler instance.
# @private
attr_accessor :dependencies_cache
attr_reader :dependency_cache_mutex
end
# Creates a new StalenessChecker
# for checking the staleness of several stylesheets at once.
#
# @param options [{Symbol => Object}]
# See {file:SASS_REFERENCE.md#Options the Sass options documentation}.
def initialize(options)
# URIs that are being actively checked for staleness. Protects against
# import loops.
@actively_checking = Set.new
# Entries in the following instance-level caches are never explicitly expired.
# Instead they are supposed to automatically go out of scope when a series of staleness
# checks (this instance of StalenessChecker was created for) is finished.
@mtimes, @dependencies_stale, @parse_trees = {}, {}, {}
@options = Sass::Engine.normalize_options(options)
end
# Returns whether or not a given CSS file is out of date
# and needs to be regenerated.
#
# @param css_file [String] The location of the CSS file to check.
# @param template_file [String] The location of the Sass or SCSS template
# that is compiled to `css_file`.
# @return [Boolean] Whether the stylesheet needs to be updated.
def stylesheet_needs_update?(css_file, template_file, importer = nil)
template_file = File.expand_path(template_file)
begin
css_mtime = File.mtime(css_file)
rescue Errno::ENOENT
return true
end
stylesheet_modified_since?(template_file, css_mtime, importer)
end
# Returns whether a Sass or SCSS stylesheet has been modified since a given time.
#
# @param template_file [String] The location of the Sass or SCSS template.
# @param mtime [Time] The modification time to check against.
# @param importer [Sass::Importers::Base] The importer used to locate the stylesheet.
# Defaults to the filesystem importer.
# @return [Boolean] Whether the stylesheet has been modified.
def stylesheet_modified_since?(template_file, mtime, importer = nil)
importer ||= @options[:filesystem_importer].new(".")
dependency_updated?(mtime).call(template_file, importer)
end
# Returns whether or not a given CSS file is out of date
# and needs to be regenerated.
#
# The distinction between this method and the instance-level \{#stylesheet\_needs\_update?}
# is that the instance method preserves mtime and stale-dependency caches,
# so it's better to use when checking multiple stylesheets at once.
#
# @param css_file [String] The location of the CSS file to check.
# @param template_file [String] The location of the Sass or SCSS template
# that is compiled to `css_file`.
# @return [Boolean] Whether the stylesheet needs to be updated.
def self.stylesheet_needs_update?(css_file, template_file, importer = nil)
new(Plugin.engine_options).stylesheet_needs_update?(css_file, template_file, importer)
end
# Returns whether a Sass or SCSS stylesheet has been modified since a given time.
#
# The distinction between this method and the instance-level \{#stylesheet\_modified\_since?}
# is that the instance method preserves mtime and stale-dependency caches,
# so it's better to use when checking multiple stylesheets at once.
#
# @param template_file [String] The location of the Sass or SCSS template.
# @param mtime [Time] The modification time to check against.
# @param importer [Sass::Importers::Base] The importer used to locate the stylesheet.
# Defaults to the filesystem importer.
# @return [Boolean] Whether the stylesheet has been modified.
def self.stylesheet_modified_since?(template_file, mtime, importer = nil)
new(Plugin.engine_options).stylesheet_modified_since?(template_file, mtime, importer)
end
private
def dependencies_stale?(uri, importer, css_mtime)
timestamps = @dependencies_stale[[uri, importer]] ||= {}
timestamps.each_pair do |checked_css_mtime, is_stale|
if checked_css_mtime <= css_mtime && !is_stale
return false
elsif checked_css_mtime > css_mtime && is_stale
return true
end
end
timestamps[css_mtime] = dependencies(uri, importer).any?(&dependency_updated?(css_mtime))
rescue Sass::SyntaxError
# If there's an error finding dependencies, default to recompiling.
true
end
def mtime(uri, importer)
@mtimes[[uri, importer]] ||=
begin
mtime = importer.mtime(uri, @options)
if mtime.nil?
with_dependency_cache {|cache| cache.delete([uri, importer])}
nil
else
mtime
end
end
end
def dependencies(uri, importer)
stored_mtime, dependencies =
with_dependency_cache {|cache| Sass::Util.destructure(cache[[uri, importer]])}
if !stored_mtime || stored_mtime < mtime(uri, importer)
dependencies = compute_dependencies(uri, importer)
with_dependency_cache do |cache|
cache[[uri, importer]] = [mtime(uri, importer), dependencies]
end
end
dependencies
end
def dependency_updated?(css_mtime)
proc do |uri, importer|
next true if @actively_checking.include?(uri)
begin
@actively_checking << uri
sass_mtime = mtime(uri, importer)
!sass_mtime ||
sass_mtime > css_mtime ||
dependencies_stale?(uri, importer, css_mtime)
ensure
@actively_checking.delete uri
end
end
end
def compute_dependencies(uri, importer)
tree(uri, importer).grep(Tree::ImportNode) do |n|
next if n.css_import?
file = n.imported_file
key = [file.options[:filename], file.options[:importer]]
@parse_trees[key] = file.to_tree
key
end.compact
end
def tree(uri, importer)
@parse_trees[[uri, importer]] ||= importer.find(uri, @options).to_tree
end
# Get access to the global dependency cache in a threadsafe manner.
# Inside the block, no other thread can access the dependency cache.
#
# @yieldparam cache [Hash] The hash that is the global dependency cache
# @return The value returned by the block to which this method yields
def with_dependency_cache
StalenessChecker.dependency_cache_mutex.synchronize do
yield StalenessChecker.dependencies_cache
end
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/plugin/rack.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/plugin/rack.rb | module Sass
module Plugin
# Rack middleware for compiling Sass code.
#
# ## Activate
#
# require 'sass/plugin/rack'
# use Sass::Plugin::Rack
#
# ## Customize
#
# Sass::Plugin.options.merge!(
# :cache_location => './tmp/sass-cache',
# :never_update => environment != :production,
# :full_exception => environment != :production)
#
# {file:SASS_REFERENCE.md#Options See the Reference for more options}.
#
# ## Use
#
# Put your Sass files in `public/stylesheets/sass`.
# Your CSS will be generated in `public/stylesheets`,
# and regenerated every request if necessary.
# The locations and frequency {file:SASS_REFERENCE.md#Options can be customized}.
# That's all there is to it!
class Rack
# The delay, in seconds, between update checks.
# Useful when many resources are requested for a single page.
# `nil` means no delay at all.
#
# @return [Float]
attr_accessor :dwell
# Initialize the middleware.
#
# @param app [#call] The Rack application
# @param dwell [Float] See \{#dwell}
def initialize(app, dwell = 1.0)
@app = app
@dwell = dwell
@check_after = Time.now.to_f
end
# Process a request, checking the Sass stylesheets for changes
# and updating them if necessary.
#
# @param env The Rack request environment
# @return [(#to_i, {String => String}, Object)] The Rack response
def call(env)
if @dwell.nil? || Time.now.to_f > @check_after
Sass::Plugin.check_for_updates
@check_after = Time.now.to_f + @dwell if @dwell
end
@app.call(env)
end
end
end
end
require 'sass/plugin'
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/plugin/configuration.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/plugin/configuration.rb | module Sass
module Plugin
# We keep configuration in its own self-contained file so that we can load
# it independently in Rails 3, where the full plugin stuff is lazy-loaded.
#
# Note that this is not guaranteed to be thread-safe. For guaranteed thread
# safety, use a separate {Sass::Plugin} for each thread.
module Configuration
# Returns the default options for a {Sass::Plugin::Compiler}.
#
# @return [{Symbol => Object}]
def default_options
@default_options ||= {
:css_location => './public/stylesheets',
:always_update => false,
:always_check => true,
:full_exception => true,
:cache_location => ".sass-cache"
}.freeze
end
# Resets the options and
# {Sass::Callbacks::InstanceMethods#clear_callbacks! clears all callbacks}.
def reset!
@options = nil
clear_callbacks!
end
# An options hash. See {file:SASS_REFERENCE.md#Options the Sass options
# documentation}.
#
# @return [{Symbol => Object}]
def options
@options ||= default_options.dup
end
# Adds a new template-location/css-location mapping.
# This means that Sass/SCSS files in `template_location`
# will be compiled to CSS files in `css_location`.
#
# This is preferred over manually manipulating the
# {file:SASS_REFERENCE.md#template_location-option `:template_location` option}
# since the option can be in multiple formats.
#
# Note that this method will change `options[:template_location]`
# to be in the Array format.
# This means that even if `options[:template_location]`
# had previously been a Hash or a String,
# it will now be an Array.
#
# @param template_location [String] The location where Sass/SCSS files will be.
# @param css_location [String] The location where compiled CSS files will go.
def add_template_location(template_location, css_location = options[:css_location])
normalize_template_location!
template_location_array << [template_location, css_location]
end
# Removes a template-location/css-location mapping.
# This means that Sass/SCSS files in `template_location`
# will no longer be compiled to CSS files in `css_location`.
#
# This is preferred over manually manipulating the
# {file:SASS_REFERENCE.md#template_location-option `:template_location` option}
# since the option can be in multiple formats.
#
# Note that this method will change `options[:template_location]`
# to be in the Array format.
# This means that even if `options[:template_location]`
# had previously been a Hash or a String,
# it will now be an Array.
#
# @param template_location [String]
# The location where Sass/SCSS files were,
# which is now going to be ignored.
# @param css_location [String]
# The location where compiled CSS files went, but will no longer go.
# @return [Boolean]
# Non-`nil` if the given mapping already existed and was removed,
# or `nil` if nothing was changed.
def remove_template_location(template_location, css_location = options[:css_location])
normalize_template_location!
template_location_array.delete([template_location, css_location])
end
# Returns the template locations configured for Sass
# as an array of `[template_location, css_location]` pairs.
# See the {file:SASS_REFERENCE.md#template_location-option `:template_location` option}
# for details.
#
# Modifications to the returned array may not be persistent. Use {#add_template_location}
# and {#remove_template_location} instead.
#
# @return [Array<(String, String)>]
# An array of `[template_location, css_location]` pairs.
def template_location_array
convert_template_location(options[:template_location], options[:css_location])
end
private
# Returns the given template location, as an array. If it's already an array,
# it is returned unmodified. Otherwise, a new array is created and returned.
#
# @param template_location [String, Array<(String, String)>]
# A single template location, or a pre-normalized array of template
# locations and CSS locations.
# @param css_location [String?]
# The location for compiled CSS files.
# @return [Array<(String, String)>]
# An array of `[template_location, css_location]` pairs.
def convert_template_location(template_location, css_location)
return template_location if template_location.is_a?(Array)
case template_location
when nil
if css_location
[[File.join(css_location, 'sass'), css_location]]
else
[]
end
when String
[[template_location, css_location]]
else
template_location.to_a
end
end
def normalize_template_location!
options[:template_location] = convert_template_location(
options[:template_location], options[:css_location])
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/plugin/merb.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/plugin/merb.rb | unless defined?(Sass::MERB_LOADED)
Sass::MERB_LOADED = true
module Sass::Plugin::Configuration
# Different default options in a m environment.
def default_options
@default_options ||= begin
version = Merb::VERSION.split('.').map {|n| n.to_i}
if version[0] <= 0 && version[1] < 5
root = MERB_ROOT
env = MERB_ENV
else
root = Merb.root.to_s
env = Merb.environment
end
{
:always_update => false,
:template_location => root + '/public/stylesheets/sass',
:css_location => root + '/public/stylesheets',
:cache_location => root + '/tmp/sass-cache',
:always_check => env != "production",
:quiet => env != "production",
:full_exception => env != "production"
}.freeze
end
end
end
config = Merb::Plugins.config[:sass] || Merb::Plugins.config["sass"] || {}
if defined? config.symbolize_keys!
config.symbolize_keys!
end
Sass::Plugin.options.merge!(config)
require 'sass/plugin/rack'
class Sass::Plugin::MerbBootLoader < Merb::BootLoader
after Merb::BootLoader::RackUpApplication
def self.run
# Apparently there's no better way than this to add Sass
# to Merb's Rack stack.
Merb::Config[:app] = Sass::Plugin::Rack.new(Merb::Config[:app])
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/logger/base.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/logger/base.rb | require 'sass/logger/log_level'
class Sass::Logger::Base
include Sass::Logger::LogLevel
attr_accessor :log_level
attr_accessor :disabled
attr_accessor :io
log_level :trace
log_level :debug
log_level :info
log_level :warn
log_level :error
def initialize(log_level = :debug, io = nil)
self.log_level = log_level
self.io = io
end
def logging_level?(level)
!disabled && self.class.log_level?(level, log_level)
end
# Captures all logger messages emitted during a block and returns them as a
# string.
def capture
old_io = io
self.io = StringIO.new
yield
io.string
ensure
self.io = old_io
end
def log(level, message)
_log(level, message) if logging_level?(level)
end
def _log(level, message)
if io
io.puts(message)
else
Kernel.warn(message)
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/logger/delayed.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/logger/delayed.rb | require 'sass/logger/log_level'
# A logger that delays messages until they're explicitly flushed to an inner
# logger.
#
# This can be installed around the current logger by calling \{#install!}, and
# the original logger can be replaced by calling \{#uninstall!}. The log
# messages can be flushed by calling \{#flush}.
class Sass::Logger::Delayed < Sass::Logger::Base
# Installs a new delayed logger as the current Sass logger, wrapping the
# original logger.
#
# This can be undone by calling \{#uninstall!}.
#
# @return [Sass::Logger::Delayed] The newly-created logger.
def self.install!
logger = Sass::Logger::Delayed.new(Sass.logger)
Sass.logger = logger
logger
end
# Creates a delayed logger wrapping `inner`.
#
# @param inner [Sass::Logger::Base] The wrapped logger.
def initialize(inner)
self.log_level = inner.log_level
@inner = inner
@messages = []
end
# Flushes all queued logs to the wrapped logger.
def flush
@messages.each {|(l, m)| @inner.log(l, m)}
end
# Uninstalls this logger from \{Sass.logger\}. This should only be called if
# the logger was installed using \{#install!}
def uninstall!
if Sass.logger != self
throw Exception.new("Can't uninstall a logger that's not currently installed.")
end
@inner.log_level = log_level
Sass.logger = @inner
end
def _log(level, message)
@messages << [level, message]
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/logger/log_level.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/logger/log_level.rb | module Sass
module Logger
module LogLevel
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def inherited(subclass)
subclass.log_levels = subclass.superclass.log_levels.dup
end
attr_writer :log_levels
def log_levels
@log_levels ||= {}
end
def log_level?(level, min_level)
log_levels[level] >= log_levels[min_level]
end
def log_level(name, options = {})
if options[:prepend]
level = log_levels.values.min
level = level.nil? ? 0 : level - 1
else
level = log_levels.values.max
level = level.nil? ? 0 : level + 1
end
log_levels.update(name => level)
define_logger(name)
end
def define_logger(name, options = {})
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{name}(message)
#{options.fetch(:to, :log)}(#{name.inspect}, message)
end
RUBY
end
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/importers/deprecated_path.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/importers/deprecated_path.rb | module Sass
module Importers
# This importer emits a deprecation warning the first time it is used to
# import a file. It is used to deprecate the current working
# directory from the list of automatic sass load paths.
class DeprecatedPath < Filesystem
# @param root [String] The absolute, expanded path to the folder that is deprecated.
def initialize(root)
@specified_root = root
@warning_given = false
super
end
# @see Sass::Importers::Base#find
def find(*args)
found = super
if found && !@warning_given
@warning_given = true
Sass::Util.sass_warn deprecation_warning
end
found
end
# @see Base#directories_to_watch
def directories_to_watch
# The current working directory was not watched in Sass 3.2,
# so we continue not to watch it while it's deprecated.
[]
end
# @see Sass::Importers::Base#to_s
def to_s
"#{@root} (DEPRECATED)"
end
protected
# @return [String] The deprecation warning that will be printed the first
# time an import occurs.
def deprecation_warning
path = @specified_root == "." ? "the current working directory" : @specified_root
<<WARNING
DEPRECATION WARNING: Importing from #{path} will not be
automatic in future versions of Sass. To avoid future errors, you can add it
to your environment explicitly by setting `SASS_PATH=#{@specified_root}`, by using the -I command
line option, or by changing your Sass configuration options.
WARNING
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/importers/base.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/importers/base.rb | module Sass
module Importers
# The abstract base class for Sass importers.
# All importers should inherit from this.
#
# At the most basic level, an importer is given a string
# and must return a {Sass::Engine} containing some Sass code.
# This string can be interpreted however the importer wants;
# however, subclasses are encouraged to use the URI format
# for pathnames.
#
# Importers that have some notion of "relative imports"
# should take a single load path in their constructor,
# and interpret paths as relative to that.
# They should also implement the \{#find\_relative} method.
#
# Importers should be serializable via `Marshal.dump`.
#
# @abstract
class Base
# Find a Sass file relative to another file.
# Importers without a notion of "relative paths"
# should just return nil here.
#
# If the importer does have a notion of "relative paths",
# it should ignore its load path during this method.
#
# See \{#find} for important information on how this method should behave.
#
# The `:filename` option passed to the returned {Sass::Engine}
# should be of a format that could be passed to \{#find}.
#
# @param uri [String] The URI to import. This is not necessarily relative,
# but this method should only return true if it is.
# @param base [String] The base filename. If `uri` is relative,
# it should be interpreted as relative to `base`.
# `base` is guaranteed to be in a format importable by this importer.
# @param options [{Symbol => Object}] Options for the Sass file
# containing the `@import` that's currently being resolved.
# @return [Sass::Engine, nil] An Engine containing the imported file,
# or nil if it couldn't be found or was in the wrong format.
def find_relative(uri, base, options)
Sass::Util.abstract(self)
end
# Find a Sass file, if it exists.
#
# This is the primary entry point of the Importer.
# It corresponds directly to an `@import` statement in Sass.
# It should do three basic things:
#
# * Determine if the URI is in this importer's format.
# If not, return nil.
# * Determine if the file indicated by the URI actually exists and is readable.
# If not, return nil.
# * Read the file and place the contents in a {Sass::Engine}.
# Return that engine.
#
# If this importer's format allows for file extensions,
# it should treat them the same way as the default {Filesystem} importer.
# If the URI explicitly has a `.sass` or `.scss` filename,
# the importer should look for that exact file
# and import it as the syntax indicated.
# If it doesn't exist, the importer should return nil.
#
# If the URI doesn't have either of these extensions,
# the importer should look for files with the extensions.
# If no such files exist, it should return nil.
#
# The {Sass::Engine} to be returned should be passed `options`,
# with a few modifications. `:syntax` should be set appropriately,
# `:filename` should be set to `uri`,
# and `:importer` should be set to this importer.
#
# @param uri [String] The URI to import.
# @param options [{Symbol => Object}] Options for the Sass file
# containing the `@import` that's currently being resolved.
# This is safe for subclasses to modify destructively.
# Callers should only pass in a value they don't mind being destructively modified.
# @return [Sass::Engine, nil] An Engine containing the imported file,
# or nil if it couldn't be found or was in the wrong format.
def find(uri, options)
Sass::Util.abstract(self)
end
# Returns the time the given Sass file was last modified.
#
# If the given file has been deleted or the time can't be accessed
# for some other reason, this should return nil.
#
# @param uri [String] The URI of the file to check.
# Comes from a `:filename` option set on an engine returned by this importer.
# @param options [{Symbol => Object}] Options for the Sass file
# containing the `@import` currently being checked.
# @return [Time, nil]
def mtime(uri, options)
Sass::Util.abstract(self)
end
# Get the cache key pair for the given Sass URI.
# The URI need not be checked for validity.
#
# The only strict requirement is that the returned pair of strings
# uniquely identify the file at the given URI.
# However, the first component generally corresponds roughly to the directory,
# and the second to the basename, of the URI.
#
# Note that keys must be unique *across importers*.
# Thus it's probably a good idea to include the importer name
# at the beginning of the first component.
#
# @param uri [String] A URI known to be valid for this importer.
# @param options [{Symbol => Object}] Options for the Sass file
# containing the `@import` currently being checked.
# @return [(String, String)] The key pair which uniquely identifies
# the file at the given URI.
def key(uri, options)
Sass::Util.abstract(self)
end
# Get the publicly-visible URL for an imported file. This URL is used by
# source maps to link to the source stylesheet. This may return `nil` to
# indicate that no public URL is available; however, this will cause
# sourcemap generation to fail if any CSS is generated from files imported
# from this importer.
#
# If an absolute "file:" URI can be produced for an imported file, that
# should be preferred to returning `nil`. However, a URL relative to
# `sourcemap_directory` should be preferred over an absolute "file:" URI.
#
# @param uri [String] A URI known to be valid for this importer.
# @param sourcemap_directory [String, NilClass] The absolute path to a
# directory on disk where the sourcemap will be saved. If uri refers to
# a file on disk that's accessible relative to sourcemap_directory, this
# may return a relative URL. This may be `nil` if the sourcemap's
# eventual location is unknown.
# @return [String?] The publicly-visible URL for this file, or `nil`
# indicating that no publicly-visible URL exists. This should be
# appropriately URL-escaped.
def public_url(uri, sourcemap_directory)
return if @public_url_warning_issued
@public_url_warning_issued = true
Sass::Util.sass_warn <<WARNING
WARNING: #{self.class.name} should define the #public_url method.
WARNING
nil
end
# A string representation of the importer.
# Should be overridden by subclasses.
#
# This is used to help debugging,
# and should usually just show the load path encapsulated by this importer.
#
# @return [String]
def to_s
Sass::Util.abstract(self)
end
# If the importer is based on files on the local filesystem
# this method should return folders which should be watched
# for changes.
#
# @return [Array<String>] List of absolute paths of directories to watch
def directories_to_watch
[]
end
# If this importer is based on files on the local filesystem This method
# should return true if the file, when changed, should trigger a
# recompile.
#
# It is acceptable for non-sass files to be watched and trigger a recompile.
#
# @param filename [String] The absolute filename for a file that has changed.
# @return [Boolean] When the file changed should cause a recompile.
def watched_file?(filename)
false
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/importers/filesystem.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/importers/filesystem.rb | require 'set'
module Sass
module Importers
# The default importer, used for any strings found in the load path.
# Simply loads Sass files from the filesystem using the default logic.
class Filesystem < Base
attr_accessor :root
# Creates a new filesystem importer that imports files relative to a given path.
#
# @param root [String] The root path.
# This importer will import files relative to this path.
def initialize(root)
@root = File.expand_path(root)
@real_root = Sass::Util.realpath(@root).to_s
@same_name_warnings = Set.new
end
# @see Base#find_relative
def find_relative(name, base, options)
_find(File.dirname(base), name, options)
end
# @see Base#find
def find(name, options)
_find(@root, name, options)
end
# @see Base#mtime
def mtime(name, options)
file, _ = Sass::Util.destructure(find_real_file(@root, name, options))
File.mtime(file) if file
rescue Errno::ENOENT
nil
end
# @see Base#key
def key(name, options)
[self.class.name + ":" + File.dirname(File.expand_path(name)),
File.basename(name)]
end
# @see Base#to_s
def to_s
@root
end
def hash
@root.hash
end
def eql?(other)
!other.nil? && other.respond_to?(:root) && root.eql?(other.root)
end
# @see Base#directories_to_watch
def directories_to_watch
[root]
end
# @see Base#watched_file?
def watched_file?(filename)
# Check against the root with symlinks resolved, since Listen
# returns fully-resolved paths.
filename =~ /\.s[ac]ss$/ && filename.start_with?(@real_root + File::SEPARATOR)
end
def public_url(name, sourcemap_directory)
file_pathname = Sass::Util.cleanpath(File.absolute_path(name, @root))
return Sass::Util.file_uri_from_path(file_pathname) if sourcemap_directory.nil?
sourcemap_pathname = Sass::Util.cleanpath(sourcemap_directory)
begin
Sass::Util.file_uri_from_path(
Sass::Util.relative_path_from(file_pathname, sourcemap_pathname))
rescue ArgumentError # when a relative path cannot be constructed
Sass::Util.file_uri_from_path(file_pathname)
end
end
protected
# If a full uri is passed, this removes the root from it
# otherwise returns the name unchanged
def remove_root(name)
if name.index(@root + "/") == 0
name[(@root.length + 1)..-1]
else
name
end
end
# A hash from file extensions to the syntaxes for those extensions.
# The syntaxes must be `:sass` or `:scss`.
#
# This can be overridden by subclasses that want normal filesystem importing
# with unusual extensions.
#
# @return [{String => Symbol}]
def extensions
{'sass' => :sass, 'scss' => :scss}
end
# Given an `@import`ed path, returns an array of possible
# on-disk filenames and their corresponding syntaxes for that path.
#
# @param name [String] The filename.
# @return [Array(String, Symbol)] An array of pairs.
# The first element of each pair is a filename to look for;
# the second element is the syntax that file would be in (`:sass` or `:scss`).
def possible_files(name)
name = escape_glob_characters(name)
dirname, basename, extname = split(name)
sorted_exts = extensions.sort
syntax = extensions[extname]
if syntax
ret = [["#{dirname}/{_,}#{basename}.#{extensions.invert[syntax]}", syntax]]
else
ret = sorted_exts.map {|ext, syn| ["#{dirname}/{_,}#{basename}.#{ext}", syn]}
end
# JRuby chokes when trying to import files from JARs when the path starts with './'.
ret.map {|f, s| [f.sub(%r{^\./}, ''), s]}
end
def escape_glob_characters(name)
name.gsub(/[\*\[\]\{\}\?]/) do |char|
"\\#{char}"
end
end
REDUNDANT_DIRECTORY = /#{Regexp.escape(File::SEPARATOR)}\.#{Regexp.escape(File::SEPARATOR)}/
# Given a base directory and an `@import`ed name,
# finds an existent file that matches the name.
#
# @param dir [String] The directory relative to which to search.
# @param name [String] The filename to search for.
# @return [(String, Symbol)] A filename-syntax pair.
def find_real_file(dir, name, options)
# On windows 'dir' or 'name' can be in native File::ALT_SEPARATOR form.
dir = dir.gsub(File::ALT_SEPARATOR, File::SEPARATOR) unless File::ALT_SEPARATOR.nil?
name = name.gsub(File::ALT_SEPARATOR, File::SEPARATOR) unless File::ALT_SEPARATOR.nil?
found = possible_files(remove_root(name)).map do |f, s|
path = if dir == "." || Sass::Util.pathname(f).absolute?
f
else
"#{escape_glob_characters(dir)}/#{f}"
end
Dir[path].map do |full_path|
full_path.gsub!(REDUNDANT_DIRECTORY, File::SEPARATOR)
[Sass::Util.cleanpath(full_path).to_s, s]
end
end.flatten(1)
if found.empty? && split(name)[2].nil? && File.directory?("#{dir}/#{name}")
return find_real_file("#{dir}/#{name}", "index", options)
end
if found.size > 1 && !@same_name_warnings.include?(found.first.first)
found.each {|(f, _)| @same_name_warnings << f}
relative_to = Sass::Util.pathname(dir)
if options[:_from_import_node]
# If _line exists, we're here due to an actual import in an
# import_node and we want to print a warning for a user writing an
# ambiguous import.
candidates = found.map do |(f, _)|
" " + Sass::Util.pathname(f).relative_path_from(relative_to).to_s
end.join("\n")
raise Sass::SyntaxError.new(<<MESSAGE)
It's not clear which file to import for '@import "#{name}"'.
Candidates:
#{candidates}
Please delete or rename all but one of these files.
MESSAGE
else
# Otherwise, we're here via StalenessChecker, and we want to print a
# warning for a user running `sass --watch` with two ambiguous files.
candidates = found.map {|(f, _)| " " + File.basename(f)}.join("\n")
Sass::Util.sass_warn <<WARNING
WARNING: In #{File.dirname(name)}:
There are multiple files that match the name "#{File.basename(name)}":
#{candidates}
WARNING
end
end
found.first
end
# Splits a filename into three parts, a directory part, a basename, and an extension
# Only the known extensions returned from the extensions method will be recognized as such.
def split(name)
extension = nil
dirname, basename = File.dirname(name), File.basename(name)
if basename =~ /^(.*)\.(#{extensions.keys.map {|e| Regexp.escape(e)}.join('|')})$/
basename = $1
extension = $2
end
[dirname, basename, extension]
end
private
def _find(dir, name, options)
full_filename, syntax = Sass::Util.destructure(find_real_file(dir, name, options))
return unless full_filename && File.file?(full_filename) && File.readable?(full_filename)
# TODO: this preserves historical behavior, but it's possible
# :filename should be either normalized to the native format
# or consistently URI-format.
full_filename = full_filename.tr("\\", "/") if Sass::Util.windows?
options[:syntax] = syntax
options[:filename] = full_filename
options[:importer] = self
Sass::Engine.new(File.read(full_filename), options)
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/scss/css_parser.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/scss/css_parser.rb | require 'sass/script/css_parser'
module Sass
module SCSS
# This is a subclass of {Parser} which only parses plain CSS.
# It doesn't support any Sass extensions, such as interpolation,
# parent references, nested selectors, and so forth.
# It does support all the same CSS hacks as the SCSS parser, though.
class CssParser < StaticParser
private
def placeholder_selector; nil; end
def parent_selector; nil; end
def interpolation(warn_for_color = false); nil; end
def use_css_import?; true; end
def block_contents(node, context)
if node.is_a?(Sass::Tree::DirectiveNode) && node.normalized_name == '@keyframes'
context = :keyframes
end
super(node, context)
end
def block_child(context)
case context
when :ruleset
declaration
when :stylesheet
directive || ruleset
when :directive
directive || declaration_or_ruleset
when :keyframes
keyframes_ruleset
end
end
def nested_properties!(node)
expected('expression (e.g. 1px, bold)')
end
def ruleset
start_pos = source_position
return unless (selector = selector_comma_sequence)
block(node(Sass::Tree::RuleNode.new(selector, range(start_pos)), start_pos), :ruleset)
end
def keyframes_ruleset
start_pos = source_position
return unless (selector = keyframes_selector)
block(node(Sass::Tree::KeyframeRuleNode.new(selector.strip), start_pos), :ruleset)
end
@sass_script_parser = Sass::Script::CssParser
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/scss/parser.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/scss/parser.rb | # -*- coding: utf-8 -*-
require 'set'
module Sass
module SCSS
# The parser for SCSS.
# It parses a string of code into a tree of {Sass::Tree::Node}s.
class Parser
# Expose for the SASS parser.
attr_accessor :offset
# @param str [String, StringScanner] The source document to parse.
# Note that `Parser` *won't* raise a nice error message if this isn't properly parsed;
# for that, you should use the higher-level {Sass::Engine} or {Sass::CSS}.
# @param filename [String] The name of the file being parsed. Used for
# warnings and source maps.
# @param importer [Sass::Importers::Base] The importer used to import the
# file being parsed. Used for source maps.
# @param line [Integer] The 1-based line on which the source string appeared,
# if it's part of another document.
# @param offset [Integer] The 1-based character (not byte) offset in the line on
# which the source string starts. Used for error reporting and sourcemap
# building.
def initialize(str, filename, importer, line = 1, offset = 1)
@template = str
@filename = filename
@importer = importer
@line = line
@offset = offset
@strs = []
@expected = nil
@throw_error = false
end
# Parses an SCSS document.
#
# @return [Sass::Tree::RootNode] The root node of the document tree
# @raise [Sass::SyntaxError] if there's a syntax error in the document
def parse
init_scanner!
root = stylesheet
expected("selector or at-rule") unless root && @scanner.eos?
root
end
# Parses an identifier with interpolation.
# Note that this won't assert that the identifier takes up the entire input string;
# it's meant to be used with `StringScanner`s as part of other parsers.
#
# @return [Array<String, Sass::Script::Tree::Node>, nil]
# The interpolated identifier, or nil if none could be parsed
def parse_interp_ident
init_scanner!
interp_ident
end
# Parses a supports clause for an @import directive
def parse_supports_clause
init_scanner!
ss
clause = supports_clause
ss
clause
end
# Parses a media query list.
#
# @return [Sass::Media::QueryList] The parsed query list
# @raise [Sass::SyntaxError] if there's a syntax error in the query list,
# or if it doesn't take up the entire input string.
def parse_media_query_list
init_scanner!
ql = media_query_list
expected("media query list") unless ql && @scanner.eos?
ql
end
# Parses an at-root query.
#
# @return [Array<String, Sass::Script;:Tree::Node>] The interpolated query.
# @raise [Sass::SyntaxError] if there's a syntax error in the query,
# or if it doesn't take up the entire input string.
def parse_at_root_query
init_scanner!
query = at_root_query
expected("@at-root query list") unless query && @scanner.eos?
query
end
# Parses a supports query condition.
#
# @return [Sass::Supports::Condition] The parsed condition
# @raise [Sass::SyntaxError] if there's a syntax error in the condition,
# or if it doesn't take up the entire input string.
def parse_supports_condition
init_scanner!
condition = supports_condition
expected("supports condition") unless condition && @scanner.eos?
condition
end
# Parses a custom property value.
#
# @return [Array<String, Sass::Script;:Tree::Node>] The interpolated value.
# @raise [Sass::SyntaxError] if there's a syntax error in the value,
# or if it doesn't take up the entire input string.
def parse_declaration_value
init_scanner!
value = declaration_value
expected('"}"') unless value && @scanner.eos?
value
end
private
include Sass::SCSS::RX
def source_position
Sass::Source::Position.new(@line, @offset)
end
def range(start_pos, end_pos = source_position)
Sass::Source::Range.new(start_pos, end_pos, @filename, @importer)
end
def init_scanner!
@scanner =
if @template.is_a?(StringScanner)
@template
else
Sass::Util::MultibyteStringScanner.new(@template.tr("\r", ""))
end
end
def stylesheet
node = node(Sass::Tree::RootNode.new(@scanner.string), source_position)
block_contents(node, :stylesheet) {s(node)}
end
def s(node)
while tok(S) || tok(CDC) || tok(CDO) || (c = tok(SINGLE_LINE_COMMENT)) || (c = tok(COMMENT))
next unless c
process_comment c, node
c = nil
end
true
end
def ss
nil while tok(S) || tok(SINGLE_LINE_COMMENT) || tok(COMMENT)
true
end
def ss_comments(node)
while tok(S) || (c = tok(SINGLE_LINE_COMMENT)) || (c = tok(COMMENT))
next unless c
process_comment c, node
c = nil
end
true
end
def whitespace
return unless tok(S) || tok(SINGLE_LINE_COMMENT) || tok(COMMENT)
ss
end
def process_comment(text, node)
silent = text =~ %r{\A//}
loud = !silent && text =~ %r{\A/[/*]!}
line = @line - text.count("\n")
comment_start = @scanner.pos - text.length
index_before_line = @scanner.string.rindex("\n", comment_start) || -1
offset = comment_start - index_before_line
if silent
value = [text.sub(%r{\A\s*//}, '/*').gsub(%r{^\s*//}, ' *') + ' */']
else
value = Sass::Engine.parse_interp(text, line, offset, :filename => @filename)
line_before_comment = @scanner.string[index_before_line + 1...comment_start]
value.unshift(line_before_comment.gsub(/[^\s]/, ' '))
end
type = if silent
:silent
elsif loud
:loud
else
:normal
end
start_pos = Sass::Source::Position.new(line, offset)
comment = node(Sass::Tree::CommentNode.new(value, type), start_pos)
node << comment
end
DIRECTIVES = Set[:mixin, :include, :function, :return, :debug, :warn, :for,
:each, :while, :if, :else, :extend, :import, :media, :charset, :content,
:_moz_document, :at_root, :error]
PREFIXED_DIRECTIVES = Set[:supports]
def directive
start_pos = source_position
return unless tok(/@/)
name = tok!(IDENT)
ss
if (dir = special_directive(name, start_pos))
return dir
elsif (dir = prefixed_directive(name, start_pos))
return dir
end
val = almost_any_value
val = val ? ["@#{name} "] + Sass::Util.strip_string_array(val) : ["@#{name}"]
directive_body(val, start_pos)
end
def directive_body(value, start_pos)
node = Sass::Tree::DirectiveNode.new(value)
if tok(/\{/)
node.has_children = true
block_contents(node, :directive)
tok!(/\}/)
end
node(node, start_pos)
end
def special_directive(name, start_pos)
sym = name.tr('-', '_').to_sym
DIRECTIVES.include?(sym) && send("#{sym}_directive", start_pos)
end
def prefixed_directive(name, start_pos)
sym = deprefix(name).tr('-', '_').to_sym
PREFIXED_DIRECTIVES.include?(sym) && send("#{sym}_directive", name, start_pos)
end
def mixin_directive(start_pos)
name = tok! IDENT
args, splat = sass_script(:parse_mixin_definition_arglist)
ss
block(node(Sass::Tree::MixinDefNode.new(name, args, splat), start_pos), :directive)
end
def include_directive(start_pos)
name = tok! IDENT
args, keywords, splat, kwarg_splat = sass_script(:parse_mixin_include_arglist)
ss
include_node = node(
Sass::Tree::MixinNode.new(name, args, keywords, splat, kwarg_splat), start_pos)
if tok?(/\{/)
include_node.has_children = true
block(include_node, :directive)
else
include_node
end
end
def content_directive(start_pos)
ss
node(Sass::Tree::ContentNode.new, start_pos)
end
def function_directive(start_pos)
name = tok! IDENT
args, splat = sass_script(:parse_function_definition_arglist)
ss
block(node(Sass::Tree::FunctionNode.new(name, args, splat), start_pos), :function)
end
def return_directive(start_pos)
node(Sass::Tree::ReturnNode.new(sass_script(:parse)), start_pos)
end
def debug_directive(start_pos)
node(Sass::Tree::DebugNode.new(sass_script(:parse)), start_pos)
end
def warn_directive(start_pos)
node(Sass::Tree::WarnNode.new(sass_script(:parse)), start_pos)
end
def for_directive(start_pos)
tok!(/\$/)
var = tok! IDENT
ss
tok!(/from/)
from = sass_script(:parse_until, Set["to", "through"])
ss
@expected = '"to" or "through"'
exclusive = (tok(/to/) || tok!(/through/)) == 'to'
to = sass_script(:parse)
ss
block(node(Sass::Tree::ForNode.new(var, from, to, exclusive), start_pos), :directive)
end
def each_directive(start_pos)
tok!(/\$/)
vars = [tok!(IDENT)]
ss
while tok(/,/)
ss
tok!(/\$/)
vars << tok!(IDENT)
ss
end
tok!(/in/)
list = sass_script(:parse)
ss
block(node(Sass::Tree::EachNode.new(vars, list), start_pos), :directive)
end
def while_directive(start_pos)
expr = sass_script(:parse)
ss
block(node(Sass::Tree::WhileNode.new(expr), start_pos), :directive)
end
def if_directive(start_pos)
expr = sass_script(:parse)
ss
node = block(node(Sass::Tree::IfNode.new(expr), start_pos), :directive)
pos = @scanner.pos
line = @line
ss
else_block(node) ||
begin
# Backtrack in case there are any comments we want to parse
@scanner.pos = pos
@line = line
node
end
end
def else_block(node)
start_pos = source_position
return unless tok(/@else/)
ss
else_node = block(
node(Sass::Tree::IfNode.new((sass_script(:parse) if tok(/if/))), start_pos),
:directive)
node.add_else(else_node)
pos = @scanner.pos
line = @line
ss
else_block(node) ||
begin
# Backtrack in case there are any comments we want to parse
@scanner.pos = pos
@line = line
node
end
end
def else_directive(start_pos)
err("Invalid CSS: @else must come after @if")
end
def extend_directive(start_pos)
selector_start_pos = source_position
@expected = "selector"
selector = Sass::Util.strip_string_array(expr!(:almost_any_value))
optional = tok(OPTIONAL)
ss
node(Sass::Tree::ExtendNode.new(selector, !!optional, range(selector_start_pos)), start_pos)
end
def import_directive(start_pos)
values = []
loop do
values << expr!(:import_arg)
break if use_css_import?
break unless tok(/,/)
ss
end
values
end
def import_arg
start_pos = source_position
return unless (str = string) || (uri = tok?(/url\(/i))
if uri
str = sass_script(:parse_string)
ss
supports = supports_clause
ss
media = media_query_list
ss
return node(Tree::CssImportNode.new(str, media.to_a, supports), start_pos)
end
ss
supports = supports_clause
ss
media = media_query_list
if str =~ %r{^(https?:)?//} || media || supports || use_css_import?
return node(
Sass::Tree::CssImportNode.new(
Sass::Script::Value::String.quote(str), media.to_a, supports), start_pos)
end
node(Sass::Tree::ImportNode.new(str.strip), start_pos)
end
def use_css_import?; false; end
def media_directive(start_pos)
block(node(Sass::Tree::MediaNode.new(expr!(:media_query_list).to_a), start_pos), :directive)
end
# http://www.w3.org/TR/css3-mediaqueries/#syntax
def media_query_list
query = media_query
return unless query
queries = [query]
ss
while tok(/,/)
ss; queries << expr!(:media_query)
end
ss
Sass::Media::QueryList.new(queries)
end
def media_query
if (ident1 = interp_ident)
ss
ident2 = interp_ident
ss
if ident2 && ident2.length == 1 && ident2[0].is_a?(String) && ident2[0].downcase == 'and'
query = Sass::Media::Query.new([], ident1, [])
else
if ident2
query = Sass::Media::Query.new(ident1, ident2, [])
else
query = Sass::Media::Query.new([], ident1, [])
end
return query unless tok(/and/i)
ss
end
end
if query
expr = expr!(:media_expr)
else
expr = media_expr
return unless expr
end
query ||= Sass::Media::Query.new([], [], [])
query.expressions << expr
ss
while tok(/and/i)
ss; query.expressions << expr!(:media_expr)
end
query
end
def query_expr
interp = interpolation
return interp if interp
return unless tok(/\(/)
res = ['(']
ss
res << sass_script(:parse)
if tok(/:/)
res << ': '
ss
res << sass_script(:parse)
end
res << tok!(/\)/)
ss
res
end
# Aliases allow us to use different descriptions if the same
# expression fails in different contexts.
alias_method :media_expr, :query_expr
alias_method :at_root_query, :query_expr
def charset_directive(start_pos)
name = expr!(:string)
ss
node(Sass::Tree::CharsetNode.new(name), start_pos)
end
# The document directive is specified in
# http://www.w3.org/TR/css3-conditional/, but Gecko allows the
# `url-prefix` and `domain` functions to omit quotation marks, contrary to
# the standard.
#
# We could parse all document directives according to Mozilla's syntax,
# but if someone's using e.g. @-webkit-document we don't want them to
# think WebKit works sans quotes.
def _moz_document_directive(start_pos)
res = ["@-moz-document "]
loop do
res << str {ss} << expr!(:moz_document_function)
if (c = tok(/,/))
res << c
else
break
end
end
directive_body(res.flatten, start_pos)
end
def moz_document_function
val = interp_uri || _interp_string(:url_prefix) ||
_interp_string(:domain) || function(false) || interpolation
return unless val
ss
val
end
def at_root_directive(start_pos)
if tok?(/\(/) && (expr = at_root_query)
return block(node(Sass::Tree::AtRootNode.new(expr), start_pos), :directive)
end
at_root_node = node(Sass::Tree::AtRootNode.new, start_pos)
rule_node = ruleset
return block(at_root_node, :stylesheet) unless rule_node
at_root_node << rule_node
at_root_node
end
def at_root_directive_list
return unless (first = tok(IDENT))
arr = [first]
ss
while (e = tok(IDENT))
arr << e
ss
end
arr
end
def error_directive(start_pos)
node(Sass::Tree::ErrorNode.new(sass_script(:parse)), start_pos)
end
# http://www.w3.org/TR/css3-conditional/
def supports_directive(name, start_pos)
condition = expr!(:supports_condition)
node = Sass::Tree::SupportsNode.new(name, condition)
tok!(/\{/)
node.has_children = true
block_contents(node, :directive)
tok!(/\}/)
node(node, start_pos)
end
def supports_clause
return unless tok(/supports\(/i)
ss
supports = import_supports_condition
ss
tok!(/\)/)
supports
end
def supports_condition
supports_negation || supports_operator || supports_interpolation
end
def import_supports_condition
supports_condition || supports_declaration
end
def supports_negation
return unless tok(/not/i)
ss
Sass::Supports::Negation.new(expr!(:supports_condition_in_parens))
end
def supports_operator
cond = supports_condition_in_parens
return unless cond
re = /and|or/i
while (op = tok(re))
re = /#{op}/i
ss
cond = Sass::Supports::Operator.new(
cond, expr!(:supports_condition_in_parens), op)
end
cond
end
def supports_declaration
name = sass_script(:parse)
tok!(/:/); ss
value = sass_script(:parse)
Sass::Supports::Declaration.new(name, value)
end
def supports_condition_in_parens
interp = supports_interpolation
return interp if interp
return unless tok(/\(/); ss
if (cond = supports_condition)
tok!(/\)/); ss
cond
else
decl = supports_declaration
tok!(/\)/); ss
decl
end
end
def supports_interpolation
interp = interpolation
return unless interp
ss
Sass::Supports::Interpolation.new(interp)
end
def variable
return unless tok(/\$/)
start_pos = source_position
name = tok!(IDENT)
ss; tok!(/:/); ss
expr = sass_script(:parse)
while tok(/!/)
flag_name = tok!(IDENT)
if flag_name == 'default'
guarded ||= true
elsif flag_name == 'global'
global ||= true
else
raise Sass::SyntaxError.new("Invalid flag \"!#{flag_name}\".", :line => @line)
end
ss
end
result = Sass::Tree::VariableNode.new(name, expr, guarded, global)
node(result, start_pos)
end
def operator
# Many of these operators (all except / and ,)
# are disallowed by the CSS spec,
# but they're included here for compatibility
# with some proprietary MS properties
str {ss if tok(%r{[/,:.=]})}
end
def ruleset
start_pos = source_position
return unless (rules = almost_any_value)
block(
node(
Sass::Tree::RuleNode.new(rules, range(start_pos)), start_pos), :ruleset)
end
def block(node, context)
node.has_children = true
tok!(/\{/)
block_contents(node, context)
tok!(/\}/)
node
end
# A block may contain declarations and/or rulesets
def block_contents(node, context)
block_given? ? yield : ss_comments(node)
node << (child = block_child(context))
while tok(/;/) || has_children?(child)
block_given? ? yield : ss_comments(node)
node << (child = block_child(context))
end
node
end
def block_child(context)
return variable || directive if context == :function
return variable || directive || ruleset if context == :stylesheet
variable || directive || declaration_or_ruleset
end
def has_children?(child_or_array)
return false unless child_or_array
return child_or_array.last.has_children if child_or_array.is_a?(Array)
child_or_array.has_children
end
# When parsing the contents of a ruleset, it can be difficult to tell
# declarations apart from nested rulesets. Since we don't thoroughly parse
# selectors until after resolving interpolation, we can share a bunch of
# the parsing of the two, but we need to disambiguate them first. We use
# the following criteria:
#
# * If the entity doesn't start with an identifier followed by a colon,
# it's a selector. There are some additional mostly-unimportant cases
# here to support various declaration hacks.
#
# * If the colon is followed by another colon, it's a selector.
#
# * Otherwise, if the colon is followed by anything other than
# interpolation or a character that's valid as the beginning of an
# identifier, it's a declaration.
#
# * If the colon is followed by interpolation or a valid identifier, try
# parsing it as a declaration value. If this fails, backtrack and parse
# it as a selector.
#
# * If the declaration value value valid but is followed by "{", backtrack
# and parse it as a selector anyway. This ensures that ".foo:bar {" is
# always parsed as a selector and never as a property with nested
# properties beneath it.
def declaration_or_ruleset
start_pos = source_position
declaration = try_declaration
if declaration.nil?
return unless (selector = almost_any_value)
elsif declaration.is_a?(Array)
selector = declaration
else
# Declaration should be a PropNode.
return declaration
end
if (additional_selector = almost_any_value)
selector << additional_selector
end
block(
node(
Sass::Tree::RuleNode.new(merge(selector), range(start_pos)), start_pos), :ruleset)
end
# Tries to parse a declaration, and returns the value parsed so far if it
# fails.
#
# This has three possible return types. It can return `nil`, indicating
# that parsing failed completely and the scanner hasn't moved forward at
# all. It can return an Array, indicating that parsing failed after
# consuming some text (possibly containing interpolation), which is
# returned. Or it can return a PropNode, indicating that parsing
# succeeded.
def try_declaration
# This allows the "*prop: val", ":prop: val", "#prop: val", and ".prop:
# val" hacks.
name_start_pos = source_position
if (s = tok(/[:\*\.]|\#(?!\{)/))
name = [s, str {ss}]
return name unless (ident = interp_ident)
name << ident
else
return unless (name = interp_ident)
name = Array(name)
end
if (comment = tok(COMMENT))
name << comment
end
name_end_pos = source_position
mid = [str {ss}]
return name + mid unless tok(/:/)
mid << ':'
# If this is a CSS variable, parse it as a property no matter what.
if name.first.is_a?(String) && name.first.start_with?("--")
return css_variable_declaration(name, name_start_pos, name_end_pos)
end
return name + mid + [':'] if tok(/:/)
mid << str {ss}
post_colon_whitespace = !mid.last.empty?
could_be_selector = !post_colon_whitespace && (tok?(IDENT_START) || tok?(INTERP_START))
value_start_pos = source_position
value = nil
error = catch_error do
value = value!
if tok?(/\{/)
# Properties that are ambiguous with selectors can't have additional
# properties nested beneath them.
tok!(/;/) if could_be_selector
elsif !tok?(/[;{}]/)
# We want an exception if there's no valid end-of-property character
# exists, but we don't want to consume it if it does.
tok!(/[;{}]/)
end
end
if error
rethrow error unless could_be_selector
# If the value would be followed by a semicolon, it's definitely
# supposed to be a property, not a selector.
additional_selector = almost_any_value
rethrow error if tok?(/;/)
return name + mid + (additional_selector || [])
end
value_end_pos = source_position
ss
require_block = tok?(/\{/)
node = node(Sass::Tree::PropNode.new(name.flatten.compact, [value], :new),
name_start_pos, value_end_pos)
node.name_source_range = range(name_start_pos, name_end_pos)
node.value_source_range = range(value_start_pos, value_end_pos)
return node unless require_block
nested_properties! node
end
def css_variable_declaration(name, name_start_pos, name_end_pos)
value_start_pos = source_position
value = declaration_value
value_end_pos = source_position
node = node(Sass::Tree::PropNode.new(name.flatten.compact, value, :new),
name_start_pos, value_end_pos)
node.name_source_range = range(name_start_pos, name_end_pos)
node.value_source_range = range(value_start_pos, value_end_pos)
node
end
# This production consumes values that could be a selector, an expression,
# or a combination of both. It respects strings and comments and supports
# interpolation. It will consume up to "{", "}", ";", or "!".
#
# Values consumed by this production will usually be parsed more
# thoroughly once interpolation has been resolved.
def almost_any_value
return unless (tok = almost_any_value_token)
sel = [tok]
while (tok = almost_any_value_token)
sel << tok
end
merge(sel)
end
def almost_any_value_token
tok(%r{
(
\\.
|
(?!url\()
[^"'/\#!;\{\}] # "
|
# interp_uri will handle most url() calls, but not ones that take strings
url\(#{W}(?=")
|
/(?![/*])
|
\#(?!\{)
|
!(?![a-z]) # TODO: never consume "!" when issue 1126 is fixed.
)+
}xi) || tok(COMMENT) || tok(SINGLE_LINE_COMMENT) || interp_string || interp_uri ||
interpolation(:warn_for_color)
end
def declaration_value(top_level: true)
return unless (tok = declaration_value_token(top_level))
value = [tok]
while (tok = declaration_value_token(top_level))
value << tok
end
merge(value)
end
def declaration_value_token(top_level)
# This comes, more or less, from the [token consumption algorithm][].
# However, since we don't have to worry about the token semantics, we
# just consume everything until we come across a token with special
# semantics.
#
# [token consumption algorithm]: https://drafts.csswg.org/css-syntax-3/#consume-token.
result = tok(%r{
(
(?!
url\(
)
[^()\[\]{}"'#/ \t\r\n\f#{top_level ? ";" : ""}]
|
\#(?!\{)
|
/(?!\*)
)+
}xi) || interp_string || interp_uri || interpolation || tok(COMMENT)
return result if result
# Fold together multiple characters of whitespace that don't include
# newlines. The value only cares about the tokenization, so this is safe
# as long as we don't delete whitespace entirely. It's important that we
# fold here rather than post-processing, since we aren't allowed to fold
# whitespace within strings and we lose that context later on.
if (ws = tok(S))
return ws.include?("\n") ? ws.gsub(/\A[^\n]*/, '') : ' '
end
if tok(/\(/)
value = declaration_value(top_level: false)
tok!(/\)/)
['(', *value, ')']
elsif tok(/\[/)
value = declaration_value(top_level: false)
tok!(/\]/)
['[', *value, ']']
elsif tok(/\{/)
value = declaration_value(top_level: false)
tok!(/\}/)
['{', *value, '}']
end
end
def declaration
# This allows the "*prop: val", ":prop: val", "#prop: val", and ".prop:
# val" hacks.
name_start_pos = source_position
if (s = tok(/[:\*\.]|\#(?!\{)/))
name = [s, str {ss}, *expr!(:interp_ident)]
else
return unless (name = interp_ident)
name = Array(name)
end
if (comment = tok(COMMENT))
name << comment
end
name_end_pos = source_position
ss
tok!(/:/)
ss
value_start_pos = source_position
value = value!
value_end_pos = source_position
ss
require_block = tok?(/\{/)
node = node(Sass::Tree::PropNode.new(name.flatten.compact, [value], :new),
name_start_pos, value_end_pos)
node.name_source_range = range(name_start_pos, name_end_pos)
node.value_source_range = range(value_start_pos, value_end_pos)
return node unless require_block
nested_properties! node
end
def value!
if tok?(/\{/)
str = Sass::Script::Tree::Literal.new(Sass::Script::Value::String.new(""))
str.line = source_position.line
str.source_range = range(source_position)
return str
end
start_pos = source_position
# This is a bit of a dirty trick:
# if the value is completely static,
# we don't parse it at all, and instead return a plain old string
# containing the value.
# This results in a dramatic speed increase.
if (val = tok(STATIC_VALUE))
str = Sass::Script::Tree::Literal.new(Sass::Script::Value::String.new(val.strip))
str.line = start_pos.line
str.source_range = range(start_pos)
return str
end
sass_script(:parse)
end
def nested_properties!(node)
@expected = 'expression (e.g. 1px, bold) or "{"'
block(node, :property)
end
def expr(allow_var = true)
t = term(allow_var)
return unless t
res = [t, str {ss}]
while (o = operator) && (t = term(allow_var))
res << o << t << str {ss}
end
res.flatten
end
def term(allow_var)
e = tok(NUMBER) ||
interp_uri ||
function(allow_var) ||
interp_string ||
tok(UNICODERANGE) ||
interp_ident ||
tok(HEXCOLOR) ||
(allow_var && var_expr)
return e if e
op = tok(/[+-]/)
return unless op
@expected = "number or function"
[op,
tok(NUMBER) || function(allow_var) || (allow_var && var_expr) || expr!(:interpolation)]
end
def function(allow_var)
name = tok(FUNCTION)
return unless name
if name == "expression(" || name == "calc("
str, _ = Sass::Shared.balance(@scanner, ?(, ?), 1)
[name, str]
else
[name, str {ss}, expr(allow_var), tok!(/\)/)]
end
end
def var_expr
return unless tok(/\$/)
line = @line
var = Sass::Script::Tree::Variable.new(tok!(IDENT))
var.line = line
var
end
def interpolation(warn_for_color = false)
return unless tok(INTERP_START)
sass_script(:parse_interpolated, warn_for_color)
end
def string
return unless tok(STRING)
Sass::Script::Value::String.value(@scanner[1] || @scanner[2])
end
def interp_string
_interp_string(:double) || _interp_string(:single)
end
def interp_uri
_interp_string(:uri)
end
def _interp_string(type)
start = tok(Sass::Script::Lexer::STRING_REGULAR_EXPRESSIONS[type][false])
return unless start
res = [start]
mid_re = Sass::Script::Lexer::STRING_REGULAR_EXPRESSIONS[type][true]
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | true |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/scss/rx.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/scss/rx.rb | # -*- coding: utf-8 -*-
module Sass
module SCSS
# A module containing regular expressions used
# for lexing tokens in an SCSS document.
# Most of these are taken from [the CSS3 spec](http://www.w3.org/TR/css3-syntax/#lexical),
# although some have been modified for various reasons.
module RX
# Takes a string and returns a CSS identifier
# that will have the value of the given string.
#
# @param str [String] The string to escape
# @return [String] The escaped string
def self.escape_ident(str)
return "" if str.empty?
return "\\#{str}" if str == '-' || str == '_'
out = ""
value = str.dup
out << value.slice!(0...1) if value =~ /^[-_]/
if value[0...1] =~ NMSTART
out << value.slice!(0...1)
else
out << escape_char(value.slice!(0...1))
end
out << value.gsub(/[^a-zA-Z0-9_-]/) {|c| escape_char c}
out
end
# Escapes a single character for a CSS identifier.
#
# @param c [String] The character to escape. Should have length 1
# @return [String] The escaped character
# @private
def self.escape_char(c)
return "\\%06x" % c.ord unless c =~ %r{[ -/:-~]}
"\\#{c}"
end
# Creates a Regexp from a plain text string,
# escaping all significant characters.
#
# @param str [String] The text of the regexp
# @param flags [Integer] Flags for the created regular expression
# @return [Regexp]
# @private
def self.quote(str, flags = 0)
Regexp.new(Regexp.quote(str), flags)
end
H = /[0-9a-fA-F]/
NL = /\n|\r\n|\r|\f/
UNICODE = /\\#{H}{1,6}[ \t\r\n\f]?/
s = '\u{80}-\u{D7FF}\u{E000}-\u{FFFD}\u{10000}-\u{10FFFF}'
NONASCII = /[#{s}]/
ESCAPE = /#{UNICODE}|\\[ -~#{s}]/
NMSTART = /[_a-zA-Z]|#{NONASCII}|#{ESCAPE}/
NMCHAR = /[a-zA-Z0-9_-]|#{NONASCII}|#{ESCAPE}/
STRING1 = /\"((?:[^\n\r\f\\"]|\\#{NL}|#{ESCAPE})*)\"/
STRING2 = /\'((?:[^\n\r\f\\']|\\#{NL}|#{ESCAPE})*)\'/
IDENT = /-*#{NMSTART}#{NMCHAR}*/
NAME = /#{NMCHAR}+/
STRING = /#{STRING1}|#{STRING2}/
URLCHAR = /[#%&*-~]|#{NONASCII}|#{ESCAPE}/
URL = /(#{URLCHAR}*)/
W = /[ \t\r\n\f]*/
VARIABLE = /(\$)(#{Sass::SCSS::RX::IDENT})/
# This is more liberal than the spec's definition,
# but that definition didn't work well with the greediness rules
RANGE = /(?:#{H}|\?){1,6}/
##
S = /[ \t\r\n\f]+/
COMMENT = %r{/\*([^*]|\*+[^/*])*\**\*/}
SINGLE_LINE_COMMENT = %r{//.*(\n[ \t]*//.*)*}
CDO = quote("<!--")
CDC = quote("-->")
INCLUDES = quote("~=")
DASHMATCH = quote("|=")
PREFIXMATCH = quote("^=")
SUFFIXMATCH = quote("$=")
SUBSTRINGMATCH = quote("*=")
HASH = /##{NAME}/
IMPORTANT = /!#{W}important/i
# A unit is like an IDENT, but disallows a hyphen followed by a digit.
# This allows "1px-2px" to be interpreted as subtraction rather than "1"
# with the unit "px-2px". It also allows "%".
UNIT = /-?#{NMSTART}(?:[a-zA-Z0-9_]|#{NONASCII}|#{ESCAPE}|-(?!\.?\d))*|%/
UNITLESS_NUMBER = /(?:[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?\d+)?/
NUMBER = /#{UNITLESS_NUMBER}(?:#{UNIT})?/
PERCENTAGE = /#{UNITLESS_NUMBER}%/
URI = /url\(#{W}(?:#{STRING}|#{URL})#{W}\)/i
FUNCTION = /#{IDENT}\(/
UNICODERANGE = /u\+(?:#{H}{1,6}-#{H}{1,6}|#{RANGE})/i
# Defined in http://www.w3.org/TR/css3-selectors/#lex
PLUS = /#{W}\+/
GREATER = /#{W}>/
TILDE = /#{W}~/
NOT = quote(":not(", Regexp::IGNORECASE)
# Defined in https://developer.mozilla.org/en/CSS/@-moz-document as a
# non-standard version of http://www.w3.org/TR/css3-conditional/
URL_PREFIX = /url-prefix\(#{W}(?:#{STRING}|#{URL})#{W}\)/i
DOMAIN = /domain\(#{W}(?:#{STRING}|#{URL})#{W}\)/i
# Custom
HEXCOLOR = /\#[0-9a-fA-F]+/
INTERP_START = /#\{/
ANY = /:(-[-\w]+-)?any\(/i
OPTIONAL = /!#{W}optional/i
IDENT_START = /-|#{NMSTART}/
IDENT_HYPHEN_INTERP = /-+(?=#\{)/
STRING1_NOINTERP = /\"((?:[^\n\r\f\\"#]|#(?!\{)|#{ESCAPE})*)\"/
STRING2_NOINTERP = /\'((?:[^\n\r\f\\'#]|#(?!\{)|#{ESCAPE})*)\'/
STRING_NOINTERP = /#{STRING1_NOINTERP}|#{STRING2_NOINTERP}/
STATIC_COMPONENT = /#{IDENT}|#{STRING_NOINTERP}|#{HEXCOLOR}|[+-]?#{NUMBER}|\!important/i
STATIC_VALUE = %r(#{STATIC_COMPONENT}(\s*[\s,\/]\s*#{STATIC_COMPONENT})*(?=[;}]))i
STATIC_SELECTOR = /(#{NMCHAR}|[ \t]|[,>+*]|[:#.]#{NMSTART}){1,50}([{])/i
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/scss/static_parser.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/scss/static_parser.rb | require 'sass/script/css_parser'
module Sass
module SCSS
# A parser for a static SCSS tree.
# Parses with SCSS extensions, like nested rules and parent selectors,
# but without dynamic SassScript.
# This is useful for e.g. \{#parse\_selector parsing selectors}
# after resolving the interpolation.
class StaticParser < Parser
# Parses the text as a selector.
#
# @param filename [String, nil] The file in which the selector appears,
# or nil if there is no such file.
# Used for error reporting.
# @return [Selector::CommaSequence] The parsed selector
# @raise [Sass::SyntaxError] if there's a syntax error in the selector
def parse_selector
init_scanner!
seq = expr!(:selector_comma_sequence)
expected("selector") unless @scanner.eos?
seq.line = @line
seq.filename = @filename
seq
end
# Parses a static at-root query.
#
# @return [(Symbol, Array<String>)] The type of the query
# (`:with` or `:without`) and the values that are being filtered.
# @raise [Sass::SyntaxError] if there's a syntax error in the query,
# or if it doesn't take up the entire input string.
def parse_static_at_root_query
init_scanner!
tok!(/\(/); ss
type = tok!(/\b(without|with)\b/).to_sym; ss
tok!(/:/); ss
directives = expr!(:at_root_directive_list); ss
tok!(/\)/)
expected("@at-root query list") unless @scanner.eos?
return type, directives
end
def parse_keyframes_selector
init_scanner!
sel = expr!(:keyframes_selector)
expected("keyframes selector") unless @scanner.eos?
sel
end
# @see Parser#initialize
# @param allow_parent_ref [Boolean] Whether to allow the
# parent-reference selector, `&`, when parsing the document.
def initialize(str, filename, importer, line = 1, offset = 1, allow_parent_ref = true)
super(str, filename, importer, line, offset)
@allow_parent_ref = allow_parent_ref
end
private
def moz_document_function
val = tok(URI) || tok(URL_PREFIX) || tok(DOMAIN) || function(false)
return unless val
ss
[val]
end
def variable; nil; end
def script_value; nil; end
def interpolation(warn_for_color = false); nil; end
def var_expr; nil; end
def interp_string; (s = tok(STRING)) && [s]; end
def interp_uri; (s = tok(URI)) && [s]; end
def interp_ident(ident = IDENT); (s = tok(ident)) && [s]; end
def use_css_import?; true; end
def special_directive(name, start_pos)
return unless %w(media import charset -moz-document).include?(name)
super
end
def selector_comma_sequence
sel = selector
return unless sel
selectors = [sel]
ws = ''
while tok(/,/)
ws << str {ss}
next unless (sel = selector)
selectors << sel
if ws.include?("\n")
selectors[-1] = Selector::Sequence.new(["\n"] + selectors.last.members)
end
ws = ''
end
Selector::CommaSequence.new(selectors)
end
def selector_string
sel = selector
return unless sel
sel.to_s
end
def selector
start_pos = source_position
# The combinator here allows the "> E" hack
val = combinator || simple_selector_sequence
return unless val
nl = str {ss}.include?("\n")
res = []
res << val
res << "\n" if nl
while (val = combinator || simple_selector_sequence)
res << val
res << "\n" if str {ss}.include?("\n")
end
seq = Selector::Sequence.new(res.compact)
if seq.members.any? {|sseq| sseq.is_a?(Selector::SimpleSequence) && sseq.subject?}
location = " of #{@filename}" if @filename
Sass::Util.sass_warn <<MESSAGE
DEPRECATION WARNING on line #{start_pos.line}, column #{start_pos.offset}#{location}:
The subject selector operator "!" is deprecated and will be removed in a future release.
This operator has been replaced by ":has()" in the CSS spec.
For example: #{seq.subjectless}
MESSAGE
end
seq
end
def combinator
tok(PLUS) || tok(GREATER) || tok(TILDE) || reference_combinator
end
def reference_combinator
return unless tok(%r{/})
res = '/'
ns, name = expr!(:qualified_name)
res << ns << '|' if ns
res << name << tok!(%r{/})
location = " of #{@filename}" if @filename
Sass::Util.sass_warn <<MESSAGE
DEPRECATION WARNING on line #{@line}, column #{@offset}#{location}:
The reference combinator #{res} is deprecated and will be removed in a future release.
MESSAGE
res
end
def simple_selector_sequence
start_pos = source_position
e = element_name || id_selector || class_selector || placeholder_selector || attrib ||
pseudo || parent_selector
return unless e
res = [e]
# The tok(/\*/) allows the "E*" hack
while (v = id_selector || class_selector || placeholder_selector ||
attrib || pseudo || (tok(/\*/) && Selector::Universal.new(nil)))
res << v
end
pos = @scanner.pos
line = @line
if (sel = str? {simple_selector_sequence})
@scanner.pos = pos
@line = line
begin
# If we see "*E", don't force a throw because this could be the
# "*prop: val" hack.
expected('"{"') if res.length == 1 && res[0].is_a?(Selector::Universal)
throw_error {expected('"{"')}
rescue Sass::SyntaxError => e
e.message << "\n\n\"#{sel}\" may only be used at the beginning of a compound selector."
raise e
end
end
Selector::SimpleSequence.new(res, tok(/!/), range(start_pos))
end
def parent_selector
return unless @allow_parent_ref && tok(/&/)
Selector::Parent.new(tok(NAME))
end
def class_selector
return unless tok(/\./)
@expected = "class name"
Selector::Class.new(tok!(IDENT))
end
def id_selector
return unless tok(/#(?!\{)/)
@expected = "id name"
Selector::Id.new(tok!(NAME))
end
def placeholder_selector
return unless tok(/%/)
@expected = "placeholder name"
Selector::Placeholder.new(tok!(IDENT))
end
def element_name
ns, name = Sass::Util.destructure(qualified_name(:allow_star_name))
return unless ns || name
if name == '*'
Selector::Universal.new(ns)
else
Selector::Element.new(name, ns)
end
end
def qualified_name(allow_star_name = false)
name = tok(IDENT) || tok(/\*/) || (tok?(/\|/) && "")
return unless name
return nil, name unless tok(/\|/)
return name, tok!(IDENT) unless allow_star_name
@expected = "identifier or *"
return name, tok(IDENT) || tok!(/\*/)
end
def attrib
return unless tok(/\[/)
ss
ns, name = attrib_name!
ss
op = tok(/=/) ||
tok(INCLUDES) ||
tok(DASHMATCH) ||
tok(PREFIXMATCH) ||
tok(SUFFIXMATCH) ||
tok(SUBSTRINGMATCH)
if op
@expected = "identifier or string"
ss
val = tok(IDENT) || tok!(STRING)
ss
end
flags = tok(IDENT) || tok(STRING)
tok!(/\]/)
Selector::Attribute.new(name, ns, op, val, flags)
end
def attrib_name!
if (name_or_ns = tok(IDENT))
# E, E|E
if tok(/\|(?!=)/)
ns = name_or_ns
name = tok(IDENT)
else
name = name_or_ns
end
else
# *|E or |E
ns = tok(/\*/) || ""
tok!(/\|/)
name = tok!(IDENT)
end
return ns, name
end
SELECTOR_PSEUDO_CLASSES = %w(not matches current any has host host-context).to_set
PREFIXED_SELECTOR_PSEUDO_CLASSES = %w(nth-child nth-last-child).to_set
SELECTOR_PSEUDO_ELEMENTS = %w(slotted).to_set
def pseudo
s = tok(/::?/)
return unless s
@expected = "pseudoclass or pseudoelement"
name = tok!(IDENT)
if tok(/\(/)
ss
deprefixed = deprefix(name)
if s == ':' && SELECTOR_PSEUDO_CLASSES.include?(deprefixed)
sel = selector_comma_sequence
elsif s == ':' && PREFIXED_SELECTOR_PSEUDO_CLASSES.include?(deprefixed)
arg, sel = prefixed_selector_pseudo
elsif s == '::' && SELECTOR_PSEUDO_ELEMENTS.include?(deprefixed)
sel = selector_comma_sequence
else
arg = expr!(:declaration_value).join
end
tok!(/\)/)
end
Selector::Pseudo.new(s == ':' ? :class : :element, name, arg, sel)
end
def prefixed_selector_pseudo
prefix = str do
expr = str {expr!(:a_n_plus_b)}
ss
return expr, nil unless tok(/of/)
ss
end
return prefix, expr!(:selector_comma_sequence)
end
def a_n_plus_b
if (parity = tok(/even|odd/i))
return parity
end
if tok(/[+-]?[0-9]+/)
ss
return true unless tok(/n/)
else
return unless tok(/[+-]?n/i)
end
ss
return true unless tok(/[+-]/)
ss
@expected = "number"
tok!(/[0-9]+/)
true
end
def keyframes_selector
ss
str do
return unless keyframes_selector_component
ss
while tok(/,/)
ss
expr!(:keyframes_selector_component)
ss
end
end
end
def keyframes_selector_component
tok(IDENT) || tok(PERCENTAGE)
end
@sass_script_parser = Class.new(Sass::Script::CssParser)
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/exec/sass_convert.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/exec/sass_convert.rb | require 'optparse'
require 'fileutils'
module Sass::Exec
# The `sass-convert` executable.
class SassConvert < Base
# @param args [Array<String>] The command-line arguments
def initialize(args)
super
require 'sass'
@options[:for_tree] = {}
@options[:for_engine] = {:cache => false, :read_cache => true}
end
# Tells optparse how to parse the arguments.
#
# @param opts [OptionParser]
def set_opts(opts)
opts.banner = <<END
Usage: sass-convert [options] [INPUT] [OUTPUT]
Description:
Converts between CSS, indented syntax, and SCSS files. For example,
this can convert from the indented syntax to SCSS, or from CSS to
SCSS (adding appropriate nesting).
END
common_options(opts)
style(opts)
input_and_output(opts)
miscellaneous(opts)
end
# Processes the options set by the command-line arguments,
# and runs the CSS compiler appropriately.
def process_result
require 'sass'
if @options[:recursive]
process_directory
return
end
super
input = @options[:input]
if File.directory?(input)
raise "Error: '#{input.path}' is a directory (did you mean to use --recursive?)"
end
output = @options[:output]
output = input if @options[:in_place]
process_file(input, output)
end
private
def common_options(opts)
opts.separator ''
opts.separator 'Common Options:'
opts.on('-F', '--from FORMAT',
'The format to convert from. Can be css, scss, sass.',
'By default, this is inferred from the input filename.',
'If there is none, defaults to css.') do |name|
@options[:from] = name.downcase.to_sym
raise "sass-convert no longer supports LessCSS." if @options[:from] == :less
unless [:css, :scss, :sass].include?(@options[:from])
raise "Unknown format for sass-convert --from: #{name}"
end
end
opts.on('-T', '--to FORMAT',
'The format to convert to. Can be scss or sass.',
'By default, this is inferred from the output filename.',
'If there is none, defaults to sass.') do |name|
@options[:to] = name.downcase.to_sym
unless [:scss, :sass].include?(@options[:to])
raise "Unknown format for sass-convert --to: #{name}"
end
end
opts.on('-i', '--in-place',
'Convert a file to its own syntax.',
'This can be used to update some deprecated syntax.') do
@options[:in_place] = true
end
opts.on('-R', '--recursive',
'Convert all the files in a directory. Requires --from and --to.') do
@options[:recursive] = true
end
opts.on("-?", "-h", "--help", "Show this help message.") do
puts opts
exit
end
opts.on("-v", "--version", "Print the Sass version.") do
puts("Sass #{Sass.version[:string]}")
exit
end
end
def style(opts)
opts.separator ''
opts.separator 'Style:'
opts.on('--dasherize', 'Convert underscores to dashes.') do
@options[:for_tree][:dasherize] = true
end
opts.on(
'--indent NUM',
'How many spaces to use for each level of indentation. Defaults to 2.',
'"t" means use hard tabs.'
) do |indent|
if indent == 't'
@options[:for_tree][:indent] = "\t"
else
@options[:for_tree][:indent] = " " * indent.to_i
end
end
opts.on('--old', 'Output the old-style ":prop val" property syntax.',
'Only meaningful when generating Sass.') do
@options[:for_tree][:old] = true
end
end
def input_and_output(opts)
opts.separator ''
opts.separator 'Input and Output:'
opts.on('-s', '--stdin', :NONE,
'Read input from standard input instead of an input file.',
'This is the default if no input file is specified. Requires --from.') do
@options[:input] = $stdin
end
encoding_option(opts)
opts.on('--unix-newlines', 'Use Unix-style newlines in written files.',
('Always true on Unix.' unless Sass::Util.windows?)) do
@options[:unix_newlines] = true if Sass::Util.windows?
end
end
def miscellaneous(opts)
opts.separator ''
opts.separator 'Miscellaneous:'
opts.on('--cache-location PATH',
'The path to save parsed Sass files. Defaults to .sass-cache.') do |loc|
@options[:for_engine][:cache_location] = loc
end
opts.on('-C', '--no-cache', "Don't cache to sassc files.") do
@options[:for_engine][:read_cache] = false
end
opts.on('-q', '--quiet', 'Silence warnings and status messages during conversion.') do |bool|
@options[:for_engine][:quiet] = bool
end
opts.on('--trace', :NONE, 'Show a full Ruby stack trace on error') do
@options[:trace] = true
end
end
def process_directory
@options[:input] = @args.shift
unless @options[:input]
raise "Error: directory required when using --recursive."
end
output = @options[:output] = @args.shift
raise "Error: --from required when using --recursive." unless @options[:from]
raise "Error: --to required when using --recursive." unless @options[:to]
unless File.directory?(@options[:input])
raise "Error: '#{@options[:input]}' is not a directory"
end
if @options[:output] && File.exist?(@options[:output]) &&
!File.directory?(@options[:output])
raise "Error: '#{@options[:output]}' is not a directory"
end
@options[:output] ||= @options[:input]
if @options[:to] == @options[:from] && !@options[:in_place]
fmt = @options[:from]
raise "Error: converting from #{fmt} to #{fmt} without --in-place"
end
ext = @options[:from]
Sass::Util.glob("#{@options[:input]}/**/*.#{ext}") do |f|
output =
if @options[:in_place]
f
elsif @options[:output]
output_name = f.gsub(/\.(c|sa|sc|le)ss$/, ".#{@options[:to]}")
output_name[0...@options[:input].size] = @options[:output]
output_name
else
f.gsub(/\.(c|sa|sc|le)ss$/, ".#{@options[:to]}")
end
unless File.directory?(File.dirname(output))
puts_action :directory, :green, File.dirname(output)
FileUtils.mkdir_p(File.dirname(output))
end
puts_action :convert, :green, f
if File.exist?(output)
puts_action :overwrite, :yellow, output
else
puts_action :create, :green, output
end
process_file(f, output)
end
end
def process_file(input, output)
input_path, output_path = path_for(input), path_for(output)
if input_path
@options[:from] ||=
case input_path
when /\.scss$/; :scss
when /\.sass$/; :sass
when /\.less$/; raise "sass-convert no longer supports LessCSS."
when /\.css$/; :css
end
elsif @options[:in_place]
raise "Error: the --in-place option requires a filename."
end
if output_path
@options[:to] ||=
case output_path
when /\.scss$/; :scss
when /\.sass$/; :sass
end
end
@options[:from] ||= :css
@options[:to] ||= :sass
@options[:for_engine][:syntax] = @options[:from]
out =
Sass::Util.silence_sass_warnings do
if @options[:from] == :css
require 'sass/css'
Sass::CSS.new(read(input), @options[:for_tree]).render(@options[:to])
else
if input_path
Sass::Engine.for_file(input_path, @options[:for_engine])
else
Sass::Engine.new(read(input), @options[:for_engine])
end.to_tree.send("to_#{@options[:to]}", @options[:for_tree])
end
end
output = input_path if @options[:in_place]
write_output(out, output)
rescue Sass::SyntaxError => e
raise e if @options[:trace]
file = " of #{e.sass_filename}" if e.sass_filename
raise "Error on line #{e.sass_line}#{file}: #{e.message}\n Use --trace for backtrace"
rescue LoadError => err
handle_load_error(err)
end
def path_for(file)
return file.path if file.is_a?(File)
return file if file.is_a?(String)
end
def read(file)
if file.respond_to?(:read)
file.read
else
open(file, 'rb') {|f| f.read}
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/exec/sass_scss.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/exec/sass_scss.rb | module Sass::Exec
# The `sass` and `scss` executables.
class SassScss < Base
attr_reader :default_syntax
# @param args [Array<String>] The command-line arguments
def initialize(args, default_syntax)
super(args)
@options[:sourcemap] = :auto
@options[:for_engine] = {
:load_paths => default_sass_path
}
@default_syntax = default_syntax
end
protected
# Tells optparse how to parse the arguments.
#
# @param opts [OptionParser]
def set_opts(opts)
opts.banner = <<END
Usage: #{default_syntax} [options] [INPUT] [OUTPUT]
Description:
Converts SCSS or Sass files to CSS.
END
common_options(opts)
watching_and_updating(opts)
input_and_output(opts)
miscellaneous(opts)
end
# Processes the options set by the command-line arguments,
# and runs the Sass compiler appropriately.
def process_result
require 'sass'
if !@options[:update] && !@options[:watch] &&
@args.first && colon_path?(@args.first)
if @args.size == 1
@args = split_colon_path(@args.first)
else
@fake_update = true
@options[:update] = true
end
end
load_compass if @options[:compass]
return interactive if @options[:interactive]
return watch_or_update if @options[:watch] || @options[:update]
super
if @options[:sourcemap] != :none && @options[:output_filename]
@options[:sourcemap_filename] = Sass::Util.sourcemap_name(@options[:output_filename])
end
@options[:for_engine][:filename] = @options[:filename]
@options[:for_engine][:css_filename] = @options[:output] if @options[:output].is_a?(String)
@options[:for_engine][:sourcemap_filename] = @options[:sourcemap_filename]
@options[:for_engine][:sourcemap] = @options[:sourcemap]
run
end
private
def common_options(opts)
opts.separator ''
opts.separator 'Common Options:'
opts.on('-I', '--load-path PATH', 'Specify a Sass import path.') do |path|
(@options[:for_engine][:load_paths] ||= []) << path
end
opts.on('-r', '--require LIB', 'Require a Ruby library before running Sass.') do |lib|
require lib
end
opts.on('--compass', 'Make Compass imports available and load project configuration.') do
@options[:compass] = true
end
opts.on('-t', '--style NAME', 'Output style. Can be nested (default), compact, ' \
'compressed, or expanded.') do |name|
@options[:for_engine][:style] = name.to_sym
end
opts.on("-?", "-h", "--help", "Show this help message.") do
puts opts
exit
end
opts.on("-v", "--version", "Print the Sass version.") do
puts("Ruby Sass #{Sass.version[:string]}")
exit
end
end
def watching_and_updating(opts)
opts.separator ''
opts.separator 'Watching and Updating:'
opts.on('--watch', 'Watch files or directories for changes.',
'The location of the generated CSS can be set using a colon:',
" #{@default_syntax} --watch input.#{@default_syntax}:output.css",
" #{@default_syntax} --watch input-dir:output-dir") do
@options[:watch] = true
end
# Polling is used by default on Windows.
unless Sass::Util.windows?
opts.on('--poll', 'Check for file changes manually, rather than relying on the OS.',
'Only meaningful for --watch.') do
@options[:poll] = true
end
end
opts.on('--update', 'Compile files or directories to CSS.',
'Locations are set like --watch.') do
@options[:update] = true
end
opts.on('-f', '--force', 'Recompile every Sass file, even if the CSS file is newer.',
'Only meaningful for --update.') do
@options[:force] = true
end
opts.on('--stop-on-error', 'If a file fails to compile, exit immediately.',
'Only meaningful for --watch and --update.') do
@options[:stop_on_error] = true
end
end
def input_and_output(opts)
opts.separator ''
opts.separator 'Input and Output:'
if @default_syntax == :sass
opts.on('--scss',
'Use the CSS-superset SCSS syntax.') do
@options[:for_engine][:syntax] = :scss
end
else
opts.on('--sass',
'Use the indented Sass syntax.') do
@options[:for_engine][:syntax] = :sass
end
end
# This is optional for backwards-compatibility with Sass 3.3, which didn't
# enable sourcemaps by default and instead used "--sourcemap" to do so.
opts.on(:OPTIONAL, '--sourcemap=TYPE',
'How to link generated output to the source files.',
' auto (default): relative paths where possible, file URIs elsewhere',
' file: always absolute file URIs',
' inline: include the source text in the sourcemap',
' none: no sourcemaps') do |type|
if type && !%w(auto file inline none).include?(type)
$stderr.puts "Unknown sourcemap type #{type}.\n\n"
$stderr.puts opts
exit
elsif type.nil?
Sass::Util.sass_warn <<MESSAGE.rstrip
DEPRECATION WARNING: Passing --sourcemap without a value is deprecated.
Sourcemaps are now generated by default, so this flag has no effect.
MESSAGE
end
@options[:sourcemap] = (type || :auto).to_sym
end
opts.on('-s', '--stdin', :NONE,
'Read input from standard input instead of an input file.',
'This is the default if no input file is specified.') do
@options[:input] = $stdin
end
encoding_option(opts)
opts.on('--unix-newlines', 'Use Unix-style newlines in written files.',
('Always true on Unix.' unless Sass::Util.windows?)) do
@options[:unix_newlines] = true if Sass::Util.windows?
end
opts.on('-g', '--debug-info',
'Emit output that can be used by the FireSass Firebug plugin.') do
@options[:for_engine][:debug_info] = true
end
opts.on('-l', '--line-numbers', '--line-comments',
'Emit comments in the generated CSS indicating the corresponding source line.') do
@options[:for_engine][:line_numbers] = true
end
end
def miscellaneous(opts)
opts.separator ''
opts.separator 'Miscellaneous:'
opts.on('-i', '--interactive',
'Run an interactive SassScript shell.') do
@options[:interactive] = true
end
opts.on('-c', '--check', "Just check syntax, don't evaluate.") do
require 'stringio'
@options[:check_syntax] = true
@options[:output] = StringIO.new
end
opts.on('--precision NUMBER_OF_DIGITS', Integer,
"How many digits of precision to use when outputting decimal numbers.",
"Defaults to #{Sass::Script::Value::Number.precision}.") do |precision|
Sass::Script::Value::Number.precision = precision
end
opts.on('--cache-location PATH',
'The path to save parsed Sass files. Defaults to .sass-cache.') do |loc|
@options[:for_engine][:cache_location] = loc
end
opts.on('-C', '--no-cache', "Don't cache parsed Sass files.") do
@options[:for_engine][:cache] = false
end
opts.on('--trace', :NONE, 'Show a full Ruby stack trace on error.') do
@options[:trace] = true
end
opts.on('-q', '--quiet', 'Silence warnings and status messages during compilation.') do
@options[:for_engine][:quiet] = true
end
end
def load_compass
begin
require 'compass'
rescue LoadError
require 'rubygems'
begin
require 'compass'
rescue LoadError
puts "ERROR: Cannot load compass."
exit 1
end
end
Compass.add_project_configuration
Compass.configuration.project_path ||= Dir.pwd
@options[:for_engine][:load_paths] ||= []
@options[:for_engine][:load_paths] += Compass.configuration.sass_load_paths
end
def interactive
require 'sass/repl'
Sass::Repl.new(@options).run
end
def watch_or_update
require 'sass/plugin'
Sass::Plugin.options.merge! @options[:for_engine]
Sass::Plugin.options[:unix_newlines] = @options[:unix_newlines]
Sass::Plugin.options[:poll] = @options[:poll]
Sass::Plugin.options[:sourcemap] = @options[:sourcemap]
if @options[:force]
raise "The --force flag may only be used with --update." unless @options[:update]
Sass::Plugin.options[:always_update] = true
end
raise <<MSG if @args.empty?
What files should I watch? Did you mean something like:
#{@default_syntax} --watch input.#{@default_syntax}:output.css
#{@default_syntax} --watch input-dir:output-dir
MSG
if !colon_path?(@args[0]) && probably_dest_dir?(@args[1])
flag = @options[:update] ? "--update" : "--watch"
err =
if !File.exist?(@args[1])
"doesn't exist"
elsif @args[1] =~ /\.css$/
"is a CSS file"
end
raise <<MSG if err
File #{@args[1]} #{err}.
Did you mean: #{@default_syntax} #{flag} #{@args[0]}:#{@args[1]}
MSG
end
dirs, files = @args.map {|name| split_colon_path(name)}.
partition {|i, _| File.directory? i}
if @fake_update && !dirs.empty?
# Issue 1602.
Sass::Util.sass_warn <<WARNING.strip
DEPRECATION WARNING: Compiling directories without --update or --watch is
deprecated and won't work in future versions of Sass. Instead use:
#{@default_syntax} --update #{@args}
WARNING
end
files.map! do |from, to|
to ||= from.gsub(/\.[^.]*?$/, '.css')
sourcemap = Sass::Util.sourcemap_name(to) if @options[:sourcemap]
[from, to, sourcemap]
end
dirs.map! {|from, to| [from, to || from]}
Sass::Plugin.options[:template_location] = dirs
Sass::Plugin.on_updated_stylesheet do |_, css, sourcemap|
[css, sourcemap].each do |file|
next unless file
puts_action :write, :green, file
end
end
had_error = false
Sass::Plugin.on_creating_directory {|dirname| puts_action :directory, :green, dirname}
Sass::Plugin.on_deleting_css {|filename| puts_action :delete, :yellow, filename}
Sass::Plugin.on_deleting_sourcemap {|filename| puts_action :delete, :yellow, filename}
Sass::Plugin.on_compilation_error do |error, _, _|
if error.is_a?(SystemCallError) && !@options[:stop_on_error]
had_error = true
puts_action :error, :red, error.message
STDOUT.flush
next
end
raise error unless error.is_a?(Sass::SyntaxError) && !@options[:stop_on_error]
had_error = true
puts_action :error, :red,
"#{error.sass_filename} (Line #{error.sass_line}: #{error.message})"
STDOUT.flush
end
if @options[:update]
Sass::Plugin.update_stylesheets(files)
exit 1 if had_error
return
end
puts ">>> Sass is watching for changes. Press Ctrl-C to stop."
Sass::Plugin.on_template_modified do |template|
puts ">>> Change detected to: #{template}"
STDOUT.flush
end
Sass::Plugin.on_template_created do |template|
puts ">>> New template detected: #{template}"
STDOUT.flush
end
Sass::Plugin.on_template_deleted do |template|
puts ">>> Deleted template detected: #{template}"
STDOUT.flush
end
Sass::Plugin.watch(files)
end
def run
input = @options[:input]
output = @options[:output]
if input == $stdin
# See issue 1745
(@options[:for_engine][:load_paths] ||= []) << ::Sass::Importers::DeprecatedPath.new(".")
end
@options[:for_engine][:syntax] ||= :scss if input.is_a?(File) && input.path =~ /\.scss$/
@options[:for_engine][:syntax] ||= @default_syntax
engine =
if input.is_a?(File) && !@options[:check_syntax]
Sass::Engine.for_file(input.path, @options[:for_engine])
else
# We don't need to do any special handling of @options[:check_syntax] here,
# because the Sass syntax checking happens alongside evaluation
# and evaluation doesn't actually evaluate any code anyway.
Sass::Engine.new(input.read, @options[:for_engine])
end
input.close if input.is_a?(File)
if @options[:sourcemap] != :none && @options[:sourcemap_filename]
relative_sourcemap_path = Sass::Util.relative_path_from(
@options[:sourcemap_filename], Sass::Util.pathname(@options[:output_filename]).dirname)
rendered, mapping = engine.render_with_sourcemap(relative_sourcemap_path.to_s)
write_output(rendered, output)
write_output(
mapping.to_json(
:type => @options[:sourcemap],
:css_path => @options[:output_filename],
:sourcemap_path => @options[:sourcemap_filename]) + "\n",
@options[:sourcemap_filename])
else
write_output(engine.render, output)
end
rescue Sass::SyntaxError => e
write_output(Sass::SyntaxError.exception_to_css(e), output) if output.is_a?(String)
raise e
ensure
output.close if output.is_a? File
end
def colon_path?(path)
!split_colon_path(path)[1].nil?
end
def split_colon_path(path)
one, two = path.split(':', 2)
if one && two && Sass::Util.windows? &&
one =~ /\A[A-Za-z]\Z/ && two =~ %r{\A[/\\]}
# If we're on Windows and we were passed a drive letter path,
# don't split on that colon.
one2, two = two.split(':', 2)
one = one + ':' + one2
end
return one, two
end
# Whether path is likely to be meant as the destination
# in a source:dest pair.
def probably_dest_dir?(path)
return false unless path
return false if colon_path?(path)
Sass::Util.glob(File.join(path, "*.s[ca]ss")).empty?
end
def default_sass_path
return unless ENV['SASS_PATH']
# The select here prevents errors when the environment's
# load paths specified do not exist.
ENV['SASS_PATH'].split(File::PATH_SEPARATOR).select {|d| File.directory?(d)}
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/exec/base.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/exec/base.rb | require 'optparse'
module Sass::Exec
# The abstract base class for Sass executables.
class Base
# @param args [Array<String>] The command-line arguments
def initialize(args)
@args = args
@options = {}
end
# Parses the command-line arguments and runs the executable.
# Calls `Kernel#exit` at the end, so it never returns.
#
# @see #parse
def parse!
begin
parse
rescue Exception => e
# Exit code 65 indicates invalid data per
# http://www.freebsd.org/cgi/man.cgi?query=sysexits. Setting it via
# at_exit is a bit of a hack, but it allows us to rethrow when --trace
# is active and get both the built-in exception formatting and the
# correct exit code.
at_exit {exit Sass::Util.windows? ? 13 : 65} if e.is_a?(Sass::SyntaxError)
raise e if @options[:trace] || e.is_a?(SystemExit)
if e.is_a?(Sass::SyntaxError)
$stderr.puts e.sass_backtrace_str("standard input")
else
$stderr.print "#{e.class}: " unless e.class == RuntimeError
$stderr.puts e.message.to_s
end
$stderr.puts " Use --trace for backtrace."
exit 1
end
exit 0
end
# Parses the command-line arguments and runs the executable.
# This does not handle exceptions or exit the program.
#
# @see #parse!
def parse
@opts = OptionParser.new(&method(:set_opts))
@opts.parse!(@args)
process_result
@options
end
# @return [String] A description of the executable
def to_s
@opts.to_s
end
protected
# Finds the line of the source template
# on which an exception was raised.
#
# @param exception [Exception] The exception
# @return [String] The line number
def get_line(exception)
# SyntaxErrors have weird line reporting
# when there's trailing whitespace
if exception.is_a?(::SyntaxError)
return (exception.message.scan(/:(\d+)/).first || ["??"]).first
end
(exception.backtrace[0].scan(/:(\d+)/).first || ["??"]).first
end
# Tells optparse how to parse the arguments
# available for all executables.
#
# This is meant to be overridden by subclasses
# so they can add their own options.
#
# @param opts [OptionParser]
def set_opts(opts)
Sass::Util.abstract(this)
end
# Set an option for specifying `Encoding.default_external`.
#
# @param opts [OptionParser]
def encoding_option(opts)
encoding_desc = 'Specify the default encoding for input files.'
opts.on('-E', '--default-encoding ENCODING', encoding_desc) do |encoding|
Encoding.default_external = encoding
end
end
# Processes the options set by the command-line arguments. In particular,
# sets `@options[:input]` and `@options[:output]` to appropriate IO streams.
#
# This is meant to be overridden by subclasses
# so they can run their respective programs.
def process_result
input, output = @options[:input], @options[:output]
args = @args.dup
input ||=
begin
filename = args.shift
@options[:filename] = filename
open_file(filename) || $stdin
end
@options[:output_filename] = args.shift
output ||= @options[:output_filename] || $stdout
@options[:input], @options[:output] = input, output
end
COLORS = {:red => 31, :green => 32, :yellow => 33}
# Prints a status message about performing the given action,
# colored using the given color (via terminal escapes) if possible.
#
# @param name [#to_s] A short name for the action being performed.
# Shouldn't be longer than 11 characters.
# @param color [Symbol] The name of the color to use for this action.
# Can be `:red`, `:green`, or `:yellow`.
def puts_action(name, color, arg)
return if @options[:for_engine][:quiet]
printf color(color, "%11s %s\n"), name, arg
STDOUT.flush
end
# Same as `Kernel.puts`, but doesn't print anything if the `--quiet` option is set.
#
# @param args [Array] Passed on to `Kernel.puts`
def puts(*args)
return if @options[:for_engine][:quiet]
Kernel.puts(*args)
end
# Wraps the given string in terminal escapes
# causing it to have the given color.
# If terminal escapes aren't supported on this platform,
# just returns the string instead.
#
# @param color [Symbol] The name of the color to use.
# Can be `:red`, `:green`, or `:yellow`.
# @param str [String] The string to wrap in the given color.
# @return [String] The wrapped string.
def color(color, str)
raise "[BUG] Unrecognized color #{color}" unless COLORS[color]
# Almost any real Unix terminal will support color,
# so we just filter for Windows terms (which don't set TERM)
# and not-real terminals, which aren't ttys.
return str if ENV["TERM"].nil? || ENV["TERM"].empty? || !STDOUT.tty?
"\e[#{COLORS[color]}m#{str}\e[0m"
end
def write_output(text, destination)
if destination.is_a?(String)
open_file(destination, 'w') {|file| file.write(text)}
else
destination.write(text)
end
end
private
def open_file(filename, flag = 'r')
return if filename.nil?
flag = 'wb' if @options[:unix_newlines] && flag == 'w'
file = File.open(filename, flag)
return file unless block_given?
yield file
file.close
end
def handle_load_error(err)
dep = err.message[/^no such file to load -- (.*)/, 1]
raise err if @options[:trace] || dep.nil? || dep.empty?
$stderr.puts <<MESSAGE
Required dependency #{dep} not found!
Run "gem install #{dep}" to get it.
Use --trace for backtrace.
MESSAGE
exit 1
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/source/range.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/source/range.rb | module Sass::Source
class Range
# The starting position of the range in the document (inclusive).
#
# @return [Sass::Source::Position]
attr_accessor :start_pos
# The ending position of the range in the document (exclusive).
#
# @return [Sass::Source::Position]
attr_accessor :end_pos
# The file in which this source range appears. This can be nil if the file
# is unknown or not yet generated.
#
# @return [String]
attr_accessor :file
# The importer that imported the file in which this source range appears.
# This is nil for target ranges.
#
# @return [Sass::Importers::Base]
attr_accessor :importer
# @param start_pos [Sass::Source::Position] See \{#start_pos}
# @param end_pos [Sass::Source::Position] See \{#end_pos}
# @param file [String] See \{#file}
# @param importer [Sass::Importers::Base] See \{#importer}
def initialize(start_pos, end_pos, file, importer = nil)
@start_pos = start_pos
@end_pos = end_pos
@file = file
@importer = importer
end
# @return [String] A string representation of the source range.
def inspect
"(#{start_pos.inspect} to #{end_pos.inspect}#{" in #{@file}" if @file})"
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/source/position.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/source/position.rb | module Sass::Source
class Position
# The one-based line of the document associated with the position.
#
# @return [Integer]
attr_accessor :line
# The one-based offset in the line of the document associated with the
# position.
#
# @return [Integer]
attr_accessor :offset
# @param line [Integer] The source line
# @param offset [Integer] The source offset
def initialize(line, offset)
@line = line
@offset = offset
end
# @return [String] A string representation of the source position.
def inspect
"#{line.inspect}:#{offset.inspect}"
end
# @param str [String] The string to move through.
# @return [Position] The source position after proceeding forward through
# `str`.
def after(str)
newlines = str.count("\n")
Position.new(line + newlines,
if newlines == 0
offset + str.length
else
str.length - str.rindex("\n") - 1
end)
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/source/map.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/source/map.rb | module Sass::Source
class Map
# A mapping from one source range to another. Indicates that `input` was
# compiled to `output`.
#
# @!attribute input
# @return [Sass::Source::Range] The source range in the input document.
#
# @!attribute output
# @return [Sass::Source::Range] The source range in the output document.
class Mapping < Struct.new(:input, :output)
# @return [String] A string representation of the mapping.
def inspect
"#{input.inspect} => #{output.inspect}"
end
end
# The mapping data ordered by the location in the target.
#
# @return [Array<Mapping>]
attr_reader :data
def initialize
@data = []
end
# Adds a new mapping from one source range to another. Multiple invocations
# of this method should have each `output` range come after all previous ranges.
#
# @param input [Sass::Source::Range]
# The source range in the input document.
# @param output [Sass::Source::Range]
# The source range in the output document.
def add(input, output)
@data.push(Mapping.new(input, output))
end
# Shifts all output source ranges forward one or more lines.
#
# @param delta [Integer] The number of lines to shift the ranges forward.
def shift_output_lines(delta)
return if delta == 0
@data.each do |m|
m.output.start_pos.line += delta
m.output.end_pos.line += delta
end
end
# Shifts any output source ranges that lie on the first line forward one or
# more characters on that line.
#
# @param delta [Integer] The number of characters to shift the ranges
# forward.
def shift_output_offsets(delta)
return if delta == 0
@data.each do |m|
break if m.output.start_pos.line > 1
m.output.start_pos.offset += delta
m.output.end_pos.offset += delta if m.output.end_pos.line > 1
end
end
# Returns the standard JSON representation of the source map.
#
# If the `:css_uri` option isn't specified, the `:css_path` and
# `:sourcemap_path` options must both be specified. Any options may also be
# specified alongside the `:css_uri` option. If `:css_uri` isn't specified,
# it will be inferred from `:css_path` and `:sourcemap_path` using the
# assumption that the local file system has the same layout as the server.
#
# Regardless of which options are passed to this method, source stylesheets
# that are imported using a non-default importer will only be linked to in
# the source map if their importers implement
# \{Sass::Importers::Base#public\_url\}.
#
# @option options :css_uri [String]
# The publicly-visible URI of the CSS output file.
# @option options :css_path [String]
# The local path of the CSS output file.
# @option options :sourcemap_path [String]
# The (eventual) local path of the sourcemap file.
# @option options :type [Symbol]
# `:auto` (default), `:file`, or `:inline`.
# @return [String] The JSON string.
# @raise [ArgumentError] If neither `:css_uri` nor `:css_path` and
# `:sourcemap_path` are specified.
def to_json(options)
css_uri, css_path, sourcemap_path =
options[:css_uri], options[:css_path], options[:sourcemap_path]
unless css_uri || (css_path && sourcemap_path)
raise ArgumentError.new("Sass::Source::Map#to_json requires either " \
"the :css_uri option or both the :css_path and :soucemap_path options.")
end
css_path &&= Sass::Util.pathname(File.absolute_path(css_path))
sourcemap_path &&= Sass::Util.pathname(File.absolute_path(sourcemap_path))
css_uri ||= Sass::Util.file_uri_from_path(
Sass::Util.relative_path_from(css_path, sourcemap_path.dirname))
result = "{\n"
write_json_field(result, "version", 3, true)
source_uri_to_id = {}
id_to_source_uri = {}
id_to_contents = {} if options[:type] == :inline
next_source_id = 0
line_data = []
segment_data_for_line = []
# These track data necessary for the delta coding.
previous_target_line = nil
previous_target_offset = 1
previous_source_line = 1
previous_source_offset = 1
previous_source_id = 0
@data.each do |m|
file, importer = m.input.file, m.input.importer
next unless importer
if options[:type] == :inline
source_uri = file
else
sourcemap_dir = sourcemap_path && sourcemap_path.dirname.to_s
sourcemap_dir = nil if options[:type] == :file
source_uri = importer.public_url(file, sourcemap_dir)
next unless source_uri
end
current_source_id = source_uri_to_id[source_uri]
unless current_source_id
current_source_id = next_source_id
next_source_id += 1
source_uri_to_id[source_uri] = current_source_id
id_to_source_uri[current_source_id] = source_uri
if options[:type] == :inline
id_to_contents[current_source_id] =
importer.find(file, {}).instance_variable_get('@template')
end
end
[
[m.input.start_pos, m.output.start_pos],
[m.input.end_pos, m.output.end_pos]
].each do |source_pos, target_pos|
if previous_target_line != target_pos.line
line_data.push(segment_data_for_line.join(",")) unless segment_data_for_line.empty?
(target_pos.line - 1 - (previous_target_line || 0)).times {line_data.push("")}
previous_target_line = target_pos.line
previous_target_offset = 1
segment_data_for_line = []
end
# `segment` is a data chunk for a single position mapping.
segment = ""
# Field 1: zero-based starting offset.
segment << Sass::Util.encode_vlq(target_pos.offset - previous_target_offset)
previous_target_offset = target_pos.offset
# Field 2: zero-based index into the "sources" list.
segment << Sass::Util.encode_vlq(current_source_id - previous_source_id)
previous_source_id = current_source_id
# Field 3: zero-based starting line in the original source.
segment << Sass::Util.encode_vlq(source_pos.line - previous_source_line)
previous_source_line = source_pos.line
# Field 4: zero-based starting offset in the original source.
segment << Sass::Util.encode_vlq(source_pos.offset - previous_source_offset)
previous_source_offset = source_pos.offset
segment_data_for_line.push(segment)
previous_target_line = target_pos.line
end
end
line_data.push(segment_data_for_line.join(","))
write_json_field(result, "mappings", line_data.join(";"))
source_names = []
(0...next_source_id).each {|id| source_names.push(id_to_source_uri[id].to_s)}
write_json_field(result, "sources", source_names)
if options[:type] == :inline
write_json_field(result, "sourcesContent",
(0...next_source_id).map {|id| id_to_contents[id]})
end
write_json_field(result, "names", [])
write_json_field(result, "file", css_uri)
result << "\n}"
result
end
private
def write_json_field(out, name, value, is_first = false)
out << (is_first ? "" : ",\n") <<
"\"" <<
Sass::Util.json_escape_string(name) <<
"\": " <<
Sass::Util.json_value_of(value)
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/cache_stores/memory.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/cache_stores/memory.rb | module Sass
module CacheStores
# A backend for the Sass cache using in-process memory.
class Memory < Base
# Since the {Memory} store is stored in the Sass tree's options hash,
# when the options get serialized as part of serializing the tree,
# you get crazy exponential growth in the size of the cached objects
# unless you don't dump the cache.
#
# @private
def _dump(depth)
""
end
# If we deserialize this class, just make a new empty one.
#
# @private
def self._load(repr)
Memory.new
end
# Create a new, empty cache store.
def initialize
@contents = {}
end
# @see Base#retrieve
def retrieve(key, sha)
return unless @contents.has_key?(key)
return unless @contents[key][:sha] == sha
obj = @contents[key][:obj]
obj.respond_to?(:deep_copy) ? obj.deep_copy : obj.dup
end
# @see Base#store
def store(key, sha, obj)
@contents[key] = {:sha => sha, :obj => obj}
end
# Destructively clear the cache.
def reset!
@contents = {}
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/cache_stores/chain.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/cache_stores/chain.rb | module Sass
module CacheStores
# A meta-cache that chains multiple caches together.
# Specifically:
#
# * All `#store`s are passed to all caches.
# * `#retrieve`s are passed to each cache until one has a hit.
# * When one cache has a hit, the value is `#store`d in all earlier caches.
class Chain < Base
# Create a new cache chaining the given caches.
#
# @param caches [Array<Sass::CacheStores::Base>] The caches to chain.
def initialize(*caches)
@caches = caches
end
# @see Base#store
def store(key, sha, obj)
@caches.each {|c| c.store(key, sha, obj)}
end
# @see Base#retrieve
def retrieve(key, sha)
@caches.each_with_index do |c, i|
obj = c.retrieve(key, sha)
next unless obj
@caches[0...i].each {|prev| prev.store(key, sha, obj)}
return obj
end
nil
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/cache_stores/base.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/cache_stores/base.rb | module Sass
module CacheStores
# An abstract base class for backends for the Sass cache.
# Any key-value store can act as such a backend;
# it just needs to implement the
# \{#_store} and \{#_retrieve} methods.
#
# To use a cache store with Sass,
# use the {file:SASS_REFERENCE.md#cache_store-option `:cache_store` option}.
#
# @abstract
class Base
# Store cached contents for later retrieval
# Must be implemented by all CacheStore subclasses
#
# Note: cache contents contain binary data.
#
# @param key [String] The key to store the contents under
# @param version [String] The current sass version.
# Cached contents must not be retrieved across different versions of sass.
# @param sha [String] The sha of the sass source.
# Cached contents must not be retrieved if the sha has changed.
# @param contents [String] The contents to store.
def _store(key, version, sha, contents)
raise "#{self.class} must implement #_store."
end
# Retrieved cached contents.
# Must be implemented by all subclasses.
#
# Note: if the key exists but the sha or version have changed,
# then the key may be deleted by the cache store, if it wants to do so.
#
# @param key [String] The key to retrieve
# @param version [String] The current sass version.
# Cached contents must not be retrieved across different versions of sass.
# @param sha [String] The sha of the sass source.
# Cached contents must not be retrieved if the sha has changed.
# @return [String] The contents that were previously stored.
# @return [NilClass] when the cache key is not found or the version or sha have changed.
def _retrieve(key, version, sha)
raise "#{self.class} must implement #_retrieve."
end
# Store a {Sass::Tree::RootNode}.
#
# @param key [String] The key to store it under.
# @param sha [String] The checksum for the contents that are being stored.
# @param root [Object] The root node to cache.
def store(key, sha, root)
_store(key, Sass::VERSION, sha, Marshal.dump(root))
rescue TypeError, LoadError => e
Sass::Util.sass_warn "Warning. Error encountered while saving cache #{path_to(key)}: #{e}"
nil
end
# Retrieve a {Sass::Tree::RootNode}.
#
# @param key [String] The key the root element was stored under.
# @param sha [String] The checksum of the root element's content.
# @return [Object] The cached object.
def retrieve(key, sha)
contents = _retrieve(key, Sass::VERSION, sha)
Marshal.load(contents) if contents
rescue EOFError, TypeError, ArgumentError, LoadError => e
Sass::Util.sass_warn "Warning. Error encountered while reading cache #{path_to(key)}: #{e}"
nil
end
# Return the key for the sass file.
#
# The `(sass_dirname, sass_basename)` pair
# should uniquely identify the Sass document,
# but otherwise there are no restrictions on their content.
#
# @param sass_dirname [String]
# The fully-expanded location of the Sass file.
# This corresponds to the directory name on a filesystem.
# @param sass_basename [String] The name of the Sass file that is being referenced.
# This corresponds to the basename on a filesystem.
def key(sass_dirname, sass_basename)
dir = Digest::SHA1.hexdigest(sass_dirname)
filename = "#{sass_basename}c"
"#{dir}/#{filename}"
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/cache_stores/null.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/cache_stores/null.rb | module Sass
module CacheStores
# Doesn't store anything, but records what things it should have stored.
# This doesn't currently have any use except for testing and debugging.
#
# @private
class Null < Base
def initialize
@keys = {}
end
def _retrieve(key, version, sha)
nil
end
def _store(key, version, sha, contents)
@keys[key] = true
end
def was_set?(key)
@keys[key]
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/cache_stores/filesystem.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/cache_stores/filesystem.rb | require 'fileutils'
module Sass
module CacheStores
# A backend for the Sass cache using the filesystem.
class Filesystem < Base
# The directory where the cached files will be stored.
#
# @return [String]
attr_accessor :cache_location
# @param cache_location [String] see \{#cache\_location}
def initialize(cache_location)
@cache_location = cache_location
end
# @see Base#\_retrieve
def _retrieve(key, version, sha)
return unless File.readable?(path_to(key))
begin
File.open(path_to(key), "rb") do |f|
if f.readline("\n").strip == version && f.readline("\n").strip == sha
return f.read
end
end
File.unlink path_to(key)
rescue Errno::ENOENT
# Already deleted. Race condition?
end
nil
rescue EOFError, TypeError, ArgumentError => e
Sass::Util.sass_warn "Warning. Error encountered while reading cache #{path_to(key)}: #{e}"
end
# @see Base#\_store
def _store(key, version, sha, contents)
compiled_filename = path_to(key)
FileUtils.mkdir_p(File.dirname(compiled_filename))
Sass::Util.atomic_create_and_write_file(compiled_filename) do |f|
f.puts(version)
f.puts(sha)
f.write(contents)
end
rescue Errno::EACCES
# pass
end
private
# Returns the path to a file for the given key.
#
# @param key [String]
# @return [String] The path to the cache file.
def path_to(key)
key = key.gsub(/[<>:\\|?*%]/) {|c| "%%%03d" % c.ord}
File.join(cache_location, key)
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/selector/simple_sequence.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/selector/simple_sequence.rb | module Sass
module Selector
# A unseparated sequence of selectors
# that all apply to a single element.
# For example, `.foo#bar[attr=baz]` is a simple sequence
# of the selectors `.foo`, `#bar`, and `[attr=baz]`.
class SimpleSequence < AbstractSequence
# The array of individual selectors.
#
# @return [Array<Simple>]
attr_accessor :members
# The extending selectors that caused this selector sequence to be
# generated. For example:
#
# a.foo { ... }
# b.bar {@extend a}
# c.baz {@extend b}
#
# The generated selector `b.foo.bar` has `{b.bar}` as its `sources` set,
# and the generated selector `c.foo.bar.baz` has `{b.bar, c.baz}` as its
# `sources` set.
#
# This is populated during the {Sequence#do_extend} process.
#
# @return {Set<Sequence>}
attr_accessor :sources
# This sequence source range.
#
# @return [Sass::Source::Range]
attr_accessor :source_range
# @see \{#subject?}
attr_writer :subject
# Returns the element or universal selector in this sequence,
# if it exists.
#
# @return [Element, Universal, nil]
def base
@base ||= (members.first if members.first.is_a?(Element) || members.first.is_a?(Universal))
end
def pseudo_elements
@pseudo_elements ||= members.select {|sel| sel.is_a?(Pseudo) && sel.type == :element}
end
def selector_pseudo_classes
@selector_pseudo_classes ||= members.
select {|sel| sel.is_a?(Pseudo) && sel.type == :class && sel.selector}.
group_by {|sel| sel.normalized_name}
end
# Returns the non-base, non-pseudo-element selectors in this sequence.
#
# @return [Set<Simple>]
def rest
@rest ||= Set.new(members - [base] - pseudo_elements)
end
# Whether or not this compound selector is the subject of the parent
# selector; that is, whether it is prepended with `$` and represents the
# actual element that will be selected.
#
# @return [Boolean]
def subject?
@subject
end
# @param selectors [Array<Simple>] See \{#members}
# @param subject [Boolean] See \{#subject?}
# @param source_range [Sass::Source::Range]
def initialize(selectors, subject, source_range = nil)
@members = selectors
@subject = subject
@sources = Set.new
@source_range = source_range
end
# Resolves the {Parent} selectors within this selector
# by replacing them with the given parent selector,
# handling commas appropriately.
#
# @param super_cseq [CommaSequence] The parent selector
# @return [CommaSequence] This selector, with parent references resolved
# @raise [Sass::SyntaxError] If a parent selector is invalid
def resolve_parent_refs(super_cseq)
resolved_members = @members.map do |sel|
next sel unless sel.is_a?(Pseudo) && sel.selector
sel.with_selector(sel.selector.resolve_parent_refs(super_cseq, false))
end.flatten
# Parent selector only appears as the first selector in the sequence
unless (parent = resolved_members.first).is_a?(Parent)
return CommaSequence.new([Sequence.new([SimpleSequence.new(resolved_members, subject?)])])
end
return super_cseq if @members.size == 1 && parent.suffix.nil?
CommaSequence.new(super_cseq.members.map do |super_seq|
members = super_seq.members.dup
newline = members.pop if members.last == "\n"
unless members.last.is_a?(SimpleSequence)
raise Sass::SyntaxError.new("Invalid parent selector for \"#{self}\": \"" +
super_seq.to_s + '"')
end
parent_sub = members.last.members
unless parent.suffix.nil?
parent_sub = parent_sub.dup
parent_sub[-1] = parent_sub.last.dup
case parent_sub.last
when Sass::Selector::Class, Sass::Selector::Id, Sass::Selector::Placeholder
parent_sub[-1] = parent_sub.last.class.new(parent_sub.last.name + parent.suffix)
when Sass::Selector::Element
parent_sub[-1] = parent_sub.last.class.new(
parent_sub.last.name + parent.suffix,
parent_sub.last.namespace)
when Sass::Selector::Pseudo
if parent_sub.last.arg || parent_sub.last.selector
raise Sass::SyntaxError.new("Invalid parent selector for \"#{self}\": \"" +
super_seq.to_s + '"')
end
parent_sub[-1] = Sass::Selector::Pseudo.new(
parent_sub.last.type,
parent_sub.last.name + parent.suffix,
nil, nil)
else
raise Sass::SyntaxError.new("Invalid parent selector for \"#{self}\": \"" +
super_seq.to_s + '"')
end
end
Sequence.new(members[0...-1] +
[SimpleSequence.new(parent_sub + resolved_members[1..-1], subject?)] +
[newline].compact)
end)
end
# Non-destructively extends this selector with the extensions specified in a hash
# (which should come from {Sass::Tree::Visitors::Cssize}).
#
# @param extends [{Selector::Simple =>
# Sass::Tree::Visitors::Cssize::Extend}]
# The extensions to perform on this selector
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
# The directives containing this selector.
# @param seen [Set<Array<Selector::Simple>>]
# The set of simple sequences that are currently being replaced.
# @param original [Boolean]
# Whether this is the original selector being extended, as opposed to
# the result of a previous extension that's being re-extended.
# @return [Array<Sequence>] A list of selectors generated
# by extending this selector with `extends`.
# @see CommaSequence#do_extend
def do_extend(extends, parent_directives, replace, seen)
seen_with_pseudo_selectors = seen.dup
modified_original = false
members = self.members.map do |sel|
next sel unless sel.is_a?(Pseudo) && sel.selector
next sel if seen.include?([sel])
extended = sel.selector.do_extend(extends, parent_directives, replace, seen, false)
next sel if extended == sel.selector
extended.members.reject! {|seq| seq.invisible?}
# For `:not()`, we usually want to get rid of any complex
# selectors because that will cause the selector to fail to
# parse on all browsers at time of writing. We can keep them
# if either the original selector had a complex selector, or
# the result of extending has only complex selectors,
# because either way we aren't breaking anything that isn't
# already broken.
if sel.normalized_name == 'not' &&
(sel.selector.members.none? {|seq| seq.members.length > 1} &&
extended.members.any? {|seq| seq.members.length == 1})
extended.members.reject! {|seq| seq.members.length > 1}
end
modified_original = true
result = sel.with_selector(extended)
result.each {|new_sel| seen_with_pseudo_selectors << [new_sel]}
result
end.flatten
groups = extends[members.to_set].group_by {|ex| ex.extender}.to_a
groups.map! do |seq, group|
sels = group.map {|e| e.target}.flatten
# If A {@extend B} and C {...},
# seq is A, sels is B, and self is C
self_without_sel = Sass::Util.array_minus(members, sels)
group.each {|e| e.success = true}
unified = seq.members.last.unify(SimpleSequence.new(self_without_sel, subject?))
next unless unified
group.each {|e| check_directives_match!(e, parent_directives)}
new_seq = Sequence.new(seq.members[0...-1] + [unified])
new_seq.add_sources!(sources + [seq])
[sels, new_seq]
end
groups.compact!
groups.map! do |sels, seq|
next [] if seen.include?(sels)
seq.do_extend(
extends, parent_directives, false, seen_with_pseudo_selectors + [sels], false)
end
groups.flatten!
if modified_original || !replace || groups.empty?
# First Law of Extend: the result of extending a selector should
# (almost) always contain the base selector.
#
# See https://github.com/nex3/sass/issues/324.
original = Sequence.new([SimpleSequence.new(members, @subject, source_range)])
original.add_sources! sources
groups.unshift original
end
groups.uniq!
groups
end
# Unifies this selector with another {SimpleSequence}, returning
# another `SimpleSequence` that is a subselector of both input
# selectors.
#
# @param other [SimpleSequence]
# @return [SimpleSequence, nil] A {SimpleSequence} matching both `sels` and this selector,
# or `nil` if this is impossible (e.g. unifying `#foo` and `#bar`)
# @raise [Sass::SyntaxError] If this selector cannot be unified.
# This will only ever occur when a dynamic selector,
# such as {Parent} or {Interpolation}, is used in unification.
# Since these selectors should be resolved
# by the time extension and unification happen,
# this exception will only ever be raised as a result of programmer error
def unify(other)
sseq = members.inject(other.members) do |member, sel|
return unless member
sel.unify(member)
end
return unless sseq
SimpleSequence.new(sseq, other.subject? || subject?)
end
# Returns whether or not this selector matches all elements
# that the given selector matches (as well as possibly more).
#
# @example
# (.foo).superselector?(.foo.bar) #=> true
# (.foo).superselector?(.bar) #=> false
# @param their_sseq [SimpleSequence]
# @param parents [Array<SimpleSequence, String>] The parent selectors of `their_sseq`, if any.
# @return [Boolean]
def superselector?(their_sseq, parents = [])
return false unless base.nil? || base.eql?(their_sseq.base)
return false unless pseudo_elements.eql?(their_sseq.pseudo_elements)
our_spcs = selector_pseudo_classes
their_spcs = their_sseq.selector_pseudo_classes
# Some psuedo-selectors can be subselectors of non-pseudo selectors.
# Pull those out here so we can efficiently check against them below.
their_subselector_pseudos = %w(matches any nth-child nth-last-child).
map {|name| their_spcs[name] || []}.flatten
# If `self`'s non-pseudo simple selectors aren't a subset of `their_sseq`'s,
# it's definitely not a superselector. This also considers being matched
# by `:matches` or `:any`.
return false unless rest.all? do |our_sel|
next true if our_sel.is_a?(Pseudo) && our_sel.selector
next true if their_sseq.rest.include?(our_sel)
their_subselector_pseudos.any? do |their_pseudo|
their_pseudo.selector.members.all? do |their_seq|
next false unless their_seq.members.length == 1
their_sseq = their_seq.members.first
next false unless their_sseq.is_a?(SimpleSequence)
their_sseq.rest.include?(our_sel)
end
end
end
our_spcs.all? do |_name, pseudos|
pseudos.all? {|pseudo| pseudo.superselector?(their_sseq, parents)}
end
end
# @see Simple#to_s
def to_s(opts = {})
res = @members.map {|m| m.to_s(opts)}.join
# :not(%foo) may resolve to the empty string, but it should match every
# selector so we replace it with "*".
res = '*' if res.empty?
res << '!' if subject?
res
end
# Returns a string representation of the sequence.
# This is basically the selector string.
#
# @return [String]
def inspect
res = members.map {|m| m.inspect}.join
res << '!' if subject?
res
end
# Return a copy of this simple sequence with `sources` merged into the
# {SimpleSequence#sources} set.
#
# @param sources [Set<Sequence>]
# @return [SimpleSequence]
def with_more_sources(sources)
sseq = dup
sseq.members = members.dup
sseq.sources = self.sources | sources
sseq
end
private
def check_directives_match!(extend, parent_directives)
dirs1 = extend.directives.map {|d| d.resolved_value}
dirs2 = parent_directives.map {|d| d.resolved_value}
return if Sass::Util.subsequence?(dirs1, dirs2)
line = extend.node.line
filename = extend.node.filename
# TODO(nweiz): this should use the Sass stack trace of the extend node,
# not the selector.
raise Sass::SyntaxError.new(<<MESSAGE)
You may not @extend an outer selector from within #{extend.directives.last.name}.
You may only @extend selectors within the same directive.
From "@extend #{extend.target.join(', ')}" on line #{line}#{" of #{filename}" if filename}.
MESSAGE
end
def _hash
[base, rest.hash].hash
end
def _eql?(other)
other.base.eql?(base) && other.pseudo_elements == pseudo_elements &&
other.rest.eql?(rest) && other.subject? == subject?
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/selector/abstract_sequence.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/selector/abstract_sequence.rb | module Sass
module Selector
# The abstract parent class of the various selector sequence classes.
#
# All subclasses should implement a `members` method that returns an array
# of object that respond to `#line=` and `#filename=`, as well as a `to_s`
# method that returns the string representation of the selector.
class AbstractSequence
# The line of the Sass template on which this selector was declared.
#
# @return [Integer]
attr_reader :line
# The name of the file in which this selector was declared.
#
# @return [String, nil]
attr_reader :filename
# Sets the line of the Sass template on which this selector was declared.
# This also sets the line for all child selectors.
#
# @param line [Integer]
# @return [Integer]
def line=(line)
members.each {|m| m.line = line}
@line = line
end
# Sets the name of the file in which this selector was declared,
# or `nil` if it was not declared in a file (e.g. on stdin).
# This also sets the filename for all child selectors.
#
# @param filename [String, nil]
# @return [String, nil]
def filename=(filename)
members.each {|m| m.filename = filename}
@filename = filename
end
# Returns a hash code for this sequence.
#
# Subclasses should define `#_hash` rather than overriding this method,
# which automatically handles memoizing the result.
#
# @return [Integer]
def hash
@_hash ||= _hash
end
# Checks equality between this and another object.
#
# Subclasses should define `#_eql?` rather than overriding this method,
# which handles checking class equality and hash equality.
#
# @param other [Object] The object to test equality against
# @return [Boolean] Whether or not this is equal to `other`
def eql?(other)
other.class == self.class && other.hash == hash && _eql?(other)
end
alias_method :==, :eql?
# Whether or not this selector should be hidden due to containing a
# placeholder.
def invisible?
@invisible ||= members.any? do |m|
next m.invisible? if m.is_a?(AbstractSequence) || m.is_a?(Pseudo)
m.is_a?(Placeholder)
end
end
# Returns the selector string.
#
# @param opts [Hash] rendering options.
# @option opts [Symbol] :style The css rendering style.
# @option placeholders [Boolean] :placeholders
# Whether to include placeholder selectors. Defaults to `true`.
# @return [String]
def to_s(opts = {})
Sass::Util.abstract(self)
end
# Returns the specificity of the selector.
#
# The base is given by {Sass::Selector::SPECIFICITY_BASE}. This can be a
# number or a range representing possible specificities.
#
# @return [Integer, Range]
def specificity
_specificity(members)
end
protected
def _specificity(arr)
min = 0
max = 0
arr.each do |m|
next if m.is_a?(String)
spec = m.specificity
if spec.is_a?(Range)
min += spec.begin
max += spec.end
else
min += spec
max += spec
end
end
min == max ? min : (min..max)
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/selector/comma_sequence.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/selector/comma_sequence.rb | module Sass
module Selector
# A comma-separated sequence of selectors.
class CommaSequence < AbstractSequence
@@compound_extend_deprecation = Sass::Deprecation.new
# The comma-separated selector sequences
# represented by this class.
#
# @return [Array<Sequence>]
attr_reader :members
# @param seqs [Array<Sequence>] See \{#members}
def initialize(seqs)
@members = seqs
end
# Resolves the {Parent} selectors within this selector
# by replacing them with the given parent selector,
# handling commas appropriately.
#
# @param super_cseq [CommaSequence] The parent selector
# @param implicit_parent [Boolean] Whether the the parent
# selector should automatically be prepended to the resolved
# selector if it contains no parent refs.
# @return [CommaSequence] This selector, with parent references resolved
# @raise [Sass::SyntaxError] If a parent selector is invalid
def resolve_parent_refs(super_cseq, implicit_parent = true)
if super_cseq.nil?
if contains_parent_ref?
raise Sass::SyntaxError.new(
"Base-level rules cannot contain the parent-selector-referencing character '&'.")
end
return self
end
CommaSequence.new(Sass::Util.flatten_vertically(@members.map do |seq|
seq.resolve_parent_refs(super_cseq, implicit_parent).members
end))
end
# Returns whether there's a {Parent} selector anywhere in this sequence.
#
# @return [Boolean]
def contains_parent_ref?
@members.any? {|sel| sel.contains_parent_ref?}
end
# Non-destrucively extends this selector with the extensions specified in a hash
# (which should come from {Sass::Tree::Visitors::Cssize}).
#
# @todo Link this to the reference documentation on `@extend`
# when such a thing exists.
#
# @param extends [Sass::Util::SubsetMap{Selector::Simple =>
# Sass::Tree::Visitors::Cssize::Extend}]
# The extensions to perform on this selector
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
# The directives containing this selector.
# @param replace [Boolean]
# Whether to replace the original selector entirely or include
# it in the result.
# @param seen [Set<Array<Selector::Simple>>]
# The set of simple sequences that are currently being replaced.
# @param original [Boolean]
# Whether this is the original selector being extended, as opposed to
# the result of a previous extension that's being re-extended.
# @return [CommaSequence] A copy of this selector,
# with extensions made according to `extends`
def do_extend(extends, parent_directives = [], replace = false, seen = Set.new,
original = true)
CommaSequence.new(members.map do |seq|
seq.do_extend(extends, parent_directives, replace, seen, original)
end.flatten)
end
# Returns whether or not this selector matches all elements
# that the given selector matches (as well as possibly more).
#
# @example
# (.foo).superselector?(.foo.bar) #=> true
# (.foo).superselector?(.bar) #=> false
# @param cseq [CommaSequence]
# @return [Boolean]
def superselector?(cseq)
cseq.members.all? {|seq1| members.any? {|seq2| seq2.superselector?(seq1)}}
end
# Populates a subset map that can then be used to extend
# selectors. This registers an extension with this selector as
# the extender and `extendee` as the extendee.
#
# @param extends [Sass::Util::SubsetMap{Selector::Simple =>
# Sass::Tree::Visitors::Cssize::Extend}]
# The subset map representing the extensions to perform.
# @param extendee [CommaSequence] The selector being extended.
# @param extend_node [Sass::Tree::ExtendNode]
# The node that caused this extension.
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
# The parent directives containing `extend_node`.
# @param allow_compound_target [Boolean]
# Whether `extendee` is allowed to contain compound selectors.
# @raise [Sass::SyntaxError] if this extension is invalid.
def populate_extends(extends, extendee, extend_node = nil, parent_directives = [],
allow_compound_target = false)
extendee.members.each do |seq|
if seq.members.size > 1
raise Sass::SyntaxError.new("Can't extend #{seq}: can't extend nested selectors")
end
sseq = seq.members.first
if !sseq.is_a?(Sass::Selector::SimpleSequence)
raise Sass::SyntaxError.new("Can't extend #{seq}: invalid selector")
elsif sseq.members.any? {|ss| ss.is_a?(Sass::Selector::Parent)}
raise Sass::SyntaxError.new("Can't extend #{seq}: can't extend parent selectors")
end
sel = sseq.members
if !allow_compound_target && sel.length > 1
@@compound_extend_deprecation.warn(sseq.filename, sseq.line, <<WARNING)
Extending a compound selector, #{sseq}, is deprecated and will not be supported in a future release.
Consider "@extend #{sseq.members.join(', ')}" instead.
See http://bit.ly/ExtendCompound for details.
WARNING
end
members.each do |member|
unless member.members.last.is_a?(Sass::Selector::SimpleSequence)
raise Sass::SyntaxError.new("#{member} can't extend: invalid selector")
end
extends[sel] = Sass::Tree::Visitors::Cssize::Extend.new(
member, sel, extend_node, parent_directives, false)
end
end
end
# Unifies this with another comma selector to produce a selector
# that matches (a subset of) the intersection of the two inputs.
#
# @param other [CommaSequence]
# @return [CommaSequence, nil] The unified selector, or nil if unification failed.
# @raise [Sass::SyntaxError] If this selector cannot be unified.
# This will only ever occur when a dynamic selector,
# such as {Parent} or {Interpolation}, is used in unification.
# Since these selectors should be resolved
# by the time extension and unification happen,
# this exception will only ever be raised as a result of programmer error
def unify(other)
results = members.map {|seq1| other.members.map {|seq2| seq1.unify(seq2)}}.flatten.compact
results.empty? ? nil : CommaSequence.new(results.map {|cseq| cseq.members}.flatten)
end
# Returns a SassScript representation of this selector.
#
# @return [Sass::Script::Value::List]
def to_sass_script
Sass::Script::Value::List.new(members.map do |seq|
Sass::Script::Value::List.new(seq.members.map do |component|
next if component == "\n"
Sass::Script::Value::String.new(component.to_s)
end.compact, separator: :space)
end, separator: :comma)
end
# Returns a string representation of the sequence.
# This is basically the selector string.
#
# @return [String]
def inspect
members.map {|m| m.inspect}.join(", ")
end
# @see AbstractSequence#to_s
def to_s(opts = {})
@members.map do |m|
next if opts[:placeholder] == false && m.invisible?
m.to_s(opts)
end.compact.
join(opts[:style] == :compressed ? "," : ", ").
gsub(", \n", ",\n")
end
private
def _hash
members.hash
end
def _eql?(other)
other.class == self.class && other.members.eql?(members)
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/selector/sequence.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/selector/sequence.rb | module Sass
module Selector
# An operator-separated sequence of
# {SimpleSequence simple selector sequences}.
class Sequence < AbstractSequence
# Sets the line of the Sass template on which this selector was declared.
# This also sets the line for all child selectors.
#
# @param line [Integer]
# @return [Integer]
def line=(line)
members.each {|m| m.line = line if m.is_a?(SimpleSequence)}
@line = line
end
# Sets the name of the file in which this selector was declared,
# or `nil` if it was not declared in a file (e.g. on stdin).
# This also sets the filename for all child selectors.
#
# @param filename [String, nil]
# @return [String, nil]
def filename=(filename)
members.each {|m| m.filename = filename if m.is_a?(SimpleSequence)}
filename
end
# The array of {SimpleSequence simple selector sequences}, operators, and
# newlines. The operators are strings such as `"+"` and `">"` representing
# the corresponding CSS operators, or interpolated SassScript. Newlines
# are also newline strings; these aren't semantically relevant, but they
# do affect formatting.
#
# @return [Array<SimpleSequence, String|Array<Sass::Tree::Node, String>>]
attr_reader :members
# @param seqs_and_ops [Array<SimpleSequence, String|Array<Sass::Tree::Node, String>>]
# See \{#members}
def initialize(seqs_and_ops)
@members = seqs_and_ops
end
# Resolves the {Parent} selectors within this selector
# by replacing them with the given parent selector,
# handling commas appropriately.
#
# @param super_cseq [CommaSequence] The parent selector
# @param implicit_parent [Boolean] Whether the the parent
# selector should automatically be prepended to the resolved
# selector if it contains no parent refs.
# @return [CommaSequence] This selector, with parent references resolved
# @raise [Sass::SyntaxError] If a parent selector is invalid
def resolve_parent_refs(super_cseq, implicit_parent)
members = @members.dup
nl = (members.first == "\n" && members.shift)
contains_parent_ref = contains_parent_ref?
return CommaSequence.new([self]) if !implicit_parent && !contains_parent_ref
unless contains_parent_ref
old_members, members = members, []
members << nl if nl
members << SimpleSequence.new([Parent.new], false)
members += old_members
end
CommaSequence.new(Sass::Util.paths(members.map do |sseq_or_op|
next [sseq_or_op] unless sseq_or_op.is_a?(SimpleSequence)
sseq_or_op.resolve_parent_refs(super_cseq).members
end).map do |path|
path_members = path.map do |seq_or_op|
next seq_or_op unless seq_or_op.is_a?(Sequence)
seq_or_op.members
end
if path_members.length == 2 && path_members[1][0] == "\n"
path_members[0].unshift path_members[1].shift
end
Sequence.new(path_members.flatten)
end)
end
# Returns whether there's a {Parent} selector anywhere in this sequence.
#
# @return [Boolean]
def contains_parent_ref?
members.any? do |sseq_or_op|
next false unless sseq_or_op.is_a?(SimpleSequence)
next true if sseq_or_op.members.first.is_a?(Parent)
sseq_or_op.members.any? do |sel|
sel.is_a?(Pseudo) && sel.selector && sel.selector.contains_parent_ref?
end
end
end
# Non-destructively extends this selector with the extensions specified in a hash
# (which should come from {Sass::Tree::Visitors::Cssize}).
#
# @param extends [Sass::Util::SubsetMap{Selector::Simple =>
# Sass::Tree::Visitors::Cssize::Extend}]
# The extensions to perform on this selector
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
# The directives containing this selector.
# @param replace [Boolean]
# Whether to replace the original selector entirely or include
# it in the result.
# @param seen [Set<Array<Selector::Simple>>]
# The set of simple sequences that are currently being replaced.
# @param original [Boolean]
# Whether this is the original selector being extended, as opposed to
# the result of a previous extension that's being re-extended.
# @return [Array<Sequence>] A list of selectors generated
# by extending this selector with `extends`.
# These correspond to a {CommaSequence}'s {CommaSequence#members members array}.
# @see CommaSequence#do_extend
def do_extend(extends, parent_directives, replace, seen, original)
extended_not_expanded = members.map do |sseq_or_op|
next [[sseq_or_op]] unless sseq_or_op.is_a?(SimpleSequence)
extended = sseq_or_op.do_extend(extends, parent_directives, replace, seen)
# The First Law of Extend says that the generated selector should have
# specificity greater than or equal to that of the original selector.
# In order to ensure that, we record the original selector's
# (`extended.first`) original specificity.
extended.first.add_sources!([self]) if original && !invisible?
extended.map {|seq| seq.members}
end
weaves = Sass::Util.paths(extended_not_expanded).map {|path| weave(path)}
trim(weaves).map {|p| Sequence.new(p)}
end
# Unifies this with another selector sequence to produce a selector
# that matches (a subset of) the intersection of the two inputs.
#
# @param other [Sequence]
# @return [CommaSequence, nil] The unified selector, or nil if unification failed.
# @raise [Sass::SyntaxError] If this selector cannot be unified.
# This will only ever occur when a dynamic selector,
# such as {Parent} or {Interpolation}, is used in unification.
# Since these selectors should be resolved
# by the time extension and unification happen,
# this exception will only ever be raised as a result of programmer error
def unify(other)
base = members.last
other_base = other.members.last
return unless base.is_a?(SimpleSequence) && other_base.is_a?(SimpleSequence)
return unless (unified = other_base.unify(base))
woven = weave([members[0...-1], other.members[0...-1] + [unified]])
CommaSequence.new(woven.map {|w| Sequence.new(w)})
end
# Returns whether or not this selector matches all elements
# that the given selector matches (as well as possibly more).
#
# @example
# (.foo).superselector?(.foo.bar) #=> true
# (.foo).superselector?(.bar) #=> false
# @param cseq [Sequence]
# @return [Boolean]
def superselector?(seq)
_superselector?(members, seq.members)
end
# @see AbstractSequence#to_s
def to_s(opts = {})
@members.map {|m| m.is_a?(String) ? m : m.to_s(opts)}.join(" ").gsub(/ ?\n ?/, "\n")
end
# Returns a string representation of the sequence.
# This is basically the selector string.
#
# @return [String]
def inspect
members.map {|m| m.inspect}.join(" ")
end
# Add to the {SimpleSequence#sources} sets of the child simple sequences.
# This destructively modifies this sequence's members array, but not the
# child simple sequences.
#
# @param sources [Set<Sequence>]
def add_sources!(sources)
members.map! {|m| m.is_a?(SimpleSequence) ? m.with_more_sources(sources) : m}
end
# Converts the subject operator "!", if it exists, into a ":has()"
# selector.
#
# @retur [Sequence]
def subjectless
pre_subject = []
has = []
subject = nil
members.each do |sseq_or_op|
if subject
has << sseq_or_op
elsif sseq_or_op.is_a?(String) || !sseq_or_op.subject?
pre_subject << sseq_or_op
else
subject = sseq_or_op.dup
subject.members = sseq_or_op.members.dup
subject.subject = false
has = []
end
end
return self unless subject
unless has.empty?
subject.members << Pseudo.new(:class, 'has', nil, CommaSequence.new([Sequence.new(has)]))
end
Sequence.new(pre_subject + [subject])
end
private
# Conceptually, this expands "parenthesized selectors". That is, if we
# have `.A .B {@extend .C}` and `.D .C {...}`, this conceptually expands
# into `.D .C, .D (.A .B)`, and this function translates `.D (.A .B)` into
# `.D .A .B, .A .D .B`. For thoroughness, `.A.D .B` would also be
# required, but including merged selectors results in exponential output
# for very little gain.
#
# @param path [Array<Array<SimpleSequence or String>>]
# A list of parenthesized selector groups.
# @return [Array<Array<SimpleSequence or String>>] A list of fully-expanded selectors.
def weave(path)
# This function works by moving through the selector path left-to-right,
# building all possible prefixes simultaneously.
prefixes = [[]]
path.each do |current|
next if current.empty?
current = current.dup
last_current = [current.pop]
prefixes = prefixes.map do |prefix|
sub = subweave(prefix, current)
next [] unless sub
sub.map {|seqs| seqs + last_current}
end.flatten(1)
end
prefixes
end
# This interweaves two lists of selectors,
# returning all possible orderings of them (including using unification)
# that maintain the relative ordering of the input arrays.
#
# For example, given `.foo .bar` and `.baz .bang`,
# this would return `.foo .bar .baz .bang`, `.foo .bar.baz .bang`,
# `.foo .baz .bar .bang`, `.foo .baz .bar.bang`, `.foo .baz .bang .bar`,
# and so on until `.baz .bang .foo .bar`.
#
# Semantically, for selectors A and B, this returns all selectors `AB_i`
# such that the union over all i of elements matched by `AB_i X` is
# identical to the intersection of all elements matched by `A X` and all
# elements matched by `B X`. Some `AB_i` are elided to reduce the size of
# the output.
#
# @param seq1 [Array<SimpleSequence or String>]
# @param seq2 [Array<SimpleSequence or String>]
# @return [Array<Array<SimpleSequence or String>>]
def subweave(seq1, seq2)
return [seq2] if seq1.empty?
return [seq1] if seq2.empty?
seq1, seq2 = seq1.dup, seq2.dup
return unless (init = merge_initial_ops(seq1, seq2))
return unless (fin = merge_final_ops(seq1, seq2))
# Make sure there's only one root selector in the output.
root1 = has_root?(seq1.first) && seq1.shift
root2 = has_root?(seq2.first) && seq2.shift
if root1 && root2
return unless (root = root1.unify(root2))
seq1.unshift root
seq2.unshift root
elsif root1
seq2.unshift root1
elsif root2
seq1.unshift root2
end
seq1 = group_selectors(seq1)
seq2 = group_selectors(seq2)
lcs = Sass::Util.lcs(seq2, seq1) do |s1, s2|
next s1 if s1 == s2
next unless s1.first.is_a?(SimpleSequence) && s2.first.is_a?(SimpleSequence)
next s2 if parent_superselector?(s1, s2)
next s1 if parent_superselector?(s2, s1)
next unless must_unify?(s1, s2)
next unless (unified = Sequence.new(s1).unify(Sequence.new(s2)))
unified.members.first.members if unified.members.length == 1
end
diff = [[init]]
until lcs.empty?
diff << chunks(seq1, seq2) {|s| parent_superselector?(s.first, lcs.first)} << [lcs.shift]
seq1.shift
seq2.shift
end
diff << chunks(seq1, seq2) {|s| s.empty?}
diff += fin.map {|sel| sel.is_a?(Array) ? sel : [sel]}
diff.reject! {|c| c.empty?}
Sass::Util.paths(diff).map {|p| p.flatten}.reject {|p| path_has_two_subjects?(p)}
end
# Extracts initial selector combinators (`"+"`, `">"`, `"~"`, and `"\n"`)
# from two sequences and merges them together into a single array of
# selector combinators.
#
# @param seq1 [Array<SimpleSequence or String>]
# @param seq2 [Array<SimpleSequence or String>]
# @return [Array<String>, nil] If there are no operators in the merged
# sequence, this will be the empty array. If the operators cannot be
# merged, this will be nil.
def merge_initial_ops(seq1, seq2)
ops1, ops2 = [], []
ops1 << seq1.shift while seq1.first.is_a?(String)
ops2 << seq2.shift while seq2.first.is_a?(String)
newline = false
newline ||= !!ops1.shift if ops1.first == "\n"
newline ||= !!ops2.shift if ops2.first == "\n"
# If neither sequence is a subsequence of the other, they cannot be
# merged successfully
lcs = Sass::Util.lcs(ops1, ops2)
return unless lcs == ops1 || lcs == ops2
(newline ? ["\n"] : []) + (ops1.size > ops2.size ? ops1 : ops2)
end
# Extracts final selector combinators (`"+"`, `">"`, `"~"`) and the
# selectors to which they apply from two sequences and merges them
# together into a single array.
#
# @param seq1 [Array<SimpleSequence or String>]
# @param seq2 [Array<SimpleSequence or String>]
# @return [Array<SimpleSequence or String or
# Array<Array<SimpleSequence or String>>]
# If there are no trailing combinators to be merged, this will be the
# empty array. If the trailing combinators cannot be merged, this will
# be nil. Otherwise, this will contained the merged selector. Array
# elements are [Sass::Util#paths]-style options; conceptually, an "or"
# of multiple selectors.
def merge_final_ops(seq1, seq2, res = [])
ops1, ops2 = [], []
ops1 << seq1.pop while seq1.last.is_a?(String)
ops2 << seq2.pop while seq2.last.is_a?(String)
# Not worth the headache of trying to preserve newlines here. The most
# important use of newlines is at the beginning of the selector to wrap
# across lines anyway.
ops1.reject! {|o| o == "\n"}
ops2.reject! {|o| o == "\n"}
return res if ops1.empty? && ops2.empty?
if ops1.size > 1 || ops2.size > 1
# If there are multiple operators, something hacky's going on. If one
# is a supersequence of the other, use that, otherwise give up.
lcs = Sass::Util.lcs(ops1, ops2)
return unless lcs == ops1 || lcs == ops2
res.unshift(*(ops1.size > ops2.size ? ops1 : ops2).reverse)
return res
end
# This code looks complicated, but it's actually just a bunch of special
# cases for interactions between different combinators.
op1, op2 = ops1.first, ops2.first
if op1 && op2
sel1 = seq1.pop
sel2 = seq2.pop
if op1 == '~' && op2 == '~'
if sel1.superselector?(sel2)
res.unshift sel2, '~'
elsif sel2.superselector?(sel1)
res.unshift sel1, '~'
else
merged = sel1.unify(sel2)
res.unshift [
[sel1, '~', sel2, '~'],
[sel2, '~', sel1, '~'],
([merged, '~'] if merged)
].compact
end
elsif (op1 == '~' && op2 == '+') || (op1 == '+' && op2 == '~')
if op1 == '~'
tilde_sel, plus_sel = sel1, sel2
else
tilde_sel, plus_sel = sel2, sel1
end
if tilde_sel.superselector?(plus_sel)
res.unshift plus_sel, '+'
else
merged = plus_sel.unify(tilde_sel)
res.unshift [
[tilde_sel, '~', plus_sel, '+'],
([merged, '+'] if merged)
].compact
end
elsif op1 == '>' && %w(~ +).include?(op2)
res.unshift sel2, op2
seq1.push sel1, op1
elsif op2 == '>' && %w(~ +).include?(op1)
res.unshift sel1, op1
seq2.push sel2, op2
elsif op1 == op2
merged = sel1.unify(sel2)
return unless merged
res.unshift merged, op1
else
# Unknown selector combinators can't be unified
return
end
return merge_final_ops(seq1, seq2, res)
elsif op1
seq2.pop if op1 == '>' && seq2.last && seq2.last.superselector?(seq1.last)
res.unshift seq1.pop, op1
return merge_final_ops(seq1, seq2, res)
else # op2
seq1.pop if op2 == '>' && seq1.last && seq1.last.superselector?(seq2.last)
res.unshift seq2.pop, op2
return merge_final_ops(seq1, seq2, res)
end
end
# Takes initial subsequences of `seq1` and `seq2` and returns all
# orderings of those subsequences. The initial subsequences are determined
# by a block.
#
# Destructively removes the initial subsequences of `seq1` and `seq2`.
#
# For example, given `(A B C | D E)` and `(1 2 | 3 4 5)` (with `|`
# denoting the boundary of the initial subsequence), this would return
# `[(A B C 1 2), (1 2 A B C)]`. The sequences would then be `(D E)` and
# `(3 4 5)`.
#
# @param seq1 [Array]
# @param seq2 [Array]
# @yield [a] Used to determine when to cut off the initial subsequences.
# Called repeatedly for each sequence until it returns true.
# @yieldparam a [Array] A final subsequence of one input sequence after
# cutting off some initial subsequence.
# @yieldreturn [Boolean] Whether or not to cut off the initial subsequence
# here.
# @return [Array<Array>] All possible orderings of the initial subsequences.
def chunks(seq1, seq2)
chunk1 = []
chunk1 << seq1.shift until yield seq1
chunk2 = []
chunk2 << seq2.shift until yield seq2
return [] if chunk1.empty? && chunk2.empty?
return [chunk2] if chunk1.empty?
return [chunk1] if chunk2.empty?
[chunk1 + chunk2, chunk2 + chunk1]
end
# Groups a sequence into subsequences. The subsequences are determined by
# strings; adjacent non-string elements will be put into separate groups,
# but any element adjacent to a string will be grouped with that string.
#
# For example, `(A B "C" D E "F" G "H" "I" J)` will become `[(A) (B "C" D)
# (E "F" G "H" "I" J)]`.
#
# @param seq [Array]
# @return [Array<Array>]
def group_selectors(seq)
newseq = []
tail = seq.dup
until tail.empty?
head = []
begin
head << tail.shift
end while !tail.empty? && head.last.is_a?(String) || tail.first.is_a?(String)
newseq << head
end
newseq
end
# Given two selector sequences, returns whether `seq1` is a
# superselector of `seq2`; that is, whether `seq1` matches every
# element `seq2` matches.
#
# @param seq1 [Array<SimpleSequence or String>]
# @param seq2 [Array<SimpleSequence or String>]
# @return [Boolean]
def _superselector?(seq1, seq2)
seq1 = seq1.reject {|e| e == "\n"}
seq2 = seq2.reject {|e| e == "\n"}
# Selectors with leading or trailing operators are neither
# superselectors nor subselectors.
return if seq1.last.is_a?(String) || seq2.last.is_a?(String) ||
seq1.first.is_a?(String) || seq2.first.is_a?(String)
# More complex selectors are never superselectors of less complex ones
return if seq1.size > seq2.size
return seq1.first.superselector?(seq2.last, seq2[0...-1]) if seq1.size == 1
_, si = seq2.each_with_index.find do |e, i|
return if i == seq2.size - 1
next if e.is_a?(String)
seq1.first.superselector?(e, seq2[0...i])
end
return unless si
if seq1[1].is_a?(String)
return unless seq2[si + 1].is_a?(String)
# .foo ~ .bar is a superselector of .foo + .bar
return unless seq1[1] == "~" ? seq2[si + 1] != ">" : seq1[1] == seq2[si + 1]
# .foo > .baz is not a superselector of .foo > .bar > .baz or .foo >
# .bar .baz, despite the fact that .baz is a superselector of .bar >
# .baz and .bar .baz. Same goes for + and ~.
return if seq1.length == 3 && seq2.length > 3
return _superselector?(seq1[2..-1], seq2[si + 2..-1])
elsif seq2[si + 1].is_a?(String)
return unless seq2[si + 1] == ">"
return _superselector?(seq1[1..-1], seq2[si + 2..-1])
else
return _superselector?(seq1[1..-1], seq2[si + 1..-1])
end
end
# Like \{#_superselector?}, but compares the selectors in the
# context of parent selectors, as though they shared an implicit
# base simple selector. For example, `B` is not normally a
# superselector of `B A`, since it doesn't match `A` elements.
# However, it is a parent superselector, since `B X` is a
# superselector of `B A X`.
#
# @param seq1 [Array<SimpleSequence or String>]
# @param seq2 [Array<SimpleSequence or String>]
# @return [Boolean]
def parent_superselector?(seq1, seq2)
base = Sass::Selector::SimpleSequence.new([Sass::Selector::Placeholder.new('<temp>')],
false)
_superselector?(seq1 + [base], seq2 + [base])
end
# Returns whether two selectors must be unified to produce a valid
# combined selector. This is true when both selectors contain the same
# unique simple selector such as an id.
#
# @param seq1 [Array<SimpleSequence or String>]
# @param seq2 [Array<SimpleSequence or String>]
# @return [Boolean]
def must_unify?(seq1, seq2)
unique_selectors = seq1.map do |sseq|
next [] if sseq.is_a?(String)
sseq.members.select {|sel| sel.unique?}
end.flatten.to_set
return false if unique_selectors.empty?
seq2.any? do |sseq|
next false if sseq.is_a?(String)
sseq.members.any? do |sel|
next unless sel.unique?
unique_selectors.include?(sel)
end
end
end
# Removes redundant selectors from between multiple lists of
# selectors. This takes a list of lists of selector sequences;
# each individual list is assumed to have no redundancy within
# itself. A selector is only removed if it's redundant with a
# selector in another list.
#
# "Redundant" here means that one selector is a superselector of
# the other. The more specific selector is removed.
#
# @param seqses [Array<Array<Array<SimpleSequence or String>>>]
# @return [Array<Array<SimpleSequence or String>>]
def trim(seqses)
# Avoid truly horrific quadratic behavior. TODO: I think there
# may be a way to get perfect trimming without going quadratic.
return seqses.flatten(1) if seqses.size > 100
# Keep the results in a separate array so we can be sure we aren't
# comparing against an already-trimmed selector. This ensures that two
# identical selectors don't mutually trim one another.
result = seqses.dup
# This is n^2 on the sequences, but only comparing between
# separate sequences should limit the quadratic behavior.
seqses.each_with_index do |seqs1, i|
result[i] = seqs1.reject do |seq1|
# The maximum specificity of the sources that caused [seq1] to be
# generated. In order for [seq1] to be removed, there must be
# another selector that's a superselector of it *and* that has
# specificity greater or equal to this.
max_spec = _sources(seq1).map do |seq|
spec = seq.specificity
spec.is_a?(Range) ? spec.max : spec
end.max || 0
result.any? do |seqs2|
next if seqs1.equal?(seqs2)
# Second Law of Extend: the specificity of a generated selector
# should never be less than the specificity of the extending
# selector.
#
# See https://github.com/nex3/sass/issues/324.
seqs2.any? do |seq2|
spec2 = _specificity(seq2)
spec2 = spec2.begin if spec2.is_a?(Range)
spec2 >= max_spec && _superselector?(seq2, seq1)
end
end
end
end
result.flatten(1)
end
def _hash
members.reject {|m| m == "\n"}.hash
end
def _eql?(other)
other.members.reject {|m| m == "\n"}.eql?(members.reject {|m| m == "\n"})
end
def path_has_two_subjects?(path)
subject = false
path.each do |sseq_or_op|
next unless sseq_or_op.is_a?(SimpleSequence)
next unless sseq_or_op.subject?
return true if subject
subject = true
end
false
end
def _sources(seq)
s = Set.new
seq.map {|sseq_or_op| s.merge sseq_or_op.sources if sseq_or_op.is_a?(SimpleSequence)}
s
end
def extended_not_expanded_to_s(extended_not_expanded)
extended_not_expanded.map do |choices|
choices = choices.map do |sel|
next sel.first.to_s if sel.size == 1
"#{sel.join ' '}"
end
next choices.first if choices.size == 1 && !choices.include?(' ')
"(#{choices.join ', '})"
end.join ' '
end
def has_root?(sseq)
sseq.is_a?(SimpleSequence) &&
sseq.members.any? {|sel| sel.is_a?(Pseudo) && sel.normalized_name == "root"}
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/selector/simple.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/selector/simple.rb | module Sass
module Selector
# The abstract superclass for simple selectors
# (that is, those that don't compose multiple selectors).
class Simple
# The line of the Sass template on which this selector was declared.
#
# @return [Integer]
attr_accessor :line
# The name of the file in which this selector was declared,
# or `nil` if it was not declared in a file (e.g. on stdin).
#
# @return [String, nil]
attr_accessor :filename
# Whether only one instance of this simple selector is allowed in a given
# complex selector.
#
# @return [Boolean]
def unique?
false
end
# @see #to_s
#
# @return [String]
def inspect
to_s
end
# Returns the selector string.
#
# @param opts [Hash] rendering options.
# @option opts [Symbol] :style The css rendering style.
# @return [String]
def to_s(opts = {})
Sass::Util.abstract(self)
end
# Returns a hash code for this selector object.
#
# By default, this is based on the value of \{#to\_a},
# so if that contains information irrelevant to the identity of the selector,
# this should be overridden.
#
# @return [Integer]
def hash
@_hash ||= equality_key.hash
end
# Checks equality between this and another object.
#
# By default, this is based on the value of \{#to\_a},
# so if that contains information irrelevant to the identity of the selector,
# this should be overridden.
#
# @param other [Object] The object to test equality against
# @return [Boolean] Whether or not this is equal to `other`
def eql?(other)
other.class == self.class && other.hash == hash && other.equality_key == equality_key
end
alias_method :==, :eql?
# Unifies this selector with a {SimpleSequence}'s {SimpleSequence#members members array},
# returning another `SimpleSequence` members array
# that matches both this selector and the input selector.
#
# By default, this just appends this selector to the end of the array
# (or returns the original array if this selector already exists in it).
#
# @param sels [Array<Simple>] A {SimpleSequence}'s {SimpleSequence#members members array}
# @return [Array<Simple>, nil] A {SimpleSequence} {SimpleSequence#members members array}
# matching both `sels` and this selector,
# or `nil` if this is impossible (e.g. unifying `#foo` and `#bar`)
# @raise [Sass::SyntaxError] If this selector cannot be unified.
# This will only ever occur when a dynamic selector,
# such as {Parent} or {Interpolation}, is used in unification.
# Since these selectors should be resolved
# by the time extension and unification happen,
# this exception will only ever be raised as a result of programmer error
def unify(sels)
return sels.first.unify([self]) if sels.length == 1 && sels.first.is_a?(Universal)
return sels if sels.any? {|sel2| eql?(sel2)}
if !is_a?(Pseudo) || (sels.last.is_a?(Pseudo) && sels.last.type == :element)
_, i = sels.each_with_index.find {|sel, _| sel.is_a?(Pseudo)}
end
return sels + [self] unless i
sels[0...i] + [self] + sels[i..-1]
end
protected
# Returns the key used for testing whether selectors are equal.
#
# This is a cached version of \{#to\_s}.
#
# @return [String]
def equality_key
@equality_key ||= to_s
end
# Unifies two namespaces,
# returning a namespace that works for both of them if possible.
#
# @param ns1 [String, nil] The first namespace.
# `nil` means none specified, e.g. `foo`.
# The empty string means no namespace specified, e.g. `|foo`.
# `"*"` means any namespace is allowed, e.g. `*|foo`.
# @param ns2 [String, nil] The second namespace. See `ns1`.
# @return [Array(String or nil, Boolean)]
# The first value is the unified namespace, or `nil` for no namespace.
# The second value is whether or not a namespace that works for both inputs
# could be found at all.
# If the second value is `false`, the first should be ignored.
def unify_namespaces(ns1, ns2)
return ns2, true if ns1 == '*'
return ns1, true if ns2 == '*'
return nil, false unless ns1 == ns2
[ns1, true]
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/selector/pseudo.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/selector/pseudo.rb | # coding: utf-8
module Sass
module Selector
# A pseudoclass (e.g. `:visited`) or pseudoelement (e.g. `::first-line`)
# selector. It can have arguments (e.g. `:nth-child(2n+1)`) which can
# contain selectors (e.g. `:nth-child(2n+1 of .foo)`).
class Pseudo < Simple
# Some pseudo-class-syntax selectors are actually considered
# pseudo-elements and must be treated differently. This is a list of such
# selectors.
#
# @return [Set<String>]
ACTUALLY_ELEMENTS = %w(after before first-line first-letter).to_set
# Like \{#type}, but returns the type of selector this looks like, rather
# than the type it is semantically. This only differs from type for
# selectors in \{ACTUALLY\_ELEMENTS}.
#
# @return [Symbol]
attr_reader :syntactic_type
# The name of the selector.
#
# @return [String]
attr_reader :name
# The argument to the selector,
# or `nil` if no argument was given.
#
# @return [String, nil]
attr_reader :arg
# The selector argument, or `nil` if no selector exists.
#
# If this and \{#arg\} are both set, \{#arg\} is considered a non-selector
# prefix.
#
# @return [CommaSequence]
attr_reader :selector
# @param syntactic_type [Symbol] See \{#syntactic_type}
# @param name [String] See \{#name}
# @param arg [nil, String] See \{#arg}
# @param selector [nil, CommaSequence] See \{#selector}
def initialize(syntactic_type, name, arg, selector)
@syntactic_type = syntactic_type
@name = name
@arg = arg
@selector = selector
end
def unique?
type == :class && normalized_name == 'root'
end
# Whether or not this selector should be hidden due to containing a
# placeholder.
def invisible?
# :not() is a special case—if you eliminate all the placeholders from
# it, it should match anything.
name != 'not' && @selector && @selector.members.all? {|s| s.invisible?}
end
# Returns a copy of this with \{#selector} set to \{#new\_selector}.
#
# @param new_selector [CommaSequence]
# @return [Array<Simple>]
def with_selector(new_selector)
result = Pseudo.new(syntactic_type, name, arg,
CommaSequence.new(new_selector.members.map do |seq|
next seq unless seq.members.length == 1
sseq = seq.members.first
next seq unless sseq.is_a?(SimpleSequence) && sseq.members.length == 1
sel = sseq.members.first
next seq unless sel.is_a?(Pseudo) && sel.selector
case normalized_name
when 'not'
# In theory, if there's a nested :not its contents should be
# unified with the return value. For example, if :not(.foo)
# extends .bar, :not(.bar) should become .foo:not(.bar). However,
# this is a narrow edge case and supporting it properly would make
# this code and the code calling it a lot more complicated, so
# it's not supported for now.
next [] unless sel.normalized_name == 'matches'
sel.selector.members
when 'matches', 'any', 'current', 'nth-child', 'nth-last-child'
# As above, we could theoretically support :not within :matches, but
# doing so would require this method and its callers to handle much
# more complex cases that likely aren't worth the pain.
next [] unless sel.name == name && sel.arg == arg
sel.selector.members
when 'has', 'host', 'host-context', 'slotted'
# We can't expand nested selectors here, because each layer adds an
# additional layer of semantics. For example, `:has(:has(img))`
# doesn't match `<div><img></div>` but `:has(img)` does.
sel
else
[]
end
end.flatten))
# Older browsers support :not but only with a single complex selector.
# In order to support those browsers, we break up the contents of a :not
# unless it originally contained a selector list.
return [result] unless normalized_name == 'not'
return [result] if selector.members.length > 1
result.selector.members.map do |seq|
Pseudo.new(syntactic_type, name, arg, CommaSequence.new([seq]))
end
end
# The type of the selector. `:class` if this is a pseudoclass selector,
# `:element` if it's a pseudoelement.
#
# @return [Symbol]
def type
ACTUALLY_ELEMENTS.include?(normalized_name) ? :element : syntactic_type
end
# Like \{#name\}, but without any vendor prefix.
#
# @return [String]
def normalized_name
@normalized_name ||= name.gsub(/^-[a-zA-Z0-9]+-/, '')
end
# @see Selector#to_s
def to_s(opts = {})
# :not() is a special case, because :not(<nothing>) should match
# everything.
return '' if name == 'not' && @selector && @selector.members.all? {|m| m.invisible?}
res = (syntactic_type == :class ? ":" : "::") + @name
if @arg || @selector
res << "("
res << @arg.strip if @arg
res << " " if @arg && @selector
res << @selector.to_s(opts) if @selector
res << ")"
end
res
end
# Returns `nil` if this is a pseudoelement selector
# and `sels` contains a pseudoelement selector different than this one.
#
# @see SimpleSequence#unify
def unify(sels)
return if type == :element && sels.any? do |sel|
sel.is_a?(Pseudo) && sel.type == :element &&
(sel.name != name || sel.arg != arg || sel.selector != selector)
end
super
end
# Returns whether or not this selector matches all elements
# that the given selector matches (as well as possibly more).
#
# @example
# (.foo).superselector?(.foo.bar) #=> true
# (.foo).superselector?(.bar) #=> false
# @param their_sseq [SimpleSequence]
# @param parents [Array<SimpleSequence, String>] The parent selectors of `their_sseq`, if any.
# @return [Boolean]
def superselector?(their_sseq, parents = [])
case normalized_name
when 'matches', 'any'
# :matches can be a superselector of another selector in one of two
# ways. Either its constituent selectors can be a superset of those of
# another :matches in the other selector, or any of its constituent
# selectors can individually be a superselector of the other selector.
(their_sseq.selector_pseudo_classes[normalized_name] || []).any? do |their_sel|
next false unless their_sel.is_a?(Pseudo)
next false unless their_sel.name == name
selector.superselector?(their_sel.selector)
end || selector.members.any? do |our_seq|
their_seq = Sequence.new(parents + [their_sseq])
our_seq.superselector?(their_seq)
end
when 'has', 'host', 'host-context', 'slotted'
# Like :matches, :has (et al) can be a superselector of another
# selector if its constituent selectors are a superset of those of
# another :has in the other selector. However, the :matches other case
# doesn't work, because :has refers to nested elements.
(their_sseq.selector_pseudo_classes[normalized_name] || []).any? do |their_sel|
next false unless their_sel.is_a?(Pseudo)
next false unless their_sel.name == name
selector.superselector?(their_sel.selector)
end
when 'not'
selector.members.all? do |our_seq|
their_sseq.members.any? do |their_sel|
if their_sel.is_a?(Element) || their_sel.is_a?(Id)
# `:not(a)` is a superselector of `h1` and `:not(#foo)` is a
# superselector of `#bar`.
our_sseq = our_seq.members.last
next false unless our_sseq.is_a?(SimpleSequence)
our_sseq.members.any? do |our_sel|
our_sel.class == their_sel.class && our_sel != their_sel
end
else
next false unless their_sel.is_a?(Pseudo)
next false unless their_sel.name == name
# :not(X) is a superselector of :not(Y) exactly when Y is a
# superselector of X.
their_sel.selector.superselector?(CommaSequence.new([our_seq]))
end
end
end
when 'current'
(their_sseq.selector_pseudo_classes['current'] || []).any? do |their_current|
next false if their_current.name != name
# Explicitly don't check for nested superselector relationships
# here. :current(.foo) isn't always a superselector of
# :current(.foo.bar), since it matches the *innermost* ancestor of
# the current element that matches the selector. For example:
#
# <div class="foo bar">
# <p class="foo">
# <span>current element</span>
# </p>
# </div>
#
# Here :current(.foo) would match the p element and *not* the div
# element, whereas :current(.foo.bar) would match the div and not
# the p.
selector == their_current.selector
end
when 'nth-child', 'nth-last-child'
their_sseq.members.any? do |their_sel|
# This misses a few edge cases. For example, `:nth-child(n of X)`
# is a superselector of `X`, and `:nth-child(2n of X)` is a
# superselector of `:nth-child(4n of X)`. These seem rare enough
# not to be worth worrying about, though.
next false unless their_sel.is_a?(Pseudo)
next false unless their_sel.name == name
next false unless their_sel.arg == arg
selector.superselector?(their_sel.selector)
end
else
throw "[BUG] Unknown selector pseudo class #{name}"
end
end
# @see AbstractSequence#specificity
def specificity
return 1 if type == :element
return SPECIFICITY_BASE unless selector
@specificity ||=
if normalized_name == 'not'
min = 0
max = 0
selector.members.each do |seq|
spec = seq.specificity
if spec.is_a?(Range)
min = Sass::Util.max(spec.begin, min)
max = Sass::Util.max(spec.end, max)
else
min = Sass::Util.max(spec, min)
max = Sass::Util.max(spec, max)
end
end
min == max ? max : (min..max)
else
min = 0
max = 0
selector.members.each do |seq|
spec = seq.specificity
if spec.is_a?(Range)
min = Sass::Util.min(spec.begin, min)
max = Sass::Util.max(spec.end, max)
else
min = Sass::Util.min(spec, min)
max = Sass::Util.max(spec, max)
end
end
min == max ? max : (min..max)
end
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value.rb | module Sass::Script::Value; end
require 'sass/script/value/base'
require 'sass/script/value/string'
require 'sass/script/value/number'
require 'sass/script/value/color'
require 'sass/script/value/bool'
require 'sass/script/value/null'
require 'sass/script/value/list'
require 'sass/script/value/arg_list'
require 'sass/script/value/map'
require 'sass/script/value/callable'
require 'sass/script/value/function'
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree.rb | # The module containing nodes in the SassScript parse tree. These nodes are
# all subclasses of {Sass::Script::Tree::Node}.
module Sass::Script::Tree
end
require 'sass/script/tree/node'
require 'sass/script/tree/variable'
require 'sass/script/tree/funcall'
require 'sass/script/tree/operation'
require 'sass/script/tree/unary_operation'
require 'sass/script/tree/interpolation'
require 'sass/script/tree/string_interpolation'
require 'sass/script/tree/literal'
require 'sass/script/tree/list_literal'
require 'sass/script/tree/map_literal'
require 'sass/script/tree/selector'
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/css_parser.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/css_parser.rb | require 'sass/script'
require 'sass/script/css_lexer'
module Sass
module Script
# This is a subclass of {Parser} for use in parsing plain CSS properties.
#
# @see Sass::SCSS::CssParser
class CssParser < Parser
private
# @private
def lexer_class; CssLexer; end
# We need a production that only does /,
# since * and % aren't allowed in plain CSS
production :div, :unary_plus, :div
def string
tok = try_tok(:string)
return number unless tok
return if @lexer.peek && @lexer.peek.type == :begin_interpolation
literal_node(tok.value, tok.source_range)
end
# Short-circuit all the SassScript-only productions
alias_method :interpolation, :space
alias_method :or_expr, :div
alias_method :unary_div, :ident
alias_method :paren, :string
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/parser.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/parser.rb | require 'sass/script/lexer'
module Sass
module Script
# The parser for SassScript.
# It parses a string of code into a tree of {Script::Tree::Node}s.
class Parser
# The line number of the parser's current position.
#
# @return [Integer]
def line
@lexer.line
end
# The column number of the parser's current position.
#
# @return [Integer]
def offset
@lexer.offset
end
# @param str [String, StringScanner] The source text to parse
# @param line [Integer] The line on which the SassScript appears.
# Used for error reporting and sourcemap building
# @param offset [Integer] The character (not byte) offset where the script starts in the line.
# Used for error reporting and sourcemap building
# @param options [{Symbol => Object}] An options hash; see
# {file:SASS_REFERENCE.md#Options the Sass options documentation}.
# This supports an additional `:allow_extra_text` option that controls
# whether the parser throws an error when extra text is encountered
# after the parsed construct.
def initialize(str, line, offset, options = {})
@options = options
@allow_extra_text = options.delete(:allow_extra_text)
@lexer = lexer_class.new(str, line, offset, options)
@stop_at = nil
end
# Parses a SassScript expression within an interpolated segment (`#{}`).
# This means that it stops when it comes across an unmatched `}`,
# which signals the end of an interpolated segment,
# it returns rather than throwing an error.
#
# @param warn_for_color [Boolean] Whether raw color values passed to
# interoplation should cause a warning.
# @return [Script::Tree::Node] The root node of the parse tree
# @raise [Sass::SyntaxError] if the expression isn't valid SassScript
def parse_interpolated(warn_for_color = false)
# Start two characters back to compensate for #{
start_pos = Sass::Source::Position.new(line, offset - 2)
expr = assert_expr :expr
assert_tok :end_interpolation
expr = Sass::Script::Tree::Interpolation.new(
nil, expr, nil, false, false, :warn_for_color => warn_for_color)
check_for_interpolation expr
expr.options = @options
node(expr, start_pos)
rescue Sass::SyntaxError => e
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
raise e
end
# Parses a SassScript expression.
#
# @return [Script::Tree::Node] The root node of the parse tree
# @raise [Sass::SyntaxError] if the expression isn't valid SassScript
def parse
expr = assert_expr :expr
assert_done
expr.options = @options
check_for_interpolation expr
expr
rescue Sass::SyntaxError => e
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
raise e
end
# Parses a SassScript expression,
# ending it when it encounters one of the given identifier tokens.
#
# @param tokens [#include?(String)] A set of strings that delimit the expression.
# @return [Script::Tree::Node] The root node of the parse tree
# @raise [Sass::SyntaxError] if the expression isn't valid SassScript
def parse_until(tokens)
@stop_at = tokens
expr = assert_expr :expr
assert_done
expr.options = @options
check_for_interpolation expr
expr
rescue Sass::SyntaxError => e
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
raise e
end
# Parses the argument list for a mixin include.
#
# @return [(Array<Script::Tree::Node>,
# {String => Script::Tree::Node},
# Script::Tree::Node,
# Script::Tree::Node)]
# The root nodes of the positional arguments, keyword arguments, and
# splat argument(s). Keyword arguments are in a hash from names to values.
# @raise [Sass::SyntaxError] if the argument list isn't valid SassScript
def parse_mixin_include_arglist
args, keywords = [], {}
if try_tok(:lparen)
args, keywords, splat, kwarg_splat = mixin_arglist
assert_tok(:rparen)
end
assert_done
args.each do |a|
check_for_interpolation a
a.options = @options
end
keywords.each do |_, v|
check_for_interpolation v
v.options = @options
end
if splat
check_for_interpolation splat
splat.options = @options
end
if kwarg_splat
check_for_interpolation kwarg_splat
kwarg_splat.options = @options
end
return args, keywords, splat, kwarg_splat
rescue Sass::SyntaxError => e
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
raise e
end
# Parses the argument list for a mixin definition.
#
# @return [(Array<Script::Tree::Node>, Script::Tree::Node)]
# The root nodes of the arguments, and the splat argument.
# @raise [Sass::SyntaxError] if the argument list isn't valid SassScript
def parse_mixin_definition_arglist
args, splat = defn_arglist!(false)
assert_done
args.each do |k, v|
check_for_interpolation k
k.options = @options
if v
check_for_interpolation v
v.options = @options
end
end
if splat
check_for_interpolation splat
splat.options = @options
end
return args, splat
rescue Sass::SyntaxError => e
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
raise e
end
# Parses the argument list for a function definition.
#
# @return [(Array<Script::Tree::Node>, Script::Tree::Node)]
# The root nodes of the arguments, and the splat argument.
# @raise [Sass::SyntaxError] if the argument list isn't valid SassScript
def parse_function_definition_arglist
args, splat = defn_arglist!(true)
assert_done
args.each do |k, v|
check_for_interpolation k
k.options = @options
if v
check_for_interpolation v
v.options = @options
end
end
if splat
check_for_interpolation splat
splat.options = @options
end
return args, splat
rescue Sass::SyntaxError => e
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
raise e
end
# Parse a single string value, possibly containing interpolation.
# Doesn't assert that the scanner is finished after parsing.
#
# @return [Script::Tree::Node] The root node of the parse tree.
# @raise [Sass::SyntaxError] if the string isn't valid SassScript
def parse_string
unless (peek = @lexer.peek) &&
(peek.type == :string ||
(peek.type == :funcall && peek.value.downcase == 'url'))
lexer.expected!("string")
end
expr = assert_expr :funcall
check_for_interpolation expr
expr.options = @options
@lexer.unpeek!
expr
rescue Sass::SyntaxError => e
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
raise e
end
# Parses a SassScript expression.
#
# @overload parse(str, line, offset, filename = nil)
# @return [Script::Tree::Node] The root node of the parse tree
# @see Parser#initialize
# @see Parser#parse
def self.parse(*args)
new(*args).parse
end
PRECEDENCE = [
:comma, :single_eq, :space, :or, :and,
[:eq, :neq],
[:gt, :gte, :lt, :lte],
[:plus, :minus],
[:times, :div, :mod],
]
ASSOCIATIVE = [:plus, :times]
class << self
# Returns an integer representing the precedence
# of the given operator.
# A lower integer indicates a looser binding.
#
# @private
def precedence_of(op)
PRECEDENCE.each_with_index do |e, i|
return i if Array(e).include?(op)
end
raise "[BUG] Unknown operator #{op.inspect}"
end
# Returns whether or not the given operation is associative.
#
# @private
def associative?(op)
ASSOCIATIVE.include?(op)
end
private
# Defines a simple left-associative production.
# name is the name of the production,
# sub is the name of the production beneath it,
# and ops is a list of operators for this precedence level
def production(name, sub, *ops)
class_eval <<RUBY, __FILE__, __LINE__ + 1
def #{name}
interp = try_ops_after_interp(#{ops.inspect}, #{name.inspect})
return interp if interp
return unless e = #{sub}
while tok = try_toks(#{ops.map {|o| o.inspect}.join(', ')})
if interp = try_op_before_interp(tok, e)
other_interp = try_ops_after_interp(#{ops.inspect}, #{name.inspect}, interp)
return interp unless other_interp
return other_interp
end
e = node(Tree::Operation.new(e, assert_expr(#{sub.inspect}), tok.type),
e.source_range.start_pos)
end
e
end
RUBY
end
def unary(op, sub)
class_eval <<RUBY, __FILE__, __LINE__ + 1
def unary_#{op}
return #{sub} unless tok = try_tok(:#{op})
interp = try_op_before_interp(tok)
return interp if interp
start_pos = source_position
node(Tree::UnaryOperation.new(assert_expr(:unary_#{op}), :#{op}), start_pos)
end
RUBY
end
end
private
def source_position
Sass::Source::Position.new(line, offset)
end
def range(start_pos, end_pos = source_position)
Sass::Source::Range.new(start_pos, end_pos, @options[:filename], @options[:importer])
end
# @private
def lexer_class; Lexer; end
def map
start_pos = source_position
e = interpolation
return unless e
return list e, start_pos unless @lexer.peek && @lexer.peek.type == :colon
pair = map_pair(e)
map = node(Sass::Script::Tree::MapLiteral.new([pair]), start_pos)
while try_tok(:comma)
pair = map_pair
return map unless pair
map.pairs << pair
map.source_range.end_pos = map.pairs.last.last.source_range.end_pos
end
map
end
def map_pair(key = nil)
return unless key ||= interpolation
assert_tok :colon
return key, assert_expr(:interpolation)
end
def expr
start_pos = source_position
e = interpolation
return unless e
list e, start_pos
end
def list(first, start_pos)
return first unless @lexer.peek && @lexer.peek.type == :comma
list = node(Sass::Script::Tree::ListLiteral.new([first], separator: :comma), start_pos)
while (tok = try_tok(:comma))
element_before_interp = list.elements.length == 1 ? list.elements.first : list
if (interp = try_op_before_interp(tok, element_before_interp))
other_interp = try_ops_after_interp([:comma], :expr, interp)
return interp unless other_interp
return other_interp
end
return list unless (e = interpolation)
list.elements << e
list.source_range.end_pos = list.elements.last.source_range.end_pos
end
list
end
production :equals, :interpolation, :single_eq
def try_op_before_interp(op, prev = nil, after_interp = false)
return unless @lexer.peek && @lexer.peek.type == :begin_interpolation
unary = !prev && !after_interp
wb = @lexer.whitespace?(op)
str = literal_node(Script::Value::String.new(Lexer::OPERATORS_REVERSE[op.type]),
op.source_range)
deprecation =
case op.type
when :comma; :potential
when :div, :single_eq; :none
when :plus; unary ? :none : :immediate
when :minus; @lexer.whitespace?(@lexer.peek) ? :immediate : :none
else; :immediate
end
interp = node(
Script::Tree::Interpolation.new(
prev, str, nil, wb, false, :originally_text => true, :deprecation => deprecation),
(prev || str).source_range.start_pos)
interpolation(first: interp)
end
def try_ops_after_interp(ops, name, prev = nil)
return unless @lexer.after_interpolation?
op = try_toks(*ops)
return unless op
interp = try_op_before_interp(op, prev, :after_interp)
return interp if interp
wa = @lexer.whitespace?
str = literal_node(Script::Value::String.new(Lexer::OPERATORS_REVERSE[op.type]),
op.source_range)
str.line = @lexer.line
deprecation =
case op.type
when :comma; :potential
when :div, :single_eq; :none
when :minus; @lexer.whitespace?(op) ? :immediate : :none
else; :immediate
end
interp = node(
Script::Tree::Interpolation.new(
prev, str, assert_expr(name), false, wa,
:originally_text => true, :deprecation => deprecation),
(prev || str).source_range.start_pos)
interp
end
def interpolation(first: nil, inner: :space)
e = first || send(inner)
while (interp = try_tok(:begin_interpolation))
wb = @lexer.whitespace?(interp)
char_before = @lexer.char(interp.pos - 1)
mid = assert_expr :expr
assert_tok :end_interpolation
wa = @lexer.whitespace?
char_after = @lexer.char
after = send(inner)
before_deprecation = e.is_a?(Script::Tree::Interpolation) ? e.deprecation : :none
after_deprecation = after.is_a?(Script::Tree::Interpolation) ? after.deprecation : :none
deprecation =
if before_deprecation == :immediate || after_deprecation == :immediate ||
# Warn for #{foo}$var and #{foo}(1) but not #{$foo}1.
(after && !wa && char_after =~ /[$(]/) ||
# Warn for $var#{foo} and (a)#{foo} but not a#{foo}.
(e && !wb && is_unsafe_before?(e, char_before))
:immediate
else
:potential
end
e = node(
Script::Tree::Interpolation.new(e, mid, after, wb, wa, :deprecation => deprecation),
(e || interp).source_range.start_pos)
end
e
end
# Returns whether `expr` is unsafe to include before an interpolation.
#
# @param expr [Node] The expression to check.
# @param char_before [String] The character immediately before the
# interpolation being checked (and presumably the last character of
# `expr`).
# @return [Boolean]
def is_unsafe_before?(expr, char_before)
return char_before == ')' if is_safe_value?(expr)
# Otherwise, it's only safe if it was another interpolation.
!expr.is_a?(Script::Tree::Interpolation)
end
# Returns whether `expr` is safe as the value immediately before an
# interpolation.
#
# It's safe as long as the previous expression is an identifier or number,
# or a list whose last element is also safe.
def is_safe_value?(expr)
return is_safe_value?(expr.elements.last) if expr.is_a?(Script::Tree::ListLiteral)
return false unless expr.is_a?(Script::Tree::Literal)
expr.value.is_a?(Script::Value::Number) ||
(expr.value.is_a?(Script::Value::String) && expr.value.type == :identifier)
end
def space
start_pos = source_position
e = or_expr
return unless e
arr = [e]
while (e = or_expr)
arr << e
end
if arr.size == 1
arr.first
else
node(Sass::Script::Tree::ListLiteral.new(arr, separator: :space), start_pos)
end
end
production :or_expr, :and_expr, :or
production :and_expr, :eq_or_neq, :and
production :eq_or_neq, :relational, :eq, :neq
production :relational, :plus_or_minus, :gt, :gte, :lt, :lte
production :plus_or_minus, :times_div_or_mod, :plus, :minus
production :times_div_or_mod, :unary_plus, :times, :div, :mod
unary :plus, :unary_minus
unary :minus, :unary_div
unary :div, :unary_not # For strings, so /foo/bar works
unary :not, :ident
def ident
return funcall unless @lexer.peek && @lexer.peek.type == :ident
return if @stop_at && @stop_at.include?(@lexer.peek.value)
name = @lexer.next
if (color = Sass::Script::Value::Color::COLOR_NAMES[name.value.downcase])
literal_node(Sass::Script::Value::Color.new(color, name.value), name.source_range)
elsif name.value == "true"
literal_node(Sass::Script::Value::Bool.new(true), name.source_range)
elsif name.value == "false"
literal_node(Sass::Script::Value::Bool.new(false), name.source_range)
elsif name.value == "null"
literal_node(Sass::Script::Value::Null.new, name.source_range)
else
literal_node(Sass::Script::Value::String.new(name.value, :identifier), name.source_range)
end
end
def funcall
tok = try_tok(:funcall)
return raw unless tok
args, keywords, splat, kwarg_splat = fn_arglist
assert_tok(:rparen)
node(Script::Tree::Funcall.new(tok.value, args, keywords, splat, kwarg_splat),
tok.source_range.start_pos, source_position)
end
def defn_arglist!(must_have_parens)
if must_have_parens
assert_tok(:lparen)
else
return [], nil unless try_tok(:lparen)
end
res = []
splat = nil
must_have_default = false
loop do
break if peek_tok(:rparen)
c = assert_tok(:const)
var = node(Script::Tree::Variable.new(c.value), c.source_range)
if try_tok(:colon)
val = assert_expr(:space)
must_have_default = true
elsif try_tok(:splat)
splat = var
break
elsif must_have_default
raise SyntaxError.new(
"Required argument #{var.inspect} must come before any optional arguments.")
end
res << [var, val]
break unless try_tok(:comma)
end
assert_tok(:rparen)
return res, splat
end
def fn_arglist
arglist(:equals, "function argument")
end
def mixin_arglist
arglist(:interpolation, "mixin argument")
end
def arglist(subexpr, description)
args = []
keywords = Sass::Util::NormalizedMap.new
splat = nil
while (e = send(subexpr))
if @lexer.peek && @lexer.peek.type == :colon
name = e
@lexer.expected!("comma") unless name.is_a?(Tree::Variable)
assert_tok(:colon)
value = assert_expr(subexpr, description)
if keywords[name.name]
raise SyntaxError.new("Keyword argument \"#{name.to_sass}\" passed more than once")
end
keywords[name.name] = value
else
if try_tok(:splat)
return args, keywords, splat, e if splat
splat, e = e, nil
elsif splat
raise SyntaxError.new("Only keyword arguments may follow variable arguments (...).")
elsif !keywords.empty?
raise SyntaxError.new("Positional arguments must come before keyword arguments.")
end
args << e if e
end
return args, keywords, splat unless try_tok(:comma)
end
return args, keywords
end
def raw
tok = try_tok(:raw)
return special_fun unless tok
literal_node(Script::Value::String.new(tok.value), tok.source_range)
end
def special_fun
first = try_tok(:special_fun)
return square_list unless first
str = literal_node(first.value, first.source_range)
return str unless try_tok(:string_interpolation)
mid = assert_expr :expr
assert_tok :end_interpolation
last = assert_expr(:special_fun)
node(
Tree::Interpolation.new(str, mid, last, false, false),
first.source_range.start_pos)
end
def square_list
start_pos = source_position
return paren unless try_tok(:lsquare)
space_start_pos = source_position
e = interpolation(inner: :or_expr)
separator = nil
if e
elements = [e]
while (e = interpolation(inner: :or_expr))
elements << e
end
# If there's a comma after a space-separated list, it's actually a
# space-separated list nested in a comma-separated list.
if try_tok(:comma)
e = if elements.length == 1
elements.first
else
node(
Sass::Script::Tree::ListLiteral.new(elements, separator: :space),
space_start_pos)
end
elements = [e]
while (e = space)
elements << e
break unless try_tok(:comma)
end
separator = :comma
else
separator = :space if elements.length > 1
end
else
elements = []
end
assert_tok(:rsquare)
end_pos = source_position
node(Sass::Script::Tree::ListLiteral.new(elements, separator: separator, bracketed: true),
start_pos, end_pos)
end
def paren
return variable unless try_tok(:lparen)
start_pos = source_position
e = map
e.force_division! if e
end_pos = source_position
assert_tok(:rparen)
e || node(Sass::Script::Tree::ListLiteral.new([]), start_pos, end_pos)
end
def variable
start_pos = source_position
c = try_tok(:const)
return string unless c
node(Tree::Variable.new(*c.value), start_pos)
end
def string
first = try_tok(:string)
return number unless first
str = literal_node(first.value, first.source_range)
return str unless try_tok(:string_interpolation)
mid = assert_expr :expr
assert_tok :end_interpolation
last = assert_expr(:string)
node(Tree::StringInterpolation.new(str, mid, last), first.source_range.start_pos)
end
def number
tok = try_tok(:number)
return selector unless tok
num = tok.value
num.options = @options
num.original = num.to_s
literal_node(num, tok.source_range.start_pos)
end
def selector
tok = try_tok(:selector)
return literal unless tok
node(tok.value, tok.source_range.start_pos)
end
def literal
t = try_tok(:color)
return literal_node(t.value, t.source_range) if t
end
# It would be possible to have unified #assert and #try methods,
# but detecting the method/token difference turns out to be quite expensive.
EXPR_NAMES = {
:string => "string",
:default => "expression (e.g. 1px, bold)",
:mixin_arglist => "mixin argument",
:fn_arglist => "function argument",
:splat => "...",
:special_fun => '")"',
}
def assert_expr(name, expected = nil)
e = send(name)
return e if e
@lexer.expected!(expected || EXPR_NAMES[name] || EXPR_NAMES[:default])
end
def assert_tok(name)
# Avoids an array allocation caused by argument globbing in assert_toks.
t = try_tok(name)
return t if t
@lexer.expected!(Lexer::TOKEN_NAMES[name] || name.to_s)
end
def assert_toks(*names)
t = try_toks(*names)
return t if t
@lexer.expected!(names.map {|tok| Lexer::TOKEN_NAMES[tok] || tok}.join(" or "))
end
def peek_tok(name)
# Avoids an array allocation caused by argument globbing in the try_toks method.
peeked = @lexer.peek
peeked && name == peeked.type
end
def try_tok(name)
peek_tok(name) && @lexer.next
end
def try_toks(*names)
peeked = @lexer.peek
peeked && names.include?(peeked.type) && @lexer.next
end
def assert_done
if @allow_extra_text
# If extra text is allowed, just rewind the lexer so that the
# StringScanner is pointing to the end of the parsed text.
@lexer.unpeek!
else
return if @lexer.done?
@lexer.expected!(EXPR_NAMES[:default])
end
end
# @overload node(value, source_range)
# @param value [Sass::Script::Value::Base]
# @param source_range [Sass::Source::Range]
# @overload node(value, start_pos, end_pos = source_position)
# @param value [Sass::Script::Value::Base]
# @param start_pos [Sass::Source::Position]
# @param end_pos [Sass::Source::Position]
def literal_node(value, source_range_or_start_pos, end_pos = source_position)
node(Sass::Script::Tree::Literal.new(value), source_range_or_start_pos, end_pos)
end
# @overload node(node, source_range)
# @param node [Sass::Script::Tree::Node]
# @param source_range [Sass::Source::Range]
# @overload node(node, start_pos, end_pos = source_position)
# @param node [Sass::Script::Tree::Node]
# @param start_pos [Sass::Source::Position]
# @param end_pos [Sass::Source::Position]
def node(node, source_range_or_start_pos, end_pos = source_position)
source_range =
if source_range_or_start_pos.is_a?(Sass::Source::Range)
source_range_or_start_pos
else
range(source_range_or_start_pos, end_pos)
end
node.line = source_range.start_pos.line
node.source_range = source_range
node.filename = @options[:filename]
node
end
# Checks a script node for any immediately-deprecated interpolations, and
# emits warnings for them.
#
# @param node [Sass::Script::Tree::Node]
def check_for_interpolation(node)
nodes = [node]
until nodes.empty?
node = nodes.pop
unless node.is_a?(Sass::Script::Tree::Interpolation) &&
node.deprecation == :immediate
nodes.concat node.children
next
end
interpolation_deprecation(node)
end
end
# Emits a deprecation warning for an interpolation node.
#
# @param node [Sass::Script::Tree::Node]
def interpolation_deprecation(interpolation)
return if @options[:_convert]
location = "on line #{interpolation.line}"
location << " of #{interpolation.filename}" if interpolation.filename
Sass::Util.sass_warn <<WARNING
DEPRECATION WARNING #{location}:
\#{} interpolation near operators will be simplified in a future version of Sass.
To preserve the current behavior, use quotes:
#{interpolation.to_quoted_equivalent.to_sass}
You can use the sass-convert command to automatically fix most cases.
WARNING
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/lexer.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/lexer.rb | require 'sass/scss/rx'
module Sass
module Script
# The lexical analyzer for SassScript.
# It takes a raw string and converts it to individual tokens
# that are easier to parse.
class Lexer
include Sass::SCSS::RX
# A struct containing information about an individual token.
#
# `type`: \[`Symbol`\]
# : The type of token.
#
# `value`: \[`Object`\]
# : The Ruby object corresponding to the value of the token.
#
# `source_range`: \[`Sass::Source::Range`\]
# : The range in the source file in which the token appeared.
#
# `pos`: \[`Integer`\]
# : The scanner position at which the SassScript token appeared.
Token = Struct.new(:type, :value, :source_range, :pos)
# The line number of the lexer's current position.
#
# @return [Integer]
def line
return @line unless @tok
@tok.source_range.start_pos.line
end
# The number of bytes into the current line
# of the lexer's current position (1-based).
#
# @return [Integer]
def offset
return @offset unless @tok
@tok.source_range.start_pos.offset
end
# A hash from operator strings to the corresponding token types.
OPERATORS = {
'+' => :plus,
'-' => :minus,
'*' => :times,
'/' => :div,
'%' => :mod,
'=' => :single_eq,
':' => :colon,
'(' => :lparen,
')' => :rparen,
'[' => :lsquare,
']' => :rsquare,
',' => :comma,
'and' => :and,
'or' => :or,
'not' => :not,
'==' => :eq,
'!=' => :neq,
'>=' => :gte,
'<=' => :lte,
'>' => :gt,
'<' => :lt,
'#{' => :begin_interpolation,
'}' => :end_interpolation,
';' => :semicolon,
'{' => :lcurly,
'...' => :splat,
}
OPERATORS_REVERSE = Sass::Util.map_hash(OPERATORS) {|k, v| [v, k]}
TOKEN_NAMES = Sass::Util.map_hash(OPERATORS_REVERSE) {|k, v| [k, v.inspect]}.merge(
:const => "variable (e.g. $foo)",
:ident => "identifier (e.g. middle)")
# A list of operator strings ordered with longer names first
# so that `>` and `<` don't clobber `>=` and `<=`.
OP_NAMES = OPERATORS.keys.sort_by {|o| -o.size}
# A sub-list of {OP_NAMES} that only includes operators
# with identifier names.
IDENT_OP_NAMES = OP_NAMES.select {|k, _v| k =~ /^\w+/}
PARSEABLE_NUMBER = /(?:(\d*\.\d+)|(\d+))(?:[eE]([+-]?\d+))?(#{UNIT})?/
# A hash of regular expressions that are used for tokenizing.
REGULAR_EXPRESSIONS = {
:whitespace => /\s+/,
:comment => COMMENT,
:single_line_comment => SINGLE_LINE_COMMENT,
:variable => /(\$)(#{IDENT})/,
:ident => /(#{IDENT})(\()?/,
:number => PARSEABLE_NUMBER,
:unary_minus_number => /-#{PARSEABLE_NUMBER}/,
:color => HEXCOLOR,
:id => /##{IDENT}/,
:selector => /&/,
:ident_op => /(#{Regexp.union(*IDENT_OP_NAMES.map do |s|
Regexp.new(Regexp.escape(s) + "(?!#{NMCHAR}|\Z)")
end)})/,
:op => /(#{Regexp.union(*OP_NAMES)})/,
}
class << self
private
def string_re(open, close)
/#{open}((?:\\.|\#(?!\{)|[^#{close}\\#])*)(#{close}|#\{)/m
end
end
# A hash of regular expressions that are used for tokenizing strings.
#
# The key is a `[Symbol, Boolean]` pair.
# The symbol represents which style of quotation to use,
# while the boolean represents whether or not the string
# is following an interpolated segment.
STRING_REGULAR_EXPRESSIONS = {
:double => {
false => string_re('"', '"'),
true => string_re('', '"')
},
:single => {
false => string_re("'", "'"),
true => string_re('', "'")
},
:uri => {
false => /url\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
},
# Defined in https://developer.mozilla.org/en/CSS/@-moz-document as a
# non-standard version of http://www.w3.org/TR/css3-conditional/
:url_prefix => {
false => /url-prefix\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
},
:domain => {
false => /domain\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
}
}
# @param str [String, StringScanner] The source text to lex
# @param line [Integer] The 1-based line on which the SassScript appears.
# Used for error reporting and sourcemap building
# @param offset [Integer] The 1-based character (not byte) offset in the line in the source.
# Used for error reporting and sourcemap building
# @param options [{Symbol => Object}] An options hash;
# see {file:SASS_REFERENCE.md#Options the Sass options documentation}
def initialize(str, line, offset, options)
@scanner = str.is_a?(StringScanner) ? str : Sass::Util::MultibyteStringScanner.new(str)
@line = line
@offset = offset
@options = options
@interpolation_stack = []
@prev = nil
@tok = nil
@next_tok = nil
end
# Moves the lexer forward one token.
#
# @return [Token] The token that was moved past
def next
@tok ||= read_token
@tok, tok = nil, @tok
@prev = tok
tok
end
# Returns whether or not there's whitespace before the next token.
#
# @return [Boolean]
def whitespace?(tok = @tok)
if tok
@scanner.string[0...tok.pos] =~ /\s\Z/
else
@scanner.string[@scanner.pos, 1] =~ /^\s/ ||
@scanner.string[@scanner.pos - 1, 1] =~ /\s\Z/
end
end
# Returns the given character.
#
# @return [String]
def char(pos = @scanner.pos)
@scanner.string[pos, 1]
end
# Returns the next token without moving the lexer forward.
#
# @return [Token] The next token
def peek
@tok ||= read_token
end
# Rewinds the underlying StringScanner
# to before the token returned by \{#peek}.
def unpeek!
return unless @tok
@scanner.pos = @tok.pos
@line = @tok.source_range.start_pos.line
@offset = @tok.source_range.start_pos.offset
end
# @return [Boolean] Whether or not there's more source text to lex.
def done?
return if @next_tok
whitespace unless after_interpolation? && !@interpolation_stack.empty?
@scanner.eos? && @tok.nil?
end
# @return [Boolean] Whether or not the last token lexed was `:end_interpolation`.
def after_interpolation?
@prev && @prev.type == :end_interpolation
end
# Raise an error to the effect that `name` was expected in the input stream
# and wasn't found.
#
# This calls \{#unpeek!} to rewind the scanner to immediately after
# the last returned token.
#
# @param name [String] The name of the entity that was expected but not found
# @raise [Sass::SyntaxError]
def expected!(name)
unpeek!
Sass::SCSS::Parser.expected(@scanner, name, @line)
end
# Records all non-comment text the lexer consumes within the block
# and returns it as a string.
#
# @yield A block in which text is recorded
# @return [String]
def str
old_pos = @tok ? @tok.pos : @scanner.pos
yield
new_pos = @tok ? @tok.pos : @scanner.pos
@scanner.string[old_pos...new_pos]
end
private
def read_token
if (tok = @next_tok)
@next_tok = nil
return tok
end
return if done?
start_pos = source_position
value = token
return unless value
type, val = value
Token.new(type, val, range(start_pos), @scanner.pos - @scanner.matched_size)
end
def whitespace
nil while scan(REGULAR_EXPRESSIONS[:whitespace]) ||
scan(REGULAR_EXPRESSIONS[:comment]) ||
scan(REGULAR_EXPRESSIONS[:single_line_comment])
end
def token
if after_interpolation? && (interp = @interpolation_stack.pop)
interp_type, interp_value = interp
if interp_type == :special_fun
return special_fun_body(interp_value)
else
raise "[BUG]: Unknown interp_type #{interp_type}" unless interp_type == :string
return string(interp_value, true)
end
end
variable || string(:double, false) || string(:single, false) || number || id || color ||
selector || string(:uri, false) || raw(UNICODERANGE) || special_fun || special_val ||
ident_op || ident || op
end
def variable
_variable(REGULAR_EXPRESSIONS[:variable])
end
def _variable(rx)
return unless scan(rx)
[:const, @scanner[2]]
end
def ident
return unless scan(REGULAR_EXPRESSIONS[:ident])
[@scanner[2] ? :funcall : :ident, @scanner[1]]
end
def string(re, open)
line, offset = @line, @offset
return unless scan(STRING_REGULAR_EXPRESSIONS[re][open])
if @scanner[0] =~ /([^\\]|^)\n/
filename = @options[:filename]
Sass::Util.sass_warn <<MESSAGE
DEPRECATION WARNING on line #{line}, column #{offset}#{" of #{filename}" if filename}:
Unescaped multiline strings are deprecated and will be removed in a future version of Sass.
To include a newline in a string, use "\\a" or "\\a " as in CSS.
MESSAGE
end
if @scanner[2] == '#{' # '
@interpolation_stack << [:string, re]
start_pos = Sass::Source::Position.new(@line, @offset - 2)
@next_tok = Token.new(:string_interpolation, range(start_pos), @scanner.pos - 2)
end
str =
if re == :uri
url = "#{'url(' unless open}#{@scanner[1]}#{')' unless @scanner[2] == '#{'}"
Script::Value::String.new(url)
else
Script::Value::String.new(Sass::Script::Value::String.value(@scanner[1]), :string)
end
[:string, str]
end
def number
# Handling unary minus is complicated by the fact that whitespace is an
# operator in SassScript. We want "1-2" to be parsed as "1 - 2", but we
# want "1 -2" to be parsed as "1 (-2)". To accomplish this, we only
# parse a unary minus as part of a number literal if there's whitespace
# before and not after it. Cases like "(-2)" are handled by the unary
# minus logic in the parser instead.
if @scanner.peek(1) == '-'
return if @scanner.pos == 0
unary_minus_allowed =
case @scanner.string[@scanner.pos - 1, 1]
when /\s/; true
when '/'; @scanner.pos != 1 && @scanner.string[@scanner.pos - 2, 1] == '*'
else; false
end
return unless unary_minus_allowed
return unless scan(REGULAR_EXPRESSIONS[:unary_minus_number])
minus = true
else
return unless scan(REGULAR_EXPRESSIONS[:number])
minus = false
end
value = (@scanner[1] ? @scanner[1].to_f : @scanner[2].to_i) * (minus ? -1 : 1)
value *= 10**@scanner[3].to_i if @scanner[3]
script_number = Script::Value::Number.new(value, Array(@scanner[4]))
[:number, script_number]
end
def id
# Colors and ids are tough to tell apart, because they overlap but
# neither is a superset of the other. "#xyz" is an id but not a color,
# "#000" is a color but not an id, "#abc" is both, and "#0" is neither.
# We need to handle all these cases correctly.
#
# To do so, we first try to parse something as an id. If this works and
# the id is also a valid color, we return the color. Otherwise, we
# return the id. If it didn't parse as an id, we then try to parse it as
# a color. If *this* works, we return the color, and if it doesn't we
# give up and throw an error.
#
# IDs in properties are used in the Basic User Interface Module
# (http://www.w3.org/TR/css3-ui/).
return unless scan(REGULAR_EXPRESSIONS[:id])
if @scanner[0] =~ /^\#[0-9a-fA-F]+$/ &&
(@scanner[0].length == 4 || @scanner[0].length == 5 ||
@scanner[0].length == 7 || @scanner[0].length == 9)
return [:color, Script::Value::Color.from_hex(@scanner[0])]
end
[:ident, @scanner[0]]
end
def color
return unless @scanner.match?(REGULAR_EXPRESSIONS[:color])
unless @scanner[0].length == 4 || @scanner[0].length == 5 ||
@scanner[0].length == 7 || @scanner[0].length == 9
return
end
script_color = Script::Value::Color.from_hex(scan(REGULAR_EXPRESSIONS[:color]))
[:color, script_color]
end
def selector
start_pos = source_position
return unless scan(REGULAR_EXPRESSIONS[:selector])
if @scanner.peek(1) == '&'
filename = @options[:filename]
Sass::Util.sass_warn <<MESSAGE
WARNING on line #{line}, column #{offset}#{" of #{filename}" if filename}:
In Sass, "&&" means two copies of the parent selector. You probably want to use "and" instead.
MESSAGE
end
script_selector = Script::Tree::Selector.new
script_selector.source_range = range(start_pos)
[:selector, script_selector]
end
def special_fun
prefix = scan(/((-[\w-]+-)?(calc|element)|expression|progid:[a-z\.]*)\(/i)
return unless prefix
special_fun_body(1, prefix)
end
def special_fun_body(parens, prefix = nil)
str = prefix || ''
while (scanned = scan(/.*?([()]|\#\{)/m))
str << scanned
if scanned[-1] == ?(
parens += 1
next
elsif scanned[-1] == ?)
parens -= 1
next unless parens == 0
else
raise "[BUG] Unreachable" unless @scanner[1] == '#{' # '
str.slice!(-2..-1)
@interpolation_stack << [:special_fun, parens]
start_pos = Sass::Source::Position.new(@line, @offset - 2)
@next_tok = Token.new(:string_interpolation, range(start_pos), @scanner.pos - 2)
end
return [:special_fun, Sass::Script::Value::String.new(str)]
end
scan(/.*/)
expected!('")"')
end
def special_val
return unless scan(/!#{W}important/i)
[:string, Script::Value::String.new("!important")]
end
def ident_op
op = scan(REGULAR_EXPRESSIONS[:ident_op])
return unless op
[OPERATORS[op]]
end
def op
op = scan(REGULAR_EXPRESSIONS[:op])
return unless op
name = OPERATORS[op]
@interpolation_stack << nil if name == :begin_interpolation
[name]
end
def raw(rx)
val = scan(rx)
return unless val
[:raw, val]
end
def scan(re)
str = @scanner.scan(re)
return unless str
c = str.count("\n")
@line += c
@offset = (c == 0 ? @offset + str.size : str.size - str.rindex("\n"))
str
end
def range(start_pos, end_pos = source_position)
Sass::Source::Range.new(start_pos, end_pos, @options[:filename], @options[:importer])
end
def source_position
Sass::Source::Position.new(@line, @offset)
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/functions.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/functions.rb | require 'sass/script/value/helpers'
module Sass::Script
# YARD can't handle some multiline tags, and we need really long tags for function declarations.
# Methods in this module are accessible from the SassScript context.
# For example, you can write
#
# $color: hsl(120deg, 100%, 50%)
#
# and it will call {Functions#hsl}.
#
# The following functions are provided:
#
# *Note: These functions are described in more detail below.*
#
# ## RGB Functions
#
# \{#rgb rgb($red, $green, $blue)}
# : Creates a {Sass::Script::Value::Color Color} from red, green, and blue
# values.
#
# \{#rgba rgba($red, $green, $blue, $alpha)}
# : Creates a {Sass::Script::Value::Color Color} from red, green, blue, and
# alpha values.
#
# \{#red red($color)}
# : Gets the red component of a color.
#
# \{#green green($color)}
# : Gets the green component of a color.
#
# \{#blue blue($color)}
# : Gets the blue component of a color.
#
# \{#mix mix($color1, $color2, \[$weight\])}
# : Mixes two colors together.
#
# ## HSL Functions
#
# \{#hsl hsl($hue, $saturation, $lightness)}
# : Creates a {Sass::Script::Value::Color Color} from hue, saturation, and
# lightness values.
#
# \{#hsla hsla($hue, $saturation, $lightness, $alpha)}
# : Creates a {Sass::Script::Value::Color Color} from hue, saturation,
# lightness, and alpha values.
#
# \{#hue hue($color)}
# : Gets the hue component of a color.
#
# \{#saturation saturation($color)}
# : Gets the saturation component of a color.
#
# \{#lightness lightness($color)}
# : Gets the lightness component of a color.
#
# \{#adjust_hue adjust-hue($color, $degrees)}
# : Changes the hue of a color.
#
# \{#lighten lighten($color, $amount)}
# : Makes a color lighter.
#
# \{#darken darken($color, $amount)}
# : Makes a color darker.
#
# \{#saturate saturate($color, $amount)}
# : Makes a color more saturated.
#
# \{#desaturate desaturate($color, $amount)}
# : Makes a color less saturated.
#
# \{#grayscale grayscale($color)}
# : Converts a color to grayscale.
#
# \{#complement complement($color)}
# : Returns the complement of a color.
#
# \{#invert invert($color, \[$weight\])}
# : Returns the inverse of a color.
#
# ## Opacity Functions
#
# \{#alpha alpha($color)} / \{#opacity opacity($color)}
# : Gets the alpha component (opacity) of a color.
#
# \{#rgba rgba($color, $alpha)}
# : Changes the alpha component for a color.
#
# \{#opacify opacify($color, $amount)} / \{#fade_in fade-in($color, $amount)}
# : Makes a color more opaque.
#
# \{#transparentize transparentize($color, $amount)} / \{#fade_out fade-out($color, $amount)}
# : Makes a color more transparent.
#
# ## Other Color Functions
#
# \{#adjust_color adjust-color($color, \[$red\], \[$green\], \[$blue\], \[$hue\], \[$saturation\], \[$lightness\], \[$alpha\])}
# : Increases or decreases one or more components of a color.
#
# \{#scale_color scale-color($color, \[$red\], \[$green\], \[$blue\], \[$saturation\], \[$lightness\], \[$alpha\])}
# : Fluidly scales one or more properties of a color.
#
# \{#change_color change-color($color, \[$red\], \[$green\], \[$blue\], \[$hue\], \[$saturation\], \[$lightness\], \[$alpha\])}
# : Changes one or more properties of a color.
#
# \{#ie_hex_str ie-hex-str($color)}
# : Converts a color into the format understood by IE filters.
#
# ## String Functions
#
# \{#unquote unquote($string)}
# : Removes quotes from a string.
#
# \{#quote quote($string)}
# : Adds quotes to a string.
#
# \{#str_length str-length($string)}
# : Returns the number of characters in a string.
#
# \{#str_insert str-insert($string, $insert, $index)}
# : Inserts `$insert` into `$string` at `$index`.
#
# \{#str_index str-index($string, $substring)}
# : Returns the index of the first occurrence of `$substring` in `$string`.
#
# \{#str_slice str-slice($string, $start-at, [$end-at])}
# : Extracts a substring from `$string`.
#
# \{#to_upper_case to-upper-case($string)}
# : Converts a string to upper case.
#
# \{#to_lower_case to-lower-case($string)}
# : Converts a string to lower case.
#
# ## Number Functions
#
# \{#percentage percentage($number)}
# : Converts a unitless number to a percentage.
#
# \{#round round($number)}
# : Rounds a number to the nearest whole number.
#
# \{#ceil ceil($number)}
# : Rounds a number up to the next whole number.
#
# \{#floor floor($number)}
# : Rounds a number down to the previous whole number.
#
# \{#abs abs($number)}
# : Returns the absolute value of a number.
#
# \{#min min($numbers...)\}
# : Finds the minimum of several numbers.
#
# \{#max max($numbers...)\}
# : Finds the maximum of several numbers.
#
# \{#random random([$limit])\}
# : Returns a random number.
#
# ## List Functions {#list-functions}
#
# Lists in Sass are immutable; all list functions return a new list rather
# than updating the existing list in-place.
#
# All list functions work for maps as well, treating them as lists of pairs.
#
# \{#length length($list)}
# : Returns the length of a list.
#
# \{#nth nth($list, $n)}
# : Returns a specific item in a list.
#
# \{#set-nth set-nth($list, $n, $value)}
# : Replaces the nth item in a list.
#
# \{#join join($list1, $list2, \[$separator, $bracketed\])}
# : Joins together two lists into one.
#
# \{#append append($list1, $val, \[$separator\])}
# : Appends a single value onto the end of a list.
#
# \{#zip zip($lists...)}
# : Combines several lists into a single multidimensional list.
#
# \{#index index($list, $value)}
# : Returns the position of a value within a list.
#
# \{#list_separator list-separator($list)}
# : Returns the separator of a list.
#
# \{#is_bracketed is-bracketed($list)}
# : Returns whether a list has square brackets.
#
# ## Map Functions {#map-functions}
#
# Maps in Sass are immutable; all map functions return a new map rather than
# updating the existing map in-place.
#
# \{#map_get map-get($map, $key)}
# : Returns the value in a map associated with a given key.
#
# \{#map_merge map-merge($map1, $map2)}
# : Merges two maps together into a new map.
#
# \{#map_remove map-remove($map, $keys...)}
# : Returns a new map with keys removed.
#
# \{#map_keys map-keys($map)}
# : Returns a list of all keys in a map.
#
# \{#map_values map-values($map)}
# : Returns a list of all values in a map.
#
# \{#map_has_key map-has-key($map, $key)}
# : Returns whether a map has a value associated with a given key.
#
# \{#keywords keywords($args)}
# : Returns the keywords passed to a function that takes variable arguments.
#
# ## Selector Functions
#
# Selector functions are very liberal in the formats they support
# for selector arguments. They can take a plain string, a list of
# lists as returned by `&` or anything in between:
#
# * A plain string, such as `".foo .bar, .baz .bang"`.
# * A space-separated list of strings such as `(".foo" ".bar")`.
# * A comma-separated list of strings such as `(".foo .bar", ".baz .bang")`.
# * A comma-separated list of space-separated lists of strings such
# as `((".foo" ".bar"), (".baz" ".bang"))`.
#
# In general, selector functions allow placeholder selectors
# (`%foo`) but disallow parent-reference selectors (`&`).
#
# \{#selector_nest selector-nest($selectors...)}
# : Nests selector beneath one another like they would be nested in the
# stylesheet.
#
# \{#selector_append selector-append($selectors...)}
# : Appends selectors to one another without spaces in between.
#
# \{#selector_extend selector-extend($selector, $extendee, $extender)}
# : Extends `$extendee` with `$extender` within `$selector`.
#
# \{#selector_replace selector-replace($selector, $original, $replacement)}
# : Replaces `$original` with `$replacement` within `$selector`.
#
# \{#selector_unify selector-unify($selector1, $selector2)}
# : Unifies two selectors to produce a selector that matches
# elements matched by both.
#
# \{#is_superselector is-superselector($super, $sub)}
# : Returns whether `$super` matches all the elements `$sub` does, and
# possibly more.
#
# \{#simple_selectors simple-selectors($selector)}
# : Returns the simple selectors that comprise a compound selector.
#
# \{#selector_parse selector-parse($selector)}
# : Parses a selector into the format returned by `&`.
#
# ## Introspection Functions
#
# \{#feature_exists feature-exists($feature)}
# : Returns whether a feature exists in the current Sass runtime.
#
# \{#variable_exists variable-exists($name)}
# : Returns whether a variable with the given name exists in the current scope.
#
# \{#global_variable_exists global-variable-exists($name)}
# : Returns whether a variable with the given name exists in the global scope.
#
# \{#function_exists function-exists($name)}
# : Returns whether a function with the given name exists.
#
# \{#mixin_exists mixin-exists($name)}
# : Returns whether a mixin with the given name exists.
#
# \{#content_exists content-exists()}
# : Returns whether the current mixin was passed a content block.
#
# \{#inspect inspect($value)}
# : Returns the string representation of a value as it would be represented in Sass.
#
# \{#type_of type-of($value)}
# : Returns the type of a value.
#
# \{#unit unit($number)}
# : Returns the unit(s) associated with a number.
#
# \{#unitless unitless($number)}
# : Returns whether a number has units.
#
# \{#comparable comparable($number1, $number2)}
# : Returns whether two numbers can be added, subtracted, or compared.
#
# \{#call call($function, $args...)}
# : Dynamically calls a Sass function reference returned by `get-function`.
#
# \{#get_function get-function($name, $css: false)}
# : Looks up a function with the given name in the current lexical scope
# and returns a reference to it.
#
# ## Miscellaneous Functions
#
# \{#if if($condition, $if-true, $if-false)}
# : Returns one of two values, depending on whether or not `$condition` is
# true.
#
# \{#unique_id unique-id()}
# : Returns a unique CSS identifier.
#
# ## Adding Custom Functions
#
# New Sass functions can be added by adding Ruby methods to this module.
# For example:
#
# module Sass::Script::Functions
# def reverse(string)
# assert_type string, :String
# Sass::Script::Value::String.new(string.value.reverse)
# end
# declare :reverse, [:string]
# end
#
# Calling {declare} tells Sass the argument names for your function.
# If omitted, the function will still work, but will not be able to accept keyword arguments.
# {declare} can also allow your function to take arbitrary keyword arguments.
#
# There are a few things to keep in mind when modifying this module.
# First of all, the arguments passed are {Value} objects.
# Value objects are also expected to be returned.
# This means that Ruby values must be unwrapped and wrapped.
#
# Most Value objects support the {Value::Base#value value} accessor for getting
# their Ruby values. Color objects, though, must be accessed using
# {Sass::Script::Value::Color#rgb rgb}, {Sass::Script::Value::Color#red red},
# {Sass::Script::Value::Color#blue green}, or {Sass::Script::Value::Color#blue
# blue}.
#
# Second, making Ruby functions accessible from Sass introduces the temptation
# to do things like database access within stylesheets.
# This is generally a bad idea;
# since Sass files are by default only compiled once,
# dynamic code is not a great fit.
#
# If you really, really need to compile Sass on each request,
# first make sure you have adequate caching set up.
# Then you can use {Sass::Engine} to render the code,
# using the {file:SASS_REFERENCE.md#custom-option `options` parameter}
# to pass in data that {EvaluationContext#options can be accessed}
# from your Sass functions.
#
# Within one of the functions in this module,
# methods of {EvaluationContext} can be used.
#
# ### Caveats
#
# When creating new {Value} objects within functions, be aware that it's not
# safe to call {Value::Base#to_s #to_s} (or other methods that use the string
# representation) on those objects without first setting {Tree::Node#options=
# the #options attribute}.
#
module Functions
@signatures = {}
# A class representing a Sass function signature.
#
# @attr args [Array<String>] The names of the arguments to the function.
# @attr delayed_args [Array<String>] The names of the arguments whose evaluation should be
# delayed.
# @attr var_args [Boolean] Whether the function takes a variable number of arguments.
# @attr var_kwargs [Boolean] Whether the function takes an arbitrary set of keyword arguments.
Signature = Struct.new(:args, :delayed_args, :var_args, :var_kwargs, :deprecated)
# Declare a Sass signature for a Ruby-defined function.
# This includes the names of the arguments,
# whether the function takes a variable number of arguments,
# and whether the function takes an arbitrary set of keyword arguments.
#
# It's not necessary to declare a signature for a function.
# However, without a signature it won't support keyword arguments.
#
# A single function can have multiple signatures declared
# as long as each one takes a different number of arguments.
# It's also possible to declare multiple signatures
# that all take the same number of arguments,
# but none of them but the first will be used
# unless the user uses keyword arguments.
#
# @example
# declare :rgba, [:hex, :alpha]
# declare :rgba, [:red, :green, :blue, :alpha]
# declare :accepts_anything, [], :var_args => true, :var_kwargs => true
# declare :some_func, [:foo, :bar, :baz], :var_kwargs => true
#
# @param method_name [Symbol] The name of the method
# whose signature is being declared.
# @param args [Array<Symbol>] The names of the arguments for the function signature.
# @option options :var_args [Boolean] (false)
# Whether the function accepts a variable number of (unnamed) arguments
# in addition to the named arguments.
# @option options :var_kwargs [Boolean] (false)
# Whether the function accepts other keyword arguments
# in addition to those in `:args`.
# If this is true, the Ruby function will be passed a hash from strings
# to {Value}s as the last argument.
# In addition, if this is true and `:var_args` is not,
# Sass will ensure that the last argument passed is a hash.
def self.declare(method_name, args, options = {})
delayed_args = []
args = args.map do |a|
a = a.to_s
if a[0] == ?&
a = a[1..-1]
delayed_args << a
end
a
end
# We don't expose this functionality except to certain builtin methods.
if delayed_args.any? && method_name != :if
raise ArgumentError.new("Delayed arguments are not allowed for method #{method_name}")
end
@signatures[method_name] ||= []
@signatures[method_name] << Signature.new(
args,
delayed_args,
options[:var_args],
options[:var_kwargs],
options[:deprecated] && options[:deprecated].map {|a| a.to_s})
end
# Determine the correct signature for the number of arguments
# passed in for a given function.
# If no signatures match, the first signature is returned for error messaging.
#
# @param method_name [Symbol] The name of the Ruby function to be called.
# @param arg_arity [Integer] The number of unnamed arguments the function was passed.
# @param kwarg_arity [Integer] The number of keyword arguments the function was passed.
#
# @return [{Symbol => Object}, nil]
# The signature options for the matching signature,
# or nil if no signatures are declared for this function. See {declare}.
def self.signature(method_name, arg_arity, kwarg_arity)
return unless @signatures[method_name]
@signatures[method_name].each do |signature|
sig_arity = signature.args.size
return signature if sig_arity == arg_arity + kwarg_arity
next unless sig_arity < arg_arity + kwarg_arity
# We have enough args.
# Now we need to figure out which args are varargs
# and if the signature allows them.
t_arg_arity, t_kwarg_arity = arg_arity, kwarg_arity
if sig_arity > t_arg_arity
# we transfer some kwargs arity to args arity
# if it does not have enough args -- assuming the names will work out.
t_kwarg_arity -= (sig_arity - t_arg_arity)
t_arg_arity = sig_arity
end
if (t_arg_arity == sig_arity || t_arg_arity > sig_arity && signature.var_args) &&
(t_kwarg_arity == 0 || t_kwarg_arity > 0 && signature.var_kwargs)
return signature
end
end
@signatures[method_name].first
end
# Sets the random seed used by Sass's internal random number generator.
#
# This can be used to ensure consistent random number sequences which
# allows for consistent results when testing, etc.
#
# @param seed [Integer]
# @return [Integer] The same seed.
def self.random_seed=(seed)
@random_number_generator = Random.new(seed)
end
# Get Sass's internal random number generator.
#
# @return [Random]
def self.random_number_generator
@random_number_generator ||= Random.new
end
# The context in which methods in {Script::Functions} are evaluated.
# That means that all instance methods of {EvaluationContext}
# are available to use in functions.
class EvaluationContext
include Functions
include Value::Helpers
# The human-readable names for [Sass::Script::Value::Base]. The default is
# just the downcased name of the type.
TYPE_NAMES = {:ArgList => 'variable argument list'}
# The environment for this function. This environment's
# {Environment#parent} is the global environment, and its
# {Environment#caller} is a read-only view of the local environment of the
# caller of this function.
#
# @return [Environment]
attr_reader :environment
# The options hash for the {Sass::Engine} that is processing the function call
#
# @return [{Symbol => Object}]
attr_reader :options
# @param environment [Environment] See \{#environment}
def initialize(environment)
@environment = environment
@options = environment.options
end
# Asserts that the type of a given SassScript value
# is the expected type (designated by a symbol).
#
# Valid types are `:Bool`, `:Color`, `:Number`, and `:String`.
# Note that `:String` will match both double-quoted strings
# and unquoted identifiers.
#
# @example
# assert_type value, :String
# assert_type value, :Number
# @param value [Sass::Script::Value::Base] A SassScript value
# @param type [Symbol, Array<Symbol>] The name(s) of the type the value is expected to be
# @param name [String, Symbol, nil] The name of the argument.
# @raise [ArgumentError] if value is not of the correct type.
def assert_type(value, type, name = nil)
valid_types = Array(type)
found_type = valid_types.find do |t|
value.is_a?(Sass::Script::Value.const_get(t)) ||
t == :Map && value.is_a?(Sass::Script::Value::List) && value.value.empty?
end
if found_type
value.check_deprecated_interp if found_type == :String
return
end
err = if valid_types.size == 1
"#{value.inspect} is not a #{TYPE_NAMES[type] || type.to_s.downcase}"
else
type_names = valid_types.map {|t| TYPE_NAMES[t] || t.to_s.downcase}
"#{value.inspect} is not any of #{type_names.join(', ')}"
end
err = "$#{name.to_s.tr('_', '-')}: " + err if name
raise ArgumentError.new(err)
end
# Asserts that the unit of the number is as expected.
#
# @example
# assert_unit number, "px"
# assert_unit number, nil
# @param number [Sass::Script::Value::Number] The number to be validated.
# @param unit [::String]
# The unit that the number must have.
# If nil, the number must be unitless.
# @param name [::String] The name of the parameter being validated.
# @raise [ArgumentError] if number is not of the correct unit or is not a number.
def assert_unit(number, unit, name = nil)
assert_type number, :Number, name
return if number.is_unit?(unit)
expectation = unit ? "have a unit of #{unit}" : "be unitless"
if name
raise ArgumentError.new("Expected $#{name} to #{expectation} but got #{number}")
else
raise ArgumentError.new("Expected #{number} to #{expectation}")
end
end
# Asserts that the value is an integer.
#
# @example
# assert_integer 2px
# assert_integer 2.5px
# => SyntaxError: "Expected 2.5px to be an integer"
# assert_integer 2.5px, "width"
# => SyntaxError: "Expected width to be an integer but got 2.5px"
# @param number [Sass::Script::Value::Base] The value to be validated.
# @param name [::String] The name of the parameter being validated.
# @raise [ArgumentError] if number is not an integer or is not a number.
def assert_integer(number, name = nil)
assert_type number, :Number, name
return if number.int?
if name
raise ArgumentError.new("Expected $#{name} to be an integer but got #{number}")
else
raise ArgumentError.new("Expected #{number} to be an integer")
end
end
# Performs a node that has been delayed for execution.
#
# @private
# @param node [Sass::Script::Tree::Node,
# Sass::Script::Value::Base] When this is a tree node, it's
# performed in the caller's environment. When it's a value
# (which can happen when the value had to be performed already
# -- like for a splat), it's returned as-is.
# @param env [Sass::Environment] The environment within which to perform the node.
# Defaults to the (read-only) environment of the caller.
def perform(node, env = environment.caller)
if node.is_a?(Sass::Script::Value::Base)
node
else
node.perform(env)
end
end
end
class << self
# Returns whether user function with a given name exists.
#
# @param function_name [String]
# @return [Boolean]
alias_method :callable?, :public_method_defined?
private
def include(*args)
r = super
# We have to re-include ourselves into EvaluationContext to work around
# an icky Ruby restriction.
EvaluationContext.send :include, self
r
end
end
# Creates a {Sass::Script::Value::Color Color} object from red, green, and
# blue values.
#
# @see #rgba
# @overload rgb($red, $green, $blue)
# @param $red [Sass::Script::Value::Number] The amount of red in the color.
# Must be between 0 and 255 inclusive, or between `0%` and `100%`
# inclusive
# @param $green [Sass::Script::Value::Number] The amount of green in the
# color. Must be between 0 and 255 inclusive, or between `0%` and `100%`
# inclusive
# @param $blue [Sass::Script::Value::Number] The amount of blue in the
# color. Must be between 0 and 255 inclusive, or between `0%` and `100%`
# inclusive
# @return [Sass::Script::Value::Color]
# @raise [ArgumentError] if any parameter is the wrong type or out of bounds
def rgb(red, green = nil, blue = nil)
if green.nil?
return unquoted_string("rgb(#{red})") if var?(red)
raise ArgumentError.new("wrong number of arguments (1 for 3)")
elsif blue.nil?
return unquoted_string("rgb(#{red}, #{green})") if var?(red) || var?(green)
raise ArgumentError.new("wrong number of arguments (2 for 3)")
end
if special_number?(red) || special_number?(green) || special_number?(blue)
return unquoted_string("rgb(#{red}, #{green}, #{blue})")
end
assert_type red, :Number, :red
assert_type green, :Number, :green
assert_type blue, :Number, :blue
color_attrs = [red, green, blue].map do |c|
if c.is_unit?("%")
c.value * 255 / 100.0
elsif c.unitless?
c.value
else
raise ArgumentError.new("Expected #{c} to be unitless or have a unit of % but got #{c}")
end
end
# Don't store the string representation for function-created colors, both
# because it's not very useful and because some functions aren't supported
# on older browsers.
Sass::Script::Value::Color.new(color_attrs)
end
declare :rgb, [:red, :green, :blue]
declare :rgb, [:red, :green]
declare :rgb, [:red]
# Creates a {Sass::Script::Value::Color Color} from red, green, blue, and
# alpha values.
# @see #rgb
#
# @overload rgba($red, $green, $blue, $alpha)
# @param $red [Sass::Script::Value::Number] The amount of red in the
# color. Must be between 0 and 255 inclusive or 0% and 100% inclusive
# @param $green [Sass::Script::Value::Number] The amount of green in the
# color. Must be between 0 and 255 inclusive or 0% and 100% inclusive
# @param $blue [Sass::Script::Value::Number] The amount of blue in the
# color. Must be between 0 and 255 inclusive or 0% and 100% inclusive
# @param $alpha [Sass::Script::Value::Number] The opacity of the color.
# Must be between 0 and 1 inclusive
# @return [Sass::Script::Value::Color]
# @raise [ArgumentError] if any parameter is the wrong type or out of
# bounds
#
# @overload rgba($color, $alpha)
# Sets the opacity of an existing color.
#
# @example
# rgba(#102030, 0.5) => rgba(16, 32, 48, 0.5)
# rgba(blue, 0.2) => rgba(0, 0, 255, 0.2)
#
# @param $color [Sass::Script::Value::Color] The color whose opacity will
# be changed.
# @param $alpha [Sass::Script::Value::Number] The new opacity of the
# color. Must be between 0 and 1 inclusive
# @return [Sass::Script::Value::Color]
# @raise [ArgumentError] if `$alpha` is out of bounds or either parameter
# is the wrong type
def rgba(*args)
case args.size
when 1
return unquoted_string("rgba(#{args.first})") if var?(args.first)
raise ArgumentError.new("wrong number of arguments (1 for 4)")
when 2
color, alpha = args
if var?(color)
return unquoted_string("rgba(#{color}, #{alpha})")
elsif var?(alpha)
if color.is_a?(Sass::Script::Value::Color)
return unquoted_string("rgba(#{color.red}, #{color.green}, #{color.blue}, #{alpha})")
else
return unquoted_string("rgba(#{color}, #{alpha})")
end
end
assert_type color, :Color, :color
if special_number?(alpha)
unquoted_string("rgba(#{color.red}, #{color.green}, #{color.blue}, #{alpha})")
else
assert_type alpha, :Number, :alpha
check_alpha_unit alpha, 'rgba'
color.with(:alpha => alpha.value)
end
when 3
if var?(args[0]) || var?(args[1]) || var?(args[2])
unquoted_string("rgba(#{args.join(', ')})")
else
raise ArgumentError.new("wrong number of arguments (3 for 4)")
end
when 4
red, green, blue, alpha = args
if special_number?(red) || special_number?(green) ||
special_number?(blue) || special_number?(alpha)
unquoted_string("rgba(#{red}, #{green}, #{blue}, #{alpha})")
else
rgba(rgb(red, green, blue), alpha)
end
else
raise ArgumentError.new("wrong number of arguments (#{args.size} for 4)")
end
end
declare :rgba, [:red, :green, :blue, :alpha]
declare :rgba, [:red, :green, :blue]
declare :rgba, [:color, :alpha]
declare :rgba, [:red]
# Creates a {Sass::Script::Value::Color Color} from hue, saturation, and
# lightness values. Uses the algorithm from the [CSS3 spec][].
#
# [CSS3 spec]: http://www.w3.org/TR/css3-color/#hsl-color
#
# @see #hsla
# @overload hsl($hue, $saturation, $lightness)
# @param $hue [Sass::Script::Value::Number] The hue of the color. Should be
# between 0 and 360 degrees, inclusive
# @param $saturation [Sass::Script::Value::Number] The saturation of the
# color. Must be between `0%` and `100%`, inclusive
# @param $lightness [Sass::Script::Value::Number] The lightness of the
# color. Must be between `0%` and `100%`, inclusive
# @return [Sass::Script::Value::Color]
# @raise [ArgumentError] if `$saturation` or `$lightness` are out of bounds
# or any parameter is the wrong type
def hsl(hue, saturation = nil, lightness = nil)
if saturation.nil?
return unquoted_string("hsl(#{hue})") if var?(hue)
raise ArgumentError.new("wrong number of arguments (1 for 3)")
elsif lightness.nil?
return unquoted_string("hsl(#{hue}, #{saturation})") if var?(hue) || var?(saturation)
raise ArgumentError.new("wrong number of arguments (2 for 3)")
end
if special_number?(hue) || special_number?(saturation) || special_number?(lightness)
unquoted_string("hsl(#{hue}, #{saturation}, #{lightness})")
else
hsla(hue, saturation, lightness, number(1))
end
end
declare :hsl, [:hue, :saturation, :lightness]
declare :hsl, [:hue, :saturation]
declare :hsl, [:hue]
# Creates a {Sass::Script::Value::Color Color} from hue,
# saturation, lightness, and alpha values. Uses the algorithm from
# the [CSS3 spec][].
#
# [CSS3 spec]: http://www.w3.org/TR/css3-color/#hsl-color
#
# @see #hsl
# @overload hsla($hue, $saturation, $lightness, $alpha)
# @param $hue [Sass::Script::Value::Number] The hue of the color. Should be
# between 0 and 360 degrees, inclusive
# @param $saturation [Sass::Script::Value::Number] The saturation of the
# color. Must be between `0%` and `100%`, inclusive
# @param $lightness [Sass::Script::Value::Number] The lightness of the
# color. Must be between `0%` and `100%`, inclusive
# @param $alpha [Sass::Script::Value::Number] The opacity of the color. Must
# be between 0 and 1, inclusive
# @return [Sass::Script::Value::Color]
# @raise [ArgumentError] if `$saturation`, `$lightness`, or `$alpha` are out
# of bounds or any parameter is the wrong type
def hsla(hue, saturation = nil, lightness = nil, alpha = nil)
if saturation.nil?
return unquoted_string("hsla(#{hue})") if var?(hue)
raise ArgumentError.new("wrong number of arguments (1 for 4)")
elsif lightness.nil?
return unquoted_string("hsla(#{hue}, #{saturation})") if var?(hue) || var?(saturation)
raise ArgumentError.new("wrong number of arguments (2 for 4)")
elsif alpha.nil?
if var?(hue) || var?(saturation) || var?(lightness)
return unquoted_string("hsla(#{hue}, #{saturation}, #{lightness})")
else
raise ArgumentError.new("wrong number of arguments (2 for 4)")
end
end
if special_number?(hue) || special_number?(saturation) ||
special_number?(lightness) || special_number?(alpha)
return unquoted_string("hsla(#{hue}, #{saturation}, #{lightness}, #{alpha})")
end
assert_type hue, :Number, :hue
assert_type saturation, :Number, :saturation
assert_type lightness, :Number, :lightness
assert_type alpha, :Number, :alpha
check_alpha_unit alpha, 'hsla'
h = hue.value
s = saturation.value
l = lightness.value
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | true |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/css_lexer.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/css_lexer.rb | module Sass
module Script
# This is a subclass of {Lexer} for use in parsing plain CSS properties.
#
# @see Sass::SCSS::CssParser
class CssLexer < Lexer
private
def token
important || super
end
def string(re, *args)
if re == :uri
uri = scan(URI)
return unless uri
return [:string, Script::Value::String.new(uri)]
end
return unless scan(STRING)
string_value = Sass::Script::Value::String.value(@scanner[1] || @scanner[2])
value = Script::Value::String.new(string_value, :string)
[:string, value]
end
def important
s = scan(IMPORTANT)
return unless s
[:raw, s]
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/callable.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/callable.rb | module Sass::Script::Value
# A SassScript object representing a null value.
class Callable < Base
# Constructs a Callable value for use in SassScript.
#
# @param callable [Sass::Callable] The callable to be used when the
# callable is called.
def initialize(callable)
super(callable)
end
def to_s(opts = {})
raise Sass::SyntaxError.new("#{to_sass} isn't a valid CSS value.")
end
def inspect
to_sass
end
# @abstract
def to_sass
Sass::Util.abstract(self)
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/bool.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/bool.rb | module Sass::Script::Value
# A SassScript object representing a boolean (true or false) value.
class Bool < Base
# The true value in SassScript.
#
# This is assigned before new is overridden below so that we use the default implementation.
TRUE = new(true)
# The false value in SassScript.
#
# This is assigned before new is overridden below so that we use the default implementation.
FALSE = new(false)
# We override object creation so that users of the core API
# will not need to know that booleans are specific constants.
#
# @param value A ruby value that will be tested for truthiness.
# @return [Bool] TRUE if value is truthy, FALSE if value is falsey
def self.new(value)
value ? TRUE : FALSE
end
# The Ruby value of the boolean.
#
# @return [Boolean]
attr_reader :value
alias_method :to_bool, :value
# @return [String] "true" or "false"
def to_s(opts = {})
@value.to_s
end
alias_method :to_sass, :to_s
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/helpers.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/helpers.rb | module Sass::Script::Value
# Provides helper functions for creating sass values from within ruby methods.
# @since `3.3.0`
module Helpers
# Construct a Sass Boolean.
#
# @param value [Object] A ruby object that will be tested for truthiness.
# @return [Sass::Script::Value::Bool] whether the ruby value is truthy.
def bool(value)
Bool.new(value)
end
# Construct a Sass Color from a hex color string.
#
# @param value [::String] A string representing a hex color.
# The leading hash ("#") is optional.
# @param alpha [::Number] The alpha channel. A number between 0 and 1.
# @return [Sass::Script::Value::Color] the color object
def hex_color(value, alpha = nil)
Color.from_hex(value, alpha)
end
# Construct a Sass Color from hsl values.
#
# @param hue [::Number] The hue of the color in degrees.
# A non-negative number, usually less than 360.
# @param saturation [::Number] The saturation of the color.
# Must be between 0 and 100 inclusive.
# @param lightness [::Number] The lightness of the color.
# Must be between 0 and 100 inclusive.
# @param alpha [::Number] The alpha channel. A number between 0 and 1.
#
# @return [Sass::Script::Value::Color] the color object
def hsl_color(hue, saturation, lightness, alpha = nil)
attrs = {:hue => hue, :saturation => saturation, :lightness => lightness}
attrs[:alpha] = alpha if alpha
Color.new(attrs)
end
# Construct a Sass Color from rgb values.
#
# @param red [::Number] The red component. Must be between 0 and 255 inclusive.
# @param green [::Number] The green component. Must be between 0 and 255 inclusive.
# @param blue [::Number] The blue component. Must be between 0 and 255 inclusive.
# @param alpha [::Number] The alpha channel. A number between 0 and 1.
#
# @return [Sass::Script::Value::Color] the color object
def rgb_color(red, green, blue, alpha = nil)
attrs = {:red => red, :green => green, :blue => blue}
attrs[:alpha] = alpha if alpha
Color.new(attrs)
end
# Construct a Sass Number from a ruby number.
#
# @param number [::Number] A numeric value.
# @param unit_string [::String] A unit string of the form
# `numeral_unit1 * numeral_unit2 ... / denominator_unit1 * denominator_unit2 ...`
# this is the same format that is returned by
# {Sass::Script::Value::Number#unit_str the `unit_str` method}
#
# @see Sass::Script::Value::Number#unit_str
#
# @return [Sass::Script::Value::Number] The sass number representing the given ruby number.
def number(number, unit_string = nil)
Number.new(number, *parse_unit_string(unit_string))
end
# @overload list(*elements, separator:, bracketed: false)
# Create a space-separated list from the arguments given.
# @param elements [Array<Sass::Script::Value::Base>] Each argument will be a list element.
# @param separator [Symbol] Either :space or :comma.
# @param bracketed [Boolean] Whether the list uses square brackets.
# @return [Sass::Script::Value::List] The space separated list.
#
# @overload list(array, separator:, bracketed: false)
# Create a space-separated list from the array given.
# @param array [Array<Sass::Script::Value::Base>] A ruby array of Sass values
# to make into a list.
# @param separator [Symbol] Either :space or :comma.
# @param bracketed [Boolean] Whether the list uses square brackets.
# @return [Sass::Script::Value::List] The space separated list.
def list(*elements, separator: nil, bracketed: false)
# Support passing separator as the last value in elements for
# backwards-compatibility.
if separator.nil?
if elements.last.is_a?(Symbol)
separator = elements.pop
else
raise ArgumentError.new("A separator of :space or :comma must be specified.")
end
end
if elements.size == 1 && elements.first.is_a?(Array)
elements = elements.first
end
Sass::Script::Value::List.new(elements, separator: separator, bracketed: bracketed)
end
# Construct a Sass map.
#
# @param hash [Hash<Sass::Script::Value::Base,
# Sass::Script::Value::Base>] A Ruby map to convert to a Sass map.
# @return [Sass::Script::Value::Map] The map.
def map(hash)
Map.new(hash)
end
# Create a sass null value.
#
# @return [Sass::Script::Value::Null]
def null
Sass::Script::Value::Null.new
end
# Create a quoted string.
#
# @param str [::String] A ruby string.
# @return [Sass::Script::Value::String] A quoted string.
def quoted_string(str)
Sass::Script::String.new(str, :string)
end
# Create an unquoted string.
#
# @param str [::String] A ruby string.
# @return [Sass::Script::Value::String] An unquoted string.
def unquoted_string(str)
Sass::Script::String.new(str, :identifier)
end
alias_method :identifier, :unquoted_string
# Parses a user-provided selector.
#
# @param value [Sass::Script::Value::String, Sass::Script::Value::List]
# The selector to parse. This can be either a string, a list of
# strings, or a list of lists of strings as returned by `&`.
# @param name [Symbol, nil]
# If provided, the name of the selector argument. This is used
# for error reporting.
# @param allow_parent_ref [Boolean]
# Whether the parsed selector should allow parent references.
# @return [Sass::Selector::CommaSequence] The parsed selector.
# @throw [ArgumentError] if the parse failed for any reason.
def parse_selector(value, name = nil, allow_parent_ref = false)
str = normalize_selector(value, name)
begin
Sass::SCSS::StaticParser.new(str, nil, nil, 1, 1, allow_parent_ref).parse_selector
rescue Sass::SyntaxError => e
err = "#{value.inspect} is not a valid selector: #{e}"
err = "$#{name.to_s.tr('_', '-')}: #{err}" if name
raise ArgumentError.new(err)
end
end
# Parses a user-provided complex selector.
#
# A complex selector can contain combinators but cannot contain commas.
#
# @param value [Sass::Script::Value::String, Sass::Script::Value::List]
# The selector to parse. This can be either a string or a list of
# strings.
# @param name [Symbol, nil]
# If provided, the name of the selector argument. This is used
# for error reporting.
# @param allow_parent_ref [Boolean]
# Whether the parsed selector should allow parent references.
# @return [Sass::Selector::Sequence] The parsed selector.
# @throw [ArgumentError] if the parse failed for any reason.
def parse_complex_selector(value, name = nil, allow_parent_ref = false)
selector = parse_selector(value, name, allow_parent_ref)
return seq if selector.members.length == 1
err = "#{value.inspect} is not a complex selector"
err = "$#{name.to_s.tr('_', '-')}: #{err}" if name
raise ArgumentError.new(err)
end
# Parses a user-provided compound selector.
#
# A compound selector cannot contain combinators or commas.
#
# @param value [Sass::Script::Value::String] The selector to parse.
# @param name [Symbol, nil]
# If provided, the name of the selector argument. This is used
# for error reporting.
# @param allow_parent_ref [Boolean]
# Whether the parsed selector should allow parent references.
# @return [Sass::Selector::SimpleSequence] The parsed selector.
# @throw [ArgumentError] if the parse failed for any reason.
def parse_compound_selector(value, name = nil, allow_parent_ref = false)
assert_type value, :String, name
selector = parse_selector(value, name, allow_parent_ref)
seq = selector.members.first
sseq = seq.members.first
if selector.members.length == 1 && seq.members.length == 1 &&
sseq.is_a?(Sass::Selector::SimpleSequence)
return sseq
end
err = "#{value.inspect} is not a compound selector"
err = "$#{name.to_s.tr('_', '-')}: #{err}" if name
raise ArgumentError.new(err)
end
# Returns true when the literal is a string containing a calc().
#
# Use \{#special_number?} in preference to this.
#
# @param literal [Sass::Script::Value::Base] The value to check
# @return Boolean
def calc?(literal)
literal.is_a?(Sass::Script::Value::String) && literal.value =~ /calc\(/
end
# Returns true when the literal is a string containing a var().
#
# @param literal [Sass::Script::Value::Base] The value to check
# @return Boolean
def var?(literal)
literal.is_a?(Sass::Script::Value::String) && literal.value =~ /var\(/
end
# Returns whether the literal is a special CSS value that may evaluate to a
# number, such as `calc()` or `var()`.
#
# @param literal [Sass::Script::Value::Base] The value to check
# @return Boolean
def special_number?(literal)
literal.is_a?(Sass::Script::Value::String) && literal.value =~ /(calc|var)\(/
end
private
# Converts a user-provided selector into string form or throws an
# ArgumentError if it's in an invalid format.
def normalize_selector(value, name)
if (str = selector_to_str(value))
return str
end
err = "#{value.inspect} is not a valid selector: it must be a string,\n" +
"a list of strings, or a list of lists of strings"
err = "$#{name.to_s.tr('_', '-')}: #{err}" if name
raise ArgumentError.new(err)
end
# Converts a user-provided selector into string form or returns
# `nil` if it's in an invalid format.
def selector_to_str(value)
return value.value if value.is_a?(Sass::Script::String)
return unless value.is_a?(Sass::Script::List)
if value.separator == :comma
return value.to_a.map do |complex|
next complex.value if complex.is_a?(Sass::Script::String)
return unless complex.is_a?(Sass::Script::List) && complex.separator == :space
return unless (str = selector_to_str(complex))
str
end.join(', ')
end
value.to_a.map do |compound|
return unless compound.is_a?(Sass::Script::String)
compound.value
end.join(' ')
end
# @private
VALID_UNIT = /#{Sass::SCSS::RX::NMSTART}#{Sass::SCSS::RX::NMCHAR}|%*/
# @example
# parse_unit_string("em*px/in*%") # => [["em", "px], ["in", "%"]]
#
# @param unit_string [String] A string adhering to the output of a number with complex
# units. E.g. "em*px/in*%"
# @return [Array<Array<String>>] A list of numerator units and a list of denominator units.
def parse_unit_string(unit_string)
denominator_units = numerator_units = Sass::Script::Value::Number::NO_UNITS
return numerator_units, denominator_units unless unit_string && unit_string.length > 0
num_over_denominator = unit_string.split(%r{ */ *})
unless (1..2).include?(num_over_denominator.size)
raise ArgumentError.new("Malformed unit string: #{unit_string}")
end
numerator_units = num_over_denominator[0].split(/ *\* */)
denominator_units = (num_over_denominator[1] || "").split(/ *\* */)
[[numerator_units, "numerator"], [denominator_units, "denominator"]].each do |units, name|
if unit_string =~ %r{/} && units.size == 0
raise ArgumentError.new("Malformed unit string: #{unit_string}")
end
if units.any? {|unit| unit !~ VALID_UNIT}
raise ArgumentError.new("Malformed #{name} in unit string: #{unit_string}")
end
end
[numerator_units, denominator_units]
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/color.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/color.rb | module Sass::Script::Value
# A SassScript object representing a CSS color.
#
# A color may be represented internally as RGBA, HSLA, or both.
# It's originally represented as whatever its input is;
# if it's created with RGB values, it's represented as RGBA,
# and if it's created with HSL values, it's represented as HSLA.
# Once a property is accessed that requires the other representation --
# for example, \{#red} for an HSL color --
# that component is calculated and cached.
#
# The alpha channel of a color is independent of its RGB or HSL representation.
# It's always stored, as 1 if nothing else is specified.
# If only the alpha channel is modified using \{#with},
# the cached RGB and HSL values are retained.
class Color < Base
# @private
#
# Convert a ruby integer to a rgba components
# @param color [Integer]
# @return [Array<Integer>] Array of 4 numbers representing r,g,b and alpha
def self.int_to_rgba(color)
rgba = (0..3).map {|n| color >> (n << 3) & 0xff}.reverse
rgba[-1] = rgba[-1] / 255.0
rgba
end
ALTERNATE_COLOR_NAMES = Sass::Util.map_vals(
{
'aqua' => 0x00FFFFFF,
'darkgrey' => 0xA9A9A9FF,
'darkslategrey' => 0x2F4F4FFF,
'dimgrey' => 0x696969FF,
'fuchsia' => 0xFF00FFFF,
'grey' => 0x808080FF,
'lightgrey' => 0xD3D3D3FF,
'lightslategrey' => 0x778899FF,
'slategrey' => 0x708090FF,
}, &method(:int_to_rgba))
# A hash from color names to `[red, green, blue]` value arrays.
COLOR_NAMES = Sass::Util.map_vals(
{
'aliceblue' => 0xF0F8FFFF,
'antiquewhite' => 0xFAEBD7FF,
'aquamarine' => 0x7FFFD4FF,
'azure' => 0xF0FFFFFF,
'beige' => 0xF5F5DCFF,
'bisque' => 0xFFE4C4FF,
'black' => 0x000000FF,
'blanchedalmond' => 0xFFEBCDFF,
'blue' => 0x0000FFFF,
'blueviolet' => 0x8A2BE2FF,
'brown' => 0xA52A2AFF,
'burlywood' => 0xDEB887FF,
'cadetblue' => 0x5F9EA0FF,
'chartreuse' => 0x7FFF00FF,
'chocolate' => 0xD2691EFF,
'coral' => 0xFF7F50FF,
'cornflowerblue' => 0x6495EDFF,
'cornsilk' => 0xFFF8DCFF,
'crimson' => 0xDC143CFF,
'cyan' => 0x00FFFFFF,
'darkblue' => 0x00008BFF,
'darkcyan' => 0x008B8BFF,
'darkgoldenrod' => 0xB8860BFF,
'darkgray' => 0xA9A9A9FF,
'darkgreen' => 0x006400FF,
'darkkhaki' => 0xBDB76BFF,
'darkmagenta' => 0x8B008BFF,
'darkolivegreen' => 0x556B2FFF,
'darkorange' => 0xFF8C00FF,
'darkorchid' => 0x9932CCFF,
'darkred' => 0x8B0000FF,
'darksalmon' => 0xE9967AFF,
'darkseagreen' => 0x8FBC8FFF,
'darkslateblue' => 0x483D8BFF,
'darkslategray' => 0x2F4F4FFF,
'darkturquoise' => 0x00CED1FF,
'darkviolet' => 0x9400D3FF,
'deeppink' => 0xFF1493FF,
'deepskyblue' => 0x00BFFFFF,
'dimgray' => 0x696969FF,
'dodgerblue' => 0x1E90FFFF,
'firebrick' => 0xB22222FF,
'floralwhite' => 0xFFFAF0FF,
'forestgreen' => 0x228B22FF,
'gainsboro' => 0xDCDCDCFF,
'ghostwhite' => 0xF8F8FFFF,
'gold' => 0xFFD700FF,
'goldenrod' => 0xDAA520FF,
'gray' => 0x808080FF,
'green' => 0x008000FF,
'greenyellow' => 0xADFF2FFF,
'honeydew' => 0xF0FFF0FF,
'hotpink' => 0xFF69B4FF,
'indianred' => 0xCD5C5CFF,
'indigo' => 0x4B0082FF,
'ivory' => 0xFFFFF0FF,
'khaki' => 0xF0E68CFF,
'lavender' => 0xE6E6FAFF,
'lavenderblush' => 0xFFF0F5FF,
'lawngreen' => 0x7CFC00FF,
'lemonchiffon' => 0xFFFACDFF,
'lightblue' => 0xADD8E6FF,
'lightcoral' => 0xF08080FF,
'lightcyan' => 0xE0FFFFFF,
'lightgoldenrodyellow' => 0xFAFAD2FF,
'lightgreen' => 0x90EE90FF,
'lightgray' => 0xD3D3D3FF,
'lightpink' => 0xFFB6C1FF,
'lightsalmon' => 0xFFA07AFF,
'lightseagreen' => 0x20B2AAFF,
'lightskyblue' => 0x87CEFAFF,
'lightslategray' => 0x778899FF,
'lightsteelblue' => 0xB0C4DEFF,
'lightyellow' => 0xFFFFE0FF,
'lime' => 0x00FF00FF,
'limegreen' => 0x32CD32FF,
'linen' => 0xFAF0E6FF,
'magenta' => 0xFF00FFFF,
'maroon' => 0x800000FF,
'mediumaquamarine' => 0x66CDAAFF,
'mediumblue' => 0x0000CDFF,
'mediumorchid' => 0xBA55D3FF,
'mediumpurple' => 0x9370DBFF,
'mediumseagreen' => 0x3CB371FF,
'mediumslateblue' => 0x7B68EEFF,
'mediumspringgreen' => 0x00FA9AFF,
'mediumturquoise' => 0x48D1CCFF,
'mediumvioletred' => 0xC71585FF,
'midnightblue' => 0x191970FF,
'mintcream' => 0xF5FFFAFF,
'mistyrose' => 0xFFE4E1FF,
'moccasin' => 0xFFE4B5FF,
'navajowhite' => 0xFFDEADFF,
'navy' => 0x000080FF,
'oldlace' => 0xFDF5E6FF,
'olive' => 0x808000FF,
'olivedrab' => 0x6B8E23FF,
'orange' => 0xFFA500FF,
'orangered' => 0xFF4500FF,
'orchid' => 0xDA70D6FF,
'palegoldenrod' => 0xEEE8AAFF,
'palegreen' => 0x98FB98FF,
'paleturquoise' => 0xAFEEEEFF,
'palevioletred' => 0xDB7093FF,
'papayawhip' => 0xFFEFD5FF,
'peachpuff' => 0xFFDAB9FF,
'peru' => 0xCD853FFF,
'pink' => 0xFFC0CBFF,
'plum' => 0xDDA0DDFF,
'powderblue' => 0xB0E0E6FF,
'purple' => 0x800080FF,
'red' => 0xFF0000FF,
'rebeccapurple' => 0x663399FF,
'rosybrown' => 0xBC8F8FFF,
'royalblue' => 0x4169E1FF,
'saddlebrown' => 0x8B4513FF,
'salmon' => 0xFA8072FF,
'sandybrown' => 0xF4A460FF,
'seagreen' => 0x2E8B57FF,
'seashell' => 0xFFF5EEFF,
'sienna' => 0xA0522DFF,
'silver' => 0xC0C0C0FF,
'skyblue' => 0x87CEEBFF,
'slateblue' => 0x6A5ACDFF,
'slategray' => 0x708090FF,
'snow' => 0xFFFAFAFF,
'springgreen' => 0x00FF7FFF,
'steelblue' => 0x4682B4FF,
'tan' => 0xD2B48CFF,
'teal' => 0x008080FF,
'thistle' => 0xD8BFD8FF,
'tomato' => 0xFF6347FF,
'transparent' => 0x00000000,
'turquoise' => 0x40E0D0FF,
'violet' => 0xEE82EEFF,
'wheat' => 0xF5DEB3FF,
'white' => 0xFFFFFFFF,
'whitesmoke' => 0xF5F5F5FF,
'yellow' => 0xFFFF00FF,
'yellowgreen' => 0x9ACD32FF
}, &method(:int_to_rgba))
# A hash from `[red, green, blue, alpha]` value arrays to color names.
COLOR_NAMES_REVERSE = COLOR_NAMES.invert.freeze
# We add the alternate color names after inverting because
# different ruby implementations and versions vary on the ordering of the result of invert.
COLOR_NAMES.update(ALTERNATE_COLOR_NAMES).freeze
# The user's original representation of the color.
#
# @return [String]
attr_reader :representation
# Constructs an RGB or HSL color object,
# optionally with an alpha channel.
#
# RGB values are clipped within 0 and 255.
# Saturation and lightness values are clipped within 0 and 100.
# The alpha value is clipped within 0 and 1.
#
# @raise [Sass::SyntaxError] if any color value isn't in the specified range
#
# @overload initialize(attrs)
# The attributes are specified as a hash. This hash must contain either
# `:hue`, `:saturation`, and `:lightness` keys, or `:red`, `:green`, and
# `:blue` keys. It cannot contain both HSL and RGB keys. It may also
# optionally contain an `:alpha` key, and a `:representation` key
# indicating the original representation of the color that the user wrote
# in their stylesheet.
#
# @param attrs [{Symbol => Numeric}] A hash of color attributes to values
# @raise [ArgumentError] if not enough attributes are specified,
# or both RGB and HSL attributes are specified
#
# @overload initialize(rgba, [representation])
# The attributes are specified as an array.
# This overload only supports RGB or RGBA colors.
#
# @param rgba [Array<Numeric>] A three- or four-element array
# of the red, green, blue, and optionally alpha values (respectively)
# of the color
# @param representation [String] The original representation of the color
# that the user wrote in their stylesheet.
# @raise [ArgumentError] if not enough attributes are specified
def initialize(attrs, representation = nil, allow_both_rgb_and_hsl = false)
super(nil)
if attrs.is_a?(Array)
unless (3..4).include?(attrs.size)
raise ArgumentError.new("Color.new(array) expects a three- or four-element array")
end
red, green, blue = attrs[0...3].map {|c| Sass::Util.round(c)}
@attrs = {:red => red, :green => green, :blue => blue}
@attrs[:alpha] = attrs[3] ? attrs[3].to_f : 1
@representation = representation
else
attrs = attrs.reject {|_k, v| v.nil?}
hsl = [:hue, :saturation, :lightness] & attrs.keys
rgb = [:red, :green, :blue] & attrs.keys
if !allow_both_rgb_and_hsl && !hsl.empty? && !rgb.empty?
raise ArgumentError.new("Color.new(hash) may not have both HSL and RGB keys specified")
elsif hsl.empty? && rgb.empty?
raise ArgumentError.new("Color.new(hash) must have either HSL or RGB keys specified")
elsif !hsl.empty? && hsl.size != 3
raise ArgumentError.new("Color.new(hash) must have all three HSL values specified")
elsif !rgb.empty? && rgb.size != 3
raise ArgumentError.new("Color.new(hash) must have all three RGB values specified")
end
@attrs = attrs
@attrs[:hue] %= 360 if @attrs[:hue]
@attrs[:alpha] ||= 1
@representation = @attrs.delete(:representation)
end
[:red, :green, :blue].each do |k|
next if @attrs[k].nil?
@attrs[k] = Sass::Util.restrict(Sass::Util.round(@attrs[k]), 0..255)
end
[:saturation, :lightness].each do |k|
next if @attrs[k].nil?
@attrs[k] = Sass::Util.restrict(@attrs[k], 0..100)
end
@attrs[:alpha] = Sass::Util.restrict(@attrs[:alpha], 0..1)
end
# Create a new color from a valid CSS hex string.
#
# The leading hash is optional.
#
# @return [Color]
def self.from_hex(hex_string, alpha = nil)
unless hex_string =~ /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i ||
hex_string =~ /^#?([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?$/i
raise ArgumentError.new("#{hex_string.inspect} is not a valid hex color.")
end
red = $1.ljust(2, $1).to_i(16)
green = $2.ljust(2, $2).to_i(16)
blue = $3.ljust(2, $3).to_i(16)
alpha = $4.ljust(2, $4).to_i(16).to_f / 0xff if $4
hex_string = "##{hex_string}" unless hex_string[0] == ?#
attrs = {:red => red, :green => green, :blue => blue, :representation => hex_string}
attrs[:alpha] = alpha if alpha
new(attrs)
end
# The red component of the color.
#
# @return [Integer]
def red
hsl_to_rgb!
@attrs[:red]
end
# The green component of the color.
#
# @return [Integer]
def green
hsl_to_rgb!
@attrs[:green]
end
# The blue component of the color.
#
# @return [Integer]
def blue
hsl_to_rgb!
@attrs[:blue]
end
# The hue component of the color.
#
# @return [Numeric]
def hue
rgb_to_hsl!
@attrs[:hue]
end
# The saturation component of the color.
#
# @return [Numeric]
def saturation
rgb_to_hsl!
@attrs[:saturation]
end
# The lightness component of the color.
#
# @return [Numeric]
def lightness
rgb_to_hsl!
@attrs[:lightness]
end
# The alpha channel (opacity) of the color.
# This is 1 unless otherwise defined.
#
# @return [Integer]
def alpha
@attrs[:alpha].to_f
end
# Returns whether this color object is translucent;
# that is, whether the alpha channel is non-1.
#
# @return [Boolean]
def alpha?
alpha < 1
end
# Returns the red, green, and blue components of the color.
#
# @return [Array<Integer>] A frozen three-element array of the red, green, and blue
# values (respectively) of the color
def rgb
[red, green, blue].freeze
end
# Returns the red, green, blue, and alpha components of the color.
#
# @return [Array<Integer>] A frozen four-element array of the red, green,
# blue, and alpha values (respectively) of the color
def rgba
[red, green, blue, alpha].freeze
end
# Returns the hue, saturation, and lightness components of the color.
#
# @return [Array<Integer>] A frozen three-element array of the
# hue, saturation, and lightness values (respectively) of the color
def hsl
[hue, saturation, lightness].freeze
end
# Returns the hue, saturation, lightness, and alpha components of the color.
#
# @return [Array<Integer>] A frozen four-element array of the hue,
# saturation, lightness, and alpha values (respectively) of the color
def hsla
[hue, saturation, lightness, alpha].freeze
end
# The SassScript `==` operation.
# **Note that this returns a {Sass::Script::Value::Bool} object,
# not a Ruby boolean**.
#
# @param other [Value] The right-hand side of the operator
# @return [Bool] True if this value is the same as the other,
# false otherwise
def eq(other)
Sass::Script::Value::Bool.new(
other.is_a?(Color) && rgb == other.rgb && alpha == other.alpha)
end
def hash
[rgb, alpha].hash
end
# Returns a copy of this color with one or more channels changed.
# RGB or HSL colors may be changed, but not both at once.
#
# For example:
#
# Color.new([10, 20, 30]).with(:blue => 40)
# #=> rgb(10, 40, 30)
# Color.new([126, 126, 126]).with(:red => 0, :green => 255)
# #=> rgb(0, 255, 126)
# Color.new([255, 0, 127]).with(:saturation => 60)
# #=> rgb(204, 51, 127)
# Color.new([1, 2, 3]).with(:alpha => 0.4)
# #=> rgba(1, 2, 3, 0.4)
#
# @param attrs [{Symbol => Numeric}]
# A map of channel names (`:red`, `:green`, `:blue`,
# `:hue`, `:saturation`, `:lightness`, or `:alpha`) to values
# @return [Color] The new Color object
# @raise [ArgumentError] if both RGB and HSL keys are specified
def with(attrs)
attrs = attrs.reject {|_k, v| v.nil?}
hsl = !([:hue, :saturation, :lightness] & attrs.keys).empty?
rgb = !([:red, :green, :blue] & attrs.keys).empty?
if hsl && rgb
raise ArgumentError.new("Cannot specify HSL and RGB values for a color at the same time")
end
if hsl
[:hue, :saturation, :lightness].each {|k| attrs[k] ||= send(k)}
elsif rgb
[:red, :green, :blue].each {|k| attrs[k] ||= send(k)}
else
# If we're just changing the alpha channel,
# keep all the HSL/RGB stuff we've calculated
attrs = @attrs.merge(attrs)
end
attrs[:alpha] ||= alpha
Color.new(attrs, nil, :allow_both_rgb_and_hsl)
end
# The SassScript `+` operation.
# Its functionality depends on the type of its argument:
#
# {Number}
# : Adds the number to each of the RGB color channels.
#
# {Color}
# : Adds each of the RGB color channels together.
#
# {Value}
# : See {Value::Base#plus}.
#
# @param other [Value] The right-hand side of the operator
# @return [Color] The resulting color
# @raise [Sass::SyntaxError] if `other` is a number with units
def plus(other)
if other.is_a?(Sass::Script::Value::Number) || other.is_a?(Sass::Script::Value::Color)
piecewise(other, :+)
else
super
end
end
# The SassScript `-` operation.
# Its functionality depends on the type of its argument:
#
# {Number}
# : Subtracts the number from each of the RGB color channels.
#
# {Color}
# : Subtracts each of the other color's RGB color channels from this color's.
#
# {Value}
# : See {Value::Base#minus}.
#
# @param other [Value] The right-hand side of the operator
# @return [Color] The resulting color
# @raise [Sass::SyntaxError] if `other` is a number with units
def minus(other)
if other.is_a?(Sass::Script::Value::Number) || other.is_a?(Sass::Script::Value::Color)
piecewise(other, :-)
else
super
end
end
# The SassScript `*` operation.
# Its functionality depends on the type of its argument:
#
# {Number}
# : Multiplies the number by each of the RGB color channels.
#
# {Color}
# : Multiplies each of the RGB color channels together.
#
# @param other [Number, Color] The right-hand side of the operator
# @return [Color] The resulting color
# @raise [Sass::SyntaxError] if `other` is a number with units
def times(other)
if other.is_a?(Sass::Script::Value::Number) || other.is_a?(Sass::Script::Value::Color)
piecewise(other, :*)
else
raise NoMethodError.new(nil, :times)
end
end
# The SassScript `/` operation.
# Its functionality depends on the type of its argument:
#
# {Number}
# : Divides each of the RGB color channels by the number.
#
# {Color}
# : Divides each of this color's RGB color channels by the other color's.
#
# {Value}
# : See {Value::Base#div}.
#
# @param other [Value] The right-hand side of the operator
# @return [Color] The resulting color
# @raise [Sass::SyntaxError] if `other` is a number with units
def div(other)
if other.is_a?(Sass::Script::Value::Number) ||
other.is_a?(Sass::Script::Value::Color)
piecewise(other, :/)
else
super
end
end
# The SassScript `%` operation.
# Its functionality depends on the type of its argument:
#
# {Number}
# : Takes each of the RGB color channels module the number.
#
# {Color}
# : Takes each of this color's RGB color channels modulo the other color's.
#
# @param other [Number, Color] The right-hand side of the operator
# @return [Color] The resulting color
# @raise [Sass::SyntaxError] if `other` is a number with units
def mod(other)
if other.is_a?(Sass::Script::Value::Number) ||
other.is_a?(Sass::Script::Value::Color)
piecewise(other, :%)
else
raise NoMethodError.new(nil, :mod)
end
end
# Returns a string representation of the color.
# This is usually the color's hex value,
# but if the color has a name that's used instead.
#
# @return [String] The string representation
def to_s(opts = {})
return smallest if options[:style] == :compressed
return representation if representation
# IE10 doesn't properly support the color name "transparent", so we emit
# generated transparent colors as rgba(0, 0, 0, 0) in favor of that. See
# #1782.
return rgba_str if Number.basically_equal?(alpha, 0)
return name if name
alpha? ? rgba_str : hex_str
end
alias_method :to_sass, :to_s
# Returns a string representation of the color.
#
# @return [String] The hex value
def inspect
alpha? ? rgba_str : hex_str
end
# Returns the color's name, if it has one.
#
# @return [String, nil]
def name
COLOR_NAMES_REVERSE[rgba]
end
private
def smallest
small_explicit_str = alpha? ? rgba_str : hex_str.gsub(/^#(.)\1(.)\2(.)\3$/, '#\1\2\3')
[representation, COLOR_NAMES_REVERSE[rgba], small_explicit_str].
compact.min_by {|str| str.size}
end
def rgba_str
split = options[:style] == :compressed ? ',' : ', '
"rgba(#{rgb.join(split)}#{split}#{Number.round(alpha)})"
end
def hex_str
red, green, blue = rgb.map {|num| num.to_s(16).rjust(2, '0')}
"##{red}#{green}#{blue}"
end
def operation_name(operation)
case operation
when :+
"add"
when :-
"subtract"
when :*
"multiply"
when :/
"divide"
when :%
"modulo"
end
end
def piecewise(other, operation)
other_num = other.is_a? Number
if other_num && !other.unitless?
raise Sass::SyntaxError.new(
"Cannot #{operation_name(operation)} a number with units (#{other}) to a color (#{self})."
)
end
result = []
(0...3).each do |i|
res = rgb[i].to_f.send(operation, other_num ? other.value : other.rgb[i])
result[i] = [[res, 255].min, 0].max
end
if !other_num && other.alpha != alpha
raise Sass::SyntaxError.new("Alpha channels must be equal: #{self} #{operation} #{other}")
end
with(:red => result[0], :green => result[1], :blue => result[2])
end
def hsl_to_rgb!
return if @attrs[:red] && @attrs[:blue] && @attrs[:green]
h = @attrs[:hue] / 360.0
s = @attrs[:saturation] / 100.0
l = @attrs[:lightness] / 100.0
# Algorithm from the CSS3 spec: http://www.w3.org/TR/css3-color/#hsl-color.
m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s
m1 = l * 2 - m2
@attrs[:red], @attrs[:green], @attrs[:blue] = [
hue_to_rgb(m1, m2, h + 1.0 / 3),
hue_to_rgb(m1, m2, h),
hue_to_rgb(m1, m2, h - 1.0 / 3)
].map {|c| Sass::Util.round(c * 0xff)}
end
def hue_to_rgb(m1, m2, h)
h += 1 if h < 0
h -= 1 if h > 1
return m1 + (m2 - m1) * h * 6 if h * 6 < 1
return m2 if h * 2 < 1
return m1 + (m2 - m1) * (2.0 / 3 - h) * 6 if h * 3 < 2
m1
end
def rgb_to_hsl!
return if @attrs[:hue] && @attrs[:saturation] && @attrs[:lightness]
r, g, b = [:red, :green, :blue].map {|k| @attrs[k] / 255.0}
# Algorithm from http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
max = [r, g, b].max
min = [r, g, b].min
d = max - min
h =
case max
when min; 0
when r; 60 * (g - b) / d
when g; 60 * (b - r) / d + 120
when b; 60 * (r - g) / d + 240
end
l = (max + min) / 2.0
s =
if max == min
0
elsif l < 0.5
d / (2 * l)
else
d / (2 - 2 * l)
end
@attrs[:hue] = h % 360
@attrs[:saturation] = s * 100
@attrs[:lightness] = l * 100
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/base.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/base.rb | module Sass::Script::Value
# The abstract superclass for SassScript objects.
#
# Many of these methods, especially the ones that correspond to SassScript operations,
# are designed to be overridden by subclasses which may change the semantics somewhat.
# The operations listed here are just the defaults.
class Base
# Returns the Ruby value of the value.
# The type of this value varies based on the subclass.
#
# @return [Object]
attr_reader :value
# The source range in the document on which this node appeared.
#
# @return [Sass::Source::Range]
attr_accessor :source_range
# Creates a new value.
#
# @param value [Object] The object for \{#value}
def initialize(value = nil)
value.freeze unless value.nil? || value == true || value == false
@value = value
@options = nil
end
# Sets the options hash for this node,
# as well as for all child nodes.
# See {file:SASS_REFERENCE.md#Options the Sass options documentation}.
#
# @param options [{Symbol => Object}] The options
attr_writer :options
# Returns the options hash for this node.
#
# @return [{Symbol => Object}]
# @raise [Sass::SyntaxError] if the options hash hasn't been set.
# This should only happen when the value was created
# outside of the parser and \{#to\_s} was called on it
def options
return @options if @options
raise Sass::SyntaxError.new(<<MSG)
The #options attribute is not set on this #{self.class}.
This error is probably occurring because #to_s was called
on this value within a custom Sass function without first
setting the #options attribute.
MSG
end
# The SassScript `==` operation.
# **Note that this returns a {Sass::Script::Value::Bool} object,
# not a Ruby boolean**.
#
# @param other [Value] The right-hand side of the operator
# @return [Sass::Script::Value::Bool] True if this value is the same as the other,
# false otherwise
def eq(other)
Sass::Script::Value::Bool.new(self.class == other.class && value == other.value)
end
# The SassScript `!=` operation.
# **Note that this returns a {Sass::Script::Value::Bool} object,
# not a Ruby boolean**.
#
# @param other [Value] The right-hand side of the operator
# @return [Sass::Script::Value::Bool] False if this value is the same as the other,
# true otherwise
def neq(other)
Sass::Script::Value::Bool.new(!eq(other).to_bool)
end
# The SassScript `==` operation.
# **Note that this returns a {Sass::Script::Value::Bool} object,
# not a Ruby boolean**.
#
# @param other [Value] The right-hand side of the operator
# @return [Sass::Script::Value::Bool] True if this value is the same as the other,
# false otherwise
def unary_not
Sass::Script::Value::Bool.new(!to_bool)
end
# The SassScript `=` operation
# (used for proprietary MS syntax like `alpha(opacity=20)`).
#
# @param other [Value] The right-hand side of the operator
# @return [Script::Value::String] A string containing both values
# separated by `"="`
def single_eq(other)
Sass::Script::Value::String.new("#{self}=#{other}")
end
# The SassScript `+` operation.
#
# @param other [Value] The right-hand side of the operator
# @return [Script::Value::String] A string containing both values
# without any separation
def plus(other)
type = other.is_a?(Sass::Script::Value::String) ? other.type : :identifier
Sass::Script::Value::String.new(to_s(:quote => :none) + other.to_s(:quote => :none), type)
end
# The SassScript `-` operation.
#
# @param other [Value] The right-hand side of the operator
# @return [Script::Value::String] A string containing both values
# separated by `"-"`
def minus(other)
Sass::Script::Value::String.new("#{self}-#{other}")
end
# The SassScript `/` operation.
#
# @param other [Value] The right-hand side of the operator
# @return [Script::Value::String] A string containing both values
# separated by `"/"`
def div(other)
Sass::Script::Value::String.new("#{self}/#{other}")
end
# The SassScript unary `+` operation (e.g. `+$a`).
#
# @param other [Value] The right-hand side of the operator
# @return [Script::Value::String] A string containing the value
# preceded by `"+"`
def unary_plus
Sass::Script::Value::String.new("+#{self}")
end
# The SassScript unary `-` operation (e.g. `-$a`).
#
# @param other [Value] The right-hand side of the operator
# @return [Script::Value::String] A string containing the value
# preceded by `"-"`
def unary_minus
Sass::Script::Value::String.new("-#{self}")
end
# The SassScript unary `/` operation (e.g. `/$a`).
#
# @param other [Value] The right-hand side of the operator
# @return [Script::Value::String] A string containing the value
# preceded by `"/"`
def unary_div
Sass::Script::Value::String.new("/#{self}")
end
# Returns the hash code of this value. Two objects' hash codes should be
# equal if the objects are equal.
#
# @return [Integer for Ruby 2.4.0+, Fixnum for earlier Ruby versions] The hash code.
def hash
value.hash
end
def eql?(other)
self == other
end
# @return [String] A readable representation of the value
def inspect
value.inspect
end
# @return [Boolean] `true` (the Ruby boolean value)
def to_bool
true
end
# Compares this object with another.
#
# @param other [Object] The object to compare with
# @return [Boolean] Whether or not this value is equivalent to `other`
def ==(other)
eq(other).to_bool
end
# @return [Integer] The integer value of this value
# @raise [Sass::SyntaxError] if this value isn't an integer
def to_i
raise Sass::SyntaxError.new("#{inspect} is not an integer.")
end
# @raise [Sass::SyntaxError] if this value isn't an integer
def assert_int!; to_i; end
# Returns the separator for this value. For non-list-like values or the
# empty list, this will be `nil`. For lists or maps, it will be `:space` or
# `:comma`.
#
# @return [Symbol]
def separator; nil; end
# Whether the value is surrounded by square brackets. For non-list values,
# this will be `false`.
#
# @return [Boolean]
def bracketed; false; end
# Returns the value of this value as a list.
# Single values are considered the same as single-element lists.
#
# @return [Array<Value>] This value as a list
def to_a
[self]
end
# Returns the value of this value as a hash. Most values don't have hash
# representations, but [Map]s and empty [List]s do.
#
# @return [Hash<Value, Value>] This value as a hash
# @raise [Sass::SyntaxError] if this value doesn't have a hash representation
def to_h
raise Sass::SyntaxError.new("#{inspect} is not a map.")
end
# Returns the string representation of this value
# as it would be output to the CSS document.
#
# @options opts :quote [String]
# The preferred quote style for quoted strings. If `:none`, strings are
# always emitted unquoted.
# @return [String]
def to_s(opts = {})
Sass::Util.abstract(self)
end
alias_method :to_sass, :to_s
# Returns whether or not this object is null.
#
# @return [Boolean] `false`
def null?
false
end
# Creates a new list containing `contents` but with the same brackets and
# separators as this object, when interpreted as a list.
#
# @param contents [Array<Value>] The contents of the new list.
# @param separator [Symbol] The separator of the new list. Defaults to \{#separator}.
# @param bracketed [Boolean] Whether the new list is bracketed. Defaults to \{#bracketed}.
# @return [Sass::Script::Value::List]
def with_contents(contents, separator: self.separator, bracketed: self.bracketed)
Sass::Script::Value::List.new(contents, separator: separator, bracketed: bracketed)
end
protected
# Evaluates the value.
#
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
# @return [Value] This value
def _perform(environment)
self
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/null.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/null.rb | module Sass::Script::Value
# A SassScript object representing a null value.
class Null < Base
# The null value in SassScript.
#
# This is assigned before new is overridden below so that we use the default implementation.
NULL = new(nil)
# We override object creation so that users of the core API
# will not need to know that null is a specific constant.
#
# @private
# @return [Null] the {NULL} constant.
def self.new
NULL
end
# @return [Boolean] `false` (the Ruby boolean value)
def to_bool
false
end
# @return [Boolean] `true`
def null?
true
end
# @return [String] '' (An empty string)
def to_s(opts = {})
''
end
def to_sass(opts = {})
'null'
end
# Returns a string representing a null value.
#
# @return [String]
def inspect
'null'
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/number.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/number.rb | module Sass::Script::Value
# A SassScript object representing a number.
# SassScript numbers can have decimal values,
# and can also have units.
# For example, `12`, `1px`, and `10.45em`
# are all valid values.
#
# Numbers can also have more complex units, such as `1px*em/in`.
# These cannot be inputted directly in Sass code at the moment.
class Number < Base
# The Ruby value of the number.
#
# @return [Numeric]
attr_reader :value
# A list of units in the numerator of the number.
# For example, `1px*em/in*cm` would return `["px", "em"]`
# @return [Array<String>]
attr_reader :numerator_units
# A list of units in the denominator of the number.
# For example, `1px*em/in*cm` would return `["in", "cm"]`
# @return [Array<String>]
attr_reader :denominator_units
# The original representation of this number.
# For example, although the result of `1px/2px` is `0.5`,
# the value of `#original` is `"1px/2px"`.
#
# This is only non-nil when the original value should be used as the CSS value,
# as in `font: 1px/2px`.
#
# @return [Boolean, nil]
attr_accessor :original
def self.precision
Thread.current[:sass_numeric_precision] || Thread.main[:sass_numeric_precision] || 10
end
# Sets the number of digits of precision
# For example, if this is `3`,
# `3.1415926` will be printed as `3.142`.
# The numeric precision is stored as a thread local for thread safety reasons.
# To set for all threads, be sure to set the precision on the main thread.
def self.precision=(digits)
Thread.current[:sass_numeric_precision] = digits.round
Thread.current[:sass_numeric_precision_factor] = nil
Thread.current[:sass_numeric_epsilon] = nil
end
# the precision factor used in numeric output
# it is derived from the `precision` method.
def self.precision_factor
Thread.current[:sass_numeric_precision_factor] ||= 10.0**precision
end
# Used in checking equality of floating point numbers. Any
# numbers within an `epsilon` of each other are considered functionally equal.
# The value for epsilon is one tenth of the current numeric precision.
def self.epsilon
Thread.current[:sass_numeric_epsilon] ||= 1 / (precision_factor * 10)
end
# Used so we don't allocate two new arrays for each new number.
NO_UNITS = []
# @param value [Numeric] The value of the number
# @param numerator_units [::String, Array<::String>] See \{#numerator\_units}
# @param denominator_units [::String, Array<::String>] See \{#denominator\_units}
def initialize(value, numerator_units = NO_UNITS, denominator_units = NO_UNITS)
numerator_units = [numerator_units] if numerator_units.is_a?(::String)
denominator_units = [denominator_units] if denominator_units.is_a?(::String)
super(value)
@numerator_units = numerator_units
@denominator_units = denominator_units
@options = nil
normalize!
end
# The SassScript `+` operation.
# Its functionality depends on the type of its argument:
#
# {Number}
# : Adds the two numbers together, converting units if possible.
#
# {Color}
# : Adds this number to each of the RGB color channels.
#
# {Value}
# : See {Value::Base#plus}.
#
# @param other [Value] The right-hand side of the operator
# @return [Value] The result of the operation
# @raise [Sass::UnitConversionError] if `other` is a number with incompatible units
def plus(other)
if other.is_a? Number
operate(other, :+)
elsif other.is_a?(Color)
other.plus(self)
else
super
end
end
# The SassScript binary `-` operation (e.g. `$a - $b`).
# Its functionality depends on the type of its argument:
#
# {Number}
# : Subtracts this number from the other, converting units if possible.
#
# {Value}
# : See {Value::Base#minus}.
#
# @param other [Value] The right-hand side of the operator
# @return [Value] The result of the operation
# @raise [Sass::UnitConversionError] if `other` is a number with incompatible units
def minus(other)
if other.is_a? Number
operate(other, :-)
else
super
end
end
# The SassScript unary `+` operation (e.g. `+$a`).
#
# @return [Number] The value of this number
def unary_plus
self
end
# The SassScript unary `-` operation (e.g. `-$a`).
#
# @return [Number] The negative value of this number
def unary_minus
Number.new(-value, @numerator_units, @denominator_units)
end
# The SassScript `*` operation.
# Its functionality depends on the type of its argument:
#
# {Number}
# : Multiplies the two numbers together, converting units appropriately.
#
# {Color}
# : Multiplies each of the RGB color channels by this number.
#
# @param other [Number, Color] The right-hand side of the operator
# @return [Number, Color] The result of the operation
# @raise [NoMethodError] if `other` is an invalid type
def times(other)
if other.is_a? Number
operate(other, :*)
elsif other.is_a? Color
other.times(self)
else
raise NoMethodError.new(nil, :times)
end
end
# The SassScript `/` operation.
# Its functionality depends on the type of its argument:
#
# {Number}
# : Divides this number by the other, converting units appropriately.
#
# {Value}
# : See {Value::Base#div}.
#
# @param other [Value] The right-hand side of the operator
# @return [Value] The result of the operation
def div(other)
if other.is_a? Number
res = operate(other, :/)
if original && other.original
res.original = "#{original}/#{other.original}"
end
res
else
super
end
end
# The SassScript `%` operation.
#
# @param other [Number] The right-hand side of the operator
# @return [Number] This number modulo the other
# @raise [NoMethodError] if `other` is an invalid type
# @raise [Sass::UnitConversionError] if `other` has incompatible units
def mod(other)
if other.is_a?(Number)
return Number.new(Float::NAN) if other.value == 0
operate(other, :%)
else
raise NoMethodError.new(nil, :mod)
end
end
# The SassScript `==` operation.
#
# @param other [Value] The right-hand side of the operator
# @return [Boolean] Whether this number is equal to the other object
def eq(other)
return Bool::FALSE unless other.is_a?(Sass::Script::Value::Number)
this = self
begin
if unitless?
this = this.coerce(other.numerator_units, other.denominator_units)
else
other = other.coerce(@numerator_units, @denominator_units)
end
rescue Sass::UnitConversionError
return Bool::FALSE
end
Bool.new(basically_equal?(this.value, other.value))
end
def hash
[value, numerator_units, denominator_units].hash
end
# Hash-equality works differently than `==` equality for numbers.
# Hash-equality must be transitive, so it just compares the exact value,
# numerator units, and denominator units.
def eql?(other)
basically_equal?(value, other.value) && numerator_units == other.numerator_units &&
denominator_units == other.denominator_units
end
# The SassScript `>` operation.
#
# @param other [Number] The right-hand side of the operator
# @return [Boolean] Whether this number is greater than the other
# @raise [NoMethodError] if `other` is an invalid type
def gt(other)
raise NoMethodError.new(nil, :gt) unless other.is_a?(Number)
operate(other, :>)
end
# The SassScript `>=` operation.
#
# @param other [Number] The right-hand side of the operator
# @return [Boolean] Whether this number is greater than or equal to the other
# @raise [NoMethodError] if `other` is an invalid type
def gte(other)
raise NoMethodError.new(nil, :gte) unless other.is_a?(Number)
operate(other, :>=)
end
# The SassScript `<` operation.
#
# @param other [Number] The right-hand side of the operator
# @return [Boolean] Whether this number is less than the other
# @raise [NoMethodError] if `other` is an invalid type
def lt(other)
raise NoMethodError.new(nil, :lt) unless other.is_a?(Number)
operate(other, :<)
end
# The SassScript `<=` operation.
#
# @param other [Number] The right-hand side of the operator
# @return [Boolean] Whether this number is less than or equal to the other
# @raise [NoMethodError] if `other` is an invalid type
def lte(other)
raise NoMethodError.new(nil, :lte) unless other.is_a?(Number)
operate(other, :<=)
end
# @return [String] The CSS representation of this number
# @raise [Sass::SyntaxError] if this number has units that can't be used in CSS
# (e.g. `px*in`)
def to_s(opts = {})
return original if original
raise Sass::SyntaxError.new("#{inspect} isn't a valid CSS value.") unless legal_units?
inspect
end
# Returns a readable representation of this number.
#
# This representation is valid CSS (and valid SassScript)
# as long as there is only one unit.
#
# @return [String] The representation
def inspect(opts = {})
return original if original
value = self.class.round(self.value)
str = value.to_s
# Ruby will occasionally print in scientific notation if the number is
# small enough. That's technically valid CSS, but it's not well-supported
# and confusing.
str = ("%0.#{self.class.precision}f" % value).gsub(/0*$/, '') if str.include?('e')
# Sometimes numeric formatting will result in a decimal number with a trailing zero (x.0)
if str =~ /(.*)\.0$/
str = $1
end
# We omit a leading zero before the decimal point in compressed mode.
if @options && options[:style] == :compressed
str.sub!(/^(-)?0\./, '\1.')
end
unitless? ? str : "#{str}#{unit_str}"
end
alias_method :to_sass, :inspect
# @return [Integer] The integer value of the number
# @raise [Sass::SyntaxError] if the number isn't an integer
def to_i
super unless int?
value.to_i
end
# @return [Boolean] Whether or not this number is an integer.
def int?
basically_equal?(value % 1, 0.0)
end
# @return [Boolean] Whether or not this number has no units.
def unitless?
@numerator_units.empty? && @denominator_units.empty?
end
# Checks whether the number has the numerator unit specified.
#
# @example
# number = Sass::Script::Value::Number.new(10, "px")
# number.is_unit?("px") => true
# number.is_unit?(nil) => false
#
# @param unit [::String, nil] The unit the number should have or nil if the number
# should be unitless.
# @see Number#unitless? The unitless? method may be more readable.
def is_unit?(unit)
if unit
denominator_units.size == 0 && numerator_units.size == 1 && numerator_units.first == unit
else
unitless?
end
end
# @return [Boolean] Whether or not this number has units that can be represented in CSS
# (that is, zero or one \{#numerator\_units}).
def legal_units?
(@numerator_units.empty? || @numerator_units.size == 1) && @denominator_units.empty?
end
# Returns this number converted to other units.
# The conversion takes into account the relationship between e.g. mm and cm,
# as well as between e.g. in and cm.
#
# If this number has no units, it will simply return itself
# with the given units.
#
# An incompatible coercion, e.g. between px and cm, will raise an error.
#
# @param num_units [Array<String>] The numerator units to coerce this number into.
# See {\#numerator\_units}
# @param den_units [Array<String>] The denominator units to coerce this number into.
# See {\#denominator\_units}
# @return [Number] The number with the new units
# @raise [Sass::UnitConversionError] if the given units are incompatible with the number's
# current units
def coerce(num_units, den_units)
Number.new(if unitless?
value
else
value * coercion_factor(@numerator_units, num_units) /
coercion_factor(@denominator_units, den_units)
end, num_units, den_units)
end
# @param other [Number] A number to decide if it can be compared with this number.
# @return [Boolean] Whether or not this number can be compared with the other.
def comparable_to?(other)
operate(other, :+)
true
rescue Sass::UnitConversionError
false
end
# Returns a human readable representation of the units in this number.
# For complex units this takes the form of:
# numerator_unit1 * numerator_unit2 / denominator_unit1 * denominator_unit2
# @return [String] a string that represents the units in this number
def unit_str
rv = @numerator_units.sort.join("*")
if @denominator_units.any?
rv << "/"
rv << @denominator_units.sort.join("*")
end
rv
end
private
# @private
# @see Sass::Script::Number.basically_equal?
def basically_equal?(num1, num2)
self.class.basically_equal?(num1, num2)
end
# Checks whether two numbers are within an epsilon of each other.
# @return [Boolean]
def self.basically_equal?(num1, num2)
(num1 - num2).abs < epsilon
end
# @private
def self.round(num)
if num.is_a?(Float) && (num.infinite? || num.nan?)
num
elsif basically_equal?(num % 1, 0.0)
num.round
else
((num * precision_factor).round / precision_factor).to_f
end
end
OPERATIONS = [:+, :-, :<=, :<, :>, :>=, :%]
def operate(other, operation)
this = self
if OPERATIONS.include?(operation)
if unitless?
this = this.coerce(other.numerator_units, other.denominator_units)
else
other = other.coerce(@numerator_units, @denominator_units)
end
end
# avoid integer division
value = :/ == operation ? this.value.to_f : this.value
result = value.send(operation, other.value)
if result.is_a?(Numeric)
Number.new(result, *compute_units(this, other, operation))
else # Boolean op
Bool.new(result)
end
end
def coercion_factor(from_units, to_units)
# get a list of unmatched units
from_units, to_units = sans_common_units(from_units, to_units)
if from_units.size != to_units.size || !convertable?(from_units | to_units)
raise Sass::UnitConversionError.new(
"Incompatible units: '#{from_units.join('*')}' and '#{to_units.join('*')}'.")
end
from_units.zip(to_units).inject(1) {|m, p| m * conversion_factor(p[0], p[1])}
end
def compute_units(this, other, operation)
case operation
when :*
[this.numerator_units + other.numerator_units,
this.denominator_units + other.denominator_units]
when :/
[this.numerator_units + other.denominator_units,
this.denominator_units + other.numerator_units]
else
[this.numerator_units, this.denominator_units]
end
end
def normalize!
return if unitless?
@numerator_units, @denominator_units =
sans_common_units(@numerator_units, @denominator_units)
@denominator_units.each_with_index do |d, i|
next unless convertable?(d) && (u = @numerator_units.find {|n| convertable?([n, d])})
@value /= conversion_factor(d, u)
@denominator_units.delete_at(i)
@numerator_units.delete_at(@numerator_units.index(u))
end
end
# This is the source data for all the unit logic. It's pre-processed to make
# it efficient to figure out whether a set of units is mutually compatible
# and what the conversion ratio is between two units.
#
# These come from http://www.w3.org/TR/2012/WD-css3-values-20120308/.
relative_sizes = [
{
'in' => Rational(1),
'cm' => Rational(1, 2.54),
'pc' => Rational(1, 6),
'mm' => Rational(1, 25.4),
'q' => Rational(1, 101.6),
'pt' => Rational(1, 72),
'px' => Rational(1, 96)
},
{
'deg' => Rational(1, 360),
'grad' => Rational(1, 400),
'rad' => Rational(1, 2 * Math::PI),
'turn' => Rational(1)
},
{
's' => Rational(1),
'ms' => Rational(1, 1000)
},
{
'Hz' => Rational(1),
'kHz' => Rational(1000)
},
{
'dpi' => Rational(1),
'dpcm' => Rational(254, 100),
'dppx' => Rational(96)
}
]
# A hash from each known unit to the set of units that it's mutually
# convertible with.
MUTUALLY_CONVERTIBLE = {}
relative_sizes.map do |values|
set = values.keys.to_set
values.keys.each {|name| MUTUALLY_CONVERTIBLE[name] = set}
end
# A two-dimensional hash from two units to the conversion ratio between
# them. Multiply `X` by `CONVERSION_TABLE[X][Y]` to convert it to `Y`.
CONVERSION_TABLE = {}
relative_sizes.each do |values|
values.each do |(name1, value1)|
CONVERSION_TABLE[name1] ||= {}
values.each do |(name2, value2)|
value = value1 / value2
CONVERSION_TABLE[name1][name2] = value.denominator == 1 ? value.to_i : value.to_f
end
end
end
def conversion_factor(from_unit, to_unit)
CONVERSION_TABLE[from_unit][to_unit]
end
def convertable?(units)
units = Array(units).to_set
return true if units.empty?
return false unless (mutually_convertible = MUTUALLY_CONVERTIBLE[units.first])
units.subset?(mutually_convertible)
end
def sans_common_units(units1, units2)
units2 = units2.dup
# Can't just use -, because we want px*px to coerce properly to px*mm
units1 = units1.map do |u|
j = units2.index(u)
next u unless j
units2.delete_at(j)
nil
end
units1.compact!
return units1, units2
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/string.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/string.rb | # -*- coding: utf-8 -*-
module Sass::Script::Value
# A SassScript object representing a CSS string *or* a CSS identifier.
class String < Base
@@interpolation_deprecation = Sass::Deprecation.new
# The Ruby value of the string.
#
# @return [String]
attr_reader :value
# Whether this is a CSS string or a CSS identifier.
# The difference is that strings are written with double-quotes,
# while identifiers aren't.
#
# @return [Symbol] `:string` or `:identifier`
attr_reader :type
def self.value(contents)
contents.gsub("\\\n", "").gsub(/\\(?:([0-9a-fA-F]{1,6})\s?|(.))/) do
next $2 if $2
# Handle unicode escapes as per CSS Syntax Level 3 section 4.3.8.
code_point = $1.to_i(16)
if code_point == 0 || code_point > 0x10FFFF ||
(code_point >= 0xD800 && code_point <= 0xDFFF)
'�'
else
[code_point].pack("U")
end
end
end
# Returns the quoted string representation of `contents`.
#
# @options opts :quote [String]
# The preferred quote style for quoted strings. If `:none`, strings are
# always emitted unquoted. If `nil`, quoting is determined automatically.
# @options opts :sass [String]
# Whether to quote strings for Sass source, as opposed to CSS. Defaults to `false`.
def self.quote(contents, opts = {})
quote = opts[:quote]
# Short-circuit if there are no characters that need quoting.
unless contents =~ /[\n\\"']|\#\{/
quote ||= '"'
return "#{quote}#{contents}#{quote}"
end
if quote.nil?
if contents.include?('"')
if contents.include?("'")
quote = '"'
else
quote = "'"
end
else
quote = '"'
end
end
# Replace single backslashes with multiples.
contents = contents.gsub("\\", "\\\\\\\\")
# Escape interpolation.
contents = contents.gsub('#{', "\\\#{") if opts[:sass]
if quote == '"'
contents = contents.gsub('"', "\\\"")
else
contents = contents.gsub("'", "\\'")
end
contents = contents.gsub(/\n(?![a-fA-F0-9\s])/, "\\a").gsub("\n", "\\a ")
"#{quote}#{contents}#{quote}"
end
# Creates a new string.
#
# @param value [String] See \{#value}
# @param type [Symbol] See \{#type}
# @param deprecated_interp_equivalent [String?]
# If this was created via a potentially-deprecated string interpolation,
# this is the replacement expression that should be suggested to the user.
def initialize(value, type = :identifier, deprecated_interp_equivalent = nil)
super(value)
@type = type
@deprecated_interp_equivalent = deprecated_interp_equivalent
end
# @see Value#plus
def plus(other)
other_value = if other.is_a?(Sass::Script::Value::String)
other.value
else
other.to_s(:quote => :none)
end
Sass::Script::Value::String.new(value + other_value, type)
end
# @see Value#to_s
def to_s(opts = {})
return @value.gsub(/\n\s*/, ' ') if opts[:quote] == :none || @type == :identifier
String.quote(value, opts)
end
# @see Value#to_sass
def to_sass(opts = {})
to_s(opts.merge(:sass => true))
end
def separator
check_deprecated_interp
super
end
def to_a
check_deprecated_interp
super
end
# Prints a warning if this string was created using potentially-deprecated
# interpolation.
def check_deprecated_interp
return unless @deprecated_interp_equivalent
@@interpolation_deprecation.warn(source_range.file, source_range.start_pos.line, <<WARNING)
\#{} interpolation near operators will be simplified in a future version of Sass.
To preserve the current behavior, use quotes:
#{@deprecated_interp_equivalent}
WARNING
end
def inspect
String.quote(value)
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/list.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/list.rb | module Sass::Script::Value
# A SassScript object representing a CSS list.
# This includes both comma-separated lists and space-separated lists.
class List < Base
# The Ruby array containing the contents of the list.
#
# @return [Array<Value>]
attr_reader :value
alias_method :to_a, :value
# The operator separating the values of the list.
# Either `:comma` or `:space`.
#
# @return [Symbol]
attr_reader :separator
# Whether the list is surrounded by square brackets.
#
# @return [Boolean]
attr_reader :bracketed
# Creates a new list.
#
# @param value [Array<Value>] See \{#value}
# @param separator [Symbol] See \{#separator}
# @param bracketed [Boolean] See \{#bracketed}
def initialize(value, separator: nil, bracketed: false)
super(value)
@separator = separator
@bracketed = bracketed
end
# @see Value#options=
def options=(options)
super
value.each {|v| v.options = options}
end
# @see Value#eq
def eq(other)
Sass::Script::Value::Bool.new(
other.is_a?(List) && value == other.value &&
separator == other.separator && bracketed == other.bracketed)
end
def hash
@hash ||= [value, separator, bracketed].hash
end
# @see Value#to_s
def to_s(opts = {})
if !bracketed && value.empty?
raise Sass::SyntaxError.new("#{inspect} isn't a valid CSS value.")
end
members = value.
reject {|e| e.is_a?(Null) || e.is_a?(List) && e.value.empty?}.
map {|e| e.to_s(opts)}
contents = members.join(sep_str)
bracketed ? "[#{contents}]" : contents
end
# @see Value#to_sass
def to_sass(opts = {})
return bracketed ? "[]" : "()" if value.empty?
members = value.map do |v|
if element_needs_parens?(v)
"(#{v.to_sass(opts)})"
else
v.to_sass(opts)
end
end
if separator == :comma && members.length == 1
return "#{bracketed ? '[' : '('}#{members.first},#{bracketed ? ']' : ')'}"
end
contents = members.join(sep_str(nil))
bracketed ? "[#{contents}]" : contents
end
# @see Value#to_h
def to_h
return {} if value.empty?
super
end
# @see Value#inspect
def inspect
(bracketed ? '[' : '(') +
value.map {|e| e.inspect}.join(sep_str(nil)) +
(bracketed ? ']' : ')')
end
# Asserts an index is within the list.
#
# @private
#
# @param list [Sass::Script::Value::List] The list for which the index should be checked.
# @param n [Sass::Script::Value::Number] The index being checked.
def self.assert_valid_index(list, n)
if !n.int? || n.to_i == 0
raise ArgumentError.new("List index #{n} must be a non-zero integer")
elsif list.to_a.size == 0
raise ArgumentError.new("List index is #{n} but list has no items")
elsif n.to_i.abs > (size = list.to_a.size)
raise ArgumentError.new(
"List index is #{n} but list is only #{size} item#{'s' if size != 1} long")
end
end
private
def element_needs_parens?(element)
if element.is_a?(List)
return false if element.value.length < 2
return false if element.bracketed
precedence = Sass::Script::Parser.precedence_of(separator || :space)
return Sass::Script::Parser.precedence_of(element.separator || :space) <= precedence
end
return false unless separator == :space
return false unless element.is_a?(Sass::Script::Tree::UnaryOperation)
element.operator == :minus || element.operator == :plus
end
def sep_str(opts = options)
return ' ' if separator == :space
return ',' if opts && opts[:style] == :compressed
', '
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/function.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/function.rb | module Sass::Script::Value
# A SassScript object representing a function.
class Function < Callable
# Constructs a Function value for use in SassScript.
#
# @param function [Sass::Callable] The callable to be used when the
# function is invoked.
def initialize(function)
unless function.type == "function"
raise ArgumentError.new("A callable of type function was expected.")
end
super
end
def to_sass
%{get-function("#{value.name}")}
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/map.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/map.rb | module Sass::Script::Value
# A SassScript object representing a map from keys to values. Both keys and
# values can be any SassScript object.
class Map < Base
# The Ruby hash containing the contents of this map.
#
# @return [Hash<Node, Node>]
attr_reader :value
alias_method :to_h, :value
# Creates a new map.
#
# @param hash [Hash<Node, Node>]
def initialize(hash)
super(hash)
end
# @see Value#options=
def options=(options)
super
value.each do |k, v|
k.options = options
v.options = options
end
end
# @see Value#separator
def separator
:comma unless value.empty?
end
# @see Value#to_a
def to_a
value.map do |k, v|
list = List.new([k, v], separator: :space)
list.options = options
list
end
end
# @see Value#eq
def eq(other)
Bool.new(other.is_a?(Map) && value == other.value)
end
def hash
@hash ||= value.hash
end
# @see Value#to_s
def to_s(opts = {})
raise Sass::SyntaxError.new("#{inspect} isn't a valid CSS value.")
end
def to_sass(opts = {})
return "()" if value.empty?
to_sass = lambda do |value|
if value.is_a?(List) && value.separator == :comma
"(#{value.to_sass(opts)})"
else
value.to_sass(opts)
end
end
"(#{value.map {|(k, v)| "#{to_sass[k]}: #{to_sass[v]}"}.join(', ')})"
end
alias_method :inspect, :to_sass
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/arg_list.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/value/arg_list.rb | module Sass::Script::Value
# A SassScript object representing a variable argument list. This works just
# like a normal list, but can also contain keyword arguments.
#
# The keyword arguments attached to this list are unused except when this is
# passed as a glob argument to a function or mixin.
class ArgList < List
# Whether \{#keywords} has been accessed. If so, we assume that all keywords
# were valid for the function that created this ArgList.
#
# @return [Boolean]
attr_accessor :keywords_accessed
# Creates a new argument list.
#
# @param value [Array<Value>] See \{List#value}.
# @param keywords [Hash<String, Value>, NormalizedMap<Value>] See \{#keywords}
# @param separator [String] See \{List#separator}.
def initialize(value, keywords, separator)
super(value, separator: separator)
if keywords.is_a?(Sass::Util::NormalizedMap)
@keywords = keywords
else
@keywords = Sass::Util::NormalizedMap.new(keywords)
end
end
# The keyword arguments attached to this list.
#
# @return [NormalizedMap<Value>]
def keywords
@keywords_accessed = true
@keywords
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/selector.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/selector.rb | module Sass::Script::Tree
# A SassScript node that will resolve to the current selector.
class Selector < Node
def initialize; end
def children
[]
end
def to_sass(opts = {})
'&'
end
def deep_copy
dup
end
protected
def _perform(environment)
selector = environment.selector
return opts(Sass::Script::Value::Null.new) unless selector
opts(selector.to_sass_script)
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/map_literal.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/map_literal.rb | module Sass::Script::Tree
# A class representing a map literal. When resolved, this returns a
# {Sass::Script::Node::Map}.
class MapLiteral < Node
# The key/value pairs that make up this map node. This isn't a Hash so that
# we can detect key collisions once all the keys have been performed.
#
# @return [Array<(Node, Node)>]
attr_reader :pairs
# Creates a new map literal.
#
# @param pairs [Array<(Node, Node)>] See \{#pairs}
def initialize(pairs)
@pairs = pairs
end
# @see Node#children
def children
@pairs.flatten
end
# @see Node#to_sass
def to_sass(opts = {})
return "()" if pairs.empty?
to_sass = lambda do |value|
if value.is_a?(ListLiteral) && value.separator == :comma
"(#{value.to_sass(opts)})"
else
value.to_sass(opts)
end
end
"(" + pairs.map {|(k, v)| "#{to_sass[k]}: #{to_sass[v]}"}.join(', ') + ")"
end
alias_method :inspect, :to_sass
# @see Node#deep_copy
def deep_copy
node = dup
node.instance_variable_set('@pairs',
pairs.map {|(k, v)| [k.deep_copy, v.deep_copy]})
node
end
protected
# @see Node#_perform
def _perform(environment)
keys = Set.new
map = Sass::Script::Value::Map.new(Hash[pairs.map do |(k, v)|
k, v = k.perform(environment), v.perform(environment)
if keys.include?(k)
raise Sass::SyntaxError.new("Duplicate key #{k.inspect} in map #{to_sass}.")
end
keys << k
[k, v]
end])
map.options = options
map
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/interpolation.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/interpolation.rb | module Sass::Script::Tree
# A SassScript object representing `#{}` interpolation outside a string.
#
# @see StringInterpolation
class Interpolation < Node
# @return [Node] The SassScript before the interpolation
attr_reader :before
# @return [Node] The SassScript within the interpolation
attr_reader :mid
# @return [Node] The SassScript after the interpolation
attr_reader :after
# @return [Boolean] Whether there was whitespace between `before` and `#{`
attr_reader :whitespace_before
# @return [Boolean] Whether there was whitespace between `}` and `after`
attr_reader :whitespace_after
# @return [Boolean] Whether the original format of the interpolation was
# plain text, not an interpolation. This is used when converting back to
# SassScript.
attr_reader :originally_text
# @return [Boolean] Whether a color value passed to the interpolation should
# generate a warning.
attr_reader :warn_for_color
# The type of interpolation deprecation for this node.
#
# This can be `:none`, indicating that the node doesn't use deprecated
# interpolation; `:immediate`, indicating that a deprecation warning should
# be emitted as soon as possible; or `:potential`, indicating that a
# deprecation warning should be emitted if the resulting string is used in a
# way that would distinguish it from a list.
#
# @return [Symbol]
attr_reader :deprecation
# Interpolation in a property is of the form `before #{mid} after`.
#
# @param before [Node] See {Interpolation#before}
# @param mid [Node] See {Interpolation#mid}
# @param after [Node] See {Interpolation#after}
# @param wb [Boolean] See {Interpolation#whitespace_before}
# @param wa [Boolean] See {Interpolation#whitespace_after}
# @param originally_text [Boolean] See {Interpolation#originally_text}
# @param warn_for_color [Boolean] See {Interpolation#warn_for_color}
def initialize(before, mid, after, wb, wa, opts = {})
@before = before
@mid = mid
@after = after
@whitespace_before = wb
@whitespace_after = wa
@originally_text = opts[:originally_text] || false
@warn_for_color = opts[:warn_for_color] || false
@deprecation = opts[:deprecation] || :none
end
# @return [String] A human-readable s-expression representation of the interpolation
def inspect
"(interpolation #{@before.inspect} #{@mid.inspect} #{@after.inspect})"
end
# @see Node#to_sass
def to_sass(opts = {})
return to_quoted_equivalent.to_sass if deprecation == :immediate
res = ""
res << @before.to_sass(opts) if @before
res << ' ' if @before && @whitespace_before
res << '#{' unless @originally_text
res << @mid.to_sass(opts)
res << '}' unless @originally_text
res << ' ' if @after && @whitespace_after
res << @after.to_sass(opts) if @after
res
end
# Returns an `unquote()` expression that will evaluate to the same value as
# this interpolation.
#
# @return [Sass::Script::Tree::Node]
def to_quoted_equivalent
Funcall.new(
"unquote",
[to_string_interpolation(self)],
Sass::Util::NormalizedMap.new,
nil,
nil)
end
# Returns the three components of the interpolation, `before`, `mid`, and `after`.
#
# @return [Array<Node>]
# @see #initialize
# @see Node#children
def children
[@before, @mid, @after].compact
end
# @see Node#deep_copy
def deep_copy
node = dup
node.instance_variable_set('@before', @before.deep_copy) if @before
node.instance_variable_set('@mid', @mid.deep_copy)
node.instance_variable_set('@after', @after.deep_copy) if @after
node
end
protected
# Converts a script node into a corresponding string interpolation
# expression.
#
# @param node_or_interp [Sass::Script::Tree::Node]
# @return [Sass::Script::Tree::StringInterpolation]
def to_string_interpolation(node_or_interp)
unless node_or_interp.is_a?(Interpolation)
node = node_or_interp
return string_literal(node.value.to_s) if node.is_a?(Literal)
if node.is_a?(StringInterpolation)
return concat(string_literal(node.quote), concat(node, string_literal(node.quote)))
end
return StringInterpolation.new(string_literal(""), node, string_literal(""))
end
interp = node_or_interp
after_string_or_interp =
if interp.after
to_string_interpolation(interp.after)
else
string_literal("")
end
if interp.after && interp.whitespace_after
after_string_or_interp = concat(string_literal(' '), after_string_or_interp)
end
mid_string_or_interp = to_string_interpolation(interp.mid)
before_string_or_interp =
if interp.before
to_string_interpolation(interp.before)
else
string_literal("")
end
if interp.before && interp.whitespace_before
before_string_or_interp = concat(before_string_or_interp, string_literal(' '))
end
concat(before_string_or_interp, concat(mid_string_or_interp, after_string_or_interp))
end
private
# Evaluates the interpolation.
#
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
# @return [Sass::Script::Value::String]
# The SassScript string that is the value of the interpolation
def _perform(environment)
res = ""
res << @before.perform(environment).to_s if @before
res << " " if @before && @whitespace_before
val = @mid.perform(environment)
if @warn_for_color && val.is_a?(Sass::Script::Value::Color) && val.name
alternative = Operation.new(Sass::Script::Value::String.new("", :string), @mid, :plus)
Sass::Util.sass_warn <<MESSAGE
WARNING on line #{line}, column #{source_range.start_pos.offset}#{" of #{filename}" if filename}:
You probably don't mean to use the color value `#{val}' in interpolation here.
It may end up represented as #{val.inspect}, which will likely produce invalid CSS.
Always quote color names when using them as strings (for example, "#{val}").
If you really want to use the color value here, use `#{alternative.to_sass}'.
MESSAGE
end
res << val.to_s(:quote => :none)
res << " " if @after && @whitespace_after
res << @after.perform(environment).to_s if @after
str = Sass::Script::Value::String.new(
res, :identifier,
(to_quoted_equivalent.to_sass if deprecation == :potential))
str.source_range = source_range
opts(str)
end
# Concatenates two string literals or string interpolation expressions.
#
# @param string_or_interp1 [Sass::Script::Tree::Literal|Sass::Script::Tree::StringInterpolation]
# @param string_or_interp2 [Sass::Script::Tree::Literal|Sass::Script::Tree::StringInterpolation]
# @return [Sass::Script::Tree::StringInterpolation]
def concat(string_or_interp1, string_or_interp2)
if string_or_interp1.is_a?(Literal) && string_or_interp2.is_a?(Literal)
return string_literal(string_or_interp1.value.value + string_or_interp2.value.value)
end
if string_or_interp1.is_a?(Literal)
string = string_or_interp1
interp = string_or_interp2
before = string_literal(string.value.value + interp.before.value.value)
return StringInterpolation.new(before, interp.mid, interp.after)
end
StringInterpolation.new(
string_or_interp1.before,
string_or_interp1.mid,
concat(string_or_interp1.after, string_or_interp2))
end
# Returns a string literal with the given contents.
#
# @param string [String]
# @return string [Sass::Script::Tree::Literal]
def string_literal(string)
Literal.new(Sass::Script::Value::String.new(string, :string))
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/funcall.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/funcall.rb | require 'sass/script/functions'
require 'sass/util'
module Sass::Script::Tree
# A SassScript parse node representing a function call.
#
# A function call either calls one of the functions in
# {Sass::Script::Functions}, or if no function with the given name exists it
# returns a string representation of the function call.
class Funcall < Node
# The name of the function.
#
# @return [String]
attr_reader :name
# The callable to be invoked
#
# @return [Sass::Callable] or nil if no callable is provided.
attr_reader :callable
# The arguments to the function.
#
# @return [Array<Node>]
attr_reader :args
# The keyword arguments to the function.
#
# @return [Sass::Util::NormalizedMap<Node>]
attr_reader :keywords
# The first splat argument for this function, if one exists.
#
# This could be a list of positional arguments, a map of keyword
# arguments, or an arglist containing both.
#
# @return [Node?]
attr_accessor :splat
# The second splat argument for this function, if one exists.
#
# If this exists, it's always a map of keyword arguments, and
# \{#splat} is always either a list or an arglist.
#
# @return [Node?]
attr_accessor :kwarg_splat
# @param name_or_callable [String, Sass::Callable] See \{#name}
# @param args [Array<Node>] See \{#args}
# @param keywords [Sass::Util::NormalizedMap<Node>] See \{#keywords}
# @param splat [Node] See \{#splat}
# @param kwarg_splat [Node] See \{#kwarg_splat}
def initialize(name_or_callable, args, keywords, splat, kwarg_splat)
if name_or_callable.is_a?(Sass::Callable)
@callable = name_or_callable
@name = name_or_callable.name
else
@callable = nil
@name = name_or_callable
end
@args = args
@keywords = keywords
@splat = splat
@kwarg_splat = kwarg_splat
super()
end
# @return [String] A string representation of the function call
def inspect
args = @args.map {|a| a.inspect}.join(', ')
keywords = @keywords.as_stored.to_a.map {|k, v| "$#{k}: #{v.inspect}"}.join(', ')
if self.splat
splat = args.empty? && keywords.empty? ? "" : ", "
splat = "#{splat}#{self.splat.inspect}..."
splat = "#{splat}, #{kwarg_splat.inspect}..." if kwarg_splat
end
"#{name}(#{args}#{', ' unless args.empty? || keywords.empty?}#{keywords}#{splat})"
end
# @see Node#to_sass
def to_sass(opts = {})
arg_to_sass = lambda do |arg|
sass = arg.to_sass(opts)
sass = "(#{sass})" if arg.is_a?(Sass::Script::Tree::ListLiteral) && arg.separator == :comma
sass
end
args = @args.map(&arg_to_sass)
keywords = @keywords.as_stored.to_a.map {|k, v| "$#{dasherize(k, opts)}: #{arg_to_sass[v]}"}
if self.splat
splat = "#{arg_to_sass[self.splat]}..."
kwarg_splat = "#{arg_to_sass[self.kwarg_splat]}..." if self.kwarg_splat
end
arglist = [args, splat, keywords, kwarg_splat].flatten.compact.join(', ')
"#{dasherize(name, opts)}(#{arglist})"
end
# Returns the arguments to the function.
#
# @return [Array<Node>]
# @see Node#children
def children
res = @args + @keywords.values
res << @splat if @splat
res << @kwarg_splat if @kwarg_splat
res
end
# @see Node#deep_copy
def deep_copy
node = dup
node.instance_variable_set('@args', args.map {|a| a.deep_copy})
copied_keywords = Sass::Util::NormalizedMap.new
@keywords.as_stored.each {|k, v| copied_keywords[k] = v.deep_copy}
node.instance_variable_set('@keywords', copied_keywords)
node
end
protected
# Evaluates the function call.
#
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
# @return [Sass::Script::Value] The SassScript object that is the value of the function call
# @raise [Sass::SyntaxError] if the function call raises an ArgumentError
def _perform(environment)
args = @args.each_with_index.
map {|a, i| perform_arg(a, environment, signature && signature.args[i])}
keywords = Sass::Util.map_hash(@keywords) do |k, v|
[k, perform_arg(v, environment, k.tr('-', '_'))]
end
splat = Sass::Tree::Visitors::Perform.perform_splat(
@splat, keywords, @kwarg_splat, environment)
fn = @callable || environment.function(@name)
if fn && fn.origin == :stylesheet
environment.stack.with_function(filename, line, name) do
return without_original(perform_sass_fn(fn, args, splat, environment))
end
end
args = construct_ruby_args(ruby_name, args, splat, environment)
if Sass::Script::Functions.callable?(ruby_name) && (!fn || fn.origin == :builtin)
local_environment = Sass::Environment.new(environment.global_env, environment.options)
local_environment.caller = Sass::ReadOnlyEnvironment.new(environment, environment.options)
result = local_environment.stack.with_function(filename, line, name) do
opts(Sass::Script::Functions::EvaluationContext.new(
local_environment).send(ruby_name, *args))
end
without_original(result)
else
opts(to_literal(args))
end
rescue ArgumentError => e
reformat_argument_error(e)
end
# Compass historically overrode this before it changed name to {Funcall#to_value}.
# We should get rid of it in the future.
def to_literal(args)
to_value(args)
end
# This method is factored out from `_perform` so that compass can override
# it with a cross-browser implementation for functions that require vendor prefixes
# in the generated css.
def to_value(args)
Sass::Script::Value::String.new("#{name}(#{args.join(', ')})")
end
private
def ruby_name
@ruby_name ||= @name.tr('-', '_')
end
def perform_arg(argument, environment, name)
return argument if signature && signature.delayed_args.include?(name)
argument.perform(environment)
end
def signature
@signature ||= Sass::Script::Functions.signature(name.to_sym, @args.size, @keywords.size)
end
def without_original(value)
return value unless value.is_a?(Sass::Script::Value::Number)
value = value.dup
value.original = nil
value
end
def construct_ruby_args(name, args, splat, environment)
args += splat.to_a if splat
# All keywords are contained in splat.keywords for consistency,
# even if there were no splats passed in.
old_keywords_accessed = splat.keywords_accessed
keywords = splat.keywords
splat.keywords_accessed = old_keywords_accessed
unless (signature = Sass::Script::Functions.signature(name.to_sym, args.size, keywords.size))
return args if keywords.empty?
raise Sass::SyntaxError.new("Function #{name} doesn't support keyword arguments")
end
# If the user passes more non-keyword args than the function expects,
# but it does expect keyword args, Ruby's arg handling won't raise an error.
# Since we don't want to make functions think about this,
# we'll handle it for them here.
if signature.var_kwargs && !signature.var_args && args.size > signature.args.size
raise Sass::SyntaxError.new(
"#{args[signature.args.size].inspect} is not a keyword argument for `#{name}'")
elsif keywords.empty?
args << {} if signature.var_kwargs
return args
end
argnames = signature.args[args.size..-1] || []
deprecated_argnames = (signature.deprecated && signature.deprecated[args.size..-1]) || []
args += argnames.zip(deprecated_argnames).map do |(argname, deprecated_argname)|
if keywords.has_key?(argname)
keywords.delete(argname)
elsif deprecated_argname && keywords.has_key?(deprecated_argname)
deprecated_argname = keywords.denormalize(deprecated_argname)
Sass::Util.sass_warn("DEPRECATION WARNING: The `$#{deprecated_argname}' argument for " +
"`#{@name}()' has been renamed to `$#{argname}'.")
keywords.delete(deprecated_argname)
else
raise Sass::SyntaxError.new("Function #{name} requires an argument named $#{argname}")
end
end
if keywords.size > 0
if signature.var_kwargs
# Don't pass a NormalizedMap to a Ruby function.
args << keywords.to_hash
else
argname = keywords.keys.sort.first
if signature.args.include?(argname)
raise Sass::SyntaxError.new(
"Function #{name} was passed argument $#{argname} both by position and by name")
else
raise Sass::SyntaxError.new(
"Function #{name} doesn't have an argument named $#{argname}")
end
end
end
args
end
def perform_sass_fn(function, args, splat, environment)
Sass::Tree::Visitors::Perform.perform_arguments(function, args, splat, environment) do |env|
env.caller = Sass::Environment.new(environment)
val = catch :_sass_return do
function.tree.each {|c| Sass::Tree::Visitors::Perform.visit(c, env)}
raise Sass::SyntaxError.new("Function #{@name} finished without @return")
end
val
end
end
def reformat_argument_error(e)
message = e.message
# If this is a legitimate Ruby-raised argument error, re-raise it.
# Otherwise, it's an error in the user's stylesheet, so wrap it.
if Sass::Util.rbx?
# Rubinius has a different error report string than vanilla Ruby. It
# also doesn't put the actual method for which the argument error was
# thrown in the backtrace, nor does it include `send`, so we look for
# `_perform`.
if e.message =~ /^method '([^']+)': given (\d+), expected (\d+)/
error_name, given, expected = $1, $2, $3
raise e if error_name != ruby_name || e.backtrace[0] !~ /:in `_perform'$/
message = "wrong number of arguments (#{given} for #{expected})"
end
elsif Sass::Util.jruby?
should_maybe_raise =
e.message =~ /^wrong number of arguments calling `[^`]+` \((\d+) for (\d+)\)/
given, expected = $1, $2
if should_maybe_raise
# JRuby 1.7 includes __send__ before send and _perform.
trace = e.backtrace.dup
raise e if trace.shift !~ /:in `__send__'$/
# JRuby (as of 1.7.2) doesn't put the actual method
# for which the argument error was thrown in the backtrace, so we
# detect whether our send threw an argument error.
if !(trace[0] =~ /:in `send'$/ && trace[1] =~ /:in `_perform'$/)
raise e
else
# JRuby 1.7 doesn't use standard formatting for its ArgumentErrors.
message = "wrong number of arguments (#{given} for #{expected})"
end
end
elsif (md = /^wrong number of arguments \(given (\d+), expected (\d+)\)/.match(e.message)) &&
e.backtrace[0] =~ /:in `#{ruby_name}'$/
# Handle ruby 2.3 error formatting
message = "wrong number of arguments (#{md[1]} for #{md[2]})"
elsif e.message =~ /^wrong number of arguments/ &&
e.backtrace[0] !~ /:in `(block in )?#{ruby_name}'$/
raise e
end
raise Sass::SyntaxError.new("#{message} for `#{name}'")
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/unary_operation.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/unary_operation.rb | module Sass::Script::Tree
# A SassScript parse node representing a unary operation,
# such as `-$b` or `not true`.
#
# Currently only `-`, `/`, and `not` are unary operators.
class UnaryOperation < Node
# @return [Symbol] The operation to perform
attr_reader :operator
# @return [Script::Node] The parse-tree node for the object of the operator
attr_reader :operand
# @param operand [Script::Node] See \{#operand}
# @param operator [Symbol] See \{#operator}
def initialize(operand, operator)
@operand = operand
@operator = operator
super()
end
# @return [String] A human-readable s-expression representation of the operation
def inspect
"(#{@operator.inspect} #{@operand.inspect})"
end
# @see Node#to_sass
def to_sass(opts = {})
operand = @operand.to_sass(opts)
if @operand.is_a?(Operation) ||
(@operator == :minus &&
(operand =~ Sass::SCSS::RX::IDENT) == 0)
operand = "(#{@operand.to_sass(opts)})"
end
op = Sass::Script::Lexer::OPERATORS_REVERSE[@operator]
op + (op =~ /[a-z]/ ? " " : "") + operand
end
# Returns the operand of the operation.
#
# @return [Array<Node>]
# @see Node#children
def children
[@operand]
end
# @see Node#deep_copy
def deep_copy
node = dup
node.instance_variable_set('@operand', @operand.deep_copy)
node
end
protected
# Evaluates the operation.
#
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
# @return [Sass::Script::Value] The SassScript object that is the value of the operation
# @raise [Sass::SyntaxError] if the operation is undefined for the operand
def _perform(environment)
operator = "unary_#{@operator}"
value = @operand.perform(environment)
value.send(operator)
rescue NoMethodError => e
raise e unless e.name.to_s == operator.to_s
raise Sass::SyntaxError.new("Undefined unary operation: \"#{@operator} #{value}\".")
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/literal.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/literal.rb | module Sass::Script::Tree
# The parse tree node for a literal scalar value. This wraps an instance of
# {Sass::Script::Value::Base}.
#
# List literals should use {ListLiteral} instead.
class Literal < Node
# The wrapped value.
#
# @return [Sass::Script::Value::Base]
attr_reader :value
# Creates a new literal value.
#
# @param value [Sass::Script::Value::Base]
# @see #value
def initialize(value)
@value = value
end
# @see Node#children
def children; []; end
# @see Node#to_sass
def to_sass(opts = {}); value.to_sass(opts); end
# @see Node#deep_copy
def deep_copy; dup; end
# @see Node#options=
def options=(options)
value.options = options
end
def inspect
value.inspect
end
def force_division!
value.original = nil if value.is_a?(Sass::Script::Value::Number)
end
protected
def _perform(environment)
value.source_range = source_range
value
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/node.rb | module Sass::Script::Tree
# The abstract superclass for SassScript parse tree nodes.
#
# Use \{#perform} to evaluate a parse tree.
class Node
# The options hash for this node.
#
# @return [{Symbol => Object}]
attr_reader :options
# The line of the document on which this node appeared.
#
# @return [Integer]
attr_accessor :line
# The source range in the document on which this node appeared.
#
# @return [Sass::Source::Range]
attr_accessor :source_range
# The file name of the document on which this node appeared.
#
# @return [String]
attr_accessor :filename
# Sets the options hash for this node,
# as well as for all child nodes.
# See {file:SASS_REFERENCE.md#Options the Sass options documentation}.
#
# @param options [{Symbol => Object}] The options
def options=(options)
@options = options
children.each do |c|
if c.is_a? Hash
c.values.each {|v| v.options = options}
else
c.options = options
end
end
end
# Evaluates the node.
#
# \{#perform} shouldn't be overridden directly;
# instead, override \{#\_perform}.
#
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
# @return [Sass::Script::Value] The SassScript object that is the value of the SassScript
def perform(environment)
_perform(environment)
rescue Sass::SyntaxError => e
e.modify_backtrace(:line => line)
raise e
end
# Returns all child nodes of this node.
#
# @return [Array<Node>]
def children
Sass::Util.abstract(self)
end
# Returns the text of this SassScript expression.
#
# @options opts :quote [String]
# The preferred quote style for quoted strings. If `:none`, strings are
# always emitted unquoted.
#
# @return [String]
def to_sass(opts = {})
Sass::Util.abstract(self)
end
# Returns a deep clone of this node.
# The child nodes are cloned, but options are not.
#
# @return [Node]
def deep_copy
Sass::Util.abstract(self)
end
# Forces any division operations with number literals in this expression to
# do real division, rather than returning strings.
def force_division!
children.each {|c| c.force_division!}
end
protected
# Converts underscores to dashes if the :dasherize option is set.
def dasherize(s, opts)
if opts[:dasherize]
s.tr('_', '-')
else
s
end
end
# Evaluates this node.
# Note that all {Sass::Script::Value} objects created within this method
# should have their \{#options} attribute set, probably via \{#opts}.
#
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
# @return [Sass::Script::Value] The SassScript object that is the value of the SassScript
# @see #perform
def _perform(environment)
Sass::Util.abstract(self)
end
# Sets the \{#options} field on the given value and returns it.
#
# @param value [Sass::Script::Value]
# @return [Sass::Script::Value]
def opts(value)
value.options = options
value
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/string_interpolation.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/string_interpolation.rb | module Sass::Script::Tree
# A SassScript object representing `#{}` interpolation within a string.
#
# @see Interpolation
class StringInterpolation < Node
# @return [Literal] The string literal before this interpolation.
attr_reader :before
# @return [Node] The SassScript within the interpolation
attr_reader :mid
# @return [StringInterpolation, Literal]
# The string literal or string interpolation before this interpolation.
attr_reader :after
# Whether this is a CSS string or a CSS identifier. The difference is that
# strings are written with double-quotes, while identifiers aren't.
#
# String interpolations are only ever identifiers if they're quote-like
# functions such as `url()`.
#
# @return [Symbol] `:string` or `:identifier`
def type
@before.value.type
end
# Returns the quote character that should be used to wrap a Sass
# representation of this interpolation.
def quote
quote_for(self) || '"'
end
# Interpolation in a string is of the form `"before #{mid} after"`,
# where `before` and `after` may include more interpolation.
#
# @param before [StringInterpolation, Literal] See {StringInterpolation#before}
# @param mid [Node] See {StringInterpolation#mid}
# @param after [Literal] See {StringInterpolation#after}
def initialize(before, mid, after)
@before = before
@mid = mid
@after = after
end
# @return [String] A human-readable s-expression representation of the interpolation
def inspect
"(string_interpolation #{@before.inspect} #{@mid.inspect} #{@after.inspect})"
end
# @see Node#to_sass
def to_sass(opts = {})
quote = type == :string ? opts[:quote] || quote_for(self) || '"' : :none
opts = opts.merge(:quote => quote)
res = ""
res << quote if quote != :none
res << _to_sass(before, opts)
res << '#{' << @mid.to_sass(opts.merge(:quote => nil)) << '}'
res << _to_sass(after, opts)
res << quote if quote != :none
res
end
# Returns the three components of the interpolation, `before`, `mid`, and `after`.
#
# @return [Array<Node>]
# @see #initialize
# @see Node#children
def children
[@before, @mid, @after].compact
end
# @see Node#deep_copy
def deep_copy
node = dup
node.instance_variable_set('@before', @before.deep_copy) if @before
node.instance_variable_set('@mid', @mid.deep_copy)
node.instance_variable_set('@after', @after.deep_copy) if @after
node
end
protected
# Evaluates the interpolation.
#
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
# @return [Sass::Script::Value::String]
# The SassScript string that is the value of the interpolation
def _perform(environment)
res = ""
before = @before.perform(environment)
res << before.value
mid = @mid.perform(environment)
res << (mid.is_a?(Sass::Script::Value::String) ? mid.value : mid.to_s(:quote => :none))
res << @after.perform(environment).value
opts(Sass::Script::Value::String.new(res, before.type))
end
private
def _to_sass(string_or_interp, opts)
result = string_or_interp.to_sass(opts)
opts[:quote] == :none ? result : result.slice(1...-1)
end
def quote_for(string_or_interp)
if string_or_interp.is_a?(Sass::Script::Tree::Literal)
return nil if string_or_interp.value.value.empty?
return '"' if string_or_interp.value.value.include?("'")
return "'" if string_or_interp.value.value.include?('"')
return nil
end
# Double-quotes take precedence over single quotes.
before_quote = quote_for(string_or_interp.before)
return '"' if before_quote == '"'
after_quote = quote_for(string_or_interp.after)
return '"' if after_quote == '"'
# Returns "'" if either or both insist on single quotes, and nil
# otherwise.
before_quote || after_quote
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/list_literal.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/list_literal.rb | module Sass::Script::Tree
# A parse tree node representing a list literal. When resolved, this returns a
# {Sass::Tree::Value::List}.
class ListLiteral < Node
# The parse nodes for members of this list.
#
# @return [Array<Node>]
attr_reader :elements
# The operator separating the values of the list. Either `:comma` or
# `:space`.
#
# @return [Symbol]
attr_reader :separator
# Whether the list is surrounded by square brackets.
#
# @return [Boolean]
attr_reader :bracketed
# Creates a new list literal.
#
# @param elements [Array<Node>] See \{#elements}
# @param separator [Symbol] See \{#separator}
# @param bracketed [Boolean] See \{#bracketed}
def initialize(elements, separator: nil, bracketed: false)
@elements = elements
@separator = separator
@bracketed = bracketed
end
# @see Node#children
def children; elements; end
# @see Value#to_sass
def to_sass(opts = {})
return bracketed ? "[]" : "()" if elements.empty?
members = elements.map do |v|
if element_needs_parens?(v)
"(#{v.to_sass(opts)})"
else
v.to_sass(opts)
end
end
if separator == :comma && members.length == 1
return "#{bracketed ? '[' : '('}#{members.first},#{bracketed ? ']' : ')'}"
end
contents = members.join(sep_str(nil))
bracketed ? "[#{contents}]" : contents
end
# @see Node#deep_copy
def deep_copy
node = dup
node.instance_variable_set('@elements', elements.map {|e| e.deep_copy})
node
end
def inspect
(bracketed ? '[' : '(') +
elements.map {|e| e.inspect}.join(separator == :space ? ' ' : ', ') +
(bracketed ? ']' : ')')
end
def force_division!
# Do nothing. Lists prevent division propagation.
end
protected
def _perform(environment)
list = Sass::Script::Value::List.new(
elements.map {|e| e.perform(environment)},
separator: separator,
bracketed: bracketed)
list.source_range = source_range
list.options = options
list
end
private
# Returns whether an element in the list should be wrapped in parentheses
# when serialized to Sass.
def element_needs_parens?(element)
if element.is_a?(ListLiteral)
return false if element.elements.length < 2
return false if element.bracketed
return Sass::Script::Parser.precedence_of(element.separator || :space) <=
Sass::Script::Parser.precedence_of(separator || :space)
end
return false unless separator == :space
if element.is_a?(UnaryOperation)
return element.operator == :minus || element.operator == :plus
end
return false unless element.is_a?(Operation)
return true unless element.operator == :div
!(is_literal_number?(element.operand1) && is_literal_number?(element.operand2))
end
# Returns whether a value is a number literal that shouldn't be divided.
def is_literal_number?(value)
value.is_a?(Literal) &&
value.value.is_a?((Sass::Script::Value::Number)) &&
!value.value.original.nil?
end
def sep_str(opts = options)
return ' ' if separator == :space
return ',' if opts && opts[:style] == :compressed
', '
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/variable.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/variable.rb | module Sass::Script::Tree
# A SassScript parse node representing a variable.
class Variable < Node
# The name of the variable.
#
# @return [String]
attr_reader :name
# The underscored name of the variable.
#
# @return [String]
attr_reader :underscored_name
# @param name [String] See \{#name}
def initialize(name)
@name = name
@underscored_name = name.tr("-", "_")
super()
end
# @return [String] A string representation of the variable
def inspect(opts = {})
"$#{dasherize(name, opts)}"
end
alias_method :to_sass, :inspect
# Returns an empty array.
#
# @return [Array<Node>] empty
# @see Node#children
def children
[]
end
# @see Node#deep_copy
def deep_copy
dup
end
protected
# Evaluates the variable.
#
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
# @return [Sass::Script::Value] The SassScript object that is the value of the variable
# @raise [Sass::SyntaxError] if the variable is undefined
def _perform(environment)
val = environment.var(name)
raise Sass::SyntaxError.new("Undefined variable: \"$#{name}\".") unless val
if val.is_a?(Sass::Script::Value::Number) && val.original
val = val.dup
val.original = nil
end
val
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/operation.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script/tree/operation.rb | module Sass::Script::Tree
# A SassScript parse node representing a binary operation,
# such as `$a + $b` or `"foo" + 1`.
class Operation < Node
@@color_arithmetic_deprecation = Sass::Deprecation.new
@@unitless_equals_deprecation = Sass::Deprecation.new
attr_reader :operand1
attr_reader :operand2
attr_reader :operator
# @param operand1 [Sass::Script::Tree::Node] The parse-tree node
# for the right-hand side of the operator
# @param operand2 [Sass::Script::Tree::Node] The parse-tree node
# for the left-hand side of the operator
# @param operator [Symbol] The operator to perform.
# This should be one of the binary operator names in {Sass::Script::Lexer::OPERATORS}
def initialize(operand1, operand2, operator)
@operand1 = operand1
@operand2 = operand2
@operator = operator
super()
end
# @return [String] A human-readable s-expression representation of the operation
def inspect
"(#{@operator.inspect} #{@operand1.inspect} #{@operand2.inspect})"
end
# @see Node#to_sass
def to_sass(opts = {})
o1 = operand_to_sass @operand1, :left, opts
o2 = operand_to_sass @operand2, :right, opts
sep =
case @operator
when :comma; ", "
when :space; " "
else; " #{Sass::Script::Lexer::OPERATORS_REVERSE[@operator]} "
end
"#{o1}#{sep}#{o2}"
end
# Returns the operands for this operation.
#
# @return [Array<Node>]
# @see Node#children
def children
[@operand1, @operand2]
end
# @see Node#deep_copy
def deep_copy
node = dup
node.instance_variable_set('@operand1', @operand1.deep_copy)
node.instance_variable_set('@operand2', @operand2.deep_copy)
node
end
protected
# Evaluates the operation.
#
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
# @return [Sass::Script::Value] The SassScript object that is the value of the operation
# @raise [Sass::SyntaxError] if the operation is undefined for the operands
def _perform(environment)
value1 = @operand1.perform(environment)
# Special-case :and and :or to support short-circuiting.
if @operator == :and
return value1.to_bool ? @operand2.perform(environment) : value1
elsif @operator == :or
return value1.to_bool ? value1 : @operand2.perform(environment)
end
value2 = @operand2.perform(environment)
if (value1.is_a?(Sass::Script::Value::Null) || value2.is_a?(Sass::Script::Value::Null)) &&
@operator != :eq && @operator != :neq
raise Sass::SyntaxError.new(
"Invalid null operation: \"#{value1.inspect} #{@operator} #{value2.inspect}\".")
end
begin
result = opts(value1.send(@operator, value2))
rescue NoMethodError => e
raise e unless e.name.to_s == @operator.to_s
raise Sass::SyntaxError.new("Undefined operation: \"#{value1} #{@operator} #{value2}\".")
end
warn_for_color_arithmetic(value1, value2)
warn_for_unitless_equals(value1, value2, result)
result
end
private
def warn_for_color_arithmetic(value1, value2)
return unless @operator == :plus || @operator == :times || @operator == :minus ||
@operator == :div || @operator == :mod
if value1.is_a?(Sass::Script::Value::Number)
return unless value2.is_a?(Sass::Script::Value::Color)
elsif value1.is_a?(Sass::Script::Value::Color)
return unless value2.is_a?(Sass::Script::Value::Color) || value2.is_a?(Sass::Script::Value::Number)
else
return
end
@@color_arithmetic_deprecation.warn(filename, line, <<WARNING)
The operation `#{value1} #{@operator} #{value2}` is deprecated and will be an error in future versions.
Consider using Sass's color functions instead.
http://sass-lang.com/documentation/Sass/Script/Functions.html#other_color_functions
WARNING
end
def warn_for_unitless_equals(value1, value2, result)
return unless @operator == :eq || @operator == :neq
return unless value1.is_a?(Sass::Script::Value::Number)
return unless value2.is_a?(Sass::Script::Value::Number)
return unless value1.unitless? != value2.unitless?
return unless result == (if @operator == :eq
Sass::Script::Value::Bool::TRUE
else
Sass::Script::Value::Bool::FALSE
end)
operation = "#{value1.to_sass} #{@operator == :eq ? '==' : '!='} #{value2.to_sass}"
future_value = @operator == :neq
@@unitless_equals_deprecation.warn(filename, line, <<WARNING)
The result of `#{operation}` will be `#{future_value}` in future releases of Sass.
Unitless numbers will no longer be equal to the same numbers with units.
WARNING
end
def operand_to_sass(op, side, opts)
return "(#{op.to_sass(opts)})" if op.is_a?(Sass::Script::Tree::ListLiteral)
return op.to_sass(opts) unless op.is_a?(Operation)
pred = Sass::Script::Parser.precedence_of(@operator)
sub_pred = Sass::Script::Parser.precedence_of(op.operator)
assoc = Sass::Script::Parser.associative?(@operator)
return "(#{op.to_sass(opts)})" if sub_pred < pred ||
(side == :right && sub_pred == pred && !assoc)
op.to_sass(opts)
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/prop_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/prop_node.rb | module Sass::Tree
# A static node representing a CSS property.
#
# @see Sass::Tree
class PropNode < Node
# The name of the property,
# interspersed with {Sass::Script::Tree::Node}s
# representing `#{}`-interpolation.
# Any adjacent strings will be merged together.
#
# @return [Array<String, Sass::Script::Tree::Node>]
attr_accessor :name
# The name of the property
# after any interpolated SassScript has been resolved.
# Only set once \{Tree::Visitors::Perform} has been run.
#
# @return [String]
attr_accessor :resolved_name
# The value of the property.
#
# For most properties, this will just contain a single Node. However, for
# CSS variables, it will contain multiple strings and nodes representing
# interpolation. Any adjacent strings will be merged together.
#
# @return [Array<String, Sass::Script::Tree::Node>]
attr_accessor :value
# The value of the property
# after any interpolated SassScript has been resolved.
# Only set once \{Tree::Visitors::Perform} has been run.
#
# @return [String]
attr_accessor :resolved_value
# How deep this property is indented
# relative to a normal property.
# This is only greater than 0 in the case that:
#
# * This node is in a CSS tree
# * The style is :nested
# * This is a child property of another property
# * The parent property has a value, and thus will be rendered
#
# @return [Integer]
attr_accessor :tabs
# The source range in which the property name appears.
#
# @return [Sass::Source::Range]
attr_accessor :name_source_range
# The source range in which the property value appears.
#
# @return [Sass::Source::Range]
attr_accessor :value_source_range
# Whether this represents a CSS custom property.
#
# @return [Boolean]
def custom_property?
name.first.is_a?(String) && name.first.start_with?("--")
end
# @param name [Array<String, Sass::Script::Tree::Node>] See \{#name}
# @param value [Array<String, Sass::Script::Tree::Node>] See \{#value}
# @param prop_syntax [Symbol] `:new` if this property uses `a: b`-style syntax,
# `:old` if it uses `:a b`-style syntax
def initialize(name, value, prop_syntax)
@name = Sass::Util.strip_string_array(
Sass::Util.merge_adjacent_strings(name))
@value = Sass::Util.merge_adjacent_strings(value)
@value = Sass::Util.strip_string_array(@value) unless custom_property?
@tabs = 0
@prop_syntax = prop_syntax
super()
end
# Compares the names and values of two properties.
#
# @param other [Object] The object to compare with
# @return [Boolean] Whether or not this node and the other object
# are the same
def ==(other)
self.class == other.class && name == other.name && value == other.value && super
end
# Returns a appropriate message indicating how to escape pseudo-class selectors.
# This only applies for old-style properties with no value,
# so returns the empty string if this is new-style.
#
# @return [String] The message
def pseudo_class_selector_message
if @prop_syntax == :new ||
custom_property? ||
!value.first.is_a?(Sass::Script::Tree::Literal) ||
!value.first.value.is_a?(Sass::Script::Value::String) ||
!value.first.value.value.empty?
return ""
end
"\nIf #{declaration.dump} should be a selector, use \"\\#{declaration}\" instead."
end
# Computes the Sass or SCSS code for the variable declaration.
# This is like \{#to\_scss} or \{#to\_sass},
# except it doesn't print any child properties or a trailing semicolon.
#
# @param opts [{Symbol => Object}] The options hash for the tree.
# @param fmt [Symbol] `:scss` or `:sass`.
def declaration(opts = {:old => @prop_syntax == :old}, fmt = :sass)
name = self.name.map {|n| n.is_a?(String) ? n : n.to_sass(opts)}.join
value = self.value.map {|n| n.is_a?(String) ? n : n.to_sass(opts)}.join
value = "(#{value})" if value_needs_parens?
if name[0] == ?:
raise Sass::SyntaxError.new("The \"#{name}: #{value}\"" +
" hack is not allowed in the Sass indented syntax")
end
# The indented syntax doesn't support newlines in custom property values,
# but we can losslessly convert them to spaces instead.
value = value.tr("\n", " ") if fmt == :sass
old = opts[:old] && fmt == :sass
"#{old ? ':' : ''}#{name}#{old ? '' : ':'}#{custom_property? ? '' : ' '}#{value}".rstrip
end
# A property node is invisible if its value is empty.
#
# @return [Boolean]
def invisible?
!custom_property? && resolved_value.empty?
end
private
# Returns whether \{#value} neesd parentheses in order to be parsed
# properly as division.
def value_needs_parens?
return false if custom_property?
root = value.first
root.is_a?(Sass::Script::Tree::Operation) &&
root.operator == :div &&
root.operand1.is_a?(Sass::Script::Tree::Literal) &&
root.operand1.value.is_a?(Sass::Script::Value::Number) &&
root.operand1.value.original.nil? &&
root.operand2.is_a?(Sass::Script::Tree::Literal) &&
root.operand2.value.is_a?(Sass::Script::Value::Number) &&
root.operand2.value.original.nil?
end
def check!
return unless @options[:property_syntax] && @options[:property_syntax] != @prop_syntax
raise Sass::SyntaxError.new(
"Illegal property syntax: can't use #{@prop_syntax} syntax when " +
":property_syntax => #{@options[:property_syntax].inspect} is set.")
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/charset_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/charset_node.rb | module Sass::Tree
# A static node representing an unprocessed Sass `@charset` directive.
#
# @see Sass::Tree
class CharsetNode < Node
# The name of the charset.
#
# @return [String]
attr_accessor :name
# @param name [String] see \{#name}
def initialize(name)
@name = name
super()
end
# @see Node#invisible?
def invisible?
true
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/css_import_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/css_import_node.rb | module Sass::Tree
# A node representing an `@import` rule that's importing plain CSS.
#
# @see Sass::Tree
class CssImportNode < DirectiveNode
# The URI being imported, either as a plain string or an interpolated
# script string.
#
# @return [String, Sass::Script::Tree::Node]
attr_accessor :uri
# The text of the URI being imported after any interpolated SassScript has
# been resolved. Only set once {Tree::Visitors::Perform} has been run.
#
# @return [String]
attr_accessor :resolved_uri
# The supports condition for this import.
#
# @return [Sass::Supports::Condition]
attr_accessor :supports_condition
# The media query for this rule, interspersed with
# {Sass::Script::Tree::Node}s representing `#{}`-interpolation. Any adjacent
# strings will be merged together.
#
# @return [Array<String, Sass::Script::Tree::Node>]
attr_accessor :query
# The media query for this rule, without any unresolved interpolation.
# It's only set once {Tree::Visitors::Perform} has been run.
#
# @return [Sass::Media::QueryList]
attr_accessor :resolved_query
# @param uri [String, Sass::Script::Tree::Node] See \{#uri}
# @param query [Array<String, Sass::Script::Tree::Node>] See \{#query}
# @param supports_condition [Sass::Supports::Condition] See \{#supports_condition}
def initialize(uri, query = [], supports_condition = nil)
@uri = uri
@query = query
@supports_condition = supports_condition
super('')
end
# @param uri [String] See \{#resolved_uri}
# @return [CssImportNode]
def self.resolved(uri)
node = new(uri)
node.resolved_uri = uri
node
end
# @see DirectiveNode#value
def value; raise NotImplementedError; end
# @see DirectiveNode#resolved_value
def resolved_value
@resolved_value ||=
begin
str = "@import #{resolved_uri}"
str << " supports(#{supports_condition.to_css})" if supports_condition
str << " #{resolved_query.to_css}" if resolved_query
str
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/for_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/for_node.rb | require 'sass/tree/node'
module Sass::Tree
# A dynamic node representing a Sass `@for` loop.
#
# @see Sass::Tree
class ForNode < Node
# The name of the loop variable.
# @return [String]
attr_reader :var
# The parse tree for the initial expression.
# @return [Script::Tree::Node]
attr_accessor :from
# The parse tree for the final expression.
# @return [Script::Tree::Node]
attr_accessor :to
# Whether to include `to` in the loop or stop just before.
# @return [Boolean]
attr_reader :exclusive
# @param var [String] See \{#var}
# @param from [Script::Tree::Node] See \{#from}
# @param to [Script::Tree::Node] See \{#to}
# @param exclusive [Boolean] See \{#exclusive}
def initialize(var, from, to, exclusive)
@var = var
@from = from
@to = to
@exclusive = exclusive
super()
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/content_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/content_node.rb | module Sass
module Tree
# A node representing the placement within a mixin of the include statement's content.
#
# @see Sass::Tree
class ContentNode < Node
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/root_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/root_node.rb | module Sass
module Tree
# A static node that is the root node of the Sass document.
class RootNode < Node
# The Sass template from which this node was created
#
# @param template [String]
attr_reader :template
# @param template [String] The Sass template from which this node was created
def initialize(template)
super()
@template = template
end
# Runs the dynamic Sass code and computes the CSS for the tree.
#
# @return [String] The compiled CSS.
def render
css_tree.css
end
# Runs the dynamic Sass code and computes the CSS for the tree, along with
# the sourcemap.
#
# @return [(String, Sass::Source::Map)] The compiled CSS, as well as
# the source map. @see #render
def render_with_sourcemap
css_tree.css_with_sourcemap
end
private
def css_tree
Visitors::CheckNesting.visit(self)
result = Visitors::Perform.visit(self)
Visitors::CheckNesting.visit(result) # Check again to validate mixins
result, extends = Visitors::Cssize.visit(result)
Visitors::Extend.visit(result, extends)
result
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/while_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/while_node.rb | require 'sass/tree/node'
module Sass::Tree
# A dynamic node representing a Sass `@while` loop.
#
# @see Sass::Tree
class WhileNode < Node
# The parse tree for the continuation expression.
# @return [Script::Tree::Node]
attr_accessor :expr
# @param expr [Script::Tree::Node] See \{#expr}
def initialize(expr)
@expr = expr
super()
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/supports_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/supports_node.rb | module Sass::Tree
# A static node representing a `@supports` rule.
#
# @see Sass::Tree
class SupportsNode < DirectiveNode
# The name, which may include a browser prefix.
#
# @return [String]
attr_accessor :name
# The supports condition.
#
# @return [Sass::Supports::Condition]
attr_accessor :condition
# @param condition [Sass::Supports::Condition] See \{#condition}
def initialize(name, condition)
@name = name
@condition = condition
super('')
end
# @see DirectiveNode#value
def value; raise NotImplementedError; end
# @see DirectiveNode#resolved_value
def resolved_value
@resolved_value ||= "@#{name} #{condition.to_css}"
end
# True when the directive has no visible children.
#
# @return [Boolean]
def invisible?
children.all? {|c| c.invisible?}
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/comment_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/comment_node.rb | require 'sass/tree/node'
module Sass::Tree
# A static node representing a Sass comment (silent or loud).
#
# @see Sass::Tree
class CommentNode < Node
# The text of the comment, not including `/*` and `*/`.
# Interspersed with {Sass::Script::Tree::Node}s representing `#{}`-interpolation
# if this is a loud comment.
#
# @return [Array<String, Sass::Script::Tree::Node>]
attr_accessor :value
# The text of the comment
# after any interpolated SassScript has been resolved.
# Only set once \{Tree::Visitors::Perform} has been run.
#
# @return [String]
attr_accessor :resolved_value
# The type of the comment. `:silent` means it's never output to CSS,
# `:normal` means it's output in every compile mode except `:compressed`,
# and `:loud` means it's output even in `:compressed`.
#
# @return [Symbol]
attr_accessor :type
# @param value [Array<String, Sass::Script::Tree::Node>] See \{#value}
# @param type [Symbol] See \{#type}
def initialize(value, type)
@value = Sass::Util.with_extracted_values(value) {|str| normalize_indentation str}
@type = type
super()
end
# Compares the contents of two comments.
#
# @param other [Object] The object to compare with
# @return [Boolean] Whether or not this node and the other object
# are the same
def ==(other)
self.class == other.class && value == other.value && type == other.type
end
# Returns `true` if this is a silent comment
# or the current style doesn't render comments.
#
# Comments starting with ! are never invisible (and the ! is removed from the output.)
#
# @return [Boolean]
def invisible?
case @type
when :loud; false
when :silent; true
else; style == :compressed
end
end
# Returns the number of lines in the comment.
#
# @return [Integer]
def lines
@value.inject(0) do |s, e|
next s + e.count("\n") if e.is_a?(String)
next s
end
end
private
def normalize_indentation(str)
ind = str.split("\n").inject(str[/^[ \t]*/].split("")) do |pre, line|
line[/^[ \t]*/].split("").zip(pre).inject([]) do |arr, (a, b)|
break arr if a != b
arr << a
end
end.join
str.gsub(/^#{ind}/, '')
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/trace_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/trace_node.rb | require 'sass/tree/node'
module Sass::Tree
# A solely static node left over after a mixin include or @content has been performed.
# Its sole purpose is to wrap exceptions to add to the backtrace.
#
# @see Sass::Tree
class TraceNode < Node
# The name of the trace entry to add.
#
# @return [String]
attr_reader :name
# @param name [String] The name of the trace entry to add.
def initialize(name)
@name = name
self.has_children = true
super()
end
# Initializes this node from an existing node.
# @param name [String] The name of the trace entry to add.
# @param node [Node] The node to copy information from.
# @return [TraceNode]
def self.from_node(name, node)
trace = new(name)
trace.line = node.line
trace.filename = node.filename
trace.options = node.options
trace
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/if_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/if_node.rb | require 'sass/tree/node'
module Sass::Tree
# A dynamic node representing a Sass `@if` statement.
#
# {IfNode}s are a little odd, in that they also represent `@else` and `@else if`s.
# This is done as a linked list:
# each {IfNode} has a link (\{#else}) to the next {IfNode}.
#
# @see Sass::Tree
class IfNode < Node
# The conditional expression.
# If this is nil, this is an `@else` node, not an `@else if`.
#
# @return [Script::Expr]
attr_accessor :expr
# The next {IfNode} in the if-else list, or `nil`.
#
# @return [IfNode]
attr_accessor :else
# @param expr [Script::Expr] See \{#expr}
def initialize(expr)
@expr = expr
@last_else = self
super()
end
# Append an `@else` node to the end of the list.
#
# @param node [IfNode] The `@else` node to append
def add_else(node)
@last_else.else = node
@last_else = node
end
def _dump(f)
Marshal.dump([expr, self.else, children])
end
def self._load(data)
expr, else_, children = Marshal.load(data)
node = IfNode.new(expr)
node.else = else_
node.children = children
node.instance_variable_set('@last_else',
node.else ? node.else.instance_variable_get('@last_else') : node)
node
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/media_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/media_node.rb | module Sass::Tree
# A static node representing a `@media` rule.
# `@media` rules behave differently from other directives
# in that when they're nested within rules,
# they bubble up to top-level.
#
# @see Sass::Tree
class MediaNode < DirectiveNode
# TODO: parse and cache the query immediately if it has no dynamic elements
# The media query for this rule, interspersed with {Sass::Script::Tree::Node}s
# representing `#{}`-interpolation. Any adjacent strings will be merged
# together.
#
# @return [Array<String, Sass::Script::Tree::Node>]
attr_accessor :query
# The media query for this rule, without any unresolved interpolation. It's
# only set once {Tree::Visitors::Perform} has been run.
#
# @return [Sass::Media::QueryList]
attr_accessor :resolved_query
# @param query [Array<String, Sass::Script::Tree::Node>] See \{#query}
def initialize(query)
@query = query
super('')
end
# @see DirectiveNode#value
def value; raise NotImplementedError; end
# @see DirectiveNode#name
def name; '@media'; end
# @see DirectiveNode#resolved_value
def resolved_value
@resolved_value ||= "@media #{resolved_query.to_css}"
end
# True when the directive has no visible children.
#
# @return [Boolean]
def invisible?
children.all? {|c| c.invisible?}
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/directive_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/directive_node.rb | module Sass::Tree
# A static node representing an unprocessed Sass `@`-directive.
# Directives known to Sass, like `@for` and `@debug`,
# are handled by their own nodes;
# only CSS directives like `@media` and `@font-face` become {DirectiveNode}s.
#
# `@import` and `@charset` are special cases;
# they become {ImportNode}s and {CharsetNode}s, respectively.
#
# @see Sass::Tree
class DirectiveNode < Node
# The text of the directive, `@` and all, with interpolation included.
#
# @return [Array<String, Sass::Script::Tree::Node>]
attr_accessor :value
# The text of the directive after any interpolated SassScript has been resolved.
# Only set once \{Tree::Visitors::Perform} has been run.
#
# @return [String]
attr_accessor :resolved_value
# @see RuleNode#tabs
attr_accessor :tabs
# @see RuleNode#group_end
attr_accessor :group_end
# @param value [Array<String, Sass::Script::Tree::Node>] See \{#value}
def initialize(value)
@value = value
@tabs = 0
super()
end
# @param value [String] See \{#resolved_value}
# @return [DirectiveNode]
def self.resolved(value)
node = new([value])
node.resolved_value = value
node
end
# @return [String] The name of the directive, including `@`.
def name
@name ||= value.first.gsub(/ .*$/, '')
end
# Strips out any vendor prefixes and downcases the directive name.
# @return [String] The normalized name of the directive.
def normalized_name
@normalized_name ||= name.gsub(/^(@)(?:-[a-zA-Z0-9]+-)?/, '\1').downcase
end
def bubbles?
has_children
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/node.rb | module Sass
# A namespace for nodes in the Sass parse tree.
#
# The Sass parse tree has three states: dynamic, static Sass, and static CSS.
#
# When it's first parsed, a Sass document is in the dynamic state.
# It has nodes for mixin definitions and `@for` loops and so forth,
# in addition to nodes for CSS rules and properties.
# Nodes that only appear in this state are called **dynamic nodes**.
#
# {Tree::Visitors::Perform} creates a static Sass tree, which is
# different. It still has nodes for CSS rules and properties but it
# doesn't have any dynamic-generation-related nodes. The nodes in
# this state are in a similar structure to the Sass document: rules
# and properties are nested beneath one another, although the
# {Tree::RuleNode} selectors are already in their final state. Nodes
# that can be in this state or in the dynamic state are called
# **static nodes**; nodes that can only be in this state are called
# **solely static nodes**.
#
# {Tree::Visitors::Cssize} is then used to create a static CSS tree.
# This is like a static Sass tree,
# but the structure exactly mirrors that of the generated CSS.
# Rules and properties can't be nested beneath one another in this state.
#
# Finally, {Tree::Visitors::ToCss} can be called on a static CSS tree
# to get the actual CSS code as a string.
module Tree
# The abstract superclass of all parse-tree nodes.
class Node
include Enumerable
def self.inherited(base)
node_name = base.name.gsub(/.*::(.*?)Node$/, '\\1').downcase
base.instance_eval <<-METHODS
# @return [Symbol] The name that is used for this node when visiting.
def node_name
:#{node_name}
end
# @return [Symbol] The method that is used on the visitor to visit nodes of this type.
def visit_method
:visit_#{node_name}
end
# @return [Symbol] The method name that determines if the parent is invalid.
def invalid_child_method_name
:"invalid_#{node_name}_child?"
end
# @return [Symbol] The method name that determines if the node is an invalid parent.
def invalid_parent_method_name
:"invalid_#{node_name}_parent?"
end
METHODS
end
# The child nodes of this node.
#
# @return [Array<Tree::Node>]
attr_reader :children
# Whether or not this node has child nodes.
# This may be true even when \{#children} is empty,
# in which case this node has an empty block (e.g. `{}`).
#
# @return [Boolean]
attr_accessor :has_children
# The line of the document on which this node appeared.
#
# @return [Integer]
attr_accessor :line
# The source range in the document on which this node appeared.
#
# @return [Sass::Source::Range]
attr_accessor :source_range
# The name of the document on which this node appeared.
#
# @return [String]
attr_writer :filename
# The options hash for the node.
# See {file:SASS_REFERENCE.md#Options the Sass options documentation}.
#
# @return [{Symbol => Object}]
attr_reader :options
def initialize
@children = []
@filename = nil
@options = nil
end
# Sets the options hash for the node and all its children.
#
# @param options [{Symbol => Object}] The options
# @see #options
def options=(options)
Sass::Tree::Visitors::SetOptions.visit(self, options)
end
# @private
def children=(children)
self.has_children ||= !children.empty?
@children = children
end
# The name of the document on which this node appeared.
#
# @return [String]
def filename
@filename || (@options && @options[:filename])
end
# Appends a child to the node.
#
# @param child [Tree::Node, Array<Tree::Node>] The child node or nodes
# @raise [Sass::SyntaxError] if `child` is invalid
def <<(child)
return if child.nil?
if child.is_a?(Array)
child.each {|c| self << c}
else
self.has_children = true
@children << child
end
end
# Compares this node and another object (only other {Tree::Node}s will be equal).
# This does a structural comparison;
# if the contents of the nodes and all the child nodes are equivalent,
# then the nodes are as well.
#
# Only static nodes need to override this.
#
# @param other [Object] The object to compare with
# @return [Boolean] Whether or not this node and the other object
# are the same
# @see Sass::Tree
def ==(other)
self.class == other.class && other.children == children
end
# True if \{#to\_s} will return `nil`;
# that is, if the node shouldn't be rendered.
# Should only be called in a static tree.
#
# @return [Boolean]
def invisible?; false; end
# The output style. See {file:SASS_REFERENCE.md#Options the Sass options documentation}.
#
# @return [Symbol]
def style
@options[:style]
end
# Computes the CSS corresponding to this static CSS tree.
#
# @return [String] The resulting CSS
# @see Sass::Tree
def css
Sass::Tree::Visitors::ToCss.new.visit(self)
end
# Computes the CSS corresponding to this static CSS tree, along with
# the respective source map.
#
# @return [(String, Sass::Source::Map)] The resulting CSS and the source map
# @see Sass::Tree
def css_with_sourcemap
visitor = Sass::Tree::Visitors::ToCss.new(:build_source_mapping)
result = visitor.visit(self)
return result, visitor.source_mapping
end
# Returns a representation of the node for debugging purposes.
#
# @return [String]
def inspect
return self.class.to_s unless has_children
"(#{self.class} #{children.map {|c| c.inspect}.join(' ')})"
end
# Iterates through each node in the tree rooted at this node
# in a pre-order walk.
#
# @yield node
# @yieldparam node [Node] a node in the tree
def each
yield self
children.each {|c| c.each {|n| yield n}}
end
# Converts a node to Sass code that will generate it.
#
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize})
# @return [String] The Sass code corresponding to the node
def to_sass(options = {})
Sass::Tree::Visitors::Convert.visit(self, options, :sass)
end
# Converts a node to SCSS code that will generate it.
#
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize})
# @return [String] The Sass code corresponding to the node
def to_scss(options = {})
Sass::Tree::Visitors::Convert.visit(self, options, :scss)
end
# Return a deep clone of this node.
# The child nodes are cloned, but options are not.
#
# @return [Node]
def deep_copy
Sass::Tree::Visitors::DeepCopy.visit(self)
end
# Whether or not this node bubbles up through RuleNodes.
#
# @return [Boolean]
def bubbles?
false
end
protected
# @see Sass::Shared.balance
# @raise [Sass::SyntaxError] if the brackets aren't balanced
def balance(*args)
res = Sass::Shared.balance(*args)
return res if res
raise Sass::SyntaxError.new("Unbalanced brackets.", :line => line)
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/keyframe_rule_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/keyframe_rule_node.rb | module Sass::Tree
class KeyframeRuleNode < Node
# The text of the directive after any interpolated SassScript has been resolved.
# Since this is only a static node, this is the only value property.
#
# @return [String]
attr_accessor :resolved_value
# @param resolved_value [String] See \{#resolved_value}
def initialize(resolved_value)
@resolved_value = resolved_value
super()
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/mixin_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/mixin_node.rb | require 'sass/tree/node'
module Sass::Tree
# A static node representing a mixin include.
# When in a static tree, the sole purpose is to wrap exceptions
# to add the mixin to the backtrace.
#
# @see Sass::Tree
class MixinNode < Node
# The name of the mixin.
# @return [String]
attr_reader :name
# The arguments to the mixin.
# @return [Array<Script::Tree::Node>]
attr_accessor :args
# A hash from keyword argument names to values.
# @return [Sass::Util::NormalizedMap<Script::Tree::Node>]
attr_accessor :keywords
# The first splat argument for this mixin, if one exists.
#
# This could be a list of positional arguments, a map of keyword
# arguments, or an arglist containing both.
#
# @return [Node?]
attr_accessor :splat
# The second splat argument for this mixin, if one exists.
#
# If this exists, it's always a map of keyword arguments, and
# \{#splat} is always either a list or an arglist.
#
# @return [Node?]
attr_accessor :kwarg_splat
# @param name [String] The name of the mixin
# @param args [Array<Script::Tree::Node>] See \{#args}
# @param splat [Script::Tree::Node] See \{#splat}
# @param kwarg_splat [Script::Tree::Node] See \{#kwarg_splat}
# @param keywords [Sass::Util::NormalizedMap<Script::Tree::Node>] See \{#keywords}
def initialize(name, args, keywords, splat, kwarg_splat)
@name = name
@args = args
@keywords = keywords
@splat = splat
@kwarg_splat = kwarg_splat
super()
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/extend_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/extend_node.rb | require 'sass/tree/node'
module Sass::Tree
# A static node representing an `@extend` directive.
#
# @see Sass::Tree
class ExtendNode < Node
# The parsed selector after interpolation has been resolved.
# Only set once {Tree::Visitors::Perform} has been run.
#
# @return [Selector::CommaSequence]
attr_accessor :resolved_selector
# The CSS selector to extend, interspersed with {Sass::Script::Tree::Node}s
# representing `#{}`-interpolation.
#
# @return [Array<String, Sass::Script::Tree::Node>]
attr_accessor :selector
# The extended selector source range.
#
# @return [Sass::Source::Range]
attr_accessor :selector_source_range
# Whether the `@extend` is allowed to match no selectors or not.
#
# @return [Boolean]
def optional?; @optional; end
# @param selector [Array<String, Sass::Script::Tree::Node>]
# The CSS selector to extend,
# interspersed with {Sass::Script::Tree::Node}s
# representing `#{}`-interpolation.
# @param optional [Boolean] See \{ExtendNode#optional?}
# @param selector_source_range [Sass::Source::Range] The extended selector source range.
def initialize(selector, optional, selector_source_range)
@selector = selector
@optional = optional
@selector_source_range = selector_source_range
super()
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/return_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/return_node.rb | module Sass
module Tree
# A dynamic node representing returning from a function.
#
# @see Sass::Tree
class ReturnNode < Node
# The expression to return.
#
# @return [Script::Tree::Node]
attr_accessor :expr
# @param expr [Script::Tree::Node] The expression to return
def initialize(expr)
@expr = expr
super()
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/warn_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/warn_node.rb | module Sass
module Tree
# A dynamic node representing a Sass `@warn` statement.
#
# @see Sass::Tree
class WarnNode < Node
# The expression to print.
# @return [Script::Tree::Node]
attr_accessor :expr
# @param expr [Script::Tree::Node] The expression to print
def initialize(expr)
@expr = expr
super()
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/each_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/each_node.rb | require 'sass/tree/node'
module Sass::Tree
# A dynamic node representing a Sass `@each` loop.
#
# @see Sass::Tree
class EachNode < Node
# The names of the loop variables.
# @return [Array<String>]
attr_reader :vars
# The parse tree for the list.
# @return [Script::Tree::Node]
attr_accessor :list
# @param vars [Array<String>] The names of the loop variables
# @param list [Script::Tree::Node] The parse tree for the list
def initialize(vars, list)
@vars = vars
@list = list
super()
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/error_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/error_node.rb | module Sass
module Tree
# A dynamic node representing a Sass `@error` statement.
#
# @see Sass::Tree
class ErrorNode < Node
# The expression to print.
# @return [Script::Tree::Node]
attr_accessor :expr
# @param expr [Script::Tree::Node] The expression to print
def initialize(expr)
@expr = expr
super()
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/rule_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/rule_node.rb | require 'pathname'
module Sass::Tree
# A static node representing a CSS rule.
#
# @see Sass::Tree
class RuleNode < Node
# The character used to include the parent selector
PARENT = '&'
# The CSS selector for this rule,
# interspersed with {Sass::Script::Tree::Node}s
# representing `#{}`-interpolation.
# Any adjacent strings will be merged together.
#
# @return [Array<String, Sass::Script::Tree::Node>]
attr_accessor :rule
# The CSS selector for this rule, without any unresolved
# interpolation but with parent references still intact. It's only
# guaranteed to be set once {Tree::Visitors::Perform} has been
# run, but it may be set before then for optimization reasons.
#
# @return [Selector::CommaSequence]
attr_accessor :parsed_rules
# The CSS selector for this rule, without any unresolved
# interpolation or parent references. It's only set once
# {Tree::Visitors::Perform} has been run.
#
# @return [Selector::CommaSequence]
attr_accessor :resolved_rules
# How deep this rule is indented
# relative to a base-level rule.
# This is only greater than 0 in the case that:
#
# * This node is in a CSS tree
# * The style is :nested
# * This is a child rule of another rule
# * The parent rule has properties, and thus will be rendered
#
# @return [Integer]
attr_accessor :tabs
# The entire selector source range for this rule.
# @return [Sass::Source::Range]
attr_accessor :selector_source_range
# Whether or not this rule is the last rule in a nested group.
# This is only set in a CSS tree.
#
# @return [Boolean]
attr_accessor :group_end
# The stack trace.
# This is only readable in a CSS tree as it is written during the perform step
# and only when the :trace_selectors option is set.
#
# @return [String]
attr_accessor :stack_trace
# @param rule [Array<String, Sass::Script::Tree::Node>, Sass::Selector::CommaSequence]
# The CSS rule, either unparsed or parsed.
# @param selector_source_range [Sass::Source::Range]
def initialize(rule, selector_source_range = nil)
if rule.is_a?(Sass::Selector::CommaSequence)
@rule = [rule.to_s]
@parsed_rules = rule
else
merged = Sass::Util.merge_adjacent_strings(rule)
@rule = Sass::Util.strip_string_array(merged)
try_to_parse_non_interpolated_rules
end
@selector_source_range = selector_source_range
@tabs = 0
super()
end
# If we've precached the parsed selector, set the line on it, too.
def line=(line)
@parsed_rules.line = line if @parsed_rules
super
end
# If we've precached the parsed selector, set the filename on it, too.
def filename=(filename)
@parsed_rules.filename = filename if @parsed_rules
super
end
# Compares the contents of two rules.
#
# @param other [Object] The object to compare with
# @return [Boolean] Whether or not this node and the other object
# are the same
def ==(other)
self.class == other.class && rule == other.rule && super
end
# Adds another {RuleNode}'s rules to this one's.
#
# @param node [RuleNode] The other node
def add_rules(node)
@rule = Sass::Util.strip_string_array(
Sass::Util.merge_adjacent_strings(@rule + ["\n"] + node.rule))
try_to_parse_non_interpolated_rules
end
# @return [Boolean] Whether or not this rule is continued on the next line
def continued?
last = @rule.last
last.is_a?(String) && last[-1] == ?,
end
# A hash that will be associated with this rule in the CSS document
# if the {file:SASS_REFERENCE.md#debug_info-option `:debug_info` option} is enabled.
# This data is used by e.g. [the FireSass Firebug
# extension](https://addons.mozilla.org/en-US/firefox/addon/103988).
#
# @return [{#to_s => #to_s}]
def debug_info
{:filename => filename &&
("file://" + URI::DEFAULT_PARSER.escape(File.expand_path(filename))),
:line => line}
end
# A rule node is invisible if it has only placeholder selectors.
def invisible?
resolved_rules.members.all? {|seq| seq.invisible?}
end
private
def try_to_parse_non_interpolated_rules
@parsed_rules = nil
return unless @rule.all? {|t| t.is_a?(String)}
# We don't use real filename/line info because we don't have it yet.
# When we get it, we'll set it on the parsed rules if possible.
parser = nil
warnings = Sass.logger.capture do
parser = Sass::SCSS::StaticParser.new(@rule.join.strip, nil, nil, 1)
@parsed_rules = parser.parse_selector rescue nil
end
# If parsing produces a warning, throw away the result so we can parse
# later with the real filename info.
@parsed_rules = nil unless warnings.empty?
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/import_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/import_node.rb | module Sass
module Tree
# A static node that wraps the {Sass::Tree} for an `@import`ed file.
# It doesn't have a functional purpose other than to add the `@import`ed file
# to the backtrace if an error occurs.
class ImportNode < RootNode
# The name of the imported file as it appears in the Sass document.
#
# @return [String]
attr_reader :imported_filename
# Sets the imported file.
attr_writer :imported_file
# @param imported_filename [String] The name of the imported file
def initialize(imported_filename)
@imported_filename = imported_filename
super(nil)
end
def invisible?; to_s.empty?; end
# Returns the imported file.
#
# @return [Sass::Engine]
# @raise [Sass::SyntaxError] If no file could be found to import.
def imported_file
@imported_file ||= import
end
# Returns whether or not this import should emit a CSS @import declaration
#
# @return [Boolean] Whether or not this is a simple CSS @import declaration.
def css_import?
if @imported_filename =~ /\.css$/
@imported_filename
elsif imported_file.is_a?(String) && imported_file =~ /\.css$/
imported_file
end
end
private
def import
paths = @options[:load_paths]
if @options[:importer]
f = @options[:importer].find_relative(
@imported_filename, @options[:filename], options_for_importer)
return f if f
end
paths.each do |p|
f = p.find(@imported_filename, options_for_importer)
return f if f
end
lines = ["File to import not found or unreadable: #{@imported_filename}."]
if paths.size == 1
lines << "Load path: #{paths.first}"
elsif !paths.empty?
lines << "Load paths:\n #{paths.join("\n ")}"
end
raise SyntaxError.new(lines.join("\n"))
rescue SyntaxError => e
raise SyntaxError.new(e.message, :line => line, :filename => @filename)
end
def options_for_importer
@options.merge(:_from_import_node => true)
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/debug_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/debug_node.rb | module Sass
module Tree
# A dynamic node representing a Sass `@debug` statement.
#
# @see Sass::Tree
class DebugNode < Node
# The expression to print.
# @return [Script::Tree::Node]
attr_accessor :expr
# @param expr [Script::Tree::Node] The expression to print
def initialize(expr)
@expr = expr
super()
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/at_root_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/at_root_node.rb | module Sass
module Tree
# A dynamic node representing an `@at-root` directive.
#
# An `@at-root` directive with a selector is converted to an \{AtRootNode}
# containing a \{RuleNode} at parse time.
#
# @see Sass::Tree
class AtRootNode < Node
# The query for this node (e.g. `(without: media)`),
# interspersed with {Sass::Script::Tree::Node}s representing
# `#{}`-interpolation. Any adjacent strings will be merged
# together.
#
# This will be nil if the directive didn't have a query. In this
# case, {#resolved\_type} will automatically be set to
# `:without` and {#resolved\_rule} will automatically be set to `["rule"]`.
#
# @return [Array<String, Sass::Script::Tree::Node>]
attr_accessor :query
# The resolved type of this directive. `:with` or `:without`.
#
# @return [Symbol]
attr_accessor :resolved_type
# The resolved value of this directive -- a list of directives
# to either include or exclude.
#
# @return [Array<String>]
attr_accessor :resolved_value
# The number of additional tabs that the contents of this node
# should be indented.
#
# @return [Number]
attr_accessor :tabs
# Whether the last child of this node should be considered the
# end of a group.
#
# @return [Boolean]
attr_accessor :group_end
def initialize(query = nil)
super()
@query = Sass::Util.strip_string_array(Sass::Util.merge_adjacent_strings(query)) if query
@tabs = 0
end
# Returns whether or not the given directive is excluded by this
# node. `directive` may be "rule", which indicates whether
# normal CSS rules should be excluded.
#
# @param directive [String]
# @return [Boolean]
def exclude?(directive)
if resolved_type == :with
return false if resolved_value.include?('all')
!resolved_value.include?(directive)
else # resolved_type == :without
return true if resolved_value.include?('all')
resolved_value.include?(directive)
end
end
# Returns whether the given node is excluded by this node.
#
# @param node [Sass::Tree::Node]
# @return [Boolean]
def exclude_node?(node)
return exclude?(node.name.gsub(/^@/, '')) if node.is_a?(Sass::Tree::DirectiveNode)
return exclude?('keyframes') if node.is_a?(Sass::Tree::KeyframeRuleNode)
exclude?('rule') && node.is_a?(Sass::Tree::RuleNode)
end
# @see Node#bubbles?
def bubbles?
true
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/function_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/function_node.rb | module Sass
module Tree
# A dynamic node representing a function definition.
#
# @see Sass::Tree
class FunctionNode < Node
# The name of the function.
# @return [String]
attr_reader :name
# The arguments to the function. Each element is a tuple
# containing the variable for argument and the parse tree for
# the default value of the argument
#
# @return [Array<Script::Tree::Node>]
attr_accessor :args
# The splat argument for this function, if one exists.
#
# @return [Script::Tree::Node?]
attr_accessor :splat
# Strips out any vendor prefixes.
# @return [String] The normalized name of the directive.
def normalized_name
@normalized_name ||= name.gsub(/^(?:-[a-zA-Z0-9]+-)?/, '\1')
end
# @param name [String] The function name
# @param args [Array<(Script::Tree::Node, Script::Tree::Node)>]
# The arguments for the function.
# @param splat [Script::Tree::Node] See \{#splat}
def initialize(name, args, splat)
@name = name
@args = args
@splat = splat
super()
return unless %w(and or not).include?(name)
raise Sass::SyntaxError.new("Invalid function name \"#{name}\".")
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/variable_node.rb | _vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/tree/variable_node.rb | module Sass
module Tree
# A dynamic node representing a variable definition.
#
# @see Sass::Tree
class VariableNode < Node
# The name of the variable.
# @return [String]
attr_reader :name
# The parse tree for the variable value.
# @return [Script::Tree::Node]
attr_accessor :expr
# Whether this is a guarded variable assignment (`!default`).
# @return [Boolean]
attr_reader :guarded
# Whether this is a global variable assignment (`!global`).
# @return [Boolean]
attr_reader :global
# @param name [String] The name of the variable
# @param expr [Script::Tree::Node] See \{#expr}
# @param guarded [Boolean] See \{#guarded}
# @param global [Boolean] See \{#global}
def initialize(name, expr, guarded, global)
@name = name
@expr = expr
@guarded = guarded
@global = global
super()
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.